UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

173 lines (172 loc) • 9.3 kB
import { PROBE_CAUSE_PATH_MAX, PROBE_REASON_MAX, inlineUntrusted } from "./untrusted-text.js"; export function isPlainRecord(x) { try { if (x === null || typeof x !== "object" || Array.isArray(x)) return false; const p = Object.getPrototypeOf(x); return p === Object.prototype || p === null; } catch { return false; } } export function safeDataValue(obj, key) { try { const d = Object.getOwnPropertyDescriptor(obj, key); return d && "value" in d ? d.value : undefined; } catch { return undefined; } } const PROBE_CAUSE_MAX_SHOWN = 8; export function copiedRiskAxes(given) { if (!isPlainRecord(given)) return {}; const irreversible = safeDataValue(given, "irreversible"); const egress = safeDataValue(given, "egress"); const copy = { ...(typeof irreversible === "boolean" ? { irreversible } : {}), ...(typeof egress === "boolean" ? { egress } : {}), }; return Object.keys(copy).length > 0 ? { riskAxes: copy } : {}; } export function normalizeProbeCause(value) { if (!isPlainRecord(value)) return undefined; const code = safeDataValue(value, "code"); if (typeof code !== "string" || code.trim().length === 0) return undefined; const family = (raw) => { if (!isPlainRecord(raw)) return undefined; const shownRaw = safeDataValue(raw, "shown"); if (!Array.isArray(shownRaw)) return undefined; const shown = shownRaw .filter((p) => typeof p === "string") .slice(0, PROBE_CAUSE_MAX_SHOWN) .map((p) => inlineUntrusted(p, PROBE_CAUSE_PATH_MAX)); const totalRaw = safeDataValue(raw, "total"); const total = typeof totalRaw === "number" && Number.isFinite(totalRaw) ? Math.max(0, Math.floor(totalRaw)) : shown.length; return { shown, total: Math.max(total, shown.length) }; }; const roots = family(safeDataValue(value, "roots")); if (roots === undefined) return undefined; const further = family(safeDataValue(value, "further")); return { code: inlineUntrusted(code, PROBE_REASON_MAX), roots, ...(further !== undefined && further.total > 0 ? { further } : {}), }; } export const CHECKPOINT_FEATURES = { resource: { introduced: "design/74", writes: "resourceLedger; gate/pendingAction kind resource_limit" }, binding: { introduced: "design/80", writes: "pendingAction.boundCallId + boundInputHash on a tool_approval; a plan_review carries no binding" }, token: { introduced: "design/164", writes: "resourceLedger.totalTokens" }, orgAdmission: { introduced: "org-admission", writes: "inheritedGate.admittedOrgScopes / ownAdmittedOrgScopes / ownAdmittedOrgWriteScope / orgAdmissionGoverned" }, f012: { introduced: "F-012", writes: "inheritedGate.constraintChain + constraintDigest together; delegationProvenance" }, realApproval: { introduced: "#130/#120", writes: "gate.realApproval (a well-formed bit) + pendingAction.requiresRealApproval; readFace.realApproval = true beside it" }, face: { introduced: "design/199", writes: "state.readFace { face, denyEntries? } for a non-default posture; realApproval: true only at the mint whose gate carries the bit (a hands-less re-park never carries the seed's marker forward)" }, requirements: { introduced: "#1320", writes: "requires (the row's words) + requirementsDigest (the row digest), both derived from its content (checkpoint-requirements.ts)" }, }; export const MAX_SUPPORTED_CHECKPOINT_VERSION = 10; export function checkpointVersionOf(cp) { return cp.version ?? 0; } export const CHECKPOINT_CONFIG_REFUSAL_CODES = Object.freeze(["config.spec_retired_key", "config.output_style_invalid", "config.language_invalid", "config.permission_mode_invalid", "config.shell_gate_value_retired", "config.approval_reach_invalid", "config.run_origin_invalid", "config.user_invoked_skill_unknown", "config.skill_deny_unreadable", "config.user_attachment_invalid", "config.tool_face_control", "config.deps_retired_key", "config.peer_presence_invalid", "config.tool_model_gate_invalid", "config.microcompact_invalid", "config.prompt_selector_invalid", "resume_at.conflicts_resume", "resume_at.mode_without_target", "config.read_face_invalid", "config.write_face_invalid", "config.invalid_argument", "config.tool_face_invalid", "config.memory_delegation_evidence", "config.memory_provenance", "config.memory_capture_policy", "config.cross_boundary_posture", "config.advisor_tool_invalid", "config.advisor_model_invalid", "config.auto_consolidation", "config.unknown_role", "config.tool_materialize_invalid", "config.memory_persistence_invalid", "config.tool_materialize_unreachable", "config.locked_registry", "config.locked_key", "config.mcp_content_class", "config.skill_listing_budget_invalid", "config.limit_unknown_key", "config.limit_invalid", "config.attachment_invalid", "config.usage_window_invalid", "config.brain_call_guardrail_invalid", "config.retention_policy", "config.retention_capability", "config.invalid_checkpoint_store", "config.invalid_session_store", "config.skill_base_dir_invalid", "config.host_floor_invalid", "config.credential_in_declaration", "config.credential_ref_invalid", "config.peer_seat_missing", "config.interaction_posture", "config.agents.no_delegation_tool", "config.spec_member_unreadable", "config.spec_unknown_key", "config.agent_config_dir_invalid", "config.agent_home_dir_invalid", "config.project_id_invalid"]); export const isCheckpointConfigRefusalCode = (word) => CHECKPOINT_CONFIG_REFUSAL_CODES.some((w) => w === word); export const CHECKPOINT_ERROR_CODES = Object.freeze([ "checkpoint.already_exists", "checkpoint.already_resolved", "checkpoint.not_found", "checkpoint.gate_mismatch", "checkpoint.resume_aborted", "checkpoint.invalid_outcome", "checkpoint.unsupported_version", "checkpoint.config_refused", "checkpoint.cwd_conflicts_restore", "checkpoint.walltime_axis_retired", "checkpoint.reopen_revote", "checkpoint.reopened_concurrently", "checkpoint.reopen_failed", "checkpoint.void_unpin_failed", "checkpoint.execution_outcome_conflict", "steering.invalid_content", "steering.queue_full", "steering.duplicate_input_id", "steering.blocked_by_hook", "wake.gate_pending", "wake.nothing_to_deliver", "resume.parent_constraint_missing", "resume.parent_constraint_mismatch", "resume.parent_constraint_unrebuildable", "resume.usage_window_exhausted", "resume.principal_mismatch", "resume.isolation_scope_mismatch", "resume.placement_mismatch", "resume.composition_mismatch", "resume.agent_definition_mismatch", "resume.preflight_rejected", "resume.constraint_rejected", "resume.constraint_unprojectable", ]); export const isCheckpointErrorCode = (word) => CHECKPOINT_ERROR_CODES.some((w) => w === word); export const SPAWN_RESUME_REFUSAL_CODES = Object.freeze(["steering.still_running", "resume.retain_off", "resume.evicted", "resume.session_not_found", "resume.row_recycling", "resume.row_gone"]); export class CheckpointError extends Error { code; detail; constructor(code, message, detail) { super(message); this.code = code; this.detail = detail; this.name = "CheckpointError"; } } export function copyOfCheckpointError(refusal, reason) { const guarded = (read) => { try { return { ok: true, value: read() }; } catch { return { ok: false }; } }; const message = guarded(() => refusal.message); const members = guarded(() => { const d = refusal.detail; return typeof d === "object" && d !== null ? Object.keys(d).map((k) => [k, guarded(() => d[k])]) : []; }); const kept = members.ok ? members.value.flatMap(([k, v]) => (v.ok && v.value !== undefined ? [[k, v.value]] : [])) : []; const detail = Object.fromEntries([...kept.filter(([k]) => reason === undefined || k !== "reason"), ...(reason !== undefined ? [["reason", reason]] : [])]); const cause = guarded(() => ("cause" in refusal ? { value: refusal.cause } : undefined)); const made = copy(new RefusalReading(refusal.code, message.ok && typeof message.value === "string" ? message.value : "", Object.keys(detail ?? {}).length > 0 ? detail : undefined)); if (cause.ok && cause.value !== undefined) Object.defineProperty(made, "cause", { value: cause.value.value, writable: true, configurable: true, enumerable: false }); return made; function copy(p) { return new CheckpointError(p.code, p.message, p.detail); } } class RefusalReading { code; message; detail; constructor(code, message, detail) { this.code = code; this.message = message; this.detail = detail; } } export function encodeAtFidelity(fidelity, value) { if (fidelity === "structured-clone") return { ok: true, value }; try { const encoded = JSON.stringify(value); return { ok: true, value: encoded === undefined ? undefined : JSON.parse(encoded) }; } catch (err) { return { ok: false, cause: err }; } }