@sema-agent/core
Version:
Stateless, task-oriented AI agent core
96 lines (95 loc) • 5.85 kB
JavaScript
import { MAILBOX_DUPLICATE_RECORD_ID_CODE, MAILBOX_INVALID_RECORD_ID_CODE, MAILBOX_TOMBSTONED_RECIPIENT_CODE, MailboxStoreError, isMailboxNameSpelling, readMailboxPeerMeta, readMailboxRecordId } from "../core/mailbox-store.js";
import { buildCrossSessionEnvelope, encodePeerAddress } from "./cross-session-envelope.js";
import { PRINCIPAL_INBOX_HANDLE } from "./cross-session-ref.js";
import { describeRejectedValue } from "../core/tool-search-setting.js";
export const PRINCIPAL_INBOX_CONSUMER_INVALID_CODE = "config.principal_inbox_consumer_invalid";
export function principalInboxConsumerOf(deps) {
const raw = deps.principalInboxConsumer;
if (raw === undefined)
return { kind: "none" };
if (raw === "terminals")
return { kind: "terminals" };
if (raw === "assistant")
return { kind: "assistant" };
if (raw !== null && typeof raw === "object" && Reflect.ownKeys(raw).includes("assistant")) {
throw consumerRefusal(`RunnerDeps.principalInboxConsumer: { assistant: "<handle>" } is retired — the handle chose the leg by its task id, and a seat chooses it now. ` +
`Declare principalInboxConsumer: "assistant", and hand the assistant's leg RunInternals.principalInboxAssistant: { sessionId: <that leg's own session id> } on every leg you start for it (a resumed leg included); ` +
`do not carry the handle into the new form`, "malformed");
}
throw consumerRefusal(`RunnerDeps.principalInboxConsumer must be absent (no principal-inbox consumer), "terminals" (the scope's terminal sessions drain it beside their own box) or "assistant" (the leg the host hands RunInternals.principalInboxAssistant reads it) ` +
`(got ${describeRejectedValue(raw)}) — a malformed value is refused rather than read as "terminals", which would let terminal sessions take cross-principal letters past the assistant`, "malformed");
}
export function consumerRefusal(message, reason) {
const e = new Error(message);
e.code = PRINCIPAL_INBOX_CONSUMER_INVALID_CODE;
e.detail = { reason };
return e;
}
export const ORG_DELIVERY_REFUSAL_CODES = Object.freeze([
"org_delivery.not_member",
"org_delivery.rate_limited",
"org_delivery.inbox_full",
"org_delivery.recipient_tombstoned",
"org_delivery.receipt_id_reused",
]);
export function isOrgDeliveryRefusalCode(value) {
return typeof value === "string" && ORG_DELIVERY_REFUSAL_CODES.includes(value);
}
export function orgDeliveryRefusalOfAppendFailure(err) {
const code = err !== null && typeof err === "object" ? err.code : undefined;
if (code === MAILBOX_TOMBSTONED_RECIPIENT_CODE)
return "org_delivery.recipient_tombstoned";
if (code === MAILBOX_DUPLICATE_RECORD_ID_CODE)
return "org_delivery.receipt_id_reused";
return undefined;
}
export function mintCrossPrincipalRecord(input) {
const { from, body, receiptId, sentAt, consumer } = input;
if (consumer?.kind !== "terminals" && consumer?.kind !== "assistant") {
throw consumerRefusal(`an organization delivery gate is minting a principal-inbox letter, but the deployment declares no principal-inbox consumer (RunnerDeps.principalInboxConsumer is absent): nobody would ever read it. Declare "terminals" or "assistant".`, "no_consumer");
}
if (typeof body.content !== "string")
throw new TypeError("mintCrossPrincipalRecord: body.content must be a string");
if (!Number.isFinite(sentAt))
throw new TypeError("mintCrossPrincipalRecord: sentAt must be a finite epoch-ms number");
readReceiptId(receiptId);
const peerMeta = readMailboxPeerMeta({ kind: "peer_message", fromScope: from.scope, gateReceiptId: receiptId, ...(body.urgent === true ? { urgent: true } : {}) });
const name = typeof from.name === "string" && from.name !== "" ? from.name : undefined;
buildCrossSessionEnvelope({ from: encodePeerAddress(name ?? "unknown"), ...(name !== undefined ? { fromName: name } : {}), fromScope: from.scope }, body.content);
return { id: crossPrincipalRecordId(from.scope, receiptId), ...(name !== undefined ? { from: name } : {}), content: body.content, sentAt, peerMeta };
}
function readReceiptId(raw) {
if (!isMailboxNameSpelling(raw)) {
throw new MailboxStoreError(MAILBOX_INVALID_RECORD_ID_CODE, "mintCrossPrincipalRecord: receiptId must be a string with a non-blank character and no control character, no format character, and at most 256 characters");
}
return raw;
}
function crossPrincipalRecordId(fromScope, receiptId) {
return readMailboxRecordId(JSON.stringify([fromScope, receiptId]));
}
export function isGateMintedRecord(meta) {
return meta !== undefined && meta.kind === "peer_message" && meta.fromScope !== undefined && meta.gateReceiptId !== undefined;
}
export const PRINCIPAL_INBOX_TRIAGE_POLICIES = Object.freeze(["triage_readonly", "draft_for_approval", "decline"]);
export function principalInboxTriagePolicy(verdict) {
switch (verdict.verdict) {
case "deliver":
return "triage_readonly";
case "hold":
return "draft_for_approval";
case "refuse":
return "decline";
default: {
const _exhaustive = verdict;
void _exhaustive;
throw new Error(`unreachable verdict ${JSON.stringify(verdict)}`);
}
}
}
export function principalInboxLetterKey(recipientScope, letter) {
const parts = [["recipientScope", recipientScope], ["letter.fromScope", letter?.fromScope], ["letter.gateReceiptId", letter?.gateReceiptId]];
for (const [name, part] of parts)
if (typeof part !== "string" || part === "")
throw new TypeError(`principalInboxLetterKey: ${name} must be a non-empty string`);
return JSON.stringify([recipientScope, letter.fromScope, letter.gateReceiptId]);
}