@sema-agent/core
Version:
Stateless, task-oriented AI agent core
126 lines (125 loc) • 6.46 kB
JavaScript
export { StoredSession } from "../internal/harness.js";
export { InMemorySessionRepo, InMemorySessionStorage, uuidv7, validateEntriesForImport, StreamingImportValidator, } from "../internal/harness.js";
export { BaseSessionStorage, leafIdAfterEntry, } from "../internal/harness.js";
export { SessionError } from "../internal/harness.js";
export { CORRUPT_SESSION_DELETE_DOORS, CORRUPT_SESSION_FORMS, CORRUPT_SESSION_WAYS, CORRUPT_SESSION_WAYS_OUT, corruptSessionWayOutSentence, isCorruptSessionForm } from "../internal/harness.js";
import { SessionError, isCorruptSessionForm } from "../internal/harness.js";
import { readMember, thrownIs } from "./thrown-value.js";
import { callerKey } from "./caller-text.js";
import { receiptRefusal, receiveOwnProperties } from "./own-property-receipt.js";
import { PRINCIPAL_NAME_SPELLING, principalNameFault, principalNameOf } from "./principal-name.js";
export function isSessionConflict(err) {
return thrownIs(err, SessionError) && readMember(err, "code") === "conflict";
}
export function isRowUnreadable(err) {
return thrownIs(err, SessionError) && readMember(err, "code") === "corrupt_session";
}
export function corruptSessionFormOf(err) {
if (!thrownIs(err, SessionError) || readMember(err, "code") !== "corrupt_session")
return undefined;
const form = readMember(readMember(err, "detail"), "form");
return isCorruptSessionForm(form) ? form : undefined;
}
function unreadableOrRethrow(err) {
if (isRowUnreadable(err))
return true;
throw err;
}
export function rowUnreadableNow(readHead) {
try {
readHead();
}
catch (err) {
return unreadableOrRethrow(err);
}
return false;
}
export async function rowUnreadableAt(readHead) {
try {
await readHead();
}
catch (err) {
return unreadableOrRethrow(err);
}
return false;
}
export function readUnreadableDeleteId(face, sessionId) {
if (typeof sessionId !== "string" || sessionId === "")
throw receiptRefusal(`${face}: the session id must be a non-empty string, got ${sessionId === "" ? "an empty string" : typeof sessionId}`);
return sessionId;
}
export const SESSION_LIST_LIMITS = Object.freeze({ default: 50, max: 1000 });
const LIST_QUERY_MEMBERS = ["owner", "includeUnowned", "after", "limit"];
export function readSessionListQuery(raw, extensions = []) {
if (raw === undefined)
return { includeUnowned: false, limit: SESSION_LIST_LIMITS.default, extensions: {} };
if (typeof raw !== "object" || raw === null)
throw receiptRefusal(`SessionStore.list: the query must be an object, got ${raw === null ? "null" : typeof raw}`);
const got = receiveOwnProperties(raw, { subject: "SessionListQuery", unit: "member", moment: "at SessionStore.list" });
const extended = {};
for (const name of Object.keys(got)) {
if (LIST_QUERY_MEMBERS.includes(name))
continue;
if (!extensions.includes(name))
throw receiptRefusal(`SessionStore.list: this store does not filter by ${callerKey(name)} — refused rather than listing the rows that filter would exclude`);
extended[name] = got[name];
}
const { owner: ownerGiven, includeUnowned, after, limit } = got;
const owner = ownerGiven === undefined ? undefined : principalNameOf(ownerGiven);
if (ownerGiven !== undefined && owner === undefined) {
throw receiptRefusal(`SessionListQuery.owner must be a principal name (${PRINCIPAL_NAME_SPELLING}) when present, got ${principalNameFault(ownerGiven)}`);
}
if (includeUnowned !== undefined && typeof includeUnowned !== "boolean")
throw receiptRefusal(`SessionListQuery.includeUnowned must be a boolean when present, got ${typeof includeUnowned}`);
if (includeUnowned !== undefined && owner === undefined)
throw receiptRefusal("SessionListQuery.includeUnowned is a member of the owner filter and was given without owner — refused rather than read as every owner's list");
if (limit !== undefined && !(typeof limit === "number" && Number.isSafeInteger(limit) && limit >= 1 && limit <= SESSION_LIST_LIMITS.max)) {
throw receiptRefusal(`SessionListQuery.limit must be an integer in 1..${SESSION_LIST_LIMITS.max} when present`);
}
return {
...(owner !== undefined ? { owner } : {}),
includeUnowned: includeUnowned === true,
...(after !== undefined ? { after: readListCursor(after) } : {}),
limit: limit ?? SESSION_LIST_LIMITS.default,
extensions: extended,
};
}
function readListCursor(raw) {
if (typeof raw !== "object" || raw === null)
throw receiptRefusal(`SessionListQuery.after must be an object when present, got ${raw === null ? "null" : typeof raw}`);
const got = receiveOwnProperties(raw, { subject: "SessionListQuery.after", unit: "member", moment: "at SessionStore.list" });
for (const name of Object.keys(got)) {
if (name !== "lastActiveAt" && name !== "sessionId")
throw receiptRefusal(`SessionListQuery.after carries ${callerKey(name)} — a cursor is a lastActiveAt and a sessionId`);
}
const { lastActiveAt, sessionId } = got;
if (typeof lastActiveAt !== "number" || !Number.isFinite(lastActiveAt))
throw receiptRefusal("SessionListQuery.after.lastActiveAt must be a finite number");
if (typeof sessionId !== "string")
throw receiptRefusal(`SessionListQuery.after.sessionId must be a string, got ${typeof sessionId}`);
return { lastActiveAt, sessionId };
}
export function hasSessionFork(store) {
return typeof store.fork === "function";
}
export function declaresSubagentPlacement(store) {
return store.placements?.subagent !== undefined;
}
export function boundedTail(pathEntries) {
let lastCompaction;
for (const e of pathEntries) {
if (e.type === "compaction")
lastCompaction = e;
}
if (!lastCompaction)
return { tail: [...pathEntries], floorEntryId: null };
const floorEntryId = lastCompaction.firstKeptEntryId;
const floorIdx = pathEntries.findIndex((e) => e.id === floorEntryId);
if (floorIdx < 0) {
return { tail: [...pathEntries], floorEntryId: null };
}
return { tail: pathEntries.slice(floorIdx), floorEntryId };
}
export function hasConversationContent(branch) {
return branch.some((e) => e.type === "message" || e.type === "custom_message" || e.type === "compaction");
}