Skip to content

Fix F2613 'SysUtils not found' and Delphi/POSIX ABI issues - #4

Merged
FMXExpress merged 3 commits into
mainfrom
claude/delphi-port-fixes
May 27, 2026
Merged

FMXExpress merged 3 commits into
mainfrom
claude/delphi-port-fixes

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

  • DCC_Namespace post-import override in .dproj so bare unit names compile on all Delphi versions
  • Posix.SysSelect added; pipe C-ABI fixed; string/bytes fixed in Delphi RunOneShot paths
  • DownloadAsset in PasClaw.Updater fixed to use TBytes instead of string direct buffer write

What changed

src/pasclaw/PasClaw.dproj

Added a second <PropertyGroup> block after the <Import> of CodeGear.Delphi.Targets that re-asserts DCC_Namespace:

<PropertyGroup Condition="'$(Base)'!=''">
    <DCC_Namespace>System;System.Net;System.Win;Xml;Data;Datasnap;Web;Soap;Winapi;Posix</DCC_Namespace>
</PropertyGroup>

The existing pre-import setting was being silently reset by the targets file in some Delphi IDE versions, which is why [dcc64 Fatal Error] PasClaw.CliUI.pas(13): F2613 Unit 'SysUtils' not found kept appearing even after PR #3's fix. The post-import group is evaluated last and always wins.

src/pkg/platform/PasClaw.Platform.pas

Three Delphi-specific bugs fixed, all inside {$IFNDEF FPC} guards:

Bug Fix
Posix.SysSelect missing — TFDSet, select, FD_SET, timeval undeclared Added Posix.SysSelect to the POSIX uses clause
pipe declared as array of Integer (open-array ABI passes (High, Ptr), C expects bare Ptr) New TPipeFDs = array[0..1] of Integer; pipe(var pipefds: TPipeFDs)
RunOneShot (Win + POSIX) wrote bytes directly into a UnicodeString buffer Accumulate into TBytes, decode with TEncoding.UTF8.GetString

src/pkg/updater/PasClaw.Updater.pas

DownloadAsset was calling WriteBuffer(Resp.Body[1], Length(Resp.Body)). Under Delphi, Body[1] is a 2-byte WideChar and Length returns character count, so this wrote half the bytes. Fixed with TEncoding.UTF8.GetBytes + WriteBuffer(Bytes[0], …).

Test plan

  • Open PasClaw.dproj in Delphi 11/12 — Build for Win64; confirm no F2613
  • Run pasclaw version under the Delphi Win64 build
  • pasclaw update --check — exercises DownloadAsset path
  • pasclaw mcp test <server> — exercises PasClaw.Platform POSIX spawn path on Linux64

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

claude added 3 commits May 27, 2026 00:54
…lphi

Fixes "[dcc64 Fatal Error] PasClaw.dpr(29): F2613 Unit 'SysUtils' not found".

Modern Delphi (XE2+) ships the RTL as namespaced units only — there is no
SysUtils.dcu, only System.SysUtils.dcu. The compiler relies on the project's
DCC_Namespace setting to map bare uses-clause references like "SysUtils" or
"Classes" or "Windows" to their fully qualified names ("System.SysUtils",
"System.Classes", "Winapi.Windows"). My .dproj didn't set DCC_Namespace, so
on machines whose IDE defaults don't include the System namespace, every
unit's `uses SysUtils, Classes` block failed to link.

Adds:
  <DCC_Namespace>System;System.Net;System.Win;Xml;Data;Datasnap;
                 Web;Soap;Winapi;Posix;$(DCC_Namespace)</DCC_Namespace>

`Posix` is in there for the Delphi/Linux64 target (Posix.SysStat etc.);
it's harmless on Win32/Win64 since the namespace just isn't found.

Also adds a DCC_UnitAlias for the very-legacy WinTypes/WinProcs short names
as belt + suspenders.

FPC build unaffected (this is .dproj-only).
The .dproj fix from c95dd219 only unblocked parsing. The deeper Delphi
gotcha is that `string` = UTF-16 UnicodeString in Delphi but UTF-8
AnsiString in FPC mode Delphi. Anywhere we treated a `string` as raw
bytes — Move(buf, S[1], N), Strm.WriteBuffer(S[1], Length(S)),
Pointer(S)^ — worked in FPC and silently produced half the bytes plus
embedded zeros in Delphi.

