Repository navigation
feat(media-understanding): shared structured extraction for image-capable providers - #119773
Conversation
|
Codex review: blocked before merge. What this changesAdds shared, schema-validated image extraction for providers without their own extraction hook and documents incompatible instruction routes. Example: Logbook analyzes two screenshots with visionModel set to ollama/qwen2.5vl:7b.
Review scores
ProductKind: Feature · Worth it: Needs a maintainer decision · Fix scope: Complete Merge readiness⛔ Blocked before merge - 2 items remain Keep open: current main still lacks shared extraction, this PR contains meaningful proven work, and its same-author issue remains open; provider-contract approval and reported conflicts still block landing. Priority: P2 Decision needed
Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherPlugins submit images, supplemental text, instructions, and an optional schema through the media-understanding SDK; provider dispatch returns extracted text and validated JSON for the caller to consume. flowchart LR
A[Plugin images and instructions] --> B[Media extraction dispatch]
B --> C[Provider extraction hook]
B --> D[Shared image completion]
D --> E[Instruction route gate]
E --> F[Configured provider stream]
F --> G[JSON parsing and validation]
G --> H[Plugin result]
Technical reviewBest possible solution: Approve a bounded shared-extraction contract and integrate it at current main’s dispatch boundary while preserving native hooks and lifecycle-owned resources. Do we have a high-confidence way to reproduce the issue? Current-main source deterministically rejects providers without extractStructured, and the contributor supplies a matching base-versus-head Ollama gateway trace; no target code was executed during this review. Is this the best way to solve the issue? Reusing the shared completion runtime is coherent, but the proposed registry hydration must be adapted to main’s intentional dispatch-owned fallback design. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against bb957f57ca2d. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +209, Tests +344, Docs +17, Generated 0. Total +570 across 11 files. Added test files: 1. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (13 earlier review cycles; latest 8 shown)
Reviewed October 17, 2026, 3:58 PM ET / 19:58 UTC (Revision 14). |
After-fix Logbook multi-frame traceAcceptance criterion 3 asked for a redacted after-fix provider or Logbook Running it is what found the remaining bug, so there is a third commit on WhereA single-purpose OpenClaw gateway, isolated from any production install: its own Vision model is // dist/extensions/anthropic/media-understanding-provider.js
import { t as anthropicMediaUnderstandingProvider } from "../../media-understanding-provider-D0g85uKl.js";
export { anthropicMediaUnderstandingProvider };so everything below runs through the generic fallback this PR adds, not through a InputSix real screenshots, 1600×1000 JPEG, 1,060,792 bytes total, 30s apart, one Before{
"pendingFrames": 0,
"visionModel": "anthropic/claude-sonnet-5",
"visionModelSource": "config",
"lastBatch": {
"id": 1, "day": "2026-08-06", "status": "error",
"error": "prepared model runtime owner was not committed after replacement for /app"
}
}That error is the pre-third-commit state of this same batch, on an image built The runGateway log for that window — two real calls, one for structured extraction of One POST for the whole six-image batch. Relevant to the P1 below: on this OutputFive observations were written. The second call then revised those into a timeline card, which is what the {
"day": "2026-08-06",
"cards": [{
"title": "Reviewing PR fix for Logbook vision analysis fallback",
"summary": "Reviewed openclaw/openclaw PR #119773 fixing Logbook vision analysis when media provider lacks structured-extraction hook, then cross-checked related docs.",
"category": "review",
"appPrimary": "github.com",
"appSecondary": "openclaw.dev",
"distractions": [],
"keyframeId": 3
}],
"stats": { "trackedMs": 150000, "categories": [{"category":"review","ms":150000}] }
}The frames happen to be screenshots of this PR, so the extraction is Why there is a new commitThe first end-to-end run failed, and not on anything the first two commits
This was invisible until now because structured extraction was Codex-only and This is the part mocked tests could not have surfaced. Acceptance criteriaPlus What this does not coverThe P1 on |
P1 addressed — split-response routes excluded from the shared fallbackThree commits since the trace above. The P1 on What the guard does
So MiniMax is unchanged rather than newly broken — it fails the same way it did One deliberate deviation from the suggested remedyThe review asked to keep MiniMax explicitly unsupported. I scoped the guard to Logbook samples up to 16 frames per analysis call, so Logbook's MiniMax route — Where the check lives, and why not in the registryAt call time in Third commit: keeping the lazy chunk lazy
VerificationTargeted tests, 61 passing across
And on the built image, real provider, same six frames as the trace above: One POST for the whole batch, schema-validated against Scope noteThis round's real-provider verification is at the extraction entry point on the |
cab30aa to
e1de773
Compare
Security boundary addressed, and rebased onto current mainThree of the review's asks in one pass. The no-secrets instructionCorrect finding, and the reasoning holds beyond Logbook: a generic path standing The instruction now lives in the shared prompt builder, so every provider routed const NO_SECRETS_INSTRUCTION =
"Return only the requested extraction. Do not include secrets such as passwords, " +
"API keys, tokens, or credentials, even when they are visible in the input.";Wording deliberately mirrors the bundled Codex extractor's own developer Two regressions, both asserting on the prompt actually handed to the model
The second exists because RebasedThe branch was 511 commits behind Current state
49 targeted tests passing across On the earlier evidenceThe end-to-end Logbook trace stands as posted. The structured-extraction path is I have not re-run the full Logbook plugin path since, because my isolated |
e1de773 to
7538674
Compare
P1 addressed — the requested provider is now resolved by id before hydrationNew commits since the reviewed head
Branch rebased onto current The fix
A correction on my partMy earlier comments called the cold-gateway failure (" Deployed an image carrying these commits to the same isolated gateway, restarted it, and invoked analysis 2.5 minutes after boot — squarely inside the window that previously always failed. Boot log confirms the mixed-active topology from your finding (13 plugins up; Before-state, the standing failure from the previous image: "lastBatch": { "id": 2, "day": "2026-08-06", "status": "error",
"error": "Provider does not support structured extraction: anthropic" }
After: batch 2 CIThe four red checks on the previous head were mine, both causes now fixed: a 101-char line added by this PR failed On running the contributor gates myself: I stood up CI on my own infrastructure for The remaining open item is yours to callThe secret-handling boundary ("Decision needed"). Source facts, since the review noted the Codex contract source was unavailable for an equivalence verdict: the Codex route delivers its no-secrets wording as @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
7538674 to
1489712
Compare
1489712 to
93981dc
Compare
P1 addressed — the route gate now fails closed on unverified transportsHead The finding was right
What changedThe gate is now an allowlist of transports whose adapters in this repo turn
Anything else — an unknown That set covers every bundled provider, so the capability is gated rather than re-narrowed toward the Codex-only status quo. Plain Rebase note, and a CI finding worth recordingThe previous head passed CI, then failed on the next push with Still open, and I am not claiming otherwise
|
|
Status: the resolution half of this PR is superseded, and I need to correct something I wrote. #139231 now carries the provider-resolution fix, rewritten by @steipete at the shared catalog owner ( What remains unfixed either way: deferred providers being discoverable doesn't give them Plan. Once #139231 resolves one way or the other, I'll rescope this branch to the structured-extraction capability alone — dropping the resolver, the The correction. The body and my earlier comment claim the system-instruction allowlist "covers every bundled provider." That's false, and I should have caught it before posting. Ollama declares That points at the defect the P1 was circling. The gate reads a declared transport name at The rescoped PR will verify bytes rather than names: compose a core |
…#139231) Keep enabled audio and structured-extraction providers discoverable after another media plugin loads, and when shared models select only images. Merge eligible manifest owners at the shared catalog; leave execution selection with the runner and preserve active instances, policy filtering, and selected image loading. Resolve capability metadata only for normalized, deduplicated untagged provider entries. Pair synthetic audio fixtures with their matching runtime/metadata generation to avoid unrelated cold plugin imports. Verified the final integration with 69 focused tests, formatting/lint/core typecheck, a fresh independent review, a sealed build, 12 audio/extraction Gateway cases, and three paired full-inventory discovery cases. Exact-head CI 34060063771 succeeded (141 successful jobs, 16 skipped). Production delta: -20 lines. Related #119772 remains open; generic extraction fallback #119773 is outside scope. Thanks to @rodrigo-fonseca-oliveira for the original diagnosis and fix. Co-authored-by: Rodrigo Oliveira <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
734cca4 to
66174e3
Compare
66174e3 to
f3aeaf8
Compare
…able providers Root cause: only the bundled Codex plugin implements `extractStructured`, and registry hydration never bound one for any other image-capable provider, so `extractStructuredWithModel` failed with "Provider does not support structured extraction" for every non-Codex `visionModel` even though those providers already describe images through the shared model runtime. Owner: media-understanding registry hydration (`provider-registry.ts`) plus the shared image runtime (`image.ts`, `image-runtime.ts`), which already own the describeImage/describeImages defaults. Canonical fix: hydrate `extractStructured` next to those defaults from a new lazy `extractStructuredWithImageModel` export. `structured-extraction.ts` runs one completion through `completeImagesWithModel` with the extraction instructions (including a no-secrets rule) as the prompt, supplemental text as `userText` in the user message, and `promptDelivery: "system-required"`. That flag makes the shared runtime refuse, before any request, exactly the routes on which it would itself demote the prompt into user content (the GitHub Copilot, OpenRouter, and Alibaba Model Studio endpoint classes and both MiniMax VLM branches), because the output is persisted. A plugin stream that demoted `Context.systemPrompt` would break every agent turn on that provider, so that boundary stays with the plugin install, not this gate. The shared extractor defaults an empty `agentDir` to the configured default agent dir. The dispatcher still passes "" through unchanged, so a bespoke extractor such as Codex - which uses a non-empty agentDir as its thread cwd (bounded-turn.ts:125) - sees no change. On the shared path that key selects prepared-model owners and "" matches none on a long-lived gateway; Logbook never passes one. Regression: structured-extraction.test.ts. Replies are parsed strictly first; a fenced or prose-wrapped reply falls back to the first balanced JSON object or array (normalization-core's extractBalancedJsonPrefix) so model formatting drift does not fail a whole batch. A reply with no JSON in it is still a controlled error. Regression: structured-extraction.test.ts (fenced reply; no-JSON reply). Removed versus the previous head of this branch: - the by-id provider resolver in `buildMediaUnderstandingRegistry` and its runtime call: superseded on main by openclaw#139231 - the `SYSTEM_INSTRUCTION_TRANSPORTS` allowlist and `api` inspection: an unverifiable promise about plugin transports; the gate now records only the one decision the runtime owns - `imagePayloadTransform` and the opencode rewrite: opencode-only and separable Production LOC: +220/-11 (image.ts +55/-8, provider-registry.ts +9/-2, image-runtime.ts +8/-1, structured-extraction.ts +148); tests +347/-3; docs and the Logbook manifest help text shortened to the rule above. The config-doc baseline hash (docs/.generated/config-baseline.sha256) is regenerated for the help-text change, as its check instructs. Sibling coverage: describeImage/describeImages hydration is untouched and Codex keeps its own `extractStructured` hook (provider-registry.test.ts). The boundary test in image.test.ts asserts the exact `Context` handed to `complete`, and the refusal cases assert no stream registration, completion, or fetch. Proof gap: a live gateway run of Logbook against a non-Codex `visionModel` is still pending. Local proof: focused Vitest suites (media-understanding, image-tool provider loading, opencode), oxfmt, oxlint, `plugin-sdk:surface:check`, and the assertion-safety and coercion guards. Closes openclaw#119772 Co-Authored-By: Claude Fable 5.1 <[email protected]>
f3aeaf8 to
ce84581
Compare
…openclaw#139231) Keep enabled audio and structured-extraction providers discoverable after another media plugin loads, and when shared models select only images. Merge eligible manifest owners at the shared catalog; leave execution selection with the runner and preserve active instances, policy filtering, and selected image loading. Resolve capability metadata only for normalized, deduplicated untagged provider entries. Pair synthetic audio fixtures with their matching runtime/metadata generation to avoid unrelated cold plugin imports. Verified the final integration with 69 focused tests, formatting/lint/core typecheck, a fresh independent review, a sealed build, 12 audio/extraction Gateway cases, and three paired full-inventory discovery cases. Exact-head CI 34060063771 succeeded (141 successful jobs, 16 skipped). Production delta: -20 lines. Related openclaw#119772 remains open; generic extraction fallback openclaw#119773 is outside scope. Thanks to @rodrigo-fonseca-oliveira for the original diagnosis and fix. Co-authored-by: Rodrigo Oliveira <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
|
Complete diagnostics for the real-behavior proof in the body (head 1. Ollama proxy log — complete. Logging pass-through at 2. MiniMax refusal — listener log, complete. Provider 3. OpenRouter aimed at the local listener — complete, included for honesty. This is the attempt that showed the OpenRouter class is classified from 4. Gateway log — every batch transition, refusal, and plugin load, all cases in order5. RPC captures — logbook.status / logbook.timeline before and after each trigger6. Gateway configs used (tokens and keys redacted) |
|
Thanks for the PR. We're closing older pull requests that have gone stale against current The provider-resolution half of this work landed in #139231, and the remaining shared-extraction branch has had no commits since early September while waiting on the author. Please open a fresh PR against current main if you still want to pursue it. |
Closes #119772
Rescoped on 6 September. The previous head of this branch bundled two fixes. The provider-resolution half landed on
mainas #139231 (18733285112b), rewritten by @steipete at the shared catalog owner — I am not carrying a second version of it here. What remains is the other half, now filed as the feature it is rather than a bug fix, at +220/−11 production lines instead of +336/−27.What Problem This Solves
Logbook's
visionModelis effectively single-provider. On currentmain:extensions/codex/media-understanding-provider.tsis the onlyextractStructuredimplementation in the repository.describeImageanddescribeImagesfrom the shared image runtime for every image-capable provider (src/media-understanding/provider-registry.ts:44-45) but neverextractStructured.extractStructuredWithModelthrowsProvider does not support structured extraction: <id>(src/media-understanding/runtime.ts:372) for any non-Codex provider — after fix(media): keep deferred audio and extraction providers discoverable #139231 made that provider resolvable, it resolves and then throws.The
extractStructuredcontract shipped in May with Codex as its only implementer; the docs already say other providers "do not currently expose" it. This PR gives them one.Why This Change Was Made
Owner: the registry hydration and the shared image runtime that already own the
describeImage/describeImagesdefaults.Canonical fix. Hydration binds
extractStructured: provider.extractStructured ?? extractStructuredWithImageModelnext to those defaults; providers with their own hook (Codex) keep it.src/media-understanding/structured-extraction.tsruns one completion throughcompleteImagesWithModelwith the extraction instructions — including a no-secrets rule — as the prompt, supplemental text inputs asuserTextin the user message, and the reply parsed and schema-validated the same way the Codex extractor does it. It never routes through a provider's bespokedescribeImages. Replies are parsed strictly first; a fenced or prose-wrapped reply falls back to the first balanced JSON object or array via normalization-core'sextractBalancedJsonPrefix, so a model that ignores "no Markdown fences" does not fail the whole batch — Codex's own extractor does a rawJSON.parse, so the shared path is now the more tolerant of the two. A reply with no JSON in it is still a controlled error.The delivery gate, and what it deliberately is not. The output is persisted, so the instructions must reach the model as an instruction, not as user text beside a screenshot.
promptDelivery: "system-required"makes the runtime refuse — before any stream is registered or request sent — exactly the routes on which the runtime itself decides to demote the prompt into user content:shouldPlaceImagePromptInUserContent(the GitHub Copilot, OpenRouter, and Alibaba Model Studio endpoint classes) and both MiniMax VLM branches. Those get a named batch error.The previous head instead carried an allowlist of transport names. That was wrong in both directions — it refused Ollama on its
apistring even though Ollama's plugin stream sendsContext.systemPromptas arole: "system"message (extensions/ollama/src/stream.runtime.ts:740), and it admitted plugin streams on a declared name it could not verify. The gate now records only the one decision the runtime owns. The trust boundary for a plugin stream that demotedsystemPromptis the plugin install — such a plugin would break every agent turn on that provider — and I have left that as a question for maintainers rather than a promise in code.agentDirdefault. The shared extractor defaults an emptyagentDirto the configured default agent dir (structured-extraction.ts). The dispatcher is unchanged and still passes""through, so a bespoke extractor such as Codex — which uses a non-emptyagentDiras its threadcwdand loads project-local configuration from it (extensions/codex/src/app-server/bounded-turn.ts:125) — sees no change at all. On the shared path that value is the key for prepared-model owners, and""matches none of them on a long-lived gateway; Logbook never passes one. An earlier revision of this head put the default in the dispatcher, which would have changed Codex's working directory for existing installs — the review caught it, and it is fixed here.Removed versus the previous head, so reviewers who saw it know what went where: the by-id resolver (superseded by #139231); the transport allowlist and
KnownApiinspection (above);imagePayloadTransformand the opencode rewrite (opencode-only and separable — opencode is now hydrated with the shared hook without its reasoning-strip transform, which I am naming as a follow-up rather than carrying an SDK-adjacent field for one plugin).runtime.ts,runtime.test.ts, and all three opencode files are byte-identical tomain.Maintainer decision requested
Hydration now supplies
extractStructuredto every image-capable provider that lacks one — including providers whosedescribeImage/describeImagesare bespoke. That is a change to the provider-plugin capability contract, and I would rather state it than have it found.What it does and does not do: the shared extractor never calls a provider's describe hooks — it runs its own completion through
completeImagesWithModel, the same stream pathdescribeImagetakes when a provider does not override it. So a provider with bespoke description hooks that previously returned a visibleProvider does not support structured extractionerror now either extracts, or returns a visible provider error recorded on the batch. The delivery gate applies either way. On currentmain, the only bundled provider with bespoke hooks and no extractor of its own is opencode (its reasoning-strip transform is the named follow-up); Codex keeps its own.I looked for a narrower rule and there isn't a correct one expressible from hook shape: deepinfra assigns the shared functions by reference, openai wraps the shared function in a lazy-import closure, and anthropic/google/ollama leave the hooks undefined — presence or identity checks each exclude a provider that is plainly on the shared path. The alternatives are therefore (a) this behavior, documented as above, or (b) an explicit opt-in on the provider contract, which is SDK surface and a maintainer call. I am asking for (a) and will implement (b) if that is the decision.
User Impact
visionModelbecomes a real choice.docs/plugins/logbook.mdand thevisionModelhelp text state this rule and nothing broader.extractStructured, for audio/video-only providers, or for plaindescribeImage/describeImages— onlypromptDelivery: "system-required"consults the gate.Evidence
Regression tests fail on pre-fix code, captured by removing the relevant line and re-running:
provider-registry.test.ts:expected undefined to be [AsyncFunction invoke]on "hydrates structured extraction from the shared runtime".promptInUserContentrefusal removed →image.test.ts: the Copilot case reachescomplete()(Cannot read properties of undefined (reading 'stopReason')), the MiniMax case resolves"portal ok"instead of rejecting — i.e. the request went out.agentDirdefault removed →structured-extraction.test.ts:''received where the configured default agent dir was expected.structured-extraction.test.ts: a```json-wrapped reply fails withStructured extraction returned invalid JSON: anthropic.Boundary tests.
image.test.tsasserts the exactContexthanded tocomplete— system prompt equals the instruction, user message holds the caller text and image only — and that refused routes make no stream registration, nocomplete, and nofetch.structured-extraction.test.tscovers prompt assembly, text-input placement, JSON parsing, and schema validation.provider-registry.test.tscovers hydration identity and bespoke-hook preservation.Ran locally on this head:
node scripts/run-vitest.mjsoverimage,provider-registry,runtime,structured-extraction,image-tool.provider-loading, and both opencode suites — all green;oxfmt,oxlinton changed files;git diff --check;pnpm plugin-sdk:surface:check(no new SDK exports);check:assertion-safety;check:coercion-helpers;config:docs:checkafter regeneratingdocs/.generated/config-baseline.sha256for the help-text change, as that check's own message instructs; an independent$autoreviewpass at P2, which produced one finding — the fenced-JSON hard failure above — fixed in this head.Left to CI on purpose:
pnpm build, thetsgotypecheck lanes, and the full suite. My development machine cannot run those lanes, so this PR's CI on the exact head is the authority for them.Real-behavior proof (this head)
Isolated dev gateway on an x86-64 Linux box (Node v24.19.0), own
OPENCLAW_STATE_DIR, own port, never the operator's gateway. Logbook capture is macOS-only, so two synthetic JPEGs (a mock editor window; no real screen content) were seeded as frames — extraction, provider resolution, and the batch pipeline are all real; only the screenshot source is not.Head
ce8458199cf95c85703fa1c884943e3541a552e1; basedd3faf5f. Built dist self-reportsOpenClaw 2026.9.2 (ce84581). Vision model:qwen2.5vl:7bon local Ollama — a plugin stream with no bespokeextractStructured, which the previous head's allowlist would have refused on itsapistring.1. Accepted route completes (Ollama)
visionModel: ollama/qwen2.5vl:7blogbook.timelinereturns two cards built from the seeded frames:batchesrow:{id:1, status:"done", error:null, frame_count:2, model:"ollama/qwen2.5vl:7b"}. Gateway log:[plugins] loading ollama from <dist>/extensions/ollama/index.js.The prompt reaches the model in the system channel. A logging pass-through proxy in front of Ollama recorded the extraction request:
That is
STRUCTURED_EXTRACTION_INSTRUCTIONSverbatim asrole: "system", images in the user message — the propertypromptDelivery: "system-required"exists to protect.2. Refusal happens before extraction I/O
visionModel: minimax/MiniMax-VL-01, with that provider'sbaseUrlpointed at a local listener that logs every TCP connection.Listener log, complete file:
The single entry is a
curlself-test proving the listener records. Zero connections after the trigger — the route was refused before any request was built.Same refusal on the OpenRouter class against the real
https://openrouter.ai/api/v1with a dummy key, terminal in 5s (a key that reached OpenRouter would return 401 instead):3. Existing route (Codex) is untouched
Empty. Neither file is in the commit's changed set, and the dispatcher still passes
agentDir: params.agentDir ?? ""unchanged (src/media-understanding/runtime.ts:387), so the bespoke Codex extractor keeps receiving""as its thread cwd. No OpenAI/Codex credentials were available for a live Codex run; the diff is the proof offered.4. Before/after on the same batch
Base
dd3faf5fbuilt separately in its own checkout, same state dir and frames:Identical frames, identical batch id, only the checkout differs.
Complete diagnostics — the full proxy and listener logs, every gateway batch/refusal/plugin-load line, RPC captures, and redacted configs — are in this comment.
Limits of this proof, stated
github-copilotclass could not be exercised. That provider validates its token against GitHub before any inference (extensions/github-copilot/runtime-auth.ts:83-96) and derives its API base URL from that response, so without valid Copilot credentials the batch fails atCopilot authentication failed: HTTP 401before the gate runs. With valid credentials the classification is the same as OpenRouter's and the gate applies; I have no Copilot account to show it live. The OpenRouter and Model Studio branches are classified frombaseUrl(resolveProviderRequestCapabilities), so they cannot be aimed at a local listener — hence OpenRouter was proven against its real host and MiniMax carried the zero-I/O proof.reviseCards) runs on the agent default model, notvisionModel. With noagents.defaults.modelconfigured, extraction succeeds and the observations are written, but the batch is then markederrorby the synthesis step. Worth its own issue; I can file it.Production LOC: +220/−11 across four files (
image.ts+55/−8,provider-registry.ts+9/−2,image-runtime.ts+8/−1,structured-extraction.ts+148). Tests +347/−3. Docs and manifest +36/−19. The growth is the capability; about 35 lines ofstructured-extraction.tsmirror Codex's parse/validate and could be shared through the SDK later, which would need a surface-budget decision I am not making here.🤖 Generated with Claude Code