Skip to content

fix(agentsapi): decouple session keys and report access errors - #162948

Merged
sjf-oa merged 5 commits into
mainfrom
sjf/agentsapi-api-key-rotation-public
Oct 1, 2026
Merged

sjf-oa merged 5 commits into
mainfrom
sjf/agentsapi-api-key-rotation-public

Conversation

@sjf-oa

@sjf-oa sjf-oa commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

An API key authenticates requests; it is not the identity of a conversation. Changing credentials should not make OpenClaw discard a saved session or demand a reset before the API can authorize the request. When the API rejects access, users need the actual recovery step instead of misleading model-fallback or generic authentication advice.

Changes

  • Store a configuration fingerprint containing model, environment and effective HTTP MCP settings. API key bytes and key-derived hashes no longer participate in the binding.

  • Authenticate each attempt with the currently resolved key while preserving the native session ID. There is no legacy fingerprint matching or migration for prelaunch credential-bearing bindings.

  • Recognize the exact SDK saved-session 404 and hosted original-key 403 responses. Preserve original SDK diagnostics and provide specific public guidance: check project permissions or restore the creating key.

  • Keep that guidance through both replay-safe prompt handling and non-replayable terminal presentation. Preserve replay restrictions and the existing effects warning. Ordinary missing-model and unrelated authentication errors retain their existing behavior.

  • Keep the native error class and transport/history error classifiers together in the plugin error module. This is a behavior-preserving extraction with no compatibility exports.

  • Correct the retained README reset advice and document the hosted service's original-key input requirement.

Model, execution environment and effective HTTP MCP changes still require a reset. Backend authorization is unchanged.

Current API Limitation

Live testing with three distinct keys that can read the same sessions established that hosted input currently requires the creating key. Both replacement keys could read both existing sessions (HTTP 200), but neither could submit input to them (four HTTP 403 responses):

hosted session input requires the API key that created its CCA thread

This PR removes OpenClaw's separate credential fingerprint restriction. It does not make hosted execution work with replacement keys under the API's current policy.

Evidence

  • 90 focused cases passed across five paths: 41 attempt/environment cases, 25 prompt-failure cases, 20 terminal-fallback cases, one public-error delivery case and three registered-harness presentation cases. The unchanged persistence suite's 10 cases also passed during the fingerprint change.

  • All six targeted error regressions fail on the preceding production implementations and pass with these fixes. The registered-harness regression calls real runEmbeddedAgent, checks the final payload and asserts exactly one attempt for a non-replayable failure.

  • New error coverage: saved-session failure during reasoning update, input submission and item retrieval; the hosted original-key requirement; preservation of public preflight copy in prompt recovery; and preservation of that copy in non-replayable terminal delivery. Missing-model and ordinary HTTP 401/403 controls remain covered.

  • Final changed-suite command: pnpm test extensions/agentsapi/agentsapi-environment.test.ts src/agents/embedded-agent-runner/run/prompt-failure.test.ts --maxWorkers=1. Wall: 22.48 s; environment shard: 10.88 s; prompt-failure shard: 8.65 s.

  • Registered-harness command: pnpm test src/agents/embedded-agent-runner/run.shared-integration.test.ts --maxWorkers=1 -t 'harness prompt failure presentation'. Wall: 25.42 s; shard: 14.57 s; added case: 0.438 s. It reuses the existing suite-level fixture. CI test timings are pending.

  • Scoped production and test type checks, lint, formatting and git diff --check passed. Two independent reviews found no actionable P0/P1 defects.

  • After the error-module refactor, all 44 existing session/environment tests passed: pnpm test extensions/agentsapi/agentsapi-session.test.ts extensions/agentsapi/agentsapi-environment.test.ts --maxWorkers=1 (32.73 s shard command wall). A focused independent review found no actionable P0/P1/P2 issues. No tests were added for the mechanical move.

  • Additional requested copied-state check passed: the v2026.9.7 binding owner wrote a real SQLite row; a closed-state copy was rejected by current continuation/reset/deletion without mutation; fresh registered-harness creation/continuation succeeded beside it; the release-tag binding owner reopened the original row after rollback. One temporary case passed (5.378 s test body, 67.36 s shard command wall). This validates the binding owner, not a full historical Gateway binary/schema downgrade. No compatibility implementation was added.

Live Linux and Slack Proof

