UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

238 lines (237 loc) • 13.6 kB
import { createPeerInboundChainRef, createPeerSelfRef } from "../../agents/peer-admission.js"; import { peerTaskFrameRefused, readsTaskFrame } from "../a2a-deployment-switches.js"; import { boundInputHashOf } from "../canonical-json.js"; import { readPendingSteerQueue } from "../checkpoint-store.js"; import { scopeKeyOf } from "../isolation-scope.js"; import { settleBeforeTurnOpen } from "./turn-open-settles.js"; import { wakeOpening } from "../run-origin.js"; import { runLedgerBookFor } from "../run-ledger.js"; import { bindRunLedgerBook } from "../run-ledger-seat.js"; import { rootAnchorOf } from "../leg-identity.js"; import { bindDeliveryObligations, createLiveNotificationLane, DeliveryObligations, DurableAppendObligations, injectionLaneOf, isDelegatedAgentTerminal, isTerminalTaskNotification, renderTaskNotificationXml, routeOrParkNotification, sessionAddressOf, SystemInjectionQueue, taskNotificationDedupKey, taskNotificationFrame, taskNotificationNoteOptions } from "../task-notification.js"; import { settleConsumedFrame, settleUndeliveredFrame } from "../frame-settlement.js"; import { createReceivingChain } from "../mods/session-receive.js"; import { asThrownError } from "../thrown-value.js"; import { ToolDetachHub } from "../tool-detach.js"; import { seatLegPrepares } from "../swappable-deps.js"; import { pendingContentAskCallId } from "./decide-continuation.js"; export function runNotificationLane(input) { const obligations = new DurableAppendObligations(); return obligations.run(() => runNotificationLaneAs(input, obligations)); } async function runNotificationLaneAs(input, obligations) { const { spec, queue, resume, internals, taskIdRef, holdSessionLock, legWrites, runEnd, promptSubmitRef, runner, self, sessions, sessionReadStates, sessionModeSeats, sessionFastModeSeats, sessionPromptSeats, sessionMcpPools, pendingSessionNotifications, prepareTask, next } = input; const prepareResume = resume ? { leafId: resume.cp.leafId, ...(resume.cp.heldRows !== undefined ? { heldRows: [...resume.cp.heldRows] } : {}), suspendedBatch: new Set(resume.cp.pendingAction.kind === "tool_approval" ? resume.cp.pendingAction.batchToolCallIds : []), seed: resume.cp.state, outcome: resume.outcome, ...(resume.cp.pendingAction.kind === "tool_approval" ? { pendingCall: { toolCallId: resume.cp.pendingAction.toolCallId, toolName: resume.cp.pendingAction.toolName, args: resume.cp.pendingAction.args } } : {}), ...((opening) => (opening !== undefined ? { opening } : {}))(resume.outcome.gate === "wake" ? wakeOpening(readPendingSteerQueue(resume.cp.state), resume.wakeMessage) : undefined), ...(resume.legMods !== undefined ? { legMods: resume.legMods } : {}), priorSuspendCount: resume.cp.suspendCount, priorLedger: resume.cp.resourceLedger, priorHumanReview: resume.cp.humanReview, workspaceHandle: resume.cp.state.workspaceHandle, executesApprovedAction: resume.cp.pendingAction.kind === "tool_approval" && resume.outcome.gate !== "wake" && resume.outcome.decision === "allow", ...(resume.outcome.gate !== "wake" && resume.outcome.decision === "allow" && pendingContentAskCallId(resume.cp) !== undefined ? { redeemedContentAskCallId: pendingContentAskCallId(resume.cp), redeemedContentAskQuestionsHash: boundInputHashOf(resume.cp.pendingAction.args?.questions), } : {}), } : undefined; const taskNotificationQueue = new SystemInjectionQueue(); const detachHub = internals?.detachHub ?? new ToolDetachHub(); let notificationHarness; let notificationIdent = () => ({}); let notificationLaneLive = true; let notificationAddress; let descendantAnchorDisclosed = false; let settlementSeat; const handOff = (payload) => { laneSeat.handOff(payload); if (settlementSeat !== undefined) settleUndeliveredFrame(settlementSeat, taskNotificationDedupKey(payload)); }; const parkTaskNotification = (payload, priority, onDisposition) => { handOff(payload); const ownSession = notificationAddress; if (ownSession !== undefined) routeOrParkNotification(pendingSessionNotifications, ownSession, payload, priority, onDisposition); else onDisposition?.("parked"); if (!isDelegatedAgentTerminal(payload)) return; const uplink = internals?.parentNotify; if (uplink !== undefined) { try { uplink(payload, { priority }); } catch (e) { runner.deps.onError?.(e, { phase: "degraded", sessionId: notificationAddress?.sessionId ?? "", classification: "descendant-terminal-uplink" }); } return; } const rootAnchor = internals?.rootSessionId; if (rootAnchor !== undefined && rootAnchor !== notificationAddress?.sessionId) { routeOrParkNotification(pendingSessionNotifications, { sessionId: rootAnchor, occupant: internals?.rootSessionIncarnation, ...(internals?.rootSessionScope !== undefined ? { scope: internals.rootSessionScope } : {}) }, payload, priority); return; } if (internals?.parentSessionId !== undefined && !descendantAnchorDisclosed) { descendantAnchorDisclosed = true; runner.deps.onError?.(new Error(`background-agent terminal ${payload.task_id} stayed on this run's own session — the delegation tree's root session is not reachable from this run (no uplink, no root anchor)`), { phase: "degraded", sessionId: notificationAddress?.sessionId ?? "", classification: "descendant-terminal-unrouted" }); } }; const receiving = createReceivingChain(() => prepared.receiveSeat); const unsubscribeTaskNotifications = taskNotificationQueue.subscribe((item) => { runLedgerBook?.observeFrame(item.payload, isTerminalTaskNotification(item.payload)); queue.push({ ...taskNotificationFrame(item.payload, item.priority), ...notificationIdent() }); receiving.pass(item.payload, { handOver: (shown) => handOver(item, shown), consumed: (verdict) => { settleConsumedFrame(prepared.frameSettlement, taskNotificationDedupKey(item.payload), verdict.by, verdict.reason); item.onDisposition?.("refused"); }, fault: (e) => runner.deps.onError?.(asThrownError(e), { phase: "degraded", sessionId: notificationAddress?.sessionId ?? "", classification: "receive-hand-over" }), }); }); function handOver(item, shown) { if (notificationHarness && prepared.batchHaltRef.current === undefined) { const xml = renderTaskNotificationXml(shown); const noteOptions = { ...taskNotificationNoteOptions(item.payload, item.priority), ...(item.payload.task_type !== "external" && isTerminalTaskNotification(item.payload) ? { capPreferred: true } : {}), }; const deliver = injectionLaneOf(item.priority) === "followUp" ? notificationHarness.followUp(xml, noteOptions) : notificationHarness.steer(xml, { ...noteOptions, ...(item.priority === "now" ? { immediate: true } : {}) }); void deliver.then(() => item.onDisposition?.("queued"), () => { parkTaskNotification(item.payload, item.priority, item.onDisposition); }); } else { parkTaskNotification(item.payload, item.priority, item.onDisposition); } } const upstreamTaskNotification = internals?.onTaskNotification; const deliveredAtTurnOpen = new Set(); const laneSeat = createLiveNotificationLane({ parkedDurably: (key) => notificationAddress !== undefined && pendingSessionNotifications.holdsDurably(notificationAddress, key), queue: taskNotificationQueue, canTakeNow: () => notificationLaneLive && notificationHarness?.acceptsInjections === true, isLive: () => notificationLaneLive, alreadyDelivered: (key) => deliveredAtTurnOpen.has(key), }); const takeOnThisLane = laneSeat.take; const takeAsDestination = (payload, priority, onDisposition) => (readsTaskFrame(runner.deps, payload) ? laneSeat.takeAsDestination(payload, priority, onDisposition) : "unavailable"); const refusePeerTaskFrame = (notification) => { runner.deps.onError?.(peerTaskFrameRefused(notification.task_id), { phase: "degraded", sessionId: notificationAddress?.sessionId ?? "", classification: "peer-task-frame-refused" }); return Promise.resolve("refused"); }; const injectTaskNotification = (notification, opts) => { if (!readsTaskFrame(runner.deps, notification)) return refusePeerTaskFrame(notification); const priority = opts?.priority ?? "later"; return new Promise((resolve) => { const own = takeOnThisLane(notification, priority, resolve); if (own === "duplicate") resolve("dropped_duplicate"); else if (own === "pending") resolve("queued"); else if (own === "unavailable") parkTaskNotification(notification, priority, resolve); }); }; const peerSelfRef = internals?.peerSelfRef ?? createPeerSelfRef(internals?.registryScope ?? scopeKeyOf(spec)); const peerInboundChainRef = internals?.peerInboundChainRef ?? createPeerInboundChainRef(); const modelCatalog = runner.deps.models; const deliveryObligations = new DeliveryObligations(); const runLedgerBook = runLedgerBookFor(spec, resume !== undefined ? { section: resume.cp.state.runLedger } : undefined, internals?.rowTaskId); if (taskIdRef !== undefined && runLedgerBook?.taskId !== undefined) taskIdRef.current = runLedgerBook.taskId; const laneSink = (notification, opts) => { if (!readsTaskFrame(runner.deps, notification)) return refusePeerTaskFrame(notification); try { upstreamTaskNotification?.(notification, opts); } catch { } const terminal = isTerminalTaskNotification(notification); const outcome = injectTaskNotification(notification, opts); if (terminal) deliveryObligations.discharge(notification); return outcome; }; bindDeliveryObligations(laneSink, deliveryObligations); const legDeps = runner.deps; seatLegPrepares(spec.getApiKeyAndHeaders, legDeps.models); const prepared = await prepareTask(spec, legDeps, sessions, prepareResume, { ...(internals ?? {}), peerSelfRef, peerInboundChainRef, detachHub, sessionReadStates, sessionModeSeats, sessionFastModeSeats, sessionPromptSeats, sessionMcpPools, onTaskNotification: laneSink, runLedgerBook, }, self, taskIdRef, holdSessionLock, legWrites, (destination, delivery) => pendingSessionNotifications.discardsStaleNotice(destination, delivery), promptSubmitRef, runEnd); settlementSeat = prepared.frameSettlement; if (runLedgerBook !== undefined) bindRunLedgerBook(runLedgerBook, prepared, rootAnchorOf(internals, prepared.sessionId, prepared.sessionIncarnation).occupant); try { pendingSessionNotifications.admit(sessionAddressOf(prepared), prepared.sessionBox); const settling = settleBeforeTurnOpen(pendingSessionNotifications, prepared, { deps: runner.deps, spec, internals }); if (settling !== undefined) await settling; } catch (err) { prepared.endModLife(); throw err; } prepared.harness.on("before_agent_start", async () => { await receiving.settled; return undefined; }); const notificationLane = { get harness() { return notificationHarness; }, set harness(h) { notificationHarness = h; }, get address() { return notificationAddress; }, set address(a) { if (notificationAddress !== undefined) pendingSessionNotifications.liveLanes.unregister(notificationAddress, takeAsDestination); notificationAddress = a; if (a !== undefined && notificationLaneLive) pendingSessionNotifications.liveLanes.register(a, takeAsDestination); }, get ident() { return notificationIdent; }, set ident(f) { notificationIdent = f; }, handOff, get live() { return notificationLaneLive; }, set live(v) { notificationLaneLive = v; if (notificationAddress === undefined) return; if (v) { pendingSessionNotifications.liveLanes.register(notificationAddress, takeAsDestination); } else { pendingSessionNotifications.liveLanes.unregister(notificationAddress, takeAsDestination); laneSeat.release(); } }, }; try { return await next({ prepared, injectTaskNotification, deliveredAtTurnOpen, peerInboundChainRef, modelCatalog, notificationLane, unsubscribeTaskNotifications, deliveryObligations }); } finally { if (notificationAddress !== undefined) pendingSessionNotifications.liveLanes.unregister(notificationAddress, takeAsDestination); prepared.endModLife(); await obligations.settle(); } }