Deliver urgent messages to archived agents (#10611)
* fix(server): deliver urgent messages to archived agents An out-of-band probe rejected urgent messages before normal dispatch could restore the archived recipient. Decline the probe so the existing dispatch path restores the recipient and delivers the prompt. Co-authored-by: Thomas Van <9481872+thomasvan@users.noreply.github.com> * fix(server): deliver urgent messages during agent restore When restore closes the history session, the stored agent still exists. Let normal dispatch reopen it instead of treating the missing session as a dispatch failure. --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Thomas Van <9481872+thomasvan@users.noreply.github.com>
This commit is contained in:
1 parent
5f424e2e94
commit
309a44c480
2 files changed
+142
-16
No files matched your search
@@ -3168,15 +3168,8 @@ export class AgentManager {
|
||||
options?: AgentRunOptions,
|
||||
onAccepted?: () => void,
|
||||
): Promise<boolean> {
|
||||
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<ActiveManagedAgent | null> {
|
||||
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<ActiveManagedAgent> {
|
||||
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<ActiveManagedAgent> {
|
||||
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. */
|
||||
|
||||
@@ -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<void> | null = null;
|
||||
private cancelHeldStart: (() => void) | null = null;
|
||||
private interruptGate: Promise<void> | null = null;
|
||||
private closeGate?: { signalStart: () => void; waitForRelease: Promise<void> };
|
||||
private nextStartError: Error | null = null;
|
||||
|
||||
constructor(
|
||||
@@ -3701,7 +3703,19 @@ class HeldTurnAgentSession implements AgentSession {
|
||||
});
|
||||
}
|
||||
|
||||
async close(): Promise<void> {}
|
||||
holdClose(): { started: Promise<void>; release: () => void } {
|
||||
const started = Promise.withResolvers<void>();
|
||||
const released = Promise.withResolvers<void>();
|
||||
this.closeGate = { signalStart: started.resolve, waitForRelease: released.promise };
|
||||
return { started: started.promise, release: released.resolve };
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
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<boolean> | 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);
|
||||
|
||||
Reference in new issue
Block a user