Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(daemon): bound safe steering at next tool output (#709)
Gustavo Yec26c3be4665a
diff --git a/src/daemon/agent-driver/README.md b/src/daemon/agent-driver/README.mdindex cb0f71dca..7ea178d9c 100644--- a/src/daemon/agent-driver/README.md+++ b/src/daemon/agent-driver/README.md@@ -111,6 +111,14 @@ There is no per-turn built-in fallback.| OpenCode | session | `http_sse` / `opencode.v2.service.1.17.20` | `steer` | `transport_request` || Pi | session | `in_process_sdk` / `pi_sdk` | `steer` | `prompt_invocation` |+For Claude and Codex, `safe_boundary_queue` waits for at most the next valid+tool-output event. A tool start closes the boundary for messages that arrive+after it; the next matching tool output reopens the boundary and flushes queued+messages even if other concurrent tools remain active. A later tool start+closes the boundary again. Compaction and review remain closed until their+matching finished events. Cursor, OpenCode, and Pi steer immediately and do not+participate in this boundary latch.+Pi's runtime behavior did not change in this migration. It already kept oneSDK session and used prompt/steer/abort/dispose on that session; contract v1formalizes that existing persistent behavior as an `in_process_sdk`diff --git a/src/daemon/agent-driver/src/controller/logical-session.test.ts b/src/daemon/agent-driver/src/controller/logical-session.test.tsindex 7ac35857e..645976df3 100644--- a/src/daemon/agent-driver/src/controller/logical-session.test.ts+++ b/src/daemon/agent-driver/src/controller/logical-session.test.ts@@ -1328,6 +1328,26 @@ describe("backend-owned delivery behavior", () => {await session.stop({ reason: "shutdown", forceAfterMs: 10 });});+ it.each(["cursor", "opencode", "pi"] as const)(+ "%s keeps immediate steering while a tool is active",+ async (backend) => {+ const { session, driver } = makeSession(backend);+ await session.start({ id: "one", kind: "user", text: "start" });+ await emit(driver, { kind: "tool_call", callId: "tool-one", name: "one", input: {} });++ await expect(session.send({ id: "two", kind: "user", text: "follow" })).resolves.toMatchObject({+ status: "accepted",+ delivery: "steer",+ });+ if (backend === "pi") {+ expect(driver.sdkHandle!.steer).toHaveBeenCalledWith("follow");+ } else {+ expect(driver.writes).toEqual(["follow"]);+ }+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });+ },+ );+it("derives deferred first-message behavior from the adapter execution declaration", async () => {const { session, driver } = makeSession("cursor", {execution: {@@ -1612,16 +1632,36 @@ describe("backend-owned delivery behavior", () => {await session.stop({ reason: "shutdown", forceAfterMs: 10 });});- it("waits for the final nested tool output before flushing a gated command", async () => {- const { session, driver } = makeSession("claude");+ it.each(["claude", "codex"] as const)(+ "%s flushes at the first valid tool output while another tool remains active",+ async (backend) => {+ const { session, driver } = makeSession(backend);+ await session.start({ id: "one", kind: "user", text: "start" });+ await emit(driver, { kind: "tool_call", callId: "tool-one", name: "one", input: {} });+ await emit(driver, { kind: "tool_call", callId: "tool-two", name: "two", input: {} });+ await session.send({ id: "two", kind: "user", text: "follow" });+ await emit(driver, { kind: "tool_output", callId: "tool-one", name: "one" });+ expect(driver.writes).toEqual(["follow"]);+ expect(session.snapshot().diagnostics.metrics.outstandingToolUses).toBe(1);+ await emit(driver, { kind: "tool_output", callId: "tool-two", name: "two" });+ expect(driver.writes).toEqual(["follow"]);+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });+ },+ );++ it("closes the boundary latch again when a later tool starts", async () => {+ const { session, driver } = makeSession("codex");await session.start({ id: "one", kind: "user", text: "start" });- await emit(driver, { kind: "tool_call", name: "one", input: {} });- await emit(driver, { kind: "tool_call", name: "two", input: {} });- await session.send({ id: "two", kind: "user", text: "follow" });- await emit(driver, { kind: "tool_output", name: "one" });- expect(driver.writes).toEqual([]);- await emit(driver, { kind: "tool_output", name: "two" });- expect(driver.writes).toEqual(["follow"]);+ await emit(driver, { kind: "tool_call", callId: "tool-one", name: "one", input: {} });+ await session.send({ id: "two", kind: "user", text: "first follow" });+ await emit(driver, { kind: "tool_output", callId: "tool-one", name: "one" });+ await vi.waitFor(() => expect(driver.writes).toEqual(["first follow"]));++ await emit(driver, { kind: "tool_call", callId: "tool-two", name: "two", input: {} });+ await session.send({ id: "three", kind: "user", text: "second follow" });+ expect(driver.writes).toEqual(["first follow"]);+ await emit(driver, { kind: "tool_output", callId: "tool-two", name: "two" });+ await vi.waitFor(() => expect(driver.writes).toEqual(["first follow", "second follow"]));await session.stop({ reason: "shutdown", forceAfterMs: 10 });});diff --git a/src/daemon/agent-driver/src/controller/logical-session.ts b/src/daemon/agent-driver/src/controller/logical-session.tsindex ef180a17c..861b99ee8 100644--- a/src/daemon/agent-driver/src/controller/logical-session.ts+++ b/src/daemon/agent-driver/src/controller/logical-session.ts@@ -216,6 +216,14 @@ implements AgentSession<Specs, Id> {private readonly steeringDeliveries = new Set<SteeringDelivery>();private laneAdmissionTail: Promise<void> = Promise.resolve();private laneAdmissionPending = 0;+ /**+ * Whether a safe-boundary backend may accept queued steering now.+ *+ * A valid tool start closes the latch. The next valid tool output reopens it,+ * even when other concurrent tool calls remain outstanding. This models the+ * serialized provider boundary instead of waiting for global tool quiescence.+ */+ private toolBoundaryOpen = true;private toolBoundaryFlushDisabled = false;private safeBoundaryFlush?: Promise<void>;private safeBoundaryDelivery?: SafeBoundaryDelivery;@@ -539,6 +547,8 @@ implements AgentSession<Specs, Id> {this.turnError = undefined;this.interruptedTurnId = undefined;this.processTurnEnded = false;+ this.toolBoundaryOpen = true;+ this.toolBoundaryFlushDisabled = false;this.state = "starting";const generation = this.lifecycleGeneration;const text = messages.map((message) => message.text).join("\n\n");@@ -794,6 +804,7 @@ implements AgentSession<Specs, Id> {return;}if (!this.startToolUse(event.callId)) return;+ this.toolBoundaryOpen = false;const startedCallId = this.toolCallId(event.callId);this.emit({type: "tool_started",@@ -809,6 +820,7 @@ implements AgentSession<Specs, Id> {return;}if (!this.finishToolUse(event.callId)) return;+ this.toolBoundaryOpen = true;const finishedCallId = this.toolCallId(event.callId);this.emit({type: "tool_finished",@@ -816,7 +828,7 @@ implements AgentSession<Specs, Id> {...(finishedCallId ? { callId: finishedCallId } : {}),name: event.name,});- if (this.outstandingToolUseCount() === 0 && !this.toolBoundaryFlushDisabled) void this.flushSafeBoundaryQueue();+ if (!this.toolBoundaryFlushDisabled) void this.flushSafeBoundaryQueue();return;case "compaction_started":case "compaction_finished":@@ -1006,6 +1018,7 @@ implements AgentSession<Specs, Id> {this.clearOutstandingToolUses();this.compacting = false;this.reviewing = false;+ this.toolBoundaryOpen = true;this.toolBoundaryFlushDisabled = false;this.state = "idle";if (this.adapter.execution.lifetime === "turn") {@@ -1031,7 +1044,8 @@ implements AgentSession<Specs, Id> {private canFlushSafeBoundaryQueue(): boolean {return this.state === "working"&& this.behavior.midTurnDelivery === "safe_boundary_queue"- && this.outstandingToolUseCount() === 0+ && this.toolBoundaryOpen+ && !this.toolBoundaryFlushDisabled&& !this.compacting&& !this.reviewing&& this.activeTurn !== undefineddiff --git a/src/daemon/src/diagnostics/privacyPolicy.test.ts b/src/daemon/src/diagnostics/privacyPolicy.test.tsindex 503f03417..787f20d4e 100644--- a/src/daemon/src/diagnostics/privacyPolicy.test.ts+++ b/src/daemon/src/diagnostics/privacyPolicy.test.ts@@ -330,7 +330,7 @@ const EXPECTED_POLICY: ReadonlyArray<{},{header: "@alook/daemon:manager",- message: "steering message sent to running agent",+ message: "steering message submitted to logical session",scope: "target",fields: {agentId: { type: "string", maxChars: 128 },diff --git a/src/daemon/src/diagnostics/privacyPolicy.ts b/src/daemon/src/diagnostics/privacyPolicy.tsindex 8ef4862b2..52b6895bc 100644--- a/src/daemon/src/diagnostics/privacyPolicy.ts+++ b/src/daemon/src/diagnostics/privacyPolicy.ts@@ -63,7 +63,7 @@ export const DAEMON_LOG_DIAGNOSTIC_POLICY: readonly DaemonLogPolicyEntry[] = [reason: string(32, { values: ["turn_end", "stopped", "terminate_stalled", "exit"] }),sessionId: string(256, { scrub: true }),} },- { header: "@alook/daemon:manager", message: "steering message sent to running agent", scope: "target", fields: {+ { header: "@alook/daemon:manager", message: "steering message submitted to logical session", scope: "target", fields: {agentId: AGENT, mode: string(8, { values: ["busy", "idle"] }),} },{ header: "@alook/daemon:manager", message: "gated busy message held", scope: "target", fields: {diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.tsindex a04501447..c2fa99c55 100644--- a/src/daemon/src/manager/managerRuntime.test.ts+++ b/src/daemon/src/manager/managerRuntime.test.ts@@ -1668,6 +1668,40 @@ describe("AgentProcessManager — logging", () => {).toBe(true);});+ it("describes a busy wake as submitted until the logical session accepts it", async () => {+ const logger = stubLogger();+ const persistentDriver = {+ ...fakeDriver("codex"),+ lifecycle: { kind: "persistent", start: "immediate", exit: "natural", inFlightWake: "queue" } as never,+ supportsStdinNotification: true,+ busyDeliveryMode: "direct",+ } as Driver;+ const session = fakeSession();+ const mgr = new AgentProcessManager({+ driverFor: () => persistentDriver,+ baseContextFor: () => ({+ workingDirectory: "/tmp",+ agentId: "a1",+ standingPrompt: "",+ config: {} as LaunchContext["config"],+ credentialProxy: {} as LaunchContext["credentialProxy"],+ }),+ sessionFactory: (hooks) => bindFactorySession(hooks, session),+ logger,+ });+ mgr.register("a1");+ mgr.deliver("a1", { seq: 1, text: "start" });+ session.startResolver?.();+ await vi.waitFor(() => expect(mgr.agentActivity("a1")).toBe("running"));++ mgr.deliver("a1", { seq: 2, text: "follow" });++ expect(logger.calls.info).toEqual(expect.arrayContaining([+ ["steering message submitted to logical session", [{ agentId: "a1", mode: "busy" }]],+ ]));+ expect(logger.calls.info.some(([message]) => message === "steering message sent to running agent")).toBe(false);+ });+it("logs warn on a pre-handshake spawn failure (ENOENT)", async () => {const logger = stubLogger();const { mgr, session } = makeManager({ logger });diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.tsindex 1583485fa..3b78dc89a 100644--- a/src/daemon/src/manager/managerRuntime.ts+++ b/src/daemon/src/manager/managerRuntime.ts@@ -1267,6 +1267,10 @@ export class AgentProcessManager {try {sent = session.send(input);if (exactOwner) this.markPendingDeliveryObserved(exactOwner, input.id);+ this.log.info("steering message submitted to logical session", {+ agentId: effect.agentId,+ mode: effect.mode,+ });} catch (error) {if (exactOwner) {this.settlePendingDelivery(exactOwner, input.id);@@ -1323,7 +1327,6 @@ export class AgentProcessManager {mode: effect.mode,});}- this.log.info("steering message sent to running agent", { agentId: effect.agentId, mode: effect.mode });break;}case "stop":