@sema-agent/core
Version:
Stateless, task-oriented AI agent core
37 lines (36 loc) • 1.29 kB
JavaScript
import { randomBytes } from "node:crypto";
export const PROMPT_HASH_SALT_CUSTOM_TYPE = "engine:prompt-hash-salt";
const SALT_SHAPE = /^[0-9a-f]{32}$/;
export function storedPromptHashSalt(branch) {
for (let i = branch.length - 1; i >= 0; i--) {
const e = branch[i];
if (e.type !== "custom" || e.customType !== PROMPT_HASH_SALT_CUSTOM_TYPE)
continue;
const v = e.data?.salt;
if (typeof v === "string" && SALT_SHAPE.test(v))
return Uint8Array.from(Buffer.from(v, "hex"));
}
return undefined;
}
export async function resolvePromptHashSalt(session, onFailure) {
let branch;
try {
branch = await session.getBranch();
}
catch (error) {
onFailure(error, "read");
return { salt: Uint8Array.from(randomBytes(16)), scope: "leg" };
}
const stored = storedPromptHashSalt(branch);
if (stored !== undefined)
return { salt: stored, scope: "session" };
const salt = Uint8Array.from(randomBytes(16));
try {
await session.appendCustomEntry(PROMPT_HASH_SALT_CUSTOM_TYPE, { salt: Buffer.from(salt).toString("hex") });
return { salt, scope: "session" };
}
catch (error) {
onFailure(error, "write");
return { salt, scope: "leg" };
}
}