Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(core): run chats concurrently — one lane per chat, one memory governor (ADR-037)

Salman Qureshi1eb3475ff987
diff --git a/.env.example b/.env.example
index 89a368f2..d6ba71df 100644
--- a/.env.example
+++ b/.env.example
@@ -163,3 +163,6 @@ SPOTIFY_REDIRECT_URI=http://127.0.0.1:8888/callback
# Opt in to on-demand plugin/MCP schemas in the main agent (default: false).
MERCURY_TOOL_DISCOVERY=false
+
+# Chats answered at the same time (0 = automatic: up to 4, 2 on Termux/small machines).
+MERCURY_MAX_CONCURRENT_TURNS=0
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 083f9c93..33e075ab 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -101,6 +101,28 @@ User message → Agent loads system prompt (soul + guardrails + persona)
→ Agent sends final response via channel
```
+## Concurrent Sessions
+
+Several chats are answered at once (ADR-037). A turn mostly waits on the model provider, so turns share one process and one event loop. There are no threads; worker threads would copy the heap per turn without making a turn faster, which matters on Termux.
+
+```
+message → lane (a session id, else channel + conversation; the terminal is one lane)
+ → waiting line (first come, first served; voice-call questions and "do mine first" go ahead)
+ → admitted when its lane is free AND the turn governor has room
+ → runs inside its own turn scope (AsyncLocalStorage)
+```
+
+| Piece | File | Role |
+|---|---|---|
+| Lanes + pump | `src/core/agent.ts` (`laneKeyFor`, `processQueue`, `startTurn`) | One turn per lane at a time; lanes run concurrently |
+| Turn state | `src/core/agent.ts` (`TurnState`) | Message, abort, activity, steps, work key, lifecycle, programming mode — per turn |
+| Turn scope | `src/utils/turn-scope.ts` | `ScopedValue`: per-turn working directory, tools switch, image switch |
+| Permission overlay | `src/capabilities/permissions.ts` (`withTurn`) | Per-turn channel, session, sender role, skill elevation, internal grant, plugin grants; Allow All and approved scopes stay shared |
+| Turn governor | `src/core/turn-governor.ts` | Concurrency limit (auto from heap/RAM/platform, `concurrency.maxTurns`), admission, one process-wide heap watch that stops the newest turn under pressure |
+| Conversation lock | `src/core/agent.ts` (`lockSession`) | Two lanes reaching one stored conversation take it one at a time |
+
+`/stop` stops the chat it was typed in (and the sub-agents it started); `/halt` stops every chat.
+
## Permission System
### Filesystem Permissions (folder-level scoping)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 98052963..ea6ea51e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,11 @@
## Unreleased
+### Chats at the same time
+- **Mercury answers several chats at once.** A long research run or coding task in one chat no longer makes the terminal, Telegram, the desktop app or a scheduled task wait. Each chat still handles its own messages in order.
+- **Sized to your machine.** Up to 4 chats run at once, 3 under 8 GB of RAM, and 2 on Termux or under 4 GB. When memory runs short, new chats wait for a free slot, and if memory keeps growing the most recently started task stops while the rest carry on. Set `concurrency.maxTurns` in `mercury.yaml` (or `MERCURY_MAX_CONCURRENT_TURNS`) to choose the limit; `1` restores one chat at a time.
+- **`/stop` stops the chat you're in.** Esc in the terminal, the Stop button in Mercury Desktop and `/stop` in Telegram stop that chat's task and the sub-agents it started. `/halt` still stops everything.
+
### Providers
- **Remote Ollama behind a username and password.** Set `username` and `password` on Ollama Local, OpenAI-compatible, LM Studio, LiteLLM or Atomic Chat in `mercury.yaml`. Mercury sends them as HTTP Basic auth for chat and for model lists, instead of a Bearer key.
diff --git a/DECISIONS.md b/DECISIONS.md
index 2c678bd9..53806623 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -375,3 +375,15 @@
- **Desktop**: Tauri updater for discovery, our own resumable download (Range/If-Range, retries, stall detection) with the package verified before it counts as ready; install on "Restart to update" or on quit. A Chrome-style top-right button whose colour rises with age (red at once for security), a panel with notes before you update and progress for the app and every connected server, "Later" for 24 h. A force-update screen for a verified minimum that only a ticked risk checklist gets past, until the next launch or 24 h, while the button stays red. "What's new" toasts after any update, once per version. Manifest messages as one toast (info) or a banner (warning/critical).
- **Releases**: `.github/workflows/desktop-release.yml` (manual) builds signed bundles and `latest.json` into a draft; `scripts/promote-desktop-release.mjs` copies `latest.json` to the website and records the release in the manifest. `scripts/publish.sh` reminds to record server releases.
- **Consequence**: An update either finishes or puts you back where you were; nothing pops up uninvited except a verified required update; one key (`~/.tauri/mercury-updates.key` + password, also needed as GitHub secrets) controls what every install trusts, so losing it means desktop updates stop and must be replaced by a manual reinstall.
+
+## ADR-037: Chats run at the same time — one lane per chat, one governor for memory
+
+- **Context**: The main agent answered one message at a time across every chat and channel. A long research run or coding task in one chat left every other chat (terminal, Telegram, the desktop app, scheduled work) waiting, often for minutes. All turn state lived on the single `Agent` instance: the running message, its abort controller, progress and step narrative, the work-ledger key, the lifecycle, the programming mode, and, in the capability registry, the working directory, the tools switch and the permission identity. Two turns at once would overwrite each other. A heap guard ran per turn against that turn's own baseline, which is meaningless with several turns sharing one heap.
+- **Decision**:
+ - **Async concurrency in one process, not threads.** A turn spends almost all its time waiting on a provider stream. Worker threads would each load the whole runtime and its own heap without making a turn faster, which is the wrong trade on Termux and small VMs. Other agent runtimes do the same: OpenClaw runs one lane per session with a global concurrency cap.
+ - **Lanes.** Every message gets a lane key: its canonical session when it names one, otherwise channel plus conversation. The terminal is one lane, and each scheduled task is its own. One turn runs per lane, in order. Different lanes run together. The waiting line stays first-come, first-served, with the existing voice-call priority and "do mine first". A message waits only for its own lane or for a free slot. Two lanes that reach the same stored conversation take it one at a time (`lockSession`), so its history never interleaves.
+ - **Per-turn state.** Each turn has a `TurnState` carried by `AsyncLocalStorage` through everything it awaits, including AI SDK callbacks, tool executions and timers. The agent's old fields (`currentMessage`, `currentAbort`, `currentActivity`, …) became accessors for the calling turn's state, so the 2,000-line turn handler stays unchanged. Outside a turn they are empty. Code that acts on a chat from outside (fast-path commands, the web/cloud stop, research finish, `/bg current`) looks up that chat's turn explicitly.
+ - **Scoped capabilities.** `ScopedValue` (`src/utils/turn-scope.ts`) gives a turn its own working directory, tools switch and "model sees images" switch. A turn starts in its chat's last directory, and the terminal's `cd` still carries over to the terminal. Permissions get a turn overlay (`PermissionManager.withTurn`): channel, session, sender role, skill elevation, the internal turn's allow-all grant and scheduled plugin grants belong to the turn, while the owner's Allow All and approved scopes stay shared and live, as before. Sub-agents keep their own derived contexts (ADR-016). A desktop Code session gets its own `ProgrammingMode` instance instead of swapping the global one. Research runs are tracked per chat.
+ - **One governor.** `TurnGovernor` sets the limit: heap headroom divided by a 192 MB per-turn budget, capped at 4, 3 under 8 GB of RAM, 2 on Termux or under 4 GB. `concurrency.maxTurns` / `MERCURY_MAX_CONCURRENT_TURNS` overrides it (1–16). It admits a turn only while the heap leaves that turn its budget (and, on Linux/Android, while the OS still has memory available), and always admits one when nothing runs. A single process-wide timer replaces the per-turn guard. The stop line is the old single-task line with one turn running and widens by one budget per extra turn. Past it, the newest turn is stopped, one per 5 s cooldown, after each turn has first compacted its own conversation. Past the exit line the process exits with a crash flag, so the work ledger recovers every interrupted chat.
+ - **Stopping.** `/stop`, Esc, the desktop Stop button and a cloud `task.stop` stop that chat's turn and the sub-agents it started. With nothing else running, `/stop` is the full stop it was (locks released, task board cleared). `/halt` stops everything.
+- **Consequence**: Chats no longer block each other, up to the limit. What stays shared is deliberate: the owner's Allow All, approved scopes, token budget, provider fallback state and permission-answer evidence for learning. The terminal's live feed shows the terminal's own turn and mirrors another chat's only while the terminal is idle. A `/workspace` or `cd` from a remote chat now moves only that chat, not the terminal. Recovered interrupted work resumes concurrently after a restart, still one turn per chat.
diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.ts
index 810738f8..f8663607 100644
--- a/apps/desktop/src/api/mercury.ts
+++ b/apps/desktop/src/api/mercury.ts
@@ -76,8 +76,12 @@ export const chat = {
deleteThread: (id: string) => http.post<{ deleted: boolean }>(`/api/chat/threads/${encodeURIComponent(id)}/delete`, { confirmSessionId: id }),
send: (content: string, sessionId?: string, attachments?: Array<{ name: string; data: string }>, code?: { programming: string; cwd?: string }) =>
http.post<{ sent: boolean; sessionId: string }>("/api/chat/send", { content, sessionId, ...(attachments?.length ? { attachments } : {}), ...(code ?? {}) }),
- /** Interrupt the running turn (same as /stop). Needs the "chat.stop" feature. */
- stop: () => http.post<{ ok: boolean; note?: string }>("/api/chat/stop", {}),
+ /**
+ * Interrupt a running turn (same as /stop). With a thread, only that chat's
+ * turn stops (runtimes that run chats at once); without one, everything.
+ * Needs the "chat.stop" feature.
+ */
+ stop: (threadId?: string | null) => http.post<{ ok: boolean; note?: string }>("/api/chat/stop", threadId ? { threadId } : {}),
/** Take back your last message and the reply (stop the turn first); returns your text. */
save: (threadId: string, saved: boolean) => http.post<{ id: string; saved: boolean; savedAt: string | null }>(`/api/chat/threads/${encodeURIComponent(threadId)}/save`, { saved }),
undo: (threadId: string, content: string) => http.post<{ ok: boolean; content: string; removed: number }>(`/api/chat/threads/${encodeURIComponent(threadId)}/undo`, { content }),
diff --git a/apps/desktop/src/app/conversation.ts b/apps/desktop/src/app/conversation.ts
index 4690a4bb..0b44715d 100644
--- a/apps/desktop/src/app/conversation.ts
+++ b/apps/desktop/src/app/conversation.ts
@@ -26,8 +26,8 @@ export interface ConversationState {
/** The stop button was pressed and the runtime hasn't confirmed yet. */
stopping: boolean;
/**
- * This chat's message is waiting in line: Mercury runs one turn at a time
- * and another chat's is running. Cleared when this chat's turn starts.
+ * This chat's message is waiting in line: every slot the runtime runs
+ * chats in is taken. Cleared when this chat's turn starts.
*/
waiting: { position: number; busyWith?: string; busySessionId?: string } | null;
setWaiting(waiting: ConversationState["waiting"]): void;
diff --git a/apps/desktop/src/app/events.ts b/apps/desktop/src/app/events.ts
index 8766daf9..345a547a 100644
--- a/apps/desktop/src/app/events.ts
+++ b/apps/desktop/src/app/events.ts
@@ -440,7 +440,7 @@ export async function stopTurn(store: ConversationStore): Promise<void> {
s.setStopping(true);
if (s.live) s.setLive((l) => ({ ...l, steps: l.steps.map((st) => (st.status === "running" ? { ...st, status: "stopped" as const, endedAt: Date.now() } : st)) }));
try {
- await api.chat.stop();
+ await api.chat.stop(s.activeId);
} catch (err) {
store.getState().setStopping(false);
throw err;
diff --git a/apps/desktop/src/views/chat/Waiting.tsx b/apps/desktop/src/views/chat/Waiting.tsx
index 6169bf90..a7fb66b8 100644
--- a/apps/desktop/src/views/chat/Waiting.tsx
+++ b/apps/desktop/src/views/chat/Waiting.tsx
@@ -8,9 +8,9 @@ import { Button } from "~/components/ui/Button";
import { ConfirmButton } from "~/components/ui/kit";
/**
- * In place of "Thinking" while this chat's message waits its turn: Mercury
- * works on one thing at a time, and another chat is ahead. Says which one and
- * what it's doing, and offers to open it or to go first (which stops it).
+ * In place of "Thinking" while this chat's message waits its turn: every
+ * slot Mercury runs chats in is taken, and another chat is ahead. Says which
+ * one and what it's doing, and offers to open it or to go first (which stops it).
*/
export function WaitingNotice({ threadId, waiting }: { threadId: string | null; waiting: { position: number; busyWith?: string; busySessionId?: string } }) {
const threads = useChat((s) => s.threads);
@@ -26,7 +26,8 @@ export function WaitingNotice({ threadId, waiting }: { threadId: string | null;
setProblem(null);
try {
await api.chat.queueFirst(threadId);
- await api.chat.stop();
+ // Stop only the chat this one waits for, not every running chat.
+ await api.chat.stop(waiting.busySessionId);
} catch (e) {
setProblem(e instanceof Error ? e.message : String(e));
} finally {
@@ -47,7 +48,7 @@ export function WaitingNotice({ threadId, waiting }: { threadId: string | null;
<div className="flex items-start gap-2.5">
<Clock size={15} className="mt-0.5 shrink-0 text-ink3" aria-hidden="true" />
<p className="text-sm text-ink2">
- <span className="font-medium text-ink">Waiting.</span> Mercury works on one thing at a time and is finishing{" "}
+ <span className="font-medium text-ink">Waiting.</span> Mercury is busy with other chats and is finishing{" "}
{waiting.busyWith ? <>“{waiting.busyWith}”</> : "something"} in <span className="text-ink">{otherName}</span>.{ahead}
</p>
</div>
diff --git a/src/capabilities/permission-context.ts b/src/capabilities/permission-context.ts
index ae685d93..965cb532 100644
--- a/src/capabilities/permission-context.ts
+++ b/src/capabilities/permission-context.ts
@@ -158,6 +158,33 @@ export function isSubsetContext(child: PermissionContext, parent: PermissionCont
export interface ContextCell {
readonly owner: object;
ctx: PermissionContext;
+ /**
+ * Set for a main-agent turn running alongside others (ADR-037). The turn
+ * has no frozen context of its own: it reads the shared session context
+ * with its own identity laid over it, so the owner's choices (Allow All,
+ * approved scopes) apply to every chat at once, while who is asking,
+ * from where, with which skill elevation or internal grant stays with
+ * the turn. `ctx` is unused for such a cell.
+ */
+ turn?: TurnOverlay;
+}
+
+/** Context fields that belong to one turn, never to the shared session. */
+export const TURN_OWNED_FIELDS = ['channelType', 'channelId', 'sessionId', 'senderRole', 'rememberApprovals', 'elevated'] as const;
+export type TurnOwnedField = typeof TURN_OWNED_FIELDS[number];
+
+export interface TurnOverlay {
+ fields: { -readonly [K in TurnOwnedField]?: PermissionContext[K] };
+ /** The internal turn's allow-all grant (beginTurnGrant), if any. */
+ grant: { scopes: ContextScope[] } | null;
+ /** Plugin tools pre-approved for this turn (a scheduled task's allowTools). */
+ pluginGrants: Set<string>;
+ /** Last computed context, valid while the session context is the same object. */
+ cache: { session: PermissionContext; ctx: PermissionContext } | null;
+}
+
+export function newTurnOverlay(): TurnOverlay {
+ return { fields: {}, grant: null, pluginGrants: new Set(), cache: null };
}
export const permissionContextStore = new AsyncLocalStorage<ContextCell>();
diff --git a/src/capabilities/permissions-turn.test.ts b/src/capabilities/permissions-turn.test.ts
new file mode 100644
index 00000000..acef827f
--- /dev/null
+++ b/src/capabilities/permissions-turn.test.ts
@@ -0,0 +1,151 @@
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import { rmSync } from 'node:fs';
+
+// permissions.yaml lives under MERCURY_HOME, resolved at import time.
+const home = await vi.hoisted(async () => {
+ const { mkdtempSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ const { join } = await import('node:path');
+ const dir = mkdtempSync(join(tmpdir(), 'mercury-turn-'));
+ process.env.MERCURY_HOME = dir;
+ return dir;
+});
+
+const { PermissionManager } = await import('./permissions.js');
+const { deriveChildContext } = await import('./permission-context.js');
+
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+const tick = (ms = 2) => new Promise((r) => setTimeout(r, ms));
+
+describe('concurrent turns (ADR-037)', () => {
+ it('each turn keeps its own channel, session and sender across awaits', async () => {
+ const pm = new PermissionManager();
+ const seen: string[] = [];
+ const turn = (channel: string, role: 'admin' | 'member', delay: number) => pm.withTurn(async () => {
+ pm.setCurrentContext('telegram', channel, `s-${channel}`);
+ pm.setCurrentSenderRole(role);
+ await tick(delay);
+ const ctx = pm.currentContext();
+ seen.push(`${ctx.channelId}/${ctx.sessionId}/${ctx.senderRole}`);
+ });
+ await Promise.all([turn('a', 'admin', 6), turn('b', 'member', 1)]);
+ expect(seen.sort()).toEqual(['a/s-a/admin', 'b/s-b/member']);
+ // The shared session context was never touched by either turn's identity.
+ expect(pm.currentContext().channelId).toBe('cli');
+ });
+
+ it("the owner's Allow All and approved scopes are shared, live, with running turns", async () => {
+ const pm = new PermissionManager();
+ let release!: () => void;
+ const gate = new Promise<void>((r) => { release = r; });
+ const result = pm.withTurn(async () => {
+ pm.setCurrentContext('web', 'w1');
+ await gate;
+ return pm.currentContext();
+ });
+ // Outside any turn (e.g. the /permissions fast path): owner changes the session.
+ pm.setAutoApproveAll(true);
+ pm.addTempScope('/tmp/approved-here', true, true);
+ release();
+ const ctx = await result;
+ expect(ctx.autoApprove).toBe(true);
+ expect(ctx.channelId).toBe('w1');
+ expect(ctx.scopes.some((s) => s.path.endsWith('approved-here'))).toBe(true);
+ });
+
+ it('a scope approved inside a turn lands on the shared session (as before)', async () => {
+ const pm = new PermissionManager();
+ await pm.withTurn(async () => {
+ pm.setCurrentContext('web', 'w1');
+ pm.addTempScope('/tmp/granted-in-turn', true, false);
+ });
+ expect(pm.currentContext().scopes.some((s) => s.path.endsWith('granted-in-turn'))).toBe(true);
+ expect(pm.currentContext().channelId).toBe('cli');
+ });
+
+ it("an internal turn's grant stays with that turn; a concurrent chat turn never sees it", async () => {
+ const pm = new PermissionManager();
+ let release!: () => void;
+ const gate = new Promise<void>((r) => { release = r; });
+ const internal = pm.withTurn(async () => {
+ pm.setCurrentContext('internal', 'sched');
+ pm.beginTurnGrant({ scopes: [{ path: '/', read: true, write: true }] });
+ await gate;
+ const ctx = pm.currentContext();
+ pm.endTurnGrant();
+ return ctx;
+ });
+ const chat = await pm.withTurn(async () => {
+ pm.setCurrentContext('telegram', 't1');
+ await tick();
+ return pm.currentContext();
+ });
+ release();
+ const internalCtx = await internal;
+ expect(internalCtx.autoApprove).toBe(true);
+ expect(internalCtx.autoApproveOrigin).toBe('turn');
+ expect(chat.autoApprove).toBe(false);
+ expect(chat.scopes.some((s) => s.path === '/')).toBe(false);
+ // Never baked into the session.
+ expect(pm.currentContext().autoApprove).toBe(false);
+ expect(pm.currentContext().scopes.some((s) => s.path === '/')).toBe(false);
+ });
+
+ it('skill elevation stays with the turn that asked for it', async () => {
+ const pm = new PermissionManager();
+ let release!: () => void;
+ const gate = new Promise<void>((r) => { release = r; });
+ const elevated = pm.withTurn(async () => {
+ pm.elevateForSkill(['run_command']);
+ await gate;
+ return pm.isShellElevated();
+ });
+ const other = await pm.withTurn(async () => {
+ await tick();
+ return pm.isShellElevated();
+ });
+ release();
+ expect(await elevated).toBe(true);
+ expect(other).toBe(false);
+ expect(pm.isShellElevated()).toBe(false);
+ });
+
+ it("plugin grants belong to the turn that set them", async () => {
+ const pm = new PermissionManager();
+ const ask = vi.fn().mockResolvedValue('no');
+ pm.onAsk(ask);
+ let release!: () => void;
+ const gate = new Promise<void>((r) => { release = r; });
+ const granted = pm.withTurn(async () => {
+ pm.setCurrentContext('telegram', 'x');
+ pm.setTurnPluginGrants(['plug:tool']);
+ await gate;
+ return pm.approvePluginTool('plug:tool', 'ok?');
+ });
+ const denied = await pm.withTurn(async () => {
+ pm.setCurrentContext('telegram', 'y');
+ return pm.approvePluginTool('plug:tool', 'ok?');
+ });
+ release();
+ expect(await granted).toBe(true);
+ expect(denied).toBe(false);
+ expect(ask).toHaveBeenCalledOnce();
+ });
+
+ it('a sub-agent inside a turn still runs on its own derived context', async () => {
+ const pm = new PermissionManager();
+ await pm.withTurn(async () => {
+ pm.setCurrentContext('web', 'parent');
+ pm.elevateForSkill(['run_command']);
+ const child = deriveChildContext(pm.currentContext());
+ await pm.withContext(child, async () => {
+ expect(pm.currentContext().channelId).toBe('parent');
+ expect(pm.isShellElevated()).toBe(false);
+ pm.setCurrentContext('web', 'child-moved');
+ });
+ expect(pm.currentContext().channelId).toBe('parent');
+ expect(pm.isShellElevated()).toBe(true);
+ });
+ });
+});
diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.ts
index 1baf59d3..b024ed96 100644
--- a/src/capabilities/permissions.ts
+++ b/src/capabilities/permissions.ts
@@ -17,10 +17,23 @@ import {
makeContext,
withChanges,
permissionContextStore,
+ newTurnOverlay,
+ TURN_OWNED_FIELDS,
type PermissionContext,
type ContextScope,
+ type TurnOverlay,
} from './permission-context.js';
+/** `ctx` with an internal turn's allow-all grant applied (origin `turn` unless the owner already allowed all). */
+function applyTurnGrant(ctx: PermissionContext, grant: { scopes: ContextScope[] } | null): PermissionContext {
+ if (!grant) return ctx;
+ return withChanges(ctx, {
+ autoApprove: true,
+ autoApproveOrigin: ctx.autoApprove ? ctx.autoApproveOrigin : 'turn',
+ scopes: [...ctx.scopes, ...grant.scopes],
+ });
+}
+
import type { McpGateRequest, McpGateResult, McpResourceGateRequest } from './mcp/types.js';
import { MCP_LIST_RESOURCES_TOOL, MCP_READ_RESOURCE_TOOL } from './mcp/naming.js';
@@ -481,24 +494,41 @@ export class PermissionManager {
*/
currentContext(): PermissionContext {
const cell = permissionContextStore.getStore();
- if (cell && cell.owner === this) return cell.ctx;
+ if (cell && cell.owner === this) return cell.turn ? this.turnContext(cell.turn) : cell.ctx;
return this.rootContext();
}
private rootContext(): PermissionContext {
if (this.rootCache) return this.rootCache;
- let ctx = this.session;
- if (this.turnGrant) {
- ctx = withChanges(ctx, {
- autoApprove: true,
- autoApproveOrigin: ctx.autoApprove ? ctx.autoApproveOrigin : 'turn',
- scopes: [...ctx.scopes, ...this.turnGrant.scopes],
- });
- }
+ const ctx = applyTurnGrant(this.session, this.turnGrant);
this.rootCache = ctx;
return ctx;
}
+ /** A concurrent turn's view: the live session with the turn's own identity and grant over it. */
+ private turnContext(turn: TurnOverlay): PermissionContext {
+ if (turn.cache && turn.cache.session === this.session) return turn.cache.ctx;
+ const ctx = applyTurnGrant(withChanges(this.session, turn.fields), turn.grant);
+ turn.cache = { session: this.session, ctx };
+ return ctx;
+ }
+
+ /** The calling code's turn overlay, when it runs in a main-agent turn of this manager. */
+ private currentTurn(): TurnOverlay | null {
+ const cell = permissionContextStore.getStore();
+ return cell && cell.owner === this && cell.turn ? cell.turn : null;
+ }
+
+ /**
+ * Run one main-agent turn (and everything it awaits or spawns) with its
+ * own identity, elevation, internal grant and plugin grants (ADR-037), so
+ * concurrent turns never see each other's. Sub-agents started inside get
+ * their own context as before (`withContext`).
+ */
+ withTurn<T>(fn: () => T): T {
+ return permissionContextStore.run({ owner: this, ctx: this.session, turn: newTurnOverlay() }, fn);
+ }
+
private ctx(): PermissionContext {
return this.currentContext();
}
@@ -511,6 +541,25 @@ export class PermissionManager {
*/
private updateContext(patch: (base: PermissionContext) => Partial<PermissionContext>): void {
const cell = permissionContextStore.getStore();
+ if (cell && cell.owner === this && cell.turn) {
+ // A concurrent turn: identity/elevation stay with the turn; everything
+ // else (Allow All, scopes the owner approved) is the shared session's,
+ // exactly as it was with one turn at a time. The base never includes
+ // the turn grant, so a grant is never baked into the session.
+ const turn = cell.turn;
+ const changes = patch(withChanges(this.session, turn.fields));
+ const shared: Partial<PermissionContext> = {};
+ for (const [key, value] of Object.entries(changes) as Array<[keyof PermissionContext, unknown]>) {
+ if ((TURN_OWNED_FIELDS as readonly string[]).includes(key)) (turn.fields as Record<string, unknown>)[key] = value;
+ else (shared as Record<string, unknown>)[key] = value;
+ }
+ if (Object.keys(shared).length > 0) {
+ this.session = withChanges(this.session, shared);
+ this.rootCache = null;
+ }
+ turn.cache = null;
+ return;
+ }
if (cell && cell.owner === this) {
cell.ctx = withChanges(cell.ctx, patch(cell.ctx));
return;
@@ -536,11 +585,24 @@ export class PermissionManager {
* user's Allow All) untouched.
*/
beginTurnGrant(grant: { scopes?: Array<{ path: string; read: boolean; write: boolean }> } = {}): void {
- this.turnGrant = { scopes: (grant.scopes ?? []).map((s) => ({ ...s, path: resolve(s.path) })) };
+ const next = { scopes: (grant.scopes ?? []).map((s) => ({ ...s, path: resolve(s.path) })) };
+ const turn = this.currentTurn();
+ if (turn) {
+ turn.grant = next;
+ turn.cache = null;
+ return;
+ }
+ this.turnGrant = next;
this.rootCache = null;
}
endTurnGrant(): void {
+ const turn = this.currentTurn();
+ if (turn) {
+ turn.grant = null;
+ turn.cache = null;
+ return;
+ }
this.turnGrant = null;
this.rootCache = null;
}
@@ -622,13 +684,15 @@ export class PermissionManager {
private turnPluginGrants = new Set<string>();
setTurnPluginGrants(tools: string[]): void {
- this.turnPluginGrants = new Set(tools);
+ const turn = this.currentTurn();
+ if (turn) turn.pluginGrants = new Set(tools);
+ else this.turnPluginGrants = new Set(tools);
}
async approvePluginTool(toolKey: string, prompt: string): Promise<boolean> {
const ctx = this.ctx();
if (this.failClosed) return true;
- if (this.turnPluginGrants.has(toolKey)) return true;
+ if ((this.currentTurn()?.pluginGrants ?? this.turnPluginGrants).has(toolKey)) return true;
if (ctx.channelType === 'internal') return ctx.autoApprove;
if (this.isGlobalAutoApproveActive()) return true;
if (this.approvedPluginToolsByContext.get(ctx.channelId)?.has(toolKey)) return true;
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.ts
index 155b07c1..614c703e 100644
--- a/src/capabilities/registry.ts
+++ b/src/capabilities/registry.ts
@@ -25,6 +25,7 @@ import { createSaveMemoryTool } from './system/save-memory.js';
import { createSearchMemoryTool } from './system/search-memory.js';
import { createSessionHistoryTools } from './system/session-history.js';
import type { SessionRepository } from '../sessions/repository.js';
+import { ScopedValue } from '../utils/turn-scope.js';
import { createForgetMemoryTool } from './system/forget-memory.js';
import { createConfirmBeliefTool } from './system/confirm-belief.js';
import { createCorrectBeliefTool } from './system/correct-belief.js';
@@ -107,7 +108,8 @@ export class CapabilityRegistry {
private sendFileHandler?: (filePath: string, channel?: string) => Promise<void>;
private sendMessageHandler?: (content: string) => Promise<void>;
private chatCommandContext?: ChatCommandContext;
- private currentCwd = process.cwd();
+ /** Per turn while a turn claims it (ADR-037); the registry-wide cwd otherwise. */
+ private readonly currentCwd = new ScopedValue(process.cwd());
private researchModeGetter: (() => boolean) | null = null;
private mcp?: McpManager;
private browser?: IsolatedBrowserReader;
@@ -185,7 +187,10 @@ export class CapabilityRegistry {
return { channelId: ctx.channelId, channelType: ctx.channelType };
}
- private toolsDisabled = false;
+ private readonly toolsDisabledValue = new ScopedValue(false);
+ private get toolsDisabled(): boolean {
+ return this.toolsDisabledValue.get();
+ }
/**
* No tools at all for the current turn (a chat channel at "general"
@@ -193,7 +198,7 @@ export class CapabilityRegistry {
* the plan and narration-guard paths, gets none.
*/
setToolsDisabled(disabled: boolean): void {
- this.toolsDisabled = disabled;
+ this.toolsDisabledValue.set(disabled);
}
areToolsDisabled(): boolean {
@@ -201,13 +206,34 @@ export class CapabilityRegistry {
}
getCwd(): string {
- return this.currentCwd;
+ return this.currentCwd.get();
+ }
+
+ /**
+ * Give the calling turn its own working directory and tools switch
+ * (ADR-037), starting from `cwd` (default: the registry-wide one). From
+ * then on `cd`, `setCwd` and `setToolsDisabled` in that turn — and in
+ * anything it awaits or spawns — change only that turn. No-op outside a
+ * turn scope.
+ */
+ claimTurnState(cwd?: string): void {
+ this.currentCwd.claim(cwd ?? this.currentCwd.getGlobal());
+ this.toolsDisabledValue.claim(false);
+ }
+
+ /** The registry-wide working directory (the terminal's), whatever turn is calling. */
+ getGlobalCwd(): string {
+ return this.currentCwd.getGlobal();
+ }
+
+ setGlobalCwd(dir: string): void {
+ this.currentCwd.setGlobal(dir);
}
/** Returns false (and keeps the current directory) when the cwd guard refuses. */
setCwd(dir: string): boolean {
if (this.cwdGuard && !this.cwdGuard(dir)) return false;
- this.currentCwd = dir;
+ this.currentCwd.set(dir);
return true;
}
diff --git a/src/capabilities/tool-images.ts b/src/capabilities/tool-images.ts
index 4c15b741..785f9583 100644
--- a/src/capabilities/tool-images.ts
+++ b/src/capabilities/tool-images.ts
@@ -1,3 +1,5 @@
+import { ScopedValue } from '../utils/turn-scope.js';
+
export interface ToolImage {
data: string;
mimeType: string;
@@ -16,14 +18,20 @@ export const MAX_TOOL_IMAGE_CHARS = 8_000_000;
const MAX_PENDING = 32;
const pendingImages = new Map<string, ToolImage[]>();
-let imagesAllowed = true;
+/** Whether the model of the calling turn can see images (per turn once claimed, ADR-037). */
+const imagesAllowed = new ScopedValue(true);
export function setToolImagesAllowed(allowed: boolean): void {
- imagesAllowed = allowed;
+ imagesAllowed.set(allowed);
}
export function toolImagesAllowed(): boolean {
- return imagesAllowed;
+ return imagesAllowed.get();
+}
+
+/** Give the calling turn its own "model sees images" switch (no-op outside a turn). */
+export function claimToolImagesForTurn(): void {
+ imagesAllowed.claim();
}
export function usableImages(images: ToolImage[]): ToolImage[] {
@@ -45,7 +53,7 @@ export function attachedImagesNote(count: number): string {
export function toolOutputWithImages(toolCallId: string, text: string): ToolImageOutput {
const images = pendingImages.get(toolCallId);
if (!images?.length) return { type: 'text', value: text };
- if (!imagesAllowed) {
+ if (!imagesAllowed.get()) {
return { type: 'text', value: `${text}\n(The current model can't view images, so the attached image was left out. Say so if it matters.)` };
}
return {
diff --git a/src/channels/web.ts b/src/channels/web.ts
index f3cb2f52..752f6e2c 100644
--- a/src/channels/web.ts
+++ b/src/channels/web.ts
@@ -269,8 +269,9 @@ export class WebChannel extends BaseChannel {
* never reached it, and it showed "Thinking" forever.
*/
/**
- * This chat's message is waiting: Mercury runs one turn at a time, and
- * another one (`busySessionId`, doing `busyWith`) is ahead of it. Sent when it
+ * This chat's message is waiting: every slot Mercury runs chats in is
+ * taken (ADR-037), and another one (`busySessionId`, doing `busyWith`) is
+ * ahead of it. Sent when it
* joins the line and whenever the line moves; the turn's own events follow
* when it starts.
*/
diff --git a/src/core/agent.ts b/src/core/agent.ts
index a2cbdd37..06808e3e 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -27,6 +27,10 @@ import { getMercuryHome } from '../utils/config.js';
import { createProvider } from '../providers/registry.js';
import type { BaseProvider } from '../providers/base.js';
import { Lifecycle } from './lifecycle.js';
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { runInTurnScope } from '../utils/turn-scope.js';
+import { claimToolImagesForTurn } from '../capabilities/tool-images.js';
+import { TurnGovernor, machineFacts, resolveTurnLimit, type GovernedTurn } from './turn-governor.js';
import { Scheduler } from './scheduler.js';
import { ProgrammingMode, scopedProgrammingState, type ProgrammingSnapshot } from './programming-mode.js';
import { ResearchMode } from './research-mode.js';
@@ -92,8 +96,8 @@ import { WorkLedger, type WorkEntry } from './work-ledger.js';
import { MAX_PROVIDER_ATTEMPT_MS, MAX_AUTOMATIC_CONTINUATIONS, needsContinuationApproval, needsRetryApproval, withAbortDeadline } from './execution-limits.js';
import { requiresFinalSend } from './response-delivery.js';
import { updateCliProviderStatus } from './provider-status.js';
-import { isTaskHeapUnsafe, taskHeapAbortThreshold, taskHeapExitThreshold } from './memory-guard.js';
-import { compactConversation, memoryGovernorThresholds, memoryGovernorVerdict } from './memory-governor.js';
+import { compactConversation } from './memory-governor.js';
+import { writeCrashFlag } from './crash-flag.js';
import { classifyStreamCompletion, isLengthTruncation, truncationContinuationPrompt, toolTruncationContinuationPrompt } from './stream-completion.js';
import { MAX_EXECUTE_CONTINUATIONS, MAX_VERIFICATION_CONTINUATIONS, executeContinuationPrompt, shouldForceExecuteContinuation, isFailedToolResult, shouldRequireVerification, isVerificationOutputOk, verificationPrompt, responseAsksUser, EXECUTE_MUTATING_TOOLS, VERIFICATION_COMMAND_PATTERN, wakeUpPrompt } from './execute-guard.js';
import { classifyTurnEnd, stepsExhaustedPrompt, STEPS_PAUSED_BANNER, WORK_NOT_STARTED_BANNER, VERIFICATION_FAILED_BANNER, type LoopEndCause } from './completion-verdict.js';
@@ -573,25 +577,181 @@ export function looksLikeCodingTask(text: string): boolean {
}
-export class Agent {
+export type AbortReason = 'stalled' | 'time-limit' | 'memory-pressure' | 'backgrounded' | 'stopped' | 'halted';
+
+/** One running turn (ADR-037): everything that used to be a single field on the agent. */
+interface TurnState {
+ readonly id: string;
+ readonly laneKey: string;
+ readonly message: ChannelMessage;
+ readonly startedAt: number;
+ abort: AbortController | null;
+ abortReason: AbortReason | null;
+ activity: string;
+ completedStepCount: number;
+ stepNarrative: import('../utils/tool-label.js').NarrativeStep[];
+ workKey: string | null;
+ lastProgressAt: number;
+ lastTypingAt: number;
+ injectedBeliefIds: string[];
readonly lifecycle: Lifecycle;
+ /** A desktop Code session's own programming mode; null = the global one. */
+ programming: ProgrammingMode | null;
+ /** Set once the turn has fully ended (late timers check it). */
+ done: boolean;
+}
+
+/**
+ * The lane a message runs in: one turn at a time per lane, lanes run
+ * concurrently (ADR-037). A canonical session id when the message names
+ * one; else the channel's conversation. The terminal is one lane.
+ */
+export function laneKeyFor(msg: ChannelMessage): string {
+ if (msg.channelType === 'cli') return 'cli';
+ const sessionId = msg.sessionId ?? (typeof msg.metadata?.sessionId === 'string' ? msg.metadata.sessionId : undefined);
+ if (sessionId) return `session:${sessionId}`;
+ if (msg.channelType === 'internal') {
+ const task = typeof msg.metadata?.scheduledTaskId === 'string' ? msg.metadata.scheduledTaskId : msg.channelId;
+ return `internal:${task}`;
+ }
+ const conversation = typeof msg.metadata?.externalConversationId === 'string' ? msg.metadata.externalConversationId : msg.channelId;
+ return `${msg.channelType}:${conversation}`;
+}
+
+export class Agent {
+ private readonly globalLifecycle: Lifecycle;
readonly scheduler: Scheduler;
readonly capabilities: CapabilityRegistry;
private running = false;
+ /** Messages waiting for their chat's lane (and a free slot), in order (ADR-037). */
private messageQueue: Array<{ message: ChannelMessage; workKey?: string }> = [];
private queuedWorkKeys = new Set<string>();
- processing = false;
+ /**
+ * Concurrent sessions (ADR-037). One running turn per lane (a chat /
+ * session); different lanes run at once, as many as the governor admits.
+ * Each turn's state lives in its own TurnState, carried through
+ * everything the turn awaits by `turnStore`; the fields below
+ * (currentMessage, currentAbort, …) read and write the CALLING turn's.
+ */
+ private readonly activeTurns = new Map<string, TurnState>();
+ private readonly turnStore = new AsyncLocalStorage<TurnState>();
+ readonly governor: TurnGovernor;
+ private turnSeq = 0;
+ private lastAdmitRefusal: string | null = null;
+ /** Each chat's working directory between its turns (the terminal's is the registry-wide one). */
+ private readonly laneCwd = new Map<string, string>();
telegramStreaming: boolean;
- currentMessage: ChannelMessage | null = null;
- currentAbort: AbortController | null = null;
- currentAbortReason: 'stalled' | 'time-limit' | 'memory-pressure' | 'backgrounded' | 'stopped' | 'halted' | null = null;
- private lastProgressAt = 0;
- currentActivity = '';
- completedStepCount = 0;
- stepNarrative: import('../utils/tool-label.js').NarrativeStep[] = [];
+
+ /** The calling turn, if the calling code runs inside one. */
+ private turn(): TurnState | undefined {
+ return this.turnStore.getStore();
+ }
+
+ /** Is any turn running? (Use isLaneBusy / turnForChannel for one chat.) */
+ get processing(): boolean {
+ return this.activeTurns.size > 0;
+ }
+
+ /** How many turns are running right now. */
+ get activeTurnCount(): number {
+ return this.activeTurns.size;
+ }
+
+ /** The calling turn's message (null outside a turn). */
+ get currentMessage(): ChannelMessage | null {
+ return this.turn()?.message ?? null;
+ }
+
+ get currentAbort(): AbortController | null {
+ return this.turn()?.abort ?? null;
+ }
+ set currentAbort(value: AbortController | null) {
+ const t = this.turn();
+ if (t) t.abort = value;
+ }
+
+ get currentAbortReason(): AbortReason | null {
+ return this.turn()?.abortReason ?? null;
+ }
+ set currentAbortReason(value: AbortReason | null) {
+ const t = this.turn();
+ if (t) t.abortReason = value;
+ }
+
+ private get lastProgressAt(): number {
+ return this.turn()?.lastProgressAt ?? 0;
+ }
+ private set lastProgressAt(value: number) {
+ const t = this.turn();
+ if (t) t.lastProgressAt = value;
+ }
+
+ get currentActivity(): string {
+ return this.turn()?.activity ?? '';
+ }
+ set currentActivity(value: string) {
+ const t = this.turn();
+ if (t) t.activity = value;
+ }
+
+ get completedStepCount(): number {
+ return this.turn()?.completedStepCount ?? 0;
+ }
+ set completedStepCount(value: number) {
+ const t = this.turn();
+ if (t) t.completedStepCount = value;
+ }
+
+ get stepNarrative(): import('../utils/tool-label.js').NarrativeStep[] {
+ return this.turn()?.stepNarrative ?? [];
+ }
+ set stepNarrative(value: import('../utils/tool-label.js').NarrativeStep[]) {
+ const t = this.turn();
+ if (t) t.stepNarrative = value;
+ }
+
+ private get currentWorkKey(): string | null {
+ return this.turn()?.workKey ?? null;
+ }
+ private set currentWorkKey(value: string | null) {
+ const t = this.turn();
+ if (t) t.workKey = value;
+ }
+
+ private get lastTypingAt(): number {
+ return this.turn()?.lastTypingAt ?? 0;
+ }
+ private set lastTypingAt(value: number) {
+ const t = this.turn();
+ if (t) t.lastTypingAt = value;
+ }
+
+ /** Beliefs injected into the calling turn's prompt (set by retrieveMemoryContext, ADR-026). */
+ get lastInjectedBeliefIds(): string[] {
+ return this.turn()?.injectedBeliefIds ?? [];
+ }
+ set lastInjectedBeliefIds(value: string[]) {
+ const t = this.turn();
+ if (t) t.injectedBeliefIds = value;
+ }
+
+ /**
+ * The calling turn's lifecycle (thinking → responding → idle); outside a
+ * turn, the runtime's own (birth, sleep, idle).
+ */
+ get lifecycle(): Lifecycle {
+ return this.turn()?.lifecycle ?? this.globalLifecycle;
+ }
+
+ /**
+ * The calling turn's programming mode: a desktop Code session's own one
+ * inside its turns, else the terminal's (global) one.
+ */
+ get programmingMode(): ProgrammingMode {
+ return this.turn()?.programming ?? this.globalProgrammingMode;
+ }
supervisor?: import('../core/supervisor.js').SubAgentSupervisor;
botManager?: import('../bots/bot-manager.js').BotManager;
- private lastTypingAt = 0;
/** Bot awaiting a persona from the next message (post-create setup flow). */
/**
* A terminal beside a live daemon (ADR-024): the daemon owns persisted
@@ -615,7 +775,8 @@ export class Agent {
readonly lastNotedBeliefId = new Map<string, string>();
/** When the last "☿ Noted" went out per channel: at most one every few minutes, so an upgrade's backlog never floods a chat. */
private readonly lastNotedAt = new Map<string, number>();
- readonly programmingMode: ProgrammingMode;
+ /** The terminal's programming mode (and every turn's that isn't a desktop Code session). */
+ readonly globalProgrammingMode: ProgrammingMode;
readonly researchMode: ResearchMode;
readonly saverMode: SaverMode;
spotifyClient?: SpotifyClient;
@@ -630,16 +791,13 @@ export class Agent {
private statusVerbsDisabled = false;
sessionSyncEnabled = false;
private readonly workLedger: WorkLedger;
- private currentWorkKey: string | null = null;
private outboxRetryTimer: ReturnType<typeof setInterval> | null = null;
private replayingOutbox = false;
- /** Beliefs injected into the current turn's prompt (set by retrieveMemoryContext, ADR-026). */
- lastInjectedBeliefIds: string[] = [];
/** "About {owner}" / "How to work with {owner}", recomputed only when the beliefs change (keeps the prompt prefix cacheable). */
private readonly ownerSections = createOwnerSectionsMemo();
private reflectionInFlight: Promise<void> | null = null;
- /** Beliefs the previous turn acted on; credited as "acted on without objection" once the next owner message shows no correction. */
- private pendingActedOn: { ids: string[]; sessionId?: string } | null = null;
+ /** Per session: beliefs its previous turn acted on; credited as "acted on without objection" once the owner's next message there shows no correction. */
+ private readonly pendingActedOn = new Map<string, string[]>();
constructor(
public config: MercuryConfig,
@@ -656,14 +814,21 @@ export class Agent {
public sessions: SessionRepository,
private generateTitle?: (input: { userMessage: string; assistantMessage: string; providerName: string }) => Promise<string>,
) {
- this.lifecycle = new Lifecycle();
+ this.globalLifecycle = new Lifecycle();
this.scheduler = scheduler;
this.capabilities = capabilities;
this.capabilities.setSessionRepository(sessions);
this.installProgressPulse();
this.telegramStreaming = config.channels.telegram.streaming ?? true;
- this.programmingMode = new ProgrammingMode();
+ this.globalProgrammingMode = new ProgrammingMode();
this.researchMode = new ResearchMode();
+ // Research runs are per chat: inside a turn, "the" run is that chat's.
+ this.researchMode.setScope(() => this.turn()?.message.channelId ?? null);
+ this.governor = new TurnGovernor({
+ limit: resolveTurnLimit(config.concurrency?.maxTurns, machineFacts()),
+ onExit: (heapUsed) => this.exitForMemory(heapUsed),
+ });
+ logger.info({ maxTurns: this.governor.limit() }, 'Concurrent turns: limit set');
this.saverMode = new SaverMode(config);
this.wireResearchModeToCapabilities();
this.backgroundTasks = new BackgroundTaskManager();
@@ -962,18 +1127,22 @@ export class Agent {
}
}
- // /stop is asynchronous: the abort lands, the turn unwinds, THEN
- // processing clears. A command typed in that window used to be answered
+ // /stop is asynchronous: the abort lands, the turn unwinds, THEN the
+ // chat's lane frees. A command typed in that window used to be answered
// "Agent is busy" — wait for the stop to finish and route it normally.
- if (this.processing && trimmed.startsWith('/') && this.currentAbortReason && !msg.metadata?.waitedForStop) {
- void this.waitUntilIdle(5000).then(() => {
+ const lane = laneKeyFor(msg);
+ const laneTurn = this.activeTurns.get(lane);
+ if (laneTurn && trimmed.startsWith('/') && laneTurn.abortReason && !msg.metadata?.waitedForStop) {
+ void this.waitUntilLaneIdle(lane, 5000).then(() => {
msg.metadata = { ...msg.metadata, waitedForStop: true };
this.enqueueMessage(msg);
});
return;
}
- if (this.processing && trimmed.startsWith('/')) {
+ // A command for a chat that is busy (or while every slot is taken) is
+ // answered on the fast path instead of waiting behind long work.
+ if (trimmed.startsWith('/') && (laneTurn || !this.governor.canAdmit(this.activeTurns.size).ok)) {
this.handleFastPathCommand(msg).catch((err) => {
logger.error({ err, content: trimmed.slice(0, 50) }, 'Fast-path command failed');
});
@@ -984,7 +1153,7 @@ export class Agent {
if (!trimmed.startsWith('/')) {
msg.metadata = {
...msg.metadata,
- workCwd: typeof msg.metadata?.workCwd === 'string' ? msg.metadata.workCwd : this.capabilities.getCwd(),
+ workCwd: typeof msg.metadata?.workCwd === 'string' ? msg.metadata.workCwd : this.cwdForLane(lane),
};
const accepted = this.workLedger.accept(msg);
workKey = accepted.entry.key;
@@ -1161,38 +1330,129 @@ export class Agent {
}
/**
- * Tell every waiting desktop/web chat where it stands: its place in line,
- * and the turn running now (which chat, and what it's doing). Without this
- * a waiting chat showed "Thinking" for a turn that hadn't started.
+ * What a waiting message waits for (ADR-037): its own chat's running turn
+ * when there is one, else (every slot taken) the oldest running turn.
+ */
+ private blockingTurnFor(msg: ChannelMessage): TurnState | undefined {
+ const own = this.activeTurns.get(laneKeyFor(msg));
+ if (own) return own;
+ let oldest: TurnState | undefined;
+ for (const t of this.activeTurns.values()) if (!oldest || t.startedAt < oldest.startedAt) oldest = t;
+ return oldest;
+ }
+
+ private describeTurn(t: TurnState): string {
+ return (t.activity || t.message.content).replace(/^\W+/u, '').replace(/\s+/g, ' ').trim().slice(0, 90) || 'another task';
+ }
+
+ /**
+ * A waiting message's place in line: the messages ahead of it that start
+ * before it — earlier ones in its own chat, and earlier ones from chats
+ * that are free (they take the next free slot first). Messages of other
+ * busy chats wait for their own chat, not for a slot, so they don't count.
*/
- private announceQueue(running: ChannelMessage | null = this.processing ? this.currentMessage : null): void {
- if (!running) return;
+ private positionOf(index: number): number {
+ const lane = laneKeyFor(this.messageQueue[index].message);
+ let ahead = 0;
+ for (let i = 0; i < index; i++) {
+ const other = laneKeyFor(this.messageQueue[i].message);
+ if (other === lane || !this.activeTurns.has(other)) ahead++;
+ }
+ return ahead + 1;
+ }
+
+ /**
+ * Tell every waiting desktop/web chat where it stands: its place in its
+ * chat's line, and the turn it waits for (which chat, and what it's
+ * doing). Without this a waiting chat showed "Thinking" for a turn that
+ * hadn't started.
+ */
+ private announceQueue(): void {
+ if (this.activeTurns.size === 0) return;
const web = this.channels.get('web') as unknown as { sendQueued?: (t: string, d: { position: number; busyWith?: string; busySessionId?: string }) => void } | undefined;
if (!web?.sendQueued) return;
- const busyWith = (this.currentActivity && this.currentMessage === running ? this.currentActivity : running.content)
- .replace(/^\W+/u, '').replace(/\s+/g, ' ').trim().slice(0, 90) || 'another task';
- const busySessionId = running.channelType === 'web' ? running.channelId : undefined;
this.messageQueue.forEach((item, i) => {
const m = item.message;
- if (m.channelType !== 'web' || m.channelId === busySessionId) return;
- web.sendQueued!(m.channelId, { position: i + 1, busyWith, busySessionId });
+ if (m.channelType !== 'web') return;
+ const blocking = this.blockingTurnFor(m);
+ if (!blocking) return;
+ // Its own chat is running: that chat already shows the running turn.
+ if (blocking.laneKey === laneKeyFor(m)) return;
+ const busySessionId = blocking.message.channelType === 'web' ? blocking.message.channelId : undefined;
+ web.sendQueued!(m.channelId, { position: this.positionOf(i), busyWith: this.describeTurn(blocking), busySessionId });
});
}
/** Where one chat's work stands, for a chat opened while it waits. */
queueStateFor(channelId: string): { state: 'running' | 'queued' | 'none'; position?: number; busyWith?: string; busySessionId?: string } {
- if (this.processing && this.currentMessage?.channelId === channelId) return { state: 'running' };
+ if (this.turnForChannel(channelId)) return { state: 'running' };
const at = this.messageQueue.findIndex((i) => i.message.channelId === channelId);
if (at === -1) return { state: 'none' };
- const running = this.processing ? this.currentMessage : null;
+ const blocking = this.blockingTurnFor(this.messageQueue[at].message);
return {
state: 'queued',
- position: at + 1,
- busyWith: running ? (this.currentActivity || running.content).replace(/\s+/g, ' ').trim().slice(0, 90) : undefined,
- busySessionId: running?.channelType === 'web' ? running.channelId : undefined,
+ position: this.positionOf(at),
+ busyWith: blocking ? this.describeTurn(blocking) : undefined,
+ busySessionId: blocking?.message.channelType === 'web' ? blocking.message.channelId : undefined,
};
}
+ /** The running turn for this chat (by channel id), if any. */
+ turnForChannel(channelId: string): TurnState | undefined {
+ for (const t of this.activeTurns.values()) if (t.message.channelId === channelId) return t;
+ return undefined;
+ }
+
+ /** The running turn for a canonical session (a cloud request's channel id is per request; its session is not). */
+ turnForSession(sessionId: string): TurnState | undefined {
+ for (const t of this.activeTurns.values()) {
+ const of = t.message.sessionId ?? (typeof t.message.metadata?.sessionId === 'string' ? t.message.metadata.sessionId : undefined);
+ if (of === sessionId) return t;
+ }
+ return undefined;
+ }
+
+ /** Is this message's chat running a turn right now? */
+ isLaneBusy(msg: ChannelMessage): boolean {
+ return this.activeTurns.has(laneKeyFor(msg));
+ }
+
+ /** The running turn of this message's chat, if any (fast-path commands act on it). */
+ turnFor(msg: ChannelMessage): TurnState | undefined {
+ return this.activeTurns.get(laneKeyFor(msg));
+ }
+
+ /** Every running turn, oldest first: what each chat is doing (for /progress, status screens). */
+ runningTurns(): Array<{ laneKey: string; channelType: string; channelId: string; content: string; activity: string; startedAt: number; completedSteps: number; narrative: import('../utils/tool-label.js').NarrativeStep[] }> {
+ return [...this.activeTurns.values()]
+ .sort((a, b) => a.startedAt - b.startedAt)
+ .map((t) => ({
+ laneKey: t.laneKey,
+ channelType: t.message.channelType,
+ channelId: t.message.channelId,
+ content: t.message.content,
+ activity: t.activity,
+ startedAt: t.startedAt,
+ completedSteps: t.completedStepCount,
+ narrative: t.stepNarrative,
+ }));
+ }
+
+ /**
+ * Abort one running turn. Its work entry is cancelled for a user stop (a
+ * restart never resumes it); a background hand-off keeps it. Returns
+ * false when it was already stopping.
+ */
+ abortTurn(t: TurnState, reason: AbortReason, ledgerNote?: string): boolean {
+ if (!t.abort || t.abort.signal.aborted) return false;
+ t.abortReason = reason;
+ t.abort.abort();
+ if (ledgerNote && t.workKey) {
+ try { this.workLedger.markCancelled(t.workKey, ledgerNote); } catch { /* entry may not exist */ }
+ }
+ return true;
+ }
+
/** "Do mine first": this chat's waiting messages move to the front of the line (in their order). */
prioritize(channelId: string): number {
const mine = this.messageQueue.filter((i) => i.message.channelId === channelId);
@@ -1210,20 +1470,22 @@ export class Agent {
isBusyWith(sessionId: string): boolean {
const of = (m: ChannelMessage | null | undefined) => m?.sessionId ?? (typeof m?.metadata?.sessionId === 'string' ? m.metadata.sessionId : undefined);
- if (this.processing && of(this.currentMessage) === sessionId) return true;
+ for (const t of this.activeTurns.values()) if (of(t.message) === sessionId) return true;
return this.messageQueue.some((i) => of(i.message) === sessionId);
}
/**
* Where work for one channel stands: running now, waiting in the queue,
- * or neither; and what Mercury is busy with when it's something else.
+ * or neither; and, when it waits, what it waits for.
*/
workStateFor(channelId: string): { state: 'running' | 'queued' | 'none'; busyWith?: string } {
- const current = this.currentMessage?.channelId;
- if (this.processing && current === channelId) return { state: 'running' };
- const busyWith = this.processing && current ? (this.currentActivity || 'another task').replace(/^\W+/u, '').trim() || 'another task' : undefined;
- if (this.messageQueue.some((i) => i.message.channelId === channelId)) return { state: 'queued', busyWith };
- return { state: 'none', busyWith };
+ if (this.turnForChannel(channelId)) return { state: 'running' };
+ const waiting = this.messageQueue.find((i) => i.message.channelId === channelId);
+ if (waiting) {
+ const blocking = this.blockingTurnFor(waiting.message);
+ return { state: 'queued', busyWith: blocking ? this.describeTurn(blocking) : undefined };
+ }
+ return { state: 'none' };
}
private async handleDuplicateWork(entry: WorkEntry): Promise<void> {
@@ -1354,13 +1616,13 @@ export class Agent {
* what was read. False when there's no research running in that chat.
*/
finishResearch(sessionId: string): { ok: boolean; reason?: string } {
- const run = this.researchMode.currentRun();
- if (!run || run.sessionId !== sessionId || run.outcome !== 'running') return { ok: false, reason: 'No research is running in this chat.' };
+ const run = this.researchMode.activeRunFor(sessionId);
+ if (!run || run.outcome !== 'running') return { ok: false, reason: 'No research is running in this chat.' };
if (run.readCount() === 0) return { ok: false, reason: 'Nothing has been read yet, so there is nothing to write from. Stop it instead, or let it read a few sources.' };
- if (!this.currentAbort || this.currentAbort.signal.aborted) return { ok: false, reason: 'The research is already finishing.' };
+ const turn = this.turnForChannel(sessionId);
+ if (!turn?.abort || turn.abort.signal.aborted) return { ok: false, reason: 'The research is already finishing.' };
run.finishRequested = true;
- this.currentAbortReason = 'stopped';
- this.currentAbort.abort();
+ this.abortTurn(turn, 'stopped');
return { ok: true };
}
@@ -1426,36 +1688,107 @@ export class Agent {
* command and the Cloud `task.stop` control so a remote stop behaves
* exactly like typing /stop locally. Returns the confirmation note.
*/
- async stopAllWork(reason: 'stopped' | 'halted'): Promise<string> {
- if (this.currentAbort && !this.currentAbort.signal.aborted) {
- this.currentAbortReason = reason;
- this.currentAbort.abort();
- }
+ /**
+ * Stop work. With a `channelId` (a `/stop` typed in a chat, the app's
+ * Stop button in one conversation, Esc in the terminal) only that chat's
+ * running turn and the sub-agents it started stop — other chats keep
+ * going (ADR-037). Without one (`/halt`, or a caller that names no chat)
+ * every running turn and every sub-agent stops.
+ */
+ async stopAllWork(reason: 'stopped' | 'halted', target?: { channelId?: string; sessionId?: string }): Promise<string> {
// The user deliberately killed this work — cancel its ledger entry so
// a restart never tries to resume it. (Only real crashes auto-resume.)
- if (this.currentWorkKey) {
- const label = reason === 'stopped' ? 'Stopped by the user (/stop).' : 'Halted by the user (/halt).';
- try { this.workLedger.markCancelled(this.currentWorkKey, label); } catch { /* entry may not exist */ }
+ const label = reason === 'stopped' ? 'Stopped by the user (/stop).' : 'Halted by the user (/halt).';
+ // A stop typed in an idle chat runs as that chat's own turn: never abort the command itself.
+ const caller = this.turn();
+ if (target && (target.channelId || target.sessionId)) {
+ let turn = (target.channelId ? this.turnForChannel(target.channelId) : undefined)
+ ?? (target.sessionId ? this.turnForSession(target.sessionId) : undefined);
+ if (turn && caller && turn.id === caller.id) turn = undefined;
+ if (turn) this.abortTurn(turn, reason, label);
+ const channelId = turn?.message.channelId ?? target.channelId;
+ const halted = this.supervisor && channelId ? await this.supervisor.haltForChannel(channelId) : [];
+ const others = [...this.activeTurns.values()]
+ .filter((t) => t !== turn && t.id !== caller?.id && !t.abort?.signal.aborted).length;
+ // Nothing else running anywhere: the full stop it always was (locks
+ // released, task board cleared), exactly as with one chat.
+ let cleared = false;
+ if (reason === 'stopped' && others === 0 && this.supervisor
+ && this.supervisor.getActiveAgents().every((a) => halted.includes(a.id) || (a.status !== 'running' && a.status !== 'pending'))) {
+ this.supervisor.clearTaskBoard();
+ cleared = true;
+ }
+ const tail = cleared ? ' Locks released, task board cleared.' : '';
+ const elsewhere = others > 0 ? ` ${others} task${others === 1 ? '' : 's'} in other chats keep${others === 1 ? 's' : ''} running — /halt stops everything.` : '';
+ if (!turn && halted.length === 0) {
+ return cleared ? `Nothing was running.${tail}` : `Nothing is running in this chat.${elsewhere}`;
+ }
+ const parts = [turn ? 'Stopped this chat\'s task' : null, halted.length ? `halted ${halted.length} sub-agent${halted.length === 1 ? '' : 's'} it started` : null].filter(Boolean);
+ return `${parts.join(', ')}.${tail}${elsewhere}`;
+ }
+ let stoppedTurns = 0;
+ for (const turn of this.activeTurns.values()) {
+ if (caller && turn.id === caller.id) continue;
+ if (this.abortTurn(turn, reason, label)) stoppedTurns++;
}
+ const turnsNote = stoppedTurns > 1 ? `${stoppedTurns} running tasks` : stoppedTurns === 1 ? 'The running task' : null;
if (this.supervisor) {
await this.supervisor.haltAll();
if (reason === 'stopped') {
this.supervisor.clearTaskBoard();
}
- return reason === 'halted' ? 'All sub-agents halted.' : 'All agents stopped, locks released, task board cleared.';
+ const agentsNote = reason === 'halted' ? 'all sub-agents halted.' : 'all agents stopped, locks released, task board cleared.';
+ return turnsNote ? `${turnsNote} ${reason}; ${agentsNote}` : agentsNote.charAt(0).toUpperCase() + agentsNote.slice(1);
}
+ if (turnsNote) return `${turnsNote} ${reason}.${reason === 'stopped' ? ' Locks released, task board cleared.' : ''}`;
return reason === 'halted' ? 'Foreground task halted.' : 'Foreground task stopped, locks released, task board cleared.';
}
- /** Resolves when no turn is running (or after the deadline). */
- private waitUntilIdle(maxMs: number): Promise<void> {
+ /** Resolves when this lane has no running turn (or after the deadline). */
+ private waitUntilLaneIdle(laneKey: string, maxMs: number): Promise<void> {
const deadline = Date.now() + maxMs;
return new Promise((resolve) => {
- const tick = () => { if (!this.processing || Date.now() >= deadline) resolve(); else setTimeout(tick, 50); };
+ const tick = () => { if (!this.activeTurns.has(laneKey) || Date.now() >= deadline) resolve(); else setTimeout(tick, 50); };
tick();
});
}
+ private readonly sessionLocks = new Map<string, Promise<void>>();
+
+ /**
+ * Take one stored conversation for the calling turn; resolves to its
+ * release. Waiters queue in order; a released lock with no waiter is
+ * forgotten, so the map only holds conversations in use.
+ */
+ private async lockSession(sessionId: string): Promise<() => void> {
+ const previous = this.sessionLocks.get(sessionId) ?? Promise.resolve();
+ let release!: () => void;
+ const mine = new Promise<void>((resolve) => { release = resolve; });
+ const chained = previous.then(() => mine);
+ this.sessionLocks.set(sessionId, chained);
+ await previous;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ release();
+ if (this.sessionLocks.get(sessionId) === chained) this.sessionLocks.delete(sessionId);
+ };
+ }
+
+ /** No turn running and none waiting. */
+ isIdle(): boolean {
+ return this.activeTurns.size === 0 && this.messageQueue.length === 0;
+ }
+
+ private idleWaiters: Array<() => void> = [];
+
+ /** Resolves once no turn runs and none waits (at once when that's already so). */
+ whenIdle(): Promise<void> {
+ if (this.isIdle()) return Promise.resolve();
+ return new Promise((resolve) => { this.idleWaiters.push(resolve); });
+ }
+
private async handleFastPathCommand(msg: ChannelMessage): Promise<void> {
return handleFastPathCommandImpl(this, msg);
}
@@ -1916,8 +2249,20 @@ export class Agent {
* Cheap no-op for non-CLI channels.
*/
private pushLiveActivity(phase: string, detail?: string): void {
+ this.cliFeed()?.setLiveActivity(phase, detail);
+ }
+
+ /**
+ * The terminal's live feed, when the calling turn may draw on it: the
+ * terminal's own turn always; another chat's only while the terminal has
+ * no turn of its own (ADR-037 — two turns must not interleave one feed).
+ */
+ private cliFeed(): CLIChannel | undefined {
const ch = this.channels.get('cli');
- if (ch instanceof CLIChannel) ch.setLiveActivity(phase, detail);
+ if (!(ch instanceof CLIChannel)) return undefined;
+ const t = this.turn();
+ if (t && t.laneKey !== 'cli' && this.activeTurns.has('cli')) return undefined;
+ return ch;
}
/**
@@ -1940,8 +2285,8 @@ export class Agent {
try { current.toolStarted(this.currentMessage.channelId, toolName); } catch { /* best effort */ }
}
}
- const ch = this.channels.get('cli');
- if (!(ch instanceof CLIChannel)) return;
+ const ch = this.cliFeed();
+ if (!ch) return;
if (status === 'running') {
void ch.sendToolEvent(toolName, argsOrResult as Record<string, any>, callId).catch(() => {});
} else {
@@ -1973,7 +2318,9 @@ export class Agent {
let timer: ReturnType<typeof setTimeout> | null = null;
const tick = () => {
- if (!this.processing || !this.currentMessage || this.currentMessage.id !== msg.id) return;
+ // Timers carry the turn's scope: a tick after the turn ended does nothing.
+ const own = this.turn();
+ if (!own || own.done || !this.currentMessage || this.currentMessage.id !== msg.id) return;
const channel = this.channels.getChannelForMessage(msg);
const elapsedMs = Date.now() - this.currentMessage.timestamp;
@@ -2102,24 +2449,27 @@ export class Agent {
* Session-scoped coding. A message that names a programming mode (Mercury
* Desktop's Code surface) runs with THAT session's mode, plan and folder;
* everything else (terminal, chat, other sessions) keeps the global mode.
- * Turns are serial (processQueue), so a swap-run-restore is race-free.
+ * The turn gets its own ProgrammingMode instance and its own working
+ * directory (ADR-037), so it can run beside other turns; the global mode
+ * is never touched.
*/
private readonly sessionProgramming = new Map<string, ProgrammingSnapshot>();
private async withSessionProgramming(msg: ChannelMessage, run: () => Promise<void>): Promise<void> {
const requested = scopedProgrammingState(msg.metadata?.programming);
const sessionKey = typeof msg.metadata?.sessionId === 'string' ? msg.metadata.sessionId : msg.sessionId;
- if (!requested || !sessionKey) return run();
- const globalMode = this.programmingMode.snapshot();
- const globalCwd = this.capabilities.getCwd();
+ const turn = this.turn();
+ if (!requested || !sessionKey || !turn) return run();
const cwd = typeof msg.metadata?.programmingCwd === 'string' ? msg.metadata.programmingCwd : null;
const saved = this.sessionProgramming.get(sessionKey);
- this.programmingMode.restore({
+ const mode = new ProgrammingMode();
+ mode.restore({
state: requested,
projectContext: cwd ?? saved?.projectContext ?? null,
// A plan made in this session stays with this session.
lastPlan: saved?.lastPlan ?? null,
});
+ turn.programming = mode;
if (cwd) {
this.capabilities.setCwd(cwd);
this.capabilities.permissions.addTempScope(cwd, true, true);
@@ -2127,70 +2477,204 @@ export class Agent {
try {
await run();
} finally {
- this.sessionProgramming.set(sessionKey, this.programmingMode.snapshot());
+ this.sessionProgramming.delete(sessionKey);
+ this.sessionProgramming.set(sessionKey, mode.snapshot());
if (this.sessionProgramming.size > 200) {
const oldest = this.sessionProgramming.keys().next().value;
if (oldest !== undefined) this.sessionProgramming.delete(oldest);
}
- this.programmingMode.restore(globalMode);
- if (cwd) this.capabilities.setCwd(globalCwd);
+ turn.programming = null;
+ }
+ }
+
+ /** Where a chat's next turn starts: its own last directory, else the terminal's. */
+ private cwdForLane(laneKey: string): string {
+ if (laneKey === 'cli') return this.capabilities.getGlobalCwd();
+ const own = this.laneCwd.get(laneKey);
+ return own && existsSync(own) ? own : this.capabilities.getGlobalCwd();
+ }
+
+ private rememberLaneCwd(laneKey: string, dir: string): void {
+ if (laneKey === 'cli') {
+ // The terminal's `cd` carries over to its next turn, as before.
+ this.capabilities.setGlobalCwd(dir);
+ return;
+ }
+ this.laneCwd.delete(laneKey);
+ this.laneCwd.set(laneKey, dir);
+ if (this.laneCwd.size > 500) {
+ const oldest = this.laneCwd.keys().next().value;
+ if (oldest !== undefined) this.laneCwd.delete(oldest);
}
}
- private async processQueue(): Promise<void> {
- if (this.processing) return;
- if (this.messageQueue.length === 0) return;
+ /**
+ * Start every waiting message whose chat is free, while the governor
+ * admits more (ADR-037). Never awaits a turn: each runs on its own and
+ * pumps again when it ends. Order: first come, first served across chats
+ * (voice-call questions and "do mine first" reorder the line as before);
+ * within a chat, strictly one after another.
+ */
+ private processQueue(): void {
if (!this.running) return;
- if (!this.lifecycle.is('idle')) return;
+ if (!this.globalLifecycle.is('idle')) return;
+ for (;;) {
+ const index = this.messageQueue.findIndex((i) => !this.activeTurns.has(laneKeyFor(i.message)));
+ if (index === -1) break;
+ const decision = this.governor.canAdmit(this.activeTurns.size);
+ if (!decision.ok) {
+ if (this.lastAdmitRefusal !== decision.reason) {
+ logger.info({ reason: decision.reason, running: this.activeTurns.size, waiting: this.messageQueue.length, limit: this.governor.limit() }, 'Turn governor: holding new turns');
+ }
+ this.lastAdmitRefusal = decision.reason;
+ break;
+ }
+ this.lastAdmitRefusal = null;
+ const [item] = this.messageQueue.splice(index, 1);
+ if (item.workKey) this.queuedWorkKeys.delete(item.workKey);
+ this.startTurn(item);
+ }
+ // The line moved: everyone still waiting learns their place and what they wait for.
+ this.announceQueue();
+ }
- this.processing = true;
+ private startTurn(item: { message: ChannelMessage; workKey?: string }): void {
+ const msg = item.message;
+ const laneKey = laneKeyFor(msg);
+ const turn: TurnState = {
+ id: `t${++this.turnSeq}`,
+ laneKey,
+ message: msg,
+ startedAt: Date.now(),
+ abort: null,
+ abortReason: null,
+ activity: '',
+ completedStepCount: 0,
+ stepNarrative: [],
+ workKey: item.workKey ?? null,
+ lastProgressAt: Date.now(),
+ lastTypingAt: 0,
+ injectedBeliefIds: [],
+ lifecycle: new Lifecycle('idle'),
+ programming: null,
+ done: false,
+ };
+ this.activeTurns.set(laneKey, turn);
+ logger.info({ turn: turn.id, lane: laneKey, running: this.activeTurns.size, limit: this.governor.limit() }, 'Turn started');
+ const startCwd = typeof msg.metadata?.workCwd === 'string' && existsSync(msg.metadata.workCwd) ? msg.metadata.workCwd : this.cwdForLane(laneKey);
+
+ void this.turnStore.run(turn, () => runInTurnScope(() => this.capabilities.permissions.withTurn(async () => {
+ // This turn's working directory, tools switch and image switch are its own.
+ this.capabilities.claimTurnState(startCwd);
+ claimToolImagesForTurn();
+ try {
+ await this.runQueuedItem(item);
+ } finally {
+ this.rememberLaneCwd(laneKey, this.capabilities.getCwd());
+ }
+ }))).catch((err) => {
+ logger.error({ err, turn: turn.id }, 'Turn failed outside its handler');
+ }).finally(() => {
+ turn.done = true;
+ if (this.activeTurns.get(laneKey) === turn) this.activeTurns.delete(laneKey);
+ logger.info({ turn: turn.id, lane: laneKey, ms: Date.now() - turn.startedAt, running: this.activeTurns.size }, 'Turn ended');
+ if (this.activeTurns.size === 0) this.governor.noteIdle();
+ this.processQueue();
+ if (this.isIdle() && this.idleWaiters.length > 0) {
+ for (const resolve of this.idleWaiters.splice(0)) resolve();
+ }
+ });
+ }
+ /** One queued message, start to finish: the work ledger and scheduled-run bookkeeping around handleMessage. */
+ private async runQueuedItem(item: { message: ChannelMessage; workKey?: string }): Promise<void> {
+ const msg = item.message;
try {
- while (this.messageQueue.length > 0) {
- const item = this.messageQueue.shift()!;
- const msg = item.message;
- if (item.workKey) this.queuedWorkKeys.delete(item.workKey);
- // The line moved: everyone still waiting learns their new place and what runs now.
- this.announceQueue(msg);
- this.currentWorkKey = item.workKey ?? null;
+ if (item.workKey) this.workLedger.markRunning(item.workKey);
+ await this.withSessionProgramming(msg, () => this.handleMessage(msg));
+ if (item.workKey && this.workLedger.get(item.workKey)?.status === 'running') {
+ this.workLedger.markFailed(item.workKey, 'Work ended without producing a durable final response');
+ }
+ } catch (err) {
+ if (item.workKey) {
+ const entry = this.workLedger.get(item.workKey);
+ if (entry?.status === 'completed') this.workLedger.markDeliveryError(item.workKey, err);
+ else this.workLedger.markFailed(item.workKey, err);
+ }
+ logger.error({ err, msg: msg.content.slice(0, 50) }, 'Failed to handle message');
+ } finally {
+ const taskId = msg.metadata?.scheduledTaskId;
+ const runId = msg.metadata?.scheduledRunId;
+ if (typeof taskId === 'string' && typeof runId === 'string') {
+ const entry = item.workKey ? this.workLedger.get(item.workKey) : undefined;
try {
- if (item.workKey) this.workLedger.markRunning(item.workKey);
- await this.withSessionProgramming(msg, () => this.handleMessage(msg));
- if (item.workKey && this.workLedger.get(item.workKey)?.status === 'running') {
- this.workLedger.markFailed(item.workKey, 'Work ended without producing a durable final response');
- }
+ this.scheduler.finishRun(taskId, runId, entry?.status === 'completed' ? 'completed' : 'failed',
+ entry?.status === 'completed' ? undefined : entry?.error ?? 'Scheduled work ended without confirmed completion');
} catch (err) {
- if (item.workKey) {
- const entry = this.workLedger.get(item.workKey);
- if (entry?.status === 'completed') this.workLedger.markDeliveryError(item.workKey, err);
- else this.workLedger.markFailed(item.workKey, err);
- }
- logger.error({ err, msg: msg.content.slice(0, 50) }, 'Failed to handle message');
- } finally {
- const taskId = msg.metadata?.scheduledTaskId;
- const runId = msg.metadata?.scheduledRunId;
- if (typeof taskId === 'string' && typeof runId === 'string') {
- const entry = item.workKey ? this.workLedger.get(item.workKey) : undefined;
- try {
- this.scheduler.finishRun(taskId, runId, entry?.status === 'completed' ? 'completed' : 'failed',
- entry?.status === 'completed' ? undefined : entry?.error ?? 'Scheduled work ended without confirmed completion');
- } catch (err) {
- // Leave the durable running record uncertain, but always release queue state.
- logger.error({ err, taskId, runId }, 'Could not persist scheduled run outcome');
- }
- }
- this.currentWorkKey = null;
- if (!this.lifecycle.is('idle') && this.lifecycle.canTransitionTo('idle')) {
- this.lifecycle.transition('idle');
- }
+ // Leave the durable running record uncertain, but always release queue state.
+ logger.error({ err, taskId, runId }, 'Could not persist scheduled run outcome');
}
}
- } finally {
- this.processing = false;
- if (this.messageQueue.length > 0) void this.processQueue();
}
}
+ /** The running turns as the governor sees them. */
+ private governedTurns(): GovernedTurn[] {
+ return [...this.activeTurns.values()].map((t) => ({
+ id: t.id,
+ startedAt: t.startedAt,
+ label: `${t.laneKey}: ${this.describeTurn(t)}`,
+ isStopping: () => t.done || !t.abort || t.abort.signal.aborted,
+ shed: (error: Error) => {
+ if (!t.abort || t.abort.signal.aborted) return;
+ t.abortReason = 'memory-pressure';
+ t.abort.abort(error);
+ this.captureHeapSnapshot();
+ },
+ }));
+ }
+
+ private heapSnapshotTaken = false;
+
+ /** Forensics, once per process: the first pressure stop writes a heap snapshot. Never throws. */
+ private captureHeapSnapshot(): void {
+ if (this.heapSnapshotTaken) return;
+ this.heapSnapshotTaken = true;
+ void (async () => {
+ try {
+ const { writeHeapSnapshot } = await import('node:v8');
+ const file = path.join(getMercuryHome(), `heap-task-${Date.now()}.heapsnapshot`);
+ writeHeapSnapshot(file);
+ logger.error({ file }, 'Heap snapshot captured for memory forensics');
+ } catch { /* forensics must never break the governor */ }
+ })();
+ }
+
+ /**
+ * The heap kept growing past the exit line even after turns were stopped:
+ * the allocator runs outside any abortable path and a V8 crash is next.
+ * Leave now, while the work ledger and sessions are still writable, so
+ * every interrupted chat is recovered on the next start.
+ */
+ private exitForMemory(heapUsed: number): void {
+ const turns = [...this.activeTurns.values()];
+ const mb = Math.round(heapUsed / 1048576);
+ try {
+ const first = turns[0];
+ writeCrashFlag({
+ reason: `Memory safety exit at ${mb}MB with ${turns.length} task(s) running: ${turns.map((t) => this.describeTurn(t).slice(0, 60)).join(' | ').slice(0, 300)}`,
+ timestamp: Date.now(),
+ activeTask: first ? this.describeTurn(first) : undefined,
+ channelId: first?.message.channelId,
+ channelType: first?.message.channelType,
+ });
+ } catch { /* best effort */ }
+ try {
+ process.stderr.write(`\n⚠ Mercury stopped: memory grew to ${mb}MB.\n Your work is saved and will be recoverable on the next start. Details: ~/.mercury/crash-report.log\n`);
+ } catch { /* stderr gone */ }
+ process.exit(0);
+ }
+
/**
* One inline continuation round: re-enter generation with the full tool
* loop and a fresh step budget, nudged by a system-style user message.
@@ -2558,6 +3042,7 @@ export class Agent {
}
await this.channels.startAll();
this.running = true;
+ this.governor.start(() => this.governedTurns());
if (!this.terminalOnly) {
const recovered = this.workLedger.recoverInterrupted();
@@ -2574,6 +3059,7 @@ export class Agent {
async sleep(): Promise<void> {
this.running = false;
+ this.governor.stop();
if (this.outboxRetryTimer) {
clearInterval(this.outboxRetryTimer);
this.outboxRetryTimer = null;
@@ -2853,7 +3339,6 @@ export class Agent {
// Short id printed on every terminal message and resolvable with /trace.
const traceId = (msg.id || '').replace(/[^a-z0-9]/gi, '').slice(-8) || Date.now().toString(36);
let loopAbortController = new AbortController();
- this.currentMessage = msg;
this.currentAbort = loopAbortController;
this.currentAbortReason = null;
const durableCwd = typeof msg.metadata?.workCwd === 'string' ? msg.metadata.workCwd : undefined;
@@ -2886,77 +3371,20 @@ export class Agent {
if (researchRun) this.emitResearch(msg, researchRun);
if (!isSlashCommand) raiseTurnIndicator();
const stopHeartbeat = isSlashCommand ? () => {} : this.startForegroundHeartbeat(msg);
- const heapBaseline = process.memoryUsage().heapUsed;
- const heapAbortThreshold = taskHeapAbortThreshold(getHeapStatistics().heap_size_limit, heapBaseline);
- const heapExitThreshold = taskHeapExitThreshold(getHeapStatistics().heap_size_limit, heapBaseline);
- const governorThresholds = memoryGovernorThresholds({
- heapSizeLimit: getHeapStatistics().heap_size_limit,
- baselineHeapUsed: heapBaseline,
- });
+ // Memory: the turn governor watches the heap for the whole process (one
+ // timer, not one per turn) and stops the newest turn under pressure
+ // (ADR-037). At step boundaries this turn checks in deterministically —
+ // the timer can't fire while the event loop is flooded.
+ const turnId = this.turn()?.id;
const memoryGovernor = (phase: string): 'ok' | 'abort' | 'exit' => {
- const verdict = memoryGovernorVerdict(process.memoryUsage().heapUsed, governorThresholds);
- if (verdict === 'abort') {
- logger.warn({ phase, heapMB: Math.round(process.memoryUsage().heapUsed / 1048576) }, 'Step governor: relief threshold exceeded — trimming conversation');
- }
- return verdict === 'ok' || verdict === 'relief' ? 'ok' : verdict;
+ const turns = this.governedTurns();
+ const verdict = this.governor.verdict(turns.length);
+ if (verdict === 'exit') return 'exit';
+ if (verdict === 'ok') return 'ok';
+ logger.warn({ phase, heapMB: Math.round(process.memoryUsage().heapUsed / 1048576), running: turns.length }, 'Step governor: over the memory line — trimming conversation');
+ return 'abort';
};
- const memoryGuard = setInterval(() => {
- const usage = process.memoryUsage();
- // Stage 2 — emergency: abort was attempted but the allocator kept
- // running outside the abortable path. Exit deliberately while the work
- // ledger and session store are still writable, so recovery survives.
- if (isTaskHeapUnsafe(usage.heapUsed, heapExitThreshold)) {
- logger.error({
- heapUsed: usage.heapUsed,
- threshold: heapExitThreshold,
- activity: this.currentActivity,
- }, 'Memory continued growing after abort — exiting to preserve work state');
- try {
- const { writeCrashFlag } = require('./crash-flag.js');
- writeCrashFlag({
- reason: `Memory safety exit at ${Math.round(usage.heapUsed / 1048576)}MB (abort threshold ${Math.round(heapAbortThreshold / 1048576)}MB). Task: ${this.currentActivity?.slice(0, 150) || 'unknown'}`,
- timestamp: Date.now(),
- activeTask: this.currentActivity || undefined,
- channelId: msg.channelId,
- channelType: msg.channelType,
- });
- } catch { /* best effort */ }
- try {
- process.stderr.write(
- `\n⚠ Mercury stopped the current task: memory grew to ${Math.round(usage.heapUsed / 1048576)}MB.\n Your work is saved and will be recoverable on the next start. Details: ~/.mercury/crash-report.log\n`,
- );
- } catch { /* stderr gone */ }
- process.exit(0);
- }
- // Stage 1 — attempt graceful stop of the current generation.
- if (!isTaskHeapUnsafe(usage.heapUsed, heapAbortThreshold) || this.currentAbortReason === 'memory-pressure') return;
- this.currentAbortReason = 'memory-pressure';
- const error = new Error(
- `Task stopped at ${Math.round(usage.heapUsed / 1048576)}MB heap usage before Mercury reached the V8 crash limit`,
- );
- logger.error({
- heapUsed: usage.heapUsed,
- heapTotal: usage.heapTotal,
- rss: usage.rss,
- threshold: heapAbortThreshold,
- activity: this.currentActivity,
- }, 'Task memory safety limit reached');
- loopAbortController.abort(error);
- // Forensics: capture a heap snapshot in the background. If growth
- // continues past the exit threshold, this .heapsnapshot identifies the
- // exact retainer. Best-effort — never throw from the guard.
- void (async () => {
- try {
- const { writeHeapSnapshot } = await import('node:v8');
- const { getMercuryHome } = await import('../utils/config.js');
- const { join } = await import('node:path');
- const file = join(getMercuryHome(), `heap-task-${Date.now()}.heapsnapshot`);
- await writeHeapSnapshot(file as any);
- logger.error({ file }, 'Heap snapshot captured for memory forensics');
- } catch { /* forensics must never break the guard */ }
- })();
- }, 1000);
- memoryGuard.unref?.();
+ const shouldYieldToMemory = (): boolean => turnId !== undefined && this.governor.shouldShed(turnId, this.governedTurns());
// Stall watchdog: the memory guard covers heap growth; this covers time.
// A task that emits nothing (no chunks, no tool events, no steps) for
// minutes is almost certainly dead — surface it, then abort the attempt
@@ -2979,6 +3407,7 @@ export class Agent {
});
stallWatchdog.start();
let canonicalSessionId: string | undefined;
+ let releaseSession: (() => void) | null = null;
if (this.supervisor && msg.channelType !== 'internal') {
const activeAgents = this.supervisor.getActiveAgents();
@@ -3101,6 +3530,10 @@ export class Agent {
: typeof msg.metadata?.externalConversationId === 'string' ? msg.metadata.externalConversationId : msg.channelId;
const canonicalSession = this.sessions.getOrCreateBound(msg.channelType, externalConversationId, suppliedSessionId);
canonicalSessionId = canonicalSession.id;
+ // Two lanes can reach one stored conversation (the terminal resuming a
+ // chat the desktop has open): their turns take it one at a time, so
+ // its history never interleaves (ADR-037).
+ releaseSession = await this.lockSession(canonicalSession.id);
// A normal chat that would write loose files into the home folder (the
// daemon's folder) writes into its own folder in ~/mercury-artifacts.
@@ -3451,8 +3884,7 @@ export class Agent {
// the step ended (tool calls pending = work in progress).
lastRoundSteps++;
lastStepHadToolCalls = !!(toolCalls && toolCalls.length > 0);
- const cliCh = this.channels.get('cli');
- if (cliCh instanceof CLIChannel) cliCh.bumpLiveActivitySteps();
+ this.cliFeed()?.bumpLiveActivitySteps();
// Every tool step goes into the per-turn trace (session history
// and /trace), not only the guard/continuation rounds.
noteToolSteps(toolCalls, toolResults);
@@ -3479,6 +3911,9 @@ export class Agent {
} catch { /* compaction is best-effort */ }
return;
}
+ // Already compacted: give way only if this is the turn the
+ // governor picks (the newest); an older one keeps working.
+ if (!shouldYieldToMemory()) return;
this.currentAbortReason = 'memory-pressure';
loopAbortController.abort(new Error(`Task stopped at ${Math.round(process.memoryUsage().heapUsed / 1048576)}MB heap usage (step governor)`));
return;
@@ -3750,8 +4185,7 @@ export class Agent {
this.completedStepCount++;
lastRoundSteps++;
lastStepHadToolCalls = !!(toolCalls && toolCalls.length > 0);
- const cliChResume = this.channels.get('cli');
- if (cliChResume instanceof CLIChannel) cliChResume.bumpLiveActivitySteps();
+ this.cliFeed()?.bumpLiveActivitySteps();
if (toolCalls && toolResults && toolCalls.length > 0) {
hasCompletedTool = true;
noteToolSteps(toolCalls, toolResults);
@@ -3788,7 +4222,7 @@ export class Agent {
const providerDeadlineAt = Date.now() + MAX_PROVIDER_ATTEMPT_MS;
this.markProgress(`Calling ${provider.name}...`);
this.pushLiveActivity(`Calling ${provider.name}`, provider.getModel());
- updateCliProviderStatus(this.channels.get('cli'), provider.name, provider.getModel());
+ if (this.cliFeed()) updateCliProviderStatus(this.channels.get('cli'), provider.name, provider.getModel());
const deepseekProviderOptions = provider instanceof DeepSeekProvider && provider.isReasoner
? { deepseek: { thinking: { type: 'enabled' as const } } }
: undefined;
@@ -4378,8 +4812,7 @@ export class Agent {
// Completion-contract tracking for the guard round.
lastRoundSteps++;
lastStepHadToolCalls = !!(toolCalls && toolCalls.length > 0);
- const cliChGen = this.channels.get('cli');
- if (cliChGen instanceof CLIChannel) cliChGen.bumpLiveActivitySteps();
+ this.cliFeed()?.bumpLiveActivitySteps();
if (toolCalls && toolResults && toolCalls.length > 0) {
hasCompletedTool = true;
noteToolSteps(toolCalls, toolResults);
@@ -4901,6 +5334,7 @@ export class Agent {
} catch { /* best effort */ }
this.lifecycle.transition('idle');
} finally {
+ releaseSession?.();
if (chatFolder) {
if (cwdBeforeChatFolder && this.capabilities.getCwd() === chatFolder) this.capabilities.setCwd(cwdBeforeChatFolder);
this.chatFolders().close(chatFolder);
@@ -4914,24 +5348,19 @@ export class Agent {
if (closed) planChannel.sendPlan(closed, msg.channelId);
}
this.emitResearch(msg, researchRun);
- this.researchMode.endRun();
+ this.researchMode.endRun(msg.channelId);
}
- clearInterval(memoryGuard);
stallWatchdog.stop();
stopHeartbeat();
this.finalizeChannelTask(msg);
this.capabilities.setToolsDisabled(false);
this.capabilities.permissions.setTurnPluginGrants([]);
- this.currentMessage = null;
this.currentAbort = null;
this.currentAbortReason = null;
this.currentActivity = '';
this.completedStepCount = 0;
this.stepNarrative = [];
- {
- const ch = this.channels.get('cli');
- if (ch instanceof CLIChannel) ch.clearLiveActivity();
- }
+ this.cliFeed()?.clearLiveActivity();
if (isInternal) {
this.capabilities.permissions.endTurnGrant();
}
@@ -5244,11 +5673,19 @@ export class Agent {
// Validation loop (§3.1): the beliefs the previous turn acted on earn
// weak support once the owner's next message in the same session shows
// no correction. Then remember what this turn acted on.
- const pending = this.pendingActedOn;
- if (pending && pending.ids.length > 0 && pending.sessionId && pending.sessionId === ctx.sessionId && !signals.correction.detected) {
- try { beliefs.actedOnOk(pending.ids, pending.sessionId); } catch (err) { logger.debug({ err }, 'actedOnOk failed'); }
+ // Per session (ADR-037): another chat's turn in between no longer resets it.
+ if (ctx.sessionId) {
+ const pending = this.pendingActedOn.get(ctx.sessionId);
+ if (pending && pending.length > 0 && !signals.correction.detected) {
+ try { beliefs.actedOnOk(pending, ctx.sessionId); } catch (err) { logger.debug({ err }, 'actedOnOk failed'); }
+ }
+ this.pendingActedOn.delete(ctx.sessionId);
+ this.pendingActedOn.set(ctx.sessionId, [...(this.lastInjectedBeliefIds ?? [])]);
+ if (this.pendingActedOn.size > 200) {
+ const oldest = this.pendingActedOn.keys().next().value;
+ if (oldest !== undefined) this.pendingActedOn.delete(oldest);
+ }
}
- this.pendingActedOn = ctx.sessionId ? { ids: [...(this.lastInjectedBeliefIds ?? [])], sessionId: ctx.sessionId } : null;
try {
const ops = await extractBeliefOperations({
@@ -5322,13 +5759,8 @@ export class Agent {
try { this.workLedger.markCancelled(item.workKey, reason); } catch { /* entry may not exist */ }
}
let stopped = dropped.length > 0;
- if (this.currentMessage?.channelId.startsWith(channelPrefix) && this.currentAbort && !this.currentAbort.signal.aborted) {
- this.currentAbortReason = 'stopped';
- this.currentAbort.abort();
- if (this.currentWorkKey) {
- try { this.workLedger.markCancelled(this.currentWorkKey, reason); } catch { /* entry may not exist */ }
- }
- stopped = true;
+ for (const turn of this.activeTurns.values()) {
+ if (turn.message.channelId.startsWith(channelPrefix) && this.abortTurn(turn, 'stopped', reason)) stopped = true;
}
if (stopped) logger.info({ channelPrefix }, 'Work stopped for one channel');
return stopped;
diff --git a/src/core/chat-queue.test.ts b/src/core/chat-queue.test.ts
index c7df9a20..4b8cd185 100644
--- a/src/core/chat-queue.test.ts
+++ b/src/core/chat-queue.test.ts
@@ -5,12 +5,13 @@ import { afterEach, describe, expect, it } from 'vitest';
import type { ChannelMessage } from '../types/channel.js';
import { Agent } from './agent.js';
import { WorkLedger } from './work-ledger.js';
+import { bareTurnFields, startFakeTurn } from './testing/fake-turns.js';
/**
- * Two chats at once on the desktop: Mercury runs one turn at a time, so the
- * second waits. It must say so (its place in line, and what's ahead of it)
- * instead of showing "Thinking" for a turn that hasn't started — and the
- * owner can put it first.
+ * Chats on the desktop when every slot is taken (ADR-037: chats run at once
+ * up to the governor's limit): a waiting chat must say so (its place in
+ * line, and what it waits for) instead of showing "Thinking" for a turn that
+ * hasn't started — and the owner can put it first.
*/
const dirs: string[] = [];
@@ -28,7 +29,7 @@ function agentWithWeb() {
const web = { sendQueued: (target: string, d: { position: number; busyWith?: string; busySessionId?: string }) => sent.push({ target, ...d }) };
const agent = Object.create(Agent.prototype) as Agent;
Object.assign(agent, {
- messageQueue: [], queuedWorkKeys: new Set(), workLedger, processing: false, currentMessage: null, currentActivity: '', currentAbort: null,
+ ...bareTurnFields(), workLedger,
channels: { get: (t: string) => (t === 'web' ? web : undefined) },
});
const enqueue = (m: ChannelMessage) => agent.queueMessage(m, workLedger.accept(m).entry.key);
@@ -38,7 +39,7 @@ function agentWithWeb() {
describe('a chat waiting for another', () => {
it('is told its place in line and what is running, as soon as it joins', () => {
const { agent, enqueue, sent } = agentWithWeb();
- Object.assign(agent, { processing: true, currentMessage: msg('r', 'research', 'Research the top news on TechCrunch today') });
+ startFakeTurn(agent, msg('r', 'research', 'Research the top news on TechCrunch today'));
enqueue(msg('j', 'jokes', 'tell me a joke'));
expect(sent).toEqual([{ target: 'jokes', position: 1, busyWith: 'Research the top news on TechCrunch today', busySessionId: 'research' }]);
expect(agent.queueStateFor('jokes')).toMatchObject({ state: 'queued', position: 1, busySessionId: 'research' });
@@ -55,14 +56,14 @@ describe('a chat waiting for another', () => {
it('uses what the running turn is doing right now, when known', () => {
const { agent, enqueue, sent } = agentWithWeb();
const running = msg('r', 'research', 'Research the top news');
- Object.assign(agent, { processing: true, currentMessage: running, currentActivity: '🔎 Searching the web' });
+ startFakeTurn(agent, running, '🔎 Searching the web');
enqueue(msg('j', 'jokes'));
expect(sent[0].busyWith).toBe('Searching the web');
});
it('"do mine first" moves the chat to the front and tells everyone their new place', () => {
const { agent, enqueue, sent } = agentWithWeb();
- Object.assign(agent, { processing: true, currentMessage: msg('r', 'research') });
+ startFakeTurn(agent, msg('r', 'research'));
enqueue(msg('a', 'alpha'));
enqueue(msg('b', 'beta'));
sent.length = 0;
@@ -71,3 +72,18 @@ describe('a chat waiting for another', () => {
expect(agent.prioritize('nobody')).toBe(0);
});
});
+
+describe('a chat waiting behind its own running turn (ADR-037)', () => {
+ it('waits for its own chat, not for another, and counts only its own line', () => {
+ const { agent, enqueue, sent } = agentWithWeb();
+ startFakeTurn(agent, msg('r1', 'research', 'long research'), '', 1);
+ startFakeTurn(agent, msg('c1', 'code', 'build it'), '🔧 Running tests', 2);
+ enqueue(msg('c2', 'code', 'and then deploy'));
+ // Its own chat runs: that chat already shows the running turn, no "waiting for another chat" notice.
+ expect(sent).toEqual([]);
+ expect(agent.queueStateFor('code')).toEqual({ state: 'running' });
+ // Another busy chat's waiting message does not push a free chat back.
+ enqueue(msg('j', 'jokes'));
+ expect(agent.queueStateFor('jokes')).toMatchObject({ state: 'queued', position: 1 });
+ });
+});
diff --git a/src/core/commands/bg-command.ts b/src/core/commands/bg-command.ts
index 7935c99b..bcf0c954 100644
--- a/src/core/commands/bg-command.ts
+++ b/src/core/commands/bg-command.ts
@@ -12,18 +12,19 @@ export async function handleBgCommand(agent: Agent, trimmed: string, msg: Channe
const args = parts.slice(1).join(' ');
if (sub === 'current') {
- if (!agent.processing || !agent.currentMessage) {
- await channel.send('No active task to background.', msg.channelId);
+ // This chat's running task (ADR-037: other chats' tasks are theirs).
+ const turn = agent.turnForChannel(msg.channelId);
+ // When the chat was idle, `/bg current` runs as the chat's own turn:
+ // that turn is the command itself, never a task to move.
+ if (!turn || turn.message.content.trim().startsWith('/')) {
+ await channel.send('No active task to background in this chat.', msg.channelId);
return;
}
- const taskDescription = agent.currentMessage.content.trim();
- const sourceChannelId = agent.currentMessage.channelId;
- const sourceChannelType = agent.currentMessage.channelType as any;
+ const taskDescription = turn.message.content.trim();
+ const sourceChannelId = turn.message.channelId;
+ const sourceChannelType = turn.message.channelType as any;
- if (agent.currentAbort) {
- agent.currentAbortReason = 'backgrounded';
- agent.currentAbort.abort();
- }
+ agent.abortTurn(turn, 'backgrounded');
if (agent.supervisor) {
const agentId = await agent.supervisor.spawn({
@@ -31,7 +32,8 @@ export async function handleBgCommand(agent: Agent, trimmed: string, msg: Channe
sourceChannelId,
sourceChannelType,
});
- const bgId = agent.backgroundTasks.spawnAgent(taskDescription, agent.capabilities.getCwd(), agentId);
+ const workCwd = turn.message.metadata?.workCwd;
+ const bgId = agent.backgroundTasks.spawnAgent(taskDescription, typeof workCwd === 'string' ? workCwd : agent.capabilities.getCwd(), agentId);
await channel.send(`📋 Active task moved to background as ${bgId}. I'll notify you when it completes.`, msg.channelId);
} else {
await channel.send('Cannot background: sub-agents not available. The active task has been aborted.', msg.channelId);
diff --git a/src/core/commands/chat-command.ts b/src/core/commands/chat-command.ts
index d77744a1..a6a54a14 100644
--- a/src/core/commands/chat-command.ts
+++ b/src/core/commands/chat-command.ts
@@ -41,7 +41,7 @@ import { createProvider, ProviderRegistry as ProviderRegistryImpl } from '../../
import { ProgrammingMode } from '../programming-mode.js';
import { logger } from '../../utils/logger.js';
import { CLIChannel } from '../../channels/cli.js';
-import { formatToolStep, formatNarrative, type NarrativeStep } from '../../utils/tool-label.js';
+import { formatToolStep, type NarrativeStep } from '../../utils/tool-label.js';
import { getTelegramHelp, getDiscordHelp, getSlackHelp } from '../../utils/manual.js';
import { WebChannel } from '../../channels/web.js';
import { describePermissionMode, loadPermissionMode, savePermissionMode } from '../../capabilities/permission-mode-store.js';
@@ -214,18 +214,20 @@ export async function handleChatCommand(agent: Agent, content: string, channelTy
}
if (cmd === '/progress' || cmd === '/still') {
- if (!agent.processing || !agent.currentMessage) {
+ // Here the chat itself was idle (this command is its turn), so report
+ // what the other chats are doing (ADR-037: they run at the same time).
+ const others = agent.runningTurns().filter((t) => t.channelId !== channelId);
+ if (others.length === 0) {
await channel.send('No active foreground task.', channelId);
return true;
}
- const elapsedSec = Math.round((Date.now() - agent.currentMessage.timestamp) / 1000);
- const stepInfo = agent.completedStepCount > 0 ? ` · step ${agent.completedStepCount}/${MAX_STEPS}` : '';
- const narrative = formatNarrative(agent.stepNarrative, agent.currentActivity, 10);
- const narrativeBlock = narrative ? `\n${narrative}` : '';
- await channel.send(
- `⏳ Task in progress (${elapsedSec}s${stepInfo})${narrativeBlock}\nUse /bg current to move it to background.`,
- channelId,
- );
+ const lines = others.map((t) => {
+ const elapsedSec = Math.round((Date.now() - t.startedAt) / 1000);
+ const stepInfo = t.completedSteps > 0 ? ` · step ${t.completedSteps}/${MAX_STEPS}` : '';
+ const doing = (t.activity || t.content).replace(/\s+/g, ' ').trim().slice(0, 80);
+ return `• ${t.channelType} (${elapsedSec}s${stepInfo}): ${doing}`;
+ });
+ await channel.send(`Nothing is running in this chat. Running elsewhere:\n${lines.join('\n')}`, channelId);
return true;
}
@@ -1752,25 +1754,16 @@ export async function handleChatCommand(agent: Agent, content: string, channelTy
return true;
}
+ // Here this chat was idle (the command is its own turn). Other chats may be
+ // running (ADR-037): /halt stops them all, /stop only what this chat started
+ // — a full stop (locks released, task board cleared) when nothing else runs.
if (cmd === '/halt') {
- if (!agent.supervisor) {
- await channel.send('Sub-agents are not available.', channelId);
- return true;
- }
- await agent.supervisor.haltAll();
- await channel.send('All sub-agents halted and queue cleared.', channelId);
+ await channel.send(await agent.stopAllWork('halted'), channelId);
return true;
}
if (cmd === '/stop') {
- if (!agent.supervisor) {
- await channel.send('Sub-agents are not available.', channelId);
- return true;
- }
- await agent.supervisor.haltAll();
- agent.supervisor.clearTaskBoard();
- agent.lifecycle.transition('idle');
- await channel.send('All sub-agents stopped, queue cleared, locks released, task board cleared. Short-term memory preserved.', channelId);
+ await channel.send(await agent.stopAllWork('stopped', { channelId }), channelId);
return true;
}
diff --git a/src/core/commands/fast-path-command.ts b/src/core/commands/fast-path-command.ts
index f284bc71..c9b49f8d 100644
--- a/src/core/commands/fast-path-command.ts
+++ b/src/core/commands/fast-path-command.ts
@@ -44,8 +44,13 @@ export async function handleFastPathCommand(agent: Agent, msg: ChannelMessage):
return;
}
- if (trimmed === '/halt' || trimmed === '/stop') {
- await channel.send(await agent.stopAllWork(trimmed === '/stop' ? 'stopped' : 'halted'), msg.channelId);
+ // /stop stops this chat's work; /halt stops everything everywhere (ADR-037).
+ if (trimmed === '/stop') {
+ await channel.send(await agent.stopAllWork('stopped', { channelId: msg.channelId }), msg.channelId);
+ return;
+ }
+ if (trimmed === '/halt') {
+ await channel.send(await agent.stopAllWork('halted'), msg.channelId);
return;
}
@@ -61,16 +66,23 @@ export async function handleFastPathCommand(agent: Agent, msg: ChannelMessage):
}
if (trimmed === '/progress' || trimmed === '/still') {
- if (!agent.processing || !agent.currentMessage) {
- await channel.send('No active foreground task.', msg.channelId);
+ const running = agent.runningTurns();
+ const mine = running.find((t) => t.channelId === msg.channelId);
+ if (!mine) {
+ const others = running.length;
+ await channel.send(others > 0
+ ? `Nothing is running in this chat. ${others} task${others === 1 ? '' : 's'} running in other chats.`
+ : 'No active foreground task.', msg.channelId);
return;
}
- const elapsedSec = Math.round((Date.now() - agent.currentMessage.timestamp) / 1000);
- const stepInfo = agent.completedStepCount > 0 ? ` · step ${agent.completedStepCount}/${MAX_STEPS}` : '';
- const narrative = formatNarrative(agent.stepNarrative, agent.currentActivity, 10);
+ const elapsedSec = Math.round((Date.now() - mine.startedAt) / 1000);
+ const stepInfo = mine.completedSteps > 0 ? ` · step ${mine.completedSteps}/${MAX_STEPS}` : '';
+ const narrative = formatNarrative(mine.narrative, mine.activity, 10);
const narrativeBlock = narrative ? `\n${narrative}` : '';
+ const others = running.length - 1;
+ const othersLine = others > 0 ? `\n(${others} more task${others === 1 ? '' : 's'} running in other chats.)` : '';
await channel.send(
- `⏳ Task in progress (${elapsedSec}s${stepInfo})${narrativeBlock}\nUse /bg current to move it to background.`,
+ `⏳ Task in progress (${elapsedSec}s${stepInfo})${narrativeBlock}\nUse /bg current to move it to background.${othersLine}`,
msg.channelId,
);
return;
@@ -100,8 +112,14 @@ export async function handleFastPathCommand(agent: Agent, msg: ChannelMessage):
const agentList = activeAgents.map(a => `**${a.id}**: ${a.task.slice(0, 40)}`).join(', ');
await channel.send(`I'm busy working on sub-agent tasks (${agentList}). Your message has been queued — I'll respond once I'm free. Use /agents to check status.`, msg.channelId);
} else {
- const elapsedSec = agent.currentMessage ? Math.round((Date.now() - agent.currentMessage.timestamp) / 1000) : 0;
- await channel.send(`I'm busy processing${elapsedSec > 0 ? ` (${elapsedSec}s elapsed)` : ''}. Use /progress for live status or /bg current to move this task to the background.`, msg.channelId);
+ const mine = agent.runningTurns().find((t) => t.channelId === msg.channelId);
+ if (mine) {
+ const elapsedSec = Math.round((Date.now() - mine.startedAt) / 1000);
+ await channel.send(`I'm busy processing${elapsedSec > 0 ? ` (${elapsedSec}s elapsed)` : ''}. Use /progress for live status or /bg current to move this task to the background.`, msg.channelId);
+ } else {
+ // This chat is free, but every slot is taken by other chats.
+ await channel.send(`I'm working on ${agent.activeTurnCount} other chat${agent.activeTurnCount === 1 ? '' : 's'} right now — yours is next in line and starts as soon as a slot frees up.`, msg.channelId);
+ }
}
agent.queueMessage(msg);
diff --git a/src/core/concurrent-turns.test.ts b/src/core/concurrent-turns.test.ts
new file mode 100644
index 00000000..079590cd
--- /dev/null
+++ b/src/core/concurrent-turns.test.ts
@@ -0,0 +1,225 @@
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+import type { ChannelMessage } from '../types/channel.js';
+import { Agent, laneKeyFor } from './agent.js';
+import { WorkLedger } from './work-ledger.js';
+import { bareTurnFields } from './testing/fake-turns.js';
+
+/**
+ * ADR-037: chats run at once, each in its own lane; one chat's messages
+ * still run strictly one after another; every turn sees only its own state;
+ * the governor's limit holds extra chats back; a stop in one chat leaves the
+ * others running.
+ */
+
+const dirs: string[] = [];
+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });
+
+const tick = (ms = 1) => new Promise<void>((r) => setTimeout(r, ms));
+
+function msg(id: string, channelId: string, channelType: ChannelMessage['channelType'] = 'web'): ChannelMessage {
+ return { id, channelId, channelType, senderId: 'u', content: `do ${id}`, timestamp: Date.now(), metadata: {} };
+}
+
+interface Gate { open: () => void; promise: Promise<void> }
+function gate(): Gate {
+ let open!: () => void;
+ const promise = new Promise<void>((r) => { open = r; });
+ return { open, promise };
+}
+
+function harness(limit = 4) {
+ const dir = mkdtempSync(join(tmpdir(), 'mercury-concurrent-'));
+ dirs.push(dir);
+ const workLedger = new WorkLedger({ filePath: join(dir, 'work-ledger.json') });
+ const agent = Object.create(Agent.prototype) as Agent;
+ const gates = new Map<string, Gate>();
+ const log: string[] = [];
+ /** What each turn saw of "its own" state after its awaits. */
+ const seen = new Map<string, { message: string | undefined; abortIsMine: boolean; activity: string }>();
+ Object.assign(agent, {
+ ...bareTurnFields({ limit }),
+ workLedger,
+ running: true,
+ channels: { get: () => undefined, getChannelForMessage: () => undefined },
+ globalLifecycle: { is: () => true },
+ supervisor: undefined,
+ withSessionProgramming: (_m: unknown, run: () => Promise<void>) => run(),
+ handleMessage: async (m: ChannelMessage) => {
+ const self = agent as unknown as { currentAbort: AbortController | null; currentActivity: string; currentMessage: ChannelMessage | null };
+ const mine = new AbortController();
+ self.currentAbort = mine;
+ self.currentActivity = `working on ${m.id}`;
+ log.push(`start ${m.id}`);
+ const g = gate();
+ gates.set(m.id, g);
+ await Promise.race([g.promise, new Promise<void>((r) => mine.signal.addEventListener('abort', () => r()))]);
+ await tick();
+ seen.set(m.id, { message: self.currentMessage?.id, abortIsMine: self.currentAbort === mine, activity: self.currentActivity });
+ log.push(`${mine.signal.aborted ? 'aborted' : 'end'} ${m.id}`);
+ workLedger.markCompleted((agent as unknown as { currentWorkKey: string }).currentWorkKey, 'done');
+ },
+ });
+ const send = (m: ChannelMessage) => {
+ agent.queueMessage(m, workLedger.accept(m).entry.key);
+ (agent as unknown as { processQueue(): void }).processQueue();
+ };
+ const finish = async (id: string) => {
+ for (let i = 0; i < 100 && !gates.has(id); i++) await tick();
+ gates.get(id)!.open();
+ await tick(5);
+ };
+ return { agent, send, finish, log, seen };
+}
+
+describe('concurrent turns', () => {
+ it('two chats run at the same time', async () => {
+ const { agent, send, finish, log } = harness();
+ send(msg('a1', 'chat-a'));
+ send(msg('b1', 'chat-b'));
+ await tick(5);
+ expect(log).toEqual(['start a1', 'start b1']);
+ expect(agent.activeTurnCount).toBe(2);
+ await finish('b1');
+ await finish('a1');
+ await agent.whenIdle();
+ expect(log).toEqual(['start a1', 'start b1', 'end b1', 'end a1']);
+ });
+
+ it("one chat's messages run one after another, in order", async () => {
+ const { agent, send, finish, log } = harness();
+ send(msg('a1', 'chat-a'));
+ send(msg('a2', 'chat-a'));
+ send(msg('b1', 'chat-b'));
+ await tick(5);
+ expect(log).toEqual(['start a1', 'start b1']);
+ await finish('a1');
+ expect(log.slice(-1)).toEqual(['start a2']);
+ await finish('a2');
+ await finish('b1');
+ await agent.whenIdle();
+ expect(log.filter((l) => l.endsWith('a1') || l.endsWith('a2'))).toEqual(['start a1', 'end a1', 'start a2', 'end a2']);
+ });
+
+ it('every turn sees its own message, abort controller and activity', async () => {
+ const { agent, send, finish, seen } = harness();
+ send(msg('a1', 'chat-a'));
+ send(msg('b1', 'chat-b'));
+ send(msg('c1', 'chat-c'));
+ await tick(5);
+ await finish('b1');
+ await finish('c1');
+ await finish('a1');
+ await agent.whenIdle();
+ for (const id of ['a1', 'b1', 'c1']) {
+ expect(seen.get(id)).toEqual({ message: id, abortIsMine: true, activity: `working on ${id}` });
+ }
+ // Outside any turn there is no "current" turn state.
+ expect(agent.currentMessage).toBeNull();
+ expect(agent.currentActivity).toBe('');
+ });
+
+ it('the limit holds extra chats back until a slot frees', async () => {
+ const { agent, send, finish, log } = harness(2);
+ send(msg('a1', 'chat-a'));
+ send(msg('b1', 'chat-b'));
+ send(msg('c1', 'chat-c'));
+ await tick(5);
+ expect(log).toEqual(['start a1', 'start b1']);
+ expect(agent.queueStateFor('chat-c')).toMatchObject({ state: 'queued', position: 1 });
+ await finish('a1');
+ expect(log).toContain('start c1');
+ await finish('b1');
+ await finish('c1');
+ await agent.whenIdle();
+ });
+
+ it('/stop in one chat stops only that chat', async () => {
+ const { agent, send, finish, log } = harness();
+ send(msg('a1', 'chat-a'));
+ send(msg('b1', 'chat-b'));
+ await tick(5);
+ const note = await agent.stopAllWork('stopped', { channelId: 'chat-a' });
+ expect(note).toMatch(/Stopped this chat's task/);
+ expect(note).toMatch(/1 task in other chats keeps running/);
+ await tick(5);
+ expect(log).toContain('aborted a1');
+ expect(log).not.toContain('aborted b1');
+ expect(agent.activeTurnCount).toBe(1);
+ expect(await agent.stopAllWork('stopped', { channelId: 'chat-z' })).toMatch(/^Nothing is running in this chat\./);
+ await finish('b1');
+ await agent.whenIdle();
+ });
+
+ it('/halt stops every chat', async () => {
+ const { agent, send, log } = harness();
+ send(msg('a1', 'chat-a'));
+ send(msg('b1', 'chat-b'));
+ await tick(5);
+ await agent.stopAllWork('halted');
+ await agent.whenIdle();
+ expect(log).toContain('aborted a1');
+ expect(log).toContain('aborted b1');
+ });
+});
+
+describe('laneKeyFor', () => {
+ it('a session id names the lane; otherwise the channel conversation', () => {
+ expect(laneKeyFor({ ...msg('x', 'req-1'), sessionId: 's1' })).toBe('session:s1');
+ expect(laneKeyFor({ ...msg('x', 'req-2'), metadata: { sessionId: 's1' } })).toBe('session:s1');
+ expect(laneKeyFor(msg('x', '12345', 'telegram'))).toBe('telegram:12345');
+ expect(laneKeyFor({ ...msg('x', 'ch', 'web'), metadata: { externalConversationId: 'conv' } })).toBe('web:conv');
+ });
+
+ it('the terminal is one lane, and each scheduled task its own', () => {
+ expect(laneKeyFor(msg('x', 'cli', 'cli'))).toBe('cli');
+ expect(laneKeyFor({ ...msg('x', 'internal', 'internal'), metadata: { scheduledTaskId: 't1' } })).toBe('internal:t1');
+ expect(laneKeyFor({ ...msg('x', 'internal', 'internal'), metadata: { scheduledTaskId: 't2' } })).toBe('internal:t2');
+ });
+});
+
+describe('one stored conversation, two lanes', () => {
+ it('turns take the conversation one at a time, in order, and the lock is forgotten after', async () => {
+ const agent = Object.create(Agent.prototype) as Agent;
+ Object.assign(agent, { sessionLocks: new Map() });
+ const lock = (id: string) => (agent as unknown as { lockSession(id: string): Promise<() => void> }).lockSession(id);
+ const order: string[] = [];
+ const releaseA = await lock('s1');
+ const b = lock('s1').then((release) => { order.push('b'); return release; });
+ const c = lock('s1').then((release) => { order.push('c'); return release; });
+ const other = await lock('s2'); // a different conversation is never held up
+ other();
+ await tick(2);
+ expect(order).toEqual([]);
+ releaseA();
+ const releaseB = await b;
+ await tick(2);
+ expect(order).toEqual(['b']);
+ releaseB();
+ releaseB(); // releasing twice is harmless
+ (await c)();
+ expect(order).toEqual(['b', 'c']);
+ expect((agent as unknown as { sessionLocks: Map<string, unknown> }).sessionLocks.size).toBe(0);
+ });
+});
+
+describe('a stop typed in an idle chat (it runs as that chat\'s own turn)', () => {
+ it('never aborts itself, and leaves other chats running', async () => {
+ const { agent, send, finish, log } = harness();
+ send(msg('b1', 'chat-b'));
+ await tick(5);
+ // Simulate the /stop command running as chat-a's own turn.
+ const internal = agent as unknown as { activeTurns: Map<string, unknown>; turnStore: { run<T>(s: unknown, fn: () => T): T } };
+ const { startFakeTurn } = await import('./testing/fake-turns.js');
+ const own = startFakeTurn(agent, msg('stop', 'chat-a')) as unknown as { abort: AbortController; id: string };
+ const note = await internal.turnStore.run(own, () => agent.stopAllWork('stopped', { channelId: 'chat-a' }));
+ expect(own.abort.signal.aborted).toBe(false);
+ expect(note).toBe('Nothing is running in this chat. 1 task in other chats keeps running — /halt stops everything.');
+ internal.activeTurns.delete('web:chat-a');
+ expect(log).not.toContain('aborted b1');
+ await finish('b1');
+ await agent.whenIdle();
+ });
+});
diff --git a/src/core/lifecycle.ts b/src/core/lifecycle.ts
index 31dfc1f1..525621ca 100644
--- a/src/core/lifecycle.ts
+++ b/src/core/lifecycle.ts
@@ -20,7 +20,12 @@ const VALID_TRANSITIONS: Transition[] = [
];
export class Lifecycle {
- private state: AgentState = 'unborn';
+ private state: AgentState;
+
+ /** A turn's own lifecycle starts at 'idle' (ADR-037); the runtime's at 'unborn'. */
+ constructor(initial: AgentState = 'unborn') {
+ this.state = initial;
+ }
getState(): AgentState {
return this.state;
diff --git a/src/core/research-mode.ts b/src/core/research-mode.ts
index 390183c7..97bc5b44 100644
--- a/src/core/research-mode.ts
+++ b/src/core/research-mode.ts
@@ -16,9 +16,32 @@ export class ResearchMode {
/** The chat it was switched on for; null = whichever message comes next. */
private armedFor: string | null = null;
private planFirst = false;
- private run: ResearchRun | null = null;
+ /**
+ * Runs going now, one per chat (ADR-037: chats run at once, so two can be
+ * researching together). Insertion order = start order.
+ */
+ private runs = new Map<string, ResearchRun>();
/** The last run in each chat, for Continue / Retry and screens that open later. */
private lastRuns = new Map<string, ResearchRun>();
+ /** The chat the calling turn belongs to (set by the agent); null outside a turn. */
+ private scope: () => string | null = () => null;
+
+ /** Tell research which chat the calling code is working for (the agent's turn scope). */
+ setScope(resolver: () => string | null): void {
+ this.scope = resolver;
+ }
+
+ /**
+ * "The" run for the calling code: inside a turn, that chat's run (never
+ * another chat's); outside one (status screens), the newest run going.
+ */
+ private get run(): ResearchRun | null {
+ const sessionId = this.scope();
+ if (sessionId !== null) return this.runs.get(sessionId) ?? null;
+ let newest: ResearchRun | null = null;
+ for (const r of this.runs.values()) newest = r;
+ return newest;
+ }
getState(): ResearchModeState {
return this.run ? 'on' : this.state;
@@ -67,7 +90,8 @@ export class ResearchMode {
this.state = 'off';
this.armedFor = null;
this.planFirst = false;
- this.run = run;
+ this.runs.delete(sessionId);
+ this.runs.set(sessionId, run);
this.lastRuns.set(sessionId, run);
if (this.lastRuns.size > 50) this.lastRuns.delete(this.lastRuns.keys().next().value as string);
logger.info({ runId: run.id, sessionId, topic: run.topic }, 'Research run started');
@@ -80,8 +104,12 @@ export class ResearchMode {
/** The run for this chat: the one going, else its last one. */
runFor(sessionId: string): ResearchRun | null {
- if (this.run?.sessionId === sessionId) return this.run;
- return this.lastRuns.get(sessionId) ?? null;
+ return this.runs.get(sessionId) ?? this.lastRuns.get(sessionId) ?? null;
+ }
+
+ /** The run going in this chat right now, if any. */
+ activeRunFor(sessionId: string): ResearchRun | null {
+ return this.runs.get(sessionId) ?? null;
}
/** What a screen opening this chat should show. */
@@ -90,12 +118,13 @@ export class ResearchMode {
return { armed: this.armedForSession(sessionId), planFirst: this.planFirst, topic: this.topic, run: run ? run.snapshot() : null };
}
- /** The run's turn is over (however it ended). Research is off again. */
- endRun(): void {
- if (!this.run) return;
- if (this.run.outcome === 'running') this.run.end('done');
- logger.info({ runId: this.run.id, outcome: this.run.outcome }, 'Research run ended');
- this.run = null;
+ /** The run's turn is over (however it ended). Research is off again for that chat. */
+ endRun(sessionId?: string): void {
+ const run = sessionId !== undefined ? this.runs.get(sessionId) ?? null : this.run;
+ if (!run) return;
+ if (run.outcome === 'running') run.end('done');
+ logger.info({ runId: run.id, outcome: run.outcome }, 'Research run ended');
+ this.runs.delete(run.sessionId);
this.topic = null;
}
diff --git a/src/core/scheduled-dispatch.test.ts b/src/core/scheduled-dispatch.test.ts
index 3eb73d52..eca586e4 100644
--- a/src/core/scheduled-dispatch.test.ts
+++ b/src/core/scheduled-dispatch.test.ts
@@ -6,6 +6,7 @@ import { Agent } from './agent.js';
import { WorkLedger } from './work-ledger.js';
import { Scheduler, type ScheduledTaskManifest } from './scheduler.js';
import type { MercuryConfig } from '../utils/config.js';
+import { bareTurnFields } from './testing/fake-turns.js';
const dirs: string[] = [];
afterEach(() => {
@@ -24,16 +25,16 @@ function harness(fail = false) {
const internal = agent as unknown as {
currentWorkKey: string;
handleScheduledTask(manifest: ScheduledTaskManifest, runId: string): Promise<'queued'>;
- processQueue(): Promise<void>;
+ processQueue(): void;
};
const scheduler = new Scheduler({ heartbeat: { intervalMinutes: 30 } } as MercuryConfig,
(manifest, runId) => internal.handleScheduledTask(manifest, runId));
const effect = vi.fn();
Object.assign(agent, {
- scheduler, workLedger, messageQueue: [], queuedWorkKeys: new Set(), processing: false, running: false,
- currentMessage: null, currentWorkKey: null,
+ ...bareTurnFields(),
+ scheduler, workLedger, running: false,
channels: { get: () => undefined, getNotificationChannel: () => undefined },
- lifecycle: { is: () => true },
+ globalLifecycle: { is: () => true },
announceQueue: () => {},
withSessionProgramming: (_msg: unknown, run: () => Promise<void>) => run(),
handleMessage: async () => {
@@ -54,7 +55,8 @@ describe('scheduled main-agent dispatch', () => {
expect(scheduler.getManifest('scheduled')?.lastRun?.status).toBe('running');
expect(effect).not.toHaveBeenCalled();
Object.assign(agent, { running: true });
- await internal.processQueue();
+ internal.processQueue();
+ await agent.whenIdle();
expect(effect).toHaveBeenCalledOnce();
expect(scheduler.getManifest('scheduled')?.lastRun?.status).toBe(fail ? 'failed' : 'completed');
scheduler.stopAll();
diff --git a/src/core/supervisor.ts b/src/core/supervisor.ts
index d623ada4..ea014ed0 100644
--- a/src/core/supervisor.ts
+++ b/src/core/supervisor.ts
@@ -446,6 +446,32 @@ export class SubAgentSupervisor {
return halted;
}
+ /**
+ * Halt only the agents started from one chat (ADR-037: a /stop in one chat
+ * leaves the others' delegated work running). Delegated grandchildren carry
+ * the same source chat. Returns the ids that were signalled.
+ */
+ async haltForChannel(channelId: string): Promise<string[]> {
+ const fromChannel = (config: SubAgentConfig) => config.sourceChannelId === channelId;
+ const halted: string[] = [];
+ for (const [agentId, agent] of this.activeAgents.entries()) {
+ if (!fromChannel(agent.config)) continue;
+ agent.abort();
+ halted.push(agentId);
+ }
+ const remaining: SubAgentConfig[] = [];
+ for (const config of this.waitQueue) {
+ if (!fromChannel(config)) {
+ remaining.push(config);
+ continue;
+ }
+ this.taskBoard.update(config.id, { status: 'halted', completedAt: Date.now(), progress: 'Halted while queued' });
+ halted.push(config.id);
+ }
+ this.waitQueue = remaining;
+ return halted;
+ }
+
async pause(agentId: string): Promise<boolean> {
const agent = this.activeAgents.get(agentId);
if (!agent) return false;
diff --git a/src/core/testing/fake-turns.ts b/src/core/testing/fake-turns.ts
new file mode 100644
index 00000000..c19daf5d
--- /dev/null
+++ b/src/core/testing/fake-turns.ts
@@ -0,0 +1,70 @@
+/**
+ * Test helpers for agent internals built with `Object.create(Agent.prototype)`
+ * (no constructor): the per-turn fields (ADR-037) live in `activeTurns`, so a
+ * test marks a chat busy by registering a running turn instead of setting
+ * `processing` / `currentMessage`.
+ */
+import { AsyncLocalStorage } from 'node:async_hooks';
+import type { ChannelMessage } from '../../types/channel.js';
+import { Agent, laneKeyFor } from '../agent.js';
+import { Lifecycle } from '../lifecycle.js';
+
+/**
+ * The fields a constructor-less agent needs for queue and turn bookkeeping:
+ * an always-admitting governor and a capability stub with a plain cwd.
+ */
+export function bareTurnFields(opts: { limit?: number; cwd?: string } = {}): Record<string, unknown> {
+ const limit = opts.limit ?? 4;
+ let cwd = opts.cwd ?? process.cwd();
+ return {
+ messageQueue: [],
+ queuedWorkKeys: new Set(),
+ activeTurns: new Map(),
+ laneCwd: new Map(),
+ turnStore: new AsyncLocalStorage(),
+ turnSeq: 0,
+ idleWaiters: [],
+ lastAdmitRefusal: null,
+ governor: {
+ limit: () => limit,
+ canAdmit: (running: number) => (running === 0 || running < limit ? { ok: true } : { ok: false, reason: 'capacity' }),
+ noteIdle: () => {},
+ },
+ capabilities: {
+ claimTurnState: () => {},
+ getCwd: () => cwd,
+ getGlobalCwd: () => cwd,
+ setGlobalCwd: (dir: string) => { cwd = dir; },
+ permissions: { withTurn: <T>(fn: () => T) => fn() },
+ },
+ };
+}
+
+/** Mark `message`'s chat as running a turn (optionally doing `activity`). Returns the turn. */
+export function startFakeTurn(agent: Agent, message: ChannelMessage, activity = '', startedAt = Date.now()): { abort: AbortController; message: ChannelMessage } {
+ const turns = (agent as unknown as { activeTurns: Map<string, unknown> }).activeTurns;
+ const turn = {
+ id: `fake-${message.id}`,
+ laneKey: laneKeyFor(message),
+ message,
+ startedAt,
+ abort: new AbortController(),
+ abortReason: null,
+ activity,
+ completedStepCount: 0,
+ stepNarrative: [],
+ workKey: null,
+ lastProgressAt: startedAt,
+ lastTypingAt: 0,
+ injectedBeliefIds: [],
+ lifecycle: new Lifecycle('idle'),
+ programming: null,
+ done: false,
+ };
+ turns.set(turn.laneKey, turn);
+ return turn;
+}
+
+export function endFakeTurns(agent: Agent): void {
+ (agent as unknown as { activeTurns: Map<string, unknown> }).activeTurns.clear();
+}
diff --git a/src/core/turn-governor.test.ts b/src/core/turn-governor.test.ts
new file mode 100644
index 00000000..4c85ba21
--- /dev/null
+++ b/src/core/turn-governor.test.ts
@@ -0,0 +1,152 @@
+import { describe, expect, it, vi } from 'vitest';
+import { autoTurnLimit, resolveTurnLimit, TurnGovernor, TURN_HEAP_BUDGET_BYTES, type GovernedTurn } from './turn-governor.js';
+import { taskHeapAbortThreshold } from './memory-guard.js';
+
+const MB = 1024 * 1024;
+const GB = 1024 * MB;
+
+function turn(id: string, startedAt: number, stopping = false): GovernedTurn & { shed: ReturnType<typeof vi.fn> } {
+ return { id, startedAt, label: id, isStopping: () => stopping, shed: vi.fn() };
+}
+
+function governor(heap: { used: number }, opts: Partial<{ limit: number; available: number | null; now: () => number; onExit: (n: number) => void }> = {}) {
+ return new TurnGovernor({
+ limit: opts.limit ?? 4,
+ heapSizeLimit: 4 * GB,
+ heapUsed: () => heap.used,
+ systemAvailable: () => (opts.available === undefined ? null : opts.available),
+ totalMem: 16 * GB,
+ now: opts.now,
+ onExit: opts.onExit,
+ });
+}
+
+describe('turn limit', () => {
+ it('is capped at 2 on Termux and small machines, 3 under 8 GB, 4 otherwise', () => {
+ expect(autoTurnLimit({ heapSizeLimit: 4 * GB, totalMem: 16 * GB, termux: false })).toBe(4);
+ expect(autoTurnLimit({ heapSizeLimit: 4 * GB, totalMem: 6 * GB, termux: false })).toBe(3);
+ expect(autoTurnLimit({ heapSizeLimit: 4 * GB, totalMem: 3 * GB, termux: false })).toBe(2);
+ expect(autoTurnLimit({ heapSizeLimit: 4 * GB, totalMem: 16 * GB, termux: true })).toBe(2);
+ });
+
+ it('follows heap headroom and never drops below 1', () => {
+ expect(autoTurnLimit({ heapSizeLimit: 512 * MB + 2 * TURN_HEAP_BUDGET_BYTES, totalMem: 16 * GB, termux: false })).toBe(2);
+ expect(autoTurnLimit({ heapSizeLimit: 256 * MB, totalMem: 16 * GB, termux: false })).toBe(1);
+ });
+
+ it('a configured limit wins and is clamped to 1..16', () => {
+ const m = { heapSizeLimit: 4 * GB, totalMem: 16 * GB, termux: true };
+ expect(resolveTurnLimit(8, m)).toBe(8);
+ expect(resolveTurnLimit(99, m)).toBe(16);
+ expect(resolveTurnLimit(0, m)).toBe(2);
+ expect(resolveTurnLimit(undefined, m)).toBe(2);
+ expect(resolveTurnLimit(Number.NaN, m)).toBe(2);
+ });
+});
+
+describe('TurnGovernor admission', () => {
+ it('always admits the first turn, even under pressure', () => {
+ const heap = { used: 3.9 * GB };
+ expect(governor(heap).canAdmit(0)).toEqual({ ok: true });
+ });
+
+ it('stops at the limit', () => {
+ const heap = { used: 100 * MB };
+ const g = governor(heap, { limit: 2 });
+ expect(g.canAdmit(1)).toEqual({ ok: true });
+ expect(g.canAdmit(2)).toEqual({ ok: false, reason: 'capacity' });
+ });
+
+ it('refuses when the heap leaves no budget for another turn', () => {
+ const heap = { used: 100 * MB };
+ const g = governor(heap);
+ const line = g.stopLine(2);
+ heap.used = line - TURN_HEAP_BUDGET_BYTES + 1;
+ expect(g.canAdmit(1)).toEqual({ ok: false, reason: 'memory' });
+ heap.used = line - TURN_HEAP_BUDGET_BYTES - 1;
+ expect(g.canAdmit(1)).toEqual({ ok: true });
+ });
+
+ it('refuses when the system is nearly out of memory (where that is measurable)', () => {
+ const heap = { used: 100 * MB };
+ expect(governor(heap, { available: 50 * MB }).canAdmit(1)).toEqual({ ok: false, reason: 'system-memory' });
+ expect(governor(heap, { available: 4 * GB }).canAdmit(1)).toEqual({ ok: true });
+ expect(governor(heap, { available: null }).canAdmit(1)).toEqual({ ok: true });
+ });
+});
+
+describe('TurnGovernor lines', () => {
+ it('with one turn, the stop line is the old per-task guard line', () => {
+ const heap = { used: 100 * MB };
+ const g = governor(heap);
+ expect(g.stopLine(1)).toBe(taskHeapAbortThreshold(4 * GB, 100 * MB));
+ expect(g.exitLine(1)).toBe(g.stopLine(1) + 256 * MB);
+ });
+
+ it('widens by one turn budget per extra turn, capped by the abort line', () => {
+ const heap = { used: 100 * MB };
+ const g = governor(heap);
+ expect(g.stopLine(3) - g.stopLine(1)).toBe(2 * TURN_HEAP_BUDGET_BYTES);
+ expect(g.stopLine(1000)).toBe(g.getThresholds().abortBytes);
+ });
+});
+
+describe('TurnGovernor pressure', () => {
+ it('sheds the newest turn that is not already stopping, once per cooldown', () => {
+ let now = 1_000_000;
+ const heap = { used: 100 * MB };
+ const g = governor(heap, { now: () => now });
+ const old = turn('old', 1);
+ const mid = turn('mid', 2);
+ const stopping = turn('new', 3, true);
+ heap.used = g.stopLine(3) + MB;
+ expect(g.check([old, mid, stopping])).toEqual({ verdict: 'shed', shed: 'mid' });
+ expect(mid.shed).toHaveBeenCalledOnce();
+ expect(old.shed).not.toHaveBeenCalled();
+ // Cooldown: nothing more for 5 s.
+ expect(g.check([old, mid, stopping]).shed).toBeUndefined();
+ now += 5_001;
+ expect(g.check([old, turn('mid2', 2, true), stopping]).shed).toBe('old');
+ });
+
+ it('does nothing below the line', () => {
+ const heap = { used: 100 * MB };
+ const g = governor(heap);
+ const t = turn('a', 1);
+ expect(g.check([t])).toEqual({ verdict: 'ok' });
+ expect(t.shed).not.toHaveBeenCalled();
+ });
+
+ it('calls onExit once past the exit line', () => {
+ const onExit = vi.fn();
+ const heap = { used: 100 * MB };
+ const g = governor(heap, { onExit });
+ heap.used = g.exitLine(1) + MB;
+ g.check([turn('a', 1)]);
+ g.check([turn('a', 1)]);
+ expect(onExit).toHaveBeenCalledOnce();
+ });
+
+ it('shouldShed is true only past the line and only for the pick', () => {
+ const heap = { used: 100 * MB };
+ const g = governor(heap);
+ const a = turn('a', 1);
+ const b = turn('b', 2);
+ expect(g.shouldShed('b', [a, b])).toBe(false);
+ heap.used = g.stopLine(2) + MB;
+ expect(g.shouldShed('b', [a, b])).toBe(true);
+ expect(g.shouldShed('a', [a, b])).toBe(false);
+ });
+
+ it('noteIdle lowers the baseline freely but raises it only a little', () => {
+ const heap = { used: 300 * MB };
+ const g = governor(heap);
+ const before = g.stopLine(1);
+ heap.used = 900 * MB;
+ g.noteIdle();
+ expect(g.stopLine(1) - before).toBeLessThanOrEqual(64 * MB);
+ heap.used = 50 * MB;
+ g.noteIdle();
+ expect(g.stopLine(1)).toBe(taskHeapAbortThreshold(4 * GB, 50 * MB));
+ });
+});
diff --git a/src/core/turn-governor.ts b/src/core/turn-governor.ts
new file mode 100644
index 00000000..73c90cdd
--- /dev/null
+++ b/src/core/turn-governor.ts
@@ -0,0 +1,268 @@
+/**
+ * Turn governor (ADR-037): the one place that decides how many chat turns
+ * run at once, and what gives way when memory gets tight.
+ *
+ * Chat turns are network-bound (they wait on a provider most of the time),
+ * so they share one process and one event loop; threads would multiply heap
+ * cost without making a turn faster. The cost of concurrency is the shared
+ * V8 heap. So this governor:
+ *
+ * - sets a ceiling from the heap limit, the machine's RAM and the platform
+ * (Termux and small machines get 2), overridable in config;
+ * - draws a stop line that is exactly the old single-task guard's line
+ * with one turn running, and one turn's heap budget higher for every
+ * further turn (never past the step governor's abort line);
+ * - admits a new turn only while the heap leaves that turn its budget
+ * below the line it would raise the stop line to (and, on Linux/Android,
+ * the system still has memory available) — but always admits one when
+ * nothing runs, so work never deadlocks;
+ * - watches the heap once per second for the whole process (replacing a
+ * guard that every turn used to run for itself) and, past the stop
+ * line, stops the NEWEST turn — one at a time, with a cooldown — so
+ * long-running work survives and the rest relieve the pressure;
+ * - past the exit line (256 MB above the stop line, which stopping turns
+ * could not prevent), hands control to `onExit` so the process stops
+ * while state can still be persisted.
+ */
+import { freemem, totalmem } from 'node:os';
+import { getHeapStatistics } from 'node:v8';
+import { memoryGovernorThresholds, type MemoryGovernorThresholds } from './memory-governor.js';
+import { taskHeapAbortThreshold } from './memory-guard.js';
+import { isTermux } from '../utils/platform.js';
+import { logger } from '../utils/logger.js';
+
+const MB = 1024 * 1024;
+const GB = 1024 * MB;
+
+/** Heap a concurrent turn is budgeted (history, stream buffers, tool output). */
+export const TURN_HEAP_BUDGET_BYTES = 192 * MB;
+/** Default ceiling for the automatic limit; config may go higher. */
+export const DEFAULT_MAX_TURNS = 4;
+/** Hard ceiling for a configured limit. */
+export const MAX_CONFIGURABLE_TURNS = 16;
+/** Between two pressure stops: give the first one time to free its memory. */
+const SHED_COOLDOWN_MS = 5_000;
+const WATCH_INTERVAL_MS = 1_000;
+
+export interface MachineFacts {
+ heapSizeLimit: number;
+ totalMem: number;
+ termux: boolean;
+}
+
+export function machineFacts(): MachineFacts {
+ return { heapSizeLimit: getHeapStatistics().heap_size_limit, totalMem: totalmem(), termux: isTermux() };
+}
+
+/**
+ * Automatic concurrent-turn limit. Heap headroom (limit minus a 512 MB
+ * reserve the process needs to persist and respond) divided by a per-turn
+ * budget, then capped by RAM and platform. Always at least 1.
+ */
+export function autoTurnLimit(m: MachineFacts): number {
+ const headroom = Math.max(0, m.heapSizeLimit - 512 * MB);
+ let limit = Math.floor(headroom / TURN_HEAP_BUDGET_BYTES);
+ limit = Math.min(limit, DEFAULT_MAX_TURNS);
+ if (m.termux || m.totalMem < 4 * GB) limit = Math.min(limit, 2);
+ else if (m.totalMem < 8 * GB) limit = Math.min(limit, 3);
+ return Math.max(1, limit);
+}
+
+/** Configured limit (> 0) wins, clamped; otherwise automatic. */
+export function resolveTurnLimit(configured: number | undefined, m: MachineFacts): number {
+ if (typeof configured === 'number' && Number.isFinite(configured) && configured > 0) {
+ return Math.min(MAX_CONFIGURABLE_TURNS, Math.max(1, Math.floor(configured)));
+ }
+ return autoTurnLimit(m);
+}
+
+/** A running turn as the governor sees it. */
+export interface GovernedTurn {
+ readonly id: string;
+ readonly startedAt: number;
+ readonly label: string;
+ /** True once the turn is stopping (by anyone); it is never picked twice. */
+ isStopping(): boolean;
+ /** Stop this turn because memory is tight. */
+ shed(error: Error): void;
+}
+
+export type GovernorVerdict = 'ok' | 'shed' | 'exit';
+
+export type AdmitDecision = { ok: true } | { ok: false; reason: 'capacity' | 'memory' | 'system-memory' };
+
+export interface TurnGovernorDeps {
+ limit: number;
+ heapSizeLimit?: number;
+ /** Current heap use (default: process.memoryUsage().heapUsed). */
+ heapUsed?: () => number;
+ /** Bytes the OS still has available, or null where that number isn't trustworthy. */
+ systemAvailable?: () => number | null;
+ totalMem?: number;
+ now?: () => number;
+ /** Heap use beyond the exit line: persist what you can and stop the process. */
+ onExit?: (heapUsed: number) => void;
+}
+
+/**
+ * macOS and Windows report "free" memory without the reclaimable cache, so
+ * a busy desktop looks out of memory all the time. Only Linux/Android
+ * (MemAvailable) is trusted for admission.
+ */
+function defaultSystemAvailable(): number | null {
+ if (process.platform !== 'linux' && process.platform !== 'android') return null;
+ return freemem();
+}
+
+export class TurnGovernor {
+ private limitValue: number;
+ private readonly heapLimit: number;
+ private readonly heapUsed: () => number;
+ private readonly systemAvailable: () => number | null;
+ private readonly totalMem: number;
+ private readonly now: () => number;
+ private readonly onExit?: (heapUsed: number) => void;
+ private baseline: number;
+ private thresholds: MemoryGovernorThresholds;
+ private lastShedAt = 0;
+ private timer: ReturnType<typeof setInterval> | null = null;
+ private exiting = false;
+
+ constructor(deps: TurnGovernorDeps) {
+ this.limitValue = Math.max(1, deps.limit);
+ this.heapLimit = deps.heapSizeLimit ?? getHeapStatistics().heap_size_limit;
+ this.heapUsed = deps.heapUsed ?? (() => process.memoryUsage().heapUsed);
+ this.systemAvailable = deps.systemAvailable ?? defaultSystemAvailable;
+ this.totalMem = deps.totalMem ?? totalmem();
+ this.now = deps.now ?? Date.now;
+ this.onExit = deps.onExit;
+ this.baseline = this.heapUsed();
+ this.thresholds = memoryGovernorThresholds({ heapSizeLimit: this.heapLimit, baselineHeapUsed: this.baseline });
+ }
+
+ limit(): number {
+ return this.limitValue;
+ }
+
+ setLimit(limit: number): void {
+ this.limitValue = Math.max(1, Math.floor(limit));
+ }
+
+ getThresholds(): MemoryGovernorThresholds {
+ return this.thresholds;
+ }
+
+ /**
+ * The heap the process sits at with no turn running. Re-measured whenever
+ * the last turn ends, so the lines follow the process (plugins loaded,
+ * caches warmed) instead of a boot-time number.
+ */
+ noteIdle(): void {
+ const used = this.heapUsed();
+ // Only move the baseline down freely; up only modestly, so a leak never
+ // drags the abort line up with it.
+ const next = used < this.baseline ? used : Math.min(used, this.baseline + 64 * MB);
+ if (next !== this.baseline) {
+ this.baseline = next;
+ this.thresholds = memoryGovernorThresholds({ heapSizeLimit: this.heapLimit, baselineHeapUsed: this.baseline });
+ }
+ }
+
+ /**
+ * Heap at which a turn is stopped with `running` turns going: the old
+ * per-task guard's line for one, plus one turn budget per extra turn,
+ * capped at the step governor's abort line.
+ */
+ stopLine(running: number): number {
+ const single = taskHeapAbortThreshold(this.heapLimit, this.baseline);
+ const widened = single + Math.max(0, running - 1) * TURN_HEAP_BUDGET_BYTES;
+ return Math.max(single, Math.min(widened, this.thresholds.abortBytes));
+ }
+
+ /** Beyond this the process exits: 256 MB past the stop line, never past the heap limit's safety margin. */
+ exitLine(running: number): number {
+ return Math.min(this.stopLine(running) + 256 * MB, Math.max(this.thresholds.exitBytes, this.stopLine(running) + 64 * MB));
+ }
+
+ verdict(running: number): GovernorVerdict {
+ const used = this.heapUsed();
+ if (used >= this.exitLine(running)) return 'exit';
+ if (used >= this.stopLine(running)) return 'shed';
+ return 'ok';
+ }
+
+ /** May one more turn start, with `running` turns already going? */
+ canAdmit(running: number): AdmitDecision {
+ if (running <= 0) return { ok: true };
+ if (running >= this.limitValue) return { ok: false, reason: 'capacity' };
+ if (this.heapUsed() + TURN_HEAP_BUDGET_BYTES >= this.stopLine(running + 1)) return { ok: false, reason: 'memory' };
+ const available = this.systemAvailable();
+ if (available !== null && available < Math.max(128 * MB, this.totalMem * 0.04)) {
+ return { ok: false, reason: 'system-memory' };
+ }
+ return { ok: true };
+ }
+
+ /**
+ * One pressure check. Past the abort line the newest running turn that
+ * isn't already stopping is shed (at most one per cooldown); past the exit
+ * line `onExit` runs once. Returns what it did, for tests and logs.
+ */
+ check(turns: GovernedTurn[]): { verdict: GovernorVerdict; shed?: string } {
+ const used = this.heapUsed();
+ const verdict = this.verdict(turns.length);
+ if (verdict === 'exit') {
+ if (!this.exiting) {
+ this.exiting = true;
+ logger.error({ heapMB: Math.round(used / MB), turns: turns.length }, 'Turn governor: heap past the exit line');
+ this.onExit?.(used);
+ }
+ return { verdict };
+ }
+ if (verdict !== 'shed') return { verdict };
+ const now = this.now();
+ if (now - this.lastShedAt < SHED_COOLDOWN_MS) return { verdict };
+ const victim = pickVictim(turns);
+ if (!victim) return { verdict };
+ this.lastShedAt = now;
+ const heapMB = Math.round(used / MB);
+ logger.warn({ heapMB, victim: victim.id, label: victim.label, running: turns.length }, 'Turn governor: memory pressure — stopping the newest turn');
+ victim.shed(new Error(`Task stopped at ${heapMB}MB heap usage so the other running work could continue`));
+ return { verdict, shed: victim.id };
+ }
+
+ /**
+ * Should this turn give way now? Used at step boundaries (deterministic,
+ * unlike the timer, which can't fire while the event loop is flooded):
+ * true only past the stop line, and only for the turn the timer would pick.
+ */
+ shouldShed(turnId: string, turns: GovernedTurn[]): boolean {
+ if (this.heapUsed() < this.stopLine(turns.length)) return false;
+ return pickVictim(turns)?.id === turnId;
+ }
+
+ start(getTurns: () => GovernedTurn[]): void {
+ if (this.timer) return;
+ this.timer = setInterval(() => {
+ const turns = getTurns();
+ if (turns.length === 0) return;
+ try { this.check(turns); } catch (err) { logger.warn({ err }, 'Turn governor check failed'); }
+ }, WATCH_INTERVAL_MS);
+ this.timer.unref?.();
+ }
+
+ stop(): void {
+ if (this.timer) clearInterval(this.timer);
+ this.timer = null;
+ }
+}
+
+/** Newest first: the turn with the least sunk work gives way. */
+function pickVictim(turns: GovernedTurn[]): GovernedTurn | undefined {
+ let victim: GovernedTurn | undefined;
+ for (const t of turns) {
+ if (t.isStopping()) continue;
+ if (!victim || t.startedAt > victim.startedAt) victim = t;
+ }
+ return victim;
+}
diff --git a/src/core/voice-queue.test.ts b/src/core/voice-queue.test.ts
index 9d7af863..632d36ff 100644
--- a/src/core/voice-queue.test.ts
+++ b/src/core/voice-queue.test.ts
@@ -5,6 +5,7 @@ import { afterEach, describe, expect, it } from 'vitest';
import type { ChannelMessage } from '../types/channel.js';
import { Agent } from './agent.js';
import { WorkLedger } from './work-ledger.js';
+import { bareTurnFields, startFakeTurn, endFakeTurns } from './testing/fake-turns.js';
/**
* Questions asked on a call: someone is waiting on the line, so they go
@@ -24,7 +25,7 @@ function bareAgent() {
dirs.push(dir);
const workLedger = new WorkLedger({ filePath: join(dir, 'work-ledger.json') });
const agent = Object.create(Agent.prototype) as Agent;
- Object.assign(agent, { messageQueue: [], queuedWorkKeys: new Set(), workLedger, processing: false, currentMessage: null, currentActivity: '', currentAbort: null });
+ Object.assign(agent, { ...bareTurnFields(), workLedger });
const enqueue = (m: ChannelMessage) => { const key = workLedger.accept(m).entry.key; agent.queueMessage(m, key); return key; };
const order = () => (agent as unknown as { messageQueue: Array<{ message: ChannelMessage }> }).messageQueue.map((i) => i.message.id);
return { agent, workLedger, enqueue, order };
@@ -45,9 +46,10 @@ describe('voice questions in the work queue', () => {
it('say what Mercury is busy with when it is something else', () => {
const { agent, enqueue } = bareAgent();
enqueue(msg('voice1', 'desktop:call:x', true));
- Object.assign(agent, { processing: true, currentMessage: msg('long', 'web:a'), currentActivity: '📄 Reading report.md' });
+ startFakeTurn(agent, msg('long', 'web:a'), '📄 Reading report.md');
expect(agent.workStateFor('desktop:call:x')).toEqual({ state: 'queued', busyWith: 'Reading report.md' });
- Object.assign(agent, { currentMessage: msg('voice1', 'desktop:call:x', true) });
+ endFakeTurns(agent);
+ startFakeTurn(agent, msg('voice1', 'desktop:call:x', true));
expect(agent.workStateFor('desktop:call:x').state).toBe('running');
});
@@ -66,3 +68,15 @@ describe('voice questions in the work queue', () => {
expect(order()).toEqual(['voice1', 'chat1']);
});
});
+
+describe('stopping one call (ADR-037)', () => {
+ it('stops only the running turn of that call; another chat keeps running', () => {
+ const { agent, enqueue } = bareAgent();
+ enqueue(msg('chat2', 'web:b'));
+ const call = startFakeTurn(agent, msg('voice1', 'desktop:call:x', true));
+ const chat = startFakeTurn(agent, msg('chat1', 'web:a'));
+ expect(agent.stopWorkFor('desktop:call:x')).toBe(true);
+ expect(call.abort.signal.aborted).toBe(true);
+ expect(chat.abort.signal.aborted).toBe(false);
+ });
+});
diff --git a/src/eval/runner.ts b/src/eval/runner.ts
index e5305b92..5135cbbc 100644
--- a/src/eval/runner.ts
+++ b/src/eval/runner.ts
@@ -409,10 +409,11 @@ export class EvalHarness {
while (settled < 25) {
await tick();
if (this.fake) vi.advanceTimersByTime(0); // zero-delay timers only (setTimeout(fn, 0))
- settled = this.agent.lifecycle.is('idle') ? settled + 1 : 0;
+ // Turns run concurrently with their own lifecycles (ADR-037): idle = none running, none waiting.
+ settled = this.agent.isIdle() ? settled + 1 : 0;
if (clock() > deadline) {
const tail = this.channel.since(eventStart).map((e) => `${e.kind}: ${e.text.slice(0, 120)}`).join('\n');
- throw new Error(`Turn did not finish within ${timeoutMs}ms (state ${this.agent.lifecycle.getState()}).\n${tail}`);
+ throw new Error(`Turn did not finish within ${timeoutMs}ms (${this.agent.activeTurnCount} running).\n${tail}`);
}
}
}
diff --git a/src/eval/scenarios/concurrency.test.ts b/src/eval/scenarios/concurrency.test.ts
new file mode 100644
index 00000000..24626fc2
--- /dev/null
+++ b/src/eval/scenarios/concurrency.test.ts
@@ -0,0 +1,148 @@
+import { afterAll, describe, expect, it } from 'vitest';
+import { MockLanguageModelV3 } from 'ai/test';
+import type { LanguageModelV3CallOptions, LanguageModelV3StreamPart } from '@ai-sdk/provider';
+import type { ChannelMessage } from '../../types/channel.js';
+import { EvalHarness } from '../runner.js';
+
+/**
+ * ADR-037 end to end: the real Agent (real handleMessage, sessions,
+ * permissions, capability registry) with a model that holds each call until
+ * the test lets it answer. Two chats run at once and each turn — deep inside
+ * the AI SDK's call into the model — sees only its own message, permission
+ * identity and session; one chat's messages still run one after another.
+ */
+
+interface Call { text: string; currentMessageId?: string; permissionChannel: string; release: () => void }
+
+const tick = (ms = 5) => new Promise<void>((r) => setTimeout(r, ms));
+
+function lastUserText(options: LanguageModelV3CallOptions): string {
+ for (let i = options.prompt.length - 1; i >= 0; i--) {
+ const m = options.prompt[i];
+ if (m.role !== 'user') continue;
+ const part = m.content.find((p) => p.type === 'text');
+ if (part && part.type === 'text') return part.text;
+ }
+ return '';
+}
+
+async function gatedHarness(name: string) {
+ const harness = await EvalHarness.create({ name, turns: [], channel: { type: 'telegram', style: 'plain' } }, { fakeTimers: false });
+ const calls: Call[] = [];
+ const model = new MockLanguageModelV3({
+ provider: 'eval.gated',
+ modelId: 'gated-model',
+ doStream: async (options) => {
+ const text = lastUserText(options);
+ let release!: () => void;
+ const gate = new Promise<void>((r) => { release = r; });
+ calls.push({
+ text,
+ currentMessageId: harness.agent.currentMessage?.id,
+ permissionChannel: harness.capabilities.permissions.currentContext().channelId,
+ release,
+ });
+ // Like a real provider request, an abort ends the call at once.
+ await new Promise<void>((resolve, reject) => {
+ const signal = options.abortSignal;
+ if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));
+ signal?.addEventListener('abort', () => reject(signal.reason ?? new Error('Aborted')), { once: true });
+ void gate.then(resolve);
+ });
+ const parts: LanguageModelV3StreamPart[] = [
+ { type: 'stream-start', warnings: [] },
+ { type: 'text-start', id: 't0' },
+ { type: 'text-delta', id: 't0', delta: `reply to ${text}` },
+ { type: 'text-end', id: 't0' },
+ { type: 'finish', usage: { inputTokens: { total: 10, noCache: 10, cacheRead: 0, cacheWrite: 0 }, outputTokens: { total: 5, text: 5, reasoning: 0 } }, finishReason: { unified: 'stop', raw: 'stop' } },
+ ];
+ return { stream: new ReadableStream<LanguageModelV3StreamPart>({ start(c) { for (const p of parts) c.enqueue(p); c.close(); } }) };
+ },
+ });
+ for (const p of harness.providers) (p as unknown as { getModelInstance: () => unknown }).getModelInstance = () => model;
+ const send = (id: string, chat: string, text: string) => {
+ const message: ChannelMessage = { id, channelId: chat, channelType: 'telegram', senderId: 'eval-user', content: text, timestamp: Date.now() };
+ harness.channel.inject(message);
+ };
+ const waitForCalls = async (n: number) => {
+ for (let i = 0; i < 400 && calls.length < n; i++) await tick();
+ return calls.length;
+ };
+ const delivered = (chat: string) => harness.channel.events.filter((e) => e.kind === 'delivered' && e.targetId === chat).map((e) => e.text);
+ return { harness, calls, send, waitForCalls, delivered };
+}
+
+describe('eval · chats run at the same time (ADR-037)', () => {
+ afterAll(async () => {
+ const { removeEvalRoot } = await import('../env.js');
+ removeEvalRoot();
+ });
+
+ it('two chats are answered at once, each with its own identity and session', async () => {
+ const { harness, calls, send, waitForCalls, delivered } = await gatedHarness('concurrency-two-chats');
+ try {
+ send('m-a', 'chat-a', 'hello alpha');
+ send('m-b', 'chat-b', 'hello bravo');
+ // Both model calls are in flight before either answers.
+ expect(await waitForCalls(2)).toBe(2);
+ expect(harness.agent.activeTurnCount).toBe(2);
+ const a = calls.find((c) => c.text === 'hello alpha')!;
+ const b = calls.find((c) => c.text === 'hello bravo')!;
+ expect(a).toMatchObject({ currentMessageId: 'm-a', permissionChannel: 'chat-a' });
+ expect(b).toMatchObject({ currentMessageId: 'm-b', permissionChannel: 'chat-b' });
+ // The second chat finishes first; the first is unaffected.
+ b.release();
+ for (let i = 0; i < 400 && delivered('chat-b').length === 0; i++) await tick();
+ expect(delivered('chat-b').join('\n')).toContain('reply to hello bravo');
+ expect(delivered('chat-a')).toEqual([]);
+ a.release();
+ await harness.agent.whenIdle();
+ expect(delivered('chat-a').join('\n')).toContain('reply to hello alpha');
+ expect(delivered('chat-a').join('\n')).not.toContain('bravo');
+ // Each chat's stored conversation holds only its own exchange.
+ const historyOf = (chat: string) => (harness.sessions.getByBinding('telegram', chat)?.messages ?? []).filter((m) => m.kind === 'message').map((m) => `${m.role}:${m.content}`);
+ expect(historyOf('chat-a')).toEqual(['user:hello alpha', 'assistant:reply to hello alpha']);
+ expect(historyOf('chat-b')).toEqual(['user:hello bravo', 'assistant:reply to hello bravo']);
+ } finally {
+ await harness.dispose();
+ }
+ });
+
+ it("one chat's second message waits for its first", async () => {
+ const { harness, calls, send, waitForCalls } = await gatedHarness('concurrency-same-chat');
+ try {
+ send('m-1', 'chat-a', 'first question');
+ send('m-2', 'chat-a', 'second question');
+ expect(await waitForCalls(1)).toBe(1);
+ await tick(30);
+ expect(calls.map((c) => c.text)).toEqual(['first question']);
+ calls[0].release();
+ expect(await waitForCalls(2)).toBe(2);
+ expect(calls[1]).toMatchObject({ text: 'second question', currentMessageId: 'm-2' });
+ calls[1].release();
+ await harness.agent.whenIdle();
+ } finally {
+ await harness.dispose();
+ }
+ });
+
+ it('/stop in one chat ends that chat only', async () => {
+ const { harness, calls, send, waitForCalls, delivered } = await gatedHarness('concurrency-stop-one');
+ try {
+ send('m-a', 'chat-a', 'long task alpha');
+ send('m-b', 'chat-b', 'long task bravo');
+ expect(await waitForCalls(2)).toBe(2);
+ send('m-stop', 'chat-a', '/stop');
+ for (let i = 0; i < 400 && harness.agent.activeTurnCount > 1; i++) await tick();
+ expect(harness.agent.activeTurnCount).toBe(1);
+ expect(harness.agent.turnForChannel('chat-b')).toBeDefined();
+ expect(delivered('chat-a').join('\n')).toMatch(/Stopped this chat's task/);
+ calls.find((c) => c.text === 'long task bravo')!.release();
+ calls.find((c) => c.text === 'long task alpha')!.release();
+ await harness.agent.whenIdle();
+ expect(delivered('chat-b').join('\n')).toContain('reply to long task bravo');
+ } finally {
+ await harness.dispose();
+ }
+ });
+});
diff --git a/src/index.ts b/src/index.ts
index 61b6bd3e..92219d80 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -2899,8 +2899,9 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
})) ?? [],
});
bootCli.startStatusPoller(2000);
- // Esc during a turn: the same stop routine `/stop` runs.
- bootCli.setInterruptHandler(() => agent.stopAllWork('stopped'));
+ // Esc during a turn: the same stop routine `/stop` runs — for the
+ // terminal's own task; with none, whatever the terminal is showing.
+ bootCli.setInterruptHandler(() => agent.stopAllWork('stopped', agent.turnForChannel('cli') ? { channelId: 'cli' } : undefined));
bootCli.mountTUI((inputText: string) => {
bootCli.sendUserMessage(inputText);
}, spotifyClient, () => {
@@ -3351,9 +3352,9 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
cloudClient!.sendStream({ conversationId, requestId, event: 'error', data: { message: 'Stop requires the session the task belongs to.' } });
return;
}
- // Same semantics as the local /stop fast-path command: abort the
- // foreground task, cancel its work-ledger entry, halt sub-agents.
- const note = await agent.stopAllWork('stopped');
+ // Same semantics as the local /stop fast-path command: abort this
+ // session's task, cancel its work-ledger entry, halt its sub-agents.
+ const note = await agent.stopAllWork('stopped', { sessionId: suppliedSessionId });
cloudClient!.sendStream({
conversationId,
sessionId: suppliedSessionId,
@@ -3561,7 +3562,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
// Settings-free skill builder: the default model writes a skill from the owner's description.
setSkillBuilder({ provider: () => providers.getDefault(), tools: () => Object.keys(capabilities.getTools()).sort() });
setCloudReload(() => agent.reloadProviders());
- setWebStop(() => agent.stopAllWork('stopped'));
+ setWebStop((target) => agent.stopAllWork('stopped', target));
setWebSessionBusy((sessionId) => agent.isBusyWith(sessionId));
setWebQueueControls({ state: (id) => agent.queueStateFor(id), prioritize: (id) => agent.prioritize(id) });
setWebResearchControls({
diff --git a/src/ui/attach-launch-pad.test.tsx b/src/ui/attach-launch-pad.test.tsx
index 4a3e9508..bbc1d24b 100644
--- a/src/ui/attach-launch-pad.test.tsx
+++ b/src/ui/attach-launch-pad.test.tsx
@@ -42,7 +42,7 @@ describe('attach TUI opens with the launch pad', () => {
it('a slash command typed while /stop is unwinding waits for idle instead of "busy"', () => {
const agent = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'core', 'agent.ts'), 'utf8').replace(/\r\n/g, '\n');
- expect(agent).toContain("this.processing && trimmed.startsWith('/') && this.currentAbortReason && !msg.metadata?.waitedForStop");
- expect(agent).toContain('private waitUntilIdle(maxMs: number): Promise<void>');
+ expect(agent).toContain("laneTurn && trimmed.startsWith('/') && laneTurn.abortReason && !msg.metadata?.waitedForStop");
+ expect(agent).toContain('private waitUntilLaneIdle(laneKey: string, maxMs: number): Promise<void>');
});
});
diff --git a/src/utils/config.ts b/src/utils/config.ts
index 75a00766..7a8739f6 100644
--- a/src/utils/config.ts
+++ b/src/utils/config.ts
@@ -311,6 +311,13 @@ export interface MercuryConfig {
mcp?: McpConfig;
/** Opt-in: discover plugin and MCP schemas on demand in the main agent's tool loop. */
toolDiscovery?: { enabled?: boolean };
+ /**
+ * Chat turns running at once (ADR-037). One turn per chat at a time; this
+ * caps how many chats are worked on together. 0 = automatic (from heap
+ * size, RAM and platform; 2 on Termux). The turn governor admits fewer
+ * while memory is tight.
+ */
+ concurrency?: { maxTurns?: number };
/** Where the files Mercury makes go (default ~/mercury-artifacts): Research/ and one folder per chat. */
artifacts?: {
outputDir?: string;
@@ -631,6 +638,7 @@ export function getDefaultConfig(): MercuryConfig {
product: '',
},
toolDiscovery: { enabled: getEnvBool('MERCURY_TOOL_DISCOVERY', false) },
+ concurrency: { maxTurns: getEnvNum('MERCURY_MAX_CONCURRENT_TURNS', 0) },
web: {
enabled: getEnvBool('MERCURY_WEB_ENABLED', false),
port: getEnvNum('MERCURY_PORT', 6174),
diff --git a/src/utils/manual.ts b/src/utils/manual.ts
index 66263e82..6d176509 100644
--- a/src/utils/manual.ts
+++ b/src/utils/manual.ts
@@ -154,7 +154,7 @@ export const CHAT_COMMAND_HELP: ReadonlyArray<readonly [string, string]> = [
['/ws commit <message>', 'Commit staged changes (Mercury co-authored)'],
['/ws undo <file>', 'Revert file changes with git checkout -- <file>'],
['/halt', 'Emergency: stop all agents + clear queue'],
- ['/stop', 'Stop all agents + clear queue + release locks + clear task board'],
+ ['/stop', "Stop this chat's task + the agents it started (a full stop when nothing else runs)"],
['/reset', 'Full reset: stop all + clear context (requires confirmation)'],
['/spotify', 'Show Spotify connection status'],
['/spotify auth', 'Connect Spotify (browser or manual code flow)'],
@@ -398,8 +398,8 @@ export function getTelegramHelp(): string {
lines.push('/models — List providers or switch AI model (saved across restarts)');
lines.push('/cloud models — List Mercury Cloud models and switch');
lines.push('/stream — Toggle text streaming on/off');
- lines.push('/stop — Stop the current task and its agents now');
- lines.push('/halt — Emergency: stop all agents and clear the queue');
+ lines.push("/stop — Stop this chat's task and its agents now (other chats keep going)");
+ lines.push("/halt — Emergency: stop every chat's task and all agents");
lines.push('');
lines.push('**Tasks**');
@@ -458,8 +458,8 @@ export function getTelegramHelp(): string {
lines.push('/agents stop <id|all> — Stop a sub-agent');
lines.push('/agents pause <id> — Pause a sub-agent');
lines.push('/agents resume <id> — Resume a sub-agent');
- lines.push('/halt — Emergency: stop all agents + clear queue');
- lines.push('/stop — Stop all + release locks + clear task board');
+ lines.push("/halt — Emergency: stop every chat's task + all agents");
+ lines.push("/stop — Stop this chat's task + its agents (full stop + release locks when nothing else runs)");
lines.push('/reset — Full reset (stop all + clear context)');
lines.push('');
diff --git a/src/utils/turn-scope.test.ts b/src/utils/turn-scope.test.ts
new file mode 100644
index 00000000..c7be41ab
--- /dev/null
+++ b/src/utils/turn-scope.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+import { ScopedValue, inTurnScope, runInTurnScope } from './turn-scope.js';
+
+const tick = () => new Promise<void>((r) => setTimeout(r, 1));
+
+describe('ScopedValue', () => {
+ it('reads and writes the process-wide value outside a turn', () => {
+ const v = new ScopedValue('a');
+ expect(inTurnScope()).toBe(false);
+ v.set('b');
+ expect(v.get()).toBe('b');
+ expect(v.claim()).toBe(false);
+ });
+
+ it('an unclaimed value inside a turn is still the process-wide one', async () => {
+ const v = new ScopedValue('a');
+ await runInTurnScope(async () => {
+ v.set('b');
+ });
+ expect(v.get()).toBe('b');
+ });
+
+ it('a claimed value is private to its turn, across awaits and timers', async () => {
+ const v = new ScopedValue('/home');
+ const seen: string[] = [];
+ const turn = (dir: string, delay: number) => runInTurnScope(async () => {
+ v.claim();
+ v.set(dir);
+ await new Promise<void>((r) => setTimeout(r, delay));
+ await tick();
+ seen.push(`${dir}:${v.get()}`);
+ });
+ await Promise.all([turn('/one', 5), turn('/two', 1)]);
+ expect(seen.sort()).toEqual(['/one:/one', '/two:/two']);
+ expect(v.get()).toBe('/home');
+ });
+
+ it('claim starts from the process-wide value unless given one', async () => {
+ const v = new ScopedValue(1);
+ await runInTurnScope(async () => {
+ v.claim();
+ expect(v.get()).toBe(1);
+ v.claim(7);
+ expect(v.get()).toBe(7);
+ expect(v.getGlobal()).toBe(1);
+ });
+ });
+
+ it('two values never share a turn copy', async () => {
+ const a = new ScopedValue('a');
+ const b = new ScopedValue('b');
+ await runInTurnScope(async () => {
+ a.claim('A');
+ expect(b.isClaimed()).toBe(false);
+ b.set('B');
+ });
+ expect(a.get()).toBe('a');
+ expect(b.get()).toBe('B');
+ });
+});
diff --git a/src/utils/turn-scope.ts b/src/utils/turn-scope.ts
new file mode 100644
index 00000000..caad0b25
--- /dev/null
+++ b/src/utils/turn-scope.ts
@@ -0,0 +1,78 @@
+/**
+ * Turn scope (ADR-037): per-turn values for state that used to be one
+ * process-wide field, so several chat turns can run at once without
+ * overwriting each other's working directory, tool switches and so on.
+ *
+ * A turn runs inside `runInTurnScope`. Everything it awaits or schedules
+ * (stream callbacks, tool executions, timers) carries the same scope through
+ * AsyncLocalStorage. A `ScopedValue` that the turn has claimed reads and
+ * writes that turn's own copy; anywhere else (no turn, or a value the turn
+ * never claimed) it reads and writes the process-wide value, which keeps
+ * single-turn behavior unchanged.
+ *
+ * Every ScopedValue is its own key, so two registries (the main agent's and
+ * a bot's) never see each other's per-turn values even when one runs inside
+ * the other's async tree.
+ */
+import { AsyncLocalStorage } from 'node:async_hooks';
+
+type Cells = Map<object, { value: unknown }>;
+
+const scopeStore = new AsyncLocalStorage<Cells>();
+
+/** Run `fn` (and everything it awaits or schedules) in a fresh turn scope. */
+export function runInTurnScope<T>(fn: () => T): T {
+ return scopeStore.run(new Map(), fn);
+}
+
+/** Is the calling code inside a turn scope? */
+export function inTurnScope(): boolean {
+ return scopeStore.getStore() !== undefined;
+}
+
+export class ScopedValue<T> {
+ private global: T;
+
+ constructor(initial: T) {
+ this.global = initial;
+ }
+
+ /** The calling turn's value when it claimed this one, else the process-wide value. */
+ get(): T {
+ const cell = scopeStore.getStore()?.get(this);
+ return cell ? (cell.value as T) : this.global;
+ }
+
+ /** Writes the calling turn's copy when it claimed this value, else the process-wide one. */
+ set(value: T): void {
+ const cell = scopeStore.getStore()?.get(this);
+ if (cell) cell.value = value;
+ else this.global = value;
+ }
+
+ /**
+ * Give the calling turn its own copy, starting at `value` (default: the
+ * current process-wide value). Outside a turn scope this is a no-op and
+ * returns false, so callers can't accidentally write a global.
+ */
+ claim(value: T = this.global): boolean {
+ const cells = scopeStore.getStore();
+ if (!cells) return false;
+ cells.set(this, { value });
+ return true;
+ }
+
+ /** Has the calling turn claimed this value? */
+ isClaimed(): boolean {
+ return scopeStore.getStore()?.has(this) === true;
+ }
+
+ /** The process-wide value, regardless of the calling turn. */
+ getGlobal(): T {
+ return this.global;
+ }
+
+ setGlobal(value: T): void {
+ this.global = value;
+ }
+}
diff --git a/src/web/api/chat.ts b/src/web/api/chat.ts
index 63b9ed94..bced2192 100644
--- a/src/web/api/chat.ts
+++ b/src/web/api/chat.ts
@@ -80,7 +80,7 @@ export function setCurrentProviderCallback(fn: () => { name: string; model: stri
currentProviderFn = fn;
}
-let stopFn: (() => Promise<string>) | null = null;
+let stopFn: ((target?: { channelId?: string; sessionId?: string }) => Promise<string>) | null = null;
let busyFn: ((sessionId: string) => boolean) | null = null;
/** Whether a session has a turn running or queued (undo waits for it). */
export function setSessionBusyLookup(fn: ((sessionId: string) => boolean) | null): void {
@@ -102,8 +102,12 @@ let researchControls: {
export function setResearchControls(controls: typeof researchControls): void {
researchControls = controls;
}
-/** The same stop the terminal's Esc and `/stop` use: abort the running turn, cancel its work entry. */
-export function setStopCallback(fn: () => Promise<string>): void {
+/**
+ * The same stop the terminal's Esc and `/stop` use: abort the running turn,
+ * cancel its work entry. Given a thread or session, only that chat's work
+ * stops (other chats keep running, ADR-037); given neither, everything does.
+ */
+export function setStopCallback(fn: (target?: { channelId?: string; sessionId?: string }) => Promise<string>): void {
stopFn = fn;
}
@@ -373,11 +377,14 @@ chat.put('/api/chat/settings', async (c) => {
// ─── Permission Resolution ───────────────────────────────────
-/** Stop button: interrupt whatever Mercury is doing right now. */
+/** Stop button: interrupt this chat's work (`threadId`/`sessionId`), or everything when neither is given. */
chat.post('/api/chat/stop', async (c) => {
if (!stopFn) return c.json({ error: 'Stop is not available on this runtime' }, 503);
try {
- const note = await stopFn();
+ const body = await c.req.json<{ threadId?: unknown; sessionId?: unknown }>().catch(() => ({} as { threadId?: unknown; sessionId?: unknown }));
+ const threadId = typeof body.threadId === 'string' && body.threadId ? body.threadId.slice(0, 200) : undefined;
+ const sessionId = typeof body.sessionId === 'string' && body.sessionId ? body.sessionId.slice(0, 200) : undefined;
+ const note = await stopFn(threadId || sessionId ? { channelId: threadId, sessionId } : undefined);
return c.json({ ok: true, note });
} catch (err) {
return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
diff --git a/website/docs/cli-commands/in-chat-commands.mdx b/website/docs/cli-commands/in-chat-commands.mdx
index 5ca9846a..c6a5d91f 100644
--- a/website/docs/cli-commands/in-chat-commands.mdx
+++ b/website/docs/cli-commands/in-chat-commands.mdx
@@ -147,8 +147,8 @@ Persistent persona-scoped agents that run outside your conversation — each wit
| Command | Description |
|---------|-------------|
-| `/halt` | Emergency: stop all agents and clear the task queue |
-| `/stop` | Stop all agents, clear queue, release file locks, clear task board |
+| `/halt` | Emergency: stop every chat's task and all agents |
+| `/stop` | Stop this chat's task and the agents it started. When nothing else is running, also release file locks and clear the task board |
| `/reset` | Full reset: stop all + clear conversation context (requires confirmation) |
:::tip[Fast-path commands]
diff --git a/website/docs/integrations/sub-agents.mdx b/website/docs/integrations/sub-agents.mdx
index 0f114c2a..6b168f5f 100644
--- a/website/docs/integrations/sub-agents.mdx
+++ b/website/docs/integrations/sub-agents.mdx
@@ -59,13 +59,13 @@ Mercury: I've delegated both tasks to parallel agents. Agent a1 is building the
| `/bg: <task>` | Run a natural-language sub-agent task in background |
| `/bg current` | Move current in-flight task to a background sub-agent |
| `/bg list` | List shell + sub-agent background tasks |
-| `/halt` | Emergency: halt all sub-agents and clear the task queue |
-| `/stop` | Full stop: halt agents, clear queue, release file locks, clear task board |
+| `/halt` | Emergency: stop every chat's task and halt all sub-agents |
+| `/stop` | Stop this chat's task and the sub-agents it started. When nothing else is running, also release file locks and clear the task board |
| `/reset` | Full reset: stop all + clear conversation context (requires confirmation) |
:::tip[`/halt` vs `/stop` vs `/reset`]
-**`/halt`** stops all agents but preserves conversation context and file locks. **`/stop`** goes further — it also releases file locks and clears the task board. **`/reset`** does everything `/stop` does plus clears the conversation context (requires confirmation).
+Chats run at the same time, so **`/stop`** stops only the chat you type it in: its task and the sub-agents it started. When nothing else is running, it also releases file locks and clears the task board. **`/halt`** stops every chat's task and all agents, but keeps file locks. **`/reset`** clears the conversation context as well (requires confirmation).
:::
diff --git a/website/docs/integrations/telegram.mdx b/website/docs/integrations/telegram.mdx
index baf98cf3..c705e6b4 100644
--- a/website/docs/integrations/telegram.mdx
+++ b/website/docs/integrations/telegram.mdx
@@ -51,7 +51,7 @@ Mercury registers 15 commands in Telegram's bot menu for quick access:
| `/help` | Show Telegram-specific command reference |
| `/status` | Config, budget, and uptime |
| `/progress` | Live status for the current task |
-| `/stop` | Stop all agents and clear queue |
+| `/stop` | Stop this chat's task and the agents it started (other chats keep going) |
| `/budget` | Token budget status and management |
| `/stream` | Toggle text streaming on/off |
| `/memory` | Second brain memory |
diff --git a/website/docs/reference/configuration.mdx b/website/docs/reference/configuration.mdx
index f8d1abc0..c126ff4a 100644
--- a/website/docs/reference/configuration.mdx
+++ b/website/docs/reference/configuration.mdx
@@ -32,6 +32,19 @@ The sign-in password is set during `mercury setup` (or `mercury web-reset-passwo
Remote access (other devices, the IP allow-list, device limits) is managed with `/server` in the terminal or `mercury server`.
+## Chats at the same time
+
+Mercury answers several chats at once: your terminal, a Telegram chat, two desktop conversations and a scheduled task can all run together. Each chat still handles its own messages one after another, in order.
+
+How many run at once is set automatically from memory and platform: up to 4, 3 on machines under 8 GB of RAM, and 2 on Termux or under 4 GB. If memory gets tight, new chats wait for a free slot. If it keeps growing, Mercury stops the most recently started task and leaves the others running. To set the limit yourself, add this to `~/.mercury/mercury.yaml` and restart Mercury:
+
+```yaml
+concurrency:
+ maxTurns: 3 # 1 = one chat at a time; 0 = automatic (default); at most 16
+```
+
+Or set `MERCURY_MAX_CONCURRENT_TURNS`. `/stop` stops the chat you type it in, and `/halt` stops all of them.
+
## Optional tool discovery
If you have many plugin or MCP tools, you can load their schemas only when the main agent needs them. Add this to `~/.mercury/mercury.yaml` and restart Mercury: