@sema-agent/core
Version:
Stateless, task-oriented AI agent core
89 lines (88 loc) • 5.71 kB
JavaScript
import { describeThrown } from "../tool-policy.js";
import { foreignLine } from "../protocol-http-auth.js";
import { extensionCallOf } from "./extension-call.js";
import { ENGINE_ORIGIN } from "./kernel/index.js";
import { isPlainRecord } from "./kernel/receive.js";
import { NEXT_IN_FLIGHT } from "./kernel/site-rules.js";
import { classicEventBase, failedHandlerClause, seatHears } from "./stations.js";
export const SESSION_SEND_ORIGIN_KINDS = Object.freeze(["model", "plugin"]);
const GO = Object.freeze({ go: true });
const FORM = "session.send takes next(e) or { isDelivered: false, reason } in place of it";
function refusalOf(a) {
if (!isPlainRecord(a) || a["isDelivered"] !== false || Object.keys(a).some((k) => k !== "isDelivered" && k !== "reason"))
return undefined;
const r = a["reason"];
return typeof r === "string" && r.trim() !== "" ? r : undefined;
}
const RANKS = Object.freeze({ of: (a) => (refusalOf(a) !== undefined ? 1 : 0), top: 1 });
export function createSessionSendStation(input) {
return {
listens: () => seatHears(input, "session.send"),
send: async (facts, signal) => {
if (!seatHears(input, "session.send"))
return GO;
const call = extensionCallOf(input.bus, facts.toolCallId);
const origin = call !== undefined ? Object.freeze({ kind: "plugin", name: call.caller.origin.plugin }) : Object.freeze({ kind: "model" });
const e = { ...classicEventBase(input.identity), origin, to: facts.to, text: facts.text };
const started = Object.freeze({ to: facts.to, text: facts.text });
const checkAnswer = (a, _e, _by, below, ran) => {
if (a === started)
return undefined;
if (isPlainRecord(a) && a["isDelivered"] === true)
return "a delivery claimed by a handler (isDelivered: true) — the engine delivers the message; next(e) lets it go";
if (refusalOf(a) === undefined)
return FORM;
if (ran.bottomStarted)
return "a refusal after the message was let go (refuse in place of next)";
if (below.includes(NEXT_IN_FLIGHT) || below.some((b) => refusalOf(b) === undefined))
return "a refusal while its next(e) still runs or after it was answered (refuse in place of next)";
return undefined;
};
let outcome;
try {
outcome = await input.bus.dispatch("session.send", e, { bottom: () => started, checkAnswer, ranks: RANKS, ...(signal !== undefined ? { signal } : {}) });
}
catch (err) {
return { go: false, by: ENGINE_ORIGIN.plugin, reason: `the session.send station could not be raised (${describeThrown(err)}); the message was not sent (fail-closed)` };
}
if (outcome.kind === "aborted")
return outcome.bottomStarted === true ? GO : { go: false, by: ENGINE_ORIGIN.plugin, reason: "the send was cancelled before the message went" };
if (outcome.kind === "failed")
return { go: false, by: outcome.registration, reason: `a session.send extension ${failedHandlerClause(outcome)} before the message went; it was not sent (fail-closed)` };
if (outcome.answer === started)
return GO;
const by = outcome.answeredBy ?? ENGINE_ORIGIN.plugin;
const reason = refusalOf(outcome.answer);
return {
go: false,
by,
reason: reason !== undefined ? `extension "${foreignLine(by, 80)}" refused this message before it went: ${foreignLine(reason, 300)}` : `extension "${foreignLine(by, 80)}" answered this message in a form session.send does not take; it was not sent (fail-closed)`,
};
},
};
}
const textOf = (content) => (Array.isArray(content) ? content.map((b) => (isPlainRecord(b) && b["type"] === "text" && typeof b["text"] === "string" ? b["text"] : "")).join("") : "");
export function createSessionSendEntry(input) {
return async (args, ctx) => {
const by = ctx.origin.plugin;
const refuse = (why) => new TypeError(`${by}: $.session.send: refused: ${why}`);
const extra = Object.keys(args).find((k) => k !== "to" && k !== "text");
if (extra !== undefined)
throw refuse(`takes { to, text }; "${foreignLine(extra, 40)}" is not one`);
const to = args["to"];
const text = args["text"];
if (typeof to !== "string" || to.trim() === "")
throw refuse("no { to } (a non-empty string)");
if (typeof text !== "string" || text.trim() === "")
throw refuse("no { text } (a non-empty string)");
if (!input.tools().includes(input.sendToolName))
return Object.freeze({ isDelivered: false, reason: "this session has no SendMessage tool (messaging between sessions and agents is not on here)" });
const answer = await input.toolCall({ tool: input.sendToolName, to, message: text }, ctx);
if (isPlainRecord(answer) && typeof answer["deny"] === "string")
return Object.freeze({ isDelivered: false, reason: answer["deny"] });
const result = isPlainRecord(answer) && isPlainRecord(answer["result"]) ? answer["result"] : undefined;
if (result === undefined)
return Object.freeze({ isDelivered: false, reason: "SendMessage did not answer" });
return result["isError"] === true ? Object.freeze({ isDelivered: false, reason: textOf(result["content"]) || "the message was not sent" }) : Object.freeze({ isDelivered: true });
};
}