UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

118 lines (117 loc) • 6.36 kB
import { isCheckpointRowUnreadable as isUnreadableRowRefusal } from "../core/checkpoint-queries.js"; import { isolationScopeOf } from "../core/isolation-scope.js"; import { parentSpecSeatOfCtx } from "../core/parent-spec-seat.js"; import { thrownText } from "../core/thrown-value.js"; import { inlineUntrusted } from "../core/untrusted-text.js"; import { foreignLine } from "../core/protocol-http-auth.js"; import { delegationRegistryOf } from "./delegation-registry-seat.js"; import { callOccupant } from "../core/task-registry-shared.js"; const yieldAdoptions = new WeakMap(); async function adoptYieldedAgents(bag, execute, enrich, leg) { const adopted = []; const refused = []; let unreadable; try { const ctx = enrich({ toolCallId: "yield-adoption" }); const store = bag.agentStore; const parkStore = ctx.checkpointStoreForChildren === undefined ? bag.checkpointStore : ctx.checkpointStoreForChildren === "disabled" ? undefined : ctx.checkpointStoreForChildren; if (store === undefined || parkStore === undefined || bag.ensureChildSessionDurable === undefined || ctx.sessionId === undefined) return { adopted, refused }; const scope = isolationScopeOf(parentSpecSeatOfCtx(ctx) ?? {}) ?? bag.scope; const owner = ctx.taskId ?? bag.owner; const sessionId = ctx.sessionId; const registry = delegationRegistryOf(ctx, bag); for (const summary of await store.listBySession(scope, sessionId, { status: "parked" })) { if ("rowVerdict" in summary) continue; if (!(summary.sessionScoped ? summary.owner === sessionId : leg.resumed && summary.owner === owner)) continue; const row = await store.get(summary.handle, scope); if (row === null || row.status !== "parked" || row.parkedCheckpointToken === undefined) continue; let cp; try { cp = await parkStore.get(row.parkedCheckpointToken); } catch (e) { if (!isUnreadableRowRefusal(e)) throw e; refused.push({ id: row.handle, why: foreignLine(thrownText(e), 300) }); continue; } if (cp === null || cp.status !== "pending" || cp.gate.kind !== "resource_limit" || cp.gate.reason !== "preempt") continue; const claim = await registry.claimParkedAgent({ agentStore: store, checkpointStore: parkStore }, row.handle, { owner, scope, sessionId, ...callOccupant(ctx, {}) }); if (!claim.ok) { if (claim.reason === "store_unreachable") refused.push({ id: row.handle, why: "the store could not be reached to claim it" }); continue; } const ticket = claim.ticket; if (ticket.token !== row.parkedCheckpointToken) { await registry.rollbackParkedClaim({ agentStore: store, checkpointStore: parkStore }, ticket).catch(() => undefined); continue; } try { const ownerGate = ctx.inheritedGateForChildren?.(); const ownerMode = ownerGate?.permissionModeCeiling?.current ?? ownerGate?.permissionMode; const out = await execute({ description: row.description ?? "yielded agent", prompt: "continue", run_in_background: true, ...(row.agentType !== undefined ? { subagent_type: row.agentType } : {}), name: row.name, ...(row.model !== undefined ? { model: row.model } : {}) }, enrich({ toolCallId: `yield-drive-${ticket.claimId}`, reviveClaim: { row: { ...structuredClone(ticket.row), parkClaimId: ticket.claimId }, rev: ticket.reservedRev, parkedResume: { ticket, outcome: { gate: "resource_limit", decision: "continue" }, ...(ownerMode !== undefined ? { inheritedGate: { permissionMode: ownerMode } } : {}) } } })); if (typeof out === "object" && out !== null && out.isError === true) throw new Error(inlineUntrusted(JSON.stringify(out.content ?? ""), 300)); adopted.push(row.handle); } catch (e) { await registry.rollbackParkedClaim({ agentStore: store, checkpointStore: parkStore }, ticket).catch(() => undefined); refused.push({ id: row.handle, why: foreignLine(thrownText(e), 300) }); } } } catch (e) { unreadable = foreignLine(thrownText(e), 300); } return { adopted, refused, ...(unreadable !== undefined ? { unreadable } : {}) }; } export function registerYieldAdoption(node, bag) { if (bag !== undefined) yieldAdoptions.set(node.execute, (enrich, leg) => adoptYieldedAgents(bag, node.execute, enrich, leg)); } export function legAdoptionOf(contributors) { return { run: async () => { try { await contributors.yielded(); } catch { } let workflowContinuation; try { workflowContinuation = await contributors.workflowParks?.(); } catch { workflowContinuation = undefined; } return workflowContinuation !== undefined ? { workflowContinuation } : {}; }, }; } export async function adoptYieldedBackgroundWork(tools, enrich, leg, onError) { const seen = new Set(); for (const tool of tools) { const adopt = typeof tool.execute === "function" ? yieldAdoptions.get(tool.execute) : undefined; if (adopt === undefined || seen.has(adopt)) continue; seen.add(adopt); const { refused, unreadable } = await adopt(enrich, leg); const said = [ ...(unreadable !== undefined ? [`this leg could not look for the yielded background agents it owns — the row store answered: ${unreadable}; the next leg looks again.`] : []), ...(refused.length > 0 ? [`this leg could not continue ${refused.length} yielded background agent(s) it owns: ${refused.map((r) => `${r.id} (${r.why})`).join("; ")} — they stay parked and the next leg tries again.`] : []), ]; for (const sentence of said) { try { onError(new Error(sentence)); } catch { } } } }