Skip to content

fix(cli): forward the selected agent id through media-understanding file calls - #145188

Closed
MertBasar0 wants to merge 1 commit into
openclaw:mainfrom
MertBasar0:fix/145119-infer-agent-id
Closed

MertBasar0 wants to merge 1 commit into
openclaw:mainfrom
MertBasar0:fix/145119-infer-agent-id

Conversation

@MertBasar0

@MertBasar0 MertBasar0 commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #145119

Rebased onto current main (59773963d18). #144931 landed in the meantime and made the same const agentId = … extraction in audio.ts and video.ts that the earlier revision carried, so this revision is smaller: four forwardings and two optional fields, with the restructuring now coming from main.

That PR is also independent confirmation of this defect. Its own evidence records: "The explicit-agent multi-agent image command still fails on both base and head because the separate forwarding defect remains." That remaining forwarding defect is what this PR repairs.

Rebased onto current main (9252b591). Revision 3 adds the real-CLI before/after proof and corrects the SDK-compatibility statement that ClawSweeper flagged.

What Problem This Solves

openclaw infer image describe --agent <valid-id> fails with AgentSelectionRequiredError on every invocation in a fleet with more than one agent and agents.ownership: "explicit". There is no script-reachable vision path through the CLI for those deployments, regardless of which agent is named.

runImageDescribe resolves the caller's --agent into an agent id and derives agentDir from it — and then drops the id. Only agentDir reached describePreparedImageWithModel and describeImageFile:

const agentId = resolveCapabilityProviderAgentId(cfg, params.agent, `infer ${params.capability}`);
const agentDir = resolveAgentDir(cfg, agentId);
...
await describeImageFile({ filePath, cfg, agentDir, prompt, timeoutMs }); // no agentId

runMediaUnderstandingFile forwards the owner conditionally (...(params.agentId ? { agentId: params.agentId } : {})), so with no id from the caller it always evaluated to {} and the owner was undefined for the rest of the pipeline. Downstream model selection then fell back to resolveAmbientOwnerAgentId → resolveSoleAgentId, which throws AgentSelectionRequiredError whenever more than one agent is configured and no explicit owner arrived.

On the "some paths recover the identity from agentDir" question raised in triage: resolveInputs in prepared-model-catalog.ts does reverse-map agentDir back to an id, but loadProviderScopedThinkingCatalog in the same file resolves the ambient owner unconditionally (params.agentId ?? resolveAmbientOwnerAgentId(params.config)), so the explicit-owner requirement still failed.

This is the layer below #124926 / #125143. That PR fixed CLI parsing so --agent is accepted and resolved; it never changed what the resolved owner is handed to.

Change

Forward the already-validated agentId alongside agentDir at the CLI call sites. No new policy and no change to selection rules.

The same defect existed at the two sibling call sites — infer audio transcribe and infer video describe both discarded the resolved id inline and passed only agentDir, and both funnel into the same runMediaUnderstandingFile owner. These four CLI call sites are the only callers of the file-oriented media-understanding runtime, so the fix covers the owner boundary completely rather than repairing one command and leaving the identical bug two functions over.

SDK compatibility

Correcting an inaccurate claim in the previous revision of this body: this does widen an SDK-visible surface, and that should be stated plainly. describeVideoFile and transcribeAudioFile are re-exported from src/plugin-sdk/media-understanding-runtime.ts, so the new agentId?: string fields on DescribeVideoFileParams and TranscribeAudioFileParams are reachable by plugin callers. (DescribeImageFileParams and DescribePreparedImageWithModelParams already carried the field.)

The addition is additive and backward compatible:

  • both fields are optional, so every existing call site still typechecks unchanged;
  • omitting agentId reproduces the previous behavior exactly — the spread in runMediaUnderstandingFile stays {} and agentDir resolution is untouched;
  • the existing runtime tests drive both helpers with agentDir alone and pass unchanged, which is the compatibility coverage for that path.

Why the existing tests missed it

The agent-routing tables in capability-cli.test.ts asserted mocks.resolveAgentDir.mock.calls[0][1] for image describe / describe-many — that only proves the directory was resolved from the right agent, never that an owner reached the runtime. Audio and video asserted agentDir on the downstream call, which is equally blind to the dropped id.

Both routing tables now assert the owner on the downstream runtime call (agentId), and a new case covers the explicit---model branch through describePreparedImageWithModel, which the original tests did not exercise for ownership at all.

Evidence

Real CLI behavior, before and after

Both runs use pnpm build output from this commit; the only difference is the four call sites in this PR. Environment: isolated HOME, three agents (alpha, beta, finance), agents.ownership: "explicit", no agents.defaults.systemAgent.agentId. The image-understanding provider is a local OpenAI-compatible listener on 127.0.0.1:8131, so the run completes end to end with no credentials and no network egress. Full config and stub are in the reproduction section below.

Before (four call sites reverted to main):

$ openclaw infer image describe --file photo.png --prompt describe --agent finance --json
[media-understanding] image: failed (0/1) reason=AgentSelectionRequiredError
{
  "ok": false,
  "error": {
    "type": "cli_error",
    "message": "AgentSelectionRequiredError: Multiple agents are configured, but this operation has no explicit owner. Select an agent explicitly; CLI callers can pass --agent <id>, channels can add a binding, and ambient services can set their agentId target."
  }
}

The explicit---model path fails the same way:

$ openclaw infer image describe --file photo.png --prompt describe --model stubvision/stub-vision-1 --agent finance --json
{
  "ok": false,
  "error": {
    "type": "cli_error",
    "message": "Multiple agents are configured, but this operation has no explicit owner. Select an agent explicitly; ..."
  }
}

The provider stub's request log stays empty across both: inference is never reached.

After (this PR):

$ openclaw infer image describe --file photo.png --prompt describe --agent finance --json
[model-fetch] start provider=stubvision api=openai-completions model=stub-vision-1 method=POST url=http://127.0.0.1:8131/v1/chat/completions policy=custom
[model-fetch] response provider=stubvision api=openai-completions model=stub-vision-1 status=200 elapsedMs=17 contentType=application/json
{
  "ok": true,
  "capability": "image.describe",
  "transport": "local",
  "provider": "stubvision",
  "model": "stub-vision-1",
  "attempts": [],
  "outputs": [
    {
      "path": ".../photo.png",
      "text": "STUB DESCRIPTION: a 1x1 test image.",
      "provider": "stubvision",
      "model": "stub-vision-1",
      "kind": "image.description"
    }
  ]
}

The explicit---model path and describe-many return the same ok: true envelope with the provider reached (status=200). The stub log records one POST /v1/chat/completions per successful run and none for the failing ones.

Reproduction

$HOME/.openclaw/openclaw.json:

