@sema-agent/core
Version:
Stateless, task-oriented AI agent core
250 lines (249 loc) • 13.4 kB
JavaScript
import { uuidv7 } from "../../internal/harness.js";
import { snapshotActorAssertion } from "../../internal/llm.js";
import { MAX_STEER_INPUT_ID_CHARS } from "../checkpoint-store.js";
import { formatHookFeedback } from "../hooks.js";
import { classicEventBase, failedHandlerClause, legNoticeTaskId, screenUserPrompt } from "../mods/stations.js";
import { countsAsOperator, inputFrameOf, isBlankInput, isScreened } from "../input-author.js";
import { buildHumanInputEvent, frameExtensionInput, personSteerFrame, projectHumanInput } from "../human-input-projection.js";
import { injectionLaneOf, isSystemInjectionPriority, steerPriorityOf, SYSTEM_INJECTION_PRIORITIES } from "../task-notification.js";
import { deliverEngineNotice } from "../types.js";
import { sanitizeUntrustedText, sentinelTagRefusal } from "../untrusted-text.js";
import { foreignLine } from "../protocol-http-auth.js";
import { screenUserAttachments } from "../user-attachment.js";
import { announceAcceptance, armAcceptance, nextHumanInputSeq } from "./steer-admission.js";
import { steerReplayRefusal } from "../steer-replay.js";
export function streamSteerVerb(input) {
const { spec, internals, queue, acceptedSteerInputs, live, ready, orTimeout, readyTimeoutMs: READY_TIMEOUT_MS, steeringError, runner } = input;
let steerChain = Promise.resolve();
const steerAs = async (author, text, options, call) => {
try {
screenUserAttachments(options?.userAttachments, { resumeLeg: true });
}
catch {
throw steeringError("a steer carries no attachments — declare them in TaskSpec.userAttachments on the next objective", "steering.invalid_content");
}
const trusted = options?.trusted ? true : false;
if (trusted && sanitizeUntrustedText(text) !== text) {
throw steeringError(sentinelTagRefusal("trusted steering text"), "steering.invalid_content");
}
const inputId = options?.inputId;
if (inputId !== undefined) {
if (typeof inputId !== "string") {
throw steeringError("inputId must be a string when supplied", "steering.invalid_content");
}
if (inputId === "" || inputId.length > MAX_STEER_INPUT_ID_CHARS) {
throw steeringError(`inputId must be a non-empty string of at most ${MAX_STEER_INPUT_ID_CHARS} characters`, "steering.invalid_content");
}
}
const priorityIn = options?.priority;
if (priorityIn !== undefined && !isSystemInjectionPriority(priorityIn)) {
throw steeringError(`priority must be one of ${SYSTEM_INJECTION_PRIORITIES.join("/")} when supplied`, "steering.invalid_content");
}
const priority = steerPriorityOf({ priority: priorityIn });
const sourceIn = options?.source;
if (sourceIn !== undefined && sourceIn !== "steer" && sourceIn !== "system") {
throw steeringError('source must be "steer" or "system" when supplied', "steering.invalid_content");
}
const source = sourceIn === "system" ? "system" : "steer";
const actorIn = options?.actor;
const actor = actorIn === undefined ? undefined : snapshotActorAssertion(actorIn);
const frameFor = (t, reminderMark) => {
switch (inputFrameOf(author)) {
case "person":
return personSteerFrame(t, actor, trusted, reminderMark, source);
case "extension":
return frameExtensionInput(call?.extension, projectHumanInput({ text: t, actor, source }));
case "verbatim":
return projectHumanInput({ text: t, actor, source });
}
};
const effectiveInputId = typeof inputId === "string" ? inputId : uuidv7();
const parkRecord = {
text,
trusted,
inputId: effectiveInputId,
...(priorityIn !== undefined ? { priority } : {}),
...(actor !== undefined ? { actor } : {}),
...(sourceIn !== undefined ? { source } : {}),
};
let given;
let record = parkRecord;
let payload;
let mintsAFrame;
let rewrittenBy;
const attribution = {
...(author !== "operator" ? { author } : {}),
...(call !== undefined ? { extension: call.extension } : {}),
};
const publishQueued = (h) => {
const identity = internals?.parentToolCallId !== undefined ? { parentToolCallId: internals.parentToolCallId, sourceTaskId: h.hookIdentity.taskId } : {};
queue.push({
...buildHumanInputEvent({
carrier: "steer",
source,
delivery: "queued",
sessionSeq: nextHumanInputSeq(h.harness),
inputId: effectiveInputId,
...(actor !== undefined ? { actor } : {}),
...(actor?.issuer !== undefined ? { issuer: actor.issuer } : {}),
...(spec.principal !== undefined ? { principal: spec.principal } : {}),
...attribution,
}),
eventId: uuidv7(),
...identity,
});
return { identity, attribution, ...(rewrittenBy !== undefined ? { rewrittenBy } : {}) };
};
const noteAccepted = () => {
if (!mintsAFrame)
return;
if (typeof inputId === "string")
acceptedSteerInputs.set(inputId, record);
announceAcceptance(record);
};
let entered = text;
const taken = () => (given !== undefined && mintsAFrame ? { replied: given.text } : { entered });
const deliver = async () => {
if (live.resultValue)
throw steeringError("the task has already finished");
const h = live.handle ?? (await orTimeout(ready));
if (!h)
throw steeringError("the task is not running");
payload = frameFor(text, h.reminderMark);
mintsAFrame = !isBlankInput(payload);
if (typeof inputId === "string") {
const prior = acceptedSteerInputs.get(inputId);
if (prior !== undefined) {
if (inputWindow() === "over")
throw steeringError("the task is no longer running");
const refusal = steerReplayRefusal(prior, parkRecord, { seat: "accepted" });
if (refusal !== undefined)
throw steeringError(refusal.message, "steering.duplicate_input_id", refusal.detail);
return { entered };
}
}
if (inputWindow() === "over")
throw steeringError("the task is no longer running");
if (!countsAsOperator(author) && h.harness.engineInjectionsHeld?.() === true) {
throw steeringError("the run stopped on the person's own refusal and they have not spoken since — an input that is not theirs does not restart it");
}
if (mintsAFrame && isScreened(author)) {
const screen = await screenUserPrompt(h.modBus, {
...classicEventBase(h.hookIdentity, h.permissionMode.observed),
prompt: text,
source,
inputId: effectiveInputId,
...(actor !== undefined ? { actor: snapshotActorAssertion(actor) } : {}),
}, call?.signal !== undefined ? AbortSignal.any([h.abortController.signal, call.signal]) : h.abortController.signal, { author, tier: priority, whileScreened: h.hookScreens.prompt, ...(call !== undefined ? { extension: call.extension, raisedUnder: { frames: call.frames, origin: call.origin } } : {}) });
if (screen?.kind === "aborted") {
throw steeringError(`the task was cancelled while the deployment's userPromptSubmit hook was still screening this steering input; the input was NOT accepted (fail-closed)`, "steering.blocked_by_hook");
}
if (screen?.kind === "failed") {
throw steeringError(`the deployment's userPromptSubmit hook ${failedHandlerClause(screen)} while screening this steering input; the input was NOT accepted (fail-closed)`, "steering.blocked_by_hook");
}
if (screen?.block !== undefined && screen.block !== "") {
throw steeringError(`the deployment's userPromptSubmit hook blocked this steering input: ${foreignLine(screen.block)}`, "steering.blocked_by_hook");
}
if (screen?.kind === "answered" && screen.rewrittenBy !== undefined) {
entered = screen.text;
payload = frameFor(screen.text, h.reminderMark);
mintsAFrame = !isBlankInput(payload);
rewrittenBy = screen.rewrittenBy;
}
if (screen?.kind === "answered" && screen.reply !== undefined) {
given = screen.reply;
record = { ...parkRecord, reply: { text: screen.reply.text, by: screen.reply.by, ...(entered !== text ? { entered } : {}) } };
}
if (screen?.additionalContext !== undefined && screen.additionalContext !== "") {
payload = `${formatHookFeedback(screen.additionalContext, h.reminderMark)}\n\n${payload}`;
}
}
const injectFramed = async () => {
if (call?.signal?.aborted === true)
throw steeringError("the extension's call was cancelled before the input was taken");
const noteOptions = { provenance: "engine-note", author, parkRecord: record, input: { inputId: effectiveInputId }, ...(actor !== undefined ? { actor } : {}) };
if (mintsAFrame)
armAcceptance(record, () => publishQueued(h));
if (injectionLaneOf(priority) === "followUp") {
await h.harness.followUp(payload, { ...noteOptions, ...(given !== undefined ? { givenAnswer: given } : {}) });
noteAccepted();
return;
}
const frame = await h.harness.steer(payload, { ...noteOptions, ...(priority === "now" ? { immediate: true } : {}) });
noteAccepted();
if (priority === "now" && frame !== undefined && h.harness.interruptTurn(frame)) {
deliverEngineNotice(runner.deps.onNotice, {
code: "task.turn_interrupted",
message: "a caller-provenance steer with priority \"now\" interrupted the running turn: in-flight work was cut at " +
"a manufactured boundary (finished tool calls keep their real results; never-started ones settle as " +
"interrupted) and the run continues with the steer at the queue head.",
detail: {
inputId: effectiveInputId,
sessionId: h.sessionId,
runId: h.runId,
...(actor?.id !== undefined ? { actorId: actor.id } : {}),
...legNoticeTaskId(h.hookIdentity),
},
});
}
};
try {
await injectFramed();
return taken();
}
catch (e) {
if (!(e instanceof Error && e.code === "invalid_state"))
throw e;
}
const birthDeadline = Date.now() + READY_TIMEOUT_MS;
while (inputWindow() !== "over" && Date.now() < birthDeadline) {
try {
await injectFramed();
return taken();
}
catch (e2) {
if (!(e2 instanceof Error && e2.code === "invalid_state"))
throw e2;
}
await new Promise((r) => setTimeout(r, 10));
}
throw steeringError("the task is no longer running");
};
const p = steerChain.then(deliver);
steerChain = p.then(() => undefined, () => undefined);
return p;
};
const authoredSteer = async (author, text, call) => {
try {
return await steerAs(author, text, call !== undefined ? { priority: call.priority } : undefined, call);
}
catch (e) {
if (isSteeringRefusal(e))
return { drop: e.message };
throw e;
}
};
const inputWindow = () => {
if (live.resultValue !== undefined || live.bodySettled)
return "over";
const h = live.handle;
if (h === undefined)
return "before";
if (h.loop.ended)
return "over";
return h.harness.takingInput ? "open" : "before";
};
return {
steer: async (text, options) => {
await steerAs("operator", text, options);
},
authoredSteer,
inputWindow,
};
}
function isSteeringRefusal(e) {
if (!(e instanceof Error))
return false;
const code = e.code;
return typeof code === "string" && code.startsWith("steering.");
}