Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
182 changes: 178 additions & 4 deletions apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import * as Fiber from "effect/Fiber";
import * as DateTime from "effect/DateTime";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
Expand Down Expand Up @@ -209,7 +210,8 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* (
entries: ReadonlyArray<unknown>,
replayGate?: ProviderReplayGate,
continuationEnabled = true,
agentId = "claude-acp",
agentId: string | Record<string, unknown> = "claude-acp",
runtimeMode: "approval-required" | "full-access" = "approval-required",
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
Expand Down Expand Up @@ -251,7 +253,9 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* (
const adapterOptions = {
selfInvocation: yield* resolveSelfInvocation(),
instanceId,
settings: yield* decodeAcpRegistryAdapterSettings({ agentId }),
settings: yield* decodeAcpRegistryAdapterSettings(
typeof agentId === "string" ? { agentId } : agentId,
),
environment: {},
...(continuationEnabled ? { continuationRequests } : {}),
makeRuntime: (runtimeInput: Parameters<typeof replayRuntime>[0]) => {
Expand All @@ -274,7 +278,6 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* (
);
const threadId = ThreadId.make("thread-claude-lifecycle");
const modelSelection = { instanceId, model: "default" } as const;
const runtimeMode = "approval-required";
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode,
interactionMode: "default",
Expand All @@ -287,7 +290,7 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* (
runtimePolicy,
});
yield* Effect.addFinalizer(() => Effect.sync(() => replayGate?.releaseAll()));
if (continuationEnabled) {
if (continuationEnabled && typeof agentId === "string") {
assert.isDefined(
runtime.hasPendingBackgroundWork,
"Claude ACP v2 must report background work after foreground idle",
Expand Down Expand Up @@ -434,6 +437,177 @@ const claudeUnrelatedChildren = [
];

describe("AcpRegistryAdapterV2", () => {
it.effect.each([
{ commandPath: "/root/.local/bin/agy", offers: 1 },
{ commandPath: "C:\\tools\\agy.exe", offers: 1 },
{ commandPath: "/opt/bin/other-agent", offers: 0 },
])("continues late output only for agy ($commandPath)", ({ commandPath, offers }) =>
Effect.gen(function* () {
const gate = makeProviderReplayGate(["wake"]);
const update = (sessionUpdate: Record<string, unknown>) =>
claudeFrames.update(CLAUDE_ROOT_SESSION, sessionUpdate);
const session = yield* openClaudeReplaySession(
[
{
type: "expect_outbound",
frame: { kind: "request", method: "initialize", params: "<any>" },
},
{
type: "emit_inbound",
frame: {
kind: "response",
method: "initialize",
result: {
protocolVersion: 1,
agentInfo: { name: "Antigravity ACP Server", version: "1.5.9" },
agentCapabilities: { loadSession: true },
authMethods: [],
},
},
},
claudeFrames.open[2],
claudeFrames.open[3],
claudeFrames.prompt(1)[0],
{
type: "emit_inbound",
frame: {
kind: "response",
method: "session/prompt",
result: { stopReason: "end_turn" },
},
},
{
...update({
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "Background work finished." },
}),
label: "wake",
},
claudeMarker("late output received"),
],
gate,
true,
{ source: "local", commandPath, commandArgs: ["acp"] },
);
yield* session.runtime.startTurn(session.turnInput(1));
assert.equal((yield* session.terminal).status, "completed");
gate.release("wake");
yield* session.throughMarker("late output received");
assert.lengthOf(session.offers, offers, "late output must only wake agy");
if (offers === 0) return;
yield* session.offers[0]!.dispatchIfCurrent!(Effect.void);
yield* session.runtime.startTurn(session.turnInput(2, { continuation: true }));
yield* TestClock.adjust("3 seconds");
const continued = yield* session.until((event) => event.type === "turn.terminal");
assert.include(JSON.stringify(continued), "Background work finished.");
const terminal = continued.at(-1)!;
if (terminal.type !== "turn.terminal") throw new Error("Missing continuation terminal");
assert.equal(terminal.status, "completed");
}).pipe(Effect.provide(layerTest)),
);

it.effect.each(["approval-required", "full-access"] as const)(
"continues an agy permission request after the prompt settles (%s)",
(runtimeMode) =>
Effect.gen(function* () {
const gate = makeProviderReplayGate(["wake"]);
const session = yield* openClaudeReplaySession(
[
{
type: "expect_outbound",
frame: { kind: "request", method: "initialize", params: "<any>" },
},
{
type: "emit_inbound",
frame: {
kind: "response",
method: "initialize",
result: {
protocolVersion: 1,
agentInfo: { name: "Antigravity ACP Server", version: "1.5.9" },
agentCapabilities: { loadSession: true },
authMethods: [],
},
},
},
claudeFrames.open[2],
claudeFrames.open[3],
claudeFrames.prompt(1)[0],
{
type: "emit_inbound",
frame: {
kind: "response",
method: "session/prompt",
result: { stopReason: "end_turn" },
},
},
{
type: "emit_inbound",
label: "wake",
frame: {
kind: "request",
method: "session/request_permission",
params: {
sessionId: CLAUDE_ROOT_SESSION,
toolCall: {
toolCallId: "late-command",
title: "Run command",
kind: "execute",
status: "pending",
},
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
},
},
},
claudeMarker("late permission received"),
{
type: "expect_outbound",
frame: {
kind: "response",
method: "session/request_permission",
result: { outcome: { outcome: "selected", optionId: "allow" } },
},
},
claudeFrames.update(CLAUDE_ROOT_SESSION, {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "Command approved." },
}),
],
gate,
true,
{ source: "local", commandPath: "/root/.local/bin/agy", commandArgs: ["acp"] },
runtimeMode,
);
yield* session.runtime.startTurn(session.turnInput(1));
assert.equal((yield* session.terminal).status, "completed");
gate.release("wake");
yield* session.throughMarker("late permission received");
assert.lengthOf(session.offers, 1, "a permission request must offer a continuation");
yield* session.offers[0]!.dispatchIfCurrent!(Effect.void);
yield* session.runtime.startTurn(session.turnInput(2, { continuation: true }));
if (runtimeMode === "approval-required") {
const events = yield* session.until(
(event) =>
event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
);
const request = events.at(-1)!;
if (request.type !== "runtime_request.updated") throw new Error("Missing approval");
yield* TestClock.adjust("5 seconds");
yield* session.runtime.respondToRuntimeRequest({
requestId: request.runtimeRequest.id,
decision: "accept",
});
}
const output = yield* session.until(
(event) => event.type === "message.updated" && event.message.text === "Command approved.",
);
assert.isTrue(output.some((event) => event.type === "message.updated"));
assert.isFalse(output.some((event) => event.type === "turn.terminal"));
yield* TestClock.adjust("3 seconds");
assert.equal((yield* session.terminal).status, "completed");
}).pipe(Effect.provide(layerTest)),
);

it("preserves and sanitizes structured ACP errors without exposing arbitrary defects", () => {
const limit = new EffectAcpErrors.AcpRequestError({
code: -31001,
Expand Down
10 changes: 10 additions & 0 deletions packages/provider-acp-registry/src/server/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,9 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
const startupKey =
options.settings.source === "local" ? `local:${options.instanceId}` : registryAgentId;
const isDevin = registryAgentId === "devin";
const isAntigravityCli =
options.settings.source === "local" &&
/^agy(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? "");
const isOmp =
options.settings.source === "local" &&
/^omp(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? "");
Expand Down Expand Up @@ -239,6 +242,13 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
: AcpProviderCapabilitiesV2,
customModels: readCustomModelEntries(options.settings.customModels).map((entry) => entry.slug),
compactViaAdvertisedCommand: true,
...(isAntigravityCli
? {
enablePostSettleContinuation: true,
deferFinalizeForBackgroundWork: true,
wakeOnDetachedRequest: true,
}
: {}),
promptFailure: (cause) => acpRegistryPromptFailure(registryAgentId, cause),
...(registryAgentId === "factory-droid"
? { extractElicitationForm: extractDroidElicitationForm }
Expand Down
26 changes: 23 additions & 3 deletions packages/provider-acp/src/server/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,8 @@ export interface AcpAdapterV2Flavor {
readonly terminateRuntimeProcessGroupOnInterrupt?: boolean;
readonly preserveRuntimeOnSettledInterrupt?: boolean;
readonly enablePostSettleContinuation?: boolean;
/** A native request after prompt settlement starts a continuation before it is handled. */
readonly wakeOnDetachedRequest?: boolean;
/** Settle on native idle after the accepted user echo, only on negotiated ACP v2. */
readonly followAgentWorkState?: boolean;
/**
Expand Down Expand Up @@ -4000,6 +4002,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
/Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text);

const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => {
if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true;
if (context.awaitingBackgroundHydration.size > 0) return true;
if (context.pendingInjectedReport.size > 0) return true;
for (const [taskId, toolCallId] of context.toolCallIdsByBackgroundTaskId) {
Expand Down Expand Up @@ -5248,7 +5251,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
});

const awaitRequestTurn = Effect.fnUntraced(function* (generation: number) {
if (!followsAgentWorkState) return true;
if (
!followsAgentWorkState &&
!(postSettleContinuationEnabled && flavor.wakeOnDetachedRequest)
)
return true;
while (true) {
const waiting = yield* runRuntimeCallbackAtGeneration(
generation,
Expand All @@ -5271,7 +5278,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
(generation: number) =>
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
Effect.suspend(() =>
!followsAgentWorkState
!followsAgentWorkState &&
!(postSettleContinuationEnabled && flavor.wakeOnDetachedRequest)
? effect
: Effect.acquireUseRelease(
runRuntimeCallbackAtGeneration(
Expand All @@ -5290,6 +5298,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
if (Option.isSome(token)) agentRequests.delete(token.value);
const context = yield* Ref.get(activeTurn);
if (context !== null) yield* settleIdleWork(context);
if (context !== null && flavor.wakeOnDetachedRequest)
yield* rearmDeferredFinalize(context);
}),
).pipe(Effect.asVoid),
),
Expand Down Expand Up @@ -6850,6 +6860,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
}
yield* targetRuntime.handleRequestPermission((nativeParams, requestContext) =>
Effect.gen(function* () {
if (
postSettleContinuationEnabled &&
flavor.wakeOnDetachedRequest &&
nativeParams.sessionId !== (yield* Ref.get(activeSessionId))
) {
return { outcome: { outcome: "cancelled" } } as const;
}
const trackedTurn = yield* Ref.get(activeTurn);
const params =
trackedTurn !== null && nativeParams.sessionId === (yield* Ref.get(activeSessionId))
Expand Down Expand Up @@ -6887,7 +6904,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
request: EffectAcpSchema.RequestPermissionRequest = params,
) => (flavor.permissionDisposition ?? acpPermissionDisposition)(policy, request);
if (followsAgentWorkState && dispositionFor(latestRuntimePolicy) === "ask") {
if (
(followsAgentWorkState && dispositionFor(latestRuntimePolicy) === "ask") ||
(postSettleContinuationEnabled && flavor.wakeOnDetachedRequest)
) {
if (!(yield* awaitRequestTurn(handlerGeneration)))
return { outcome: { outcome: "cancelled" } } as const;
}
Expand Down
Loading