Skip to content
Merged
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
119 changes: 97 additions & 22 deletions apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,21 +211,38 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* (
replayGate?: ProviderReplayGate,
continuationEnabled = true,
agentId: string | Record<string, unknown> = "claude-acp",
replacementEntries?: ReadonlyArray<unknown>,
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const replayDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-lifecycle-" });
const transcript = yield* decodeAcpReplayTranscript(
{
provider: ACP_REGISTRY_PROVIDER,
protocol: "acp.ndjson-jsonrpc",
version: "1",
scenario: "claude-lifecycle",
entries: entries as never,
},
ACP_REGISTRY_PROVIDER,
const scriptPath = yield* path.fromFileUrl(
new URL("../../../scripts/acp-replay-agent.ts", import.meta.url),
);
const makeReplay = Effect.fn("openClaudeReplaySession.makeReplay")(function* (
entries: ReadonlyArray<unknown>,
name: string,
) {
const transcript = yield* decodeAcpReplayTranscript(
{
provider: ACP_REGISTRY_PROVIDER,
protocol: "acp.ndjson-jsonrpc",
version: "1",
scenario: name,
entries: entries as never,
},
ACP_REGISTRY_PROVIDER,
);
return makeAcpReplayRuntime({
transcript,
statusPath: path.join(replayDir, `${name}.json`),
scriptPath,
childProcessSpawner,
fileSystem,
...(replayGate === undefined ? {} : { replayGate }),
});
});
const offers: Array<ProviderContinuationRequest> = [];
const offered = yield* Queue.unbounded<void>();
const continuationRequests = {
Expand All @@ -239,16 +256,12 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* (
let onTermination: NonNullable<
AcpSessionRuntime.AcpSessionRuntimeOptions["onTermination"]
> = () => Effect.die("Runtime has not started");
const replayRuntime = makeAcpReplayRuntime({
transcript,
statusPath: path.join(replayDir, "status.json"),
scriptPath: yield* path.fromFileUrl(
new URL("../../../scripts/acp-replay-agent.ts", import.meta.url),
),
childProcessSpawner,
fileSystem,
...(replayGate === undefined ? {} : { replayGate }),
});
const replayRuntime = yield* makeReplay(entries, "claude-lifecycle");
const replacementRuntime =
replacementEntries === undefined
? replayRuntime
: yield* makeReplay(replacementEntries, "replacement");
let started = false;
const adapterOptions = {
selfInvocation: yield* resolveSelfInvocation(),
instanceId,
Expand All @@ -259,7 +272,9 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* (
...(continuationEnabled ? { continuationRequests } : {}),
makeRuntime: (runtimeInput: Parameters<typeof replayRuntime>[0]) => {
onTermination = runtimeInput.onTermination;
return replayRuntime({
const replay = started ? replacementRuntime : replayRuntime;
started = true;
return replay({
...runtimeInput,
protocolLogging: {
logIncoming: false,
Expand Down Expand Up @@ -2001,7 +2016,10 @@ describe("AcpRegistryAdapterV2", () => {
);

// regression: #38599 Hermes replies on its own when a background process it started exits
it.effect("does not drop Hermes' reply after a background process finishes", () =>
it.effect.each([
{ launch: "hermes acp", commandPath: "hermes", commandArgs: ["acp"] },
{ launch: "a wrapper", commandPath: "node", commandArgs: ["hermes-acp.mjs"] },
])("does not drop Hermes' reply after a background process finishes ($launch)", (launch) =>
Effect.gen(function* () {
const gate = makeProviderReplayGate(["process-exit"]);
const sessionId = "hermes-session";
Expand Down Expand Up @@ -2061,7 +2079,7 @@ describe("AcpRegistryAdapterV2", () => {
],
gate,
true,
{ source: "local", commandPath: "hermes", commandArgs: ["acp"] },
{ source: "local", commandPath: launch.commandPath, commandArgs: launch.commandArgs },
);
yield* session.runtime.startTurn(session.turnInput(1));
const foreground = yield* session.until((event) => event.type === "turn.terminal");
Expand All @@ -2078,6 +2096,63 @@ describe("AcpRegistryAdapterV2", () => {
}).pipe(Effect.provide(layerTest)),
);

it.effect("protects Hermes background work when a wrapper launches it on replacement", () =>
Effect.gen(function* () {
const gate = makeProviderReplayGate(["process-exit"]);
const request = (method: string) => ({
type: "expect_outbound",
frame: { kind: "request", method, params: "<any>" },
});
const respond = (method: string, result: object) => ({
type: "emit_inbound",
frame: { kind: "response", method, result },
});
const open = (sessionId: string, name: string) => [
request("initialize"),
respond("initialize", { protocolVersion: 1, agentInfo: { name, version: "1.0.0" } }),
request("session/new"),
respond("session/new", { sessionId }),
];
const sessionId = "hermes-replacement";
const session = yield* openClaudeReplaySession(
open("initial-session", "generic-agent"),
gate,
true,
{ source: "local", commandPath: "node", commandArgs: ["agent-wrapper.mjs"] },
[
...open(sessionId, "hermes-agent"),
request("session/prompt"),
respond("session/prompt", { stopReason: "end_turn" }),
{
...claudeFrames.update(sessionId, {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "Background command finished" },
}),
label: "process-exit",
},
],
);
const { threadId, modelSelection, runtimePolicy } = session.turnInput(1);
const replaceThread = {
threadId,
modelSelection,
runtimePolicy,
forceNewNativeThread: true,
};
const pendingWork = session.runtime.hasPendingBackgroundWork ?? Effect.succeed(false);
assert.isFalse(yield* pendingWork);
const providerThread = yield* session.runtime.ensureThread(replaceThread);
yield* session.runtime.startTurn({ ...session.turnInput(1), providerThread });
assert.equal((yield* session.terminal).status, "completed");

gate.release("process-exit");
yield* Queue.take(session.offered);
assert.isTrue(yield* pendingWork);
const error = yield* session.runtime.ensureThread(replaceThread).pipe(Effect.flip);
assert.include(String(error.cause), "background work is active");
}).pipe(Effect.provide(layerTest)),
);

// Copilot flattens MCP titles and reports kind "read" for MCP calls and glob ("other" for rg);
// its native tool.execution_start event carries the real identity.
it.effect.each(["glob", "rg"])("keeps Copilot's MCP and %s identity", (toolName) =>
Expand Down
15 changes: 8 additions & 7 deletions packages/provider-acp-registry/src/server/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,10 @@ function makeAcpRegistryRuntime(
});
}

const isHermes = (
initializeResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["initializeResult"],
) => initializeResult.agentInfo?.name === "hermes-agent";

export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(function* (
options: AcpRegistryAdapterV2Options,
) {
Expand Down Expand Up @@ -212,10 +216,6 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
registryAgentId === "kimi-code" ||
(options.settings.source === "local" &&
/^kimi(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""));
// Hermes Agent is not in the public registry; local installs run `hermes acp`.
const isHermes =
options.settings.source === "local" &&
/^hermes(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? "");
const isClaude =
registryAgentId === "claude-acp" ||
(options.settings.source === "local" &&
Expand Down Expand Up @@ -289,9 +289,10 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
: {}),
// Hermes replies on the root session when a background process it started exits; no
// prompt response follows, so the continuation ends on the deferred-finalize debounce.
...(isHermes
? { enablePostSettleContinuation: true, deferFinalizeForBackgroundWork: true }
: {}),
// Hermes is not in the public registry and may run through a wrapper, so only its
// initialize reply identifies it.
enablePostSettleContinuation: isHermes,
deferFinalizeForBackgroundWork: isHermes,
...(isDevin
? {
clientCapabilitiesMeta: {
Expand Down
45 changes: 35 additions & 10 deletions packages/provider-acp/src/server/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -585,7 +585,7 @@ export interface AcpAdapterV2Flavor {
readonly isProviderWakeNotification?: (
notification: EffectAcpSchema.SessionNotification,
) => boolean;
readonly deferFinalizeForBackgroundWork?: boolean;
readonly deferFinalizeForBackgroundWork?: AcpNegotiatedFlag;
readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
/** Interrupt the local prompt fiber before `session/cancel` (Grok wedged prompts). */
readonly interruptPromptOnCancel?: boolean;
Expand Down Expand Up @@ -617,7 +617,7 @@ export interface AcpAdapterV2Flavor {
readonly restartRuntimeOnEveryInterrupt?: boolean;
readonly terminateRuntimeProcessGroupOnInterrupt?: boolean;
readonly preserveRuntimeOnSettledInterrupt?: boolean;
readonly enablePostSettleContinuation?: boolean;
readonly enablePostSettleContinuation?: AcpNegotiatedFlag;
/** Settle on native idle after the accepted user echo, only on negotiated ACP v2. */
readonly followAgentWorkState?: boolean;
/**
Expand All @@ -635,6 +635,19 @@ export interface AcpAdapterV2Flavor {
) => boolean;
}

/**
* A flavor flag that is either fixed, or read from the agent's `initialize` result for
* agents identified only there, such as one launched through a wrapper command.
*/
type AcpNegotiatedFlag =
| boolean
| ((initializeResult: EffectAcpSchema.InitializeResponse) => boolean);

const readNegotiatedFlag = (
flag: AcpNegotiatedFlag | undefined,
initializeResult: EffectAcpSchema.InitializeResponse,
) => (typeof flag === "function" ? flag(initializeResult) : flag === true);

function acpSupportsImagePrompts(input: {
readonly flavorSupportsImagePrompts?: boolean | undefined;
readonly negotiatedImage?: boolean | undefined;
Expand Down Expand Up @@ -1849,8 +1862,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
);
const driver = flavor.driver;
const continuationRequests = options.continuationRequests;
const postSettleContinuationEnabled =
flavor.enablePostSettleContinuation === true && continuationRequests !== undefined;

const readCapabilities = Effect.gen(function* () {
if (flavor.supportsNativeGoals === undefined) return flavor.capabilities;
Expand Down Expand Up @@ -2057,6 +2068,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
};
let pendingStopCloseTurn: ActiveAcpTurn | null = null;
let followsAgentWorkState = false;
let postSettleContinuationEnabled = false;
let defersFinalizeForBackgroundWork = false;
let agentWork: Extract<
EffectAcpSchema.SessionUpdate,
{ sessionUpdate: "state_update" }
Expand Down Expand Up @@ -2097,6 +2110,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
flavor.followAgentWorkState === true &&
continuationRequests !== undefined &&
setup.initializeResult.protocolVersion === 2;
postSettleContinuationEnabled =
continuationRequests !== undefined &&
readNegotiatedFlag(flavor.enablePostSettleContinuation, setup.initializeResult);
defersFinalizeForBackgroundWork = readNegotiatedFlag(
flavor.deferFinalizeForBackgroundWork,
setup.initializeResult,
);
agentWork = null;
rootForegroundWork = undefined;
agentRequests.clear();
Expand Down Expand Up @@ -4053,7 +4073,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
const rearmDeferredFinalize =
/* Provider events include streaming deltas; avoid a span for each update. */
Effect.fnUntraced(function* (context: ActiveAcpTurn) {
if (!flavor.deferFinalizeForBackgroundWork) return;
if (!defersFinalizeForBackgroundWork) return;
if (!context.promptSettled || context.finalized) return;
if (hasDeferredBackgroundWork(context)) return;
yield* scheduleDeferredFinalize(context);
Expand Down Expand Up @@ -8290,7 +8310,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
});

scheduleDeferredFinalize = Effect.fn("scheduleDeferredFinalize")(function* (context) {
if (!flavor.deferFinalizeForBackgroundWork) return;
if (!defersFinalizeForBackgroundWork) return;
if (!context.promptSettled || context.finalized || context.interrupted) return;
if (hasDeferredBackgroundWork(context)) return;
context.backgroundFinalizeGeneration += 1;
Expand Down Expand Up @@ -8877,7 +8897,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
context.promptSettled = true;
context.promptSettledStatus = "completed";
if (drainedWakeCount === 0) {
if (continuationWasRequested && flavor.deferFinalizeForBackgroundWork === true) {
if (continuationWasRequested && defersFinalizeForBackgroundWork) {
if (hasDeferredBackgroundWork(context)) {
yield* rearmDeferredFinalize(context);
} else {
Expand Down Expand Up @@ -9006,7 +9026,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
? "interrupted"
: "cancelled"
: "completed";
if (flavor.deferFinalizeForBackgroundWork === true && !context.interrupted) {
if (defersFinalizeForBackgroundWork && !context.interrupted) {
context.promptSettled = true;
context.promptSettledStatus = status;
for (const [taskId, completion] of context.backgroundCommands) {
Expand All @@ -9027,7 +9047,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
return;
}
if (
flavor.deferFinalizeForBackgroundWork === true &&
defersFinalizeForBackgroundWork &&
!context.interrupted &&
hasDeferredBackgroundWork(context)
) {
Expand Down Expand Up @@ -9173,6 +9193,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
}),
);

// A replacement agent can negotiate capabilities the initial agent did not have.
const canReportBackgroundWork =
continuationRequests !== undefined &&
(flavor.followAgentWorkState === true || Boolean(flavor.enablePostSettleContinuation));
const sessionRuntime: ProviderAdapter.ProviderAdapterV2SessionRuntime = {
instanceId: options.instanceId,
driver,
Expand All @@ -9190,9 +9214,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
: flavor.getModelContextWindow?.(selection, session);
},
}),
...(postSettleContinuationEnabled || followsAgentWorkState
...(canReportBackgroundWork
? {
hasPendingBackgroundWork: Effect.gen(function* () {
if (!postSettleContinuationEnabled && !followsAgentWorkState) return false;
const rootSessionId = yield* Ref.get(activeSessionId);
if (
followsAgentWorkState &&
Expand Down
Loading
Loading