Skip to content

fix: active-memory recall fails with billing rejections on subscription-only Claude CLI setups - #106840

Merged
Patrick-Erichsen merged 1 commit into
openclaw:mainfrom
bill-starfoundry:fix/active-memory-claude-cli-recall
Jul 16, 2026
Merged

Patrick-Erichsen merged 1 commit into
openclaw:mainfrom
bill-starfoundry:fix/active-memory-claude-cli-recall

Conversation

@bill-starfoundry

@bill-starfoundry bill-starfoundry commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Closes #106839
Related: #86761

What Problem This Solves

Fixes an issue where agents running on the Claude CLI runtime with subscription-only auth (Claude Code OAuth, no Anthropic API key) would have every active-memory recall either fail with a billing rejection (no extra-usage balance) or silently draw paid metered extra usage (extra usage enabled) — while main-session turns correctly ran on plan limits through the CLI backend. Anthropic routing direct anthropic-messages calls on subscription tokens to extra-usage billing is long-standing behavior; the embedded runner's direct-API passthrough (cli_runtime_passthrough_openclaw) was never a viable path for these credentials.

Why This Change Was Made

Adds an opt-in RunEmbeddedAgentParams.cliBackendDispatch: "subscription-auth": when the run's provider is claude-cli — directly or via a canonical anthropic/<model> ref whose configured agentRuntime is claude-cli — a backend is registered, and the ordered credential selection resolves to subscription (oauth/token) or nothing rather than an API key, the run executes through runCliAgent as a one-shot turn. Active-memory recall opts in. The dispatch preserves the embedded run's contracts:

  • Tool restriction is enforced server-side: toolsAllow maps to the selectable-backend surface, bounds the loopback MCP grant (tools outside it can be neither listed nor called, even under bypass permission modes), and restricted runs get an exclusive loopback-only MCP bundle — user/plugin MCP servers are not merged in.
  • Transcript parity: the run is mirrored into the caller-owned session file (user turn, live tool call/result records, assistant snapshot — flushed immediately on abort), so persistTranscripts, timeout partial-text salvage, and the live terminal-search watcher work identically to embedded runs.
  • Isolation: fresh CLI process per run, no live-session reuse, session-scoped MCP cleanup (never the process-wide loopback server), CLI session bindings dropped from the result.
  • Scope: claude-cli only; google-gemini-cli and custom backends keep the passthrough — their direct-API contracts were not verified and this PR makes no claims about them. An available API key keeps the existing fast passthrough. The core-side provider set could move to a CliBackendConfig capability flag if maintainers prefer that seam.

User Impact

Subscription-only Claude CLI deployments get working active-memory recall on plan limits, consistent with their main turns — instead of failing every turn or silently consuming paid extra usage. Setups with an Anthropic API key see no behavior change. No config changes required; note that CLI-dispatched recalls measured 13.8–16.9s on a dev laptop, so the plugin's default 15s timeoutMs is tight — 30s is comfortable.

Evidence

Current-head success (read this first): on PR head aebb9ee1f7 (a code-identical rebase of proof head 92917da5ae, whose dist produced the run below), a live subscription-only recall with the default plugin config (no timeoutMs override) completes end-to-end:

# Subscription-only auth store (the reported failure setup):
[plugins] active-memory: ... activeProvider=claude-cli activeModel=claude-opus-4-8 thinking=off fast=inherit start timeoutMs=45000 queryChars=70 searchQueryChars=70
[agents/embedded-cli-dispatch] dispatching embedded run through CLI backend: runId=active-memory-mrn4uh1l-3d620c7b provider=claude-cli model=claude-opus-4-8
[plugins] active-memory: ... done status=ok elapsedMs=11941 summaryChars=64

# Same head + build, auth store seeded with a claude-cli api_key profile:
[plugins] active-memory: ... activeProvider=claude-cli activeModel=claude-opus-4-8 start timeoutMs=15000 queryChars=170 searchQueryChars=169
[plugins] active-memory: ... done status=failed elapsedMs=1178 summaryChars=0
# 15000 ms plain default selected, no [agents/embedded-cli-dispatch] line: the API-key run
# stays on the direct passthrough (it fails here only because the fixture key is fake).
# timeoutMs above is selected by the runner's own dispatch eligibility, not a route-only check.

timeoutMs=45000 is the new CLI-runtime default applied from unset config; status=ok with a grounded, cited summary is the successful default-config recall the review asked for. Details, the deny-path proof, and earlier rounds follow.

Before (subscription-only claude-cli setup): every recall fails in under a second, with the recall session recording the direct anthropic-messages route.

Before: per-turn billing rejection on the passthrough
# Gateway log excerpt: active-memory recall on a subscription-only claude-cli
# setup (Linux), before this change. Every eligible turn produced this failure.

