UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

225 lines (224 loc) • 10 kB
import { userAttachmentOf } from "../../internal/llm.js"; import { isAbsoluteForFamily, pathFamilyOf, sha256 } from "../../tools/fs/safety.js"; import { entriesCarriedAcrossLegs } from "../../tools/fs/fs-shared.js"; import { normalizeFileText } from "../../tools/fs/encoding.js"; import { applyRecordedEdit, offloadedDetailOf } from "@sema-agent/primitives"; import { attachmentTransmissionId, isInstructionLaneEntry } from "../user-attachment.js"; import { fileArgPath } from "../tool-registry.js"; import { leadingSystemReminderOpen } from "../reminder-mint.js"; const READ_TOOL = "Read"; const WRITE_TOOL = "Write"; const EDIT_TOOL = "Edit"; const RETRACTING_RESULTS = [ { toolName: "NotebookEdit", type: "notebook-edit", pathField: "notebookPath" }, ]; function replayedEditContent(rest) { const originalFile = rest.originalFile; if (typeof originalFile !== "string" || offloadedDetailOf(originalFile) !== undefined) return undefined; const member = (v) => (typeof v === "string" && offloadedDetailOf(v) === undefined ? v : undefined); let edits; const rawEdits = rest.edits; if (Array.isArray(rawEdits) && rawEdits.length > 0) { const out = []; for (const e of rawEdits) { const r = e; const oldS = member(r?.oldString); const newS = member(r?.newString); if (oldS === undefined || newS === undefined) return undefined; out.push({ oldString: oldS, newString: newS, replaceAll: r.replaceAll === true }); } edits = out; } else { const oldS = member(rest.oldString); const newS = member(rest.newString); if (oldS === undefined || newS === undefined) return undefined; edits = [{ oldString: oldS, newString: newS, replaceAll: rest.replaceAll === true }]; } let working = originalFile; for (const e of edits) { if (e.oldString !== "" && !working.includes(e.oldString)) return undefined; working = applyRecordedEdit(working, e); } if (normalizeFileText(working) !== working) return undefined; return working; } function cardOf(details) { if (typeof details !== "object" || details === null) return undefined; const rest = details; return typeof rest.type === "string" ? { type: rest.type, rest } : undefined; } const CARDLESS_READ_NOTE = /^Warning: the file exists but (?:the contents are empty\.|is shorter than the provided offset \([0-9.e+]+\)\. The file has \d+ lines\.)<\/system-reminder>$/; function isCardlessRead(m) { if (m.details !== undefined) return false; const first = typeof m.content === "string" ? m.content : Array.isArray(m.content) ? m.content[0] : undefined; const text = typeof first === "string" ? first : typeof first === "object" && first !== null && first.type === "text" ? first.text : undefined; if (typeof text !== "string") return false; const open = leadingSystemReminderOpen(text); return open !== undefined && CARDLESS_READ_NOTE.test(text.slice(open.length)); } function noteCalls(m, into) { if (!Array.isArray(m.content)) return; const blocks = m.content, here = new Set(); for (const block of blocks) { if (typeof block !== "object" || block === null) continue; const b = block; if (b.type !== "toolCall" || typeof b.id !== "string" || here.has(b.id)) continue; here.add(b.id); into.set(b.id, { name: b.name, path: b.name === READ_TOOL ? fileArgPath(b.arguments) : undefined }); } } function wholeFileFromReadCard(rest) { const file = rest.file; if (typeof file !== "object" || file === null) return undefined; const f = file; if (typeof f.content !== "string" || f.truncatedByTokenCap === true) return undefined; if (f.startLine !== 1 || typeof f.numLines !== "number" || f.numLines !== f.totalLines) return undefined; return f.content; } function cutPageFromReadCard(rest) { const file = rest.file; if (typeof file !== "object" || file === null) return undefined; const f = file; if (f.truncatedByTokenCap !== true) return undefined; const { startLine, numLines, totalLines } = f; if (typeof startLine !== "number" || typeof numLines !== "number" || typeof totalLines !== "number") return undefined; const page = typeof f.content === "string" ? f.content : ""; return { hash: sha256(normalizeFileText(page)), totalLines, truncated: true, isPartialView: true, view: { start: startLine, end: startLine + numLines - 1 } }; } export function wholeFileRecordsFromTranscript(messages) { return readStateFromTranscript(messages).records; } export function readStateFromTranscript(messages) { const byPath = new Map(); const put = (path, rec) => { byPath.delete(path); byPath.set(path, rec); }; const seen = new Set(); let unplaced = false; const calls = new Map(); const saw = (path) => { if (typeof path !== "string") return; if (offloadedDetailOf(path) === undefined && isAbsoluteForFamily(pathFamilyOf({ root: path }), path)) seen.add(path); else unplaced = true; }; for (const m of messages) { const attachment = userAttachmentOf(m); if (attachment?.withdraws !== undefined) { const held = byPath.get(attachment.withdraws); if (held !== undefined && attachment.supply === "path" && "observation" in held && isInstructionLaneEntry(held.observation)) (byPath.delete(attachment.withdraws), seen.add(attachment.withdraws)); continue; } if (attachment?.observation !== undefined) { const { key, entry, stampedAt } = attachment.observation; const at = typeof stampedAt === "number" && Number.isFinite(stampedAt) ? stampedAt : m.timestamp; if (isAbsoluteForFamily(pathFamilyOf({ root: key }), key)) put(key, { path: key, observation: { ...entry, witnesses: [attachmentTransmissionId(attachment)] }, at }); continue; } if (m.role === "compactionSummary") { unplaced = true; continue; } if (m.role === "assistant") { noteCalls(m, calls); continue; } if (m.role !== "toolResult" || m.isError) continue; if (m.toolName === READ_TOOL && isCardlessRead(m)) { const call = calls.get(m.toolCallId); if (call?.name !== READ_TOOL || call.path === undefined) unplaced = true; else saw(call.path); continue; } const card = cardOf(m.details); if (card === undefined) continue; const { type, rest } = card; if (m.toolName === EDIT_TOOL && type === "edit") { const changed = rest.filePath; if (typeof changed !== "string") continue; saw(changed); const replayed = replayedEditContent(rest); if (replayed !== undefined && offloadedDetailOf(changed) === undefined && isAbsoluteForFamily(pathFamilyOf({ root: changed }), changed)) { put(changed, { path: changed, content: replayed, at: m.timestamp }); } else { byPath.delete(changed); } continue; } const retracts = RETRACTING_RESULTS.find((r) => r.toolName === m.toolName && r.type === type); if (retracts !== undefined) { const changed = rest[retracts.pathField]; saw(changed); if (typeof changed === "string") byPath.delete(changed); continue; } const isRead = m.toolName === READ_TOOL && type === "text"; const isWrite = (m.toolName === WRITE_TOOL && (type === "create" || type === "update")) || (m.toolName === EDIT_TOOL && type === "create"); const nested = rest.file; if (m.toolName === READ_TOOL && type === "notebook") { saw(typeof nested === "object" && nested !== null ? nested.filePath : undefined); continue; } if (!isRead && !isWrite) continue; const holder = isRead ? (typeof nested === "object" && nested !== null ? nested : undefined) : rest; const filePath = holder?.filePath; saw(filePath); if (typeof filePath !== "string" || offloadedDetailOf(filePath) !== undefined || !isAbsoluteForFamily(pathFamilyOf({ root: filePath }), filePath)) continue; const cut = isRead ? cutPageFromReadCard(rest) : undefined; if (cut !== undefined) { put(filePath, { path: filePath, observation: { ...cut, witnesses: [m.toolCallId] }, at: m.timestamp }); continue; } const content = isRead ? wholeFileFromReadCard(rest) : typeof rest.content === "string" ? rest.content : undefined; if (content === undefined) continue; if (offloadedDetailOf(content) !== undefined) continue; put(filePath, { path: filePath, content, at: m.timestamp, ...(isRead ? { transmittedByToolCallId: m.toolCallId } : {}) }); } return { records: [...byPath.values()], unentered: { paths: [...seen].filter((p) => !byPath.has(p)), unplaced } }; } export function legCarriedReads(input) { if (input.spec.compaction?.attachWorkingFiles === false) return false; const c = input.carrier; if (c.from === "checkpoint") return entriesCarriedAcrossLegs(input.resume?.seed.readFileState ?? []).length > 0; if (c.from === "seat") return entriesCarriedAcrossLegs(c.state).length > 0; if (c.from === "none") return false; return input.transcript === undefined ? undefined : wholeFileRecordsFromTranscript(input.transcript).length > 0; }