UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

366 lines (365 loc) • 19.2 kB
import { hasBackgroundShellOver } from "./background-shell.js"; import { callerText } from "./caller-text.js"; import { deliverEngineNotice } from "./engine-notice.js"; import { envNameKeyOn, readEnvLayer } from "./secret-env.js"; import { isDeploymentEnvCode } from "./remote-env.js"; import { readMember } from "./thrown-value.js"; import { egressForeignText, egressThrownText } from "./untrusted-egress.js"; import { isAbsoluteForFamily } from "./unc-spelling.js"; import { namesNeedingFact } from "./tool-mount-plan.js"; import { inlineUntrusted } from "./untrusted-text.js"; export function hasModelShell(env) { return modelShellOf(env) !== undefined; } const receivedStarts = new WeakMap(); function receivedStart(env) { const kept = receivedStarts.get(env); if (kept !== undefined) return kept; const start = env.modelShell; if (typeof start === "object" && start !== null) { const first = receivedStarts.get(env); if (first !== undefined) return first; receivedStarts.set(env, start); } return start; } function modelShellOf(env) { try { const start = receivedStart(env); return typeof start === "object" && start !== null && typeof start.exec === "function" ? start : undefined; } catch { return undefined; } } export function startsInBackground(start) { try { return typeof start?.spawnBackground === "function"; } catch { return false; } } export function declaredModelShell(env) { const declared = declaredStart(env); const background = declared.kind === "asks" || declared.kind === "mounted" ? declared.background : undefined; return { mounted: declared.kind === "asks" ? undefined : declared.kind === "mounted", backgroundLaunch: background?.launch === true }; } export function mountedModelShellOf(reading, factory) { const r = reading; if (typeof r === "object" && r !== null && r.kind === "mounted" && typeof r.start?.exec === "function" && typeof r.background === "object" && r.background !== null) return r; throw new TypeError(`${factory}: options.modelShell must be the mounted reading readModelShell(env) answers for this environment — read it once with readModelShell(env) and hand it to every shell tool you mount; where it is not mounted, mount none`); } export function backgroundLifecycleOf(env, reading) { return reading.background.launch ? env : undefined; } export const MODEL_SHELL_UNDECLARED_REFUSAL = "this environment does not start commands on bash; no command can run here"; export const STARTED_SHELL = "bash"; export const STARTUP_FILE_NAMES = Object.freeze(["BASH_ENV", "ENV"]); export function startedShellDeclaration(shell) { return shell === STARTED_SHELL ? {} : { startedShell: shell }; } const UNDECLARED = Object.freeze({ kind: "undeclared" }); const unavailable = (cause) => Object.freeze({ kind: "unavailable", cause }); function backgroundFaceOf(env, spawnBackground) { try { const caps = env.backgroundCapabilities; const launch = typeof spawnBackground === "function" && hasBackgroundShellOver(env, caps); return Object.freeze({ launch, detach: launch && caps.supportsDetach === true }); } catch { return Object.freeze({ launch: false, detach: false }); } } function mountedReading(member, exec, spawnBackground, background, shell, version) { const start = Object.freeze({ exec: (script, options) => Reflect.apply(exec, member, [script, options]), ...(typeof spawnBackground === "function" ? { spawnBackground: (script, options) => Reflect.apply(spawnBackground, member, [script, options]) } : {}), }); return Object.freeze({ kind: "mounted", shell, version, start, background }); } export const MODEL_SHELL_READY_TIMEOUT_MS = 5_000; function declaredStart(env) { let start; try { start = receivedStart(env); } catch (error) { return unavailable(`reading ExecutionEnv.modelShell threw: ${egressThrownText("same-principal", error)}`); } if (start === undefined) return UNDECLARED; if (typeof start !== "object" || start === null) return unavailable("ExecutionEnv.modelShell is not a method group with an exec function"); let exec; let ready; try { exec = start.exec; } catch (error) { return unavailable(`reading ExecutionEnv.modelShell.exec threw: ${egressThrownText("same-principal", error)}`); } if (typeof exec !== "function") return unavailable("ExecutionEnv.modelShell is not a method group with an exec function"); let spawnBackground; try { spawnBackground = start.spawnBackground; } catch (error) { return unavailable(`reading ExecutionEnv.modelShell.spawnBackground threw: ${egressThrownText("same-principal", error)}`); } try { ready = start.ready; } catch (error) { return unavailable(`reading ExecutionEnv.modelShell.ready threw: ${egressThrownText("same-principal", error)}`); } const member = start; const background = backgroundFaceOf(env, spawnBackground); const mounted = (kind) => ("kind" in kind ? kind : mountedReading(member, exec, spawnBackground, background, kind.shell, kind.version)); if (ready === undefined) return mounted({ shell: STARTED_SHELL, version: "" }); if (typeof ready !== "function") return unavailable("ExecutionEnv.modelShell.ready is not a function"); return { kind: "asks", start, ready: ready, mounted, background }; } export function readModelShell(env) { return readModelShellWithin(env, MODEL_SHELL_READY_TIMEOUT_MS); } export async function readModelShellWithin(env, timeoutMs) { const declared = declaredStart(env); if (declared.kind !== "asks") return declared; const { start, ready, mounted } = declared; const bound = Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.min(timeoutMs, MODEL_SHELL_READY_TIMEOUT_MS) : MODEL_SHELL_READY_TIMEOUT_MS; let timer; const late = new Promise((settle) => { timer = setTimeout(() => settle(unavailable(`ExecutionEnv.modelShell.ready did not settle within ${bound} ms (timed out)`)), bound); }); const asked = (async () => { try { const answer = await Reflect.apply(ready, start, []); if (typeof answer === "object" && answer !== null && answer.ok === true) return mounted(kindReading(answer.value)); const failure = typeof answer === "object" && answer !== null ? answer.error : undefined; if (failure === undefined) return unavailable("ExecutionEnv.modelShell.ready answered no result"); const cause = egressThrownText("same-principal", failure); const refusal = refusalOf(failure, cause); return refusal !== undefined ? Object.freeze({ kind: "unavailable", cause, refusal }) : unavailable(cause); } catch (error) { return unavailable(`ExecutionEnv.modelShell.ready threw: ${egressThrownText("same-principal", error)}`); } })(); try { return await Promise.race([asked, late]); } finally { clearTimeout(timer); } } function refusalOf(failure, cause) { const code = readMember(failure, "code"); const message = readMember(failure, "message"); return isDeploymentEnvCode(code) ? Object.freeze({ code, message: typeof message === "string" ? egressForeignText("same-principal", message) : cause }) : undefined; } function kindReading(value) { const shell = typeof value === "object" && value !== null ? value.shell : undefined; const version = typeof value === "object" && value !== null ? value.version : undefined; if (typeof version !== "string") return unavailable("ready reported no shell kind"); if (version === "" && (shell === STARTED_SHELL || shell === "zsh")) return { shell, version }; if (shell === STARTED_SHELL) { const read = bashVersionReading(version); if (read === undefined) return unavailable("ready reported a version that is not of the form M.N"); return read.below === undefined ? { shell: STARTED_SHELL, version: read.version } : unavailable(`the start ${read.below}`); } if (shell === "zsh") return ZSH_VERSION_FORM.test(version) ? { shell: "zsh", version } : unavailable("ready reported a version that is not of the form M.N[.P]"); return unavailable("ready reported no shell kind"); } function bashVersionReading(text) { const read = /^([0-9]+)\.([0-9]+)$/.exec(text); if (read === null) return undefined; const m = Number(read[1]); const n = Number(read[2]); return { version: text, below: m > 3 || (m === 3 && n >= 2) ? undefined : `is bash ${text}, below 3.2` }; } const ZSH_VERSION_FORM = /^[0-9]+\.[0-9]+(?:\.[0-9]+)?$/; export const SHELL_KIND_QUESTION = 'if [ -n "${ZSH_VERSION-}" ]; then [ "$(emulate)" = zsh ] && [[ "$(builtin set -o)" == "$(builtin emulate zsh; builtin set -o)" ]] && (( ${#functions} + ${#galiases} + ${#saliases} == 0 )) && [[ "${(ok)aliases}" == "run-help which-command" ]] && builtin print -rn -- "zsh $ZSH_VERSION"; else builtin shopt -qo braceexpand && ! builtin shopt -qo posix && builtin printf "bash %s.%s" "${BASH_VERSINFO[0]}" "${BASH_VERSINFO[1]}"; fi'; export const SHELL_KIND_QUESTION_OPTIONS = Object.freeze(["-f", "-p", "-c"]); export function readShellKindAnswer(stdout) { const answered = /^bash (.*)$/s.exec(stdout); const bash = answered === null ? undefined : bashVersionReading(answered[1]); if (bash !== undefined) return bash.below === undefined ? { ok: true, shell: "bash", version: bash.version } : { ok: false, reason: bash.below }; const zsh = stdout.startsWith("zsh ") ? stdout.slice("zsh ".length) : undefined; if (zsh !== undefined && ZSH_VERSION_FORM.test(zsh)) return { ok: true, shell: "zsh", version: zsh }; return { ok: false, reason: "gave no answer to the shell-kind question" }; } export const ZSH_START_PREFIX = Object.freeze([ "'builtin' 'emulate' '-R' 'zsh'", "'builtin' 'unalias' '-m' '*'", "'builtin' 'unalias' '-s' '-m' '*'", "'builtin' 'unfunction' '-m' '*'", "'builtin' 'trap' '-'", "'builtin' 'hash' '-r'", "'builtin' 'hash' '-rd'", ]); export function zshStartArgs(program) { return ["-f", "-c", `${ZSH_START_PREFIX.join("\n")}\n'builtin' 'eval' "builtin shift; $1"`, program]; } export function shellStartArgs(shell, program) { if (shell !== STARTED_SHELL && shell !== "zsh") throw new Error(`shellStartArgs: shell must be ${STARTED_SHELL} or zsh (got ${callerText(shell)})`); if (typeof program !== "string") throw new Error(`shellStartArgs: program must be a string (got ${callerText(program)})`); return shell === "zsh" ? zshStartArgs(program) : ["-c"]; } const row = (match, text, inherited) => Object.freeze({ match, text, inherited }); export const SHELL_STATE_ENV = Object.freeze([ row("name", "SHELLOPTS", "dropped"), row("name", "BASHOPTS", "dropped"), ...STARTUP_FILE_NAMES.map((name) => row("name", name, "absolute-path")), row("name", "BASH_COMPAT", "dropped"), row("name", "POSIXLY_CORRECT", "dropped"), row("name", "POSIX_PEDANTIC", "dropped"), row("name", "PS4", "passes"), row("name-prefix", "BASH_FUNC_", "passes"), row("value-prefix", "() {", "passes"), ]); export function shellStateEnvRowOf(name, value, platform = process.platform) { const key = envNameKeyOn(name, platform); return SHELL_STATE_ENV.find((r) => r.match === "name" ? key === envNameKeyOn(r.text, platform) : r.match === "name-prefix" ? key.startsWith(envNameKeyOn(r.text, platform)) : typeof value === "string" && value.startsWith(r.text)); } export function configuredShellLayer(layer, label, platform = process.platform) { if (layer === undefined) return { kept: undefined, dropped: [] }; const entries = readEnvLayer(layer, label); if (typeof entries === "string") throw new Error(entries); const dropped = []; const kept = []; for (const [key, value] of entries) { const held = shellStateEnvRowOf(key, value, platform); if (held === undefined) kept.push([key, value]); else dropped.push({ key, from: "configured", row: held }); } return { kept: Object.fromEntries(kept), dropped }; } export function configuredNamesKeptOut(layers, platform = process.platform) { const gives = (layer, key) => Object.keys(layer.kept ?? {}).some((k) => envNameKeyOn(k, platform) === key) || layer.dropped.some((d) => envNameKeyOn(d.key, platform) === key); return layers.flatMap((layer, i) => layer.dropped.filter((d) => !layers.slice(i + 1).some((later) => gives(later, envNameKeyOn(d.key, platform))))); } export function inheritedShellState(env, platform = process.platform, configuredDropped = []) { const named = new Set(configuredDropped.map((d) => envNameKeyOn(d.key, platform))); const dropped = []; const kept = []; for (const [key, value] of Object.entries(env)) { if (named.has(envNameKeyOn(key, platform))) continue; const held = shellStateEnvRowOf(key, value, platform); const passes = held === undefined || held.inherited === "passes" || (held.inherited === "absolute-path" && typeof value === "string" && isAbsoluteFor(value, platform)); if (passes) kept.push([key, value]); else dropped.push({ key, from: "inherited", row: held }); } return { kept: Object.fromEntries(kept), dropped }; } function isAbsoluteFor(path, platform) { return isAbsoluteForFamily("posix", path) || (platform === "win32" && isAbsoluteForFamily("win", path)); } export function withoutAnyShellState(env, platform = process.platform) { return Object.fromEntries(Object.entries(env).filter(([key, value]) => shellStateEnvRowOf(key, value, platform) === undefined)); } export const SHELL_KIND_QUESTION_ENV_NAMES = Object.freeze(["PATH", "HOME", "LANG", "LC_*"]); const PLATFORM_WORDS = Object.freeze({ aix: true, android: true, darwin: true, freebsd: true, haiku: true, linux: true, openbsd: true, sunos: true, win32: true, cygwin: true, netbsd: true, }); export function shellKindQuestionEnv(env, platform) { if (typeof env !== "object" || env === null || Array.isArray(env)) { throw new Error(`shellKindQuestionEnv: env must be a record (got ${callerText(env)})`); } if (platform !== undefined && (typeof platform !== "string" || (!Object.hasOwn(PLATFORM_WORDS, platform) && platform !== process.platform))) { throw new Error(`shellKindQuestionEnv: platform must be one of ${Object.keys(PLATFORM_WORDS).join(", ")} (got ${callerText(platform)})`); } const on = platform ?? process.platform; const wanted = (key) => SHELL_KIND_QUESTION_ENV_NAMES.some((n) => (n.endsWith("*") ? envNameKeyOn(key, on).startsWith(envNameKeyOn(n.slice(0, -1), on)) : envNameKeyOn(key, on) === envNameKeyOn(n, on))); return Object.fromEntries(Object.entries(withoutAnyShellState(env, on)).filter(([key]) => wanted(key))); } export function announceModelShellUnmounted(reading, facts, onNotice) { if (reading.kind === "mounted" || facts["env.hands"] !== true || facts["env.performsIo"] !== true) return; deliverEngineNotice(onNotice, modelShellUnmountedNotice(reading)); } function unmountedBecause(reading) { if (reading.kind === "undeclared") return "it declares no ExecutionEnv.modelShell"; return reading.cause.trim() === "" ? "its start is unavailable" : `its start is unavailable: ${reading.cause}`; } export const MODEL_SHELL_CAUSE_MAX = 300; export function shellToolAbsence(reading, facts) { if (reading.kind === "mounted" || facts["env.hands"] !== true || facts["env.performsIo"] !== true) return undefined; const cause = reading.kind === "unavailable" && reading.cause.trim() !== "" ? inlineUntrusted(reading.cause, MODEL_SHELL_CAUSE_MAX) : undefined; const names = namesNeedingFact("env.modelShell"); return (name, text) => { if (!names.has(name)) return undefined; if (reading.kind === "undeclared") return text("core/engine.model-shell-absent-undeclared"); return cause === undefined ? text("core/engine.model-shell-absent-unavailable") : text("core/engine.model-shell-absent-unavailable-cause", { cause }); }; } export function modelShellUnmountedNotice(reading) { const because = unmountedBecause(reading); const tail = reading.kind === "undeclared" ? " Declare `ExecutionEnv.modelShell` on the adapter, or give the host a bash (3.2 or later) or a zsh." : ""; return { code: "config.model_shell_unmounted", message: `The execution environment does not start the model's commands (${because}), so Bash, Monitor and background commands are not offered on this leg.${tail}`, detail: reading.kind === "undeclared" ? { reason: "undeclared" } : { reason: "unavailable", cause: reading.cause }, }; } export function shellStateEnvDroppedNotice(dropped, more = false) { const keys = dropped.map((d) => d.key); const others = "Others were left out too; the environment keeps only the first names it drops, so those are not named."; if (dropped.length === 0) return { code: "config.shell_state_env_dropped", message: `The environment for the model's shell left out variables that change how the shell reads a command. ${others}`, detail: { keys, more: true } }; const list = (of) => of.map((d) => `\`${d.key}\``).join(", "); const never = dropped.filter((d) => d.row.inherited === "dropped"); const bodies = dropped.filter((d) => d.from === "configured" && d.row.match === "value-prefix"); const relative = dropped.filter((d) => d.from === "inherited" && d.row.inherited === "absolute-path"); const movable = dropped.filter((d) => d.from === "configured" && d.row.inherited !== "dropped" && d.row.match !== "value-prefix"); const ways = [ ...(movable.length > 0 ? [`Set ${list(movable)} in the host process's own environment if the host needs them (\`BASH_ENV\` and \`ENV\` as absolute paths).`] : []), ...(relative.length > 0 ? [`${list(relative)} in the host process's own environment ${relative.length === 1 ? "is" : "are"} not an absolute path; give the startup file as one.`] : []), ...(never.length > 0 ? [`${list(never)} ${never.length === 1 ? "is" : "are"} not passed from any source; set the option inside the command.`] : []), ...(bodies.length > 0 ? [`${list(bodies)} ${bodies.length === 1 ? "holds" : "hold"} a function body, which configuration never passes.`] : []), ]; return { code: "config.shell_state_env_dropped", message: `The environment for the model's shell carries ${list(dropped)}, which change how the shell reads a command; they are not passed to it. ${ways.join(" ")}${more ? ` ${others}` : ""}`, detail: { keys, ...(more ? { more: true } : {}) }, }; }