Skip to content

Add TPasClawAgent + TPasClawServer components for embedding the CLI - #37

Merged
FMXExpress merged 1 commit into
mainfrom
claude/pr34-delphi-component
May 28, 2026
Merged

FMXExpress merged 1 commit into
mainfrom
claude/pr34-delphi-component

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Lets other Delphi / FPC applications embed PasClaw without shelling out to the CLI. Two TComponent descendants in one new unit, plus a tiny extraction from Cmd.Root so command dispatch can be called from non-CLI contexts.

TPasClawAgent

  • Chat(Prompt; out Reply, Err): Boolean — one-shot through the configured provider; OnText / OnToolCall / OnToolResult fire as the tool loop runs.
  • ChatHistory(History; out Reply, Err): Boolean — multi-turn variant.
  • Execute(Cmd, Args): Integer — pass-through to every CLI subcommand via the new DispatchCommand entry point. Mirrors pasclaw <cmd> <args...> byte-for-byte (stdout goes to host process's console).
  • Published: ProviderName, Model, SystemPrompt, MaxIterations, UseTools, UseMCP, UseHashline + OnText / OnToolCall / OnToolResult / OnError.

TPasClawServer

  • Start: Boolean / Stop / IsRunning. Start spawns an internal TThread that drives TGatewayServer.Start + WaitForStop; Stop signals shutdown and joins.
  • Published: BindAddr, Port, MaxIter, Debug, EnableTools, EnableMCP, EnableHashline, ProviderName, Model + OnStarted / OnStopped / OnError.

Refactor

PasClaw.Cmd.Root now exposes function DispatchCommand(const Cmd: string; const Argv: array of string): Integer; which RunRootCommand calls after CLI-only setup (argv parsing, --no-color stripping, log-level wiring). Same stdout byte-for-byte for the CLI; non-CLI callers (the component, tests) can dispatch any subcommand without re-reading ParamStr.

Single-instance contract

PasClaw.MCP.Bridge (GBindings[32]) and PasClaw.Skills.Loader (GSpecs[64]) hold their state in module-level arrays with compile-time fixed handler-slot tables. Only one live TPasClawAgent and one live TPasClawServer per process — each constructor checks a unit-level instance pointer and the second create raises EPasClawInstance with a clear message. Lifting that restriction is a larger refactor of those two units' handler tables, deferred.

Sample

samples/component-console/SampleConsole.dpr — ~30-line console program that creates TPasClawAgent, calls Execute('version', []), then Chat('Say hi in three words.'). Builds under both FPC and Delphi.

Test plan

  • make (FPC) still builds the pasclaw binary — new unit included via Makefile UNIT_DIRS
  • Delphi .dproj still builds — new unit listed in DCCReference + on the search path
  • CLI unchanged: pasclaw version, pasclaw status, etc. print identical output as before the DispatchCommand extraction
  • Sample console builds and runs: prints the version banner, then prints either a reply or an error string
  • Drop TPasClawAgent / TPasClawServer on a Delphi form (with the unit installed) — they appear on the PasClaw palette tab and the published properties are editable in the Object Inspector
  • Single-instance guard: creating a second TPasClawAgent while the first is live raises EPasClawInstance with the documented message; freeing the first then creating another succeeds

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

Two TComponent descendants let other Delphi/FPC applications embed
PasClaw functionality without shelling out to the binary. Neither
duplicates business logic — they compose the same building blocks
(LoadConfig, NewProviderFromConfig, TToolRegistry, RegisterFSTools/
RegisterShellTool, MCP bridge, TGatewayServer, RunToolLoop) the CLI
already uses, adapted to TComponent property/event idioms.

TPasClawAgent
  - Chat(Prompt, out Reply, out Err): Boolean — one-shot through the
    configured provider; OnText / OnToolCall / OnToolResult fire as
    the tool loop runs.
  - ChatHistory(History, out Reply, out Err): Boolean — multi-turn
    variant taking an existing TMessage array.
  - Execute(Cmd, Args): Integer — pass-through to every CLI subcommand
    via the new PasClaw.Cmd.Root.DispatchCommand entry point. Mirrors
    `pasclaw <cmd> <args...>` byte-for-byte (stdout goes to the host
    process's console, same as the CLI).
  - Published: ProviderName, Model, SystemPrompt, MaxIterations,
    UseTools, UseMCP, UseHashline + OnText/OnToolCall/OnToolResult/
    OnError events. Provider/Registry/Config exposed as runtime
    properties for advanced callers.

TPasClawServer
  - Start: Boolean / Stop / IsRunning lifecycle. Start spawns a small
    internal TThread that calls TGatewayServer.Start + WaitForStop;
    Stop signals shutdown and joins.
  - Published: BindAddr, Port, MaxIter, Debug, EnableTools, EnableMCP,
    EnableHashline, ProviderName, Model + OnStarted/OnStopped/OnError.
  - Server property exposes the underlying TGatewayServer for hosts
    that want to inspect it.

Single-instance contract
  PasClaw.MCP.Bridge (GBindings[32]) and PasClaw.Skills.Loader
  (GSpecs[64]) hold their state in module-level arrays with
  compile-time fixed handler-slot tables, so only one live
  TPasClawAgent and one live TPasClawServer are supported per process.
  Each constructor checks a unit-level GAgentInstance / GServerInstance
  pointer; the second create raises EPasClawInstance with a message
  pointing at the limitation. Freeing the first then creating another
  works. The destructor clears the pointer.

Refactor: PasClaw.Cmd.Root now exposes
  function DispatchCommand(const Cmd: string; const Argv: array of string): Integer;
which RunRootCommand calls after CLI-specific setup (argv reading,
--no-color stripping, config-driven log level). This keeps the
dispatch logic in one place and lets non-CLI callers (the component,
tests) invoke commands without re-reading ParamStr. RunRootCommand's
behavior from a user's POV is unchanged — same stdout byte-for-byte.

Build wiring
  - Makefile UNIT_DIRS gains src/pkg/component (FPC).
  - PasClaw.dproj DCC_UnitSearchPath + DCCReference updated (Delphi).
  - samples/component-console/SampleConsole.dpr — minimal console
    program that creates TPasClawAgent, calls Execute('version', []),
    then Chat('Say hi in three words.'). Builds under both compilers
    once the project's PasClaw unit search path is configured.

The Component unit's `procedure Register` lights up the IDE palette
under a `PasClaw` tab when included in a design-time package; we do
not ship a .dpk in this PR — embedders can add the unit to whatever
package they already use.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit f090f9a into main May 28, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 254c2d4b22

ℹ️ 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".

FServer.Start(FAddr, FPort);
FServer.WaitForStop;
except
on E: Exception do FErr := E.ClassName + ': ' + E.Message;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Surface worker startup failures from Start

When the listener cannot bind (for example, the configured port is already in use), the exception is swallowed inside the worker and only stored in FErr, but Start has already returned True and no caller ever reads Err or fires OnError. This leaves embedders thinking the server started successfully while the background thread has already exited, so Start should either perform/confirm the bind synchronously or propagate the worker error before reporting success.

Useful? React with 👍 / 👎.

property EnableMCP: Boolean read FEnableMCP write FEnableMCP default True;
property EnableHashline: Boolean read FEnableHashline write FEnableHashline default True;
property ProviderName: string read FProviderName write FProviderName;
property Model: string read FModel write FModel;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply the server Model property before creating the gateway

The Model property is published for TPasClawServer, but it is never read in the server path (rg FModel only finds the declaration/property here and the agent's use). As a result, embedding code that sets TPasClawServer.Model still serves /v1/chat, /v1/models, and default /v1/chat/completions responses using FConfig.DefaultModel; apply FModel to the loaded config or pass it into TGatewayServer before construction.

Useful? React with 👍 / 👎.

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