fix(hermes): delay bridge question completion until native receipt

Return the committed question to Hermes before publishing the tool bridge's
own completion fact. Hold that fact until native terminal delivery, after
final prompt usage. Keep other harnesses on their existing order and treat a
typed already-terminal passive interrupt as settled cancellation.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-08 02:36:28 -05:00
1 parent 7dd2b7ae3c
commit 8ad3eb9a5c
14 files changed
+131 -17

No files matched your search

@@ -1042,3 +1042,29 @@ as `already_terminal`; the test still requires verified owned close and the
receipt. This is deterministic transport proof, not live billing or Daytona
proof. The first focused sidecar run timed out under restricted local IPC;
its failure log is retained separately from the passing authorized IPC retry.
### 2026-10-08 early tool-bridge completion correction
The clean `1f3af78114` question campaign still failed after 644.970 seconds.
Its original infrastructure classification and `not_started` cleanup verdict
remain unchanged. The selected public run was pending and unpriced, and the
company paused before it could continue. Independent checks confirm the owned
process group, server listener and temporary instance directory are gone.
The key's full unknown-spend reservation remains held.
The live trace identifies an earlier event than the first reproduction used:
the control-plane tool bridge emits its own `dynamicToolCall` completion before
returning the tool result to Hermes. The controller parks on that event before
the native callback can finish. The managed Hermes launch policy now defers
that completed fact until the native terminal notification, after final usage.
Its original call identity and structured result remain intact. Other profiles
keep their existing order. Passive cancellation treats the driver's typed
`already_terminal` result as settled; other interruption failures still fail.
The native regression now cancels at that earlier bridge event. All four
fixtures pass in 139.789 seconds, including exactly one model request and a
complete reported token delta surviving immediate shutdown. Shared Runner and
Codex regressions pass 318 checks. The final result-copy and ordering tests pass
51 checks. Runner TypeScript and generated contracts pass. The pinned runtime
and Rust inputs are unchanged from `1f3af78114`. This remains deterministic
proof. Clean-head live billing, fresh cloud CI and review remain required.
+4 -1
View File
@@ -139,7 +139,10 @@ extend the task's execution deadline.
tool completion callback, before another model request. The bridge publishes
that tool's completed result after native finalization. Both Runner event
pumps read the prompt usage receipt before forwarding this completion to the
controller. Other tool activity still streams immediately. Tool identities
controller. The tool bridge also defers its own completed question fact until
the native terminal notification, which follows that receipt. The managed
Hermes profile selects this launch policy; other profiles retain their
existing order. Other tool activity still streams immediately. Tool identities
and results are preserved; wait and accounting authority remain with the
controller. Missing usage remains unknown.
- Paperclip owns task titles. Hermes keeps its immediate derived session title;
@@ -124,7 +124,7 @@ for (const question of [false, true]) test(question
let cancellationOutcome;
for await (const event of session.events()) {
events.push(event);
if (question && event.eventType === 'tool.execution.completed') {
if (question && event.eventType === 'item.completed' && event.payload.kind === 'dynamicToolCall') {
cancellationOutcome = session.cancel({ reason: 'committed question wait', signal: new AbortController().signal }).cleanup
.then(() => ({ stopped: true }), error => ({ error }));
break;
@@ -181,6 +181,7 @@ function createTransportBackedNativeSessionBackend(
transportFactory: options.transportFactory,
dynamicTools: options.dynamicTools,
dynamicToolHandler: options.dynamicToolHandler,
deferCommittedQuestionResults: input.provider.kind === "acpx" && input.provider.agent === "hermes",
completionFeedback: options.completionFeedback,
environment: options.environment,
workingDirectoryAuthority: options.workingDirectoryAuthority,
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";
import type { HarnessDriver, HarnessSession, PersistedHarnessSession } from "../contracts/harness-driver.js";
import type { PrpEvent, PrpStructuredRunResult, PrpTerminalState } from "../protocol/replay-contract.js";
import { NativeSessionProtocolIntegrityError } from "../contracts/native-session-backend.js";
import { HarnessOperationAlreadyTerminalError } from "../contracts/harness-driver.js";
import { HarnessDriverBackend } from "./harness-driver-backend.js";
const result: PrpStructuredRunResult = {
@@ -1010,6 +1011,22 @@ describe("HarnessDriverBackend", () => {
expect(start).not.toHaveBeenCalled();
});
it.each([true, false])("treats only a typed already-terminal interruption as settled cleanup (%s)", async alreadyTerminal => {
class TerminalRaceSession extends FakeHarnessSession {
async interrupt() {
throw alreadyTerminal ? new HarnessOperationAlreadyTerminalError("interruption") : new Error("provider stop failed");
}
}
const backend = new HarnessDriverBackend({ ...driver, async openSession() { return new TerminalRaceSession(); } });
const session = await backend.openSession({
identity: { runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" }, workingDirectory: "/workspace",
});
const cancelled = session.cancel({ reason: "governed stop", signal: new AbortController().signal });
if (alreadyTerminal) await expect(cancelled.cleanup).resolves.toBeUndefined();
else await expect(cancelled.cleanup).rejects.toThrow("provider stop failed");
await expect(session.startTurn({ message: { role: "user", text: "No further work" } })).rejects.toThrow("native_session_cancelled");
});
it("does not synthesize a fallback after explicit run cancellation", async () => {
class CancelledProviderSession extends FakeHarnessSession {
override async *events() {
@@ -13,6 +13,7 @@ import type {
PersistedNativeSession,
} from "../contracts/native-session-backend.js";
import { NativeSessionProtocolIntegrityError } from "../contracts/native-session-backend.js";
import { HarnessOperationAlreadyTerminalError } from "../contracts/harness-driver.js";
import type {
PrpEvent,
PrpTerminalState,
@@ -762,7 +763,11 @@ class HarnessNativeSession implements NativeSession {
reason: input.reason,
signal: input.signal,
}),
),
).catch(error => {
// Cancellation already revoked output synchronously. A native
// turn that ended before its passive interrupt needs no stop.
if (!(error instanceof HarnessOperationAlreadyTerminalError)) throw error;
}),
};
}
@@ -19,6 +19,8 @@ describe("Hermes native extensions", () => {
...completion, rawOutput: { ...committed, interaction: { ...committed.interaction, [key]: "" } },
}))]) expect(isHermesCommittedQuestionCompletion(event, "run")).toBe(false);
expect(isHermesCommittedQuestionCompletion({ ...completion, rawOutput: committed }, "other-run")).toBe(false);
expect(isHermesCommittedQuestionCompletion({ ...completion, title: completion.title + ": Choose the color", rawOutput: committed }, "run")).toBe(true);
expect(isHermesCommittedQuestionCompletion({ ...completion, title: completion.title + "_other", rawOutput: committed }, "run")).toBe(false);
});
const adapter = () => createAcpxProfileExtensionAdapter("hermes", { sessionId: "session", turnId: "turn", workspacePath: "/workspace" })!;
it("keeps native child identities stable across start, progress and completion", async () => {
@@ -117,7 +117,8 @@ export function acpxProfileClientCapabilities(agent: QualifiedAcpxAgent): Record
*/
export function isHermesCommittedQuestionCompletion(event: AcpRuntimeEventShape, runId: string): boolean {
if (event.type !== "tool_call" || event.tag !== "tool_call_update" || event.status !== "completed"
|| event.title !== "mcp__paperclip__request_human_input") return false;
|| !(event.title === "mcp__paperclip__request_human_input"
|| event.title?.startsWith("mcp__paperclip__request_human_input: "))) return false;
const object = (value: unknown): Record<string, unknown> | null => {
if (typeof value === "string") {
if (value.length > 65_536) return null;
@@ -948,6 +948,7 @@ export class CodexAppServerDriver implements HarnessDriver {
skillInputs: this.#options.skillInputs,
reasoningEffort: this.#options.reasoningEffort,
dynamicToolHandler: this.#options.dynamicToolHandler,
deferCommittedQuestionResults: this.#options.deferCommittedQuestionResults,
completionFeedback: this.#options.completionFeedback,
});
}
@@ -44,6 +44,43 @@ import {
} from "./codex-app-server-driver.test-support.js";
describe("Codex app-server Codex driver", () => {
it.each([true, false])("orders committed bridge question results after native usage only for the managed policy (%s)", async defer => {
const transport = new FakeCodexTransport();
const committed = { disposition: "applied", interaction: { id: "question", companyId: "company", issueId: "issue",
sourceRunId: "run-question", kind: "ask_user_questions", status: "pending", continuationPolicy: "wake_assignee" } };
const session = await makeDriver([transport], { deferCommittedQuestionResults: defer,
dynamicTools: [{ name: "request_human_input", inputSchema: { type: "object" } }],
dynamicToolHandler: async () => committed,
}).openSession({ runId: "run-question", normalizedSessionId: "normalized-question", workingDirectory: WORKSPACE });
const { turnId } = await session.startTurn({ message: { role: "user", text: "Ask the assigned question" } });
const events: PrpEvent[] = [];
const collected = (async () => {
for await (const event of session.events()) {
events.push(event);
if (["turn.completed", "turn.interrupted", "turn.failed"].includes(event.eventType)) return;
}
})();
await transport.invoke({ id: "question-rpc", method: "item/tool/call", params: {
threadId: "thread-1", turnId, callId: "question-call", tool: "request_human_input", arguments: {},
} });
const completedQuestion = (event: PrpEvent) => event.eventType === "item.completed" && event.payload.kind === "dynamicToolCall";
await vi.waitFor(() => expect(events.some(event => event.eventType === "item.started")).toBe(true));
if (defer) expect(events.some(completedQuestion)).toBe(false);
else await vi.waitFor(() => expect(events.some(completedQuestion)).toBe(true));
transport.push("thread/tokenUsage/updated", { threadId: "thread-1", turnId,
tokenUsage: { total: { inputTokens: 10, outputTokens: 5 } },
});
transport.push("turn/completed", { threadId: "thread-1", turn: { id: turnId, status: "interrupted", items: [] } });
await collected;
const questionIndex = events.findIndex(completedQuestion);
const usageIndex = events.findIndex(event => event.payload.kind === "usage");
expect(questionIndex).toBeGreaterThanOrEqual(0);
if (defer) expect(questionIndex).toBeGreaterThan(usageIndex);
else expect(questionIndex).toBeLessThan(usageIndex);
expect(events[questionIndex]?.payload.item).toMatchObject({ id: "question-call", result: committed });
await session.close({ reason: "bridge question ordering verified" });
});
it("admits a strictly bound semantic result from the durable runner", async () => {
const transport = new FakeCodexTransport();
const session = await makeDriver([transport]).openSession({
@@ -48,6 +48,8 @@ export interface CodexAppServerDriverOptions {
}) => CodexAppServerTransport;
/** Additional control-plane tools exposed to the provider for this run. */
dynamicTools?: readonly Readonly<Record<string, unknown>>[];
/** Native Hermes stops at a committed question and sends final usage first. */
deferCommittedQuestionResults?: boolean;
/** Executes an admitted additional tool call. Completion tools remain driver-owned. */
dynamicToolHandler?: (call: {
tool: string;
@@ -123,6 +123,7 @@ export class CodexHarnessSession
}
this.runId = input.runId;
this.lastAccountingUsageEvent = null;
this.committedQuestionResults.clear();
this.result = null;
this.resultFingerprint = null;
this.resultCallId = null;
@@ -1,4 +1,4 @@
import { isAcpxCanonicalInputMethod } from "../acpx/profile-extensions.js";
import { isAcpxCanonicalInputMethod, isHermesCommittedQuestionCompletion } from "../acpx/profile-extensions.js";
import { isSemanticToolOutcomeUnknownError } from "../../contracts/native-session-backend.js";
import type { HarnessRuntimeRequest, PaperclipQuestionSet } from "../../contracts/harness-driver.js";
import {
@@ -133,19 +133,23 @@ async function handleServerRequestBody(
turnId,
arguments: request.params.arguments,
});
state.emit(
"item.completed",
{
kind: "dynamicToolCall",
item: {
type: "tool_result",
id: callId,
tool_use_id: callId,
result,
},
const completed = {
kind: "dynamicToolCall",
item: {
type: "tool_result",
id: callId,
tool_use_id: callId,
result,
},
{ turnId, itemId: callId },
);
};
if (state.deferCommittedQuestionResults && tool === "request_human_input"
&& isHermesCommittedQuestionCompletion({ type: "tool_call", tag: "tool_call_update", status: "completed",
title: "mcp__paperclip__request_human_input", rawOutput: result }, state.runId)) {
if (state.committedQuestionResults.size >= 16) throw new Error("Hermes committed question result limit exceeded");
state.committedQuestionResults.set(callId, { payload: structuredClone(completed), turnId, itemId: callId });
} else {
state.emit("item.completed", completed, { turnId, itemId: callId });
}
return dynamicToolResponse(result);
} catch (error) {
// Preserve uncertain effects for the durable controller. A normal
@@ -105,6 +105,8 @@ export class CodexSessionState {
readonly dynamicTools: readonly Readonly<Record<string, unknown>>[];
readonly completionFeedback: CodexAppServerDriverOptions["completionFeedback"];
readonly dynamicToolHandler: CodexAppServerDriverOptions["dynamicToolHandler"];
readonly deferCommittedQuestionResults: boolean;
readonly committedQuestionResults = new Map<string, { payload: Record<string, unknown>; turnId: string; itemId: string }>();
readonly eventQueue = new AsyncQueue<PrpEvent>();
sourceSequence: number;
activeTurnId: string | null;
@@ -180,6 +182,7 @@ export class CodexSessionState {
dynamicTools: readonly Readonly<Record<string, unknown>>[];
completionFeedback?: CodexAppServerDriverOptions["completionFeedback"];
dynamicToolHandler?: CodexAppServerDriverOptions["dynamicToolHandler"];
deferCommittedQuestionResults?: boolean;
}) {
this.codexUsageBaseline = input.codexUsageBaseline ?? null;
if (this.codexUsageBaseline) this.usageSnapshot = codexRunUsage(this.codexUsageBaseline);
@@ -204,6 +207,7 @@ export class CodexSessionState {
this.reasoningEffort = input.reasoningEffort;
this.dynamicTools = input.dynamicTools;
this.dynamicToolHandler = input.dynamicToolHandler;
this.deferCommittedQuestionResults = input.deferCommittedQuestionResults === true;
this.completionFeedback = input.completionFeedback;
this.currentGoal = input.goal === undefined ? null : structuredClone(input.goal);
for (const entry of input.lineage ?? [input.opened.lineage]) {
@@ -435,6 +439,16 @@ export class CodexSessionState {
payload: Record<string, unknown>,
refs: { turnId?: string; itemId?: string } = {},
): void {
if (["turn.completed", "turn.failed", "turn.interrupted", "turn.cancelled"].includes(eventType)) {
// Native terminal notification follows the final prompt receipt. Release
// the bridge's own completed tool facts here, before publishing terminal,
// so controller parking cannot interrupt delivery of that receipt.
for (const [id, completed] of this.committedQuestionResults) {
if (completed.turnId !== refs.turnId) continue;
this.committedQuestionResults.delete(id);
this.emit("item.completed", completed.payload, { turnId: completed.turnId, itemId: completed.itemId });
}
}
const sourceSeq = ++this.sourceSequence;
const event: PrpEvent = {
schema: "paperclip.prp.event.v1",