A native Linux ARM64 Gateway used real hosted Linux sessions. Keys were changed through a file-backed provider SecretRef and openclaw secrets reload, with explicit provider auth: "api-key". Key replacement required no Gateway restart.

  • PASS: both supplied keys now produce the specific original-key explanation through Slack. The earlier live check exposed a separate non-replayable renderer that ignored public copy; the final change fixes that path without relaxing replay protection.
  • PASS: an inaccessible saved session produces the project-permissions explanation without missing-model fallback or reset advice.
  • PASS: restoring the creating key recovered both original sessions during the initial matrix, with fresh Linux commands and unchanged session IDs, hosted environment IDs, UUID files and SHA-256 hashes. On the final image both original sessions accepted input and executed Linux commands after restoring the regular key. Session A retained its file and checksum; session B's /tmp/key-rotation-b.txt was missing. A separate read-only command confirmed session B's Linux runner and /workspace remained usable. Its session/environment IDs were unchanged; the file was not recreated. The cause of that file loss was not established, so final session-B filesystem continuity is recorded as a failed check, separately from successful authentication/execution recovery.

The final image uses the terminal-rendering revision. Its production source is identical to the head used for live verification; the only subsequent change fixes the test fixture's error-constructor import after module reset. The later error-module extraction and documentation correction were checked separately above without rebuilding the live Gateway. No staging or production deployment was performed.

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@sjf-oa
sjf-oa force-pushed the sjf/agentsapi-api-key-rotation-public branch 2 times, most recently from d3f1064 to 242a11c Compare October 1, 2026 19:30
@sjf-oa
sjf-oa force-pushed the sjf/agentsapi-api-key-rotation-public branch from 242a11c to bbb6d43 Compare October 1, 2026 19:30
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 1, 2026
@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 1, 2026, 6:59 PM ET / 22:59 UTC (Revision 7).

ClawSweeper review

What this changes

The Agents API plugin separates saved conversation identity from API credentials and preserves specific session-access recovery guidance through agent replies.

Merge readiness

✅ Ready for maintainer review

The PR remains useful and has no actionable findings. The new copied-state evidence satisfies the previous cutover and rollback blocker within the already accepted no-legacy policy.

Priority: P2
Reviewed head: 6f110b8f715e3ef65f42d8299f1492e00506cb68

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Focused implementation and meaningful live evidence now include the previously requested stored-state cutover proof.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Linux ARM64 Gateway and Slack observations exercise the changed session-request and final-error paths, showing denied replacement keys, actionable guidance, and execution recovery with the creating key. Supplemental copied-state proof satisfies the approved rejection-and-preservation cutover and binding-owner rollback contract; it does not claim a full binary downgrade or complete hosted filesystem continuity.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Linux ARM64 Gateway and Slack observations exercise the changed session-request and final-error paths, showing denied replacement keys, actionable guidance, and execution recovery with the creating key. Supplemental copied-state proof satisfies the approved rejection-and-preservation cutover and binding-owner rollback contract; it does not claim a full binary downgrade or complete hosted filesystem continuity.
Evidence reviewed 12 items Pinned introduction: Reviewed the verified merge-base-to-head production and test hunks. Checkout and original head are 6f110b8; endpoint drift and the stale test merge were not treated as PR introduction or evidence of removed main behavior.
Still necessary on main and latest release: Fetched main still includes the resolved API key in the session fingerprint and reads authFingerprint bindings. v2026.9.7 also stores the old format; the requested correction is therefore not already implemented.
Released binding contract: The release binding owner uses the same agentsapi-sessions store with paired sessionId/authFingerprint fields.
Findings None None.
Security None None.

How this fits together

The Agents API plugin connects OpenClaw conversations and tools to OpenAI-hosted agent sessions. Its saved bindings select the remote conversation, while each attempt supplies current credentials and returns replies or actionable errors.

flowchart TD
  A[Conversation request] --> B[Saved session binding]
  B --> C[Configuration identity check]
  D[Current API credentials] --> E[Hosted session request]
  C --> E
  E --> F[Backend authorization]
  F --> G[Reply or recovery guidance]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +40, Tests +162, Docs +13. Total +215 across 12 files.

View PR surface stats
Area Files Added Removed Net
Source 7 127 87 +40
Tests 4 244 82 +162
Docs 1 14 1 +13
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 385 170 +215

Review metrics

Metric Value Why it matters
Production versus regression coverage production +40 lines; tests and test support +162 lines Production growth supports specific error guidance using existing owners, with regression coverage for transport, recovery, and terminal delivery.

Technical review

Best possible solution:

Keep configuration identity plugin-owned, authenticate through the existing SDK, and deliver precise recovery guidance under the accepted no-legacy cutover.

Do we have a high-confidence way to reproduce the issue?

