UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

273 lines (272 loc) • 20.5 kB
import { bindPeerLaneDrain } from "../../agents/peer-session-drain.js"; import { teamRoleOf } from "../../agents/team-role.js"; import { resolveCheckpointStore } from "../checkpoint-store.js"; import { createHookEnvCapabilities, mintHookInvocationIdentity } from "../hooks.js"; import { wiredHookEntries } from "../hook-seats.js"; import { isRemoteExecutionEnv, missingRestoreSurface } from "../remote-env.js"; import { isVolatileOffloadStore } from "../tool-result-store.js"; import { durableMandateSourceOf, isLiveApproverSeat } from "../tool-policy.js"; import { deliverEngineNotice } from "../types.js"; import { inlineUntrusted } from "../untrusted-text.js"; import { mountWriteProtection } from "./write-protection-station.js"; import { autoRunOnRecommendationEffective } from "./memory-consolidation-driver.js"; import { GLOBAL_USAGE_KEY, usageRetryAfterMs, windowsGovernCost } from "../usage-window-store.js"; import { LSP_CONTRACT_ID, askSeatEffective, countElicitOptIns, deriveHandsSeam, deriveLspSeam, deriveWiringManifest, resolveAskSeamForm, resolveDeclaredDurability, resolveElicitSeam, resolveQuestionSeam, resolveSubagentTranscriptTier } from "../wiring-manifest.js"; import { modePolicyOf } from "../mode-policy.js"; import { DEFAULT_IRREVERSIBLE_SCOPE } from "./checkpoint-scope.js"; export function mcpManifestEntries(entries, statuses) { return (entries ?? []).map((entry) => { const status = statuses.find((s) => s.name === entry.name); const source = typeof entry.source === "string" && entry.source.length > 0 ? { source: inlineUntrusted(entry.source, 80) } : {}; const liveness = status?.liveness !== undefined ? { liveness: { ...status.liveness } } : {}; if (status === undefined) return { name: entry.name, ...source, status: "skipped", toolCount: 0 }; if (status.status === "connected") return { name: entry.name, ...source, status: "connected", toolCount: status.toolNames?.length ?? 0, ...liveness }; return { name: entry.name, ...source, status: "failed", ...liveness, ...(status.errorCode !== undefined ? { errorCode: status.errorCode, delivered: status.delivered, ...(status.httpStatus !== undefined ? { httpStatus: status.httpStatus } : {}) } : {}), ...(status.error !== undefined ? { error: inlineUntrusted(status.error, 240) } : {}), toolCount: 0, }; }); } function buildUsageGovernance(windows, deps, principal, sessionId) { if (windows === undefined || windows.length === 0) return undefined; const store = deps.usageWindowStore; if (store === undefined) { deps.onError?.(new Error("RunnerDeps.usageWindows is set but INACTIVE: no `usageWindowStore` is wired, so cross-task usage cannot be counted and no window can be enforced. Wire InMemoryUsageWindowStore (process-local) or FileUsageWindowStore (restart-surviving)."), { phase: "config", sessionId }); return undefined; } const key = principal || GLOBAL_USAGE_KEY; const governsCost = windowsGovernCost(windows); let chargedTokens = 0; let chargedCostMicroUsd = 0; let announcedCostGap = false; let recordedUnpricedGap = false; return { key, governsCost, async check(now) { const readings = await store.read(key, windows, now); if (!announcedCostGap && readings.some((r) => r.costUnknown === true)) { announcedCostGap = true; deps.onError?.(new Error(`the usage window for ledger key ${JSON.stringify(key)} holds spend that nothing could price, so its maxCostUsd ceiling is being evaluated against a LOWER BOUND until that charge ages out of the window. Price every model this deployment can reach (including degrade targets and the compaction model).`), { phase: "config", sessionId }); } return usageRetryAfterMs(readings, windows); }, async commit(cumulativeTokens, cumulativeCostMicroUsd, now) { if (!governsCost) { const delta = cumulativeTokens - chargedTokens; if (delta <= 0) return; await store.charge(key, delta, now, windows); chargedTokens = cumulativeTokens; return; } if (cumulativeCostMicroUsd === undefined) { const tokenDelta = cumulativeTokens - chargedTokens; if (tokenDelta > 0 || !recordedUnpricedGap) { await store.charge(key, Math.max(0, tokenDelta), now, windows, null); chargedTokens = Math.max(chargedTokens, cumulativeTokens); recordedUnpricedGap = true; } const e = new Error("a deployment usage window declares maxCostUsd, but this run's spend has NO cost figure (RB-368 unpriced: a model served without a RunnerDeps.pricing entry or a Model.cost declaration). Refused rather than charged a fabricated 0 — the money ceiling would have silently stopped applying. Price every model this run can reach, or drop maxCostUsd from the window."); e.code = "config.usage_window_unpriced"; throw e; } const tokenDelta = cumulativeTokens - chargedTokens; const costDelta = cumulativeCostMicroUsd - chargedCostMicroUsd; if (tokenDelta <= 0 && costDelta <= 0) return; await store.charge(key, Math.max(0, tokenDelta), now, windows, Math.max(0, costDelta)); chargedTokens = cumulativeTokens; chargedCostMicroUsd = cumulativeCostMicroUsd; }, }; } const ungatedWarnedShapes = new WeakMap(); function announceDurableGateUnavailable(args) { if (args.mandate === undefined || args.storeWired) return; const source = args.mandate; const cause = args.taskStoreDisabled ? "task_store_disabled" : "no_deployment_store"; const inheritedContentMandate = (args.parentConstraints ?? []).some((pc) => pc.contentMandate === true); const liveQuestionFace = args.liveQuestionFace && !inheritedContentMandate; deliverEngineNotice(args.onNotice, { code: "config.durable_gate_unavailable", message: `Durable approval gate mandated but unavailable: ${source === "force_durable_gate" ? "the runtime entitlement forceDurableGate is in force for this principal" : "this task opted into durable approval (durableApproval) with no live approver seat"}, ` + `but ${cause === "task_store_disabled" ? 'this task disabled the checkpoint store (checkpointStore: "disabled")' : "this deployment wired no checkpoint store"}, ` + `so no interactive ask of this task can be parked for a durable answer. Asks resolve on the live chain instead ` + `(${args.liveApprover ? "a live approver answers permission asks in-stream" : args.blanketAllow ? 'a blanket "allow" posture answers ordinary permission asks without judgment (a mandated ask is refused)' : "permission asks are denied fail-closed — no live approver is wired"}; ` + `${liveQuestionFace ? "a live question face answers AskUserQuestion in-stream" : args.liveQuestionFace ? "AskUserQuestion is withheld from the live face by an inherited durable mandate and refused" : "AskUserQuestion has no live face and is refused"}) ` + `and NO durable approval record is written. ${cause === "task_store_disabled" ? "Run this task with its store" : "Wire a checkpoint store on this deployment"}, or ${source === "force_durable_gate" ? "withdraw the entitlement for principals served here" : "give the task a live approver seat (or drop durableApproval)"}.`, detail: { sessionId: args.sessionId, runId: args.runId, ...(args.principal ? { principal: args.principal } : {}), cause, source, liveApprover: args.liveApprover, liveQuestionFace, }, }); } export function prepareWiringManifest(input) { const { spec, deps, internals, resume, sessionId, runId, hostTaskId, taskScope, hooks, preToolUseObservational, policyLayers, effectivePolicy, handsEnabled, taskRootFinal, mcp, irreversibleTools, egressTools, toolEffects, ownedEnv, executionEnv, offloadStore, onceLedger, usageWindows, envLifetimeSuspendAt, runtimeCaps, resolvedInteractionPosture, durableQuestionFace, liveQuestionFace, checkpointStore, sessions, modelGateManifest, autoModeArmReason, permissionMode, lockedPreflight, peerLaneRefs, frameSettlement, sessionBox, harness, pausedRef, frozenOnAsk, liveInheritedGate, delegation, toolRoster, readDenyBuiltinTiersActive, lspManagerWired, shellReadStationArmed, lspDiagnosticsLive, fileHistoryFact } = input; const onAsk = spec.onAsk ?? deps.onAsk; const handWriteTools = toolRoster.entries.filter((e) => e.mountedBy === "hands" && (e.effect === "write" || e.effect === "idempotent")).map((e) => e.name); const hasEffectAwareGate = Boolean(policyLayers.length > 0 || (hooks?.preToolUse !== undefined && !preToolUseObservational)); const peerWriteUngated = modePolicyOf(permissionMode.current).unstated === "ask" ? [] : mcp.tools.filter((t) => t.permissionSeat === "passthrough" && !irreversibleTools.has(t.name) && !egressTools.has(t.name) && (toolEffects.get(t.name) ?? "write") !== "read").map((t) => t.name); const firstPartyWriteUngated = (spec.tools ?? []) .map((t) => t.name) .filter((name) => !irreversibleTools.has(name) && !egressTools.has(name) && toolEffects.get(name) === "write"); const handOrFirstPartyUngated = !hasEffectAwareGate && (handWriteTools.length > 0 || firstPartyWriteUngated.length > 0); if (handOrFirstPartyUngated || peerWriteUngated.length > 0) { const what = [ !hasEffectAwareGate && handWriteTools.length > 0 ? `hand tools [${handWriteTools.join(", ")}]` : undefined, peerWriteUngated.length > 0 ? `server write tools under ${permissionMode.current} [${peerWriteUngated.join(", ")}]` : undefined, !hasEffectAwareGate && firstPartyWriteUngated.length > 0 ? `write tools [${firstPartyWriteUngated.join(", ")}]` : undefined, ] .filter(Boolean) .join(" + "); if (!ungatedWarnedShapes.get(deps)?.has(what)) { let shapes = ungatedWarnedShapes.get(deps); if (!shapes) { shapes = new Set(); ungatedWarnedShapes.set(deps, shapes); } shapes.add(what); deps.onError?.(new Error(`write-capable ${what} are present but UNGATED — wire an effect-aware tool policy (or a PreToolUse hook). ` + `bash/MCP irreversible actions are otherwise unadjudicated; the deployment sandbox/egress boundary is the only protection (design/77 §4, design/53 §2.H). ` + (peerWriteUngated.length > 0 ? `Under ${permissionMode.current} a server's tools run with nobody stating them; a deny or ask rule naming them still gates them. ` : "") + `(This warning fires once per deployment per tool-set shape.)`), { phase: "config", sessionId }); } } const preToolContexts = new Map(); const blockedToolCalls = new Set(); const gateOutcomes = new Map(); const batchHaltRef = {}; const blockedTracked = Boolean(hooks?.postToolUse || hooks?.preToolUse || hooks?.postToolUseFailure || hooks?.postToolBatch); const restoreSurfaceGap = ownedEnv !== undefined && isRemoteExecutionEnv(ownedEnv) && ownedEnv.capabilities.suspendable ? missingRestoreSurface(ownedEnv) : []; const incompleteSuspendAdapter = restoreSurfaceGap.length > 0 ? restoreSurfaceGap : undefined; const durableSuspendInfraReady = resolveCheckpointStore(spec, deps) !== undefined && !(offloadStore !== undefined && isVolatileOffloadStore(offloadStore)) && (ownedEnv === undefined || isRemoteExecutionEnv(ownedEnv)) && incompleteSuspendAdapter === undefined; const resourceSuspendEligible = spec.resourceSuspend !== undefined && durableSuspendInfraReady; if (spec.resourceSuspend !== undefined && !resourceSuspendEligible) { const why = resolveCheckpointStore(spec, deps) === undefined ? "no CheckpointStore is wired" : offloadStore !== undefined && isVolatileOffloadStore(offloadStore) ? "tool-result offload uses the in-memory store (a resume needs durable results)" : incompleteSuspendAdapter !== undefined ? `the per-task execution env declares capabilities.suspendable but its adapter does not implement ${incompleteSuspendAdapter.join(" or ")} (a snapshot nothing can restore is worse than no snapshot)` : "the per-task execution env is not a RemoteExecutionEnv (it would be destroyed on suspend)"; onceLedger.onError(new Error(`resourceSuspend is set but INACTIVE: ${why}; resource limits will hard-fail, not suspend`), { phase: "config", sessionId, }); } const usageGovernance = buildUsageGovernance(usageWindows, deps, spec.principal, sessionId); const platformSuspendArmed = durableSuspendInfraReady && (envLifetimeSuspendAt !== undefined || usageGovernance !== undefined); const durableApproval = spec.durableApproval ?? (runtimeCaps?.forceDurableGate ? { scope: spec.principal || DEFAULT_IRREVERSIBLE_SCOPE } : undefined); const writeProtection = mountWriteProtection({ deps, env: handsEnabled ? executionEnv : undefined, rootPath: taskRootFinal, roster: toolRoster, sessionId, runId }); const wiringQuestionSeam = resolveQuestionSeam(spec, deps); const wiringQuestionStripped = internals?.questionFaceStripped === true; const wiringAskSeam = resolveAskSeamForm(spec, deps); const wiringManifest = deriveWiringManifest({ half: "effective", leg: resume !== undefined ? "resume" : internals?.isDelegatedChild === true ? "child" : "root", teamRole: teamRoleOf({ isDelegatedChild: delegation.isDelegatedChild, ...(internals?.explicitAgentName !== undefined ? { spawnName: internals.explicitAgentName } : {}) }), ...(spec.peerPresence !== undefined ? { peerPresence: spec.peerPresence } : {}), askForm: wiringAskSeam.form, ...(wiringAskSeam.provenance !== undefined ? { askProvenance: wiringAskSeam.provenance } : {}), questionWired: wiringQuestionSeam.wired, ...(wiringQuestionSeam.provenance !== undefined ? { questionProvenance: wiringQuestionSeam.provenance } : {}), ...(wiringQuestionStripped ? { questionStrippedByEngine: true } : {}), ...(resolvedInteractionPosture !== undefined ? { interactionPosture: resolvedInteractionPosture } : {}), ...(spec.interactiveTools === true && !wiringQuestionSeam.wired && !durableQuestionFace && !wiringQuestionStripped ? { interactiveToolsWithoutDeliveryFace: true } : {}), elicitSeamWired: resolveElicitSeam(deps), elicitServersOptedIn: countElicitOptIns(spec), parkCapable: checkpointStore !== undefined, parkDurableApprovalOptIn: spec.durableApproval !== undefined, parkForceDurableGate: runtimeCaps?.forceDurableGate === true, parkSafetyVocabularyArmed: irreversibleTools.size > 0 || egressTools.size > 0 || shellReadStationArmed, ...(checkpointStore !== undefined ? { checkpointDurability: resolveDeclaredDurability(checkpointStore, "checkpointStore") } : {}), sessionDurability: resolveDeclaredDurability(sessions, "sessionStore"), backgroundAgentStoreWired: deps.backgroundAgentStore !== undefined, subagentTranscriptTier: resolveSubagentTranscriptTier(deps.backgroundAgentStore !== undefined, sessions), permissionRuleStoreWired: deps.permissionRuleStore?.partitions.durable === true, permissionRuleSyncWired: deps.permissionRuleSyncWired === true, permissionRuleOrgGoverned: deps.permissionRuleStore?.partitions.org === true, hostChildEventSinkWired: deps.onBackgroundChildEvent !== undefined, lockedConfigWired: deps.lockedConfig !== undefined, complianceWired: deps.compliancePostureResolver !== undefined, memoryAdmissionWired: deps.memoryScopeAdmission !== undefined, retentionPolicyWired: deps.retentionPolicy !== undefined, ...(modelGateManifest !== undefined ? { modelGate: modelGateManifest } : {}), autoMode: { ...autoModeArmReason() }, permissionMode: permissionMode.receipt(), mcp: mcpManifestEntries(lockedPreflight.mcp, mcp.statuses), ...(writeProtection !== undefined ? { writeProtectionTargetView: writeProtection.targetView } : {}), readDenyBuiltinTiersActive, autoConsolidationOnRecommendation: autoRunOnRecommendationEffective(deps), tools: toolRoster, hooks: wiredHookEntries(hooks, spec.hooks !== undefined ? "spec" : "deps", preToolUseObservational), ...(lspManagerWired ? { lsp: deriveLspSeam(toolRoster.entries.some((e) => e.contract.contractId === LSP_CONTRACT_ID), lspDiagnosticsLive) } : {}), hands: deriveHandsSeam(handsEnabled), fileHistory: fileHistoryFact, }); peerLaneRefs.askEffective = askSeatEffective(wiringManifest); peerLaneRefs.permissionMode = () => permissionMode.current; const sessionBoxBound = sessionBox !== undefined && internals?.onTaskNotification !== undefined ? sessionBox : undefined; if (sessionBoxBound !== undefined && internals?.onTaskNotification !== undefined) { bindPeerLaneDrain(harness, { deps, sessionId, runId, scope: taskScope, inject: internals.onTaskNotification, ownTokens: () => internals?.peerSelfRef?.current.ownTokens ?? [], refs: peerLaneRefs, settlement: frameSettlement, selfName: () => internals?.explicitAgentName, parked: () => pausedRef.current !== undefined, }); frameSettlement.boxBacked = (payload) => peerLaneRefs.isBoxBacked?.(payload) ?? false; } const parkLaneArmed = wiringManifest.parkLane.effective === true; const gateMachineryActive = effectivePolicy !== undefined || hooks?.preToolUse !== undefined || egressTools.size > 0 || irreversibleTools.size > 0 || shellReadStationArmed || resourceSuspendEligible || platformSuspendArmed || spec.enablePlanMode === true; announceDurableGateUnavailable({ onNotice: deps.onNotice, mandate: durableMandateSourceOf({ forceDurableGate: runtimeCaps?.forceDurableGate === true, durableApprovalDeclared: spec.durableApproval !== undefined, onAsk: frozenOnAsk }), storeWired: checkpointStore !== undefined, taskStoreDisabled: spec.checkpointStore === "disabled", liveApprover: isLiveApproverSeat(frozenOnAsk), blanketAllow: frozenOnAsk === "allow", liveQuestionFace: liveQuestionFace !== undefined, parentConstraints: liveInheritedGate?.parentConstraints, sessionId, runId, principal: spec.principal }); const hookIdentity = mintHookInvocationIdentity({ sessionId, taskId: hostTaskId, legKind: wiringManifest.leg.kind, isDelegatedChild: delegation.isDelegatedChild, ...(internals?.insideFork === true ? { insideFork: true } : {}), ...(internals?.agentName !== undefined ? { agentName: internals.agentName } : {}), ...(internals?.explicitAgentName !== undefined ? { spawnName: internals.explicitAgentName } : {}), ...(internals?.spawnAgentType !== undefined ? { agentType: internals.spawnAgentType } : {}), ...(internals?.parentToolCallId !== undefined ? { parentToolCallId: internals.parentToolCallId } : {}), }); const hookContextConsumerWired = hooks?.preToolUse !== undefined || hooks?.postToolUse !== undefined || hooks?.postToolUseFailure !== undefined; const hookEnvFace = hookContextConsumerWired && (ownedEnv ?? deps.executionEnv) != null ? createHookEnvCapabilities(executionEnv) : undefined; return { onAsk, preToolContexts, blockedToolCalls, gateOutcomes, batchHaltRef, blockedTracked, incompleteSuspendAdapter, durableSuspendInfraReady, resourceSuspendEligible, usageGovernance, platformSuspendArmed, durableApproval, wiringManifest, writeProtection, parkLaneArmed, gateMachineryActive, hookIdentity, hookEnvFace, sessionBoxBound }; }