Files
Netcatty/docs/features/terminal-execute-bulk.md
T
Radwan Selo a4805b3e3d feat(capabilities): add terminal_execute_bulk to run one command on many sessions (#4342)
* feat(capabilities): add terminal_execute_bulk to run one command on many sessions

Add a terminal_execute_bulk MCP tool that runs the same short command on
2-20 open terminal sessions and groups identical results.

- All-or-nothing preflight: scope, closing, busy, connected, transport
  and the per-shell command safety policy are checked for every target
  before anything is sent. Any bad target cancels the whole call and all
  bad targets are reported at once.
- One approval listing every host. Remembered grants and external-client
  session approval never satisfy it (policy.requiresFreshApproval), and a
  pending fan-out is not swept up by another request's session approval.
- Targets are claimed before the prompt and re-checked after it; all
  targets then start in the same synchronous turn under a single per-chat
  exec lock, each with its own wall-clock timeout.
- Results are grouped only when status, exit code, stdout, stderr and
  error are identical on the full output, then truncated (tailLines and
  size caps). JSON output matches the other tools.
- Loaded on demand through the terminal_bulk toolset.

* fix(capabilities): harden terminal_execute_bulk after review

- Only trust the metadata "connected" flag for worker-hosted sessions; a
  live main-process session with a stale snapshot is no longer refused.
- Keep targets protected from idle auto-close from the claim through the
  approval wait to completion, and release on every path.
- Classify blocklist refusals before status keywords so a pattern such as
  "cancel-job" is reported as not_sent, not cancelled.
- List the terminal_bulk toolset in the MCP server instructions and the
  netcatty-mcp skill so clients can discover it.
- Test that the bulk RPC gets the same timeout budget as terminal_execute.

* fix(capabilities): validate worker sessions up front and cancel them at the deadline

An independent review found that the default (terminal worker) sessions
could receive a partial send, and that the backstop deadline never
reached the worker.

- Add a no-send precheck mode to the worker exec handler. The bulk
  preflight now runs every deterministic check for worker sessions
  (transport, shell kind, shell-specific safety patterns, unsupported
  local shell, busy job) so a refusal cancels the whole call before any
  host receives the command.
- Add netcatty:ai:exec:cancel and call it at the deadline, so a stuck
  worker command is cancelled before the per-chat lock is released
  instead of overlapping the next command. Background jobs are left
  alone.
- Make the deadline grace 3s and give the bulk RPC extra timeout budget
  for its preflight, so the backstop fires before the client gives up.
- Do not group hosts whose exec layer already dropped different amounts
  of output, and share one size budget between stdout and stderr.
- Restrict the capability to the sidebar agent; the global agent runs
  delegated, which bulk refuses.
- Document that live terminal readiness is a send-time state.

* test(capabilities): cover terminal_execute_bulk over the real MCP wire and close mutation gaps

- Drive the tool through the real stdio MCP server: hidden until the
  terminal_bulk toolset is loaded, schema shape, JSON result, Error text
  with isError, schema rejection of a native array, and privacy masking
  of the grouped result with token restoration in the command.
- Mutation testing (18 deliberate breakages of the safety-critical
  lines) left three survivors; add tests that kill two of them: hosts
  differing only in exit code, status, stderr or error never share a
  group, and a session-scoped answer to a fan-out approval does not
  approve later writes from that client.
- Assert that delegated agents cannot reach the fan-out at the gate.

* fix(capabilities): address review findings on terminal_execute_bulk

- Keep the tool MCP-only for now. The in-app agent has no completed-write
  replay for it after a context-compaction retry, and its SDK approval
  gate would stack a second prompt on the bridge's fresh approval. Both
  can follow in a separate change.
- Re-run the transport preflight for every claimed target after the
  approval and before the synchronous start, so a worker session that
  changed while the user was deciding cancels the whole call instead of
  being refused after other hosts have started.
- Never group hosts whose exec layer already dropped part of the output:
  equal retained tails do not prove equal full results.

* fix(capabilities): only report not_sent on explicit evidence and flag capped output

- Classify a host as not_sent only when the exec layer says so (a known
  pre-send code or refusal text). An error with no output and no exit
  code, such as a terminal worker exiting after it typed the command,
  is now reported as error, so a mutating command is never presented as
  safe to retry blindly. SHELL_NOT_READY and EXECUTION_NOT_AUTHORIZED
  are now recognised, so a call where every host refuses fails as
  not sent instead of returning ok.
- Have execViaRawPty and execViaChannel set outputTruncated when they
  stop collecting at their size cap, so hosts that differ only in the
  discarded output are never grouped.

* test(capabilities): run terminal_execute_bulk against the real worker exec handler

Wire the bridge to the production terminal-worker exec handler with fake
shells that speak the wrapper protocol, and cover the grouped result,
Stop while every host is running, and real per-host timeouts.

* fix(capabilities): do not probe hosts before the bulk approval

In confirm mode the preflight ran the shell-kind probe, which opens an
SSH exec channel and runs a remote command, before the approval prompt.
Denying the call (or another target failing) still executed something on
the host, and on an account with a forced command that could trigger it.

- The preflight before the prompt is now read-only: no channel is opened,
  and the safety check uses the shell kind only if it is already known,
  otherwise the shell-independent patterns.
- The full check, including the probe and the shell-aware patterns, runs
  right after approval and before any command is sent, so the call is
  still all-or-nothing. Without a prompt the full check runs first.
- The worker precheck honours the same distinction.

* fix(capabilities): recheck local guards before probing hosts after approval

After the approval the bulk call ran the probing transport pass first and
rechecked cancellation, scope and the privacy policy afterwards. A call
that was no longer authorized (Stop pressed, session out of scope,
privacy settings changed while the prompt was open) was rejected only
after the hosts had already been probed.

Run the local, read-only guards first, then the probing pass, then the
guards again because the pass awaits, and only then take the chat lock
and start. A refusal by the privacy hook now happens before the lock is
taken.

* fix(capabilities): re-read the permission mode and classify exec refusals precisely

- Re-evaluate the live permission mode with the other local guards, both
  before the probing pass and again before the start. Switching to
  observer while a prompt is open (or while hosts are being checked) now
  refuses the call, and a call that needed no approval is refused if the
  mode turns into confirm before it starts.
- Keep the code of an error the exec layer throws, so SHELL_PROMPT_PENDING
  (thrown before anything is written) is reported as not_sent and an
  all-refused call fails as not sent.
- Recognise the executors' real closed-stream messages ("Stream closed
  unexpectedly", "Serial port closed unexpectedly") as connection_lost.
2026-11-25 15:45:53 +08:00

6.2 KiB
Raw Blame History

Run one command on many sessions (terminal_execute_bulk)

terminal_execute_bulk runs the same short command on 2–20 open terminal sessions and waits for all of them. It is available to MCP clients only (the in-app agents do not get it yet). Load it over MCP with load_netcatty_tools and the terminal_bulk toolset. For a single host use terminal_execute; fewer than 2 sessions is rejected.

Input

Field Type Notes
command string Same rules as terminal_execute.
sessionIds string JSON array of 2–20 unique session IDs, for example ["s-1","s-2"]. Resolve IDs with get_environment.
tailLines number, optional Keep the last N lines of each distinct output. Default 100 (also used for 0), maximum 2000.

All-or-nothing

Before anything is sent, every target is checked with the same rules a single terminal_execute uses: session scope, closing, already busy, connected, able to run commands, and the command safety policy for that session's shell. If any target fails, no command is sent to any host and the call fails, listing every bad target at once:

Error: nothing was sent. 2 of 5 targets cannot run this command:
- s-9: Session "s-9" is not in the current scope.
- s-3 (web3): Session already has another command in progress. …
Remove or fix these session ids and retry.

Out-of-scope IDs are reported without a label, so a session outside the current scope is never revealed.

Approval and safety

  • Observer mode refuses the call, and the live permission mode is re-read after the prompt and again just before the start, so switching to observer while a prompt is open refuses it. Confirm mode asks once, with a card that lists the command and every host.
  • A fan-out approval is never satisfied by a remembered "always allow" grant, and it is never covered by "allow for this session" from an external MCP client. A pending fan-out is not approved by another request's session approval either. Each call asks.
  • All targets are claimed before the prompt, so no other command can start on them while you decide. Everything is checked again right after approval; if anything changed, nothing is sent.
  • In confirm mode no host is contacted before you answer. The checks before the prompt only read local state and apply the shell-independent safety patterns. The shell-kind probe (which opens an SSH exec channel, as a single command does just before it runs) and the shell-specific safety patterns run right after you approve, once the local guards (Stop, scope, privacy policy) have been rechecked and still before any command is sent. So a refusal that depends on the host's shell can appear after approval, and denying a call leaves every host untouched. Without a prompt (auto mode) the full check runs first.
  • Every command still goes through the normal execution path, including the per-shell safety policy, shell readiness checks, privacy masking, and cancel.
  • Sessions hosted by the terminal worker (the default) are checked the same way: the worker runs every deterministic check (transport, shell kind, the shell-specific safety patterns, unsupported local shells, a busy background job) in a no-send precheck mode, so a refusal there also cancels the whole call before any host receives the command.
  • The one thing that cannot be known in advance is the live state of a terminal at the moment of sending, for example a pager, a password prompt, or a prompt that cannot be recognized. A host in that state reports not_sent (SHELL_READINESS_UNKNOWN) and the other hosts still run, because commands already sent cannot be taken back.

Timeouts

Every host gets the same timeout, the global command timeout from Settings. Each host has its own timer, started when that host's command starts, so a slow host never uses up another host's time. All hosts start together, so the call takes about one timeout in the worst case, like terminal_execute. As a backstop, a host that has not finished 3 seconds after the timeout is reported as timeout and the chat's running commands are cancelled, including those inside the terminal worker, before the per-chat lock is released. The RPC timeout budget for this tool is larger than for terminal_execute so the backstop always fires first.

Output

JSON text, in the same style as the other Netcatty tools. Hosts with identical results are grouped, which keeps the response small on large fleets.

{
  "ok": true,
  "hostCount": 5,
  "counts": { "completed": 4, "timeout": 1 },
  "groups": [
    {
      "hosts": [
        { "sessionId": "s-web1", "label": "web1" },
        { "sessionId": "s-web2", "label": "web2" }
      ],
      "status": "completed",
      "exitCode": 0,
      "stdout": "active"
    },
    {
      "hosts": [{ "sessionId": "s-db1", "label": "db1" }],
      "status": "timeout",
      "exitCode": null,
      "stdout": "",
      "stderr": "connect: no route",
      "error": "Command timed out (60s)"
    }
  ]
}
  • status records what happened, not whether it was good: completed, timeout, cancelled, connection_lost, error, or not_sent.
  • exitCode is a number only for completed. A non-zero exit code is a normal result, not a tool failure. Serial and network-device sessions have no exit code (null).
  • stderr and error are omitted when empty.
  • Output is grouped on the full, untruncated result, so two hosts that differ only in the part that was cut off are never merged. tailLines and a per-group size cap are then applied; a cut group has outputTruncated: true (also set when the exec layer had already dropped the beginning of a very large output) and, when lines were dropped, omittedLines.
  • If no host received the command, the call fails with Error: No command was sent to any host. and one line per host.
  • ok: false results (invalid input, preflight failure, denial, cancel) are returned as Error: … text with isError, like every other tool.

Not included

The in-app agents (Catty and the global agent) do not get this tool yet. A CLI command, targets by group or tag, opening missing sessions, per-host commands, and a per-call timeout are not part of this tool. Plugin agents cannot call it.