Repository navigation
Compose nanobot-style sectioned system prompt with PasClaw identity - #50
Conversation
Until now the LLM had no built-in idea what it was. PasClaw forwarded
whatever single string the caller put into Options.SystemPrompt and
nothing else — `pasclaw agent "hi"` with no --system flag literally
sent an empty system prompt. Picoclaw and nanobot both compose a much
richer prompt out of identity / workspace / memory / skill catalog /
rules, joined by "\n\n---\n\n" so each section reads as a clearly
delimited block. This change brings PasClaw to feature parity, with
the persona content the user actually wants.
New unit src/pkg/agent/PasClaw.Agent.Prompt.pas exposes one helper:
BuildSystemPrompt(Cfg: TConfig; const UserSys: string): string
Sections emitted in order, skipping any that are empty:
IDENTITY "You are PasClaw, the best 10x programmer in the world."
+ the language list + version + runtime string. The
runtime string is OS + arch + compiler (Free Pascal or
Delphi) — no Python version, since we are not a Python
program.
WORKSPACE Resolved absolute paths inside ~/.pasclaw so the model
can rely on them: memory dir, skills dir, logs dir.
MEMORY Verbatim contents of <home>/workspace/memory/MEMORY.md
if the file exists. Lets the user pin facts that
persist across sessions (same convention picoclaw and
nanobot already use).
SKILLS One line per registered skill, pulled from
PasClaw.Skills.Loader. Only emitted when at least one
skill is actually installed.
RULES Five behavioral rules:
1. ALWAYS use tools when an action is needed.
2. Be precise; match the language's native idioms.
3. Verify changes after editing code.
4. Truncated tool calls — if fs_write returns
"missing required argument: content" (see PR #41),
re-emit or switch to fs_edit_hashline.
5. Memory — when something seems memorable update
<abs>/workspace/memory/MEMORY.md.
USER Whatever the caller passed via --system / the component
property / the request body. Appended last so the user
can override or extend by recency in the prompt.
Sections are joined by "\n\n---\n\n" so the model sees them as
horizontal-rule-separated blocks — matches picoclaw's
renderPromptPartsLegacy and HKUDS/nanobot's build_system_prompt
joiner exactly.
Also exposes:
HasSystemMessage(const Messages: array of TMessage): Boolean
Used by the /v1/chat/completions gateway path to decide whether to
inject the composed prompt or honor a client-supplied system message.
Wired into all four sites that previously set Options.SystemPrompt:
src/cmd/PasClaw.Cmd.Agent.pas
BuildLoopConfig grows a Cfg parameter and passes it through.
--system "..." text is now appended as the USER section, not
used as the entire system prompt — bare-bones invocations
(`pasclaw agent "hi"`) get the full identity + memory + rules
for free.
src/pkg/gateway/PasClaw.Gateway.Server.pas
/v1/chat — the legacy single-message endpoint — always uses the
composed prompt.
/v1/chat/completions — the OpenAI-compatible endpoint — uses
HasSystemMessage(Msgs) to gate: bare-bones clients get the
composed prompt, but third-party tooling that supplies its own
persona via the messages array wins (we don't want to silently
override an integrating app's character).
src/pkg/component/PasClaw.Component.pas
TPasClawAgent.SystemPrompt is now treated as additive — the
composed identity is always there, the property text is appended.
Memory and skill catalog reads swallow their errors (missing
MEMORY.md or a misconfigured skill manifest just means that section
is skipped, not a hard failure).
Build wiring: src/pkg/agent added to Makefile UNIT_DIRS and
PasClaw.dproj DCC_UnitSearchPath; the new unit added to the
DCCReference list between skills and memory.
On nanobot vs picoclaw: I checked both before writing this. Picoclaw
ships a "You are picoclaw, a helpful AI assistant" persona baked into
the identity preamble. Nanobot HKUDS does NOT — its identity.md
template is pure scaffolding (runtime, workspace paths, tool
contract); the persona lives in user-editable workspace files
(AGENTS.md, SOUL.md, USER.md). PasClaw takes the picoclaw approach
for the persona but the nanobot approach for sectioning structure.
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: 645d45797f
ℹ️ 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".
| if Desc = '' then | ||
| Lines.Add('- `' + Skills[i].Name + '`') | ||
| else | ||
| Lines.Add('- `' + Skills[i].Name + '` — ' + Desc); |
There was a problem hiding this comment.
Use the actual registered skill tool names
When any installed skill is present, this section tells the model to call the skill by Skills[i].Name, but RegisterSkills registers the provider tool as skill_ + name (PasClaw.Skills.Loader.pas). For a manifest named weather, the prompt advertises weather even though the callable tool is skill_weather, so models following the new system prompt will try a nonexistent tool or avoid the available one.
Useful? React with 👍 / 👎.
| Result.MaxIterations := A.MaxIterations; | ||
| Result.Options := DefaultChatOptions; | ||
| Result.Options.SystemPrompt := A.SystemPrompt; | ||
| Result.Options.SystemPrompt := BuildSystemPrompt(Cfg, A.SystemPrompt); |
There was a problem hiding this comment.
Do not advertise tools in no-tools sessions
When the CLI is run with pasclaw agent --no-tools, Reg remains nil, so RunToolLoop sends an empty tool list, but this call still builds a prompt that can include installed skills and a rule to always use tools. In that context the model is explicitly instructed to use capabilities that are disabled for the request, which can produce unusable responses instead of respecting --no-tools.
Useful? React with 👍 / 👎.
Windows commands, regex allow-lists, stale-registry no-tools prompt,
sample build instructions
Five legitimate issues raised in review of the prior commit.
1. Case-sensitive path comparison on POSIX
PathInsideDirectory used SameText, which treats
/tmp/workspace and /tmp/Workspace as the same prefix on
case-sensitive filesystems. If both happen to exist, a
restricted fs_read for /tmp/Workspace/secret would pass the
prefix check, then the actual ReadFileText opens the
differently-cased path — sandbox bypass. New PathsEqual
helper does the right thing per OS:
{$IFDEF MSWINDOWS} SameText (Windows is case-insensitive)
{$ELSE} A = B (case-sensitive)
2. Relative-path bypass in shell sandbox
HasOutsideAbsolutePath only fired on '/'-prefixed tokens, so
`cd .. && cat secret` slipped through silently with
restrict_to_workspace=true: no absolute path appeared, and
RunOneShot inherited the parent's cwd so the relative paths
resolved wherever pasclaw was launched.
Three defenses, layered:
a) cd / chdir / pushd / popd added to ForbiddenTokens so
the model cannot change cwd inside the shell.
b) New HasTraversalToken refuses any whitespace-separated
token containing '..'. Catches `cat ../secret`,
`(cd ..)`, `bash -c '...cd..'`, etc.
c) RunOneShot grows a WorkingDir parameter, plumbed through
all four platform impls (FPC POSIX/Windows via
TProcess.CurrentDirectory; Delphi Windows + Delphi POSIX
via ChDir/restore around TStdioProcess.Spawn). Tool_Shell
passes CurrentWorkspace when RestrictionActive, so even
a token the denylist missed runs from the workspace and
cannot reach files above it via relative paths.
3. Windows command coverage
The denylist was POSIX-shaped: rm, mkfs, dd, etc. cmd.exe and
PowerShell users had no equivalent. Added 9 Windows tokens
(del, erase, rd, rmdir, format, attrib, takeown, icacls,
runas) and 17 PowerShell substrings (del /f|q|s, rd /s,
rmdir /s, format /q, powershell -e/-en/-enc/-ec,
-encodedcommand, iex (, invoke-expression,
[convert]::frombase64, [text.encoding],
.getstring([byte[], set-executionpolicy). Picoclaw's
windowsDenyPatterns set is the reference. Patterns are
checked unconditionally — running shell_exec on Linux today
does not mean a portable policy should let `format c:`
through if the same config is deployed on Windows tomorrow.
4. Regex allow-lists (FPC + Delphi)
New unit src/pkg/tools/PasClaw.Tools.Regex.pas wraps the two
regex engines behind one call:
{$IFDEF FPC} uses RegExpr.TRegExpr
{$ELSE} uses System.RegularExpressions.TRegEx
Both are bundled with their respective compilers (no extra
package install needed; FPC ships RegExpr in fcl-regexpr,
Delphi has System.RegularExpressions since XE). Invalid
patterns return False rather than raising so a malformed
regex in config.json does not crash the agent — the sandbox
layer treats False the same as "no allowlist match" and
falls through to the workspace check.
AllowReadPaths / AllowWritePaths now match via the regex
wrapper instead of the in-unit glob matcher. PCRE syntax —
^/tmp/.*, ^/usr/(include|share)/.*, etc. README updated.
Existing glob users migrate: '/tmp/*' becomes '^/tmp/.*'
(anchor the prefix, replace * with .*).
5. Stale FRegistry leaks tools into "no tools" prompt
TPasClawAgent.EnsureRegistry caches FRegistry and only
honours FUseTools when the registry is nil. A component used
with UseTools=True, then flipped to False, would build a
"No tools in this session" prompt while still sending the
cached registry to RunToolLoop — contradictory instructions
plus actual tool access. Single source of truth is the
registry handed to RunToolLoop. Every BuildSystemPrompt call
site now derives the third arg from `<scope>.Registry <> nil`:
Cmd.Agent - Reg parameter
Component - Cfg.Registry
Gateway - LoopCfg.Registry
PR #51's content (skill_ tool name prefix + no-tools rules +
ToolsEnabled parameter) was also reapplied here. The PR was
merged but the squash collapsed only PR #50's commits into
main, so the actual changes were lost.
Sample (samples/component-console/SampleConsole.dpr):
The header comment shipped a literal
`fpc -Fu../../src/cmd -Fu../../src/pkg/...` instruction. The
'...' isn't an FPC wildcard — it tried to use '...' as a
directory name and failed. Also the sample needs ~25 unit
search paths plus three Indy paths, not just two. Replaced
the broken instruction with a real Makefile at
samples/component-console/Makefile that re-uses the top-level
UNIT_DIRS list re-rooted at the repo root. Comment now points
at it.
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Windows commands, regex allow-lists, stale-registry no-tools prompt,
sample build instructions
Five legitimate issues raised in review of the prior commit.
1. Case-sensitive path comparison on POSIX
PathInsideDirectory used SameText, which treats
/tmp/workspace and /tmp/Workspace as the same prefix on
case-sensitive filesystems. If both happen to exist, a
restricted fs_read for /tmp/Workspace/secret would pass the
prefix check, then the actual ReadFileText opens the
differently-cased path — sandbox bypass. New PathsEqual
helper does the right thing per OS:
{$IFDEF MSWINDOWS} SameText (Windows is case-insensitive)
{$ELSE} A = B (case-sensitive)
2. Relative-path bypass in shell sandbox
HasOutsideAbsolutePath only fired on '/'-prefixed tokens, so
`cd .. && cat secret` slipped through silently with
restrict_to_workspace=true: no absolute path appeared, and
RunOneShot inherited the parent's cwd so the relative paths
resolved wherever pasclaw was launched.
Three defenses, layered:
a) cd / chdir / pushd / popd added to ForbiddenTokens so
the model cannot change cwd inside the shell.
b) New HasTraversalToken refuses any whitespace-separated
token containing '..'. Catches `cat ../secret`,
`(cd ..)`, `bash -c '...cd..'`, etc.
c) RunOneShot grows a WorkingDir parameter, plumbed through
all four platform impls (FPC POSIX/Windows via
TProcess.CurrentDirectory; Delphi Windows + Delphi POSIX
via ChDir/restore around TStdioProcess.Spawn). Tool_Shell
passes CurrentWorkspace when RestrictionActive, so even
a token the denylist missed runs from the workspace and
cannot reach files above it via relative paths.
3. Windows command coverage
The denylist was POSIX-shaped: rm, mkfs, dd, etc. cmd.exe and
PowerShell users had no equivalent. Added 9 Windows tokens
(del, erase, rd, rmdir, format, attrib, takeown, icacls,
runas) and 17 PowerShell substrings (del /f|q|s, rd /s,
rmdir /s, format /q, powershell -e/-en/-enc/-ec,
-encodedcommand, iex (, invoke-expression,
[convert]::frombase64, [text.encoding],
.getstring([byte[], set-executionpolicy). Picoclaw's
windowsDenyPatterns set is the reference. Patterns are
checked unconditionally — running shell_exec on Linux today
does not mean a portable policy should let `format c:`
through if the same config is deployed on Windows tomorrow.
4. Regex allow-lists (FPC + Delphi)
New unit src/pkg/tools/PasClaw.Tools.Regex.pas wraps the two
regex engines behind one call:
{$IFDEF FPC} uses RegExpr.TRegExpr
{$ELSE} uses System.RegularExpressions.TRegEx
Both are bundled with their respective compilers (no extra
package install needed; FPC ships RegExpr in fcl-regexpr,
Delphi has System.RegularExpressions since XE). Invalid
patterns return False rather than raising so a malformed
regex in config.json does not crash the agent — the sandbox
layer treats False the same as "no allowlist match" and
falls through to the workspace check.
AllowReadPaths / AllowWritePaths now match via the regex
wrapper instead of the in-unit glob matcher. PCRE syntax —
^/tmp/.*, ^/usr/(include|share)/.*, etc. README updated.
Existing glob users migrate: '/tmp/*' becomes '^/tmp/.*'
(anchor the prefix, replace * with .*).
5. Stale FRegistry leaks tools into "no tools" prompt
TPasClawAgent.EnsureRegistry caches FRegistry and only
honours FUseTools when the registry is nil. A component used
with UseTools=True, then flipped to False, would build a
"No tools in this session" prompt while still sending the
cached registry to RunToolLoop — contradictory instructions
plus actual tool access. Single source of truth is the
registry handed to RunToolLoop. Every BuildSystemPrompt call
site now derives the third arg from `<scope>.Registry <> nil`:
Cmd.Agent - Reg parameter
Component - Cfg.Registry
Gateway - LoopCfg.Registry
PR #51's content (skill_ tool name prefix + no-tools rules +
ToolsEnabled parameter) was also reapplied here. The PR was
merged but the squash collapsed only PR #50's commits into
main, so the actual changes were lost.
Sample (samples/component-console/SampleConsole.dpr):
The header comment shipped a literal
`fpc -Fu../../src/cmd -Fu../../src/pkg/...` instruction. The
'...' isn't an FPC wildcard — it tried to use '...' as a
directory name and failed. Also the sample needs ~25 unit
search paths plus three Indy paths, not just two. Replaced
the broken instruction with a real Makefile at
samples/component-console/Makefile that re-uses the top-level
UNIT_DIRS list re-rooted at the repo root. Comment now points
at it.
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Summary
Until now the LLM had no built-in idea what it was.
pasclaw agent "hi"with no--systemflag literally sent an empty system prompt — the model picked a personality from whatever the underlying provider defaulted to. Picoclaw and nanobot both compose a much richer prompt out of identity + workspace + memory + skill catalog + rules, joined by\n\n---\n\nso each section reads as a clearly delimited block. This PR brings PasClaw to feature parity, with the persona you wanted ("best 10x programmer in the world").What the model now sees on a bare
pasclaw agent "hi"Memory and Skills sections are only emitted when their underlying files actually exist, so a fresh
pasclaw onboardinstall still produces clean output.What picoclaw and nanobot actually ship (for reference)
pkg/agent/context.go:170getIdentity): single string# picoclaw 🦞 (<version>) You are picoclaw, a helpful AI assistant. ## Workspace … ## Important Rules 1–4.Composed via aPromptPart{Layer,Slot,Source}registry, rendered with\n\n---\n\n.nanobot/templates/agent/identity.md): noYou are Xpersona in the template. Persona lives in user-editable bootstrap files (AGENTS.md / SOUL.md / USER.md). The template only provides scaffolding (runtime, workspace paths, tool contract, channel-specific format hints).build_system_prompt()joins sections with\n\n---\n\n.PasClaw takes the picoclaw approach for the persona content but the nanobot/picoclaw approach for sectioning structure. No Python version in the runtime string — we're a Free Pascal / Delphi program.
New unit
src/pkg/agent/PasClaw.Agent.Prompt.pasexposes:Wiring (4 sites that previously set
Options.SystemPrompt)Cmd.Agent.pas:155Result.Options.SystemPrompt := A.SystemPrompt:= BuildSystemPrompt(Cfg, A.SystemPrompt)—--system "..."is now additive (appended as USER section), so bare invocations get the full identity for freeGateway.Server.pas:360(/v1/chat):= BuildSystemPrompt(FCfg, '')alwaysGateway.Server.pas:810(/v1/chat/completions):= BuildSystemPrompt(FCfg, '')only whennot HasSystemMessage(Msgs)— third-party clients that supply their own persona via the messages array winComponent.pas:294(TPasClawAgent)if FSystemPrompt <> '' then ...(override semantics):= BuildSystemPrompt(FConfig, FSystemPrompt)— additive, like the CLIBuildLoopConfiginCmd.Agentgrows aCfg: TConfigparameter (both call sites updated).Build wiring
Makefile:src/pkg/agentadded toUNIT_DIRS.PasClaw.dproj:..\pkg\agentadded toDCC_UnitSearchPath; the new unit added to theDCCReferencelist betweenskillsandmemory.Failure modes
MEMORY.md→ MEMORY section skipped, no error.FConfig = nilon the component path →Cfgparameter currently unused insideBuildSystemPrompt(signature is forward-compatible for future config-driven knobs).Test plan
pasclaw agent "hi"— confirm the assembled system prompt appears (use--debugto see the body bytes growing to ~3–4 KB just from the preamble).pasclaw agent --system "Use British English." "hi"— confirm identity is present AND the British-English line shows up at the bottom (appended, not replaced).MEMORY.mdinto~/.pasclaw/workspace/memory/— confirm contents appear under the MEMORY section.curl /v1/chat -d '{"message":"hi"}'— composed prompt is in effect.curl /v1/chat/completions -d '{"messages":[{"role":"system","content":"You are a parrot."},{"role":"user","content":"hi"}]}'— model behaves as a parrot, NOT as PasClaw. (Client wins.)curl /v1/chat/completions -d '{"messages":[{"role":"user","content":"hi"}]}'— model uses composed PasClaw prompt (no client system message → we inject).make) + Delphi.dprojbuild cleanly.make smoke— every top-level command still runs.https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code