Skip to content

feat(agentsapi): configure hosted or self-hosted environments - #158307

Merged
sjf-oa merged 24 commits into
mainfrom
sjf/agentsapi-environment-setting
Sep 28, 2026
Merged

sjf-oa merged 24 commits into
mainfrom
sjf/agentsapi-environment-setting

Conversation

@sjf-oa

@sjf-oa sjf-oa commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Agents API users need to choose between an OpenAI-hosted environment and their own executor. This adds that choice to the existing plugin while keeping hosted execution as the default and preserving existing hosted session bindings. Executor skill-directory support remains separate in stacked PR #159363.

Changes and operating requirements

  • plugins.entries.agentsapi.config.environment selects openai_hosted or self_hosted.
  • Self-hosted creation receives the resolved workspace as workspace_directory. Operators must provide that path inside the executor and an external controller that owns executor connection, reconnection, and cleanup.
  • Changing the environment or self-hosted workspace requires resetting the OpenClaw session. Existing hosted bindings remain compatible; the plugin never resets or migrates saved sessions automatically.
  • The existing 60-second input-submission deadline remains unchanged. Late executor attachment can fail the turn. Timeout changes are deferred.
  • Named prompt constants describe the execution environment while preserving main's shared prompt preparation, hooks, memory routing, and per-turn context.
  • Hosted attachments and output transfers retain their behavior. Self-hosted attachments remain unsupported.

Evidence

Published head: 6ea95a59429ec28852ba37f9fb787d5e478eb300, rebased onto main f446771950b645472710b7f39a396274e0419d0a. Agents API source, tests, database-worker routing and generated configuration baselines are byte-identical to the preceding CI-green head. Main now contains the equivalent shared workflow-fixture repair in b9cd492ac60fe4cd5924fe6faa3962df9659ee29; the redundant PR commit was dropped while preserving main's canonical helper path. The registered-harness test retains its typed-lint fix.

  • All 42 targeted unit tests passed on the preceding head 9dd15f3aac90e26225ef93bc7eaae052d3c0cedc: environment selection, instructions, attempts, client requests, and the registered-harness SQLite persistence test. Command: pnpm test extensions/agentsapi/agentsapi-environment.test.ts extensions/agentsapi/agentsapi-attempt.instructions.test.ts extensions/agentsapi/agentsapi-attempt.test.ts extensions/agentsapi/agentsapi-client.test.ts extensions/agentsapi/agentsapi-harness.persistence.test.ts --maxWorkers=1. Total wall time: 60.14 seconds, including fresh worker preparation. The persistence case took 2.359 seconds; its shard took 37.85 seconds, and the other four files took 16.95 seconds.

  • On the preceding head 20015be80bc60b2e65d8c7015c5aaeecfa5194ec, the changed persistence test passed again with pnpm test extensions/agentsapi/agentsapi-harness.persistence.test.ts --maxWorkers=1, taking 16.34 seconds wall time (case: 2.090 seconds; shard: 15.88 seconds). Focused type-aware lint, pnpm tsgo:extensions:test, formatting check, and git diff --check also passed.

  • The persistence test reopens an existing hosted binding, continues it with the default setting, rejects an environment change before provider writes, resets, creates a self-hosted session, and continues it after another database reopen. It uses the actual registered harness and SQLite state owner with a fake provider.

  • Before the test-only correction, pnpm tsgo:extensions:test passed in 15.95 seconds. pnpm config:docs:check and git diff --check passed. Frozen dependency installation succeeded.

  • On the prior reviewed head, GitHub CI passed 106 extension cases across 10 files and extension-test typechecking. The persistence case took 2.661 seconds in CI, its worker shard 36.36 seconds including preparation, and the other changed-extension shard 20.27 seconds. Current-head CI is the enforced landing gate; prior-head results are not represented as current-head CI.

  • Prior CI failures from stale core test-manifest entries were inherited from main. The updated main baseline removes both entries; no unrelated CI fix is added by this PR.

  • The inherited CI fixture defect was reproduced as five missing-helper failures. After provision of the actual static-check helper, the preceding head 617bc68fa4ab9501238e0855cb1f14670ec19ac2 passed all 449 workflow-planning tests in 170.98 seconds wall time and passed the full GitHub CI gate. Its CI workflow-planning suite took 102.338 seconds (103.90 seconds including Vitest overhead); the containing job took 255 seconds including other work.

  • On the published rebased head, 27 focused workflow cases passed in 20.62 seconds wall time with pnpm test test/scripts/ci-workflow-planning.test.ts --maxWorkers=1 --reporter=dot -t 'preserves compiler placement and concurrency|retains compiler coverage|preserves type workload|halts only the type row|runs declared typechecks'. pnpm config:docs:check and git diff --check passed. Main also updated CI routing assertions, so the earlier full 449-case result is not claimed for the new file bytes. Current-head GitHub CI is the required landing gate.

