Repository navigation
Attach mode: the gateway announces itself, and the terminal can be its client - #613
Conversation
…s client PR F of docs/opencode2-plan.md. The CLI, the TUI, the web UI and the desktop all write the same session files, and only the gateway serialises turns per session -- its turn lock is in-process. A terminal opened while a gateway is up was a second writer with no lock and no view of the turn the browser started. OpenCode's answer is one service and clients. This is the version of it that does not rewrite the TUI: the gateway owns the session when it is running, and the in-process path stays for when it is not. Discovery. `pasclaw gateway` and `pasclaw serve` write <home>/run/gateway.json on start (port, bind, pid, a sha256 of the token, started_at, version) and remove it on stop. A reader treats a file whose pid is dead as absent, so a crash never leaves clients attaching to nothing, and a second gateway that failed to bind does not delete the first one's file on its way out (remove only acts on our own pid or a stale one). `pasclaw status` prints whether one is running, where, since when. The file is only removed when the gateway's finally runs, and nothing caught SIGINT / SIGTERM / Ctrl-C before: the process died where it stood, which would have left a stale file after every Ctrl-C. InstallStopSignalHandler makes the first signal set a flag (nothing else happens in the handler) and restore the default action, so a second one still kills a gateway stuck shutting down; WaitForStop polls the flag in half-second slices. A gateway now logs "stopped", frees its channels and registry, and removes its run file on Ctrl-C. Attach. `pasclaw agent --attach` (and `pasclaw tui --attach`) become a client of that gateway: nothing runs locally -- no provider, registry or shell backend -- and each line is one turn through /v1/chat/completions with X-PasClaw-Session and session_context, so the gateway holds the transcript and the turn lock; the reply streams back with one-line tool traces. /sessions, /new, /resume <id> and /delete <id> go through /v1/sessions (the client gains CreateSession and DeleteSession beside its existing Sessions). -m sends one turn and exits. cli.attach in config makes it the default: auto attaches when a gateway is up and runs locally otherwise, on always attaches and fails when none is running, off (default) never. The token comes from this config's gateway.token; a hash mismatch with the running gateway is warned about before the first request fails with 401. v1 is the line client on both TUI builds; the full-screen panes against a remote session list, and watching a turn another surface started (an SSE feed per session), are later steps. Tested in runfile_tests: write / read round trip with our pid and the token hash, the sha256 vector, wildcard binds mapping to loopback, a dead-pid file read as absent but still inspectable, remove acting on our own and stale files and leaving another live process's alone, garbage and portless files, and ResolveAttach across off / auto / on / --attach with and without a live file, the token-mismatch warning, and the cli.attach config round-trip, and SIGTERM sent to the test process setting the stop flag instead of killing it. Attach itself was run end to end against a gateway on a scratch home: run file written, session created and listed over HTTP, SIGINT stopping the gateway within a second and removing the file, status reporting each state, and --attach with no gateway exiting 1 with the reason. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 164a8378d7
ℹ️ 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".
| Hist.AddObject(M); | ||
| Printer.Printed := False; | ||
| if not Quiet then Print(Ansi.BoldBlue + 'pasclaw' + Ansi.Reset + ' > '); | ||
| Reply := Client.Chat(Hist.ToJSON, '', Printer.Chunk, Printer.ToolTrace); |
There was a problem hiding this comment.
Forward agent restrictions to attached turns
When --attach or cli.attach is combined with existing options such as --plan, --no-tools, --model, --system, or --max-tokens, this call sends only the user message and silently discards those options. In particular, the gateway's ParseModeFromBody defaults a request without mode to build mode, so pasclaw agent --attach --plan unexpectedly exposes mutating tools despite the requested read-only mode. Pass these settings in the attached request or reject unsupported combinations rather than silently changing their semantics.
Useful? React with 👍 / 👎.
| Removed in the finally below; a crash leaves it, and readers | ||
| treat a dead pid as absent. } | ||
| WriteGatewayRunFile(GetHome, Args.Addr, Args.Port, Cfg.Gateway.Token, FormatVersion); | ||
| InstallStopSignalHandler; { Ctrl-C / SIGTERM -> WaitForStop returns -> the finally runs } |
There was a problem hiding this comment.
Wake the Telegram loop on the first stop signal
For pasclaw gateway --telegram, the command blocks in TTelegramChannel.Run instead of calling Server.WaitForStop; that loop checks only its private FStop, while this handler changes only the unrelated global GStopRequested. Consequently the first SIGINT/SIGTERM no longer stops the process or reaches the cleanup finally; on Unix the operator must send a second signal, which kills the process without graceful cleanup and leaves the run file stale. The signal path must also request that the Telegram channel stop.
Useful? React with 👍 / 👎.
| if not FileExists(Info.Path) then Exit; | ||
| Text := ReadFileText(Info.Path); |
There was a problem hiding this comment.
Handle run-file deletion between existence check and open
When status, agent --attach, or tui --attach races with gateway shutdown, the gateway can delete gateway.json after FileExists succeeds but before ReadFileText opens it. ReadFileText then raises instead of fulfilling this function's documented missing-file False result, and none of these callers catches the exception, so a normal concurrent shutdown can crash the client. Catch open/read failures here and return False.
Useful? React with 👍 / 👎.
| function ConsoleHandler(CtrlType: DWORD): BOOL; stdcall; | ||
| begin | ||
| GStopRequested := True; | ||
| Result := True; { handled: the process keeps running until the finally has run } |
There was a problem hiding this comment.
Let a second Windows control event force termination
On Windows, every Ctrl-C/control event sets the flag and returns True, so the handler remains installed and consumes subsequent events as well. If shutdown hangs in channel or server cleanup, the documented second Ctrl-C cannot invoke the default termination behavior, unlike the Unix implementation that restores SIG_DFL after the first signal. Return False once stop is already requested or unregister the handler after the first event.
Useful? React with 👍 / 👎.
#611 (permissions) and #612 (worktrees) are both in main now, so this PR's diff against main is attach mode alone. One conflict, docs/configuration.md: this branch's cli.attach row sat where main reworded shell_timeout_sec (the tree-kill wording). Kept both. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
Four review findings, all real.
**P1: an attached turn dropped the flags it was given.** It sent the
user's message and nothing else, and the gateway treats a request with
no mode as BUILD mode -- so `pasclaw agent --attach --plan` ran with
mutating tools exposed, the one thing --plan exists to prevent.
--model, --system, --max-tokens and --no-tools went the same way.
/v1/chat/completions already takes all five per request (mode, model,
system, max_tokens, no_tools), so they are forwarded: TPasClawClient
gains TurnOptions, written into the body by a new ChatRequestBody only
when set, so every existing caller sends the body it always did. --system
goes as the `system` field, not a system message -- the gateway composes
the field into its own prompt (workspace, memory, the plan-mode section),
where a system message would replace all of it.
The flags a gateway turn cannot carry -- --provider, --thinking,
--max-iterations, --no-mcp, --no-hashline, --no-plan, --orient,
--goal-*, --backend, --profile; on `tui` its provider/mcp/hashline/
backend/profile flags -- are refused by name, exit 2, before anything is
sent. Quietly running `--attach --provider x` on the gateway's provider
would change what the command means. Display flags stay local.
On the way: DefaultAgentArgs assigned field by field and never set Mode,
Attach, Session, BackendOverride or Profile, so the enum and the Boolean
among them held whatever the stack did -- including this PR's own
Attach. It starts from Default(TAgentArgs) now. And ChatRequestBody frees
the JSON wrapper each copied history message comes in, which the inline
version leaked.
**P1: `pasclaw gateway --telegram` ignored the first Ctrl-C.** That
command blocks in TTelegramChannel.Run, not Server.WaitForStop, and the
signal handler only sets a process-wide flag -- which nothing in the
channel read. The first signal did nothing; the second (SIG_DFL by then)
killed the process without the cleanup the handler exists for, leaving
the run file stale. The channel now takes a StopCheck, a plain function
it polls between long-polls alongside its own FStop, and the gateway
sets it to StopRequested. A plain function because a signal handler may
only set a flag; it never reaches into the object. The stop lands when
the current long-poll returns, up to ~25 s, and the gateway says so at
startup and in the docs.
**P2: the run file vanishing mid-read crashed the client.** The gateway
deletes gateway.json on its way out, unordered against a reader:
FileExists could say yes and ReadFileText then raise, and none of
`status`, `agent --attach`, `tui --attach` catches it. A read that fails
is now the documented "absent".
**P2: on Windows, a second Ctrl-C could not force termination.** The
console handler returned True for every event, so it kept consuming them
and a hung shutdown could not be broken out of -- unlike Unix, where the
first signal restores SIG_DFL. Once stop is already requested it now
returns False, which hands the event to the default handler. Not run
here: there is no Windows in this environment.
Tested (test-runfile), each fix negative-verified by reverting it:
- the real `pasclaw agent --attach --plan --model ... --system ...
--max-tokens 123 --no-tools -m hello` against a fake gateway that
records what arrives: mode=plan, the model, system as a field,
max_tokens, no_tools. A flagless turn sends none of them.
`--attach --provider x --no-mcp` exits 2, names both flags, and the
fake gateway receives no turn. Reverting the forwarding fails on
mode; reverting the refusal fails on the exit code.
- ChatRequestBody: the options appear only when set, and system is
never a system message.
- the run file raced for real: one thread writes and deletes it in a
loop while another reads it (~250k reads in 1.5 s). Reverting the
guard fails with exactly the predicted EFOpenError.
- Telegram: with the stop flag up, Run returns without polling, which
also keeps the test off the network. Reverting it to FStop alone
fails.
test-runfile now depends on $(BIN), since one case runs the binary.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
main now carries #608 through #613, which this branch was stacked on. One conflict, in the Makefile: this branch's new test-skill-args and test-instructions targets sat beside test-runfile, which #613 made depend on $(BIN). Both kept. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
Three Delphi-only compile errors in PasClaw.Gateway.RunFile (from #613), none of which FPC sees -- two are in the Windows branch and the third is an FPC-only RTL function: - E2003 PROCESS_QUERY_LIMITED_INFORMATION: dcc64's Winapi.Windows does not declare it. Declared here as RUNFILE_PROCESS_QUERY_LIMITED ($1000) under MSWINDOWS -- our own name, so it cannot collide with a Windows unit that does. - E2003 LocalTimeToUniversal: FPC's DateUtils only. started_at now comes from PasClaw.Utils.NowIsoUtc, which already picks TTimeZone.Local.ToUniversalTime on Delphi (as Agents and MemoryFetch do) and quotes its separators: the old format string left ':' bare, which FormatDateTime replaces with the locale's time separator. DateUtils is no longer used and leaves the uses clause. - E2010 DeleteFile: Winapi.Windows comes after SysUtils in scope on Delphi, so its DeleteFile(PWideChar) won over SysUtils.DeleteFile. Now SysUtils.DeleteFile, by name. A scan of the units #608 through #618 touched found no other unguarded FPC-only identifier and no other Windows-shadowed RTL call. Tested: FPC build, test-runfile (now also checks started_at is ISO 8601 UTC with literal separators). Not run: dcc64 -- there is no Delphi compiler in this environment, and no win64 RTL for FPC either, so the Windows branch is unbuilt here. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
PR F of
docs/opencode2-plan.md. Targetsmaindirectly: A through E (#608, #609, #619, #611, #612) are merged, and main is merged in here, so the diff is attach mode only.What
The CLI, the TUI, the web UI and the desktop all write the same session files, and only the gateway serialises turns per session (its turn lock is in-process). A terminal opened while a gateway was up was a second writer with no lock and no view of the turn the browser started. OpenCode's answer is one service and clients; this is the version that does not rewrite the TUI: the gateway owns the session when it is running, and the in-process path stays for when it is not.
pasclaw gateway/pasclaw servewrite$PASCLAW_HOME/run/gateway.json(port, bind, pid, token_hash, started_at, version) on start and remove it on stop (PasClaw.Gateway.RunFile). A file whose pid is dead is treated as absent, and remove only acts on our own pid or a stale one, so a second gateway that failed to bind cannot delete the first one's file. A file that vanishes or cannot be read mid-read is also absent.pasclaw statusreports running / stale / none.InstallStopSignalHandlermakes the first signal set a flag; a second one kills (Unix: the default action is restored; Windows: the console handler hands the second event to the default handler).WaitForStoppolls the flag, and so does the Telegram channel's loop, sogateway --telegramstops too, once the current long-poll returns (up to ~25 s).pasclaw agent --attach/pasclaw tui --attach(PasClaw.Cmd.Attach): nothing runs locally. Each line is one turn through/v1/chat/completionswithX-PasClaw-Session+session_context, streamed back with one-line tool traces./sessions,/new,/resume <id>,/delete <id>go through/v1/sessions(the client gainsCreateSession/DeleteSession).-msends one turn and exits.--attachwith no gateway exits 1 with the reason.--plan/--build/--mode,--model,--system,--max-tokensand--no-toolsare sent with every turn (mode,model,system,max_tokens,no_tools); withoutmodethe gateway would run build mode.--systemgoes as thesystemfield so the gateway composes it into its own prompt. Flags a gateway turn cannot carry (--provider,--thinking,--max-iterations,--no-mcp,--no-hashline,--no-plan,--orient/--no-orient,--goal-*,--backend,--profile) are refused by name with exit 2 before anything is sent.cli.attach: off|auto|onin config (defaultoff):autoattaches when a gateway is up and runs locally otherwise;onalways attaches. The token comes from this config'sgateway.token; a hash mismatch with the running gateway is warned about up front.Review fixes
TPasClawClientgainsTurnOptions; a newChatRequestBodywrites each option only when set, so other callers send the body they always did. Also:DefaultAgentArgsleftMode,Attach,Session,BackendOverrideandProfileuninitialised and now starts fromDefault(TAgentArgs), and the history copy no longer leaks the JSON wrapper of each message.gateway --telegramignored the first Ctrl-C. It blocks inTTelegramChannel.Run, which only read its ownFStop. The channel now takes aStopCheck(a plain function, because a signal handler may only set a flag), and the gateway sets it toStopRequested.Tests
runfile_tests(make test-runfile, which now depends on the binary): write / read round trip with our pid and token hash, the sha256 vector, wildcard binds → loopback, dead-pid file absent but inspectable, remove semantics (own / stale / another live pid), garbage and portless files,ResolveAttachacross off / auto / on /--attachwith and without a live file, the token-mismatch warning,cli.attachround-trip, and SIGTERM sent to the test process setting the stop flag instead of killing it.The review fixes add these cases, and each one was checked by reverting its fix and watching the case fail:
pasclaw agent --attach --plan --model … --system … --max-tokens 123 --no-tools -m helloruns against a fake gateway that records each request. The body carries every option; a turn with no flags sends none of them;--attach --provider x --no-mcpexits 2, names both flags and sends nothing.ChatRequestBodyincludes each option only when set and never sendssystemas a message.EFOpenError.Runreturns without polling.Full
make testgreen (49 passes).Docs
docs/commands.md(the--attachsection, with the forwarded and refused flags),docs/gateway.md("Run file and attached terminals", stop behaviour including--telegram),docs/configuration.md(cli.attach),docs/sessions.md,docs/agent-features.md.🤖 Generated with Claude Code
https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U