Skip to content

refactor(anthropic): replace handwritten Claude sessions with Agent SDK - #128131

Merged
steipete merged 8 commits into
mainfrom
codex/anthropic-agent-sdk
Aug 24, 2026
Merged

steipete merged 8 commits into
mainfrom
codex/anthropic-agent-sdk

Conversation

@steipete

@steipete steipete commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Replace OpenClaw's handwritten Claude Code process, stream-protocol, turn, timeout, and session machinery with Anthropic's official @anthropic-ai/claude-agent-sdk, following the same supported Claude Code execution boundary used by T3 Code. The SDK runs the user's installed, unmodified Claude executable and leaves subscription authentication inside Claude Code; a Claude subscription is not treated as direct Messages API access.

  • Remove 2,023 lines across the old Claude process/session/turn/timeout implementations and replace the obsolete protocol-specific registry, capability gate, secondary queues, weak maps, and pending-creation machinery with one private provider-neutral, host-owned live-session record per owner.
  • Reduce the complete branch by 1,186 production runtime lines and 5,368 lines overall (4,701 additions, 10,069 deletions); test/support code still shrinks by 4,245 lines despite the substantially stronger regression coverage.
  • Keep one official Agent SDK query and Claude subprocess warm across compatible agent turns. Full system prompts, model/auth identity, environment, skills, MCP topology, and tool policy determine reuse; deliberate fresh/reseed turns close the old process and normal resume preserves it.
  • Keep authority in OpenClaw: the now-opaque plugin capability exposes neither owner keys nor bearer state; each turn must prove exact admitted-run ownership and session generation, privately adopt the existing MCP process bearer, reactivate the correct capture key, re-evaluate native-tool policy, and fence approvals after cancellation or replacement.
  • Preserve canonical subprocess-tree ownership across every SDK execution: POSIX Claude children receive private process groups, Windows descendants are traversed before their root exits, SDK graceful cancellation remains intact, private credential buffers are zeroized, and custom-process stderr is continuously drained.
  • Route every local agent turn through the SDK approval owner, including native-tool turns and explicitly selected OAuth/token/API-key credentials. Selected credentials still travel only through private descriptor 3 using the SDK's official custom-spawn contract, and copied credential buffers are zeroized after delivery.
  • Reject cross-owner process-handle reuse, preserve resumable transcripts when required-generation fingerprints change, and serialize live-capable third-party owners through the existing canonical queue.
  • Fix a longstanding real warm-session defect: materialized native Claude skill directories are now claimed by the first SDK process and survive per-turn cleanup until that exact subprocess exits; MCP grants and auth resources remain strictly turn-scoped.
  • Delete the abandoned beta-only live-session capability/version-advisory system, deprecated MCP tool-availability projections and inferred enforcement, doctor/onboarding plumbing, unused handwritten stream/control fixtures, unreachable skill-materialization fallback, and test-only lifecycle seams; retain stable-shipped public configuration and documented setup-token behavior.
  • Let the SDK own one-shot string-prompt execution directly and normalize user-only Claude settings plus permissions in one canonical pass instead of maintaining duplicate wrappers and synthetic streams.
  • Deliver SDK system prompts directly, without temporary files, command-line exposure, or leaked OpenClaw cache-boundary markers; preserve Claude's variadic and repeated directory/tool arguments through official SDK options.
  • Fence already-cancelled one-shot requests immediately before SDK startup, including cancellation during its dynamic import, so a stale run can never spawn an actual Claude subprocess.
  • Preserve session-scoped non-Bash "Allow always" grants, pending-tool/background watchdog grace, retryable initialization-only stalls, canonical expired-session recovery, bounded background-task completion, and first-process native-skill artifacts until the child exits.
  • Preserve the newer main interrupted-response contract: streamed assistant text survives caller cancellation and deadlines, while the transcript, session binding, execution trace, completion reason, and agent-end hook consistently record an unsuccessful aborted/timeout turn.
  • Repair clean default Docker builds at the generic bundled-plugin ownership boundary: mandatory root-packaged plugin dependency manifests are staged before the frozen install, while OPENCLAW_EXTENSIONS and optional-plugin runtime selection remain unchanged.
  • Remove the unnecessary ~272 MiB Claude platform executable from default production Docker images while retaining it automatically when an explicitly selected plugin declares that platform requirement.
  • Retain existing transports for paired-node execution, isolated side questions, compaction, and third-party backends outside the official Anthropic SDK path.
  • Prune stale assertion-safety exceptions for the deleted handwritten Claude session machinery.
  • Remove 18 obsolete internal stream-parser, reply-registry, and plugin-barrel exports plus an unused Claude test helper; every historically shipped public CLI-backend SDK type remains available from its canonical SDK entrypoint.

Live evidence

The actual built production Anthropic adapter was executed against the real installed Claude Code executable, with all Anthropic credential environment variables removed and native tools denied. The genuine SDK/CLI process produced the following redacted structured events:

{"ok":false,"name":"Error","message":"Claude Code returned an error result: Failed to authenticate: OAuth session expired and could not be refreshed","events":[{"type":"system","subtype":"init"},{"type":"system","subtype":"status"},{"type":"assistant","error":"authentication_failed"},{"type":"result","subtype":"success","isError":true}]}

This proves the bundled SDK chunk resolves, the real installed Claude subprocess starts, genuine initialization/status/assistant/result records stream through the simpler SDK-native string prompt, and the existing owner correctly handles Anthropic's error result despite its misleading success subtype.

