Repository navigation
feat(claude): add claude-bridge app-server harness extension - #86655
Closed
zeroaltitude wants to merge 270 commits into
Closed
zeroaltitude wants to merge 270 commits into
zeroaltitude wants to merge 270 commits into
Conversation
…ng) + P2 (replayMetadata side effects)
Tank's 2026-05-21 seventh-round static review surfaced two real
correctness issues.
P1 — concurrent turn cross-routing on the shared client. The shared
ClaudeAppServerClient dispatches server requests to per-turn handlers
by registration order, and the handlers didn't filter on threadId or
turnId. Two Claude turns running concurrently (e.g. one Discord +
one Slack at the same time) could route the second turn's
item/tool/call or item/commandExecution/requestApproval to the FIRST
turn's bridge — wrong sessionKey, channel, cwd, policy context.
Fix mirrors codex's isCurrentThreadTurnRequestParams /
isCurrentApprovalTurnRequestParams pattern: each runAttempt now holds a
mutable turnIdentity = { threadId?, turnId? } ref. Both
registerToolCallHandler and registerApprovalHandler take this ref and
filter incoming requests: if the request's params.threadId or
params.turnId is set and doesn't match the bound identity, return
undefined so the next handler in the chain tries. turnIdentity is
populated late — threadId in step 6 (after ensureThread), turnId in
step 7 (after turn/start) — because that's the natural data flow. A
request that arrives before the threadId is bound also returns
undefined to avoid claiming requests intended for other turns.
P2 — replayMetadata was hardcoded {hadPotentialSideEffects:false,
replaySafe:true}. If a messaging-tool send fired during the turn we
already pushed an external Discord/Slack message, so the turn is
emphatically NOT replay-safe. Now: when bridge.telemetry
.didSendViaMessagingTool is true, set replayMetadata to
{hadPotentialSideEffects:true, replaySafe:false}. Mirrors codex's
posture (and the user's clear intent — a duplicate Discord message on
replay would be a real failure mode).
Type-check (tsgo:extensions) clean. Remaining Tank-#7 findings
(transcript loss on non-cwd rotations, plugin npm dep declaration,
statePath ignored) coming in follow-up commits.
…tations) + P3 (statePath cleanup) Tank-#7 P2 — approvalPolicy and developerInstructions rotations were still calling thread/start and therefore still eating the SDK conversation transcript, despite the cwd-via-resume fix. Same fix pattern as cwd: send the divergent fields on thread/resume, the server's applyResumeOverrides already patches each one in-place into meta, and the SDK's next turn picks them up from the updated meta. No thread rotation, no transcript loss. The only remaining rotation reason is dynamicToolsFingerprint mismatch — the SDK's MCP server registration is set at thread/start and there's no resume-time refresh path for it. Rotation here still drops the SDK transcript; logged loudly ("rotating thread (transcript will reset)") so we'll see it on the wire. Follow-up needed if/when the catalog churn becomes visible in practice (file a beads issue then). Concretely: - approvalPolicy diverged → resume with {approvalPolicy} - developerInstructions hash diverged → resume with {developerInstructions} - cwd diverged (Tank-#6) → resume with {cwd} After any of these patches, we rewrite the binding sidecar so the new state is the baseline for next resume — no re-patching every turn. Tank-#7 P3 — `appServer.statePath` was exposed in the plugin schema + uiHints but was never read by the extension or the server. ThreadStore state goes to `<sessionFile>.claude-binding.json` regardless. Removed from schema rather than wire it, since binding-per-session-file is the right shape and a global state-path override has no current use case. If a deployment needs to relocate state, the cleaner path is to move the session files (which the binding sidecar follows by construction). Type-check (tsgo:extensions) clean.
… provenance taint chain engages for claude turns Live debugging revealed that NO provenance hooks were firing for claude turns — not just the outbound footer (which my prior agent_end fix targeted), but also the inbound taint header. Tabitha confirmed she had no provenance metadata in her context at all. Log grep showed 0 claude turns in provenance's turn-tracking output vs 210 codex turns. Root cause: codex fires three lifecycle hooks per turn (before_prompt_build, llm_input, agent_end). My claude extension was only firing llm_output + agent_end, so provenance's per-turn state never got seeded at turn-start. When my agent_end fired later, finalTaintBySession had nothing to flush because there was no turn-start state to begin with. Two wires added: - resolveAgentHarnessBeforePromptBuildResult right after building developerInstructions. Lets provenance inject inbound taint headers into the user prompt + modify developerInstructions. The diff between the returned prompt and userPromptText is captured as openclawPromptPrefix and prepended to the per-turn user message in buildInput. - runAgentHarnessLlmInputHook just before turn/start, with the proper PluginHookLlmInputEvent shape (runId/sessionId/provider/model/ systemPrompt/prompt/historyMessages/imagesCount). Also consolidated the previously-duplicated hookCtxForHarness object into a single harnessHookCtx built right after sandboxSessionKey + hookChannelFields are resolved, so all three lifecycle hooks (before_prompt_build, llm_input, llm_output, agent_end) share one context. Type-check (tsgo:extensions) clean. Diagnostic log at agent_end firing is still in place; can verify on the wire that provenance now logs [provenance:1594...] Turn Start lines for claude turns the same way it does for codex turns.
…ckaging metadata, remove diagnostic log, beef up rotation notes Tank-#8 static review against feat/claude-app-server-extension. P2 — strict request scoping. The turn-identity filter on tool-call and approval handlers was permissive: it only rejected when BOTH a bound id and an incoming id were present and didn't match. Tighter: require turnIdentity.threadId AND turnIdentity.turnId AND matching params threadId+turnId; everything else returns undefined so the next handler in the chain tries. P2 — packaging surface (partial). Root package.json files-exclusion list adds !dist/extensions/claude/** (parallel to codex's entry). New @openclaw/claude entry in scripts/lib/official-external-provider- catalog.json (kind:"harness", install block) so claude is discoverable as an official external plugin. DEFERRED: extensions/claude/package.json should also declare @openclaw/claude-app-server as a runtime dep, but the server is not yet published to the npm registry (it's npm-linked locally from ~/projects/openclaw-plugins/openclaw-claude/server). Adding the dep now would break `pnpm install` with ERR_PNPM_FETCH_404. To finish this half: (a) cut a real release of @openclaw/claude-app-server to npm, (b) re-add the runtime dep with the matching version range. Filed as PR-blocker note for the upstreaming PR. P3 — removed the TEMPORARY DIAGNOSTIC log at agent_end firing. It served its live-debug purpose (confirmed hooks fire and surfaced the missing before_prompt_build wire); no longer needed. P3 — beefed up the known-limitation comment on dynamic-tool catalog rotation. Cites the thread/fork or in-place mcpServers refresh mitigation that needs investigation if catalog churn becomes visible in practice. Should appear in the upstream PR description. tsgo:extensions clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…Slack vs Discord footer divergence diagnostic Tank-#7-followup live diagnostic. The slack-vs-discord provenance footer asymmetry can't be channel-side hook wiring (capabilities and dispatcher construction are structurally equivalent), so the divergence must be in WHICH channel deliveries reach deliverOutboundPayloads — that's the one entry point that calls applyMessageSendingHook (besides the dispatcher's auto-reply wrapper, which neither slack nor discord goes through). Adding an info-level log at deliverOutboundPayloads entry with channel/to/sessionKey/payloads-len so we can see, on the live gateway, whether discord deliveries actually pass through here for Tabitha's user-prompted replies (and slack ones don't). The answer narrows where the regression lives. To remove once the asymmetry is understood. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…the real callers land
Mirrors extensions/codex/doctor-contract-api.ts. Exports the same three contract surfaces openclaw doctor consumes via loadBundledChannelDoctorContractApi: - legacyConfigRules: empty (no retired claude config keys yet — claude harness landed 2026-05-20). - normalizeCompatibilityConfig: no-op until claude accumulates retired keys; pins the surface so future retirements have a registered home without restructuring. - sessionRouteStateOwners: claims session keys whose auth profile or runtime identifier belongs to the claude harness so openclaw doctor can attribute orphaned session state to the right extension. Test mirrors codex/doctor-contract-api.test.ts shape. Validation: tsgo:core clean (preexisting integration-only TS6133 unrelated), node scripts/run-vitest.mjs extensions/claude/doctor-contract-api.test.ts 3/3 passed, node scripts/run-oxlint.mjs on touched files clean.
…sume)
Mirrors extensions/codex/src/commands.ts. Registers a /claude command with
subcommand routing through src/command-handlers.ts:
- status shared-client liveness + command path + in-flight count +
last stderr (read via new peekSharedClaudeAppServerClient).
- version bridge package.json version + installed
@openclaw/claude-app-server version (or "not installed").
- threads reads the active session's .claude-binding.json sidecar via
readClaudeAppServerBinding and renders thread id, model, cwd,
approval policy, sandbox, dynamic tools fingerprint, updatedAt.
- resume writes the binding sidecar with a fresh threadId, preserving
other fields so the next turn issues thread/resume instead of
thread/start.
- help subcommand listing (default when no args).
Plumbing additions in src/app-server/client.ts:
- peekSharedClaudeAppServerClient(): snapshot of the current shared client
WITHOUT forcing spawn — keeps /claude status cheap when no turn has run.
- ClaudeAppServerClient.pendingRequestCount()
- ClaudeAppServerClient.commandDescription()
- ClaudeAppServerClient.lastErrorMessage() (reads tail of stderr buffer)
index.ts registers the command via api.registerCommand. Lazy import in
commands.ts keeps the registration import-light.
Validation: tsgo:core clean (no claude-related errors), 11/11 vitest in
extensions/claude/src/commands.test.ts (includes real-tmpdir binding
sidecar read/write roundtrip), oxlint on touched files clean.
Pre-existing curly/no-unnecessary-type-assertion lint debt in
extensions/claude/src/app-server/client.ts is unrelated to this change
and not touched here.
Mirrors extensions/codex/src/app-server/vision-tools.ts. Until now the
filter function was inlined in run-attempt.ts; extract it to its own
module for parity with codex and add a complementary modelSupportsVision
helper for the case where params.model.input isn't populated.
src/app-server/vision-tools.ts:
- filterToolsForVisionInputs<T>(tools, { modelHasVision, hasInboundImages }):
drops the `image` tool only when both flags are true. Otherwise leaves
the tool list untouched. Identical semantics to the codex helper.
- modelSupportsVision(modelId): name-based vision-capability check
against a conservative VISION_MODEL_PREFIXES list (claude-sonnet-*,
claude-opus-*, claude-3-5-*, claude-3-7-sonnet, claude-3-opus,
claude-haiku-4*). Unknown ids default to FALSE so we never accidentally
drop the image tool from a non-vision turn.
src/app-server/run-attempt.ts:
- Deleted the inline filterToolsForVisionInputs duplicate.
- Imports filterToolsForVisionInputs + modelSupportsVision from the new
module.
- modelHasVision now falls back to modelSupportsVision(params.modelId)
when params.model.input is not declared (manual model entries, legacy
configs). This restores correct vision filtering for catalog entries
that don't carry the modern modalities array.
src/app-server/vision-tools.test.ts: 18 tests covering both flag-gate
combinations for filterToolsForVisionInputs (kept when either flag is
false, dropped when both true, empty input passthrough, non-mutation)
and modelSupportsVision (8 vision-capable model id forms + 5 non-vision
or empty/undefined cases).
Validation: tsgo:core clean (no claude-related errors); vitest 18/18
new vision-tools tests; native-tools-coverage 1/1 still passes
(unchanged); oxlint on touched files clean.
The /claude slash command added in 85772a5 registers with ownership: "reserved" (parity with codex's /codex command), but the allowlist in src/plugins/command-registration.ts:35 only had "codex" listed. Runtime registration failed with: ERROR: reserved command ownership requires a reserved command name: claude Add "claude" right after "codex" so the bundled claude harness can claim reserved ownership of /claude the same way the bundled codex harness claims /codex. Validation: tsgo:core clean; pnpm build clean; gateway restart loads the claude plugin with no Diagnostics: ERROR; `pnpm openclaw plugins inspect claude --runtime` now shows "Commands: claude" under the loaded plugin.
… entry Added 2026-05-21 to trace slack-vs-discord footer asymmetry; that investigation is closed. The probe was logging channel/target/session metadata on every outbound send across all callers — shared hot-path noise that doesn't belong in production. Tank review (2026-05-22) flagged this as P2 cleanup before upstream PR.
Tank review (2026-05-22) reported 88+ oxlint errors blocking the upstream PR. Auto-fixed via 'oxlint --fix' for the 85 eslint(curly) issues (single-line if statements missing braces). Hand-fixed the 2 remaining typescript(no-base-to-string) errors in run-attempt.ts: - Line 1061: item.error could be anything; switched to typeof-string check with a 'tool failed' fallback rather than String() coercion. - Line 1389: errToMessage's last-resort String() coerced unknown-typed err to '[object Object]'; switched to JSON.stringify with an unknown-error fallback. Net: 93 → 0 errors. tsgo:core clean; 33/33 claude tests still pass.
…lease install gap Tank review (2026-05-22) flagged that publishing @openclaw/claude without a runtime dep on @openclaw/claude-app-server leaves users without the spawned binary. The proper fix is to publish @openclaw/claude-app-server to npm first and then declare the dep, which we'll do as a separate release step. Until then, document the gap explicitly so users can resolve the install manually. README covers: - The three-piece architecture (bridge + plugin manifest + external server). - Why src/app-server/ is named the same as codex's directory despite holding client-side code (mirrors the codex protocol name, not the role). - The pre-release install requirement: install @openclaw/claude-app-server from openclaw-plugins until 0.1.0 publishes to npm. Includes the diagnostic to detect a missing binary (`spawn openclaw-claude-app-server ENOENT`). - /claude slash command + subcommand inventory. - Server-side hot-path features (rate-limits, image-sanitizer, plugin-inventory) and bridge-side features (vision-tools, doctor-contract-api).
Tank report 2026-05-22 trio #1: config.ts upgrade. config.ts: replace manual type guards with zod schemas. The existing file already had the extract-from-run-attempt and manifest-alignment work; this commit adds the explicit strict-schema layer Tank flagged. - approvalPolicySchema (enum) - sandboxConfigSchema (union of short string + structured object) - positiveIntegerSchema for the two timeouts - appServerConfigSchema with .strict() so unknown keys fail closed - dynamicToolsConfigSchema with .strict() - pluginConfigSchema composing the two top-level sections resolveClaudeAppServerConfig now parses each section independently with safeParse so partial misconfiguration (e.g. one bad sandbox value) doesn't kill the defaults for unrelated sections. normalizeClaude* helpers also use safeParse with fallback-to-default. Top-of-file docblock now explicitly separates "BRIDGE enforces" from "ECHOED to server" concerns per Tank's request. Apparent split: - BRIDGE: command/args/env, turnTimeoutMs, turnIdleTimeoutMs, approval promotion, dynamicTools.exclude. - ECHOED: sandbox (server gets the value but the actual filesystem gate is openclaw's resolveSandboxContext earlier in the turn). openclaw.plugin.json: rewrite the appServer.approvalPolicy UI hint. Previously claimed "the plugin currently auto-declines unhandled approval requests" — stale since command/file approval routing was wired through openclaw's BeforeToolCall hook chain. New help describes the actual behavior (BeforeToolCall routing + automatic never→untrusted promotion when any policy registers). Validation: tsgo:core clean; 5/5 config tests still pass (3 resolver cases + 2 manifest alignment cases); oxlint clean.
… boundaries Tank report 2026-05-22 trio #2. Replaces the inline `response.thread?.id` cast in run-attempt.ts with boundary-time validation against zod schemas. Mirrors extensions/codex/src/app-server/protocol-validators.ts; we use zod rather than AJV because we own both sides of this protocol (server lives in openclaw-plugins/openclaw-claude/server, no codegen needed), and zod is already a project dep used by the freshly-zod-ified config.ts. Two helper shapes per response/notification: - assertX(value): throws ClaudeAppServerProtocolError (with parsed zod issues attached) on invalid input. Used at request-result boundaries where we can't proceed without a valid payload — thread/start, thread/resume, turn/start, and outbound turn/start params. - readX(value): returns parsed value or undefined. Used for notification/request inspection where the runtime can keep going by skipping a malformed event — item/tool/call dispatch, error notification enrichment, turn-completed notification. Schemas are intentionally lenient (`.passthrough()` on extra fields) so forward-compat server updates don't break the bridge. Wiring change in run-attempt.ts: replace the inline `response.thread?.id` typeof check with assertThreadStartResponse(), which throws ClaudeAppServerProtocolError with structured issues instead of a stringified JSON.stringify(threadId) error. protocol-validators.test.ts: 26 tests covering thread/start happy path + forward-compat passthrough + missing/empty thread.id, the thread/resume target alias, turn/start status enum validation and nullable error, outbound turn/start params, and the four read* helpers' undefined-on-bad-input semantics. Validation: tsgo:core clean; vitest 64/64 (entire claude suite, includes 26 new validator tests); oxlint clean.
Tank report 2026-05-22 trio #3 (final). Mirrors extensions/codex/src/app-server/thread-lifecycle.ts at smaller scope. Owns the rotate-vs-resume decision tree, the binding-compatibility checks, and the in-place resume patch envelope that lets the server absorb cwd/approvalPolicy/developerInstructions changes without losing the SDK transcript. Pulled out of run-attempt.ts so future fixes (thread/fork support, server-side mcpServers refresh on resume, additional rotation reasons) land in a dedicated module instead of inflating the turn runner. Public surface: - startOrResumeClaudeThread(args) → { threadId, outcome, rotationReason? } outcome: "resumed" (in-place patch path) | "started" (fresh thread/start) - isThreadNotFound(err): predicate exposed for callers that need to distinguish thread-not-found from transport errors. Run-attempt.ts changes: - Replaced inline ensureThread() (~150 LOC) with startOrResumeClaudeThread. - Removed inline isThreadNotFound + THREAD_NOT_FOUND_RE. - Kept fingerprintString (used by developerInstructionsFingerprint computation that callers still drive). - Comment references updated from ensureThread → thread-lifecycle. The extraction preserves all existing rotation/resume semantics: - Tank #6 cwd in-place patch. - Tank #7 approvalPolicy + developerInstructions in-place patches. - dynamic tool fingerprint mismatch is the only rotation reason. - thread-not-found on resume falls back to fresh start. - KNOWN LIMITATION docblock about mid-session catalog churn carried forward verbatim. Test coverage in thread-lifecycle.test.ts (11 tests, isolated from the turn runner): - Fresh start when no binding exists. - Binding sidecar written on fresh start with correct fingerprints. - Resume when fingerprint matches. - Rotation with the dynamic-tool-catalog reason on fingerprint shift. - thread-not-found error from thread/resume → fresh start recovery. - Other resume errors propagate (ECONNRESET stays an ECONNRESET). - In-place patch envelope sends cwd/approvalPolicy/developerInstructions when they diverge, persists patched values to the binding. - Patch envelope is empty when nothing diverged (one network round-trip per turn, no spurious patches). - isThreadNotFound: top-level message + nested data.message paths; unrelated errors return false. Validation: tsgo:core clean; vitest 75/75 (entire claude suite includes new 11 lifecycle tests + 64 from earlier); oxlint clean.
Tank report 2026-05-22 P0. The file existed on disk and the resolver- behavior + manifest-alignment tests pass against the recently-zod-ified config.ts, but it was never `git add`-ed to the branch — `git status` shows it as untracked. Add it now so CI sees the 5 cases: - applies runtime defaults for missing config - normalizes configured app-server + dynamic-tool options - rejects malformed optional values instead of casting them - keeps appServer parser keys aligned with manifest schema - keeps dynamicTools parser keys aligned with manifest schema No code change; just makes the existing coverage authoritative.
…daries Tank report 2026-05-22 P1. Stops casting server payloads at the four hot-path boundaries. Each boundary now goes through the assert/read helpers from protocol-validators.ts (added in 5591dcb), so malformed shapes fail closed at the protocol edge instead of silently producing undefined values that propagate downstream. run-attempt.ts wiring changes: 1. registerToolCallHandler() now reads item/tool/call params via readDynamicToolCallParams (returns undefined → handler chain tries the next consumer). The previous `as DynamicToolCallParams` cast plus one-off typeof check was permissive enough that a malformed params payload could let the bridge claim a request it can't fulfill, dead-ending the call. With the read helper, missing/empty callId/threadId/turnId/tool → undefined → handler skips, and the server's default-no-handler rejection takes over. 2. turn/start outbound params validated via assertTurnStartParams BEFORE the round-trip. Catches client-side bugs (empty threadId, unknown effort enum) before the server has to 400 us. 3. turn/start response validated via assertTurnStartResponse BEFORE reading startResp.turn.id. The previous cast could produce turnId=undefined which poisoned the turnIdentity filter that the tool-call/approval handlers use to scope requests to the current turn — under concurrency, that meant the wrong turn could claim another turn's tool calls. 4. turn/completed notifications validated via readTurnCompletedNotification (with readTurn as a fallback for variants where the runner already accepts `turn` directly). Returns undefined preserves the prior tolerant-of-partial-payload behavior downstream (`turn?.status === "failed"` still works as a guard). Tests added (4 new cases in protocol-validators.test.ts; 30/30 file total): - assertTurnStartResponse fails closed when turn.id is empty (would-be undefined turnId regression). - assertTurnStartResponse fails closed when turn is missing entirely. - readDynamicToolCallParams fails closed on missing tool name (handler chain skip). - readDynamicToolCallParams fails closed on missing turnId (cross-turn claim prevention). Validation: tsgo:core clean; vitest 79/79 (entire claude suite includes 4 new regression tests); oxlint clean across all 33 affected files.
Tank report 2026-05-22 P2: "If thread/fork is too much for this pass, keep current rotation behavior but make the limitation explicit in PR notes." thread-lifecycle.ts already carries the KNOWN LIMITATION docblock for in-tree maintainers; the README didn't surface it for upstream-PR readers and end users. Adds a "Known limitations" section to extensions/claude/README.md covering: 1. Tool-catalog change resets conversation transcript (the rotation reason that survives the in-place resume patches added in Tank #6/#7). Documents the root cause (SDK MCP registration is fixed at thread/start, not refreshable on resume) and the two mitigations under consideration: thread/fork support on the server, or refreshable MCP registration in the SDK. 2. @openclaw/claude-app-server pre-publish install path (re-surfaced from the install section for the limitations index). 3. Codex parity scope still pending — event projection, transcript mirroring, dynamic-tool middleware. Architecturally the scaffolding to land these (config.ts, protocol-validators.ts, thread-lifecycle.ts) is in place, just not yet exercised. Linked to beads openclaw-7w9. Docs-only; no code change.
Tank report 2026-05-22 P3.
Mirrors extensions/codex/src/app-server/event-projector.ts at smaller
scope. Pulled out of run-attempt.ts so the turn runner stays
orchestration-focused (promise + idle timer + unsubscribe lifecycle)
while the projector owns the notification shape readers, current-turn
filtering, accumulator mutation, native-tool AfterToolCall emission,
and assistant/reasoning stream emission.
Public surface:
- ClaudeAppServerEventProjector class with:
- matchesTurn(notif): turn-identity filter for idle-timer gating
- processNotification(notif): handles one notification, returns
terminal outcome ({ kind: "completed" } | { kind: "failed", error }
| null). Caller resolves/rejects.
- markSettled(): external settle from idle-timeout/abort path.
- finalize(): folds streamed text/reasoning deltas into the
accumulator. Called once after settle.
- Standalone helpers (also used by other modules later): isToolItem,
extractItemName, emitToolEvent, emitItemEvent, emitReasoningDeltaEvent.
run-attempt.ts changes:
- runTurn() now instantiates ClaudeAppServerEventProjector and lets it
process notifications via projector.processNotification(notif).
Caller-side resolve/reject still owns the promise wiring.
- Idle-timer reset is gated on projector.matchesTurn(notif) so stray
notifications for other turns on the shared client don't extend the
current turn's deadline.
- The old 175-LOC inline notification switch + helpers section is
deleted. The accumulator mutation, AfterToolCall hook fire,
contentItems/result branching, and turn/completed text recovery all
live in event-projector.ts now.
- runAgentHarnessAfterToolCallHook import dropped (only the projector
fires it now).
Tests (event-projector.test.ts, 32 new cases):
- isToolItem / extractItemName helpers cover all known item types and
the name vs tool precedence.
- matchesTurn: matches by params.turnId, matches by params.turn.id
(nested), rejects mismatched, rejects missing identity.
- Terminal outcomes: turn/completed → completed; turn/completed with
status=failed → failed; turn/error → failed; cross-turn notification
→ null; no double-settle after a terminal; external markSettled
short-circuits subsequent notifications.
- Accumulator: tool start records into toolMetas + toolCalls; tool
completion pairs onto prior start record; dynamic-tool contentItems
payload preserved; isError flag set on failed status; ignores items
missing the item field.
- finalize: folds text deltas into acc.assistantTexts; folds reasoning
deltas into acc.reasoning; picks up agentMessage text from
turn/completed when no deltas streamed; no-op when nothing seen.
run-attempt.ts net shrink: ~175 LOC moved out.
Full suite: 111/111 passing (was 79; +32 projector tests).
Tank report 2026-05-22 P4.
Mirrors extensions/codex/src/app-server/transcript-mirror.ts at smaller
scope. Claude's accumulator (from event-projector.ts) already carries
the assistant text + tool call/result pairs from a turn; this module
turns those into AgentMessage entries, fires
runAgentHarnessBeforeMessageWriteHook so plugins (provenance, vestige,
etc.) can intercept, and appends to the OpenClaw session transcript
with stable idempotency keys so replay/recovery doesn't duplicate
entries.
Idempotency keys: `claude/${threadId}/${turnId}/${role}/${index}`. The
threadId+turnId pair plus per-turn item index uniquely identifies an
entry across replay.
Lifecycle outcome integration: assistant message meta carries
`lifecycleOutcome: "started" | "resumed"` from
startOrResumeClaudeThread so replay tooling can distinguish a fresh
thread's first reply from a resumed thread's reply.
Smaller-than-codex scope:
- We emit one assistant message per turn (joined deltas + non-
streaming fallback already folded by event-projector.finalize()).
- We don't yet mirror reasoning as a separate message; the SDK's
session log preserves it on the server side. Possible follow-up.
- We don't read existing idempotency keys to dedupe — the idempotency
key shape is stable enough that the transcript writer can dedupe at
its own layer if it chooses to.
run-attempt.ts wiring: after a turn completes successfully (not
aborted), the mirror is called with the lifecycle outcome and
accumulator. Fire-and-forget at the catch layer — a mirror failure
shouldn't abort the turn result.
Tests (transcript-mirror.test.ts, 10 new cases): idempotency key shape
+ uniqueness across threads/turns/indices; empty-acc emits nothing;
single assistant message; lifecycleOutcome tagged on meta; tool
results emitted before assistant (deterministic ordering); stable
idempotency keys on every message; non-string tool results
stringified; errored tool results flagged in meta.
121/121 passing (was 111; +10 mirror tests). tsgo:core clean. oxlint
clean.
Tank report 2026-05-22 P5 (focused subset).
Adds the toolResultMaxChars cap codex enforces on dynamic-tool output.
Without this cap, a tool that returns a very large payload (file_fetch
on a huge file, vestige_search with wide query, etc.) silently inflates
the model's input window — Anthropic's API rejects payloads exceeding
its limits with an opaque 400 instead of a clean truncation signal.
Implementation:
- DEFAULT_CLAUDE_DYNAMIC_TOOL_RESULT_MAX_CHARS = 16_000 (matches codex's
DEFAULT_CODEX_DYNAMIC_TOOL_RESULT_MAX_CHARS).
- projectContentItems(result, maxChars) truncates inputText blocks (the
ones that count toward the model's input window). inputImage blocks
pass through unchanged.
- truncateForToolResult(text, maxChars) is the per-block helper:
appends a "[truncated to N chars]" suffix so the model can recognize
and react to the elision rather than guessing whether the result was
complete.
- Cap can be disabled per-call by passing maxChars=0 or negative
(returns input unchanged). Useful for tests + future per-tool
overrides.
Tests (dynamic-tools-truncation.test.ts, 7 cases): unchanged under
cap, unchanged at exact cap, truncates with suffix when over, preserves
opening text, disabled with maxChars<=0, the default constant matches
the documented value, oversized inputs land within 16k.
P5 deferred items (carried forward as PR notes for follow-up):
- createAgentToolResultMiddlewareRunner({ runtime: "claude" }) wiring.
Codex uses this for chained middleware on tool results. Requires a
bigger refactor of dynamic-tools.ts to thread the runner through the
result-projection path; better as a separate change once the
middleware registry supports "claude" as a runtime label.
- messagingToolSourceReplyPayloads telemetry. Codex tracks these for
source-reply suppression in delivery; claude doesn't yet have an
equivalent reply-source pipeline, so the telemetry would have no
consumer.
- namespace/deferLoading for dynamic tools. Codex supports searchable
vs direct tool loading; the claude SDK and our server side both
treat all dynamic tools as direct today.
128/128 passing (was 121; +7 truncation tests). tsgo:core clean.
oxlint clean.
…ency Tank report 2026-05-22 P6 — runtime dependency closure. Closes the runtime-dependency gap Tank flagged: the bridge now declares @zeroaltitude/[email protected] as a regular dependency in extensions/claude/package.json, so installing @openclaw/claude pulls the binary into node_modules/.bin/openclaw-claude-app-server automatically. No separate install step needed. The package was published to npm today (https://registry.npmjs.org/@zeroaltitude/claude-app-server) under the maintainer's personal scope as a fork-preview path. Once the upstream OpenClaw PR lands and maintainers republish under @openclaw/claude-app-server, this dependency declaration will switch to the @openclaw scope. Changes: - extensions/claude/package.json: declare the runtime dep. - pnpm-workspace.yaml: add @zeroaltitude/[email protected] to minimumReleaseAgeExclude so the 48h release-age policy doesn't block the install. The scope-pinned version means this exception expires naturally when we move to 0.2.0+. - pnpm-lock.yaml: refreshed via pnpm install. Resolves @zeroaltitude/claude-app-server and its transitive deps (@anthropic-ai/claude-agent-sdk, @modelcontextprotocol/sdk, ajv, zod). 16 new packages added; the binary symlinks to node_modules/.bin/openclaw-claude-app-server. - extensions/claude/README.md: replace "Pre-release status" language with the normal install story. The Architecture table now names @zeroaltitude/claude-app-server in the server row. Header docstring references the new package. Scope-migration note retained so the expected @openclaw rename is documented. Verification: - pnpm install: 16 added, lockfile clean. - ls node_modules/.bin/openclaw-claude-app-server: symlinks to @zeroaltitude/claude-app-server's bin/openclaw-claude-app-server.mjs. - tsgo:core: clean (no claude-related errors). - vitest extensions/claude: still passing. Tank task-list status now reads ✓ P0-P6 except P5 deferred-middleware items (carried as documented follow-ups in the README, not blocking).
…tool-result cap Address Tank's 2026-05-22 final-rereview findings. P1: transcript-mirror appended every message unconditionally and called emitSessionTranscriptUpdate with the wrong field name (transcriptPath instead of sessionFile, which the event normalizer silently treats as a no-op). Replays / crash recovery / mid-turn retries duplicated transcript entries. Port codex's readTranscriptIdempotencyKeys() flow so existing keys are skipped, emit with sessionFile, and only emit after at least one append. P2: dynamic-tool toolResultMaxChars was hardcoded to 16_000 and truncated per text block. A multi-block result could still exceed the configured cap. Add resolveClaudeDynamicToolResultMaxChars(ctx) that reads agents.list[].contextLimits.toolResultMaxChars (falling back to agents.defaults.contextLimits.toolResultMaxChars then 16_000) and budget aggregate text across all blocks in a single result, matching codex's convertToolContents algorithm. P3: README 'Known limitations' section called out event projection, transcript mirroring, and toolResultMaxChars as not implemented; all three now ARE implemented. Move them into 'Hot-path features' and narrow the remaining bullet to the three genuinely-deferred middleware items (runtime label, source-reply telemetry, namespace/deferLoading). Verification: targeted vitest 29/29 (4 new mirror integration tests covering replay dedupe + partial overlap; 8 new dynamic-tool tests covering aggregate budgeting + resolver precedence); full claude extension suite 140/140; tsgo clean on touched files.
…ude-bridge The 'claude-app-server' name implied an official Anthropic package, which it isn't. New name reflects ownership accurately: ZeroAltitude publishes it, OpenClaw owns the integration surface, Claude is the target system. Tank suggested this rename in the 2026-05-22 re-review. Bridge surface renames: - extensions/claude dep: @zeroaltitude/[email protected] -> @zeroaltitude/[email protected] - pnpm-workspace.yaml minimumReleaseAgeExclude entry updated - pnpm-lock.yaml refreshed (binary symlinks to node_modules/.bin/openclaw-claude-bridge) - DEFAULT_COMMAND in client.ts: openclaw-claude-app-server -> openclaw-claude-bridge - HARNESS_ID: claude-app-server -> claude-bridge (in harness.ts, openclaw.plugin.json onAgentHarnesses, doctor-contract-api runtimeIds, run-attempt agentHarnessId) - log/error prefixes: claude-app-server: ... -> claude-bridge: ... across client.ts, run-attempt.ts, thread-lifecycle.ts, event-projector.ts, protocol-validators.ts, thread-store.ts - locateServerPackageVersion in command-handlers.ts now resolves @zeroaltitude/openclaw-claude-bridge (was @openclaw/claude-app-server, which had never been published) - README + extension package description + JSDoc comments updated throughout to point at the new names - doctor-contract-api.test.ts expectation updated to claude-bridge Existing thread bindings under ~/.openclaw/state/claude-app-server/ are migrated to ~/.openclaw/state/claude-bridge/ automatically on the new server's first launch (see plugins-repo commit a4644ec). Verification: 140/140 claude tests green; tsgo clean on all touched files; bridge installs successfully and the binary resolves at node_modules/.bin/openclaw-claude-bridge.
Tank's 2026-05-22 task-list item #2 — closes the 'real-runtime confidence gate' gap that unit coverage alone cannot fill. 5 protocol-level tests that pass without an API key: - spawn + initialize handshake - server reports @zeroaltitude/openclaw-claude-bridge as its name - thread/start returns a real UUID, thread/unsubscribe completes - model/list returns the anthropic catalog (data shape: { data, nextCursor }) - transcript-mirror replay-safety with a real server-issued threadId 2 additional tests gated on ANTHROPIC_API_KEY: - dynamic-tool round-trip: project an openclaw_echo tool, drive a real turn that calls it, capture the server-initiated item/tool/call request, assert tool name matches - command approval routing: thread/start with on-request policy + sandbox read-only, prompt Bash usage, decline the resulting requestApproval and assert the bridge saw it Gating: OPENCLAW_LIVE_TEST=1 to run any of it; describe.skip if the flag is absent. The API-key block additionally requires ANTHROPIC_API_KEY to be set. Verification: 5/5 pass against the real binary (node_modules/.bin/openclaw-claude-bridge -> @zeroaltitude/[email protected]) in ~5s wall-clock; tsgo clean on the new file.
Tank's 2026-05-22 task-list items #3 + #4. #3: claude tool-result middleware port. Add 'claude' as a recognized AgentToolResultMiddlewareRuntime label so plugins can register tool-result middlewares scoped to the claude bridge the same way codex does. Wire createAgentToolResultMiddlewareRunner({ runtime: 'claude', ... }) into createClaudeDynamicToolBridge. The runner runs between raw tool.execute() and downstream telemetry/projection; errors in middleware fall back to the unmiddlewared result (no turn-fatal failure). #4: messaging source-reply telemetry. Add messagingToolSourceReplyPayloads to ClaudeDynamicToolTelemetry and port codex's extractInternalSourceReplyPayload helper. When a messaging tool returns a details.sourceReplySink === 'internal-ui' payload (the agent invoking the tool to surface a structured reply to a parent source message rather than send a fresh outbound), the payload lands in the new array and the regular messagingToolSent* fields are skipped for that call. Mirrors codex behavior so the downstream reply pipeline preserves parent-message attribution. Verification: 142/142 claude tests; tsgo clean on touched files (the 3 pre-existing baseline-drift errors in thread-lifecycle.test + commands.test remain unchanged).
Tank's 2026-05-22 task-list items #5 + #8. #5: namespace + deferred-loading plumbing. Mirror codex's createCodexDynamicToolSpec({ loading, directToolNames }) signature on the claude bridge: - DynamicToolSpec gains optional namespace + deferLoading - createClaudeDynamicToolBridge accepts loading ('searchable' | 'direct', default 'direct') and directToolNames - In searchable mode, non-direct specs ship with namespace='openclaw' + deferLoading=true; ALWAYS_DIRECT (sessions_yield) stays eagerly registered - Default 'direct' preserves current eager-loading behavior so callers don't see a behavior change The Anthropic claude-agent-sdk doesn't yet honor namespace / deferLoading at runtime (every MCP-registered tool loads eagerly). The flags are forwarded as protocol metadata so that either future SDK support OR a server-side search-meta-tool can honor them without a protocol bump. See 'True SDK surface differences' in the README. #8: parity-status doc. Replace the old 'Known limitations' section in extensions/claude/README.md with a three-bucket structure that separates implemented parity (everything from Tank's 1-7), planned bridge work (scope migration, server-side deferred-loading runtime), and true SDK surface differences (MCP-at-thread-start, no native deferred loading, no sourceReplyDeliveryMode plumbing). Lets future readers tell temporary gaps apart from permanent SDK constraints. 4 new tests covering loading-mode plumbing (19/19 truncation tests total). 146/146 claude tests; tsgo clean on touched files.
…rt keys
packages/plugin-sdk/package.json carried "./infra-runtime" and
"./security-runtime" twice each in "exports" — merge residue that main does
not have (main has one of each; only this feature branch has two).
Duplicate keys in a JSON object are not an error, the last one wins, so the
duplicates were inert. Removing them is textual only, and the commit proves
that rather than asserting it: the script refuses to touch a pair whose
blocks are not byte-identical, and it re-parses the file afterwards and
asserts the resolved `exports` map is unchanged (56 keys, equal before and
after). Removed the EARLIER block of each pair, which is the one JSON
resolution was already discarding.
Left inert they are still worth removing: a reader cannot tell which of two
identical-looking entries is live, and the next merge into this region has
two plausible ancestors to reconcile instead of one.
Validation:
node -e JSON.parse equivalence resolved exports identical, 56 keys
pnpm tsgo:core exit 0
git diff --check exit 0
pnpm plugin-sdk:surface:check exit 1 — INHERITED, not caused by this
change: the identical failure ("public exports 4344 > 4335") reproduces
on the clean feature branch with this commit stashed. Untouched here per
refs/openclaw.md (a red gate tracing outside our diff is not ours).
Beads: openclaw-bsj
`oneShot` tells the bridge to close its claude subprocess the instant the
turn ends (openclaw-claude/server/src/turn-runner.ts:576). It must mean
"no follow-up turn will ever arrive on this thread" — finality. The
predicate also included `Boolean(params.spawnedBy)`, which is provenance,
not finality, and the two are not the same thing.
`spawnedBy` is a persisted column on the session row
(src/config/sessions/session-accessor.sqlite-session-row.ts:75,106), so it
is set on EVERY turn of a spawned session for that session's whole life —
not merely its first. And spawned sessions are explicitly conversational:
`sessions_send` exists to deliver follow-up turns to them. Marking them
final therefore meant:
1. a multi-turn conversation with a spawned agent respawned its
subprocess on every single turn, paying a cold prompt cache each time;
2. a subagent could not background work and still have it alive at its
own next turn — which is exactly what "spawn a child to do the long
thing and reap its report later" requires. That pattern could not work
by construction.
Extracted the predicate as `isOneShotTurn()` so it is testable at all (it
was an inline const with no coverage) and pinned the behaviour with four
cases, including the two that matter: a spawned session on an ordinary
trigger is NOT one-shot, while a spawned HEARTBEAT turn still is — finality
wins where it genuinely applies.
TRADEOFF, taken deliberately: a true fire-and-forget child
(sessions_spawn mode:"run") now holds its subprocess until the idle sweep
rather than closing at once. That is the case the original comment was
optimising, and this is memory for no benefit there — but it is the safe
direction of error. Wrongly retaining costs bounded memory that
cli.ts:131-137's sweepIdle already exists to reclaim (30 min default, swept
every 5 min, tunable via appServer.queryThreadTimeoutMs). Wrongly closing
silently destroys live work with no error anywhere.
The precise fix is to gate on the spawn's own mode — "run" vs "session",
which SpawnMode (src/agents/spawn-plan.ts:28) already models and the
subagent registry already persists as spawn_mode. That signal does not
reach EmbeddedRunAttemptParams today; wiring it needs a child-session-patch
and session-row addition, so it is left as a documented follow-up rather
than guessed at in this commit.
Validation:
pnpm tsgo:core exit 0
pnpm tsgo:core:test exit 0
pnpm vitest run .../run-attempt.oneshot.test.ts 4 passed (new)
pnpm vitest run extensions/claude/src/app-server/ 294 passed, 1 failed
— the failure is the pre-existing win32 .cmd shim test, which fails
identically on the clean feature branch.
git diff --check exit 0
mutation check: re-adding `Boolean(params.spawnedBy)` fails the
"does NOT treat a spawned session as one-shot" case (1 failed | 3
passed), so the new coverage is non-vacuous.
pnpm oxlint exit 1 — INHERITED max-lines: run-attempt.ts already
reports 1520 lines against a 700 limit on the clean branch (1524
with this change). Not introduced here and not split in this commit,
per refs/openclaw.md.
Beads: openclaw-81h9
…pp-server-extension
…-server-extension
Picks up the attempt-teardown WARN wording fix, published as @zeroaltitude/[email protected] from openclaw-claude 3ecf8bd. The old WARN asserted "was silently killed" on a code path that cannot know whether anything was running, and which is the normal end of every one-shot turn — 42 of them in under two hours on a live gateway, essentially all routine. It now describes the teardown instead of claiming a loss. No exclude-list change needed, and that is worth recording because the obvious move here is wrong. pnpm-workspace.yaml's minimumReleaseAgeExclude already carries this package as a BARE NAME (line 18), which matches every version. The documented hazard — pnpm's matcher short-circuits on the first rule whose package NAME matches and only consults that rule's version list, so a second `name@version` entry silently blocks everything not listed in the first — applies to pinned entries. Adding `[email protected]` alongside the bare name would have created exactly that trap. Lockfile churn is scoped, not broad: 5 insertions / 5 deletions, all of them the bridge's specifier, version and resolution. Done with a filtered `pnpm --filter @openclaw/claude install` rather than a bare workspace install. The new integrity hash (sha512-/sduYxx0Py98o...) matches the published tarball, and the installed dist under node_modules does contain the reworded string — so this is verified end to end, not assumed from the version number. Validation: pnpm tsgo:core exit 0 pnpm vitest run extensions/claude/ 345 passed, 1 failed — the failure is the pre-existing win32 .cmd shim test, unrelated and failing identically before this change. git diff --check exit 0 Beads: openclaw-tb9g
…he thread A tool-catalog change used to force a new SDK session. That costs a full transcript copy, a fresh session id (so a cold prompt cache) and a respawned subprocess that strands whatever the previous turn backgrounded. And catalog changes are frequently POLICY, not configuration: the gateway's owner-only control-plane deny (src/gateway/tool-resolution.ts:243) removes 13 tools whenever senderIsOwner resolves false, which varies per turn. We were paying the full price repeatedly for a security input flipping. On drift we now call the bridge's thread/refresh_tools first, which applies the new surface to the RUNNING session via the SDK's Query.setMcpServers (bridge 0.7.5). Only if that reports no live attempt — or errors, e.g. an older bridge without the method — do we fall back to the existing fork path. New outcome "refreshed" distinguishes it. This is mitigation (b) from this file's own KNOWN LIMITATION note, which said it "probably requires SDK support — the SDK's MCP registration isn't refreshable today". That was true when written and is now stale: @anthropic-ai/claude-agent-sdk 0.3.220 exposes setMcpServers on the live Query (sdk.d.ts:2550). I've rewritten the note rather than deleted it, because that stale sentence is what sent me down two wrong paths first — a fingerprint-suppression attempt that turned out to be a policy bypass (reverted in 7399464) and a transient-thread diversion that merely made rotation cheaper. TWO WAYS THIS COULD SILENTLY DO NOTHING, both tested and mutation-checked: 1. Not re-recording the binding. After a successful refresh the binding must store the NEW dynamicToolsFingerprint against the SAME thread, or the next turn still sees drift and rotates anyway, wasting the refresh. Mutation: dropping the binding write fails the test (1 failed | 26 passed). 2. Treating a failed refresh as success. If the RPC throws and we proceed, the model keeps the OLD tool surface while we believe the new policy is applied — a policy bypass. tryRefreshToolsInPlace returns false on any error. Mutation: returning true from the catch fails the test (1 failed | 26 passed). Also asserts no refresh RPC is attempted when there is no drift, so this adds no per-turn chatter on the common path. Validation: pnpm tsgo:core exit 0 pnpm tsgo:core:test exit 0 pnpm vitest run .../thread-lifecycle.test.ts 27 passed (5 new) pnpm vitest run extensions/claude/ 345 passed, 1 failed — the failure is the pre-existing win32 .cmd shim test, unrelated. pnpm oxlint <touched files> exit 0 git diff --check exit 0 bridge pin 0.7.4 -> 0.7.5, scoped install, lockfile diff 5/5 lines verified the installed dist actually contains handlers/thread-refresh-tools.js Beads: openclaw-djc6
…p-server-extension
The shared harnessHookCtx built for before_prompt_build / llm_input /
llm_output / agent_end carried eight fields and no sender identity, so every
plugin downstream of those hooks saw an anonymous turn. `params.senderId` was
available all along — used at run-attempt.ts:794 in the same file — it just
was never threaded into the hook context.
Codex threads exactly these fields (extensions/codex/src/app-server/
run-attempt-tool-setup.ts:289-293, 316-317). This harness did not, and the
asymmetry is what made the failure harness-specific and easy to miss.
MEASURED CONSEQUENCE, which is why this is a security fix and not a tidy-up:
openclaw-provenance sources identity for taint classification and logged
"sender=unknown owner=unset" on 16996 of 16996 turns. Its configured
trustedSenderIds allowlist (7 ids) could therefore NEVER match, because
matching requires a senderId that never arrived. Every turn was classified
trusted via missingIdentityTrust:"trusted" — trust by fallback rather than by
verifying the sender. A security plugin failing open, invisibly, while its
config read as though senders were being verified.
Confirmed empirically before changing anything: a diagnostic probe added to
provenance (openclaw-plugins 0c51b2b) reported hookCtx.senderId=ABSENT on all
11 live sessions, including session=eddie provider=discord — a genuine user
turn where identity should have been present. That ruled out the alternative
explanation, since buildAgentHookContextIdentityFields
(src/plugins/hook-agent-context.ts:135-138) already strips identity for any
trigger !== "user", so heartbeat/cron/memory turns SHOULD be anonymous. Only
the user-turn case was wrong.
Scope kept deliberately narrow:
- Only senderId and chatId are passed; they are the identity fields
PluginHookAgentContext actually declares.
- senderName/senderUsername/senderE164/senderIsOwner are NOT passed — the
type does not carry them, and consumers needing ownership derive it from
senderId against their own owner list (provenance's computeSenderIsOwner
does precisely this).
- No filtering by trigger here: core already owns that policy at
hook-agent-context.ts:135-138, and duplicating it in the harness would put
the same rule in two places to drift apart.
- Keys are omitted rather than set to null/empty, so "not supplied" stays
distinguishable from "known absent".
Validation:
pnpm tsgo:core exit 0
pnpm vitest run .../run-attempt.oneshot.test.ts 7 passed (3 new)
pnpm oxlint exit 1 — INHERITED max-lines only (run-attempt.ts was already
~1520 lines against a 700 limit before this change); no other rule fires.
Verifiable end-to-end after deploy without further code: the provenance
IDENTITY_PROBE should switch from senderId=ABSENT to the real Discord id on a
user turn.
Beads: openclaw-ax8s
…-server-extension
Four conflicts. Two were unions, two needed reconstruction. runtime-preparation.ts — main narrowed model-auth to a type-only import and added resolvePreparedModelThinkingCompat (efc33f8, "preserve GPT-5.6 Max and Ultra through Codex"). This branch still calls getApiKeyForModelCore, so both imports are kept. Verified by usage counts taken with the conflict block excised. source-reply-payloads.ts — main extended the sourceReplyMirror type with transcriptOwner while this branch added a sibling preserveDraftPreview field (used across 4 files). Different additions to the same type, so union. channels/message/lifecycle.test.ts — three interleaved hunks from both sides adding tests to the same describe. Rather than edit markers across a 230-line tangle, test blocks were enumerated on both parents by indent-matched brace scanning: 3 tests unique to this branch (all preserveDraftPreview) and 4 unique to main. Took main's file whole and inserted this branch's 3 after the same anchor test the branch had used ("treats live preview fallback delivery as terminal state"), confirmed present on both sides. npm-install-security-scan.release.test.ts — this is the one worth reading. Two mistakes were caught by checking rather than by assuming: 1. Keeping all three of this branch's allowlist entries DUPLICATED two keys, because main already carries the codex http.ts and processes.ts entries elsewhere in the file. A duplicate-key scan caught it; only the @openclaw/claude entry is new. 2. The claude entry's count of 1 was then wrong — the suite reported two findings for src/app-server/client.ts. Inspecting the file shows the two hits are genuinely different: a doc-comment false positive at :86, and the REAL intentional spawn of the bridge binary at :245, whose command is routed through resolveWindowsSpawnProgram first. So the count is 2, and the comment was rewritten to describe both rather than only the false positive. Bumping the count without reading the file would have silently widened a security allowlist. Validation: pnpm tsgo passes; vitest on both touched suites gives 2 files / 128 tests passing.
`tryRefreshToolsInPlace` is the cheap alternative to rotating a thread when the
dynamic-tool catalog changes. Against a bridge older than 0.7.6 it is actively
harmful: the bridge forwarded our shape-only `{ type: "sdk", name: "openclaw" }`
entry straight to the SDK's `Query.setMcpServers`, which reads the absent
`instance` as "no longer desired" and disconnects the in-process MCP transport —
while still telling the CLI the server exists. Every subsequent
`mcp__openclaw__*` call in that session then failed with
`SDK MCP server not found: openclaw`, and because the bridge re-fingerprints the
attempt on refresh precisely so it is NOT respawned, the wedge persisted for the
attempt's whole life (~30 minutes of idleness before the sweeper cleared it).
Those bridges also never applied the new catalog, so a policy narrowing we
believed had taken effect silently hadn't.
The pre-fix bridge answers `{ refreshed: true }` in both cases. There is no
capability flag, no error, and nothing observable in the response that
distinguishes it from a fixed bridge — so openclaw cannot detect the failure and
must not ask an old bridge in the first place. Hence a version gate.
- version.ts: add MIN_BRIDGE_VERSION_FOR_TOOL_REFRESH = "0.7.6", deliberately
NOT a bump of MIN_CLAUDE_BRIDGE_VERSION. An older bridge is still perfectly
usable, it just gets routed down the rotation path; raising the hard floor
would refuse working installs outright, which this extension's version
contract reserves for changes it genuinely cannot tolerate.
- thread-lifecycle.ts: gate the refresh on the version reported at `initialize`
(`client.getServerInfo()?.version`) and rotate when below. The read sits
inside the existing try, because this function's contract is best-effort —
any surprise must degrade to rotation, never fail the turn. Also rewrites the
comment on the shape-only payload to explain why it is correct against a fixed
bridge and what it did to an old one, so nobody "helpfully" changes it back.
- package.json: bump the @zeroaltitude/openclaw-claude-bridge pin to 0.7.6.
The wire format is unchanged: a >= 0.7.6 bridge recognises the server name as
one it owns and splices its own live instance in.
Tests: thread-lifecycle.test.ts gains the gate cases (pre-fix bridge is not
asked even when it would answer `refreshed: true`; unknown version rotates;
above-gate refreshes) and its ad-hoc client stubs now supply `getServerInfo` via
a shared `asClient` helper so they exercise the real path. version.test.ts gains
the two contract invariants for the new constant: it may never outrun the
dependency pin (a gate the bundled binary can never satisfy is dead code) and
must sit at or above the hard floor.
Validation, from the topic worktree:
- pnpm tsgo:core clean
- pnpm tsgo:core:test clean
- pnpm config:schema:check [base-config-schema] ok
- pnpm vitest run extensions/claude/src/app-server/ 307 passed, 1 failed
- node scripts/run-oxlint.mjs <touched> clean
- ./node_modules/.bin/oxfmt --check <touched> clean
- git diff --check clean
Two gate results are PRE-EXISTING on the base commit, verified by re-running
each with these changes stashed and getting identical output:
- client.test.ts "materializes a win32 .cmd shim down to its real Node
entrypoint" fails (src/plugin-sdk/windows-spawn.ts) — unrelated to this change.
- pnpm plugin-sdk:surface:check fails its budget with byte-identical numbers
(public entrypoints 147 > 146, exports 4344 > 4335, callable 2586 > 2577).
NOTE FOR DEPLOY: the 0.7.6 pin is not on npm yet, so `pnpm install` on this
branch fails with ERR_PNPM_NO_MATCHING_VERSION until the bridge is published.
Validation above was run by installing at the published 0.7.5 and then restoring
the 0.7.6 pin; the lockfile is deliberately untouched and needs refreshing after
publish.
Beads: openclaw-d42b
Co-Authored-By: Claude Opus 5 <[email protected]>
…nsport-d42b # Conflicts: # src/agents/embedded-agent-runner/run/runtime-preparation.ts # src/agents/embedded-agent-runner/run/source-reply-payloads.ts # src/channels/message/lifecycle.test.ts # src/plugins/npm-install-security-scan.release.test.ts
@zeroaltitude/openclaw-claude-bridge 0.7.6 is now published (npm latest). The fix it carries is the one that matters at runtime: thread/refresh_tools no longer destroys the live SDK MCP transport, so mcp__openclaw__* calls keep dispatching after a dynamic-tool catalog change instead of failing with "SDK MCP server not found: openclaw" for the rest of the attempt's life. Both halves of that defect live in the bridge package, so this pin bump is sufficient to fix the deployed behaviour on its own. The core-side change (a MIN_BRIDGE_VERSION_FOR_TOOL_REFRESH gate that falls back to thread rotation when the bridge is older than 0.7.6) is separate hardening for old-bridge installs and rides on fix/refresh-tools-transport-d42b; it is not needed for this deploy. Lockfile refreshed against the published version rather than hand-edited: pnpm install resolves 2 references to 0.7.6 and none to 0.7.5, and the on-disk resolution reports 0.7.6. pnpm tsgo clean.
…' into feat/claude-app-server-extension
…ool bridge
The claude app-server bridge collected `didSendViaMessagingTool` and the
`messagingToolSent*` fields but never `didDeliverSourceReplyViaMessageTool`
and never the per-send `sourceReplyFinal` markers.
`hasCompletedSourceReplyDeliveryEvidence` reads exactly those two:
`resolveExplicitFinalSourceReplyDeliveryEvidence` finds no boolean markers,
returns undefined, and the legacy fallback then sees
`didDeliverSourceReplyViaMessageTool !== true` with an empty
`messagingToolSourceReplyPayloads`. So the predicate was structurally false
for every claude-bridge turn.
Measured consequence: across five agents over seven days
(2026-08-17 18:32 .. 2026-08-24 20:53) `message_tool_run_outcomes` holds
6397 rows and **zero** are `tool_delivered` — main 1972, tank 1911,
narcissus 1287, shiva 1001, tennyson 226, all `mute` — including turns whose
gateway log shows `Tools used: ..., message.send, message.send` in the source
Discord channel one second before the row was written. Every model in this
deployment resolves to `agentRuntime: { id: "claude-bridge" }`, so the whole
population runs through this seam. The same predicate gates fallback
settlement, followup delivery, and duplicate-recovery suppression, so the
blind spot also re-nags replies the agent already posted.
codex's equivalent bridge already does this
(extensions/codex/src/app-server/dynamic-tools.ts). This ports the core of
that attribution: the hook context carries `sourceReplyDeliveryMode`,
`collectTelemetry` runs `isDeliveredMessageToolOnlySourceReplyResult` over
each confirmed messaging send, sets the flag, and stamps `sourceReplyFinal`
(default true, false only for an explicit `final: false`) onto the target and
source-reply payload records. `allowExplicitSourceRoute` is deliberately left
unset so a send carrying an explicit `to`/`channel` route is not credited —
the bridge has no confirmed target record to route-check it against, and
failing closed costs only a `mute` while failing open would suppress genuine
undelivered-reply recovery.
Validation (worktree openclaw-fix-claude-bridge-source-reply-evidence, branch
cut from origin/feat/claude-app-server-extension @ bcd1472):
- new `dynamic-tools-source-reply.test.ts`: 5/5 fail on the pristine tip
("expected undefined to be true"), 5/5 pass with this change
- pnpm vitest run extensions/claude/src/app-server: 312 passed, 1 failed
- pnpm tsgo:core: clean (exit 0)
- pnpm config:schema:check: [base-config-schema] ok
- pnpm oxlint on the three touched files: clean
- git diff --check: clean
Inherited failures, byte-identical on the pristine branch tip and untouched
by this diff: the win32 `.cmd` shim case in `client.test.ts`; two
`tsgo:extensions` errors (`run-attempt.ts` "refreshed" thread state,
`thread-lifecycle.ts` `dynamicToolsCount`) from the merged
`fix/refresh-tools-transport-d42b`; `plugin-sdk:surface:check` drift
(2590 > 2581 callable exports) which the feature branch itself introduces;
`oxlint` max-lines on `run-attempt.ts` (1524 lines before this change).
Beads: bighat-s04p
Co-Authored-By: Claude Opus 5 <[email protected]>
…aw tools recordToolCompletion fires AfterToolCall for native tools only, because dynamic-tools.ts already fires it when the bridge invokes an AnyAgentTool. The guard read `if (!merged.isDynamic)`, with isDynamic set from `item.type === "dynamicToolCall"`. That misses the case the bridge actually creates. OpenClaw tools are served as an IN-PROCESS MCP SERVER, so the Claude CLI reports them as ordinary `mcpToolCall` items carrying the raw `mcp__openclaw__*` transport name. They slipped past the guard and fired AfterToolCall a second time — the exact double-count the guard's own comment says it exists to prevent. Field evidence, across 3 days of gateway journal: prefixed and unprefixed after_tool_call counts pair off exactly — heartbeat_respond 99/99, vestige_dream 9/9, sessions_spawn 8/8, vestige_search 3/3 — while before_tool_call is never prefixed (0 of 118). Six independent tools pairing exactly is one population counted twice, not two populations. Fixed at the producer via isBridgeOwnedToolCall(), which treats a dynamicToolCall OR anything in our loopback mcp__openclaw__ namespace as already-reported. The completion guard re-checks the item directly as well, since a completion whose start was never recorded falls back to a merged object carrying no isDynamic. DELIBERATELY NOT fixed downstream. Stripping the prefix in the shared after-tool-call consumer seam would have been one line and off main, but it turns "one prefixed + one unprefixed" into two byte-identical unprefixed events — real duplicate processing of messaging sends. That masks a producer defect with a consumer guard and makes behaviour strictly worse (bighat-djbs refutation). The prefix is detected locally rather than imported from cli-runner/tool-policy.ts: that module's constant is private, and widening the plugin-sdk public surface to share it would trip the surface-budget gate for a five-character string. Tests: 4 cases covering the regression, native tools staying native, a third-party MCP server's tool staying native (guards against over-broadening), and plain dynamicToolCall still recognised. MUTATION-VERIFIED AGAINST THE PRODUCTION CODE, not just the helper: restoring the original `item.type === "dynamicToolCall"` and the isDynamic-only guard fails the regression case (1 failed / 49 passed); reverting to the fix returns 50/50. This is the check I got wrong on openclaw#128832, where I mutated an extracted helper against its own unit tests and mistook a tautology for evidence. Gates: pnpm tsgo clean, oxlint clean, oxfmt clean, git diff --check clean, event-projector 50/50. Beads: bighat-bs2r
…hp8) runtimeBindings in commands-models.ts is a hardcoded list that carried only openai/codex and anthropic/claude-bridge. Providers absent from it never get a key in runtimeChoicesByProvider, so the model picker silently renders no runtime chooser for them. extensions/glm-bridge is a deliberate mirror of extensions/claude — it runs the same @zeroaltitude/openclaw-claude-bridge process against Z.ai's Anthropic-compatible endpoint, declares the glm-bridge harness id, and defaults modelProvider to zai. It was installed and enabled, but unreachable from the picker for want of a row here. Regression test asserts zai has a chooser at all and that both glm-bridge and openclaw are offered. Mutation-verified: deleting the production row fails the test (1 failed / 36 passed); restoring it gives 37/37. Co-Authored-By: Claude Opus 5 <[email protected]>
Cherry-pick of the same fix from `fix/zai-runtime-chooser` (cut off
`origin/main`), plus the two harness bindings that only exist on this
branch.
`extensions/glm-bridge` is an app-server agent harness
(`activation.onAgentHarnesses: ["glm-bridge"]`) that runs the same
@zeroaltitude/openclaw-claude-bridge process against Z.ai's
Anthropic-compatible endpoint, so it serves the `zai` model provider rather
than `anthropic` (its `appServer.modelProvider` defaults to `"zai"`). It had
no row in the runtime-binding array, so `runtimeChoicesByProvider.get("zai")`
returned `undefined` and `/models` offered no runtime chooser for zai at all
— the reported symptom.
The `anthropic`/`claude-bridge` row that this branch carried inline moves
into the shared binding list alongside it, so the guard test now covers all
four bundled harnesses rather than leaving two of them unchecked.
`glm-bridge` also gains an `AGENT_RUNTIME_LABELS` entry ("GLM app-server",
matching `claude-bridge`'s "Claude app-server") so the new chooser row does
not render a raw runtime id.
Validation (all from this worktree):
- pnpm oxlint <touched files> — exit 0
- pnpm tsgo:core — exit 0
- pnpm tsgo:core:test — exit 0
- pnpm vitest run src/agents/app-server-runtime-bindings.test.ts
src/auto-reply/reply/commands-models.app-server-runtime-choices.test.ts
src/auto-reply/reply/commands-models.test.ts — 3 files, 43 tests passed
(3 + 4 + 36; this branch runs the agents suite in one vitest project,
where origin/main runs it in two)
- pnpm tsx scripts/proof-app-server-runtime-chooser-bindings.ts:
[1] github-copilot runtime choices: ["openclaw","copilot"]
[1b] zai runtime choices: ["openclaw","glm-bridge"]
[2] openai runtime choices: ["codex","openclaw"]
[3] proof-standalone runtime choices: absent (as expected)
[4] bundled app-server harnesses
["claude-bridge","codex","copilot","glm-bridge"] all bound
All runtime assertions passed.
- git diff --check — exit 0
Beads: openclaw-ahp8
…o collapse-fc-0827 # Conflicts: # src/auto-reply/reply/commands-models.ts
# Conflicts: # pnpm-lock.yaml
… (openclaw-vgx7) resolveCompatibleAgentRuntimeForProvider hardcoded a single app-server binding — Codex — so every other bridge harness was rejected by the /model directive even when the picker had just offered it. Symptom: selecting GLM in the Discord model picker silently did nothing. The picker sends '/model zai/glm-5.3 --runtime glm-bridge'; the directive answered 'Runtime "glm-bridge" is not supported for zai', returned an error before touching the model, and the picker dispatches with suppressReplies so the explanation never reached the user. Typing '/model zai/glm-5.2' by hand worked, because a bare model directive carries no runtime to reject. anthropic + claude-bridge failed the same way. This resolver is the third copy of the provider->runtime mapping. It now reads the same app-server-runtime-bindings.ts list the runtime chooser uses, so a harness cannot be offerable and unusable at once. Codex keeps a separate branch for OpenClaw's virtual 'codex' provider namespace, which is not a model provider and so has no binding row. The regression test iterates the bindings list rather than naming providers, so it covers rows added downstream (anthropic/claude-bridge, zai/glm-bridge) without edits. Mutation-verified: restoring the hardcoded check fails it. Co-Authored-By: Claude Opus 5 <[email protected]> (cherry picked from commit 3f44c40)
…ed (openclaw-vj9a)
`pnpm install --frozen-lockfile` failed on this branch with
Broken lockfile: missing snapshot for
@anthropic-ai/[email protected](@anthropic-ai/[email protected]([email protected]))...
The `origin/main` merge (ec737f9) took main's side of `pnpm-lock.yaml`
in that region. Main had moved the workspace to `@anthropic-ai/[email protected]`,
so its lockfile carries no `@anthropic-ai/[email protected]` peer key at all — and
the merge dropped the `[email protected](...0.118.0...)` snapshot while
leaving the `@zeroaltitude/[email protected](...0.118.0...)`
snapshot that depends on it, plus the `extensions/claude` importer line
pointing at that stale peer-keyed version. Result: an unresolvable lockfile,
so neither this branch nor any integration containing it could install.
Repaired with a scoped re-resolution, not a broad reinstall:
pnpm --filter @openclaw/claude update \
@zeroaltitude/[email protected] --lockfile-only
The diff is confined to `@anthropic-ai/claude-agent-sdk` and the bridge: the
`extensions/claude` importer now resolves the bridge against
`@anthropic-ai/[email protected]`, and the `0.3.235` snapshot plus its eight
platform binary packages are restored. No other package changes.
Verified: `pnpm install --frozen-lockfile` green, `pnpm tsgo:core` clean,
`pnpm deps:pins:check` and `pnpm deps:patches:check` pass.
Co-Authored-By: Claude <[email protected]>
…st (openclaw-vj9a)
`pnpm tsgo:core:test` failed on this branch with
run.claude-bridge-auth-materialization.test.ts(15,3): error TS2305:
Module '"./run.overflow-compaction.harness.js"' has no exported member
'overflowBaseRunParams'.
The `origin/main` merge (ec737f9) picked up main's replacement of the
harness's `overflowBaseRunParams` constant with a `createOverflowRunParams(state)`
factory, which takes `workspaceDir` from a real `OpenClawTestState` temp dir
instead of a hardcoded `/tmp/workspace`. Main updated the two call sites it
owns (`run.before-agent-finalize.test-support.ts`,
`run.before-agent-reply-cron.test-support.ts`); it could not update this
branch-owned test, so the import was left dangling.
Adopts the same pattern here: create the test state in `beforeEach`, clean it
up in `afterEach`, and spread `createOverflowRunParams(state)` at the call
site. No change to what the test asserts.
Verified: `pnpm vitest run` on this file is 1 file / 1 test, passing;
`pnpm tsgo:core:test` no longer reports this file. The only remaining
`tsgo:core:test` errors are the six pre-existing `@types/ws` errors in
`src/gateway/server.channels-start-outcomes.test.ts`, whose blob is identical
to `origin/main` — red on main, inherited here.
Co-Authored-By: Claude <[email protected]>
…'s (openclaw-vj9a)
`pnpm plugin-sdk:surface:check` failed on this branch with
public entrypoints 148 > 147
public exports 4362 > 4353
public callable exports 2600 > 2591
The `origin/main` merge (ec737f9) took main's side of the budget block
wholesale. Both sides had independently raised the same three counters since
their merge base, so the merge kept main's numbers (147 / 4353 / 2591) and
silently dropped this branch's own increments — a clean merge with no conflict
marker, and no gate but this one would have caught it.
The overrun is exactly this branch's `@openclaw/plugin-sdk/host-env-security`
subpath: +1 entrypoint, and the 9 function symbols it re-exports
(`inspectHostExecEnvOverrides`, `isDangerousHostEnvOverrideVarName`,
`isDangerousHostEnvVarName`, `isDangerousHostInheritedEnvVarName`,
`normalizeEnvVarKey`, `normalizeHostOverrideEnvVarKey`, `sanitizeHostExecEnv`,
`sanitizeHostExecEnvWithDiagnostics`, `sanitizeSystemRunEnvOverrides`) for
+9 exports and +9 callables. The deltas match that inventory exactly, so this
re-applies the branch's increment on top of main's current numbers rather than
restoring the branch's stale absolute values.
Verified: `pnpm plugin-sdk:surface:check` exits 0; the three suites that pin
these numbers (`test/scripts/plugin-sdk-surface-report.test.ts`,
`test/package-scripts.test.ts`, `test/scripts/changed-lanes.test.ts`) are
3 files / 259 tests, all passing.
Co-Authored-By: Claude <[email protected]>
Contributor
Author
|
Retiring this draft from the core upstream queue. Current upstream has an official Anthropic Agent SDK runtime that owns the central authentication, approval, tool, warm-reuse, and session-resume behavior this 112-file parallel bridge originally supplied. Keeping a second core runtime would duplicate that ownership while carrying unresolved GLM packaging and external-plugin boundaries. Any still-useful GLM experiments should return as a focused, independently owned external plugin rather than merging this historical core branch. The exact branch tip remains recoverable as Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What Problem This Solves
This branch predates OpenClaw's official Anthropic Agent SDK runtime. It set out to give Claude users a first-class harness with native tool dispatch, approval and sandbox policy, rate-limit surfacing, persistent sessions, transcript projection, and operational commands. It also explored routing Z.ai GLM models through the same bridge protocol.
Why This Change Was Made
The implementation adds bundled Claude and GLM bridge extensions around
@zeroaltitude/openclaw-claude-bridge, following the Codex app-server shape: a managed stdio child, projected tool/model events, resumable bindings, shared-client lifecycle, and provider-specific configuration.User Impact
The bridge has supported real daily Claude workloads on the author's gateway. But current upstream main now includes the official Anthropic Agent SDK runtime, which owns the central auth, approval, tool, warm-reuse, and session-resume behavior this draft originally supplied.
Current recommendation: do not merge this 111-file parallel runtime into core. Keep the official Anthropic runtime canonical and, if the remaining bridge/GLM experiments are still useful, package them as independently owned external plugins after repairing their package boundaries.
Evidence
extensions/anthropic/agent-sdk.runtime.tsandextensions/anthropic/cli-backend.ts.extensions/claude, experimentalextensions/glm-bridge, and core SDK enablers), so resolving those defects would still leave a product decision about whether OpenClaw should support two bundled Claude runtimes.The historical production evidence demonstrates that the experiment worked; it does not justify duplicating the now-official core runtime.
Related design discussion: openclaw/openclaw#111222.
🤖 Generated with Claude Code
Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).