UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

171 lines (170 loc) • 8.36 kB
import { hasWorkspaceSync } from "../remote-env.js"; import { deliverEngineNotice } from "../engine-notice.js"; import { readMember, thrownText } from "../thrown-value.js"; import { teardownLegBudget } from "./teardown-bounded.js"; import { remoteEnvFailureNote } from "./remote-env-retry.js"; const IN_FLIGHT = new Set(); function workspaceIdentitiesOf(env) { const identities = [env]; try { const read = readMember(env, "workspaceHandle"); if (typeof read === "function") { const handle = read.call(env); const provider = readMember(handle, "provider"); const sandboxId = readMember(handle, "sandboxId"); if (typeof provider === "string" && typeof sandboxId === "string" && sandboxId !== "") identities.push(`${provider}\u0000${sandboxId}`); } } catch { } return identities; } function inFlightOn(env) { const mine = workspaceIdentitiesOf(env); for (const entry of IN_FLIGHT) if (workspaceIdentitiesOf(entry.env).some((identity) => mine.includes(identity))) return entry; return undefined; } function readAnswer(answer) { const ok = readMember(answer, "ok"); if (ok === true) return { ok: true }; if (ok === false) { const error = readMember(answer, "error"); const code = readMember(error, "code"); const message = readMember(error, "message"); if (typeof code === "string" && code.trim() !== "") return { ok: false, code: code, message: typeof message === "string" ? message : "", how: "answered" }; } return { ok: false, code: "unknown", message: "the workspace sync answered outside the seam's shape", how: "answered" }; } async function syncOnce(env, reason, boundMs, cut) { const release = new AbortController(); let timer; let onCut; const waitEnds = new Promise((resolve) => { timer = setTimeout(() => resolve("timeout"), Math.max(1, boundMs)); if (cut !== undefined) { if (cut.aborted) resolve("aborted"); onCut = () => resolve("aborted"); cut.addEventListener("abort", onCut, { once: true }); } }); const stopped = (why, made) => { release.abort(); const before = made ? "the workspace sync did not answer" : "the workspace sync was not made: the previous sync of this workspace had not settled"; return { ok: false, code: why, message: why === "timeout" ? `${before} within the engine's ${boundMs} ms bound` : `${before} before the run was cut`, how: made ? "unanswered" : "not_made" }; }; try { for (let prior = inFlightOn(env); prior !== undefined; prior = inFlightOn(env)) { if (prior.abandoned) { const returned = await Promise.race([prior.settled.then(() => true), new Promise((resolve) => setTimeout(() => resolve(false), 0))]); if (returned) continue; return { ok: false, code: "command_in_flight", message: "the workspace sync was not made: the previous sync of this workspace did not return within a later sync's whole wait after its abortSignal fired, and this workspace is not synced in this process until that call returns", how: "skipped" }; } const first = await Promise.race([prior.settled.then(() => "settled"), waitEnds]); if (first !== "settled") { const outcome = stopped(first, false); if (first === "timeout" && prior.release.signal.aborted) { prior.abandoned = true; return { ...outcome, message: `${outcome.message}; its abortSignal had fired, so the engine gives up on it and does not sync this workspace in this process until it returns`, gaveUp: true }; } if (reason === "destroy") prior.release.abort(); return outcome; } } if (cut?.aborted) return { ok: false, code: "aborted", message: "the workspace sync was not made: the run was cut before it started", how: "not_made" }; const call = Promise.resolve() .then(() => env.syncWorkspace(reason, { abortSignal: release.signal })) .then(readAnswer, (thrown) => ({ ok: false, code: "unknown", message: `the workspace sync threw: ${thrownText(thrown)}`, how: "answered" })); const own = { env, settled: call.then(() => undefined), release, abandoned: false }; IN_FLIGHT.add(own); void own.settled.then(() => IN_FLIGHT.delete(own)); const answer = await Promise.race([call, waitEnds]); return typeof answer === "string" ? stopped(answer, true) : answer; } finally { if (timer !== undefined) clearTimeout(timer); if (onCut !== undefined) cut?.removeEventListener("abort", onCut); } } export function legWorkspaceSync(input) { const { env } = input; if (env === undefined || !hasWorkspaceSync(env)) return undefined; let stretch = "synced"; let skipTold = false; const sync = async (reason, boundMs, cut, resultOpen) => { let outcome; try { outcome = await syncOnce(env, reason, boundMs, cut); } catch (thrown) { outcome = { ok: false, code: "unknown", message: `the workspace sync could not be made: ${thrownText(thrown)}`, how: "unanswered" }; } if (outcome.ok) return true; const abandonment = outcome.how === "skipped" || outcome.gaveUp === true; if (outcome.how === "skipped" && skipTold) return false; if (abandonment) skipTold = true; const note = remoteEnvFailureNote("syncWorkspace", outcome, outcome.how === "answered" || outcome.how === "unanswered" ? 1 : 0); if (resultOpen) input.remoteEnvFailures.push(note); const message = abandonment ? `The execution environment's workspace sync (${reason}) was not made (${note.code}): an earlier sync of this workspace did not return within a later sync's whole wait after the engine fired its abortSignal, and none is started beside it. ` + `This workspace is not synced again in this process until that call returns (told once per run). The run went on and its result is unchanged. Check that the adapter's sync settles once its abortSignal fires.` : `The execution environment's workspace sync (${reason}) did not answer ok (${note.code}). The run went on and its result is unchanged; ` + `what the workspace held at this point may not be kept. Check the adapter's sync seat and its storage.`; try { deliverEngineNotice(input.onNotice, { code: "workspace.sync_failed", message, detail: { reason, code: note.code, retryable: note.retryable, sessionId: input.sessionId, ...(input.runId !== undefined ? { runId: input.runId } : {}) }, }); } catch { } return outcome.how === "answered"; }; return { turnOpened: () => { stretch = "open"; }, turnEnded: async () => { if (stretch !== "open") return; stretch = "synced"; const answered = await sync("turn_end", teardownLegBudget(), input.runSignal, true); if (!answered && stretch === "synced") stretch = "unkept"; }, parking: async (cut) => { await sync("turn_end", teardownLegBudget(), cut, true); }, legEnded: async (destroying, boundMs) => { if (destroying) await sync("destroy", boundMs, undefined, false); else if (stretch !== "synced") { stretch = "synced"; await sync("turn_end", boundMs, undefined, false); } }, }; } export async function syncAtRewindEnd(env, destroying, input) { const seat = legWorkspaceSync({ env, sessionId: input.sessionId, onNotice: input.onNotice, remoteEnvFailures: [], runSignal: new AbortController().signal }); if (seat === undefined) return; seat.turnOpened(); await seat.legEnded(destroying, input.boundMs); }