Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(agents): a durable Hermes drive that lost its session opens a new one instead of ending the task (#6234)

dduponte101c9956b94
diff --git a/docs/content/docs/spaces/guides/keep-an-agent-running.mdx b/docs/content/docs/spaces/guides/keep-an-agent-running.mdx
index c71e3e84e7..621b64b545 100644
--- a/docs/content/docs/spaces/guides/keep-an-agent-running.mdx
+++ b/docs/content/docs/spaces/guides/keep-an-agent-running.mdx
@@ -90,8 +90,7 @@ the conversation or the working folder of the old one. Plan for it:
within about a minute, with the same name and an empty disk; the old record
stays listed as offline until you delete it.
-Known problems today: Hermes answers the recovery note after a restart with a
-refusal and ends the session without finishing the task; OpenCode refuses a
+Known problems today: OpenCode refuses a
command that touches a folder outside its workspace (the same call is asked
twice, and the second ask is refused as a repeat); `cua agent logs
session:NAME` shows only the driver's heartbeat lines, not what the agent did.
diff --git a/libs/cua/crates/cua-agents/runner/acp-runner.mjs b/libs/cua/crates/cua-agents/runner/acp-runner.mjs
index 2573488e29..f9e4d87c07 100644
--- a/libs/cua/crates/cua-agents/runner/acp-runner.mjs
+++ b/libs/cua/crates/cua-agents/runner/acp-runner.mjs
@@ -1039,6 +1039,20 @@ async function drive(a) {
}
}
const request = { cwd: cfg.cwd, mcpServers };
+ const openNewSession = async () => {
+ try {
+ return await requestStartup(acp.methods.agent.session.new, request, "session");
+ } catch (e) {
+ // Some agents reject session MCP servers they cannot start; keep
+ // the run and say so rather than failing it.
+ if (fatal(e) || !request.mcpServers.length) throw e;
+ emit("notice", {
+ message: `the agent refused the run's MCP servers (${e?.message ?? e}${e?.data ? ": " + JSON.stringify(e.data) : ""}); continuing without them`,
+ });
+ request.mcpServers = [];
+ return await requestStartup(acp.methods.agent.session.new, request, "session");
+ }
+ };
const wantSession = state.sessionId;
let sessionId = null;
let resumed = false;
@@ -1074,19 +1088,7 @@ async function drive(a) {
lostSessionId: wantSession,
});
}
- let res;
- try {
- res = await requestStartup(acp.methods.agent.session.new, request, "session");
- } catch (e) {
- // Some agents reject session MCP servers they cannot start; keep
- // the run and say so rather than failing it.
- if (fatal(e) || !request.mcpServers.length) throw e;
- emit("notice", {
- message: `the agent refused the run's MCP servers (${e?.message ?? e}${e?.data ? ": " + JSON.stringify(e.data) : ""}); continuing without them`,
- });
- request.mcpServers = [];
- res = await requestStartup(acp.methods.agent.session.new, request, "session");
- }
+ const res = await openNewSession();
sessionId = res.sessionId;
modes = res.modes ?? null;
}
@@ -1114,18 +1116,23 @@ async function drive(a) {
// Guard mode keeps the harness asking: it selects the harness's own
// ask-for-approval mode when its default does not ask (Codex), else none.
const want = (durable?.guard ? cfg.guardModeKinds : cfg.modeKinds) ?? [];
- const mode = (modes?.availableModes ?? []).find((m) => want.includes(m?._meta?.kind) || want.includes(m.id));
- // A resume response without modes: select the mode the first drive chose (kept in state.json).
- const modeId = mode?.id ?? (resumed && !modes?.availableModes ? state.modeId : undefined);
- if (modeId && modeId !== modes?.currentModeId) {
- try {
- await ctx.request(acp.methods.agent.session.setMode, { sessionId, modeId });
- save({ modeId });
- emit("mode", { modeId, ...(resumed ? { resumed: true } : {}) });
- } catch (e) {
- emit("notice", { message: `could not switch to mode ${modeId}: ${e?.message ?? e}` });
+ const applyMode = async () => {
+ const mode = (modes?.availableModes ?? []).find((m) => want.includes(m?._meta?.kind) || want.includes(m.id));
+ // A resume response without modes: select the mode the first drive chose (kept in state.json).
+ const modeId = mode?.id ?? (resumed && !modes?.availableModes ? state.modeId : undefined);
+ if (modeId && modeId !== modes?.currentModeId) {
+ try {
+ await ctx.request(acp.methods.agent.session.setMode, { sessionId, modeId });
+ save({ modeId });
+ emit("mode", { modeId, ...(resumed ? { resumed: true } : {}) });
+ } catch (e) {
+ emit("notice", { message: `could not switch to mode ${modeId}: ${e?.message ?? e}` });
+ }
}
- }
+ };
+ await applyMode();
+ // Set once the agent has answered a prompt of this session with anything but a refusal.
+ let sessionProven = false;
const promptTurn = async (msg) => {
state.turn += 1;
@@ -1178,6 +1185,49 @@ async function drive(a) {
return;
}
if (stale()) return;
+ if (durable && resumed && !sessionProven && res?.stopReason === "refusal") {
+ // The first prompt of a session the agent "resumed" came back refused
+ // at once: the agent does not have it. (Hermes answers session/resume
+ // for an id it lost, for example with the Space its database lived
+ // in, by making another session, and then refuses the old id.) Open
+ // a new session and send the recovery note again, as when the agent
+ // could not reload the session at all.
+ resumed = false;
+ degraded = true;
+ emit("degraded", { reason: "the agent refused the resumed session; it no longer has it", lostSessionId: sessionId });
+ try {
+ const ns = await openNewSession();
+ sessionId = ns.sessionId;
+ modes = ns.modes ?? null;
+ } catch (e) {
+ if (stale()) return;
+ emit("error", { message: withAuthHint(e?.message ?? String(e), e), code: e?.code ?? null, data: e?.data ?? null });
+ throw new AgentFailure(`prompt failed: could not open a new session: ${e?.message ?? e}`, isAuthError(e));
+ }
+ save({ sessionId, degraded: true });
+ emit("session", { sessionId, resumed: false, modes });
+ await applyMode();
+ const p = planFromJournal();
+ const note = buildRecoveryNote({
+ epoch: durable.epoch,
+ prevEpoch: p.prevEpoch,
+ entries: entries.slice(),
+ degraded: true,
+ history: p.history,
+ interrupted: extra.recovery ? p.open : null,
+ });
+ const again = extra.recovery ? note : `${note}\n\n${msg.text}`;
+ try {
+ res = await ctx.request(acp.methods.agent.session.prompt, { sessionId, prompt: blocks(again, msg.files) });
+ } catch (e) {
+ if (stale()) return;
+ flush();
+ emit("error", { message: withAuthHint(e?.message ?? String(e), e), code: e?.code ?? null, data: e?.data ?? null });
+ throw new AgentFailure(`prompt failed: ${e?.message ?? e}`, isAuthError(e));
+ }
+ if (stale()) return;
+ }
+ if (res?.stopReason !== "refusal") sessionProven = true;
endTurn(res?.stopReason ?? null, res?.usage ?? null);
};
diff --git a/libs/cua/crates/cua-agents/runner/test/durable.test.mjs b/libs/cua/crates/cua-agents/runner/test/durable.test.mjs
index 5bf7fb09cc..e7b6c9816d 100644
--- a/libs/cua/crates/cua-agents/runner/test/durable.test.mjs
+++ b/libs/cua/crates/cua-agents/runner/test/durable.test.mjs
@@ -387,6 +387,51 @@ t("an agent with session/resume is resumed with it, and secrets never reach the
assert.match(box.tools().find((x) => x.kind === "outcome").summary, /token \[redacted\] used/);
});
+t("an agent that lost the session and refuses its id gets a new session and the recovery note (CUA-2966)", async (box) => {
+ // Hermes: session/resume of an id it no longer has (the Space with its database is gone) succeeds by making
+ // another session, and the next prompt for the old id is refused at once with no model request.
+ box.script({
+ resume: true,
+ loadSession: true,
+ forgets: true,
+ prompts: [
+ { match: "recovery", steps: [{ say: "carrying on" }] },
+ { match: ".", steps: [tool("call-1", { output: "first" }), { crash: true, once: "c1" }] },
+ ],
+ });
+ box.config({ durable: { maxAgentRestarts: 0 }, prompt: "Ship the release" });
+ assert.equal((await box.go({ epoch: 1, resume: false })).code, 1);
+ // The new Space: the agent's own session store is empty.
+ fs.rmSync(path.join(box.mock, "sessions.json"), { force: true });
+ const r = await box.go({ epoch: 2 });
+ assert.equal(r.code, 0, r.stderr);
+ const log = box.agentLog();
+ assert.ok(log.some((l) => l.ev === "session_resume_forgot"), "the agent was asked to resume the lost id");
+ assert.equal(log.filter((l) => l.ev === "prompt_refused").length, 1, "its id was refused once");
+ assert.ok(log.some((l) => l.ev === "session_new" && l.id !== undefined), "a new session was opened");
+ // The recovery note reached the agent, as the degraded kind: the journal is all that is known.
+ const note = box.prompts().find((x) => x.includes("[cua durable recovery]"));
+ assert.ok(note, "the recovery note was sent to the new session");
+ assert.match(note, /starting with a fresh context/);
+ assert.match(note, /Tool calls that completed \(do not repeat them\):/);
+ assert.match(note, /run call-1/);
+ const ev = box.events();
+ assert.ok(ev.some((e) => e.type === "degraded"), "the degraded notice is in the journal");
+ assert.ok(ev.filter((e) => e.type === "turn_ended").pop()?.stopReason !== "refusal", "the turn did not end as a refusal");
+ assert.equal(ev.filter((e) => e.type === "run_exited").pop()?.status ?? "done", "done");
+ // The next drive finds the session the runner saved, no longer lost.
+ assert.equal(JSON.parse(fs.readFileSync(path.join(box.state, "state.json"), "utf8")).degraded, true);
+});
+
+t("a refusal after the session has answered is the agent's own answer, not a lost session", async (box) => {
+ box.script({ resume: true, forgets: true, prompts: [{ match: ".", steps: [{ say: "ok" }] }] });
+ box.config({ durable: { maxAgentRestarts: 0 } });
+ const r = await box.go({ epoch: 1, resume: false });
+ assert.equal(r.code, 0, r.stderr);
+ assert.ok(!box.events().some((e) => e.type === "degraded"));
+ assert.equal(box.agentLog().filter((l) => l.ev === "prompt_refused").length, 0);
+});
+
// ---- the recovery note, exactly -----------------------------------------------------
t("the recovery note text", async (box) => {
diff --git a/libs/cua/crates/cua-agents/runner/test/mock-acp-agent.mjs b/libs/cua/crates/cua-agents/runner/test/mock-acp-agent.mjs
index 7a09876b34..ba029d461d 100644
--- a/libs/cua/crates/cua-agents/runner/test/mock-acp-agent.mjs
+++ b/libs/cua/crates/cua-agents/runner/test/mock-acp-agent.mjs
@@ -5,8 +5,11 @@
// the agent saw), effects.log (one line per executed tool),
// marks/ (once-only markers)
// MOCK_SCRIPT path to JSON: {"loadSession": bool, "resume": bool,
-// "prompts": [{"match": "regex", "steps": [...]}]}; the first
-// entry whose regex matches the prompt text runs
+// "forgets": bool, "prompts": [{"match": "regex", "steps": [...]}]};
+// the first entry whose regex matches the prompt text runs.
+// "forgets": like Hermes, session/resume of an id the agent
+// lost succeeds (it makes another session), and a prompt for
+// an id it does not know is answered with stopReason "refusal"
//
// Steps: {say}, {tool: {id,title,kind,input,permission,effect,fail}},
// {crash, once}, {killRunner, once}, {hold}, {pause}, {startsOnly}
@@ -143,12 +146,20 @@ agent
return {};
})
.onRequest("session/resume", (ctx) => {
+ if (!sessions()[ctx.params.sessionId] && script.forgets) {
+ log({ ev: "session_resume_forgot", id: ctx.params.sessionId });
+ return {};
+ }
if (!sessions()[ctx.params.sessionId]) throw new Error("unknown session");
log({ ev: "session_resume", id: ctx.params.sessionId });
return {};
})
.onRequest("session/prompt", async (ctx) => {
const text = ctx.params.prompt.map((b) => b.text ?? "").join("\n");
+ if (script.forgets && !sessions()[ctx.params.sessionId]) {
+ log({ ev: "prompt_refused", id: ctx.params.sessionId });
+ return { stopReason: "refusal" };
+ }
log({ ev: "prompt", text });
const entry = script.prompts.find((p) => new RegExp(p.match, "s").test(text));
if (script.promptError && (!script.promptError.match || new RegExp(script.promptError.match).test(text))) {