UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

182 lines (181 loc) • 8.97 kB
import { parseScopeKey } from "./memory-engine/scope-contract.js"; import { attrEscape } from "./task-notification.js"; import { sanitizeUntrustedText, ENGINE_AUTHORITY_ENVELOPE_TAGS } from "./untrusted-text.js"; import { describeRejectedValue } from "./tool-search-setting.js"; import { CREDENTIAL_VOCABULARY, scanSecrets } from "@sema-agent/primitives"; const REFUSE_WRITE_POLICY = Object.freeze({ grade: "strict", readings: Object.freeze([Object.freeze({ kind: "raw" })]), urlUserinfo: "keep-username", onUnresolvedReading: "secret", }); const refuseLabel = (id) => id.replaceAll("-", "_"); export function detectSecret(text) { if (!text) return null; const { spans } = scanSecrets(text, REFUSE_WRITE_POLICY); const found = new Set(spans.map((s) => s.family)); for (const row of CREDENTIAL_VOCABULARY.values) if (row.strict !== undefined && found.has(row.id)) return refuseLabel(row.id); return spans.length === 0 ? null : refuseLabel(spans[0].family); } export function firstSentence(text) { const t = text.trim().replace(/\s+/g, " "); const dot = t.search(/[.!?](\s|$)/); const cut = dot >= 0 && dot < 160 ? dot + 1 : Math.min(t.length, 120); return t.slice(0, cut).trim(); } export const MEMORY_PROJECT_KEY_ABSENT_REASONS = Object.freeze(["not_git", "bare", "unreadable"]); export function normalizeMemorySpec(input) { if (!input) return undefined; if (Object.prototype.hasOwnProperty.call(input, "scope")) { const e = new Error("TaskSpec.memory: the singular `scope` field was removed — write `scopes: [\"<scope>\"]` instead " + "(an ordered read layering; `writeScope` defaults to its last entry). Refusing to start with memory silently off."); e.code = "config.memory_scope_spelling"; throw e; } if (input.capture !== undefined && input.capture !== "off") { const rawCapture = input.capture; const e = new Error(`TaskSpec.memory.capture must be exactly "off" when present (got ${describeRejectedValue(rawCapture)}) — the capture opt-out is a ` + `single-member closed set (absence = capture as usual; there is no "on" spelling). Refusing to guess ` + `which way a privacy switch was meant.`); e.code = "config.memory_capture_spelling"; throw e; } const projectKey = readProjectKey(input); const raw = input.scopes ?? []; const scopes = []; const seen = new Set(); for (const s of raw) { const t = typeof s === "string" ? s.trim() : ""; if (!t || seen.has(t)) continue; seen.add(t); scopes.push(t); } if (scopes.length === 0) return undefined; let writeScope; if (input.writeScope === null) { writeScope = null; } else if (typeof input.writeScope === "string" && input.writeScope.trim()) { writeScope = input.writeScope.trim(); } else { writeScope = scopes[scopes.length - 1]; } const trustedTools = []; const trustedSeen = new Set(); for (const t of input.trustedTools ?? []) { const name = typeof t === "string" ? t.trim() : ""; if (!name || trustedSeen.has(name)) continue; trustedSeen.add(name); trustedTools.push(name); } const contentSafety = { ...(trustedTools.length > 0 ? { trustedTools } : {}), ...(input.execIsExternalContent === true ? { execIsExternalContent: true } : {}), }; const origins = input.scopeOrigins !== undefined ? { scopeOrigins: input.scopeOrigins } : {}; if (projectKey?.scope !== undefined && writeScope !== null && writeScope !== projectKey.scope) { const e = new Error(`TaskSpec.memory.projectKey declares project scope ${JSON.stringify(projectKey.scope)} while writeScope is ${JSON.stringify(writeScope)} — ` + `every entry this session writes would land in ${JSON.stringify(writeScope)} instead of the project's own layer. ` + `Pin writeScope to the project scope (or drop projectKey if the layering is deliberate). Refusing to start mis-addressed.`); e.code = "config.memory_write_scope_mismatch"; throw e; } const capture = input.capture === "off" ? { capture: "off" } : {}; const project = projectKey !== undefined ? { projectKey } : {}; if (input.scopeContract === "v2") { for (const key of writeScope !== null ? [...scopes, writeScope] : scopes) parseScopeKey(key); return { scopes, writeScope, enabled: input.enabled !== false, scopeContract: "v2", ...contentSafety, ...origins, ...capture, ...project }; } return { scopes, writeScope, enabled: input.enabled !== false, ...contentSafety, ...origins, ...capture, ...project }; } export function memoryEngineOpens(memorySpec, deps) { return Boolean(memorySpec && memorySpec.enabled && deps.memoryBackend); } function readProjectKey(input) { const raw = input.projectKey; if (raw === undefined) return undefined; const refuse = (why) => { const e = new Error(`TaskSpec.memory.projectKey must be exactly { scope: "<non-empty>" } or { absent: ${MEMORY_PROJECT_KEY_ABSENT_REASONS.map((r) => JSON.stringify(r)).join(" | ")} } — ${why}. ` + `Refusing to guess whether this deployment has a project identity.`); e.code = "config.memory_project_key_spelling"; throw e; }; if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return refuse(`got ${raw === null ? "null" : Array.isArray(raw) ? "an array" : typeof raw}`); const scope = raw.scope; const absent = raw.absent; if ((scope === undefined) === (absent === undefined)) return refuse(absent === undefined ? "neither arm was spelled" : "both arms were spelled"); if (absent !== undefined) { if (typeof absent !== "string" || !MEMORY_PROJECT_KEY_ABSENT_REASONS.includes(absent)) { return refuse(`the absence reason ${typeof absent === "string" ? JSON.stringify(absent.slice(0, 64)) : typeof absent} is not one of the stated words`); } return { absent: absent }; } if (typeof scope !== "string" || scope.trim() === "") return refuse(typeof scope === "string" ? "the project scope is blank" : `the project scope is ${typeof scope}`); return { scope: scope.trim() }; } export function memoryProjectScopeAbsentNotice(input) { return { code: "memory.project_scope_absent", message: `No project identity was derived for this session's working root (${input.reason}), so its memory layering is used as declared: ` + `${input.writeScope === null ? "the session writes nothing (read-only layering)" : `entries this session writes go to the shared layer ${JSON.stringify(input.writeScope)}`}. ` + `If this root should have its own project memory, fix how the deployment resolves it — nothing here retries.`, detail: { reason: input.reason, taskRoot: input.taskRoot, sessionId: input.sessionId, ...(input.writeScope !== null ? { writeScope: input.writeScope } : {}) }, }; } export const MAX_MEMORY_BYTES = 100 * 1024; export const MEMORY_WRAPPER_TAGS = ["user_memory"]; export const MEMORY_INJECTION_TAGS = [...ENGINE_AUTHORITY_ENVELOPE_TAGS]; export function composeMemoryBlock(content, scope) { const trimmed = (content ?? "").trim(); if (!trimmed) { return undefined; } let payload = trimmed; const bytes = Buffer.byteLength(trimmed, "utf8"); if (bytes > MAX_MEMORY_BYTES) { const buf = Buffer.from(trimmed, "utf8"); let cut = MAX_MEMORY_BYTES; while (cut > 0 && (buf[cut] & 0xc0) === 0x80) { cut--; } const head = buf.subarray(0, cut).toString("utf8"); payload = `${head}\n<truncated bytes=${bytes - cut}>`; } return `<user_memory scope="${attrEscape(scope)}">\n${sanitizeUntrustedText(payload, [...MEMORY_INJECTION_TAGS])}\n</user_memory>`; } export function composeLayeredMemoryBlock(layers) { const sections = []; for (const layer of layers) { const trimmed = (layer.content ?? "").trim(); if (!trimmed) continue; let payload = trimmed; const bytes = Buffer.byteLength(trimmed, "utf8"); if (bytes > MAX_MEMORY_BYTES) { const buf = Buffer.from(trimmed, "utf8"); let cut = MAX_MEMORY_BYTES; while (cut > 0 && (buf[cut] & 0xc0) === 0x80) cut--; payload = `${buf.subarray(0, cut).toString("utf8")}\n<truncated bytes=${bytes - cut}>`; } sections.push(`<scope name="${attrEscape(layer.scope)}">\n` + `${sanitizeUntrustedText(payload, [...MEMORY_INJECTION_TAGS])}\n` + `</scope>`); } if (sections.length === 0) return undefined; return `<user_memory>\n${sections.join("\n")}\n</user_memory>`; }