{
  "agents": {
    "ownership": "explicit",
    "entries": { "alpha": {}, "beta": {}, "finance": {} },
    "defaults": { "imageModel": { "primary": "stubvision/stub-vision-1" } }
  },
  "models": {
    "mode": "merge",
    "providers": {
      "stubvision": {
        "baseUrl": "http://127.0.0.1:8131/v1",
        "apiKey": "stub-key-not-a-secret",
        "api": "openai-completions",
        "authHeader": true,
        "models": [{
          "id": "stub-vision-1", "name": "Stub Vision 1", "api": "openai-completions",
          "reasoning": false, "input": ["text", "image"],
          "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },
          "contextWindow": 128000, "maxTokens": 4096
        }]
      }
    }
  },
  "tools": {
    "media": {
      "models": [{ "provider": "stubvision", "model": "stub-vision-1", "capabilities": ["image"] }],
      "image": { "enabled": true, "preferredModel": "stubvision/stub-vision-1" }
    }
  }
}

The stub is an HTTP listener on 127.0.0.1:8131 that answers POST /v1/chat/completions with an ordinary OpenAI chat-completion body. No credentials are involved; apiKey above is a literal placeholder.

Unit coverage

Red — production change reverted, new assertions only:

FAIL routes --agent through image describe owner selection
FAIL routes --agent through image describe-many owner selection
FAIL routes --agent through image describe with explicit model owner selection
FAIL routes --agent through audio transcribe owner selection
FAIL routes --agent through video describe owner selection
FAIL inherits parent --agent through image describe owner selection
FAIL inherits parent --agent through image describe-many owner selection
FAIL inherits parent --agent through audio transcribe owner selection
FAIL inherits parent --agent through video describe owner selection

AssertionError: expected undefined to be 'beta'

Tests  9 failed | 11 passed | 229 skipped (249)

Green — with the fix:

node scripts/run-vitest.mjs run --config test/vitest/vitest.cli.config.ts src/cli/capability-cli.test.ts

Test Files  1 passed (1)
     Tests  249 passed (249)

Adjacent suite, unchanged: test/vitest/vitest.media-understanding.config.ts reports 5 failed | 595 passed | 1 skipped both with this change and on a clean main checkout on the same machine — identical failures (whisper/macOS path fixtures, an auto-audio subscription case, two agent-directory cases). Pre-existing and unrelated.

oxlint, oxfmt --check, and scripts/run-lint.mts are clean on all five touched files. Full-repo tsc --noEmit OOMs locally even at a 12 GB heap, so typechecking is left to CI — check-test-types-hosted-core-shard and check-lint-hosted-core-shard passed on the previous revision.

CI status on this revision

checks-node-compact-large-15 (src/agents/cli-runner/execute-plugin-native-bash.test.ts), which was red on the pre-rebase revision, now passes on current main.

Two checks remain red, and neither is from this change. Both live in subsystems with no import path to the CLI capability commands or the media-understanding runtime:

Check Failing test Measurement
checks-node-compact-large-14 src/agents/sessions/settings-storage.test.ts Reverting all five files to main reproduces the identical four failures, so it is red on main
checks-node-compact-large-10 src/proxy-capture/runtime.lifecycle.test.ts Passes locally on this branch, 25/25 — CI-only

openclaw/ci-gate is red only because it aggregates those two.

🤖 Generated with Claude Code

@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. cli CLI command changes size: S labels Sep 11, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 11, 2026
@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 13, 2026, 8:58 AM ET / 12:58 UTC (Revision 5).

ClawSweeper review

What this changes

The PR carries the selected agent through image description, audio transcription, and video description calls, adds two optional runtime parameters, and strengthens CLI routing tests.

Merge readiness

✅ Ready for maintainer review

This remains a useful, narrowly scoped fix: current main still drops the selected agent identity, and the related merged credential repairs explicitly leave that defect unresolved. No introduced correctness bug was found.

Priority: P2
Reviewed head: 8dfa5563e6307eac624ca9257cff7685ca5f1196

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused boundary repair with meaningful CLI proof, targeted regression coverage, and no actionable correctness findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The captured before/after traces exercise the production image CLI and media runtime against a real loopback HTTP listener: the previous ownership error becomes a provider request and successful description. This adequately demonstrates the shared forwarding repair; sibling audio/video coverage is supplemental regression coverage.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The captured before/after traces exercise the production image CLI and media runtime against a real loopback HTTP listener: the previous ownership error becomes a provider request and successful description. This adequately demonstrates the shared forwarding repair; sibling audio/video coverage is supplemental regression coverage.
Evidence reviewed 9 items Introduced patch and current-main necessity: The host-pinned introduction contains four argument forwardings and two optional parameter fields. Comparing the affected production files with fetched main shows those same changes are still absent there; unrelated endpoint drift was excluded from review.
Existing runtime owns identity propagation: runMediaUnderstandingFile already forwards agentId into runCapability, and both audio/video helpers spread their parameters into that owner. The explicit-model image path likewise already forwards agentId. No parallel selection implementation is added.
Source-backed failure mechanism: The provider-scoped catalog resolves an ambient owner when agentId is absent, even though another catalog helper can recover identity from agentDir. This supports the reported explicit multi-agent failure and explains why forwarding only the directory was insufficient.
Findings None None.
Security None None.

How this fits together

OpenClaw’s inference CLI accepts media files and an agent selection, then calls the shared media-understanding runtime. That runtime uses the selected agent’s model context and provider configuration to return descriptions or transcripts.

flowchart TD
  A[Media file and agent option] --> B[CLI validates agent selection]
  B --> C[Prepare selected account]
  C --> D[Media understanding runtime]
  D --> E[Model and provider selection]
  E --> F[Provider request]
  F --> G[Description or transcript]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +6, Tests +20. Total +26 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 4 6 0 +6
Tests 1 32 12 +20
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 38 12 +26

Review metrics

Metric Value Why it matters
SDK parameter change 2 optional agentId fields; 0 required parameters added The public helpers gain the existing owner context while directory-only callers remain source-compatible.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #145119
Summary: This PR is a candidate fix for the canonical image report and also repairs sibling audio/video forwarding.

Members:

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

Technical review

Best possible solution:

Preserve the existing agent-selection owner and carry its validated identity consistently through all file-based media calls.

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

Yes: the supplied CLI traces and current source identify a concrete multi-agent image-description failure when a valid --agent is dropped before catalog resolution; this review did not execute the CLI.

Is this the best way to solve the issue?

Yes: forwarding the already-validated identity repairs the existing boundary without adding another resolver, changing defaults, or requiring migration.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against df5c530888c4.

Labels