Extended live testing then ran the actual built OpenClaw adapter, actual official Anthropic Agent SDK, and actual installed Claude Code executable against a loopback-only synthetic Anthropic SSE server with a throwaway fake API key. This produced genuine successful subprocess conversations without accessing any account or provider: streamed plain replies, exact zero-tool requests, a host-denied Bash tool attempt, an actually executed host-approved printf SDK_TOOL_OK command whose output returned in the next real model request, and two successful turns retaining the same observed Claude PID and session UUID (one registration, two activations). It also proved successful persisted-session resume across distinct Claude PIDs, real process replacement with changed model/system prompt and owner generation, three isolated concurrent session owners, and correct 429/529 terminal error classification. In-flight cancellation terminated and demonstrably reaped the actual Claude PID; malformed settings/effort/turn-limit arguments and already-aborted admission failed before making HTTP requests. This proves the actual SDK/Claude process, native tool execution, and HTTP-stream integration, but the synthetic server is deliberately not subscription-authentication proof.

The final rebuilt-artifact stress pass issued 61 synthetic provider requests through 28 actual Claude subprocesses, with zero surviving processes and zero retained owner handles. It proved ten consecutive turns on one Claude PID/session/generation, three genuinely parallel owners, same-owner overlap rejection, six alternating allowed/denied native Bash turns, persisted-session resume, model/system-prompt restart, HTTP 400/401/403/429/500/529 classification, malformed/truncated SSE, and partial streamed output before both abort and timeout.

The selected-credential path was live-tested separately through the actual built backend, installed Claude binary, and SDK custom spawner. A throwaway fake API key appeared only on descriptor 3, never in the subprocess environment or argv; all four copied credential buffers were zeroized. The real Claude process completed a plain response, denied a real Bash command before side effects, executed an explicitly approved real shell command, and reaped the child on cancellation.

Finally, the rebuilt production adapter and installed Claude Code executable were tested against Anthropic's actual hosted API using the existing approved live-test API key, retrieved without prompting or logging secrets and delivered exclusively through private descriptor 3. Five genuinely authenticated turns returned LIVE_AUTH_OK, retained BLUE-731 across two turns on the same Claude process/session, denied a real Bash action, executed an approved real shell command returning LIVE_TOOL_OK, and canceled after visible streamed output. All five copied credential buffers were zeroized, the child environment contained no API key, and all five real Claude subprocesses were reaped. Total metered provider cost: $0.0313352. This proves real API-key authentication and the exact SDK/provider/tool path; it is not a claim of successful Claude subscription authentication.

Additional actual-subprocess SDK control-protocol scenarios verified exact per-turn allow/deny callbacks, malformed tool-input rejection, gateway-MCP bypass only for host-owned tools, background-agent provisional-result holding, fingerprint-change restart, stale-owner rejection, pending-approval cancellation fencing, native session resume flags, and cleanup/reaping. An already-aborted one-shot initially launched a real Claude process; a failing regression captured that defect, and the fixed source plus rebuilt artifact now reject both default and custom abort reasons before any subprocess starts.

Both built operator entry points (agent --local and isolated agent exec) were also run with separate temporary state/config, no provider credentials, and the real installed Claude executable. Both reached the official SDK/warm-session owner and returned the same structured, actionable expired-OAuth failure; plugin discovery, Claude model catalog, MCP startup, and provider error classification were exercised end to end.

A separate real SDK-to-Claude native Bash probe verified the OpenClaw approval callback remains authoritative across all four combinations of ordinary disableAllHooks and enterprise-managed allowManagedHooksOnly / disableAllHooks. Even with settings that otherwise auto-allow Bash, the host callback denied the actual shell action, the model received the denial, and the command never executed.

All three local Claude installations report loggedIn: false, all six local Claude account slots report no_credentials, and OpenClaw has no configured Anthropic OAuth profile. Consequently the real authenticated proof uses Anthropic's approved live-test API key, not a Claude subscription. Anthropic's current first-party documentation explicitly supports subscription-backed Agent SDK and third-party app usage through the user's own already-authenticated, unmodified Claude executable; the newly documented claude auth login recovery is the required operator setup for that credential variant.

