@sema-agent/core
Version:
Stateless, task-oriented AI agent core
139 lines (138 loc) • 6.94 kB
JavaScript
import { renderTaskNotificationXml } from "../task-notification.js";
import { describeThrown } from "../tool-policy.js";
import { foreignLine } from "../protocol-http-auth.js";
import { ENGINE_ORIGIN } from "./kernel/index.js";
import { isPlainRecord } from "./kernel/receive.js";
import { classicEventBase, failedHandlerClause, seatHears, textChanges } from "./stations.js";
export const SESSION_RECEIVE_ORIGIN_KINDS = Object.freeze(["task", "agent", "peer", "host", "engine"]);
const ENGINE = Object.freeze({ kind: "engine" });
export function receiveOriginOf(p) {
if (p.agentMessage !== undefined)
return Object.freeze({ kind: "agent", from: p.agentMessage.from });
if (p.crossSessionMessage !== undefined)
return Object.freeze({ kind: "peer", from: p.crossSessionMessage.from });
if (p.crossSessionNotice !== undefined || p.inboxNotice !== undefined)
return ENGINE;
if (p.task_type === "external")
return Object.freeze({ kind: "host", ...(p.source !== undefined ? { from: p.source } : {}) });
return Object.freeze({ kind: "task", taskType: p.task_type });
}
function eventOf(p) {
return Object.freeze({ taskId: p.task_id, taskType: p.task_type, status: p.status, ...(p.seq !== undefined ? { seq: p.seq } : {}) });
}
const FORM = "session.receive takes { text } (a non-blank string) or { consumed: <reason> }";
function readAnswer(a) {
if (!isPlainRecord(a))
return { why: FORM };
const keys = Object.keys(a);
if (keys.length === 1 && keys[0] === "consumed") {
const r = a["consumed"];
return typeof r === "string" && r.trim() !== "" ? { consumed: r } : { why: "a consumed that is not a reason (a non-empty string)" };
}
if (keys.length === 1 && keys[0] === "text") {
const t = a["text"];
return typeof t === "string" && t.trim() !== "" ? { text: t } : { why: "a text that is not a non-blank string (consume the frame instead)" };
}
return { why: FORM };
}
const RANKS = Object.freeze({ of: (a) => (isPlainRecord(a) && Object.hasOwn(a, "consumed") ? 1 : 0), top: 1 });
export function createReceiveSeat() {
let bound;
const consumed = (binding, frame, by, reason) => {
const verdict = Object.freeze({ kind: "consumed", by, reason });
binding.report(consumedFrameReport(frame, verdict));
return verdict;
};
const receiveBound = async (binding, payload) => {
const made = payload.received === undefined ? payload : (({ received: _r, ...rest }) => rest)(payload);
const text = renderTaskNotificationXml(made);
const e = { ...classicEventBase(binding.identity), origin: receiveOriginOf(made), event: eventOf(made), text };
const changes = textChanges(text);
const checkHandOn = (handed, by) => {
const t = handed["text"];
if (typeof t !== "string" || t.trim() === "")
return "next() handed on a text that is not a non-blank string";
changes.handedOn(by.plugin, t);
return undefined;
};
const bottom = (handed) => Object.freeze({ text: handed["text"] });
const checkAnswer = (a, handed, by, below) => {
const read = readAnswer(a);
if ("why" in read)
return read.why;
if ("text" in read) {
const up = below.length > 0 ? readAnswer(below[below.length - 1]) : undefined;
changes.answered(by.plugin, read.text, handed["text"], up !== undefined && "text" in up ? up.text : undefined);
}
return undefined;
};
let outcome;
try {
outcome = await binding.bus.dispatch("session.receive", e, { bottom, checkAnswer, checkHandOn, ranks: RANKS, ...(binding.signal !== undefined ? { signal: binding.signal } : {}) });
}
catch (err) {
return consumed(binding, made, ENGINE_ORIGIN.plugin, `the session.receive station could not be raised (${describeThrown(err)}); the frame was not handed over (fail-closed)`);
}
if (outcome.kind === "aborted")
return Object.freeze({ kind: "arrived", payload: made });
if (outcome.kind === "failed")
return consumed(binding, made, outcome.registration, `a session.receive extension ${failedHandlerClause(outcome)}; the frame was not handed over (fail-closed)`);
const read = readAnswer(outcome.answer);
const by = outcome.answeredBy ?? ENGINE_ORIGIN.plugin;
if ("consumed" in read)
return consumed(binding, made, by, read.consumed);
if ("why" in read)
return consumed(binding, made, by, `extension "${foreignLine(by, 80)}" answered in a form session.receive does not take (${read.why}); the frame was not handed over (fail-closed)`);
if (read.text === text)
return Object.freeze({ kind: "arrived", payload: made });
return Object.freeze({ kind: "arrived", payload: { ...made, received: Object.freeze({ text: read.text, rewrittenBy: changes.rewrittenBy() }) } });
};
return {
listens: () => seatHears(bound, "session.receive"),
receive: async (payload) => {
const binding = bound;
if (!seatHears(binding, "session.receive"))
return Object.freeze({ kind: "arrived", payload });
try {
return await receiveBound(binding, payload);
}
catch (err) {
return consumed(binding, payload, ENGINE_ORIGIN.plugin, `the session.receive station could not judge the frame (${describeThrown(err)}); it was not handed over (fail-closed)`);
}
},
bind: (binding) => {
bound = binding;
},
};
}
export function createReceivingChain(seatOf) {
let tail;
return {
pass: (payload, arms) => {
const seat = seatOf();
if (!seat.listens())
return arms.handOver(payload);
tail = (tail ?? Promise.resolve())
.then(async () => {
const verdict = await seat.receive(payload);
if (verdict.kind === "arrived")
arms.handOver(verdict.payload);
else
arms.consumed?.(verdict);
})
.catch((err) => {
try {
arms.fault(err);
}
catch {
}
});
},
get settled() {
return tail;
},
};
}
export function consumedFrameReport(payload, verdict) {
return new Error(`session.receive: the ${payload.task_type} frame for ${foreignLine(payload.task_id, 80)} (${payload.status}) was not handed to the model — consumed by ${verdict.by === ENGINE_ORIGIN.plugin ? "the engine" : `extension "${foreignLine(verdict.by, 80)}"`}: ${foreignLine(verdict.reason, 300)}`);
}