UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

737 lines (736 loc) • 26.1 kB
import { d as asPositiveFiniteNumber } from "./number-coercion-D6u-4YD8.mjs"; import { i as asOptionalObjectRecord } from "./record-coerce-CVPuDqcc.mjs"; import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs"; import { n as ignoreMissingPath } from "./errno-DFcoqIT9.mjs"; import { a as resolveRootPath } from "./boundary-path-C2gXEiXe.mjs"; import { i as clampNumber } from "./utils-C8YECn2Q.mjs"; import "./errors-BKzCeTYb.mjs"; import { a as canonicalPathFromExistingAncestor, s as findExistingAncestor, t as FsSafeError, w as root } from "./fs-safe-BbWvmdVn.mjs"; import { a as overwriteFileHandle } from "./file-descriptor-DQ-v5bLt.mjs"; import { i as decodeWindowsTextFileBuffer } from "./windows-encoding-BGmFeZe1.mjs"; import { n as detectMime } from "./mime-D2wVBzpa.mjs"; import { n as normalizeMediaReferenceSource } from "./inbound-media-uri-DpK4_BLW.mjs"; import { n as DEFAULT_MAX_LINES, t as DEFAULT_MAX_BYTES } from "./truncate-DCXARhAL.mjs"; import { t as collectTextContentBlocks } from "./content-blocks-DgfxPwgj.mjs"; import { i as sanitizeToolResultImages } from "./tool-images-BhKV9Bbe.mjs"; import { m as resolveHostWorkspaceRoot, n as assertSandboxPath, p as resolveHostRootAsync } from "./sandbox-paths-CGD5HJYL.mjs"; import { i as resolveContainerPathCandidate, l as toRelativeWorkspacePath, o as resolveSandboxPathMapping, t as mapContainerPathToWorkspaceRoot } from "./path-policy-CyYRyWre.mjs"; import { o as resolveToCwd, t as expandOsHomePrefix } from "./path-utils-B5H__xjt.mjs"; import { a as normalizeFileToolPathParamsFromKeys, c as wrapToolParamValidation, i as normalizeFileToolPathParam, n as assertRequiredParams, o as prepareReadToolParams, r as isDailyMemoryReadPath, t as REQUIRED_PARAM_GROUPS } from "./agent-tools.params-D3Fjhk01.mjs"; import { i as rememberSkillInstructionDelivery, t as createAlreadyDeliveredSkillResult } from "./skill-instruction-result-RZ7WPgCg.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 { a as resolveMediaReferenceSandboxPath, t as classifyMediaReferenceSource } from "./media-reference-DDon-yG0.mjs"; import { a as normalizePositiveLimit, i as formatReadContinuationNotice, n as createReadTool, o as createEditTool, r as createBoundedReadTextPage, t as createWriteTool } from "./tools-EkGDfRbZ.mjs"; import "./read-file-page-D9qANuJA.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 sniffMimeFromBase64 } from "./sniff-mime-from-base64-IFkz2jJd.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import { Value } from "typebox/value"; //#region src/agents/agent-tools.read.operations.ts function createSandboxReadOperations(e) { return { resolveQueueKey: (t, n) => resolveSandboxFileQueueKey(e, t, n), resolvePath: (e) => { const t = normalizeMediaReferenceSource(e); if (classifyMediaReferenceSource(t).isMediaStoreUrl) return resolveMediaReferenceSandboxPath(t, "media/inbound").resolved; return resolveContainerPathCandidate(e); }, decodeText: ({ buffer: t, absolutePath: n }) => e.bridge.resolvePath({ filePath: n, cwd: e.root }).hostPath ? decodeWindowsTextFileBuffer({ buffer: t }) : decodeWindowsTextFileBuffer({ buffer: t, platform: "linux" }), readFile: (t, n) => e.bridge.readFile({ filePath: t, cwd: e.root, signal: n ?? e.abortSignal }), access: (t, n) => assertSandboxFileExists(e, t, n), detectImageMimeType: async (e, t) => { const n = await detectMime({ buffer: t, filePath: e }); return n?.startsWith("image/") ? n : void 0; } }; } function createSandboxMutationOperations(e) { return withMemoryWriteProvenance({ resolveQueueKey: (t, n) => resolveSandboxFileQueueKey(e, t, n), writeFile: async (t, n, r) => { await e.bridge.writeFile({ filePath: t, cwd: e.root, data: n, mkdir: true, signal: r ?? e.abortSignal }); }, readFile: (t, n) => e.bridge.readFile({ filePath: t, cwd: e.root, signal: n ?? e.abortSignal }), statFile: (t, n) => e.bridge.stat({ filePath: t, cwd: e.root, signal: n ?? e.abortSignal }), access: (t, n) => assertSandboxFileExists(e, t, n) }, e.memoryWriteProvenance); } async function resolveSandboxFileQueueKey(e, t, n) { return await resolveSandboxFileMutationQueueKey({ bridge: e.bridge, root: e.root, filePath: t, cwd: e.root, signal: n }); } async function assertSandboxFileExists(e, t, n) { const r = await e.bridge.stat({ filePath: t, cwd: e.root, signal: n ?? e.abortSignal }); if (!r) throw createFsAccessError("ENOENT", t); if (r.type === "directory") throw createFsAccessError("EISDIR", t); } function createFsAccessError(e, t) { const n = /* @__PURE__ */ new Error(`Sandbox FS error (${e}): ${t}`); n.code = e; return n; } //#endregion //#region src/agents/host-file-write.ts async function openHostFileForUpdate(e) { try { return (await fs.stat(e)).isFile() ? await fs.open(e, "r+") : void 0; } catch (e) { return ignoreMissingPath(e); } } async function writeHostFile(e, t, n) { const r = captureAgentToolSourceExecutionGuard(n); const i = path.resolve(expandOsHomePrefix(e)); await runWithAgentToolSourceExecutionScope(r, async () => { r(); await fs.mkdir(path.dirname(i), { recursive: true }); }); const a = await openHostFileForUpdate(i); if (!a) { await runWithAgentToolSourceExecutionScope(r, async () => { r(); await fs.writeFile(i, t, "utf-8"); }); return; } try { await runWithAgentToolSourceExecutionScope(r, async () => { await overwriteFileHandle(a, Buffer.from(t, "utf-8"), { beforeWrite: r }); }); } finally { await a.close().catch(() => void 0); } } //#endregion //#region src/agents/workspace-file-ops.ts async function writeHostWorkspaceFile(e, t, n, r, i) { const a = captureAgentToolSourceExecutionGuard(i); const o = await resolveHostRootAsync(e, n); const s = toRelativeWorkspacePath(o, n); const c = await t(o); await runWithAgentToolSourceExecutionScope(a, async () => { await c.write(path.resolve(c.rootReal, s), r, { mkdir: true, mutationSymlinks: "follow-parents-within-root", assertBeforeMutation: () => { a(); toRelativeWorkspacePath(resolveHostWorkspaceRoot(e, n), n); } }); }); } async function toCanonicalRelativeWorkspacePath(e, t) { const n = toRelativeWorkspacePath(e, t); const r = path.resolve(e, n); const i = path.dirname(r); const [a, o] = await Promise.all([fs.realpath(e), canonicalPathFromExistingAncestor(i)]); const s = path.join(o, path.basename(r)); return toRelativeWorkspacePath(a, s); } //#endregion //#region src/agents/agent-tools.read.ts const DEFAULT_READ_PAGE_MAX_BYTES = 32768; const MAX_ADAPTIVE_READ_MAX_BYTES = 131072; const ADAPTIVE_READ_CONTEXT_SHARE = .1; const CHARS_PER_TOKEN_ESTIMATE = 4; const MAX_ADAPTIVE_READ_PAGES = 4; /** Erase a schema-specific session tool only after its input passes that owned schema. */ function eraseSessionFileTool(e) { return { ...e, execute: async (t, n, r, i) => { if (!Value.Check(e.parameters, n)) throw new Error(`Invalid parameters for ${e.name}`); const a = n; return await e.execute(t, a, r, i ? (e) => i(e) : void 0); } }; } const READ_CONTINUATION_NOTICE_RE = /\n\n\[(?:Showing (?:lines|part of line) [^\]]*|Read output capped [^\]]*|\d+ more lines? in file\. [^\]]*)\]\s*$/; function resolveAdaptiveReadMaxBytes(e) { const t = asPositiveFiniteNumber(e?.modelContextWindowTokens); if (t === void 0) return DEFAULT_READ_PAGE_MAX_BYTES; const n = Math.floor(t * CHARS_PER_TOKEN_ESTIMATE * ADAPTIVE_READ_CONTEXT_SHARE); return clampNumber(n, DEFAULT_READ_PAGE_MAX_BYTES, MAX_ADAPTIVE_READ_MAX_BYTES); } function malformedXmlArgValuePathError(e) { return /* @__PURE__ */ new Error(`Malformed path parameter: ${e}. Supply correct parameters before retrying.`); } function getToolResultText(e) { const t = collectTextContentBlocks(e.content); return t.length > 0 ? t.join("\n") : void 0; } function getReadResultContent(e) { const t = e.details; return t.kind === "text" || t.kind === "truncated" ? t.content : void 0; } function withToolResultText(e, t, n) { let r = false; const i = e.content.map((e) => { if (!r && e.type === "text") { r = true; return Object.assign({}, e, { text: t }); } return e; }); const a = { type: "text", text: t }; return { ...e, content: r ? i : [a], ...n !== void 0 && getReadResultContent(e) !== void 0 ? { details: { kind: "text", content: n } } : {} }; } function extractReadTruncationDetails(e) { const t = e.details; if (t.kind !== "truncated") return null; return { ...t.truncation, continuation: t.continuation }; } function withReadContinuation(e, t, n, r, i, a) { const o = e.details.kind === "truncated" ? e.details.truncation : a; if (!o) return withToolResultText(e, t); return { ...withToolResultText(e, t), details: { kind: "truncated", content: r, truncation: { ...o, outputLines: n.offset - i, outputBytes: Buffer.byteLength(r, "utf8"), lastLinePartial: n.kind === "cursor" }, continuation: n } }; } function stripReadContinuationNotice(e) { return e.replace(READ_CONTINUATION_NOTICE_RE, ""); } async function executeReadWithAdaptivePaging(e) { const t = e.args.limit; const n = typeof t === "number"; const r = Math.floor(asPositiveFiniteNumber(e.args.offset) ?? 1); const i = n ? { limit: normalizePositiveLimit(t, DEFAULT_MAX_LINES) } : {}; let a = typeof e.args.cursor === "number" ? { kind: "cursor", offset: r, cursor: e.args.cursor, ...i } : { kind: "line", offset: r, ...i }; let o; let s = ""; let c = ""; let l = 0; let u = ""; for (let t = 0; t < MAX_ADAPTIVE_READ_PAGES; t += 1) { const i = { ...e.args, offset: a.offset, ...a.kind === "cursor" ? { cursor: a.cursor } : {}, ...a.limit === void 0 ? {} : { limit: a.limit } }; if (a.kind === "line") delete i.cursor; const d = await e.base.execute(e.toolCallId, i, e.signal); o ??= d; const f = getToolResultText(d); if (typeof f !== "string") return d; const p = extractReadTruncationDetails(d); const m = a.offset - 1 + (p?.outputLines ?? 0); const h = p !== null && p.totalLines !== void 0 && m >= p.totalLines; const g = p?.continuation; const _ = g || h ? stripReadContinuationNotice(f) : f; const v = getReadResultContent(d); const y = v ?? _; const b = t > 0 && a.kind === "line" ? "\n" : ""; const x = l + b.length + Buffer.byteLength(_, "utf8"); const S = `${c}${b}${y}`; const C = g ? formatReadContinuationNotice(g, e.maxBytes) : ""; if (x + Buffer.byteLength(C, "utf8") > e.maxBytes || Buffer.byteLength(S, "utf8") > e.maxBytes || !toolResultFitsBudget(S, e.modelBudget) || !toolResultFitsBudget(`${s}${b}${_}${C}`, e.modelBudget)) { if (t > 0) return withReadContinuation(o, `${s}${u}`, a, c, r); const n = y.split("\n").length; const i = v === void 0 || !_.endsWith(y) ? "" : _.slice(0, _.length - y.length); const l = createBoundedReadTextPage({ content: y, startLine: a.offset, endLine: a.offset + n - 1, totalLines: p ? p.totalLines : a.offset + n - 1, continuation: g, ...a.kind === "cursor" ? { cursor: a.cursor } : {}, limit: a.limit, maxBytes: e.maxBytes, pageMaxBytes: Math.min(DEFAULT_MAX_BYTES, e.maxBytes) - Buffer.byteLength(i, "utf8"), prefix: i, modelBudget: e.modelBudget, adaptive: true }); if (l.details.kind === "text") return withToolResultText(d, `${i}${l.text}`, l.details.content); return withReadContinuation(o, `${i}${l.text}`, l.details.continuation, l.details.content, r, l.details.truncation); } if (n && v !== void 0) return d; s += `${b}${_}`; c = S; l = x; if (!g || h) return withToolResultText(d, s, c); if (n || t === 3) return withReadContinuation(o, `${s}${C}`, g, c, r); u = C; a = g; } return o; } function rewriteReadImageHeader(e, t) { if (e.startsWith("Read image file [") && e.endsWith("]")) return `Read image file [${t}]`; return e; } async function normalizeReadImageResult(e, t) { const n = e.content; const r = n.find((e) => e.type === "image"); if (!r) return e; if (!r.data.trim()) throw new Error(`read: image payload is empty (${t})`); const i = await sniffMimeFromBase64(r.data); if (!i) return e; if (!i.startsWith("image/")) throw new Error(`read: file looks like ${i} but was treated as ${r.mimeType} (${t})`); if (i === r.mimeType) return e; const a = n.map((e) => { if (e.type === "image") return Object.assign({}, e, { mimeType: i }); if (e.type === "text") return Object.assign({}, e, { text: rewriteReadImageHeader(e.text, i) }); return e; }); return { ...e, content: a }; } function normalizeReadResultDetails(e) { if (e.details.kind !== "image") return e; const t = getToolResultText(e) ?? ""; const n = e.content.find((e) => e.type === "image"); if (n) return { ...e, details: { kind: "image", content: t, mimeType: n.mimeType } }; return { ...e, details: { kind: "text", content: t } }; } function isSandboxRootEscapeError(e) { return e instanceof Error && /^Path escapes sandbox root \(/i.test(e.message); } function withWorkspaceSafeTempHint(e) { if (!isSandboxRootEscapeError(e)) return e; const t = e.message.includes(".openclaw/tmp/") ? e.message : `${e.message}. Use a relative path under \`.openclaw/tmp/\` inside the workspace for scratch/temp/meta files that file tools need to read or write later.`; return new Error(t, { cause: e }); } async function assertSandboxPathWithinAnyRoot(e) { let t; const n = /* @__PURE__ */ new Set(); for (const [r, i] of e.roots.entries()) { if (!i) continue; const a = path.resolve(i); if (n.has(a)) continue; n.add(a); try { return await assertSandboxPath({ filePath: e.filePath, cwd: r === 0 ? e.cwd ?? a : a, root: a, ...r === 0 && e.allowLinkedWorktrees ? { allowLinkedWorktrees: true } : {} }); } catch (e) { if (!isSandboxRootEscapeError(e)) throw e; t ??= e; } } throw toErrorObject(t ?? /* @__PURE__ */ new Error("Path guard has no configured roots."), "Non-Error thrown"); } /** Wrap a file tool with workspace guards and optional container path mapping. */ function wrapToolWorkspaceRootGuardWithOptions(e, t, n) { const r = n?.bridge?.pathMappings; const i = n?.bridge && r === void 0; const a = n?.containerMounts ?? r ?? (n?.containerWorkdir ? [{ hostRoot: t, containerRoot: n.containerWorkdir }] : []); const o = n?.pathParamKeys && n.pathParamKeys.length > 0 ? n.pathParamKeys : ["path"]; return { ...e, execute: async (r, s, c, l) => { const u = asOptionalObjectRecord(s); let d; for (const e of o) { const r = u?.[e]; if (typeof r !== "string" || !r.trim()) continue; const o = await normalizeFileToolPathParam(r, n?.resolutionCwd ?? t, n?.bridge); if (!o.trim()) throw malformedXmlArgValuePathError(e); if (o !== r && u) { d ??= { ...u }; d[e] = o; } const s = n?.bridge && !i ? n.bridge.resolvePath({ filePath: resolveContainerPathCandidate(o), cwd: n.resolutionCwd ?? t }).containerPath : o; const c = resolveContainerPathCandidate(s); const l = resolveSandboxPathMapping(a, c); const f = l?.mapping.hostRoot ?? t; const p = l?.hostPath ?? c; const m = l ? [] : n?.additionalRoots ?? []; let h; try { if (n?.bridge && !i && !l) throw new Error(`Path escapes sandbox root (${n.containerWorkdir ?? t}): ${s}`); if (!n?.bridge || i || n.readPathValidation !== "bridge") h = await assertSandboxPathWithinAnyRoot({ cwd: !l ? n?.resolutionCwd : void 0, filePath: p, roots: [f, ...m], allowLinkedWorktrees: !n?.bridge && n?.allowLinkedWorktrees }); } catch (e) { throw withWorkspaceSafeTempHint(e); } if (n?.normalizeGuardedPathParams && u) { d ??= { ...u }; d[e] = n.bridge && !i ? s : h.resolved; } } return e.execute(r, d ?? s, c, l); } }; } function withSandboxToolAbortSignal(e, t) { return { ...e, execute: (n, r, i, a) => e.execute(n, r, t && i ? AbortSignal.any([t, i]) : i ?? t, a) }; } /** Preserve the sandbox namespace before session tools use host path resolution. */ function wrapSandboxFileToolPath(e, t) { return { ...e, execute: async (n, r, i, a) => { const o = asOptionalObjectRecord(r); const s = o?.path; const c = s === void 0 || s === "" ? t.defaultPath : s; if (!o || typeof c !== "string") return e.execute(n, r, i, a); const l = await normalizeFileToolPathParam(c, t.root, t.bridge); if (l === "") throw malformedXmlArgValuePathError("path"); const u = t.bridge.resolvePath({ filePath: resolveContainerPathCandidate(l), cwd: t.root }); return e.execute(n, { ...o, path: u.containerPath }, i, a); } }; } function createSandboxedReadTool(e) { return withSandboxToolAbortSignal(createOpenClawReadTool(eraseSessionFileTool(createReadTool(e.root, { operations: createSandboxReadOperations(e), maxBytes: resolveAdaptiveReadMaxBytes(e), modelBudget: resolveToolResultBudget(e.modelContextWindowTokens), modelHasVision: e.modelHasVision })), { modelContextWindowTokens: e.modelContextWindowTokens, imageSanitization: e.imageSanitization, cwd: e.root, bridge: e.bridge }), e.abortSignal); } function createSandboxedWriteTool(e) { const t = eraseSessionFileTool(createWriteTool(e.root, { operations: createSandboxMutationOperations(e) })); return withSandboxToolAbortSignal(wrapToolParamValidation(wrapSandboxFileToolPath(t, e), REQUIRED_PARAM_GROUPS.write), e.abortSignal); } function createSandboxedEditTool(e) { const t = eraseSessionFileTool(createEditTool(e.root, { operations: createSandboxMutationOperations(e) })); return withSandboxToolAbortSignal(wrapToolParamValidation(wrapSandboxFileToolPath(t, e), REQUIRED_PARAM_GROUPS.edit), e.abortSignal); } function createHostWorkspaceMutationTool(e, t, n) { const r = createHostMutationOperations(n?.containmentRoot ?? t, n); const i = e === "write" ? eraseSessionFileTool(createWriteTool(t, { operations: r })) : eraseSessionFileTool(createEditTool(t, { operations: r })); return wrapToolParamValidation(i, REQUIRED_PARAM_GROUPS[e], t); } function createHostWorkspaceWriteTool(e, t) { return createHostWorkspaceMutationTool("write", e, t); } function createHostWorkspaceEditTool(e, t) { return createHostWorkspaceMutationTool("edit", e, t); } function createOpenClawReadTool(e, t) { const n = resolveToolResultBudget(t?.modelContextWindowTokens); return { ...e, prepareArguments: prepareReadToolParams, execute: async (r, i, a) => { const o = asOptionalObjectRecord(i); const s = o ? await normalizeFileToolPathParamsFromKeys(o, ["path"], t?.cwd, t?.bridge) : void 0; assertRequiredParams(s, REQUIRED_PARAM_GROUPS.read, e.name); const c = typeof s?.path === "string" ? s.path : "<unknown>"; const l = await normalizeReadImageResult(await executeReadWithAdaptivePaging({ base: e, toolCallId: r, args: s?.optional === void 0 && isDailyMemoryReadPath(c) ? { ...s, optional: true } : s ?? {}, signal: a, maxBytes: resolveAdaptiveReadMaxBytes(t), modelBudget: n }), c); return normalizeReadResultDetails({ ...await sanitizeToolResultImages(l, `read:${c}`, t?.imageSanitization), details: l.details }); } }; } /** Serve exact non-filesystem skill locators before workspace path guards run. */ function wrapReadToolWithSkillContent(e, t, n) { const r = n?.cwd ?? process.cwd(); const resolveInstructionPath = (e) => { if (e.startsWith("node://")) return e; const t = mapContainerPathToWorkspaceRoot({ filePath: e, root: r, containerWorkdir: n?.containerWorkdir }); return resolveToCwd(t, r); }; const i = new Map((n?.instructionPaths ?? []).map((e) => [resolveInstructionPath(e), void 0])); for (const e of t ?? []) i.set(resolveInstructionPath(e.filePath), e.filePath.startsWith("node://") ? e.readContent : void 0); if (i.size === 0) return e; const a = n?.instructionDeliveryCache; const readContent = (e) => { const t = i.get(e); if (t === void 0) throw Object.assign(/* @__PURE__ */ new Error(`Virtual skill file not found: ${e}`), { code: "ENOENT" }); return t; }; let o; return { ...e, execute: async (t, r, s, c) => { const l = asOptionalObjectRecord(r); const u = l?.path; const d = typeof u === "string" ? normalizeFileToolPathParam(u) : void 0; const f = d ? resolveInstructionPath(d) : void 0; if (!d || !f || !i.has(f)) return e.execute(t, r, s, c); for (;;) { const e = a?.get(f); if (!e) break; const t = await e; if (a?.get(f) !== e) continue; if (t) return createAlreadyDeliveredSkillResult(e); a?.delete(f); } let settleDelivery = (e) => void 0; let p; if (a) { p = new Promise((e) => { settleDelivery = e; }); a.set(f, p); } const resetDelivery = () => { settleDelivery(false); if (p && a?.get(f) === p) a.delete(f); }; const m = typeof i.get(f) === "string" ? o ??= createOpenClawReadTool(eraseSessionFileTool(createReadTool("/", { maxBytes: resolveAdaptiveReadMaxBytes(n), modelBudget: resolveToolResultBudget(n?.modelContextWindowTokens), operations: { resolvePath: (e) => e, access: async (e) => void readContent(e), readFile: async (e) => Buffer.from(readContent(e), "utf8") } })), n) : e; const h = { ...l, path: d }; const { offset: g, limit: _, cursor: v, ...y } = h; try { const e = await m.execute(t, y, s, c); const n = e.details; const r = n.kind; if (r === "truncated") { resetDelivery(); return g !== void 0 || _ !== void 0 || v !== void 0 ? await m.execute(t, h, s) : e; } if (r !== "text") { resetDelivery(); return e; } if (!s?.aborted) rememberSkillInstructionDelivery(e, n.content, p); settleDelivery(true); return e; } catch (e) { resetDelivery(); throw e; } } }; } function resolveHostPath(e) { return path.resolve(expandOsHomePrefix(e)); } async function statHostFile(e) { try { const t = await fs.stat(e); return { type: t.isFile() ? "file" : t.isDirectory() ? "directory" : "other", size: t.size, mtimeMs: t.mtimeMs }; } catch (e) { if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") return null; throw e; } } function createHostMutationOperations(e, t) { if (!(t?.workspaceOnly ?? false)) return withMemoryWriteProvenance({ mkdir: async (e) => { const n = resolveHostPath(e); const r = captureAgentToolSourceExecutionGuard(t?.abortSignal); await runWithAgentToolSourceExecutionScope(r, async () => { r(); await fs.mkdir(n, { recursive: true }); }); }, writeFile: (e, n) => writeHostFile(e, n, t?.abortSignal), readFile: async (e) => fs.readFile(resolveHostPath(e)), statFile: (e) => statHostFile(resolveHostPath(e)), access: async (e) => { await fs.access(resolveHostPath(e)); } }, t?.memoryWriteProvenance); const n = /* @__PURE__ */ new Map(); const getRoot = (e) => { let t = n.get(e); if (!t) { t = root(e); n.set(e, t); } return t; }; return withMemoryWriteProvenance({ mkdir: async (n) => { const r = captureAgentToolSourceExecutionGuard(t?.abortSignal); const i = await resolveHostRootAsync(e, n); const a = toRelativeWorkspacePath(i, n, { allowRoot: true }); const o = await resolveRootPath({ absolutePath: path.resolve(i, a), rootPath: i, boundaryLabel: "workspace root" }); const s = await findExistingAncestor(o.rootCanonicalPath); if (s && s !== o.rootCanonicalPath) { const e = await root(s); await runWithAgentToolSourceExecutionScope(r, async () => { await e.mkdir(`./${path.relative(s, o.rootCanonicalPath)}`, { assertBeforeMutation: r }); }); } const c = await getRoot(i); const l = toRelativeWorkspacePath(c.rootReal, o.canonicalPath, { allowRoot: true }); const u = { mutationSymlinks: "reject", assertBeforeMutation: () => { r(); toRelativeWorkspacePath(resolveHostWorkspaceRoot(e, n), n, { allowRoot: true }); } }; await runWithAgentToolSourceExecutionScope(r, async () => { if (l) await c.mkdir(`./${l}`, u); else await c.ensureRoot(u); }); }, writeFile: (n, r) => writeHostWorkspaceFile(e, getRoot, n, r, t?.abortSignal), readFile: async (t) => { const n = await resolveHostRootAsync(e, t); const r = await toCanonicalRelativeWorkspacePath(n, t); const i = await getRoot(n); return (await i.read(path.resolve(i.rootReal, r))).buffer; }, statFile: async (t) => { const n = await resolveHostRootAsync(e, t); const r = toRelativeWorkspacePath(n, t); return statHostFile(path.resolve(n, r)); }, access: async (t) => { const n = await resolveHostRootAsync(e, t); let r; try { r = await toCanonicalRelativeWorkspacePath(n, t); } catch { return; } try { const e = await getRoot(n); await (await e.open(path.resolve(e.rootReal, r))).handle.close().catch(() => {}); } catch (e) { if (e instanceof FsSafeError && e.code === "not-found") throw createFsAccessError("ENOENT", t); if (e instanceof FsSafeError && e.code === "outside-workspace") return; throw e; } } }, t?.memoryWriteProvenance); } //#endregion export { createSandboxedReadTool as a, wrapReadToolWithSkillContent as c, writeHostFile as d, createSandboxedEditTool as i, wrapSandboxFileToolPath as l, createHostWorkspaceWriteTool as n, createSandboxedWriteTool as o, createOpenClawReadTool as r, resolveAdaptiveReadMaxBytes as s, createHostWorkspaceEditTool as t, wrapToolWorkspaceRootGuardWithOptions as u };