@sema-agent/core
Version:
Stateless, task-oriented AI agent core
74 lines (73 loc) • 2.98 kB
JavaScript
import { canonicalize, REGISTRY_SHAPE_DERIVES_PATHS, scopeDirFor, scopeRegistryShape } from "./layout.js";
import { sessionAccountWriteHome } from "./delegation-settlement.js";
function rankNewer(a, b) {
return a >= b ? (a > b ? 1 : 0) : -1;
}
export async function sessionWriteHomeOf(input) {
const { memoryDir, controlDir, sessionId, contributions } = input;
try {
if (!REGISTRY_SHAPE_DERIVES_PATHS[scopeRegistryShape(controlDir)])
return { state: "unreadable" };
if (contributions === undefined)
return { state: "unreadable" };
let newest;
for (const [id, at] of contributions) {
if (newest === undefined || at > newest.at || (at === newest.at && id > newest.id))
newest = { id, at };
}
const account = await sessionAccountWriteHome(input.docs, sessionId);
const sources = [];
const fromAccount = async () => (account === undefined ? undefined : { scope: account.writeScope, at: account.openedAt });
const fromNewest = async () => {
if (newest === undefined)
return undefined;
const scope = (await input.readEntries([newest.id])).find((e) => e.id === newest.id)?.scope;
return scope === undefined ? undefined : { scope, at: newest.at };
};
if (account !== undefined && (newest === undefined || rankNewer(account.openedAt, newest.at) >= 0))
sources.push(fromAccount, fromNewest);
else
sources.push(fromNewest, fromAccount);
let named;
for (const source of sources) {
named = await source();
if (named !== undefined)
break;
}
return named === undefined ? { state: "none" } : { state: "named", home: canonicalize(scopeDirFor(memoryDir, controlDir, named.scope)), at: named.at };
}
catch {
return { state: "unreadable" };
}
}
function readingOf(reading) {
if (typeof reading !== "object" || reading === null)
return { state: "unreadable" };
const r = reading;
if (r.state === "none")
return { state: "none" };
if (r.state === "named" && typeof r.home === "string" && r.home.trim() !== "" && typeof r.at === "number" && Number.isFinite(r.at)) {
return { state: "named", home: r.home, at: r.at };
}
return { state: "unreadable" };
}
export function chooseSessionWriteHome(readings) {
let best;
let tied = false;
for (const given of readings) {
const r = readingOf(given);
if (r.state === "unreadable")
return undefined;
if (r.state !== "named")
continue;
const rank = best === undefined ? 1 : rankNewer(r.at, best.at);
if (rank === 1) {
best = r;
tied = false;
}
else if (rank === 0) {
tied = true;
}
}
return best === undefined || tied ? undefined : best.home;
}