UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

133 lines (132 loc) • 11.8 kB
import { createAgentTranscriptTool, AGENT_TRANSCRIPT_TOOL_NAME } from "../../agents/agent-transcript-tool.js"; import { createSendMessageTool, SEND_MESSAGE_TOOL_NAME } from "../../agents/send-message-tool.js"; import { listAgentsMountable, mountListAgents, peerLaneSendMessageSeats } from "../../agents/peer-session-drain.js"; import { resolvePeerLaneConfig } from "../../agents/peer-admission.js"; import { createReadInboxTool, READ_INBOX_TOOL_NAME } from "../../agents/read-inbox-tool.js"; import { createMonitorTool } from "../../tools/monitor.js"; import { createWorktreeTools } from "../../tools/worktree.js"; import { createTaskOutputTool, createTaskStopTool, defaultTaskRegistry } from "../task-registry.js"; import { createReadToolResultTool } from "../tool-result-store.js"; import { emitTrace } from "../trace.js"; import { deliverEngineNotice } from "../types.js"; import { RosterBuilder } from "../tool-roster.js"; import { sendMessageContinuationSeats } from "./send-message-continuation.js"; export function prepareDelegationSurface(input) { const { spec, deps, internals, resume, sessionId, hostTaskId, taskScope, taskRootFinal, taskRootCanonical, executionEnv, runnerSelf, backgroundTaskToolsActive, workflowToolsActive, peerLaneActive, peerSendMessageBuiltIn, peerLaneRefs, sessionBox, roster, toolEffects, axisExplicitNegatives, envHandToolNames, toolFaceSnapshot, firstPartyOffload, offloadStore, subagentRetain, enrichSpecToolCtx, checkpointSeat, handsCwdRef, wsSnapshot, rebaseWsPath, rebaseRestoredPath, workspaceStateSettle } = input; let worktreeSessionRef; const delegationSurfaceActive = backgroundTaskToolsActive || workflowToolsActive; let sendMessageTier; if (delegationSurfaceActive || internals?.parentNotify !== undefined || peerLaneActive) { if (delegationSurfaceActive) { roster.mountAll([ firstPartyOffload(createTaskOutputTool({ registry: defaultTaskRegistry, owner: hostTaskId, scope: taskScope, sessionId, workflowStore: deps.workflowRunStore, agentStore: deps.backgroundAgentStore, notificationWired: internals?.onTaskNotification !== undefined, oneShot: spec.oneShot, toolResultStore: offloadStore, ...(checkpointSeat !== undefined ? { checkpointSeat } : {}) })), firstPartyOffload(createTaskStopTool({ registry: defaultTaskRegistry, owner: hostTaskId, scope: taskScope, sessionId, workflowStore: deps.workflowRunStore, agentStore: deps.backgroundAgentStore })), ], { source: "builtin", mountedBy: "delegation" }); } if (runnerSelf && !(spec.tools ?? []).some((t) => t.name === SEND_MESSAGE_TOOL_NAME)) { axisExplicitNegatives.set(SEND_MESSAGE_TOOL_NAME, { ...axisExplicitNegatives.get(SEND_MESSAGE_TOOL_NAME), egress: false }); const { reviveSpawn, tier } = sendMessageContinuationSeats({ specTools: spec.tools ?? [], agentStore: deps.backgroundAgentStore, mailbox: deps.mailboxStore, runner: runnerSelf, enrichSpecToolCtx }); sendMessageTier = tier; roster.mount(firstPartyOffload(createSendMessageTool({ runner: runnerSelf, registry: defaultTaskRegistry, ...(subagentRetain ? { retain: subagentRetain } : {}), owner: hostTaskId, scope: taskScope, ...(sessionId !== undefined ? { sessionId } : {}), ...(internals?.onTaskNotification !== undefined ? { notify: internals.onTaskNotification } : {}), ...(spec.oneShot !== undefined ? { oneShot: spec.oneShot } : {}), retrievalToolMounted: delegationSurfaceActive, ...(internals?.onSubagentSpawn !== undefined ? { sink: internals.onSubagentSpawn } : {}), ...(internals?.parentNotify !== undefined ? { uplink: internals.parentNotify, ...(internals.parentPeerRef !== undefined ? { uplinkRecipient: internals.parentPeerRef } : {}) } : {}), ...(internals?.uplinkSessionId !== undefined ? { uplinkSessionId: internals.uplinkSessionId } : {}), ...(internals?.explicitAgentName !== undefined ? { senderName: internals.explicitAgentName } : {}), ...(internals?.parentRetainLedger !== undefined ? { siblingRetain: internals.parentRetainLedger } : {}), ...(internals?.parentTaskId !== undefined ? { parentTaskId: internals.parentTaskId } : {}), ...(internals?.parentSessionId !== undefined ? { parentSessionId: internals.parentSessionId } : {}), enrichCtx: enrichSpecToolCtx, ...(deps.rosterStore !== undefined ? { roster: deps.rosterStore } : {}), ...(deps.peerLane !== undefined ? { lane: deps.peerLane } : {}), ...(deps.onNotice !== undefined ? { onNotice: deps.onNotice } : {}), ...(internals?.peerSelfRef !== undefined ? { peerSelf: internals.peerSelfRef } : {}), ...(internals?.peerInboundChainRef !== undefined ? { peerInbound: internals.peerInboundChainRef } : {}), ...(deps.onBackgroundChildEvent ? { onBackgroundChildEvent: deps.onBackgroundChildEvent } : {}), ...(deps.backgroundAgentStore !== undefined ? { agentStore: deps.backgroundAgentStore } : {}), ...(deps.mailboxStore !== undefined ? { mailbox: deps.mailboxStore } : {}), ...(reviveSpawn !== undefined ? { reviveSpawn } : {}), ...(peerLaneActive ? peerLaneSendMessageSeats({ peerDirectory: deps.peerDirectory, sessionId, scope: taskScope, ...(internals?.explicitAgentName !== undefined ? { name: internals.explicitAgentName } : {}), refs: peerLaneRefs, listingMounted: listAgentsMountable({ exclude: toolFaceSnapshot.exclude, specTools: spec.tools ?? [] }) }) : {}), onNotifyError: (f) => emitTrace(deps.tracer, () => ({ kind: "observer.notify_failed", version: 1, taskId: hostTaskId, site: f.site, message: f.error.message, ts: Date.now() })), onTranscriptIntegrityGap: (handle, scope) => deliverEngineNotice(deps.onNotice, { code: "delegation.transcript_integrity", message: `delegation transcript integrity: agent ${handle}'s durable row binds a transcript session the session store attests is gone — the declared transcript durability is being contradicted (check the session store wiring/retention)`, detail: { handle, ...(scope !== undefined ? { scope } : {}) }, }), })), { source: "builtin", mountedBy: delegationSurfaceActive ? "delegation" : internals?.parentNotify !== undefined ? "hostInternals" : "peerLane" }); if (delegationSurfaceActive && !(spec.tools ?? []).some((t) => t.name === AGENT_TRANSCRIPT_TOOL_NAME)) { roster.mount(firstPartyOffload(createAgentTranscriptTool({ runner: runnerSelf, registry: defaultTaskRegistry, agentStore: deps.backgroundAgentStore, ...(checkpointSeat !== undefined ? { checkpointSeat } : {}), owner: hostTaskId, scope: taskScope, ...(sessionId !== undefined ? { sessionId } : {}), enrichCtx: enrichSpecToolCtx, onTranscriptIntegrityGap: (handle, scope) => deliverEngineNotice(deps.onNotice, { code: "delegation.transcript_integrity", message: `delegation transcript integrity: agent ${handle}'s durable row binds a transcript session the session store attests is gone — the declared transcript durability is being contradicted (check the session store wiring/retention)`, detail: { handle, ...(scope !== undefined ? { scope } : {}) }, }), })), { source: "builtin", mountedBy: "delegation" }); } } } if (sessionBox !== undefined && internals?.onTaskNotification !== undefined && !(toolFaceSnapshot.exclude ?? []).includes(READ_INBOX_TOOL_NAME) && !(spec.tools ?? []).some((t) => t.name === READ_INBOX_TOOL_NAME)) { toolEffects.set(READ_INBOX_TOOL_NAME, "read"); roster.mount(firstPartyOffload(createReadInboxTool({ pull: () => peerLaneRefs.pull })), { source: "builtin", mountedBy: "peerLane" }); } const listAgents = (peerLaneActive || delegationSurfaceActive) && peerSendMessageBuiltIn && listAgentsMountable({ exclude: toolFaceSnapshot.exclude, specTools: spec.tools ?? [] }) ? mountListAgents({ ...(peerLaneActive ? { peerDirectory: deps.peerDirectory } : {}), freshWindowMs: resolvePeerLaneConfig(deps.peerLane, deps.onNotice).listingFreshWindowMs, sessionId, scope: taskScope, hostTaskId, ...(internals?.parentTaskId !== undefined ? { parentTaskId: internals.parentTaskId } : {}), ...(internals?.parentSessionId !== undefined ? { parentSessionId: internals.parentSessionId } : {}), registry: defaultTaskRegistry, ...(deps.rosterStore !== undefined ? { roster: deps.rosterStore } : {}), ...(sendMessageTier !== undefined ? { continuationTier: sendMessageTier } : {}), ...(checkpointSeat !== undefined ? { readSeats: { checkpointSeat } } : {}), specTools: spec.tools ?? [], toolEffects }) : undefined; if (listAgents !== undefined) roster.mount(firstPartyOffload(listAgents), { source: "builtin", mountedBy: "peerLane" }); if (backgroundTaskToolsActive) { envHandToolNames.add("Monitor"); roster.mount(firstPartyOffload(createMonitorTool(executionEnv, { registry: defaultTaskRegistry, ...(input.shellReadAdmission !== undefined ? { shellReadAdmission: input.shellReadAdmission } : {}), owner: hostTaskId, scope: taskScope, ...(sessionId !== undefined ? { sessionId } : {}), ...(internals?.onTaskNotification !== undefined ? { onTaskNotification: internals.onTaskNotification } : {}), ...(handsCwdRef !== undefined ? { cwdRef: handsCwdRef } : {}), rootCanonical: taskRootCanonical, ...(offloadStore !== undefined ? { toolResultStore: offloadStore } : {}), retainBackgroundProcesses: spec.retainBackgroundProcesses === true, })), { source: "builtin", mountedBy: "backgroundTasks" }); } if (handsCwdRef !== undefined) { worktreeSessionRef = { ...(resume?.seed.activeWorktree ? { current: { ...resume.seed.activeWorktree, worktreeDir: rebaseRestoredPath(resume.seed.activeWorktree.worktreeDir), originalCwd: rebaseRestoredPath(resume.seed.activeWorktree.originalCwd), }, } : wsSnapshot?.activeWorktree !== undefined ? { current: { ...wsSnapshot.activeWorktree, worktreeDir: rebaseWsPath(wsSnapshot.activeWorktree.worktreeDir), originalCwd: rebaseWsPath(wsSnapshot.activeWorktree.originalCwd), }, } : {}), }; if (workspaceStateSettle !== undefined) workspaceStateSettle.restoredWorktreeDir = worktreeSessionRef.current?.worktreeDir; roster.mountAll(createWorktreeTools(executionEnv, { repoRoot: taskRootFinal, cwdRef: handsCwdRef, session: worktreeSessionRef }).map((t) => (envHandToolNames.add(t.name), firstPartyOffload(t))), { source: "builtin", mountedBy: "hands" }); } if (offloadStore) roster.mount(createReadToolResultTool(offloadStore), { source: "builtin", mountedBy: "optional" }); return { delegationSurfaceActive, worktreeSessionRef }; }