Repository navigation
fix(gateway): select openai-completions owner from session key - #138329
teddytennant wants to merge 1 commit into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs changes before merge. What this changesThis PR lets agent-scoped session keys select the executing agent, rejects contradictory selectors, and applies the operator agent allowlist to embeddings. Example: An explicit alpha/beta fleet receives POST /v1/chat/completions with model "openclaw" and x-openclaw-session-key "agent:beta:trace-owner".
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Needs changes before merge - 1 item remains Keep this PR open: it fixes a current multi-agent routing failure, and no introduced correctness defect was found. The previous conflict is resolved; enforced maintainer security approval and unfinished CI remain landing gates. Priority: P2 Before merge
FindingsNone. Agent review detailsHow this fits togetherThe Gateway’s OpenAI-compatible HTTP adapters translate authenticated requests into agent turns or embedding-provider calls, sharing agent selection and existing authorization owners. flowchart TD
A[HTTP client] --> B[Gateway authentication]
B --> C[Shared agent selector]
C --> D[Operator agent policy]
D --> E[Chat and Responses execution]
D --> F[Embedding provider]
E --> G[HTTP response]
F --> G
Technical reviewBest possible solution: Land the shared ownership repair after the existing exact-head CI and maintainer security gates pass. Do we have a high-confidence way to reproduce the issue? Current main’s resolver demonstrably ignores the session-key owner before default resolution; supplied Gateway traces and base-versus-head assertions support the reported failure, although no target code was executed during this review. Is this the best way to solve the issue? The repair belongs in the existing shared selector and command owner, and reuses the existing role policy rather than adding a parallel routing or authorization mechanism. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against cbc95bc981bd. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +88, Tests +358, Docs +15. Total +461 across 13 files. Added test files: 1. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (20 earlier review cycles; latest 8 shown)
Reviewed October 13, 2026, 11:33 AM ET / 15:33 UTC (Revision 21). |
sylvesterkaczmarek
left a comment
There was a problem hiding this comment.
The precedence change looks correct: a concrete model/agent selection still wins, but the generic openclaw alias no longer forces default-agent resolution before an authoritative x-openclaw-session-key can identify its owner. Using parseAgentSessionKey plus assertKnownAgentId is also preferable to string splitting because the session-key grammar stays centralized. The explicit multi-agent/no-header regression is important to show this does not weaken AgentSelectionRequiredError for genuinely ambiguous requests.
a3eda25 to
4489437
Compare
|
Pushed the docs half: openai-http-api.md now lists the selector order and the no-default-agent case where an agent-scoped session key supplies the owner, and the body carries a real Gateway before/after against the mock provider showing beta's model being fetched. |
4489437 to
a18b469
Compare
d57fda6 to
dce4ffc
Compare
|
rebased onto current main ( the plugin drain readers failure was the old assertion, not the session-key owner change. reload waits for retained work before it stops admitting ordinary calls, so readers test passed here, plus the gateway owner tests and new head: |
dce4ffc to
ed9f818
Compare
|
rebased onto current main ( the chat admission failures were the old fixture, not the session-key owner change. those three cases close the agent database from inside the admission callback's writer, and the drain guard rejects that ( admission file passed here under bun (6/6), plus the gateway owner tests (184). new head: |
|
retriggered ci with an empty commit and pushed
new head: |
|
retriggered ci with an empty commit and pushed
same failure on main's scheduled CI, without this PR: https://github.com/openclaw/openclaw/actions/runs/37999811982/job/114055140161 ( new head: |
|
current-head loopback gateway + curl traces are in the evidence section (0d69691, http-utils 36a7f65dd24b). chat completions, model openclaw, x-openclaw-session-key agent:beta:trace-owner, alpha+beta, no default: 200. mock saw beta-model and runtime agent=beta. openclaw/alpha, and x-openclaw-agent-id alpha, against an agent:beta session key: both 400, selected agent alpha does not match the session key. mock saw nothing. /v1/responses with that session key: 200, mock beta-model, runtime agent=beta. /v1/embeddings: 200, mock beta-embed. upgrade from published 2026.9.9 (bcfc888): default agent main, user upgrade-thread, no session-key header, 200 on main-model. same state dir on this head, same request with a second turn: 200, still main-model, same session agent:main:openai-user:upgrade-thread, provider transcript still has the first turn. |
|
upgrade from published 2026.10.2 (b8952d4) is in the evidence section. isolated state dir, default agent main, no agents.ownership. non-default settings were thinkingDefault low, timeoutSeconds 900, identity name Upgrade Trace, theme harbor, primary openai/main-model. chat completion, model openclaw, user upgrade-thread, no session-key header: 200. mock saw main-model and runtime name=Upgrade Trace, agent=main, session agent:main:openai-user:upgrade-thread. this head is package 2026.9.9, so a plain gateway run refused state preparation against lastTouchedVersion 2026.10.2. restarted with OPENCLAW_ALLOW_OLDER_BINARY_DESTRUCTIVE_ACTIONS=1 on the same state dir. second turn 200, still main-model, provider transcript still has the first user turn and assistant OPENCLAW_E2E_TURN1, then the second user turn. those settings and lastTouchedVersion 2026.10.2 were unchanged. @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
merged upstream main into fix/openai-completions-agent-owner and pushed ebf0374. the only conflict was the request-context test imports. kept the session-key owner assertions and upstream's runtime config snapshot setup. http-utils.ts is still blob 36a7f65dd24b. selector order and command ownership are unchanged. guarded upgrade from published 2026.10.2 (b8952d4) is in the evidence section. no OPENCLAW_ALLOW_OLDER_BINARY_DESTRUCTIVE_ACTIONS. this head is OpenClaw 2026.10.2 (ebf0374), so a plain gateway run is not refused as an older binary. current main still stops that first run until doctor --fix migrates the agent database off schema 24. after that, plain gateway run on the same state dir: turn 2 200, same session agent:main:openai-user:upgrade-thread, provider transcript still has the turn-1 user text, assistant OPENCLAW_E2E_TURN1, then the turn-2 user text. thinkingDefault low, timeoutSeconds 900, identity Upgrade Trace / harbor, primary openai/main-model, lastTouchedVersion 2026.10.2 stayed. focused gateway tests passed (request-context 32, openai/openresponses/embeddings/agent-run 254). oxlint, oxfmt, and pnpm tsgo on the touched gateway surface passed. @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
operator-role proof on the loopback mock. trusted-proxy profiles, not the owner token. gateway.roles: beta-operator agents=["beta"], alpha-only agents=["alpha"], both operator.write. allowed: beta-operator POST /v1/chat/completions model openclaw session agent:beta:trace-allowed -> 200 OPENCLAW_E2E_ALLOWED_OK, provider saw beta-model, runtime agent=beta. embeddings skipped that ceiling. before the fix alpha-only POST /v1/embeddings session agent:beta returned 200 and the provider saw beta-embed. d1c134a rejects it with 403 and no provider request; beta-operator still gets beta-embed. request-context session-key tests: 6 pass on head. merge-base resolver 5d5407a fails 4 (explicit fleet throws, default beats the session key, header and model conflicts do not throw). agreeing selector and the ownerless-fleet check pass on both. @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
resolved the conflict with current main in src/gateway/http-utils.request-context.test.ts. kept main's async session access and this pr's session-key owner selection, conflicting-selector rejection, and embeddings role ceiling. new head 39e12b9. pnpm tsgo clean. oxfmt and oxlint clean on the touched gateway files. pnpm test passed for src/gateway/http-utils.request-context.test.ts, src/gateway/embeddings-http.role-ceiling.test.ts, src/gateway/openai-compatible-agent-run.test.ts (56), and the ownerless-fleet plus aggregate-usage cases in src/gateway/openai-http.test.ts (2). @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
A generic model with no agent header resolved to the configured default while the command runner derived the agent from the session key, so an agent-scoped session key was rejected as a mismatch. Use the session key's agent when nothing else names an owner, and reject a header or model that names a different agent than the session key.
39e12b9 to
eb21142
Compare
What Problem This Solves
Generic
openclaw/openclaw/defaultaliases forced a default agent beforex-openclaw-session-keycould name the owner. In an explicit multi-agent fleet with no default, a completion withmodel: openclawandx-openclaw-session-key: agent:scripts:foobarstill gotAgentSelectionRequiredErrorfromresolveDefaultAgentIdafter #137913.Why This Change Was Made
resolveAgentIdForRequestinsrc/gateway/http-utils.tsnow resolves the owner in this order: agent header, agent-specific model, configured default for a generic model, then the agent-prefixed session key, then the required default. The generic alias askstryResolveDefaultAgentIdinstead of throwing, so a fleet with no default falls through to the session key. The parsed agent goes throughparseAgentSessionKeyplusassertKnownAgentId, so the session-key grammar stays in one place and an unknown agent is still rejected.x-openclaw-agent-idstill wins. Two agents with no session key and no agent header still returnAgentSelectionRequiredError.The Chat Completions and Responses references only described
x-openclaw-session-keyas session routing, sodocs/gateway/openai-http-api.mdnow lists the selector precedence and the case where an agent-scoped key supplies the owner, anddocs/gateway/openresponses-http-api.mdpoints at it.pnpm format:docs:check,docs:check-mdxandcodespellon the two pages are clean.User Impact
Operators running an explicit multi-agent fleet without a default agent can send
model: "openclaw"plus the agent's own session key to the Chat Completions, Responses and embeddings endpoints and reach that agent, instead of a400. Fleets with a default agent behave as before.Evidence
Current head
d1c134a6926febaf6cec329cb4e37a5233d9762d. Selector behavior is unchanged fromebf037423f4c37db14f74ab2a024e43a2a04c3ac(src/gateway/http-utils.tsblob36a7f65dd24bad89b0fea397d32a5258d2b0839c).d1c134a6926adds the embeddings operator-role ceiling. The Gateway command isnode --import ./scripts/tsx.mjs src/entry.ts gateway run --bind loopback --force. The provider isscripts/e2e/mock-openai-server.mjson loopback. The client iscurl. State dirs are throwaway. The September chat-only before/after trace (main returned 400, an earlier head returned 200) predates conflict rejection and did not cover Responses, embeddings, or an upgrade. The Chat Completions, conflict, Responses, and embeddings traces below were captured on0d69691; the selector file is the same blob, so they still describe this head. The v2026.10.2 upgrade trace is fromebf03742, with the older-binary guard left enabled. The operator-role traces are from this head's parent process onebf03742for chat, and from a restart ond1c134a6926for the embeddings ceiling.Chat Completions, session key owns the agent
Two agents,
agents.ownership: "explicit", no default. Alpha's model isopenai/alpha-model, beta's isopenai/beta-model. Token auth. Chat Completions and Responses enabled.The mock request for that turn is
POST /v1/chat/completionswithmodel=beta-model. The user text containsRuntime: agent=beta | session=agent:beta:trace-owner. The gateway session write isagentId=beta. A later activity-recap call usesgpt-5.6-lunaand is not the agent turn.Contradictory selectors
Same gateway.
model: "openclaw/alpha"withx-openclaw-session-key: agent:beta:trace-conflict-model:x-openclaw-agent-id: alphawithx-openclaw-session-key: agent:beta:trace-conflict-headerandmodel: "openclaw"returns the same 400 and message. Neither request reached the mock.Responses and embeddings
POST /v1/responses,model: "openclaw",stream: false,x-openclaw-session-key: agent:beta:trace-responses, inputReply with OPENCLAW_E2E_RESPONSES_OK:The mock agent turn is
model=beta-modelandRuntime: agent=beta | session=agent:beta:trace-responses.POST /v1/embeddings,model: "openclaw",input: "OPENCLAW_E2E_EMBED_OK",x-openclaw-session-key: agent:beta:trace-embed. Beta's memory-search model isbeta-embed; alpha's isalpha-embed.The mock embeddings request for that call is
model=beta-embedwith inputOPENCLAW_E2E_EMBED_OK.Operator role, grant, and revocation
Trusted-proxy identity, not the shared-secret owner token.
gateway.auth.modeistrusted-proxy(x-forwarded-user, requiredx-forwarded-proto, loopback allowed). Roles are the realgateway.roles.definitionsentries.beta-operatorhasagents: ["beta"],scopes: ["operator.write"],sessions.others: "none".alpha-onlyhasagents: ["alpha"]and the same scope ceiling. Each caller is a user profile assigned that role. The fleet is still explicit alpha/beta with no default.modelisopenclaw. The session header isx-openclaw-session-key: agent:beta:.... The provider is the same loopback mock. Forwarded client addresses, provider keys, host, repo path, OS, and node lines are omitted.Allowed restricted operator
[email protected],POST /v1/chat/completions, sessionagent:beta:trace-allowed, contentReply with OPENCLAW_E2E_ALLOWED_OK.The mock went from 0 requests to 1:
POST /v1/chat/completions,model=beta-model. The provider user text includesRuntime: agent=beta | session=agent:beta:trace-allowed | model=openai/beta-model | default_model=openai/beta-model | channel=webchat. It does not containalpha-model.Role forbidden from beta
[email protected], same endpoint, sessionagent:beta:trace-forbidden, contentReply with OPENCLAW_E2E_FORBIDDEN_OK.The mock stayed at 1. No new provider request.
Revoked grant before further provider I/O
After that allowed turn,
gateway.roles.definitions.beta-operator.agentschanged from["beta"]to[]. The running gateway logged:Same profile, same session
agent:beta:trace-allowed, contentReply with OPENCLAW_E2E_REVOKED_OK:The mock stayed at 1.
Embeddings ceiling
Chat and Responses already call
authorizeGatewaySessionCreationafter the shared selector. Embeddings did not, so a session-key owner reached the embedding provider when the role disallowed that agent.Before
d1c134a6926,[email protected],POST /v1/embeddings, modelopenclaw, sessionagent:beta:trace-embed-forbidden, inputOPENCLAW_E2E_EMBED_FORBIDDEN:The mock logged
POST /v1/embeddingswithmodel=beta-embed.d1c134a6926applies the same ceiling before embedding provider I/O. The gateway was restarted on that commit, andbeta-operator.agentswas restored to["beta"].[email protected], sessionagent:beta:trace-embed-forbidden-fixed, inputOPENCLAW_E2E_EMBED_FORBIDDEN_FIXED:The mock request count did not change.
[email protected], sessionagent:beta:trace-embed-allowed-fixed, inputOPENCLAW_E2E_EMBED_ALLOWED_FIXED:The new mock line is
POST /v1/embeddings,model=beta-embed.pnpm test -- src/gateway/embeddings-http.role-ceiling.test.tspassed in the gateway-server Vitest project (1 test).Base vs head regression tests
pnpm test -- src/gateway/http-utils.request-context.test.ts -t "agent-prefixed session key|session key owner|explicit owner when a multi-agent"Head
d1c134a6926: 6 passed. Those cases are the session-key owner in an explicit fleet, the session key beating a default agent, header conflict, model conflict, an agreeing selector, and an ownerless fleet still requiring an owner.Merge-base
5d5407ae973addb2174301fb17808382ef0a97a1: the same tests ran against that commit'sresolveAgentIdForRequest. The new conflict-error export was stubbed so this tree's module graph could load. The resolver body is the merge-base function and does not read the session key. 4 failed, 2 passed:AgentSelectionRequiredError(explicit fleet, no default)mainto bescriptsUpgrade from published v2026.9.9
[email protected](bcfc888) from npm.openclaw setup --non-interactivewrote the state dir with agentmain(meta.lastTouchedVersion2026.9.9, noagents.ownership). That CLI enabled chat completions. The mock provider (openai/main-modelon loopback,allowPrivateNetwork) was then in the config, andopenclaw config validateon 2026.9.9 accepted it. Nox-openclaw-session-key.Mock:
model=main-model,Runtime: agent=main | session=agent:main:openai-user:upgrade-thread.Stopped that Gateway and started this head on the same state dir and config. Same shape,
user: "upgrade-thread", contentReply with OPENCLAW_E2E_TURN2, still no session-key header:Mock:
model=main-model, same sessionagent:main:openai-user:upgrade-thread. The provider transcript is the turn-1 user text, assistantOPENCLAW_E2E_TURN1, then the turn-2 user text.lastTouchedVersionstayed2026.9.9.Upgrade from published v2026.10.2
[email protected](b8952d4) from npm.openclaw setup --non-interactive --accept-risk --auth-choice skip --no-install-daemonwrote an isolated state dir with default agentmain(meta.lastTouchedVersion2026.10.2, noagents.ownership). Chat completions were then enabled. The mock provider is this tree'sscripts/e2e/mock-openai-server.mjson loopback (openai/main-model,api: openai-completions,allowPrivateNetwork, context window 200000).openclaw config validateon 2026.10.2 accepted it. Token auth. Nox-openclaw-session-key.OPENCLAW_ALLOW_OLDER_BINARY_DESTRUCTIVE_ACTIONSwas unset for every command.Non-default agent settings on that state, read back with
openclaw config getbefore either Gateway start:agents.defaults.thinkingDefaultlow,agents.defaults.timeoutSeconds900,agents.entries.main.identity.nameUpgrade Trace,agents.entries.main.identity.themeharbor,agents.defaults.model.primaryopenai/main-model.2026.10.2 Gateway startup:
Mock agent turn:
POST /v1/chat/completions,model=main-model. The user text containsReply with OPENCLAW_E2E_TURN1andRuntime: name=Upgrade Trace | agent=main | session=agent:main:openai-user:upgrade-thread | model=openai/main-model | default_model=openai/main-model(host, repo path, and OS fields omitted). A later activity-recap call usesgpt-5.6-lunaand is not the agent turn.Stopped that Gateway. This head is package
2026.10.2(ebf0374), the same version aslastTouchedVersion, so the older-binary guard does not treat it as a downgrade. A plaingateway runon the same state dir, with the guard left enabled, did not print the older-binary refusal. It stopped before listening because the published release's agent database is schema 24 and this tree expects schema 26:That is current main's schema gate, not the version guard.
openclaw doctor --fix --non-interactive --yesfrom this head, still with the override unset, migrated the agent database to schema 26 and finished withDoctor complete. It also disabled skills that are not installed in this environment. The authored agent settings above were unchanged, andlastTouchedVersionstayed2026.10.2.The following plain
gateway runloggedagent model: openai/main-model (thinking=low, fast=off)and[gateway] ready. A chat attempt while startup inspection was still running returned 500 (Agent main has not completed startup inspection and preparation). The log then saidagent database recovered after background inspection and preparation. The same request after that recovery:Mock:
model=main-model. The provider transcript includes the turn-1 user text (still carryingname=Upgrade Trace | agent=main | session=agent:main:openai-user:upgrade-thread), assistantOPENCLAW_E2E_TURN1, then the turn-2 user text. After that turn, the config file still had thinkingDefaultlow, timeoutSeconds900, identity nameUpgrade Trace, themeharbor, primaryopenai/main-model, chat completionstrue, andlastTouchedVersion2026.10.2.agents.ownershipstayed unset. The running Gateway process did not haveOPENCLAW_ALLOW_OLDER_BINARY_DESTRUCTIVE_ACTIONSset.This replaces the earlier v2026.10.2 trace that only continued after
OPENCLAW_ALLOW_OLDER_BINARY_DESTRUCTIVE_ACTIONS=1.AI-assisted. Fully tested.