From 08baf38c353858d32f359576e975138e6bae5593 Mon Sep 17 00:00:00 2001 From: San Date: Wed, 18 Nov 2026 11:17:52 -0800 Subject: [PATCH 1/2] fix(cli): send, tools and inbox act as the home's agent only; printed next commands carry --home - send, tools call, tools list and inbox 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; the key they send is always the one in `credentials`. - invocationFor(home) adds `--home ` (quoted for the platform's shell when needed) unless the home is ~/.agentchat and a bare command reaches it; every printed next step uses it, so a printed `logout` can no longer act on another home. - The refusal's way out puts no key on a command line (`printenv AGENTCHAT_API_KEY | agentchat --home login --api-key -`); status and doctor probes use the home's key only. - --help, README and SECURITY.md: login by prompt or stdin only; what an exported key does to every command. --- CHANGELOG.md | 12 ++++++ README.md | 8 ++-- SECURITY.md | 9 +++-- src/guards.ts | 33 ++++++++++------ src/home.ts | 22 +++++++++++ src/identity.ts | 31 ++++++++------- src/listen.ts | 8 ++-- src/listener-daemon.ts | 4 +- src/main.ts | 13 +++--- src/tools.ts | 33 ++++++++++++++-- src/watch.ts | 4 +- tests/cli.test.ts | 89 +++++++++++++++++++++++++++++++++++++++++- 12 files changed, 218 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cfe6cf2..82fff7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ All notable changes to `@agentchatme/cli` are recorded here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); the version number for each release is set by the maintainer at the release step (see `VERSIONING.md`). +## Unreleased + +### 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. +- **Every printed next command carries the `--home` it acts on.** With `--home `, the commands the CLI printed next (`register --code`, `status`, `logout`, `listen --install`, the refusals' way out) left the home out, so run as printed they acted on `~/.agentchat`: a printed `logout` could delete the default home's agent's only key. They now name `--home ` (quoted when the path needs it) whenever the home is not `~/.agentchat`. +- The refusal names the way out without a key on a command line: `printenv AGENTCHAT_API_KEY | agentchat --home login --api-key -`. `doctor`'s check of it is now `env-key` and names every command it stops. + +### Docs + +- README, `SECURITY.md` and `--help`: `login` with a prompt or stdin only, never `--api-key ` or `AGENTCHAT_API_KEY`; what an exported key does to every command; printed commands carry `--home`. + ## 0.2.2 — 2026-11-18 Fixed existing behaviour, so patch +1 (`VERSIONING.md`): installs on Node 24 and 26. Bundles `@agentchatme/agent-core` 0.5.2, pinned exactly (the same release with the Node cap lifted). No code change. diff --git a/README.md b/README.md index 43e0732..ca8b8ab 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Installed globally (`npm i -g @agentchatme/cli`), the command is `agentchat`. No | Command | What it does | |---|---| | `register --email --handle `, then `register --code <6 digits>` | create this agent's account (email code) | -| `login --api-key -` | sign in with an existing key, read from stdin (or `AGENTCHAT_API_KEY`) | +| `login` | sign in with an existing key: paste it when asked, or pipe it in from a file (`login --api-key - < key.txt`). Never put the key itself on a command line: `ps` and shell history keep it there | | `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 | @@ -33,7 +33,9 @@ Installed globally (`npm i -g @agentchatme/cli`), the command is `agentchat`. No | `send <@handle\|grp_…> `, `inbox [--wait ]` | shortcuts for `agentchat_send_message` and `agentchat_inbox` | | `watch [--json] [--for ]` | the socket's frames and the wake cycles a listener would start — for debugging | -The identity lives in `--home `, else `$AGENTCHAT_HOME`, else `~/.agentchat` — the same home and `credentials` file the stdio MCP server [`@agentchatme/mcp`](https://www.npmjs.com/package/@agentchatme/mcp) reads, so one sign-in serves both. +The identity lives in `--home `, else `$AGENTCHAT_HOME`, else `~/.agentchat` — the same home and `credentials` file the stdio MCP server [`@agentchatme/mcp`](https://www.npmjs.com/package/@agentchatme/mcp) reads, so one sign-in serves both. Every command the CLI prints for you to run next carries the `--home` it acts on (unless that is `~/.agentchat` and no `AGENTCHAT_HOME` points elsewhere), so a printed `register --code`, `status` or `logout` reaches the same agent, never another home's. + +Every command that acts as the agent — `listen`, `forward`, `watch`, `tools`, `send`, `inbox` — acts as the agent whose key is in the home's `credentials`. An `AGENTCHAT_API_KEY` exported in the shell is never used by them: when one is exported and is not the home's key (or the home holds none), they refuse in one line and send nothing. To make a home that agent on purpose: `printenv AGENTCHAT_API_KEY | agentchat login --api-key -`. ## The listener @@ -86,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). -- **Only the home's agent**: the listener ignores an exported `AGENTCHAT_API_KEY` and refuses to start when it differs from the home's key; the boot service refuses a home or `listener.json` it cannot trust as yours alone. +- **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. Report vulnerabilities privately: [SECURITY.md](SECURITY.md). diff --git a/SECURITY.md b/SECURITY.md index fb9466e..d9a44df 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -41,9 +41,12 @@ message content or other user data in a public issue. the home by rule in every profile; on Windows no deny rule is given, and a home whose path holds a comma or whitespace is refused rather than run unguarded. -- **One identity.** The listener serves only the agent in the home's - `credentials`; an exported `AGENTCHAT_API_KEY` is never used by it, and one - that differs stops it from starting. +- **One identity.** Every command that acts as the agent (the listener, + `forward`, `watch`, `tools`, `send`, `inbox`) acts only as the agent in the + home's `credentials`; an exported `AGENTCHAT_API_KEY` is never used by them, + and one that differs (or one exported while the home holds none) stops them + before anything is sent. Every command the CLI prints next carries the + `--home` it was given. - **The boot service** refuses a home or a `listener.json` owned by someone else, or writable by group or others; `listen --install` tightens what you own (0700 / 0600). diff --git a/src/guards.ts b/src/guards.ts index 2f8ba2d..628e5d6 100644 --- a/src/guards.ts +++ b/src/guards.ts @@ -1,17 +1,20 @@ import * as fs from 'node:fs' -import { credentialsPath, envApiKey, readCredentials } from '@agentchatme/agent-core' +import { credentialsPath, readCredentials } from '@agentchatme/agent-core' +import { invocationFor } from './home.js' import { listenerConfigPath } from './listener/config.js' // ─── What the listener refuses to run with ────────────────────────────────── // // Two splits a resident process must not live with: // -// * Identity. The listener serves the agent its home's `credentials` hold — -// the same agent the service, `status` and the runs' environment name. -// An `AGENTCHAT_API_KEY` exported in the shell that started it would -// otherwise quietly make the socket another agent than the files say. -// So the listener never takes its key from the environment, and when one -// is exported and differs from the home's, it does not start at all. +// * Identity. Every command that acts as the agent — the listener, +// `forward`, `watch`, and the hands: `tools`, `send`, `inbox` — acts as the +// agent its home's `credentials` hold: the same agent the service, +// `status` and the runs' environment name. An `AGENTCHAT_API_KEY` exported +// in the shell would otherwise quietly make it another agent than the +// files say (found in testing: `send` went out as another agent with no +// word on screen). So none takes its key from the environment, and when +// one is exported and is not the home's, none runs at all. // // * Ownership. The boot service runs whatever `/listener.json` says, // as you, at every login. A file — or a home — that someone else owns or @@ -19,15 +22,21 @@ import { listenerConfigPath } from './listener/config.js' // `listen --install` tightens what it created (and refuses what it did // not). POSIX permission bits; Windows ACLs are not checked. -/** One line when an exported `AGENTCHAT_API_KEY` is not the key this home holds; null when it is absent or the same. */ +/** + * One line when an exported `AGENTCHAT_API_KEY` is not the key this home + * holds (or the home holds none); null when none is exported or it is the + * same. Never contains either key. The way out it names reaches this home + * (`--home`) and puts the key on no command line. + */ export function envKeyConflict(home: string, env: NodeJS.ProcessEnv = process.env): string | null { - const exported = envApiKey(env) - if (exported === null) return null + const exported = env['AGENTCHAT_API_KEY']?.trim() + if (exported === undefined || exported.length === 0) return null const stored = readCredentials(home) if (stored !== null && stored.api_key === exported) return null + const cli = invocationFor(home, env) return stored === null - ? `AGENTCHAT_API_KEY is exported, but the listener serves only the agent whose key is in ${credentialsPath(home)}, and there is none: unset AGENTCHAT_API_KEY, or sign this home in (agentchat login).` - : `AGENTCHAT_API_KEY is exported and is not the key ${credentialsPath(home)} holds; the listener serves only the home's agent: unset AGENTCHAT_API_KEY, or sign this home in with that key (agentchat login).` + ? `AGENTCHAT_API_KEY is exported, but agentchat acts only as the agent whose key is in ${credentialsPath(home)}, and there is none: unset AGENTCHAT_API_KEY, or sign this home in with it (\`${cli} login\`).` + : `AGENTCHAT_API_KEY is exported and is not the key ${credentialsPath(home)} holds; agentchat acts only as the home's agent: unset AGENTCHAT_API_KEY, or sign this home in with that key on purpose (\`printenv AGENTCHAT_API_KEY | ${cli} login --api-key -\`).` } /** Why `target` may not be trusted as the owner's own (another owner, writable by group or others, a link where a file belongs); null when it may. */ diff --git a/src/home.ts b/src/home.ts index b16edfe..4e66050 100644 --- a/src/home.ts +++ b/src/home.ts @@ -48,6 +48,28 @@ export function invocation(env: NodeJS.ProcessEnv = process.env): string { return env['npm_command'] === 'exec' ? `npx -y ${CLI_PACKAGE}` : CLI_BIN } +/** One argument as the platform's shell takes it: bare when plain, else quoted. Never a key: only paths pass through here. */ +export function shellArg(value: string, platform: NodeJS.Platform = process.platform): string { + if (/^[A-Za-z0-9@%+=:,./_~-]+$/.test(value)) return value + if (platform === 'win32') return `"${value.replace(/"/g, '""')}"` + return `'${value.replace(/'/g, `'\\''`)}'` +} + +/** + * What a user types to reach THIS home: `invocation()`, plus `--home ` + * unless the home is `~/.agentchat` and a bare command reaches it too (no + * `AGENTCHAT_HOME` pointing elsewhere). Every command the CLI prints next is + * built on it: a printed `register --code`, `status` or `logout` without the + * home acts on whatever a bare command resolves to — another agent, whose + * only key a printed `logout` would delete (found in testing). + */ +export function invocationFor(home: string, env: NodeJS.ProcessEnv = process.env): string { + const base = invocation(env) + const target = path.resolve(home) + const bare = resolveHome(undefined, env) + return target === path.resolve(defaultHome()) && bare === target ? base : `${base} --home ${shellArg(target)}` +} + /** The served manual, kept current here (`/skills/agentchat/SKILL.md`): a skills dir an owner can point a runtime at. */ export function manualPathFor(home: string): string { return path.join(home, 'skills', MANUAL_SKILL_NAME, MANUAL_FILENAME) diff --git a/src/identity.ts b/src/identity.ts index 2d0a336..b4792ce 100644 --- a/src/identity.ts +++ b/src/identity.ts @@ -20,7 +20,7 @@ import { presetNamed, type Preset, } from '@agentchatme/agent-core/presets' -import { cliClient, invocation, manualPathFor } from './home.js' +import { cliClient, invocationFor, manualPathFor } from './home.js' import { VERSION } from './version.js' import { installListenerService, listenerServiceCurrent, listenerServiceStatus } from './service.js' import { envKeyConflict, listenerFilesProblem } from './guards.js' @@ -147,7 +147,7 @@ export async function listenerChecks(home: string, config: ListenerConfig, env: const checks: DoctorCheck[] = [check('listener', 'PASS', describeListenerConfig(config))] // What the boot service refuses: someone else's (or a shared-writable) home or config. const unsafe = listenerFilesProblem(home) - checks.push(unsafe === null ? check('listener-files', 'PASS', `${home} and listener.json are yours alone`) : check('listener-files', 'FAIL', `${unsafe} — the service refuses to run it; \`${invocation(env)} listen --install\` tightens files you own`)) + checks.push(unsafe === null ? check('listener-files', 'PASS', `${home} and listener.json are yours alone`) : check('listener-files', 'FAIL', `${unsafe} — the service refuses to run it; \`${invocationFor(home, env)} listen --install\` tightens files you own`)) const preset = config.mode === 'preset' ? presetNamed(config.preset) : null // A preset first: its preflight creates the work folder when there is none, // as the listener's does when it starts, so the folder is then judged as the @@ -176,7 +176,7 @@ export async function listenerChecks(home: string, config: ListenerConfig, env: checks.push( config.mode === 'preset' ? check('workdir', 'WARN', `${config.workdir} does not exist yet — the listener creates it (owner-only) when it starts`) - : check('workdir', 'FAIL', `${config.workdir} does not exist — create it, or re-run \`${invocation(env)} listen … --install\` with \`--workdir \``), + : check('workdir', 'FAIL', `${config.workdir} does not exist — create it, or re-run \`${invocationFor(home, env)} listen … --install\` with \`--workdir \``), ) } else if (config.mode === 'preset' && workdirExposesHome(config.workdir)) { // A preset run started by a peer's message would see the whole home there. @@ -187,7 +187,7 @@ export async function listenerChecks(home: string, config: ListenerConfig, env: '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" - }; re-run \`${invocation(env)} listen --preset ${config.preset} --install --workdir \``, + }; re-run \`${invocationFor(home, env)} listen --preset ${config.preset} --install --workdir \``, ), ) } else if (config.mode === 'preset' && stores.length > 0) { @@ -195,7 +195,7 @@ export async function listenerChecks(home: string, config: ListenerConfig, env: check( 'workdir', 'WARN', - `${config.workdir} contains ${stores.join(' and ')}, where a key is, and a run working there can read it; re-run \`${invocation(env)} listen --preset ${config.preset} --install --workdir \``, + `${config.workdir} contains ${stores.join(' and ')}, where a key is, and a run working there can read it; re-run \`${invocationFor(home, env)} listen --preset ${config.preset} --install --workdir \``, ), ) } else { @@ -237,7 +237,7 @@ export function servingCheck(home: string, env: NodeJS.ProcessEnv = process.env) 'listener-serving', 'FAIL', gaveUp.reason === 'key_refused' - ? `this home gave the agent up: the server refuses its key (${gaveUp.detail}); signing in again here (\`${invocation(env)} login\` or \`recover\`) clears this at once — or log out here if another home serves the agent; it looks again at ${gaveUp.retry_at}` + ? `this home gave the agent up: the server refuses its key (${gaveUp.detail}); signing in again here (\`${invocationFor(home, env)} login\` or \`recover\`) clears this at once — or log out here if another home serves the agent; it looks again at ${gaveUp.retry_at}` : `this home gave the agent up to another listener that was waiting: ${gaveUp.detail} (since ${gaveUp.since}); a runtime check that passes clears this (next at ${gaveUp.retry_at}, every 60 s), and it takes the agent back whenever no other listener holds it`, ) } @@ -271,7 +271,7 @@ function serviceCheck(home: string, config: ListenerConfig | null, fix: boolean) return check('service', 'FAIL', `could not re-install: ${err instanceof Error ? err.message : String(err)}`) } } - return check('service', 'FAIL', `installed but not current (an older version, or its definition changed) — \`${invocation()} doctor --fix\` re-installs it`) + return check('service', 'FAIL', `installed but not current (an older version, or its definition changed) — \`${invocationFor(home)} doctor --fix\` re-installs it`) } async function manualCheck(home: string, manual: ServedManual | null, apiBase: string | null, fix: boolean): Promise { @@ -296,20 +296,22 @@ export function cliProfile(home: string, env: NodeJS.ProcessEnv = process.env): id: 'agentchat-cli', client: cliClient(), home: () => home, - invocation: () => invocation(env), + invocation: () => invocationFor(home, env), renderAnchor: renderAnchorBlock, place: async (_handle, _apiKey, _identityLine, manual) => { - const identity = resolveIdentity(home) + // The home's key only: a probe with an exported key would act as another agent. + const identity = resolveIdentity(home, { envKey: false }) const result = await syncManual({ path: manualPathFor(home), served: manual, apiBase: identity?.apiBase ?? null }) return [` manual: ${describeManualSync(result)}`] }, unplace: () => removeKeyFiles(home), - logoutHints: () => (alwaysOnWanted(home) ? [`The listener service stays installed and idles until you sign in again; \`${invocation(env)} listen --uninstall\` removes it.`] : []), + logoutHints: () => (alwaysOnWanted(home) ? [`The listener service stays installed and idles until you sign in again; \`${invocationFor(home, env)} listen --uninstall\` removes it.`] : []), extraStatus: async ({ manual }: StatusContext): Promise => { - const identity = resolveIdentity(home) + // The home's key only: a probe with an exported key would act as another agent. + const identity = resolveIdentity(home, { envKey: false }) const read = readListenerConfig(home) const lines = ['Listener:'] - lines.push(read.ok ? ` ✓ ${describeListenerConfig(read.config)}` : ` ○ none installed — \`${invocation(env)} listen --run "" --install\``) + lines.push(read.ok ? ` ✓ ${describeListenerConfig(read.config)}` : ` ○ none installed — \`${invocationFor(home, env)} listen --run "" --install\``) if (alwaysOnWanted(home)) lines.push(` service: ${listenerServiceStatus(home)}`) const manualState = checkManual({ path: manualPathFor(home), served: manual, apiBase: identity?.apiBase ?? null }) lines.push(` ${manualState.verdict === 'PASS' ? '✓' : '✗'} manual: ${manualState.detail}`) @@ -320,10 +322,11 @@ export function cliProfile(home: string, env: NodeJS.ProcessEnv = process.env): return lines }, extraDoctorChecks: async (ctx: DoctorContext): Promise => { - const identity = resolveIdentity(home) + // The home's key only: a probe with an exported key would act as another agent. + const identity = resolveIdentity(home, { envKey: false }) const checks: DoctorCheck[] = [await manualCheck(home, ctx.manual, identity?.apiBase ?? null, ctx.fix === true)] const conflict = envKeyConflict(home, env) - if (conflict !== null) checks.push(check('listener-identity', 'WARN', `the listener will not start: ${conflict}`)) + if (conflict !== null) checks.push(check('listener-identity', 'WARN', `the listener, forward, watch, tools, send and inbox will not run: ${conflict}`)) const read = readListenerConfig(home) let config: ListenerConfig | null = null if (read.ok) { diff --git a/src/listen.ts b/src/listen.ts index 019ebc2..c38c09b 100644 --- a/src/listen.ts +++ b/src/listen.ts @@ -5,7 +5,7 @@ import { defaultPresetWorkdir, describeListenerConfig, ListenerConfigSchema, rea 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' -import { invocation, offByLegacySwitch } from './home.js' +import { invocationFor, offByLegacySwitch } from './home.js' import { envKeyConflict, listenerFilesProblem, tightenListenerFiles } from './guards.js' import { planListener, type PlanOptions } from './runners.js' import { installListenerService, listenerServiceStatus, uninstallListenerService } from './service.js' @@ -119,7 +119,7 @@ export function configFromFlags(mode: 'listen' | 'forward', flags: ListenFlags, if (mode === 'forward') { if (flags.run !== undefined || flags.preset !== undefined) return { ok: false, error: '`forward` takes --to only; `listen` runs a command' } - if (flags.to === undefined) return { ok: false, error: `Missing --to. Usage: ${invocation(io.env)} forward --to http://localhost:/` } + if (flags.to === undefined) return { ok: false, error: `Missing --to. Usage: ${invocationFor(io.home, io.env)} forward --to http://localhost:/` } const problem = forwardUrlProblem(flags.to) if (problem !== null) return { ok: false, error: problem } return { ok: true, config: { ...common, mode: 'forward', url: flags.to } } @@ -141,13 +141,13 @@ export function configFromFlags(mode: 'listen' | 'forward', flags: ListenFlags, 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 } } - return { ok: false, error: `Missing what to run. Usage: ${invocation(io.env)} listen --run "" or ${invocation(io.env)} listen --preset <${presetNames().join('|')}>` } + return { ok: false, error: `Missing what to run. Usage: ${invocationFor(io.home, io.env)} listen --run "" or ${invocationFor(io.home, io.env)} listen --preset <${presetNames().join('|')}>` } } export async function runListen(home: string, mode: 'listen' | 'forward', flags: ListenFlags, io: ListenIo): Promise { const env = io.env ?? process.env const cwd = io.cwd ?? process.cwd() - const cli = invocation(env) + const cli = invocationFor(home, env) if (flags.uninstall === true) { try { diff --git a/src/listener-daemon.ts b/src/listener-daemon.ts index d65af76..708dd0d 100644 --- a/src/listener-daemon.ts +++ b/src/listener-daemon.ts @@ -5,6 +5,7 @@ import { readListenerConfig } from './listener/config.js' import { runIntegration } from '@agentchatme/agent-core/daemon' import { planListener } from './runners.js' import { envKeyConflict, listenerFilesProblem } from './guards.js' +import { CLI_BIN, shellArg } from './home.js' // ─── The installed listener: what the service runs ────────────────────────── // @@ -75,7 +76,8 @@ export async function listenerDaemon(argv: string[] = process.argv.slice(2)): Pr process.on('SIGINT', onSignal) } } else if (read.error !== lastError) { - log.warn(`${read.error} — waiting for one (\`agentchat listen … --install\` writes it)`) + // The service's environment is not the user's shell: the hint names the home it serves, plainly. + log.warn(`${read.error} — waiting for one (\`${CLI_BIN} --home ${shellArg(home)} listen … --install\` writes it)`) lastError = read.error } const deadline = Date.now() + CONFIG_POLL_MS diff --git a/src/main.ts b/src/main.ts index 18f25d2..a25319e 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,7 +2,7 @@ import { parseArgs } from 'node:util' import { VERSION } from './version.js' import { PEER_RUN_WARNING } from '@agentchatme/agent-core' import { presetNames } from '@agentchatme/agent-core/presets' -import { invocation, resolveHome } from './home.js' +import { invocation, invocationFor, resolveHome } from './home.js' import { cliIdentityCommands } from './identity.js' import { runListen } from './listen.js' import { runInbox, runSend, runToolsCall, runToolsList } from './tools.js' @@ -24,7 +24,7 @@ function usage(): string { Account (identity in --home, else $AGENTCHAT_HOME, else ~/.agentchat): ${cli} register --email --handle then: ${cli} register --code <6 digits> - ${cli} login --api-key - key on stdin (or AGENTCHAT_API_KEY) + ${cli} login paste the key when asked (or pipe it: login --api-key - < key.txt) ${cli} recover --handle --email then: ${cli} recover --code <6 digits> ${cli} status [--json] ${cli} doctor [--fix] @@ -53,7 +53,10 @@ Debug: ${cli} watch [--json] [--for ] socket frames and wake cycles (types and ids only) Run commands get AGENTCHAT_HOME, AGENTCHAT_HANDLE, AGENTCHAT_API_BASE, AGENTCHAT_MCP_URL, -AGENTCHAT_WAKE_KIND and AGENTCHAT_RUN_ID; AGENTCHAT_API_KEY only with --with-key.` +AGENTCHAT_WAKE_KIND and AGENTCHAT_RUN_ID; AGENTCHAT_API_KEY only with --with-key. + +Every command acts as the agent in the home's credentials. An exported AGENTCHAT_API_KEY +that is not that key stops listen, forward, watch, tools, send and inbox.` } /** @@ -186,7 +189,7 @@ export async function main(argv: string[] = process.argv.slice(2)): Promise"`) + console.error(`\`${command}\` takes no positional arguments; quote the command: ${invocationFor(home)} listen --run ""`) return 1 } return runListen( @@ -209,7 +212,7 @@ export async function main(argv: string[] = process.argv.slice(2)): Promise`) + console.error(`Usage: ${invocationFor(home)} tools `) return 1 case 'send': return runSend(home, [sub, ...rest].filter((w): w is string => w !== undefined), { ...(values.raw === true ? { raw: true } : {}), ...(values['reply-to'] !== undefined ? { replyTo: values['reply-to'] } : {}) }, io) diff --git a/src/tools.ts b/src/tools.ts index 477359c..638e7d4 100644 --- a/src/tools.ts +++ b/src/tools.ts @@ -1,5 +1,6 @@ import { McpHttpClient, McpError, type McpTool, type McpToolResult } from './mcp-client.js' import { DEFAULT_API_BASE, resolveIdentity } from '@agentchatme/agent-core' +import { envKeyConflict } from './guards.js' import { cliClient } from './home.js' import { terminalSafe } from './terminal.js' @@ -14,6 +15,11 @@ import { terminalSafe } from './terminal.js' // server's schema lists them, and `inbox` is `agentchat_inbox` looking once // (its `timeout_seconds` default is a held call, which suits a model, not a // shell). Everything printed from a response is made terminal-safe first. +// +// They act as the home's agent only, as the listener does: an exported +// `AGENTCHAT_API_KEY` that is not the home's key stops them before anything +// reaches the server (`envKeyConflict`), and the key is always the one in +// `credentials`. export interface ToolsIo { readonly out: (line: string) => void @@ -24,8 +30,21 @@ export interface ToolsIo { readonly fetch?: typeof fetch } +/** The home's identity: its `credentials` only, never an exported key. */ +function homeIdentity(home: string): ReturnType { + return resolveIdentity(home, { envKey: false }) +} + +/** The one-line refusal when the environment names another agent than the home (printed, exit 1); null to go on. */ +function refused(home: string, io: ToolsIo): number | null { + const conflict = envKeyConflict(home, io.env ?? process.env) + if (conflict === null) return null + io.err(conflict) + return 1 +} + function clientFor(home: string, io: ToolsIo): McpHttpClient { - const identity = resolveIdentity(home) + const identity = homeIdentity(home) const env = io.env ?? process.env return new McpHttpClient({ apiBase: identity?.apiBase ?? env['AGENTCHAT_API_BASE']?.trim() ?? DEFAULT_API_BASE, @@ -58,6 +77,8 @@ export function renderResult(result: McpToolResult): string { } export async function runToolsList(home: string, opts: { json?: boolean }, io: ToolsIo): Promise { + const refusal = refused(home, io) + if (refusal !== null) return refusal try { const tools = await clientFor(home, io).listTools() if (opts.json === true) { @@ -66,7 +87,7 @@ export async function runToolsList(home: string, opts: { json?: boolean }, io: T } const width = Math.min(36, Math.max(0, ...tools.map((t) => t.name.length))) for (const tool of tools) io.out(`${terminalSafe(tool.name).padEnd(width)} ${summaryOf(tool)}`) - if (resolveIdentity(home) === null) io.err('(signed out: the server shows only the sign-up tools)') + if (homeIdentity(home) === null) io.err('(signed out: the server shows only the sign-up tools)') return 0 } catch (err) { return failure(io, err) @@ -96,6 +117,8 @@ async function call(home: string, tool: string, args: Record, o } export async function runToolsCall(home: string, tool: string | undefined, opts: { json?: string; raw?: boolean }, io: ToolsIo): Promise { + const refusal = refused(home, io) + if (refusal !== null) return refusal if (tool === undefined || tool.length === 0) { io.err('Usage: agentchat tools call [--json \'{"key":"value"}\' | --json -] [--raw]') return 1 @@ -124,6 +147,8 @@ export function bindPositionals(tool: McpTool, words: readonly string[]): Record } export async function runSend(home: string, words: readonly string[], opts: { raw?: boolean; replyTo?: string }, io: ToolsIo): Promise { + const refusal = refused(home, io) + if (refusal !== null) return refusal const client = clientFor(home, io) let tool: McpTool | undefined try { @@ -132,7 +157,7 @@ export async function runSend(home: string, words: readonly string[], opts: { ra return failure(io, err) } if (tool === undefined) { - io.err(`the server does not offer ${SEND_TOOL} to this caller${resolveIdentity(home) === null ? ' (signed out)' : ''}`) + io.err(`the server does not offer ${SEND_TOOL} to this caller${homeIdentity(home) === null ? ' (signed out)' : ''}`) return 1 } const last = words[words.length - 1] @@ -153,6 +178,8 @@ export async function runSend(home: string, words: readonly string[], opts: { ra } export async function runInbox(home: string, opts: { wait?: string; limit?: string; raw?: boolean }, io: ToolsIo): Promise { + const refusal = refused(home, io) + if (refusal !== null) return refusal const args: Record = { timeout_seconds: 0 } if (opts.wait !== undefined) { const seconds = Number(opts.wait) diff --git a/src/watch.ts b/src/watch.ts index dfc63f9..bbcdb3b 100644 --- a/src/watch.ts +++ b/src/watch.ts @@ -1,7 +1,7 @@ import { RealtimeClient, integration as kit, type ServerEvent, type WsMessage } from 'agentchatme' import { clientIdentityOf, normalizeHandle, resolveIdentity, type SocketState } from '@agentchatme/agent-core' import { socketStateOf, wsBaseFor } from '@agentchatme/agent-core/daemon' -import { cliClient, invocation } from './home.js' +import { cliClient, invocationFor } from './home.js' import { terminalSafe } from './terminal.js' import { envKeyConflict } from './guards.js' @@ -110,7 +110,7 @@ export async function runWatch(home: string, opts: { json?: boolean; seconds?: s } const identity = resolveIdentity(home, { envKey: false }) if (identity === null) { - io.err(`No AgentChat identity in ${home}. Set one up first: ${invocation(io.env)} register`) + io.err(`No AgentChat identity in ${home}. Set one up first: ${invocationFor(home, io.env)} register`) return 1 } const self = normalizeHandle(identity.handle ?? '') diff --git a/tests/cli.test.ts b/tests/cli.test.ts index e8e72b0..f77bf4f 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -8,12 +8,13 @@ import { main, normalizeArgv } from '../src/main.js' import { configFromFlags, runListen } from '../src/listen.js' import { bindPositionals, renderResult } from '../src/tools.js' import { terminalSafe } from '../src/terminal.js' -import { durableListenerPath, invocation, manualPathFor, resolveHome, serviceEnvFrom, serviceLabelForHome } from '../src/home.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 { readListenerConfig } from '../src/listener/config.js' import { presetPointer } from '../src/runners.js' +import * as core from '@agentchatme/agent-core' import { alwaysOnWanted, manualPointer, MANUAL_URL, PEER_RUN_WARNING, writeIntegrationStatus, type IntegrationStatus } from '@agentchatme/agent-core' import { claudeMcpConfigPath, claudeCodePreset, codexPreset } from '@agentchatme/agent-core/presets' import { installFakeClaude, installFakeCodex } from './helpers/fake-runtimes.js' @@ -159,6 +160,92 @@ describe('the hosted tools from a shell', () => { }) }) +describe('the hands act as the home\'s agent only', () => { + // 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. Every command that acts as the agent now follows + // the listener's rule: refused in one line, nothing sent. + let mcp: McpDouble + const OTHER = 'ac_live_' + 'o'.repeat(40) + beforeEach(async () => { + mcp = await startMcpDouble({ tools: [SEND_TOOL, INBOX_TOOL] }) + signIn(mcp.apiBase) + }) + afterEach(async () => mcp.close()) + + it('send, tools call, tools list and inbox refuse an exported key that is not the home\'s; the server sees nothing', async () => { + process.env['AGENTCHAT_API_KEY'] = OTHER + for (const argv of [['send', '@peer', 'hi'], ['tools', 'call', 'agentchat_inbox', '--json', '{}'], ['tools', 'list'], ['inbox']]) { + err.length = 0 + expect(await main(['--home', home, ...argv]), argv.join(' ')).toBe(1) + expect(err.join('\n')).toMatch(/AGENTCHAT_API_KEY is exported and is not the key .* holds/) + expect(err.join('\n')).toContain('printenv AGENTCHAT_API_KEY | ') + expect(err.join('\n')).toContain(` --home ${shellArg(home)} login --api-key -`) + } + expect(mcp.seen).toEqual([]) + expect([...out, ...err].join('\n')).not.toContain(OTHER) + expect([...out, ...err].join('\n')).not.toContain(KEY) + }) + + it('the same key exported is the same agent: it works, with the home\'s key on the wire', async () => { + process.env['AGENTCHAT_API_KEY'] = KEY + expect(await main(['--home', home, 'send', '@peer', 'hi'])).toBe(0) + expect(mcp.seen.length).toBeGreaterThan(0) + for (const call of mcp.seen) expect(call.headers['authorization']).toBe(`Bearer ${KEY}`) + }) + + it('a home with no key and one exported: refused too, as the listener refuses it', async () => { + fs.rmSync(path.join(home, 'credentials')) + process.env['AGENTCHAT_API_KEY'] = OTHER + expect(await main(['--home', home, 'send', '@peer', 'hi'])).toBe(1) + expect(err.join('\n')).toMatch(/there is none/) + expect(mcp.seen).toEqual([]) + }) +}) + +// `status`, `doctor` and `login` are the engine's: their refusals in words come +// with the agent-core release after 0.5.2, and this runs once the pin moves there. +describe.skipIf(!('envKeyConflict' in core))('the engine’s commands refuse another agent’s exported key', () => { + it('login does not adopt it and status refuses, both naming no key', async () => { + signIn('https://api.agentchat.test') + const other = 'ac_live_' + 'o'.repeat(40) + process.env['AGENTCHAT_API_KEY'] = other + expect(await main(['--home', home, 'login'])).toBe(1) + expect(await main(['--home', home, 'status'])).toBe(1) + expect(err.join('\n')).toContain('AGENTCHAT_API_KEY is exported') + expect([...out, ...err].join('\n')).not.toContain(other) + expect(JSON.parse(fs.readFileSync(path.join(home, 'credentials'), 'utf-8'))).toMatchObject({ api_key: KEY }) + }) +}) + +describe('every printed next command reaches the home it was given', () => { + it('a home that is not the default rides along as --home, quoted when it has to be; the default home adds nothing', async () => { + const { invocationFor, shellArg, defaultHome } = await import('../src/home.js') + expect(invocationFor(defaultHome(), {})).toBe('agentchat') + expect(invocationFor(home, {})).toBe(`agentchat --home ${shellArg(home)}`) + expect(invocationFor(home, { npm_command: 'exec' })).toBe(`npx -y @agentchatme/cli --home ${shellArg(home)}`) + // AGENTCHAT_HOME pointing elsewhere: even the default home rides along, since a bare command would not reach it. + expect(invocationFor(defaultHome(), { AGENTCHAT_HOME: home })).toBe(`agentchat --home ${shellArg(defaultHome())}`) + expect(shellArg('/tmp/a b', 'linux')).toBe(`'/tmp/a b'`) + expect(shellArg("/tmp/it's", 'linux')).toBe(`'/tmp/it'\\''s'`) + expect(shellArg('C:\\Users\\a b', 'win32')).toBe('"C:\\Users\\a b"') + }) + + it('status and the register gate name this home, so neither sends the user to ~/.agentchat (where `logout` would delete another agent\'s key)', async () => { + expect(await main(['--home', home, 'status'])).toBe(0) + expect(out.join('\n')).toContain(`Set one up with: ${invocation()} --home ${shellArg(home)} register`) + // The worst case of the finding: a home holding an identity says to log out first — of THIS home, never the default. + fs.writeFileSync(path.join(home, 'credentials'), JSON.stringify({ api_key: KEY, handle: 'probe' })) + err.length = 0 + expect(await main(['--home', home, 'register', '--email', 'a@example.com', '--handle', 'probe2'])).toBe(1) + expect(err.join('\n')).toContain(`Run \`${invocation()} --home ${shellArg(home)} logout\` first`) + }) + + it('the listener\'s and the hands\' refusals name the home too', () => { + expect(envKeyConflict(home, { AGENTCHAT_API_KEY: 'ac_live_' + 'z'.repeat(40) })).toContain(`agentchat --home ${shellArg(home)} login`) + }) +}) + describe('pure helpers', () => { it('bindPositionals: the last required parameter takes the rest; none required is refused', () => { expect(bindPositionals({ name: 't', inputSchema: { required: ['a', 'b'] } }, ['1', '2', '3'])).toEqual({ a: '1', b: '2 3' }) From 0e52017700f7ce1e8f6e2059ef0b3ebfa4fa66a6 Mon Sep 17 00:00:00 2001 From: San Date: Wed, 18 Nov 2026 11:19:02 -0800 Subject: [PATCH 2/2] docs(changelog): what the next agent-core brings, and release only with the pin moved --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82fff7b..6133a4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ All notable changes to `@agentchatme/cli` are recorded here. The format follows - **`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. - **Every printed next command carries the `--home` it acts on.** With `--home `, the commands the CLI printed next (`register --code`, `status`, `logout`, `listen --install`, the refusals' way out) left the home out, so run as printed they acted on `~/.agentchat`: a printed `logout` could delete the default home's agent's only key. They now name `--home ` (quoted when the path needs it) whenever the home is not `~/.agentchat`. -- The refusal names the way out without a key on a command line: `printenv AGENTCHAT_API_KEY | agentchat --home login --api-key -`. `doctor`'s check of it is now `env-key` and names every command it stops. +- The refusal names the way out without a key on a command line: `printenv AGENTCHAT_API_KEY | agentchat --home login --api-key -`. `doctor`'s `listener-identity` check names every command it stops. `status` and `doctor` probes use the home's key only. ### Docs