Verification

  • Exact rebased-head focused regression pass: 684 passing tests, including 439 plugin dependency-contract cases and current main's explicit-current-source delivery regression, across the SDK provider, lifecycle/approval/cleanup owners, Docker/build ownership, CLI help, interrupted-response integration, and provider/CLI contract suites. Newly added cases cover real process-grandchild termination, private descriptor delivery/zeroization, 1 MiB child-stderr drainage, ambient and selected-credential native approval, variadic directory/tool arguments, prompt-file and cache-marker elimination, exact MCP capture ownership, hard approval/background deadlines, two-turn cleanup, restart, cancellation races, and both abort/deadline settlement.
  • Earlier broad SDK/runtime/security/sibling-provider suite: 604 passing tests covering persistent same-query reuse, real native skill-manifest/materialization and process-owned cleanup, already-aborted zero-spawn fencing, changed-prompt restart, exact MCP authorization and capture rotation, host-owned session approvals, policy tightening, background completion, watchdog grace, required-generation expiry/recovery, cross-owner rejection, third-party serialization, and Google provider compatibility.
  • Broader existing CLI/setup/onboarding/auth/events/diagnostics suite: 352 passing tests; plus 13 passing production-distribution end-to-end scenarios, including ordered Claude/provider fault recovery and a real built Gateway with persisted session/transcript product proof: 969 passing tests total.
  • Complete core, plugin, and repository-script TypeScript project graphs pass.
  • Full production build passes, including bundled plugin assets, runtime postbuild, and loading 48 built plugin/control-plane modules.
  • A complete clean default Linux/arm64 production Docker build passes the frozen workspace install, offline production prune, production bundle, Control UI build, and final package-import closure check. Its production filesystem contains the SDK and working bundled provider but zero SDK native platform binaries, removing 271,825,824 bytes; selecting ACPX preserves its declared 14 supported platform package requirements.
  • Plugin SDK surface check passes; direct dependency pin guard checks 619 dependency specs across 177 package manifests with zero violations; maximum-lines ratchet passes.
  • Production, full-tree, and script dead-export scans all report zero unused exports; the assertion-safety ratchet passes after removing unsafe casts and stale exceptions for deleted legacy files.
  • Actual root npm pack --dry-run --json --ignore-scripts inspection proves zero node_modules entries and zero SDK native binaries in the published artifact; the SDK JavaScript contributes an approximately 1.2 MiB production chunk. Source/Docker installs select at most the matching host binary; the dependency already exists in the full workspace through ACPX.
  • Independent isolated Codex P1 architecture/security review after the approval, fd-3, interruption, process-tree, Docker, assertion, dead-export, and lint repairs: no accepted/actionable findings.

Credential and dependency boundaries

Related context

@clawsweeper

clawsweeper Bot commented Aug 23, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling extensions: anthropic size: XL maintainer Maintainer-authored PR labels Aug 23, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 23, 2026
@clawsweeper

clawsweeper Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 24, 2026, 4:33 AM ET / 08:33 UTC.

ClawSweeper review

What this changes

Replaces the Anthropic plugin’s handwritten warm Claude CLI session transport with Anthropic’s Agent SDK and a generic host-owned reusable-session interface.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep open for maintainer review: this replaces a security- and availability-sensitive Claude execution path and adds a public CLI-plugin transport; no concrete code defect was found, but the pinned SDK contract could not be directly audited and two current check lanes are failing.

Priority: P2
Reviewed head: 283b66f4d779ccfa4b976e2ed3835974e258f161

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch has substantial owner-boundary coverage and detailed runtime evidence, with dependency-contract and exact-head CI verification still material before merge.
Proof confidence 🌊 off-meta tidepool Not applicable: Maintainer-authored PRs are exempt from the contributor proof gate; the PR body nevertheless documents extensive redacted after-fix subprocess and hosted-API runs.
Patch quality 🐚 platinum hermit (4/6) Security review found an item that needs attention.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Maintainer-authored PRs are exempt from the contributor proof gate; the PR body nevertheless documents extensive redacted after-fix subprocess and hosted-API runs.
Evidence reviewed 7 items Changed execution boundary: The Anthropic runtime directly imports and invokes the Agent SDK, including its custom subprocess path; this establishes the dependency-specific review gate.
Host authority enforcement: The core executor revalidates admitted-run authority before and after awaited native-tool approval, then fences retained callbacks before iterator cleanup.
Live-session ownership: The generic registry binds a session to its exact owner, fingerprint, generation, and capture grant before activation, with focused tests for rejection and cleanup cases.
Findings None None.
Security Needs attention Audit the pinned SDK’s subprocess and hook contract: The patch delegates Claude process startup, permission callbacks, and query lifecycle to a newly added runtime dependency, whose installed 0.3.219 source/types were unavailable for direct review.

How this fits together

Local Claude CLI agent turns are prepared by the Anthropic plugin, executed through the core CLI runner, and returned as normalized agent output. This change moves Claude subprocess/session handling into the official SDK while core retains admission, tool approval, MCP capture, and cleanup ownership.

flowchart LR
  A[Agent turn] --> B[Anthropic CLI plugin]
  B --> C[Core CLI runner]
  C --> D[Host-owned session and approval gate]
  D --> E[Anthropic Agent SDK]
  E --> F[Installed Claude Code process]
  F --> G[Streamed agent output]
  D --> H[Gateway MCP tools]
Loading

Before merge

  • Resolve security concern: Audit the pinned SDK’s subprocess and hook contract - The patch delegates Claude process startup, permission callbacks, and query lifecycle to a newly added runtime dependency, whose installed 0.3.219 source/types were unavailable for direct review.
  • Resolve merge risk (P1) - The new pinned SDK owns child-process protocol behavior and custom spawn callbacks, but its exact source/types were unavailable for direct contract review.
  • Resolve merge risk (P1) - Existing Claude CLI users can encounter changed session, approval, credential-forwarding, or process-lifecycle behavior on upgrade; exact-head CI still includes two failed check lanes whose logs were unavailable here.
  • Complete next step (P2) - Protected maintainer work needs a human dependency-contract and exact-head CI review before merge.

Findings

  • [medium] Audit the pinned SDK’s subprocess and hook contract — extensions/anthropic/agent-sdk.runtime.ts:4
Agent review details

Security

Needs attention: The new SDK-backed custom spawn and permission path needs an exact-version dependency audit before merge.

Review metrics

