@sema-agent/core
Version:
Stateless, task-oriented AI agent core
137 lines (136 loc) • 6.95 kB
JavaScript
import { types } from "node:util";
import { readRowExpectation, sessionRowMatches } from "../../engine/session/repo-utils.js";
import { callerKey } from "../caller-text.js";
import { isPlainRecord } from "../mods/kernel/receive.js";
import { foreignLine } from "../protocol-http-auth.js";
import { readElements, readMember, thrownText } from "../thrown-value.js";
import { egressThrownText } from "../untrusted-egress.js";
export function readPlainRequest(request, keys, bad) {
if (typeof request !== "object" || request === null)
return bad(`the request must be a plain object, got ${request === null ? "null" : typeof request}`);
if (types.isProxy(request) || !isPlainRecord(request))
return bad("the request must be a plain data object (not a Proxy, and with no prototype that could supply a member)");
let descriptors;
try {
descriptors = Object.getOwnPropertyDescriptors(request);
}
catch {
return bad("the request could not be read");
}
const own = Reflect.ownKeys(descriptors);
const unknown = own.filter((k) => typeof k !== "string" || !keys.has(k));
if (unknown.length > 0)
return bad(`unknown key ${unknown.map((k) => callerKey(k)).join(", ")}`);
const read = {};
for (const k of own) {
const d = descriptors[k];
if (!("value" in d))
return bad(`member ${JSON.stringify(k)} is an accessor, not a value`);
read[k] = d.value;
}
return read;
}
export function shownValue(v) {
return typeof v === "string" ? JSON.stringify(v.slice(0, 40)) : v === null || typeof v === "boolean" || typeof v === "number" ? String(v) : `a ${typeof v}`;
}
export function claimIdleSession(seats, sessionId, busy) {
if (seats.sessionBusy(sessionId))
throw busy();
return seats.takeSessionLock(sessionId);
}
const EXPECT_KEYS = new Set(["row", "log"]);
const EXPECT_ROW_KEYS = new Set(["owner", "incarnation", "leafId"]);
const EXPECT_LOG_KEYS = new Set(["length", "lastEntryId"]);
export function readRowExpectationMember(raw, bad, refuse = {}) {
if (raw === undefined)
return undefined;
const fail = (what) => {
bad(what);
throw new TypeError(`readRowExpectationMember: bad must throw the caller's refusal, and it returned (refusing ${what})`);
};
const { row, log } = readPlainRequest(raw, EXPECT_KEYS, (what) => fail(`expect: ${what}`));
if (log !== undefined && refuse.log !== undefined)
return fail(refuse.log);
if (row === null && refuse.noRow !== undefined)
return fail(refuse.noRow);
const cells = row === null ? null : readPlainRequest(row, EXPECT_ROW_KEYS, (what) => fail(`expect.row: ${what}`));
const mark = log === undefined ? undefined : readPlainRequest(log, EXPECT_LOG_KEYS, (what) => fail(`expect.log: ${what}`));
let read;
try {
read = readRowExpectation({
row: cells === null ? null : { owner: cells.owner, incarnation: cells.incarnation },
...(mark !== undefined ? { log: { length: mark.length, lastEntryId: mark.lastEntryId } } : {}),
});
}
catch (err) {
return fail(`expect: ${thrownText(err)}`);
}
if (read.row === null && read.log !== undefined && read.log.length !== 0) {
return fail("expect.log: a log mark naming entries beside row null — a row that is not there holds none, so only the empty log's mark ({ length: 0, lastEntryId: null }) goes with row null; name the row and its log, or no row alone");
}
return read;
}
const OCCUPANT_ONLY = {
log: "expect.log is not taken here — this verb replaces no log; name the occupant only, expect: { row: { owner, incarnation } }",
noRow: "expect.row must be the session's row as a read answered it ({ owner, incarnation }) — null names no session, and this verb's session must exist",
};
export function readOccupantExpectation(raw, bad) {
const read = readRowExpectationMember(raw, bad, OCCUPANT_ONLY);
return read === undefined ? undefined : { row: read.row };
}
export async function acquireExistingSession(sessions, sessionId, verb, nothingDone, expect) {
const notFound = (what) => {
const e = new Error(`${verb}: session "${sessionId}" ${what} — ${nothingDone}`);
e.code = "resume.session_not_found";
return e;
};
let acquired;
try {
acquired = await sessions.acquire(sessionId, { requireExisting: true });
}
catch (err) {
if (readMember(err, "code") !== "not_found")
throw err;
throw notFound("does not exist");
}
if (expect !== undefined && !sessionRowMatches(expect, await acquired.session.getMetadata(), occupantBindsNoLog)) {
throw notFound("is not the session the request expected (its owner or occupant is not the row named in expect: deleted and created again, or another owner's)");
}
return acquired;
}
function occupantBindsNoLog() {
throw new TypeError("an occupant expectation binds no log");
}
export async function refuseParkedSession(store, sessionId, whose, words) {
if (store === undefined)
return;
const parked = (why, cause) => {
const e = new Error(`${words.verb}: ${why} — ${words.undone}`, cause !== undefined ? { cause } : undefined);
e.code = words.code;
throw e;
};
if (typeof store.listBySession !== "function")
return parked(`${whose} checkpoint store has no listBySession, so it cannot say whether session "${sessionId}" is parked at a checkpoint`);
let answer;
try {
answer = await store.listBySession({ sessionId, status: "pending", limit: 1 });
}
catch (err) {
return parked(`${whose} checkpoint store could not say whether session "${sessionId}" is parked at a checkpoint (listBySession failed: ${egressThrownText("same-principal", err)})`, err);
}
const unanswered = (what) => parked(`${whose} checkpoint store answered ${what}, so it cannot say whether session "${sessionId}" is parked at a checkpoint`, new Error(`listBySession answered ${what}`));
const rows = readElements(readMember(answer, "rows"));
if (rows === undefined)
return unanswered("without a list of rows");
if (rows.length === 0)
return;
const row = rows[0];
const kind = readMember(row, "kind");
const checkpoint = kind === "row" ? readMember(row, "checkpoint") : undefined;
const token = kind === "row" ? readMember(checkpoint, "token") : kind === "unreadable" ? readMember(row, "token") : undefined;
if (typeof token !== "string" || token === "")
return unanswered("a first row that is no checkpoint row with a token");
const id = readMember(checkpoint, "checkpointId");
const named = typeof id === "string" && id.trim() !== "" ? `checkpoint "${foreignLine(id, 64)}"` : "a checkpoint";
return parked(`session "${sessionId}" is parked at ${named}, which is pending`);
}