fix(exec): skip node approval prepare in yolo mode

This commit is contained in:
Peter Steinberger
2026-04-27 01:27:32 +01:00
parent 11e17793e1
commit acd1bd7d31
4 changed files with 409 additions and 215 deletions

View File

@@ -7,6 +7,7 @@ Docs: https://docs.openclaw.ai
### Fixes
- macOS Gateway: write launchd services with a state-dir `WorkingDirectory`, use a durable state-dir temp path instead of freezing macOS session `TMPDIR`, create that temp directory before bootstrap, and label abort-shaped launchd exits as `SIGABRT/abort` in status output. Fixes #53679 and #70223; refs #71848. Thanks @dlturock, @stammi922, and @palladius.
- Exec/node: skip approval-plan preparation for full-trust `host=node` runs so interpreter and script commands no longer fail with `SYSTEM_RUN_DENIED: approval cannot safely bind` when effective policy is `security=full` and `ask=off`. Fixes #48457 and duplicate #69251. Thanks @ajtran303, @jaserNo1, @Blakeshannon, @lesliefag, and @AvIsBeastMC.
- Memory/QMD: prefer QMD's `--mask` collection pattern flag so root memory indexing stays scoped to `MEMORY.md` instead of widening to every markdown file in the workspace. Thanks @codex.
- Codex harness: normalize cached input tokens before session/context accounting so prompt cache reads are not double-counted in `/status`, `session_status`, or persisted `sessionEntry.totalTokens`. Fixes #69298. Thanks @richardmqq.
- Hooks/session-memory: use the host local timezone for memory filenames, fallback timestamp slugs, and markdown headers instead of UTC dates. Fixes #46703. (#46721) Thanks @Astro-Han.

View File