Review disposition and remaining proof limits

Independent review and the completed ClawSweeper review found no code or security defects; ClawSweeper accepted the saved-binding compatibility evidence. The maintainer has directed landing with the documented external-controller requirement, manual-reset behavior, and unchanged deadline, and has waived further ClawSweeper reviews. This does not represent the bot as having approved the PR or bypass the enforced GitHub CI gate.

Historical native-arm64 Docker Gateway testing exercised fresh self-hosted sessions, real executor commands, and delivered Slack replies using operator attachment. Two successful initial turns started 29 seconds after session creation. Automatic external-controller startup within the deadline, its failure recovery, and a live persisted hosted-to-self-hosted transition remain unverified. The passing SQLite test establishes the stored-binding behavior with a fake provider, not those live deployment results.

@clawsweeper

clawsweeper Bot commented Sep 25, 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 docs Improvements or additions to documentation extensions: agentsapi size: M size: L and removed size: M labels Sep 25, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 25, 2026
@clawsweeper

clawsweeper Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 28, 2026, 12:20 AM ET / 04:20 UTC (Revision 16).

ClawSweeper review

What this changes

The branch adds hosted or self-hosted selection to the Agents API plugin, updates saved-session checks and setup guidance, and adds request and SQLite persistence tests.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep open. Current main does not provide this mode, and the reviewed patch has no established blocking code defect. The remaining blocker is direct maintainer acceptance of the manual session reset and prompt external executor attachment required by the proposed operating contract.

Priority: P2
Reviewed head: 6ea95a59429ec28852ba37f9fb787d5e478eb300
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The plugin-scoped patch and historical real-flow proof provide good review confidence; the remaining choice concerns its operator contract.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Historical live output from a native-arm64 Docker Gateway shows self-hosted executor turns completing through the Agents API plugin and Slack replies being delivered; it does not show automatic controller startup on this head. The registered-harness SQLite test separately verifies continuation of an existing hosted binding and reset before a new self-hosted binding, so existing-state data compatibility is sufficient.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Historical live output from a native-arm64 Docker Gateway shows self-hosted executor turns completing through the Agents API plugin and Slack replies being delivered; it does not show automatic controller startup on this head. The registered-harness SQLite test separately verifies continuation of an existing hosted binding and reset before a new self-hosted binding, so existing-state data compatibility is sufficient.
Evidence reviewed 11 items Current main: The fetched main revision still creates an OpenAI-hosted session and has no self-hosted environment setting in the plugin configuration.
Introduced session behavior: The attempt resolves live plugin configuration, preserves the prior hosted fingerprint, binds self-hosted sessions to their environment and workspace, and rejects a changed binding before provider writes.
SDK dependency signal: The new environment type is imported from the official OpenAI Node SDK and passed through its session-create request, making that SDK contract applicable.
Findings None None.
Security None None.

How this fits together