Yes: current-main source includes credential bytes in saved-session identity, and supplied live observations establish the misleading access-error path. This read-only review did not execute a reproduction.

Is this the best way to solve the issue?

Yes, within the accepted scope: the patch uses the existing binding, SDK, and sanitized error-rendering owners, and the requested stored-state validation now covers the intentional break.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 3bb7cf9b839e.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: This is a bounded correction to an optional agent runtime with scoped live and persistence evidence.
  • merge-risk: 🚨 compatibility: Released bindings become intentionally unsupported under the accepted policy; copied-state proof now verifies preservation, fresh operation, and binding-owner rollback.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Linux ARM64 Gateway and Slack observations exercise the changed session-request and final-error paths, showing denied replacement keys, actionable guidance, and execution recovery with the creating key. Supplemental copied-state proof satisfies the approved rejection-and-preservation cutover and binding-owner rollback contract; it does not claim a full binary downgrade or complete hosted filesystem continuity.
  • proof: sufficient: Contributor real behavior proof is sufficient. Linux ARM64 Gateway and Slack observations exercise the changed session-request and final-error paths, showing denied replacement keys, actionable guidance, and execution recovery with the creating key. Supplemental copied-state proof satisfies the approved rejection-and-preservation cutover and binding-owner rollback contract; it does not claim a full binary downgrade or complete hosted filesystem continuity.

Evidence

What I checked:

  • Pinned introduction: Reviewed the verified merge-base-to-head production and test hunks. Checkout and original head are 6f110b8; endpoint drift and the stale test merge were not treated as PR introduction or evidence of removed main behavior. (6f110b8f715e)
  • Still necessary on main and latest release: Fetched main still includes the resolved API key in the session fingerprint and reads authFingerprint bindings. v2026.9.7 also stores the old format; the requested correction is therefore not already implemented. (extensions/agentsapi/agentsapi-bindings.ts:9, 3bb7cf9b839e)
  • Released binding contract: The release binding owner uses the same agentsapi-sessions store with paired sessionId/authFingerprint fields. (extensions/agentsapi/agentsapi-bindings.ts:151, c074824a27c9)
  • Identity and authorization boundary: The new fingerprint retains model, relevant environment configuration, and effective MCP settings. Each attempt constructs the existing Agents API SDK client with the currently resolved key; backend authorization and current-owner request checks remain intact. This path uses the hosted SDK session API rather than a local Codex app-server contract. (extensions/agentsapi/agentsapi-attempt.ts:236, 6f110b8f715e)
  • Accepted compatibility tradeoff: The previous completed review records acceptance of the no-legacy policy, reiterated in the supplied maintainer context at fix(agentsapi): decouple session keys and report access errors #162948 (comment). Released bindings intentionally cannot continue, reset, or delete through the new reader; no compatibility reader or migration should be added. This remains a compatibility limitation, not an unresolved policy choice. (extensions/agentsapi/agentsapi-bindings.ts:159, 6f110b8f715e)
  • Copied-state proof resolves prior blocker: The supplied complete proof at fix(agentsapi): decouple session keys and report access errors #162948 (comment) uses the exact release binding owner and real SQLite stores. Its recorded output shows unchanged released rows after rejected continuation, reset, and deletion; fresh registered-harness creation and continuation alongside them; and release-owner reopening after handles are closed. Provider execution is mocked, appropriately separate from the earlier live API evidence. This establishes the accepted binding cutover and rollback contract, without claiming a historical Gateway binary/schema downgrade. (extensions/agentsapi/agentsapi-harness.persistence.test.ts:29, 6f110b8f715e)

Likely related people:

  • sjf-oa: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • fuller-stack-dev: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (6 earlier review cycles)
  • reviewed 2026-10-01T19:41:17.688Z sha bbb6d43 :: needs real behavior proof before merge. :: [P1] Preserve admission and recovery for released binding rows
  • reviewed 2026-10-01T21:54:28.427Z sha bbb6d43 :: blocked before merge. :: [P1] Preserve admission and recovery for released binding rows
  • reviewed 2026-10-01T22:16:48.533Z sha ea34e9e :: blocked before merge. :: [P1] Preserve admission and recovery for released binding rows
  • reviewed 2026-10-01T22:27:53.114Z sha be2b982 :: blocked before merge. :: [P1] Preserve admission and recovery for released binding rows
  • reviewed 2026-10-01T22:37:10.261Z sha be2b982 :: blocked before merge. :: [P1] Preserve admission and recovery for released binding rows | [P3] Remove the contradictory API-key reset instruction
  • reviewed 2026-10-01T22:49:09.934Z sha 6f110b8 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 1, 2026
