Skip to content
4 changes: 4 additions & 0 deletions .gitleaksignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@
16ed51f1b97aa99586ffb85af9f563236546d9cd:test/setup-slack.test.ts:slack-app-token:37
16ed51f1b97aa99586ffb85af9f563236546d9cd:test/setup-slack.test.ts:slack-app-token:94
16ed51f1b97aa99586ffb85af9f563236546d9cd:test/setup-slack.test.ts:slack-legacy-workspace-token:36

# Verified false positive: the fake password "hunter2" in a redaction test (test/turn-transcript.test.ts,
# `curl -u admin:hunter2` on the line after a `curl -d` fixture). Nothing real; the test checks it is removed.
b0522d0f661a0903711ea0b61ba23f8a63c552f8:test/turn-transcript.test.ts:curl-auth-user:157
53 changes: 53 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,59 @@ All notable changes to `@inceptionstack/roundhouse` are documented here.

## [Unreleased]

### Added
- **`/stop [question]`.** Ends the turn in progress like `/cancel`, then has a
sub-agent that can only read (`read`, `grep`, `find`, `ls`; no MCP, no
project context files, prompt templates, themes or project settings) review what the agent did
so far and post its report in the chat. The transcript it reads has obvious
secrets removed and every line behind a bar; the report has them removed
again. The report starts no agent turn; the agent hears about the stop with
the owner's next message, and gets the report as data with the first message
after it arrives (never with a "do not resume" line if the owner has written
since). A reviewer that fails or times out is reported. Needs
`AgentAdapter.describeTurn` (implemented for pi).
After its first live use: the transcript begins with the exchange before the
stopped turn (reviewers could not tell what a "yes" referred to); every
stopped turn gets its own review, up to two at a time, and each report is
titled with the time of its stop; roundhouse's memory-save prompt no longer
counts as the owner's request; a turn whose request was compacted away is
still reviewed; a turn waiting behind a memory save is recognised as not yet
begun; `/stop` on a turn that is already stopped aborts the agent again and
starts nothing else.
- Sub-agents can be given a tool allowlist (`SpawnSpec.tools`, pi's `--tools`
plus the flags that close everything else), files to read in their run folder
(`SpawnSpec.files`), and a delivery (`SpawnSpec.delivery: "chat"`: post the
output instead of handing it to the agent). The delivery is stored with the run,
so it survives a restart.

