Repository navigation
fix(agentsapi): decouple session keys and report access errors - #162948
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
d3f1064 to
242a11c
Compare
242a11c to
bbb6d43
Compare
|
Codex review: needs maintainer review before merge. Reviewed October 1, 2026, 6:59 PM ET / 22:59 UTC (Revision 7). ClawSweeper reviewWhat this changesThe 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 Review scores
Verification
How this fits togetherThe 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]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +40, Tests +162, Docs +13. Total +215 across 12 files. View PR surface stats
Review metrics
Technical reviewBest 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. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (6 earlier review cycles)
|
34644b5 to
8fef80a
Compare
8fef80a to
f5b8b6b
Compare
f5b8b6b to
ea34e9e
Compare
639c270 to
be2b982
Compare
ClawSweeper requested: "Remove the contradictory API-key reset instruction"
|
@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. |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review The requested isolated stored-state proof now passes on the unchanged PR head.
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: Result: 1 passed, 10 unrelated existing cases filtered out; test body 5.378 s, shard command wall 67.36 s. 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");
});
});
});
|
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…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]>
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):
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 --checkpassed. 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 providerauth: "api-key". Key replacement required no Gateway restart./tmp/key-rotation-b.txtwas missing. A separate read-only command confirmed session B's Linux runner and/workspaceremained 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.