@@ -0,0 +1,312 @@
import crypto from "node:crypto";
import type { AgentToolResult } from "@mariozechner/pi-agent-core";
import {
type ExecApprovalsFile,
type ExecAsk,
type ExecSecurity,
type SystemRunApprovalPlan,
evaluateShellAllowlist,
hasDurableExecApproval,
resolveExecApprovalsFromFile,
} from "../infra/exec-approvals.js";
import {
describeInterpreterInlineEval,
detectInterpreterInlineEvalArgv,
} from "../infra/exec-inline-eval.js";
import { buildNodeShellCommand } from "../infra/node-shell.js";
import { parsePreparedSystemRunPayload } from "../infra/system-run-approval-context.js";
import type { ExecuteNodeHostCommandParams } from "./bash-tools.exec-host-node.js";
import type { ExecToolDetails } from "./bash-tools.exec-types.js";
import { callGatewayTool } from "./tools/gateway.js";
import { listNodes, resolveNodeIdFromList } from "./tools/nodes-utils.js";
export type NodeExecutionTarget = {
nodeId: string;
platform?: string | null;
argv: string[];
env: Record<string, string> | undefined;
invokeTimeoutMs: number;
};
export type PreparedNodeRun = {
plan: SystemRunApprovalPlan;
argv: string[];
rawCommand: string;
cwd: string | undefined;
agentId: string | undefined;
sessionKey: string | undefined;
};
export type NodeApprovalAnalysis = {
analysisOk: boolean;
allowlistSatisfied: boolean;
durableApprovalSatisfied: boolean;
inlineEvalHit: ReturnType<typeof detectInterpreterInlineEvalArgv>;
};
export function shouldSkipNodeApprovalPrepare(params: {
hostSecurity: ExecSecurity;
hostAsk: ExecAsk;
strictInlineEval?: boolean;
}): boolean {
return (
params.hostSecurity === "full" && params.hostAsk === "off" && params.strictInlineEval !== true
);
}
export function formatNodeRunToolResult(params: {
raw: unknown;
startedAt: number;
cwd: string | undefined;
}): AgentToolResult<ExecToolDetails> {
const payload =
params.raw && typeof params.raw === "object"
? (params.raw as { payload?: unknown }).payload
: undefined;
const payloadObj =
payload && typeof payload === "object" ? (payload as Record<string, unknown>) : {};
const stdout = typeof payloadObj.stdout === "string" ? payloadObj.stdout : "";
const stderr = typeof payloadObj.stderr === "string" ? payloadObj.stderr : "";
const errorText = typeof payloadObj.error === "string" ? payloadObj.error : "";
const success = typeof payloadObj.success === "boolean" ? payloadObj.success : false;
const exitCode = typeof payloadObj.exitCode === "number" ? payloadObj.exitCode : null;
return {
content: [
{
type: "text",
text: stdout || stderr || errorText || "",
},
],
details: {
status: success ? "completed" : "failed",
exitCode,
durationMs: Date.now() - params.startedAt,
aggregated: [stdout, stderr, errorText].filter(Boolean).join("\n"),
cwd: params.cwd,
} satisfies ExecToolDetails,
};
}
export async function resolveNodeExecutionTarget(
params: ExecuteNodeHostCommandParams,
): Promise<NodeExecutionTarget> {
if (params.boundNode && params.requestedNode && params.boundNode !== params.requestedNode) {
throw new Error(`exec node not allowed (bound to ${params.boundNode})`);
}
const nodeQuery = params.boundNode || params.requestedNode;
const nodes = await listNodes({});
if (nodes.length === 0) {
throw new Error(
"exec host=node requires a paired node (none available). This requires a companion app or node host.",
);
}
let nodeId: string;
try {
nodeId = resolveNodeIdFromList(nodes, nodeQuery, !nodeQuery);
} catch (err) {
if (!nodeQuery && String(err).includes("node required")) {
throw new Error(
"exec host=node requires a node id when multiple nodes are available (set tools.exec.node or exec.node).",
{ cause: err },
);
}
throw err;
}
const nodeInfo = nodes.find((entry) => entry.nodeId === nodeId);
const supportsSystemRun = Array.isArray(nodeInfo?.commands)
? nodeInfo?.commands?.includes("system.run")
: false;
if (!supportsSystemRun) {
throw new Error(
"exec host=node requires a node that supports system.run (companion app or node host).",
);
}
return {
nodeId,
platform: nodeInfo?.platform,
argv: buildNodeShellCommand(params.command, nodeInfo?.platform),
env: params.requestedEnv ? { ...params.requestedEnv } : undefined,
invokeTimeoutMs: Math.max(
10_000,
(typeof params.timeoutSec === "number" ? params.timeoutSec : params.defaultTimeoutSec) *
1000 +
5_000,
),
};
}
export function buildNodeSystemRunInvoke(params: {
target: NodeExecutionTarget;
command: string[];
rawCommand: string;
cwd: string | undefined;
timeoutSec: number | undefined;
agentId: string | undefined;
sessionKey: string | undefined;
approved?: boolean;
approvalDecision?: "allow-once" | "allow-always" | null;
runId?: string;
suppressNotifyOnExit?: boolean;
notifyOnExit?: boolean;
systemRunPlan?: SystemRunApprovalPlan;
}): Record<string, unknown> {
return {
nodeId: params.target.nodeId,
command: "system.run",
params: {
command: params.command,
rawCommand: params.rawCommand,
...(params.systemRunPlan ? { systemRunPlan: params.systemRunPlan } : {}),
...(params.cwd != null ? { cwd: params.cwd } : {}),
env: params.target.env,
timeoutMs: typeof params.timeoutSec === "number" ? params.timeoutSec * 1000 : undefined,
agentId: params.agentId,
sessionKey: params.sessionKey,
approved: params.approved,
approvalDecision: params.approvalDecision ?? undefined,
runId: params.runId ?? undefined,
suppressNotifyOnExit:
params.suppressNotifyOnExit === true || params.notifyOnExit === false ? true : undefined,
},
idempotencyKey: crypto.randomUUID(),
};
}
export async function invokeNodeSystemRunDirect(params: {
request: ExecuteNodeHostCommandParams;
target: NodeExecutionTarget;
}): Promise<AgentToolResult<ExecToolDetails>> {
const startedAt = Date.now();
const raw = await callGatewayTool(
"node.invoke",
{ timeoutMs: params.target.invokeTimeoutMs },
buildNodeSystemRunInvoke({
target: params.target,
command: params.target.argv,
rawCommand: params.request.command,
cwd: params.request.workdir,
timeoutSec: params.request.timeoutSec,
agentId: params.request.agentId,
sessionKey: params.request.sessionKey,
notifyOnExit: params.request.notifyOnExit,
}),
);
return formatNodeRunToolResult({ raw, startedAt, cwd: params.request.workdir });
}
export async function prepareNodeSystemRun(params: {
request: ExecuteNodeHostCommandParams;
target: NodeExecutionTarget;
}): Promise<PreparedNodeRun> {
const prepareRaw = await callGatewayTool(
"node.invoke",
{ timeoutMs: 15_000 },
{
nodeId: params.target.nodeId,
command: "system.run.prepare",
params: {
command: params.target.argv,
rawCommand: params.request.command,
...(params.request.workdir != null ? { cwd: params.request.workdir } : {}),
agentId: params.request.agentId,
sessionKey: params.request.sessionKey,
},
idempotencyKey: crypto.randomUUID(),
},
);
const prepared = parsePreparedSystemRunPayload(prepareRaw?.payload);
if (!prepared) {
throw new Error("invalid system.run.prepare response");
}
return {
plan: prepared.plan,
argv: prepared.plan.argv,
rawCommand: prepared.plan.commandText,
cwd: prepared.plan.cwd ?? params.request.workdir,
agentId: prepared.plan.agentId ?? params.request.agentId,
sessionKey: prepared.plan.sessionKey ?? params.request.sessionKey,
};
}
export async function analyzeNodeApprovalRequirement(params: {
request: ExecuteNodeHostCommandParams;
target: NodeExecutionTarget;
prepared: PreparedNodeRun;
hostSecurity: ExecSecurity;
hostAsk: ExecAsk;
}): Promise<NodeApprovalAnalysis> {
const baseAllowlistEval = evaluateShellAllowlist({
command: params.request.command,
allowlist: [],
safeBins: new Set(),
cwd: params.request.workdir,
env: params.request.env,
platform: params.target.platform,
trustedSafeBinDirs: params.request.trustedSafeBinDirs,
});
let analysisOk = baseAllowlistEval.analysisOk;
let allowlistSatisfied = false;
let durableApprovalSatisfied = false;
const inlineEvalHit =
params.request.strictInlineEval === true
? (baseAllowlistEval.segments
.map((segment) =>
detectInterpreterInlineEvalArgv(segment.resolution?.effectiveArgv ?? segment.argv),
)
.find((entry) => entry !== null) ?? null)
: null;
if (inlineEvalHit) {
params.request.warnings.push(
`Warning: strict inline-eval mode requires explicit approval for ${describeInterpreterInlineEval(
inlineEvalHit,
)}.`,
);
}
if ((params.hostAsk === "always" || params.hostSecurity === "allowlist") && analysisOk) {
try {
const approvalsSnapshot = await callGatewayTool<{ file: string }>(
"exec.approvals.node.get",
{ timeoutMs: 10_000 },
{ nodeId: params.target.nodeId },
);
const approvalsFile =
approvalsSnapshot && typeof approvalsSnapshot === "object"
? approvalsSnapshot.file
: undefined;
if (approvalsFile && typeof approvalsFile === "object") {
const resolved = resolveExecApprovalsFromFile({
file: approvalsFile as ExecApprovalsFile,
agentId: params.request.agentId,
overrides: { security: "full" },
});
// Allowlist-only precheck; safe bins are node-local and may diverge.
const allowlistEval = evaluateShellAllowlist({
command: params.request.command,
allowlist: resolved.allowlist,
safeBins: new Set(),
cwd: params.request.workdir,
env: params.request.env,
platform: params.target.platform,
trustedSafeBinDirs: params.request.trustedSafeBinDirs,
});
durableApprovalSatisfied = hasDurableExecApproval({
analysisOk: allowlistEval.analysisOk,
segmentAllowlistEntries: allowlistEval.segmentAllowlistEntries,
allowlist: resolved.allowlist,
commandText: params.prepared.rawCommand,
});
allowlistSatisfied = allowlistEval.allowlistSatisfied;
analysisOk = allowlistEval.analysisOk;
}
} catch {
// Fall back to requiring approval if node approvals cannot be fetched.
}
}
return {
analysisOk,
allowlistSatisfied,
durableApprovalSatisfied,
inlineEvalHit,
};
}

