From 3a3c786d57241a047b0fab33d4f26e5c8e9b2dc1 Mon Sep 17 00:00:00 2001 From: Lakshmi Tanmay Date: Mon, 2 Nov 2026 14:18:06 +0530 Subject: [PATCH 1/5] fix(server): load Antigravity project and global rules --- apps/server/scripts/acp-mock-agent.ts | 14 ++ .../Adapters/AcpAdapterV2.test.ts | 110 ++++++++++ .../Adapters/AntigravityAdapterV2.test.ts | 201 ++++++++++++----- .../Adapters/AntigravityAdapterV2.ts | 18 +- .../src/provider/Drivers/AntigravityDriver.ts | 1 + .../acp/AntigravityInstructions.test.ts | 31 +++ .../provider/acp/AntigravityInstructions.ts | 60 +++++ packages/provider-acp/src/server/adapter.ts | 206 ++++++++++++------ 8 files changed, 523 insertions(+), 118 deletions(-) create mode 100644 apps/server/src/provider/acp/AntigravityInstructions.test.ts create mode 100644 apps/server/src/provider/acp/AntigravityInstructions.ts diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index a97aab9cdf2b1..d00c4f3b2a19d 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -60,6 +60,7 @@ const agentVersion = process.env.T3_ACP_AGENT_VERSION ?? "0.0.0"; const geminiApiKey = process.env.GEMINI_API_KEY; const idleError = process.env.T3_ACP_IDLE_ERROR; const emitTrackedToolCallKindThenHang = process.env.T3_ACP_EMIT_TRACKED_TOOL_CALL_KIND_THEN_HANG; +const resumeReadPath = process.env.T3_ACP_RESUME_READ_PATH; const clientFsProbePath = process.env.T3_ACP_CLIENT_FS_PROBE_PATH; const clientFsProbeLogPath = process.env.T3_ACP_CLIENT_FS_PROBE_LOG_PATH; const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); @@ -642,6 +643,19 @@ const program = Effect.gen(function* () { yield* agent.handleResumeSession((request) => Effect.gen(function* () { yield* requireAuthentication(); + if (resumeReadPath !== undefined) { + const read = yield* agent.raw.request("fs/read_text_file", { + sessionId: request.sessionId, + path: resumeReadPath, + }); + yield* agent.client.sessionUpdate({ + sessionId: request.sessionId, + update: { + sessionUpdate: "user_message_chunk", + content: { type: "text", text: `native-resume-read:${encodeJson(read)}` }, + }, + }); + } yield* agent.client.sessionUpdate({ sessionId: request.sessionId, update: { diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 02d6f64c0be66..7086b1acc6d11 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -5640,6 +5640,116 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("preserves the workspace runtime on background work or failed reactivation", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceB = yield* fs.makeTempDirectoryScoped(); + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const instanceId = ProviderInstanceId.make("acp-workspace-reactivation"); + let applyMutation: AcpAdapterV2ExtensionContext["applyBackgroundTaskMutation"] | undefined; + const inputs: Array = []; + const nativeRuntime = makeMockRuntime({ childProcessSpawner, mockAgentPath }); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + replaceRuntimeOnActivation: () => true, + enablePostSettleContinuation: true, + registerExtensions: (context) => + Effect.sync(() => { + applyMutation = context.applyBackgroundTaskMutation; + }), + makeRuntime: (input): ReturnType => { + inputs.push(input); + if (inputs.length === 2) + return Effect.fail( + new EffectAcpErrors.AcpTransportError({ + detail: "Fixture activation failure", + cause: null, + }), + ); + return nativeRuntime(input).pipe( + Effect.map((candidate) => + inputs.length === 3 + ? { + ...candidate, + start: () => + candidate.start().pipe( + Effect.tap(() => + originalMutation({ + sessionId, + taskId: "late-workspace-task", + status: "running", + }), + ), + ), + } + : candidate, + ), + ); + }, + }, + continuationRequests: { offer: () => Effect.void }, + }); + const threadId = ThreadId.make("thread-workspace-reactivation"); + const modelSelection = { instanceId, model: "default" } as const; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const runtime = yield* adapter.openSession({ + threadId, + modelSelection, + runtimePolicy, + providerSessionId: ProviderSessionId.make("session-workspace-reactivation"), + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + if (applyMutation === undefined) return yield* Effect.die("Expected background task handler"); + const originalMutation = applyMutation; + const sessionId = "mock-session-1"; + assert.equal(providerThread.nativeThreadRef?.nativeId, sessionId); + yield* originalMutation({ sessionId, taskId: "workspace-task", status: "running" }); + const nextPolicy = { ...runtimePolicy, cwd: workspaceB }; + const resume = () => + runtime.resumeThread({ providerThread, modelSelection, runtimePolicy: nextPolicy }); + const busy = yield* Effect.exit(resume()); + assert.isTrue(Exit.isFailure(busy)); + if (Exit.isFailure(busy)) + assert.include(Cause.pretty(busy.cause), "background work is running"); + assert.lengthOf(inputs, 1); + assert.isTrue(yield* runtime.hasPendingBackgroundWork!); + yield* originalMutation({ sessionId, taskId: "workspace-task", status: "completed" }); + assert.isFalse(yield* runtime.hasPendingBackgroundWork!); + assert.isTrue(Exit.isFailure(yield* Effect.exit(resume()))); + const unchanged = yield* runtime.readThreadSnapshot({ providerThread }); + assert.equal(unchanged.providerThread.nativeThreadRef?.nativeId, sessionId); + assert.isTrue(Exit.isFailure(yield* Effect.exit(resume()))); + assert.isTrue(yield* runtime.hasPendingBackgroundWork!); + yield* originalMutation({ sessionId, taskId: "late-workspace-task", status: "completed" }); + yield* resume(); + assert.deepEqual( + inputs.map((input) => [input.cwd, input.runtimePolicy.cwd, input.resumeSessionId]), + [ + [runtimePolicy.cwd, runtimePolicy.cwd, undefined], + [workspaceB, workspaceB, sessionId], + [workspaceB, workspaceB, sessionId], + [workspaceB, workspaceB, sessionId], + ], + ); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + it.effect("replaces the ACP session and clears conversation state on rollback", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index b281ecc16ab84..05c914843c31b 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -44,6 +44,7 @@ import { } from "./AntigravityAdapterV2.ts"; const flavor = makeAntigravityAcpAdapterFlavor({ + userHome: process.cwd(), instanceId: ProviderInstanceId.make("antigravity-test"), random: undefined as never, fileSystem: undefined as never, @@ -163,6 +164,7 @@ describe("AntigravityAdapterV2 compaction", () => { const startupMilestone = yield* Deferred.make(); const consumeStartupCommands = yield* Deferred.make(); const adapter = yield* makeAntigravityAdapterV2({ + userHome: process.cwd(), instanceId, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => @@ -245,6 +247,7 @@ describe("AntigravityAdapterV2 session open", () => { Effect.gen(function* () { const instanceId = ProviderInstanceId.make("antigravity-sign-in-test"); const adapter = yield* makeAntigravityAdapterV2({ + userHome: process.cwd(), instanceId, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: () => Effect.fail(cause), @@ -293,6 +296,7 @@ describe("AntigravityAdapterV2 client file system", () => { const crypto = yield* SecureRandom.SecureRandom; const instanceId = ProviderInstanceId.make("antigravity-containment-test"); const adapter = yield* makeAntigravityAdapterV2({ + userHome: process.cwd(), instanceId, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => @@ -433,6 +437,9 @@ describe("AntigravityAdapterV2 workspace changes", () => { type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; const promptReceived = yield* Deferred.make[0]>(); const host = yield* ProviderHost.ProviderHost; + const logs = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-workspace-log-" }); + const requestLog = path.join(logs, "requests.ndjson"); + const constructions: Array<{ cwd: string; policyCwd: string | null }> = []; const document = ChatFileAttachment.make({ type: "file", id: "native-pdf", @@ -445,26 +452,36 @@ describe("AntigravityAdapterV2 workspace changes", () => { let readTextFile: Parameters[0] | undefined; const instanceId = ProviderInstanceId.make("antigravity-workspace-change-test"); const adapter = yield* makeAntigravityAdapterV2({ + userHome: process.cwd(), instanceId, selfInvocation: yield* resolveSelfInvocation(), - makeRuntime: (input) => - makeAntigravityAcpRuntime({ + makeRuntime: (input) => { + constructions.push({ cwd: input.cwd, policyCwd: input.runtimePolicy.cwd }); + return makeAntigravityAcpRuntime({ ...input, childProcessSpawner, spawn: { command: process.execPath, args: [mockAgentPath], cwd: input.cwd, - env: { T3_ACP_ANTIGRAVITY: "1", T3_ACP_HANG_PROMPT_FOREVER: "1" }, + env: { + T3_ACP_ANTIGRAVITY: "1", + T3_ACP_AGENT_VERSION: "1.4.5", + T3_ACP_SESSION_LIFECYCLE: "1", + T3_ACP_RESUME_READ_PATH: path.join(input.cwd, "b.txt"), + T3_ACP_REQUEST_LOG_PATH: requestLog, + T3_ACP_HANG_PROMPT_FOREVER: constructions.length === 1 ? "0" : "1", + }, }, }).pipe( Effect.provideService(SecureRandom.SecureRandom, crypto), Effect.map((runtime): RuntimeService => ({ ...runtime, prompt: (request) => - Deferred.succeed(promptReceived, request).pipe( - Effect.andThen(runtime.prompt(request)), - ), + (constructions.length === 1 + ? Effect.void + : Deferred.succeed(promptReceived, request) + ).pipe(Effect.andThen(runtime.prompt(request))), start: () => runtime.start().pipe( Effect.map((started) => ({ @@ -483,7 +500,8 @@ describe("AntigravityAdapterV2 workspace changes", () => { readTextFile = handler; }).pipe(Effect.andThen(runtime.handleReadTextFile(handler))), })), - ), + ); + }, withProcess: (_stop, task) => task, defaultModel: Effect.undefined, }); @@ -491,6 +509,13 @@ describe("AntigravityAdapterV2 workspace changes", () => { const workspaceB = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-b-" }); yield* fileSystem.writeFileString(path.join(workspaceA, "a.txt"), "from a"); yield* fileSystem.writeFileString(path.join(workspaceB, "b.txt"), "from b"); + for (const [workspace, marker] of [ + [workspaceA, "WORKSPACE_A"], + [workspaceB, "WORKSPACE_B"], + ] as const) { + yield* fileSystem.writeFileString(path.join(workspace, "AGENTS.md"), `${marker}_AGENTS`); + yield* fileSystem.writeFileString(path.join(workspace, "GEMINI.md"), `${marker}_GEMINI`); + } const policyFor = (cwd: string) => ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", @@ -511,54 +536,106 @@ describe("AntigravityAdapterV2 workspace changes", () => { runtimePolicy: policyFor(workspaceA), }); const now = yield* DateTime.now; - yield* session - .startTurn({ - appThread: { - createdBy: "user", - creationSource: "web", - id: threadId, - projectId: ProjectId.make("project-antigravity-workspace-change"), - title: "Antigravity workspace change", - providerInstanceId: instanceId, - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: workspaceB, - activeProviderThreadId: providerThread.id, - lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, - forkedFrom: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - lastVisitedAt: null, - deletedAt: null, - }, - threadId, - runId: RunId.make("run-antigravity-workspace-change"), - runOrdinal: 1, - providerTurnOrdinal: 1, - attemptId: RunAttemptId.make("attempt-antigravity-workspace-change"), - rootNodeId: NodeId.make("node-antigravity-workspace-change"), - providerThread, - message: { - createdBy: "user", - creationSource: "web", - messageId: MessageId.make("message-antigravity-workspace-change"), - text: "read b.txt", - attachments: [document], - }, + const turnInput: ProviderAdapter.ProviderAdapterV2TurnInput = { + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-workspace-change"), + title: "Antigravity workspace change", + providerInstanceId: instanceId, modelSelection, - runtimePolicy: policyFor(workspaceB), - }) - .pipe(Effect.forkScoped); + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: workspaceB, + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make("run-antigravity-workspace-change"), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: RunAttemptId.make("attempt-antigravity-workspace-change"), + rootNodeId: NodeId.make("node-antigravity-workspace-change"), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-antigravity-workspace-change"), + text: "read b.txt", + attachments: [document], + }, + modelSelection, + runtimePolicy: policyFor(workspaceB), + }; + yield* session.startTurn({ + ...turnInput, + appThread: { ...turnInput.appThread, worktreePath: workspaceA }, + runtimePolicy: policyFor(workspaceA), + runId: RunId.make("run-antigravity-workspace-a"), + attemptId: RunAttemptId.make("attempt-antigravity-workspace-a"), + rootNodeId: NodeId.make("node-antigravity-workspace-a"), + message: { + ...turnInput.message, + messageId: MessageId.make("message-antigravity-workspace-a"), + text: "remember workspace A", + }, + }); + yield* session.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.runHead, + ); + yield* session.startTurn({ ...turnInput, runOrdinal: 2, providerTurnOrdinal: 2 }); yield* session.events.pipe( Stream.filter((event) => event.type === "provider_turn.updated"), Stream.runHead, ); const sent = yield* Deferred.await(promptReceived); + const requests = (yield* fileSystem.readFileString(requestLog)) + .trim() + .split("\n") + .map( + (line) => + JSON.parse(line) as { + method: string; + params: { sessionId?: string; cwd?: string; _meta?: unknown }; + }, + ); + const setup = requests.filter((request) => + ["session/new", "session/load", "session/resume"].includes(request.method), + ); + assert.deepEqual(constructions, [ + { cwd: workspaceA, policyCwd: workspaceA }, + { cwd: workspaceB, policyCwd: workspaceB }, + ]); + assert.deepEqual( + setup.map((request) => request.method), + ["session/new", "session/resume"], + ); + assert.equal(setup[1]?.params.sessionId, providerThread.nativeThreadRef?.nativeId); + assert.equal(setup[1]?.params.cwd, workspaceB); + const originalRules = JSON.stringify(setup[0]?.params._meta); + const refreshedRules = JSON.stringify(setup[1]?.params._meta); + assert.include(originalRules, "WORKSPACE_A_AGENTS"); + assert.include(originalRules, "WORKSPACE_A_GEMINI"); + assert.include(refreshedRules, "WORKSPACE_B_AGENTS"); + assert.include(refreshedRules, "WORKSPACE_B_GEMINI"); + assert.notInclude(refreshedRules, "WORKSPACE_A"); + assert.notInclude(JSON.stringify(sent.prompt), "WORKSPACE_A"); + const snapshot = yield* session.readThreadSnapshot({ providerThread }); + assert.include(JSON.stringify(snapshot), "native-resume-started"); + assert.include(JSON.stringify(snapshot), "native-resume-read:"); + assert.include(JSON.stringify(snapshot), "from b"); + assert.include(JSON.stringify(snapshot), "remember workspace A"); assert.deepEqual( sent.prompt.filter((block) => block.type === "resource_link"), [ @@ -615,6 +692,7 @@ describe("AntigravityAdapterV2 html_render pages", () => { const failed = { ...report, html: "

Revenue

" }; const errored = { ...report, html: "

Revenue error

" }; const adapter = yield* makeAntigravityAdapterV2({ + userHome: process.cwd(), instanceId, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => @@ -899,6 +977,7 @@ describe("AntigravityAdapterV2 subagent reads", () => { const instanceId = ProviderInstanceId.make("antigravity-subagent-reads-test"); const threadId = ThreadId.make("thread-antigravity-subagent-reads"); const adapter = yield* makeAntigravityAdapterV2({ + userHome: process.cwd(), instanceId, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => @@ -1091,6 +1170,7 @@ describe("AntigravityAdapterV2 runtime mode ceiling", () => { const modesSet: Array = []; const instanceId = ProviderInstanceId.make("antigravity-ceiling-test"); const adapter = yield* makeAntigravityAdapterV2({ + userHome: process.cwd(), instanceId, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => @@ -1145,7 +1225,7 @@ describe("AntigravityAdapterV2 runtime mode ceiling", () => { }); describe("AntigravityAdapterV2 session system prompt", () => { - it.effect.each(["1.4.5", "1.4.1"])( + it.effect.each(["1.4.5", "1.4.1", "1.5.1"])( "carries PR linking once in the %s session setup or once per turn", (agentVersion) => Effect.gen(function* () { @@ -1161,8 +1241,10 @@ describe("AntigravityAdapterV2 session system prompt", () => { type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; const promptReceived = yield* Deferred.make[0]>(); const instanceId = ProviderInstanceId.make("antigravity-system-prompt-test"); + const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-home-" }); const adapter = yield* makeAntigravityAdapterV2({ instanceId, + userHome: home, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => makeAntigravityAcpRuntime({ @@ -1193,6 +1275,19 @@ describe("AntigravityAdapterV2 session system prompt", () => { defaultModel: Effect.undefined, }); const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-sp-" }); + yield* fileSystem.makeDirectory(path.join(home, ".gemini")); + yield* fileSystem.writeFileString( + path.join(home, ".gemini", "GEMINI.md"), + "GLOBAL_RULE_28704: Use global conventions.", + ); + yield* fileSystem.writeFileString( + path.join(workspace, "AGENTS.md"), + "PROJECT_RULE_28704: Use repository conventions.", + ); + yield* fileSystem.writeFileString( + path.join(workspace, "GEMINI.md"), + "GEMINI_RULE_28704: Use Gemini conventions.", + ); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", interactionMode: "default", @@ -1266,6 +1361,12 @@ describe("AntigravityAdapterV2 session system prompt", () => { assert.include(sent, "through the Antigravity harness, as gemini-test-low"); if (agentVersion === "1.4.5") { assert.include(append, "pull_request_linking"); + assert.include(append, "GLOBAL_RULE_28704"); + assert.include(append, "PROJECT_RULE_28704"); + assert.include(append, "GEMINI_RULE_28704"); + assert.isBelow(append.indexOf("GLOBAL_RULE_28704"), append.indexOf("PROJECT_RULE_28704")); + assert.isBelow(append.indexOf("PROJECT_RULE_28704"), append.indexOf("GEMINI_RULE_28704")); + assert.notInclude(sent, "PROJECT_RULE_28704"); assert.notInclude(sent, ""); } else { assert.notInclude(append, "systemPrompt"); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index b6f746269a6f2..470dd525c8c24 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -32,6 +32,7 @@ import { antigravitySubagentLaunches, describeAntigravitySubagentLaunches, } from "../../provider/acp/AntigravityChildWork.ts"; +import { readAntigravityInstructions } from "../../provider/acp/AntigravityInstructions.ts"; import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts"; import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; import { @@ -72,9 +73,11 @@ const AntigravityProviderCapabilitiesV2 = { export interface AntigravityAdapterV2Options { readonly instanceId: ProviderInstanceId; + readonly userHome: string; readonly selfInvocation: SelfInvocation; readonly makeRuntime: ( - input: Omit, + input: Omit & + Pick, ) => Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError | ProviderSetupError, @@ -139,6 +142,16 @@ export function makeAntigravityAcpAdapterFlavor( cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir]; const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")( function* (input: AcpAdapterV2RuntimeInput) { + const instructions: Array = []; + for (const filePath of [ + options.path.join(options.userHome, ".gemini", "GEMINI.md"), + options.path.join(input.cwd, "AGENTS.md"), + options.path.join(input.cwd, "GEMINI.md"), + ]) { + const contents = yield* readAntigravityInstructions(filePath); + if (contents?.trim()) instructions.push(`# ${filePath}\n\n${contents}`); + } + instructions.push(PULL_REQUEST_LINKING_INSTRUCTIONS); const scope = yield* Scope.fork(yield* Effect.scope); const runtime = yield* options .withProcess( @@ -146,7 +159,7 @@ export function makeAntigravityAcpAdapterFlavor( options.makeRuntime({ ...input, clientFileReads: true, - sessionSystemPromptAppend: PULL_REQUEST_LINKING_INSTRUCTIONS, + sessionSystemPromptAppend: instructions.join("\n\n"), additionalDirectories: [options.host.paths.attachmentsDir], }), ) @@ -213,6 +226,7 @@ export function makeAntigravityAcpAdapterFlavor( // Agents that advertise HTTP MCP skip the stdio bridge process; others keep stdio. mcpOverHttp: true, sessionCarriesPullRequestLinking: antigravityAppendsSystemPrompt, + replaceRuntimeOnActivation: antigravityAppendsSystemPrompt, makeRuntime, buildAttachmentPrompt: ({ text, diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 75bca5acc87be..a5024e633848c 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -459,6 +459,7 @@ export const AntigravityDriver: ProviderDriver< const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel)); const orchestrationAdapter = yield* makeAntigravityAdapterV2({ instanceId, + userHome, selfInvocation, makeRuntime, withProcess: authFlow.withProcess, diff --git a/apps/server/src/provider/acp/AntigravityInstructions.test.ts b/apps/server/src/provider/acp/AntigravityInstructions.test.ts new file mode 100644 index 0000000000000..6dc381f473610 --- /dev/null +++ b/apps/server/src/provider/acp/AntigravityInstructions.test.ts @@ -0,0 +1,31 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import * as HostProcess from "@t3tools/shared/HostProcess"; + +import { readAntigravityInstructions } from "./AntigravityInstructions.ts"; + +it.effect("reads only bounded regular instruction files and skips missing files", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped(); + const file = path.join(root, "AGENTS.md"); + const limit = 256 * 1024; + yield* fs.writeFileString(file, "a".repeat(limit)); + assert.lengthOf((yield* readAntigravityInstructions(file))!, limit); + yield* fs.writeFileString(file, "a".repeat(limit + 1)); + assert.isTrue(Exit.isFailure(yield* Effect.exit(readAntigravityInstructions(file)))); + assert.isUndefined(yield* readAntigravityInstructions(path.join(root, "missing"))); + assert.isTrue(Exit.isFailure(yield* Effect.exit(readAntigravityInstructions(root)))); + if ((yield* HostProcess.Platform) !== "win32") { + const device = path.join(root, "GEMINI.md"); + yield* fs.symlink("/dev/zero", device); + assert.isTrue(Exit.isFailure(yield* Effect.exit(readAntigravityInstructions(device)))); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/provider/acp/AntigravityInstructions.ts b/apps/server/src/provider/acp/AntigravityInstructions.ts new file mode 100644 index 0000000000000..1738bff255748 --- /dev/null +++ b/apps/server/src/provider/acp/AntigravityInstructions.ts @@ -0,0 +1,60 @@ +// Nonblocking descriptor reads prevent special files from hanging session startup. +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodeFSP from "node:fs/promises"; +import * as Effect from "effect/Effect"; +import * as EffectAcpErrors from "effect-acp/errors"; + +const INSTRUCTION_MAX_BYTES = 256 * 1024; + +export const readAntigravityInstructions = Effect.fn("AntigravityInstructions.read")( + (filePath: string) => + Effect.tryPromise({ + try: async () => { + try { + const info = await NodeFSP.stat(filePath); + if (!info.isFile() || info.size > INSTRUCTION_MAX_BYTES) { + throw new Error("Instructions must be a regular file of at most 256 KiB."); + } + // Nonblocking open and descriptor validation also cover replacement by a FIFO after stat. + const file = await NodeFSP.open( + filePath, + NodeFS.constants.O_RDONLY | NodeFS.constants.O_NONBLOCK, + ); + try { + const opened = await file.stat(); + if (!opened.isFile() || opened.size > INSTRUCTION_MAX_BYTES) { + throw new Error("Instructions must be a regular file of at most 256 KiB."); + } + const buffer = Buffer.alloc(INSTRUCTION_MAX_BYTES + 1); + let size = 0; + while (size < buffer.length) { + const { bytesRead } = await file.read(buffer, size, buffer.length - size, size); + if (bytesRead === 0) break; + size += bytesRead; + } + if (size > INSTRUCTION_MAX_BYTES) { + throw new Error("Instructions exceed 256 KiB."); + } + return buffer.toString("utf8", 0, size); + } finally { + await file.close(); + } + } catch (cause) { + if ( + typeof cause === "object" && + cause !== null && + "code" in cause && + cause.code === "ENOENT" + ) + return undefined; + throw cause; + } + }, + catch: (cause) => + new EffectAcpErrors.AcpTransportError({ + detail: `Could not read Antigravity instructions at '${filePath}' (regular files up to 256 KiB only).`, + cause, + }), + }), +); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 723ad6ec5e7c7..6903cad400e75 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -399,6 +399,10 @@ export interface AcpAdapterV2Flavor { } | undefined; readonly withRuntimeStartup?: (effect: Effect.Effect) => Effect.Effect; + /** Rebuild workspace-bound startup metadata on activation, preserving the native session. */ + readonly replaceRuntimeOnActivation?: ( + initializeResult: EffectAcpSchema.InitializeResponse, + ) => boolean; readonly makeRuntime: ( input: AcpAdapterV2RuntimeInput, ) => Effect.Effect< @@ -2474,6 +2478,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); }), ).pipe(Effect.asVoid); + let runtimeCwd = input.runtimePolicy.cwd ?? process.cwd(); const makeRuntimeInput = ( runtimeGeneration: number, agentRequests: Set, @@ -2483,8 +2488,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( handleRuntimeTerminationAtGeneration(runtimeGeneration), ): AcpAdapterV2RuntimeInput => { return { - cwd: input.runtimePolicy.cwd ?? process.cwd(), - runtimePolicy: input.runtimePolicy, + cwd: latestRuntimePolicy.cwd ?? process.cwd(), + runtimePolicy: latestRuntimePolicy, mcpServers: mcpContext.servers, acpMcpServers: mcpContext.acpServers, httpMcpServers: mcpContext.httpServers, @@ -6521,6 +6526,29 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( turnKey: context === null ? null : String(context.providerTurnId), })); + const wireAcpRuntimeClientFileHandlers = Effect.fn("AcpAdapterV2.wireClientFileHandlers")( + function* (targetRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"]) { + const clientFileSystem = flavor.clientFileSystem; + if (clientFileSystem !== undefined) { + yield* targetRuntime.handleReadTextFile((request) => + clientPolicyContext.pipe( + Effect.flatMap(({ policy }) => + clientFileSystem.readTextFile(request, policy.cwd), + ), + ), + ); + const writeTextFile = clientFileSystem.writeTextFile; + if (writeTextFile !== undefined) { + yield* targetRuntime.handleWriteTextFile((request) => + clientPolicyContext.pipe( + Effect.flatMap(({ policy }) => writeTextFile(request, policy.cwd)), + ), + ); + } + } + }, + ); + const denyClientRequest = (operation: string, disposition: "ask" | "deny") => Effect.logWarning("ACP client policy denied a client-mediated operation", { operation, @@ -6621,22 +6649,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.succeed(request), requestContext.requestId, ); - const clientFileSystem = flavor.clientFileSystem; - if (clientFileSystem !== undefined) { - yield* targetRuntime.handleReadTextFile((request) => - clientPolicyContext.pipe( - Effect.flatMap(({ policy }) => clientFileSystem.readTextFile(request, policy.cwd)), - ), - ); - const writeTextFile = clientFileSystem.writeTextFile; - if (writeTextFile !== undefined) { - yield* targetRuntime.handleWriteTextFile((request) => - clientPolicyContext.pipe( - Effect.flatMap(({ policy }) => writeTextFile(request, policy.cwd)), - ), - ); - } - } + yield* wireAcpRuntimeClientFileHandlers(targetRuntime); if (handlerOptions.mcp !== false) { yield* wireAcpRuntimeMcpHandlers(targetRuntime, runtimeMcpBridge); } @@ -7050,6 +7063,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runtimeMcpBridge = yield* makeRuntimeMcpBridge(mcpContext, runtimeScope); const runtimeGeneration = yield* Ref.get(runtimeCallbackGeneration); openAgentRequests = new Set(); + runtimeCwd = latestRuntimePolicy.cwd ?? process.cwd(); runtime = yield* flavor .makeRuntime( makeRuntimeInput(runtimeGeneration, openAgentRequests, mcpContext, resumeSessionId), @@ -7085,6 +7099,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( commitSessionState: ( replacement: AcpSessionRuntime.AcpSessionRuntimeStartResult, ) => Effect.Effect, + resumeSessionId?: string, ) { const previousScope = runtimeScope; const previousGeneration = yield* Ref.get(runtimeCallbackGeneration); @@ -7131,7 +7146,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( replacementGeneration, replacementAgentRequests, mcpContext, - undefined, + resumeSessionId, handleCandidateTermination, ), ) @@ -7146,6 +7161,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.suspend(() => handleCandidateSessionUpdate(notification)), ); yield* wireAcpRuntimeMcpHandlers(replacementRuntime, replacementMcpBridge); + yield* wireAcpRuntimeClientFileHandlers(replacementRuntime); const started = yield* replacementRuntime.start(); return { replacementRuntime, started }; }); @@ -7169,6 +7185,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.uninterruptible( Effect.gen(function* () { yield* awaitAdmittedNativeResponses; + if (resumeSessionId !== undefined) yield* assertCanReactivateWorkspace; yield* wireAcpRuntimeHandlers( replacementExit.value.replacementRuntime, replacementGeneration, @@ -7190,6 +7207,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return yield* lifecycle.error; } yield* quarantineNativeTransportAtGeneration(previousGeneration); + runtimeCwd = latestRuntimePolicy.cwd ?? process.cwd(); runtime = replacementExit.value.replacementRuntime; runtimeScope = replacementScope; runtimeMcpBridge = replacementMcpBridge; @@ -7256,6 +7274,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( function* ( threadId: ThreadId | null, candidate: AcpSessionRuntime.AcpSessionRuntimeStartResult, + preserveHistory = false, ) { rememberTerminalEnvironment(candidate.sessionId, yield* readMcpContext(threadId)); yield* Ref.set(runtimeRestartRequired, false); @@ -7263,12 +7282,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* setActiveSessionSetup(candidate); yield* Ref.set(activeSelection, null); yield* Ref.set(activeInteractionMode, null); - yield* Ref.set(promptInstructionStates, new Map()); - yield* Ref.set(promptRuntimeInstructions, new Map()); - yield* Ref.set(compactionMarkers, new Map()); - yield* Ref.set(completedCompactionIds, new Set()); - yield* Ref.set(providerTurns, new Map()); - yield* Ref.set(snapshot, emptySnapshotState()); + if (!preserveHistory) { + yield* Ref.set(promptInstructionStates, new Map()); + yield* Ref.set(promptRuntimeInstructions, new Map()); + yield* Ref.set(compactionMarkers, new Map()); + yield* Ref.set(completedCompactionIds, new Set()); + yield* Ref.set(providerTurns, new Map()); + yield* Ref.set(snapshot, emptySnapshotState()); + } yield* continuationPermit.withPermit( Effect.gen(function* () { yield* Ref.update(continuationGeneration, (value) => value + 1); @@ -7323,6 +7344,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( flavor.modelOptionArrivesLate === true, flavor.forkFromTurn?.supported(started.initializeResult) === true, ); + const replaceRuntimeOnActivation = + flavor.replaceRuntimeOnActivation?.(started.initializeResult) === true; const canLoadSession = started.initializeResult.agentCapabilities?.loadSession === true; const canResumeSession = started.initializeResult.agentCapabilities?.sessionCapabilities?.resume != null; @@ -7332,6 +7355,49 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( started.initializeResult.agentCapabilities?.promptCapabilities?.image === true, }); + const hasPendingBackgroundWork = Effect.gen(function* () { + const rootSessionId = yield* Ref.get(activeSessionId); + if ( + followsAgentWorkState && + rootSessionId !== null && + hasWorkingDescendant(rootSessionId) + ) + return true; + if ( + followsAgentWorkState && + (agentWork?.state === "running" || + agentWork?.state === "requires_action" || + agentRequests.size > 0) + ) + return true; + if ((yield* Ref.get(wakeBuffer)).length > 0) return true; + if (yield* Ref.get(continuationRequested)) return true; + if ((yield* Ref.get(runningBackgroundTaskIds)).size > 0) return true; + const active = yield* Ref.get(activeTurn); + if ( + active !== null && + [...active.subagents.values()].some(acpSubagentHasPendingBackgroundWork) + ) { + return true; + } + const carryover = yield* Ref.get(carryoverSubagents); + if (carryover !== null && carryover.subagents.some(acpSubagentHasPendingBackgroundWork)) { + return true; + } + return false; + }); + + const assertCanReactivateWorkspace = Effect.gen(function* () { + const pendingWork = yield* hasPendingBackgroundWork; + if ((yield* Ref.get(activeTurn)) !== null || pendingWork) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: + "Cannot reactivate an ACP workspace while background work is running; wait for it to finish or stop it first", + }); + } + }); + const activateSession = Effect.fnUntraced(function* ( sessionId: string, threadId: ThreadId | null, @@ -7342,6 +7408,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (initialFailure !== undefined) { return yield* initialFailure; } + if (replaceRuntimeOnActivation) { + yield* assertCanReactivateWorkspace; + const preserveHistory = (yield* Ref.get(activeSessionId)) === sessionId; + return yield* startReplacementAcpRuntime( + threadId, + (candidate) => commitReplacementSession(threadId, candidate, preserveHistory), + sessionId, + ); + } const mcpContext = yield* readMcpContext(threadId); const activationOptions = acpMcpActivation(mcpContext); prepareTerminalEnvironment(mcpContext, sessionId); @@ -8265,15 +8340,25 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } useProviderThreadIdentity(turnInput.providerThread); // load/resume can invoke client methods; install the incoming policy before activation. + const previousRuntimePolicy = latestRuntimePolicy; latestRuntimePolicy = turnInput.runtimePolicy; const requestedSessionId = yield* nativeThreadId(driver, turnInput.providerThread); const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired( turnInput.threadId, ); const needsSessionActivation = - (yield* Ref.get(activeSessionId)) !== requestedSessionId || restartAfterInterrupt; + (yield* Ref.get(activeSessionId)) !== requestedSessionId || + restartAfterInterrupt || + (replaceRuntimeOnActivation && + runtimeCwd !== (latestRuntimePolicy.cwd ?? process.cwd())); if (needsSessionActivation) { - const activated = yield* activateSession(requestedSessionId, turnInput.threadId); + const activated = yield* activateSession(requestedSessionId, turnInput.threadId).pipe( + Effect.tapError(() => + Effect.sync(() => { + latestRuntimePolicy = previousRuntimePolicy; + }), + ), + ); yield* Ref.set(activeSessionId, activated.sessionId); yield* setActiveSessionSetup(activated); yield* configureSession(activated, turnInput.modelSelection, turnInput.runtimePolicy); @@ -8837,40 +8922,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }), ...(postSettleContinuationEnabled || followsAgentWorkState ? { - hasPendingBackgroundWork: Effect.gen(function* () { - const rootSessionId = yield* Ref.get(activeSessionId); - if ( - followsAgentWorkState && - rootSessionId !== null && - hasWorkingDescendant(rootSessionId) - ) - return true; - if ( - followsAgentWorkState && - (agentWork?.state === "running" || - agentWork?.state === "requires_action" || - agentRequests.size > 0) - ) - return true; - if ((yield* Ref.get(wakeBuffer)).length > 0) return true; - if (yield* Ref.get(continuationRequested)) return true; - if ((yield* Ref.get(runningBackgroundTaskIds)).size > 0) return true; - const active = yield* Ref.get(activeTurn); - if ( - active !== null && - [...active.subagents.values()].some(acpSubagentHasPendingBackgroundWork) - ) { - return true; - } - const carryover = yield* Ref.get(carryoverSubagents); - if ( - carryover !== null && - carryover.subagents.some(acpSubagentHasPendingBackgroundWork) - ) { - return true; - } - return false; - }), + hasPendingBackgroundWork, } : {}), ensureThread: Effect.fn("AcpAdapterV2.ensureThread")( @@ -8889,6 +8941,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( "Cannot replace ACP session while a turn or background work is active", }); yield* awaitRuntimeTeardown(); + const previousRuntimePolicy = latestRuntimePolicy; + latestRuntimePolicy = threadInput.runtimePolicy; const previousItemIdentityVersion = itemIdentityVersion; itemIdentityVersion = 2; prepareTerminalEnvironment(yield* readMcpContext(threadInput.threadId)); @@ -8898,6 +8952,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.tapError(() => Effect.sync(() => { itemIdentityVersion = previousItemIdentityVersion; + latestRuntimePolicy = previousRuntimePolicy; }), ), ); @@ -8958,19 +9013,38 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const restorePreviousItemIdentity = Effect.sync(() => { itemIdentityVersion = previousItemIdentityVersion; }); + const nextSelection = threadInput.modelSelection ?? input.modelSelection; + const nextRuntimePolicy = threadInput.runtimePolicy ?? latestRuntimePolicy; + const previousRuntimePolicy = latestRuntimePolicy; + latestRuntimePolicy = nextRuntimePolicy; const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired( threadInput.providerThread.appThreadId, ).pipe(Effect.tapError(() => restorePreviousItemIdentity)); - if ((yield* Ref.get(activeSessionId)) !== sessionId || restartAfterInterrupt) { - yield* Ref.set(snapshot, emptySnapshotState()); + if ( + (yield* Ref.get(activeSessionId)) !== sessionId || + restartAfterInterrupt || + (replaceRuntimeOnActivation && + runtimeCwd !== (nextRuntimePolicy.cwd ?? process.cwd())) + ) { + if (!replaceRuntimeOnActivation) { + yield* Ref.set(snapshot, emptySnapshotState()); + } const activated = yield* activateSession( sessionId, threadInput.providerThread.appThreadId, - ).pipe(Effect.tapError(() => restorePreviousItemIdentity)); + ).pipe( + Effect.tapError(() => + restorePreviousItemIdentity.pipe( + Effect.andThen( + Effect.sync(() => { + latestRuntimePolicy = previousRuntimePolicy; + }), + ), + ), + ), + ); yield* Ref.set(activeSessionId, activated.sessionId); yield* setActiveSessionSetup(activated); - const nextSelection = threadInput.modelSelection ?? input.modelSelection; - const nextRuntimePolicy = threadInput.runtimePolicy ?? input.runtimePolicy; yield* configureSession(activated, nextSelection, nextRuntimePolicy); yield* Ref.set(activeSelection, nextSelection); yield* Ref.set(activeInteractionMode, nextRuntimePolicy.interactionMode); From 7c610e06446162c134d817b98100fffb1e2ef1ed Mon Sep 17 00:00:00 2001 From: Lakshmi Tanmay Date: Thu, 12 Nov 2026 22:25:39 +0530 Subject: [PATCH 2/5] test(acp): cover rejected replacement and interrupt recovery --- .../Adapters/AcpAdapterV2.test.ts | 562 ++++++++++-------- 1 file changed, 327 insertions(+), 235 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 7086b1acc6d11..ca856ec9937bf 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -5640,114 +5640,192 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); - it.effect("preserves the workspace runtime on background work or failed reactivation", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const workspaceB = yield* fs.makeTempDirectoryScoped(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const instanceId = ProviderInstanceId.make("acp-workspace-reactivation"); - let applyMutation: AcpAdapterV2ExtensionContext["applyBackgroundTaskMutation"] | undefined; - const inputs: Array = []; - const nativeRuntime = makeMockRuntime({ childProcessSpawner, mockAgentPath }); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - selfInvocation: yield* resolveSelfInvocation(), - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - replaceRuntimeOnActivation: () => true, - enablePostSettleContinuation: true, - registerExtensions: (context) => - Effect.sync(() => { - applyMutation = context.applyBackgroundTaskMutation; - }), - makeRuntime: (input): ReturnType => { - inputs.push(input); - if (inputs.length === 2) - return Effect.fail( - new EffectAcpErrors.AcpTransportError({ - detail: "Fixture activation failure", - cause: null, - }), - ); - return nativeRuntime(input).pipe( - Effect.map((candidate) => - inputs.length === 3 - ? { - ...candidate, - start: () => - candidate.start().pipe( - Effect.tap(() => - originalMutation({ - sessionId, - taskId: "late-workspace-task", - status: "running", + it.effect.each(["startTurn", "resumeThread"] as const)( + "preserves the workspace runtime on background work or failed reactivation via %s", + (activation) => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceB = yield* fs.makeTempDirectoryScoped(); + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const instanceId = ProviderInstanceId.make("acp-workspace-reactivation"); + let applyMutation: AcpAdapterV2ExtensionContext["applyBackgroundTaskMutation"] | undefined; + const inputs: Array = []; + const prompts: Array = []; + let originalClosed = false; + const nativeRuntime = makeMockRuntime({ childProcessSpawner, mockAgentPath }); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + replaceRuntimeOnActivation: () => true, + sessionModeForPolicy: () => "code", + enablePostSettleContinuation: true, + registerExtensions: (context) => + Effect.sync(() => { + applyMutation = context.applyBackgroundTaskMutation; + }), + makeRuntime: (input): ReturnType => { + inputs.push(input); + if (inputs.length === 2) + return Effect.fail( + new EffectAcpErrors.AcpTransportError({ + detail: "Fixture activation failure", + cause: null, + }), + ); + return nativeRuntime(input).pipe( + Effect.tap(() => + inputs.length === 1 + ? Effect.addFinalizer(() => + Effect.sync(() => { + originalClosed = true; + }), + ) + : Effect.void, + ), + Effect.map((candidate) => + inputs.length === 4 + ? { + ...candidate, + setMode: () => + Effect.fail( + new EffectAcpErrors.AcpTransportError({ + detail: "Fixture mode configuration failure", + cause: null, }), ), - ), - } - : candidate, - ), - ); + } + : inputs.length === 3 + ? { + ...candidate, + start: () => + candidate.start().pipe( + Effect.tap(() => + originalMutation({ + sessionId, + taskId: "late-workspace-task", + status: "running", + }), + ), + ), + } + : { + ...candidate, + prompt: (request) => { + prompts.push(input.cwd); + return candidate.prompt(request); + }, + }, + ), + ); + }, }, - }, - continuationRequests: { offer: () => Effect.void }, - }); - const threadId = ThreadId.make("thread-workspace-reactivation"); - const modelSelection = { instanceId, model: "default" } as const; - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const runtime = yield* adapter.openSession({ - threadId, - modelSelection, - runtimePolicy, - providerSessionId: ProviderSessionId.make("session-workspace-reactivation"), - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - if (applyMutation === undefined) return yield* Effect.die("Expected background task handler"); - const originalMutation = applyMutation; - const sessionId = "mock-session-1"; - assert.equal(providerThread.nativeThreadRef?.nativeId, sessionId); - yield* originalMutation({ sessionId, taskId: "workspace-task", status: "running" }); - const nextPolicy = { ...runtimePolicy, cwd: workspaceB }; - const resume = () => - runtime.resumeThread({ providerThread, modelSelection, runtimePolicy: nextPolicy }); - const busy = yield* Effect.exit(resume()); - assert.isTrue(Exit.isFailure(busy)); - if (Exit.isFailure(busy)) - assert.include(Cause.pretty(busy.cause), "background work is running"); - assert.lengthOf(inputs, 1); - assert.isTrue(yield* runtime.hasPendingBackgroundWork!); - yield* originalMutation({ sessionId, taskId: "workspace-task", status: "completed" }); - assert.isFalse(yield* runtime.hasPendingBackgroundWork!); - assert.isTrue(Exit.isFailure(yield* Effect.exit(resume()))); - const unchanged = yield* runtime.readThreadSnapshot({ providerThread }); - assert.equal(unchanged.providerThread.nativeThreadRef?.nativeId, sessionId); - assert.isTrue(Exit.isFailure(yield* Effect.exit(resume()))); - assert.isTrue(yield* runtime.hasPendingBackgroundWork!); - yield* originalMutation({ sessionId, taskId: "late-workspace-task", status: "completed" }); - yield* resume(); - assert.deepEqual( - inputs.map((input) => [input.cwd, input.runtimePolicy.cwd, input.resumeSessionId]), - [ - [runtimePolicy.cwd, runtimePolicy.cwd, undefined], - [workspaceB, workspaceB, sessionId], - [workspaceB, workspaceB, sessionId], - [workspaceB, workspaceB, sessionId], - ], - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + continuationRequests: { offer: () => Effect.void }, + }); + const threadId = ThreadId.make("thread-workspace-reactivation"); + const modelSelection = { instanceId, model: "default" } as const; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const runtime = yield* adapter.openSession({ + threadId, + modelSelection, + runtimePolicy, + providerSessionId: ProviderSessionId.make("session-workspace-reactivation"), + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + if (applyMutation === undefined) + return yield* Effect.die("Expected background task handler"); + const originalMutation = applyMutation; + const sessionId = "mock-session-1"; + assert.equal(providerThread.nativeThreadRef?.nativeId, sessionId); + const nextPolicy = { ...runtimePolicy, cwd: workspaceB }; + const turnInput = makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + messageText: "original workspace history", + }); + const turn = (ordinal: number) => + runtime.startTurn({ + ...turnInput, + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: turnInput.appThread.createdAt, + ordinal, + messageText: "original workspace history", + }), + }); + const completed = runtime.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.runHead, + Effect.map((event) => { + assert.isTrue(Option.isSome(event)); + if (Option.isSome(event) && event.value.type === "turn.terminal") + assert.equal(event.value.status, "completed"); + }), + ); + yield* turn(1); + yield* completed; + const resume = () => + activation === "resumeThread" + ? runtime.resumeThread({ providerThread, modelSelection, runtimePolicy: nextPolicy }) + : runtime.startTurn({ ...turnInput, runtimePolicy: nextPolicy }); + yield* originalMutation({ sessionId, taskId: "workspace-task", status: "running" }); + const busy = yield* Effect.exit(resume()); + assert.isTrue(Exit.isFailure(busy)); + if (Exit.isFailure(busy)) + assert.include(Cause.pretty(busy.cause), "background work is running"); + assert.lengthOf(inputs, 1); + assert.isTrue(yield* runtime.hasPendingBackgroundWork!); + yield* originalMutation({ sessionId, taskId: "workspace-task", status: "completed" }); + assert.isFalse(yield* runtime.hasPendingBackgroundWork!); + assert.isTrue(Exit.isFailure(yield* Effect.exit(resume()))); + const unchanged = yield* runtime.readThreadSnapshot({ providerThread }); + assert.equal(unchanged.providerThread.nativeThreadRef?.nativeId, sessionId); + assert.isTrue(Exit.isFailure(yield* Effect.exit(resume()))); + assert.isTrue(yield* runtime.hasPendingBackgroundWork!); + yield* originalMutation({ sessionId, taskId: "late-workspace-task", status: "completed" }); + const rejected = yield* Effect.exit(resume()); + assert.isTrue(Exit.isFailure(rejected)); + if (Exit.isFailure(rejected)) + assert.include(Cause.pretty(rejected.cause), "Fixture mode configuration failure"); + assert.isFalse(originalClosed, "configuration rejection must retain the original process"); + yield* turn(2); + yield* completed; + assert.deepEqual(prompts, [runtimePolicy.cwd, runtimePolicy.cwd]); + assert.lengthOf(inputs, 4, "returning to the original workspace must reuse its runtime"); + const retained = yield* runtime.readThreadSnapshot({ providerThread }); + assert.include(JSON.stringify(retained), "original workspace history"); + yield* resume(); + assert.deepEqual( + inputs.map((input) => [input.cwd, input.runtimePolicy.cwd, input.resumeSessionId]), + [ + [runtimePolicy.cwd, runtimePolicy.cwd, undefined], + [workspaceB, workspaceB, sessionId], + [workspaceB, workspaceB, sessionId], + [workspaceB, workspaceB, sessionId], + [workspaceB, workspaceB, sessionId], + ], + ); + }).pipe(Effect.provide(layerTest), Effect.scoped), ); it.effect("replaces the ACP session and clears conversation state on rollback", () => @@ -6688,143 +6766,157 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); - it.live("terminalizes an empty successful foreground Bash tool when the turn completes", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* bundledMockAgentPath; - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: (runtimeOrdinal) => - runtimeOrdinal === 1 ? { T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH_THEN_HANG: "1" } : {}, - ownDetachedProcessGroup: true, - processGroupTerminationGrace: 0, - protocolEvents, - }), - normalizeToolCall: normalizeXAiAcpToolCallState, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-empty-successful-bash"); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-empty-successful-bash"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); + it.live.each([ + { replacement: false, activation: "startTurn" }, + { replacement: true, activation: "startTurn" }, + { replacement: true, activation: "resumeThread" }, + ] as const)( + "terminalizes an empty successful foreground Bash tool and recovers once ($replacement, $activation)", + ({ replacement, activation }) => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const protocolEvents = yield* Queue.bounded(256); + const instanceId = ProviderInstanceId.make("acp-test"); + let constructions = 0; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + replaceRuntimeOnActivation: () => replacement, + makeRuntime: makeMockRuntime({ + wrapRuntime: (runtime) => { + constructions++; + return runtime; + }, + childProcessSpawner, + mockAgentPath, + environment: (runtimeOrdinal) => + runtimeOrdinal === 1 ? { T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH_THEN_HANG: "1" } : {}, + ownDetachedProcessGroup: true, + protocolEvents, + }), + normalizeToolCall: normalizeXAiAcpToolCallState, + restartRuntimeAfterInterrupt: true, + terminateRuntimeProcessGroupOnInterrupt: true, + }, + selfInvocation, + }); + const threadId = ThreadId.make("thread-acp-empty-successful-bash"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-empty-successful-bash"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* runtime.startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), + ); - const statuses: string[] = []; - let runningStartedAt: DateTime.Utc | null = null; - let completedStartedAt: DateTime.Utc | null = null; - let completedAt: DateTime.Utc | null = null; - let completedInput: string | null = null; - let completedOutput: string | null | undefined; - let completedExitCode: number | null | undefined; - let runningProjectedExitCode: number | undefined = undefined; - let terminal = false; - while (!terminal) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === "tool-call-empty-success-1" - ) { - statuses.push(event.turnItem.status); - if (event.turnItem.status === "running") { - runningStartedAt ??= event.turnItem.startedAt; - if (event.turnItem.type === "command_execution") { - runningProjectedExitCode = event.turnItem.exitCode; + const statuses: string[] = []; + let runningStartedAt: DateTime.Utc | null = null; + let completedStartedAt: DateTime.Utc | null = null; + let completedAt: DateTime.Utc | null = null; + let completedInput: string | null = null; + let completedOutput: string | null | undefined; + let completedExitCode: number | null | undefined; + let runningProjectedExitCode: number | undefined = undefined; + let terminal = false; + while (!terminal) { + const event = yield* Queue.take(events); + if ( + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "tool-call-empty-success-1" + ) { + statuses.push(event.turnItem.status); + if (event.turnItem.status === "running") { + runningStartedAt ??= event.turnItem.startedAt; + if (event.turnItem.type === "command_execution") { + runningProjectedExitCode = event.turnItem.exitCode; + } } - } - if (event.turnItem.status === "completed") { - completedStartedAt = event.turnItem.startedAt; - completedAt = event.turnItem.completedAt; - if (event.turnItem.type === "command_execution") { - completedInput = event.turnItem.input; - completedOutput = event.turnItem.output; - completedExitCode = event.turnItem.exitCode; + if (event.turnItem.status === "completed") { + completedStartedAt = event.turnItem.startedAt; + completedAt = event.turnItem.completedAt; + if (event.turnItem.type === "command_execution") { + completedInput = event.turnItem.input; + completedOutput = event.turnItem.output; + completedExitCode = event.turnItem.exitCode; + } } } + if (event.type === "turn.terminal") terminal = true; } - if (event.type === "turn.terminal") terminal = true; - } - assert.deepEqual(statuses, ["running", "running", "completed"]); - assert.deepEqual(completedStartedAt, runningStartedAt); - assert.isNotNull(completedAt); - assert.equal(completedInput, "true"); - assert.equal(completedOutput, undefined); - assert.equal( - runningProjectedExitCode, - undefined, - "mid-stream exit_code must not project until the tool is terminal", - ); - assert.equal(completedExitCode, 0); + assert.deepEqual(statuses, ["running", "running", "completed"]); + assert.deepEqual(completedStartedAt, runningStartedAt); + assert.isNotNull(completedAt); + assert.equal(completedInput, "true"); + assert.equal(completedOutput, undefined); + assert.equal( + runningProjectedExitCode, + undefined, + "mid-stream exit_code must not project until the tool is terminal", + ); + assert.equal(completedExitCode, 0); - yield* Queue.takeAll(protocolEvents); - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - yield* runtime.interruptTurn({ - providerThread, - providerTurnId: secondProviderTurnId, - requestRuntimeRestart: true, - }); - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 3 }), - ); - const loadAfterRestart = yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/resume", - ), - Stream.runHead, - ); - assert.isTrue(Option.isSome(loadAfterRestart)); - }).pipe(Effect.provide(layerTest)), + yield* Queue.takeAll(protocolEvents); + yield* runtime + .startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), + ) + .pipe(Effect.forkScoped); + yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", + ), + Stream.runHead, + ); + const secondProviderTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), + }); + yield* runtime.interruptTurn({ + providerThread, + providerTurnId: secondProviderTurnId, + requestRuntimeRestart: true, + }); + if (activation === "resumeThread") + yield* runtime.resumeThread({ providerThread, modelSelection, runtimePolicy }); + yield* runtime.startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 3 }), + ); + assert.equal(constructions, 2, "interrupt recovery must construct one replacement runtime"); + const loadAfterRestart = yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/resume", + ), + Stream.runHead, + ); + assert.isTrue(Option.isSome(loadAfterRestart)); + }).pipe(Effect.provide(layerTest)), ); it.effect("drains native ACP cancellation before admitting the next prompt", () => From d655404514c9fdf1d79bb00879cc69babbc6677c Mon Sep 17 00:00:00 2001 From: Lakshmi Tanmay Date: Thu, 12 Nov 2026 22:29:20 +0530 Subject: [PATCH 3/5] fix(acp): configure replacement before retiring the live runtime --- .../Adapters/AcpAdapterV2.test.ts | 270 ++++++++++-------- .../acp/AntigravityInstructions.test.ts | 2 +- packages/provider-acp/src/server/adapter.ts | 141 ++++++--- 3 files changed, 262 insertions(+), 151 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index ca856ec9937bf..d21b2dc31a8fc 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -1296,102 +1296,105 @@ describe("AcpAdapterV2", () => { assert.equal(promptOrdinal, 2, "continuation turn must not dispatch session/prompt"); }).pipe(Effect.provide(layerTest)), ); - it.live("fails an end_turn the outcome check rejects and restarts before the next turn", () => - Effect.gen(function* () { - const instanceId = ProviderInstanceId.make("acp-test-prompt-outcome"); - const threadId = ThreadId.make("thread-acp-prompt-outcome"); - const quota = { - class: "usage_limit", - message: "Quota reached.", - code: "RESOURCE_EXHAUSTED", - retryable: true, - resetAt: "2030-01-01T00:00:00.000Z", - } as const; - // The runtime ordinal of each prompt, and the session each check watched. - const promptRuntimes: Array = []; - const promptTexts: Array = []; - const watchedSessions: Array = []; - const adapter = yield* makeAcpAdapterV2({ - instanceId, - selfInvocation: yield* resolveSelfInvocation(), - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - watchPromptOutcome: (sessionId) => - Effect.sync(() => { - watchedSessions.push(sessionId); - const failed = watchedSessions.length === 1; - return () => Effect.succeed(failed ? quota : undefined); - }), - makeRuntime: makeMockRuntime({ - childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner, - mockAgentPath: yield* bundledMockAgentPath, - wrapRuntime: (runtime, runtimeOrdinal) => ({ - ...runtime, - prompt: (payload) => - Effect.sync(() => { - promptRuntimes.push(runtimeOrdinal); - promptTexts.push( - payload.prompt - .flatMap((block) => (block.type === "text" ? [block.text] : [])) - .join("\n"), - ); - return { stopReason: "end_turn" as const }; - }), - }), - }), - }, - }); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-prompt-outcome"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const runTurn = (ordinal: number) => - Effect.gen(function* () { - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - ordinal, + it.live.each([false, true])( + "fails an end_turn the outcome check rejects and restarts before the next turn (replacement: %s)", + (replacement) => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("acp-test-prompt-outcome"); + const threadId = ThreadId.make("thread-acp-prompt-outcome"); + const quota = { + class: "usage_limit", + message: "Quota reached.", + code: "RESOURCE_EXHAUSTED", + retryable: true, + resetAt: "2030-01-01T00:00:00.000Z", + } as const; + // The runtime ordinal of each prompt, and the session each check watched. + const promptRuntimes: Array = []; + const promptTexts: Array = []; + const watchedSessions: Array = []; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + replaceRuntimeOnActivation: () => replacement, + watchPromptOutcome: (sessionId) => + Effect.sync(() => { + watchedSessions.push(sessionId); + const failed = watchedSessions.length === 1; + return () => Effect.succeed(failed ? quota : undefined); + }), + makeRuntime: makeMockRuntime({ + childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner, + mockAgentPath: yield* bundledMockAgentPath, + wrapRuntime: (runtime, runtimeOrdinal) => ({ + ...runtime, + prompt: (payload) => + Effect.sync(() => { + promptRuntimes.push(runtimeOrdinal); + promptTexts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + return { stopReason: "end_turn" as const }; + }), + }), }), - ); - const events = yield* runtime.events.pipe( - Stream.takeUntil((event) => event.type === "turn.terminal"), - Stream.runCollect, - ); - return events.at(-1); + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-prompt-outcome"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, }); + const runTurn = (ordinal: number) => + Effect.gen(function* () { + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + }), + ); + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + return events.at(-1); + }); - const failed = yield* runTurn(1); - if (failed?.type !== "turn.terminal" || failed.status !== "failed") { - return assert.fail("expected a failed terminal"); - } - assert.deepEqual(failed.failure, quota); - const completed = yield* runTurn(2); - assert.equal(completed?.type === "turn.terminal" ? completed.status : null, "completed"); - assert.deepEqual(promptRuntimes, [1, 2], "the next turn runs on a fresh runtime"); - // The fresh runtime has no record of what reached the agent, so it sends T3's notes again. - assert.include(promptTexts[1] ?? "", ""); - assert.include(promptTexts[1] ?? "", "T3 Code interaction mode: Default"); - assert.equal(watchedSessions.length, 2); - assert.equal(watchedSessions[0], watchedSessions[1]); - }).pipe(Effect.provide(layerTest)), + const failed = yield* runTurn(1); + if (failed?.type !== "turn.terminal" || failed.status !== "failed") { + return assert.fail("expected a failed terminal"); + } + assert.deepEqual(failed.failure, quota); + const completed = yield* runTurn(2); + assert.equal(completed?.type === "turn.terminal" ? completed.status : null, "completed"); + assert.deepEqual(promptRuntimes, [1, 2], "the next turn runs on a fresh runtime"); + // The fresh runtime has no record of what reached the agent, so it sends T3's notes again. + assert.include(promptTexts[1] ?? "", ""); + assert.include(promptTexts[1] ?? "", "T3 Code interaction mode: Default"); + assert.equal(watchedSessions.length, 2); + assert.equal(watchedSessions[0], watchedSessions[1]); + }).pipe(Effect.provide(layerTest)), ); it.live("retains returned usage when Stop finalizes before the prompt callback", () => Effect.gen(function* () { @@ -5640,22 +5643,27 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); - it.effect.each(["startTurn", "resumeThread"] as const)( - "preserves the workspace runtime on background work or failed reactivation via %s", - (activation) => + it.effect.each([ + { activation: "startTurn", rejection: "mode" }, + { activation: "resumeThread", rejection: "mode" }, + { activation: "startTurn", rejection: "model" }, + { activation: "resumeThread", rejection: "model" }, + ] as const)( + "preserves the workspace runtime on background work or failed $rejection reactivation via $activation", + ({ activation, rejection }) => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; const workspaceB = yield* fs.makeTempDirectoryScoped(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); + const mockAgentPath = yield* bundledMockAgentPath; const instanceId = ProviderInstanceId.make("acp-workspace-reactivation"); let applyMutation: AcpAdapterV2ExtensionContext["applyBackgroundTaskMutation"] | undefined; const inputs: Array = []; const prompts: Array = []; let originalClosed = false; + let originalRead: + | Parameters[0] + | undefined; const nativeRuntime = makeMockRuntime({ childProcessSpawner, mockAgentPath }); const adapter = yield* makeAcpAdapterV2({ instanceId, @@ -5665,6 +5673,9 @@ describe("AcpAdapterV2", () => { capabilities: AcpProviderCapabilitiesV2, replaceRuntimeOnActivation: () => true, sessionModeForPolicy: () => "code", + clientFileSystem: { + readTextFile: (_request, cwd) => Effect.succeed({ content: cwd ?? "" }), + }, enablePostSettleContinuation: true, registerExtensions: (context) => Effect.sync(() => { @@ -5693,13 +5704,27 @@ describe("AcpAdapterV2", () => { inputs.length === 4 ? { ...candidate, - setMode: () => - Effect.fail( - new EffectAcpErrors.AcpTransportError({ - detail: "Fixture mode configuration failure", - cause: null, - }), - ), + ...(rejection === "model" + ? { + setConfigOption: () => + Effect.fail( + new EffectAcpErrors.AcpRequestError({ + code: -32602, + errorMessage: "Fixture model configuration failure", + }), + ), + } + : {}), + setMode: + rejection === "model" + ? candidate.setMode + : () => + Effect.fail( + new EffectAcpErrors.AcpTransportError({ + detail: "Fixture mode configuration failure", + cause: null, + }), + ), } : inputs.length === 3 ? { @@ -5717,6 +5742,10 @@ describe("AcpAdapterV2", () => { } : { ...candidate, + handleReadTextFile: (handler) => { + originalRead = handler; + return candidate.handleReadTextFile(handler); + }, prompt: (request) => { prompts.push(input.cwd); return candidate.prompt(request); @@ -5761,9 +5790,8 @@ describe("AcpAdapterV2", () => { messageText: "original workspace history", }); const turn = (ordinal: number) => - runtime.startTurn({ - ...turnInput, - ...makeTurnInput({ + runtime.startTurn( + makeTurnInput({ threadId, providerThread, instanceId, @@ -5772,7 +5800,7 @@ describe("AcpAdapterV2", () => { ordinal, messageText: "original workspace history", }), - }); + ); const completed = runtime.events.pipe( Stream.filter((event) => event.type === "turn.terminal"), Stream.runHead, @@ -5806,8 +5834,23 @@ describe("AcpAdapterV2", () => { const rejected = yield* Effect.exit(resume()); assert.isTrue(Exit.isFailure(rejected)); if (Exit.isFailure(rejected)) - assert.include(Cause.pretty(rejected.cause), "Fixture mode configuration failure"); + assert.include( + Cause.pretty(rejected.cause), + `Fixture ${rejection} configuration failure`, + ); assert.isFalse(originalClosed, "configuration rejection must retain the original process"); + const retainedBeforeTurn = yield* runtime.readThreadSnapshot({ providerThread }); + assert.deepEqual(retainedBeforeTurn.messages, unchanged.messages); + assert.deepEqual(retainedBeforeTurn.providerTurns, unchanged.providerTurns); + if (originalRead === undefined) + return yield* Effect.die("Expected original client file handler"); + assert.equal( + (yield* originalRead( + { sessionId, path: "policy-probe" }, + { requestId: "policy-probe", method: "fs/read_text_file" }, + )).content, + runtimePolicy.cwd, + ); yield* turn(2); yield* completed; assert.deepEqual(prompts, [runtimePolicy.cwd, runtimePolicy.cwd]); @@ -5825,7 +5868,7 @@ describe("AcpAdapterV2", () => { [workspaceB, workspaceB, sessionId], ], ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("replaces the ACP session and clears conversation state on rollback", () => @@ -6797,6 +6840,7 @@ describe("AcpAdapterV2", () => { environment: (runtimeOrdinal) => runtimeOrdinal === 1 ? { T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH_THEN_HANG: "1" } : {}, ownDetachedProcessGroup: true, + processGroupTerminationGrace: 0, protocolEvents, }), normalizeToolCall: normalizeXAiAcpToolCallState, diff --git a/apps/server/src/provider/acp/AntigravityInstructions.test.ts b/apps/server/src/provider/acp/AntigravityInstructions.test.ts index 6dc381f473610..81741c9e05308 100644 --- a/apps/server/src/provider/acp/AntigravityInstructions.test.ts +++ b/apps/server/src/provider/acp/AntigravityInstructions.test.ts @@ -27,5 +27,5 @@ it.effect("reads only bounded regular instruction files and skips missing files" yield* fs.symlink("/dev/zero", device); assert.isTrue(Exit.isFailure(yield* Effect.exit(readAntigravityInstructions(device)))); } - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(NodeServices.layer)), ); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 6903cad400e75..0da65a23f5795 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2022,7 +2022,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const providerThreadByNativeSessionId = yield* Ref.make( new Map(), ); - const nativeBuildConfigurationBySessionId = new Map(); + let nativeBuildConfigurationBySessionId = new Map(); const initialSessionActivationFailure = yield* Ref.make<{ readonly sessionId: string; readonly error: EffectAcpErrors.AcpError; @@ -7100,6 +7100,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( replacement: AcpSessionRuntime.AcpSessionRuntimeStartResult, ) => Effect.Effect, resumeSessionId?: string, + configureCandidate?: ( + candidateRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"], + started: AcpSessionRuntime.AcpSessionRuntimeStartResult, + ) => Effect.Effect< + AcpSessionRuntime.AcpSessionRuntimeStartResult, + EffectAcpErrors.AcpError | AcpModelSelectionError + >, ) { const previousScope = runtimeScope; const previousGeneration = yield* Ref.get(runtimeCallbackGeneration); @@ -7163,7 +7170,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* wireAcpRuntimeMcpHandlers(replacementRuntime, replacementMcpBridge); yield* wireAcpRuntimeClientFileHandlers(replacementRuntime); const started = yield* replacementRuntime.start(); - return { replacementRuntime, started }; + const configured = + configureCandidate === undefined + ? started + : yield* configureCandidate(replacementRuntime, started); + return { replacementRuntime, started: configured }; }); const replacementExit = yield* Effect.exit( (flavor.withRuntimeStartup?.(startup) ?? startup).pipe( @@ -7277,16 +7288,19 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( preserveHistory = false, ) { rememberTerminalEnvironment(candidate.sessionId, yield* readMcpContext(threadId)); + const restartRequired = yield* Ref.get(runtimeRestartRequired); yield* Ref.set(runtimeRestartRequired, false); yield* Ref.set(activeSessionId, candidate.sessionId); yield* setActiveSessionSetup(candidate); yield* Ref.set(activeSelection, null); yield* Ref.set(activeInteractionMode, null); - if (!preserveHistory) { + if (!preserveHistory || restartRequired) { yield* Ref.set(promptInstructionStates, new Map()); yield* Ref.set(promptRuntimeInstructions, new Map()); yield* Ref.set(compactionMarkers, new Map()); yield* Ref.set(completedCompactionIds, new Set()); + } + if (!preserveHistory) { yield* Ref.set(providerTurns, new Map()); yield* Ref.set(snapshot, emptySnapshotState()); } @@ -7401,6 +7415,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const activateSession = Effect.fnUntraced(function* ( sessionId: string, threadId: ThreadId | null, + modelSelection: ModelSelection, + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, ) { const initialFailure = yield* Ref.modify(initialSessionActivationFailure, (failure) => failure?.sessionId === sessionId ? [failure.error, null] : [undefined, failure], @@ -7411,10 +7427,32 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (replaceRuntimeOnActivation) { yield* assertCanReactivateWorkspace; const preserveHistory = (yield* Ref.get(activeSessionId)) === sessionId; + const candidateBuildConfiguration = new Map(nativeBuildConfigurationBySessionId); return yield* startReplacementAcpRuntime( threadId, - (candidate) => commitReplacementSession(threadId, candidate, preserveHistory), + (candidate) => + commitReplacementSession(threadId, candidate, preserveHistory).pipe( + Effect.tap(() => + Effect.sync(() => { + nativeBuildConfigurationBySessionId = candidateBuildConfiguration; + }), + ), + ), sessionId, + (candidateRuntime, candidate) => + Ref.make(candidate).pipe( + Effect.flatMap((candidateSetup) => + configureSession( + candidate, + modelSelection, + runtimePolicy, + [], + candidateRuntime, + candidateBuildConfiguration, + candidateSetup, + ), + ), + ), ); } const mcpContext = yield* readMcpContext(threadId); @@ -7434,6 +7472,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const validateModelSelection = Effect.fn("AcpAdapterV2.validateModelSelection")(function* ( modelSelection: ModelSelection, + targetRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"] = runtime, + setup?: AcpSessionRuntime.AcpSessionRuntimeStartResult, ) { const model = flavor.resolveModelId?.(modelSelection) ?? modelSelection.model; if ( @@ -7444,8 +7484,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( flavor.customModels?.includes(model) === true ) return; - const option = findModelConfigOption(yield* runtime.getConfigOptions); - const models = (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models; + const option = findModelConfigOption(yield* targetRuntime.getConfigOptions); + const models = (setup ?? (yield* Ref.get(activeSessionSetup)))?.sessionSetupResult.models; const available = option?.type === "select" ? flattenSelectChoices(option.options).some((choice) => choice.value === model) @@ -7465,9 +7505,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( modelSelection: ModelSelection, runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, unsetOptionDefaults: NonNullable = [], + targetRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"] = runtime, + buildConfiguration: Map< + string, + AcpNativeBuildConfiguration + > = nativeBuildConfigurationBySessionId, + sessionSetup: Ref.Ref = activeSessionSetup, ) { - yield* Ref.set(activeSelection, null); - yield* validateModelSelection(modelSelection); + if (targetRuntime === runtime) yield* Ref.set(activeSelection, null); + yield* validateModelSelection(modelSelection, targetRuntime, startResult); const requestedModel = flavor.resolveModelId?.(modelSelection) ?? modelSelection.model; // Invalid params is the agent refusing the value, and the runtime // raises the same code when the session's model option does not offer @@ -7481,7 +7527,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (flavor.applyModelSelection !== undefined) { appliedModel = yield* flavor .applyModelSelection({ - runtime, + runtime: targetRuntime, startResult, modelSelection, }) @@ -7490,7 +7536,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // Stored catalog choices can expire; explicitly configured custom IDs // are validated by the agent instead. const isCustomModel = flavor.customModels?.includes(requestedModel) === true; - const modelOption = findModelConfigOption(yield* runtime.getConfigOptions); + const modelOption = findModelConfigOption(yield* targetRuntime.getConfigOptions); const modelState = startResult.sessionSetupResult.models; if (modelOption?.type === "select") { if ( @@ -7499,7 +7545,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (choice) => choice.value === requestedModel, ) ) { - yield* runtime + yield* targetRuntime .setConfigOption(modelOption.id, requestedModel, { resendCurrentValue: flavor.alwaysSetModel === true, }) @@ -7512,14 +7558,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( modelState.availableModels.some((model) => model.modelId === requestedModel)) ) { if (modelState.currentModelId !== requestedModel) { - yield* runtime.setSessionModel(requestedModel).pipe(Effect.mapError(rejectedModel)); + yield* targetRuntime + .setSessionModel(requestedModel) + .pipe(Effect.mapError(rejectedModel)); } appliedModel = requestedModel; } } if (appliedModel !== undefined) { const applied = appliedModel; - yield* Ref.update(activeSessionSetup, (setup) => { + yield* Ref.update(sessionSetup, (setup) => { if (setup === null) { return setup; } @@ -7536,7 +7584,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }; }); } - const configOptions = yield* runtime.getConfigOptions; + const configOptions = yield* targetRuntime.getConfigOptions; // Under a policy ceiling, a mode the user picks applies only when the flavor can place // it under the ceiling; an unknown mode could be the agent's own skip-approval mode. const ceiling = runtimePolicy.maxRuntimeMode; @@ -7610,7 +7658,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); if (!advertisedValues.includes(selection.value)) continue; } - yield* runtime.setConfigOption(selection.id, selection.value).pipe( + yield* targetRuntime.setConfigOption(selection.id, selection.value).pipe( Effect.catchTags({ AcpRequestError: (error) => error.code === -32602 @@ -7624,7 +7672,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); } for (const selection of flavor.sessionConfigForPolicy?.(runtimePolicy) ?? []) { - const option = (yield* runtime.getConfigOptions).find( + const option = (yield* targetRuntime.getConfigOptions).find( (candidate) => candidate.id === selection.id, ); if (option?.type !== "select" || option.currentValue === selection.value) continue; @@ -7632,23 +7680,23 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( "value" in entry ? [entry.value] : entry.options.map((choice) => choice.value), ); if (!advertisedValues.includes(selection.value)) continue; - yield* runtime.setConfigOption(selection.id, selection.value); + yield* targetRuntime.setConfigOption(selection.id, selection.value); } const policyMode = flavor.sessionModeForPolicy?.(runtimePolicy); if (policyMode !== undefined) { - yield* runtime.setMode(policyMode); + yield* targetRuntime.setMode(policyMode); } - const modeState = yield* runtime.getModeState; + const modeState = yield* targetRuntime.getModeState; if ( modeSelection !== undefined && typeof modeSelection.value === "string" && modeState?.availableModes.some((mode) => mode.id === modeSelection.value) === true && modeState.currentModeId !== modeSelection.value ) { - yield* runtime.setMode(modeSelection.value); + yield* targetRuntime.setMode(modeSelection.value); } - const effectiveModeState = yield* runtime.getModeState; - const effectiveConfigOptions = yield* runtime.getConfigOptions; + const effectiveModeState = yield* targetRuntime.getModeState; + const effectiveConfigOptions = yield* targetRuntime.getConfigOptions; const planSensitiveOptions = effectiveConfigOptions.filter( ( option, @@ -7660,8 +7708,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (option.category === "mode" || option.category === "collaboration_mode"), ); if (runtimePolicy.interactionMode === "plan") { - if (!nativeBuildConfigurationBySessionId.has(startResult.sessionId)) { - nativeBuildConfigurationBySessionId.set(startResult.sessionId, { + if (!buildConfiguration.has(startResult.sessionId)) { + buildConfiguration.set(startResult.sessionId, { ...(effectiveModeState === undefined ? {} : { modeId: effectiveModeState.currentModeId }), @@ -7675,7 +7723,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( isAcpPlanModeId(mode.id), ); if (planMode !== undefined && effectiveModeState?.currentModeId !== planMode.id) { - yield* runtime.setMode(planMode.id); + yield* targetRuntime.setMode(planMode.id); } for (const option of planSensitiveOptions) { const choices = option.options.flatMap((entry) => @@ -7683,11 +7731,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); const requested = choices.find(isAcpPlanModeId); if (requested !== undefined && option.currentValue !== requested) { - yield* runtime.setConfigOption(option.id, requested); + yield* targetRuntime.setConfigOption(option.id, requested); } } } else { - const nativeBuild = nativeBuildConfigurationBySessionId.get(startResult.sessionId); + const nativeBuild = buildConfiguration.get(startResult.sessionId); if (nativeBuild !== undefined) { if ( nativeBuild.modeId !== undefined && @@ -7696,7 +7744,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (mode) => mode.id === nativeBuild.modeId, ) === true ) { - yield* runtime.setMode(nativeBuild.modeId); + yield* targetRuntime.setMode(nativeBuild.modeId); } for (const saved of nativeBuild.configOptions) { const option = effectiveConfigOptions.find( @@ -7707,20 +7755,22 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( "value" in entry ? [entry.value] : entry.options.map((choice) => choice.value), ); if (option.currentValue !== saved.value && choices.includes(saved.value)) { - yield* runtime.setConfigOption(option.id, saved.value); + yield* targetRuntime.setConfigOption(option.id, saved.value); } } - nativeBuildConfigurationBySessionId.delete(startResult.sessionId); + buildConfiguration.delete(startResult.sessionId); } } - yield* validateModelSelection(modelSelection); + const configuredSetup = (yield* Ref.get(sessionSetup)) ?? startResult; + yield* validateModelSelection(modelSelection, targetRuntime, configuredSetup); yield* ( flavor.onSessionConfigurationUpdate?.( - yield* runtime.getConfigOptions, - yield* runtime.getModeState, - (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models, + yield* targetRuntime.getConfigOptions, + yield* targetRuntime.getModeState, + configuredSetup.sessionSetupResult.models, ) ?? Effect.void ); + return configuredSetup; }); yield* configureSession( @@ -8309,9 +8359,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const restartRuntimeAfterTeardownIfRequired = Effect.fnUntraced(function* ( threadId: ThreadId | null, + replacingRuntime = false, ) { const restartRequired = yield* Ref.get(runtimeRestartRequired); if (!restartRequired) return false; + if (replacingRuntime) return true; yield* restartAcpRuntime(threadId); yield* Ref.set(runtimeRestartRequired, false); yield* Ref.set(activeSessionId, null); @@ -8345,6 +8397,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const requestedSessionId = yield* nativeThreadId(driver, turnInput.providerThread); const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired( turnInput.threadId, + replaceRuntimeOnActivation, ); const needsSessionActivation = (yield* Ref.get(activeSessionId)) !== requestedSessionId || @@ -8352,7 +8405,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (replaceRuntimeOnActivation && runtimeCwd !== (latestRuntimePolicy.cwd ?? process.cwd())); if (needsSessionActivation) { - const activated = yield* activateSession(requestedSessionId, turnInput.threadId).pipe( + const activated = yield* activateSession( + requestedSessionId, + turnInput.threadId, + turnInput.modelSelection, + turnInput.runtimePolicy, + ).pipe( Effect.tapError(() => Effect.sync(() => { latestRuntimePolicy = previousRuntimePolicy; @@ -8361,7 +8419,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); yield* Ref.set(activeSessionId, activated.sessionId); yield* setActiveSessionSetup(activated); - yield* configureSession(activated, turnInput.modelSelection, turnInput.runtimePolicy); + if (!replaceRuntimeOnActivation) + yield* configureSession( + activated, + turnInput.modelSelection, + turnInput.runtimePolicy, + ); yield* Ref.set(activeSelection, turnInput.modelSelection); yield* Ref.set(activeInteractionMode, turnInput.runtimePolicy.interactionMode); } else { @@ -9019,6 +9082,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( latestRuntimePolicy = nextRuntimePolicy; const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired( threadInput.providerThread.appThreadId, + replaceRuntimeOnActivation, ).pipe(Effect.tapError(() => restorePreviousItemIdentity)); if ( (yield* Ref.get(activeSessionId)) !== sessionId || @@ -9032,6 +9096,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const activated = yield* activateSession( sessionId, threadInput.providerThread.appThreadId, + nextSelection, + nextRuntimePolicy, ).pipe( Effect.tapError(() => restorePreviousItemIdentity.pipe( @@ -9045,7 +9111,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); yield* Ref.set(activeSessionId, activated.sessionId); yield* setActiveSessionSetup(activated); - yield* configureSession(activated, nextSelection, nextRuntimePolicy); + if (!replaceRuntimeOnActivation) + yield* configureSession(activated, nextSelection, nextRuntimePolicy); yield* Ref.set(activeSelection, nextSelection); yield* Ref.set(activeInteractionMode, nextRuntimePolicy.interactionMode); } From 2d2ab35e7d819b85db16b87f2a798af991ea195d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 14 Nov 2026 11:59:44 +0000 Subject: [PATCH 4/5] refactor(server): keep Antigravity rules loading inside its adapter Workspace handoffs already detach and restart single-thread ACP sessions, and an ACP runtime keeps the cwd it started with, so the shared ACP adapter does not need to replace runtimes when a turn's cwd differs. Drop that machinery and its tests. Read the rules files through the injected FileSystem and skip a missing, oversized or unreadable file with a warning instead of failing the session. Co-Authored-By: Claude Opus 5.5 --- apps/server/scripts/acp-mock-agent.ts | 14 - .../Adapters/AcpAdapterV2.test.ts | 692 ++++++------------ .../Adapters/AntigravityAdapterV2.test.ts | 196 ++--- .../Adapters/AntigravityAdapterV2.ts | 30 +- .../acp/AntigravityInstructions.test.ts | 31 - .../provider/acp/AntigravityInstructions.ts | 60 -- packages/provider-acp/src/server/adapter.ts | 341 +++------ 7 files changed, 403 insertions(+), 961 deletions(-) delete mode 100644 apps/server/src/provider/acp/AntigravityInstructions.test.ts delete mode 100644 apps/server/src/provider/acp/AntigravityInstructions.ts diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index d00c4f3b2a19d..a97aab9cdf2b1 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -60,7 +60,6 @@ const agentVersion = process.env.T3_ACP_AGENT_VERSION ?? "0.0.0"; const geminiApiKey = process.env.GEMINI_API_KEY; const idleError = process.env.T3_ACP_IDLE_ERROR; const emitTrackedToolCallKindThenHang = process.env.T3_ACP_EMIT_TRACKED_TOOL_CALL_KIND_THEN_HANG; -const resumeReadPath = process.env.T3_ACP_RESUME_READ_PATH; const clientFsProbePath = process.env.T3_ACP_CLIENT_FS_PROBE_PATH; const clientFsProbeLogPath = process.env.T3_ACP_CLIENT_FS_PROBE_LOG_PATH; const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); @@ -643,19 +642,6 @@ const program = Effect.gen(function* () { yield* agent.handleResumeSession((request) => Effect.gen(function* () { yield* requireAuthentication(); - if (resumeReadPath !== undefined) { - const read = yield* agent.raw.request("fs/read_text_file", { - sessionId: request.sessionId, - path: resumeReadPath, - }); - yield* agent.client.sessionUpdate({ - sessionId: request.sessionId, - update: { - sessionUpdate: "user_message_chunk", - content: { type: "text", text: `native-resume-read:${encodeJson(read)}` }, - }, - }); - } yield* agent.client.sessionUpdate({ sessionId: request.sessionId, update: { diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 07642db0b3eaf..b7808ef897ee7 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -1327,105 +1327,102 @@ describe("AcpAdapterV2", () => { assert.equal(promptOrdinal, 2, "continuation turn must not dispatch session/prompt"); }).pipe(Effect.provide(layerTest)), ); - it.live.each([false, true])( - "fails an end_turn the outcome check rejects and restarts before the next turn (replacement: %s)", - (replacement) => - Effect.gen(function* () { - const instanceId = ProviderInstanceId.make("acp-test-prompt-outcome"); - const threadId = ThreadId.make("thread-acp-prompt-outcome"); - const quota = { - class: "usage_limit", - message: "Quota reached.", - code: "RESOURCE_EXHAUSTED", - retryable: true, - resetAt: "2030-01-01T00:00:00.000Z", - } as const; - // The runtime ordinal of each prompt, and the session each check watched. - const promptRuntimes: Array = []; - const promptTexts: Array = []; - const watchedSessions: Array = []; - const adapter = yield* makeAcpAdapterV2({ - instanceId, - selfInvocation: yield* resolveSelfInvocation(), - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - replaceRuntimeOnActivation: () => replacement, - watchPromptOutcome: (sessionId) => - Effect.sync(() => { - watchedSessions.push(sessionId); - const failed = watchedSessions.length === 1; - return () => Effect.succeed(failed ? quota : undefined); - }), - makeRuntime: makeMockRuntime({ - childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner, - mockAgentPath: yield* bundledMockAgentPath, - wrapRuntime: (runtime, runtimeOrdinal) => ({ - ...runtime, - prompt: (payload) => - Effect.sync(() => { - promptRuntimes.push(runtimeOrdinal); - promptTexts.push( - payload.prompt - .flatMap((block) => (block.type === "text" ? [block.text] : [])) - .join("\n"), - ); - return { stopReason: "end_turn" as const }; - }), - }), + it.live("fails an end_turn the outcome check rejects and restarts before the next turn", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("acp-test-prompt-outcome"); + const threadId = ThreadId.make("thread-acp-prompt-outcome"); + const quota = { + class: "usage_limit", + message: "Quota reached.", + code: "RESOURCE_EXHAUSTED", + retryable: true, + resetAt: "2030-01-01T00:00:00.000Z", + } as const; + // The runtime ordinal of each prompt, and the session each check watched. + const promptRuntimes: Array = []; + const promptTexts: Array = []; + const watchedSessions: Array = []; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + watchPromptOutcome: (sessionId) => + Effect.sync(() => { + watchedSessions.push(sessionId); + const failed = watchedSessions.length === 1; + return () => Effect.succeed(failed ? quota : undefined); }), - }, - }); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-prompt-outcome"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, + makeRuntime: makeMockRuntime({ + childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner, + mockAgentPath: yield* bundledMockAgentPath, + wrapRuntime: (runtime, runtimeOrdinal) => ({ + ...runtime, + prompt: (payload) => + Effect.sync(() => { + promptRuntimes.push(runtimeOrdinal); + promptTexts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + return { stopReason: "end_turn" as const }; + }), + }), + }), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-prompt-outcome"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const runTurn = (ordinal: number) => + Effect.gen(function* () { + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + }), + ); + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + return events.at(-1); }); - const runTurn = (ordinal: number) => - Effect.gen(function* () { - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - ordinal, - }), - ); - const events = yield* runtime.events.pipe( - Stream.takeUntil((event) => event.type === "turn.terminal"), - Stream.runCollect, - ); - return events.at(-1); - }); - const failed = yield* runTurn(1); - if (failed?.type !== "turn.terminal" || failed.status !== "failed") { - return assert.fail("expected a failed terminal"); - } - assert.deepEqual(failed.failure, quota); - const completed = yield* runTurn(2); - assert.equal(completed?.type === "turn.terminal" ? completed.status : null, "completed"); - assert.deepEqual(promptRuntimes, [1, 2], "the next turn runs on a fresh runtime"); - // The fresh runtime has no record of what reached the agent, so it sends T3's notes again. - assert.include(promptTexts[1] ?? "", ""); - assert.include(promptTexts[1] ?? "", "T3 Code interaction mode: Default"); - assert.equal(watchedSessions.length, 2); - assert.equal(watchedSessions[0], watchedSessions[1]); - }).pipe(Effect.provide(layerTest)), + const failed = yield* runTurn(1); + if (failed?.type !== "turn.terminal" || failed.status !== "failed") { + return assert.fail("expected a failed terminal"); + } + assert.deepEqual(failed.failure, quota); + const completed = yield* runTurn(2); + assert.equal(completed?.type === "turn.terminal" ? completed.status : null, "completed"); + assert.deepEqual(promptRuntimes, [1, 2], "the next turn runs on a fresh runtime"); + // The fresh runtime has no record of what reached the agent, so it sends T3's notes again. + assert.include(promptTexts[1] ?? "", ""); + assert.include(promptTexts[1] ?? "", "T3 Code interaction mode: Default"); + assert.equal(watchedSessions.length, 2); + assert.equal(watchedSessions[0], watchedSessions[1]); + }).pipe(Effect.provide(layerTest)), ); it.live("retains returned usage when Stop finalizes before the prompt callback", () => Effect.gen(function* () { @@ -5755,234 +5752,6 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); - it.effect.each([ - { activation: "startTurn", rejection: "mode" }, - { activation: "resumeThread", rejection: "mode" }, - { activation: "startTurn", rejection: "model" }, - { activation: "resumeThread", rejection: "model" }, - ] as const)( - "preserves the workspace runtime on background work or failed $rejection reactivation via $activation", - ({ activation, rejection }) => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fs = yield* FileSystem.FileSystem; - const workspaceB = yield* fs.makeTempDirectoryScoped(); - const mockAgentPath = yield* bundledMockAgentPath; - const instanceId = ProviderInstanceId.make("acp-workspace-reactivation"); - let applyMutation: AcpAdapterV2ExtensionContext["applyBackgroundTaskMutation"] | undefined; - const inputs: Array = []; - const prompts: Array = []; - let originalClosed = false; - let originalRead: - | Parameters[0] - | undefined; - const nativeRuntime = makeMockRuntime({ childProcessSpawner, mockAgentPath }); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - selfInvocation: yield* resolveSelfInvocation(), - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - replaceRuntimeOnActivation: () => true, - sessionModeForPolicy: () => "code", - clientFileSystem: { - readTextFile: (_request, cwd) => Effect.succeed({ content: cwd ?? "" }), - }, - enablePostSettleContinuation: true, - registerExtensions: (context) => - Effect.sync(() => { - applyMutation = context.applyBackgroundTaskMutation; - }), - makeRuntime: (input): ReturnType => { - inputs.push(input); - if (inputs.length === 2) - return Effect.fail( - new EffectAcpErrors.AcpTransportError({ - detail: "Fixture activation failure", - cause: null, - }), - ); - return nativeRuntime(input).pipe( - Effect.tap(() => - inputs.length === 1 - ? Effect.addFinalizer(() => - Effect.sync(() => { - originalClosed = true; - }), - ) - : Effect.void, - ), - Effect.map((candidate) => - inputs.length === 4 - ? { - ...candidate, - ...(rejection === "model" - ? { - setConfigOption: () => - Effect.fail( - new EffectAcpErrors.AcpRequestError({ - code: -32602, - errorMessage: "Fixture model configuration failure", - }), - ), - } - : {}), - setMode: - rejection === "model" - ? candidate.setMode - : () => - Effect.fail( - new EffectAcpErrors.AcpTransportError({ - detail: "Fixture mode configuration failure", - cause: null, - }), - ), - } - : inputs.length === 3 - ? { - ...candidate, - start: () => - candidate.start().pipe( - Effect.tap(() => - originalMutation({ - sessionId, - taskId: "late-workspace-task", - status: "running", - }), - ), - ), - } - : { - ...candidate, - handleReadTextFile: (handler) => { - originalRead = handler; - return candidate.handleReadTextFile(handler); - }, - prompt: (request) => { - prompts.push(input.cwd); - return candidate.prompt(request); - }, - }, - ), - ); - }, - }, - continuationRequests: { offer: () => Effect.void }, - }); - const threadId = ThreadId.make("thread-workspace-reactivation"); - const modelSelection = { instanceId, model: "default" } as const; - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const runtime = yield* adapter.openSession({ - threadId, - modelSelection, - runtimePolicy, - providerSessionId: ProviderSessionId.make("session-workspace-reactivation"), - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - if (applyMutation === undefined) - return yield* Effect.die("Expected background task handler"); - const originalMutation = applyMutation; - const sessionId = "mock-session-1"; - assert.equal(providerThread.nativeThreadRef?.nativeId, sessionId); - const nextPolicy = { ...runtimePolicy, cwd: workspaceB }; - const turnInput = makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - messageText: "original workspace history", - }); - const turn = (ordinal: number) => - runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: turnInput.appThread.createdAt, - ordinal, - messageText: "original workspace history", - }), - ); - const completed = runtime.events.pipe( - Stream.filter((event) => event.type === "turn.terminal"), - Stream.runHead, - Effect.map((event) => { - assert.isTrue(Option.isSome(event)); - if (Option.isSome(event) && event.value.type === "turn.terminal") - assert.equal(event.value.status, "completed"); - }), - ); - yield* turn(1); - yield* completed; - const resume = () => - activation === "resumeThread" - ? runtime.resumeThread({ providerThread, modelSelection, runtimePolicy: nextPolicy }) - : runtime.startTurn({ ...turnInput, runtimePolicy: nextPolicy }); - yield* originalMutation({ sessionId, taskId: "workspace-task", status: "running" }); - const busy = yield* Effect.exit(resume()); - assert.isTrue(Exit.isFailure(busy)); - if (Exit.isFailure(busy)) - assert.include(Cause.pretty(busy.cause), "background work is running"); - assert.lengthOf(inputs, 1); - assert.isTrue(yield* runtime.hasPendingBackgroundWork!); - yield* originalMutation({ sessionId, taskId: "workspace-task", status: "completed" }); - assert.isFalse(yield* runtime.hasPendingBackgroundWork!); - assert.isTrue(Exit.isFailure(yield* Effect.exit(resume()))); - const unchanged = yield* runtime.readThreadSnapshot({ providerThread }); - assert.equal(unchanged.providerThread.nativeThreadRef?.nativeId, sessionId); - assert.isTrue(Exit.isFailure(yield* Effect.exit(resume()))); - assert.isTrue(yield* runtime.hasPendingBackgroundWork!); - yield* originalMutation({ sessionId, taskId: "late-workspace-task", status: "completed" }); - const rejected = yield* Effect.exit(resume()); - assert.isTrue(Exit.isFailure(rejected)); - if (Exit.isFailure(rejected)) - assert.include( - Cause.pretty(rejected.cause), - `Fixture ${rejection} configuration failure`, - ); - assert.isFalse(originalClosed, "configuration rejection must retain the original process"); - const retainedBeforeTurn = yield* runtime.readThreadSnapshot({ providerThread }); - assert.deepEqual(retainedBeforeTurn.messages, unchanged.messages); - assert.deepEqual(retainedBeforeTurn.providerTurns, unchanged.providerTurns); - if (originalRead === undefined) - return yield* Effect.die("Expected original client file handler"); - assert.equal( - (yield* originalRead( - { sessionId, path: "policy-probe" }, - { requestId: "policy-probe", method: "fs/read_text_file" }, - )).content, - runtimePolicy.cwd, - ); - yield* turn(2); - yield* completed; - assert.deepEqual(prompts, [runtimePolicy.cwd, runtimePolicy.cwd]); - assert.lengthOf(inputs, 4, "returning to the original workspace must reuse its runtime"); - const retained = yield* runtime.readThreadSnapshot({ providerThread }); - assert.include(JSON.stringify(retained), "original workspace history"); - yield* resume(); - assert.deepEqual( - inputs.map((input) => [input.cwd, input.runtimePolicy.cwd, input.resumeSessionId]), - [ - [runtimePolicy.cwd, runtimePolicy.cwd, undefined], - [workspaceB, workspaceB, sessionId], - [workspaceB, workspaceB, sessionId], - [workspaceB, workspaceB, sessionId], - [workspaceB, workspaceB, sessionId], - ], - ); - }).pipe(Effect.provide(layerTest)), - ); - it.effect("replaces the ACP session and clears conversation state on rollback", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -6921,158 +6690,143 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); - it.live.each([ - { replacement: false, activation: "startTurn" }, - { replacement: true, activation: "startTurn" }, - { replacement: true, activation: "resumeThread" }, - ] as const)( - "terminalizes an empty successful foreground Bash tool and recovers once ($replacement, $activation)", - ({ replacement, activation }) => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* bundledMockAgentPath; - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - let constructions = 0; - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - replaceRuntimeOnActivation: () => replacement, - makeRuntime: makeMockRuntime({ - wrapRuntime: (runtime) => { - constructions++; - return runtime; - }, - childProcessSpawner, - mockAgentPath, - environment: (runtimeOrdinal) => - runtimeOrdinal === 1 ? { T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH_THEN_HANG: "1" } : {}, - ownDetachedProcessGroup: true, - processGroupTerminationGrace: 0, - protocolEvents, - }), - normalizeToolCall: normalizeXAiAcpToolCallState, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-empty-successful-bash"); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-empty-successful-bash"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); + it.live("terminalizes an empty successful foreground Bash tool when the turn completes", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const protocolEvents = yield* Queue.bounded(256); + const instanceId = ProviderInstanceId.make("acp-test"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + environment: (runtimeOrdinal) => + runtimeOrdinal === 1 ? { T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH_THEN_HANG: "1" } : {}, + ownDetachedProcessGroup: true, + processGroupTerminationGrace: 0, + protocolEvents, + }), + normalizeToolCall: normalizeXAiAcpToolCallState, + restartRuntimeAfterInterrupt: true, + terminateRuntimeProcessGroupOnInterrupt: true, + }, + selfInvocation, + }); + const threadId = ThreadId.make("thread-acp-empty-successful-bash"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-empty-successful-bash"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* runtime.startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), + ); - const statuses: string[] = []; - let runningStartedAt: DateTime.Utc | null = null; - let completedStartedAt: DateTime.Utc | null = null; - let completedAt: DateTime.Utc | null = null; - let completedInput: string | null = null; - let completedOutput: string | null | undefined; - let completedExitCode: number | null | undefined; - let runningProjectedExitCode: number | undefined = undefined; - let terminal = false; - while (!terminal) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === "tool-call-empty-success-1" - ) { - statuses.push(event.turnItem.status); - if (event.turnItem.status === "running") { - runningStartedAt ??= event.turnItem.startedAt; - if (event.turnItem.type === "command_execution") { - runningProjectedExitCode = event.turnItem.exitCode; - } + const statuses: string[] = []; + let runningStartedAt: DateTime.Utc | null = null; + let completedStartedAt: DateTime.Utc | null = null; + let completedAt: DateTime.Utc | null = null; + let completedInput: string | null = null; + let completedOutput: string | null | undefined; + let completedExitCode: number | null | undefined; + let runningProjectedExitCode: number | undefined = undefined; + let terminal = false; + while (!terminal) { + const event = yield* Queue.take(events); + if ( + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "tool-call-empty-success-1" + ) { + statuses.push(event.turnItem.status); + if (event.turnItem.status === "running") { + runningStartedAt ??= event.turnItem.startedAt; + if (event.turnItem.type === "command_execution") { + runningProjectedExitCode = event.turnItem.exitCode; } - if (event.turnItem.status === "completed") { - completedStartedAt = event.turnItem.startedAt; - completedAt = event.turnItem.completedAt; - if (event.turnItem.type === "command_execution") { - completedInput = event.turnItem.input; - completedOutput = event.turnItem.output; - completedExitCode = event.turnItem.exitCode; - } + } + if (event.turnItem.status === "completed") { + completedStartedAt = event.turnItem.startedAt; + completedAt = event.turnItem.completedAt; + if (event.turnItem.type === "command_execution") { + completedInput = event.turnItem.input; + completedOutput = event.turnItem.output; + completedExitCode = event.turnItem.exitCode; } } - if (event.type === "turn.terminal") terminal = true; } + if (event.type === "turn.terminal") terminal = true; + } - assert.deepEqual(statuses, ["running", "running", "completed"]); - assert.deepEqual(completedStartedAt, runningStartedAt); - assert.isNotNull(completedAt); - assert.equal(completedInput, "true"); - assert.equal(completedOutput, undefined); - assert.equal( - runningProjectedExitCode, - undefined, - "mid-stream exit_code must not project until the tool is terminal", - ); - assert.equal(completedExitCode, 0); + assert.deepEqual(statuses, ["running", "running", "completed"]); + assert.deepEqual(completedStartedAt, runningStartedAt); + assert.isNotNull(completedAt); + assert.equal(completedInput, "true"); + assert.equal(completedOutput, undefined); + assert.equal( + runningProjectedExitCode, + undefined, + "mid-stream exit_code must not project until the tool is terminal", + ); + assert.equal(completedExitCode, 0); - yield* Queue.takeAll(protocolEvents); - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - yield* runtime.interruptTurn({ - providerThread, - providerTurnId: secondProviderTurnId, - requestRuntimeRestart: true, - }); - if (activation === "resumeThread") - yield* runtime.resumeThread({ providerThread, modelSelection, runtimePolicy }); - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 3 }), - ); - assert.equal(constructions, 2, "interrupt recovery must construct one replacement runtime"); - const loadAfterRestart = yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/resume", - ), - Stream.runHead, - ); - assert.isTrue(Option.isSome(loadAfterRestart)); - }).pipe(Effect.provide(layerTest)), + yield* Queue.takeAll(protocolEvents); + yield* runtime + .startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), + ) + .pipe(Effect.forkScoped); + yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", + ), + Stream.runHead, + ); + const secondProviderTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), + }); + yield* runtime.interruptTurn({ + providerThread, + providerTurnId: secondProviderTurnId, + requestRuntimeRestart: true, + }); + yield* runtime.startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 3 }), + ); + const loadAfterRestart = yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/resume", + ), + Stream.runHead, + ); + assert.isTrue(Option.isSome(loadAfterRestart)); + }).pipe(Effect.provide(layerTest)), ); it.effect("drains native ACP cancellation before admitting the next prompt", () => diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 05c914843c31b..5b44a32e1e5c8 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -437,9 +437,6 @@ describe("AntigravityAdapterV2 workspace changes", () => { type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; const promptReceived = yield* Deferred.make[0]>(); const host = yield* ProviderHost.ProviderHost; - const logs = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-workspace-log-" }); - const requestLog = path.join(logs, "requests.ndjson"); - const constructions: Array<{ cwd: string; policyCwd: string | null }> = []; const document = ChatFileAttachment.make({ type: "file", id: "native-pdf", @@ -455,33 +452,24 @@ describe("AntigravityAdapterV2 workspace changes", () => { userHome: process.cwd(), instanceId, selfInvocation: yield* resolveSelfInvocation(), - makeRuntime: (input) => { - constructions.push({ cwd: input.cwd, policyCwd: input.runtimePolicy.cwd }); - return makeAntigravityAcpRuntime({ + makeRuntime: (input) => + makeAntigravityAcpRuntime({ ...input, childProcessSpawner, spawn: { command: process.execPath, args: [mockAgentPath], cwd: input.cwd, - env: { - T3_ACP_ANTIGRAVITY: "1", - T3_ACP_AGENT_VERSION: "1.4.5", - T3_ACP_SESSION_LIFECYCLE: "1", - T3_ACP_RESUME_READ_PATH: path.join(input.cwd, "b.txt"), - T3_ACP_REQUEST_LOG_PATH: requestLog, - T3_ACP_HANG_PROMPT_FOREVER: constructions.length === 1 ? "0" : "1", - }, + env: { T3_ACP_ANTIGRAVITY: "1", T3_ACP_HANG_PROMPT_FOREVER: "1" }, }, }).pipe( Effect.provideService(SecureRandom.SecureRandom, crypto), Effect.map((runtime): RuntimeService => ({ ...runtime, prompt: (request) => - (constructions.length === 1 - ? Effect.void - : Deferred.succeed(promptReceived, request) - ).pipe(Effect.andThen(runtime.prompt(request))), + Deferred.succeed(promptReceived, request).pipe( + Effect.andThen(runtime.prompt(request)), + ), start: () => runtime.start().pipe( Effect.map((started) => ({ @@ -500,8 +488,7 @@ describe("AntigravityAdapterV2 workspace changes", () => { readTextFile = handler; }).pipe(Effect.andThen(runtime.handleReadTextFile(handler))), })), - ); - }, + ), withProcess: (_stop, task) => task, defaultModel: Effect.undefined, }); @@ -509,13 +496,6 @@ describe("AntigravityAdapterV2 workspace changes", () => { const workspaceB = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-b-" }); yield* fileSystem.writeFileString(path.join(workspaceA, "a.txt"), "from a"); yield* fileSystem.writeFileString(path.join(workspaceB, "b.txt"), "from b"); - for (const [workspace, marker] of [ - [workspaceA, "WORKSPACE_A"], - [workspaceB, "WORKSPACE_B"], - ] as const) { - yield* fileSystem.writeFileString(path.join(workspace, "AGENTS.md"), `${marker}_AGENTS`); - yield* fileSystem.writeFileString(path.join(workspace, "GEMINI.md"), `${marker}_GEMINI`); - } const policyFor = (cwd: string) => ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", @@ -536,106 +516,54 @@ describe("AntigravityAdapterV2 workspace changes", () => { runtimePolicy: policyFor(workspaceA), }); const now = yield* DateTime.now; - const turnInput: ProviderAdapter.ProviderAdapterV2TurnInput = { - appThread: { - createdBy: "user", - creationSource: "web", - id: threadId, - projectId: ProjectId.make("project-antigravity-workspace-change"), - title: "Antigravity workspace change", - providerInstanceId: instanceId, + yield* session + .startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-workspace-change"), + title: "Antigravity workspace change", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: workspaceB, + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make("run-antigravity-workspace-change"), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: RunAttemptId.make("attempt-antigravity-workspace-change"), + rootNodeId: NodeId.make("node-antigravity-workspace-change"), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-antigravity-workspace-change"), + text: "read b.txt", + attachments: [document], + }, modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: workspaceB, - activeProviderThreadId: providerThread.id, - lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, - forkedFrom: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - lastVisitedAt: null, - deletedAt: null, - }, - threadId, - runId: RunId.make("run-antigravity-workspace-change"), - runOrdinal: 1, - providerTurnOrdinal: 1, - attemptId: RunAttemptId.make("attempt-antigravity-workspace-change"), - rootNodeId: NodeId.make("node-antigravity-workspace-change"), - providerThread, - message: { - createdBy: "user", - creationSource: "web", - messageId: MessageId.make("message-antigravity-workspace-change"), - text: "read b.txt", - attachments: [document], - }, - modelSelection, - runtimePolicy: policyFor(workspaceB), - }; - yield* session.startTurn({ - ...turnInput, - appThread: { ...turnInput.appThread, worktreePath: workspaceA }, - runtimePolicy: policyFor(workspaceA), - runId: RunId.make("run-antigravity-workspace-a"), - attemptId: RunAttemptId.make("attempt-antigravity-workspace-a"), - rootNodeId: NodeId.make("node-antigravity-workspace-a"), - message: { - ...turnInput.message, - messageId: MessageId.make("message-antigravity-workspace-a"), - text: "remember workspace A", - }, - }); - yield* session.events.pipe( - Stream.filter((event) => event.type === "turn.terminal"), - Stream.runHead, - ); - yield* session.startTurn({ ...turnInput, runOrdinal: 2, providerTurnOrdinal: 2 }); + runtimePolicy: policyFor(workspaceB), + }) + .pipe(Effect.forkScoped); yield* session.events.pipe( Stream.filter((event) => event.type === "provider_turn.updated"), Stream.runHead, ); const sent = yield* Deferred.await(promptReceived); - const requests = (yield* fileSystem.readFileString(requestLog)) - .trim() - .split("\n") - .map( - (line) => - JSON.parse(line) as { - method: string; - params: { sessionId?: string; cwd?: string; _meta?: unknown }; - }, - ); - const setup = requests.filter((request) => - ["session/new", "session/load", "session/resume"].includes(request.method), - ); - assert.deepEqual(constructions, [ - { cwd: workspaceA, policyCwd: workspaceA }, - { cwd: workspaceB, policyCwd: workspaceB }, - ]); - assert.deepEqual( - setup.map((request) => request.method), - ["session/new", "session/resume"], - ); - assert.equal(setup[1]?.params.sessionId, providerThread.nativeThreadRef?.nativeId); - assert.equal(setup[1]?.params.cwd, workspaceB); - const originalRules = JSON.stringify(setup[0]?.params._meta); - const refreshedRules = JSON.stringify(setup[1]?.params._meta); - assert.include(originalRules, "WORKSPACE_A_AGENTS"); - assert.include(originalRules, "WORKSPACE_A_GEMINI"); - assert.include(refreshedRules, "WORKSPACE_B_AGENTS"); - assert.include(refreshedRules, "WORKSPACE_B_GEMINI"); - assert.notInclude(refreshedRules, "WORKSPACE_A"); - assert.notInclude(JSON.stringify(sent.prompt), "WORKSPACE_A"); - const snapshot = yield* session.readThreadSnapshot({ providerThread }); - assert.include(JSON.stringify(snapshot), "native-resume-started"); - assert.include(JSON.stringify(snapshot), "native-resume-read:"); - assert.include(JSON.stringify(snapshot), "from b"); - assert.include(JSON.stringify(snapshot), "remember workspace A"); assert.deepEqual( sent.prompt.filter((block) => block.type === "resource_link"), [ @@ -1225,7 +1153,7 @@ describe("AntigravityAdapterV2 runtime mode ceiling", () => { }); describe("AntigravityAdapterV2 session system prompt", () => { - it.effect.each(["1.4.5", "1.4.1", "1.5.1"])( + it.effect.each(["1.4.5", "1.4.1"])( "carries PR linking once in the %s session setup or once per turn", (agentVersion) => Effect.gen(function* () { @@ -1276,18 +1204,9 @@ describe("AntigravityAdapterV2 session system prompt", () => { }); const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-sp-" }); yield* fileSystem.makeDirectory(path.join(home, ".gemini")); - yield* fileSystem.writeFileString( - path.join(home, ".gemini", "GEMINI.md"), - "GLOBAL_RULE_28704: Use global conventions.", - ); - yield* fileSystem.writeFileString( - path.join(workspace, "AGENTS.md"), - "PROJECT_RULE_28704: Use repository conventions.", - ); - yield* fileSystem.writeFileString( - path.join(workspace, "GEMINI.md"), - "GEMINI_RULE_28704: Use Gemini conventions.", - ); + yield* fileSystem.writeFileString(path.join(home, ".gemini", "GEMINI.md"), "GLOBAL_RULE"); + yield* fileSystem.writeFileString(path.join(workspace, "AGENTS.md"), "AGENTS_RULE"); + yield* fileSystem.writeFileString(path.join(workspace, "GEMINI.md"), "GEMINI_RULE"); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", interactionMode: "default", @@ -1361,12 +1280,9 @@ describe("AntigravityAdapterV2 session system prompt", () => { assert.include(sent, "through the Antigravity harness, as gemini-test-low"); if (agentVersion === "1.4.5") { assert.include(append, "pull_request_linking"); - assert.include(append, "GLOBAL_RULE_28704"); - assert.include(append, "PROJECT_RULE_28704"); - assert.include(append, "GEMINI_RULE_28704"); - assert.isBelow(append.indexOf("GLOBAL_RULE_28704"), append.indexOf("PROJECT_RULE_28704")); - assert.isBelow(append.indexOf("PROJECT_RULE_28704"), append.indexOf("GEMINI_RULE_28704")); - assert.notInclude(sent, "PROJECT_RULE_28704"); + assert.isBelow(append.indexOf("GLOBAL_RULE"), append.indexOf("AGENTS_RULE")); + assert.isBelow(append.indexOf("AGENTS_RULE"), append.indexOf("GEMINI_RULE")); + assert.notInclude(sent, "AGENTS_RULE"); assert.notInclude(sent, ""); } else { assert.notInclude(append, "systemPrompt"); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 470dd525c8c24..4247c8c4df03c 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -32,7 +32,6 @@ import { antigravitySubagentLaunches, describeAntigravitySubagentLaunches, } from "../../provider/acp/AntigravityChildWork.ts"; -import { readAntigravityInstructions } from "../../provider/acp/AntigravityInstructions.ts"; import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts"; import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; import { @@ -76,8 +75,7 @@ export interface AntigravityAdapterV2Options { readonly userHome: string; readonly selfInvocation: SelfInvocation; readonly makeRuntime: ( - input: Omit & - Pick, + input: Omit, ) => Effect.Effect< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError | ProviderSetupError, @@ -127,6 +125,8 @@ const extractAntigravitySubagentUpdate: NonNullable cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir]; + // agy acp loads no rules files itself, so they ride the session system prompt append. + const readRulesFile = (filePath: string) => + options.fileSystem.stat(filePath).pipe( + Effect.flatMap((info) => + info.type === "File" && info.size <= RULES_FILE_MAX_BYTES + ? options.fileSystem.readFileString(filePath) + : Effect.logWarning("Skipping Antigravity rules file", { + filePath, + reason: `not a regular file of at most ${RULES_FILE_MAX_BYTES} bytes`, + }).pipe(Effect.as("")), + ), + Effect.catch((error) => + error.reason._tag === "NotFound" + ? Effect.succeed("") + : Effect.logWarning("Skipping Antigravity rules file", { filePath, error }).pipe( + Effect.as(""), + ), + ), + ); const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")( function* (input: AcpAdapterV2RuntimeInput) { const instructions: Array = []; @@ -148,8 +167,8 @@ export function makeAntigravityAcpAdapterFlavor( options.path.join(input.cwd, "AGENTS.md"), options.path.join(input.cwd, "GEMINI.md"), ]) { - const contents = yield* readAntigravityInstructions(filePath); - if (contents?.trim()) instructions.push(`# ${filePath}\n\n${contents}`); + const contents = yield* readRulesFile(filePath); + if (contents.trim()) instructions.push(`# ${filePath}\n\n${contents}`); } instructions.push(PULL_REQUEST_LINKING_INSTRUCTIONS); const scope = yield* Scope.fork(yield* Effect.scope); @@ -226,7 +245,6 @@ export function makeAntigravityAcpAdapterFlavor( // Agents that advertise HTTP MCP skip the stdio bridge process; others keep stdio. mcpOverHttp: true, sessionCarriesPullRequestLinking: antigravityAppendsSystemPrompt, - replaceRuntimeOnActivation: antigravityAppendsSystemPrompt, makeRuntime, buildAttachmentPrompt: ({ text, diff --git a/apps/server/src/provider/acp/AntigravityInstructions.test.ts b/apps/server/src/provider/acp/AntigravityInstructions.test.ts deleted file mode 100644 index 81741c9e05308..0000000000000 --- a/apps/server/src/provider/acp/AntigravityInstructions.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { assert, it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as FileSystem from "effect/FileSystem"; -import * as Path from "effect/Path"; - -import * as HostProcess from "@t3tools/shared/HostProcess"; - -import { readAntigravityInstructions } from "./AntigravityInstructions.ts"; - -it.effect("reads only bounded regular instruction files and skips missing files", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fs.makeTempDirectoryScoped(); - const file = path.join(root, "AGENTS.md"); - const limit = 256 * 1024; - yield* fs.writeFileString(file, "a".repeat(limit)); - assert.lengthOf((yield* readAntigravityInstructions(file))!, limit); - yield* fs.writeFileString(file, "a".repeat(limit + 1)); - assert.isTrue(Exit.isFailure(yield* Effect.exit(readAntigravityInstructions(file)))); - assert.isUndefined(yield* readAntigravityInstructions(path.join(root, "missing"))); - assert.isTrue(Exit.isFailure(yield* Effect.exit(readAntigravityInstructions(root)))); - if ((yield* HostProcess.Platform) !== "win32") { - const device = path.join(root, "GEMINI.md"); - yield* fs.symlink("/dev/zero", device); - assert.isTrue(Exit.isFailure(yield* Effect.exit(readAntigravityInstructions(device)))); - } - }).pipe(Effect.provide(NodeServices.layer)), -); diff --git a/apps/server/src/provider/acp/AntigravityInstructions.ts b/apps/server/src/provider/acp/AntigravityInstructions.ts deleted file mode 100644 index 1738bff255748..0000000000000 --- a/apps/server/src/provider/acp/AntigravityInstructions.ts +++ /dev/null @@ -1,60 +0,0 @@ -// Nonblocking descriptor reads prevent special files from hanging session startup. -// @effect-diagnostics nodeBuiltinImport:off -import * as NodeFS from "node:fs"; -import * as NodeFSP from "node:fs/promises"; -import * as Effect from "effect/Effect"; -import * as EffectAcpErrors from "effect-acp/errors"; - -const INSTRUCTION_MAX_BYTES = 256 * 1024; - -export const readAntigravityInstructions = Effect.fn("AntigravityInstructions.read")( - (filePath: string) => - Effect.tryPromise({ - try: async () => { - try { - const info = await NodeFSP.stat(filePath); - if (!info.isFile() || info.size > INSTRUCTION_MAX_BYTES) { - throw new Error("Instructions must be a regular file of at most 256 KiB."); - } - // Nonblocking open and descriptor validation also cover replacement by a FIFO after stat. - const file = await NodeFSP.open( - filePath, - NodeFS.constants.O_RDONLY | NodeFS.constants.O_NONBLOCK, - ); - try { - const opened = await file.stat(); - if (!opened.isFile() || opened.size > INSTRUCTION_MAX_BYTES) { - throw new Error("Instructions must be a regular file of at most 256 KiB."); - } - const buffer = Buffer.alloc(INSTRUCTION_MAX_BYTES + 1); - let size = 0; - while (size < buffer.length) { - const { bytesRead } = await file.read(buffer, size, buffer.length - size, size); - if (bytesRead === 0) break; - size += bytesRead; - } - if (size > INSTRUCTION_MAX_BYTES) { - throw new Error("Instructions exceed 256 KiB."); - } - return buffer.toString("utf8", 0, size); - } finally { - await file.close(); - } - } catch (cause) { - if ( - typeof cause === "object" && - cause !== null && - "code" in cause && - cause.code === "ENOENT" - ) - return undefined; - throw cause; - } - }, - catch: (cause) => - new EffectAcpErrors.AcpTransportError({ - detail: `Could not read Antigravity instructions at '${filePath}' (regular files up to 256 KiB only).`, - cause, - }), - }), -); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 1e7a07efbd494..332c4bee95ec6 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -407,10 +407,6 @@ export interface AcpAdapterV2Flavor { } | undefined; readonly withRuntimeStartup?: (effect: Effect.Effect) => Effect.Effect; - /** Rebuild workspace-bound startup metadata on activation, preserving the native session. */ - readonly replaceRuntimeOnActivation?: ( - initializeResult: EffectAcpSchema.InitializeResponse, - ) => boolean; readonly makeRuntime: ( input: AcpAdapterV2RuntimeInput, ) => Effect.Effect< @@ -2033,7 +2029,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const providerThreadByNativeSessionId = yield* Ref.make( new Map(), ); - let nativeBuildConfigurationBySessionId = new Map(); + const nativeBuildConfigurationBySessionId = new Map(); const initialSessionActivationFailure = yield* Ref.make<{ readonly sessionId: string; readonly error: EffectAcpErrors.AcpError; @@ -2489,7 +2485,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); }), ).pipe(Effect.asVoid); - let runtimeCwd = input.runtimePolicy.cwd ?? process.cwd(); const makeRuntimeInput = ( runtimeGeneration: number, agentRequests: Set, @@ -2499,8 +2494,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( handleRuntimeTerminationAtGeneration(runtimeGeneration), ): AcpAdapterV2RuntimeInput => { return { - cwd: latestRuntimePolicy.cwd ?? process.cwd(), - runtimePolicy: latestRuntimePolicy, + cwd: input.runtimePolicy.cwd ?? process.cwd(), + runtimePolicy: input.runtimePolicy, mcpServers: mcpContext.servers, acpMcpServers: mcpContext.acpServers, httpMcpServers: mcpContext.httpServers, @@ -6531,29 +6526,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( turnKey: context === null ? null : String(context.providerTurnId), })); - const wireAcpRuntimeClientFileHandlers = Effect.fn("AcpAdapterV2.wireClientFileHandlers")( - function* (targetRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"]) { - const clientFileSystem = flavor.clientFileSystem; - if (clientFileSystem !== undefined) { - yield* targetRuntime.handleReadTextFile((request) => - clientPolicyContext.pipe( - Effect.flatMap(({ policy }) => - clientFileSystem.readTextFile(request, policy.cwd), - ), - ), - ); - const writeTextFile = clientFileSystem.writeTextFile; - if (writeTextFile !== undefined) { - yield* targetRuntime.handleWriteTextFile((request) => - clientPolicyContext.pipe( - Effect.flatMap(({ policy }) => writeTextFile(request, policy.cwd)), - ), - ); - } - } - }, - ); - const denyClientRequest = (operation: string, disposition: "ask" | "deny") => Effect.logWarning("ACP client policy denied a client-mediated operation", { operation, @@ -6654,7 +6626,22 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.succeed(request), requestContext.requestId, ); - yield* wireAcpRuntimeClientFileHandlers(targetRuntime); + const clientFileSystem = flavor.clientFileSystem; + if (clientFileSystem !== undefined) { + yield* targetRuntime.handleReadTextFile((request) => + clientPolicyContext.pipe( + Effect.flatMap(({ policy }) => clientFileSystem.readTextFile(request, policy.cwd)), + ), + ); + const writeTextFile = clientFileSystem.writeTextFile; + if (writeTextFile !== undefined) { + yield* targetRuntime.handleWriteTextFile((request) => + clientPolicyContext.pipe( + Effect.flatMap(({ policy }) => writeTextFile(request, policy.cwd)), + ), + ); + } + } if (handlerOptions.mcp !== false) { yield* wireAcpRuntimeMcpHandlers(targetRuntime, runtimeMcpBridge); } @@ -7089,7 +7076,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runtimeMcpBridge = yield* makeRuntimeMcpBridge(mcpContext, runtimeScope); const runtimeGeneration = yield* Ref.get(runtimeCallbackGeneration); openAgentRequests = new Set(); - runtimeCwd = latestRuntimePolicy.cwd ?? process.cwd(); runtime = yield* flavor .makeRuntime( makeRuntimeInput(runtimeGeneration, openAgentRequests, mcpContext, resumeSessionId), @@ -7125,14 +7111,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( commitSessionState: ( replacement: AcpSessionRuntime.AcpSessionRuntimeStartResult, ) => Effect.Effect, - resumeSessionId?: string, - configureCandidate?: ( - candidateRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"], - started: AcpSessionRuntime.AcpSessionRuntimeStartResult, - ) => Effect.Effect< - AcpSessionRuntime.AcpSessionRuntimeStartResult, - EffectAcpErrors.AcpError | AcpModelSelectionError - >, ) { const previousScope = runtimeScope; const previousGeneration = yield* Ref.get(runtimeCallbackGeneration); @@ -7179,7 +7157,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( replacementGeneration, replacementAgentRequests, mcpContext, - resumeSessionId, + undefined, handleCandidateTermination, ), ) @@ -7194,13 +7172,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.suspend(() => handleCandidateSessionUpdate(notification)), ); yield* wireAcpRuntimeMcpHandlers(replacementRuntime, replacementMcpBridge); - yield* wireAcpRuntimeClientFileHandlers(replacementRuntime); const started = yield* replacementRuntime.start(); - const configured = - configureCandidate === undefined - ? started - : yield* configureCandidate(replacementRuntime, started); - return { replacementRuntime, started: configured }; + return { replacementRuntime, started }; }); const replacementExit = yield* Effect.exit( (flavor.withRuntimeStartup?.(startup) ?? startup).pipe( @@ -7222,7 +7195,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.uninterruptible( Effect.gen(function* () { yield* awaitAdmittedNativeResponses; - if (resumeSessionId !== undefined) yield* assertCanReactivateWorkspace; yield* wireAcpRuntimeHandlers( replacementExit.value.replacementRuntime, replacementGeneration, @@ -7244,7 +7216,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return yield* lifecycle.error; } yield* quarantineNativeTransportAtGeneration(previousGeneration); - runtimeCwd = latestRuntimePolicy.cwd ?? process.cwd(); runtime = replacementExit.value.replacementRuntime; runtimeScope = replacementScope; runtimeMcpBridge = replacementMcpBridge; @@ -7311,25 +7282,19 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( function* ( threadId: ThreadId | null, candidate: AcpSessionRuntime.AcpSessionRuntimeStartResult, - preserveHistory = false, ) { rememberTerminalEnvironment(candidate.sessionId, yield* readMcpContext(threadId)); - const restartRequired = yield* Ref.get(runtimeRestartRequired); yield* Ref.set(runtimeRestartRequired, false); yield* Ref.set(activeSessionId, candidate.sessionId); yield* setActiveSessionSetup(candidate); yield* Ref.set(activeSelection, null); yield* Ref.set(activeInteractionMode, null); - if (!preserveHistory || restartRequired) { - yield* Ref.set(promptInstructionStates, new Map()); - yield* Ref.set(promptRuntimeInstructions, new Map()); - yield* Ref.set(compactionMarkers, new Map()); - yield* Ref.set(completedCompactionIds, new Set()); - } - if (!preserveHistory) { - yield* Ref.set(providerTurns, new Map()); - yield* Ref.set(snapshot, emptySnapshotState()); - } + yield* Ref.set(promptInstructionStates, new Map()); + yield* Ref.set(promptRuntimeInstructions, new Map()); + yield* Ref.set(compactionMarkers, new Map()); + yield* Ref.set(completedCompactionIds, new Set()); + yield* Ref.set(providerTurns, new Map()); + yield* Ref.set(snapshot, emptySnapshotState()); yield* continuationPermit.withPermit( Effect.gen(function* () { yield* Ref.update(continuationGeneration, (value) => value + 1); @@ -7384,8 +7349,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( flavor.modelOptionArrivesLate === true, flavor.forkFromTurn?.supported(started.initializeResult) === true, ); - const replaceRuntimeOnActivation = - flavor.replaceRuntimeOnActivation?.(started.initializeResult) === true; const canLoadSession = started.initializeResult.agentCapabilities?.loadSession === true; const canResumeSession = started.initializeResult.agentCapabilities?.sessionCapabilities?.resume != null; @@ -7395,54 +7358,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( started.initializeResult.agentCapabilities?.promptCapabilities?.image === true, }); - const hasPendingBackgroundWork = Effect.gen(function* () { - const rootSessionId = yield* Ref.get(activeSessionId); - if ( - followsAgentWorkState && - rootSessionId !== null && - hasWorkingDescendant(rootSessionId) - ) - return true; - if ( - followsAgentWorkState && - (agentWork?.state === "running" || - agentWork?.state === "requires_action" || - agentRequests.size > 0) - ) - return true; - if ((yield* Ref.get(wakeBuffer)).length > 0) return true; - if (yield* Ref.get(continuationRequested)) return true; - if ((yield* Ref.get(runningBackgroundTaskIds)).size > 0) return true; - const active = yield* Ref.get(activeTurn); - if ( - active !== null && - [...active.subagents.values()].some(acpSubagentHasPendingBackgroundWork) - ) { - return true; - } - const carryover = yield* Ref.get(carryoverSubagents); - if (carryover !== null && carryover.subagents.some(acpSubagentHasPendingBackgroundWork)) { - return true; - } - return false; - }); - - const assertCanReactivateWorkspace = Effect.gen(function* () { - const pendingWork = yield* hasPendingBackgroundWork; - if ((yield* Ref.get(activeTurn)) !== null || pendingWork) { - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ - driver, - detail: - "Cannot reactivate an ACP workspace while background work is running; wait for it to finish or stop it first", - }); - } - }); - const activateSession = Effect.fnUntraced(function* ( sessionId: string, threadId: ThreadId | null, - modelSelection: ModelSelection, - runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, ) { const initialFailure = yield* Ref.modify(initialSessionActivationFailure, (failure) => failure?.sessionId === sessionId ? [failure.error, null] : [undefined, failure], @@ -7450,37 +7368,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (initialFailure !== undefined) { return yield* initialFailure; } - if (replaceRuntimeOnActivation) { - yield* assertCanReactivateWorkspace; - const preserveHistory = (yield* Ref.get(activeSessionId)) === sessionId; - const candidateBuildConfiguration = new Map(nativeBuildConfigurationBySessionId); - return yield* startReplacementAcpRuntime( - threadId, - (candidate) => - commitReplacementSession(threadId, candidate, preserveHistory).pipe( - Effect.tap(() => - Effect.sync(() => { - nativeBuildConfigurationBySessionId = candidateBuildConfiguration; - }), - ), - ), - sessionId, - (candidateRuntime, candidate) => - Ref.make(candidate).pipe( - Effect.flatMap((candidateSetup) => - configureSession( - candidate, - modelSelection, - runtimePolicy, - [], - candidateRuntime, - candidateBuildConfiguration, - candidateSetup, - ), - ), - ), - ); - } const mcpContext = yield* readMcpContext(threadId); const activationOptions = acpMcpActivation(mcpContext); prepareTerminalEnvironment(mcpContext, sessionId); @@ -7498,8 +7385,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const validateModelSelection = Effect.fn("AcpAdapterV2.validateModelSelection")(function* ( modelSelection: ModelSelection, - targetRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"] = runtime, - setup?: AcpSessionRuntime.AcpSessionRuntimeStartResult, ) { const model = flavor.resolveModelId?.(modelSelection) ?? modelSelection.model; if ( @@ -7510,8 +7395,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( flavor.customModels?.includes(model) === true ) return; - const option = findModelConfigOption(yield* targetRuntime.getConfigOptions); - const models = (setup ?? (yield* Ref.get(activeSessionSetup)))?.sessionSetupResult.models; + const option = findModelConfigOption(yield* runtime.getConfigOptions); + const models = (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models; const available = option?.type === "select" ? flattenSelectChoices(option.options).some((choice) => choice.value === model) @@ -7531,15 +7416,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( modelSelection: ModelSelection, runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, unsetOptionDefaults: NonNullable = [], - targetRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"] = runtime, - buildConfiguration: Map< - string, - AcpNativeBuildConfiguration - > = nativeBuildConfigurationBySessionId, - sessionSetup: Ref.Ref = activeSessionSetup, ) { - if (targetRuntime === runtime) yield* Ref.set(activeSelection, null); - yield* validateModelSelection(modelSelection, targetRuntime, startResult); + yield* Ref.set(activeSelection, null); + yield* validateModelSelection(modelSelection); const requestedModel = flavor.resolveModelId?.(modelSelection) ?? modelSelection.model; // Invalid params is the agent refusing the value, and the runtime // raises the same code when the session's model option does not offer @@ -7553,7 +7432,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (flavor.applyModelSelection !== undefined) { appliedModel = yield* flavor .applyModelSelection({ - runtime: targetRuntime, + runtime, startResult, modelSelection, }) @@ -7562,7 +7441,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // Stored catalog choices can expire; explicitly configured custom IDs // are validated by the agent instead. const isCustomModel = flavor.customModels?.includes(requestedModel) === true; - const modelOption = findModelConfigOption(yield* targetRuntime.getConfigOptions); + const modelOption = findModelConfigOption(yield* runtime.getConfigOptions); const modelState = startResult.sessionSetupResult.models; if (modelOption?.type === "select") { if ( @@ -7571,7 +7450,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (choice) => choice.value === requestedModel, ) ) { - yield* targetRuntime + yield* runtime .setConfigOption(modelOption.id, requestedModel, { resendCurrentValue: flavor.alwaysSetModel === true, }) @@ -7584,16 +7463,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( modelState.availableModels.some((model) => model.modelId === requestedModel)) ) { if (modelState.currentModelId !== requestedModel) { - yield* targetRuntime - .setSessionModel(requestedModel) - .pipe(Effect.mapError(rejectedModel)); + yield* runtime.setSessionModel(requestedModel).pipe(Effect.mapError(rejectedModel)); } appliedModel = requestedModel; } } if (appliedModel !== undefined) { const applied = appliedModel; - yield* Ref.update(sessionSetup, (setup) => { + yield* Ref.update(activeSessionSetup, (setup) => { if (setup === null) { return setup; } @@ -7610,7 +7487,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }; }); } - const configOptions = yield* targetRuntime.getConfigOptions; + const configOptions = yield* runtime.getConfigOptions; // Under a policy ceiling, a mode the user picks applies only when the flavor can place // it under the ceiling; an unknown mode could be the agent's own skip-approval mode. const ceiling = runtimePolicy.maxRuntimeMode; @@ -7684,7 +7561,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); if (!advertisedValues.includes(selection.value)) continue; } - yield* targetRuntime.setConfigOption(selection.id, selection.value).pipe( + yield* runtime.setConfigOption(selection.id, selection.value).pipe( Effect.catchTags({ AcpRequestError: (error) => error.code === -32602 @@ -7698,7 +7575,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); } for (const selection of flavor.sessionConfigForPolicy?.(runtimePolicy) ?? []) { - const option = (yield* targetRuntime.getConfigOptions).find( + const option = (yield* runtime.getConfigOptions).find( (candidate) => candidate.id === selection.id, ); if (option?.type !== "select" || option.currentValue === selection.value) continue; @@ -7706,23 +7583,23 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( "value" in entry ? [entry.value] : entry.options.map((choice) => choice.value), ); if (!advertisedValues.includes(selection.value)) continue; - yield* targetRuntime.setConfigOption(selection.id, selection.value); + yield* runtime.setConfigOption(selection.id, selection.value); } const policyMode = flavor.sessionModeForPolicy?.(runtimePolicy); if (policyMode !== undefined) { - yield* targetRuntime.setMode(policyMode); + yield* runtime.setMode(policyMode); } - const modeState = yield* targetRuntime.getModeState; + const modeState = yield* runtime.getModeState; if ( modeSelection !== undefined && typeof modeSelection.value === "string" && modeState?.availableModes.some((mode) => mode.id === modeSelection.value) === true && modeState.currentModeId !== modeSelection.value ) { - yield* targetRuntime.setMode(modeSelection.value); + yield* runtime.setMode(modeSelection.value); } - const effectiveModeState = yield* targetRuntime.getModeState; - const effectiveConfigOptions = yield* targetRuntime.getConfigOptions; + const effectiveModeState = yield* runtime.getModeState; + const effectiveConfigOptions = yield* runtime.getConfigOptions; const planSensitiveOptions = effectiveConfigOptions.filter( ( option, @@ -7734,8 +7611,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (option.category === "mode" || option.category === "collaboration_mode"), ); if (runtimePolicy.interactionMode === "plan") { - if (!buildConfiguration.has(startResult.sessionId)) { - buildConfiguration.set(startResult.sessionId, { + if (!nativeBuildConfigurationBySessionId.has(startResult.sessionId)) { + nativeBuildConfigurationBySessionId.set(startResult.sessionId, { ...(effectiveModeState === undefined ? {} : { modeId: effectiveModeState.currentModeId }), @@ -7749,7 +7626,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( isAcpPlanModeId(mode.id), ); if (planMode !== undefined && effectiveModeState?.currentModeId !== planMode.id) { - yield* targetRuntime.setMode(planMode.id); + yield* runtime.setMode(planMode.id); } for (const option of planSensitiveOptions) { const choices = option.options.flatMap((entry) => @@ -7757,11 +7634,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); const requested = choices.find(isAcpPlanModeId); if (requested !== undefined && option.currentValue !== requested) { - yield* targetRuntime.setConfigOption(option.id, requested); + yield* runtime.setConfigOption(option.id, requested); } } } else { - const nativeBuild = buildConfiguration.get(startResult.sessionId); + const nativeBuild = nativeBuildConfigurationBySessionId.get(startResult.sessionId); if (nativeBuild !== undefined) { if ( nativeBuild.modeId !== undefined && @@ -7770,7 +7647,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (mode) => mode.id === nativeBuild.modeId, ) === true ) { - yield* targetRuntime.setMode(nativeBuild.modeId); + yield* runtime.setMode(nativeBuild.modeId); } for (const saved of nativeBuild.configOptions) { const option = effectiveConfigOptions.find( @@ -7781,22 +7658,20 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( "value" in entry ? [entry.value] : entry.options.map((choice) => choice.value), ); if (option.currentValue !== saved.value && choices.includes(saved.value)) { - yield* targetRuntime.setConfigOption(option.id, saved.value); + yield* runtime.setConfigOption(option.id, saved.value); } } - buildConfiguration.delete(startResult.sessionId); + nativeBuildConfigurationBySessionId.delete(startResult.sessionId); } } - const configuredSetup = (yield* Ref.get(sessionSetup)) ?? startResult; - yield* validateModelSelection(modelSelection, targetRuntime, configuredSetup); + yield* validateModelSelection(modelSelection); yield* ( flavor.onSessionConfigurationUpdate?.( - yield* targetRuntime.getConfigOptions, - yield* targetRuntime.getModeState, - configuredSetup.sessionSetupResult.models, + yield* runtime.getConfigOptions, + yield* runtime.getModeState, + (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models, ) ?? Effect.void ); - return configuredSetup; }); yield* configureSession( @@ -8385,11 +8260,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const restartRuntimeAfterTeardownIfRequired = Effect.fnUntraced(function* ( threadId: ThreadId | null, - replacingRuntime = false, ) { const restartRequired = yield* Ref.get(runtimeRestartRequired); if (!restartRequired) return false; - if (replacingRuntime) return true; yield* restartAcpRuntime(threadId); yield* Ref.set(runtimeRestartRequired, false); yield* Ref.set(activeSessionId, null); @@ -8418,39 +8291,18 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } useProviderThreadIdentity(turnInput.providerThread); // load/resume can invoke client methods; install the incoming policy before activation. - const previousRuntimePolicy = latestRuntimePolicy; latestRuntimePolicy = turnInput.runtimePolicy; const requestedSessionId = yield* nativeThreadId(driver, turnInput.providerThread); const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired( turnInput.threadId, - replaceRuntimeOnActivation, ); const needsSessionActivation = - (yield* Ref.get(activeSessionId)) !== requestedSessionId || - restartAfterInterrupt || - (replaceRuntimeOnActivation && - runtimeCwd !== (latestRuntimePolicy.cwd ?? process.cwd())); + (yield* Ref.get(activeSessionId)) !== requestedSessionId || restartAfterInterrupt; if (needsSessionActivation) { - const activated = yield* activateSession( - requestedSessionId, - turnInput.threadId, - turnInput.modelSelection, - turnInput.runtimePolicy, - ).pipe( - Effect.tapError(() => - Effect.sync(() => { - latestRuntimePolicy = previousRuntimePolicy; - }), - ), - ); + const activated = yield* activateSession(requestedSessionId, turnInput.threadId); yield* Ref.set(activeSessionId, activated.sessionId); yield* setActiveSessionSetup(activated); - if (!replaceRuntimeOnActivation) - yield* configureSession( - activated, - turnInput.modelSelection, - turnInput.runtimePolicy, - ); + yield* configureSession(activated, turnInput.modelSelection, turnInput.runtimePolicy); yield* Ref.set(activeSelection, turnInput.modelSelection); yield* Ref.set(activeInteractionMode, turnInput.runtimePolicy.interactionMode); } else { @@ -9015,7 +8867,40 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }), ...(postSettleContinuationEnabled || followsAgentWorkState ? { - hasPendingBackgroundWork, + hasPendingBackgroundWork: Effect.gen(function* () { + const rootSessionId = yield* Ref.get(activeSessionId); + if ( + followsAgentWorkState && + rootSessionId !== null && + hasWorkingDescendant(rootSessionId) + ) + return true; + if ( + followsAgentWorkState && + (agentWork?.state === "running" || + agentWork?.state === "requires_action" || + agentRequests.size > 0) + ) + return true; + if ((yield* Ref.get(wakeBuffer)).length > 0) return true; + if (yield* Ref.get(continuationRequested)) return true; + if ((yield* Ref.get(runningBackgroundTaskIds)).size > 0) return true; + const active = yield* Ref.get(activeTurn); + if ( + active !== null && + [...active.subagents.values()].some(acpSubagentHasPendingBackgroundWork) + ) { + return true; + } + const carryover = yield* Ref.get(carryoverSubagents); + if ( + carryover !== null && + carryover.subagents.some(acpSubagentHasPendingBackgroundWork) + ) { + return true; + } + return false; + }), } : {}), ensureThread: Effect.fn("AcpAdapterV2.ensureThread")( @@ -9034,8 +8919,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( "Cannot replace ACP session while a turn or background work is active", }); yield* awaitRuntimeTeardown(); - const previousRuntimePolicy = latestRuntimePolicy; - latestRuntimePolicy = threadInput.runtimePolicy; const previousItemIdentityVersion = itemIdentityVersion; itemIdentityVersion = 2; prepareTerminalEnvironment(yield* readMcpContext(threadInput.threadId)); @@ -9045,7 +8928,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.tapError(() => Effect.sync(() => { itemIdentityVersion = previousItemIdentityVersion; - latestRuntimePolicy = previousRuntimePolicy; }), ), ); @@ -9106,43 +8988,20 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const restorePreviousItemIdentity = Effect.sync(() => { itemIdentityVersion = previousItemIdentityVersion; }); - const nextSelection = threadInput.modelSelection ?? input.modelSelection; - const nextRuntimePolicy = threadInput.runtimePolicy ?? latestRuntimePolicy; - const previousRuntimePolicy = latestRuntimePolicy; - latestRuntimePolicy = nextRuntimePolicy; const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired( threadInput.providerThread.appThreadId, - replaceRuntimeOnActivation, ).pipe(Effect.tapError(() => restorePreviousItemIdentity)); - if ( - (yield* Ref.get(activeSessionId)) !== sessionId || - restartAfterInterrupt || - (replaceRuntimeOnActivation && - runtimeCwd !== (nextRuntimePolicy.cwd ?? process.cwd())) - ) { - if (!replaceRuntimeOnActivation) { - yield* Ref.set(snapshot, emptySnapshotState()); - } + if ((yield* Ref.get(activeSessionId)) !== sessionId || restartAfterInterrupt) { + yield* Ref.set(snapshot, emptySnapshotState()); const activated = yield* activateSession( sessionId, threadInput.providerThread.appThreadId, - nextSelection, - nextRuntimePolicy, - ).pipe( - Effect.tapError(() => - restorePreviousItemIdentity.pipe( - Effect.andThen( - Effect.sync(() => { - latestRuntimePolicy = previousRuntimePolicy; - }), - ), - ), - ), - ); + ).pipe(Effect.tapError(() => restorePreviousItemIdentity)); yield* Ref.set(activeSessionId, activated.sessionId); yield* setActiveSessionSetup(activated); - if (!replaceRuntimeOnActivation) - yield* configureSession(activated, nextSelection, nextRuntimePolicy); + const nextSelection = threadInput.modelSelection ?? input.modelSelection; + const nextRuntimePolicy = threadInput.runtimePolicy ?? input.runtimePolicy; + yield* configureSession(activated, nextSelection, nextRuntimePolicy); yield* Ref.set(activeSelection, nextSelection); yield* Ref.set(activeInteractionMode, nextRuntimePolicy.interactionMode); } From 3405a023a8fa8757a9303db1cabdf63104e4e2f0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 14 Nov 2026 14:04:35 +0000 Subject: [PATCH 5/5] fix(server): send Antigravity rules with turns when the agent drops the append Agents without system-prompt append support, such as 1.4.1, discarded the rules with the session metadata. They now ride the turn prompt alongside T3's runtime instructions, which the ACP adapter resends on a session's first turn and after compaction. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AntigravityAdapterV2.test.ts | 2 + .../Adapters/AntigravityAdapterV2.ts | 46 ++++++++++++++----- 2 files changed, 36 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 5b44a32e1e5c8..2c58b5326a302 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1287,6 +1287,8 @@ describe("AntigravityAdapterV2 session system prompt", () => { } else { assert.notInclude(append, "systemPrompt"); assert.include(sent, ""); + assert.isBelow(sent.indexOf("GLOBAL_RULE"), sent.indexOf("AGENTS_RULE")); + assert.isBelow(sent.indexOf("AGENTS_RULE"), sent.indexOf("GEMINI_RULE")); } }).pipe(Effect.provide(layerSession)), ); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 4247c8c4df03c..cd99f4cf4f409 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -127,6 +127,19 @@ const extractAntigravitySubagentUpdate: NonNullable[0]; + +// The ACP adapter resends runtime instructions on a session's first turn, after compaction and on +// change; rules follow them so the agent's history keeps one current copy. +const withTurnRules = (payload: PromptPayload, rules: string): PromptPayload => { + const index = payload.prompt.findIndex( + (block) => block.type === "text" && block.text.startsWith(""), + ); + return index === -1 + ? payload + : { ...payload, prompt: payload.prompt.toSpliced(index, 0, { type: "text", text: rules }) }; +}; + interface AntigravityFlavorServices { readonly random: SecureRandom.SecureRandom["Service"]; readonly fileSystem: FileSystem.FileSystem; @@ -161,16 +174,18 @@ export function makeAntigravityAcpAdapterFlavor( ); const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")( function* (input: AcpAdapterV2RuntimeInput) { - const instructions: Array = []; + const rules: Array = []; for (const filePath of [ options.path.join(options.userHome, ".gemini", "GEMINI.md"), options.path.join(input.cwd, "AGENTS.md"), options.path.join(input.cwd, "GEMINI.md"), ]) { const contents = yield* readRulesFile(filePath); - if (contents.trim()) instructions.push(`# ${filePath}\n\n${contents}`); + if (contents.trim()) rules.push(`# ${filePath}\n\n${contents}`); } - instructions.push(PULL_REQUEST_LINKING_INSTRUCTIONS); + const rulesText = rules.join("\n\n"); + // Set on start: whether this agent drops the system-prompt append, so rules ride the turns. + let rulesInTurns = false; const scope = yield* Scope.fork(yield* Effect.scope); const runtime = yield* options .withProcess( @@ -178,7 +193,7 @@ export function makeAntigravityAcpAdapterFlavor( options.makeRuntime({ ...input, clientFileReads: true, - sessionSystemPromptAppend: instructions.join("\n\n"), + sessionSystemPromptAppend: [...rules, PULL_REQUEST_LINKING_INSTRUCTIONS].join("\n\n"), additionalDirectories: [options.host.paths.attachmentsDir], }), ) @@ -212,7 +227,14 @@ export function makeAntigravityAcpAdapterFlavor( ), ), prompt: (payload, promptOptions) => - Effect.sync(reads.reset).pipe(Effect.andThen(runtime.prompt(payload, promptOptions))), + Effect.sync(reads.reset).pipe( + Effect.andThen( + runtime.prompt( + rulesInTurns ? withTurnRules(payload, rulesText) : payload, + promptOptions, + ), + ), + ), handleSessionUpdate: (handler) => { projectUpdate = handler; return runtime.handleSessionUpdate((notification) => @@ -220,13 +242,13 @@ export function makeAntigravityAcpAdapterFlavor( ); }, start: () => - runtime - .start() - .pipe( - Effect.tap( - (started) => options.onSessionStarted?.(started, input.cwd) ?? Effect.void, - ), - ), + runtime.start().pipe( + Effect.tap((started) => { + rulesInTurns = + rulesText !== "" && !antigravityAppendsSystemPrompt(started.initializeResult); + return options.onSessionStarted?.(started, input.cwd) ?? Effect.void; + }), + ), } satisfies typeof runtime; }, Effect.provideService(SecureRandom.SecureRandom, options.random),