Repository navigation
Delphi UTF-8 / byte-buffer fixes (stacks on PR #2) - #3
Merged
Merged
Conversation
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.
This was referenced May 27, 2026
FMXExpress
pushed a commit
that referenced
this pull request
Jun 16, 2026
…self-shadow inherit Three Codex P2 findings, all legit. P2 #1 -- the profile-selection block sat under `if FileExists(Path)` so `pasclaw agent --profile low-token` and `PASCLAW_PROFILE=low-token` silently used plain defaults on a fresh deploy that hadn't created config.json yet. Moved profile resolution OUT of the FileExists guard so it runs unconditionally; config.json is then layered on top when it exists. The third-tier "profile field in config.json" fallback is still gated on HasConfigFile (only meaningful when the file exists). P2 #2 -- `pasclaw profile use <name>` wrote the "profile" key by hand-crafting JSON, so any subsequent SaveConfig() (auth login, model set, /v1/config PUT, the TUI's settings tab, ...) would drop the key because TConfig didn't know about it. Added Profile: string field to TConfig that round-trips through FromJSON / ToJSON. DoUse now goes through LoadConfig + SetField + SaveConfig like every other config-mutating command. P2 #3 -- the documented "fork a built-in" pattern -- $PASCLAW_HOME/profiles/low-token.json containing `{"_inherits":["low-token"], "tool_output_cap":4096}` -- false-cycled. LookupProfile returned the user file for both the child AND its inherited parent (because both lookups asked for "low-token"), and the resolver then saw the same name twice in Visited and reported a cycle. Added a LookupProfileInternal overload with a `BypassUserShadow` switch + threaded NameToBypass through ResolveInto. When a user-shadow's _inherits contains its own name, the recursive parent lookup bypasses the user file and reaches the built-in directly. Visited is briefly popped + re-added across the recursive call so the cycle guard doesn't false-fire. Tests: TestProfileWithoutConfigFile P2 #1 TestSaveConfigPreservesProfile P2 #2 (round-trip + SaveConfig preserves through a second mutation) TestSelfShadowInherit P2 #3 (verifies two-layer resolution: built-in first, user override second) All existing test-config-profile, test-config-secret-merge, test- config-env-subst, test-plan-build-mode, test-loop-shaping-defaults remain green. Live-verified each fix end-to-end via the CLI.
FMXExpress
pushed a commit
that referenced
this pull request
Jun 16, 2026
PR #295 review feedback, two legit fixes + one deferred. * P2 #1 (generation-number): ExtractTextAndMetadata's primary path looked content streams up via Format('%d 0 obj', [ObjID]), hardcoding generation 0. An incrementally-updated PDF whose page /Contents references "12 1 R" would silently fall through to the empty-text branch. Switched to ObjIndex.TryGetValue, which the parser already builds via BuildObjectIndex and which records the position of every <id> <gen> obj regardless of gen. Stream-bounds check now uses 'endobj' (mirroring GetObjectStreamData) instead of the next 'obj' keyword. * P2 #3 (positioned-Tj spacing): "BT (Hello) Tj 50 0 Td (World) Tj ET" used to extract "HelloWorld". ParseTextOperators now detects Td/TD/Tm/T*/'/" position operators and flips a NeedSpaceBeforeNext flag; the next paren-close or hex-close emits via a local EmitWithSpacing helper that prepends a single space. The existing TJ-array negative-number spacing (>120 units = word boundary) is unchanged and still handles intra-TJ glyph runs. * P2 #2 (per-page font resource map): BuildResourceFontMap is still document-wide -- proper per-page maps would restructure GetPageContentStreamIDs to thread a TDictionary per content stream through ParseTextOperators, which is a bigger refactor than this PR warrants. Added a header comment explaining the known limitation: single-font and same-font-across-pages docs work, and the CP1252 fallback keeps ASCII readable when /ToUnicode misses on per-page-subset fonts (LaTeX output). New regression tests in src/tests/kb_pdf_extract_tests.pas: * TestPositionedTjSpacing -- "Foo Bar" via Td between Tj operands. * TestNonZeroGenerationContent -- "4 1 obj" content stream resolves. End-to-end smoke: `kb add` + `kb search "cross reference"` on a PDF with three position-separated Tj operands now returns "Cross reference Document" (was "CrossreferenceDocument").
FMXExpress
pushed a commit
that referenced
this pull request
Jun 16, 2026
Three Delphi-correctness fixes flagged by Codex. * P2 #1 (UTF-8 decode in ReadHead): Move(Buf[0], Result[1], N) on a UnicodeString reinterprets UTF-8 bytes as UTF-16 code units and leaves the second half of the allocation as garbage. Now goes through TEncoding.UTF8.GetString -- same path ReadFileText uses in PasClaw.Utils. * P2 #2 (UTF-8 write of AGENTS.md): TFileStream.WriteBuffer(Body[1], Length(Body)) under Delphi writes Length-in-chars (UTF-16 units) bytes of UTF-16 memory, producing a half-size NUL-laced file. Replaced with WriteFileText, which encodes properly under both compilers. * P2 #3 (/init unwired in positioned TUI): SubmitInput's slash dispatcher now recognises /init. To keep the framebuffer clean (Provider.Chat status output would corrupt the rendered display), the action goes through a new stdio-free RunInit worker that returns a TInitOutcome record; the positioned TUI reports the result via Flash, the CLI's Cmd_Init_Run wraps the same worker with PrintLn/PrintErr. Public surface change: PasClaw.Cmd.Init now exports RunInit + TInitOutcome so the TUI (and any future programmatic caller, e.g. a /v1/init gateway endpoint) can drive the bootstrap without screen-scraping CLI output. New tests: * TestDigestUtf8 -- writes a README with a multibyte UTF-8 codepoint (`é` as C3 A9) and asserts it survives the ReadHead/digest path. Pins the regression. * TestRunInitArgFailures -- exercises the no-network arg-validation paths of RunInit (missing dir, existing AGENTS.md without --force) and asserts Status / ErrorMsg shape.
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).
4 tasks done
khongten001
pushed a commit
to khongten001/PasClaw
that referenced
this pull request
Jul 13, 2026
…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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Stacks on top of PR #2. The
DCC_Namespacefix in PR #2 unblocked parsing under Delphi, but exposed a deeper portability bug that I'd missed: anywhere I treated astringas a raw byte buffer, the code silently produces half the bytes (plus embedded zeros) under Delphi becausestring= UTF-16UnicodeStringin Delphi vs UTF-8AnsiStringin FPC mode Delphi.This PR walks every byte/string boundary in the project and routes it through explicit
TEncoding.UTF8orUTF8Stringso the bytes on the wire / on disk are identical in both compilers.What was broken in Delphi (and silent in FPC)
Strm.WriteBuffer(S[1], Length(S))string= AnsiString,S[1]is a byte,Lengthreturns bytesstring= UnicodeString,S[1]is a 2-byte WideChar,Lengthreturns code units, so we write half the bytesPointer(S)^cast as bytesMove(Buf, S[1], N)to fill a stringTStringStream.Create(s)SetLength(Body, n)+ReadBuffer(Body[1], n)Fixes (file by file)
src/pkg/utils/PasClaw.Utils.pas—ReadFileTextreads intoTBytesthen decodes withTEncoding.UTF8.GetString.WriteFileTextencodes withTEncoding.UTF8.GetBytesbeforeWriteBuffer. Drops theTStringStream.DataStringtrick which was ANSI-default in Delphi.src/pkg/memory/PasClaw.Memory.pas—WriteLinecallsTEncoding.UTF8.GetBytes(S + #10)before writing. The NDJSON log is now byte-identical between toolchains.src/pkg/mcp/PasClaw.MCP.StdioClient.pas—FBufferandChunkare nowUTF8String(1 byte per char in both FPC and Delphi). TheMove(Buf[0], Chunk[1], N)accumulator is safe again; when a complete#10-terminated line is extracted, the assignment toLine: stringtriggers UTF-8 decode under Delphi automatically.src/pkg/gateway/PasClaw.Gateway.Server.pas—HandleChatreads the POST body intoTBytesand decodes UTF-8 to a string. PreviouslySetLength(Body, n) + ReadBuffer(Body[1], n)produced a half-length corruptedUnicodeStringunder Delphi.src/pkg/providers/PasClaw.Providers.HTTP.pas— bothTStringStreamconstructors pinTEncoding.UTF8so JSON bodies (request and response) round-trip non-ASCII correctly. Delphi's default ANSI codepage was the bug.src/pkg/providers/PasClaw.Providers.Stream.pas— same fix for the SSE streaming path'sReqandRespstreams.Audit method
grep -rnfor the five patterns above; reviewed every hit. The remainingLength(S)/S[i]usages are pure ASCII parsing (cron field splitter, slash-command detection, template{{ }}scanner) where character vs byte semantics happen to coincide.Test plan
make) — 268k lines, 0 errorsmake smoke— all 11 commands OKPasClaw.dprojin Delphi 11/12 — Build for Win64pasclaw mcp testagainst a stdio MCP server works under Delphipasclaw agentPOST to/v1/chatbody decodes correctly under DelphiCommits
b86bde7Delphi string-as-bytes fixes: explicit UTF-8 at every byte boundaryGenerated by Claude Code