UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

57 lines (56 loc) • 2.95 kB
function errorMeansDead(code) { return code === "not_found" || code === "not_directory"; } function resolutionFailureMeansDead(code) { return errorMeansDead(code) || code === "unknown"; } function cancelled(signal) { return signal?.aborted === true; } export async function isDeadCwd(env, dir, signal) { const info = await env.fileInfo(dir, signal); if (!info.ok) { if (info.error.code !== "unknown") return errorMeansDead(info.error.code); const resolved = await env.canonicalPath(dir, signal); return !resolved.ok && resolutionFailureMeansDead(resolved.error.code); } if (info.value.kind === "directory") return false; if (info.value.kind !== "symlink") return true; const target = await env.canonicalPath(dir, signal); if (!target.ok) return resolutionFailureMeansDead(target.error.code); const followed = await env.fileInfo(target.value, signal); if (!followed.ok) return errorMeansDead(followed.error.code); return followed.value.kind !== "directory" && followed.value.kind !== "symlink"; } export async function diagnoseDeadCwd(env, toolName, effectiveCwd, root, cwdRef, signal) { if (!(await isDeadCwd(env, effectiveCwd, signal))) return undefined; if (cancelled(signal)) return undefined; if (root === undefined) { return (`Error (${toolName}): command did not run — the working directory no longer exists (or is no longer a directory): ${effectiveCwd} ` + `(it was likely deleted or replaced by a previous command). No reset target is known to this tool; ` + "re-establish the working directory with a Bash `cd` to a live directory and retry."); } if (cwdRef && cwdRef.current !== root) { const rootAlive = !(await isDeadCwd(env, root, signal)); if (cancelled(signal)) return undefined; if (rootAlive) { cwdRef.current = root; return (`Error (${toolName}): command did not run — the working directory no longer exists (or is no longer a directory): ${effectiveCwd}\n` + `(it was likely deleted or replaced by a previous command). The working directory has been reset to ${root}; ` + `re-run your command (cd first if you need a different directory).`); } return (`Error (${toolName}): command did not run — the working directory ${effectiveCwd} AND the task root ${root} no longer exist. ` + `The shell has no usable directory to run in; this task cannot recover its working tree.`); } return (`Error (${toolName}): command did not run — the task root directory no longer exists (or is no longer a directory): ${effectiveCwd}. ` + `It was likely deleted by a previous command (e.g. rm -rf on the current directory). There is no directory to reset to; ` + `this task cannot recover its working tree.`); }