Label justifications:

  • P2: This repairs a bounded failure in media inference commands for explicit multi-agent configurations.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The captured before/after traces exercise the production image CLI and media runtime against a real loopback HTTP listener: the previous ownership error becomes a provider request and successful description. This adequately demonstrates the shared forwarding repair; sibling audio/video coverage is supplemental regression coverage.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured before/after traces exercise the production image CLI and media runtime against a real loopback HTTP listener: the previous ownership error becomes a provider request and successful description. This adequately demonstrates the shared forwarding repair; sibling audio/video coverage is supplemental regression coverage.

Evidence

What I checked:

  • Introduced patch and current-main necessity: The host-pinned introduction contains four argument forwardings and two optional parameter fields. Comparing the affected production files with fetched main shows those same changes are still absent there; unrelated endpoint drift was excluded from review. (src/cli/capability-cli/image.ts:183, 8dfa5563e630)
  • Existing runtime owns identity propagation: runMediaUnderstandingFile already forwards agentId into runCapability, and both audio/video helpers spread their parameters into that owner. The explicit-model image path likewise already forwards agentId. No parallel selection implementation is added. (src/media-understanding/runtime.ts:231, 8dfa5563e630)
  • Source-backed failure mechanism: The provider-scoped catalog resolves an ambient owner when agentId is absent, even though another catalog helper can recover identity from agentDir. This supports the reported explicit multi-agent failure and explains why forwarding only the directory was insufficient. (src/agents/prepared-model-catalog.ts:422, 8dfa5563e630)
  • Latest release still contains the omission: The v2026.9.4 image-description source resolves agentId but passes only agentDir to both description paths. Neither that release nor inspected current main contains this repair. (src/cli/capability-cli/image.ts, 3a9d69db306c)
  • Supplied production CLI proof: The complete captured PR body, sourceRevision 237ba6b3137202df35acfa693d05c5a7fc86ea727ba6db22d115cdf0327a8fe1, contains before/after CLI traces using three explicit-owner agents and a loopback HTTP provider. Before forwarding, image description fails before any request; afterward it records POST /v1/chat/completions, HTTP 200, and a successful description. Explicit-model and describe-many success are also reported. Audio/video forwarding is supported by source inspection and regression assertions rather than separate runtime traces.
  • SDK compatibility addressed: The PR body explicitly acknowledges the SDK-visible addition. Both new fields are optional; existing audio/video calls without agentId retain their previous runtime path. Existing runtime tests exercise directory-only callers. The change adds no export, required argument, persisted format, configuration option, or default. (src/media-understanding/runtime-types.ts:114, 8dfa5563e630)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • omarshahine: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-09-11T19:16:08.275Z sha 2d3873cb6132bdee9770b035d998f88df3510963 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-11T21:36:47.427Z sha 2d3873cb6132bdee9770b035d998f88df3510963 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-11T23:00:37.258Z sha 217ff8355d53c3264bc43311a97abfccb42e9b22 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T12:06:38.224Z sha 8dfa5563e6307eac624ca9257cff7685ca5f1196 :: needs maintainer review before merge. :: none

@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Sep 11, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 11, 2026
@MertBasar0
MertBasar0 force-pushed the fix/145119-infer-agent-id branch from 2d3873c to 217ff83 Compare September 11, 2026 22:52
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 11, 2026
@MertBasar0

Copy link
Copy Markdown
Contributor Author

CI note for reviewers: the one red shard is not from this PR.

checks-node-compact-large-15 fails in src/agents/cli-runner/execute-plugin-native-bash.test.ts — three cases under "native Bash execution policy", e.g. expected 'deny' to be 'allow' at line 50. That file has no import relationship to the CLI capability commands or the media-understanding runtime this PR touches.

Control experiment: this branch is main plus five files. Reverting all five to main makes the working tree identical to main, and the same three cases still fail locally:

FAIL src/agents/cli-runner/execute-plugin-native-bash.test.ts > native Bash execution policy > applies allowlist/on-miss to native Bash with configured PATH
FAIL ... > applies deny/on-miss to native Bash with configured PATH
FAIL ... > applies allowlist/off to native Bash with configured PATH
Test Files  1 failed (1)
     Tests  3 failed (3)

Identical with the five files restored, so the failure is independent of this change. openclaw/ci-gate is red only because it aggregates that shard.

The three shards that were red on the pre-rebase revision (checks-node-compact-small-17/49/51: doctor-update.ledger.test.ts, pr-main-refresh.test.ts, a gateway CPU benchmark) are all green after rebasing onto 9252b591.

Possible lead, unverified: the most recent main change under src/agents/cli-runner/ is #145164 ("await stored MCP policy within relay lifetime"), which landed shortly before this rebase and touches the native hook relay that these policy cases exercise. I have not bisected it and am not proposing a fix here, per the contributing guidance on failures already red on main. Happy to open a separate report if that is useful and it is not already tracked.