@sjf-oa sjf-oa changed the title fix(agentsapi): preserve sessions across API key rotation fix(agentsapi): decouple session keys and report access errors Oct 1, 2026
@sjf-oa
sjf-oa force-pushed the sjf/agentsapi-api-key-rotation-public branch from 34644b5 to 8fef80a Compare October 1, 2026 22:07
@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Oct 1, 2026
@sjf-oa
sjf-oa force-pushed the sjf/agentsapi-api-key-rotation-public branch from 8fef80a to f5b8b6b Compare October 1, 2026 22:11
@sjf-oa
sjf-oa force-pushed the sjf/agentsapi-api-key-rotation-public branch from f5b8b6b to ea34e9e Compare October 1, 2026 22:11
@clawsweeper clawsweeper Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Oct 1, 2026
@sjf-oa
sjf-oa force-pushed the sjf/agentsapi-api-key-rotation-public branch from 639c270 to be2b982 Compare October 1, 2026 22:21
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Oct 1, 2026
ClawSweeper requested: "Remove the contradictory API-key reset instruction"
@sjf-oa

sjf-oa commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The maintainer has explicitly confirmed the compatibility decision: keep no legacy support. Bindings created before this change are intentionally unsupported, and this PR must not add an authFingerprint reader, compatibility path, or migration. The prior format's presence in v2026.9.7 is acknowledged; the maintainer has reviewed the consequence that these records cannot continue, reset, or delete through the new reader and has selected the intentional break. Please evaluate this PR under that explicit scope rather than treating a migration as outstanding author work.

The README contradiction is fixed in 6f110b8. It no longer instructs users to reset when changing an API key, and it explains the hosted service's current requirement to restore the creating key for input. This addresses your request: "Remove the contradictory API-key reset instruction".

The latest source refactor only moves the native error class and two existing classifiers into the plugin error module. All 44 existing session/environment tests passed afterward, and the independent focused review found no actionable P0/P1/P2 issues. The PR body retains the live API/Slack evidence and the explicitly recorded filesystem-continuity limitation.

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 1, 2026
@sjf-oa

sjf-oa commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The requested isolated stored-state proof now passes on the unchanged PR head.

  • Used the exact binding implementation from v2026.9.7 (source revision) to write a synthetic sessionId/authFingerprint binding through the real SQLite-backed plugin store.
  • Closed database handles and copied the state directory into a separate test state. The current registered harness rejected continuation, reset, and deletion with Invalid Agents API binding row: local-persisted-session. The complete stored record remained equal after each operation.
  • Created and continued a fresh session through the current registered harness in the same copied state, preserving the unsupported record alongside it.
  • Closed/reopened storage and switched back to the exact v2026.9.7 binding owner. It reacquired the original native session ID and fingerprint, and its released row remained equal afterward.

This is binding-owner cutover and rollback proof against real SQLite persistence. Provider execution uses the existing fixture; actual API/Slack behavior is covered by the earlier live proof. It does not claim a full historical Gateway binary/database-schema downgrade. No production compatibility path or migration was added. The temporary proof case reuses the existing persistence suite and is not added to every-PR CI.

Command: pnpm test extensions/agentsapi/agentsapi-harness.persistence.test.ts --maxWorkers=1 -t 'preserves copied released binding'

Result: 1 passed, 10 unrelated existing cases filtered out; test body 5.378 s, shard command wall 67.36 s.