The Agents API plugin receives an OpenClaw agent turn, workspace, configuration, credentials, and saved session binding. It creates or continues an OpenAI session and returns the completed result for channel delivery.

flowchart LR
A[Agent turn and workspace] --> B[Agents API plugin]
C[Environment setting] --> B
B --> D{Saved session matches?}
D -->|No| E[Session reset required]
D -->|Yes| F[OpenAI session]
F --> G[Hosted or operator executor]
G --> H[Channel reply]
Loading

Decision needed

Question Recommendation
Should the bundled Agents API plugin ship opt-in self-hosted execution with manual session reset on environment changes and operator-managed executor attachment within the existing 60-second input deadline? Accept the documented contract: Approve manual reset and prompt external-controller attachment as explicit responsibilities for operators who enable self-hosted mode.

Why: These are intentional operator-facing tradeoffs. Source and documentation establish them, but the captured PR thread does not independently record a qualifying maintainer accepting both.

Before merge

  • Resolve merge risk (P1) - Selecting self-hosted mode for an existing hosted session stops its next turn until the operator resets that OpenClaw session; direct maintainer acceptance of this upgrade interruption is not recorded in the captured discussion.
  • Resolve merge risk (P1) - A self-hosted turn can fail if the operator's external controller does not attach its executor within the existing 60-second input deadline; automatic attachment and recovery were not shown by the historical live run.
  • Complete next step (P2) - Record a qualifying maintainer's direct acceptance of the manual-reset and external-controller deadline contract before merge.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

PR surface

Source +80, Tests +778, Docs +65, Config 0, Generated 0. Total +923 across 20 files.

View PR surface stats
Area Files Added Removed Net
Source 7 116 36 +80
Tests 6 778 0 +778
Docs 4 75 10 +65
Config 1 1 1 0
Generated 2 3 3 0
Other 0 0 0 0
Total 20 973 50 +923

Review metrics

Metric Value Why it matters
New operator configuration 1 setting, 2 values; hosted default retained The new behavior is opt-in, while a changed saved session still requires operator action.
Test-to-production growth tests +778 net lines vs production +80 net lines, about 9.7:1 Production growth is concentrated in the plugin-owned mode; the PR reports measured costs for its request and persistence coverage.

Root-cause cluster

Relationship: canonical
Canonical: #158307
Summary: This PR owns environment selection; the open stacked PR proposes separate self-hosted skill-directory discovery.

Members:

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

Merge-risk options

Maintainer options:

  1. Accept opt-in operation (recommended)
    A qualifying maintainer can accept the documented reset and controller timing obligations for this mode.
  2. Verify controller timing
    Require a redacted controller-led first-turn trace before accepting the attachment risk.
  3. Hold self-hosted support
    Pause this branch if the required operator workflow is unsuitable for the bundled plugin.

Technical review

Best possible solution:

Ship the opt-in mode with an owner-approved operating contract that keeps hosted sessions working by default and gives operators clear controller setup and session-reset recovery guidance.

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

Not applicable: this PR adds an opt-in mode rather than repairing a current-main defect. The historical native run supplies a concrete behavior check for fresh self-hosted turns.

Is this the best way to solve the issue?

Yes for the code boundary: the existing plugin uses the official SDK environment parameter and preserves hosted session identity. Acceptance of the operator contract remains a maintainer decision.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded, opt-in agent-runtime capability with limited immediate user impact.
  • merge-risk: 🚨 compatibility: Changing an existing saved hosted session to self-hosted mode intentionally requires manual reset before its next turn.
  • merge-risk: 🚨 availability: Self-hosted turns depend on an external executor attaching before the current input deadline.
  • 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 (live_output): Historical live output from a native-arm64 Docker Gateway shows self-hosted executor turns completing through the Agents API plugin and Slack replies being delivered; it does not show automatic controller startup on this head. The registered-harness SQLite test separately verifies continuation of an existing hosted binding and reset before a new self-hosted binding, so existing-state data compatibility is sufficient.
  • proof: sufficient: Contributor real behavior proof is sufficient. Historical live output from a native-arm64 Docker Gateway shows self-hosted executor turns completing through the Agents API plugin and Slack replies being delivered; it does not show automatic controller startup on this head. The registered-harness SQLite test separately verifies continuation of an existing hosted binding and reset before a new self-hosted binding, so existing-state data compatibility is sufficient.

