import type { AgentToolResult, AgentToolUpdateCallback } from "@code-yeongyu/senpi" import { createChildProgress } from "../../progress" import { loadSenpiBarrel } from "../../lazy/senpi-barrel" import type { TaskRecord } from "../../state" import type { KernelToolGrant } from "../../kernel-tools/resolve" import { buildStartSpec } from "./execute-spec" import type { ForegroundWaitOptions } from "./foreground-wait" import { waitForForegroundTask } from "./foreground-wait" import { partialDetails, recordDetails, startedDetails, withLiveSpawnFacts, type SingleSpawnParams, } from "./result-details" import { appendMissingSkills } from "./skill-result" import { evaluateSpawnPolicy } from "./spawn-policy" import { backgroundConversionText, backgroundStartText, type StartLabels } from "./start-presentation" import type { TaskToolContext, TaskToolDeps, TaskToolDetails, TaskToolMode } from "./types" import { validateTaskTarget } from "./validation" type RunSpawnInput = ForegroundWaitOptions & { readonly params: SingleSpawnParams readonly signal: AbortSignal | undefined readonly onUpdate: AgentToolUpdateCallback | undefined readonly ctx: TaskToolContext // Transient grant resolved by the caller against the parent's live kernel-tool capability. readonly kernelTools?: KernelToolGrant } function result(text: string, details: TaskToolDetails): AgentToolResult { return { content: [{ type: "text", text }], details } } function continuationFooter(taskId: string): string { return `\n\n[task_id: ${taskId} - continue with task_send(to="${taskId}", message="...")]` } function syncResult( record: TaskRecord, mode: TaskToolMode, skills: ReturnType["skills"], ): AgentToolResult { const body = record.final_response ?? record.error_message ?? `Task ${record.status}` return result(appendMissingSkills(body + continuationFooter(record.task_id), skills), { ...recordDetails(record, mode), ...(skills === undefined ? {} : { skills }), }) } export async function runSpawn(deps: TaskToolDeps, input: RunSpawnInput): Promise> { const { params, signal, onUpdate, ctx, env, scheduleDeadline } = input if (signal?.aborted) { const reason = "Parent aborted before spawn" return result(reason, { task_id: "", status: "cancelled", mode: "spawn", reason }) } const selection = validateTaskTarget(params) if (selection.kind === "error") { return result(selection.error.message, { task_id: "", status: "invalid_arguments", mode: "spawn", reason: selection.error.message, }) } const policy = selection.kind === "subagent_type" ? evaluateSpawnPolicy(deps, selection.subagentType, params.prompt, ctx.sessionManager.getSessionId()) : undefined if (policy?.kind === "deny") { return result(policy.message, { task_id: "", status: "denied", mode: "spawn", reason: policy.message }) } const effectiveParams = policy?.kind === "force" ? { ...params, prompt: policy.prompt, load_skills: [] } : params const target = selection.kind === "category" ? { category: selection.category } : { subagentType: selection.subagentType } const startLabels: StartLabels = { taskSummary: params.task_summary, description: params.description, } // The default skill discovery inside buildStartSpec reads the senpi barrel synchronously, so the // barrel is warmed here (memoized: a cache hit once the engine barrel is loaded). await loadSenpiBarrel() const spec = buildStartSpec( effectiveParams, target, ctx.sessionManager.getSessionId(), deps, ctx.cwd, input.kernelTools, ) const started = await deps.manager.start(spec) if (started.kind === "plan_unresolved") { const agents = started.error.availableAgents const categories = started.error.availableCategories const agentSuffix = agents && agents.length > 0 ? ` Available agents: ${agents.join(", ")}.` : "" const categorySuffix = categories && categories.length > 0 ? started.error.code === "model_unavailable" ? ` Valid category names: ${categories.join(", ")}. Retry one of these, or configure categories..models in omo.json: model overrides cannot be combined with category.` : ` Available categories: ${categories.join(", ")}.` : "" return result(started.error.message + agentSuffix + categorySuffix, { task_id: "", status: "plan_error", mode: "spawn", reason: started.error.message, }) } if (started.kind === "held") return result("Task admission is held by your Stop. Resume the run to continue.", { task_id: started.task_id, status: "paused", mode: "spawn", pause_seq: started.pauseSeq, }) if (started.kind === "depth_denied") { return result(started.reason, { task_id: "", status: "denied", mode: "spawn", reason: started.reason }) } if (started.kind === "start_failed") { return result(appendMissingSkills(started.error_message, spec.skills), { task_id: started.task_id, status: "error", mode: "spawn", name: started.name, ...(started.category !== undefined && { category: started.category }), ...(started.subagent_type !== undefined && { subagent_type: started.subagent_type }), execution_mode: started.execution_mode, model: started.model, ...(started.resolved_model !== undefined && { resolved_model: started.resolved_model }), run_in_background: started.run_in_background, ...(started.failure_kind === undefined ? {} : { failure_kind: started.failure_kind }), ...(started.failure_reason === undefined ? {} : { failure_reason: started.failure_reason }), reason: started.error_message, ...(spec.skills === undefined ? {} : { skills: spec.skills }), }) } if (started.kind === "residency_denied") { return result(started.reason, { task_id: "", status: "residency_denied", mode: "spawn", reason: started.reason }) } // What the started child actually runs as. The spec names no mode only when omo.json says `auto` // and this wiring has no daemon gate at all, which IS in-process. const executionMode = spec.execution_mode ?? "in-process" if (params.run_in_background === true) { return result( appendMissingSkills(backgroundStartText(started, startLabels), spec.skills), startedDetails(started, params, executionMode, spec.skills), ) } const startedAt = Date.now() const progress = createChildProgress( started.task_id, { ...(params.category !== undefined && { category: params.category }), ...(params.subagent_type !== undefined && { agentType: params.subagent_type }), ...(started.resolved_model !== undefined && { resolvedModel: started.resolved_model }), ...(params.model !== undefined && { model: params.model }), name: started.name, ...(params.task_summary !== undefined && { taskSummary: params.task_summary }), ...(params.description !== undefined && { description: params.description }), }, startedAt, ) let timer: ReturnType | undefined let emittedAt = 0 let receivedChildEvent = false let closed = false const launch = started.starting === true ? deps.manager.whenLaunched?.(started.task_id) : undefined let launching = launch !== undefined const emit = (): void => { if (closed || launching || onUpdate === undefined) return emittedAt = Date.now() onUpdate({ content: [{ type: "text", text: progress.contentText() }], details: partialDetails( withLiveSpawnFacts(started, deps.manager.get(started.task_id)), params, executionMode, progress.details(), spec.skills, ), }) } const schedule = (): void => { if (closed || launching || onUpdate === undefined) return if (!receivedChildEvent) { receivedChildEvent = true emit() return } const remaining = 250 - (Date.now() - emittedAt) if (remaining <= 0) { emit() } else if (timer === undefined) { timer = setTimeout(() => { timer = undefined emit() }, remaining) timer.unref?.() } } const unsubscribe = deps.manager.subscribeChild(started.task_id, (event) => { if (progress.accept(event)) schedule() }) if (started.status === "pending") { onUpdate?.({ content: [{ type: "text", text: "" }], details: partialDetails( withLiveSpawnFacts(started, deps.manager.get(started.task_id)), params, executionMode, { progress: { activity: "queued ยท waiting for slot", startedAt }, childId: started.task_id, turns: 0, }, spec.skills, ), }) } else { emit() } // Do not publish running partials with incomplete facts while the launch is still in flight. // whenLaunched is optional and may reject: a failed launch releases the partials too, and the wait below reports it. if (launch !== undefined) { const launchSettled = (): void => { launching = false emit() } void launch.then(launchSettled, launchSettled) } const parent = deps.manager.findTaskByChildSession?.(ctx.sessionManager.getSessionId()) const parked = parent === undefined ? undefined : deps.manager.concurrency?.park(parent.task_id, parent.notification.run_epoch) let promoted = false try { const waited = await waitForForegroundTask({ manager: deps.manager, taskId: started.task_id, signal, ctx, ...(env !== undefined && { env }), ...(scheduleDeadline !== undefined && { scheduleDeadline }), }) if (waited.kind === "promoted") { promoted = true return result( appendMissingSkills(backgroundConversionText(started, startLabels, waited.budgetSeconds), spec.skills), { ...startedDetails(started, params, executionMode, spec.skills), run_in_background: true, }, ) } if (timer !== undefined) { clearTimeout(timer) timer = undefined emit() } return syncResult(waited.record, "spawn", spec.skills) } catch (error) { if (!signal?.aborted || error !== signal.reason) throw error const reason = "parent turn aborted" await deps.manager.cancelTask(started.task_id, reason) return result(`Task ${started.task_id} cancelled: ${reason}.${continuationFooter(started.task_id)}`, { ...startedDetails(started, params, executionMode, spec.skills), status: "cancelled", reason, }) } finally { closed = true if (timer !== undefined) clearTimeout(timer) unsubscribe() await deps.manager.concurrency?.unpark(parked, signal, { overflow: promoted }) } }