Metric Value Why it matters
Production and test delta production −1,186; tests/support −4,245 (reported in PR body) The large refactor is presented as a net deletion, so review should focus on retained ownership invariants rather than raw size.
Plugin SDK contract 7 types added, 1 legacy requirement type removed The public CLI-backend seam now supports plugin-owned execution and reusable-session lifecycle capabilities.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/commands/doctor-claude-cli.test.ts, migration/backfill/repair: src/commands/doctor-claude-cli.ts, serialized state: scripts/lib/bundled-plugin-build-entries.mjs, serialized state: scripts/lib/docker-plugin-selection.mjs, serialized state: scripts/lib/root-package-bundled-plugin-excludes.mjs, serialized state: src/agents/cli-runner.helpers.test.ts, and 12 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Complete SDK and upgrade verification (recommended)
    Inspect the exact pinned SDK’s query, hook, and custom-spawn contract, then resolve the failing exact-head checks before merging this execution-path replacement.

Technical review

Best possible solution:

Complete a direct audit of the resolved Agent SDK version and land only after exact-head validation demonstrates safe upgrade behavior for existing Claude CLI sessions.

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

Not applicable: this is a runtime refactor rather than a report of a separately reproducible user defect; the PR body supplies post-change runtime evidence.

Is this the best way to solve the issue?

Unclear: the generic host-owned seam is coherent, but direct inspection of the exact Agent SDK contract is still required before calling this the best implementation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 3e5b935edf3f.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool 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 broad but actively maintained provider-runtime refactor with meaningful, bounded user impact.
  • merge-risk: 🚨 compatibility: It changes how existing Claude CLI sessions, credentials, and resume behavior execute after upgrade.
  • merge-risk: 🚨 security-boundary: A new SDK custom-spawn and permission-hook path handles credentials and native tool authorization.
  • merge-risk: 🚨 availability: The change replaces warm subprocess lifecycle, cancellation, and process-tree cleanup for local Claude turns.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: Maintainer-authored PRs are exempt from the contributor proof gate; the PR body nevertheless documents extensive redacted after-fix subprocess and hosted-API runs.

Evidence

Security concerns:

  • [medium] Audit the pinned SDK’s subprocess and hook contract — extensions/anthropic/agent-sdk.runtime.ts:4
    The patch delegates Claude process startup, permission callbacks, and query lifecycle to a newly added runtime dependency, whose installed 0.3.219 source/types were unavailable for direct review.
    Confidence: 0.86

What I checked:

Likely related people:

  • steipete: Current reviewed runtime and generic session-owner lines blame to this PR head; recent history also shows continued Claude CLI maintenance. (role: current refactor author and recent area contributor; confidence: high; commits: 283b66f4d779, 2e606d96e1e7; files: extensions/anthropic/agent-sdk.runtime.ts, src/agents/cli-runner/cli-live-session-registry.ts)
  • VACInc: Commit 1b9d3ac introduced the preceding Claude live-session architecture that this change replaces. (role: prior warm-session feature contributor; confidence: medium; commits: 1b9d3ac57d13, 7f93011562db; files: extensions/anthropic/cli-backend.ts, src/agents/cli-runner)
  • joshavant: Commit d636f5f maintained the prior Claude live-session protocol gate adjacent to the replaced path. (role: adjacent protocol-gate contributor; confidence: medium; commits: d636f5f8e098; files: src/agents/cli-runner)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Inspect the resolved 0.3.219 SDK source/types for its query, hook, and custom-spawn contract.
  • Resolve the two failed exact-head check lanes and refresh the review against their output.

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-08-23T06:21:40.342Z sha 48f9e0b :: needs real behavior proof before merge. :: [P1] Keep SDK subprocesses under managed lifecycle ownership | [P3] Remove the release-owned changelog entry
  • reviewed 2026-08-23T23:55:59.190Z sha fe842da :: needs real behavior proof before merge. :: [P1] Keep the SDK child under managed lifecycle ownership | [P1] Avoid bundling every Agent SDK platform binary | [P2] Qualify the SDK-native tool documentation | [P3] Remove the release-owned changelog entry
  • reviewed 2026-08-24T01:15:25.191Z sha 63fbaa3 :: needs real behavior proof before merge. :: [P1] Keep the SDK child under managed lifecycle ownership | [P1] Prevent all-platform Agent SDK binaries from reaching plugin installs | [P2] Qualify the SDK-native tool documentation | [P3] Remove the release-owned changelog entry
  • reviewed 2026-08-24T01:41:53.974Z sha b432b66 :: needs real behavior proof before merge. :: [P1] Bundle only the host’s Agent SDK binary | [P1] Keep the SDK child under managed lifecycle ownership | [P1] Bind native-tool approval to the originating turn | [P2] Document the Agent SDK eligibility gate | [P3] Remove the release-owned changelog entry
  • reviewed 2026-08-24T04:16:57.559Z sha b4eaed2 :: needs real behavior proof before merge. :: [P1] Preserve host approval for native-tool turns | [P1] Do not package foreign Agent SDK binaries | [P2] Document the SDK fallback eligibility
  • reviewed 2026-08-24T07:26:52.967Z sha 4508a01 :: found issues before merge. :: [P3] Remove the release-owned changelog entry

@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Aug 23, 2026
@steipete steipete changed the title refactor(anthropic): explore official Claude Agent SDK runtime refactor(anthropic): replace handwritten Claude sessions with Agent SDK Aug 23, 2026
@openclaw-barnacle openclaw-barnacle Bot added the commands Command implementations label Aug 24, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 24, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 24, 2026
@openclaw-barnacle openclaw-barnacle Bot added cli CLI command changes scripts Repository scripts docker Docker and sandbox tooling labels Aug 24, 2026
@clawsweeper clawsweeper Bot added 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: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 24, 2026
obviyus added a commit that referenced this pull request Sep 13, 2026
Related: #144392

