import "./tool-display-DMBmPBI-.js";
import "./paths-WcYpcMAY.js";
import { yt as logVerbose } from "./entry.js";
import "./auth-profiles-CaNK0cUT.js";
import { C as parseAgentSessionKey, S as isSubagentSessionKey } from "./session-key-Fto5gqqw.js";
import "./exec-CmvuUufz.js";
import { l as resolveAgentWorkspaceDir } from "./agent-scope-E2aR3Ci_.js";
import "./github-copilot-token-CKOQDjEZ.js";
import "./emitter-BKo8D7Oj.js";
import "./sqlite-CVrhPija.js";
import "./reliability-BnL75OlZ.js";
import "./pi-model-discovery-Cd63DV2B.js";
import "./model-nrbMzlbz.js";
import "./frontmatter-C3D7gE4Z.js";
import "./skills-UwTwDeDw.js";
import "./manifest-registry-AgGLF4V7.js";
import "./validation-B00oOkJ3.js";
import { o as loadConfig } from "./config-CoCeK5B2.js";
import "./client-DtQEs2_8.js";
import { n as callGateway } from "./call-CkgY6Bq7.js";
import { t as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-DKXbq8GH.js";
import { Ct as spawnSubagentDirect, Ft as sortSubagentRuns, Mt as getSubagentDepthFromSessionStore, Nt as resolveSubagentLabel, Pt as resolveSubagentTargetFromRuns, St as truncateLine, Tt as getTemplate, a as listSubagentRunsForRequester, bt as formatTokenUsageDisplay, c as replaceSubagentRunAfterSteer, h as abortEmbeddedPiRun, o as markSubagentRunForSteerRestart, p as clearSessionQueues, s as markSubagentRunTerminated, t as clearSubagentRunSteerRestart, xt as resolveTotalTokens, yt as formatDurationCompact } from "./subagent-registry-BSfrC7gZ.js";
import { a as loadSessionStore, u as updateSessionStore } from "./sessions-CFJLtXRH.js";
import "./tokens-D-4TlWcT.js";
import "./heartbeat-XNOTz34R.js";
import "./accounts-CNwod9BY.js";
import "./accounts-C3i8BBiA.js";
import "./normalize-CRf-uoB2.js";
import "./bindings-B1hNZin3.js";
import "./helpers-C1I2eYI4.js";
import "./allow-list-C1QL6XM_.js";
import "./logging-BiuZwq5D.js";
import "./client-BrCP9C3o.js";
import "./plugins-DMpYx7kb.js";
import "./targets-DvKzWjKi.js";
import "./with-timeout-xvreNRIp.js";
import "./diagnostic-CvuUUG_n.js";
import "./diagnostic-session-state-Dom6CWV9.js";
import { n as AGENT_LANE_SUBAGENT } from "./lanes-6YZC1uc5.js";
import "./reply-payloads-DHkZZC3s.js";
import "./route-reply-0Dr2Q7BS.js";
import "./tts-CLI3TzKv.js";
import "./image-ops-D0pBQqKh.js";
import "./audio-xR21p4sl.js";
import "./pi-embedded-helpers-D-q9ylFX.js";
import "./sandbox-C79rEJ_w.js";
import "./chrome-BTLLz_O2.js";
import "./tailscale-V4nwZFBO.js";
import "./auth-Beo6eR0R.js";
import "./server-context-T5wFkzWi.js";
import "./routes-Ch0tqbTH.js";
import "./redact-2qrQ_uJt.js";
import "./errors-BlUw40-o.js";
import "./paths-Cb76_eC_.js";
import "./ssrf-BEPhIfOk.js";
import "./store-Bz34pm8z.js";
import "./ports-BsKQWWi9.js";
import "./trash-Cn3CsF86.js";
import "./dock-BvRrtCWj.js";
import "./accounts-CdYdWklO.js";
import { c as resolveStorePath } from "./paths-CDTtU20P.js";
import "./tool-images-B4eVOjD0.js";
import "./thinking-C03RqJxq.js";
import "./models-config-By95gdZa.js";
import "./chat-trace-C0wGIaWO.js";
import "./response-prefix-template-C1xl3U-G.js";
import "./tool-tracking-CtNygH0q.js";
import "./memory-cli-85mo64bb.js";
import "./manager-CFXUPO5v.js";
import "./gemini-auth-dH8SvNUd.js";
import "./session-files-0TqN4M7r.js";
import "./retry-Bdf0L_dZ.js";
import "./hybrid-DSp5ZIQe.js";
import { a as jsonResult, o as readNumberParam, u as readStringParam } from "./common-CxpUJZLb.js";
import "./send-BozJfiUK.js";
import "./chunk-CNObemR3.js";
import "./markdown-tables-Cex18ib0.js";
import "./fetch-guard-BLrk92iq.js";
import "./fetch-DFo2YRBT.js";
import "./media-PPft1pQs.js";
import "./ir-CRxad2DW.js";
import "./render-JkHfM4BD.js";
import "./commands-registry-Ckq8wOdS.js";
import { f as resolveInternalSessionKey, p as resolveMainSessionAlias } from "./sessions-helpers-NrlH9x7w.js";
import "./pi-embedded-utils-BCSBp2bL.js";
import "./external-content-pnoCpvzd.js";
import "./runner-Dbz36vkv.js";
import "./image-tool.helpers-Bb25eyJc.js";
import "./image-DnnIE6E3.js";
import "./model-catalog-c_sp3sxR.js";
import "./session-utils-CwXLwy_N.js";
import "./workspace-dirs-Dm1vImLQ.js";
import "./skill-commands-B6qVCgej.js";
import "./fetch-CbnJhXfl.js";
import "./pairing-store-BHSQgDEs.js";
import "./exec-approvals-DGBfDg6X.js";
import "./gateway-CWnGRD4E.js";
import "./nodes-utils-DKSV6jwI.js";
import "./session-cost-usage-COXOEQzN.js";
import "./typed-schema-NhH7oBv2.js";
import "./knowledge-graph-njh3pt-F.js";
import "./model-fallback-N2p6k-x8.js";
import "./send-DpN8GxWR.js";
import "./channel-activity-Renq827a.js";
import "./tables-BD7LbCl1.js";
import "./server-startup-users-Dzui320y.js";
import "./resolve-route-CjJJ3gIl.js";
import "./replies-f6OSxuwk.js";
import "./reply-prefix-CjtRvYlq.js";
import "./pi-tools.policy-CW2flz_o.js";
import "./send-CdF3YtrB.js";
import "./onboard-helpers-HmtMUhNQ.js";
import "./prompt-style-BNQCf62G.js";
import "./onboard-helpers-CMBWpQU-.js";
import "./outbound-attachment-BhyLC0RY.js";
import "./targets-Df3HJYGb.js";
import "./pairing-labels-B7JDegCR.js";
import "./send-oTQYKgod.js";
import "./send-BxB9sGGU.js";
import "./proxy-BWmn1C2E.js";
import "./links-BcL73qkF.js";
import "./cli-utils-CpDxBFOW.js";
import "./help-format-CSTLKmFP.js";
import "./progress-Dh4aWkCA.js";
import "./active-listener-Bqb34bVB.js";
import { r as optionalStringEnum } from "./typebox-C14oleuH.js";
import { a as readStatusJson, i as RATE_LIMIT_PER_MINUTE, n as executeOrchestration, o as readTaskOutputForGather, r as MAX_TASKS_PER_ORCHESTRATION, s as runAggregation, t as executePipeline } from "./orchestration-pipeline-CpJD9air.js";
import { r as readManifest } from "./orchestration-manifest-qOFXJrth.js";
import * as path$1 from "node:path";
import * as fs$1 from "node:fs";
import crypto from "node:crypto";
import { Type } from "@sinclair/typebox";

//#region src/agents/subagents/orchestration/orchestration-gather.ts
/**
* Orchestration gather — collects task results by orchestrationId,
* reads status.json and output files, supports filtering and cleanup.
*/
/**
* Gather results for an orchestration by reading the manifest and task output
* directories. Pure disk reads (no state mutation except cleanup).
*/
function gatherOrchestrationResults(params) {
	const manifest = readManifest(params.orchestrationDir);
	if (!manifest) return {
		orchestrationId: params.orchestrationId,
		status: "pending",
		taskCount: 0,
		tasks: []
	};
	let filteredTasks = manifest.tasks;
	if (params.template) filteredTasks = filteredTasks.filter((t) => t.template === params.template);
	if (params.label) filteredTasks = filteredTasks.filter((t) => t.label === params.label);
	if (!params.includeRunning) filteredTasks = filteredTasks.filter((t) => t.status !== "running" && t.status !== "pending");
	const gatherTasks = [];
	for (const manifestTask of filteredTasks) {
		const taskResult = buildGatherTaskResult(manifestTask, params);
		gatherTasks.push(taskResult);
	}
	const isInterrupted = manifest.status === "interrupted";
	const completedCount = manifest.tasks.filter((t) => t.status === "completed" || t.status === "failed").length;
	const incompleteCount = manifest.tasks.filter((t) => t.status === "pending" || t.status === "running" || t.status === "skipped").length;
	const result = {
		orchestrationId: params.orchestrationId,
		status: manifest.status,
		mode: manifest.mode,
		startedAt: manifest.startedAt,
		completedAt: manifest.completedAt,
		taskCount: manifest.taskCount,
		tasks: gatherTasks,
		...isInterrupted ? {
			interrupted: true,
			completedTasks: completedCount,
			incompleteTasks: incompleteCount,
			canResume: true
		} : {}
	};
	if (params.cleanup) try {
		fs$1.rmSync(params.orchestrationDir, {
			recursive: true,
			force: true
		});
	} catch {}
	return result;
}
function buildGatherTaskResult(manifestTask, params) {
	if (manifestTask.status === "running" || manifestTask.status === "pending") return {
		index: manifestTask.index,
		label: manifestTask.label,
		template: manifestTask.template,
		status: manifestTask.status,
		statusJson: null,
		files: []
	};
	if (manifestTask.outputDir) {
		const output = readTaskOutputForGather(manifestTask.outputDir, params.maxInlineBytes);
		const run = params.runs.find((r) => r.orchestrationId === params.orchestrationId && r.label === manifestTask.label);
		return {
			index: manifestTask.index,
			label: manifestTask.label,
			template: manifestTask.template,
			status: manifestTask.status,
			statusJson: output.status,
			files: output.files,
			resultText: run?.resultText ?? output.status?.summary,
			error: manifestTask.error
		};
	}
	return {
		index: manifestTask.index,
		label: manifestTask.label,
		template: manifestTask.template,
		status: manifestTask.status,
		statusJson: null,
		files: [],
		error: manifestTask.error
	};
}

//#endregion
//#region src/agents/tools/sessions/subagents-tool.ts
const SUBAGENT_ACTIONS = [
	"list",
	"kill",
	"steer",
	"orchestrate",
	"gather",
	"orchestrations"
];
const DEFAULT_RECENT_MINUTES = 30;
const MAX_RECENT_MINUTES = 1440;
const MAX_STEER_MESSAGE_CHARS = 4e3;
const STEER_RATE_LIMIT_MS = 2e3;
const STEER_ABORT_SETTLE_TIMEOUT_MS = 5e3;
const steerRateLimit = /* @__PURE__ */ new Map();
const orchestrateRateWindow = [];
const SubagentsToolSchema = Type.Object({
	action: optionalStringEnum(SUBAGENT_ACTIONS),
	target: Type.Optional(Type.String()),
	message: Type.Optional(Type.String()),
	recentMinutes: Type.Optional(Type.Number({ minimum: 1 })),
	mode: Type.Optional(Type.String()),
	tasks: Type.Optional(Type.Array(Type.Object({
		label: Type.String(),
		prompt: Type.String(),
		template: Type.Optional(Type.String()),
		model: Type.Optional(Type.String()),
		timeoutSeconds: Type.Optional(Type.Number())
	}))),
	stages: Type.Optional(Type.Array(Type.Object({
		tasks: Type.Array(Type.Object({
			label: Type.String(),
			prompt: Type.String(),
			template: Type.Optional(Type.String()),
			model: Type.Optional(Type.String()),
			timeoutSeconds: Type.Optional(Type.Number())
		})),
		onStageFailure: Type.Optional(Type.String())
	}))),
	maxConcurrency: Type.Optional(Type.Number()),
	onFailure: Type.Optional(Type.String()),
	maxRetries: Type.Optional(Type.Number()),
	maxTotalTokens: Type.Optional(Type.Number()),
	aggregationPrompt: Type.Optional(Type.String()),
	aggregationTemplate: Type.Optional(Type.String()),
	dryRun: Type.Optional(Type.Boolean()),
	orchestrationId: Type.Optional(Type.String()),
	template: Type.Optional(Type.String()),
	label: Type.Optional(Type.String()),
	includeRunning: Type.Optional(Type.Boolean()),
	cleanup: Type.Optional(Type.Boolean()),
	resumeOrchestrationId: Type.Optional(Type.String()),
	status: Type.Optional(Type.String()),
	since: Type.Optional(Type.Number()),
	until: Type.Optional(Type.Number())
});
function resolveRunStatus(entry) {
	if (!entry.endedAt) return "running";
	const status = entry.outcome?.status ?? "done";
	if (status === "ok") return "done";
	if (status === "error") return "failed";
	return status;
}
function resolveModelRef(entry) {
	const model = typeof entry?.model === "string" ? entry.model.trim() : "";
	const provider = typeof entry?.modelProvider === "string" ? entry.modelProvider.trim() : "";
	if (model.includes("/")) return model;
	if (model && provider) return `${provider}/${model}`;
	if (model) return model;
	if (provider) return provider;
	const overrideModel = typeof entry?.modelOverride === "string" ? entry.modelOverride.trim() : "";
	const overrideProvider = typeof entry?.providerOverride === "string" ? entry.providerOverride.trim() : "";
	if (overrideModel.includes("/")) return overrideModel;
	if (overrideModel && overrideProvider) return `${overrideProvider}/${overrideModel}`;
	if (overrideModel) return overrideModel;
	return overrideProvider || void 0;
}
function resolveModelDisplay(entry, fallbackModel) {
	const modelRef = resolveModelRef(entry) || fallbackModel || void 0;
	if (!modelRef) return "model n/a";
	const slash = modelRef.lastIndexOf("/");
	if (slash >= 0 && slash < modelRef.length - 1) return modelRef.slice(slash + 1);
	return modelRef;
}
function resolveSubagentTarget(runs, token, options) {
	return resolveSubagentTargetFromRuns({
		runs,
		token,
		recentWindowMinutes: options?.recentMinutes ?? DEFAULT_RECENT_MINUTES,
		label: (entry) => resolveSubagentLabel(entry),
		errors: {
			missingTarget: "Missing subagent target.",
			invalidIndex: (value) => `Invalid subagent index: ${value}`,
			unknownSession: (value) => `Unknown subagent session: ${value}`,
			ambiguousLabel: (value) => `Ambiguous subagent label: ${value}`,
			ambiguousLabelPrefix: (value) => `Ambiguous subagent label prefix: ${value}`,
			ambiguousRunIdPrefix: (value) => `Ambiguous subagent run id prefix: ${value}`,
			unknownTarget: (value) => `Unknown subagent target: ${value}`
		}
	});
}
function resolveStorePathForKey(cfg, key, parsed) {
	return resolveStorePath(cfg.session?.store, { agentId: parsed?.agentId });
}
function resolveSessionEntryForKey(params) {
	const parsed = parseAgentSessionKey(params.key);
	const storePath = resolveStorePathForKey(params.cfg, params.key, parsed);
	let store = params.cache.get(storePath);
	if (!store) {
		store = loadSessionStore(storePath);
		params.cache.set(storePath, store);
	}
	return {
		storePath,
		entry: store[params.key]
	};
}
function resolveRequesterKey(params) {
	const { mainKey, alias } = resolveMainSessionAlias(params.cfg);
	const callerSessionKey = resolveInternalSessionKey({
		key: params.agentSessionKey?.trim() || alias,
		alias,
		mainKey
	});
	if (!isSubagentSessionKey(callerSessionKey)) return {
		requesterSessionKey: callerSessionKey,
		callerSessionKey,
		callerIsSubagent: false
	};
	if (getSubagentDepthFromSessionStore(callerSessionKey, { cfg: params.cfg }) < (params.cfg.agents?.defaults?.subagents?.maxSpawnDepth ?? 2)) return {
		requesterSessionKey: callerSessionKey,
		callerSessionKey,
		callerIsSubagent: true
	};
	const cache = /* @__PURE__ */ new Map();
	const callerEntry = resolveSessionEntryForKey({
		cfg: params.cfg,
		key: callerSessionKey,
		cache
	}).entry;
	return {
		requesterSessionKey: (typeof callerEntry?.spawnedBy === "string" ? callerEntry.spawnedBy.trim() : "") || callerSessionKey,
		callerSessionKey,
		callerIsSubagent: true
	};
}
async function killSubagentRun(params) {
	if (params.entry.endedAt) return { killed: false };
	const childSessionKey = params.entry.childSessionKey;
	const resolved = resolveSessionEntryForKey({
		cfg: params.cfg,
		key: childSessionKey,
		cache: params.cache
	});
	const sessionId = resolved.entry?.sessionId;
	const aborted = sessionId ? abortEmbeddedPiRun(sessionId) : false;
	const cleared = clearSessionQueues([childSessionKey, sessionId]);
	if (cleared.followupCleared > 0 || cleared.laneCleared > 0) logVerbose(`subagents tool kill: cleared followups=${cleared.followupCleared} lane=${cleared.laneCleared} keys=${cleared.keys.join(",")}`);
	if (resolved.entry) await updateSessionStore(resolved.storePath, (store) => {
		const current = store[childSessionKey];
		if (!current) return;
		current.abortedLastRun = true;
		current.updatedAt = Date.now();
		store[childSessionKey] = current;
	});
	return {
		killed: markSubagentRunTerminated({
			runId: params.entry.runId,
			childSessionKey,
			reason: "killed"
		}) > 0 || aborted || cleared.followupCleared > 0 || cleared.laneCleared > 0,
		sessionId
	};
}
/**
* Recursively kill all descendant subagent runs spawned by a given parent session key.
* This ensures that when a subagent is killed, all of its children (and their children) are also killed.
*/
async function cascadeKillChildren(params) {
	const childRuns = listSubagentRunsForRequester(params.parentChildSessionKey);
	const seenChildSessionKeys = params.seenChildSessionKeys ?? /* @__PURE__ */ new Set();
	let killed = 0;
	const labels = [];
	for (const run of childRuns) {
		const childKey = run.childSessionKey?.trim();
		if (!childKey || seenChildSessionKeys.has(childKey)) continue;
		seenChildSessionKeys.add(childKey);
		if (!run.endedAt) {
			if ((await killSubagentRun({
				cfg: params.cfg,
				entry: run,
				cache: params.cache
			})).killed) {
				killed += 1;
				labels.push(resolveSubagentLabel(run));
			}
		}
		const cascade = await cascadeKillChildren({
			cfg: params.cfg,
			parentChildSessionKey: childKey,
			cache: params.cache,
			seenChildSessionKeys
		});
		killed += cascade.killed;
		labels.push(...cascade.labels);
	}
	return {
		killed,
		labels
	};
}
function buildListText(params) {
	const lines = [];
	lines.push("active subagents:");
	if (params.active.length === 0) lines.push("(none)");
	else lines.push(...params.active.map((entry) => entry.line));
	lines.push("");
	lines.push(`recent (last ${params.recentMinutes}m):`);
	if (params.recent.length === 0) lines.push("(none)");
	else lines.push(...params.recent.map((entry) => entry.line));
	return lines.join("\n");
}
function createSubagentsTool(opts) {
	return {
		label: "Subagents",
		name: "subagents",
		description: "Manage sub-agents: list, kill, steer, orchestrate (fan-out/pipeline), gather results, or list orchestrations.",
		parameters: SubagentsToolSchema,
		execute: async (_toolCallId, args) => {
			const params = args;
			const action = readStringParam(params, "action") ?? "list";
			const cfg = loadConfig();
			const requester = resolveRequesterKey({
				cfg,
				agentSessionKey: opts?.agentSessionKey
			});
			const runs = sortSubagentRuns(listSubagentRunsForRequester(requester.requesterSessionKey));
			const recentMinutesRaw = readNumberParam(params, "recentMinutes");
			const recentMinutes = recentMinutesRaw ? Math.max(1, Math.min(MAX_RECENT_MINUTES, Math.floor(recentMinutesRaw))) : DEFAULT_RECENT_MINUTES;
			if (action === "list") {
				const now = Date.now();
				const recentCutoff = now - recentMinutes * 6e4;
				const cache = /* @__PURE__ */ new Map();
				let index = 1;
				const buildListEntry = (entry, runtimeMs) => {
					const sessionEntry = resolveSessionEntryForKey({
						cfg,
						key: entry.childSessionKey,
						cache
					}).entry;
					const totalTokens = resolveTotalTokens(sessionEntry);
					const usageText = formatTokenUsageDisplay(sessionEntry);
					const status = resolveRunStatus(entry);
					const runtime = formatDurationCompact(runtimeMs);
					const label = truncateLine(resolveSubagentLabel(entry), 48);
					const task = truncateLine(entry.task.trim(), 72);
					const line = `${index}. ${label} (${resolveModelDisplay(sessionEntry, entry.model)}, ${runtime}${usageText ? `, ${usageText}` : ""}) ${status}${task.toLowerCase() !== label.toLowerCase() ? ` - ${task}` : ""}`;
					const baseView = {
						index,
						runId: entry.runId,
						sessionKey: entry.childSessionKey,
						label,
						task,
						status,
						runtime,
						runtimeMs,
						model: resolveModelRef(sessionEntry) || entry.model,
						totalTokens,
						startedAt: entry.startedAt
					};
					index += 1;
					return {
						line,
						view: entry.endedAt ? {
							...baseView,
							endedAt: entry.endedAt
						} : baseView
					};
				};
				const active = runs.filter((entry) => !entry.endedAt).map((entry) => buildListEntry(entry, now - (entry.startedAt ?? entry.createdAt)));
				const recent = runs.filter((entry) => !!entry.endedAt && (entry.endedAt ?? 0) >= recentCutoff).map((entry) => buildListEntry(entry, (entry.endedAt ?? now) - (entry.startedAt ?? entry.createdAt)));
				const text = buildListText({
					active,
					recent,
					recentMinutes
				});
				return jsonResult({
					status: "ok",
					action: "list",
					requesterSessionKey: requester.requesterSessionKey,
					callerSessionKey: requester.callerSessionKey,
					callerIsSubagent: requester.callerIsSubagent,
					total: runs.length,
					active: active.map((entry) => entry.view),
					recent: recent.map((entry) => entry.view),
					text
				});
			}
			if (action === "kill") {
				const target = readStringParam(params, "target", { required: true });
				if (target === "all" || target === "*") {
					const cache = /* @__PURE__ */ new Map();
					const seenChildSessionKeys = /* @__PURE__ */ new Set();
					const killedLabels = [];
					let killed = 0;
					for (const entry of runs) {
						const childKey = entry.childSessionKey?.trim();
						if (!childKey || seenChildSessionKeys.has(childKey)) continue;
						seenChildSessionKeys.add(childKey);
						if (!entry.endedAt) {
							if ((await killSubagentRun({
								cfg,
								entry,
								cache
							})).killed) {
								killed += 1;
								killedLabels.push(resolveSubagentLabel(entry));
							}
						}
						const cascade = await cascadeKillChildren({
							cfg,
							parentChildSessionKey: childKey,
							cache,
							seenChildSessionKeys
						});
						killed += cascade.killed;
						killedLabels.push(...cascade.labels);
					}
					return jsonResult({
						status: "ok",
						action: "kill",
						target: "all",
						killed,
						labels: killedLabels,
						text: killed > 0 ? `killed ${killed} subagent${killed === 1 ? "" : "s"}.` : "no running subagents to kill."
					});
				}
				const resolved = resolveSubagentTarget(runs, target, { recentMinutes });
				if (!resolved.entry) return jsonResult({
					status: "error",
					action: "kill",
					target,
					error: resolved.error ?? "Unknown subagent target."
				});
				const killCache = /* @__PURE__ */ new Map();
				const stopResult = await killSubagentRun({
					cfg,
					entry: resolved.entry,
					cache: killCache
				});
				const seenChildSessionKeys = /* @__PURE__ */ new Set();
				const targetChildKey = resolved.entry.childSessionKey?.trim();
				if (targetChildKey) seenChildSessionKeys.add(targetChildKey);
				const cascade = await cascadeKillChildren({
					cfg,
					parentChildSessionKey: resolved.entry.childSessionKey,
					cache: killCache,
					seenChildSessionKeys
				});
				if (!stopResult.killed && cascade.killed === 0) return jsonResult({
					status: "done",
					action: "kill",
					target,
					runId: resolved.entry.runId,
					sessionKey: resolved.entry.childSessionKey,
					text: `${resolveSubagentLabel(resolved.entry)} is already finished.`
				});
				const cascadeText = cascade.killed > 0 ? ` (+ ${cascade.killed} descendant${cascade.killed === 1 ? "" : "s"})` : "";
				return jsonResult({
					status: "ok",
					action: "kill",
					target,
					runId: resolved.entry.runId,
					sessionKey: resolved.entry.childSessionKey,
					label: resolveSubagentLabel(resolved.entry),
					cascadeKilled: cascade.killed,
					cascadeLabels: cascade.killed > 0 ? cascade.labels : void 0,
					text: stopResult.killed ? `killed ${resolveSubagentLabel(resolved.entry)}${cascadeText}.` : `killed ${cascade.killed} descendant${cascade.killed === 1 ? "" : "s"} of ${resolveSubagentLabel(resolved.entry)}.`
				});
			}
			if (action === "steer") {
				const target = readStringParam(params, "target", { required: true });
				const message = readStringParam(params, "message", { required: true });
				if (message.length > MAX_STEER_MESSAGE_CHARS) return jsonResult({
					status: "error",
					action: "steer",
					target,
					error: `Message too long (${message.length} chars, max ${MAX_STEER_MESSAGE_CHARS}).`
				});
				const resolved = resolveSubagentTarget(runs, target, { recentMinutes });
				if (!resolved.entry) return jsonResult({
					status: "error",
					action: "steer",
					target,
					error: resolved.error ?? "Unknown subagent target."
				});
				if (resolved.entry.endedAt) return jsonResult({
					status: "done",
					action: "steer",
					target,
					runId: resolved.entry.runId,
					sessionKey: resolved.entry.childSessionKey,
					text: `${resolveSubagentLabel(resolved.entry)} is already finished.`
				});
				if (requester.callerIsSubagent && requester.callerSessionKey === resolved.entry.childSessionKey) return jsonResult({
					status: "forbidden",
					action: "steer",
					target,
					runId: resolved.entry.runId,
					sessionKey: resolved.entry.childSessionKey,
					error: "Subagents cannot steer themselves."
				});
				const rateKey = `${requester.callerSessionKey}:${resolved.entry.childSessionKey}`;
				const now = Date.now();
				if (now - (steerRateLimit.get(rateKey) ?? 0) < STEER_RATE_LIMIT_MS) return jsonResult({
					status: "rate_limited",
					action: "steer",
					target,
					runId: resolved.entry.runId,
					sessionKey: resolved.entry.childSessionKey,
					error: "Steer rate limit exceeded. Wait a moment before sending another steer."
				});
				steerRateLimit.set(rateKey, now);
				markSubagentRunForSteerRestart(resolved.entry.runId);
				const targetSession = resolveSessionEntryForKey({
					cfg,
					key: resolved.entry.childSessionKey,
					cache: /* @__PURE__ */ new Map()
				});
				const sessionId = typeof targetSession.entry?.sessionId === "string" && targetSession.entry.sessionId.trim() ? targetSession.entry.sessionId.trim() : void 0;
				if (sessionId) abortEmbeddedPiRun(sessionId);
				const cleared = clearSessionQueues([resolved.entry.childSessionKey, sessionId]);
				if (cleared.followupCleared > 0 || cleared.laneCleared > 0) logVerbose(`subagents tool steer: cleared followups=${cleared.followupCleared} lane=${cleared.laneCleared} keys=${cleared.keys.join(",")}`);
				try {
					await callGateway({
						method: "agent.wait",
						params: {
							runId: resolved.entry.runId,
							timeoutMs: STEER_ABORT_SETTLE_TIMEOUT_MS
						},
						timeoutMs: STEER_ABORT_SETTLE_TIMEOUT_MS + 2e3
					});
				} catch {}
				const idempotencyKey = crypto.randomUUID();
				let runId = idempotencyKey;
				try {
					const response = await callGateway({
						method: "agent",
						params: {
							message,
							sessionKey: resolved.entry.childSessionKey,
							sessionId,
							idempotencyKey,
							deliver: false,
							channel: INTERNAL_MESSAGE_CHANNEL,
							lane: AGENT_LANE_SUBAGENT,
							timeout: 0
						},
						timeoutMs: 1e4
					});
					if (typeof response?.runId === "string" && response.runId) runId = response.runId;
				} catch (err) {
					clearSubagentRunSteerRestart(resolved.entry.runId);
					const error = err instanceof Error ? err.message : String(err);
					return jsonResult({
						status: "error",
						action: "steer",
						target,
						runId,
						sessionKey: resolved.entry.childSessionKey,
						sessionId,
						error
					});
				}
				replaceSubagentRunAfterSteer({
					previousRunId: resolved.entry.runId,
					nextRunId: runId,
					fallback: resolved.entry,
					runTimeoutSeconds: resolved.entry.runTimeoutSeconds ?? 0
				});
				return jsonResult({
					status: "accepted",
					action: "steer",
					target,
					runId,
					sessionKey: resolved.entry.childSessionKey,
					sessionId,
					mode: "restart",
					label: resolveSubagentLabel(resolved.entry),
					text: `steered ${resolveSubagentLabel(resolved.entry)}.`
				});
			}
			if (action === "orchestrate") {
				const mode = readStringParam(params, "mode");
				if (mode !== "parallel" && mode !== "pipeline") return jsonResult({
					status: "error",
					action: "orchestrate",
					error: "mode is required and must be 'parallel' or 'pipeline'."
				});
				const tasksRaw = params.tasks;
				const stagesRaw = params.stages;
				if (mode === "parallel" && (!tasksRaw || tasksRaw.length === 0)) return jsonResult({
					status: "error",
					action: "orchestrate",
					error: "tasks array is required for parallel mode."
				});
				if (mode === "pipeline" && (!stagesRaw || stagesRaw.length === 0)) return jsonResult({
					status: "error",
					action: "orchestrate",
					error: "stages array is required for pipeline mode."
				});
				let totalTaskCount = 0;
				const allTasksList = [];
				if (mode === "parallel" && tasksRaw) {
					totalTaskCount = tasksRaw.length;
					allTasksList.push(...tasksRaw);
				} else if (mode === "pipeline" && stagesRaw) for (const stage of stagesRaw) {
					totalTaskCount += stage.tasks.length;
					allTasksList.push(...stage.tasks);
				}
				if (totalTaskCount > MAX_TASKS_PER_ORCHESTRATION) return jsonResult({
					status: "error",
					action: "orchestrate",
					error: `Too many tasks (${totalTaskCount}). Maximum is ${MAX_TASKS_PER_ORCHESTRATION} per orchestrate call.`
				});
				const now = Date.now();
				const windowStart = now - 6e4;
				while (orchestrateRateWindow.length > 0 && orchestrateRateWindow[0] < windowStart) orchestrateRateWindow.shift();
				if (orchestrateRateWindow.length >= RATE_LIMIT_PER_MINUTE) return jsonResult({
					status: "rate_limited",
					action: "orchestrate",
					error: `Orchestrate rate limit exceeded (max ${RATE_LIMIT_PER_MINUTE}/minute). Wait before starting another orchestration.`
				});
				orchestrateRateWindow.push(now);
				const callerDepth = getSubagentDepthFromSessionStore(requester.callerSessionKey, { cfg });
				const maxSpawnDepth = cfg.agents?.defaults?.subagents?.maxSpawnDepth ?? 2;
				if (callerDepth + 1 >= maxSpawnDepth) return jsonResult({
					status: "forbidden",
					action: "orchestrate",
					error: `Insufficient spawn depth for orchestration (current: ${callerDepth}, max: ${maxSpawnDepth}). Workers need at least 1 level.`
				});
				for (const task of allTasksList) if (task.template) {
					if (!getTemplate(task.template)) return jsonResult({
						status: "error",
						action: "orchestrate",
						error: `Template "${task.template}" not found for task "${task.label}".`
					});
				}
				const agentId = parseAgentSessionKey(requester.callerSessionKey)?.agentId ?? "main";
				const agentWorkspace = resolveAgentWorkspaceDir(cfg, agentId);
				const spawnCtx = { agentSessionKey: opts?.agentSessionKey };
				const spawnFn = async (task, outputDir) => {
					const startMs = performance.now();
					try {
						const result = await spawnSubagentDirect({
							task: task.prompt,
							label: task.label,
							template: task.template,
							model: task.model,
							runTimeoutSeconds: task.timeoutSeconds,
							cleanup: "keep"
						}, spawnCtx);
						if (result.status === "error" || result.status === "forbidden") return {
							label: task.label,
							index: task.index ?? 0,
							status: "failed",
							error: result.error ?? "Spawn failed",
							durationMs: Math.round(performance.now() - startMs),
							childSessionKey: result.childSessionKey,
							runId: result.runId,
							template: task.template
						};
						const waitTimeoutMs = (task.timeoutSeconds ?? 300) * 1e3;
						try {
							const waitResult = await callGateway({
								method: "agent.wait",
								params: {
									runId: result.runId,
									timeoutMs: waitTimeoutMs
								},
								timeoutMs: waitTimeoutMs + 1e4
							});
							const durationMs = Math.round(performance.now() - startMs);
							const statusJson = readStatusJson(outputDir);
							if (waitResult?.status === "error") return {
								label: task.label,
								index: task.index ?? 0,
								status: "failed",
								error: waitResult.error ?? "Subagent failed",
								durationMs,
								childSessionKey: result.childSessionKey,
								runId: result.runId,
								template: task.template
							};
							if (waitResult?.status === "timeout") return {
								label: task.label,
								index: task.index ?? 0,
								status: "timeout",
								error: "Subagent timed out",
								durationMs,
								childSessionKey: result.childSessionKey,
								runId: result.runId,
								template: task.template
							};
							return {
								label: task.label,
								index: task.index ?? 0,
								status: "completed",
								resultText: statusJson?.summary ?? "Completed",
								durationMs,
								childSessionKey: result.childSessionKey,
								runId: result.runId,
								template: task.template
							};
						} catch {
							return {
								label: task.label,
								index: task.index ?? 0,
								status: "timeout",
								error: "Subagent wait timed out",
								durationMs: Math.round(performance.now() - startMs),
								childSessionKey: result.childSessionKey,
								runId: result.runId,
								template: task.template
							};
						}
					} catch (err) {
						return {
							label: task.label,
							index: task.index ?? 0,
							status: "failed",
							error: err instanceof Error ? err.message : String(err),
							durationMs: Math.round(performance.now() - startMs),
							template: task.template
						};
					}
				};
				const orchestrationContext = {
					agentWorkspace,
					agentId,
					requesterSessionKey: requester.requesterSessionKey
				};
				const orchestrationConfig = {
					mode,
					tasks: mode === "parallel" ? tasksRaw : void 0,
					stages: mode === "pipeline" ? stagesRaw : void 0,
					maxConcurrency: readNumberParam(params, "maxConcurrency") ?? void 0,
					onFailure: readStringParam(params, "onFailure"),
					maxRetries: readNumberParam(params, "maxRetries") ?? void 0,
					maxTotalTokens: readNumberParam(params, "maxTotalTokens") ?? void 0,
					aggregationPrompt: readStringParam(params, "aggregationPrompt") ?? void 0,
					aggregationTemplate: readStringParam(params, "aggregationTemplate") ?? void 0,
					dryRun: params.dryRun === true,
					orchestrationId: readStringParam(params, "orchestrationId") ?? void 0
				};
				let orchestrationResult;
				if (mode === "parallel") orchestrationResult = await executeOrchestration(orchestrationConfig, spawnFn, orchestrationContext);
				else orchestrationResult = await executePipeline(orchestrationConfig, spawnFn, orchestrationContext);
				if (orchestrationConfig.aggregationPrompt && orchestrationResult.tasks.length > 0) {
					const orchDir = path$1.join(agentWorkspace, "orchestrations", orchestrationResult.orchestrationId);
					const aggregationText = await runAggregation({
						aggregationPrompt: orchestrationConfig.aggregationPrompt,
						results: orchestrationResult.tasks,
						orchestrationDir: orchDir,
						spawnFn,
						aggregationTemplate: orchestrationConfig.aggregationTemplate
					});
					if (aggregationText) orchestrationResult.aggregationResult = aggregationText;
				}
				return jsonResult({
					status: "ok",
					action: "orchestrate",
					orchestrationId: orchestrationResult.orchestrationId,
					mode: orchestrationResult.mode,
					orchestrationStatus: orchestrationResult.status,
					taskCount: orchestrationResult.tasks.length,
					completedCount: orchestrationResult.tasks.filter((t) => t.status === "completed").length,
					failedCount: orchestrationResult.tasks.filter((t) => t.status === "failed" || t.status === "timeout").length,
					totalDurationMs: orchestrationResult.totalDurationMs,
					tokensUsed: orchestrationResult.tokensUsed,
					aggregationResult: orchestrationResult.aggregationResult ?? void 0,
					tasks: orchestrationResult.tasks.map((t) => ({
						label: t.label,
						status: t.status,
						resultText: t.resultText,
						error: t.error,
						durationMs: t.durationMs,
						template: t.template
					}))
				});
			}
			if (action === "gather") {
				const orchestrationId = readStringParam(params, "orchestrationId");
				if (!orchestrationId) return jsonResult({
					status: "error",
					action: "gather",
					error: "orchestrationId is required for gather action."
				});
				const agentWorkspace = resolveAgentWorkspaceDir(cfg, parseAgentSessionKey(requester.callerSessionKey)?.agentId ?? "main");
				const orchestrationDir = path$1.join(agentWorkspace, "orchestrations", orchestrationId);
				if (!readManifest(orchestrationDir)) return jsonResult({
					status: "error",
					action: "gather",
					orchestrationId,
					error: `Orchestration "${orchestrationId}" not found.`
				});
				const gatherResult = gatherOrchestrationResults({
					orchestrationDir,
					orchestrationId,
					template: readStringParam(params, "template") ?? void 0,
					label: readStringParam(params, "label") ?? void 0,
					includeRunning: params.includeRunning === true,
					cleanup: params.cleanup === true,
					runs
				});
				return jsonResult({
					status: "ok",
					action: "gather",
					orchestrationId: gatherResult.orchestrationId,
					orchestrationStatus: gatherResult.status,
					mode: gatherResult.mode,
					startedAt: gatherResult.startedAt,
					completedAt: gatherResult.completedAt,
					taskCount: gatherResult.taskCount,
					tasks: gatherResult.tasks,
					interrupted: gatherResult.interrupted,
					completedTasks: gatherResult.completedTasks,
					incompleteTasks: gatherResult.incompleteTasks,
					canResume: gatherResult.canResume
				});
			}
			if (action === "orchestrations") {
				const agentWorkspace = resolveAgentWorkspaceDir(cfg, parseAgentSessionKey(requester.callerSessionKey)?.agentId ?? "main");
				const orchestrationsDir = path$1.join(agentWorkspace, "orchestrations");
				if (!fs$1.existsSync(orchestrationsDir)) return jsonResult({
					status: "ok",
					action: "orchestrations",
					orchestrations: [],
					total: 0
				});
				const statusFilter = readStringParam(params, "status") ?? void 0;
				const sinceFilter = readNumberParam(params, "since") ?? void 0;
				const untilFilter = readNumberParam(params, "until") ?? void 0;
				const entries = fs$1.readdirSync(orchestrationsDir, { withFileTypes: true });
				const orchestrations = [];
				for (const entry of entries) {
					if (!entry.isDirectory()) continue;
					const manifest = readManifest(path$1.join(orchestrationsDir, entry.name));
					if (!manifest) continue;
					if (statusFilter && manifest.status !== statusFilter) continue;
					if (sinceFilter && manifest.startedAt < sinceFilter) continue;
					if (untilFilter && manifest.startedAt > untilFilter) continue;
					orchestrations.push({
						orchestrationId: manifest.orchestrationId,
						status: manifest.status,
						mode: manifest.mode,
						taskCount: manifest.taskCount,
						startedAt: manifest.startedAt,
						completedAt: manifest.completedAt
					});
				}
				orchestrations.sort((a, b) => b.startedAt - a.startedAt);
				return jsonResult({
					status: "ok",
					action: "orchestrations",
					orchestrations,
					total: orchestrations.length
				});
			}
			return jsonResult({
				status: "error",
				error: "Unsupported action."
			});
		}
	};
}

//#endregion
export { createSubagentsTool };