diff --git a/docs/harnesses.md b/docs/harnesses.md index 15d53470..53c59223 100644 --- a/docs/harnesses.md +++ b/docs/harnesses.md @@ -94,6 +94,8 @@ Install [Antigravity CLI](https://antigravity.google/docs/getting-started?tab=cl With **Antigravity CLI 1.5.9 or newer**, Loop uses the documented [ACP interface](https://antigravity.google/docs/ide/extensions/acp), launched with `agy acp --process-per-session`. Each native session receives its own authenticated Loop MCP connection through ACP session creation or resuming. This enables Agent mail, team delegation and Loop tool integrations without editing global or project MCP configuration. ACP must advertise HTTP MCP support; setup fails before sending a prompt if it does not. Enable Antigravity again after upgrading the CLI so Loop refreshes its saved runtime version and capabilities. Existing streaming sessions switch to ACP on their next turn; refreshing does not interrupt a running turn. See [session reuse](state-machines.md#companion_sessionsstate). +When Antigravity returns `end_turn` while a tool call or approval is still open, Loop keeps receiving output and approvals. For overlapping steering requests, Loop keeps waiting for inherited work that was open before steering. Otherwise, the final prompt response remains authoritative if all work has settled and reactive waiting has not started. An overlapping request that never resolves is subject to the one-hour watchdog. A tool that has already reported a terminal status cannot establish that another wakeup is pending. Antigravity can send usage updates both during a continuation and after its final text. Until ACP supplies a definitive completion signal, Loop bounds the wait and interrupts the run with its partial output preserved in the conversation trace. This can leave a successful background continuation without a published Result. Daemons identified before the prompt returns can outlive ordinary completed turns. A late daemon update can clear an open tool but does not certify completion after reactive waiting has begun. See the [upstream ACP discussion](https://github.com/google-antigravity/antigravity-cli/issues/1461). + Model discovery and session initialization send no model prompt. Saved instructions accompany explicit prompts, and interrupted tasks are never automatically replayed. Existing native conversation IDs and workspace bindings are retained when a newer runtime resumes a conversation created by the streaming adapter. Commands and skills come from the session’s ACP catalog. Catalog probes and slash-leading prompts or live replies wait up to five seconds for that catalog. A discovered command stays at the start of an explicit prompt, followed by saved instructions; other slash-leading text stays literal, including when discovery times out. Saved instructions starting with `/` also stay literal. The model catalog comes from ACP; if the account no longer offers a previously selected model through that interface, select an available model explicitly. Loop does not choose a replacement model after failure. Antigravity requires `--billing existing`. Its native sign-in, billing and permission rules apply; Loop does not verify a subscription entitlement. ACP permission requests appear in Loop's approval flow. CLI 1.5.2–1.5.8 uses `agy acp` with approvals and live steering, while Agent mail and team delegation require 1.5.9 or newer. A reply during a running ACP turn uses another `session/prompt`; Loop waits for the original prompt echo, then confirms delivery from an exact reply echo or normal request completion. Replies wait while an approval is open. Unconfirmed replies are not automatically resent. Older streaming runtimes queue follow-ups for the next turn. Antigravity is not bundled in the Docker images. diff --git a/src/adapters/acp.ts b/src/adapters/acp.ts index 8f1037ac..31bdbc81 100644 --- a/src/adapters/acp.ts +++ b/src/adapters/acp.ts @@ -73,6 +73,8 @@ function matchEcho(echo: Echo, chunk: string) { } // agy echoes a prompt within a second of receiving it. const ECHO_WAIT = 5000; +const REACTIVE_IDLE_MS = 60_000; +const REACTIVE_WATCHDOG_MS = 60 * 60_000; const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms).unref()); const text = (value: unknown) => @@ -141,6 +143,18 @@ export class Acp implements Adapter { protected resumeWithoutReplay = false; /** Report each turn's cumulative token usage from prompt responses. */ protected reportsUsage = false; + /** agy can return end_turn before its background work wakes the model. */ + protected waitsForReactiveTurns = false; + private reactiveTools = new Set(); + private reactiveEnd = false; + private reactiveIdle?: NodeJS.Timeout; + private reactiveWatchdog?: NodeJS.Timeout; + private reactiveWatchdogStarted = 0; + private reactiveBudget = REACTIVE_WATCHDOG_MS; + private retireReactiveSession = false; + get reusable() { + return !this.retireReactiveSession; + } /** Prompt requests open in the current turn. A steering agent answers an * earlier request when it folds a later one into the same turn; the turn * ends only when the last open request settles. */ @@ -154,6 +168,8 @@ export class Acp implements Adapter { private steering = false; /** The steering input's echo arrived, so it joined the running turn. */ private steerJoined = false; + private toolsAtFirstSteerDispatch?: Set; + private workWhileSteerUnconfirmed = false; /** An earlier request of this turn ended it normally. */ private earlierEnd = false; private end!: () => void; @@ -241,6 +257,8 @@ export class Acp implements Adapter { ); this.child = child; child.once("error", () => { + clearTimeout(this.reactiveIdle); + clearTimeout(this.reactiveWatchdog); this.end(); this.cancelPermissions(); if (!this.closed && !this.terminalReported) { @@ -258,6 +276,8 @@ export class Acp implements Adapter { }); child.stderr.resume(); child.once("exit", () => { + clearTimeout(this.reactiveIdle); + clearTimeout(this.reactiveWatchdog); this.end(); const memory = nativeMemoryFailure(child); this.modeConfirmation?.reject(memory || new Error("ACP agent exited")); @@ -581,6 +601,7 @@ export class Acp implements Adapter { !this.connection || !this.session || this.active || + !this.reusable || this.pendingSettingWrites ) throw new Error("ACP session is unavailable or busy"); @@ -592,6 +613,10 @@ export class Acp implements Adapter { this.messageId = randomUUID(); this.turnUsage = undefined; this.earlierEnd = false; + this.toolsAtFirstSteerDispatch = undefined; + this.reactiveTools.clear(); + this.reactiveEnd = false; + this.reactiveBudget = REACTIVE_WATCHDOG_MS; const expected = this.echoOf(value).trim(); this.promptEcho = undefined; this.promptEchoed = expected @@ -608,6 +633,7 @@ export class Acp implements Adapter { /** Sends one prompt request in the current turn. Only the last open request * to settle reports the turn's terminal status. */ private send(value: string, steer = false) { + clearTimeout(this.reactiveIdle); this.openPrompts++; const request = this.connection!.prompt({ sessionId: this.session!, @@ -618,33 +644,76 @@ export class Acp implements Adapter { (result) => { const last = --this.openPrompts === 0; this.addUsage(result); - if (!last && result.stopReason === "end_turn") this.earlierEnd = true; - if (!last || this.closed || this.terminalReported) return; + if (this.closed || this.terminalReported) return; + if (result.stopReason === "end_turn") { + if (!last) this.earlierEnd = true; + // Antigravity gives reactive passes no definitive end signal. + // Preserve their output as partial instead of publishing it + // based on usage, steering replies, or elapsed time. + const inheritedWork = [ + ...(this.toolsAtFirstSteerDispatch ?? []), + ].some((id) => this.reactiveTools.has(id)); + if ( + (last || + inheritedWork || + (!this.steerJoined && this.permissions.size)) && + this.waitForReactiveTurn() + ) + return; + if (!last && this.waitsForReactiveTurns) { + if ( + this.echo && + (this.reactiveTools.size || this.permissions.size) + ) + this.workWhileSteerUnconfirmed = true; + this.refreshReactiveWait(); + } + } + if (!last) return; this.terminalReported = true; const limited = ["max_tokens", "max_turn_requests"].includes( result.stopReason, ); + const interrupted = + this.cancelling || + this.reactiveEnd || + limited || + result.stopReason === "cancelled"; + if (interrupted && (this.reactiveEnd || this.reactiveTools.size)) + this.retireReactiveSession = true; this.emit({ type: "status", - status: - this.cancelling || - ["cancelled", "max_tokens", "max_turn_requests"].includes( - result.stopReason, - ) - ? "interrupted" - : "completed", + status: interrupted ? "interrupted" : "completed", detail: limited ? "ACP turn stopped at the agent's limit." : undefined, - recoverable: true, + recoverable: !this.retireReactiveSession, }); }, (error: unknown) => { const last = --this.openPrompts === 0; if (!last || this.closed || this.terminalReported) return; - this.terminalReported = true; // A rejected steering input that never joined the turn does not // undo the turn's own normal end. + if ( + this.cancelling && + (this.reactiveEnd || + (this.waitsForReactiveTurns && this.earlierEnd)) + ) { + this.interruptReactiveTurn(); + return; + } + if ( + steer && + (this.reactiveEnd || + (this.earlierEnd && + (!this.steerJoined || + this.reactiveTools.size || + this.permissions.size))) && + this.waitForReactiveTurn(this.workWhileSteerUnconfirmed) + ) + return; + this.terminalReported = true; if (steer && !this.steerJoined && this.earlierEnd) { this.emit({ type: "status", @@ -665,12 +734,88 @@ export class Acp implements Adapter { }, ) .finally(() => { - if (this.openPrompts) return; + if (this.openPrompts || !this.terminalReported) return; + clearTimeout(this.reactiveIdle); + clearTimeout(this.reactiveWatchdog); + this.reactiveWatchdog = undefined; this.active = false; this.cancelPermissions(); }); return request; } + private waitForReactiveTurn(observedContinuation = false) { + if ( + this.cancelling || + !this.waitsForReactiveTurns || + !( + observedContinuation || + this.reactiveEnd || + this.reactiveTools.size || + this.permissions.size + ) + ) + return false; + this.reactiveEnd = true; + this.refreshReactiveWait(); + return true; + } + private refreshReactiveWait() { + clearTimeout(this.reactiveIdle); + if ( + this.closed || + this.terminalReported || + !(this.reactiveEnd || (this.earlierEnd && this.openPrompts)) + ) + return; + if (this.cancelling) { + this.interruptReactiveTurn(); + return; + } + if (this.permissions.size) return; + // The reactive wait stays bounded even if a concurrent steer never + // answers. Human approval time does not count against the watchdog. + if (!this.reactiveWatchdog) { + this.reactiveWatchdogStarted = performance.now(); + this.reactiveWatchdog = setTimeout( + () => + this.interruptReactiveTurn( + "Antigravity did not finish its reactive turn within an hour.", + ), + this.reactiveBudget, + ).unref(); + } + if (!this.reactiveEnd || this.openPrompts || this.reactiveTools.size) + return; + // ACP usage updates also occur mid-pass. A quiet reactive wait can + // preserve partial output, but cannot certify a completed Result. + this.reactiveIdle = setTimeout( + () => + this.interruptReactiveTurn( + "Antigravity did not confirm the end of its reactive turn.", + ), + REACTIVE_IDLE_MS, + ).unref(); + } + private interruptReactiveTurn(detail?: string) { + if (!this.cancelling && this.session && this.connection) { + this.cancelling = true; + // The supervisor also retires the process when it sees this adapter + // is no longer reusable. A blocked cancel write cannot delay that. + void this.connection.cancel({ sessionId: this.session }).catch(() => {}); + } + clearTimeout(this.reactiveIdle); + clearTimeout(this.reactiveWatchdog); + this.reactiveWatchdog = undefined; + this.retireReactiveSession = true; + this.terminalReported = true; + this.active = false; + this.emit({ + type: "status", + status: "interrupted", + detail, + recoverable: false, + }); + } private addUsage(result: unknown) { if (!this.reportsUsage) return; const usage = z @@ -750,6 +895,8 @@ export class Acp implements Adapter { throw new NotDelivered("ACP session is busy."); beforeDispatch?.(); this.steerJoined = false; + this.toolsAtFirstSteerDispatch ??= new Set(this.reactiveTools); + this.workWhileSteerUnconfirmed = false; const echoed = new Promise((resolve) => { if (expected) this.echo = { @@ -782,10 +929,17 @@ export class Acp implements Adapter { } async cancel() { this.cancelling = true; + clearTimeout(this.reactiveIdle); + clearTimeout(this.reactiveWatchdog); + this.reactiveWatchdog = undefined; this.finishCommandDiscovery(false); this.cancelPermissions(); - if (!this.closed && this.session && this.connection && this.active) - await this.connection.cancel({ sessionId: this.session }); + const notification = + !this.closed && this.session && this.connection && this.active + ? this.connection.cancel({ sessionId: this.session }) + : undefined; + this.refreshReactiveWait(); + await notification; } async answer( id: string, @@ -805,9 +959,13 @@ export class Acp implements Adapter { outcome: { outcome: "selected", optionId: answer.choice }, }); this.emit({ type: "resolved", id }); + if (this.waitsForReactiveTurns && !this.cancelling) + this.refreshReactiveWait(); } async dispose() { this.closed = true; + clearTimeout(this.reactiveIdle); + clearTimeout(this.reactiveWatchdog); this.creatingSession = false; this.startupCommands = undefined; this.finishCommandDiscovery(false); @@ -1102,11 +1260,21 @@ export class Acp implements Adapter { if (!choices.length) return Promise.resolve({ outcome: { outcome: "cancelled" } }); const id = randomUUID(); + clearTimeout(this.reactiveIdle); + if (this.reactiveWatchdog) + this.reactiveBudget = Math.max( + 0, + this.reactiveBudget - + (performance.now() - this.reactiveWatchdogStarted), + ); + clearTimeout(this.reactiveWatchdog); + this.reactiveWatchdog = undefined; return new Promise((resolve) => { this.permissions.set(id, { choices: new Set(choices.map((choice) => choice.optionId)), resolve, }); + if (this.earlierEnd && this.echo) this.workWhileSteerUnconfirmed = true; this.emit({ type: "request", request: { @@ -1170,18 +1338,64 @@ export class Acp implements Adapter { return; } if (u.sessionUpdate === "agent_message_chunk") { - if (!this.loading && u.content.type === "text") + if (!this.loading && u.content.type === "text") { this.emit({ type: "delta", id: this.messageId, text: text(u.content.text), }); + } + if (this.earlierEnd && this.echo) this.workWhileSteerUnconfirmed = true; + this.refreshReactiveWait(); + return; + } + if ( + u.sessionUpdate === "agent_thought_chunk" && + (this.earlierEnd || this.reactiveEnd) && + !this.cancelling + ) { + if (this.earlierEnd && this.echo) this.workWhileSteerUnconfirmed = true; + this.refreshReactiveWait(); + return; + } + if ( + u.sessionUpdate === "usage_update" && + this.reactiveEnd && + !this.cancelling + ) { + this.refreshReactiveWait(); return; } if ( u.sessionUpdate === "tool_call" || u.sessionUpdate === "tool_call_update" ) { + let reactiveWorkChanged = false; + if (this.waitsForReactiveTurns && !this.loading) { + const input = u.rawInput; + const title = u.title ?? this.toolItems.get(u.toolCallId)?.title; + const command = + input && + typeof input === "object" && + "CommandLine" in input && + typeof input.CommandLine === "string"; + const daemon = + (command || title === "run_command" || title === "schedule") && + input && + typeof input === "object" && + "IsDaemon" in input && + input.IsDaemon === true; + if (daemon || u.status === "completed" || u.status === "failed") { + reactiveWorkChanged = this.reactiveTools.delete(u.toolCallId); + } else if (u.sessionUpdate === "tool_call") { + this.reactiveTools.add(u.toolCallId); + // A pending steer might own this tool. Its successful response + // decides whether work remains; a rejection retains the evidence. + if (this.earlierEnd && this.echo) + this.workWhileSteerUnconfirmed = true; + reactiveWorkChanged = true; + } + } const old = this.toolItems.get(u.toolCallId); const title = text(u.title) || old?.title || "ACP tool"; const memoryTool = @@ -1196,6 +1410,8 @@ export class Acp implements Adapter { }; this.toolItems.set(u.toolCallId, item); this.emit({ type: "item", item }); + if (reactiveWorkChanged || this.reactiveTools.has(u.toolCallId)) + this.refreshReactiveWait(); return; } const kind = u.kind ?? this.toolKinds.get(u.toolCallId); @@ -1414,6 +1630,8 @@ export class Acp implements Adapter { }, this.loading, ); + if (reactiveWorkChanged || this.reactiveTools.has(u.toolCallId)) + this.refreshReactiveWait(); return; } if (u.sessionUpdate === "plan") { diff --git a/src/adapters/antigravity.ts b/src/adapters/antigravity.ts index 588c96dd..2fca7243 100644 --- a/src/adapters/antigravity.ts +++ b/src/adapters/antigravity.ts @@ -29,6 +29,7 @@ class AntigravityAcp extends Acp { protected override requireWorkspaceTools = false; protected override resumeWithoutReplay = true; protected override reportsUsage = true; + protected override waitsForReactiveTurns = true; override capabilities = { approvals: true, questions: false, @@ -207,6 +208,7 @@ export class Antigravity implements Adapter { } canReuse(registration: Options) { return ( + this.reusable !== false && meetsMinimum(registration.version, ANTIGRAVITY_ACP_MINIMUM_VERSION) === this.adapter instanceof Acp && meetsMinimum( diff --git a/test/antigravity-steering-native.test.ts b/test/antigravity-steering-native.test.ts index fe433de8..6a326cb7 100644 --- a/test/antigravity-steering-native.test.ts +++ b/test/antigravity-steering-native.test.ts @@ -404,6 +404,56 @@ it("steers a running turn through agy acp without a restart or replaying the tas ]); }); +it("preserves unconfirmed Antigravity reactive output without publishing a Result", async () => { + process.env.LOOP_TEST_AGY_MODE = "reactive"; + const { run } = task("agy-reactive"); + const before = prompts().length; + const execution = sessions.execute( + claim("antigravity-fixture", (candidate) => candidate.id === run.id)!, + ); + const checkpoint = () => + db + .prepare("SELECT stage,output FROM agent_checkpoints WHERE run_id=?") + .get(run.id); + const decision = () => + db + .prepare( + "SELECT id FROM native_decisions WHERE run_id=? AND state='pending'", + ) + .get(run.id) as { id: string } | undefined; + try { + await until(() => !!decision()); + expect(checkpoint()).toMatchObject({ output: "" }); + expect(checkpoint()).not.toMatchObject({ stage: "done" }); + expect(ownedRun(run.id, OWNER).state).toBe("awaiting_approval"); + await sessions.decisions.answer(decision()!.id, "reactive-approval", { + choice: "allow", + }); + const reactiveOutput = () => + db + .prepare("SELECT item FROM native_items WHERE run_id=?") + .all(run.id) + .some((row) => + JSON.parse((row as { item: string }).item).text?.includes("Done."), + ); + await until(reactiveOutput, 5000); + await sessions.interrupt(run.id); + expect(await execution).toMatchObject({ + kind: "already-moved", + reason: "native-interrupted", + }); + expect(checkpoint()).toMatchObject({ stage: "native", output: "" }); + expect(reactiveOutput()).toBe(true); + expect(prompts().slice(before)).toEqual([ + "Saved fixture instructions\n\nExplicit task", + ]); + } finally { + delete process.env.LOOP_TEST_AGY_MODE; + await sessions.interrupt(run.id); + await execution; + } +}, 10_000); + it("replaces an idle ACP session after refreshing workspace-tool support while retaining native context", async () => { const { run } = task("agy-acp-upgrade"); const before = await sessions.session(run); diff --git a/test/antigravity-steering.node.test.ts b/test/antigravity-steering.node.test.ts index 329271b2..586d1e04 100644 --- a/test/antigravity-steering.node.test.ts +++ b/test/antigravity-steering.node.test.ts @@ -3,6 +3,7 @@ import assert from "node:assert/strict"; import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; +import { ClientSideConnection } from "@agentclientprotocol/sdk"; import { Antigravity } from "../src/adapters/antigravity.js"; import type { AdapterEvent } from "../src/adapters/events.js"; import { NotDelivered, type Options } from "../src/adapters/types.js"; @@ -22,7 +23,7 @@ function fixture(t: { after(fn: () => void): void }) { t.after(() => { delete process.env.LOOP_TEST_AGY_LOG; delete process.env.LOOP_TEST_AGY_MODE; - rmSync(dir, { recursive: true, force: true }); + rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); }); return () => existsSync(path) @@ -41,6 +42,512 @@ const statuses = (events: AdapterEvent[]) => const complete = (events: AdapterEvent[]) => events.filter((e) => e.type === "status" && e.status === "completed"); +test("Antigravity waits through successive reactive passes and approvals", async (t) => { + const requests = fixture(t); + process.env.LOOP_TEST_AGY_MODE = "reactive"; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Run background work"); + await until(() => events.some((e) => e.type === "request")); + const approval = events.find((e) => e.type === "request")!; + assert.deepEqual(statuses(events), ["ready"]); + assert.deepEqual( + events.flatMap((e) => (e.type === "delta" ? [e.text] : [])), + ["Waiting.", "Waiting again."], + ); + await adapter.answer(approval.request.id, { choice: "allow" }); + await until(() => + events.some((e) => e.type === "delta" && e.text === "Done."), + ); + assert.deepEqual(statuses(events), ["ready"]); + assert.deepEqual( + events.flatMap((e) => (e.type === "delta" ? [e.text] : [])), + ["Waiting.", "Waiting again.", "Done."], + ); + assert.deepEqual(prompts(requests), ["Run background work"]); + await assert.rejects(adapter.prompt("Next turn"), /busy/); +}); + +test("Antigravity completes normally with only a known daemon still running", async (t) => { + fixture(t); + process.env.LOOP_TEST_AGY_MODE = "daemon-only"; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Start a daemon"); + await until(() => complete(events).length === 1); + assert.deepEqual(statuses(events), ["ready", "completed"]); +}); + +for (const mode of [ + "reactive-daemon-failed", + "reactive-daemon-failed-unsteered", +]) + test(`Antigravity keeps a failed daemon launch open in ${mode}`, async (t) => { + fixture(t); + process.env.LOOP_TEST_AGY_MODE = mode; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Start a daemon"); + await until(() => + events.some((e) => e.type === "delta" && e.text === "Daemon failed."), + ); + assert.deepEqual(statuses(events), ["ready"]); + }); + +for (const mode of [ + "reactive-steering", + "reactive-rejected-steer-late-tool", + "reactive-rejected-steer-settled-tool", + "reactive-rejected-steer-text-before-tool", + "reactive-echoed-steer-open-tool", + "reactive-inherited-steer-settled-tool", + "reactive-daemon-unechoed-steer-output", + "reactive-steer-daemon", + "reactive-daemon-failed-after-identification", + "reactive-daemon-output-before-tool", +]) + test(`Antigravity keeps accepting output after overlapping prompts in ${mode}`, async (t) => { + const requests = fixture(t); + process.env.LOOP_TEST_AGY_MODE = mode; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Run background work"); + await until(() => events.some((e) => e.type === "delta")); + if ( + mode.includes("rejected") || + mode.includes("unechoed") || + mode === "reactive-daemon-failed-after-identification" || + mode === "reactive-daemon-output-before-tool" + ) + await assert.rejects(adapter.steer!("Keep going"), /Steer rejected/); + else await adapter.steer!("Keep going"); + await until(() => + events.some((e) => e.type === "delta" && e.text === "Done."), + ); + assert.deepEqual(statuses(events), ["ready"]); + assert.deepEqual( + events.flatMap((e) => (e.type === "delta" ? [e.text] : [])), + mode === "reactive-daemon-unechoed-steer-output" || + mode === "reactive-daemon-output-before-tool" + ? ["Daemon started.", "Waiting.", "Done."] + : mode === "reactive-steer-daemon" || + mode === "reactive-daemon-failed-after-identification" + ? ["Daemon started.", "Done."] + : mode === "reactive-rejected-steer-text-before-tool" + ? ["Waiting.", "Still waiting.", "Done."] + : ["Waiting.", "Done."], + ); + assert.deepEqual(prompts(requests), ["Run background work", "Keep going"]); + }); + +for (const mode of [ + "reactive-sync-answer", + "reactive-sync-subagent", + "reactive-steered-sync-tool", + "reactive-steered-sync-open-at-first-end", + "reactive-steered-sync-before-echo", + "reactive-steered-sync-without-echo", +]) + test(`Antigravity handles an async-capable tool that settles before end_turn in ${mode}`, async (t) => { + fixture(t); + process.env.LOOP_TEST_AGY_MODE = mode; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Run background work"); + if (mode.startsWith("reactive-steered-sync")) + await adapter.steer!("Keep going"); + await until(() => + events.some((e) => e.type === "delta" && e.text === "Done."), + ); + await until(() => complete(events).length === 1); + assert.deepEqual( + events.flatMap((e) => (e.type === "delta" ? [e.text] : [])), + mode === "reactive-sync-subagent" ? ["Done."] : ["Waiting.", "Done."], + ); + }); + +test("Antigravity completes a synchronous tool-only turn at end_turn", async (t) => { + fixture(t); + process.env.LOOP_TEST_AGY_MODE = "reactive-tool-only"; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Run the tool"); + await until(() => complete(events).length === 1, 2000); +}); + +test("Antigravity keeps the first steer baseline across a second overlapping steer", async (t) => { + fixture(t); + process.env.LOOP_TEST_AGY_MODE = "reactive-overlapping-steers"; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Start work"); + await adapter.steer!("First steer"); + await until(() => + events.some((e) => e.type === "activity" && e.activity.id === "steer-tool"), + ); + await adapter.steer!("Second steer"); + await until(() => complete(events).length === 1, 2000); + assert.deepEqual(statuses(events), ["ready", "completed"]); +}); + +test("Antigravity retires the live session when a steering limit interrupts reactive work", async (t) => { + fixture(t); + process.env.LOOP_TEST_AGY_MODE = "reactive-steer-limit"; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Run background work"); + await assert.rejects(adapter.steer!("Keep going"), /max_tokens/); + assert.deepEqual(statuses(events), ["ready", "interrupted"]); + assert.equal(adapter.reusable, false); + assert.equal(adapter.canReuse({ ...options, version: "1.5.14" }), false); + await assert.rejects(adapter.prompt("Next turn"), /unavailable/); +}); + +test("Antigravity keeps accepting reactive output after echoing and acknowledging a steer", async (t) => { + fixture(t); + process.env.LOOP_TEST_AGY_MODE = "reactive-steer-ack"; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Run background work"); + await until(() => + events.some((e) => e.type === "delta" && e.text === "Waiting."), + ); + await adapter.steer!("Keep going"); + await until(() => + events.some((e) => e.type === "delta" && e.text === "Done."), + ); + assert.deepEqual(statuses(events), ["ready"]); + assert.deepEqual( + events.flatMap((e) => (e.type === "delta" ? [e.text] : [])), + ["Waiting.", "Acknowledged.", "Done."], + ); +}); + +for (const mode of [ + "reactive-stalled", + "reactive-stalled-steer", + "reactive-stalled-joined-steer", +]) + test( + `Antigravity bounds the wait for ${mode}`, + { timeout: 5000 }, + async (t) => { + fixture(t); + process.env.LOOP_TEST_AGY_MODE = mode; + const events: AdapterEvent[] = []; + let endPrompt!: () => void; + const promptEnded = new Promise((resolve) => { + endPrompt = resolve; + }); + const adapter = new Antigravity( + { ...options, version: "1.5.14" }, + (e) => { + events.push(e); + if (e.type === "usage") endPrompt(); + }, + ); + t.after(() => adapter.dispose()); + await adapter.start(); + t.mock.timers.enable({ apis: ["setTimeout"] }); + try { + await adapter.prompt("Run background work"); + if (mode === "reactive-stalled-joined-steer") + await adapter.steer!("Keep going"); + await promptEnded; + if (mode === "reactive-stalled-steer") + await adapter.steer!("Keep going"); + t.mock.timers.tick(60_000); + assert.deepEqual(statuses(events), ["ready"]); + t.mock.timers.tick(59 * 60_000); + assert.deepEqual(statuses(events), ["ready", "interrupted"]); + assert.equal(adapter.reusable, false); + } finally { + t.mock.timers.reset(); + } + }, + ); + +test("Antigravity cancels a reactive turn with an outstanding steering request", async (t) => { + const requests = fixture(t); + process.env.LOOP_TEST_AGY_MODE = "reactive-stalled-steer"; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Run background work"); + await until(() => events.some((e) => e.type === "usage")); + await adapter.steer!("Keep going"); + await adapter.cancel(); + await until(() => requests().some((r) => r.acp === "session/cancel")); + assert.deepEqual(statuses(events), ["ready", "interrupted"]); + assert.equal(adapter.reusable, false); +}); + +test("Antigravity preserves a reactive continuation when an echoed steer later rejects", async (t) => { + fixture(t); + process.env.LOOP_TEST_AGY_MODE = "reactive-reject-joined"; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Start work"); + await until(() => events.some((e) => e.type === "usage")); + await adapter.steer!("Keep going"); + await until(() => + events.some((e) => e.type === "delta" && e.text === "Done."), + ); + assert.deepEqual(statuses(events), ["ready"]); +}); + +test("Antigravity interrupts when cancellation rejects an unjoined steer after end_turn", async (t) => { + fixture(t); + process.env.LOOP_TEST_AGY_MODE = "reactive-cancel-unjoined-steer"; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Start work"); + const rejected = assert.rejects( + adapter.steer!("Keep going"), + /Steer rejected/, + ); + await until(() => events.some((e) => e.type === "usage")); + await adapter.cancel(); + await rejected; + assert.deepEqual(statuses(events), ["ready", "interrupted"]); +}); + +test("Antigravity interrupts an unanswered acknowledged steer on cancellation", async (t) => { + fixture(t); + process.env.LOOP_TEST_AGY_MODE = "reactive-stalled-joined-steer"; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Start work"); + await adapter.steer!("Keep going"); + await until(() => events.some((e) => e.type === "usage")); + await adapter.cancel(); + assert.deepEqual(statuses(events), ["ready", "interrupted"]); + assert.equal(adapter.reusable, false); +}); + +for (const mode of [ + "reactive-approval-at-first-end", + "reactive-steer-owned-approval", +]) + test(`Antigravity handles an approval spanning the original end_turn in ${mode}`, async (t) => { + fixture(t); + process.env.LOOP_TEST_AGY_MODE = mode; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Start work"); + const steer = adapter.steer!("Keep going"); + await until(() => events.some((e) => e.type === "usage")); + const approval = events.find((e) => e.type === "request")!; + await adapter.answer(approval.request.id, { choice: "allow" }); + await steer; + await until(() => + events.some((e) => e.type === "delta" && e.text === "Done."), + ); + if (mode === "reactive-steer-owned-approval") + await until(() => complete(events).length === 1, 2000); + assert.deepEqual( + statuses(events), + mode === "reactive-steer-owned-approval" + ? ["ready", "completed"] + : ["ready"], + ); + }); + +test("Antigravity reports interruption before a blocked cancel notification settles", async (t) => { + fixture(t); + process.env.LOOP_TEST_AGY_MODE = "reactive-stalled"; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Run background work"); + await until(() => events.some((e) => e.type === "usage")); + let deliver!: () => void; + t.mock.method( + ClientSideConnection.prototype, + "cancel", + () => + new Promise((resolve) => { + deliver = resolve; + }), + ); + const cancelled = adapter.cancel(); + try { + assert.deepEqual(statuses(events), ["ready", "interrupted"]); + assert.equal(adapter.reusable, false); + } finally { + deliver(); + await cancelled; + } +}); + +test( + "Antigravity pauses the reactive budget during approval and resumes with the remaining time", + { timeout: 5000 }, + async (t) => { + fixture(t); + process.env.LOOP_TEST_AGY_MODE = "reactive-budget"; + const events: AdapterEvent[] = []; + let endPrompt!: () => void; + const promptEnded = new Promise((resolve) => { + endPrompt = resolve; + }); + let requestApproval!: (id: string) => void; + const approval = new Promise((resolve) => { + requestApproval = resolve; + }); + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => { + events.push(e); + if (e.type === "usage") endPrompt(); + if (e.type === "request") requestApproval(e.request.id); + }); + t.after(() => adapter.dispose()); + await adapter.start(); + t.mock.timers.enable({ apis: ["setTimeout", "Date"] }); + t.mock.method(performance, "now", () => Date.now()); + try { + await adapter.prompt("Run background work"); + await promptEnded; + t.mock.timers.tick(59 * 60_000); + await adapter.steer!("Keep going"); + const decisionId = await approval; + t.mock.timers.tick(60 * 60_000); + assert.deepEqual(statuses(events), ["ready"]); + await adapter.answer(decisionId, { choice: "allow" }); + t.mock.timers.tick(5_000); + assert.deepEqual(statuses(events), ["ready"]); + t.mock.timers.tick(55_000); + assert.deepEqual(statuses(events), ["ready", "interrupted"]); + } finally { + t.mock.timers.reset(); + } + }, +); + +for (const mode of ["reactive-reordered", "reactive-final-usage"]) + test( + `Antigravity preserves partial output and interrupts in ${mode}`, + { timeout: 5000 }, + async (t) => { + const requests = fixture(t); + process.env.LOOP_TEST_AGY_MODE = mode; + const events: AdapterEvent[] = []; + let settle!: () => void; + const settled = new Promise((resolve) => { + settle = resolve; + }); + const adapter = new Antigravity( + { ...options, version: "1.5.14" }, + (e) => { + events.push(e); + if ( + e.type === "activity" && + e.activity.kind === "tool" && + e.activity.id === "background" && + e.activity.patch.status === "completed" + ) + settle(); + }, + ); + t.after(() => adapter.dispose()); + await adapter.start(); + t.mock.timers.enable({ apis: ["setTimeout"] }); + try { + await adapter.prompt("Run background work"); + await settled; + assert.deepEqual(statuses(events), ["ready"]); + t.mock.timers.tick(5_000); + assert.deepEqual(statuses(events), ["ready"]); + t.mock.timers.tick(55_000); + assert.deepEqual(statuses(events), ["ready", "interrupted"]); + assert.equal(adapter.reusable, false); + } finally { + t.mock.timers.reset(); + } + await until(() => requests().some((r) => r.acp === "session/cancel")); + }, + ); + +for (const stop of ["cancel", "dispose"] as const) + test(`Antigravity ${stop} can stop a turn waiting for a reactive wakeup`, async (t) => { + const requests = fixture(t); + process.env.LOOP_TEST_AGY_MODE = "reactive-stalled"; + const events: AdapterEvent[] = []; + const adapter = new Antigravity({ ...options, version: "1.5.14" }, (e) => + events.push(e), + ); + t.after(() => adapter.dispose()); + await adapter.start(); + await adapter.prompt("Wait for background work"); + await until(() => events.some((e) => e.type === "usage")); + assert.deepEqual(statuses(events), ["ready"]); + await adapter[stop](); + if (stop === "cancel") { + await until(() => requests().some((r) => r.acp === "session/cancel")); + assert.deepEqual(statuses(events), ["ready", "interrupted"]); + assert.equal(adapter.reusable, false); + } else { + assert.deepEqual(statuses(events), ["ready"]); + } + }); + for (const version of ["1.5.2", "1.5.9"]) test(`Antigravity ${version} waits for delayed discovery before framing a slash-leading steer`, async (t) => { const requests = fixture(t); diff --git a/test/fixtures/fake-antigravity-steering.mjs b/test/fixtures/fake-antigravity-steering.mjs index 0f56cc0f..8cd343e6 100755 --- a/test/fixtures/fake-antigravity-steering.mjs +++ b/test/fixtures/fake-antigravity-steering.mjs @@ -127,6 +127,348 @@ const finish = (sessionId, stopReason = "end_turn") => { }; let permission = 0; const permissions = new Map(); +let endReactiveSteer; +let rejectSteerOnCancel; + +function reactiveTurn(sessionId, mode) { + const tool = (toolCallId, rawInput, title = toolCallId) => + update(sessionId, { + sessionUpdate: "tool_call", + toolCallId, + title, + status: "in_progress", + rawInput, + }); + const complete = (toolCallId, status = "completed", rawInput) => + update(sessionId, { + sessionUpdate: "tool_call_update", + toolCallId, + status, + rawInput, + }); + const message = (text) => + update(sessionId, { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text }, + }); + const reportUsage = () => + update(sessionId, { sessionUpdate: "usage_update", used: 20, size: 100 }); + + if (mode === "reactive-overlapping-steers") { + const echoSteer = (request) => + update(sessionId, { + sessionUpdate: "user_message_chunk", + content: { type: "text", text: request.params.prompt[0].text }, + }); + message("Waiting."); + endReactiveSteer = (first) => { + echoSteer(first); + tool("steer-tool", {}, "Synchronous tool"); + endReactiveSteer = (second) => { + echoSteer(second); + finish(sessionId); + complete("steer-tool"); + reply(first.id, { stopReason: "end_turn" }); + message("Done."); + reply(second.id, { stopReason: "end_turn" }); + }; + }; + return; + } + if ( + mode === "reactive-cancel-unjoined-steer" || + mode === "reactive-approval-at-first-end" || + mode === "reactive-steer-owned-approval" + ) { + message("Waiting."); + endReactiveSteer = (request) => { + if (mode === "reactive-cancel-unjoined-steer") { + finish(sessionId); + rejectSteerOnCancel = () => + send({ + id: request.id, + error: { code: -32603, message: "Steer rejected" }, + }); + return; + } + const id = `perm-${++permission}`; + permissions.set(id, () => { + if (mode === "reactive-steer-owned-approval") { + message("Done."); + reply(request.id, { stopReason: "end_turn" }); + return; + } + reply(request.id, { stopReason: "end_turn" }); + setTimeout(() => message("Done."), 30); + }); + if (mode === "reactive-steer-owned-approval") + update(sessionId, { + sessionUpdate: "user_message_chunk", + content: { type: "text", text: request.params.prompt[0].text }, + }); + send({ + id, + method: "session/request_permission", + params: { + sessionId, + toolCall: { toolCallId: "approval-only", title: "Reactive approval" }, + options: [ + { optionId: "allow", name: "Allow once", kind: "allow_once" }, + ], + }, + }); + finish(sessionId); + }; + return; + } + if (mode === "reactive-steered-sync-without-echo") { + message("Waiting."); + endReactiveSteer = (request) => { + finish(sessionId); + message("Done."); + reply(request.id, { stopReason: "end_turn" }); + }; + return; + } + if ( + [ + "reactive-rejected-steer-late-tool", + "reactive-rejected-steer-settled-tool", + "reactive-echoed-steer-open-tool", + "reactive-steered-sync-tool", + "reactive-steered-sync-open-at-first-end", + "reactive-steered-sync-before-echo", + "reactive-inherited-steer-settled-tool", + "reactive-rejected-steer-text-before-tool", + ].includes(mode) + ) { + const inherited = mode === "reactive-inherited-steer-settled-tool"; + const beforeEcho = mode === "reactive-steered-sync-before-echo"; + const startTool = () => + tool("late-background", { CommandLine: "sleep 5" }, "sleep 5"); + if (inherited) startTool(); + message("Waiting."); + endReactiveSteer = (request) => { + const synchronous = mode.startsWith("reactive-steered-sync"); + const joined = + synchronous || inherited || mode === "reactive-echoed-steer-open-tool"; + if (beforeEcho) { + finish(sessionId); + startTool(); + } + if (joined) + update(sessionId, { + sessionUpdate: "user_message_chunk", + content: { type: "text", text: request.params.prompt[0].text }, + }); + if (mode === "reactive-steered-sync-open-at-first-end") startTool(); + if (!beforeEcho) finish(sessionId); + if (mode === "reactive-rejected-steer-text-before-tool") + message("Still waiting."); + else if ( + !beforeEcho && + !inherited && + mode !== "reactive-steered-sync-open-at-first-end" + ) + startTool(); + if ( + synchronous || + inherited || + mode === "reactive-rejected-steer-settled-tool" + ) + complete("late-background"); + if (synchronous) message("Done."); + if (joined) reply(request.id, { stopReason: "end_turn" }); + else + send({ + id: request.id, + error: { code: -32603, message: "Steer rejected" }, + }); + setTimeout(() => { + if (synchronous) return; + if (mode === "reactive-rejected-steer-text-before-tool") startTool(); + if (!inherited && mode !== "reactive-rejected-steer-settled-tool") + complete("late-background"); + message("Done."); + reportUsage(); + }, 30); + }; + return; + } + if ( + [ + "reactive-steer-daemon", + "reactive-daemon-unechoed-steer-output", + "reactive-daemon-failed", + "reactive-daemon-failed-unsteered", + "reactive-daemon-failed-after-identification", + "reactive-daemon-output-before-tool", + ].includes(mode) + ) { + if (mode !== "reactive-daemon-output-before-tool") + tool("daemon", undefined, "sleep 90"); + message("Daemon started."); + const identifyDaemon = () => { + finish(sessionId); + if (mode === "reactive-daemon-output-before-tool") message("Waiting."); + if (mode === "reactive-daemon-output-before-tool") + tool("daemon", undefined, "sleep 90"); + update(sessionId, { + sessionUpdate: "tool_call_update", + toolCallId: "daemon", + status: mode === "reactive-daemon-failed" ? "failed" : "in_progress", + rawInput: { CommandLine: "sleep 90", IsDaemon: true }, + }); + }; + if ( + mode === "reactive-daemon-failed" || + mode === "reactive-daemon-failed-unsteered" + ) { + identifyDaemon(); + setTimeout(() => { + if (mode === "reactive-daemon-failed-unsteered") + complete("daemon", "failed"); + message("Daemon failed."); + }, 30); + } else + endReactiveSteer = (request) => { + identifyDaemon(); + if (mode === "reactive-daemon-failed-after-identification") { + complete("daemon", "failed"); + setTimeout(() => message("Done."), 30); + } + if (mode === "reactive-daemon-output-before-tool") + setTimeout(() => message("Done."), 30); + if (mode === "reactive-daemon-unechoed-steer-output") { + message("Waiting."); + setTimeout(() => message("Done."), 30); + } + if (mode !== "reactive-steer-daemon") + send({ + id: request.id, + error: { code: -32603, message: "Steer rejected" }, + }); + else { + update(sessionId, { + sessionUpdate: "user_message_chunk", + content: { type: "text", text: request.params.prompt[0].text }, + }); + message("Done."); + reply(request.id, { stopReason: "end_turn" }); + } + }; + return; + } + if (mode === "reactive-sync-subagent") { + tool("subagent", {}, "invoke_subagent"); + complete("subagent"); + message("Done."); + finish(sessionId); + return; + } + tool("daemon", { CommandLine: "sleep 90", IsDaemon: true }, "sleep 90"); + if (mode !== "daemon-only" && mode !== "reactive-stalled-joined-steer") + tool( + "background", + { + CommandLine: "sleep 5", + IsDaemon: false, + WaitMsBeforeAsync: 500, + }, + "run_command", + ); + message(mode === "daemon-only" ? "Daemon started." : "Waiting."); + reportUsage(); + if (["reactive-sync-answer", "reactive-tool-only"].includes(mode)) { + complete("background", "completed", { + CommandLine: "sleep 5", + WaitMsBeforeAsync: 500, + }); + if (mode === "reactive-sync-answer") message("Done."); + finish(sessionId); + return; + } + if (mode === "reactive-steer-limit") { + endReactiveSteer = (request) => { + finish(sessionId); + reply(request.id, { stopReason: "max_tokens" }); + }; + return; + } + if (mode === "reactive-stalled-joined-steer") { + endReactiveSteer = (request) => { + update(sessionId, { + sessionUpdate: "user_message_chunk", + content: { type: "text", text: request.params.prompt[0].text }, + }); + tool("background", { CommandLine: "sleep 5" }, "sleep 5"); + finish(sessionId); + }; + return; + } + if (mode === "reactive-steering" || mode === "reactive-steer-ack") { + endReactiveSteer = (request) => { + finish(sessionId); + complete("background"); + if (mode === "reactive-steer-ack") { + update(sessionId, { + sessionUpdate: "user_message_chunk", + content: { type: "text", text: request.params.prompt[0].text }, + }); + message("Acknowledged."); + reportUsage(); // This usage precedes the still-open steering response. + } + reply(request.id, { stopReason: "end_turn" }); + if (mode === "reactive-steer-ack") reportUsage(); + setTimeout(() => { + message("Done."); + reportUsage(); + }, 30); + }; + return; + } + finish(sessionId); + if (mode === "reactive-reordered" || mode === "reactive-final-usage") { + setTimeout(() => { + message("Done."); + if (mode === "reactive-reordered") reportUsage(); + complete("background"); + if (mode === "reactive-final-usage") reportUsage(); + }, 30); + return; + } + if (mode !== "reactive") return; + + reportUsage(); // Even a usage update following end_turn leaves open work. + setTimeout(() => { + complete("background"); + tool("subagent", {}, "invoke_subagent"); + message("Waiting again."); + reportUsage(); + setTimeout(() => { + complete("subagent", "failed"); + tool("follow-up", {}); + const id = `perm-${++permission}`; + permissions.set(id, (result) => { + if (result.outcome.outcome !== "selected") return; + message("Done."); + complete("follow-up"); + reportUsage(); + }); + send({ + id, + method: "session/request_permission", + params: { + sessionId, + toolCall: { toolCallId: "follow-up", title: "Reactive approval" }, + options: [ + { optionId: "allow", name: "Allow once", kind: "allow_once" }, + ], + }, + }); + }, 30); + }, 30); +} createInterface({ input: process.stdin }).on("line", (line) => { const req = JSON.parse(line); @@ -180,10 +522,66 @@ createInterface({ input: process.stdin }).on("line", (line) => { case "session/close": return reply(req.id, {}); case "session/cancel": + if (rejectSteerOnCancel) { + const reject = rejectSteerOnCancel; + rejectSteerOnCancel = undefined; + return reject(); + } return finish(sessionId, "cancelled"); case "session/prompt": { const text = req.params.prompt[0].text; + if ( + turn === 1 && + [ + "reactive-stalled-steer", + "reactive-budget", + "reactive-reject-joined", + ].includes(mode) + ) { + update(sessionId, { + sessionUpdate: "user_message_chunk", + content: { type: "text", text }, + }); + if (mode === "reactive-reject-joined") { + send({ + id: req.id, + error: { code: -32603, message: "Steer rejected" }, + }); + setTimeout(() => { + update(sessionId, { + sessionUpdate: "tool_call_update", + toolCallId: "background", + status: "completed", + }); + update(sessionId, { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Done." }, + }); + }, 30); + } + if (mode === "reactive-budget") + send({ + id: `perm-${++permission}`, + method: "session/request_permission", + params: { + sessionId, + toolCall: { + toolCallId: "background", + title: "Reactive approval", + }, + options: [ + { optionId: "allow", name: "Allow once", kind: "allow_once" }, + ], + }, + }); + return; + } if (open.length) { + if (endReactiveSteer) { + const finishSteering = endReactiveSteer; + endReactiveSteer = undefined; + return finishSteering(req); + } // A prompt during a running turn steers it. if (mode === "steer-limit") { // No echo, and the turn stops at a limit. @@ -280,6 +678,8 @@ createInterface({ input: process.stdin }).on("line", (line) => { 300, ); } else echo(); + if (outcome()?.startsWith("reactive") || outcome() === "daemon-only") + return reactiveTurn(sessionId, outcome()); if (outcome() === "hang") return; if (text.includes("[slow]")) { update(sessionId, {