View File

@@ -238,6 +238,13 @@ describe("executeNodeHostCommand", () => {
});
it("forwards prepared systemRunPlan on async node invoke after approval", async () => {
resolveExecHostApprovalContextMock.mockReturnValue({
approvals: { allowlist: [], file: { version: 1, agents: {} } },
hostSecurity: "full",
hostAsk: "always",
askFallback: "deny",
});
const result = await executeNodeHostCommand({
command: "bun ./script.ts",
workdir: "/tmp/work",
@@ -259,11 +266,11 @@ describe("executeNodeHostCommand", () => {
);
await vi.waitFor(() => {
expect(callGatewayToolMock).toHaveBeenCalledTimes(2);
expect(callGatewayToolMock).toHaveBeenCalledTimes(3);
});
expect(callGatewayToolMock).toHaveBeenNthCalledWith(
2,
3,
"node.invoke",
expect.anything(),
expect.objectContaining({
@@ -277,9 +284,7 @@ describe("executeNodeHostCommand", () => {
);
});
it("suppresses node completion events when notifyOnExit is disabled", async () => {
requiresExecApprovalMock.mockReturnValue(false);
it("skips approval prepare in full/off mode", async () => {
await executeNodeHostCommand({
command: "bun ./script.ts",
workdir: "/tmp/work",
@@ -294,17 +299,28 @@ describe("executeNodeHostCommand", () => {
notifyOnExit: false,
});
expect(callGatewayToolMock).toHaveBeenNthCalledWith(
2,
expect(callGatewayToolMock).toHaveBeenCalledTimes(1);
expect(callGatewayToolMock).toHaveBeenCalledWith(
"node.invoke",
expect.anything(),
expect.objectContaining({
command: "system.run",
params: expect.objectContaining({
command: ["bash", "-lc", "bun ./script.ts"],
rawCommand: "bun ./script.ts",
suppressNotifyOnExit: true,
}),
}),
);
expect(callGatewayToolMock).toHaveBeenCalledWith(
"node.invoke",
expect.anything(),
expect.objectContaining({
params: expect.not.objectContaining({
systemRunPlan: expect.anything(),
}),
}),
);
});
it("denies timed-out inline-eval requests instead of invoking the node", async () => {

View File

@@ -1,26 +1,24 @@
import crypto from "node:crypto";
import type { AgentToolResult } from "@mariozechner/pi-agent-core";
import {
type ExecApprovalsFile,
type ExecAsk,
type ExecSecurity,
evaluateShellAllowlist,
hasDurableExecApproval,
requiresExecApproval,
resolveExecApprovalAllowedDecisions,
resolveExecApprovalsFromFile,
} from "../infra/exec-approvals.js";
import {
describeInterpreterInlineEval,
detectInterpreterInlineEvalArgv,
} from "../infra/exec-inline-eval.js";
import { buildNodeShellCommand } from "../infra/node-shell.js";
import { parsePreparedSystemRunPayload } from "../infra/system-run-approval-context.js";
import {
buildExecApprovalRequesterContext,
buildExecApprovalTurnSourceContext,
registerExecApprovalRequestForHostOrThrow,
} from "./bash-tools.exec-approval-request.js";
import {
analyzeNodeApprovalRequirement,
buildNodeSystemRunInvoke,
formatNodeRunToolResult,
invokeNodeSystemRunDirect,
prepareNodeSystemRun,
resolveNodeExecutionTarget,
shouldSkipNodeApprovalPrepare,
} from "./bash-tools.exec-host-node-phases.js";
import * as execHostShared from "./bash-tools.exec-host-shared.js";
import {
DEFAULT_NOTIFY_TAIL_CHARS,
@@ -29,7 +27,6 @@ import {
} from "./bash-tools.exec-runtime.js";
import type { ExecToolDetails } from "./bash-tools.exec-types.js";
import { callGatewayTool } from "./tools/gateway.js";
import { listNodes, resolveNodeIdFromList } from "./tools/nodes-utils.js";
export type ExecuteNodeHostCommandParams = {
command: string;
@@ -66,132 +63,27 @@ export async function executeNodeHostCommand(
ask: params.ask,
host: "node",
});
if (params.boundNode && params.requestedNode && params.boundNode !== params.requestedNode) {
throw new Error(`exec node not allowed (bound to ${params.boundNode})`);
const target = await resolveNodeExecutionTarget(params);
if (
shouldSkipNodeApprovalPrepare({
hostSecurity,
hostAsk,
strictInlineEval: params.strictInlineEval,
})
) {
return await invokeNodeSystemRunDirect({ request: params, target });
}
const nodeQuery = params.boundNode || params.requestedNode;
const nodes = await listNodes({});
if (nodes.length === 0) {
throw new Error(
"exec host=node requires a paired node (none available). This requires a companion app or node host.",
);
}
let nodeId: string;
try {
nodeId = resolveNodeIdFromList(nodes, nodeQuery, !nodeQuery);
} catch (err) {
if (!nodeQuery && String(err).includes("node required")) {
throw new Error(
"exec host=node requires a node id when multiple nodes are available (set tools.exec.node or exec.node).",
{ cause: err },
);
}
throw err;
}
const nodeInfo = nodes.find((entry) => entry.nodeId === nodeId);
const supportsSystemRun = Array.isArray(nodeInfo?.commands)
? nodeInfo?.commands?.includes("system.run")
: false;
if (!supportsSystemRun) {
throw new Error(
"exec host=node requires a node that supports system.run (companion app or node host).",
);
}
const argv = buildNodeShellCommand(params.command, nodeInfo?.platform);
const prepareRaw = await callGatewayTool(
"node.invoke",
{ timeoutMs: 15_000 },
{
nodeId,
command: "system.run.prepare",
params: {
command: argv,
rawCommand: params.command,
...(params.workdir != null ? { cwd: params.workdir } : {}),
agentId: params.agentId,
sessionKey: params.sessionKey,
},
idempotencyKey: crypto.randomUUID(),
},
);
const prepared = parsePreparedSystemRunPayload(prepareRaw?.payload);
if (!prepared) {
throw new Error("invalid system.run.prepare response");
}
const runArgv = prepared.plan.argv;
const runRawCommand = prepared.plan.commandText;
const runCwd = prepared.plan.cwd ?? params.workdir;
const runAgentId = prepared.plan.agentId ?? params.agentId;
const runSessionKey = prepared.plan.sessionKey ?? params.sessionKey;
const nodeEnv = params.requestedEnv ? { ...params.requestedEnv } : undefined;
const baseAllowlistEval = evaluateShellAllowlist({
command: params.command,
allowlist: [],
safeBins: new Set(),
cwd: params.workdir,
env: params.env,
platform: nodeInfo?.platform,
trustedSafeBinDirs: params.trustedSafeBinDirs,
const prepared = await prepareNodeSystemRun({ request: params, target });
const approvalAnalysis = await analyzeNodeApprovalRequirement({
request: params,
target,
prepared,
hostSecurity,
hostAsk,
});
let analysisOk = baseAllowlistEval.analysisOk;
let allowlistSatisfied = false;
let durableApprovalSatisfied = false;
const inlineEvalHit =
params.strictInlineEval === true
? (baseAllowlistEval.segments
.map((segment) =>
detectInterpreterInlineEvalArgv(segment.resolution?.effectiveArgv ?? segment.argv),
)
.find((entry) => entry !== null) ?? null)
: null;
if (inlineEvalHit) {
params.warnings.push(
`Warning: strict inline-eval mode requires explicit approval for ${describeInterpreterInlineEval(
inlineEvalHit,
)}.`,
);
}
if ((hostAsk === "always" || hostSecurity === "allowlist") && analysisOk) {
try {
const approvalsSnapshot = await callGatewayTool<{ file: string }>(
"exec.approvals.node.get",
{ timeoutMs: 10_000 },
{ nodeId },
);
const approvalsFile =
approvalsSnapshot && typeof approvalsSnapshot === "object"
? approvalsSnapshot.file
: undefined;
if (approvalsFile && typeof approvalsFile === "object") {
const resolved = resolveExecApprovalsFromFile({
file: approvalsFile as ExecApprovalsFile,
agentId: params.agentId,
overrides: { security: "full" },
});
// Allowlist-only precheck; safe bins are node-local and may diverge.
const allowlistEval = evaluateShellAllowlist({
command: params.command,
allowlist: resolved.allowlist,
safeBins: new Set(),
cwd: params.workdir,
env: params.env,
platform: nodeInfo?.platform,
trustedSafeBinDirs: params.trustedSafeBinDirs,
});
durableApprovalSatisfied = hasDurableExecApproval({
analysisOk: allowlistEval.analysisOk,
segmentAllowlistEntries: allowlistEval.segmentAllowlistEntries,
allowlist: resolved.allowlist,
commandText: runRawCommand,
});
allowlistSatisfied = allowlistEval.allowlistSatisfied;
analysisOk = allowlistEval.analysisOk;
}
} catch {
// Fall back to requiring approval if node approvals cannot be fetched.
}
}
const { analysisOk, allowlistSatisfied, durableApprovalSatisfied, inlineEvalHit } =
approvalAnalysis;
const requiresAsk =
requiresExecApproval({
ask: hostAsk,
@@ -200,40 +92,6 @@ export async function executeNodeHostCommand(
allowlistSatisfied,
durableApprovalSatisfied,
}) || inlineEvalHit !== null;
const invokeTimeoutMs = Math.max(
10_000,
(typeof params.timeoutSec === "number" ? params.timeoutSec : params.defaultTimeoutSec) * 1000 +
5_000,
);
const buildInvokeParams = (
approvedByAsk: boolean,
approvalDecision: "allow-once" | "allow-always" | null,
runId?: string,
suppressNotifyOnExit?: boolean,
) =>
({
nodeId,
command: "system.run",
params: {
command: runArgv,
rawCommand: runRawCommand,
systemRunPlan: prepared.plan,
cwd: runCwd,
env: nodeEnv,
timeoutMs: typeof params.timeoutSec === "number" ? params.timeoutSec * 1000 : undefined,
agentId: runAgentId,
sessionKey: runSessionKey,
approved: approvedByAsk,
approvalDecision:
approvalDecision === "allow-always" && inlineEvalHit !== null
? "allow-once"
: (approvalDecision ?? undefined),
runId: runId ?? undefined,
suppressNotifyOnExit:
suppressNotifyOnExit === true || params.notifyOnExit === false ? true : undefined,
},
idempotencyKey: crypto.randomUUID(),
}) satisfies Record<string, unknown>;
let inlineApprovedByAsk = false;
let inlineApprovalDecision: "allow-once" | "allow-always" | null = null;
@@ -250,15 +108,15 @@ export async function executeNodeHostCommand(
await registerExecApprovalRequestForHostOrThrow({
approvalId,
systemRunPlan: prepared.plan,
env: nodeEnv,
workdir: runCwd,
env: target.env,
workdir: prepared.cwd,
host: "node",
nodeId,
nodeId: target.nodeId,
security: hostSecurity,
ask: hostAsk,
...buildExecApprovalRequesterContext({
agentId: runAgentId,
sessionKey: runSessionKey,
agentId: prepared.agentId,
sessionKey: prepared.sessionKey,
}),
...buildExecApprovalTurnSourceContext(params),
});
@@ -324,7 +182,7 @@ export async function executeNodeHostCommand(
onFailure: () =>
void execHostShared.sendExecApprovalFollowupResult(
followupTarget,
`Exec denied (node=${nodeId} id=${approvalId}, approval-request-failed): ${params.command}`,
`Exec denied (node=${target.nodeId} id=${approvalId}, approval-request-failed): ${params.command}`,
),
});
if (decision === undefined) {
@@ -366,7 +224,7 @@ export async function executeNodeHostCommand(
if (deniedReason) {
await execHostShared.sendExecApprovalFollowupResult(
followupTarget,
`Exec denied (node=${nodeId} id=${approvalId}, ${deniedReason}): ${params.command}`,
`Exec denied (node=${target.nodeId} id=${approvalId}, ${deniedReason}): ${params.command}`,
);
return;
}
@@ -374,8 +232,25 @@ export async function executeNodeHostCommand(
try {
const raw = await callGatewayTool(
"node.invoke",
{ timeoutMs: invokeTimeoutMs },
buildInvokeParams(approvedByAsk, approvalDecision, approvalId, true),
{ timeoutMs: target.invokeTimeoutMs },
buildNodeSystemRunInvoke({
target,
command: prepared.argv,
rawCommand: prepared.rawCommand,
cwd: prepared.cwd,
timeoutSec: params.timeoutSec,
agentId: prepared.agentId,
sessionKey: prepared.sessionKey,
approved: approvedByAsk,
approvalDecision:
approvalDecision === "allow-always" && inlineEvalHit !== null
? "allow-once"
: approvalDecision,
runId: approvalId,
suppressNotifyOnExit: true,
notifyOnExit: params.notifyOnExit,
systemRunPlan: prepared.plan,
}),
);
const payload =
raw?.payload && typeof raw.payload === "object"
@@ -393,13 +268,13 @@ export async function executeNodeHostCommand(
const output = normalizeNotifyOutput(combined.slice(-DEFAULT_NOTIFY_TAIL_CHARS));
const exitLabel = payload.timedOut ? "timeout" : `code ${payload.exitCode ?? "?"}`;
const summary = output
? `Exec finished (node=${nodeId} id=${approvalId}, ${exitLabel})\n${output}`
: `Exec finished (node=${nodeId} id=${approvalId}, ${exitLabel})`;
? `Exec finished (node=${target.nodeId} id=${approvalId}, ${exitLabel})\n${output}`
: `Exec finished (node=${target.nodeId} id=${approvalId}, ${exitLabel})`;
await execHostShared.sendExecApprovalFollowupResult(followupTarget, summary);
} catch {
await execHostShared.sendExecApprovalFollowupResult(
followupTarget,
`Exec denied (node=${nodeId} id=${approvalId}, invoke-failed): ${params.command}`,
`Exec denied (node=${target.nodeId} id=${approvalId}, invoke-failed): ${params.command}`,
);
}
})();
@@ -416,7 +291,7 @@ export async function executeNodeHostCommand(
sentApproverDms,
unavailableReason,
allowedDecisions: resolveExecApprovalAllowedDecisions({ ask: hostAsk }),
nodeId,
nodeId: target.nodeId,
});
}
}
@@ -424,31 +299,21 @@ export async function executeNodeHostCommand(
const startedAt = Date.now();
const raw = await callGatewayTool(
"node.invoke",
{ timeoutMs: invokeTimeoutMs },
buildInvokeParams(inlineApprovedByAsk, inlineApprovalDecision, inlineApprovalId),
{ timeoutMs: target.invokeTimeoutMs },
buildNodeSystemRunInvoke({
target,
command: prepared.argv,
rawCommand: prepared.rawCommand,
cwd: prepared.cwd,
timeoutSec: params.timeoutSec,
agentId: prepared.agentId,
sessionKey: prepared.sessionKey,
approved: inlineApprovedByAsk,
approvalDecision: inlineApprovalDecision,
runId: inlineApprovalId,
notifyOnExit: params.notifyOnExit,
systemRunPlan: prepared.plan,
}),
);
const payload =
raw && typeof raw === "object" ? (raw as { payload?: unknown }).payload : undefined;
const payloadObj =
payload && typeof payload === "object" ? (payload as Record<string, unknown>) : {};
const stdout = typeof payloadObj.stdout === "string" ? payloadObj.stdout : "";
const stderr = typeof payloadObj.stderr === "string" ? payloadObj.stderr : "";
const errorText = typeof payloadObj.error === "string" ? payloadObj.error : "";
const success = typeof payloadObj.success === "boolean" ? payloadObj.success : false;
const exitCode = typeof payloadObj.exitCode === "number" ? payloadObj.exitCode : null;
return {
content: [
{
type: "text",
text: stdout || stderr || errorText || "",
},
],
details: {
status: success ? "completed" : "failed",
exitCode,
durationMs: Date.now() - startedAt,
aggregated: [stdout, stderr, errorText].filter(Boolean).join("\n"),
cwd: params.workdir,
} satisfies ExecToolDetails,
};
return formatNodeRunToolResult({ raw, startedAt, cwd: params.workdir });
}