Files
Netcatty/electron/bridges/mcpServerBridge/execBulk.cjs
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

581 lines
24 KiB
JavaScript

"use strict";
/**
* terminal_execute_bulk: run one command on 2-20 terminal sessions.
*
* Contract (see docs/features/terminal-execute-bulk.md):
* - all-or-nothing preflight: if any target cannot run the command, nothing is
* sent to any host;
* - one approval for the whole fan-out (never satisfied by remembered grants
* or session-wide approval);
* - every target starts in the same synchronous turn, each with its own
* wall-clock timeout (the user's command timeout);
* - identical results are grouped to save tokens.
*/
const MIN_BULK_TARGETS = 2;
const MAX_BULK_TARGETS = 20;
const DEFAULT_TAIL_LINES = 100;
const MAX_TAIL_LINES = 2000;
const MAX_DISTINCT_OUTPUT_CHARS = 32 * 1024;
const MAX_RESPONSE_CHARS = 256 * 1024;
const MIN_GROUP_OUTPUT_CHARS = 2 * 1024;
const DEADLINE_GRACE_MS = 3 * 1000;
const BULK_RPC_METHOD = "netcatty/execBulk";
/**
* Private marker placed on the inner execution context while the bulk call
* already holds the per-chat exec lock. A Symbol cannot come from RPC params.
*/
const CHAT_LOCK_HELD = Symbol("netcatty.execBulk.chatLockHeld");
function labelPart(sessionId, label) {
return label ? `${sessionId} (${label})` : sessionId;
}
/**
* @param {{ command?: unknown, sessionIds?: unknown, tailLines?: unknown }} params
* @returns {{ ok: true, command: string, sessionIds: string[], tailLines: number } | { ok: false, error: string }}
*/
function parseBulkExecParams(params = {}) {
const command = params?.command;
if (typeof command !== "string" || !command.trim()) {
return { ok: false, error: "Invalid command" };
}
const shapeError = `sessionIds must be a JSON array of ${MIN_BULK_TARGETS}-${MAX_BULK_TARGETS} session ID strings`;
let rawIds = params?.sessionIds;
if (typeof rawIds === "string") {
try {
rawIds = JSON.parse(rawIds);
} catch {
return { ok: false, error: shapeError };
}
}
if (!Array.isArray(rawIds) || rawIds.some((id) => typeof id !== "string" || !id.trim())) {
return { ok: false, error: shapeError };
}
if (rawIds.length < MIN_BULK_TARGETS) {
return { ok: false, error: `${shapeError}. Use terminal_execute to run a command on a single session` };
}
if (rawIds.length > MAX_BULK_TARGETS) {
return { ok: false, error: shapeError };
}
const sessionIds = rawIds.map((id) => id.trim());
const duplicates = [...new Set(sessionIds.filter((id, index) => sessionIds.indexOf(id) !== index))];
if (duplicates.length > 0) {
return { ok: false, error: `sessionIds must be unique. Duplicates: ${duplicates.join(", ")}` };
}
let tailLines = DEFAULT_TAIL_LINES;
if (params?.tailLines !== undefined && params?.tailLines !== null) {
const parsed = Number(params.tailLines);
if (!Number.isFinite(parsed) || parsed < 0) {
return { ok: false, error: "tailLines must be a non-negative number" };
}
if (parsed > 0) tailLines = Math.min(MAX_TAIL_LINES, Math.floor(parsed));
}
return { ok: true, command, sessionIds, tailLines };
}
/**
* @param {Array<{ sessionId: string, label?: string, error: string }>} failures
* @param {number} total
*/
function formatPreflightFailure(failures, total) {
// The MCP layer prefixes "Error: "; keep the message itself prefix-free.
const lines = failures.map((failure) => `- ${labelPart(failure.sessionId, failure.label)}: ${failure.error}`);
return [
`nothing was sent. ${failures.length} of ${total} targets cannot run this command:`,
...lines,
"Remove or fix these session ids and retry.",
].join("\n");
}
// A result means "the command was never sent" only on explicit evidence from the exec layer.
// A missing exit code alone proves nothing: a worker that dies after typing the command also
// returns an error with no output, and the command may already have taken effect.
const NOT_SENT_CODES = new Set([
"SHELL_READINESS_UNKNOWN",
"SHELL_NOT_READY",
"SHELL_PROMPT_PENDING",
"EXECUTION_NOT_AUTHORIZED",
"COMMAND_ALREADY_RUNNING",
]);
const NOT_SENT_PATTERNS = [
/^Command blocked by safety policy/,
/no command was sent/i,
/command was not sent/i,
/start a new chat/i,
/^Session already has /,
/^Session not found/,
/^Session ".*" is closing\./,
/^Session does not support command execution/,
/^No terminal stream or SSH client available/,
/^Network device session has no writable PTY stream/,
/^Serial file transfer is already in progress/,
/^AI execution is not supported/,
/^Another Netcatty command is already running/,
];
const TIMEOUT_PATTERN = /timed out/i;
const CANCELLED_PATTERN = /cancel/i;
const LOST_PATTERN = /connection lost|terminated unexpectedly|closed unexpectedly|stream lost|connection closed/i;
/**
* Normalize one exec result into the public per-host shape.
* `status` records what happened; it never judges the exit code.
*/
function classifyHostResult(result) {
const normalized = classifyHostResultCore(result);
const record = result && typeof result === "object" ? result : {};
// The exec layer keeps only the tail of very large output and reports that it did.
// Two hosts that differ only in the dropped head must not look identical.
return {
...normalized,
sourceTruncated: record.outputTruncated === true,
};
}
function classifyHostResultCore(result) {
if (!result || typeof result !== "object") {
return { status: "error", exitCode: null, stdout: "", stderr: "", error: "Invalid execution result" };
}
const stdout = typeof result.stdout === "string" ? result.stdout : "";
const stderr = typeof result.stderr === "string" ? result.stderr : "";
const error = typeof result.error === "string" ? result.error : "";
const numericExit = typeof result.exitCode === "number" && Number.isFinite(result.exitCode)
? result.exitCode
: null;
// The exec layer says explicitly that nothing was sent (this includes errors it threw
// with such a code before writing anything).
if (NOT_SENT_CODES.has(result.code)) {
return { status: "not_sent", exitCode: null, stdout: "", stderr: "", error: error || "No command was sent." };
}
// Any other exception inside the exec machinery: we cannot claim the command did or did not run.
if (result.thrown === true) {
return { status: "error", exitCode: null, stdout, stderr, error: error || "Execution failed" };
}
if (error) {
let status = "error";
// Refusals can quote text (such as a blocklist pattern) that contains any word,
// so check them before the status keywords.
if (NOT_SENT_PATTERNS.some((pattern) => pattern.test(error))) status = "not_sent";
else if (TIMEOUT_PATTERN.test(error)) status = "timeout";
else if (CANCELLED_PATTERN.test(error)) status = "cancelled";
else if (LOST_PATTERN.test(error)) status = "connection_lost";
// Anything else, including a worker that exited mid-command, is unknown: never claim
// the command was not sent without evidence.
return { status, exitCode: null, stdout, stderr, error };
}
return { status: "completed", exitCode: numericExit, stdout, stderr, error: "" };
}
/**
* Keep the last `tailLines` lines, then the last `maxChars` characters.
* @returns {{ text: string, omittedLines: number, truncated: boolean }}
*/
function tailText(text, tailLines, maxChars) {
if (!text) return { text: "", omittedLines: 0, truncated: false };
let kept = text;
let omittedLines = 0;
let truncated = false;
const lines = kept.split("\n");
// A trailing newline does not start another line.
const countable = lines.length > 1 && lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;
if (countable > tailLines) {
omittedLines = countable - tailLines;
truncated = true;
kept = lines.slice(omittedLines).join("\n");
}
if (kept.length > maxChars) {
truncated = true;
const cut = kept.slice(kept.length - maxChars);
const firstNewline = cut.indexOf("\n");
// Prefer starting on a line boundary so no partial first line is shown.
const trimmed = firstNewline >= 0 && firstNewline < cut.length - 1 ? cut.slice(firstNewline + 1) : cut;
const dropped = kept.slice(0, kept.length - trimmed.length);
omittedLines += (dropped.match(/\n/g) || []).length;
kept = trimmed;
}
return { text: kept, omittedLines, truncated };
}
/**
* Group identical per-host results (compared on the full raw output, before
* truncation) and build the public payload.
*
* @param {Array<{ sessionId: string, label?: string, result: object }>} entries ordered like the request
* @param {{ tailLines?: number }} [options]
*/
function groupBulkResults(entries, options = {}) {
const tailLines = options.tailLines || DEFAULT_TAIL_LINES;
const groupsByKey = new Map();
const counts = {};
for (const entry of entries) {
const normalized = classifyHostResult(entry.result);
counts[normalized.status] = (counts[normalized.status] || 0) + 1;
// When the exec layer already dropped the head of a very large output, equal tails
// cannot prove equal results, so such hosts always stay in their own group.
const key = JSON.stringify([
normalized.status, normalized.exitCode, normalized.stdout, normalized.stderr, normalized.error,
normalized.sourceTruncated ? entry.sessionId : null,
]);
let group = groupsByKey.get(key);
if (!group) {
group = { normalized, hosts: [] };
groupsByKey.set(key, group);
}
group.hosts.push({ sessionId: entry.sessionId, label: entry.label || "" });
}
const groupCount = groupsByKey.size;
const perGroupChars = Math.min(
MAX_DISTINCT_OUTPUT_CHARS,
Math.max(MIN_GROUP_OUTPUT_CHARS, Math.floor(MAX_RESPONSE_CHARS / Math.max(1, groupCount))),
);
const groups = [];
for (const { normalized, hosts } of groupsByKey.values()) {
// One budget per group, shared by both streams, so the response stays under the cap.
const stdoutChars = Math.floor(perGroupChars * 0.75);
const out = tailText(normalized.stdout, tailLines, stdoutChars);
const err = tailText(normalized.stderr, tailLines, perGroupChars - stdoutChars);
const omittedLines = out.omittedLines + err.omittedLines;
const group = {
hosts,
status: normalized.status,
exitCode: normalized.exitCode,
stdout: out.text,
};
if (err.text) group.stderr = err.text;
if (normalized.error) group.error = normalized.error;
if (out.truncated || err.truncated || normalized.sourceTruncated) {
group.outputTruncated = true;
if (omittedLines > 0) group.omittedLines = omittedLines;
}
groups.push(group);
}
return {
ok: true,
hostCount: entries.length,
counts,
groups,
};
}
/**
* @param {object} deps injected by mcpServerBridge (keeps this module testable)
*/
function createExecBulkHandler(deps) {
const {
getSessions,
getSessionMeta,
validateSessionScope,
closingTerminalSessions,
getSessionBusyError,
pendingSessionWriteApprovals,
getActiveChatExecution,
beginChatExecution,
isChatSessionCancelled,
preflightMainExec,
preflightWorkerExec,
execOnSession,
requestApproval,
sessionIdleManager,
getCommandTimeoutMs,
getLivePermission,
cancelExecsForChat,
USER_DENIED_MESSAGE,
CHAT_SESSION_CANCELLED_MESSAGE,
debugLog = () => {},
setTimeoutFn = setTimeout,
clearTimeoutFn = clearTimeout,
} = deps;
function resolveLabel(sessionId, chatSessionId) {
const meta = getSessionMeta(sessionId, chatSessionId) || {};
const session = getSessions()?.get?.(sessionId) || {};
return meta.label || meta.hostname || session.label || session.hostname || "";
}
/** Cheap, side-effect-free checks, in the same order as a single exec. */
function checkTargetSync(sessionId, ctx, { includePendingWrite }) {
const scopeError = validateSessionScope(sessionId, ctx.chatSessionId, ctx.scopedSessionIds);
// Never reveal a label (or existence) for an out-of-scope id.
if (scopeError) return { sessionId, label: "", error: scopeError };
const label = resolveLabel(sessionId, ctx.chatSessionId);
const fail = (error) => ({ sessionId, label, error });
if (closingTerminalSessions.has(sessionId)) return fail(`Session "${sessionId}" is closing.`);
const busy = getSessionBusyError(sessionId);
if (busy) return fail(busy.error);
if (includePendingWrite && pendingSessionWriteApprovals.has(sessionId)) {
return fail("Session already has another command request awaiting approval or startup. Wait for it to finish before starting a new command.");
}
const hasMainSession = Boolean(getSessions()?.get?.(sessionId));
const meta = getSessionMeta(sessionId, ctx.chatSessionId);
if (!hasMainSession && !meta) return fail("Session not found");
// A live main-process session is connected by definition; its metadata snapshot
// can be stale. Only worker-hosted sessions rely on the metadata flag.
if (!hasMainSession && meta.connected === false) return fail(`Session "${sessionId}" is not connected.`);
return null;
}
/**
* Transport + command-safety checks. With probe:false nothing may touch the remote host
* (used before the approval prompt); with probe:true the shell kind may be probed over an
* SSH exec channel, exactly like a single exec does after approval.
*/
async function checkTargetTransport(sessionId, label, ctx, { probe = true } = {}) {
const hasMainSession = Boolean(getSessions()?.get?.(sessionId));
const probeParams = {
sessionId,
command: ctx.command,
chatSessionId: ctx.chatSessionId,
scopedSessionIds: ctx.scopedSessionIds,
};
let outcome;
try {
outcome = hasMainSession
? await preflightMainExec(probeParams, { probe })
: await preflightWorkerExec(probeParams, { probe });
} catch (err) {
outcome = { ok: false, error: err?.message || String(err) };
}
if (outcome && outcome.ok === false) {
return { sessionId, label, error: outcome.error || "Session does not support command execution" };
}
return null;
}
async function preflightAll(ctx, { probe = true } = {}) {
const failures = new Array(ctx.sessionIds.length).fill(null);
const pending = [];
ctx.sessionIds.forEach((sessionId, index) => {
const syncFailure = checkTargetSync(sessionId, ctx, { includePendingWrite: true });
if (syncFailure) {
failures[index] = syncFailure;
return;
}
pending.push(checkTargetTransport(sessionId, resolveLabel(sessionId, ctx.chatSessionId), ctx, { probe })
.then((failure) => { failures[index] = failure; }));
});
await Promise.all(pending);
return failures.filter(Boolean);
}
function preflightFailureResult(failures, total) {
return {
ok: false,
code: "BULK_PREFLIGHT_FAILED",
error: formatPreflightFailure(failures, total),
};
}
/**
* @param {object} params RPC params (command, sessionIds, tailLines, chatSessionId, scopedSessionIds)
* @param {object} approvalContext transport context (externalSocket, beforeExecute)
* @param {{ requiresApproval?: boolean }} permission result of the permission check
*/
async function run(params, approvalContext = {}, permission = {}) {
const parsed = parseBulkExecParams(params);
if (!parsed.ok) return { ok: false, error: parsed.error };
const { command, sessionIds, tailLines } = parsed;
const chatSessionId = params?.chatSessionId || null;
const ctx = {
command,
sessionIds,
chatSessionId,
scopedSessionIds: params?.scopedSessionIds,
};
// Phase 1: preflight. Nothing is sent. Report every bad target at once.
const active = getActiveChatExecution(chatSessionId);
if (active) {
return {
ok: false,
code: "COMMAND_ALREADY_RUNNING",
error: `Another Netcatty command is already running for chat session "${chatSessionId}". Wait for it to finish before starting a new exec.`,
activeCommand: active.command,
activeSessionId: active.sessionId,
};
}
// When a prompt is coming, nothing may touch the remote hosts before the user answers,
// so the shell-kind probes wait until after approval. Without a prompt there is no
// boundary to protect and the full check runs right away.
const approvalRequired = permission.requiresApproval === true;
const failures = await preflightAll(ctx, { probe: !approvalRequired });
if (failures.length > 0) return preflightFailureResult(failures, sessionIds.length);
// Claim every target synchronously so no other command can slip in while
// the user decides. Another claim between preflight and here wins safely.
const claimConflicts = sessionIds
.filter((sessionId) => pendingSessionWriteApprovals.has(sessionId))
.map((sessionId) => ({
sessionId,
label: resolveLabel(sessionId, chatSessionId),
error: "Session already has another command request awaiting approval or startup. Wait for it to finish before starting a new command.",
}));
if (claimConflicts.length > 0) return preflightFailureResult(claimConflicts, sessionIds.length);
for (const sessionId of sessionIds) pendingSessionWriteApprovals.set(sessionId, BULK_RPC_METHOD);
// Keep the sessions from idle auto-close while waiting for approval and running.
const activeSessionIds = sessionIds.filter((sessionId) => sessionIdleManager.beginActivity(chatSessionId, sessionId));
let chatLock = null;
let approvalGranted = false;
try {
// Phase 2: one approval listing every host. Never satisfied by grants or
// session-wide approval.
if (permission.requiresApproval) {
const approved = await requestApproval(
BULK_RPC_METHOD,
{
command,
sessions: sessionIds.map((sessionId) => labelPart(sessionId, resolveLabel(sessionId, chatSessionId))),
},
chatSessionId,
{ ...approvalContext, requireFreshApproval: true },
);
if (!approved) return { ok: false, error: USER_DENIED_MESSAGE };
approvalGranted = true;
}
// Phase 3: commit. Guards that only read local state come first, so a call that is no
// longer authorized (cancelled, out of scope, privacy policy changed while the prompt
// was open) never causes a remote probe.
const localGuards = () => {
if (isChatSessionCancelled(chatSessionId)) {
return { ok: false, error: CHAT_SESSION_CANCELLED_MESSAGE };
}
// The permission mode can change while the prompt is open or the hosts are being
// checked; the snapshot taken at dispatch time is not enough.
const live = typeof getLivePermission === "function" ? getLivePermission(params) : null;
if (live) {
if (live.allowed === false) return { ok: false, error: live.error };
if (live.requiresApproval === true && !approvalGranted) {
return {
ok: false,
error: "The permission mode changed to confirm while this call was pending. Run it again to be asked for approval.",
};
}
}
const recheck = sessionIds
.map((sessionId) => checkTargetSync(sessionId, ctx, { includePendingWrite: false }))
.filter(Boolean);
if (recheck.length > 0) return preflightFailureResult(recheck, sessionIds.length);
try {
// Privacy policy may have changed while approval was pending.
approvalContext.beforeExecute?.();
} catch (err) {
return { ok: false, error: err?.message || String(err) };
}
return null;
};
const staleBeforeProbe = localGuards();
if (staleBeforeProbe) return staleBeforeProbe;
// Now re-run the full transport checks (worker precheck, shell-kind probe, shell-aware
// blocklist) for every claimed target: this is the first time the probes may run when a
// prompt was shown, and otherwise it catches changes during the wait. The claims keep
// other commands off these sessions meanwhile; no user command has been sent yet.
const staleTransport = (await Promise.all(sessionIds.map((sessionId) => (
checkTargetTransport(sessionId, resolveLabel(sessionId, chatSessionId), ctx, { probe: true })
)))).filter(Boolean);
if (staleTransport.length > 0) return preflightFailureResult(staleTransport, sessionIds.length);
// That pass awaited, so check the local guards again. Everything from here to the
// start loop is synchronous.
const staleAfterProbe = localGuards();
if (staleAfterProbe) return staleAfterProbe;
chatLock = beginChatExecution(chatSessionId, `bulk:${sessionIds.length}`, command);
if (!chatLock.ok) {
return {
ok: false,
code: "COMMAND_ALREADY_RUNNING",
error: `Another Netcatty command is already running for chat session "${chatSessionId}". Wait for it to finish before starting a new exec.`,
activeCommand: chatLock.active.command,
activeSessionId: chatLock.active.sessionId,
};
}
const labels = new Map(sessionIds.map((sessionId) => [sessionId, resolveLabel(sessionId, chatSessionId)]));
const results = new Map();
const runs = sessionIds.map((sessionId) => {
let started;
try {
started = Promise.resolve(execOnSession(
{ sessionId, command, chatSessionId, scopedSessionIds: params?.scopedSessionIds },
{ beforeExecute: approvalContext.beforeExecute, [CHAT_LOCK_HELD]: true },
));
} catch (err) {
started = Promise.resolve({ ok: false, thrown: true, code: err?.code, error: err?.message || String(err) });
}
return started
.catch((err) => ({ ok: false, thrown: true, code: err?.code, error: err?.message || String(err) }))
.then((result) => { results.set(sessionId, result); });
});
// Phase 4: wait. Each host enforces its own wall-clock timeout; this
// deadline is only a backstop so a stuck host cannot hang the call.
const timeoutMs = getCommandTimeoutMs();
let deadlineTimer = null;
const deadline = new Promise((resolve) => {
deadlineTimer = setTimeoutFn(() => resolve("deadline"), timeoutMs + DEADLINE_GRACE_MS);
});
const outcome = await Promise.race([Promise.all(runs).then(() => "done"), deadline]);
clearTimeoutFn(deadlineTimer);
if (outcome === "deadline") {
debugLog("execBulk:deadline", { chatSessionId, settled: results.size, total: sessionIds.length });
try { cancelExecsForChat(chatSessionId); } catch { /* best effort */ }
}
const timeoutSeconds = Math.round(timeoutMs / 1000);
const entries = sessionIds.map((sessionId) => ({
sessionId,
label: labels.get(sessionId),
result: results.has(sessionId)
? results.get(sessionId)
: { ok: false, exitCode: -1, error: `Command timed out (${timeoutSeconds}s)` },
}));
const payload = groupBulkResults(entries, { tailLines });
if (payload.groups.every((group) => group.status === "not_sent")) {
const detail = payload.groups
.flatMap((group) => group.hosts.map((host) => `- ${labelPart(host.sessionId, host.label)}: ${group.error || "not sent"}`))
.join("\n");
return { ok: false, code: "BULK_NOT_SENT", error: `No command was sent to any host.\n${detail}` };
}
return payload;
} finally {
chatLock?.release?.();
for (const sessionId of activeSessionIds) sessionIdleManager.endActivity(chatSessionId, sessionId);
for (const sessionId of sessionIds) {
if (pendingSessionWriteApprovals.get(sessionId) === BULK_RPC_METHOD) {
pendingSessionWriteApprovals.delete(sessionId);
}
}
}
}
return { run };
}
module.exports = {
BULK_RPC_METHOD,
CHAT_LOCK_HELD,
DEADLINE_GRACE_MS,
DEFAULT_TAIL_LINES,
MAX_BULK_TARGETS,
MAX_TAIL_LINES,
MIN_BULK_TARGETS,
classifyHostResult,
createExecBulkHandler,
formatPreflightFailure,
groupBulkResults,
parseBulkExecParams,
tailText,
};