Repository navigation
cmd: pasclaw relay worker + cog-relay Replicate cog - #323
Conversation
V1 of the inverse-direction relay: a pasclaw process polls a remote gateway's /v1/relay/poll over SSE, forwards each inference request through the locally-configured provider (default = Cfg.DefaultProvider, or --provider NAME), and POSTs the result to /v1/relay/respond/<id>. Lets a box with a real LLM lend that capacity to a separate gateway box that doesn't: gateway runs `pasclaw gateway` with a Relay provider; worker runs `pasclaw relay --gateway-url ...`; the worker's local Anthropic/OpenAI/Gemini/etc. provider services jobs that reached the gateway from its agent loop. Scope: single-threaded, one Provider.Chat() per event, no tool loop on the worker side (gateway-side owns the agent loop). Reconnects on SSE drop with exponential backoff (1s -> 30s). Bearer auth via PASCLAW_GATEWAY_TOKEN or --gateway-token. Refuses to forward to a provider that is itself a relay (would loop). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Sibling to /cog/ and /cog-build/. Runs the Pascal-side `pasclaw relay` worker as a Replicate predictor: each predict() call seeds a provider config from the operator's chosen API keys / local-server URLs / custom-OpenAI-compat block, spawns the relay subprocess for lifetime_seconds (default 300), then returns the captured worker log. Use case is credential isolation: put one API key on the cog, point N gateways at it. The gateway never holds the key; it just gets results back through the relay queue. Also covers bursty CI (deploy, burst, tear down) and air-gapped gateways (gateway can reach Replicate but not the provider directly). Provider-config shape matches cog-build verbatim (six cloud keys + three local URLs + custom escape hatch). Worker bridge logic itself is the existing `pasclaw relay` from the previous commit -- this just wraps it. README.md updated with the 2026-06-21 entry. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4884ea65ec
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| Result[i].Role := MsgRoleFromString(Obj.GetStr('role', 'user')); | ||
| Result[i].Content := Obj.GetStr('content', ''); |
There was a problem hiding this comment.
Preserve tool-call metadata in relayed history
When a relayed session continues after a tool call, the history includes assistant ToolCalls and tool-result ToolCallId/Name fields, but this decoder rebuilds each message with only role and content before calling the local provider. In that scenario OpenAI/Anthropic/Gemini request builders receive tool-result messages without their required tool-call ids, so gateway-owned tool execution through pasclaw relay can fail or stall after the first tool call. The relay worker needs to carry the tool-call metadata through when decoding the envelope.
Useful? React with 👍 / 👎.
| if R.StatusCode = -1 then | ||
| Root.PutStr('error', R.Content) |
There was a problem hiding this comment.
Propagate upstream error status in relay replies
This only serializes an error when the worker provider returns StatusCode = -1, but normal provider failures such as 401, 429, and 5xx return positive non-2xx status codes with error content. In those cases the worker posts a response without an error field, and the gateway decodes it as a successful relay response (StatusCode := 200), preventing fallback/retry and surfacing the provider error text as the assistant reply. Treat any non-2xx provider status as an error in the relay response.
Useful? React with 👍 / 👎.
…press#324 review) Three review fixes against PR FMXExpress#324. P2 FMXExpress#1: temporal-dead-zone on /#relay deep link. Page loaded with the hash already set ran showTab("relay") in the boot block before the relay tab's `let` / `const` state bindings (relayTimer, relaySetupDone, relayShowToken, RELAY_TOKEN_PLACEHOLDER) had initialised. setupRelayTab() / renderRelaySnippets() then hit ReferenceError on each, and bookmarked Relay URLs landed on a blank tab. Moved all four bindings above the boot block. P2 FMXExpress#2: nonexistent CLI command -- resolved on its own. PR FMXExpress#323 landed `pasclaw relay` into main; the snippet's command is real now. No code change needed. P2 FMXExpress#3: browser snippet relied on EventSource constructor headers, which native browser EventSource silently ignores. Without Authorization the gateway returns 401 on token-protected setups, and even untokened setups returned 400 ("X-Relay-Worker-Id is required"). Two changes: - Gateway (HandleRelayPoll): accept ?worker_id= and ?caps= as fallbacks for the equivalent headers. Mirrors the existing ?token= fallback the bearer-auth gate already uses on /v1/* routes. Header still wins when both are present. - Webui browser snippet: rewritten to use URLSearchParams + URL-only EventSource. Auth + worker identity + capabilities all ride as query params. fetch() for the response POST keeps the Authorization header. - docs/providers-relay.md: the same broken EventSource-headers pattern was in the docs reference implementation. Rewritten to match. Added a "Query-string fallback for browser EventSource workers" note to the wire-protocol section so non-browser workers know they can keep the header path (no extra URL noise, no token-in-server-logs concern). webui.res regenerated. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Two PR FMXExpress#323 review fixes. P1: Tool-call metadata MUST round-trip through the envelope. A multi- turn relayed session that fires a tool call had assistant messages with ToolCalls and tool-result messages with ToolCallId/Name; both got dropped because BuildRelayRequestBody only emitted role+content, and the worker's DecodeMessages only read those two. The second turn then sent OpenAI/Anthropic/Gemini a request with no tool_call_id -> "missing tool_call_id" 400 / silent stall. Encoder now emits the OpenAI-shape fields (tool_calls array, tool_call_id, name) when non-empty; worker decoder reads them back. Same wire fields workers already see for response tool calls (HandleRelayRespond), so any worker that already forwards results forward this too. P2: Workers must encode any non-2xx upstream provider status as a relay error, not as a successful reply. Pre-fix, BuildResponseJSON only treated StatusCode=-1 (socket/TLS failure) as an error. A 429 or 5xx from upstream OpenAI/etc. fell into the else branch with the error JSON body as content, and the gateway's DecodeResponse mapped that to StatusCode := 200 -- bypassing Cfg.Fallbacks entirely and surfacing the provider error text to the agent as the assistant's reply. New ResponseIsError helper treats StatusCode -1 and anything outside [200..299] as error (StatusCode = 0 from older providers still treats as success to preserve compat). Tests: extended src/tests/relay_queue_tests.pas with - tool-call metadata round-trips through the envelope - worker encodes non-2xx upstream status as a relay error covering 429 / 500 / -1 / 200 / 0 paths. Same suite, runs via `make test-relay-queue`. All 20 cases green. BuildRelayWorkerResponseJSON is now exported from PasClaw.Cmd.Relay solely so the test program can drive the encoder directly. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
PR FMXExpress#326 review P2: a browser worker page served from a different origin than the gateway -- the documented browser/WebLLM case -- got blocked by CORS before the bearer-token / worker-id checks ever ran. The query-string fallback fix in the previous commit was necessary (EventSource can't set headers) but not sufficient (CORS blocks all of it). Adds permissive CORS on the three /v1/relay/* endpoints: - EmitRelayCors: Access-Control-Allow-Origin: *, Allow-Methods: GET, POST, OPTIONS, Allow-Headers reflecting the browser's preflight request (or a sensible default), Max-Age: 600 (10-minute preflight cache). - HandleRelayOptionsPreflight: 204 + Allow-* headers for the CORS preflight request, before the bearer-token gate (per the CORS spec, preflights must not carry credentials). - OnCommandOther wired on TIdHTTPServer to receive OPTIONS; routes /v1/relay/* preflights to HandleRelayOptionsPreflight and 405s everything else. - HandleRelayPoll, HandleRelayRespond, HandleRelayStatus stamp CORS headers on the actual response. HandleRelayStatus's signature gained an ARequest parameter so it can read Access-Control-Request-Headers like the others. - EmitSSEResponseHeaders now copies AResp.CustomHeaders into the raw HTTP response line. The SSE handler bypasses Indy's response writer to fix the chunked-encoding bug; that bypass silently dropped any CORS headers EmitRelayCors stamped, so /v1/relay/poll's SSE response was missing them. Now passes through cleanly. - Auth-gate intact: GET /v1/relay/poll without a token still returns 401 + WWW-Authenticate. The CORS preflight doesn't require auth, but the subsequent actual request does. - docs/providers-relay.md: new "CORS" callout under the wire protocol section explaining the policy + why permissive is safe (token = auth boundary, no cookies). - webui browser snippet: comment updated to note CORS is handled server-side, no client setup required. Why permissive (Allow-Origin: *)? The relay endpoints are guarded by a bearer token (or the ?token= query fallback). Anyone reaching them already had to present credentials. Echoing the Origin header (vs hard-allowlisting) would require operators to configure a CORS allowlist, which buys nothing security-wise because the token IS the gate. Allow-Origin: * is safe here specifically because we don't use credentials=include -- cookies aren't involved, the token rides as a header or query param. Live smoke (port 18889, token gated): - OPTIONS /v1/relay/respond/req_x -> 204 + Allow-* headers - GET /v1/relay/poll w/ Origin -> 200 SSE + CORS headers - GET /v1/relay/status w/ Origin -> 200 JSON + CORS headers - POST /v1/relay/respond w/ Origin -> 200 + CORS headers - GET /v1/relay/poll w/o token -> 401 + WWW-Authenticate This branch (claude/webui-relay-fixes-v2) replaces the PR FMXExpress#326 stack: rebased the two FMXExpress#324 commits + the FMXExpress#325 tool-metadata fix + this CORS commit straight onto current main. Closes the merge conflict on PR FMXExpress#326 (stale base after PR FMXExpress#323 merged) and addresses the P1 tool-metadata review by carrying FMXExpress#325's fix into this PR. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Summary
pasclaw relayCLI command: SSE pull-worker that polls a remote PasClaw gateway's/v1/relay/poll, forwards each inference job through the locally-configured provider, and POSTs the result to/v1/relay/respond/<id>. Bearer auth viaPASCLAW_GATEWAY_TOKENor--gateway-token; reconnects on drop with 1s→30s exponential backoff; refuses to forward through a relay-kind provider (would loop). Single file (src/cmd/PasClaw.Cmd.Relay.pas, ~430 LOC) using IndyTIdHTTP.Getwith a custom destinationTStreamthat parses SSE frames inline and dispatches synchronously.cog-relay/Replicate cog: wrapspasclaw relayas a Replicate predictor. Same provider-config plumbing ascog-build/(six cloud API-key Secrets + three local OpenAI-compat URLs + custom-kind escape hatch). Eachpredict()call spawns the worker forlifetime_seconds(default 300), SIGTERMs at expiry. Use case: one $-budget API key on the cog lends compute to N gateways that never see the key.Test plan
make all)relaysubcommandpasclaw relay --helprenders without errorspasclaw relaywith missing flags prints structured CLI errordefault_provider=relay, token configured/v1/relay/statusshowedconnected_workers: 1, correct id + capsPOST /v1/chatenqueued a request → worker received it via SSE → calledProvider.Chat()→ posted error back → response surfaced to clienttotal_enqueued: 1,total_failed: 1,requests_seen: 1on the workerpython3 -m py_compile cog-relay/predict.pyclean🤖 Generated with Claude Code
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code