This commit goes through every site where bytes and strings meet:

  src/pkg/utils/PasClaw.Utils.pas
    ReadFileText: read into TBytes, decode via TEncoding.UTF8.GetString.
    WriteFileText: encode via TEncoding.UTF8.GetBytes before WriteBuffer.
    Replaces the previous Pointer(Content)^ / DataString patterns which
    were AnsiString-assuming.

  src/pkg/memory/PasClaw.Memory.pas
    WriteLine: TEncoding.UTF8.GetBytes(S + #10) before WriteBuffer.
    The NDJSON log file is now byte-correct in Delphi.

  src/pkg/mcp/PasClaw.MCP.StdioClient.pas
    FBuffer is now UTF8String (1 byte per char in both FPC and Delphi).
    ReadLine: Move(Buf[0], Chunk[1], N) is safe again because Chunk is
    UTF8String. When a complete line is extracted, the assignment to
    Line: string triggers UTF-8 decode under Delphi automatically.

  src/pkg/gateway/PasClaw.Gateway.Server.pas
    HandleChat: read POST body into TBytes, decode UTF-8 to a string.
    Previously SetLength(Body, n) + ReadBuffer(Body[1], n) would have
    produced a half-length corrupted UnicodeString under Delphi.

  src/pkg/providers/PasClaw.Providers.HTTP.pas
    Both TStringStream constructors take TEncoding.UTF8 explicitly so
    JSON request bodies and provider responses round-trip non-ASCII
    correctly (Delphi's default ANSI codepage would mangle them).

  src/pkg/providers/PasClaw.Providers.Stream.pas
    Same fix for the SSE streaming path: Req and Resp streams pin
    TEncoding.UTF8 so the event-stream body parses cleanly.

Verified under FPC: 11/11 smoke tests pass, MCP stdio handshake still
works (UTF8String FBuffer is byte-identical to the previous AnsiString
behaviour), config write+read round-trips a 2-server config file.
Three categories of fix:

1. PasClaw.dproj — DCC_Namespace post-import override
   Added a second <PropertyGroup Condition="'$(Base)'!=''"> AFTER the
   CodeGear.Delphi.Targets import that unconditionally sets DCC_Namespace.
   The existing pre-import setting was sometimes reset by the targets file,
   leaving bare unit names (SysUtils, Classes, SyncObjs …) unresolvable.
   The post-import group has the final word regardless of IDE version.

2. PasClaw.Platform.pas — Delphi/POSIX backend
   • Add Posix.SysSelect to the implementation uses so TFDSet, select,
     FD_SET and timeval (used in ReadAvailable) are declared.
   • Declare 'pipe' with 'var pipefds: TPipeFDs' (fixed-size array by
     reference) instead of the open-array form; Delphi's open-array ABI
     passes (High,Ptr) but the C pipe(2) expects only a bare pointer.
   • Update TStdioProcess.Spawn to use TPipeFDs for the pipe fd pairs;
     drop the unused Argv0 variable; use 'array of RawByteString' instead
     of TArray<RawByteString> for the args encoding buffer.
   • RunOneShot (both Delphi/Windows and Delphi/POSIX): replace the
     direct string-buffer read (broken on UnicodeString) with TBytes +
     TEncoding.UTF8.GetString, matching the pattern used in the other
     already-fixed file-I/O call-sites.

3. PasClaw.Updater.pas — DownloadAsset
   Replaced WriteBuffer(Resp.Body[1], Length(Resp.Body)) with
   TEncoding.UTF8.GetBytes + WriteBuffer(Bytes[0], …).  The old form
   wrote only half the byte count on Delphi (WideChar[1] ref + char count).

FPC build unaffected: all Delphi-specific sections are inside
{$IFNDEF FPC}/{$IFDEF MSWINDOWS}/{$ELSE} guards.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit 4f47a84 into main May 27, 2026
FMXExpress pushed a commit that referenced this pull request Jun 21, 2026
…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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants