UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

59 lines (58 loc) • 2.87 kB
import { leafIdAfterEntry } from "../../internal/harness.js"; import { userAttachmentOf } from "../../internal/llm.js"; import { isPersonsWordsRow } from "../user-row-origin.js"; export function rewindTargetNamed(target, asker) { return asker === "resumeAt" ? `resumeAt entry "${target}"` : `Runner.rewindConversation: entry "${target}" (to)`; } export function beforeTakes(entry) { return beforeRefusalOf(entry) === undefined; } export async function judgeRewindTarget(read, target, mode, sessionId, asker) { const named = rewindTargetNamed(target, asker); const refusal = (sentence) => new Error(`${named} ${sentence}`); const entry = await read.getEntry(target); if (!entry) { const e = refusal(`not found in session "${sessionId}"`); e.code = "resume_at.not_found"; throw e; } const startId = leafIdAfterEntry(entry); if (startId === null) { const e = refusal(`is a leaf move to the empty branch: it names no conversation a run could continue from — name another entry of session "${sessionId}"`); e.code = "resume_at.empty_branch"; throw e; } const start = startId === entry.id ? entry : await read.getEntry(startId); if (start === undefined) { const e = refusal(`is a leaf move to entry "${startId}", which session "${sessionId}" does not hold`); e.code = "resume_at.not_found"; throw e; } if (mode === "at") return { mode, entry, start }; const notBefore = beforeRefusalOf(entry); if (notBefore === "resume_at.before_target_not_user") { const e = refusal(`is ${kindOf(entry)}, not a person's words; ${asker === "resumeAt" ? `resumeAtMode "before"` : "a rewind of the conversation"} lands before the person's words that opened a turn`); e.code = "resume_at.before_target_not_user"; throw e; } if (notBefore === "resume_at.before_root_unsupported") { const e = refusal(`is the root of session "${sessionId}"'s log (it has no parent), so there is nothing before it to land on — start a new session instead`); e.code = "resume_at.before_root_unsupported"; throw e; } return { mode, entry, landing: entry.parentId }; } function beforeRefusalOf(entry) { if (entry.type !== "message" || !isPersonsWordsRow(entry.message)) return "resume_at.before_target_not_user"; return entry.parentId === null ? "resume_at.before_root_unsupported" : undefined; } function kindOf(entry) { if (entry.type !== "message") return `a "${entry.type}" entry`; const msg = entry.message; if (msg.role !== "user") return `a role "${String(msg.role)}" message`; return userAttachmentOf(msg) !== undefined ? "an attachment frame (a file the engine delivered with a person's input)" : `the engine's own line (${String(msg.origin)})`; }