obviyus added a commit that referenced this pull request Sep 12, 2026
…ces (#144931)

Closes #144930.

## What Problem This Solves

Local image, embedding, audio, and video inference fail before sending a provider request when the selected agent saves its credential as a SecretRef. Local model inference already prepares the same credential.

## Why This Change Was Made

Extend the existing selected-agent account-secret preparation to every local media and embedding runner. Rename the model-only helper to match its shared scope. Keep the preparation behavior, account selection, auth precedence, and storage unchanged.

This carries forward @masatohoshino’s repair from #144931 and retains @Bruce-Yii’s shared preparation from #141569.

## User Impact

Local media and embedding commands can use the selected agent’s saved credential reference, as local model inference already does. Missing secrets still fail before provider traffic.

## Evidence

Real CLI proof uses an isolated state, an account created with `onboard --secret-input-mode ref`, a distinct saved account on another agent, and local protocol-compatible HTTP fixtures. No Gateway or external provider account is used.

| Command | Base `f96c900b1d424820c43a184d67694003583581bf` | Head `7ab685a8195d534e22ee52202a2752c178c424de` |
| --- | --- | --- |
| Embedding create | Exit 1; unmaterialized account reference; zero requests | Exit 0; expected embedding; selected credential at HTTP egress |
| Image generate | Exit 1; same error; zero requests | Exit 0; PNG written; selected credential at HTTP egress |
| Audio transcribe | Exit 1; same error; zero requests | Exit 0; expected transcript; selected credential at HTTP egress |
| Video generate | Exit 1; same error; zero requests | Exit 0; authenticated create/download; fixture bytes written |
| Image describe, sole agent | Exit 1; unmaterialized account reference; zero requests | Exit 0; selected credential at HTTP egress; returned image description |
| Video describe, sole agent | Exit 1; unmaterialized account reference; zero requests | Exit 0; selected credential at HTTP egress; returned video description |
| Local model run | Exit 0; selected credential | Exit 0; selected credential |
| Missing selected secret | Exit 1; zero requests | Exit 1; zero requests despite a usable other-agent account |

Image proof uses the existing local-image fixture opt-in on both base and head. Audio and video use the existing private-network request opt-in. The original small-audio and image network-policy setup failures are retained in private evidence.

An independent source-blind pass confirms successful outputs and selected credentials for all four capability families, zero traffic for each missing-secret case, and the current credential after rotation in a new CLI process. The other-agent account succeeds when selected directly.

Description proof retains the real media runtime and provider adapters. Both matched pairs use the same saved account database and command arguments; configs differ only by the local fixture port. Image returns “A synthetic blue square is visible.” Video sends a playable ten-frame input and returns “A synthetic blue square moves across the video.” Removing the selected secret makes each command fail before HTTP. A separate independent audit confirms the captured requests, exact selected credential classification, media payload bytes, outputs, and base/head state comparison.

Image description uses a documented sole-agent configuration to isolate secret preparation. The explicit-agent multi-agent image command still fails on both base and head because the separate forwarding defect remains. Those failures are retained. Initial video fixture configuration and endpoint-policy failures are also retained; the qualified proof uses an existing provider adapter that supports a local compatible endpoint. No runtime or auth function is mocked in these description proofs.

Limits: HTTP fixtures prove credential routing and output handling, not external provider generation quality. Generated-video output is a synthetic container; its playback is unconfirmed. The playable video above is the description input. The independent pass observed audio model-override behavior outside this credential repair; no forwarding change is included.

## Consumers

- `model.ts`: existing local model caller migrates to the shared helper name; Gateway model flow remains unchanged.
- `embedding.ts`: `infer embedding create` prepares selected-account secrets before creating its embedding provider.
- `image.ts`: generation/edit share one runner; describe/describe-many share another; both prepare before provider auth.
- `audio.ts`: transcription prepares before the media runtime.
- `video.ts`: generation and description prepare before their respective runtimes.
- `local-account-secrets.test.ts`: retains both existing preparation contract tests under the new name.
- `capability-cli.test.ts`: mock follows the shared helper rename; command wiring coverage is retained.
- `local-runners.account-secrets.test.ts`: six registered command routes reach real SQLite account and secrets owners before mocked provider execution.
- Search across source, plugins, UI, native apps and docs finds no other consumer of the retired helper/module names. Provider inventories do not perform inference; TTS and web use separate auth contracts.
- Pipeline: registered command → config-reference resolution → selected agent → existing account-secret preparation → provider auth → HTTP request and output. Fixture HTTP headers are the credential proof boundary.

## Invalidation

No new cached or persisted state. The existing preparation activates a process-local snapshot only when none exists. Each standalone CLI process rereads the selected account and current secret value. An already active snapshot remains owned by the secrets runtime. Existing tests retain source-config preservation and active-snapshot behavior. Missing-secret and other-agent controls verify owner isolation. Independent rotation checks pass for embedding, image, audio and video in fresh CLI processes.

## Contention

No new locks, queues or transactions held. Existing account loading and snapshot activation owners remain unchanged.

## Tests

Base `f96c900b1d424820c43a184d67694003583581bf` reproduces unmaterialized account-reference failures for embedding, image generation, image description, audio transcription, video generation and video description: exit 1, zero HTTP requests. The same account succeeds for local model inference.

The regression table fails all six cases on the base with `SECRET_SURFACE_UNAVAILABLE`. It invokes the registered image generate/describe, embedding create, audio transcribe and video generate/describe commands. No new production test seam is needed.

Targeted validation passes: 316 tests across nine files, including capability commands, the existing model account-secret sibling, lazy registration, and command-secret coverage. Targeted formatting, diff whitespace, file-size and assertion safety checks pass. Full typechecking runs in CI.

Test deletion ledger: no behavior deleted. The existing helper test file is renamed with its two cases preserved; the wiring suite mock follows that rename. No baseline or snapshot exceptions.

Upgrade behavior: no schema, config, protocol, persistence, updater, Doctor or plugin contract changes; existing credentials and auth precedence are retained.

Related open work: #145188 and #145171 repair agent-option forwarding in the same owner files. Their defect is separate; this patch does not duplicate their change. Recheck overlap on the landing merge tree.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 12, 2026
…ces (openclaw#144931)

Closes openclaw#144930.

## What Problem This Solves

Local image, embedding, audio, and video inference fail before sending a provider request when the selected agent saves its credential as a SecretRef. Local model inference already prepares the same credential.

## Why This Change Was Made

Extend the existing selected-agent account-secret preparation to every local media and embedding runner. Rename the model-only helper to match its shared scope. Keep the preparation behavior, account selection, auth precedence, and storage unchanged.

This carries forward @masatohoshino’s repair from openclaw#144931 and retains @Bruce-Yii’s shared preparation from openclaw#141569.

## User Impact

Local media and embedding commands can use the selected agent’s saved credential reference, as local model inference already does. Missing secrets still fail before provider traffic.

## Evidence

Real CLI proof uses an isolated state, an account created with `onboard --secret-input-mode ref`, a distinct saved account on another agent, and local protocol-compatible HTTP fixtures. No Gateway or external provider account is used.

| Command | Base `ead0a74e21dfcd6de2007cc0695c732966a11dc0` | Head `7ab685a8195d534e22ee52202a2752c178c424de` |
| --- | --- | --- |
| Embedding create | Exit 1; unmaterialized account reference; zero requests | Exit 0; expected embedding; selected credential at HTTP egress |
| Image generate | Exit 1; same error; zero requests | Exit 0; PNG written; selected credential at HTTP egress |
| Audio transcribe | Exit 1; same error; zero requests | Exit 0; expected transcript; selected credential at HTTP egress |
| Video generate | Exit 1; same error; zero requests | Exit 0; authenticated create/download; fixture bytes written |
| Image describe, sole agent | Exit 1; unmaterialized account reference; zero requests | Exit 0; selected credential at HTTP egress; returned image description |
| Video describe, sole agent | Exit 1; unmaterialized account reference; zero requests | Exit 0; selected credential at HTTP egress; returned video description |
| Local model run | Exit 0; selected credential | Exit 0; selected credential |
| Missing selected secret | Exit 1; zero requests | Exit 1; zero requests despite a usable other-agent account |

Image proof uses the existing local-image fixture opt-in on both base and head. Audio and video use the existing private-network request opt-in. The original small-audio and image network-policy setup failures are retained in private evidence.

An independent source-blind pass confirms successful outputs and selected credentials for all four capability families, zero traffic for each missing-secret case, and the current credential after rotation in a new CLI process. The other-agent account succeeds when selected directly.

Description proof retains the real media runtime and provider adapters. Both matched pairs use the same saved account database and command arguments; configs differ only by the local fixture port. Image returns “A synthetic blue square is visible.” Video sends a playable ten-frame input and returns “A synthetic blue square moves across the video.” Removing the selected secret makes each command fail before HTTP. A separate independent audit confirms the captured requests, exact selected credential classification, media payload bytes, outputs, and base/head state comparison.

Image description uses a documented sole-agent configuration to isolate secret preparation. The explicit-agent multi-agent image command still fails on both base and head because the separate forwarding defect remains. Those failures are retained. Initial video fixture configuration and endpoint-policy failures are also retained; the qualified proof uses an existing provider adapter that supports a local compatible endpoint. No runtime or auth function is mocked in these description proofs.

Limits: HTTP fixtures prove credential routing and output handling, not external provider generation quality. Generated-video output is a synthetic container; its playback is unconfirmed. The playable video above is the description input. The independent pass observed audio model-override behavior outside this credential repair; no forwarding change is included.

## Consumers

- `model.ts`: existing local model caller migrates to the shared helper name; Gateway model flow remains unchanged.
- `embedding.ts`: `infer embedding create` prepares selected-account secrets before creating its embedding provider.
- `image.ts`: generation/edit share one runner; describe/describe-many share another; both prepare before provider auth.
- `audio.ts`: transcription prepares before the media runtime.
- `video.ts`: generation and description prepare before their respective runtimes.
- `local-account-secrets.test.ts`: retains both existing preparation contract tests under the new name.
- `capability-cli.test.ts`: mock follows the shared helper rename; command wiring coverage is retained.
- `local-runners.account-secrets.test.ts`: six registered command routes reach real SQLite account and secrets owners before mocked provider execution.
- Search across source, plugins, UI, native apps and docs finds no other consumer of the retired helper/module names. Provider inventories do not perform inference; TTS and web use separate auth contracts.
- Pipeline: registered command → config-reference resolution → selected agent → existing account-secret preparation → provider auth → HTTP request and output. Fixture HTTP headers are the credential proof boundary.

## Invalidation

No new cached or persisted state. The existing preparation activates a process-local snapshot only when none exists. Each standalone CLI process rereads the selected account and current secret value. An already active snapshot remains owned by the secrets runtime. Existing tests retain source-config preservation and active-snapshot behavior. Missing-secret and other-agent controls verify owner isolation. Independent rotation checks pass for embedding, image, audio and video in fresh CLI processes.

## Contention

No new locks, queues or transactions held. Existing account loading and snapshot activation owners remain unchanged.

## Tests

Base `ead0a74e21dfcd6de2007cc0695c732966a11dc0` reproduces unmaterialized account-reference failures for embedding, image generation, image description, audio transcription, video generation and video description: exit 1, zero HTTP requests. The same account succeeds for local model inference.

The regression table fails all six cases on the base with `SECRET_SURFACE_UNAVAILABLE`. It invokes the registered image generate/describe, embedding create, audio transcribe and video generate/describe commands. No new production test seam is needed.

Targeted validation passes: 316 tests across nine files, including capability commands, the existing model account-secret sibling, lazy registration, and command-secret coverage. Targeted formatting, diff whitespace, file-size and assertion safety checks pass. Full typechecking runs in CI.

Test deletion ledger: no behavior deleted. The existing helper test file is renamed with its two cases preserved; the wiring suite mock follows that rename. No baseline or snapshot exceptions.

Upgrade behavior: no schema, config, protocol, persistence, updater, Doctor or plugin contract changes; existing credentials and auth precedence are retained.

Related open work: openclaw#145188 and openclaw#145171 repair agent-option forwarding in the same owner files. Their defect is separate; this patch does not duplicate their change. Recheck overlap on the landing merge tree.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Sep 12, 2026
Related: #144931

## What Problem This Solves

Restoring an agent backup and registering that directory under a new agent name lets local capability inference use the original agent's saved credential. This follows supported `backup create`, `backup restore --target`, and `agents add --agent-dir` commands. Local model inference already refuses the durable owner mismatch. Follow-up to our #144931; found by the adversarial round, with no external reporter.

## Why This Change Was Made

The shared local account preparation now passes the selected identity to the auth database owner before resolving credentials, including when a secrets snapshot is active. The auth reader delegates to the existing durable schema-owner assertion without requiring a newer session schema. No schema, migration, configuration, or protocol change.

The decision 'may this agent use this saved credential' is made by exactly one mechanism at `src/state/openclaw-agent-db-schema-helpers.ts:311`.

## User Impact

A restored directory registered under another name now produces the same owner-mismatch refusal across local inference commands before any provider request. Legitimate saved credentials continue to work.

## Evidence

Pinned base: `d5e652099074b5801cc7e4e3a108c035d2888e99`.

- Supported restore reproduction: base embedding exits 0 and sends one recorded provider request with the original agent's synthetic credential. The model control exits 1 with `belongs to agent ops; requested agent restored` and sends no request.
- Candidate `2e81eb5998b460c47463907b0b8fdac88b19ead0`: restored embedding and model both exit 1 with the owner mismatch and zero provider requests. All six repaired commands—embedding, image generation, image description, audio transcription, video generation, and video description—reject the foreign owner before dispatch. Model inference remains a separate unchanged control. A supplemental video-generation capture uses the configured recorder endpoint: the legitimate owner creates and downloads a video; the restored owner exits 1 with the owner mismatch and sends zero create/content requests.
- Final pre-landing rebase: head `f1a33f00c1c7cdcc332b3e5464430f46a49e044c` preserves the exact repair patch and all four changed files. The six restored-owner refusal commands and legitimate-owner video/model controls were refreshed on this head; prior pinned-base, rotation, older-state, and targeted-test evidence remains retained.
- Legitimate saved-reference accounts succeed for all six command families. The known multi-agent image-description forwarding failure remains unchanged; the sole-agent description control succeeds, as in the original proof. #145188/#145171 track that separate path.
- Rotated credentials succeed through model, embedding, image edit, describe-many, audio, video generation/download, and video description. An unavailable unrelated credential does not block the healthy account.
- Previous state: v2026.9.4 application source created a schema-19 saved account; candidate embedding succeeds with its credential through the existing schema-20 upgrade path. The older source needed only upstream build-tool repair #144831 to complete its build; application sources were unchanged from the tag.
- All six registered capability regression cases fail on the original code. Candidate capability tests: 255 passed; auth SQLite sibling: 16 passed. The helper provenance test passes after an isolation-only correction.
- A source-blind validator independently ran the supported restore and legitimate-account CLI flows on pre-rebase head `2e81eb5998b460c47463907b0b8fdac88b19ead0`: PASS. The focused post-rebase CLI refresh was run by the repair worker.
- Proof uses synthetic credentials and a loopback provider to measure actual credential routing and request absence.

## Consumers

Seven calls to `prepareLocalCapabilityAccountSecrets` cover local `model run`, `embedding create`, image `generate`/`edit`, image `describe`/`describe-many`, audio `transcribe`, video `generate`/download, and video `describe`. Their shared preparation retains the selected identity and validates before credential use. No command-specific predicates were added.

`capability` is an alias for the same registered command tree at `src/cli/capability-cli.ts:106-124`, as documented by `docs/cli/infer.md:9`; it reaches the same preparation owner.

Test consumers: `src/cli/capability-cli/local-account-secrets.test.ts:35,49` imports and calls the preparation helper for source-config provenance, and lines 18-20 mock the new auth-owner adapter for isolation. `src/cli/capability-cli.test.ts:336-338` mocks shared preparation for command-wiring coverage.

`assertAuthProfileStoreAgentOwner` has one production caller: shared local capability account preparation. The existing canonical assertion remains used by agent database schema, read-only access, writable open, admission, and maintenance. Model preparation also reaches that same assertion through persisted model-catalog reads.

Memory CLI uses its separate config-reference preparation in `extensions/memory-core/src/cli-runtime-common.ts`; adversarial finding F4 remains separate. Provider listings, web, and speech synthesis do not consume this helper.

Related open PRs #145188 and #145171 forward agent identity through media-understanding calls. They are separate from this saved-credential admission. Preserve the shared preparation call when reconciling landing order. Their branches and metadata were not changed.

## Invalidation

No owner verdict is cached. Every shared preparation call reads durable metadata, before the active-snapshot shortcut. Existing auth read-pool lifecycle and credential revision invalidation remain the owners. Credential mutation advances the revision; snapshot activation validates it; clearing the runtime clears linked snapshots. Database/root closure and process exit close pooled readers. No additional cache or lifecycle was introduced.

## Contention

No explicit transaction, lock, or queue is held across an await. The short metadata read uses the existing auth read connection and busy policy. Credential preparation retains its existing asynchronous lifecycle.

## Tests

The registered entry points `infer image generate`, `infer image describe`, `infer embedding create`, `infer audio transcribe`, `infer video generate`, and `infer video describe` each first succeed for their durable owner, then reject another selected identity without further credential egress, with both active and cleared secrets snapshots.

Deletion ledger: removed the helper-only “does not replace an already active secrets runtime snapshot” case because its no-directory-resolution assertion preserved the unsafe bypass. The registered-command cases now cover admission with an active snapshot. The helper source-config provenance case remains, with its new database dependency mocked to keep fixed paths isolated.

Moved side effects: none. Production grows by 25 net lines to connect explicit selected identity to the existing durable decision through the version-tolerant auth reader.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 13, 2026
…145692)

Related: openclaw#144931

## What Problem This Solves

Restoring an agent backup and registering that directory under a new agent name lets local capability inference use the original agent's saved credential. This follows supported `backup create`, `backup restore --target`, and `agents add --agent-dir` commands. Local model inference already refuses the durable owner mismatch. Follow-up to our openclaw#144931; found by the adversarial round, with no external reporter.

## Why This Change Was Made

The shared local account preparation now passes the selected identity to the auth database owner before resolving credentials, including when a secrets snapshot is active. The auth reader delegates to the existing durable schema-owner assertion without requiring a newer session schema. No schema, migration, configuration, or protocol change.

The decision 'may this agent use this saved credential' is made by exactly one mechanism at `src/state/openclaw-agent-db-schema-helpers.ts:311`.

## User Impact

A restored directory registered under another name now produces the same owner-mismatch refusal across local inference commands before any provider request. Legitimate saved credentials continue to work.

## Evidence

Pinned base: `79a02b57732d6f4b24c7325d41a452d9d494e319`.

- Supported restore reproduction: base embedding exits 0 and sends one recorded provider request with the original agent's synthetic credential. The model control exits 1 with `belongs to agent ops; requested agent restored` and sends no request.
- Candidate `2e81eb5998b460c47463907b0b8fdac88b19ead0`: restored embedding and model both exit 1 with the owner mismatch and zero provider requests. All six repaired commands—embedding, image generation, image description, audio transcription, video generation, and video description—reject the foreign owner before dispatch. Model inference remains a separate unchanged control. A supplemental video-generation capture uses the configured recorder endpoint: the legitimate owner creates and downloads a video; the restored owner exits 1 with the owner mismatch and sends zero create/content requests.
- Final pre-landing rebase: head `f1a33f00c1c7cdcc332b3e5464430f46a49e044c` preserves the exact repair patch and all four changed files. The six restored-owner refusal commands and legitimate-owner video/model controls were refreshed on this head; prior pinned-base, rotation, older-state, and targeted-test evidence remains retained.
- Legitimate saved-reference accounts succeed for all six command families. The known multi-agent image-description forwarding failure remains unchanged; the sole-agent description control succeeds, as in the original proof. openclaw#145188/openclaw#145171 track that separate path.
- Rotated credentials succeed through model, embedding, image edit, describe-many, audio, video generation/download, and video description. An unavailable unrelated credential does not block the healthy account.
- Previous state: v2026.9.4 application source created a schema-19 saved account; candidate embedding succeeds with its credential through the existing schema-20 upgrade path. The older source needed only upstream build-tool repair openclaw#144831 to complete its build; application sources were unchanged from the tag.
- All six registered capability regression cases fail on the original code. Candidate capability tests: 255 passed; auth SQLite sibling: 16 passed. The helper provenance test passes after an isolation-only correction.
- A source-blind validator independently ran the supported restore and legitimate-account CLI flows on pre-rebase head `2e81eb5998b460c47463907b0b8fdac88b19ead0`: PASS. The focused post-rebase CLI refresh was run by the repair worker.
- Proof uses synthetic credentials and a loopback provider to measure actual credential routing and request absence.

## Consumers

Seven calls to `prepareLocalCapabilityAccountSecrets` cover local `model run`, `embedding create`, image `generate`/`edit`, image `describe`/`describe-many`, audio `transcribe`, video `generate`/download, and video `describe`. Their shared preparation retains the selected identity and validates before credential use. No command-specific predicates were added.

`capability` is an alias for the same registered command tree at `src/cli/capability-cli.ts:106-124`, as documented by `docs/cli/infer.md:9`; it reaches the same preparation owner.

Test consumers: `src/cli/capability-cli/local-account-secrets.test.ts:35,49` imports and calls the preparation helper for source-config provenance, and lines 18-20 mock the new auth-owner adapter for isolation. `src/cli/capability-cli.test.ts:336-338` mocks shared preparation for command-wiring coverage.

`assertAuthProfileStoreAgentOwner` has one production caller: shared local capability account preparation. The existing canonical assertion remains used by agent database schema, read-only access, writable open, admission, and maintenance. Model preparation also reaches that same assertion through persisted model-catalog reads.

Memory CLI uses its separate config-reference preparation in `extensions/memory-core/src/cli-runtime-common.ts`; adversarial finding F4 remains separate. Provider listings, web, and speech synthesis do not consume this helper.

Related open PRs openclaw#145188 and openclaw#145171 forward agent identity through media-understanding calls. They are separate from this saved-credential admission. Preserve the shared preparation call when reconciling landing order. Their branches and metadata were not changed.

## Invalidation

No owner verdict is cached. Every shared preparation call reads durable metadata, before the active-snapshot shortcut. Existing auth read-pool lifecycle and credential revision invalidation remain the owners. Credential mutation advances the revision; snapshot activation validates it; clearing the runtime clears linked snapshots. Database/root closure and process exit close pooled readers. No additional cache or lifecycle was introduced.

## Contention

No explicit transaction, lock, or queue is held across an await. The short metadata read uses the existing auth read connection and busy policy. Credential preparation retains its existing asynchronous lifecycle.

## Tests

The registered entry points `infer image generate`, `infer image describe`, `infer embedding create`, `infer audio transcribe`, `infer video generate`, and `infer video describe` each first succeed for their durable owner, then reject another selected identity without further credential egress, with both active and cleared secrets snapshots.

Deletion ledger: removed the helper-only “does not replace an already active secrets runtime snapshot” case because its no-directory-resolution assertion preserved the unsafe bypass. The registered-command cases now cover admission with an active snapshot. The helper source-config provenance case remains, with its new database dependency mocked to keep fixed paths isolated.

Moved side effects: none. Production grows by 25 net lines to connect explicit selected identity to the existing durable decision through the version-tolerant auth reader.

Co-authored-by: Ayaan Zaidi <[email protected]>
@MertBasar0
MertBasar0 force-pushed the fix/145119-infer-agent-id branch from 217ff83 to 8dfa556 Compare September 13, 2026 12:00
…ile calls

`openclaw infer image describe`, `image describe-many`, `audio transcribe`,
and `video describe` resolved the caller's `--agent` into an agent id, derived
`agentDir` from it, and then dropped the id: only `agentDir` was passed into
`describeImageFile`, `describePreparedImageWithModel`, `transcribeAudioFile`,
and `describeVideoFile`.

The media-understanding runtime forwards the owner conditionally
(`...(params.agentId ? { agentId: params.agentId } : {})`), so the owner stayed
`undefined` for the rest of the pipeline. Downstream model selection then fell
back to `resolveAmbientOwnerAgentId` -> `resolveSoleAgentId`, which throws
`AgentSelectionRequiredError` on any fleet with more than one agent and
`agents.ownership: "explicit"` — even though a valid `--agent` was supplied.
`resolveInputs` recovers the identity from `agentDir`, but
`loadProviderScopedThinkingCatalog` resolves the ambient owner unconditionally,
so the explicit-owner requirement still failed.

These four CLI call sites are the only callers of the file-oriented
media-understanding runtime, so forwarding the resolved id completes the owner
boundary rather than patching one command. `DescribeImageFileParams` and
`DescribePreparedImageWithModelParams` already accepted `agentId`;
`TranscribeAudioFileParams` and `DescribeVideoFileParams` gain the same optional
field, which `runMediaUnderstandingFile` already honors.

The agent-routing tests asserted `resolveAgentDir` call arguments for image
describe, so they only proved directory resolution and never that an owner
reached the runtime — which is why openclaw#124926 / openclaw#125143 left this path broken.
Both routing tables now assert the owner on the downstream runtime call, and a
case covers the explicit-`--model` branch.

Fixes openclaw#145119

Co-Authored-By: Claude Opus 5 <[email protected]>
obviyus added a commit that referenced this pull request Sep 13, 2026
## What Problem This Solves

Image inference accepts `--agent`, discards the selected identity, and fails in explicit multi-agent fleets—even when the named agent exists.

Supersedes #145188 by @MertBasar0. Reported in #145119 by @jarvis-stephens-bot.

## User Impact

Image description works with the selected agent. Audio and video commands carry the same selected identity and retain their existing successful output behavior.

## Why This Change Was Made

The decision which agent owns the operation stays with `resolveCapabilityProviderAgentId` in `src/cli/capability-cli/shared.ts`. All four CLI call sites now forward that decision alongside its credential directory. Tests check both values at the runtime boundary. Current audio evaluation order and provider/model output are preserved.

## Evidence

With three explicit-owner agents and a synthetic loopback provider, the following commands failed before any HTTP request on main `4394ad538cac`. They succeed on `068dc9c759d9`:

```sh
pnpm openclaw infer image describe --file image.png --prompt describe --agent finance --json
pnpm openclaw infer image describe --file image.png --prompt describe --model stubvision/stub-vision-1 --agent finance --json
pnpm openclaw infer image describe-many --file image.png --file image.png --prompt describe --agent finance --json
```

Sanitized terminal captures:

```text
Before: exit 1; ok=false; AgentSelectionRequiredError; HTTP requests=0
After describe: exit 0; ok=true; SYNTHETIC_IMAGE_DESCRIPTION; requests=1
After explicit model: exit 0; ok=true; SYNTHETIC_IMAGE_DESCRIPTION; requests=1
After describe-many: exit 0; ok=true; two descriptions; requests=2
```

The real Gateway passed its health check. These media commands use local transport. Sole-agent image, configured audio transcription, and configured video description succeed before and after; audio/video are consistency controls, not reproduced failures.

The new registered-command assertions fail nine cases on trusted main `21aaac7ad6e7` and pass after the repair. On merge `e0665878861f` (parents `068dc9c759d9` and main `1692f891b167`), all five selected test files pass: **332 tests**.

<details>
<summary>Validation commands and limits</summary>

```sh
node scripts/run-vitest.mjs run --config test/vitest/vitest.cli.config.ts src/cli/capability-cli.test.ts --testNamePattern 'owner selection'
node --import tsx scripts/ci-run-node-test-shard.mts
pnpm openclaw infer audio transcribe --file audio.wav --agent finance --json
pnpm openclaw infer video describe --file video.mp4 --agent finance --json
```

The CI test runner selected the full capability CLI, local account-secret, media runtime, settings-storage, and proxy lifecycle test files. CLI/account tests: 259; media runtime: 33; settings: 15; proxy: 25. An inherited color setting first affected the settings numeric-output assertion; disabling forced color passed without source or test changes. The successful owner/runtime suites were not repeated.

Formatting, syntax lint, assertion safety, line limits, and unused-export checks pass. [CI run 34784959798](https://github.com/openclaw/openclaw/actions/runs/34784959798) passed at `068dc9c759d99233ed17b668bef97b94ad10ab86`, including production and test typechecks.

The original PR's settings failure was repaired upstream in #147029. Its old proxy child-exit failure remains unexplained; both exact tests passed in its matched main-parent CI. The current tests pass, but this does not waive fresh CI or declare the old proxy failure unrelated.

</details>

**External SDK compatibility:** The same external consumer compiled and ran against the shipped 2026.9.4 package and the packaged candidate at `068dc9c759d9` in one isolated container. Directory-only and `agentId` calls passed for both audio and video: four successful calls per package, with the expected credential directory and loopback-only transport.

## Compatibility

Audio/video SDK parameter types gain optional `agentId` fields. Existing directory-only callers remain valid. There is no new export, config key, schema, migration, protocol, or dependency.

## Consumers

The selected agent identity and its credential directory now reach all four media CLI runtime calls. The existing runtime uses that identity for image model and workspace context. Audio and video retain their existing credential-directory behavior.

The optional audio/video `agentId` fields extend the existing SDK parameter types. Existing directory-only callers remain valid. Browser screenshot description, sticker description, and voice transcription callers are unchanged; this PR does not claim to repair their separate identity-forwarding gaps.

The three image command cases fail before any HTTP request on the recorded main baseline and succeed on the candidate. Configured audio/video and sole-agent image commands pass before and after. Automatic-selection cases were not executed.

The media commands use local transport. The running Gateway is a health control. The 332 passing tests are the selected complete test files on the recorded fresh merge; full CI and typechecking passed in the exact-head run linked above.

No cache or persisted state is added; existing account preparation and request cleanup keep their owners.

Co-authored-by: MertBasar0 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
@obviyus

obviyus commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator

Thanks @MertBasar0!

Proof: Superseded by merged #147456, which carried your commit under your authorship and preserves your contributor credit. The image commands now succeed with the selected agent.

  • Bug: Image commands lost a valid --agent selection before inference.
  • Fix: The media CLI carries that identity alongside its credential directory.
Before After
Explicit agent selection fails before HTTP Image descriptions succeed with the selected agent

@obviyus obviyus closed this Sep 13, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
## What Problem This Solves

Image inference accepts `--agent`, discards the selected identity, and fails in explicit multi-agent fleets—even when the named agent exists.

Supersedes openclaw#145188 by @MertBasar0. Reported in openclaw#145119 by @jarvis-stephens-bot.

## User Impact

Image description works with the selected agent. Audio and video commands carry the same selected identity and retain their existing successful output behavior.

## Why This Change Was Made

The decision which agent owns the operation stays with `resolveCapabilityProviderAgentId` in `src/cli/capability-cli/shared.ts`. All four CLI call sites now forward that decision alongside its credential directory. Tests check both values at the runtime boundary. Current audio evaluation order and provider/model output are preserved.

## Evidence

With three explicit-owner agents and a synthetic loopback provider, the following commands failed before any HTTP request on main `bccb84ab286d`. They succeed on `068dc9c759d9`:

```sh
pnpm openclaw infer image describe --file image.png --prompt describe --agent finance --json
pnpm openclaw infer image describe --file image.png --prompt describe --model stubvision/stub-vision-1 --agent finance --json
pnpm openclaw infer image describe-many --file image.png --file image.png --prompt describe --agent finance --json
```

Sanitized terminal captures:

```text
Before: exit 1; ok=false; AgentSelectionRequiredError; HTTP requests=0
After describe: exit 0; ok=true; SYNTHETIC_IMAGE_DESCRIPTION; requests=1
After explicit model: exit 0; ok=true; SYNTHETIC_IMAGE_DESCRIPTION; requests=1
After describe-many: exit 0; ok=true; two descriptions; requests=2
```

The real Gateway passed its health check. These media commands use local transport. Sole-agent image, configured audio transcription, and configured video description succeed before and after; audio/video are consistency controls, not reproduced failures.

The new registered-command assertions fail nine cases on trusted main `d8799ec248a5` and pass after the repair. On merge `e0665878861f` (parents `068dc9c759d9` and main `3642fc8281b9`), all five selected test files pass: **332 tests**.

<details>
<summary>Validation commands and limits</summary>

```sh
node scripts/run-vitest.mjs run --config test/vitest/vitest.cli.config.ts src/cli/capability-cli.test.ts --testNamePattern 'owner selection'
node --import tsx scripts/ci-run-node-test-shard.mts
pnpm openclaw infer audio transcribe --file audio.wav --agent finance --json
pnpm openclaw infer video describe --file video.mp4 --agent finance --json
```

The CI test runner selected the full capability CLI, local account-secret, media runtime, settings-storage, and proxy lifecycle test files. CLI/account tests: 259; media runtime: 33; settings: 15; proxy: 25. An inherited color setting first affected the settings numeric-output assertion; disabling forced color passed without source or test changes. The successful owner/runtime suites were not repeated.

Formatting, syntax lint, assertion safety, line limits, and unused-export checks pass. [CI run 34784959798](https://github.com/openclaw/openclaw/actions/runs/34784959798) passed at `068dc9c759d99233ed17b668bef97b94ad10ab86`, including production and test typechecks.

The original PR's settings failure was repaired upstream in openclaw#147029. Its old proxy child-exit failure remains unexplained; both exact tests passed in its matched main-parent CI. The current tests pass, but this does not waive fresh CI or declare the old proxy failure unrelated.

</details>

**External SDK compatibility:** The same external consumer compiled and ran against the shipped 2026.9.4 package and the packaged candidate at `068dc9c759d9` in one isolated container. Directory-only and `agentId` calls passed for both audio and video: four successful calls per package, with the expected credential directory and loopback-only transport.

## Compatibility

Audio/video SDK parameter types gain optional `agentId` fields. Existing directory-only callers remain valid. There is no new export, config key, schema, migration, protocol, or dependency.

## Consumers

The selected agent identity and its credential directory now reach all four media CLI runtime calls. The existing runtime uses that identity for image model and workspace context. Audio and video retain their existing credential-directory behavior.

The optional audio/video `agentId` fields extend the existing SDK parameter types. Existing directory-only callers remain valid. Browser screenshot description, sticker description, and voice transcription callers are unchanged; this PR does not claim to repair their separate identity-forwarding gaps.

The three image command cases fail before any HTTP request on the recorded main baseline and succeed on the candidate. Configured audio/video and sole-agent image commands pass before and after. Automatic-selection cases were not executed.

The media commands use local transport. The running Gateway is a health control. The 332 passing tests are the selected complete test files on the recorded fresh merge; full CI and typechecking passed in the exact-head run linked above.

No cache or persisted state is added; existing account preparation and request cleanup keep their owners.

Co-authored-by: MertBasar0 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

2 participants