### Fixed
- **A request cancelled before it had started ran anyway, unseen.** `/cancel`
(and `/stop`) on a message that was still waiting, behind a memory save or
while its conversation was being opened, answered "cancelled" and aborted
whatever was running; the waiting request then started and ran in full with
nobody reading its output. The pi adapter now drops a streamed prompt that was
asked for before its thread was aborted, and aborts again a run that begins
after the abort. What such a message carried (the memory files, a note about
an earlier `/stop`) goes with the next message instead of being lost
(`PromptHooks.onStart`, `AdapterInfo.reportsPromptStart`).
- **A prompt that failed before it started lost the memory files it carried,
and its error.** When the session would not open, or pi's own checks failed
(expired credentials), the memory state already said "injected", so the next
message went out without the files; and the stream could end before the
error was recorded, so the owner saw "Agent returned no response" instead of
the error. The gateway now re-arms the injection on the error path too, the
pi adapter counts a prompt as started only when pi reports it
(`preflightResult`), and the error is recorded before the stream ends.
- A sub-agent's result that arrived while a turn was running took that turn's
place as "the turn in this chat" (and the owner's message did the same to a
result's turn), so `/cancel` and `/stop` acted on the turn that was waiting.
A turn now takes the place when it gets the thread lock.
- **A sub-agent that hung was never cut off by the gateway that started it.** The
watcher leaves runs started in the same process alone, and nothing else
enforced their deadline. `spawn()` now arms a timer for it.
- A sub-agent that could not be started no longer leaves its run folder behind,
and its logs are created with mode 0600.

## [0.7.0] — 2026-11-22

> **Upgrade notes.** Needs Node >= 22.19 and pi 1.x.
Expand Down
4 changes: 4 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,12 @@ If `promptStream` is missing, `agent.prompt()` is called and the full text is sp

**Handlers return at once; the turn runs detached.** The Chat SDK's Telegram polling awaits a message handler before it asks for more updates. A handler that awaited the agent turn made the bot deaf for the length of the turn (`/cancel` could not arrive). `accept()` in `Gateway.start()` starts the work and returns; `inFlightWork` tracks it and `whenIdle()` waits for it (tests use that). Messages are chained per chat in arrival order, because `handle()` awaits pairing and attachment downloads before the turn lock. Only commands about the running turn or the gateway skip the chain: the pre-turn ones and descriptors marked `immediate` (`skipsTheLine`). `/new`, `/topic`, `/compact` and commands the gateway does not know (prompts for the agent) stay in line; letting them jump moved earlier messages into the wrong conversation. Button handlers (`onAction`) are detached the same way. `test/telegram-slash-integration.test.ts` drives the adapter's real polling loop and fails if a handler blocks again. Consequence: Telegram considers a message delivered before its turn ends, so a turn cut off by a restart is not redelivered. `accept()` therefore writes a marker in `~/.roundhouse/in-flight/` for every allowed request, removed when its work ends, so it survives only a request that was cut off or never started. The next gateway reads the markers before `chat.initialize()` (a message waiting at Telegram starts its turn, and writes its own marker, the moment polling begins) and reports that snapshot, one notice per chat, instead of re-running anything. `Gateway.stop()` stops polling first for the same reason. `/cancel` acts on `runningTurns` (keyed by chat, set when the turn is accepted), not on the session the chat currently points at.

**`/stop` is `/cancel` plus a review, and the review is read-only.** `handleStop` (`src/gateway/stop-command.ts`) is a pre-turn command: it takes a snapshot of the turn (`describeTurn()`; pi: `renderTurn()` over `session.messages`, which must not go through the thread queue because the turn holds it), aborts the running turn exactly as `/cancel` does, sets the agent's note (`StopNotes.stop`) *in the same tick as the abort* so the next queued message cannot slip past its check, then spawns a `review` sub-agent with `tools: ["read","grep","find","ls"]` (the launcher adds `--no-mcp --no-context-files --no-prompt-templates --no-themes --no-approve`: `--tools` alone keeps MCP tools, and the working directory's `AGENTS.md` is text the stopped agent could have written), `delivery: "chat"`, and the turn as `turn.md` in the run folder (`SpawnSpec.files`). A turn whose abort signal is already set (stopped or cancelled a moment ago, still winding down) is not noted or reviewed again, but `agent.abort` is still called: after an abort the turn can be saving memory or compacting, and the first abort may not have taken. It reviews the snapshot taken before the abort when a later request has begun by the time the abort settles; it does not review at all when the turn's request is not in the conversation yet (`running.started` false, or `TurnDescription.reached === false`: the pi adapter stamps `promptStartedAt` when a prompt leaves its queue and compares the last user message's timestamp with it), because the last user message is then an earlier turn; two snapshots are told apart by `requestAt`, not by the words of the request. (The adapter's mark is `promptAskedAt`, set when `promptStream`'s iterator starts, not when the prompt leaves the thread queue: a turn queued behind a memory save has not begun either.) In `renderTurn` a turn starts at the last user message that is not the gateway's memory-save prompt (`MAINTENANCE_PROMPT_RE`; a test holds it to `buildFlushPrompt`), falls back to the last `compactionSummary` when the request was compacted away (`requestAt` is then the summary's time), and is preceded by the exchange before it (`contextBefore`: the previous owner message and the end of the assistant's last reply), which is context for the reviewer and never counted as steps. Keep the reviewer without a shell: the transcript is untrusted text. `renderTurn` puts every line of request, speech, call arguments and results behind `│ `, removes obvious secrets (`redactSecrets`, best effort), and marks a call with no result. `handleSubagentCompletion` sends a `delivery: "chat"` run to `deliverReviewToChat` (redact, post, delete `turn.md`, hand the report to `StopNotes.report`) instead of `injectSubagentResult`; the delivery is stored in `status.json`, so a restart between spawn and completion still posts. `StopNotes` (in memory; a list of records per session, one per stop, each with its own review, at most `MAX_ACTIVE_REVIEWS` running) gives each stop note once and each report once: `peek()` in `handleAgentTurn` after the checks that can drop the turn and after transcription, `commit()` only when the prompt starts, so a message dropped in between leaves the note for the next one; `pending` keeps a record alive while `/stop` is still starting the reviewer; a report is matched to its stop by run id (so two reviews can finish in either order, and the post's title carries the stop's time), and the report text has `<` `>` replaced so it cannot close its `<stop_review>` wrapper. `SubAgentOrchestratorImpl.spawn` arms a deadline timer: the watcher skips runs the same process started, so nothing else enforces it. `test/stop-review.test.ts` drives the gateway with a fake agent and sub-agent service.

**Commands that change the conversation go through the adapter.** `/new` calls `restart()`, which leaves a `.new-session` marker in the thread's session directory; `createSession` then uses `SessionManager.create` instead of `continueRecent` (which reopens the newest transcript, i.e. the one just closed) and records the fresh session's file name in the marker. The marker goes once a prompt in that session completes, or at the next `createSession` if the named file exists (pi writes the transcript as soon as the first message is appended, so a restart in the middle of the first turn resumes that session instead of starting a third). `/model` writes pi's default and calls `setModel()`, which uses `session.setModel()` on purpose: pi restores a session's model from its transcript, so the default alone never reaches an existing conversation. (The temporary flush/compaction swaps still avoid `setModel()`.) `/think` uses `thinkingLevel()`.

**An abort also cancels what has not started.** `session.abort()` stops what is running; a streamed prompt that is still waiting in the thread queue (behind a memory save), opening its session or loading images is not running yet, and used to start afterwards and run in full with nobody reading. `promptStream` takes a number from a counter when it is called, `abort()` records a later one for the thread before anything else, and `runPromptAndFollowUps` returns without calling `session.prompt` when the abort is the later of the two (`test/pi-adapter-session.test.ts`). A run that begins after such an abort all the same (pi's `abort()` only reaches a run that is under way, not one still in `prompt()`'s preflight) is aborted again at its `agent_start`. The non-streamed path (`doPrompt`: memory flush, cron) is not covered, on purpose: a skipped flush would be recorded as done. The adapter also tells the gateway when the agent really has a message (`PromptHooks.onStart`, `AdapterInfo.reportsPromptStart`). The moment is pi's own: `session.prompt()` is given `preflightResult`, and `"started"` comes only after pi's checks (input hooks, model, credentials, the run's first messages); a prompt that fails them throws without it, one an extension takes over reports `"handled"`, and one pi puts off (it arrived while `agent_settled` handlers ran, so `prompt()` comes back at once) reports when its turn comes. Nothing else counts: do not add a "it came back, so it ran" fallback. The options object is typed `PromptOptions`, so a pi without `preflightResult` fails the type check rather than making every message look undelivered. Until then what the message carries counts as undelivered: the `/stop` note is committed on it, and a memory injection is re-armed (`rearmMemoryInjection`) when the turn ends without it, **whichever way it ends** (`rearmIfUndelivered` runs after the stream and in the catch): a cancelled prompt ends its stream quietly, a failed one throws. An error from `runPromptAndFollowUps` is put in the stream's error slot before the stream is marked done; set later (by the handler on the queue's promise) it lost a race with the reader, and a prompt that failed before producing anything was shown as "Agent returned no response" and skipped the gateway's error path. In the gateway, `runningTurns` holds a turn from the moment it is accepted only if the chat has no record; a turn that arrives while another holds the place (a sub-agent's result during the owner's turn, or his message during the result's) registers when it gets the thread lock, so `/cancel` and `/stop` always act on the turn that is running.

**Thread serialization.** The pi adapter keeps one queue per `threadId` (`threadQueues` in pi.ts). `prompt()` and `promptStream()` both `enqueue()` onto this chain so overlapping user messages in the same thread never race inside the pi session. Don't remove this — pi sessions are not safe for concurrent prompts.

**Per-thread sessions persist as `.jsonl`** at `<sessionDir>/<threadIdToDir(threadId)>/<session>.jsonl` (default `~/.roundhouse/sessions/`). Thread IDs are encoded reversibly by `threadIdToDir` in `src/util.ts` (`_` → `__`, `:` → `_c`, other → `_xNNNN`) so that `telegram:123` and `telegram_123` do not collide. `SessionManager.continueRecent` resumes the most recent jsonl in that dir; `SessionManager.create` starts a new one if none exist.
Expand Down
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,7 @@ Roundhouse automatically registers these commands with Telegram on startup:
| `/verbose` | Toggle tool status messages on/off for this chat |
| `/status` | Show gateway status: version, agent, model, context usage, uptime, etc. |
| `/cancel` | Stop the current agent run (abort tools, LLM calls, compaction) |
| `/stop [question]` | Stop the current agent run, then have a read-only sub-agent review what it did so far and report here |
| `/restart` | Restart the gateway service (requires `allowedUsers` to be configured) |
| `/doctor` | Run health checks and show system status |
| `/crons` | Manage scheduled jobs (list, trigger, pause, resume) |
Expand Down Expand Up @@ -357,6 +358,14 @@ Toggles verbose mode for the current chat. When ON, shows tool call status messa

Aborts the current agent run for this chat — stops any in-progress tool calls, LLM generation, and compaction. The session is preserved; send another message to continue the conversation.

### `/stop`

Ends the turn in progress the way `/cancel` does, then hands what the agent did so far to a reviewer: a sub-agent that can read and search files and nothing else (`read`, `grep`, `find`, `ls`: no shell, no edits, no MCP, and none of the working directory's `AGENTS.md`/`CLAUDE.md`, prompt templates, themes or project settings, which the agent under review could have written). The reviewer gets the turn as a file (the exchange just before it, so that a request like "yes" can be understood; then your request, what the agent said, each tool call and what came back; long output shortened, every line behind a `│` so tool output cannot pass for the transcript's own structure, and obvious secrets such as bot tokens, API keys, passphrases and private keys removed) and answers in six parts: what was asked, what is done, what was in progress, problems, what is left behind to undo, and a suggestion. Add a question after the command (`/stop why did it touch the router?`) and the reviewer answers that too.

The report is posted in the chat as it is (secrets removed again, and titled with the time of the stop it is about), usually within a minute or two, and **no agent turn starts because of it**: the agent that was stopped does not start working again. With your next message the agent is told that the turn was stopped on purpose, and with the first message after the report arrives it is given the report to weigh as data. Each comes once; they are kept in memory, so a restart drops them, and a stop that you never write after is forgotten after 12 hours.

Edge cases: with nothing running, `/stop` says so. Before the agent has your request in its conversation (it is still fetching an attachment, waiting for the turn before it, or getting ready) there is nothing of the turn to review, and only the stop happens: the request is dropped and never runs (it used to run after the memory save it had been waiting behind), and the agent is then told you cancelled a message it never saw. Every stopped turn gets its own review, up to two running at a time; a third turn stopped while both still run is stopped but not reviewed, and you are told. A second `/stop` on a turn that is already stopped (or was cancelled) and is still winding down tells the agent to stop again and starts nothing else. roundhouse's own memory-save prompt is not taken for a request of yours: a stop while memory is being saved reviews the turn that led to it. A turn so long that its request was compacted away is reviewed from the compaction on, and the transcript says so. If the reviewer fails or runs out of its 10 minutes, you are told, and the turn it was given stays in `~/.roundhouse/subagents/<run>/turn.md`; after a delivered report that file is deleted (the rest of the run folder, with the report in `stdout.log`, stays, mode 0700). `/stop` needs an agent that can describe its turn (pi can; kiro cannot, and is only stopped). The report is posted to the chat, not to a forum topic or Slack thread, so use it in a private chat (`chat.dmOnly`).

### Follow-up notifications

When extensions (e.g. code review) queue follow-up work after the agent responds, the gateway shows:
Expand All @@ -367,7 +376,7 @@ Fast operations that complete within 2 seconds show no extra messages.

## While the agent is working

Messages are received while a turn runs. Commands about the turn in progress or the gateway (`/cancel`, `/status`, `/model`, `/think`, `/verbose`, `/doctor`, `/crons`, `/restart`, `/later`) are handled at once; `/model` and `/think` answer at once and take effect when the turn ends. Everything else waits its turn in the order sent: ordinary messages, `/new`, `/topic`, `/compact`, and commands meant for the agent.
Messages are received while a turn runs. Commands about the turn in progress or the gateway (`/cancel`, `/stop`, `/status`, `/model`, `/think`, `/verbose`, `/doctor`, `/crons`, `/restart`, `/later`) are handled at once; `/model` and `/think` answer at once and take effect when the turn ends. Everything else waits its turn in the order sent: ordinary messages, `/new`, `/topic`, `/compact`, and commands meant for the agent.

If the gateway is restarted or dies before it has finished your requests, they are not run again. The next gateway lists the requests that were cut off or still waiting; say "continue" or send them again.

Expand Down
Loading
Loading