[agent/embedded] embedded run agent end: runId=active-memory-... isError=true model=claude-opus-4-8 provider=claude-cli error=LLM request failed: provider rejected the request schema or tool payload. rawError={"type":"error","error":{"type":"invalid_request_error","message":"Third-party apps now draw from your extra usage, not your plan limits. Add more at claude.ai/settings/usage and keep going."}...
[agent/embedded] embedded run failover decision: ... stage=assistant decision=surface_error reason=billing from=claude-cli/claude-opus-4-8
[plugins] active-memory: memory sub-agent failed, skipping recall: LLM request rejected: ...
[plugins] active-memory: ... done status=failed elapsedMs=650 summaryChars=0

# The recall session transcript recorded the direct-API route:
#   "api":"anthropic-messages","provider":"claude-cli"
# with an empty assistant message, stopReason:"error", zero usage.

After (macOS, this branch, from source, no API key or synced credential profile): recall dispatches through the CLI backend as an independent one-shot process, the Claude child calls the memory tools through the grant-filtered loopback MCP bridge, and the run completes in 16.9s.

After: CLI-backend dispatch with grant-scoped MCP tool calls
2026-07-13T13:06:11.303-06:00 [plugins] active-memory: agent=main session=agent:main:direct:probe activeProvider=claude-cli activeModel=claude-opus-4-8 start timeoutMs=60000 queryChars=357 searchQueryChars=46
2026-07-13T13:06:11.529-06:00 [agents/embedded-cli-dispatch] dispatching embedded run through CLI backend: runId=active-memory-mrjlf6xz-8e7d1d14 provider=claude-cli model=claude-opus-4-8
2026-07-13T13:06:11.611-06:00 [agent/cli-backend] cli exec: provider=claude-cli model=claude-opus-4-8 promptChars=4384 trigger=manual useResume=false session=none resumeSession=none reuse=none historyPrompt=none
2026-07-13T13:06:28.240-06:00 [plugins] active-memory: agent=main session=agent:main:direct:probe activeProvider=claude-cli activeModel=claude-opus-4-8 done status=unavailable elapsedMs=16937 summaryChars=0
2026-07-13T13:06:28.320-06:00 [agent/cli-backend] claude live session start: provider=claude-cli model=claude-opus-4-8 activeSessions=1
2026-07-13T13:06:30.563-06:00 [agent/cli-backend] claude live session turn: provider=claude-cli model=claude-opus-4-8 durationMs=2241 rawLines=19 outBytes=18 outHash=6418a0305fab
2026-07-13T13:06:30.565-06:00 [agent/cli-backend] claude live session close: provider=claude-cli model=claude-opus-4-8 reason=restart
   2 "name":"mcp__openclaw__memory_get"
   2 "name":"mcp__openclaw__memory_search"
After: persistTranscripts announcing the persisted transcript
2026-07-13T13:46:16.067-06:00 [plugins] active-memory: agent=main session=agent:main:direct:probe activeProvider=claude-cli activeModel=claude-opus-4-8 start timeoutMs=30000 queryChars=223 searchQueryChars=52
2026-07-13T13:46:16.429-06:00 [agents/embedded-cli-dispatch] dispatching embedded run through CLI backend: runId=active-memory-mrjmuqgz-022c38a4 provider=claude-cli model=claude-opus-4-8
2026-07-13T13:46:35.408-06:00 [plugins] active-memory: agent=main session=agent:main:direct:probe activeProvider=claude-cli activeModel=claude-opus-4-8 transcript=~/.openclaw-recall-probe2/plugins/active-memory/transcripts/agents/main/active-memory/active-memory-mrjmuqgz-022c38a4.jsonl
2026-07-13T13:46:35.411-06:00 [plugins] active-memory: agent=main session=agent:main:direct:probe activeProvider=claude-cli activeModel=claude-opus-4-8 done status=unavailable elapsedMs=19343 summaryChars=0
After: the persisted OpenClaw transcript (full record chain)
{"type":"session","version":3,"id":"active-memory-mrjmuqgz-022c38a4","timestamp":"2026-07-13T19:46:16.431Z","cwd":"~/.openclaw/workspace-recall-probe2"}
{"type":"message","id":"dfc7835d-0bd3-46a0-9993-243e8b34d2f3","parentId":null,"timestamp":"2026-07-13T19:46:16.431Z","message":{"role":"user","content":[{"type":"text","text":"You are a memory search agent.\nAnother model is preparing the final user-facing answer.\nYour job is to search memory and return only the most relevant memory context for that model.\nYou receive a bounded search query plus conversation context, including the user's latest message.\nUse only the available memory tools.\nUse the bounded search query with the configured memory tools.\nConfigured memory tools: memory_search, memory_get.\nDo not use channel metadata, provider metadata, debug output, or the full conversation context as the memory tool query.\nIf the available memory tools find nothing useful, reply with NONE.\nWhen searching for preference or habit recall, use permissive search limits or thresholds before deciding that no useful memory exists.\nDo not answer the user directly.\nPrompt style: balanced.\nTreat the latest user message as the primary query.\nUse recent conversation only to disambiguate what the latest user message means.\nDo not return memory just because it matched the broader recent topic; return memory only if it clearly helps with the latest user message itself.\nIf recent context and the latest user message point to different memory domains, prefer the domain that best matches the latest user message.\nIf the user is directly asking about favorites, preferences, habits, routines, or personal facts, treat that as a strong recall signal.\nQuestions like 'what is my favorite food', 'do you remember my flight preferences', or 'what do i usually get' should normally return memory when relevant results exist.\nIf the provided conversation context already contains recalled-memory summaries, debug output, or prior memory/tool traces, ignore that surfaced text unless the latest user message clearly requires re-checking it.\nReturn memory only when it would materially help the other model answer the user's latest message.\nMutable operational facts (cron/job health, automation status, deployments, incidents, service availability) go stale quickly: include the source timestamp when available, say when the memory may be stale, and tell the answering model to verify live before relying on it.\nDo not summarize mutable operational facts as simply current/running/healthy unless the memory result itself contains a current source timestamp and matching health state.\nIf the connection is weak, broad, or only vaguely related, reply with NONE.\nIf nothing clearly useful is found, reply with NONE.\nReturn exactly one of these two forms:\n1. NONE\n2. one compact plain-text summary\nIf something is useful, reply with one compact plain-text summary under 220 characters total.\nWrite the summary as a memory note about the user, not as a reply to the user.\nDo not explain your reasoning.\nDo not return bullets, numbering, labels, XML, JSON, or markdown list formatting.\nDo not prefix the summary with 'Memory:' or any other label.\n\nGood examples:\nUser message: What is my favorite food?\nReturn: User's favorite food is ramen; tacos also come up often.\nUser message: Do you remember my flight preferences?\nReturn: User prefers aisle seats and extra buffer over tight connections.\nRecent context: user was discussing flights and airport planning.\nLatest user message: I might see a movie while I wait for the flight.\nReturn: User's favorite movie snack is buttery popcorn with extra salt.\nUser message: Explain DNS over HTTPS.\nReturn: NONE\n\nBad examples:\nReturn: - Favorite food is ramen\nReturn: 1. Favorite food is ramen\nReturn: Memory: Favorite food is ramen\nReturn: {\"memory\":\"Favorite food is ramen\"}\nReturn: <memory>Favorite food is ramen</memory>\nReturn: Ramen seems to be your favorite food.\nReturn: You like aisle seats and extra buffer.\nReturn: I prefer aisle seats and extra buffer.\nRecent context: user was discussing flights and airport planning. Latest user message: I might see a movie while I wait for the flight. Return: User prefers aisle seats and extra buffer over tight connections.\n\nBounded memory search query:\nTranscript parity check: what are my favorite wings?\n\nConversation context:\nRecent conversation tail:\nuser: Quick memory check: favorite wings?\nuser: Final check: what are my favorite wings again?\nassistant: Lemon pepper. 🍋\n\nLatest user message:\nTranscript parity check: what are my favorite wings?"}],"timestamp":1783971976429}}
{"type":"message","id":"321b2cf2-f121-447c-944d-11706bac311a","parentId":"dfc7835d-0bd3-46a0-9993-243e8b34d2f3","timestamp":"2026-07-13T19:46:27.465Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"toolu_01XBmeEUymFqWkprAMaRZLun","name":"memory_search","arguments":{"query":"favorite wings"}}],"stopReason":"toolUse","api":"cli","provider":"claude-cli","model":"claude-opus-4-8","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"timestamp":1783971987464}}
{"type":"message","id":"4b72573e-fcc8-4d18-ace2-2371104ccba7","parentId":"321b2cf2-f121-447c-944d-11706bac311a","timestamp":"2026-07-13T19:46:27.897Z","message":{"role":"toolResult","toolCallId":"toolu_01XBmeEUymFqWkprAMaRZLun","toolName":"memory_search","content":[],"isError":false,"timestamp":1783971987896}}
{"type":"message","id":"73114aef-2ca5-4954-af62-95b5f8bcff37","parentId":"4b72573e-fcc8-4d18-ace2-2371104ccba7","timestamp":"2026-07-13T19:46:32.683Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"toolu_01RwHa7h5UodUnbYFTC2AsQk","name":"memory_get","arguments":{"path":"favorite-wings.md"}}],"stopReason":"toolUse","api":"cli","provider":"claude-cli","model":"claude-opus-4-8","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"timestamp":1783971992682}}
{"type":"message","id":"e01c5415-f452-41d4-ad26-662e9dd0942b","parentId":"73114aef-2ca5-4954-af62-95b5f8bcff37","timestamp":"2026-07-13T19:46:32.702Z","message":{"role":"toolResult","toolCallId":"toolu_01RwHa7h5UodUnbYFTC2AsQk","toolName":"memory_get","content":[{"type":"text","text":"{\n  \"path\": \"favorite-wings.md\",\n  \"text\": \"\",\n  \"disabled\": true,\n  \"error\": \"path required\"\n}"}],"isError":true,"timestamp":1783971992701}}
{"type":"message","id":"bdb84eb0-04c4-43f2-8510-66f0684ad020","parentId":"e01c5415-f452-41d4-ad26-662e9dd0942b","timestamp":"2026-07-13T19:46:35.392Z","message":{"role":"assistant","content":[{"type":"text","text":"User's favorite wings are lemon pepper."}],"stopReason":"stop","api":"cli","provider":"claude-cli","model":"claude-opus-4-8","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"timestamp":1783971995391}}

Round 3 (ClawSweeper review follow-up — successful default-config recall, deny-path proof, and a route-sensitive default budget):

  • Runtime-owner review round: fail-closed tool policy, pinned-profile resolution, lifecycle parity (round 9). Addressing @Patrick-Erichsen's review: (1) the dispatch gate now fails closed on tool policy — only a non-empty named allowlist (the only state the CLI bridge expresses faithfully) dispatches; deny-all [], wildcards, absent allowlists, and disableTools/modelRun keep the embedded passthrough, so no closed state widens and the wildcard-grant/merged-MCP-servers path is unreachable. (2) Eligibility forwards the pinned authProfileId into CLI runtime resolution, matching sibling routing callers. (3) Dispatched runs emit onExecutionStarted (with lifecycleGeneration) at the same post-admission boundary as the native path. Regression tests cover each closed-state refusal, the pin forwarding, and the lifecycle signal.
  • Dispatch eligibility is provider-owned (round 8 — the reviewer-recommended capability shape). The core provider allowlist is deleted. The anthropic plugin's claude-cli backend now declares CliBackendPlugin.subscriptionAuthDispatch: true (documented in docs/plugins/cli-backend-plugins.md), and core eligibility reads the registered backend descriptor: no descriptor or no declared capability → the passthrough is untouched. Backends that never declare it (gemini, codex, config-only backends without a plugin descriptor) are structurally excluded, replacing the hardcoded claude-cli set. This implements the "Adopt a generic backend capability (recommended)" option from the ClawSweeper maintainer-decision block; the remaining owner ask shrinks to approving the new SDK capability field.
  • Eligibility honors an explicitly pinned auth profile (round 7). Addressing the re-review P1: RunEmbeddedAgentParams.authProfileId now threads through the shared eligibility decision — a run pinned to an API-key profile keeps the passthrough (and the 15s default) even when the ordered selection would pick a subscription profile, and a pinned OAuth/token profile dispatches even when an API key sorts first; an unresolvable pinned id falls back to ordered selection like the passthrough. Profile-selection regression tests cover both explicit directions plus the fallback. Live proof of both routing directions on this head is in the lead block above (subscription → 45s dispatch status=ok; seeded claude-cli API-key store → 15s passthrough, no dispatch).
  • Timeout selection shares the full dispatch eligibility (round 6). Addressing the re-review's remaining P2: the eligibility gate (route resolution, registered backend, stored credential mode) moved to cli-backend-dispatch-eligibility.ts, consumed by both the dispatch itself and a new plugin-runtime seam api.runtime.agent.resolveCliBackendDispatchEligibility (documented in docs/plugins/sdk-runtime.md). Active-memory's 45s default now applies exactly when the run will dispatch through the CLI backend — API-key and missing-backend routes that keep the direct passthrough keep the plain 15s default. Regression tests: core eligibility (oauth resolves, API-key undefined, missing backend undefined, canonical-ref resolution) plus plugin-level budget tests for the eligible and ineligible paths.
  • Default recall budget on CLI-runtime routes. CLI-dispatched recalls measured 9–20s end-to-end, uncomfortably close to the plain 15s timeoutMs default. When the recall route resolves to the claude-cli runtime (direct provider ref or a canonical provider/model ref whose configured agentRuntime.id is claude-cli), the default budget is now 45s. This changes one default surface only for routes that could not work before this PR; an explicitly configured timeoutMs always wins, and no new config keys are added. Help text updated in openclaw.plugin.json.
  • Live success proof with default config. Fixture memories were seeded in the scratch profile's workspace and timeoutMs was removed from the plugin config. The run below is the full success chain on a subscription-only claude-cli route: new default applied, CLI-backend dispatch, real memory_search hits, grounded cited summary, status=ok.
  • The success proof caught a real bridge defect. The first fixed-deadline runs still classified no_relevant_memory with summaryChars=0 despite the model returning the correct facts: claude stream-json echoes MCP tool_result content as a bare content-block array, and the transcript mirror only unwrapped {content: [...]} shapes, so every mirrored tool result was empty and active-memory's usable-result gate discarded the summary. Fixed in cli-backend-dispatch-transcript.ts with a regression test pinning the live stream shape. (This also explains the empty "content":[] tool results visible in the earlier transcript excerpt above.)
  • Repeated on the exact current head. After rebasing onto current main, the dist was rebuilt from PR head 2b7b5bac7d and the same default-config run repeated: start timeoutMs=45000 → CLI-backend dispatch → two grounded memory_search hits → done status=ok elapsedMs=13661 summaryChars=109 ("User prefers SQLite with Kysely for prototypes; Copperfin demo project's staging dashboard runs on port 4173.").
  • Lane admission (round 4). Addressing the review finding at run.ts: the CLI-dispatch decision moved from the top of runEmbeddedAgent to inside the lane-admitted global-lane task, so dispatched runs now pass the same session/global lane queues, lifecycle-generation checks, harness admission, placement turn admission, and run-context claiming as native embedded runs. A new ordering test (run.cli-dispatch-lane.test.ts) pins that both lane admissions fully wrap dispatch resolution and execution. The live success run above executed on this shape.
  • Exact-head checks (round 5). check-dependencies also required the dispatch internals (resolveEmbeddedCliBackendDispatch, runEmbeddedAgentViaCliBackend) to stop being test-only exports — knip's production scan does not count test imports. They are module-private now and the gate tests exercise the public runEmbeddedAgentViaCliBackendIfEligible wrapper.
  • Exact-head checks (round 5, continued). The failing check-dependencies and checks-fast-loc-ratchet CI checks are repaired: the three unused type exports are no longer exported and the now-used buildAssistantMessageWithZeroUsage baseline entry is removed; the three grown legacy files were brought back under their ratchet baselines by moving the loopback grant-context builders into a new cli-runner/mcp-grant-context.ts module, deduplicating the run/prep stage-summary emitters into attempt-stage-timing.ts (they were verbatim copies), and simplifying an ad-hoc type guard with the existing isRecord helper. No behavior change; existing prepare/grant/lane tests cover the moved code.
  • Pre-existing check-dependencies failure on current main. The two remaining knip findings on this PR's merge ref (attempt-abort.ts: releaseEmbeddedAttemptSessionLockForAbort, attempt-prompt-skip.ts: PromptSubmissionSkipReason) reproduce identically on a pristine upstream/main checkout (4bff6b188e) with the exact CI knip invocation — they were introduced by recent main-side refactors and are unrelated to this branch. All findings for files this PR touches are resolved.
  • Real deny-path proof under bypassPermissions. While a recall run was live, the child's grant credentials (Bearer token + capture-key header, lifted from the child's process environment) were replayed from an independent MCP client: tools/list returned only ["memory_get","memory_search"], the allowed memory_search returned real indexed content, and the excluded sessions_list was rejected at the grant layer (isError:true, "Tool not available"). A token-only replay without the capture-key header was rejected 401 unauthorized.
After (round 3): default-config success run — status=ok with grounded summary
# Plugin config: {enabled, logging, agents:[main], persistTranscripts} — no timeoutMs override.
# Route: agents.defaults.models["anthropic/claude-opus-4-8"].agentRuntime.id = claude-cli.
# Workspace memory seeded: MEMORY.md + memory/2026-07-12.md (fixture facts).

[plugins] active-memory: agent=main session=agent:main:main activeProvider=claude-cli activeModel=claude-opus-4-8 start timeoutMs=45000 queryChars=111 searchQueryChars=111
[agents/embedded-cli-dispatch] dispatching embedded run through CLI backend: runId=active-memory-mrjvtysh-ad8b9df9 provider=claude-cli model=claude-opus-4-8
[plugins] active-memory: ... transcript=~/.openclaw-recall-probe2/plugins/active-memory/transcripts/agents/main/active-memory/active-memory-mrjvtysh-ad8b9df9.jsonl
[plugins] active-memory: ... done status=ok elapsedMs=8987 summaryChars=161

# Repeated on a dist rebuilt from the exact PR head 2b7b5bac7dacc7a5d315af5376321df6f4e31dee:
[plugins] active-memory: ... start timeoutMs=45000 queryChars=122 searchQueryChars=122
[agents/embedded-cli-dispatch] dispatching embedded run through CLI backend: runId=active-memory-mrjy32s4-93f88d65 provider=claude-cli model=claude-opus-4-8
[plugins] active-memory: ... done status=ok elapsedMs=13661 summaryChars=109
# assistant: User prefers SQLite with Kysely for prototypes; Copperfin demo project's staging dashboard runs on port 4173.

# Persisted transcript (toolResult content now mirrored):
toolCall  memory_search {"query":"Copperfin staging dashboard port"}
toolCall  memory_search {"query":"beta feedback form deadline"}
toolResult memory_search blocks=1 {"type":"text","text":"{ \"results\": [ { \"path\": \"MEMORY.md\", \"startLine\": 1, \"endLine\": 5, \"score\": 0.5565..., \"snippet\": \"...codename is 'Copperfin'; its staging dashboard runs on port 4173...\" ...
toolResult memory_search blocks=1 {"type":"text","text":"{ \"results\": [ { \"path\": \"memory/2026-07-12.md\", \"startLine\": 1, \"endLine\": 5, \"score\": 0.5683... ...
assistant: Copperfin staging dashboard runs on port 4173; beta feedback form deadline is July 25 (recorded 2026-07-12). Source: MEMORY.md#L1-L5, memory/2026-07-12.md#L1-L5.
After (round 3): live deny-path replay against the loopback grant
# Child argv captured during a live recall run (env stripped):
claude -p --output-format stream-json ... --permission-mode bypassPermissions --strict-mcp-config \
  --mcp-config <tmp>/mcp.json --tools  --allowedTools mcp__openclaw__memory_search,mcp__openclaw__memory_get \
  --model claude-opus-4-8 ...

# Independent MCP client replaying the child grant's credentials:
tools/list (2): ["memory_get","memory_search"]
tools/call memory_search (allowed): {"content":[{"type":"text","text":"{ \"results\": [ { \"path\": \"MEMORY.md\", ... port 4173 ..." ...
tools/call sessions_list (excluded): {"content":[{"type":"text","text":"Tool not available: sessions_list"}],"isError":true}

# Bearer token alone (no x-openclaw-cli-capture-key header): 401 {"error":"unauthorized"}

Validation:

  • Focused suites for the dispatch gate/adapter, transcript recorder (real-file record shapes incl. abort-flush dedup), loopback grant filtering + cache separation, and prepare-level grant/exclusive-bundle integration; pnpm check and pnpm build clean.
  • Two rounds of codex review --base upstream/main run locally; all seven findings across both rounds fixed in-branch with tests.
  • Round 3 (post-ClawSweeper): 181 active-memory + dispatch/recorder/grant tests plus the full src/agents/embedded-agent-runner suite (1909 tests) green after the deadline default and bare-array fixes; tsgo core and test-type lanes clean; branch rebased onto current main.
  • Local full-suite runs on macOS were load-flaky; every failure was triaged as pass-on-idle-rerun or pre-existing on clean upstream/main (packages/speech-core/src/tts.test.ts). CI should be treated as the authoritative full gate.
AI session log (curated: prompts + review rounds)

AI session log (curated)

This change was developed in a single interactive Claude Code (Claude Fable 5)
session, human-directed throughout. This is a curated log — author prompts
are quoted verbatim where they contain nothing private, and marked
[redacted: …] where they referenced the author's own infrastructure; agent
work is summarized. The raw transcript is withheld because it interleaves
private operator configuration; it can be shared with maintainers on request
after review.

1. Task briefing (author prompt, redacted paraphrase)

Investigate and fix active-memory recall failing on agentRuntime.id: "claude-cli" sessions with subscription-only auth. Verified symptoms:
main turns work through the CLI backend; recall goes through
runEmbeddedAgent, harness selection returns
cli_runtime_passthrough_openclaw, and the direct anthropic-messages call
is rejected ("Third-party apps now draw from your extra usage…").
[redacted: deployment details, version, log excerpts]
Hard constraints: local branch only, nothing pushed or filed; scope code
changes to claude-cli / the verified condition — a previous PR from this
team overclaimed that a bug affected all CLI backends including Gemini and
the maintainer had to correct it; deliver a verified-vs-assumed list.

2. Investigation (agent, with parallel research subagents)

Mapped both dispatch paths (embedded runner vs runCliAgent), confirmed no
CLI dispatch existed for embedded runs, and ran three parallel deep-dives:
CLI live-session concurrency (distinct session ids run as independent
processes), the selectable-backend tool surface (toolsAllow fails closed on
CLI runs; cliToolAvailability is the supported restriction), and credential
mode detection (claude-cli profiles are always subscription OAuth; mode is
resolvable from stored metadata without network).

3. Implementation and first review round

Implemented the opt-in cliBackendDispatch: "subscription-auth" dispatch,
then ran a multi-angle AI review (8 independent finder passes + verification)
which produced fixes: a cheap ordered-credential gate instead of credential
materialization on the per-turn path, native-path semantics for the bridged
tool results, wildcard-allowlist handling, and a shared MCP-prefix helper.

4. Author scope and framing direction (verbatim prompts)

"I don't think we should include logic for tripping the recall circuit
breaker on billing rejections. There could be quite a lot of debate around
that and I feel like that is better left for a separate PR."

"I want to challenge … how we are seemingly hedging by making this fix
opt-in." — (After discussion of the adapter's supported parameter subset
and unverified callers, the author kept the opt-in.)

"Anthropic has rejected subscription-based calls to the API from
third-party apps for a long time … This is a known issue and was not a
recent regression." — (All regression framing removed from code, commit,
and drafts.)

"If a user has extra usage enabled … it will actually work but it will
draw from the far more expensive extra usage bucket which they may not even
realize." — (Silent-cost impact added to problem framing.)

5. Codex review rounds (per CONTRIBUTING)

codex review --base upstream/main was run locally twice. Round 1 (4
findings): grant-level tool enforcement on the loopback MCP surface, ordered
auth-profile selection for mixed stores, session-scoped MCP cleanup instead
of the process-wide server close, and transcript persistence. The author
directed full transcript parity:

"It seems to me that if we are going to make active memory work with
claude-cli subscription usage, we should strive for full parity. Otherwise,
we are fixing one issue and introducing more that need to be addressed
later."

Round 2 (3 findings, after the parity work): exclusive loopback-only MCP
bundle for restricted runs, canonical anthropic/<model> refs resolving
through the runtime policy before the dispatch gate, and abort-time flushing
of the streamed assistant snapshot. All seven findings across both rounds
were verified against source before fixing, fixed with tests, and re-validated.

6. Validation

Focused unit/integration suites for every touched surface; pnpm check and
pnpm build clean; end-to-end verification on macOS from source with a
scratch profile and subscription-only auth (dispatch, grant-filtered MCP tool
calls, persisted transcript chain, 13.8–16.9s latency measurements). Local
full-suite runs were load-flaky; every failure was triaged as pass-on-idle or
pre-existing on clean upstream/main.

7. Author understanding

Scope, semantics, naming, and framing decisions were made by the human
author; the final diff, commit message, and this evidence set were reviewed
by the author before submission.


AI-assisted: developed with Claude Code (Claude Fable 5); reviewed and understood by the author; two local Codex review rounds applied pre-submission (findings and disposition in the session log above).

🤖 Generated with Claude Code

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: XL labels Jul 13, 2026
@clawsweeper clawsweeper Bot added 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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 13, 2026
@clawsweeper

clawsweeper Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 16, 2026, 3:25 AM ET / 07:25 UTC.

Summary
The PR adds provider-declared subscription-auth CLI dispatch for opted-in embedded runs, applies it to active-memory recall, hard-bounds loopback MCP tools, mirrors CLI-run transcripts, and conditionally raises the recall timeout.

PR surface: Source +876, Tests +1155, Docs +3. Total +2034 across 33 files.

Reproducibility: yes. The linked issue gives a concrete current-main subscription-only Claude CLI setup whose active-memory helper reaches the direct API path and deterministically receives the billing rejection, and the PR supplies before/after live logs from the same class of setup.

Review metrics: 2 noteworthy metrics.

  • Plugin/runtime contract surfaces: 2 added. The backend capability and runtime eligibility helper become compatibility-sensitive interfaces that future plugin and helper code may depend on.
  • Implicit timeout defaults: 1 changed conditionally. Eligible subscription-auth CLI recalls move from 15 seconds to 45 seconds while explicit operator values and API-key routes remain unchanged.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #106839
Summary: This PR is the direct candidate fix for the active-memory billing-rejection report; broader helper bypass and long-lived CLI-session billing errors remain distinct work.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🦞 diamond lobster
Proof: 🦞 diamond lobster
Patch quality: 🦞 diamond lobster
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Risk before merge

  • [P1] The new subscriptionAuthDispatch descriptor and plugin-runtime eligibility helper become compatibility-sensitive contracts for bundled and third-party plugin code.
  • [P1] A credential-selection regression could leave subscription users on the billing-broken direct path or incorrectly move API-key users onto the slower CLI path.
  • [P2] The conditional implicit timeout change can alter recall latency and watchdog behavior for eligible existing installations, so fresh and upgrade behavior must remain covered.
  • [P1] The exact-head required CI gate is not green; the failing large test shard must be diagnosed or rerun successfully before merge.

Maintainer options:

  1. Approve, refresh, and prove (recommended)
    Approve the provider-owned contract, refresh onto current main, resolve the failing exact-head shard, and retain the focused auth/tool/lifecycle/live proof before merge.
  2. Reshape with broader routing
    Pause this branch and integrate the fix into the canonical helper-routing direction if maintainers do not want the new plugin API.
  3. Accept the permanent surface
    Merge the new API and conditional timeout as an intentional compatibility commitment after owner sign-off and green exact-head gates.

Next step before merge

  • [P2] A runtime owner should approve, reject, or reshape the permanent plugin capability and eligibility-helper contract, then the failing exact-head CI shard must be cleared; no safe mechanical contributor repair is currently identified.

Maintainer decision needed

  • Question: Should CliBackendPlugin.subscriptionAuthDispatch and api.runtime.agent.resolveCliBackendDispatchEligibility become the permanent plugin/runtime contract for subscription-auth embedded helper dispatch?
  • Rationale: The observable bug and implementation are well supported, but accepting a new plugin descriptor plus runtime helper is a long-lived API and ownership choice that automated review cannot safely make.
  • Likely owner: steipete — The contributor and prior ClawSweeper review route the permanent runtime-boundary decision to this person.
  • Options:
    • Approve provider-owned seam (recommended): Accept the capability and shared eligibility helper, then merge after the exact-head CI failure is resolved and the branch is refreshed.
    • Fold into helper routing: Move this behavior into the broader canonical helper-dispatch architecture tracked by CLI-backed helper paths still bypass CLI dispatch on latest main #57326 before landing.
    • Narrow the public surface: Keep the active-memory fix but replace the general plugin/runtime API with a smaller owner-approved internal seam.

Security
Cleared: The current head addresses the prior tool-widening concern with fail-closed bridge admission, exclusive loopback MCP configuration, and server-side grant filtering; no concrete remaining security or supply-chain defect is established.

Review details

Best possible solution:

Keep the provider-owned dispatch capability fail-closed and opt-in, but land it only after the runtime owner accepts the permanent API shape, the branch is refreshed against current main, and exact-head checks confirm subscription dispatch, API-key passthrough, pinned-profile routing, bounded MCP tools, lifecycle parity, transcripts, abort handling, and conditional timeout behavior.

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

Yes. The linked issue gives a concrete current-main subscription-only Claude CLI setup whose active-memory helper reaches the direct API path and deterministically receives the billing rejection, and the PR supplies before/after live logs from the same class of setup.

Is this the best way to solve the issue?

Unclear only at the permanent API boundary. The provider-owned, opt-in, fail-closed bridge is the narrowest technically coherent fix shown and preserves API-key behavior, but maintainers must decide whether this general plugin/runtime contract is preferable to folding the work into the broader helper-routing architecture.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 7e1d93d36d76.

Label changes

Label justifications:

  • P1: Subscription-only Claude CLI users can lose active-memory recall on every eligible turn or unintentionally consume metered usage.
  • merge-risk: 🚨 compatibility: The PR adds plugin/runtime API surfaces and conditionally changes an existing implicit timeout default.
  • merge-risk: 🚨 auth-provider: Correct dispatch depends on provider-runtime resolution, pinned auth profiles, credential ordering, and API-key versus subscription mode.
  • merge-risk: 🚨 availability: Incorrect eligibility or timeout budgeting could leave recalls failing, timing out, or taking an unintended execution path.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Exact-head live output shows default-config subscription-only recall dispatching through Claude CLI and succeeding while a seeded API-key profile remains on direct passthrough; redacted transcript and restricted-tool evidence support the changed runtime path.
  • proof: sufficient: Contributor real behavior proof is sufficient. Exact-head live output shows default-config subscription-only recall dispatching through Claude CLI and succeeding while a seeded API-key profile remains on direct passthrough; redacted transcript and restricted-tool evidence support the changed runtime path.
Evidence reviewed

PR surface:

Source +876, Tests +1155, Docs +3. Total +2034 across 33 files.

View PR surface stats
Area Files Added Removed Net
Source 24 1087 211 +876
Tests 7 1155 0 +1155
Docs 2 3 0 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 33 2245 211 +2034

What I checked:

Likely related people:

  • steipete: The PR discussion explicitly requests this person's approval for the permanent embedded-to-CLI dispatch seam, and recent repository history shows broad ownership of agent runtime direction. (role: likely runtime decision owner; confidence: medium; commits: bb46b79; files: src/agents/embedded-agent-runner/cli-backend-dispatch.ts, src/plugins/cli-backend.types.ts, src/plugins/runtime/types-core.ts)
  • Patrick-Erichsen: Reviewed this bridge's tool-policy, pinned-auth, and lifecycle contracts and is assigned to the PR, making this person the strongest exact-surface reviewer. (role: recent runtime reviewer and adjacent contributor; confidence: high; files: src/agents/embedded-agent-runner/cli-backend-dispatch.ts, src/agents/embedded-agent-runner/cli-backend-dispatch-eligibility.ts, src/agents/embedded-agent-runner/run-orchestrator.ts)
  • obviyus: Authored the merged active-memory auth-health isolation fix, so has direct history with recall-specific billing/auth failure handling. (role: recent active-memory auth contributor; confidence: medium; commits: bdba4fa1bfe0; files: extensions/active-memory/recall-run.ts, extensions/active-memory/index.ts)
  • Takhoffman: Introduced the bundled Active Memory feature and remains closely connected to its recall behavior and defaults. (role: active-memory feature introducer; confidence: medium; files: extensions/active-memory/index.ts, extensions/active-memory/config.ts, extensions/active-memory/recall-run.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.
Review history (25 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-15T02:29:52.727Z sha 07245c1d30d4ea6c866810bb923674404357af68 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-15T03:42:11.291Z sha 07245c1d30d4ea6c866810bb923674404357af68 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-15T04:53:32.258Z sha 07245c1d30d4ea6c866810bb923674404357af68 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-15T06:03:39.328Z sha 80e68ef3cc8bceeb050acc1cb1c9c4265c5a81c7 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-15T07:15:33.010Z sha cddf828336e2ad387eb742df6aad2f70ecf88b95 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-15T08:29:17.863Z sha cddf828336e2ad387eb742df6aad2f70ecf88b95 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-15T09:45:17.701Z sha cddf828336e2ad387eb742df6aad2f70ecf88b95 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-16T06:51:07.735Z sha 92917da5ae88d4307f40bf36739f3d7f0abd56ee :: needs maintainer review before merge. :: none

@bill-starfoundry
bill-starfoundry force-pushed the fix/active-memory-claude-cli-recall branch 2 times, most recently from 869b614 to 2b7b5ba Compare July 14, 2026 00:10
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 14, 2026
@bill-starfoundry
bill-starfoundry force-pushed the fix/active-memory-claude-cli-recall branch from 2b7b5ba to 26e00b3 Compare July 14, 2026 02:21
@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. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 14, 2026
@bill-starfoundry
bill-starfoundry force-pushed the fix/active-memory-claude-cli-recall branch from 26e00b3 to a03c794 Compare July 14, 2026 02:58
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Jul 14, 2026
@bill-starfoundry
bill-starfoundry force-pushed the fix/active-memory-claude-cli-recall branch 2 times, most recently from a23f0cc to 3157bd8 Compare July 14, 2026 03:19
@clawsweeper clawsweeper Bot removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Jul 14, 2026
@bill-starfoundry
bill-starfoundry force-pushed the fix/active-memory-claude-cli-recall branch from 565b1fb to 8add8c3 Compare July 14, 2026 16:38
@openclaw-barnacle openclaw-barnacle Bot removed the scripts Repository scripts label Jul 14, 2026
@bill-starfoundry
bill-starfoundry force-pushed the fix/active-memory-claude-cli-recall branch from 8add8c3 to 361e7af Compare July 14, 2026 18:17
@bill-starfoundry

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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. labels Jul 15, 2026
@bill-starfoundry
bill-starfoundry force-pushed the fix/active-memory-claude-cli-recall branch from 07245c1 to 80e68ef Compare July 15, 2026 05:12
@bill-starfoundry
bill-starfoundry force-pushed the fix/active-memory-claude-cli-recall branch from 80e68ef to cddf828 Compare July 15, 2026 06:26
@bill-starfoundry

Copy link
Copy Markdown
Contributor Author

Requesting runtime-owner sign-off on the dispatch boundary — cc @steipete (ClawSweeper routed this decision to you as the likely runtime owner)

This PR fixes a P1 for subscription-only Claude CLI users: active-memory recall fails on every eligible turn with Anthropic's billing rejection (or silently draws metered extra usage) because the embedded helper calls the API directly instead of going through the CLI. Details and full evidence are in the PR body; ClawSweeper's current verdict is "no concrete contributor-facing blocker" with proof rated sufficient.

The one open item every review cycle has flagged is the permanent boundary question, and rather than wait I've implemented the option ClawSweeper recommended in each of its reviews — provider-owned capability:

  • CliBackendPlugin.subscriptionAuthDispatch?: boolean — a backend descriptor field, declared by the anthropic plugin for claude-cli (documented in docs/plugins/cli-backend-plugins.md).
  • Core has no provider allowlist: eligibility reads the registered backend descriptor, so backends that never declare the capability (gemini, codex, config-only backends) are structurally excluded.
  • Callers still opt in per run via cliBackendDispatch: "subscription-auth"; active-memory's timeout budgeting consumes the same eligibility decision through api.runtime.agent.resolveCliBackendDispatchEligibility.

The ask: approve this capability field as the seam (or tell me the shape you'd prefer — including folding into the broader helper-routing work in #57326 — and I'll rework; the dispatch/proof machinery is shape-neutral).

For the three merge-risk labels, the proof shortcuts:

  • auth-provider: eligibility honors pinned authProfileId and ordered profile selection, with live proof in both directions — subscription store → CLI dispatch (status=ok), seeded claude-cli API-key store → direct passthrough untouched.
  • availability: the 45s recall budget applies only when the run is actually eligible for CLI dispatch (measured runs 9–20s); API-key routes keep the plain 15s default. Both proven live on the current head.
  • compatibility: one default changed (timeoutMs 15s→45s, only on eligible routes, explicit config always wins), no new config keys; the SDK additions are the capability field and the runtime eligibility helper, both documented.

Branch is current with main and MERGEABLE; happy to do a final rebase at merge time.

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Jul 15, 2026
@Patrick-Erichsen Patrick-Erichsen self-assigned this Jul 15, 2026

@Patrick-Erichsen Patrick-Erichsen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes for three contract regressions. The Active Memory named-tool path is bounded and the focused tests pass, but the new generic embedded-dispatch bridge does not preserve runEmbeddedAgent tool, auth, and lifecycle semantics.

@bill-starfoundry
bill-starfoundry force-pushed the fix/active-memory-claude-cli-recall branch from cddf828 to 92917da Compare July 16, 2026 06:33
@bill-starfoundry

Copy link
Copy Markdown
Contributor Author

Thanks @Patrick-Erichsen — all three findings were correct, and all three are addressed on the current head (92917da5ae):

1. Tool-policy preservation → implemented as fail-closed. The dispatch gate now dispatches only when the embedded tool state is one the CLI bridge can express faithfully: a non-empty, wildcard-free named allowlist, translated to native: [] + the named loopback MCP tools, which also bounds the server-side grant and forces the loopback-exclusive MCP config in prepare. Every other state — deny-all [], wildcard or mixed-wildcard lists, absent allowlists, disableTools, modelRun — refuses dispatch and stays on the embedded passthrough, with a regression test per closed state.

Why fail-closed rather than a full translation layer: refusal preserves the caller's assumed semantics exactly — no closed state can silently widen, and the wildcard-grant / merged-user-MCP-servers path you identified is now unreachable, because a run without a bounded grant never reaches prepare through this bridge. A faithful translation for the remaining states (deny-all, flag-based restrictions, true wildcard) would be machinery for callers that don't exist yet; today's only opted-in caller (active-memory) always passes a named allowlist. When the broader helper-path adoption tracked in #57326 brings a caller that needs one of those states, translating it then — with that caller's tests — seems like the right time to build it. Happy to do the full translation now instead if you'd prefer.

2. authProfileId now threads into runtime resolution. Eligibility forwards the pinned profile into resolveCliRuntimeExecutionProvider, matching the sibling routing callers, so a canonical ref pinned to a CLI-runtime profile resolves and dispatches even without a configured agentRuntime. Test asserts the forwarding.

3. onExecutionStarted fires for dispatched runs. runCliAgent declares an onExecutionStarted callback but never invokes it (type-level only), so I took your alternative: the bridge invokes params.onExecutionStarted({ lifecycleGeneration }) once at the post-admission dispatch boundary — the same point the native path emits it. Test asserts single invocation with the lifecycle generation.

Validation: full dispatch/eligibility/lane/prepare/active-memory suites green, tsgo clean, and a fresh live recall proof on the exact head (start timeoutMs=45000 → CLI dispatch → done status=ok) is in the PR body's lead evidence block.

@bill-starfoundry
bill-starfoundry force-pushed the fix/active-memory-claude-cli-recall branch from 0b09889 to a58fbe0 Compare July 16, 2026 16:22
…subscription-only claude-cli auth

Embedded runs targeting a CLI runtime provider fall through to the openclaw
harness and call the provider API directly with the runtime's credentials
(cli_runtime_passthrough_openclaw). Anthropic routes direct anthropic-messages
calls on subscription OAuth tokens to metered extra-usage billing — this is
long-standing behavior, not a recent change. Without extra-usage balance,
every such run (e.g. active-memory recall) fails with a billing error; with
extra-usage enabled, the run silently draws paid metered usage instead of the
plan limits the CLI runtime was configured for. Only CLI-backed execution
runs on plan limits for those credentials.

Add an opt-in RunEmbeddedAgentParams.cliBackendDispatch: "subscription-auth"
that dispatches the run through runCliAgent as a one-shot turn when the
provider is claude-cli, a CLI backend is registered, and the ordered auth
profile selection for the passthrough resolves to a subscription (oauth/token)
credential or nothing rather than an API key; resolution stays on stored
credential metadata, with no credential materialization or refresh on the
per-turn path. The dispatch translates toolsAllow into the selectable-backend
surface (native: [], allowlisted loopback MCP tools; wildcard allowlists stay
MCP-only), runs with a fresh CLI process (no live-session reuse; session-
scoped bundle-MCP retirement on run end rather than the process-wide loopback
close), bridges CLI tool result events to onAgentToolResult with native-path
semantics (normalizeToolName + isToolResultError), and drops CLI session
bindings from the result.

The selectable-backend MCP list now also bounds the loopback MCP grant
server-side: the grant carries a per-run gateway tool allowlist enforced in
scoped tool resolution, so tools outside the run's allowlist can be neither
listed nor called even under CLI bypass permission modes where
--allowedTools is advisory.

active-memory recall opts in so recall works on claude-cli subscription-only
instances and stops drawing metered extra usage where it previously could.
Scoped to claude-cli; other CLI runtimes keep the passthrough until their
direct-API contract is verified.

The dispatch also mirrors the run into the run's session transcript through the session
accessor (user turn, tool call/result records as they stream, final assistant
snapshot at run end) so transcript consumers keep parity with embedded runs:
active-memory's persistTranscripts, timeout partial-text salvage, and the
live terminal-search watcher that polls the session file mid-run.

Post-review hardening: canonical anthropic/<model> refs whose configured
agentRuntime is claude-cli resolve through the runtime policy before the
dispatch gate (they previously stayed on the failing passthrough); restricted
dispatches serve an exclusive loopback-only MCP bundle so user/plugin MCP
servers stay outside the run's tool universe; and the transcript recorder
flushes the latest assistant snapshot the moment the run aborts, so timeout
salvage sees partial text even while the killed CLI child is still settling.

Recalls routed to the claude-cli runtime default to a 45s budget (measured
CLI-dispatched runs take 14-20s, over the plain 15s default); explicit
timeoutMs config always wins.

Transcript mirror keeps bare-array tool_result content (claude stream-json
echoes MCP results without a {content} wrapper); dropping it classified every
successful recall as no_relevant_memory.

CLI dispatch resolves inside session/global lane admission so dispatched
runs obey the same lifecycle, placement, and concurrency gates as native
embedded runs.

LOC-ratchet offsets move the loopback grant-context builders to
cli-runner/mcp-grant-context.ts and dedupe the run/prep stage-summary
emitters into attempt-stage-timing.ts; unused type exports dropped and the
now-used stream-message baseline entry removed.

The recall timeout default now consumes the runner's own dispatch
eligibility through a new plugin-runtime seam
(agent.resolveCliBackendDispatchEligibility): API-key and missing-backend
routes keep the passthrough and its plain 15s default.

Eligibility honors an explicitly pinned authProfileId (the credential the
run executes on) before ordered profile selection, in both directions.

Transcript mirror composes buildAssistantMessage + buildUsageWithNoCost
directly; main trimmed the zero-usage wrapper export (ab0ccc2) before
this branch's usage landed.

Dispatch eligibility is provider-owned: the anthropic plugin's claude-cli
backend declares CliBackendPlugin.subscriptionAuthDispatch and core reads
the registered descriptor instead of a core provider allowlist.

Dispatch fails closed on tool policy (only non-empty named allowlists are
expressible on the CLI surface; deny-all, wildcards, absent allowlists, and
disableTools/modelRun keep the passthrough), threads the pinned
authProfileId into CLI runtime resolution, and emits onExecutionStarted at
the admitted dispatch boundary.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: anthropic gateway Gateway runtime merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. 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. P1 High-priority user-facing bug, regression, or broken workflow. plugin: file-transfer proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: XL 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.

[BUG] Active-memory recall fails every turn with a billing rejection on subscription-only Claude CLI setups

2 participants