@devries-cameron20 / t3code Mirror · read-only / commits / 7bae751d89
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 07:15 UTC

fix(server): Hermes keeps its background reply when launched through a wrapper (#38659)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 19, 2026 at 03:50 UTC 7bae751d89c9f950b174edb7a276ba5fcbacda33
4 files changed +270 -39
apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
+97 -22
@@ -211,21 +211,38 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* (
211 replayGate?: ProviderReplayGate,
212 continuationEnabled = true,
213 agentId: string | Record<string, unknown> = "claude-acp",
214 + replacementEntries?: ReadonlyArray<unknown>,
215 ) {
216 const fileSystem = yield* FileSystem.FileSystem;
217 const path = yield* Path.Path;
218 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
219 const replayDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-lifecycle-" });
219 - const transcript = yield* decodeAcpReplayTranscript(
220 - {
221 - provider: ACP_REGISTRY_PROVIDER,
222 - protocol: "acp.ndjson-jsonrpc",
223 - version: "1",
224 - scenario: "claude-lifecycle",
225 - entries: entries as never,
226 - },
227 - ACP_REGISTRY_PROVIDER,
220 + const scriptPath = yield* path.fromFileUrl(
221 + new URL("../../../scripts/acp-replay-agent.ts", import.meta.url),
222 );
223 + const makeReplay = Effect.fn("openClaudeReplaySession.makeReplay")(function* (
224 + entries: ReadonlyArray<unknown>,
225 + name: string,
226 + ) {
227 + const transcript = yield* decodeAcpReplayTranscript(
228 + {
229 + provider: ACP_REGISTRY_PROVIDER,
230 + protocol: "acp.ndjson-jsonrpc",
231 + version: "1",
232 + scenario: name,
233 + entries: entries as never,
234 + },
235 + ACP_REGISTRY_PROVIDER,
236 + );
237 + return makeAcpReplayRuntime({
238 + transcript,
239 + statusPath: path.join(replayDir, `${name}.json`),
240 + scriptPath,
241 + childProcessSpawner,
242 + fileSystem,
243 + ...(replayGate === undefined ? {} : { replayGate }),
244 + });
245 + });
246 const offers: Array<ProviderContinuationRequest> = [];
247 const offered = yield* Queue.unbounded<void>();
248 const continuationRequests = {
@@ -239,16 +256,12 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* (
256 let onTermination: NonNullable<
257 AcpSessionRuntime.AcpSessionRuntimeOptions["onTermination"]
258 > = () => Effect.die("Runtime has not started");
242 - const replayRuntime = makeAcpReplayRuntime({
243 - transcript,
244 - statusPath: path.join(replayDir, "status.json"),
245 - scriptPath: yield* path.fromFileUrl(
246 - new URL("../../../scripts/acp-replay-agent.ts", import.meta.url),
247 - ),
248 - childProcessSpawner,
249 - fileSystem,
250 - ...(replayGate === undefined ? {} : { replayGate }),
251 - });
259 + const replayRuntime = yield* makeReplay(entries, "claude-lifecycle");
260 + const replacementRuntime =
261 + replacementEntries === undefined
262 + ? replayRuntime
263 + : yield* makeReplay(replacementEntries, "replacement");
264 + let started = false;
265 const adapterOptions = {
266 selfInvocation: yield* resolveSelfInvocation(),
267 instanceId,
@@ -259,7 +272,9 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* (
272 ...(continuationEnabled ? { continuationRequests } : {}),
273 makeRuntime: (runtimeInput: Parameters<typeof replayRuntime>[0]) => {
274 onTermination = runtimeInput.onTermination;
262 - return replayRuntime({
275 + const replay = started ? replacementRuntime : replayRuntime;
276 + started = true;
277 + return replay({
278 ...runtimeInput,
279 protocolLogging: {
280 logIncoming: false,
@@ -2001,7 +2016,10 @@ describe("AcpRegistryAdapterV2", () => {
2016 );
2017
2018 // regression: #38599 Hermes replies on its own when a background process it started exits
2004 - it.effect("does not drop Hermes' reply after a background process finishes", () =>
2019 + it.effect.each([
2020 + { launch: "hermes acp", commandPath: "hermes", commandArgs: ["acp"] },
2021 + { launch: "a wrapper", commandPath: "node", commandArgs: ["hermes-acp.mjs"] },
2022 + ])("does not drop Hermes' reply after a background process finishes ($launch)", (launch) =>
2023 Effect.gen(function* () {
2024 const gate = makeProviderReplayGate(["process-exit"]);
2025 const sessionId = "hermes-session";
@@ -2061,7 +2079,7 @@ describe("AcpRegistryAdapterV2", () => {
2079 ],
2080 gate,
2081 true,
2064 - { source: "local", commandPath: "hermes", commandArgs: ["acp"] },
2082 + { source: "local", commandPath: launch.commandPath, commandArgs: launch.commandArgs },
2083 );
2084 yield* session.runtime.startTurn(session.turnInput(1));
2085 const foreground = yield* session.until((event) => event.type === "turn.terminal");
@@ -2078,6 +2096,63 @@ describe("AcpRegistryAdapterV2", () => {
2096 }).pipe(Effect.provide(layerTest)),
2097 );
2098
2099 + it.effect("protects Hermes background work when a wrapper launches it on replacement", () =>
2100 + Effect.gen(function* () {
2101 + const gate = makeProviderReplayGate(["process-exit"]);
2102 + const request = (method: string) => ({
2103 + type: "expect_outbound",
2104 + frame: { kind: "request", method, params: "<any>" },
2105 + });
2106 + const respond = (method: string, result: object) => ({
2107 + type: "emit_inbound",
2108 + frame: { kind: "response", method, result },
2109 + });
2110 + const open = (sessionId: string, name: string) => [
2111 + request("initialize"),
2112 + respond("initialize", { protocolVersion: 1, agentInfo: { name, version: "1.0.0" } }),
2113 + request("session/new"),
2114 + respond("session/new", { sessionId }),
2115 + ];
2116 + const sessionId = "hermes-replacement";
2117 + const session = yield* openClaudeReplaySession(
2118 + open("initial-session", "generic-agent"),
2119 + gate,
2120 + true,
2121 + { source: "local", commandPath: "node", commandArgs: ["agent-wrapper.mjs"] },
2122 + [
2123 + ...open(sessionId, "hermes-agent"),
2124 + request("session/prompt"),
2125 + respond("session/prompt", { stopReason: "end_turn" }),
2126 + {
2127 + ...claudeFrames.update(sessionId, {
2128 + sessionUpdate: "agent_message_chunk",
2129 + content: { type: "text", text: "Background command finished" },
2130 + }),
2131 + label: "process-exit",
2132 + },
2133 + ],
2134 + );
2135 + const { threadId, modelSelection, runtimePolicy } = session.turnInput(1);
2136 + const replaceThread = {
2137 + threadId,
2138 + modelSelection,
2139 + runtimePolicy,
2140 + forceNewNativeThread: true,
2141 + };
2142 + const pendingWork = session.runtime.hasPendingBackgroundWork ?? Effect.succeed(false);
2143 + assert.isFalse(yield* pendingWork);
2144 + const providerThread = yield* session.runtime.ensureThread(replaceThread);
2145 + yield* session.runtime.startTurn({ ...session.turnInput(1), providerThread });
2146 + assert.equal((yield* session.terminal).status, "completed");
2147 +
2148 + gate.release("process-exit");
2149 + yield* Queue.take(session.offered);
2150 + assert.isTrue(yield* pendingWork);
2151 + const error = yield* session.runtime.ensureThread(replaceThread).pipe(Effect.flip);
2152 + assert.include(String(error.cause), "background work is active");
2153 + }).pipe(Effect.provide(layerTest)),
2154 + );
2155 +
2156 // Copilot flattens MCP titles and reports kind "read" for MCP calls and glob ("other" for rg);
2157 // its native tool.execution_start event carries the real identity.
2158 it.effect.each(["glob", "rg"])("keeps Copilot's MCP and %s identity", (toolName) =>
packages/provider-acp-registry/src/server/adapter.ts
+8 -7
@@ -182,6 +182,10 @@ function makeAcpRegistryRuntime(
182 });
183 }
184
185 +const isHermes = (
186 + initializeResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["initializeResult"],
187 +) => initializeResult.agentInfo?.name === "hermes-agent";
188 +
189 export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(function* (
190 options: AcpRegistryAdapterV2Options,
191 ) {
@@ -212,10 +216,6 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
216 registryAgentId === "kimi-code" ||
217 (options.settings.source === "local" &&
218 /^kimi(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""));
215 - // Hermes Agent is not in the public registry; local installs run `hermes acp`.
216 - const isHermes =
217 - options.settings.source === "local" &&
218 - /^hermes(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? "");
219 const isClaude =
220 registryAgentId === "claude-acp" ||
221 (options.settings.source === "local" &&
@@ -289,9 +289,10 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
289 : {}),
290 // Hermes replies on the root session when a background process it started exits; no
291 // prompt response follows, so the continuation ends on the deferred-finalize debounce.
292 - ...(isHermes
293 - ? { enablePostSettleContinuation: true, deferFinalizeForBackgroundWork: true }
294 - : {}),
292 + // Hermes is not in the public registry and may run through a wrapper, so only its
293 + // initialize reply identifies it.
294 + enablePostSettleContinuation: isHermes,
295 + deferFinalizeForBackgroundWork: isHermes,
296 ...(isDevin
297 ? {
298 clientCapabilitiesMeta: {
packages/provider-acp/src/server/adapter.ts
+35 -10
@@ -585,7 +585,7 @@ export interface AcpAdapterV2Flavor {
585 readonly isProviderWakeNotification?: (
586 notification: EffectAcpSchema.SessionNotification,
587 ) => boolean;
588 - readonly deferFinalizeForBackgroundWork?: boolean;
588 + readonly deferFinalizeForBackgroundWork?: AcpNegotiatedFlag;
589 readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
590 /** Interrupt the local prompt fiber before `session/cancel` (Grok wedged prompts). */
591 readonly interruptPromptOnCancel?: boolean;
@@ -617,7 +617,7 @@ export interface AcpAdapterV2Flavor {
617 readonly restartRuntimeOnEveryInterrupt?: boolean;
618 readonly terminateRuntimeProcessGroupOnInterrupt?: boolean;
619 readonly preserveRuntimeOnSettledInterrupt?: boolean;
620 - readonly enablePostSettleContinuation?: boolean;
620 + readonly enablePostSettleContinuation?: AcpNegotiatedFlag;
621 /** Settle on native idle after the accepted user echo, only on negotiated ACP v2. */
622 readonly followAgentWorkState?: boolean;
623 /**
@@ -635,6 +635,19 @@ export interface AcpAdapterV2Flavor {
635 ) => boolean;
636 }
637
638 +/**
639 + * A flavor flag that is either fixed, or read from the agent's `initialize` result for
640 + * agents identified only there, such as one launched through a wrapper command.
641 + */
642 +type AcpNegotiatedFlag =
643 + | boolean
644 + | ((initializeResult: EffectAcpSchema.InitializeResponse) => boolean);
645 +
646 +const readNegotiatedFlag = (
647 + flag: AcpNegotiatedFlag | undefined,
648 + initializeResult: EffectAcpSchema.InitializeResponse,
649 +) => (typeof flag === "function" ? flag(initializeResult) : flag === true);
650 +
651 function acpSupportsImagePrompts(input: {
652 readonly flavorSupportsImagePrompts?: boolean | undefined;
653 readonly negotiatedImage?: boolean | undefined;
@@ -1849,8 +1862,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
1862 );
1863 const driver = flavor.driver;
1864 const continuationRequests = options.continuationRequests;
1852 - const postSettleContinuationEnabled =
1853 - flavor.enablePostSettleContinuation === true && continuationRequests !== undefined;
1865
1866 const readCapabilities = Effect.gen(function* () {
1867 if (flavor.supportsNativeGoals === undefined) return flavor.capabilities;
@@ -2057,6 +2068,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
2068 };
2069 let pendingStopCloseTurn: ActiveAcpTurn | null = null;
2070 let followsAgentWorkState = false;
2071 + let postSettleContinuationEnabled = false;
2072 + let defersFinalizeForBackgroundWork = false;
2073 let agentWork: Extract<
2074 EffectAcpSchema.SessionUpdate,
2075 { sessionUpdate: "state_update" }
@@ -2097,6 +2110,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
2110 flavor.followAgentWorkState === true &&
2111 continuationRequests !== undefined &&
2112 setup.initializeResult.protocolVersion === 2;
2113 + postSettleContinuationEnabled =
2114 + continuationRequests !== undefined &&
2115 + readNegotiatedFlag(flavor.enablePostSettleContinuation, setup.initializeResult);
2116 + defersFinalizeForBackgroundWork = readNegotiatedFlag(
2117 + flavor.deferFinalizeForBackgroundWork,
2118 + setup.initializeResult,
2119 + );
2120 agentWork = null;
2121 rootForegroundWork = undefined;
2122 agentRequests.clear();
@@ -4053,7 +4073,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4073 const rearmDeferredFinalize =
4074 /* Provider events include streaming deltas; avoid a span for each update. */
4075 Effect.fnUntraced(function* (context: ActiveAcpTurn) {
4056 - if (!flavor.deferFinalizeForBackgroundWork) return;
4076 + if (!defersFinalizeForBackgroundWork) return;
4077 if (!context.promptSettled || context.finalized) return;
4078 if (hasDeferredBackgroundWork(context)) return;
4079 yield* scheduleDeferredFinalize(context);
@@ -8290,7 +8310,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8310 });
8311
8312 scheduleDeferredFinalize = Effect.fn("scheduleDeferredFinalize")(function* (context) {
8293 - if (!flavor.deferFinalizeForBackgroundWork) return;
8313 + if (!defersFinalizeForBackgroundWork) return;
8314 if (!context.promptSettled || context.finalized || context.interrupted) return;
8315 if (hasDeferredBackgroundWork(context)) return;
8316 context.backgroundFinalizeGeneration += 1;
@@ -8877,7 +8897,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8897 context.promptSettled = true;
8898 context.promptSettledStatus = "completed";
8899 if (drainedWakeCount === 0) {
8880 - if (continuationWasRequested && flavor.deferFinalizeForBackgroundWork === true) {
8900 + if (continuationWasRequested && defersFinalizeForBackgroundWork) {
8901 if (hasDeferredBackgroundWork(context)) {
8902 yield* rearmDeferredFinalize(context);
8903 } else {
@@ -9006,7 +9026,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
9026 ? "interrupted"
9027 : "cancelled"
9028 : "completed";
9009 - if (flavor.deferFinalizeForBackgroundWork === true && !context.interrupted) {
9029 + if (defersFinalizeForBackgroundWork && !context.interrupted) {
9030 context.promptSettled = true;
9031 context.promptSettledStatus = status;
9032 for (const [taskId, completion] of context.backgroundCommands) {
@@ -9027,7 +9047,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
9047 return;
9048 }
9049 if (
9030 - flavor.deferFinalizeForBackgroundWork === true &&
9050 + defersFinalizeForBackgroundWork &&
9051 !context.interrupted &&
9052 hasDeferredBackgroundWork(context)
9053 ) {
@@ -9173,6 +9193,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
9193 }),
9194 );
9195
9196 + // A replacement agent can negotiate capabilities the initial agent did not have.
9197 + const canReportBackgroundWork =
9198 + continuationRequests !== undefined &&
9199 + (flavor.followAgentWorkState === true || Boolean(flavor.enablePostSettleContinuation));
9200 const sessionRuntime: ProviderAdapter.ProviderAdapterV2SessionRuntime = {
9201 instanceId: options.instanceId,
9202 driver,
@@ -9190,9 +9214,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
9214 : flavor.getModelContextWindow?.(selection, session);
9215 },
9216 }),
9193 - ...(postSettleContinuationEnabled || followsAgentWorkState
9217 + ...(canReportBackgroundWork
9218 ? {
9219 hasPendingBackgroundWork: Effect.gen(function* () {
9220 + if (!postSettleContinuationEnabled && !followsAgentWorkState) return false;
9221 const rootSessionId = yield* Ref.get(activeSessionId);
9222 if (
9223 followsAgentWorkState &&
scripts/scenarios/hermes-wrapper-keeps-background-reply.e2e.ts new
+130
@@ -0,0 +1,130 @@
1 +// @effect-diagnostics nodeBuiltinImport:off -- The scenario stages a local ACP executable and its wake gate.
2 +import * as NodeFSP from "node:fs/promises";
3 +import * as NodePath from "node:path";
4 +
5 +import { expect } from "e2e";
6 +
7 +import { T3_HOME } from "../e2e.config.ts";
8 +import { makeState, runPromise, test, WEB } from "./t3.ts";
9 +
10 +const COMPLETION = "The background command printed DONE.";
11 +const ACP = `
12 +import { unwatchFile, watchFile } from "node:fs";
13 +import { createInterface } from "node:readline";
14 +
15 +const sessionId = "hermes-scenario";
16 +const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
17 +const respond = (id, result) => send({ id, result });
18 +const chunk = (text) => send({
19 + method: "session/update",
20 + params: { sessionId, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } },
21 +});
22 +for await (const line of createInterface({ input: process.stdin })) {
23 + const { id, method } = JSON.parse(line);
24 + if (id === undefined) continue;
25 + if (method === "initialize") {
26 + respond(id, {
27 + protocolVersion: 1,
28 + agentInfo: { name: "hermes-agent", version: "0.23.1" },
29 + agentCapabilities: { loadSession: true },
30 + authMethods: [],
31 + });
32 + } else if (method === "session/new") {
33 + respond(id, { sessionId });
34 + } else if (method === "session/prompt") {
35 + chunk("Started it in the background.");
36 + respond(id, { stopReason: "end_turn" });
37 + // Hermes sends the follow-up on the root session, without another prompt response.
38 + const gate = process.argv[2];
39 + watchFile(gate, { interval: 100 }, (stat) => {
40 + if (stat.nlink === 0) return;
41 + unwatchFile(gate);
42 + chunk(${JSON.stringify(COMPLETION)});
43 + });
44 + } else {
45 + send({ id, error: { code: -32601, message: "Method not found" } });
46 + }
47 +}
48 +`;
49 +
50 +test(
51 + "Hermes sends its background completion reply when launched through a wrapper",
52 + WEB,
53 + async ({ t3, app, screen }) => {
54 + const project = await t3.project("demo");
55 + const script = NodePath.join(project, "hermes-acp.mjs");
56 + const gate = NodePath.join(project, "process-exited");
57 + const settingsPath = NodePath.join(T3_HOME, "userdata/settings.json");
58 + const originalSettings = await NodeFSP.readFile(settingsPath, "utf8");
59 + const settings = JSON.parse(originalSettings);
60 + await NodeFSP.writeFile(script, ACP);
61 + settings.providerInstances["hermes-wrapper"] = {
62 + driver: "acpRegistry",
63 + displayName: "Hermes Agent",
64 + enabled: true,
65 + config: {
66 + source: "local",
67 + commandPath: process.execPath,
68 + commandArgs: [script, gate],
69 + },
70 + };
71 + try {
72 + await NodeFSP.writeFile(settingsPath, JSON.stringify(settings));
73 + const { cli } = makeState(T3_HOME);
74 + // The watcher reloads settings asynchronously. Retry only before a thread was created.
75 + let threadId: string | undefined;
76 + for (let attempt = 0; attempt < 8 && threadId === undefined; attempt++) {
77 + const started = await runPromise(
78 + cli(
79 + [
80 + "thread",
81 + "start",
82 + project,
83 + "Start a background command that reports DONE when it exits.",
84 + "--title",
85 + "Hermes background reply",
86 + "--provider",
87 + "hermes-wrapper",
88 + "--model",
89 + "default",
90 + "--wait",
91 + "--json",
92 + ],
93 + [0, 1],
94 + ),
95 + );
96 + if (!started.stdout.includes("threadId")) continue;
97 + const result = JSON.parse(started.stdout) as {
98 + threadId: string;
99 + status: string;
100 + reply: string | null;
101 + };
102 + if (
103 + result.status !== "completed" ||
104 + !result.reply?.includes("Started it in the background.")
105 + ) {
106 + throw new Error(
107 + `Hermes foreground turn did not complete: ${started.stdout} ${started.stderr}`,
108 + );
109 + }
110 + threadId = result.threadId;
111 + }
112 + if (threadId === undefined) throw new Error("Could not start the Hermes foreground turn.");
113 +
114 + await t3.open({ threadId });
115 + await screen
116 + .getByText("Started it in the background.", { exact: true })
117 + .waitFor({ timeout: 60_000 });
118 + await NodeFSP.writeFile(gate, "");
119 + try {
120 + await expect(screen.getByText(COMPLETION, { exact: true })).toBeVisible({
121 + timeout: 15_000,
122 + });
123 + } finally {
124 + await app.screenshot("hermes-background-reply");
125 + }
126 + } finally {
127 + await NodeFSP.writeFile(settingsPath, originalSettings);
128 + }
129 + },
130 +);