PASS: copied released row rejected by continuation, reset and deletion; record intact after each operation
PASS: fresh registered-harness session created and continued beside preserved unsupported record
PASS: v2026.9.7 binding owner reopened the same original session ID and fingerprint after candidate rejection
Temporary proof case (existing persistence fixture reused)
it("preserves copied released binding records through rejection and binding-owner rollback", async () => {
  await withOpenClawTestState({ label: "agentsapi-release-source" }, async (source) => {
    const sourceParams = await createAttempt(source.stateDir);
    const runtimeFor = (env: NodeJS.ProcessEnv) => {
      const runtime = createPluginRuntimeMock();
      runtime.state.openKeyedStore = <T>(options: Parameters<typeof runtime.state.openKeyedStore>[0]) =>
        createPluginStateKeyedStoreForTests<T>("agentsapi", { ...options, env });
      runtime.state.openSyncKeyedStore = <T>(options: Parameters<typeof runtime.state.openSyncKeyedStore>[0]) =>
        createPluginStateSyncKeyedStoreForTests<T>("agentsapi", { ...options, env });
      return runtime;
    };
    const released = { sessionId: "release-native-session", authFingerprint: "release-proof-fingerprint" };
    await createReleasedBindings(runtimeFor(source.env)).withSession(sourceParams.sessionId, () => {}, async (_binding, bind) => {
      await bind(released);
    });
    await reopenState();
    await withOpenClawTestState({ label: "agentsapi-release-copy" }, async (copied) => {
      await fs.cp(source.stateDir, copied.stateDir, { recursive: true });
      const params = await createAttempt(copied.stateDir);
      const store = () => createPluginStateKeyedStoreForTests<Record<string, unknown>>("agentsapi", {
        namespace: "agentsapi-sessions", maxEntries: 100_000, overflowPolicy: "reject-new", env: copied.env,
      });
      const original = await store().lookup(params.sessionId);
      expect(original).toEqual(released);
      const harness = registerHarness(copied.env);
      try {
        const rejected = `Invalid Agents API binding row: ${params.sessionId}`;
        await expect(harness.runAttempt(params)).rejects.toThrow(rejected);
        expect(await store().lookup(params.sessionId)).toEqual(original);
        await expect(harness.reset({ sessionId: params.sessionId, reason: "reset" })).rejects.toThrow(rejected);
        expect(await store().lookup(params.sessionId)).toEqual(original);
        await expect(harness.withSessionDeletion({ agentId: params.agentId, sessionKey: params.sessionKey!, sessionId: params.sessionId, assertCurrent: () => {} }, async (mutation) => {
          mutation.commit();
        })).rejects.toThrow(rejected);
        expect(await store().lookup(params.sessionId)).toEqual(original);
        console.log("PASS: copied released row rejected by continuation, reset and deletion; record intact after each operation");

        vi.spyOn(AgentsApiClient.prototype, "create").mockResolvedValue("fresh-proof-native");
        vi.spyOn(AgentsApiClient.prototype, "setReasoningEffort").mockResolvedValue(undefined);
        const message = vi.spyOn(AgentsApiClient.prototype, "message").mockResolvedValue(undefined);
        vi.spyOn(AgentsApiClient.prototype, "items").mockResolvedValue([]);
        const freshId = "fresh-cutover-local";
        const freshTarget = { ...params.sessionTarget, sessionId: freshId, sessionKey: "agent:main:fresh-cutover" };
        await upsertSessionEntry({ ...freshTarget, entry: { sessionId: freshId, updatedAt: Date.now() } });
        const fresh = { ...params, ...freshTarget, sessionTarget: freshTarget, runId: "fresh-cutover-first" };
        expect(await harness.runAttempt(fresh)).toMatchObject({ terminal: { kind: "ok" } });
        expect(await harness.runAttempt({ ...fresh, runId: "fresh-cutover-second" })).toMatchObject({ terminal: { kind: "ok" } });
        expect(message.mock.calls.map(([id]) => id)).toEqual(["fresh-proof-native", "fresh-proof-native"]);
        expect(await store().lookup(params.sessionId)).toEqual(original);
        console.log("PASS: fresh registered-harness session created and continued beside preserved unsupported record");
      } finally {
        await harness.dispose();
      }
      await reopenState();
      await createReleasedBindings(runtimeFor(copied.env)).withSession(params.sessionId, () => {}, async (binding) => {
        expect(binding).toEqual(released);
      });
      await reopenState();
      expect(await store().lookup(params.sessionId)).toEqual(original);
      console.log("PASS: v2026.9.7 binding owner reopened the same original session ID and fingerprint after candidate rejection");
    });
  });
});

createReleasedBindings imports the unmodified release-tag binding module. The existing fixture supplies real registered-harness dispatch, host session generation, SQLite stores and binding lifecycle; the helper also returns the registered withSessionDeletion hook.

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 1, 2026
@sjf-oa
sjf-oa merged commit 6a1852b into main Oct 1, 2026
149 of 151 checks passed
@sjf-oa
sjf-oa deleted the sjf/agentsapi-api-key-rotation-public branch October 1, 2026 23:38
@sjf-oa

sjf-oa commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…law#162948)

* fix(agentsapi): preserve sessions across API key rotation

* fix(agentsapi): preserve actionable saved-session access errors

* fix(agents): preserve harness errors after non-replayable attempts

* refactor(agentsapi): centralize error types and classifiers

* docs(agentsapi): correct key rotation reset guidance

ClawSweeper requested: "Remove the contradictory API-key reset instruction"

---------

Co-authored-by: Sarah Fortune <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling extensions: agentsapi merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants