UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

73 lines (72 loc) • 2.73 kB
export const BACKGROUND_START_FAILURE_KINDS = Object.freeze({ unsupported: "never_started", not_found: "never_started", spawn_failed: "never_started", sandbox_unavailable: "never_started", limit_exceeded: "never_started", timeout: "unknown", io: "unknown", }); export const BACKGROUND_SHELL_ERROR_CODES = Object.freeze(Object.keys(BACKGROUND_START_FAILURE_KINDS)); export class BackgroundShellError extends Error { code; cause; refusedBy; briefMessage; constructor(code, message, cause) { super(message); this.code = code; this.cause = cause; this.name = "BackgroundShellError"; } } export function retainsBackgroundProcesses(lanes) { return (lanes.env === true || lanes.task === true || lanes.marked === true) && lanes.envDying !== true; } export function envDeclaresRetain(env) { const caps = env.backgroundCapabilities; return typeof caps === "object" && caps !== null && caps.retainBackgroundProcesses === true; } export async function createBackgroundOutputFile(env, prefix) { try { const tf = await env.createTempFile({ prefix, suffix: ".output" }); if (!tf.ok) return undefined; const canon = await env.canonicalPath(tf.value); return canon.ok ? canon.value : tf.value; } catch { return undefined; } } function hasLifecycleMembers(e) { return (typeof e.spawnBackground === "function" && typeof e.pollBackground === "function" && typeof e.killBackground === "function" && typeof e.disposeBackgroundShells === "function"); } function declaresSupported(declaration) { return typeof declaration === "object" && declaration !== null && declaration.supported === true; } export function hasBackgroundShell(env) { const e = env; return hasLifecycleMembers(e) && declaresSupported(e.backgroundCapabilities); } export function hasBackgroundShellOver(env, declaration) { return hasLifecycleMembers(env) && declaresSupported(declaration); } export async function sweepBackgroundShells(env, attribution, opts) { try { attribution?.markStopSourceForEnvSweep(env, "env_sweep", opts?.except); } catch { } await env.disposeBackgroundShells(opts?.except !== undefined ? { except: opts.except } : undefined); } export async function sweepRunBoundaryBackgroundShells(env, registry, lanes) { const envDying = lanes.envDying === true; if (retainsBackgroundProcesses({ env: envDeclaresRetain(env), task: lanes.task, envDying })) return; const except = envDying ? [] : registry.runningShellIds(env); await sweepBackgroundShells(env, registry, except.length > 0 ? { except } : undefined); }