Supersedes #145788 by @Marvinthebored. Thanks to @EnotionZ for the issue report. The original commit and authorship are preserved.

## What Problem This Solves

Canceling a reply makes the next turn forget the conversation, even though earlier messages still appear in history.

## User Impact

Stopping a reply keeps the established conversation available for the next turn. Invalid sessions and account boundaries still receive their existing checks.

## Why This Change Was Made

Retain established native bindings on cancellation. Clear unfinished replacements on both thrown errors and returned partial-output interruptions. An incomplete fork claim is restored by current-owner cleanup even when the signal is aborted. New claims, successor publication, and recovery arming retain their abort guards; all writes retain session, lifecycle, writer, and source-binding checks.

This preserves partial-output reporting from #126883 while removing cancellation-only binding invalidation. No schema, migration, configuration, protocol, or dependency change.

## Final-head evidence

Head `b068bf05618ddcd3e1b28894c68ad734e0eac997` includes a one-line test-type correction that passes the existing defined session entry; the command still reloads persisted state before choosing the next native binding. All 157 tests in that file, targeted lint, and formatting pass. Production source is unchanged from `2c163fd9eb57100ae3a2eec38cb6038e5f752851`.

The complete affected owner suites passed on fresh merge `4b66a1a18209c21b5e92986452b2b98b95ae6fa1`, with parents `2c163fd9eb57100ae3a2eec38cb6038e5f752851` and main `9542320aa5cdcc4af53e3b05ad75160992a34407`. All **28 complete canonical groups exited 0**: 46,971 labeled passes and 88 skips. Three cases are unlabelled in the native support summary; no status is inferred. This includes both fork-restoration cases and all four abort/timeout × established/replacement command cases. Complete current group membership, exact commands, numeric exits, and raw logs are retained.

```sh
env -u NO_COLOR -u FORCE_COLOR node --import tsx scripts/ci-run-node-test-shard.mts
```

