@sema-agent/core
Version:
Stateless, task-oriented AI agent core
174 lines (173 loc) • 12.3 kB
JavaScript
import { uuidv7 } from "../../internal/harness.js";
import { observeThenableRejection } from "../safe-notify.js";
import { forwardSafely, hostSinkNotifier } from "./forward-sink.js";
import { createSnapshotFrameSeat } from "../snapshot-frame-seat.js";
import { emitsChildRowFrames, taskStartedFrame } from "../delegation-frames.js";
import { delegationTerminalReceipt } from "../mods/station-receipt.js";
import { recordFrameReceipt, toolResultReceiptKey } from "../frame-settlement.js";
import { createReceivingChain } from "../mods/session-receive.js";
import { discloseDroppedPending, isSystemInjectionPriority, isTerminalTaskNotification, parkAtSeat, renderTaskNotificationXml, sessionAddressOf, taskNotificationDedupKey, taskNotificationFrame, taskNotificationNoteOptions } from "../task-notification.js";
import { buildAppliedHumanInputEvent } from "../human-input-projection.js";
import { announceAcceptance, nextHumanInputSeq } from "./steer-admission.js";
import { deliverDelegationLifecycle, deliverEngineNotice, parentLegIds, parkedInputIdsOf, undrainedUserInputNotices } from "../types.js";
import { droppedInputsDisclosure, droppedInputsNotice } from "../input-author.js";
import { legNoticeTaskId } from "../mods/stations.js";
import { announceDigest, withAnnounceDigests } from "./announce-once-ledger.js";
import { inputSourceOf } from "../steer-replay.js";
import { mintCallerStopGate } from "./caller-stop-gate.js";
export function runIdentityWiring(input) {
const { spec, queue, prepared, resume, internals, taskIdRef, onReady, manualCompactRef, notifyRef, captureOptOutRef, mcpRedialRef, injectTaskNotification, deliveredAtTurnOpen, peerInboundChainRef, notificationLane, pendingSessionNotifications, runner } = input;
notificationLane.harness = prepared.harness;
notificationLane.address = sessionAddressOf(prepared);
if (taskIdRef)
taskIdRef.effectiveMemoryScopes = prepared.effectiveMemoryScopes;
if (taskIdRef)
taskIdRef.editedFiles = prepared.editedFilesSnapshot;
if (taskIdRef)
taskIdRef.readFloorUnkept = prepared.readFloorUnkept;
if (taskIdRef)
taskIdRef.posture = prepared;
const runSourceTaskId = prepared.taskId;
const parentToolCallId = internals?.parentToolCallId;
const ident = () => parentToolCallId !== undefined ? { eventId: uuidv7(), parentToolCallId, sourceTaskId: runSourceTaskId } : { eventId: uuidv7() };
notificationLane.ident = ident;
const internalsNotifier = hostSinkNotifier(runner.deps.onNotice, "run_internals");
const legAt = Object.freeze({ taskId: prepared.taskId, sessionId: prepared.sessionId, runId: prepared.runId });
const offerLegFrame = (frame) => {
Object.freeze(frame);
const accepted = queue.push(frame);
if (accepted && internals?.onLegFrame !== undefined) {
internalsNotifier.notify(() => observeThenableRejection(internals.onLegFrame?.(frame, legAt), internalsNotifier, "runtask.onLegFrame"), "runtask.onLegFrame");
}
return accepted;
};
createSnapshotFrameSeat(() => prepared.wiringManifest).subscribe((manifest) => offerLegFrame({ type: "wiring_manifest", manifest, ...ident() }));
prepared.toolRosterDeltas.subscribe((delta) => queue.push({ type: "tool_roster_delta", delta, ...ident() }));
prepared.mcp.pending?.open();
prepared.toolDisclosure?.subscribe((snapshot) => queue.push({ type: "tool_disclosure", ...snapshot, ...ident() }));
prepared.prefixChanges.subscribe(({ causes, segments, ...where }) => queue.push({ type: "prefix_changed", ...where, causes: [...causes], ...(segments !== undefined ? { segments: [...segments] } : {}), ...ident() }));
prepared.workspaceFrame.subscribe((snapshot) => offerLegFrame({ type: "workspace_changed", ...snapshot, ...ident() }));
const delegationLifecycleNotifier = hostSinkNotifier(runner.deps.onNotice, "delegation_lifecycle");
const emitDelegationLifecycle = (event) => {
if (!prepared.hookIdentity.isDelegatedChild || runner.deps.onDelegationLifecycle === undefined)
return;
deliverDelegationLifecycle(runner.deps.onDelegationLifecycle, event.phase === "terminal" ? { ...event, ...delegationTerminalReceipt(prepared.modBus, internals) } : event, delegationLifecycleNotifier, "runtask.onDelegationLifecycle", runner.deps.onNotice);
};
if (emitsChildRowFrames(prepared.hookIdentity) && (resume === undefined || resume.opensCycle === true)) {
const started = taskStartedFrame({ taskId: runSourceTaskId, sessionId: prepared.sessionId, model: prepared.model.id, identity: prepared.hookIdentity, startedAt: prepared.legStartedAt }, internals, ident());
queue.push(started);
forwardSafely(internals, started);
emitDelegationLifecycle({ phase: "spawn", identity: prepared.hookIdentity });
}
if (taskIdRef !== undefined && prepared.hookIdentity.isDelegatedChild && runner.deps.onDelegationLifecycle !== undefined) {
taskIdRef.delegationTerminalOwed = { identity: prepared.hookIdentity, receipt: () => delegationTerminalReceipt(prepared.modBus, internals) };
}
manualCompactRef.emitMooted = (reason) => {
queue.push({ type: "compaction_outcome", outcome: "mooted", trigger: "manual", reason, ...ident() });
};
prepared.harness.onUndrainedEngineNotes = (payloads, tiers) => {
const address = notificationLane.address;
if (address === undefined)
return;
const boxBacked = prepared.frameSettlement.boxBacked;
payloads.forEach((p, i) => {
if (boxBacked !== undefined && boxBacked(p))
return;
const tier = tiers[i];
notificationLane.handOff(p);
parkAtSeat(pendingSessionNotifications, address, p, isSystemInjectionPriority(tier) ? tier : "later");
});
};
prepared.harness.engineInjectionsHeld = () => prepared.batchHaltRef.current !== undefined;
let undrainedUserAtEnd;
let userInputLostAtEnd = false;
prepared.harness.onUndrainedUserInputs = (counts, parkRecords) => {
userInputLostAtEnd = counts.steer + counts.followUp > 0;
const inputIds = parkRecords !== undefined ? parkedInputIdsOf(parkRecords) : undefined;
if (prepared.pausedRef.current !== undefined || prepared.undeliveredContinuationRef.current.parkedSteers.length > 0) {
undrainedUserAtEnd = { steer: counts.steer, followUp: counts.followUp, ...(inputIds !== undefined ? { inputIds } : {}) };
return;
}
for (const notice of undrainedUserInputNotices({ ...counts, ...(inputIds !== undefined ? { inputIds } : {}) }, prepared.taskId, prepared.sessionId, prepared.runId, parentLegIds(internals))) {
deliverEngineNotice(runner.deps.onNotice, notice);
}
};
prepared.harness.onUndrainedOtherInputs = (authors) => {
runner.deps.onError?.(droppedInputsDisclosure(authors), { phase: "degraded", sessionId: prepared.sessionId, classification: "undelivered-input-dropped" });
const notice = droppedInputsNotice(authors, { ...prepared.legNotice.route.address, ...legNoticeTaskId(prepared), runId: prepared.runId });
const digest = announceDigest(notice.code, prepared.sessionId);
const record = prepared.announcedListingsRef;
if (record.advisories?.includes(digest) === true)
return;
deliverEngineNotice(runner.deps.onNotice, notice, prepared.legNotice.admission);
record.advisories = withAnnounceDigests(record.advisories, [digest]);
prepared.frameReceipts.listingSnapshotOwed = true;
};
prepared.harness.onEngineNoteConsumed = (p) => {
const payload = p;
const peer = payload?.peer;
if (peer !== undefined && Array.isArray(peer.hopChain))
peerInboundChainRef.current = [...peer.hopChain];
const address = notificationLane.address;
if (address !== undefined && typeof payload?.task_id === "string" && typeof payload.status === "string")
pendingSessionNotifications.markDelivered(address, taskNotificationDedupKey(payload));
};
prepared.harness.onUserInputConsumed = (record) => {
const steer = record;
const accepted = announceAcceptance(steer);
queue.push({ ...buildAppliedHumanInputEvent({ carrier: "steer", source: inputSourceOf(steer, "steer"), sessionSeq: nextHumanInputSeq(prepared.harness), inputId: steer.inputId, actor: steer.actor, principal: spec.principal, runOrigin: steer.runOrigin, ...accepted?.attribution, rewrittenBy: accepted?.rewrittenBy }), eventId: uuidv7(), ...accepted?.identity });
};
prepared.harness.onFrameCommitted = (carrier, entryId) => {
if (carrier.kind === "attachment")
return void prepared.attachmentDelivery.settle(carrier.inputId, carrier.ordinal);
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 receiving = createReceivingChain(() => prepared.receiveSeat);
const ownAddress = sessionAddressOf(prepared);
const pendingIdle = pendingSessionNotifications.drain(ownAddress, runner.deps);
if (pendingIdle !== undefined) {
for (const payload of discloseDroppedPending(pendingIdle, prepared.taskReadHandleOf, () => prepared.listBackgroundTasks({ settled: true }))) {
const parkedPriority = pendingIdle.priorities?.get(payload);
deliveredAtTurnOpen.add(taskNotificationDedupKey(payload));
prepared.runLedgerBook?.observeFrame(payload, isTerminalTaskNotification(payload));
queue.push({ ...taskNotificationFrame(payload, parkedPriority), ...ident() });
const handOver = (shown) => {
void prepared.harness.nextTurn(renderTaskNotificationXml(shown), taskNotificationNoteOptions(payload, parkedPriority)).catch(() => {
pendingSessionNotifications.pend(ownAddress, payload, parkedPriority);
});
};
receiving.pass(payload, { handOver, fault: () => pendingSessionNotifications.pend(ownAddress, payload, parkedPriority) });
}
}
if (receiving.settled !== undefined)
prepared.turnOpenRedelivery.current = receiving.settled;
}
const loopLatch = { ended: false, userInterrupted: false, userHalted: false, callerStop: mintCallerStopGate(spec.signal) };
onReady({ harness: prepared.harness, abortController: prepared.abortController, loop: loopLatch, reminderMark: prepared.reminderMark, sessionId: prepared.sessionId, runId: prepared.runId, hookIdentity: prepared.hookIdentity, modBus: prepared.modBus, hookScreens: prepared.hookScreens, permissionMode: prepared.permissionMode, fastMode: prepared.fastMode });
const stats = { turns: 0, tokens: 0, toolCalls: 0, promptTokens: 0, totalInputTokens: 0, cachedTokens: 0, cacheWriteTokens: 0, cacheWriteTokensLong: 0, outputTokens: 0, costMicroUsd: 0, apiDurationMs: 0 };
return { runSourceTaskId, parentToolCallId, ident, emitDelegationLifecycle, loopLatch, stats, internalsNotifier, offerLegFrame, undrainedUserAtEnd: { get current() { return undrainedUserAtEnd; } }, userInputLostAtEnd: { get current() { return userInputLostAtEnd; } } };
}