diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 76d9a1db5..4e1b0456d 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -3168,15 +3168,8 @@ export class AgentManager { options?: AgentRunOptions, onAccepted?: () => void, ): Promise { - if (this.collectingRuntimes.has(agentId) || !this.agents.has(agentId)) { - await this.waitForAgentClose(agentId); - await ensureAgentLoaded(agentId, { - agentManager: this, - agentStorage: this.requireRegistry(), - logger: this.logger, - }); - } - const agent = await this.ensureInteractiveSession(agentId); + const agent = await this.findOutOfBandRecipient(agentId); + if (!agent) return false; // Providers parse slash commands from the raw text, so a command another agent sent // must reach them without its sender envelope. const agentMessage = typeof prompt === "string" ? parseAgentMessage(prompt) : null; @@ -3222,6 +3215,31 @@ export class AgentManager { return true; } + private async findOutOfBandRecipient(agentId: string): Promise { + const live = this.agents.get(agentId); + const collecting = this.collectingRuntimes.has(agentId); + if (live?.session && !collecting && !this.historySessions.has(live.session)) { + return live; + } + if (collecting || !live) { + await this.waitForAgentClose(agentId); + const storage = this.requireRegistry(); + // Normal dispatch owns unarchiving. Decline without loading archived history. + if ((await storage.get(agentId))?.archivedAt) return null; + await ensureAgentLoaded(agentId, { + agentManager: this, + agentStorage: storage, + logger: this.logger, + }); + } + return this.runLifecycleMutation(agentId, async () => { + const record = await this.registry?.get(agentId); + // Restore closes any history session. Normal dispatch can reopen the stored agent. + if (record && (record.archivedAt || !this.agents.get(agentId)?.session)) return null; + return this.upgradeHistorySessionUnlocked(this.requireSessionAgent(agentId)); + }); + } + async appendTimelineItem( agentId: string, item: AgentTimelineItem, @@ -3345,13 +3363,22 @@ export class AgentManager { /** Inside the agent's lane: a history session is upgraded before anything is applied to it. */ private async ensureInteractiveSessionUnlocked(agentId: string): Promise { const agent = this.requireSessionAgent(agentId); - if (this.historySessions.has(agent.session)) { - const record = await this.registry?.get(agentId); - if (record?.archivedAt) throw new Error(`Agent is archived: ${agentId}`); - // Reload validates the directory before releasing readable history. - await this.trackAgentRegistrationOperation(this.reloadAgentSessionInternal(agentId)); + if ( + this.historySessions.has(agent.session) && + (await this.registry?.get(agentId))?.archivedAt + ) { + throw new Error(`Agent is archived: ${agentId}`); } - return this.requireSessionAgent(agentId); + return this.upgradeHistorySessionUnlocked(agent); + } + + private async upgradeHistorySessionUnlocked( + agent: ActiveManagedAgent, + ): Promise { + if (!this.historySessions.has(agent.session)) return agent; + // Reload validates the directory before releasing readable history. + await this.trackAgentRegistrationOperation(this.reloadAgentSessionInternal(agent.id)); + return this.requireSessionAgent(agent.id); } /** Inside the agent's lane: transparently reopens a retired plugin session before applying config. */ diff --git a/packages/server/src/server/agent/mcp-server.test.ts b/packages/server/src/server/agent/mcp-server.test.ts index a70768482..bc50c1385 100644 --- a/packages/server/src/server/agent/mcp-server.test.ts +++ b/packages/server/src/server/agent/mcp-server.test.ts @@ -25,6 +25,7 @@ import { z } from "zod"; import { createTestLogger } from "../../test-utils/test-logger.js"; import { createAgentMcpServer as createAgentMcpServerWithDependencies } from "./mcp-server.js"; import { createMcpHandler } from "@modelcontextprotocol/server"; +import { ensureAgentLoaded } from "./agent-loading.js"; import { AgentManager, type ManagedAgent } from "./agent-manager.js"; import { AgentStorage, type StoredAgentRecord } from "./agent-storage.js"; import { createTestAgentClients } from "../test-utils/fake-agent-client.js"; @@ -3510,6 +3511,7 @@ class HeldTurnAgentSession implements AgentSession { private turnStartGate: Promise | null = null; private cancelHeldStart: (() => void) | null = null; private interruptGate: Promise | null = null; + private closeGate?: { signalStart: () => void; waitForRelease: Promise }; private nextStartError: Error | null = null; constructor( @@ -3701,7 +3703,19 @@ class HeldTurnAgentSession implements AgentSession { }); } - async close(): Promise {} + holdClose(): { started: Promise; release: () => void } { + const started = Promise.withResolvers(); + const released = Promise.withResolvers(); + this.closeGate = { signalStart: started.resolve, waitForRelease: released.promise }; + return { started: started.promise, release: released.resolve }; + } + + async close(): Promise { + if (this.closeGate) { + this.closeGate.signalStart(); + await this.closeGate.waitForRelease; + } + } } class HeldTurnAgentClient implements AgentClient { @@ -3860,6 +3874,91 @@ describe("send_agent_prompt MCP tool", () => { }, ); + it.each([ + { activeTurnBehavior: "interrupt", history: "closed" }, + { activeTurnBehavior: "steer", history: "closed" }, + { activeTurnBehavior: "queue", history: "closed" }, + { activeTurnBehavior: "interrupt", history: "open" }, + { activeTurnBehavior: "interrupt", history: "restoring" }, + ] as const)( + "an agent-scoped $activeTurnBehavior send starts a turn on an archived agent (history: $history)", + async ({ activeTurnBehavior, history }) => { + const workdir = await mkdtemp(join(tmpdir(), "mcp-send-archived-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const client = new HeldTurnAgentClient("codex", true); + const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger }); + let mcpClient: Client | undefined; + let restore: Promise | undefined; + let releaseHistoryClose: (() => void) | undefined; + try { + const sender = await manager.createAgent( + { provider: "codex", cwd: existingCwd }, + undefined, + { workspaceId: "wks_parent" }, + ); + const recipient = await manager.createAgent( + { provider: "codex", cwd: existingCwd }, + undefined, + { workspaceId: "wks_parent" }, + ); + await manager.archiveAgent(recipient.id); + if (history !== "closed") { + await ensureAgentLoaded(recipient.id, { + agentManager: manager, + agentStorage: storage, + logger, + }); + } + const openedSessions = client.sessions.length; + + const server = await createAgentMcpServer({ + agentManager: manager, + agentStorage: storage, + callerAgentId: sender.id, + providerSnapshotManager: createOpenCodeManager().manager, + logger, + }); + mcpClient = await connectInMemoryMcpClient(server); + if (history === "restoring") { + const closing = client.sessions.at(-1)!.holdClose(); + releaseHistoryClose = closing.release; + restore = manager.unarchiveSnapshot(recipient.id); + await closing.started; + } + const response = await mcpClient.callTool({ + name: "send_agent_prompt", + arguments: { + agentId: recipient.id, + prompt: "Start work", + notifyOnFinish: false, + activeTurnBehavior, + }, + }); + expect(response.structuredContent).toMatchObject({ + success: true, + deliveryStatus: "queued", + activeTurnBehavior, + }); + const dispatch = serverDeliveries + .get(server)! + .waitForDispatch(recipient.id, AbortSignal.timeout(5_000)); + releaseHistoryClose?.(); + await Promise.all([restore, dispatch]); + expect((await storage.get(recipient.id))?.archivedAt).toBeNull(); + expect(manager.getAgent(recipient.id)?.lifecycle).toBe("running"); + expect(client.sessions).toHaveLength(openedSessions + 1); + expect(client.sessions.at(-1)?.prompts.map(parseAgentMessage)).toEqual([ + expect.objectContaining({ text: "Start work" }), + ]); + } finally { + releaseHistoryClose?.(); + await restore?.catch(() => undefined); + await mcpClient?.close(); + await removeAgentStateDir(manager, storage, workdir); + } + }, + ); + it("tells an agent caller that an idle recipient starts a turn with its queued message", async () => { const workdir = await mkdtemp(join(tmpdir(), "mcp-send-idle-")); const storage = new AgentStorage(join(workdir, "agents"), logger);