UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

125 lines (124 loc) • 8.14 kB
import { uuidv7 } from "../../internal/harness.js"; import { createSafeNotifier, observeThenableRejection } from "../safe-notify.js"; import { recordFrameReceipt, toolResultReceiptKey } from "../frame-settlement.js"; import { discloseDroppedPending, renderTaskNotificationXml, taskNotificationDedupKey } from "../task-notification.js"; import { buildAppliedHumanInputEvent } from "../human-input-projection.js"; import { announceAcceptance, nextHumanInputSeq } from "./steer-admission.js"; import { deliverDelegationLifecycle, deliverEngineNotice, parentLegIds, undrainedUserInputNotices } from "../types.js"; export function runIdentityWiring(input) { const { spec, queue, prepared, internals, taskIdRef, onReady, manualCompactRef, notifyRef, captureOptOutRef, mcpRedialRef, injectTaskNotification, deliveredAtTurnOpen, peerInboundChainRef, notificationLane, pendingSessionNotifications, runner } = input; notificationLane.harness = prepared.harness; notificationLane.sessionId = prepared.sessionId; if (taskIdRef) taskIdRef.effectiveMemoryScopes = prepared.effectiveMemoryScopes; if (taskIdRef) taskIdRef.editedFiles = prepared.editedFilesSnapshot; const runSourceTaskId = spec.taskId ?? prepared.sessionId; const parentToolCallId = internals?.parentToolCallId; const ident = () => parentToolCallId !== undefined ? { eventId: uuidv7(), parentToolCallId, sourceTaskId: runSourceTaskId } : { eventId: uuidv7() }; notificationLane.ident = ident; const internalsNotifier = createSafeNotifier({ onError: (f) => console.warn(`[sema-core] ${f.site}: run-internals sink threw (contained; further failures counted, not re-disclosed): ${f.error.message}`), }); const wiringManifest = prepared.wiringManifest; queue.push({ type: "wiring_manifest", manifest: wiringManifest, ...ident() }); internalsNotifier.notify(() => observeThenableRejection(internals?.onWiringManifest?.(wiringManifest), internalsNotifier, "runtask.onWiringManifest"), "runtask.onWiringManifest"); prepared.toolRosterDeltas.subscribe((delta) => queue.push({ type: "tool_roster_delta", delta, ...ident() })); prepared.toolDisclosure?.subscribe((snapshot) => queue.push({ type: "tool_disclosure", ...snapshot, ...ident() })); const delegationLifecycleNotifier = createSafeNotifier({ onError: (f) => console.warn(`[sema-core] ${f.site}: delegation-lifecycle observer threw (contained; further failures counted, not re-disclosed): ${f.error.message}`), }); const emitDelegationLifecycle = (event) => { if (!prepared.hookIdentity.isDelegatedChild) return; if (runner.deps.onDelegationLifecycle === undefined) return; deliverDelegationLifecycle(runner.deps.onDelegationLifecycle, event, delegationLifecycleNotifier, "runtask.onDelegationLifecycle"); }; emitDelegationLifecycle({ phase: "spawn", identity: prepared.hookIdentity }); if (taskIdRef !== undefined && prepared.hookIdentity.isDelegatedChild && runner.deps.onDelegationLifecycle !== undefined) { taskIdRef.delegationTerminalOwed = prepared.hookIdentity; } manualCompactRef.emitMooted = (reason) => { queue.push({ type: "compaction_outcome", outcome: "mooted", trigger: "manual", reason, ...ident() }); }; prepared.harness.onUndrainedEngineNotes = (payloads) => { if (notificationLane.sessionId === undefined) return; const boxBacked = prepared.frameSettlement.boxBacked; for (const p of payloads) { if (boxBacked !== undefined && boxBacked(p)) continue; pendingSessionNotifications.pend(notificationLane.sessionId, p); } }; prepared.harness.engineInjectionsHeld = () => prepared.batchHaltRef.current !== undefined; let undrainedUserAtEnd; let userInputLostAtEnd = false; prepared.harness.onUndrainedUserInputs = (counts) => { userInputLostAtEnd = counts.steer + counts.followUp > 0; if (prepared.pausedRef.current !== undefined || prepared.undeliveredContinuationRef.current.parkedSteers.length > 0) { undrainedUserAtEnd = counts; return; } for (const notice of undrainedUserInputNotices(counts, spec.taskId ?? prepared.sessionId, prepared.sessionId, prepared.runId, parentLegIds(internals))) { deliverEngineNotice(runner.deps.onNotice, notice); } }; prepared.harness.onEngineNoteConsumed = (p) => { const payload = p; const peer = payload?.peer; if (peer !== undefined && Array.isArray(peer.hopChain)) peerInboundChainRef.current = [...peer.hopChain]; if (notificationLane.sessionId !== undefined && typeof payload?.task_id === "string" && typeof payload.status === "string") pendingSessionNotifications.markDelivered(notificationLane.sessionId, taskNotificationDedupKey(payload)); }; prepared.harness.onUserInputConsumed = (record) => { const steer = record; const identity = announceAcceptance(steer); queue.push({ ...buildAppliedHumanInputEvent({ carrier: "steer", source: "steer", sessionSeq: nextHumanInputSeq(prepared.harness), inputId: steer.inputId, actor: steer.actor, principal: spec.principal }), eventId: uuidv7(), ...identity }); }; prepared.harness.onFrameCommitted = (carrier, entryId) => { const seam = prepared.frameSettlement; if (seam.awaiting.size === 0) return; const key = carrier.kind === "tool_result" ? toolResultReceiptKey(carrier.toolCallId) : (() => { const payload = carrier.payload; return typeof payload?.task_id === "string" && typeof payload.status === "string" ? taskNotificationDedupKey(payload) : undefined; })(); if (key !== undefined) recordFrameReceipt(seam, key, carrier.kind === "tool_result" ? carrier.content : undefined, entryId); }; if (notifyRef) notifyRef.inject = injectTaskNotification; if (captureOptOutRef && prepared.memoryEngineSession?.captureOptOut !== undefined) { captureOptOutRef.flip = prepared.memoryEngineSession.captureOptOut.flip; } if (mcpRedialRef && prepared.mcpRedial !== undefined) { mcpRedialRef.redial = prepared.mcpRedial; } try { internals?.onNotifyInjectorReady?.(injectTaskNotification); } catch { } { const pendingIdle = pendingSessionNotifications.drain(prepared.sessionId); if (pendingIdle !== undefined) { for (const payload of discloseDroppedPending(pendingIdle)) { const parkedPriority = pendingIdle.priorities?.get(payload); deliveredAtTurnOpen.add(taskNotificationDedupKey(payload)); queue.push({ type: "task_notification", notification: payload, ...(parkedPriority !== undefined ? { priority: parkedPriority } : {}), ...ident() }); void prepared.harness.nextTurn(renderTaskNotificationXml(payload), { provenance: "engine-note", enginePayload: payload }).catch(() => { pendingSessionNotifications.pend(prepared.sessionId, payload, parkedPriority); }); } } } const loopLatch = { ended: false, userInterrupted: false, userHalted: false }; onReady({ harness: prepared.harness, abortController: prepared.abortController, loop: loopLatch, reminderMark: prepared.reminderMark, sessionId: prepared.sessionId, runId: prepared.runId, hookTimeoutMs: prepared.hookTimeoutMs, hookIdentity: prepared.hookIdentity, permissionMode: prepared.permissionMode }); const stats = { turns: 0, tokens: 0, toolCalls: 0, promptTokens: 0, totalInputTokens: 0, cachedTokens: 0, cacheWriteTokens: 0, cacheWriteTokensLong: 0, outputTokens: 0, costMicroUsd: 0 }; return { runSourceTaskId, parentToolCallId, ident, emitDelegationLifecycle, loopLatch, stats, internalsNotifier, undrainedUserAtEnd: { get current() { return undrainedUserAtEnd; } }, userInputLostAtEnd: { get current() { return userInputLostAtEnd; } } }; }