Hosted [CI run 34774482283, attempt 1](https://github.com/openclaw/openclaw/actions/runs/34774482283) passed except `checks-node-compact-small-32` and its aggregate gate. Its QA-profile routing assertion is **base-red**: the same test fails on plain main `28887b564210326174413d0d8ade72b38268d5f3` and fresh candidate/main merge `7ea7374fcf62570c9b3fa631cf17072ef5eda2d6`, both exit 1. #143968 (`07b96d9b4122e1afdd0efbb662b2335eb716dfec`) added `qa-profile-run-status.test.ts` as a sixth workflow reader without updating the five-target expectation. This PR changes none of those routing inputs.

```sh
OPENCLAW_E2E_USE_PREBUILT_DIST=1 node scripts/run-vitest.mjs run \
  test/scripts/test-projects.test.ts -t 'routes QA Profile Evidence'
```

## Fork-claim correction

Candidate `2c163fd9eb57100ae3a2eec38cb6038e5f752851` restores a committed fork claim after cancellation before a successor appears. Previously, restoration rejected the aborted signal, lost the fork marker, and let the next command resume the source directly. Cleanup now uses the existing current-owner settlement assertion. Stale session, lifecycle, writer, placement, and source-binding checks remain enforced.

The regression fails on `e2ca5b29bfa09810aaa20eca8a1d0e85ced913c8`: the marker is absent and the next command receives `forkCliSessionOnResume=false`. After correction, both the recovery-error control and actual-signal cancellation pass; stored/cache markers and the source checkpoint remain, and the next command receives `forkCliSessionOnResume=true`.

```sh
env -u NO_COLOR -u FORCE_COLOR node scripts/run-vitest.mjs run \
  --config test/vitest/vitest.agents.config.ts \
  src/agents/command/attempt-execution.cli.test.ts --maxWorkers=1 \
  -t 'preserves a restored fork marker before a successor'
```

Fresh merge `54a5c90a8b4585f72842e380365b95263b05983d` has first parent candidate `2c163fd9eb57100ae3a2eec38cb6038e5f752851` and second parent main `adb6e518a44218650883f3daec4bd319165e0017`. All **436 tests in seven complete focused files passed**, including command successor/flag cleanup, aborted pre-successor restoration, stale-store guards, returned interruption, thrown cancellation, auto-reply, and fork-runner siblings. This bounded rerun supplements the earlier complete suites.

Both real Gateway cancellation shapes also passed on that merge: before output (zero assistant events) and after first output. Both next turns resumed the same native binding, logged `historyPrompt=none`, and recalled `PEBBLE-7429`. Both drivers exited 0. The new catalog regression uses the real command/store entry point with a mocked native runner; it proves next-turn fork routing, not a new live source-transcript isolation capture.

Targeted lint passed, including max-lines:

```sh
pnpm exec oxlint --config .oxlintrc.json \
  src/agents/command/attempt-execution.ts \
  src/agents/command/attempt-execution.cli.test.ts
```

Original red evidence remains intact. Exact commands, merge identities, numeric exits, and complete captures are retained. The complete affected-suite rerun and final-head CI classification are recorded above.

## Earlier evidence

Validated corrected candidate `4fd555e5957f86289cf981ce4cf4b0bb1122c679` on temporary merge `d5f41d1cd6c9b603db32deec1d60c1ba93e7e04d`. Its parents are that candidate and main `a0cce74d389d737d6dcf21de7344af10cf862f72`.

All 28 complete canonical CI groups for the affected agent, reply, scheduled-run, and fast test suites exited 0 on that merge. Reporters label **46,859 tests passed and 88 skipped**. The full command persistence matrix passed, including unfinished-successor and temporary-flag cleanup for abort and timeout, plus established-binding resume.

Each complete group ran through the CI command, with its canonical configuration, include list and environment preserved:

```sh
node --import tsx scripts/ci-run-node-test-shard.mts
```

These are the complete affected test suites on the recorded merge. Final-head CI and its reproduced base-red exception are recorded above. Initial host setup failures were retained, then resolved by removing conflicting color settings and making GNU timeout available without replacing existing command resolution. No source assertions or timeouts were relaxed. One native summary leaves three cases unlabeled; the raw count line is retained without assigning them a status.

The real Gateway was also rerun from the merge with isolated state, workspace and port:

```sh
OPENCLAW_CONFIG_PATH="$PROOF/openclaw.json" OPENCLAW_STATE_DIR="$PROOF/state" \
  pnpm openclaw gateway --port 21978 --bind loopback
```

`chat.send` remembered a synthetic code, a second request started a long reply, `chat.abort` canceled it, and the next `chat.send` requested the code without repeating it.

| Cancellation | Recorded main | Corrected merge |
| --- | --- | --- |
| Before output | Fresh native session; `UNKNOWN` | Same native binding; `PEBBLE-7429` |
| After first output | Fresh native session; `UNKNOWN` | Same native binding; `PEBBLE-7429` |

Both drivers exited 0. Both continuations logged `useResume=true` with the same native fingerprint and `historyPrompt=none`. The pre-output run had zero assistant events before cancellation. Original red captures, merge parents, selection, exact commands, numeric exits and complete logs are preserved. Final-head CI and its reproduced base-red exception are recorded above.

## Compatibility and prior behavior

This deliberately changes the cancellation-only binding invalidation retained by #126883 and #128131. Partial output remains visible, interrupted turns remain unsuccessful, and successful authentication settlement remains suppressed. Expired-session recovery from #115513 and the retired-field migration from #143347 remain unchanged. There is no schema, migration, configuration, protocol, dependency, or permission change.

## Consumers

Command attempts, auto-reply turns, and scheduled turns consume the binding result. History import, session freshness, catalog continuation, export, runtime selection, and detached-media continuation read the retained binding or its explicit absence.

Catalog adoption seeds a binding with `forceReuse` and a one-shot fork marker. The command path claims that marker before execution and can persist a successor before final settlement. These writes require the current session, lifecycle, writer, and expected source binding. Successful settlement removes the temporary reuse flag; interrupted replacement cleanup removes the successor and flag together. An established binding remains available after cancellation. Cancellation before a fork successor appears restores the one-shot marker, so the next command must still fork from the source. Cache updates occur at the successful commit, and scheduled continuation publication follows base-session persistence.

## Evidence limits

The real Gateway sequences cover cancellation before output and after the first output. Both failed on main `fe3b2891fdeaa1a891d54cb2b306e975fc5408cf` and passed at `f9c5b148cf4d92de5211315a4e8c374bef279d9d`. The next turn resumed the same native binding without replaying local history and recalled the seeded code.

The initial 272 focused tests include command persistence and next-turn routing, auto-reply retention, failed-flush cleanup, and scheduled-run settlement. They ran on the branch based on `f85a9945daaebc61d041db27b4d3175d17082e37`. The later fresh merge `d5f41d1cd6c9b603db32deec1d60c1ba93e7e04d`, recorded above, passed all 28 complete affected test groups and both real Gateway cancellation shapes. No browser-click or platform-specific UI claim is made.

The two test suites that failed on the contributor head pass when applied to the refreshed main base and after correction. The original hosted failures were not reproduced in their original shard order, so their cause remains unclassified. No assertion or timeout was relaxed for this repair.

## Test ledger clarification

- The ordinary-abort policy and command assertions now require retention instead of unconditional deletion. Command coverage also checks the subsequent resume.
- The contributor-only interrupted-flush helper matrix was removed before the final diff because command persistence coverage supersedes it.
- The retained interrupted-partial-output fixture now names an established reusable session. Its unchanged clear assertion independently protects failed transcript flush; its partial-output, unsuccessful-hook, timeout, and authentication assertions remain.
- The new composition cases invoke `runAgentAttempt`, claim a fork, persist its successor, abort the actual signal, consume the production settlement result, reopen stored state, and check the next attempt. The channel regression invokes `executeAgentTurn`; the failed-flush regression invokes `runPreparedCliAgent`. Direct policy-unit assertions supplement these entry-point checks.

The earlier head `e2ca5b29bfa09810aaa20eca8a1d0e85ced913c8` only replaces a retained unflushed ID with the equivalent condition at its two consumers. Review accepted that behavior-preserving delta. CI run [34769866871](https://github.com/openclaw/openclaw/actions/runs/34769866871) passed at attempt 2 on this exact head. Attempt 1 had one test failure in an unrelated QA binary-admission case; it passed on the retry without a code or timeout change and is recorded as a flake.

Co-authored-by: Marvinthebored <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
Related: openclaw#144392

Supersedes openclaw#145788 by @Marvinthebored. Thanks to @EnotionZ for the issue report. The original commit and authorship are preserved.

## What Problem This Solves

Canceling a reply makes the next turn forget the conversation, even though earlier messages still appear in history.

## User Impact

Stopping a reply keeps the established conversation available for the next turn. Invalid sessions and account boundaries still receive their existing checks.

## Why This Change Was Made

Retain established native bindings on cancellation. Clear unfinished replacements on both thrown errors and returned partial-output interruptions. An incomplete fork claim is restored by current-owner cleanup even when the signal is aborted. New claims, successor publication, and recovery arming retain their abort guards; all writes retain session, lifecycle, writer, and source-binding checks.

This preserves partial-output reporting from openclaw#126883 while removing cancellation-only binding invalidation. No schema, migration, configuration, protocol, or dependency change.

## Final-head evidence

Head `b068bf05618ddcd3e1b28894c68ad734e0eac997` includes a one-line test-type correction that passes the existing defined session entry; the command still reloads persisted state before choosing the next native binding. All 157 tests in that file, targeted lint, and formatting pass. Production source is unchanged from `2c163fd9eb57100ae3a2eec38cb6038e5f752851`.

The complete affected owner suites passed on fresh merge `4b66a1a18209c21b5e92986452b2b98b95ae6fa1`, with parents `2c163fd9eb57100ae3a2eec38cb6038e5f752851` and main `a9a9a16114bea90d6eac90486356697df2462cb9`. All **28 complete canonical groups exited 0**: 46,971 labeled passes and 88 skips. Three cases are unlabelled in the native support summary; no status is inferred. This includes both fork-restoration cases and all four abort/timeout × established/replacement command cases. Complete current group membership, exact commands, numeric exits, and raw logs are retained.

```sh
env -u NO_COLOR -u FORCE_COLOR node --import tsx scripts/ci-run-node-test-shard.mts
```

Hosted [CI run 34774482283, attempt 1](https://github.com/openclaw/openclaw/actions/runs/34774482283) passed except `checks-node-compact-small-32` and its aggregate gate. Its QA-profile routing assertion is **base-red**: the same test fails on plain main `a1105f105a093f768914a29c24b70d6ba406cad8` and fresh candidate/main merge `7ea7374fcf62570c9b3fa631cf17072ef5eda2d6`, both exit 1. openclaw#143968 (`41aebf15de48524e80c95f05e0c1212f2dfd29c6`) added `qa-profile-run-status.test.ts` as a sixth workflow reader without updating the five-target expectation. This PR changes none of those routing inputs.

```sh
OPENCLAW_E2E_USE_PREBUILT_DIST=1 node scripts/run-vitest.mjs run \
  test/scripts/test-projects.test.ts -t 'routes QA Profile Evidence'
```

## Fork-claim correction

Candidate `2c163fd9eb57100ae3a2eec38cb6038e5f752851` restores a committed fork claim after cancellation before a successor appears. Previously, restoration rejected the aborted signal, lost the fork marker, and let the next command resume the source directly. Cleanup now uses the existing current-owner settlement assertion. Stale session, lifecycle, writer, placement, and source-binding checks remain enforced.

The regression fails on `e2ca5b29bfa09810aaa20eca8a1d0e85ced913c8`: the marker is absent and the next command receives `forkCliSessionOnResume=false`. After correction, both the recovery-error control and actual-signal cancellation pass; stored/cache markers and the source checkpoint remain, and the next command receives `forkCliSessionOnResume=true`.

```sh
env -u NO_COLOR -u FORCE_COLOR node scripts/run-vitest.mjs run \
  --config test/vitest/vitest.agents.config.ts \
  src/agents/command/attempt-execution.cli.test.ts --maxWorkers=1 \
  -t 'preserves a restored fork marker before a successor'
```

Fresh merge `54a5c90a8b4585f72842e380365b95263b05983d` has first parent candidate `2c163fd9eb57100ae3a2eec38cb6038e5f752851` and second parent main `e08263bdd3341031c219bb147638f23a1f4c3c03`. All **436 tests in seven complete focused files passed**, including command successor/flag cleanup, aborted pre-successor restoration, stale-store guards, returned interruption, thrown cancellation, auto-reply, and fork-runner siblings. This bounded rerun supplements the earlier complete suites.

Both real Gateway cancellation shapes also passed on that merge: before output (zero assistant events) and after first output. Both next turns resumed the same native binding, logged `historyPrompt=none`, and recalled `PEBBLE-7429`. Both drivers exited 0. The new catalog regression uses the real command/store entry point with a mocked native runner; it proves next-turn fork routing, not a new live source-transcript isolation capture.

Targeted lint passed, including max-lines:

```sh
pnpm exec oxlint --config .oxlintrc.json \
  src/agents/command/attempt-execution.ts \
  src/agents/command/attempt-execution.cli.test.ts
```

Original red evidence remains intact. Exact commands, merge identities, numeric exits, and complete captures are retained. The complete affected-suite rerun and final-head CI classification are recorded above.

## Earlier evidence

Validated corrected candidate `4fd555e5957f86289cf981ce4cf4b0bb1122c679` on temporary merge `d5f41d1cd6c9b603db32deec1d60c1ba93e7e04d`. Its parents are that candidate and main `e0ad90d2bc2effce521cbde79cec2be56cece725`.

All 28 complete canonical CI groups for the affected agent, reply, scheduled-run, and fast test suites exited 0 on that merge. Reporters label **46,859 tests passed and 88 skipped**. The full command persistence matrix passed, including unfinished-successor and temporary-flag cleanup for abort and timeout, plus established-binding resume.

Each complete group ran through the CI command, with its canonical configuration, include list and environment preserved:

```sh
node --import tsx scripts/ci-run-node-test-shard.mts
```

These are the complete affected test suites on the recorded merge. Final-head CI and its reproduced base-red exception are recorded above. Initial host setup failures were retained, then resolved by removing conflicting color settings and making GNU timeout available without replacing existing command resolution. No source assertions or timeouts were relaxed. One native summary leaves three cases unlabeled; the raw count line is retained without assigning them a status.

The real Gateway was also rerun from the merge with isolated state, workspace and port:

```sh
OPENCLAW_CONFIG_PATH="$PROOF/openclaw.json" OPENCLAW_STATE_DIR="$PROOF/state" \
  pnpm openclaw gateway --port 21978 --bind loopback
```

`chat.send` remembered a synthetic code, a second request started a long reply, `chat.abort` canceled it, and the next `chat.send` requested the code without repeating it.

| Cancellation | Recorded main | Corrected merge |
| --- | --- | --- |
| Before output | Fresh native session; `UNKNOWN` | Same native binding; `PEBBLE-7429` |
| After first output | Fresh native session; `UNKNOWN` | Same native binding; `PEBBLE-7429` |

Both drivers exited 0. Both continuations logged `useResume=true` with the same native fingerprint and `historyPrompt=none`. The pre-output run had zero assistant events before cancellation. Original red captures, merge parents, selection, exact commands, numeric exits and complete logs are preserved. Final-head CI and its reproduced base-red exception are recorded above.

## Compatibility and prior behavior

This deliberately changes the cancellation-only binding invalidation retained by openclaw#126883 and openclaw#128131. Partial output remains visible, interrupted turns remain unsuccessful, and successful authentication settlement remains suppressed. Expired-session recovery from openclaw#115513 and the retired-field migration from openclaw#143347 remain unchanged. There is no schema, migration, configuration, protocol, dependency, or permission change.

## Consumers

Command attempts, auto-reply turns, and scheduled turns consume the binding result. History import, session freshness, catalog continuation, export, runtime selection, and detached-media continuation read the retained binding or its explicit absence.

Catalog adoption seeds a binding with `forceReuse` and a one-shot fork marker. The command path claims that marker before execution and can persist a successor before final settlement. These writes require the current session, lifecycle, writer, and expected source binding. Successful settlement removes the temporary reuse flag; interrupted replacement cleanup removes the successor and flag together. An established binding remains available after cancellation. Cancellation before a fork successor appears restores the one-shot marker, so the next command must still fork from the source. Cache updates occur at the successful commit, and scheduled continuation publication follows base-session persistence.

## Evidence limits

The real Gateway sequences cover cancellation before output and after the first output. Both failed on main `0c664785f82d3af6c2101efb53d7269d30261f4c` and passed at `f9c5b148cf4d92de5211315a4e8c374bef279d9d`. The next turn resumed the same native binding without replaying local history and recalled the seeded code.

The initial 272 focused tests include command persistence and next-turn routing, auto-reply retention, failed-flush cleanup, and scheduled-run settlement. They ran on the branch based on `329bc5bf9694af38477f9fd45ebe47ad86b538a9`. The later fresh merge `d5f41d1cd6c9b603db32deec1d60c1ba93e7e04d`, recorded above, passed all 28 complete affected test groups and both real Gateway cancellation shapes. No browser-click or platform-specific UI claim is made.

The two test suites that failed on the contributor head pass when applied to the refreshed main base and after correction. The original hosted failures were not reproduced in their original shard order, so their cause remains unclassified. No assertion or timeout was relaxed for this repair.

## Test ledger clarification

- The ordinary-abort policy and command assertions now require retention instead of unconditional deletion. Command coverage also checks the subsequent resume.
- The contributor-only interrupted-flush helper matrix was removed before the final diff because command persistence coverage supersedes it.
- The retained interrupted-partial-output fixture now names an established reusable session. Its unchanged clear assertion independently protects failed transcript flush; its partial-output, unsuccessful-hook, timeout, and authentication assertions remain.
- The new composition cases invoke `runAgentAttempt`, claim a fork, persist its successor, abort the actual signal, consume the production settlement result, reopen stored state, and check the next attempt. The channel regression invokes `executeAgentTurn`; the failed-flush regression invokes `runPreparedCliAgent`. Direct policy-unit assertions supplement these entry-point checks.

The earlier head `e2ca5b29bfa09810aaa20eca8a1d0e85ced913c8` only replaces a retained unflushed ID with the equivalent condition at its two consumers. Review accepted that behavior-preserving delta. CI run [34769866871](https://github.com/openclaw/openclaw/actions/runs/34769866871) passed at attempt 2 on this exact head. Attempt 1 had one test failure in an unrelated QA binary-admission case; it passed on the retry without a code or timeout change and is recorded as a flake.

Co-authored-by: Marvinthebored <[email protected]>
Co-authored-by: Ayaan Zaidi <[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 cli CLI command changes commands Command implementations dependencies-changed PR changes dependency-related files docker Docker and sandbox tooling docs Improvements or additions to documentation extensions: anthropic extensions: google gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants