mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-26 10:53:56 +00:00
* 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.
576 lines
25 KiB
JavaScript
576 lines
25 KiB
JavaScript
/* eslint-disable no-undef */
|
|
// Module-level require: code inside createExecHandlerApi runs under `with (ctx)`
|
|
// where bare `require` resolves to ctx.require (based in electron/bridges/).
|
|
const { clearSessionFlowState } = require("../terminalFlowAck.cjs");
|
|
const { getVisibleIdlePrompt } = require("../ai/shellUtils.cjs");
|
|
const { classifyShellReadiness } = require("../ai/shellReadinessState.cjs");
|
|
const { emitJobDiag } = require("../ai/jobStartupDiagnostics.cjs");
|
|
const {
|
|
ensureSessionShellKind,
|
|
remoteDisallowsExecChannelProbe, sessionDisallowsExtraSshChannel, ensureSessionShellKindForExec,
|
|
} = require("../ai/sessionShellKind.cjs");
|
|
const { CHAT_LOCK_HELD } = require("./execBulk.cjs");
|
|
|
|
function createExecHandlerApi(ctx) {
|
|
with (ctx) {
|
|
function resolveExecContext(params) {
|
|
const { sessionId, command } = params;
|
|
debugLog("handleExec:start", { sessionId, command, chatSessionId: params?.chatSessionId });
|
|
if (!sessionId || !command) throw new Error("sessionId and command are required");
|
|
if (typeof command !== 'string' || !command.trim()) {
|
|
return { ok: false, error: 'Invalid command', exitCode: 1 };
|
|
}
|
|
|
|
const session = sessions?.get(sessionId);
|
|
debugLog("handleExec:sessionLookup", {
|
|
sessionId,
|
|
found: Boolean(session),
|
|
protocol: session?.protocol || session?.type || null,
|
|
shellKind: session?.shellKind || null,
|
|
});
|
|
if (!session) return { ok: false, error: "Session not found" };
|
|
|
|
// Look up device type from metadata (set by renderer from Host.deviceType).
|
|
const chatSessionId = params?.chatSessionId || null;
|
|
const meta = getSessionMeta(sessionId, chatSessionId) || {};
|
|
// Mosh sessions use a shell-backed PTY and cannot connect to vendor CLIs,
|
|
// so network device mode only applies to SSH and serial sessions.
|
|
// Prefer session.protocol (runtime truth) over meta.protocol (renderer hint)
|
|
// because Mosh tabs report as protocol:"ssh" in metadata but "mosh" in session.
|
|
const sessionProtocol = session.protocol || session.type || meta.protocol || "";
|
|
const isSshOrSerial = sessionProtocol === "ssh" || sessionProtocol === "serial";
|
|
const isNetworkDevice = (meta.deviceType === "network" && isSshOrSerial) || sessionProtocol === "serial";
|
|
|
|
// The blocklist targets shell-specific patterns (rm -rf, eval, $(), etc.) that
|
|
// are meaningless on network device CLIs. Serial sessions skip the check because
|
|
// commands like "shutdown" (disable an interface) are routine on Cisco/Huawei.
|
|
//
|
|
// Design note: the serial protocol is explicitly chosen by the user in the UI
|
|
// for network devices / embedded systems. While startSerialSession technically
|
|
// supports PTY devices, users connecting to a Linux/BusyBox shell should use
|
|
// the "local" protocol (which goes through the normal shell path with blocklist).
|
|
// Additionally, execViaRawPty sends commands without shell wrapping, so shell
|
|
// metacharacters in blocklist patterns (eval, $(), backticks, pipes) cannot
|
|
// actually be interpreted even if sent to a serial-connected shell.
|
|
if ((session.protocol === "local" || session.type === "local") && session.shellKind === "unknown") {
|
|
return {
|
|
ok: false,
|
|
error: "AI execution is not supported for this local shell executable. Configure the local terminal to use bash/zsh/sh, fish, PowerShell/pwsh, or cmd.exe.",
|
|
};
|
|
}
|
|
|
|
const sshClient = session.conn || session.sshClient;
|
|
const ptyStream = session.stream || session.pty || session.proc;
|
|
return {
|
|
ok: true,
|
|
context: {
|
|
sessionId,
|
|
command,
|
|
session,
|
|
chatSessionId,
|
|
sessionProtocol,
|
|
isNetworkDevice,
|
|
sshClient,
|
|
ptyStream,
|
|
},
|
|
};
|
|
}
|
|
|
|
function handleExec(params, executionContext = {}) {
|
|
const resolved = resolveExecContext(params);
|
|
if (!resolved.ok) return resolved;
|
|
const {
|
|
sessionId,
|
|
command,
|
|
session,
|
|
chatSessionId,
|
|
sessionProtocol,
|
|
isNetworkDevice,
|
|
sshClient,
|
|
ptyStream,
|
|
} = resolved.context;
|
|
const reservation = reserveSessionExecution(sessionId, "exec");
|
|
if (!reservation.ok) return reservation;
|
|
const sessionToken = reservation.token;
|
|
// terminal_execute_bulk holds the per-chat lock once for the whole fan-out.
|
|
const executionLock = executionContext?.[CHAT_LOCK_HELD] === true
|
|
? { ok: true, release() {} }
|
|
: beginChatExecution(chatSessionId, sessionId, command);
|
|
if (!executionLock.ok) {
|
|
releaseSessionExecution(sessionId, sessionToken);
|
|
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: executionLock.active.command,
|
|
activeSessionId: executionLock.active.sessionId,
|
|
};
|
|
}
|
|
|
|
const runExecution = (factory) => {
|
|
try {
|
|
executionContext.beforeExecute?.();
|
|
return Promise.resolve(factory()).finally(() => {
|
|
releaseSessionExecution(sessionId, sessionToken);
|
|
executionLock.release();
|
|
});
|
|
} catch (err) {
|
|
releaseSessionExecution(sessionId, sessionToken);
|
|
executionLock.release();
|
|
return { ok: false, error: err?.message || String(err) };
|
|
}
|
|
};
|
|
|
|
// Network devices (switches/routers) connected via SSH: use raw execution.
|
|
// Their vendor CLIs (Huawei VRP, Cisco IOS, etc.) don't run a POSIX shell,
|
|
// so shell-wrapped commands with markers would fail. Raw mode sends commands
|
|
// as-is with idle-timeout completion detection — same as serial sessions.
|
|
if (isNetworkDevice && ptyStream && typeof ptyStream.write === "function") {
|
|
return runExecution(() => execViaRawPty(ptyStream, command, {
|
|
timeoutMs: commandTimeoutMs,
|
|
trackForCancellation: activePtyExecs,
|
|
chatSessionId: params?.chatSessionId,
|
|
encoding: "utf8", // SSH PTY streams use UTF-8, not latin1
|
|
}));
|
|
}
|
|
|
|
// Prefer the interactive PTY so the user sees command/output in-session.
|
|
if (ptyStream && typeof ptyStream.write === "function") {
|
|
// Probe remote login shell once when shellKind is unset so fish
|
|
// sessions get the fish wrapper instead of the posix default (#1854).
|
|
// Cancellable: Stop during the probe must not still type the command.
|
|
return runExecution(async () => {
|
|
const probed = await ensureSessionShellKindForExec(session, {
|
|
trackForCancellation: activePtyExecs,
|
|
chatSessionId,
|
|
});
|
|
if (!probed.ok) return probed;
|
|
executionContext.beforeExecute?.();
|
|
const safety = checkCommandSafetyForShell(command, resolveSessionBlocklistShellKind(session));
|
|
if (safety.blocked) {
|
|
debugLog("handleExec:blocklisted", { sessionId, matchedPattern: safety.matchedPattern });
|
|
return { ok: false, error: `Command blocked by safety policy. Pattern: ${safety.matchedPattern}` };
|
|
}
|
|
return execViaPty(ptyStream, command, {
|
|
beforeInput: executionContext.beforeExecute,
|
|
onInterrupt: () => clearSessionFlowState(session),
|
|
trackForCancellation: activePtyExecs,
|
|
timeoutMs: commandTimeoutMs,
|
|
shellKind: session.shellKind,
|
|
loginShellHint: session._loginShellKind,
|
|
probeLiveShell: true,
|
|
bastionKeystrokes: remoteDisallowsExecChannelProbe(session.remoteSshVersion),
|
|
skipPendingInputClear: session.singleChannelSsh === true,
|
|
onProbeAborted: (marker) => echoCommandToSession(session, sessionId, `${marker}_R`, { syntheticEcho: false }),
|
|
onEchoSuppressionPrime: (marker) => echoCommandToSession(session, sessionId, `${marker}_I`, { syntheticEcho: false }),
|
|
expectedPrompt: getFreshIdlePrompt(session),
|
|
getReadyPrompt: typeof session._promptTrackTail === "string"
|
|
? () => getFreshIdlePrompt(session) || getVisibleIdlePrompt(session) : undefined,
|
|
classifyReadiness: () => classifyShellReadiness(session),
|
|
typedInput: true,
|
|
echoCommand: (rawCommand) => echoCommandToSession(session, sessionId, rawCommand),
|
|
chatSessionId,
|
|
// MCP callers have terminal_start as a fallback for long commands,
|
|
// so enforce a hard wall-clock timeout here to match the MCP budget.
|
|
enforceWallTimeout: true,
|
|
});
|
|
});
|
|
}
|
|
|
|
// Network devices require an interactive PTY for raw command execution.
|
|
// If we got here, ptyStream wasn't writable — there's no usable channel.
|
|
if (isNetworkDevice) {
|
|
releaseSessionExecution(sessionId, sessionToken);
|
|
executionLock.release();
|
|
return { ok: false, error: "Network device session has no writable PTY stream for command execution" };
|
|
}
|
|
|
|
// Fallback: SSH exec channel (invisible to terminal).
|
|
// At this point ptyStream is not writable (already returned above if it was).
|
|
if (!session.singleChannelSsh && sshClient && typeof sshClient.exec === "function") {
|
|
return runExecution(async () => {
|
|
const probed = await ensureSessionShellKindForExec(session, {
|
|
trackForCancellation: activePtyExecs,
|
|
chatSessionId,
|
|
});
|
|
if (!probed.ok) return probed;
|
|
executionContext.beforeExecute?.();
|
|
const safety = checkCommandSafetyForShell(command, resolveSessionBlocklistShellKind(session));
|
|
if (safety.blocked) {
|
|
debugLog("handleExec:blocklisted", { sessionId, matchedPattern: safety.matchedPattern });
|
|
return { ok: false, error: `Command blocked by safety policy. Pattern: ${safety.matchedPattern}` };
|
|
}
|
|
return execViaChannel(sshClient, command, {
|
|
timeoutMs: commandTimeoutMs,
|
|
trackForCancellation: activePtyExecs,
|
|
// Pass chatSessionId so cancelPtyExecsForSession can interrupt this
|
|
// exec channel when the originating SDK agent run is stopped.
|
|
chatSessionId: params?.chatSessionId,
|
|
});
|
|
});
|
|
}
|
|
|
|
// Serial port: raw command execution (no shell wrapping)
|
|
if (session.protocol === "serial" && session.serialPort && typeof session.serialPort.write === "function") {
|
|
if (session.ymodemActive || session.zmodemSentry?.isActive?.()) {
|
|
releaseSessionExecution(sessionId, sessionToken);
|
|
executionLock.release();
|
|
return { ok: false, error: "Serial file transfer is already in progress" };
|
|
}
|
|
return runExecution(() => execViaRawPty(session.serialPort, command, {
|
|
timeoutMs: commandTimeoutMs,
|
|
trackForCancellation: activePtyExecs,
|
|
chatSessionId: params?.chatSessionId,
|
|
encoding: session.serialEncoding || "utf8",
|
|
}));
|
|
}
|
|
|
|
releaseSessionExecution(sessionId, sessionToken);
|
|
executionLock.release();
|
|
return { ok: false, error: "Session does not support command execution" };
|
|
}
|
|
|
|
/**
|
|
* Side-effect-free (apart from the cached shell-kind probe handleExec also
|
|
* runs) check that handleExec would accept this command on this session.
|
|
* Mirrors handleExec's transport order; used by terminal_execute_bulk to
|
|
* validate every target before any command is sent.
|
|
*/
|
|
async function preflightExec(params, { probe = true } = {}) {
|
|
const resolved = resolveExecContext(params);
|
|
if (!resolved.ok) return resolved;
|
|
const { session, sessionId, command, chatSessionId, isNetworkDevice, sshClient, ptyStream } = resolved.context;
|
|
const hasWritablePty = Boolean(ptyStream && typeof ptyStream.write === "function");
|
|
const checkShellCommand = async () => {
|
|
let safety;
|
|
if (probe) {
|
|
const probed = await ensureSessionShellKindForExec(session, {
|
|
trackForCancellation: activePtyExecs,
|
|
chatSessionId,
|
|
});
|
|
if (!probed.ok) return probed;
|
|
safety = checkCommandSafetyForShell(command, resolveSessionBlocklistShellKind(session));
|
|
} else {
|
|
// Nothing may touch the remote host yet (no approval has been given): use the
|
|
// shell kind only if it is already known, otherwise the shell-independent
|
|
// patterns. The authoritative check re-runs after approval, and again at exec.
|
|
const knownKind = resolveSessionBlocklistShellKind(session);
|
|
safety = knownKind
|
|
? checkCommandSafetyForShell(command, knownKind)
|
|
: checkCommandSafetyCommonOnly(command);
|
|
}
|
|
if (safety.blocked) {
|
|
debugLog("preflightExec:blocklisted", { sessionId, matchedPattern: safety.matchedPattern });
|
|
return { ok: false, error: `Command blocked by safety policy. Pattern: ${safety.matchedPattern}` };
|
|
}
|
|
return { ok: true };
|
|
};
|
|
|
|
if (isNetworkDevice && hasWritablePty) return { ok: true };
|
|
if (hasWritablePty) return checkShellCommand();
|
|
if (isNetworkDevice) {
|
|
return { ok: false, error: "Network device session has no writable PTY stream for command execution" };
|
|
}
|
|
if (!session.singleChannelSsh && sshClient && typeof sshClient.exec === "function") {
|
|
return checkShellCommand();
|
|
}
|
|
if (session.protocol === "serial" && session.serialPort && typeof session.serialPort.write === "function") {
|
|
if (session.ymodemActive || session.zmodemSentry?.isActive?.()) {
|
|
return { ok: false, error: "Serial file transfer is already in progress" };
|
|
}
|
|
return { ok: true };
|
|
}
|
|
return { ok: false, error: "Session does not support command execution" };
|
|
}
|
|
|
|
function handleJobStart(params, executionContext = {}) {
|
|
const resolved = resolveExecContext(params);
|
|
if (!resolved.ok) return resolved;
|
|
const {
|
|
sessionId,
|
|
command,
|
|
session,
|
|
chatSessionId,
|
|
isNetworkDevice,
|
|
sessionProtocol,
|
|
ptyStream,
|
|
} = resolved.context;
|
|
|
|
if (isNetworkDevice || sessionProtocol === "serial") {
|
|
return {
|
|
ok: false,
|
|
error: "Background execution currently supports shell-backed PTY sessions only.",
|
|
};
|
|
}
|
|
|
|
if (!ptyStream || typeof ptyStream.write !== "function") {
|
|
return {
|
|
ok: false,
|
|
error: "Background execution requires a writable PTY-backed terminal session.",
|
|
};
|
|
}
|
|
|
|
const reservation = reserveSessionExecution(sessionId, "job");
|
|
if (!reservation.ok) return reservation;
|
|
const sessionToken = reservation.token;
|
|
|
|
const jobId = createBackgroundJobId();
|
|
const timeoutMs = Math.max(commandTimeoutMs, DEFAULT_BACKGROUND_JOB_TIMEOUT_MS);
|
|
const startedAt = Date.now();
|
|
|
|
// Register the job *before* the shell-kind probe so chat-delete /
|
|
// cancelBackgroundJobsForSession can see it while we await. Without
|
|
// this, the first terminal_start on an unprobed remote session has no
|
|
// backgroundJobs entry during the probe and still starts the PTY job
|
|
// after cancel (Codex P2 on #2061). Not registered in activePtyExecs —
|
|
// terminal_start is designed to survive SDK Stop; only chat cancel
|
|
// (which walks backgroundJobs) should abort a pending start.
|
|
let probeCancelRequested = false;
|
|
const job = {
|
|
id: jobId,
|
|
sessionId,
|
|
chatSessionId: chatSessionId || null,
|
|
command,
|
|
status: "running",
|
|
startedAt,
|
|
updatedAt: startedAt,
|
|
exitCode: null,
|
|
error: null,
|
|
stdout: "",
|
|
outputBaseOffset: 0,
|
|
totalOutputChars: 0,
|
|
outputTruncated: false,
|
|
pendingShellProbe: true,
|
|
handle: {
|
|
cancel: () => {
|
|
probeCancelRequested = true;
|
|
},
|
|
},
|
|
};
|
|
backgroundJobs.set(jobId, job);
|
|
|
|
// Probe so fish login shells are not mis-wrapped as posix (#1854).
|
|
return Promise.resolve(ensureSessionShellKind(session)).then(() => {
|
|
if (probeCancelRequested || job.status === "stopping") {
|
|
job.status = "cancelled";
|
|
job.error = "Cancelled";
|
|
job.updatedAt = Date.now();
|
|
job.pendingShellProbe = false;
|
|
releaseSessionExecution(sessionId, sessionToken);
|
|
return {
|
|
ok: false,
|
|
error: "Cancelled",
|
|
jobId,
|
|
sessionId,
|
|
status: "cancelled",
|
|
};
|
|
}
|
|
|
|
const safety = checkCommandSafetyForShell(command, resolveSessionBlocklistShellKind(session));
|
|
if (safety.blocked) {
|
|
job.status = "failed";
|
|
job.error = `Command blocked by safety policy. Pattern: ${safety.matchedPattern}`;
|
|
job.updatedAt = Date.now();
|
|
job.pendingShellProbe = false;
|
|
backgroundJobs.delete(jobId);
|
|
releaseSessionExecution(sessionId, sessionToken);
|
|
return { ok: false, error: job.error };
|
|
}
|
|
|
|
let handle;
|
|
try {
|
|
executionContext.beforeExecute?.();
|
|
handle = startPtyJob(ptyStream, command, {
|
|
beforeInput: executionContext.beforeExecute,
|
|
onInterrupt: () => clearSessionFlowState(session),
|
|
// Intentionally do NOT register in activePtyExecs: terminal_start jobs
|
|
// are designed to survive SDK agent "Stop" so the model can stop polling
|
|
// without aborting a long-running build/scan/log stream. The job is
|
|
// managed via terminal_stop and the per-session execution lock.
|
|
timeoutMs,
|
|
sessionId,
|
|
jobId,
|
|
diagnosticsSession: session,
|
|
shellKind: session.shellKind,
|
|
loginShellHint: session._loginShellKind,
|
|
probeLiveShell: true,
|
|
bastionKeystrokes: remoteDisallowsExecChannelProbe(session.remoteSshVersion),
|
|
skipPendingInputClear: session.singleChannelSsh === true,
|
|
onProbeAborted: (marker) => echoCommandToSession(session, sessionId, `${marker}_R`, { syntheticEcho: false }),
|
|
onEchoSuppressionPrime: (marker) => echoCommandToSession(session, sessionId, `${marker}_I`, { syntheticEcho: false }),
|
|
chatSessionId,
|
|
expectedPrompt: getFreshIdlePrompt(session),
|
|
getReadyPrompt: typeof session._promptTrackTail === "string"
|
|
? () => getFreshIdlePrompt(session) || getVisibleIdlePrompt(session) : undefined,
|
|
classifyReadiness: () => classifyShellReadiness(session),
|
|
typedInput: true,
|
|
echoCommand: (rawCommand) => echoCommandToSession(session, sessionId, rawCommand),
|
|
maxBufferedChars: MAX_BACKGROUND_JOB_OUTPUT_CHARS,
|
|
normalizeFinalOutput: false,
|
|
});
|
|
} catch (err) {
|
|
job.status = "failed";
|
|
job.error = err?.message || String(err);
|
|
job.updatedAt = Date.now();
|
|
job.pendingShellProbe = false;
|
|
releaseSessionExecution(sessionId, sessionToken);
|
|
return { ok: false, error: err?.message || String(err) };
|
|
}
|
|
|
|
job.handle = handle;
|
|
job.pendingShellProbe = false;
|
|
|
|
handle.resultPromise.then((result) => {
|
|
job.updatedAt = Date.now();
|
|
job.exitCode = result.exitCode ?? null;
|
|
job.code = result.code;
|
|
storeCompletedJobOutput(job, result.stdout || "", result);
|
|
const isForcedCancel = typeof result.error === "string" && result.error.includes("forced");
|
|
if (result.error === "Cancelled" || isForcedCancel) {
|
|
// Forced cancel means the process ignored SIGINT for the cancel
|
|
// wall-clock window. We mark the job as cancelled and release the
|
|
// lock so the session is reusable; the error message tells the
|
|
// caller the process may still be running so subsequent commands
|
|
// should be considered carefully. This is consistent: callers see
|
|
// completed=true exactly when the lock is no longer held.
|
|
job.status = "cancelled";
|
|
job.error = result.error;
|
|
releaseSessionExecution(sessionId, sessionToken);
|
|
return;
|
|
}
|
|
if (result.error) {
|
|
job.status = "failed";
|
|
job.error = result.error;
|
|
releaseSessionExecution(sessionId, sessionToken);
|
|
return;
|
|
}
|
|
// A non-zero exit code without an error message still represents a
|
|
// failed command (e.g. a build/test that returned 1). Mark it as failed
|
|
// so callers don't have to special-case exitCode against status.
|
|
if (typeof result.exitCode === "number" && result.exitCode !== 0) {
|
|
job.status = "failed";
|
|
job.error = `Command exited with code ${result.exitCode}`;
|
|
releaseSessionExecution(sessionId, sessionToken);
|
|
return;
|
|
}
|
|
job.status = "completed";
|
|
releaseSessionExecution(sessionId, sessionToken);
|
|
}).catch((err) => {
|
|
job.updatedAt = Date.now();
|
|
job.status = "failed";
|
|
job.error = err?.message || String(err);
|
|
storeCompletedJobOutput(job, job.stdout || "");
|
|
releaseSessionExecution(sessionId, sessionToken);
|
|
});
|
|
|
|
return {
|
|
ok: true,
|
|
jobId,
|
|
sessionId,
|
|
command,
|
|
status: "running",
|
|
startedAt,
|
|
outputMode: "foreground-mirrored",
|
|
recommendedPollIntervalMs: DEFAULT_BACKGROUND_JOB_POLL_INTERVAL_MS,
|
|
};
|
|
}).catch((err) => {
|
|
// Probe (or unexpected rejection) must not leave the session lock held.
|
|
job.status = "failed";
|
|
job.error = err?.message || String(err);
|
|
job.updatedAt = Date.now();
|
|
job.pendingShellProbe = false;
|
|
releaseSessionExecution(sessionId, sessionToken);
|
|
return { ok: false, error: err?.message || String(err) };
|
|
});
|
|
}
|
|
|
|
function getScopedJob(jobId, chatSessionId) {
|
|
const job = backgroundJobs.get(jobId);
|
|
if (!job) return null;
|
|
// Per-chat isolation: a job started under a chat session can only be
|
|
// accessed by callers presenting the same chatSessionId. Unscoped or
|
|
// statically-scoped callers cannot reach into another chat's jobs.
|
|
if (job.chatSessionId) {
|
|
if (!chatSessionId || job.chatSessionId !== chatSessionId) {
|
|
return null;
|
|
}
|
|
}
|
|
return job;
|
|
}
|
|
|
|
// A worker job whose route is gone falls through to these handlers, so the
|
|
// miss must be logged here as well as in the worker-route handlers.
|
|
function logJobLookupMiss(op, jobId, chatSessionId) {
|
|
emitJobDiag("job-stop-miss", {
|
|
jobId,
|
|
chatSessionId: chatSessionId || null,
|
|
op,
|
|
reason: backgroundJobs.has(jobId) ? "scope-mismatch" : "job-missing",
|
|
});
|
|
}
|
|
|
|
function handleJobPoll(params) {
|
|
const { jobId, offset = 0, chatSessionId, scopedSessionIds } = params || {};
|
|
if (!jobId) throw new Error("jobId is required");
|
|
const job = getScopedJob(jobId, chatSessionId || null);
|
|
if (!job) {
|
|
logJobLookupMiss("poll", jobId, chatSessionId);
|
|
return { ok: false, error: "Background job not found" };
|
|
}
|
|
// Re-check session scope so a caller that lost access to the host
|
|
// cannot continue reading output from jobs on that session.
|
|
// Covers dynamic (chatSessionId) and static (scopedSessionIds) modes.
|
|
if (job.sessionId) {
|
|
const scopeErr = validateSessionScope(job.sessionId, chatSessionId || null, scopedSessionIds);
|
|
if (scopeErr) return { ok: false, error: scopeErr };
|
|
}
|
|
return serializeBackgroundJob(job, offset);
|
|
}
|
|
|
|
function handleJobStop(params) {
|
|
const { jobId, chatSessionId, scopedSessionIds } = params || {};
|
|
if (!jobId) throw new Error("jobId is required");
|
|
const job = getScopedJob(jobId, chatSessionId || null);
|
|
if (!job) {
|
|
logJobLookupMiss("stop", jobId, chatSessionId);
|
|
return { ok: false, error: "Background job not found" };
|
|
}
|
|
// For statically scoped MCP clients, validate that the job's session is
|
|
// within the caller's static scope so a foreign jobId cannot cancel jobs
|
|
// outside the caller's allowed sessions. Dynamic chat scope is already
|
|
// enforced by getScopedJob (caller's chatSessionId must match the job's),
|
|
// and we intentionally do NOT re-check dynamic scope here so jobs can
|
|
// still be stopped after workspace membership changes — otherwise the
|
|
// session lock would stay held forever.
|
|
if (Array.isArray(scopedSessionIds) && job.sessionId) {
|
|
if (!scopedSessionIds.includes(job.sessionId)) {
|
|
return { ok: false, error: `Session "${job.sessionId}" is not in the current scope.` };
|
|
}
|
|
}
|
|
if (job.status === "running") {
|
|
try {
|
|
job.handle?.cancel?.();
|
|
} catch (err) {
|
|
return { ok: false, error: err?.message || String(err) };
|
|
}
|
|
job.status = "stopping";
|
|
job.error = "Cancellation requested";
|
|
job.updatedAt = Date.now();
|
|
}
|
|
return serializeBackgroundJob(job, 0);
|
|
}
|
|
|
|
return {
|
|
resolveExecContext,
|
|
preflightExec,
|
|
handleExec,
|
|
handleJobStart,
|
|
getScopedJob,
|
|
handleJobPoll,
|
|
handleJobStop,
|
|
};
|
|
}
|
|
}
|
|
|
|
module.exports = { createExecHandlerApi };
|