Evidence

What I checked:

Likely related people:

  • Sarah Fortune: Raw commit e9fcdb4 adds extensions/agentsapi/index.ts:6 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: e9fcdb4002d1; files: extensions/agentsapi/index.ts)
  • Peter Steinberger: 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 (15 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-27T02:00:46.750Z sha ac6ebe999ee161a9782d223f59d13942ec62cae1 :: blocked before merge. :: [P1] Allow the self-hosted executor connection window
  • reviewed 2026-09-27T03:13:55.981Z sha 1b6b32b :: blocked before merge. :: [P1] Allow the self-hosted executor connection window | [P2] Refresh the config baseline on this branch
  • reviewed 2026-09-27T17:01:07.628Z sha 5c649cdd2e6b497dc532759fce821ad43daaaeeb :: blocked before merge. :: none
  • reviewed 2026-09-27T17:09:06.687Z sha 44f71a69466a7f6653d2dc9d03a6d35fdfbbad74 :: blocked before merge. :: none
  • reviewed 2026-09-27T19:56:37.786Z sha c1807fa :: blocked before merge. :: none
  • reviewed 2026-09-28T03:37:54.992Z sha 9dd15f3aac90e26225ef93bc7eaae052d3c0cedc :: blocked before merge. :: none
  • reviewed 2026-09-28T03:50:19.581Z sha 20015be80bc60b2e65d8c7015c5aaeecfa5194ec :: blocked before merge. :: none
  • reviewed 2026-09-28T04:04:47.403Z sha 617bc68fa4ab9501238e0855cb1f14670ec19ac2 :: blocked before merge. :: none

@sjf-oa
sjf-oa force-pushed the sjf/agentsapi-environment-setting branch 2 times, most recently from 3309b2b to d46a97a Compare September 26, 2026 02:30
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XL and removed size: L labels Sep 26, 2026
@sjf-oa
sjf-oa changed the base branch from main to sjf/agentsapi-agent-instructions September 26, 2026 02:31
@openclaw-barnacle openclaw-barnacle Bot added size: L and removed agents Agent runtime and tooling size: XL labels Sep 26, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Sep 26, 2026
@sjf-oa
sjf-oa force-pushed the sjf/agentsapi-agent-instructions branch from f1858c4 to 40e5c6a Compare September 26, 2026 05:12
Base automatically changed from sjf/agentsapi-agent-instructions to main September 26, 2026 05:39
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XL and removed size: L labels Sep 26, 2026
@sjf-oa
sjf-oa force-pushed the sjf/agentsapi-environment-setting branch from d46a97a to c11987e Compare September 26, 2026 05:43
@openclaw-barnacle openclaw-barnacle Bot removed agents Agent runtime and tooling size: XL labels Sep 26, 2026
@sjf-oa
sjf-oa force-pushed the sjf/agentsapi-environment-setting branch from 617bc68 to 6ea95a5 Compare September 28, 2026 04:11
@sjf-oa
sjf-oa merged commit c0196ae into main Sep 28, 2026
133 checks passed
@sjf-oa
sjf-oa deleted the sjf/agentsapi-environment-setting branch September 28, 2026 04:59
@sjf-oa

sjf-oa commented Sep 28, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

MarMarLabs added a commit to MarMarLabs/openclaw that referenced this pull request Sep 28, 2026
46 upstream commits, including the static evidence fixture fix
(57f1abe) and the Linux process-tree memory limits change (openclaw#160024),
which also copies the static step helper into the workflow planning test
root. Those two fix the test type check and the planning test that failed
on the previous merge, in files this branch does not touch.

Two conflicts, both generated: docs/.generated/config-baseline.counts.json
and docs/.generated/config-baseline.sha256. openclaw#158307 adds an agentsapi
plugin setting, so plugin goes from 4350 to 4351. This branch keeps
channel at 3788 and core stays at 2464. Both files came from upstream and
were regenerated. test/vitest/vitest.extension-database-workers-paths.mjs
changed on both sides in separate places and merged cleanly with the
upstream agentsapi entry and this branch's Feishu entry both kept.

build:docker ran in a separate detached checkout of this commit outside the
nested node_modules install. Regenerating there changed those two files and
nothing else, giving the predicted counts, the upstream core and plugin
hashes, this branch's channel hash and a new combined hash. The three
generated-file checks pass there.

Upstream deleted eight test files in this range. None of them were added
or changed by this branch.

Feishu: 106 files and 1854 tests in the extension project, 17 files and
312 tests in the database-workers project. The forwarder test and the
routing guards pass, 1931 tests. tsgo:core, tsgo:extensions,
tsgo:extensions:test, tsgo:test:root, the line-cap, max-lines and
assertion-safety ratchets against upstream/main, oxlint and oxfmt on the
43 changed code files all pass.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 29, 2026
…aw#158307)

* feat(agentsapi): configure hosted or self-hosted environments

* style(agentsapi): format environment configuration

* test(agentsapi): verify SDK continuation request paths

* test(agentsapi): complete typed attempt fixtures

* test(agentsapi): complete host capability fixture

* refactor(agentsapi): update environment instructions

* test(agentsapi): preserve hosted transfers after rebase

* chore(agentsapi): refresh baseline and formatting after rebase

* test(agentsapi): adapt environment fixtures to workspace context

* docs(agentsapi): explain the external executor controller

* docs(agentsapi): refresh generated plugin inventory

* docs(agentsapi): refresh generated plugin reference

* test(agentsapi): use SDK function type after rebase

* docs(agentsapi): refresh standalone environment config baseline

* refactor(agentsapi): remove unused config type export

* docs(agentsapi): state the executor connection deadline

* test(agentsapi): adapt environment fixture to projection class

* test(agentsapi): cover persisted environment bindings and reset

* style(agentsapi): format persisted binding test

* test(agentsapi): adapt environment fixture to shared prompt helpers

* test(agentsapi): run persistence proof in database worker lane

* test(agentsapi): assert registered harness results safely

* docs(agentsapi): refresh hashes after conflict resolution

* test(agentsapi): bind persisted harness fixture methods

---------

Co-authored-by: Sarah Fortune <[email protected]>
obviyus added a commit that referenced this pull request Nov 1, 2026
…olicies (#190036)

## Summary

- **Problem:** `modelPolicy.allow` had two grammars under one name. Operator roles accepted a model-name prefix such as `openai/gpt-*`; agent policies rejected it. Role matching used a separate glob matcher, and five other callers detected wildcards by hand (`endsWith("/*")`, `slice(0, -2)`, `startsWith`). The copies agreed today but could drift, for example on padded refs like `"openai / *"`.
- **Fix:** `src/config/model-policy-ref.ts` now owns one parser (`parseModelPolicyWildcardRef`: `provider/*`, `provider/namespace/*`, `provider/family-*`) and one matcher (`modelPolicyWildcardMatches`). Role policy matching, config validation, `isModelKeyAllowedBySet`, configured model entries, alias candidates, `models status` and the legacy Codex wildcard migration use them. The role-only parser, the role glob matcher and the role-only validation branch are deleted.
- **User impact:** agent policies now also accept model-name prefixes such as `openai/gpt-*`. Existing agent and role configs keep their meaning; no config is invalidated.

## Evidence

**Live Gateway, real operator-role identity.** Setup:
- Candidate Gateway (`openclaw.mjs gateway run` from this branch) on an isolated HOME, state and loopback port.
- `gateway.auth.mode: "trusted-proxy"` with a loopback proxy that sets `x-forwarded-user: [email protected]`.
- `gateway.roles.default: "limited"`, with `modelPolicy: { allow: ["fixture/echo-*"], deny: ["fixture/echo-restricted*"] }`.
- A loopback fake OpenAI-completions provider that logs every request.
- The client is the real `GatewayClient` (webchat mode, device identity, no token), so the proxy-verified user is its only credential.

```text
(1)+(2) sessions.patch fixture/echo-restricted       -> FORBIDDEN "Your operator role cannot use this model…"
        sessions.patch fixture/echo-restricted-mini  -> FORBIDDEN
        sessions.patch fixture/other-x               -> FORBIDDEN (outside allow)
        sessions.patch fixture/echo-main             -> ok
        agent run on that session                    -> status ok
        provider log: POST /v1/chat/completions model=echo-main   (only request; no echo-restricted* or other-x call)
(3)     live reload narrows the role: deny += "fixture/echo-main*"
        [reload] config change detected; evaluating reload (gateway.roles.definitions.limited.modelPolicy.deny)
        next agent run on the pinned echo-main session -> status error "Your operator role cannot use this model…"
        provider requests before=2 after=2 (no new provider call)
(4)     upgrade cell, same state directory:
        published [email protected] Gateway writes and serves the role config:
          echo-restricted / echo-restricted-mini / other-x -> FORBIDDEN, echo-main -> ok, provider called with echo-main
        stop; candidate `doctor --fix` (agent DB schema 25 -> 39, role config untouched); candidate Gateway on that state:
          identical sessions.patch decisions (diff: IDENTICAL), provider called only with echo-main
```

**Role policy compatibility (main vs this PR, real owner code).** One script prepared role policies through `prepareOperatorModelPolicy` on an `origin/main` checkout and on this branch. It evaluated `allows()` for 12 models under 5 policies (family deny `vendor/restricted-v1*`, family allow `vendor/gpt-*`, nested `router/anthropic/*`, padded ` VENDOR / gpt-* ` with deny `vendor/gpt-5.5*`, inherited-source deny `vendor/restricted-*`). It also captured the `main` snapshots with `captureOperatorModelPolicySnapshot` and restored them on this branch with `restoreOperatorModelPolicySnapshot`.

```text
prepared decisions, main vs PR:           0 differences / 60
main snapshots restored on PR vs main:    0 differences / 60
familyDeny on PR: vendor/restricted-v1 false, vendor/restricted-v1-mini false, vendor/restricted-v2 true, vendor/primary true
```

**Admission proof.** New case in `src/gateway/sessions-patch.operator-model-policy.test.ts` drives `projectSessionsPatchEntry` (the `sessions.patch` owner that admits a model before any run or provider request) with role policy `allow: ["fixture/*"]`, `deny: ["fixture/restricted-v1*"]`, once with the freshly prepared policy and once with a policy restored from its captured snapshot:

```text
fixture/restricted-v1       -> FORBIDDEN "operator role cannot use this model"
fixture/restricted-v1-mini  -> FORBIDDEN
fixture/allowed             -> ok; after the operator source is revoked, its commit guard -> FORBIDDEN
```

It fails with this PR's first matcher (strict length check) and passes now. Rebased onto #190019; `pnpm check:changed` and the auth-model-policy suites pass on the rebased head.

Role admission suites that consume this predicate before provider calls also pass on this branch: model fallback, CLI runner, isolated completion and image fallback operator-policy suites, plus `operator-model-policy.test.ts` (65 tests).

- New regression in `model-visibility-policy.test.ts` (agent policy `openai/gpt-5.6-*` allows `gpt-5.6-sol`, not `gpt-5.5`) fails on `origin/main` and passes here.
- Validation table adds `openai/gpt-*` (valid for agents) and rejects `openai/gpt *` and `*`.
- Focused suites pass: model visibility, config model-ref validation, operator model policy, role mutation authority, `models status`, legacy Codex model migration, configured model entries, model selection.
- Role compatibility: `modelPolicyWildcardMatches` is a plain prefix test, the same set the old role glob (`^prefix.*$`) accepted, because the parser forbids any other `*`. A new operator-policy regression (`allow: ["vendor/*"]`, `deny: ["vendor/restricted-v1*"]` must deny `vendor/restricted-v1` itself) fails on the first head of this PR and passes now. Stored role snapshots keep the same canonical wildcard keys, so restored policies match as before.
- `pnpm check:changed` (dead-code step skipped) passes; config docs baseline regenerated.

## Merge danger

Two-way door: no stored state or migration; a revert restores the narrower agent grammar. Blast radius: model policy matching for agents and operator roles. Role semantics are unchanged (same prefix rule, same normalized `provider/model` key).

Pash/Sarah check: Sarah's commits on these files (#161609, #162335, #161048, #161004, #159363, #158307, #158703, #151176, #123875) touch Agents API, Codex and Slack config help/validation entries. This PR edits only model-policy wildcard parsing, matching and help text, so their behavior is unchanged.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 2, 2026
…olicies (openclaw#190036)

## Summary

- **Problem:** `modelPolicy.allow` had two grammars under one name. Operator roles accepted a model-name prefix such as `openai/gpt-*`; agent policies rejected it. Role matching used a separate glob matcher, and five other callers detected wildcards by hand (`endsWith("/*")`, `slice(0, -2)`, `startsWith`). The copies agreed today but could drift, for example on padded refs like `"openai / *"`.
- **Fix:** `src/config/model-policy-ref.ts` now owns one parser (`parseModelPolicyWildcardRef`: `provider/*`, `provider/namespace/*`, `provider/family-*`) and one matcher (`modelPolicyWildcardMatches`). Role policy matching, config validation, `isModelKeyAllowedBySet`, configured model entries, alias candidates, `models status` and the legacy Codex wildcard migration use them. The role-only parser, the role glob matcher and the role-only validation branch are deleted.
- **User impact:** agent policies now also accept model-name prefixes such as `openai/gpt-*`. Existing agent and role configs keep their meaning; no config is invalidated.

## Evidence

**Live Gateway, real operator-role identity.** Setup:
- Candidate Gateway (`openclaw.mjs gateway run` from this branch) on an isolated HOME, state and loopback port.
- `gateway.auth.mode: "trusted-proxy"` with a loopback proxy that sets `x-forwarded-user: [email protected]`.
- `gateway.roles.default: "limited"`, with `modelPolicy: { allow: ["fixture/echo-*"], deny: ["fixture/echo-restricted*"] }`.
- A loopback fake OpenAI-completions provider that logs every request.
- The client is the real `GatewayClient` (webchat mode, device identity, no token), so the proxy-verified user is its only credential.

```text
(1)+(2) sessions.patch fixture/echo-restricted       -> FORBIDDEN "Your operator role cannot use this model…"
        sessions.patch fixture/echo-restricted-mini  -> FORBIDDEN
        sessions.patch fixture/other-x               -> FORBIDDEN (outside allow)
        sessions.patch fixture/echo-main             -> ok
        agent run on that session                    -> status ok
        provider log: POST /v1/chat/completions model=echo-main   (only request; no echo-restricted* or other-x call)
(3)     live reload narrows the role: deny += "fixture/echo-main*"
        [reload] config change detected; evaluating reload (gateway.roles.definitions.limited.modelPolicy.deny)
        next agent run on the pinned echo-main session -> status error "Your operator role cannot use this model…"
        provider requests before=2 after=2 (no new provider call)
(4)     upgrade cell, same state directory:
        published [email protected] Gateway writes and serves the role config:
          echo-restricted / echo-restricted-mini / other-x -> FORBIDDEN, echo-main -> ok, provider called with echo-main
        stop; candidate `doctor --fix` (agent DB schema 25 -> 39, role config untouched); candidate Gateway on that state:
          identical sessions.patch decisions (diff: IDENTICAL), provider called only with echo-main
```

**Role policy compatibility (main vs this PR, real owner code).** One script prepared role policies through `prepareOperatorModelPolicy` on an `origin/main` checkout and on this branch. It evaluated `allows()` for 12 models under 5 policies (family deny `vendor/restricted-v1*`, family allow `vendor/gpt-*`, nested `router/anthropic/*`, padded ` VENDOR / gpt-* ` with deny `vendor/gpt-5.5*`, inherited-source deny `vendor/restricted-*`). It also captured the `main` snapshots with `captureOperatorModelPolicySnapshot` and restored them on this branch with `restoreOperatorModelPolicySnapshot`.

```text
prepared decisions, main vs PR:           0 differences / 60
main snapshots restored on PR vs main:    0 differences / 60
familyDeny on PR: vendor/restricted-v1 false, vendor/restricted-v1-mini false, vendor/restricted-v2 true, vendor/primary true
```

**Admission proof.** New case in `src/gateway/sessions-patch.operator-model-policy.test.ts` drives `projectSessionsPatchEntry` (the `sessions.patch` owner that admits a model before any run or provider request) with role policy `allow: ["fixture/*"]`, `deny: ["fixture/restricted-v1*"]`, once with the freshly prepared policy and once with a policy restored from its captured snapshot:

```text
fixture/restricted-v1       -> FORBIDDEN "operator role cannot use this model"
fixture/restricted-v1-mini  -> FORBIDDEN
fixture/allowed             -> ok; after the operator source is revoked, its commit guard -> FORBIDDEN
```

It fails with this PR's first matcher (strict length check) and passes now. Rebased onto openclaw#190019; `pnpm check:changed` and the auth-model-policy suites pass on the rebased head.

Role admission suites that consume this predicate before provider calls also pass on this branch: model fallback, CLI runner, isolated completion and image fallback operator-policy suites, plus `operator-model-policy.test.ts` (65 tests).

- New regression in `model-visibility-policy.test.ts` (agent policy `openai/gpt-5.6-*` allows `gpt-5.6-sol`, not `gpt-5.5`) fails on `origin/main` and passes here.
- Validation table adds `openai/gpt-*` (valid for agents) and rejects `openai/gpt *` and `*`.
- Focused suites pass: model visibility, config model-ref validation, operator model policy, role mutation authority, `models status`, legacy Codex model migration, configured model entries, model selection.
- Role compatibility: `modelPolicyWildcardMatches` is a plain prefix test, the same set the old role glob (`^prefix.*$`) accepted, because the parser forbids any other `*`. A new operator-policy regression (`allow: ["vendor/*"]`, `deny: ["vendor/restricted-v1*"]` must deny `vendor/restricted-v1` itself) fails on the first head of this PR and passes now. Stored role snapshots keep the same canonical wildcard keys, so restored policies match as before.
- `pnpm check:changed` (dead-code step skipped) passes; config docs baseline regenerated.

## Merge danger

Two-way door: no stored state or migration; a revert restores the narrower agent grammar. Blast radius: model policy matching for agents and operator roles. Role semantics are unchanged (same prefix rule, same normalized `provider/model` key).

Pash/Sarah check: Sarah's commits on these files (openclaw#161609, openclaw#162335, openclaw#161048, openclaw#161004, openclaw#159363, openclaw#158307, openclaw#158703, openclaw#151176, openclaw#123875) touch Agents API, Codex and Slack config help/validation entries. This PR edits only model-policy wildcard parsing, matching and help text, so their behavior is unchanged.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[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

docs Improvements or additions to documentation extensions: agentsapi merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants