openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,378 lines (1,377 loc) • 49.1 kB
JavaScript
import { i as asOptionalObjectRecord } from "./record-coerce-CVPuDqcc.mjs";
import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs";
import { a as openRootFile } from "./boundary-file-read-BfaFLDqt.mjs";
import { t as canAccess } from "./path-existence-Co7-GyVr.mjs";
import { i as createAbortError, o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as FsSafeError, w as root } from "./fs-safe-BbWvmdVn.mjs";
import { t as createLazyImportLoader } from "./lazy-promise-DiCvjz9w.mjs";
import { r as decodeUtf8Input } from "./utf8-input-BHczGT8v.mjs";
import { o as PROCESS_TOOL_DISPLAY_SUMMARY } from "./tool-catalog-C1ALpCJD.mjs";
import { p as bindAgentToolReplaySafety, t as bindAgentToolActionDescriptor } from "./agent-tool-metadata-nrQgRaqv.mjs";
import { n as ToolInputError } from "./tool-input-error-B1hgavSw.mjs";
import { t as DEFAULT_MAX_BYTES } from "./truncate-DCXARhAL.mjs";
import { r as resolveSkillFileHost } from "./skill-file-host-DYVvMKod.mjs";
import { n as resolveSkillReadPath, r as resolveWorkspaceSkillSourcePath } from "./workspace-skill-read-path-nJAkXHnD.mjs";
import { i as getAgentWorkspaceAccess, t as WorkspaceAccessUnavailableError } from "./workspace-access-CnjZBg1i.mjs";
import { a as markHostRootEscape, i as isPathBoundaryEscapeError, m as resolveHostWorkspaceRoot, n as assertSandboxPath, p as resolveHostRootAsync, r as isHostRootEscapeError } from "./sandbox-paths-CGD5HJYL.mjs";
import { a as resolvePathFromInput, c as toRelativeSandboxPath, n as preserveAtPrefixedRelativePath, o as resolveSandboxPathMapping, r as relativePathInsideSandboxRoot } from "./path-policy-CyYRyWre.mjs";
import { a as resolveLocalPathToCwd, o as resolveToCwd } from "./path-utils-B5H__xjt.mjs";
import { i as normalizeFileToolPathParam } from "./agent-tools.params-D3Fjhk01.mjs";
import { i as toDisplayPath, r as resolveApplyPatchInputPath } from "./apply-patch-paths-CccblVw-.mjs";
import { r as captureAgentToolSourceExecutionGuard, s as runWithAgentToolSourceExecutionScope } from "./agent-tool-source-execution-guard-CD-ezY7E.mjs";
import { i as resolveToolResultBudget, s as toolResultFitsBudget } from "./tool-result-limits-BISboI8s.mjs";
import { r as describeProcessTool } from "./bash-tools.descriptions-CjRLwO0Y.mjs";
import { c as processSchema } from "./exec-tool-timeout-CpkOuB67.mjs";
import { t as createLazyExecTool } from "./lazy-exec-tool-C-cI3niu.mjs";
import { n as withToolOperatorHint } from "./tool-operator-hint-BZarHbv6.mjs";
import { a as normalizePositiveLimit, c as assertFileToolNotAborted, f as wrapToolDefinition, n as createReadTool, s as lsSchema } from "./tools-EkGDfRbZ.mjs";
import { r as withFileMutationQueueKeysResolution, t as resolveFileMutationQueueKey } from "./file-mutation-queue-C-FUKJ7m.mjs";
import "./read-file-page-D9qANuJA.mjs";
import { a as resolveReadOnlyWorkspaceSkillMounts } from "./workspace-mounts-CKCN0wG6.mjs";
import { r as resolveSandboxFileMutationQueueKey } from "./file-mutation-identity-B9yq_vIv.mjs";
import { n as withMemoryWriteProvenance } from "./memory-write-provenance-z3UaKwZY.mjs";
import { t as buildSandboxFsMounts } from "./fs-paths-BcNIEM2k.mjs";
import { a as createSandboxedReadTool, c as wrapReadToolWithSkillContent, d as writeHostFile, i as createSandboxedEditTool, l as wrapSandboxFileToolPath, n as createHostWorkspaceWriteTool, o as createSandboxedWriteTool, r as createOpenClawReadTool, s as resolveAdaptiveReadMaxBytes, t as createHostWorkspaceEditTool, u as wrapToolWorkspaceRootGuardWithOptions } from "./agent-tools.read-B-sEhFib.mjs";
import { t as ProcessToolOutputSchema } from "./bash-tools.process-schema-UWH4XghY.mjs";
import fs from "node:fs";
import path from "node:path";
import fs$1, { readdir } from "node:fs/promises";
import { promisify } from "node:util";
import { PATH_ALIAS_POLICIES } from "@openclaw/fs-safe/advanced";
import { Type } from "typebox";
//#region src/agents/apply-patch-containment-hint.ts
/**
* Remediation for apply_patch workspace containment.
*
* Which control imposed the boundary decides which remedy is true, so the runtime owner
* names its own source rather than the tool guessing from configuration it cannot see.
*/
const HINTS = {
"required-root": "apply_patch is contained by this run's required workspace root. Full session permission mode and workspaceOnly configuration settings do not lift this boundary. Keep patch paths within the required root.",
config: "apply_patch is workspace-contained by configuration. Both tools.exec.applyPatch.workspaceOnly and tools.fs.workspaceOnly impose this independently, so clearing one can leave the other in force. tools.exec.mode does not affect it.",
session: "apply_patch is workspace-contained by this session's permission mode. Only a full permission mode lifts it; configuration settings do not override a session mode."
};
/**
* Keep workspace binding guidance model-visible and permission controls operator-only.
* Container mounts cannot be rebound by selecting a host cwd.
*/
function withApplyPatchContainmentHint(e, t, n) {
if (!isHostRootEscapeError(e)) return e;
const r = n ? markHostRootEscape(new Error(`${e.message}. Keep patch paths within the bound root. For an authorized task in another repository, ask the parent to respawn the worker with sessions_spawn and cwd set to that repository. Changing exec workdir does not rebind file tools.`, { cause: e })) : e;
return t ? withToolOperatorHint(r, HINTS[t]) : r;
}
//#endregion
//#region src/agents/apply-patch-file-ops.ts
const readFileDescriptor = promisify(fs.readFile);
const closeFileDescriptor = promisify(fs.close);
async function createPatchTarget(e) {
if (await e.ops.createFileExclusive(e.target.resolved, e.contents) === "exists") throw new Error(`Cannot create ${e.target.display}: the file already exists. ${e.hint}`);
}
async function resolvePatchFileOps(e) {
const t = captureAgentToolSourceExecutionGuard(e.signal);
if (e.sandbox) {
const { root: n, bridge: r } = e.sandbox;
return withPatchMemoryWriteProvenance(e.memoryWriteProvenance, {
readFile: (i) => runWithAgentToolSourceExecutionScope(t, async () => {
const a = await r.readFile({
filePath: i,
cwd: n,
signal: e.signal
});
t();
return decodeUtf8Input(a, `File ${i}`);
}),
writeFile: (i, a) => runWithAgentToolSourceExecutionScope(t, async () => {
t();
await r.writeFile({
filePath: i,
cwd: n,
data: a,
signal: e.signal
});
}),
createFileExclusive: (i, a) => runWithAgentToolSourceExecutionScope(t, async () => {
if (!r.createFileExclusive) throw new Error("Sandbox filesystem bridge does not support atomic file creation; refusing to overwrite an existing path.");
t();
return await r.createFileExclusive({
filePath: i,
cwd: n,
data: a,
mkdir: true,
signal: e.signal
});
}),
remove: (i) => runWithAgentToolSourceExecutionScope(t, async () => {
t();
await r.remove({
filePath: i,
cwd: n,
force: false,
signal: e.signal
});
})
});
}
if (e.workspaceOnly === false) return withPatchMemoryWriteProvenance(e.memoryWriteProvenance, {
readFile: (e) => runWithAgentToolSourceExecutionScope(t, async () => {
const n = await fs$1.readFile(e);
t();
return decodeUtf8Input(n, `File ${e}`);
}),
writeFile: async (t, n) => {
await writeHostFile(t, n, e.signal);
},
createFileExclusive: async (e, n) => {
try {
await runWithAgentToolSourceExecutionScope(t, async () => {
t();
await fs$1.writeFile(e, n, {
encoding: "utf8",
flag: "wx"
});
});
return "created";
} catch (e) {
if (e.code === "EEXIST") return "exists";
throw e;
}
},
remove: (e) => runWithAgentToolSourceExecutionScope(t, async () => {
t();
await fs$1.rm(e);
}),
mkdirp: async (e) => {
await runWithAgentToolSourceExecutionScope(t, async () => {
t();
await fs$1.mkdir(e, { recursive: true });
});
}
});
const n = e.root ?? e.cwd;
const r = await root(n, { assertBeforeMutation: t });
const i = /* @__PURE__ */ new Map([[path.resolve(n), r]]);
const resolveTarget = async (e) => {
const r = await resolveHostRootAsync(n, e);
const a = toRelativeSandboxPath(r, e);
let o = i.get(r);
if (!o) {
o = await root(r, { assertBeforeMutation: t });
i.set(r, o);
}
const assertBeforeMutation = () => {
t();
toRelativeSandboxPath(resolveHostWorkspaceRoot(n, e), e);
};
return {
root: o,
relative: a,
assertBeforeMutation
};
};
return withPatchMemoryWriteProvenance(e.memoryWriteProvenance, {
readFile: (e) => runWithAgentToolSourceExecutionScope(t, async () => {
const r = await resolveHostRootAsync(n, e);
const i = await openRootFile({
absolutePath: e,
rootPath: r,
boundaryLabel: "workspace root",
symlinks: "follow-parents-within-root"
});
assertBoundaryRead(i, e);
try {
t();
const n = await readFileDescriptor(i.fd);
t();
return decodeUtf8Input(n, `File ${e}`);
} finally {
await closeFileDescriptor(i.fd);
}
}),
writeFile: async (e, n) => {
await runWithAgentToolSourceExecutionScope(t, async () => {
const { root: t, relative: r, assertBeforeMutation: i } = await resolveTarget(e);
i();
await t.write(path.resolve(t.rootReal, r), n, {
encoding: "utf8",
mutationSymlinks: "follow-parents-within-root",
assertBeforeMutation: i
}).catch(rethrowHostMutationError);
});
},
createFileExclusive: async (e, n) => {
try {
await runWithAgentToolSourceExecutionScope(t, async () => {
const { root: t, relative: r, assertBeforeMutation: i } = await resolveTarget(e);
i();
await t.create(path.resolve(t.rootReal, r), n, {
encoding: "utf8",
mutationSymlinks: "reject",
assertBeforeMutation: i
});
});
return "created";
} catch (e) {
if (e instanceof FsSafeError && e.code === "already-exists") return "exists";
return rethrowHostMutationError(e);
}
},
remove: async (e) => {
await runWithAgentToolSourceExecutionScope(t, async () => {
const { root: t, relative: n, assertBeforeMutation: r } = await resolveTarget(e);
r();
await t.remove(`./${n}`, { assertBeforeMutation: r }).catch(rethrowHostMutationError);
});
}
});
}
function rethrowHostMutationError(e) {
if (e instanceof FsSafeError && (e.code === "outside-workspace" || e.code === "path-alias" && e.cause instanceof Error && /^(?:Path escapes|Path resolves outside|Symlink escapes) root \(/.test(e.cause.message))) markHostRootEscape(e);
throw e;
}
var PatchCreateExistsSignal = class extends Error {};
function withPatchMemoryWriteProvenance(e, t) {
const n = withMemoryWriteProvenance(t, e);
if (!e) return n;
return {
...n,
createFileExclusive: async (n, r) => {
if (!await e.classifies(n)) return t.createFileExclusive(n, r);
try {
await e.write({
absolutePath: n,
contentBefore: "",
contentAfter: r,
commit: async () => {
if (await t.createFileExclusive(n, r) === "exists") throw new PatchCreateExistsSignal();
}
});
return "created";
} catch (e) {
if (e instanceof PatchCreateExistsSignal) return "exists";
throw e;
}
}
};
}
function assertBoundaryRead(e, t) {
if (e.ok) return;
const n = e.reason === "validation" ? "unsafe path" : "path not found";
const r = /* @__PURE__ */ new Error(`Failed boundary read for ${t} (${n})`);
const i = e.error && typeof e.error === "object" && "code" in e.error ? e.error.code : void 0;
if (i === "ENOENT" || i === "ENOTDIR") r.code = i;
if (e.reason === "validation" && (e.error instanceof FsSafeError && e.error.code === "outside-workspace" || isPathBoundaryEscapeError(e.error, "workspace root"))) markHostRootEscape(r);
throw r;
}
//#endregion
//#region src/agents/apply-patch-parse.ts
const BEGIN_PATCH_MARKER = "*** Begin Patch";
const END_PATCH_MARKER = "*** End Patch";
const ADD_FILE_MARKER = "*** Add File: ";
const DELETE_FILE_MARKER = "*** Delete File: ";
const UPDATE_FILE_MARKER = "*** Update File: ";
const MOVE_TO_MARKER = "*** Move to: ";
const EOF_MARKER = "*** End of File";
const CHANGE_CONTEXT_MARKER = "@@ ";
const EMPTY_CHANGE_CONTEXT_MARKER = "@@";
function parsePatchText(e) {
const t = e.trim();
if (!t) throw new ToolInputError("Invalid patch: input is empty.");
const n = checkPatchBoundaries(t.split(/\r?\n/)).slice(1, -1);
const r = [];
for (let e = 0; e < n.length;) {
const { hunk: t, consumed: i } = parseOneHunk(n.slice(e), e + 2);
r.push(t);
e += i;
}
return r;
}
function checkPatchBoundaries(e) {
const t = e[0];
const n = e.at(-1);
const r = e.length >= 4 && n && (t === "<<EOF" || t === "<<'EOF'" || t === "<<\"EOF\"") && n.endsWith("EOF") ? e.slice(1, -1) : e;
if (r[0]?.trim() !== BEGIN_PATCH_MARKER) throw new ToolInputError("The first line of the patch must be '*** Begin Patch'");
if (r.at(-1)?.trim() !== END_PATCH_MARKER) throw new ToolInputError("The last line of the patch must be '*** End Patch'");
return r;
}
function parseOneHunk(e, t) {
const n = e[0].trim();
if (n.startsWith(ADD_FILE_MARKER)) {
const t = n.slice(14);
let r = "";
let i = 1;
for (const t of e.slice(1)) if (t.startsWith("+")) {
r += `${t.slice(1)}\n`;
i += 1;
} else break;
return {
hunk: {
kind: "add",
path: t,
contents: r
},
consumed: i
};
}
if (n.startsWith(DELETE_FILE_MARKER)) return {
hunk: {
kind: "delete",
path: n.slice(17)
},
consumed: 1
};
if (n.startsWith(UPDATE_FILE_MARKER)) {
const r = n.slice(17);
let i = 1;
let a;
const o = e[i]?.trim();
if (o?.startsWith(MOVE_TO_MARKER)) {
a = o.slice(13);
i += 1;
}
const s = [];
while (i < e.length) {
const n = e[i];
if (n.trim() === "") {
i += 1;
continue;
}
if (n.startsWith("***")) break;
const { chunk: r, consumed: a } = parseUpdateFileChunk(e.slice(i), t + i, s.length === 0);
s.push(r);
i += a;
}
if (s.length === 0) throw new ToolInputError(`Invalid patch hunk at line ${t}: Update file hunk for path '${r}' is empty`);
return {
hunk: {
kind: "update",
path: r,
movePath: a,
chunks: s
},
consumed: i
};
}
throw new ToolInputError(`Invalid patch hunk at line ${t}: '${e[0]}' is not a valid hunk header. Valid hunk headers: '*** Add File: {path}', '*** Delete File: {path}', '*** Update File: {path}'`);
}
function parseUpdateFileChunk(e, t, n) {
let r;
let i = 0;
const a = e.at(0);
if (a === EMPTY_CHANGE_CONTEXT_MARKER) i = 1;
else if (a?.startsWith(CHANGE_CONTEXT_MARKER)) {
r = a.slice(3);
i = 1;
} else if (!n) throw new ToolInputError(`Invalid patch hunk at line ${t}: Expected update hunk to start with a @@ context marker, got: '${a}'`);
if (i >= e.length || e[i] === EOF_MARKER) throw new ToolInputError(`Invalid patch hunk at line ${t + 1}: Update hunk does not contain any lines`);
const o = {
changeContext: r,
oldLines: [],
newLines: [],
contextOldIndexes: [],
isEndOfFile: false
};
let s = 0;
for (const n of e.slice(i)) {
if (n === EOF_MARKER) {
o.isEndOfFile = true;
s += 1;
break;
}
const e = n[0];
if (!e || e === " " || e === "+" || e === "-") {
const t = n.slice(1);
if (e !== "-") {
o.contextOldIndexes.push(e === "+" ? void 0 : o.oldLines.length);
o.newLines.push(t);
}
if (e !== "+") o.oldLines.push(t);
s += 1;
continue;
}
if (s === 0) throw new ToolInputError(`Invalid patch hunk at line ${t + 1}: Unexpected line found in update hunk: '${n}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`);
break;
}
return {
chunk: o,
consumed: s + i
};
}
//#endregion
//#region src/agents/apply-patch-update.ts
/**
* Locates expected old lines with tolerant matching, applies chunks in order,
* and retains source bytes that the patch does not change.
*/
const DASH_PUNCTUATION = /[\u2010-\u2015\u2212]/g;
const SINGLE_QUOTE_PUNCTUATION = /[\u2018-\u201B]/g;
const DOUBLE_QUOTE_PUNCTUATION = /[\u201C-\u201F]/g;
const SPACE_PUNCTUATION = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
async function applyUpdateHunk(e, t, n) {
const r = parseSourceFile(await n.readFile(e).catch((t) => {
throw new Error(`Failed to read file to update ${e}: ${formatErrorMessage(t)}`);
}));
const i = computeReplacements(r, e, t);
const a = applyReplacements(r.lines, i);
ensureInteriorEndings(a, r.preferredEnding);
return r.bom + a.map((e) => e.text + e.ending).join("");
}
function computeReplacements(e, t, n) {
const r = e.lines.map((e) => e.text);
const i = [];
let a = 0;
for (const o of n) {
if (o.changeContext) {
const e = seekSequence(r, [o.changeContext], a, false);
if (e.kind === "ambiguous") throw new ToolInputError(`Found ${e.occurrences} occurrences of context '${o.changeContext}' in ${t}. The context must be unique; use a more specific @@ context line.`);
if (e.kind === "missing") throw new ToolInputError(`Failed to find context '${o.changeContext}' in ${t}`);
a = e.index + 1;
}
if (o.oldLines.length === 0) {
const t = o.changeContext && !o.isEndOfFile ? a : e.lines.length;
const n = buildChangedLines({
sourceLines: e.lines,
startIndex: t,
oldCount: 0,
newLines: o.newLines,
preferredEnding: e.preferredEnding
});
const r = n.at(-1);
if (e.missingFinalEnding && t === e.lines.length && r) r.ending = "";
i.push([
t,
0,
n
]);
a = t;
continue;
}
let n = o.oldLines;
let s = o.newLines;
let c = seekSequence(r, n, a, o.isEndOfFile);
if (c.kind === "missing" && n[n.length - 1] === "") {
n = n.slice(0, -1);
if (s.length > 0 && s[s.length - 1] === "") s = s.slice(0, -1);
c = seekSequence(r, n, a, o.isEndOfFile);
}
if (c.kind === "ambiguous") throw new ToolInputError(`Found ${c.occurrences} occurrences of these lines in ${t}. The lines must be unique; include more surrounding lines in the hunk:\n${o.oldLines.join("\n")}`);
if (c.kind === "missing") throw new ToolInputError(`Failed to find expected lines in ${t}:\n${o.oldLines.join("\n")}`);
const l = c.index;
const u = n.length;
const d = o.contextOldIndexes;
const f = [];
let p = 0;
let m = 0;
for (const [t, r] of d.entries()) {
if (r === void 0 || r >= n.length || t >= s.length) continue;
appendLines(f, buildChangedLines({
sourceLines: e.lines,
startIndex: l + p,
oldCount: r - p,
newLines: s.slice(m, t),
preferredEnding: e.preferredEnding
}));
f.push(e.lines[l + r]);
p = r + 1;
m = t + 1;
}
appendLines(f, buildChangedLines({
sourceLines: e.lines,
startIndex: l + p,
oldCount: n.length - p,
newLines: s.slice(m),
preferredEnding: e.preferredEnding
}));
i.push([
l,
u,
f
]);
a = l + n.length;
}
i.sort((e, t) => e[0] - t[0]);
return i;
}
function appendLines(e, t) {
for (const n of t) e.push(n);
}
function buildChangedLines(e) {
const { sourceLines: t, startIndex: n, oldCount: r, newLines: i, preferredEnding: a } = e;
const o = t.slice(n, n + r);
const s = o.find((e) => e.ending)?.ending || t.at(n)?.ending || t.at(n - 1)?.ending || a;
return i.map((e, t) => {
let n = s;
if (o.length === i.length) n = o.at(t)?.ending ?? s;
else if (t === i.length - 1 && o.length > 0) n = o.at(-1)?.ending ?? s;
else if (t < o.length - 1) n = o.at(t)?.ending ?? s;
return {
text: e,
ending: n
};
});
}
function applyReplacements(e, t) {
let n = e;
for (const [e, r, i] of t.toReversed()) n = n.slice(0, e).concat(i, n.slice(e + r));
return n;
}
function parseSourceFile(e) {
const t = e.startsWith("") ? "" : "";
const n = ((t ? e.slice(1) : e).match(/[^\r\n]*(?:\r\n|\r|\n)|[^\r\n]+/g) ?? []).map(splitLineEnding);
return {
bom: t,
lines: n,
preferredEnding: n.find((e) => e.ending)?.ending || "\n",
missingFinalEnding: n.length > 0 && n.at(-1)?.ending === ""
};
}
function splitLineEnding(e) {
for (const t of [
"\r\n",
"\r",
"\n"
]) if (e.endsWith(t)) return {
text: e.slice(0, -t.length),
ending: t
};
return {
text: e,
ending: ""
};
}
function ensureInteriorEndings(e, t) {
for (const n of e.slice(0, -1)) n.ending ||= t;
}
function seekSequence(e, t, n, r) {
if (t.length === 0) return {
kind: "found",
index: n
};
if (t.length > e.length) return { kind: "missing" };
const i = e.length - t.length;
const a = r ? Math.max(n, i) : n;
if (a > i) return { kind: "missing" };
const o = [
(e) => e,
(e) => e.trimEnd(),
(e) => e.trim(),
(e) => normalizePunctuation(e.trim())
];
for (const n of o) {
let r = null;
let o = 0;
for (let s = a; s <= i; s += 1) if (linesMatch(e, t, s, n)) {
r ??= s;
o += 1;
}
if (r !== null) return o === 1 ? {
kind: "found",
index: r
} : {
kind: "ambiguous",
occurrences: o
};
}
return { kind: "missing" };
}
function linesMatch(e, t, n, r) {
for (let i = 0; i < t.length; i += 1) {
const a = e.at(n + i);
const o = t.at(i);
if (a === void 0 || o === void 0 || r(a) !== r(o)) return false;
}
return true;
}
function normalizePunctuation(e) {
return e.replace(DASH_PUNCTUATION, "-").replace(SINGLE_QUOTE_PUNCTUATION, "'").replace(DOUBLE_QUOTE_PUNCTUATION, "\"").replace(SPACE_PUNCTUATION, " ");
}
//#endregion
//#region src/agents/apply-patch.ts
function normalizeUpdateComparison(e) {
const t = e.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
if (t.length === 0 || t.endsWith("\n")) return t;
return `${t}\n`;
}
const applyPatchSchema = Type.Object({ input: Type.String({ description: "Patch content using the *** Begin Patch/End Patch format." }) });
const ApplyPatchToolOutputSchema = Type.Object({ summary: Type.Object({
added: Type.Array(Type.String()),
modified: Type.Array(Type.String()),
deleted: Type.Array(Type.String())
}, { additionalProperties: false }) }, { additionalProperties: false });
function createApplyPatchTool(e = {}) {
const t = e.cwd ?? process.cwd();
const n = e.root ?? t;
const r = e.sandbox;
const i = e.workspaceOnly ?? Boolean(r);
return {
name: "apply_patch",
label: "apply_patch",
description: "Patch one/many files. Input requires *** Begin Patch and *** End Patch.",
parameters: applyPatchSchema,
outputSchema: ApplyPatchToolOutputSchema,
execute: async (a, o, s) => {
const c = e.abortSignal ? AbortSignal.any(s ? [s, e.abortSignal] : [e.abortSignal]) : s;
const l = o;
const u = typeof l.input === "string" ? l.input : "";
if (!u.trim()) throw new ToolInputError("Provide a patch input.");
if (c?.aborted) throw createAbortError("Aborted");
let d;
try {
d = await applyPatch(u, {
cwd: t,
root: n,
sandbox: r,
workspaceOnly: i,
memoryWriteProvenance: e.memoryWriteProvenance,
signal: c
});
} catch (t) {
throw withApplyPatchContainmentHint(t, i ? e.containmentSource : void 0, !r);
}
return {
content: [{
type: "text",
text: d.text
}],
details: { summary: d.summary }
};
}
};
}
async function applyPatch(e, t) {
const n = parsePatchText(e);
if (n.length === 0) throw new ToolInputError("No files were modified.");
const r = {
...t,
patchInputPaths: await resolvePatchInputPaths(n, t)
};
const i = resolvePatchHunks(n, r);
return await withFileMutationQueueKeysResolution(i.then((e) => e.flatMap(({ keys: e }) => e)), async () => {
const e = await i;
const t = await resolvePatchFileOps(r);
await preflightUpdateHunks(e, t, r.signal);
return await commitPatchHunks(e, t, r);
}, t.signal);
}
async function resolvePatchHunks(e, t) {
const n = [];
const r = [];
for (const i of e) {
throwIfPatchAborted(t.signal);
if (i.kind === "delete") {
const e = await resolveOrderedPatchPath(i.path, t, r, PATH_ALIAS_POLICIES.unlinkTarget);
const a = e.removed && (e.removed.link || e.readmit) ? e.removed : await resolveUnlinkedPath(i.path, e.target, e.stage, t);
r.push(a);
n.push({
hunk: i,
target: e.target,
stage: a.stage,
keys: [...e.keys, a.key],
removesContents: true,
...e.readmit ? { readmit: true } : {}
});
continue;
}
const e = await resolveOrderedPatchPath(i.path, t, r);
const a = i.kind === "update" && i.movePath ? await resolveOrderedPatchPath(i.movePath, t, r) : void 0;
let o = true;
if (a && a.stage !== e.stage) {
const n = await resolveUnlinkedPath(i.path, e.target, e.stage, t);
o = !n.link || e.stage !== e.target.queueKey;
r.push(n);
e.keys.push(n.key);
}
const s = i.kind === "update" && !t.sandbox && t.workspaceOnly === false ? hardlinkInode(await fs$1.stat(e.target.resolved).catch(() => void 0)) : void 0;
n.push({
hunk: i,
target: e.target,
stage: e.stage,
keys: a ? [...e.keys, ...a.keys] : e.keys,
removesContents: o,
...a ? {
moveTarget: a.target,
moveStage: a.stage
} : {},
...e.readmit || a?.readmit ? { readmit: true } : {},
...e.unread ? { unread: true } : {},
...s ? { contentStage: INODE_STAGE + s } : {}
});
}
return n;
}
const PATH_STAGE = "\0path\0";
const INODE_STAGE = "\0inode\0";
/**
* Queue identity follows a final symlink to the file it names, so a link and
* its target share one key, but removing the link leaves that file in place.
* Such a path stages by its spelling instead, apart from the file it named.
*/
async function resolveUnlinkedPath(e, t, n, r) {
const i = await resolvePathKey(t, r);
const a = r.sandbox ? void 0 : await lstatHostPath(t.resolved);
const o = r.sandbox ? i !== t.queueKey : a?.isSymbolicLink() === true;
const s = await resolveLexicalPatchPath(e, r);
const c = hardlinkInode(a);
return {
path: s,
key: i,
stage: o ? PATH_STAGE + s : n,
link: o,
...c ? { inode: c } : {},
...a?.isSymbolicLink() && a.nlink === 1 ? { entry: `${a.dev}:${a.ino}` } : {}
};
}
/** Queue identity of the directory entry itself, not the file a final link names. */
async function resolvePathKey(e, t) {
const n = t.sandbox ? path.posix : path;
const r = n.dirname(e.resolved);
const i = t.sandbox ? await resolveSandboxFileMutationQueueKey({
bridge: t.sandbox.bridge,
root: t.sandbox.root,
filePath: r,
cwd: t.cwd,
signal: t.signal
}) : await resolveFileMutationQueueKey(r);
return n.join(i, n.basename(e.resolved));
}
async function resolvePatchFilePath(e, t) {
return t.patchInputPaths?.get(e) ?? (t.sandbox ? await resolveApplyPatchInputPath(e, t) : preserveAtPrefixedRelativePath(e, t.cwd));
}
/** The unadmitted spelling of a patch path, for matching it against earlier removals. */
async function resolveLexicalPatchPath(e, t) {
const n = await resolvePatchFilePath(e, t);
return t.sandbox ? t.sandbox.bridge.resolvePath({
filePath: n,
cwd: t.cwd
}).containerPath : resolvePathFromInput(n, t.cwd);
}
/**
* Admission sees the snapshot, so a path at or under a link an earlier hunk
* unlinks (for example `Delete File: link` then `Add File: link`) still names
* the link here; it stages by spelling, apart from the link target. When an
* earlier removal changes what admission sees (a link or file replaced by a
* directory, the other name of a hardlink), a refused path is admitted again
* in commit order instead, so the link target is never used.
*/
async function resolveOrderedPatchPath(e, t, n, r = PATH_ALIAS_POLICIES.strict) {
if (n.length === 0) {
const n = await resolvePatchPath(e, t, r);
return {
target: n,
stage: n.queueKey,
keys: [n.queueKey]
};
}
const i = await spellLikeRemovedLink(await resolveLexicalPatchPath(e, t), n, t);
let a;
try {
a = await resolvePatchPath(e, t, r);
} catch (r) {
const a = findUnlinkedPath(n, { lexical: i }, t);
const o = {
resolved: i,
display: e
};
if (a) {
const e = a.key;
return {
target: {
...o,
queueKey: e
},
stage: a.stage,
keys: [e],
readmit: true,
removed: a
};
}
const s = await resolveFreedHardlink(e, t, n);
if (!s) throw r;
return {
target: s,
stage: s.queueKey,
keys: [s.queueKey],
readmit: true,
unread: true
};
}
const o = findUnlinkedPath(n, {
lexical: i,
key: n.some((e) => e.link) ? await resolvePathKey(a, t) : void 0
}, t);
return o?.link ? {
target: a,
stage: o.stage,
keys: [a.queueKey, o.key],
removed: o
} : {
target: a,
stage: a.queueKey,
keys: [a.queueKey]
};
}
/**
* The filesystem decides which spellings name one entry (case-insensitive
* volumes, for example). Rewrite a path at or under a host symlink an earlier
* hunk removes to that removal's spelling, matched by the link entry's identity.
*/
async function spellLikeRemovedLink(e, t, n) {
const r = /* @__PURE__ */ new Map();
for (const e of t) if (e.entry) r.set(e.entry, e.path);
if (n.sandbox || r.size === 0) return e;
for (let t = e;; t = path.dirname(t)) {
const n = await lstatHostPath(t);
const i = n?.isSymbolicLink() && r.get(`${n.dev}:${n.ino}`);
if (i) return path.join(i, path.relative(t, e));
if (path.dirname(t) === t) return e;
}
}
/** Another name of a host hardlink an earlier hunk removes; admission waits for commit order. */
async function resolveFreedHardlink(e, t, n) {
if (t.sandbox || !n.some((e) => e.inode)) return;
const r = await resolvePatchPath(e, t, PATH_ALIAS_POLICIES.unlinkTarget).catch(() => void 0);
const i = r && await lstatHostPath(r.resolved);
const a = hardlinkInode(i);
const o = n.filter((e) => a && e.inode === a).length;
return i && o > 0 && i.nlink - o === 1 ? r : void 0;
}
async function lstatHostPath(e) {
return await fs$1.lstat(e).catch(() => void 0);
}
function hardlinkInode(e) {
return e?.isFile() && e.nlink > 1 ? `${e.dev}:${e.ino}` : void 0;
}
/**
* The latest removal of this path itself, matched by spelling or entry
* identity, or of a path above it.
*/
function findUnlinkedPath(e, t, n) {
const r = n.sandbox ? path.posix : path;
for (const n of e.toReversed()) {
const e = r.relative(n.path, t.lexical);
if (e === "" || n.key === t.key) return n;
if (!(e === ".." || e.startsWith(`..${r.sep}`) || r.isAbsolute(e))) return {
path: t.lexical,
key: r.join(n.key, e),
stage: PATH_STAGE + t.lexical,
link: true
};
}
}
const REMOVED = Symbol("removed");
/**
* Reject predictable update failures (missing file, context mismatch, invalid
* UTF-8) before any hunk mutates the workspace. Staged contents follow earlier
* adds, updates, deletes, and moves by physical identity. A path at a removed
* link, or under a removed path, stages by spelling and starts out removed.
*/
async function preflightUpdateHunks(e, t, n) {
const r = /* @__PURE__ */ new Map();
for (const i of e) {
throwIfPatchAborted(n);
const { hunk: e, target: a, moveStage: o, removesContents: s, unread: c } = i;
if (e.kind !== "update") {
r.set(i.stage, e.kind === "add" ? e.contents : REMOVED);
continue;
}
const l = i.contentStage && !r.has(i.stage) && !i.stage.startsWith(PATH_STAGE) ? i.contentStage : i.stage;
const u = r.has(l) ? r.get(l) : l.startsWith(PATH_STAGE) ? REMOVED : c ? null : void 0;
let d = false;
const f = u === null ? null : await applyUpdateHunk(a.resolved, e.chunks, { readFile: u === void 0 ? (e) => t.readFile(e).catch((e) => {
d = true;
throw e;
}) : async () => readStaged(u) }).catch((e) => {
if (d && hasCaseVariant(r, l)) return null;
throw e;
});
if (o !== void 0 && o !== i.stage) {
if (s) r.set(i.stage, REMOVED);
r.set(o, f);
} else r.set(l, f);
}
}
/**
* A missing path keeps its spelling in its identity, so on a case-insensitive
* filesystem a file an earlier hunk creates can stage under another spelling.
* Leave such an unreadable path to the commit pass.
*/
function hasCaseVariant(e, t) {
const n = t.toLowerCase();
for (const t of e.keys()) if (t.toLowerCase() === n) return true;
return false;
}
function readStaged(e) {
if (e === REMOVED) throw new Error("an earlier hunk in this patch removes it");
return e;
}
function throwIfPatchAborted(e) {
if (e?.aborted) throw createAbortError("Aborted", { cause: e.reason });
}
async function commitPatchHunks(e, t, n) {
const r = {
added: /* @__PURE__ */ new Set(),
modified: /* @__PURE__ */ new Set(),
deleted: /* @__PURE__ */ new Set()
};
const i = /* @__PURE__ */ new Set();
for (const a of e) {
throwIfPatchAborted(n.signal);
const { hunk: e } = a;
const { target: o, moveTarget: s } = a.readmit ? await readmitPatchHunk(e, n) : a;
if (e.kind === "add") {
await ensureDir(o.resolved, t);
await createPatchTarget({
target: o,
contents: e.contents,
ops: t,
hint: `Use "*** Update File: ${o.display}" to change it, or delete it earlier in the same patch.`
});
r.added.add(o.display);
continue;
}
if (e.kind === "delete") {
await t.remove(o.resolved);
r.deleted.add(o.display);
continue;
}
const c = await applyUpdateHunk(o.resolved, e.chunks, t);
if (s) await ensureDir(s.resolved, t);
if (s && a.moveStage !== a.stage) {
i.delete(o.display);
await createPatchTarget({
target: s,
contents: c,
ops: t,
hint: "Delete it earlier in the same patch to replace it."
});
await t.remove(o.resolved);
r.modified.add(s.display);
continue;
}
if (normalizeUpdateComparison(await t.readFile(o.resolved)) === normalizeUpdateComparison(c)) i.add(o.display);
else {
i.delete(o.display);
await t.writeFile(o.resolved, c);
r.modified.add(o.display);
}
}
const a = {
added: [...r.added],
modified: [...r.modified],
deleted: [...r.deleted]
};
return {
summary: a,
text: i.size > 0 && Object.values(a).every((e) => e.length === 0) ? `No changes made to ${Array.from(i).join(", ")}.` : formatSummary(a)
};
}
async function readmitPatchHunk(e, t) {
return {
target: await resolvePatchPath(e.path, t, e.kind === "delete" ? PATH_ALIAS_POLICIES.unlinkTarget : PATH_ALIAS_POLICIES.strict),
...e.kind === "update" && e.movePath ? { moveTarget: await resolvePatchPath(e.movePath, t) } : {}
};
}
async function resolvePatchInputPaths(e, t) {
const n = /* @__PURE__ */ new Set();
for (const t of e) {
n.add(t.path);
if (t.kind === "update" && t.movePath) n.add(t.movePath);
}
const r = /* @__PURE__ */ new Map();
for (const e of n) r.set(e, t.sandbox ? await resolveApplyPatchInputPath(e, t) : preserveAtPrefixedRelativePath(e, t.cwd));
return r;
}
function formatSummary(e) {
const t = ["Success. Updated the following files:"];
const n = {
A: e.added,
M: e.modified,
D: e.deleted
};
for (const [e, r] of Object.entries(n)) for (const n of r) t.push(`${e} ${n}`);
return t.join("\n");
}
async function ensureDir(e, t) {
const n = path.dirname(e);
if (!n || n === ".") return;
await t.mkdirp?.(n);
}
async function resolvePatchPath(e, t, n = PATH_ALIAS_POLICIES.strict) {
const r = await resolvePatchFilePath(e, t);
if (t.sandbox) {
const e = t.sandbox.bridge.resolvePath({
filePath: r,
cwd: t.cwd
});
if (t.workspaceOnly !== false) {
const i = t.sandbox.bridge.pathMappings === void 0;
const a = resolveSandboxPathMapping(t.sandbox.workspaceMounts ?? [], e.containerPath);
if (!i && !a) throw markHostRootEscape(/* @__PURE__ */ new Error(`Path escapes sandbox root (${t.sandbox.root}): ${r}`));
if (e.hostPath) {
const r = i ? t.sandbox.root : a.mapping.hostRoot;
await assertSandboxPath({
filePath: e.hostPath,
cwd: r,
root: r,
allowFinalSymlinkForUnlink: n.allowFinalSymlinkForUnlink,
allowFinalHardlinkForUnlink: n.allowFinalHardlinkForUnlink
});
}
}
return {
resolved: e.containerPath,
queueKey: await resolveSandboxFileMutationQueueKey({
bridge: t.sandbox.bridge,
root: t.sandbox.root,
filePath: r,
cwd: t.cwd,
signal: t.signal
}),
display: e.relativePath || e.containerPath
};
}
const i = t.workspaceOnly !== false ? (await assertSandboxPath({
filePath: r,
cwd: t.cwd,
root: t.root ?? t.cwd,
allowLinkedWorktrees: true,
allowFinalSymlinkForUnlink: n.allowFinalSymlinkForUnlink,
allowFinalHardlinkForUnlink: n.allowFinalHardlinkForUnlink
})).resolved : resolvePathFromInput(r, t.cwd);
return {
resolved: i,
queueKey: await resolveFileMutationQueueKey(i),
display: toDisplayPath(i, t.cwd)
};
}
//#endregion
//#region src/agents/lazy-process-tool.ts
const bashToolsModuleLoader = createLazyImportLoader(() => import("./bash-tools-BSb3XkVL.mjs"));
/** Build process lazily so tool discovery does not load the shell runtime. */
function createLazyProcessTool(e) {
let t;
const loadTool = async () => {
if (!t) {
const { createProcessTool: n } = await bashToolsModuleLoader.load();
t = n(e);
}
return t;
};
return {
name: "process",
label: "process",
displaySummary: PROCESS_TOOL_DISPLAY_SUMMARY,
description: describeProcessTool({ hasCronTool: e?.hasCronTool === true }),
parameters: processSchema,
outputSchema: ProcessToolOutputSchema,
execute: async (e, t, n, r) => {
const i = await loadTool();
n?.throwIfAborted();
return i.execute(e, t, n, r);
}
};
}
//#endregion
//#region src/agents/sessions/tools/ls.ts
const DEFAULT_LIMIT = 500;
const defaultLsOperations = { readDirectory: async (e) => (await readdir(e, { withFileTypes: true })).map((e) => ({
name: e.name,
isDirectory: e.isDirectory()
})) };
function formatLsContinuation(e) {
return `\n\n[More entries. Continue with the same path and after=${JSON.stringify(e)}.]`;
}
function createLsTool(e, t) {
const n = t?.operations ?? defaultLsOperations;
const r = t?.operations ? resolveToCwd : resolveLocalPathToCwd;
const i = wrapToolDefinition({
name: "ls",
label: "ls",
description: "List directory entries in binary filename order, including dotfiles and links. Names are JSON-quoted; / marks actual directories. Pass the returned after cursor with the same path to continue.",
parameters: lsSchema,
async execute(i, { path: a, limit: o, after: s }, c, l, u) {
assertFileToolNotAborted(c);
const runListing = async () => {
try {
const i = r(a || ".", e);
const l = normalizePositiveLimit(o, DEFAULT_LIMIT);
const u = await n.readDirectory(i, c);
assertFileToolNotAborted(c);
const d = u.filter((e) => s === void 0 || e.name > s).toSorted((e, t) => e.name < t.name ? -1 : e.name > t.name ? 1 : 0);
if (d.length === 0) return {
content: [{
type: "text",
text: "(empty directory)"
}],
details: { content: "(empty directory)" }
};
const fitsPage = (e) => Buffer.byteLength(e) <= 51200 && toolResultFitsBudget(e, t?.modelBudget);
const f = [];
let p = "";
for (const e of d) {
if (f.length >= l) break;
const t = JSON.stringify(e.name + (e.isDirectory ? "/" : ""));
const n = p ? `${p}\n${t}` : t;
if (!fitsPage(n)) break;
f.push(t);
p = n;
}
while (f.length > 0) {
const e = f.length < d.length ? d[f.length - 1].name : void 0;
const t = p + (e === void 0 ? "" : formatLsContinuation(e));
if (fitsPage(t)) return {
content: [{
type: "text",
text: t
}],
details: {
content: t,
...e === void 0 ? {} : { nextAfter: e }
}
};
f.pop();
p = f.join("\n");
}
throw new Error("A directory entry cannot fit within the listing output budget.");
} catch (e) {
throw toErrorObject(e, "Non-Error rejection");
}
};
return await racePromiseWithAbortSignal(runListing, c, () => /* @__PURE__ */ new Error("Operation aborted"));
}
});
return t?.operations ? i : bindAgentToolReplaySafety(i, "bounded-read");
}
//#endregion
//#region src/agents/core-coding-tools.ts
const filesystemAction = Object.freeze({
family: "data",
operation: "filesystem"
});
const processAction = Object.freeze({
family: "tool",
operation: "process"
});
function resolveSkillReadRoots(e) {
const t = /* @__PURE__ */ new Set();
for (const n of e ?? []) {
if (resolveSkillFileHost(n) === "workspace") continue;
const e = typeof n.baseDir === "string" ? n.baseDir.trim() : "";
const r = typeof n.filePath === "string" ? n.filePath.trim() : "";
const i = e || (r ? path.dirname(r) : "");
if (!i || !path.isAbsolute(i)) continue;
t.add(path.resolve(i));
}
return t.size > 0 ? Array.from(t) : void 0;
}
/** Route only selected workspace Skills; their paths never name Gateway files. */
function wrapWorkspaceSkillRead(e, t, n) {
const r = t?.filter((e) => resolveSkillFileHost(e) === "workspace") ?? [];
const i = t?.filter((e) => resolveSkillFileHost(e) !== "workspace") ?? [];
if (r.length === 0) return e;
const a = getAgentWorkspaceAccess(n.skillsSnapshot?.skillRoots?.agentWorkspaceDir ?? n.codingRoot, "loadSkills");
const o = a?.loadSkills ? a.skillResources : void 0;
return {
...e,
execute: async (t, a, s, c) => {
const l = asOptionalObjectRecord(a);
const u = l?.path ?? l?.file_path;
const d = typeof u === "string" ? normalizeFileToolPathParam(u) : void 0;
const f = d ? r.map((e) => ({
skill: e,
sourcePath: resolveWorkspaceSkillSourcePath(e, d)
})).find((e) => e.sourcePath !== void 0) : void 0;
const p = d && !f ? resolvePathFromInput(d, n.codingRoot) : void 0;
const m = p ? r.filter((e) => relativePathInsideSandboxRoot(e.baseDir, p) !== null) : [];
const h = m.length === 1 && p && !await canAccess(p) && !i.some((e) => relativePathInsideSandboxRoot(e.baseDir, p) !== null) ? m[0] : void 0;
const g = f?.skill ?? h;
const _ = f?.sourcePath ?? (h ? p : void 0);
if (!g || !_) return e.execute(t, a, s, c);
if (!o) throw new WorkspaceAccessUnavailableError("Remote workspace Skill resources are unavailable.");
const v = AbortSignal.any([s, n.abortSignal].filter((e) => Boolean(e)));
const y = createReadTool(n.codingRoot, {
maxBytes: resolveAdaptiveReadMaxBytes(n),
modelBudget: resolveToolResultBudget(n.modelContextWindowTokens),
modelHasVision: n.modelHasVision,
operations: {
resolvePath: () => _,
resolveQueueKey: (e) => `workspace-skill:${e}`,
access: async () => v.throwIfAborted(),
readFile: async () => {
v.throwIfAborted();
if (_ === g.filePath) return Buffer.from(await o.readInstructions(g.filePath, { signal: v }));
const { prepareSkillBundle: e } = await import("./bundle-ZOPGRO85.mjs");
const t = await o.readSkillFiles(g, { allowMissingRoot: false });
v.throwIfAborted();
const n = relativePathInsideSandboxRoot(g.baseDir, _);
const r = !g.baseDir.startsWith("/") && path.win32.isAbsolute(g.baseDir) ? n.split("\\").join("/") : n;
const i = t && e(t).files.find((e) => e.path === r);
if (!i) throw Object.assign(/* @__PURE__ */ new Error(`Skill file not found: ${_}`), { code: "ENOENT" });
return i.bytes;
}
}
});
return createOpenClawReadTool(y, {
modelContextWindowTokens: n.modelContextWindowTokens,
imageSanitization: n.imageSanitization,
cwd: n.codingRoot
}).execute(t, {
...l,
path: _
}, v, c);
}
};
}
/** Materialize only the core file and shell families selected by the runtime owner. */
function createCoreCodingTools(e) {
const t = e.sandbox;
const n = t?.workspaceDir;
const r = t?.fsBridge;
const i = t?.workspaceAccess !== "ro";
if (n && !r && (e.includeBaseCodingTools || e.shellTools !== "disabled")) throw new Error("Sandbox filesystem bridge is unavailable.");
const a = e.skillReadResources ?? e.skillsSnapshot?.resolvedSkills;
const o = n ? void 0 : resolveSkillReadRoots(a);
const s = !n ? e.attachmentReadRoot : void 0;
const c = [...o ?? [], ...s && fs.existsSync(s) ? [s] : []];
const l = e.shellTools !== "disabled" || e.includeBaseCodingTools && e.workspaceOnly;
const u = t && l ? resolveReadOnlyWorkspaceSkillMounts({
workspaceDir: t.workspaceDir,
agentWorkspaceDir: t.agentWorkspaceDir,
skillsWorkspaceDir: t.skillsWorkspaceDir,
workdir: t.containerWorkdir,
workspaceAccess: t.workspaceAccess
}) : [];
const d = t && (e.includeBaseCodingTools && e.workspaceOnly || e.shellTools !== "disabled" && e.applyPatchEnabled && e.applyPatchWorkspaceOnly) ? r?.pathMappings ?? buildSandboxFsMounts(t) : [];
const f = t ? d.filter((e) => relativePathInsideSandboxRoot(t.containerWorkdir, e.containerRoot) !== null) : [];
const p = d;
const guardWorkspaceTool = (i) => e.workspaceOnly ? wrapToolWorkspaceRootGuardWithOptions(i, n ?? e.containmentRoot, n ? {
containerMounts: f,
containerWorkdir: t.containerWorkdir,
bridge: r,
normalizeGuardedPathParams: true
} : {
resolutionCwd: e.codingRoot,
normalizeGuardedPathParams: true,
allowLinkedWorktrees: i.name !== "ls"
}) : i;
const m = [];
if (e.includeBaseCodingTools) {
const i = r?.readDirectory?.bind(r);
const o = i ? { readDirectory: (e, n) => i({
filePath: e,
cwd: t?.containerWorkdir,
signal: n
}) } : e.workspaceOnly && !t ? { readDirectory: async (t) => {
return (await (await root(e.containmentRoot)).list(path.relative(e.containmentRoot, t), { withFileTypes: true })).map(({ name: e, isDirectory: t }) => ({
name: e,
isDirectory: t
}));
} } : void 0;
if (!t || i) {
const t = guardWorkspaceTool(createLsTool(e.codingRoot, {
operations: o,
modelBudget: resolveToolResultBudget(e.modelContextWindowTokens)
}));
m.push(bindAgentToolReplaySafety(n ? wrapSandboxFileToolPath(t, {
root: n,
bridge: r,
defaultPath: "."
}) : t, "bounded-read"));
}
const s = n ? createSandboxedReadTool({
root: n,
bridge: r,
modelContextWindowTokens: e.modelContextWindowTokens,
imageSanitization: e.imageSanitization,
modelHasVision: e.modelHasVision
}) : createReadTool(e.codingRoot, {
maxBytes: resolveAdaptiveReadMaxBytes(e),
modelBudget: resolveToolResultBudget(e.modelContextWindowTokens),
modelHasVision: e.modelHasVision
});
const l = e.workspaceOnly ? wrapToolWorkspaceRootGuardWithOptions(s, n ?? e.containmentRoot, n ? {
containerMounts: p,
containerWorkdir: t.containerWorkdir,
bridge: r,
readPathValidation: "bridge"
} : {
additionalRoots: c.length > 0 ? c : void 0,
allowLinkedWorktrees: true,
resolutionCwd: e.codingRoot,
normalizeGuardedPathParams: true
}) : s;
const u = n ? l : createOpenClawReadTool(l, {
modelContextWindowTokens: e.modelContextWindowTokens,
imageSanitization: e.imageSanitization,
cwd: e.codingRoot
});
m.push(bindAgentToolReplaySafety(wrapReadToolWithSkillContent(n ? u : wrapWorkspaceSkillRead(u, a, e), a?.map((e) => ({
filePath: resolveSkillReadPath(e),
readContent: e.readContent
})), {
modelContextWindowTokens: e.modelContextWindowTokens,
imageSanitization: e.imageSanitization,
cwd: e.codingRoot,
containerWorkdir: t?.containerWorkdir,
instructionPaths: e.skillInstructionPaths,
instructionDeliveryCache: e.skillInstructionDeliveryCache
}), "bounded-read"));
if (!e.readOnly && !n) for (const t of [createHostWorkspaceEditTool, createHostWorkspaceWriteTool]) {
const n = t(e.codingRoot, e);
m.push(guardWorkspaceTool(n));
}
}
if (e.includeBaseCodingTools && !e.readOnly && n && i) {
const t = {
root: n,
bridge: r,
memoryWriteProvenance: e.memoryWriteProvenance,
abortSignal: e.abortSignal
};
for (const e of [createSandboxedEditTool, createSandboxedWriteTool]) {
const n = e(t);
m.push(guardWorkspaceTool(n));
}
}
e.recordToolPrepStage?.("base-coding-tools");
const h = [];
if (e.shellTools !== "disabled" && e.applyPatchEnabled && (!n || i)) h.push(createApplyPatchTool({
cwd: e.codingRoot,
root: e.containmentRoot,
sandbox: n && i ? {
root: n,
bridge: r,
workspaceMounts: f
} : void 0,
workspaceOnly: e.applyPatchWorkspaceOnly,
containmentSource: e.applyPatchContainmentSource,
memoryWriteProvenance: e.memoryWriteProvenance,
abortSignal: e.abortSignal
}));
if (e.shellTools === "full") h.push(createLazyExecTool({
...e.execDefaults,
...t?.required ? { sandboxRequired: true } : {},
cwd: e.codingRoot,
sandbox: t ? {
containerName: t.containerName,
workspaceDir: t.workspaceDir,
containerWorkdir: t.containerWorkdir,
workdirValidation: t.backend?.workdirValidation,
validateWorkdir: t.backend?.validateWorkdir?.bind(t.backend),
discardPreparedWorkdir: t.backend?.discardPreparedWorkdir?.bind(t.backend),
workdirRoots: t.backend?.workdirRoots,
readOnlyWorkspaceSkillMounts: u,
env: t.backend?.env ?? t.docker.env,
prepareProcessCleanup: t.backend?.prepareProcessCleanup?.bind(t.backend),
buildExecSpec: t.backend?.buildExecSpec.bind(t.backend),
finalizeExec: t.backend?.finalizeExec?.bind(t.backend)
} : void 0
}), createLazyProcessTool(e.processDefaults));
e.recordToolPrepStage?.("shell-tools");
m.forEach((e) => bindAgentToolActionDescriptor(e, filesystemAction));
h.forEach((e) => bindAgentToolActionDescriptor(e, processAction));
return [...m, ...h];
}
//#endregion
export { createCoreCodingTools as t };