// @generated by scripts/build-runtime.mjs; do not edit. // @ts-nocheck -- the generated entry uses a .ts extension for Pi's Jiti loader. // src/ui/conversation-viewer.ts import { getMarkdownTheme } from "@earendil-works/pi-coding-agent"; import { Input, Markdown, matchesKey as matchesKey2, ScrollView, stripTerminalSequences as stripTerminalSequences2, truncateToWidth as truncateToWidth3, visibleWidth as visibleWidth2, wrapTextWithAnsi as wrapTextWithAnsi2 } from "@earendil-works/pi-tui"; // src/agent-types.ts import { createCodingTools, createReadOnlyTools } from "@earendil-works/pi-coding-agent"; // src/default-agents.ts var READ_ONLY_SURFACE = { builtinToolNames: ["read", "grep", "find", "ls"], extensions: false, skills: true }; var DEFAULT_AGENTS = /* @__PURE__ */ new Map([ [ "general-purpose", { name: "general-purpose", displayName: "Agent", description: "General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.", // builtinToolNames omitted — means "all available tools" (resolved at lookup time) // inheritContext / runInBackground / isolated omitted — strategy fields, callers decide per-call. // Setting them to false would lock callsite intent (see resolveAgentInvocationConfig in invocation-config.ts). extensions: true, skills: true, systemPrompt: "", promptMode: "append", isDefault: true } ], [ "Explore", { name: "Explore", displayName: "Explore", description: 'Fast read-only search agent for locating code. Use it to find files by pattern (eg. "src/components/**/*.tsx"), grep for symbols or keywords (eg. "API endpoints"), or answer "where is X defined / which files reference Y." Do NOT use it for code review, design-doc auditing, cross-file consistency checks, or open-ended analysis \u2014 it reads excerpts rather than whole files and will miss content past its read window. When calling, specify search breadth: "quick" for a single targeted lookup, "medium" for moderate exploration, or "very thorough" to search across multiple locations and naming conventions.', ...READ_ONLY_SURFACE, // Bind the role per machine, not to a provider or model generation. model: "@cheap", systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS You are a file search specialist. You excel at thoroughly navigating and exploring codebases. Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools. You are STRICTLY PROHIBITED from: - Creating new files - Modifying existing files - Deleting files - Moving or copying files - Creating temporary files anywhere, including /tmp - Using redirect operators (>, >>, |) or heredocs to write to files - Running ANY commands that change system state # Tool Usage - Use the find tool for file pattern matching - Use the grep tool for content search - Use the read tool for reading files - Make independent tool calls in parallel for efficiency - Adapt search approach based on thoroughness level specified # Output - Use absolute file paths in all references - Report findings as regular messages - Do not use emojis - Be thorough and precise`, promptMode: "replace", isDefault: true } ], [ "Plan", { name: "Plan", displayName: "Plan", description: "Software architect agent for designing implementation plans. Use this when you need to plan the implementation strategy for a task. Returns step-by-step plans, identifies critical files, and considers architectural trade-offs.", ...READ_ONLY_SURFACE, systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS You are a software architect and planning specialist. Your role is EXCLUSIVELY to explore the codebase and design implementation plans. You do NOT have access to file editing tools \u2014 attempting to edit files will fail. You are STRICTLY PROHIBITED from: - Creating new files - Modifying existing files - Deleting files - Moving or copying files - Creating temporary files anywhere, including /tmp - Using redirect operators (>, >>, |) or heredocs to write to files - Running ANY commands that change system state # Planning Process 1. Understand requirements 2. Explore thoroughly (read files, find patterns, understand architecture) 3. Design solution based on your assigned perspective 4. Detail the plan with step-by-step implementation strategy # Requirements - Consider trade-offs and architectural decisions - Identify dependencies and sequencing - Anticipate potential challenges - Follow existing patterns where appropriate # Tool Usage - Use the find tool for file pattern matching - Use the grep tool for content search - Use the read tool for reading files # Output Format - Use absolute file paths - Do not use emojis - End your response with: ### Critical Files for Implementation List 3-5 files most critical for implementing this plan: - /absolute/path/to/file.ts - [Brief reason]`, promptMode: "replace", isDefault: true } ] ]); // src/agent-types.ts var BUILTIN_TOOL_NAMES = [ ...new Set([...createCodingTools("."), ...createReadOnlyTools(".")].map((t) => t.name)) ]; var agents = /* @__PURE__ */ new Map(); var disableDefaults = false; function isDefaultsDisabled() { return disableDefaults; } function setDefaultsDisabled(b) { disableDefaults = b; } var NO_FALLBACK = "none"; var fallbackSubagent; function getFallbackSubagent() { return fallbackSubagent; } function setFallbackSubagent(v) { fallbackSubagent = v; } function buildAgentRegistry(userAgents) { const registry = /* @__PURE__ */ new Map(); if (!disableDefaults) { for (const [name, config] of DEFAULT_AGENTS) registry.set(name, config); } for (const [name, config] of userAgents) registry.set(name, config); return registry; } function registerAgents(userAgents) { agents.clear(); for (const [name, config] of buildAgentRegistry(userAgents)) { agents.set(name, config); } } function resolveKeyIn(registry, name) { if (registry.has(name)) return name; const lower = name.toLowerCase(); for (const key of registry.keys()) { if (key.toLowerCase() === lower) return key; } return void 0; } function resolveKey(name) { return resolveKeyIn(agents, name); } function resolveTypeIn(registry, name) { return resolveKeyIn(registry, name); } function getAgentConfigIn(registry, name) { const key = resolveKeyIn(registry, name); return key ? registry.get(key) : void 0; } function getAvailableTypesIn(registry) { return [...registry.entries()].filter(([_, config]) => config.enabled !== false).map(([name]) => name); } function resolveUnambiguousKeyIn(registry, name) { if (registry.has(name)) return name; const lower = name.toLowerCase(); const matches = [...registry.keys()].filter((key) => key.toLowerCase() === lower); return matches.length === 1 ? matches[0] : void 0; } function resolveEnabledTypeIn(registry, requested) { const raw = typeof requested === "string" ? requested.trim() : ""; if (!raw) return void 0; const key = resolveUnambiguousKeyIn(registry, raw); return key !== void 0 && registry.get(key)?.enabled !== false ? key : void 0; } function resolveSpawnTypeIn(registry, requested) { const raw = typeof requested === "string" ? requested.trim() : ""; const available = () => getAvailableTypesIn(registry).join(", ") || "(none)"; const key = resolveEnabledTypeIn(registry, raw); if (key !== void 0) return { ok: true, type: key }; const reason = raw ? `Unknown or disabled agent type: "${raw}".` : "No agent type given."; const configured = typeof fallbackSubagent === "string" ? fallbackSubagent.trim() : void 0; if (configured !== void 0 && configured.toLowerCase() === NO_FALLBACK) { return { ok: false, message: `${reason} Available: ${available()}.` }; } if (configured !== void 0) { const fallbackKey = resolveUnambiguousKeyIn(registry, configured); if (fallbackKey === void 0 || registry.get(fallbackKey)?.enabled === false) { return { ok: false, message: `${reason} The configured fallbackSubagent "${configured}" is itself unknown or disabled. Available: ${available()}.` }; } return { ok: true, type: fallbackKey, fellBackFrom: raw }; } return { ok: true, type: "general-purpose", fellBackFrom: raw }; } function resolveSpawnType(requested) { return resolveSpawnTypeIn(agents, requested); } function resolveType(name) { return resolveKey(name); } function getAgentConfig(name) { return getAgentConfigIn(agents, name); } function getAvailableTypes() { return getAvailableTypesIn(agents); } function getAllTypes() { return [...agents.keys()]; } var MEMORY_TOOL_NAMES = ["read", "write", "edit"]; function getMemoryToolNames(existingToolNames) { return MEMORY_TOOL_NAMES.filter((n) => !existingToolNames.has(n)); } var READONLY_MEMORY_TOOL_NAMES = ["read"]; function getReadOnlyMemoryToolNames(existingToolNames) { return READONLY_MEMORY_TOOL_NAMES.filter((n) => !existingToolNames.has(n)); } function getToolNamesForType(type) { const key = resolveKey(type); const raw = key ? agents.get(key) : void 0; const config = raw?.enabled !== false ? raw : void 0; return config?.builtinToolNames ?? [...BUILTIN_TOOL_NAMES]; } function getConfig(type) { const key = resolveKey(type); const config = key ? agents.get(key) : void 0; if (config && config.enabled !== false) { return { displayName: config.displayName ?? config.name, color: config.color, description: config.description, builtinToolNames: config.builtinToolNames ?? BUILTIN_TOOL_NAMES, extensions: config.extensions, excludeExtensions: config.excludeExtensions, skills: config.skills, promptMode: config.promptMode }; } const gp = agents.get("general-purpose"); if (gp && gp.enabled !== false) { return { displayName: gp.displayName ?? gp.name, color: gp.color, description: gp.description, builtinToolNames: gp.builtinToolNames ?? BUILTIN_TOOL_NAMES, extensions: gp.extensions, excludeExtensions: gp.excludeExtensions, skills: gp.skills, promptMode: gp.promptMode }; } return { displayName: "Agent", description: "General-purpose agent for complex, multi-step tasks", builtinToolNames: BUILTIN_TOOL_NAMES, extensions: true, skills: true, promptMode: "append" }; } // src/agent-color.ts var NAMED_AGENT_COLORS = { // Claude Code's eight subagent colors, as its default theme renders them. red: "#DC2626", blue: "#6A9BCC", green: "#16A34A", yellow: "#CA8A04", purple: "#827DBD", orange: "#D97757", pink: "#C46686", cyan: "#0891B2", // Agency Agents palette aliases. amber: "#F59E0B", teal: "#008080", indigo: "#6366F1", gold: "#EAB308", "neon-green": "#10B981", "neon-cyan": "#06B6D4", "metallic-blue": "#3B82F6", violet: "#8B5CF6", rose: "#F43F5E", lime: "#84CC16", gray: "#6B7280", grey: "#6B7280", fuchsia: "#D946EF", slate: "#64748B", navy: "#1E3A8A" }; var CUBE_VALUES = [0, 95, 135, 175, 215, 255]; var GRAY_VALUES = Array.from({ length: 24 }, (_, i) => 8 + i * 10); var BLACK = { r: 0, g: 0, b: 0 }; var WHITE = { r: 255, g: 255, b: 255 }; function resolveAgentColor(value) { if (!value) return void 0; const normalized = value.trim().toLowerCase(); const resolved2 = NAMED_AGENT_COLORS[normalized] ?? normalized; return /^#[0-9a-f]{6}$/i.test(resolved2) ? resolved2.toUpperCase() : void 0; } function parseHex(hex) { return { r: Number.parseInt(hex.slice(1, 3), 16), g: Number.parseInt(hex.slice(3, 5), 16), b: Number.parseInt(hex.slice(5, 7), 16) }; } function nearest(values, value) { return values.reduce((best, v, i) => Math.abs(value - v) < Math.abs(value - values[best]) ? i : best, 0); } function rgbTo256({ r, g, b }) { const [rIndex, gIndex, bIndex] = [r, g, b].map((channel) => nearest(CUBE_VALUES, channel)); const distance = ({ r: cr, g: cg, b: cb }) => 0.299 * (r - cr) ** 2 + 0.587 * (g - cg) ** 2 + 0.114 * (b - cb) ** 2; const grayIndex = nearest(GRAY_VALUES, Math.round(0.299 * r + 0.587 * g + 0.114 * b)); const gray = { r: GRAY_VALUES[grayIndex], g: GRAY_VALUES[grayIndex], b: GRAY_VALUES[grayIndex] }; const cube = { r: CUBE_VALUES[rIndex], g: CUBE_VALUES[gIndex], b: CUBE_VALUES[bIndex] }; if (Math.max(r, g, b) - Math.min(r, g, b) < 10 && distance(gray) < distance(cube)) { return { index: 232 + grayIndex, rgb: gray }; } return { index: 16 + 36 * rIndex + 6 * gIndex + bIndex, rgb: cube }; } function ansiColor(layer, color) { const code = layer === "foreground" ? 38 : 48; return typeof color === "number" ? `\x1B[${code};5;${color}m` : `\x1B[${code};2;${color.r};${color.g};${color.b}m`; } function relativeLuminance({ r, g, b }) { const linear = (value) => { const channel = value / 255; return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4; }; return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b); } function renderAgentNameLabel(name, color, theme, style = {}) { const resolved2 = resolveAgentColor(color); if (!resolved2) { const text = style.bold ? theme.bold(name) : name; return style.fallbackColor ? theme.fg(style.fallbackColor, text) : text; } const rgb = parseHex(resolved2); const quantized = (theme.getColorMode?.() ?? "truecolor") === "256color" ? rgbTo256(rgb) : void 0; const shown = quantized?.rgb ?? rgb; const contrasting = relativeLuminance(shown) > 0.179 ? BLACK : WHITE; const label = style.bold ? theme.bold(` ${name} `) : ` ${name} `; return ansiColor("background", quantized?.index ?? rgb) + ansiColor("foreground", quantized ? rgbTo256(contrasting).index : contrasting) + label + "\x1B[39m" + (style.restoreBackground ?? "\x1B[49m"); } function hasAgentBadge(type) { return type !== void 0 && resolveAgentColor(getConfig(type).color) !== void 0; } function renderAgentName(type, theme, style = {}) { if (!type) return renderAgentNameLabel("Agent", void 0, theme, style); const config = getConfig(type); return renderAgentNameLabel(config.displayName, config.color, theme, style); } // src/clock.ts var realClock = { now: () => Date.now(), setTimeout(callback, ms) { const timer = setTimeout(callback, ms); return { cancel: () => clearTimeout(timer) }; }, setInterval(callback, ms) { const timer = setInterval(callback, ms); return { cancel: () => clearInterval(timer), unref: () => { timer.unref(); } }; } }; // src/context.ts function extractText(content) { return content.filter((c) => c.type === "text").map((c) => c.text ?? "").join("\n"); } function buildParentContext(ctx) { const entries = ctx.sessionManager.getBranch(); if (!entries || entries.length === 0) return ""; const parts = []; for (const entry of entries) { if (entry.type === "message") { const msg = entry.message; if (msg.role === "user") { const text = typeof msg.content === "string" ? msg.content : extractText(msg.content); if (text.trim()) parts.push(`[User]: ${text.trim()}`); } else if (msg.role === "assistant") { const text = extractText(msg.content); if (text.trim()) parts.push(`[Assistant]: ${text.trim()}`); } } else if (entry.type === "compaction") { if (entry.summary) { parts.push(`[Summary]: ${entry.summary}`); } } } if (parts.length === 0) return ""; return `# Parent Conversation Context The following is the conversation history from the parent session that spawned you. Use this context to understand what has been discussed and decided so far. ${parts.join("\n\n")} --- # Your Task (below) `; } // src/usage.ts function getLifetimeTotal(u) { return u ? u.input + u.output + u.cacheWrite : 0; } function getLifetimeCost(u) { return u?.cost ?? 0; } function addUsage(into, delta) { into.input += delta.input; into.output += delta.output; into.cacheWrite += delta.cacheWrite; if (delta.cacheRead) into.cacheRead = (into.cacheRead ?? 0) + delta.cacheRead; if (delta.cost) into.cost = (into.cost ?? 0) + delta.cost; } function toReportedUsage(u) { const { input, output, cacheWrite, cacheRead = 0, cost = 0 } = u; if (input === 0 && output === 0 && cacheWrite === 0 && cacheRead === 0 && cost === 0) return void 0; return { input, output, cacheRead, cacheWrite, totalTokens: input + output + cacheRead + cacheWrite, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: cost } }; } var PendingUsagePool = class { pending = { input: 0, output: 0, cacheWrite: 0, cacheRead: 0, cost: 0 }; dirty = false; add(delta) { addUsage(this.pending, delta); this.dirty = true; } /** * Take everything accumulated so far as a pi `Usage`, resetting the pool. * Returns undefined when nothing is pending, so callers can leave the tool * result untouched rather than attaching a zero. */ drain() { if (!this.dirty) return void 0; const drained = toReportedUsage(this.pending); this.pending = { input: 0, output: 0, cacheWrite: 0, cacheRead: 0, cost: 0 }; this.dirty = false; return drained; } }; function getSessionContextPercent(session) { if (!session) return null; try { return session.getSessionStats().contextUsage?.percent ?? null; } catch { return null; } } // src/ui/agent-widget.ts import { truncateToWidth as truncateToWidth2 } from "@earendil-works/pi-tui"; // src/agent-manager.ts import { randomUUID as randomUUID2 } from "node:crypto"; import { accessSync, constants, opendirSync, statSync as statSync6 } from "node:fs"; import { isAbsolute as isAbsolute4 } from "node:path"; // src/agent-runner.ts import { readFileSync as readFileSync8 } from "node:fs"; import { homedir as homedir5 } from "node:os"; import { basename as basename3, dirname as dirname3, isAbsolute as isAbsolute3, join as join9, resolve as resolve5 } from "node:path"; import { createAgentSession, createCodemodeExtension, createMcpExtension, createToolSearchExtension, defineTool as defineTool3, SessionManager, SettingsManager as SettingsManager4 } from "@earendil-works/pi-coding-agent"; import { Type as Type3 } from "typebox"; // src/child-context.ts import { AsyncLocalStorage } from "node:async_hooks"; var contextKey = /* @__PURE__ */ Symbol.for("pi-subagents:child-session-context"); var globals = globalThis; var childSessionContext = globals[contextKey] ?? new AsyncLocalStorage(); globals[contextKey] = childSessionContext; function inChildSessionContext() { return childSessionContext.getStore() === true; } function runInChildSessionContext(fn) { return childSessionContext.run(true, fn); } function bindChildResourceLoader(loader) { const reload = loader.reload.bind(loader); loader.reload = () => runInChildSessionContext(reload); return loader; } // src/env.ts async function detectEnv(pi, cwd) { let isGitRepo = false; let branch = ""; try { const result = await pi.exec("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 5e3 }); isGitRepo = result.code === 0 && result.stdout.trim() === "true"; } catch { } if (isGitRepo) { try { const result = await pi.exec("git", ["branch", "--show-current"], { cwd, timeout: 5e3 }); branch = result.code === 0 ? result.stdout.trim() : "unknown"; } catch { branch = "unknown"; } } return { isGitRepo, branch, platform: process.platform }; } // src/home-paths.ts import { homedir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { getAgentDir } from "@earendil-works/pi-coding-agent"; function resolveAgentDir(homeDir) { if (homeDir === void 0) return getAgentDir(); const configured = process.env.PI_CODING_AGENT_DIR; if (!configured) return join(homeDir, ".pi", "agent"); return normalizeHomePath(configured, homeDir); } function normalizeHomePath(path, homeDir = homedir()) { if (process.platform === "win32" && path.startsWith("/") && !path.startsWith("//") && !path.includes("\\")) { const [, letter, remainder] = path.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i) ?? []; if (letter) path = `${letter.toUpperCase()}:\\${remainder?.replaceAll("/", "\\") ?? ""}`; } if (path === "~") return homeDir; if (path.startsWith("~/") || process.platform === "win32" && path.startsWith("~\\")) { return join(homeDir, path.slice(2)); } return path.startsWith("file://") ? fileURLToPath(path) : path; } // src/memory.ts import { existsSync, lstatSync, mkdirSync, readFileSync } from "node:fs"; import { homedir as homedir2 } from "node:os"; import { join as join2 } from "node:path"; var MAX_MEMORY_LINES = 200; function isUnsafeName(name) { if (!name || name.length > 128) return true; return !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name); } function isSymlink(filePath) { try { return lstatSync(filePath).isSymbolicLink(); } catch { return false; } } function safeReadFile(filePath) { if (!existsSync(filePath)) return void 0; if (isSymlink(filePath)) return void 0; try { return readFileSync(filePath, "utf-8"); } catch { return void 0; } } function resolveMemoryDir(agentName, scope, cwd, homeDir = homedir2()) { if (isUnsafeName(agentName)) { throw new Error(`Unsafe agent name for memory directory: "${agentName}"`); } switch (scope) { case "user": { const current = join2(resolveAgentDir(homeDir), "agent-memory", agentName); const legacy = join2(homeDir, ".pi", "agent-memory", agentName); if (!existsSync(current) && existsSync(legacy) && !isSymlink(legacy)) { return legacy; } return current; } case "project": return join2(cwd, ".pi", "agent-memory", agentName); case "local": return join2(cwd, ".pi", "agent-memory-local", agentName); } } function ensureMemoryDir(memoryDir) { if (existsSync(memoryDir)) { if (isSymlink(memoryDir)) { throw new Error(`Refusing to use symlinked memory directory: ${memoryDir}`); } return; } mkdirSync(memoryDir, { recursive: true }); } function readMemoryIndex(memoryDir) { if (isSymlink(memoryDir)) return void 0; const memoryFile = join2(memoryDir, "MEMORY.md"); const content = safeReadFile(memoryFile); if (content === void 0) return void 0; const lines = content.split("\n"); if (lines.length > MAX_MEMORY_LINES) { return lines.slice(0, MAX_MEMORY_LINES).join("\n") + "\n... (truncated at 200 lines)"; } return content; } function buildMemoryBlock(agentName, scope, cwd, homeDir = homedir2()) { const memoryDir = resolveMemoryDir(agentName, scope, cwd, homeDir); ensureMemoryDir(memoryDir); const existingMemory = readMemoryIndex(memoryDir); const header = `# Agent Memory You have a persistent memory directory at: ${memoryDir}/ Memory scope: ${scope} This memory persists across sessions. Use it to build up knowledge over time.`; const memoryContent = existingMemory ? ` ## Current MEMORY.md ${existingMemory}` : ` No MEMORY.md exists yet. Create one at ${join2(memoryDir, "MEMORY.md")} to start building persistent memory.`; const instructions = ` ## Memory Instructions - MEMORY.md is an index file \u2014 keep it concise (under 200 lines). Lines after 200 are truncated. - Store detailed memories in separate files within ${memoryDir}/ and link to them from MEMORY.md. - Each memory file should use this frontmatter format: \`\`\`markdown --- name: description: type: --- \`\`\` - Update or remove memories that become outdated. Check for existing memories before creating duplicates. - You have Read, Write, and Edit tools available for managing memory files.`; return header + memoryContent + instructions; } function buildReadOnlyMemoryBlock(agentName, scope, cwd, homeDir = homedir2()) { const memoryDir = resolveMemoryDir(agentName, scope, cwd, homeDir); const existingMemory = readMemoryIndex(memoryDir); const header = `# Agent Memory (read-only) Memory scope: ${scope} You have read-only access to memory. You can reference existing memories but cannot create or modify them.`; const memoryContent = existingMemory ? ` ## Current MEMORY.md ${existingMemory}` : ` No memory is available yet. Other agents or sessions with write access can create memories for you to consume.`; return header + memoryContent; } // src/nested-tools.ts import { defineTool } from "@earendil-works/pi-coding-agent"; import { Type as Type2 } from "typebox"; // src/abortable.ts function abortable(promise, signal) { if (!signal) return promise; if (signal.aborted) return Promise.reject(signal.reason); return new Promise((resolve6, reject) => { let settled = false; const cleanup = () => signal.removeEventListener("abort", onAbort); const onAbort = () => { settled = true; cleanup(); reject(signal.reason); }; signal.addEventListener("abort", onAbort, { once: true }); promise.then( (value) => { if (settled) return; settled = true; cleanup(); resolve6(value); }, (error) => { if (settled) return; settled = true; cleanup(); reject(error); } ); }); } // src/custom-agents.ts import { existsSync as existsSync3, readdirSync, readFileSync as readFileSync3, statSync as statSync2 } from "node:fs"; import { basename as basename2, join as join4 } from "node:path"; import { parseFrontmatter } from "@earendil-works/pi-coding-agent"; // src/error-message.ts function errorMessage(error) { return error instanceof Error ? error.message : String(error); } // src/package-resources.ts import { existsSync as existsSync2, readFileSync as readFileSync2, realpathSync, statSync } from "node:fs"; import { basename, dirname, isAbsolute, join as join3, relative, resolve, sep } from "node:path"; import { DefaultPackageManager, SettingsManager } from "@earendil-works/pi-coding-agent"; var KIND_EXTENSION = { agents: ".md", workflows: ".js" }; var MAX_PACKAGE_RESOURCE_BYTES = 1048576; var agentsGate; var workflowsGate; var projectTrustedState = false; function setPackageAgentsGate(gate) { agentsGate = gate; invalidatePackageCache(); } function setPackageWorkflowsGate(gate) { workflowsGate = gate; invalidatePackageCache(); } function getPackageAgentsGate() { return agentsGate; } function getPackageWorkflowsGate() { return workflowsGate; } function setProjectTrusted(trusted) { if (projectTrustedState === trusted) return; projectTrustedState = trusted; invalidatePackageCache(); } function isProjectTrusted() { return projectTrustedState; } function stringArray(val) { return Array.isArray(val) && val.every((e) => typeof e === "string") ? val : void 0; } function normalizeDeclaration(val) { const asArray = stringArray(val); if (asArray) return { agents: asArray }; if (!val || typeof val !== "object" || Array.isArray(val)) return void 0; const obj = val; const agents2 = stringArray(obj.agents); const workflows = stringArray(obj.workflows); if (!agents2 && !workflows) return void 0; return { agents: agents2, workflows }; } function readSubagentManifest(pkg) { if (!pkg || typeof pkg !== "object") return void 0; const obj = pkg; const piKey = obj.pi; if (piKey && typeof piKey === "object" && !Array.isArray(piKey)) { const nested = normalizeDeclaration(piKey.subagents); if (nested) return nested; } return normalizeDeclaration(obj["pi-subagents"]); } function readPackageJson(root) { try { const parsed = JSON.parse(readFileSync2(join3(root, "package.json"), "utf-8")); return parsed && typeof parsed === "object" ? parsed : void 0; } catch { return void 0; } } function unscopedShortName(name) { const short = name.startsWith("@") ? name.slice(name.indexOf("/") + 1) : name; return short.toLowerCase(); } function realOrSelf(path) { const abs = resolve(path); try { return realpathSync(abs); } catch { const parent = dirname(abs); return parent === abs ? abs : join3(realOrSelf(parent), basename(abs)); } } function isInside(root, candidate) { const rel = relative(realOrSelf(root), realOrSelf(candidate)); return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel); } function expandEntry(root, entry) { const target = resolve(root, entry); if (!isInside(root, target) || !existsSync2(target)) return void 0; return target; } function resolveDeclaredPaths(root, entries, kind) { const dirs = []; const files = []; const excluded = /* @__PURE__ */ new Set(); if (!entries) return { dirs, files, excluded }; for (const entry of entries) { if (!entry.startsWith("!")) continue; const target = resolve(root, entry.slice(1)); if (isInside(root, target)) excluded.add(realOrSelf(target)); } const ext = KIND_EXTENSION[kind]; for (const entry of entries) { if (entry.startsWith("!")) continue; const path = expandEntry(root, entry); if (!path || excluded.has(realOrSelf(path))) continue; let stat; try { stat = statSync(path); } catch { continue; } if (stat.isDirectory()) { if (!dirs.includes(path)) dirs.push(path); } else if (stat.isFile() && path.endsWith(ext) && !files.includes(path)) { files.push(path); } } return { dirs, files, excluded }; } function configuredPackages(cwd, projectTrusted, homeDir) { try { if (typeof DefaultPackageManager !== "function") return []; const agentDir = resolveAgentDir(homeDir); const settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted }); const manager = new DefaultPackageManager({ cwd, agentDir, settingsManager }); if (typeof manager.listConfiguredPackages !== "function") return []; if (homeDir === void 0) return manager.listConfiguredPackages(); const rows = []; for (const scope of ["user", "project"]) { const settings = scope === "user" ? settingsManager.getGlobalSettings() : settingsManager.getProjectSettings(); for (const pkg of settings.packages ?? []) { const source = typeof pkg === "string" ? pkg : pkg.source; rows.push({ source, scope, installedPath: manager.getInstalledPath(normalizeHomePath(source, homeDir), scope) }); } } return rows; } catch { return []; } } function listPiPackages(cwd, projectTrusted = false, homeDir) { const seen = /* @__PURE__ */ new Set(); const out = []; for (const entry of configuredPackages(cwd, projectTrusted, homeDir)) { const root = entry.installedPath; if (!root || seen.has(root)) continue; const manifest = readPackageJson(root); const declared = manifest ? readSubagentManifest(manifest) : void 0; if (!manifest || !declared) continue; seen.add(root); const name = typeof manifest.name === "string" ? manifest.name : void 0; out.push({ source: entry.source, name, shortName: name ? unscopedShortName(name) : void 0, scope: entry.scope, root, declared }); } return out; } function packageAllowed(pkg, gate) { if (gate === false) return false; if (gate === void 0 || gate === true) return true; const candidates = new Set( [pkg.shortName, pkg.name?.toLowerCase(), pkg.source.toLowerCase()].filter( (v) => typeof v === "string" ) ); return gate.some((allowed) => candidates.has(allowed.trim().toLowerCase())); } function emptyPaths() { return { dirs: [], files: [], excluded: /* @__PURE__ */ new Set() }; } function emptyEntry() { return { agents: emptyPaths(), workflows: emptyPaths(), owners: [] }; } var cache = /* @__PURE__ */ new Map(); function invalidatePackageCache() { cache.clear(); } function scan(cwd, projectTrusted, gate, homeDir) { const entry = emptyEntry(); for (const pkg of listPiPackages(cwd, projectTrusted, homeDir)) { if (!packageAllowed(pkg, gate)) continue; entry.owners.push({ root: resolve(pkg.root), name: pkg.name ?? pkg.shortName ?? pkg.source }); for (const kind of ["agents", "workflows"]) { const resolvedPaths = resolveDeclaredPaths(pkg.root, pkg.declared[kind], kind); entry[kind].dirs.push(...resolvedPaths.dirs); entry[kind].files.push(...resolvedPaths.files); for (const path of resolvedPaths.excluded) entry[kind].excluded.add(path); } } entry.owners.sort((a, b) => b.root.length - a.root.length); return entry; } function cacheEntryFor(cwd, kind, opts) { const gate = opts.gate ?? (kind === "agents" ? agentsGate : workflowsGate); if (gate === false || Array.isArray(gate) && gate.length === 0) return emptyEntry(); const projectTrusted = opts.projectTrusted ?? projectTrustedState; const key = `${cwd}\0${opts.homeDir ?? ""}\0${resolveAgentDir(opts.homeDir)}\0${projectTrusted ? 1 : 0}\0${JSON.stringify(gate ?? true)}`; let hit = cache.get(key); if (!hit) { hit = scan(cwd, projectTrusted, gate, opts.homeDir); cache.set(key, hit); } return hit; } function resolved(cwd, kind, opts) { return cacheEntryFor(cwd, kind, opts)[kind]; } function packageNameForPath(path, cwd, kind = "agents", opts = {}) { const abs = resolve(path); return cacheEntryFor(cwd, kind, opts).owners.find( (o) => abs === o.root || abs.startsWith(o.root + sep) )?.name; } function packageAgentDirs(cwd, opts = {}) { return [...resolved(cwd, "agents", opts).dirs]; } function packageAgentFiles(cwd, opts = {}) { return [...resolved(cwd, "agents", opts).files]; } function isPackageResourceExcluded(path, cwd, kind, opts = {}) { const excluded = resolved(cwd, kind, opts).excluded; return excluded.size > 0 && excluded.has(realOrSelf(path)); } function packageWorkflowDirs(cwd, opts = {}) { return [...resolved(cwd, "workflows", opts).dirs]; } function packageWorkflowFiles(cwd, opts = {}) { const out = /* @__PURE__ */ new Map(); for (const path of resolved(cwd, "workflows", opts).files) { const name = basename(path, KIND_EXTENSION.workflows); if (!out.has(name)) out.set(name, path); } return out; } // src/custom-agents.ts var RESERVED_IN_TYPE = ":"; function loadCustomAgents(cwd, strict = false, opts = {}) { const globalDir = join4(resolveAgentDir(opts.homeDir), "agents"); const workspaceProjectDir = join4(cwd, ".agents", "agents"); const projectDir = join4(cwd, ".pi", "agents"); const projectTrusted = opts.projectTrusted ?? isProjectTrusted(); const discovery = { projectTrusted, homeDir: opts.homeDir }; const pkgDirs = opts.packageDirs ?? packageAgentDirs(cwd, discovery); const pkgFiles = opts.packageFiles ?? packageAgentFiles(cwd, discovery); const excluded = opts.packageExcluded ?? ((path) => isPackageResourceExcluded(path, cwd, "agents", discovery)); const agents2 = /* @__PURE__ */ new Map(); for (const dir of pkgDirs) loadFromDir(dir, agents2, "package", strict, excluded); for (const file of pkgFiles) loadOneFile(file, agents2, "package", strict); loadFromDir(globalDir, agents2, "global", strict); if (projectTrusted) { loadFromDir(workspaceProjectDir, agents2, "project", strict); loadFromDir(projectDir, agents2, "project", strict); } warnedLastLoad = warnedThisLoad; warnedThisLoad = /* @__PURE__ */ new Set(); return agents2; } function loadFromDir(dir, agents2, source, strict, excluded) { if (!existsSync3(dir)) return; let files; try { files = readdirSync(dir).filter((f) => f.endsWith(".md")); } catch { return; } for (const file of files) { const path = join4(dir, file); if (excluded?.(path)) continue; loadOneFile(path, agents2, source, strict); } } function loadOneFile(path, agents2, source, strict) { const filenameType = basename2(path, ".md"); if (source === "package" && !withinSizeLimit(path)) { warnIfNew(`Skipping package agent ${path}: not a regular file, or larger than ${MAX_PACKAGE_RESOURCE_BYTES} bytes.`); return; } const parsed = readAgentFile(path, strict && source !== "package"); if (!parsed) { warnSkippedOverride(filenameType, agents2); return; } const { frontmatter: fm, body } = parsed; const declared = str(fm.name)?.trim(); if (declared?.includes(RESERVED_IN_TYPE)) { warnIfNew( `Agent file ${path} declares name "${declared}", which contains "${RESERVED_IN_TYPE}" \u2014 reserved for plugin-scoped identifiers. Rename it, or move the label to \`display_name:\`. Skipping.` ); return; } const name = declared || filenameType; const { builtinToolNames, extSelectors } = parseToolsField(fm.tools); agents2.set(name, { name, // Only `display_name` now: `name` is the type, and `getConfig` already // falls back to the type when no label is set — so a Claude Code file // with `name: code-reviewer` still badges as "code-reviewer". displayName: str(fm.display_name), color: str(fm.color), description: str(fm.description) ?? name, builtinToolNames, extSelectors, disallowedTools: csvListOptional(fm.disallowed_tools), extensions: inheritField(fm.extensions ?? fm.inherit_extensions), excludeExtensions: csvListOptional(fm.exclude_extensions), skills: inheritField(fm.skills ?? fm.inherit_skills), model: str(fm.model), thinking: str(fm.thinking), maxTurns: nonNegativeInt(fm.max_turns), persistSession: fm.persist_session != null ? fm.persist_session === true : void 0, outputTranscript: fm.output_transcript != null ? fm.output_transcript !== false : void 0, sessionDir: str(fm.session_dir), allowedSubagents: parseAllowedSubagents(fm.allowed_subagents), systemPrompt: body.trim(), promptMode: fm.prompt_mode === "append" ? "append" : "replace", inheritContext: fm.inherit_context != null ? fm.inherit_context === true : void 0, runInBackground: fm.run_in_background != null ? fm.run_in_background === true : void 0, isolated: fm.isolated != null ? fm.isolated === true : void 0, memory: parseMemory(fm.memory), isolation: parseIsolation(fm.isolation), enabled: fm.enabled !== false, // default true; explicitly false disables source, sourcePath: path }); } function withinSizeLimit(path) { try { const stat = statSync2(path); return stat.isFile() && stat.size <= MAX_PACKAGE_RESOURCE_BYTES; } catch { return false; } } function parseAgentFrontmatter(content) { return parseFrontmatter(content.startsWith("\uFEFF") ? content.slice(1) : content); } function readAgentFile(path, strict) { try { return parseAgentFrontmatter(readFileSync3(path, "utf-8")); } catch (err) { const reason = errorMessage(err); if (strict) throw new Error(`${path}: ${reason}`); warnIfNew(`Skipping agent file ${path}: ${reason}`); return void 0; } } function warnSkippedOverride(name, agents2) { const surviving = agents2.get(name); if (!surviving?.sourcePath || surviving.enabled === false) return; warnIfNew(`Agent "${name}" now loads from ${surviving.sourcePath} instead`); } var warnedLastLoad = /* @__PURE__ */ new Set(); var warnedThisLoad = /* @__PURE__ */ new Set(); function warnIfNew(message) { warnedThisLoad.add(message); if (warnedLastLoad.has(message)) return; console.warn(`[pi-subagents] ${message}`); } function str(val) { return typeof val === "string" ? val : void 0; } function nonNegativeInt(val) { return typeof val === "number" && val >= 0 ? val : void 0; } function parseCsvField(val) { if (val === void 0 || val === null) return void 0; const s = String(val).trim(); if (!s || s === "none") return void 0; const items = s.split(",").map((t) => t.trim()).filter(Boolean); return items.length > 0 ? items : void 0; } function parseAllowedSubagents(val) { if (typeof val === "boolean") return val ? "all" : void 0; const items = parseCsvField(val); if (!items) return void 0; return items.some((i) => i === "*" || i.toLowerCase() === "all") ? "all" : items; } function csvList(val, defaults) { if (val === void 0 || val === null) return defaults; return parseCsvField(val) ?? []; } function parseToolsField(val) { const entries = csvList(val, BUILTIN_TOOL_NAMES); const isWildcard = (e) => e === "*" || e.toLowerCase() === "all"; const hasWildcard = entries.some(isWildcard); const plain = entries.filter((e) => !isWildcard(e) && !e.startsWith("ext:")); const extEntries = entries.filter((e) => e.startsWith("ext:")); return { builtinToolNames: hasWildcard ? [.../* @__PURE__ */ new Set([...BUILTIN_TOOL_NAMES, ...plain])] : plain, extSelectors: extEntries.length > 0 ? extEntries : void 0 }; } function csvListOptional(val) { return parseCsvField(val); } function parseMemory(val) { if (val === "user" || val === "project" || val === "local") return val; return void 0; } function parseIsolation(val) { if (val === "worktree") return "worktree"; if (val === "off" || val === "none" || val === "no" || val === false) return "off"; return void 0; } function inheritField(val) { if (val === void 0 || val === null || val === true) return true; if (val === false || val === "none") return false; const items = csvList(val, []); return items.length > 0 ? items : false; } // src/invocation-config.ts import { homedir as homedir3 } from "node:os"; import { resolve as resolve2 } from "node:path"; import { Type } from "typebox"; var isolationParamShape = { isolation: Type.Optional( Type.Union([Type.Literal("off"), Type.Literal("worktree")], { description: 'Isolation mode. Default "off". "off" runs the agent in the current checkout, the same as omitting the field. "worktree" creates a temporary git worktree so the agent works on an isolated copy of the repo (a copy cannot see uncommitted or staged changes in the main checkout).' }) ) }; function isolationParam(enabled) { return enabled ? isolationParamShape : {}; } var cwdParam = { cwd: Type.Optional( Type.String({ description: 'Working directory for the agent: absolute, "~/"-prefixed, or relative to the session cwd. Default: the session cwd. With isolation: "worktree", the worktree is created from the git repo containing this directory, the agent runs at the same subdirectory inside the copy, and the result branch lands in that repo. Pass it whenever the target repo is not the session cwd. Project config (.pi extensions, skills, settings) still loads from the session cwd.' }) ) }; function resolveCwdParam(cwd, sessionCwd, homeDir = homedir3()) { const trimmed = cwd?.trim(); if (!trimmed) return void 0; if (trimmed === "~") return homeDir; if (trimmed.startsWith("~/")) return resolve2(homeDir, trimmed.slice(2)); return resolve2(sessionCwd, trimmed); } function resolveAgentInvocationConfig(agentConfig, params, opts) { const requested = agentConfig?.isolation ?? params.isolation; const isolation = requested === "worktree" && opts?.worktreeAllowed !== false ? "worktree" : void 0; return { // A specialist's frontmatter is a reusable default, not a policy boundary: // an explicit dispatch chooses the effort for this run. Pi still clamps the // selected level to the resolved model, and agent-manager records that // requested-versus-effective difference after the session starts. thinking: params.thinking ?? agentConfig?.thinking, maxTurns: agentConfig?.maxTurns ?? params.max_turns, inheritContext: agentConfig?.inheritContext ?? params.inherit_context ?? false, runInBackground: agentConfig?.runInBackground ?? params.run_in_background ?? opts?.defaultRunInBackground ?? false, isolated: agentConfig?.isolated ?? params.isolated ?? false, isolation }; } // src/model-tiers.ts function tierDisclosure(outcome) { if (outcome.kind !== "routed" && outcome.kind !== "static") return outcome; const { provider, id, name, api } = outcome.model; return { ...outcome, model: { provider, id, name, api } }; } var TIER_NAME = /^[a-z0-9][a-z0-9._-]*$/; var MODEL_REF = /^[^\s/]+\/\S+$/; var bindings = {}; var policy = {}; function parseTierBinding(tier, members) { if (tier.trim() !== tier || !TIER_NAME.test(tier) || !Array.isArray(members) || members.length === 0 || members.some((ref) => typeof ref !== "string" || ref.trim() !== ref || !MODEL_REF.test(ref))) return void 0; const refs = members; if (refs.some((ref) => ref.startsWith("router/"))) { return refs.length === 1 ? { kind: "routed", tier, profile: refs[0] } : void 0; } return { kind: "static", tier, members: [...refs] }; } function setModelTiers(tiers, resolution) { bindings = Object.fromEntries(Object.entries(tiers ?? {}).map(([key, refs]) => [key, [...refs]])); policy = { ...resolution }; } function configuredTierNames() { return Object.keys(bindings).sort(); } function getModelResolution() { return { ...policy }; } function tierBinding(tier) { return parseTierBinding(tier, bindings[tier]); } function exactTierModel(ref, registry) { if (ref.trim() !== ref || !MODEL_REF.test(ref)) return void 0; const slash = ref.indexOf("/"); const found = registry.find(ref.slice(0, slash), ref.slice(slash + 1)); if (!found) return void 0; if (ref.startsWith("router/")) return found.api === "pi-virtual" ? found : void 0; const available = registry.getAvailable?.() ?? registry.getAll(); return available.some((model) => model.provider === found.provider && model.id === found.id) ? found : void 0; } async function resolveTier(tier, deps) { const binding = deps.binding ?? tierBinding(tier); if (!binding) return { kind: "unmapped", tier }; if (binding.kind === "routed") { const model = exactTierModel(binding.profile, deps.registry); if (!model) return { kind: "unavailable", tier, tried: [binding.profile] }; const admission = await deps.admit(binding.profile); if (admission.block) return { kind: "exhausted", tier, block: admission.block, skipped: [] }; return { kind: "routed", tier, model, profile: binding.profile, admitted: admission.resolvedModel }; } const skipped = []; const blocks = []; for (const member of binding.members) { const model = exactTierModel(member, deps.registry); if (!model) { skipped.push({ ref: member, why: "no-credentials" }); continue; } const admission = await deps.admit(member); if (admission.block) { skipped.push({ ref: member, why: "quota" }); blocks.push(admission.block); continue; } return { kind: "static", tier, model, member, skipped, quotaSignal: admission.quotaSignal }; } if (blocks.length) { const resets = blocks.flatMap((block) => block.resetAt === void 0 ? [] : [block.resetAt]); return { kind: "exhausted", tier, skipped, block: { model: `@${tier}`, wait: blocks.every((block) => block.wait !== false), resetAt: resets.length ? Math.min(...resets) : void 0 } }; } return { kind: "unavailable", tier, tried: [...binding.members] }; } function isTierDisclosure(raw) { if (!raw || typeof raw !== "object") return false; const value = raw; if (typeof value.tier !== "string") return false; if (value.kind === "unmapped") return true; if (value.kind === "unavailable") return Array.isArray(value.tried) && value.tried.every((ref) => typeof ref === "string"); const skipsValid = Array.isArray(value.skipped) && value.skipped.every((skip) => skip && typeof skip === "object" && typeof skip.ref === "string" && (skip.why === "quota" || skip.why === "no-credentials")); if (value.kind === "exhausted") { const block = value.block; return skipsValid && !!block && typeof block.model === "string" && (block.wait === void 0 || typeof block.wait === "boolean") && (block.resetAt === void 0 || typeof block.resetAt === "number" && Number.isFinite(block.resetAt)); } const model = value.model; if (!model || typeof model.provider !== "string" || typeof model.id !== "string" || typeof model.name !== "string" || typeof model.api !== "string") return false; if (value.answered !== void 0 && typeof value.answered !== "string") return false; if (value.kind === "routed") return typeof value.profile === "string" && value.profile.startsWith("router/") && (value.admitted === void 0 || typeof value.admitted === "string"); return value.kind === "static" && typeof value.member === "string" && skipsValid && typeof value.quotaSignal === "boolean"; } function tierNote(outcome, answering) { if (!outcome) return ""; const tier = `@${outcome.tier}`; const answered = answering ?? (outcome.kind === "routed" || outcome.kind === "static" ? outcome.answered : void 0); switch (outcome.kind) { case "routed": return `Model: ${tier} -> ${answered ?? outcome.admitted ?? outcome.profile} via ${outcome.profile}${answered && outcome.admitted && answered !== outcome.admitted ? ` (switched from ${outcome.admitted} within tier)` : ""}`; case "static": return `Model: ${tier} -> ${answered ?? outcome.member} (static${outcome.quotaSignal ? "" : "; no quota signal"})${outcome.skipped.length ? `; skipped ${outcome.skipped.map((skip) => `${skip.ref}: ${skip.why}`).join(", ")}` : ""}`; case "unmapped": return `Note: model tier ${tier} is unmapped; inheriting the parent model.`; case "unavailable": return `Note: model tier ${tier} is unavailable; inheriting the parent model.`; case "exhausted": return `Model: ${tier} is exhausted.`; } } // src/model-resolver.ts var modelAliases = /* @__PURE__ */ new Map(); function setModelAliases(aliases) { modelAliases = new Map( Object.entries(aliases ?? {}).map(([alias, candidates]) => [alias.toLowerCase(), [...candidates]]) ); } var agentModels = /* @__PURE__ */ new Map(); function setAgentModels(models) { agentModels = new Map(Object.entries(models ?? {}).map(([type, model]) => [type.toLowerCase(), model])); } function getAgentModels() { return new Map(agentModels); } var modelScopeProvider; function setModelScopeProvider(provider) { modelScopeProvider = provider; } function getModelAliases() { return new Map([...modelAliases].map(([alias, candidates]) => [alias, [...candidates]])); } function describeModel(model) { return { modelName: (model.name ?? model.id).replace(/^Claude\s+/i, "").toLowerCase(), modelId: `${model.provider}/${model.id}` }; } function modelFallbackTo(input, parent) { return parent ? { input, used: `${parent.provider}/${parent.id}` } : { input }; } function modelFallbackNote(fallback) { if (!fallback) return ""; const whose = fallback.via === "agent" ? "the agent's own model" : "parent model"; const used = fallback.used ? `${whose} ${fallback.used}` : "the session default model"; const inputs = [fallback.input, ...fallback.also ?? []]; const named = inputs.length === 1 ? `model "${inputs[0]}" did` : `models ${inputs.map((i) => `"${i}"`).join(", ")} did`; return `Note: configured ${named} not resolve; running on ${used}.`; } var VIRTUAL_MODEL_API = "pi-virtual"; function isVirtualModel(model) { return model?.api === VIRTUAL_MODEL_API; } function describeVirtualModel(model) { const described = describeModel(model); return { ...described, modelName: `${described.modelName} (routing)` }; } function describePhysicalModel(message, registry) { if (!message?.provider || !message.model || isVirtualModel(message)) return void 0; const found = registry?.find?.(message.provider, message.model); return describeModel({ provider: message.provider, id: message.model, name: found?.name }); } function parseModelVersion(id) { const bare = id.slice(id.lastIndexOf("/") + 1).toLowerCase(); const claude = /^claude-[a-z]+-(\d{1,2})(?:[-.](\d{1,2})(?!\d))?(?:-|$)/.exec(bare) ?? /^claude-(\d{1,2})(?:[-.](\d{1,2})(?!\d))?-[a-z]/.exec(bare); const match = claude ?? /^gpt-(\d+)(?:[.-](\d{1,2})(?!\d))?(?:-|$)/.exec(bare); if (!match) return void 0; return [Number(match[1]), Number(match[2] ?? 0)]; } function compareVersionsDesc(a, b) { if (a && b) return b[0] - a[0] || b[1] - a[1]; return a ? -1 : b ? 1 : 0; } function resolveModel(input, registry, context) { const aliasCandidates = modelAliases.get(input.trim().toLowerCase()); if (aliasCandidates) { for (const candidate of aliasCandidates) { const resolved2 = exactTierModel(candidate, registry); if (resolved2) return resolved2; } return `Model alias "${input}" has no available candidate. Candidates: ${aliasCandidates.map((candidate) => ` ${candidate}`).join("\n")}`; } return resolveCanonicalModel(input, registry, context); } function scopedCandidates(candidates, registry, context) { const scope = modelScopeProvider?.(registry, context); const scoped = scope ? candidates.filter((candidate) => scope.has(`${candidate.entry.provider}/${candidate.entry.id}`.toLowerCase())) : []; return scoped.length > 0 ? scoped : candidates; } function compareModelIdentity(a, b) { const left = `${a.provider}/${a.id}`; const right = `${b.provider}/${b.id}`; return Number(left > right) - Number(left < right); } function rankFuzzy(matches, registry, context) { const ranked = scopedCandidates(matches, registry, context).map((c) => ({ ...c, version: parseModelVersion(c.entry.id) })).sort((a, b) => compareVersionsDesc(a.version, b.version) || b.score - a.score || compareModelIdentity(a.entry, b.entry)); return ranked[0]?.entry; } function versionRuns(value) { return [...value.replace(/-\d{8}$/, "").matchAll(/(?:^|[\s-])(\d+(?:[\s-]+\d+)*)(?=$|[\s-])/g)].map((match) => match[1].replace(/\s+/g, "-")); } function resolveCanonicalModel(input, registry, context) { const all = registry.getAvailable?.() ?? registry.getAll(); const availableSet = new Set(all.map((m) => `${m.provider}/${m.id}`.toLowerCase())); const slashIdx = input.indexOf("/"); if (slashIdx !== -1) { const provider = input.slice(0, slashIdx); const modelId = input.slice(slashIdx + 1); if (availableSet.has(input.toLowerCase())) { const found = registry.find(provider, modelId); if (found) return found; } } const normalize = (s) => s.toLowerCase().replace(/\./g, "-"); const query = normalize(input); const requestedVersions = versionRuns(query.slice(slashIdx + 1)); const matches = []; for (const m of all) { const id = normalize(m.id); const name = normalize(m.name); const full = normalize(`${m.provider}/${m.id}`); const idVersions = versionRuns(id); const versions = idVersions.length > 0 ? idVersions : versionRuns(name); if (!requestedVersions.every((requested) => versions.some((version) => version === requested || version.startsWith(`${requested}-`)))) continue; let score = 0; if (id === query || full === query) { score = 100; } else if (id.includes(query) || full.includes(query)) { score = 60 + query.length / id.length * 30; } else if (name.includes(query)) { score = 40 + query.length / name.length * 20; } else if ( // A trailing date-stamp token (e.g. "20251001") is optional, so a // date-pinned config like "claude-haiku-4-5-20251001" still matches an // undated registry id like "claude-haiku-4-5". query.split(/[\s\-/]+/).every((part) => /^\d{8}$/.test(part) || id.includes(part) || name.includes(part) || m.provider.toLowerCase().includes(part)) ) { score = 20; } if (score >= 20) matches.push({ entry: m, score }); } const exact = matches.filter((c) => c.score === 100); const exactBest = exact.sort((a, b) => compareModelIdentity(a.entry, b.entry))[0]; const bestMatch = exactBest ? exactBest.entry : rankFuzzy(matches, registry, context); if (bestMatch) { const found = registry.find(bestMatch.provider, bestMatch.id); if (found) return found; } if (slashIdx !== -1) { const bare = resolveCanonicalModel(input.slice(slashIdx + 1), registry, context); if (typeof bare !== "string") return bare; } const modelList = scopedCandidates(all.map((entry) => ({ entry })), registry, context).map(({ entry }) => ` ${entry.provider}/${entry.id}`).sort().join("\n"); return `Model not found: "${input}". Available models: ${modelList}`; } // src/enabled-models.ts import { existsSync as existsSync4, readFileSync as readFileSync4, statSync as statSync3 } from "node:fs"; import { join as join5 } from "node:path"; function settingsPaths(cwd, homeDir) { return [ join5(cwd, ".pi", "settings.json"), join5(resolveAgentDir(homeDir), "settings.json") ]; } function readField(path) { if (!existsSync4(path)) return void 0; try { const raw = JSON.parse(readFileSync4(path, "utf-8")); if (Array.isArray(raw?.enabledModels)) return raw.enabledModels; } catch { } return void 0; } function readEnabledModels(cwd, homeDir) { const [project, global] = settingsPaths(cwd, homeDir); return readField(project) ?? readField(global); } var cachedAllowed; var cachedHash = ""; var cachedPatternsKey = ""; function hashOf(path) { try { const s = statSync3(path); return `${s.mtimeMs}-${s.size}`; } catch { return "missing"; } } function resolveEnabledModels(patterns, registry, cwd = process.cwd(), homeDir) { const patternsKey = JSON.stringify(patterns); const [project, global] = settingsPaths(cwd, homeDir); const fileHash = `${project}:${hashOf(project)};${global}:${hashOf(global)}`; if (fileHash === cachedHash && patternsKey === cachedPatternsKey) { return cachedAllowed; } if (!patterns || patterns.length === 0) { cachedHash = fileHash; cachedPatternsKey = patternsKey; cachedAllowed = void 0; return void 0; } const available = registry.getAvailable?.() ?? registry.getAll(); const allowed = /* @__PURE__ */ new Set(); for (const pattern of patterns) { const trimmed = pattern.trim(); if (!trimmed) continue; resolveExact(trimmed, available, allowed); } const result = allowed.size > 0 ? allowed : void 0; cachedHash = fileHash; cachedPatternsKey = patternsKey; cachedAllowed = result; return result; } function isModelInScope(model, allowed) { return allowed.has(modelKey(model)); } function modelKey(model) { return `${model.provider}/${model.id}`.toLowerCase(); } function resolveExact(pattern, available, allowed) { const slashIdx = pattern.indexOf("/"); if (slashIdx === -1) return; const provider = pattern.slice(0, slashIdx).toLowerCase(); const modelId = pattern.slice(slashIdx + 1).toLowerCase(); const exact = available.find( (m) => m.provider.toLowerCase() === provider && m.id.toLowerCase() === modelId ); if (exact) { allowed.add(modelKey(exact)); } } // src/model-scope.ts var scopeModelsEnabled = false; function isScopeModelsEnabled() { return scopeModelsEnabled; } function setScopeModelsEnabled(enabled) { scopeModelsEnabled = enabled; } function checkModelScope(args) { const { model, cwd, modelRegistry, callerSupplied, agentLabel, modelInput } = args; if (!scopeModelsEnabled || !model) return { kind: "ok" }; const allowed = resolveEnabledModels(readEnabledModels(cwd, args.homeDir), modelRegistry, cwd, args.homeDir); if (!allowed || isModelInScope(model, allowed)) return { kind: "ok" }; if (callerSupplied) { const list = [...allowed].sort().map((m) => ` ${m}`).join("\n"); return { kind: "error", message: `Model not in scope: "${modelInput}". Allowed models (from enabledModels): ${list}` }; } const modelLabel = modelInput ?? `${model.provider}/${model.id}`; return { kind: "warn", message: `Agent "${agentLabel}" using out-of-scope model "${modelLabel}"` }; } // src/quota-admission.ts import { nanoid } from "nanoid"; var ADMIT_CHANNEL = "router:rpc:admit"; var ADMIT_TIMEOUT_MS = 100; function mayPark(block) { return block.resetAt !== void 0 && block.wait !== false; } function modelRef(model) { return `${model.provider}/${model.id}`; } async function checkAdmission(events, model, timeoutMs = ADMIT_TIMEOUT_MS, clock = realClock, signal) { return (await admissionOutcome(events, model, timeoutMs, clock, signal)).block; } function admissionOutcome(events, model, timeoutMs = ADMIT_TIMEOUT_MS, clock = realClock, signal) { if (signal?.aborted) return Promise.reject(new DOMException("Admission cancelled", "AbortError")); const requestId = nanoid(); return new Promise((resolve6, reject) => { const cleanup = () => { timer.cancel(); unsubscribe(); signal?.removeEventListener("abort", abort); }; const abort = () => { cleanup(); reject(new DOMException("Admission cancelled", "AbortError")); }; const finish = (outcome) => { cleanup(); resolve6(outcome); }; const unsubscribe = events.on(`${ADMIT_CHANNEL}:reply:${requestId}`, (raw) => { const reply = raw; if (reply?.success !== true || typeof reply.data?.ok !== "boolean") return finish({ quotaSignal: false }); if (reply.data.ok) return finish({ quotaSignal: true, resolvedModel: typeof reply.data.resolvedModel === "string" ? reply.data.resolvedModel : void 0 }); const resetAt = reply.data.resetAt; const wait = reply.data.wait; finish({ quotaSignal: true, block: { model, resetAt: typeof resetAt === "number" && Number.isFinite(resetAt) ? resetAt : void 0, ...typeof wait === "boolean" ? { wait } : {} } }); }); const timer = clock.setTimeout(() => finish({ quotaSignal: false }), timeoutMs); signal?.addEventListener("abort", abort, { once: true }); events.emit(ADMIT_CHANNEL, { requestId, model }); }); } function describeBlock(block) { const when = block.resetAt === void 0 ? "an unknown time" : new Date(block.resetAt).toISOString(); return `Subscription quota for ${block.model} is exhausted; it resets at ${when}.`; } var QUOTA_RESTART_GRACE_MS = 6e4; var PARKED_RESUME_DELAY_MS = 1e4; // src/model-selection.ts var LEGACY_MODEL_PINS = /* @__PURE__ */ new Map([ ["claude-haiku-4-5", "anthropic/claude-haiku-4-5"] ]); function modelRequest(type, definitionModel, paramModel) { if (paramModel != null && (typeof paramModel !== "string" || paramModel.trim() !== "")) { return { requested: typeof paramModel === "string" ? paramModel : `${paramModel.provider}/${paramModel.id}`, source: "param" }; } const overrides = getAgentModels(); const typed = overrides.get(type.toLowerCase()); if (typed?.trim()) return { requested: typed, source: "agentModels:type" }; const wildcard = overrides.get("*"); if (wildcard?.trim()) return { requested: wildcard, source: "agentModels:*" }; if (definitionModel?.trim()) return { requested: definitionModel, source: "definition" }; return { source: "parent" }; } function selectModel(request) { const input = modelRequest(request.agentType, request.definitionModel, request.paramModel); let selection = { ...input, model: request.parentModel, outcome: "inherited" }; if (input.requested) { const requested = input.requested.trim(); const legacy = getModelAliases().get(requested.toLowerCase()); const legacyBinding = legacy ? parseTierBinding("legacy", legacy) : void 0; const cheapCompatibility = requested === "@cheap" && request.agentType === "Explore" && input.source === "definition" ? parseTierBinding("cheap", getModelAliases().get("claude-haiku-4-5")) : void 0; const binding = requested.startsWith("@") ? tierBinding(requested.slice(1)) ?? cheapCompatibility : legacyBinding ? { ...legacyBinding, tier: requested } : void 0; if (requested.startsWith("@") || legacy) { const tier = requested.startsWith("@") ? requested.slice(1) : requested; const refs = binding?.kind === "routed" ? [binding.profile] : binding?.members ?? []; const model = refs.map((ref) => exactTierModel(ref, request.registry)).find(Boolean); if (!binding || !model) { const outcome = binding ? { kind: "unavailable", tier, tried: refs } : { kind: "unmapped", tier }; const mode = outcome.kind === "unmapped" ? getModelResolution().onUnmapped : getModelResolution().onUnavailable; if (mode === "error") return `Model tier @${tier} is ${outcome.kind}.`; selection = { ...selection, tier: outcome, outcome: "fallback", fallback: modelFallbackTo(input.requested, request.parentModel) }; } else { selection = { ...input, model, outcome: "resolved", tierBinding: binding, tierParent: request.parentModel }; } } else { const compatibilityPin = input.source === "definition" && request.agentType === "Explore" ? LEGACY_MODEL_PINS.get(requested) : void 0; const resolved2 = request.paramModel != null && typeof request.paramModel === "object" ? request.paramModel : input.source === "param" ? resolveModel(requested, request.registry, { cwd: request.cwd, homeDir: request.homeDir }) : exactTierModel(compatibilityPin ?? requested, request.registry) ?? `Model not found: "${requested}".`; if (typeof resolved2 !== "string") selection = { ...input, model: resolved2, outcome: "resolved" }; else if (compatibilityPin) { const tier = { kind: "unavailable", tier: requested, tried: [compatibilityPin] }; if (getModelResolution().onUnavailable === "error") return `Model tier @${requested} is unavailable.`; selection = { ...selection, tier, outcome: "fallback", fallback: modelFallbackTo(input.requested, request.parentModel) }; } else { if (input.source === "param" || getModelResolution().onUnavailable === "error") return resolved2; selection = { ...selection, outcome: "fallback", fallback: modelFallbackTo(input.requested, request.parentModel) }; } } } const scope = checkModelScope({ model: selection.model, cwd: request.cwd, modelRegistry: request.registry, callerSupplied: input.source === "param" && !selection.tierBinding && !selection.tier, agentLabel: request.agentLabel ?? request.agentType, modelInput: input.requested, homeDir: request.homeDir }); if (scope.kind === "error") return scope.message; if (scope.kind === "warn") selection.scopeWarning = scope.message; return selection; } function describeSelection(selection, registry) { const admitted = selection?.tier?.kind === "routed" ? selection.tier.admitted : void 0; if (admitted) { const slash = admitted.indexOf("/"); const provider = admitted.slice(0, slash); const id = admitted.slice(slash + 1); return describeModel(registry.find(provider, id) ?? { provider, id }); } const model = selection?.model; return model ? isVirtualModel(model) ? describeVirtualModel(model) : describeModel(model) : {}; } function modelIdentityNote(carrier) { const selected = carrier?.modelSelection?.model; return selected && !carrier?.modelTier ? `Resolved model: ${selected.provider}/${selected.id}${isVirtualModel(selected) ? " (routing alias; physical response model: unknown)" : ""}.` : ""; } function modelSelectionNote(carrier) { const tier = carrier?.modelTier; const fallback = carrier?.modelFallback; const sameRequest = tier && (fallback?.input === tier.tier || fallback?.input === `@${tier.tier}`); return [tierNote(tier, carrier?.invocation?.modelId), sameRequest ? "" : modelFallbackNote(fallback)].filter(Boolean).join("\n"); } async function admitModelSelection(selection, registry, events, clock = realClock, signal) { if (!selection.tierBinding || selection.tierAdmitted) return selection.tier?.kind === "exhausted" ? selection.tier.block : void 0; selection.tier = await resolveTier(selection.tierBinding.tier, { registry, binding: selection.tierBinding, admit: (ref) => admissionOutcome(events, ref, void 0, clock, signal) }); selection.tierAdmitted = true; if (selection.tier.kind === "routed" || selection.tier.kind === "static") selection.model = selection.tier.model; if (selection.tier.kind === "exhausted") return selection.tier.block; if (selection.tier.kind === "unavailable") { if (getModelResolution().onUnavailable === "error") throw new Error(`Model tier @${selection.tier.tier} is unavailable.`); selection.model = selection.tierParent; selection.outcome = "fallback"; selection.fallback = modelFallbackTo(selection.requested ?? `@${selection.tier.tier}`, selection.tierParent); delete selection.tierBinding; } delete selection.tierParent; return void 0; } // src/output-file.ts import { appendFileSync, chmodSync, existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join as join6 } from "node:path"; var outputTranscriptDefault = true; function getOutputTranscriptDefault() { return outputTranscriptDefault; } function setOutputTranscriptDefault(b) { outputTranscriptDefault = b; } function encodeCwd(cwd) { return cwd.replace(/[/\\]/g, "-").replace(/^[A-Za-z]:-/, "").replace(/^-+/, ""); } function sessionTaskDir(cwd, sessionId) { const encoded = encodeCwd(cwd); const root = join6(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`); mkdirSync2(root, { recursive: true, mode: 448 }); try { chmodSync(root, 448); } catch (err) { if (process.platform !== "win32") throw err; } const dir = join6(root, encoded, sessionId, "tasks"); mkdirSync2(dir, { recursive: true }); return dir; } function createOutputFilePath(cwd, agentId, sessionId) { return join6(sessionTaskDir(cwd, sessionId), `${agentId}.output`); } function ensureOutputFile(path) { try { appendFileSync(path, "", "utf-8"); } catch { } } function appendModelFallbackEntry(path, agentId, fallback) { try { if (existsSync5(path) && readFileSync5(path, "utf-8").includes('"type":"model-fallback"')) return; appendFileSync( path, `${JSON.stringify({ isSidechain: true, agentId, type: "model-fallback", modelFallback: fallback, note: modelFallbackNote(fallback), timestamp: (/* @__PURE__ */ new Date()).toISOString() })} `, "utf-8" ); } catch { } } function appendModelTierEntry(path, agentId, modelTier) { try { appendFileSync(path, `${JSON.stringify({ isSidechain: true, agentId, type: "model-tier", modelTier: tierDisclosure(modelTier), note: tierNote(modelTier), timestamp: (/* @__PURE__ */ new Date()).toISOString() })} `, "utf-8"); } catch { } } function writeInitialEntry(path, agentId, prompt, cwd) { const entry = { isSidechain: true, agentId, type: "user", message: { role: "user", content: prompt }, timestamp: (/* @__PURE__ */ new Date()).toISOString(), cwd }; writeFileSync(path, JSON.stringify(entry) + "\n", "utf-8"); } function streamToOutputFile(session, path, agentId, cwd, startIndex) { let writtenCount = startIndex; const flush = () => { const messages = session.messages; if (writtenCount === void 0) { const prompt = messages.findIndex((m) => m.role === "user"); if (prompt === -1) return; writtenCount = prompt + 1; } while (writtenCount < messages.length) { const msg = messages[writtenCount++]; if (msg.role === "system") continue; const entry = { isSidechain: true, agentId, type: msg.role === "assistant" ? "assistant" : msg.role === "user" ? "user" : "toolResult", message: msg, timestamp: (/* @__PURE__ */ new Date()).toISOString(), cwd }; try { appendFileSync(path, JSON.stringify(entry) + "\n", "utf-8"); } catch { } } }; const unsubscribe = session.subscribe((event) => { if (event.type === "turn_end") flush(); if (event.type === "compaction_start") flush(); if (event.type === "compaction_end" && !event.aborted && event.result) { queueMicrotask(() => { writtenCount = session.messages.length; }); } }); return () => { flush(); unsubscribe(); }; } // src/status-note.ts function getStatusNote(status, stoppedBy) { switch (status) { case "stopped": return stoppedBy === "parent" ? " (stopped by the parent with stop_subagent before completion \u2014 output is partial; the task was NOT finished)" : " (STOPPED BY THE USER before completion \u2014 output is partial; the task was NOT finished)"; case "aborted": return " (aborted \u2014 hit the turn limit before completion; output may be incomplete)"; case "steered": return " (wrapped up at the turn limit \u2014 output may be partial)"; default: return ""; } } function getForegroundOutcomeNote(status, stoppedBy) { switch (status) { case "stopped": return stoppedBy === "parent" ? " (stopped by the parent with stop_subagent \u2014 everything the agent produced is above; the task is unfinished)" : " (STOPPED BY THE USER \u2014 everything the agent produced is above; the task is unfinished)"; case "aborted": return " (aborted at the turn limit \u2014 everything the agent produced is above; the task is unfinished)"; case "steered": return " (wrapped up at the turn limit \u2014 everything the agent produced is above; the task may be unfinished)"; default: return ""; } } function resumeHint(record) { return record.status === "error" && record.session ? `transcript intact; resume agent ${record.id} to continue` : ""; } function partialOutputSuffix(record) { const partial = record.result?.trim(); return partial ? ` Partial output before the failure: ${partial}` : ""; } // src/worktree.ts import { randomUUID } from "node:crypto"; import { existsSync as existsSync6, lstatSync as lstatSync2, readdirSync as readdirSync2, readFileSync as readFileSync6, realpathSync as realpathSync2, statSync as statSync4 } from "node:fs"; import { tmpdir as tmpdir2 } from "node:os"; import { join as join7, relative as relative2, resolve as resolve3 } from "node:path"; // src/git-path.ts var SIMPLE_ESCAPES = { a: 7, b: 8, f: 12, n: 10, r: 13, t: 9, v: 11, '"': 34, "\\": 92 }; var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); var QUOTE_PATH_ARGS = ["-c", "core.quotePath=true"]; function unquoteGitPath(text) { const quoted = text.length >= 2 && text.startsWith('"') && text.endsWith('"'); const body = quoted ? text.slice(1, -1) : text; for (let i = 0; i < body.length; i++) { if (body.charCodeAt(i) > 127) throw new Error(`git printed a non-ASCII path unquoted (${JSON.stringify(text)}); it may be mis-decoded`); } if (!quoted) return text; const bytes = []; for (let i = 0; i < body.length; i++) { const char = body.charAt(i); if (char === '"') throw new Error(`malformed quoted git path ${JSON.stringify(text)}`); if (char !== "\\") { bytes.push(body.charCodeAt(i)); continue; } const next = body.charAt(i + 1); const octal = /^[0-3][0-7]{2}$/.test(body.slice(i + 1, i + 4)) ? body.slice(i + 1, i + 4) : void 0; if (octal) { bytes.push(Number.parseInt(octal, 8)); i += 3; } else if (next in SIMPLE_ESCAPES) { bytes.push(SIMPLE_ESCAPES[next]); i += 1; } else { throw new Error(`malformed escape in quoted git path ${JSON.stringify(text)}`); } } try { return UTF8.decode(Uint8Array.from(bytes)); } catch { throw new Error(`git path ${JSON.stringify(text)} is not valid UTF-8 and cannot be inspected`); } } // src/worktree.ts var worktreeIsolationEnabled = true; function setWorktreeIsolationEnabled(enabled) { worktreeIsolationEnabled = enabled; } function isWorktreeIsolationEnabled() { return worktreeIsolationEnabled; } async function git(pi, cwd, args, timeout) { return (await gitRaw(pi, cwd, args, timeout)).trim(); } async function gitRaw(pi, cwd, args, timeout) { const result = await pi.exec("git", args, { cwd, timeout }); if (result.killed) throw new GitTimeoutError(`\`git ${args.join(" ")}\` timed out after ${timeout}ms in ${cwd}`); if (result.code !== 0) { throw new Error(result.stderr.trim() || `git ${args.join(" ")} failed (exit ${result.code})`); } return result.stdout; } var GitTimeoutError = class extends Error { }; var WorktreeError = class extends Error { }; async function step(run, cause) { try { return await run; } catch (err) { const detail = errorMessage(err); throw new WorktreeError(err instanceof GitTimeoutError ? detail : cause(detail)); } } async function createWorktree(pi, cwd, agentId) { const inside = await step( git(pi, cwd, ["rev-parse", "--is-inside-work-tree"], 5e3), (detail) => `${cwd} is not inside a git repository (${detail})` ); if (inside !== "true") throw new WorktreeError(`${cwd} is inside a git directory but not a work tree`); const repoRoot = realpathSync2(await step( git(pi, cwd, ["rev-parse", "--show-toplevel"], 5e3), (detail) => `${cwd} has no git work tree toplevel (${detail})` )); const baseSha = await step( git(pi, cwd, ["rev-parse", "--verify", "HEAD"], 5e3), () => `${repoRoot} has no commits yet; commit at least once` ); const subdir = relative2(repoRoot, realpathSync2(cwd)); const branch = `pi-agent-${agentId}`; const suffix = randomUUID().slice(0, 8); const worktreePath = join7(tmpdir2(), `pi-agent-${agentId}-${suffix}`); await step( git(pi, cwd, ["worktree", "add", "--detach", worktreePath, "HEAD"], 3e4), (detail) => `\`git worktree add\` failed in ${repoRoot}: ${detail}` ); return { path: worktreePath, branch, baseSha, repoRoot, workPath: subdir ? join7(worktreePath, subdir) : worktreePath }; } async function cleanupWorktree(pi, cwd, worktree, agentDescription) { if (!existsSync6(worktree.path)) { return { hasChanges: false }; } let branch; try { await assertSubmodulesDisposable(pi, worktree.path, worktree.baseSha); const status = await dirtyState(pi, worktree.path); if (status) { const modes = await indexOnlyModes(pi, worktree.path); if (modes.length > 0) { throw new Error(`mode staged only in the index; worktree kept: ${modes.join(", ")}`); } await git(pi, worktree.path, ["add", "-A"], 1e4); if (!await git(pi, worktree.path, ["diff", "--cached", "--name-only"], 1e4)) { throw new Error(`uncommitted changes could not be staged (a submodule \`ignore\` setting can hide a moved gitlink); worktree kept: ${status}`); } const safeDesc = agentDescription.slice(0, 200); const commitMsg = `pi-agent: ${safeDesc}`; await git(pi, worktree.path, ["commit", "--no-verify", "-m", commitMsg], 1e4); } else { const currentSha = await git(pi, worktree.path, ["rev-parse", "HEAD"], 5e3); if (currentSha === worktree.baseSha) { await removeWorktree(pi, cwd, worktree.path, worktree.baseSha); return { hasChanges: false }; } } let branchName = worktree.branch; try { await git(pi, worktree.path, ["branch", branchName], 5e3); } catch { branchName = `${worktree.branch}-${Date.now()}`; await git(pi, worktree.path, ["branch", branchName], 5e3); } worktree.branch = branchName; branch = branchName; await removeWorktree(pi, cwd, worktree.path, worktree.baseSha); return { hasChanges: true, branch: worktree.branch }; } catch (error) { return { hasChanges: true, ...branch ? { branch } : {}, path: worktree.path, error: (error instanceof Error ? error.message : String(error)) || "Unknown git failure" }; } } async function gitLines(pi, repo, args, timeout) { return (await gitRaw(pi, repo, [...QUOTE_PATH_ARGS, ...args], timeout)).split("\n").filter(Boolean); } var INDEX_BATCH = 200; async function updateIndex(pi, repo, flag, paths) { for (let i = 0; i < paths.length; i += INDEX_BATCH) { await git(pi, repo, ["update-index", flag, "--", ...paths.slice(i, i + INDEX_BATCH)], 3e4); } } async function clearHiddenIndexBits(pi, repo) { const assumed = []; const skipped = []; for (const entry of await gitLines(pi, repo, ["ls-files", "-v"], 3e4)) { const tag = entry.charAt(0); const hidden = tag !== tag.toUpperCase() || tag === "S"; if (!hidden) continue; const path = unquoteGitPath(entry.slice(2)); if (tag !== tag.toUpperCase()) assumed.push(path); if (tag.toLowerCase() === "s" && lstatOrUndefined(join7(repo, path))) skipped.push(path); } await updateIndex(pi, repo, "--no-assume-unchanged", assumed); await updateIndex(pi, repo, "--no-skip-worktree", skipped); } function lstatOrUndefined(path) { try { return lstatSync2(path, { bigint: true }); } catch (error) { const code = error.code; if (code === "ENOENT" || code === "ENOTDIR") return void 0; throw error; } } async function indexOnlyModes(pi, repo) { if (await git(pi, repo, ["config", "--type=bool", "--default", "true", "core.fileMode"], 5e3) === "false") return []; const paths = []; for (const line of await gitLines(pi, repo, ["diff", "--cached", "--raw", "--no-renames"], 3e4)) { const tab = line.indexOf(" "); const [oldMode, newMode] = line.slice(1, tab).split(" "); if (oldMode === newMode || newMode !== "100644" && newMode !== "100755") continue; const path = unquoteGitPath(line.slice(tab + 1)); const disk = lstatOrUndefined(join7(repo, path)); if (disk?.isFile() && (disk.mode & 0o100n) !== 0n !== (newMode === "100755")) paths.push(path); } return paths; } async function dirtyState(pi, repo) { await clearHiddenIndexBits(pi, repo); return await git(pi, repo, ["status", "--porcelain", "--untracked-files=all", "--ignore-submodules=none"], 1e4); } var GITLINK_MODE = "160000"; async function gitlinks(pi, repo, rev) { const links = /* @__PURE__ */ new Map(); for (const entry of await gitLines(pi, repo, rev ? ["ls-tree", "-r", rev] : ["ls-files", "-s"], 3e4)) { const tab = entry.indexOf(" "); const [mode, second, third] = entry.slice(0, tab).split(" "); if (mode === GITLINK_MODE) links.set(unquoteGitPath(entry.slice(tab + 1)), rev ? third : second); } return links; } async function unpublished(pi, gitArgs, cwd, published) { const stash = await git(pi, cwd, [...gitArgs, "stash", "list"], 1e4); const known = []; for (const sha of published) { const probe = await pi.exec("git", [...gitArgs, "cat-file", "-e", `${sha}^{commit}`], { cwd, timeout: 5e3 }); if (!probe.killed && probe.code === 0) known.push(sha); } const commits = await git(pi, cwd, [...gitArgs, "rev-list", "--branches", "--tags", "HEAD", "--not", "--remotes", ...known], 3e4); return [stash, commits].filter(Boolean).join("\n"); } function gitDirOf(dir) { const dotGit = join7(dir, ".git"); if (statSync4(dotGit).isDirectory()) return dotGit; const target = /^gitdir: (.+)$/m.exec(readFileSync6(dotGit, "utf8"))?.[1]; if (!target) throw new Error(`${dotGit} is neither a directory nor a gitdir file`); return resolve3(dir, target.trim()); } async function inspectRepo(pi, dir, label, recorded, trusted, seen, problems) { seen.add(realpathSync2(gitDirOf(dir))); const dirty = await dirtyState(pi, dir); const lost = await unpublished(pi, [], dir, recorded ? [recorded] : []); const detail = [dirty, lost].filter(Boolean).join("\n"); if (detail) problems.push(`${label}: ${detail}`); const head = await git(pi, dir, ["rev-parse", "HEAD"], 5e3); await inspectGitlinks(pi, dir, head === recorded ? "HEAD" : void 0, trusted, seen, problems); await inspectIgnoredRepos(pi, dir, dir, trusted, seen, problems); } async function inspectIgnoredRepos(pi, repo, root, trusted, seen, problems) { for (const dir of await ignoredRepoDirs(pi, repo)) { if (!seen.has(realpathSync2(gitDirOf(dir)))) { await inspectRepo(pi, dir, relative2(root, dir), void 0, trusted, seen, problems); } } } async function inspectGitlinks(pi, repo, baseRev, trusted, seen, problems) { const base = baseRev ? await gitlinks(pi, repo, baseRev) : /* @__PURE__ */ new Map(); for (const sha of base.values()) trusted.add(sha); for (const path of (await gitlinks(pi, repo)).keys()) { const dir = join7(repo, path); if (existsSync6(join7(dir, ".git"))) await inspectRepo(pi, dir, path, base.get(path), trusted, seen, problems); } } async function ignoredRepoDirs(pi, worktreePath) { const entries = await gitLines(pi, worktreePath, ["status", "--porcelain", "--ignored", "--untracked-files=all", "--ignore-submodules=none"], 3e4); const dirs = entries.filter((entry) => entry.startsWith("!! ") && /\/"?$/.test(entry)).map((entry) => unquoteGitPath(entry.slice(3))); return dirs.map((dir) => join7(worktreePath, dir)).filter((dir) => existsSync6(join7(dir, ".git"))); } function moduleGitDirs(dir) { if (existsSync6(join7(dir, "HEAD")) && existsSync6(join7(dir, "objects"))) { const nested = join7(dir, "modules"); return [dir, ...existsSync6(nested) ? moduleGitDirs(nested) : []]; } return readdirSync2(dir, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() ? moduleGitDirs(join7(dir, entry.name)) : []); } function modulesDir(worktreePath) { const dir = join7(gitDirOf(worktreePath), "modules"); return existsSync6(dir) ? dir : void 0; } async function assertSubmodulesDisposable(pi, worktreePath, baseSha) { const seen = /* @__PURE__ */ new Set(); const trusted = /* @__PURE__ */ new Set(); const problems = []; await inspectGitlinks(pi, worktreePath, baseSha, trusted, seen, problems); await inspectIgnoredRepos(pi, worktreePath, worktreePath, trusted, seen, problems); const modules = modulesDir(worktreePath); for (const gitDir of modules ? moduleGitDirs(modules) : []) { if (seen.has(realpathSync2(gitDir))) continue; const lost = await unpublished(pi, ["--git-dir", gitDir], worktreePath, trusted); if (lost) problems.push(`${gitDir}: ${lost}`); } if (problems.length) throw new Error(`submodule work would be lost on removal; worktree kept: ${problems.join("\n")}`); } async function hasSubmoduleState(pi, worktreePath) { return (await gitlinks(pi, worktreePath)).size > 0 || modulesDir(worktreePath) !== void 0; } async function removeWorktree(pi, cwd, worktreePath, baseSha) { try { await git(pi, cwd, ["-c", "status.showUntrackedFiles=all", "worktree", "remove", worktreePath], 1e4); } catch (error) { if (!await hasSubmoduleState(pi, worktreePath)) throw error; if (await dirtyState(pi, worktreePath)) throw error; await assertSubmodulesDisposable(pi, worktreePath, baseSha); await git(pi, cwd, ["worktree", "remove", "--force", worktreePath], 1e4); } } async function pruneWorktrees(pi, cwd) { try { await git(pi, cwd, ["worktree", "prune"], 5e3); } catch { } } // src/nested-tools.ts var maxSubagentDepth = 2; function getMaxSubagentDepth() { return maxSubagentDepth; } function setMaxSubagentDepth(n) { maxSubagentDepth = Math.max(0, Math.floor(n)); } var NESTED_TOOL_NAMES = ["Agent", "get_subagent_result", "steer_subagent", "stop_subagent"]; var NESTED_BACKGROUND_ERROR = "Background agents are not available inside a subagent: when you finish, this session ends and nothing is left to receive the result. Omit run_in_background; the call blocks and returns the child's result inline."; var NESTED_WORKFLOW_ERROR = "Workflows are not available inside a subagent: a workflow runs in the background and reports to the session that started it, and this session ends when you return your answer. Do the work directly, or call Agent in the foreground."; var NESTED_WORKFLOW_NO_AGENT_ERROR = "Workflows are not available inside a subagent: a workflow runs in the background and reports to the session that started it, and this session ends when you return your answer. Nested subagents are disabled for this session, so there is no Agent tool either. Do the work directly."; function textResult(text, isError = false) { return { content: [{ type: "text", text }], isError, details: {} }; } function ownsRecord(record, parentAgentId) { return record?.parentAgentId === parentAgentId; } function formatRecord(record, position) { const note = [modelSelectionNote(record), modelIdentityNote(record)].filter(Boolean).join("\n"); return note ? `${note} ${formatOutcome(record, position)}` : formatOutcome(record, position); } function formatOutcome(record, position) { if (record.status === "error") { return `Agent failed: ${record.error ?? "unknown error"}${partialOutputSuffix(record)}`; } if (record.status === "queued" || record.status === "running") { return `Agent ${record.id} is ${record.status}.`; } const text = record.result?.trim() || record.error?.trim() || "No output."; const note = position === "inline" ? getForegroundOutcomeNote(record.status, record.stoppedBy) : getStatusNote(record.status, record.stoppedBy); return note ? `Nested agent${note}. ${text}` : text; } function loadNestedRegistry(scope) { return buildAgentRegistry(loadCustomAgents(scope.configCwd, false, { projectTrusted: scope.projectTrusted, homeDir: scope.homeDir })); } function allowedTypeSet(registry, allowedSubagents) { return allowedSubagents === "all" ? void 0 : new Set(allowedSubagents.map((name) => resolveTypeIn(registry, name) ?? name)); } function availableNestedTypes(registry, allowedSubagents) { const allowed = allowedTypeSet(registry, allowedSubagents); return getAvailableTypesIn(registry).filter((name) => allowed === void 0 || allowed.has(name)); } function hasNestableTypes(allowedSubagents, scope) { return availableNestedTypes(loadNestedRegistry(scope), allowedSubagents).length > 0; } function createNestedSubagentTools(context) { const loadRegistry = () => loadNestedRegistry(context); const allowedTypesIn = (registry) => allowedTypeSet(registry, context.allowedSubagents); const availableIn = (registry) => availableNestedTypes(registry, context.allowedSubagents); const listAvailable = (registry) => { const names = availableIn(registry); return names.length > 0 ? names.join(", ") : "no agent types are currently available"; }; const agentTool = defineTool({ name: NESTED_TOOL_NAMES[0], label: "Agent", description: "Launch a child-safe nested subagent for bounded delegated work. Only use agent types allowed by this parent agent; nesting is depth-limited.", parameters: Type2.Object({ prompt: Type2.String({ description: "Self-contained task for the nested agent." }), description: Type2.String({ description: "Short 3-5 word task description." }), subagent_type: Type2.String({ description: `Allowed nested agent type. Available: ${listAvailable(loadRegistry())}.` }), model: Type2.Optional(Type2.String({ description: "Optional configured @tier or provider/model override; explicit values win over agentModels and the definition." })), thinking: Type2.Optional(Type2.String({ description: "Optional thinking level." })), max_turns: Type2.Optional(Type2.Number({ minimum: 1 })), run_in_background: Type2.Optional( Type2.Boolean({ description: "Not supported inside a subagent: nested spawns always block and return the child's result inline. Passing true returns an error." }) ), resume: Type2.Optional(Type2.String({ description: "Resume a nested agent owned by this parent." })), isolated: Type2.Optional(Type2.Boolean()), inherit_context: Type2.Optional(Type2.Boolean()), ...isolationParam(isWorktreeIsolationEnabled()) }), execute: async (_toolCallId, params, signal, _onUpdate, ctx) => { if (params.run_in_background === true) return textResult(NESTED_BACKGROUND_ERROR, true); if (params.resume) { const existing = context.manager.getRecord(params.resume); if (!ownsRecord(existing, context.parentAgentId)) { return textResult(`Nested agent not found or not owned by this parent: "${params.resume}".`, true); } if (existing.status === "running" || existing.status === "queued") { return textResult( `Nested agent "${params.resume}" is still ${existing.status}; it can only be resumed once its current run finishes.`, true ); } const resumed = await context.manager.resume(params.resume, params.prompt, signal, { maxTurns: getAgentConfigIn(loadRegistry(), existing.type)?.maxTurns ?? params.max_turns }); return resumed ? textResult(formatRecord(resumed, "inline"), resumed.status === "error") : textResult(`Failed to resume nested agent "${params.resume}".`, true); } if (context.depth >= context.maxSubagentDepth) { return textResult( `Nested subagent call blocked (depth=${context.depth}, max=${context.maxSubagentDepth}). Complete the task directly.`, true ); } const registry = loadRegistry(); const rawType = params.subagent_type; const resolvedType = resolveEnabledTypeIn(registry, rawType); if (resolvedType === void 0) { if (availableIn(registry).length === 0) { return textResult( `No nested agent types are available to this parent, so Agent cannot spawn anything. Do the work yourself, inline.`, true ); } return textResult( `Unknown or disabled nested agent type: "${rawType}". Allowed: ${availableIn(registry).join(", ")}.`, true ); } const allowed = allowedTypesIn(registry); if (allowed !== void 0 && !allowed.has(resolvedType)) { return textResult( `Nested agent type "${resolvedType}" is not allowed for this parent. Allowed: ${[...allowed].join(", ")}.`, true ); } const config = getAgentConfigIn(registry, resolvedType); const invocation = resolveAgentInvocationConfig(config, params, { worktreeAllowed: isWorktreeIsolationEnabled(), defaultRunInBackground: false }); const selection = selectModel({ homeDir: context.homeDir, agentType: resolvedType, definitionModel: config?.model, paramModel: params.model, parentModel: ctx.model, registry: ctx.modelRegistry, cwd: context.configCwd, agentLabel: config?.displayName }); if (typeof selection === "string") return textResult(selection, true); const model = selection.model; const rootSessionId = context.manager.getRecord(context.parentAgentId)?.rootSessionId; const childDepth = context.depth + 1; const options = { homeDir: context.homeDir, description: params.description, model, modelSelection: selection, maxTurns: invocation.maxTurns, isolated: invocation.isolated, inheritContext: invocation.inheritContext, thinkingLevel: invocation.thinking, isolation: invocation.isolation, invocation: { thinking: invocation.thinking, maxTurns: invocation.maxTurns, isolated: invocation.isolated, inheritContext: invocation.inheritContext, isolation: invocation.isolation }, // Nested children are hidden from every reporting surface, so their spend // would otherwise be unattributable. Fold it into every ancestor's record: // the top-level one appears in lifecycle events, completion notifications, // and `/agents`, and those all read `lifetimeUsage`. The whole chain is // walked, not just the immediate parent — a spawn callback only fires for // that child's OWN turns, so stopping at one level would hide a // great-grandchild from the only record anyone can see. (The live // widget/fleet counters read their own per-agent activity tracker, which // still sees only the top-level agent's own turns.) onAssistantUsage: (usage) => { for (let id = context.parentAgentId; id !== void 0; ) { const ancestor = context.manager.getRecord(id); if (!ancestor) break; addUsage(ancestor.lifetimeUsage, usage); id = ancestor.parentAgentId; } }, depth: childDepth, parentAgentId: context.parentAgentId, maxSubagentDepth: context.maxSubagentDepth, configCwd: context.configCwd, configProjectTrusted: context.projectTrusted, rootSessionId }; const transcriptSessionId = rootSessionId !== void 0 && (config?.outputTranscript ?? getOutputTranscriptDefault()) ? rootSessionId : void 0; let childId; const attachTranscript = (id) => { childId = id; if (transcriptSessionId === void 0) return; const rec = context.manager.getRecord(id); if (!rec) return; rec.outputFile = createOutputFilePath(context.configCwd, id, transcriptSessionId); writeInitialEntry(rec.outputFile, id, params.prompt, ctx.cwd); }; options.onSessionCreated = (session) => { const rec = childId === void 0 ? void 0 : context.manager.getRecord(childId); if (rec?.outputFile && childId !== void 0) { rec.outputCleanup = streamToOutputFile(session, rec.outputFile, childId, ctx.cwd); } }; try { const { record } = await context.manager.spawnAndWait( context.pi, ctx, resolvedType, params.prompt, { ...options, signal, onPrepare: attachTranscript } ); return textResult(formatRecord(record, "inline"), record.status === "error"); } catch (err) { return textResult(errorMessage(err), true); } } }); const resultTool = defineTool({ name: NESTED_TOOL_NAMES[1], label: "Get Nested Agent Result", description: "Check or wait for a background nested agent owned by this parent.", parameters: Type2.Object({ agent_id: Type2.String(), wait: Type2.Optional(Type2.Boolean()) }), execute: async (_toolCallId, params, signal) => { const record = context.manager.getRecord(params.agent_id); if (!ownsRecord(record, context.parentAgentId)) { return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true); } if (params.wait && (record.status === "queued" || record.status === "running")) { while (record.status === "queued") { await abortable(new Promise((resolve6) => setTimeout(resolve6, 250)), signal); } if (record.promise) await abortable(record.promise, signal); } return textResult(formatRecord(record, "fetched"), record.status === "error"); } }); const steerTool = defineTool({ name: NESTED_TOOL_NAMES[2], label: "Steer Nested Agent", description: "Send guidance to a running nested agent owned by this parent.", parameters: Type2.Object({ agent_id: Type2.String(), message: Type2.String() }), execute: async (_toolCallId, params) => { const record = context.manager.getRecord(params.agent_id); if (!ownsRecord(record, context.parentAgentId) || record.status !== "running") { return textResult(`Running nested agent not found or not owned by this parent: "${params.agent_id}".`, true); } if (!record.session) { if (!record.pendingSteers) record.pendingSteers = []; record.pendingSteers.push(params.message); return textResult(`Steering message queued for nested agent ${params.agent_id}.`); } try { await record.session.steer(params.message); } catch (err) { return textResult(`Failed to steer nested agent: ${err instanceof Error ? err.message : String(err)}`, true); } return textResult(`Steering message sent to nested agent ${params.agent_id}.`); } }); const stopTool = defineTool({ name: NESTED_TOOL_NAMES[3], label: "Stop Nested Agent", description: "Stop a running or queued nested agent owned by this parent. It ends with status `stopped` before its next tool call.", parameters: Type2.Object({ agent_id: Type2.String() }), execute: async (_toolCallId, params) => { const record = context.manager.getRecord(params.agent_id); if (!ownsRecord(record, context.parentAgentId) || record.status !== "running" && record.status !== "queued") { return textResult(`Running nested agent not found or not owned by this parent: "${params.agent_id}".`, true); } context.manager.abort(record.id, "parent"); return textResult(`Nested agent ${params.agent_id} stopped.`); } }); return [agentTool, resultTool, steerTool, stopTool]; } // src/plan-mode-children.ts var PLAN_MODE_STATE_QUERY = "pi-plan-mode:state-query"; var PLAN_MODE_GATE_QUERY = "pi-plan-mode:gate-query"; var PLAN_MODE_STATE_VERSION = 1; var planModeSeen = /* @__PURE__ */ new WeakSet(); function answerPlanGateQueries(events) { events.on(PLAN_MODE_GATE_QUERY, (data) => { planModeSeen.add(events); const reply = data?.reply; if (typeof reply === "function") reply({ version: PLAN_MODE_STATE_VERSION, gate: "@nredd/pi-subagents" }); }); } var PLAN_MODE_SILENT_ERROR = "Plan mode is installed but did not answer whether it is planning, so this subagent was not started. Reload Pi, or update @nredd/pi-plan-mode and @nredd/pi-subagents together."; var FAIL_CLOSED_TOOLS = /* @__PURE__ */ new Set(["read", "grep", "find", "ls"]); var failClosedPolicy = ({ toolName }) => FAIL_CLOSED_TOOLS.has(toolName) ? void 0 : `Plan mode is active and sent no tool policy this subagent understands, so '${toolName}' is blocked.`; function queryPlanPolicy(events, silent = "refuse") { if (!events) return void 0; const policies = []; let answered = false; events.emit(PLAN_MODE_STATE_QUERY, { version: PLAN_MODE_STATE_VERSION, reply: (state2) => { const answer = state2; if (answer?.version !== PLAN_MODE_STATE_VERSION || typeof answer.active !== "boolean") { policies.push(failClosedPolicy); return; } answered = true; if (!answer.active) return; policies.push(typeof answer.evaluate === "function" ? answer.evaluate : failClosedPolicy); } }); if (!answered && policies.length === 0 && planModeSeen.has(events)) { if (silent === "refuse") throw new Error(PLAN_MODE_SILENT_ERROR); return failClosedPolicy; } if (policies.length === 0) return void 0; return (call) => { for (const policy2 of policies) { const reason = policy2(call); if (reason !== void 0) return reason; } return void 0; }; } function planningNow(events) { return queryPlanPolicy(events, "restrict") !== void 0; } function planSteerBlocked(record, events) { return (record.status === "running" || record.status === "queued") && !record.planGate?.policy && planningNow(events); } function planSteerRefusal(id) { return `Cannot steer agent "${id}" while Plan mode is active: it started before Plan and runs without Plan's restrictions, so a steer could make it edit. Wait for it to finish and steer it then (that resumes it read-only), stop it with stop_subagent, or leave Plan mode (/plan exit) first.`; } var PLAN_SCHEDULE_REFUSAL = "Cannot schedule an agent while Plan mode is active: it would start later, after Plan, without Plan's restrictions. Start it now, or leave Plan mode first."; var PLAN_PARK_REFUSAL = "The agent was not started or parked: Plan mode is active, and a parked agent would start after Plan without Plan's restrictions. Retry after the reset, or leave Plan mode first."; function planGateReason(gate, call, tools, exempt) { const policy2 = gate?.policy; if (!policy2 || exempt.has(call.toolName)) return void 0; return policy2({ ...call, tool: tools().find((tool) => tool.name === call.toolName) }); } var PLAN_MODE_CHILD_PROMPT = ` Your parent is in Plan mode, so you are too: investigate and report, do not change anything. edit and write are blocked, bash runs only reviewed read-only commands, and other tools run only when Plan mode admits them. `; // src/prompts.ts function buildAgentPrompt(config, cwd, env, parentSystemPrompt, extras) { const activeAgentTag = ` `; const envBlock = `# Environment Working directory: ${cwd} ${env.isGitRepo ? `Git repository: yes Branch: ${env.branch}` : "Not a git repository"} Platform: ${env.platform}`; const worktreeBlock = extras?.worktreeBase ? ` Your working directory is an isolated git worktree copy of ${extras.worktreeBase}. Work only inside it \u2014 never in ${extras.worktreeBase}, even if other instructions name that path as your working directory. ` : ""; const workflowBlock = extras?.workflowChild ? ` Your final message IS the return value of this task. A workflow script captures it and passes it to the next stage; no person reads it. Return only the answer, in exactly the shape the prompt asks for \u2014 no preamble, no summary of what you did, no offer to continue. ` : ""; const planModeBlock = extras?.planMode ? ` ${PLAN_MODE_CHILD_PROMPT}` : ""; const nestingBlock = extras?.nestingDisabled ? ` Nested subagents are disabled for this session, so you have no Agent tool. Do the work yourself, inline. Do not emulate subagents by running another agent CLI (e.g. \`claude -p\`) from bash. ` : ""; const extraSections = []; if (extras?.memoryBlock) { extraSections.push(extras.memoryBlock); } if (extras?.skillBlocks?.length) { for (const skill of extras.skillBlocks) { extraSections.push(` # Preloaded Skill: ${skill.name} ${skill.content}`); } } const extrasSuffix = extraSections.length > 0 ? "\n\n" + extraSections.join("\n") : ""; if (config.promptMode === "append") { const identity = parentSystemPrompt || genericBase; const bridge = ` You are operating as a sub-agent invoked to handle a specific task. - Use the read tool instead of cat/head/tail - Use the edit tool instead of sed/awk - Use the write tool instead of echo/heredoc - Use the find tool instead of bash find/ls for file search - Use the grep tool instead of bash grep/rg for content search - Make independent tool calls in parallel - Use absolute file paths - Do not use emojis - Be concise but complete `; const customSection = config.systemPrompt?.trim() ? ` ${config.systemPrompt} ` : ""; return identity + "\n\n" + bridge + "\n\n" + activeAgentTag + envBlock + worktreeBlock + planModeBlock + workflowBlock + nestingBlock + customSection + extrasSuffix; } const replaceHeader = `You are a pi coding agent sub-agent. You have been invoked to handle a specific task autonomously. ${envBlock}`; return activeAgentTag + replaceHeader + worktreeBlock + planModeBlock + workflowBlock + nestingBlock + "\n\n" + config.systemPrompt + extrasSuffix; } var genericBase = `# Role You are a general-purpose coding agent for complex, multi-step tasks. You have full access to read, write, edit files, and execute commands. Do what has been asked; nothing more, nothing less.`; // src/resource-loader.ts import { DefaultPackageManager as DefaultPackageManager2, DefaultResourceLoader, SettingsManager as SettingsManager2 } from "@earendil-works/pi-coding-agent"; var RESOURCE_FIELDS = ["extensions", "skills", "prompts", "themes"]; function expandSetting(entry, homeDir, modifiers = true) { const prefix = modifiers && /^[!+-]/.test(entry) ? entry[0] : ""; const path = entry.slice(prefix.length); const trimmed = path.trim(); if (trimmed !== "~" && !trimmed.startsWith("~/") && !(process.platform === "win32" && trimmed.startsWith("~\\"))) return entry; return prefix + normalizeHomePath(trimmed, homeDir); } function normalizeResourceSettings(settings, homeDir) { const normalized = { ...settings }; for (const field of RESOURCE_FIELDS) { if (settings[field]) normalized[field] = settings[field].map((entry) => expandSetting(entry, homeDir)); } if (settings.packages) { normalized.packages = settings.packages.map((pkg) => { if (typeof pkg === "string") return expandSetting(pkg, homeDir, false); const copy = { ...pkg, source: expandSetting(pkg.source, homeDir, false) }; for (const field of RESOURCE_FIELDS) { if (pkg[field]) copy[field] = pkg[field].map((entry) => expandSetting(entry, homeDir)); } return copy; }); } return normalized; } function normalizeHomeResourceSettings(settingsManager, homeDir) { const globalSettings = settingsManager.getGlobalSettings.bind(settingsManager); const projectSettings = settingsManager.getProjectSettings.bind(settingsManager); Object.assign(settingsManager, { getGlobalSettings: () => normalizeResourceSettings(globalSettings(), homeDir), getProjectSettings: () => normalizeResourceSettings(projectSettings(), homeDir) }); return settingsManager; } function createHomePackageManager(options, homeDir) { if (homeDir === void 0) return new DefaultPackageManager2(options); return new DefaultPackageManager2({ ...options, homeDir, settingsManager: normalizeHomeResourceSettings(options.settingsManager, homeDir) }); } function createHomeResourceLoader(options, homeDir) { if (homeDir === void 0) return new DefaultResourceLoader(options); const settingsManager = options.settingsManager ?? SettingsManager2.create(options.cwd, options.agentDir); return new DefaultResourceLoader({ ...options, homeDir, settingsManager: normalizeHomeResourceSettings(settingsManager, homeDir) }); } // src/skill-loader.ts import { existsSync as existsSync7, mkdirSync as mkdirSync3, mkdtempSync, readdirSync as readdirSync3, readFileSync as readFileSync7, realpathSync as realpathSync3, rmSync, statSync as statSync5, symlinkSync } from "node:fs"; import { homedir as homedir4, tmpdir as tmpdir3 } from "node:os"; import { dirname as dirname2, isAbsolute as isAbsolute2, join as join8, relative as relative3, resolve as resolve4, sep as sep2 } from "node:path"; import { loadSkills, SettingsManager as SettingsManager3 } from "@earendil-works/pi-coding-agent"; var skipMissingSource = async () => "skip"; async function preloadSkills(skillNames, cwd, options) { if (skillNames.length === 0) return []; const primary = createHomePackageManager({ cwd, agentDir: options.agentDir, settingsManager: options.settingsManager }, options.homeDir); const primaryResources = await primary.resolve(skipMissingSource); const fallbackSettings = SettingsManager3.create(cwd, options.agentDir, { projectTrusted: false }); const fallback = createHomePackageManager({ cwd, agentDir: options.agentDir, settingsManager: fallbackSettings }, options.homeDir); const fallbackResources = await fallback.resolve(skipMissingSource); const rejectedProjectPaths = new Set(primaryResources.skills.filter((resource) => isTier(resource, "project") && isSymlinkedProjectSkill(resource, cwd)).map((resource) => canonicalPath(resource.path))); const isBehindRejectedAlias = (resource) => { const canonical = canonicalPath(resource.path); return canonical !== void 0 && rejectedProjectPaths.has(canonical); }; const aliasFreeSkills = rejectedProjectPaths.size === 0 ? [] : await resolveAliasFreePackageSkills(cwd, options); const recoveredPackages = aliasFreeSkills.filter(isBehindRejectedAlias); const disabledNames = new Set(loadTier( [...primaryResources.skills, ...fallbackResources.skills, ...recoveredPackages].filter((resource) => !resource.enabled), cwd, options.agentDir ).map((skill) => skill.name)); const project = discoveredSkills( primaryResources.skills.filter((resource) => resource.enabled && isTier(resource, "project") && !isSymlinkedProjectSkill(resource, cwd)), cwd, options.agentDir ); const user = discoveredSkills( [ ...primaryResources.skills, // Only restore a user candidate Pi collapsed behind a rejected project alias. // Other fallback user resources could bypass Pi's project filters. ...fallbackResources.skills.filter(isBehindRejectedAlias) ].filter((resource) => resource.enabled && isTier(resource, "user") && !isAmbientUserAgentsSkill(resource, options.homeDir)), cwd, options.agentDir ); const packages = discoveredSkills( [ ...primaryResources.skills, // Only restore a package candidate Pi collapsed behind a rejected project alias. ...recoveredPackages ].filter((resource) => resource.enabled && isTier(resource, "package") && !isAmbientUserAgentsSkill(resource, options.homeDir)), cwd, options.agentDir ); const home = resolve4(options.homeDir ?? homedir4()); const legacyUserRoots = [join8(options.agentDir, "skills"), join8(home, ".agents", "skills"), join8(home, ".pi", "skills")]; return skillNames.map((name) => { const native = project.get(name) ?? user.get(name) ?? packages.get(name); const content = native ?? (disabledNames.has(name) ? void 0 : (options.settingsManager.isProjectTrusted() ? findInRoots(projectSkillRoots(cwd).map((root) => join8(root, "skills")), name, false) : void 0) ?? findInRoots(legacyUserRoots, name, true)); return { name, content: content ?? `(Skill "${name}" not found in Pi's configured skill resources)` }; }); } function isTier(resource, tier) { return tier === "package" ? resource.metadata.origin === "package" : resource.metadata.origin === "top-level" && resource.metadata.scope === tier; } function absolutizeProjectSource(source, cwd) { const local = resolve4(cwd, ".pi", source); return !source.startsWith("npm:") && existsSync7(local) ? local : source; } async function resolveAliasFreePackageSkills(cwd, options) { const scratch = mkdtempSync(join8(tmpdir3(), "skill-preload-")); try { for (const dir of ["npm", "git"]) { const real = join8(cwd, ".pi", dir); if (!existsSync7(real)) continue; mkdirSync3(join8(scratch, ".pi"), { recursive: true }); symlinkSync(real, join8(scratch, ".pi", dir), "dir"); } const project = options.settingsManager.getProjectSettings(); const settings = { global: options.settingsManager.getGlobalSettings(), project: { ...project, packages: project.packages?.map((pkg) => typeof pkg === "string" ? absolutizeProjectSource(pkg, cwd) : { ...pkg, source: absolutizeProjectSource(pkg.source, cwd) }) } }; const settingsManager = SettingsManager3.fromStorage( { withLock: (scope, read) => void read(JSON.stringify(settings[scope])) }, { projectTrusted: options.settingsManager.isProjectTrusted() } ); const manager = createHomePackageManager({ cwd: scratch, agentDir: options.agentDir, settingsManager }, options.homeDir); return (await manager.resolve(skipMissingSource)).skills.filter((resource) => resource.metadata.origin === "package"); } finally { rmSync(scratch, { recursive: true, force: true }); } } function loadTier(resources, cwd, agentDir) { return loadSkills({ cwd, agentDir, skillPaths: resources.map((resource) => resource.path), includeDefaults: false }).skills; } function discoveredSkills(resources, cwd, agentDir) { return new Map(loadTier(resources, cwd, agentDir).map((skill) => [skill.name, readFileSync7(skill.filePath, "utf-8").trim()])); } function findInRoots(roots, name, trusted) { if (isUnsafeName(name)) return void 0; for (const root of roots) { const content = findInRoot(root, name, trusted); if (content !== void 0) return content; } return void 0; } function findInRoot(root, name, trusted) { if (!trusted && isPathThroughSymlink(dirname2(root), root)) return void 0; const flat = readSkillFile(join8(root, `${name}.md`), trusted)?.trim(); if (flat !== void 0) return flat; if (!existsSync7(root)) return void 0; const queue = [root]; const seen = /* @__PURE__ */ new Set(); for (const current of queue) { if (trusted) { const canonical = canonicalPath(current); if (canonical === void 0 || seen.has(canonical)) continue; seen.add(canonical); } let entries; try { entries = readdirSync3(current, { withFileTypes: true }).sort((left, right) => Number(left.name > right.name) - Number(left.name < right.name)); } catch { continue; } for (const entry of entries) { if (entry.name.startsWith(".") || entry.name === "node_modules") continue; const path = join8(current, entry.name); if (!trusted && isPathThroughSymlink(dirname2(root), path)) continue; const isDirectory = entry.isDirectory() || trusted && entry.isSymbolicLink() && isDirectoryTarget(path); if (!isDirectory) continue; const skillFile = join8(path, "SKILL.md"); if (existsSync7(skillFile)) { const content = entry.name === name ? readSkillFile(skillFile, trusted)?.trim() : void 0; if (content !== void 0) return content; continue; } queue.push(path); } } return void 0; } function readSkillFile(path, trusted) { if (!trusted) return safeReadFile(path); try { return statSync5(path).isFile() ? readFileSync7(path, "utf-8") : void 0; } catch { return void 0; } } function isDirectoryTarget(path) { try { return statSync5(path).isDirectory(); } catch { return false; } } function canonicalPath(path) { try { return realpathSync3(path); } catch { return void 0; } } function isAmbientUserAgentsSkill(resource, homeDir, runtimeHome = homedir4()) { if (homeDir === void 0 || resource.metadata.scope !== "user" || resource.metadata.source !== "auto") return false; const injectedRoot = join8(resolve4(homeDir), ".agents", "skills"); return !isPathWithin(injectedRoot, resource.path) && isPathWithin(join8(runtimeHome, ".agents", "skills"), resource.path); } function isSymlinkedProjectSkill(resource, cwd) { return projectSkillRoots(cwd).some((root) => isPathThroughSymlink(root, resource.path)); } function projectSkillRoots(cwd) { const roots = [join8(cwd, ".pi")]; let directory = resolve4(cwd); while (true) { roots.push(join8(directory, ".agents")); if (existsSync7(join8(directory, ".git"))) break; const parent = dirname2(directory); if (parent === directory) break; directory = parent; } return roots; } function isPathWithin(root, path) { const relativePath = relative3(resolve4(root), resolve4(path)); return relativePath === "" || !relativePath.startsWith(`..${sep2}`) && relativePath !== ".." && !isAbsolute2(relativePath); } function isPathThroughSymlink(root, path) { const absoluteRoot = resolve4(root); if (!isPathWithin(absoluteRoot, path)) return false; const relativePath = relative3(absoluteRoot, resolve4(path)); let current = absoluteRoot; if (isSymlink(current)) return true; for (const segment of relativePath.split(sep2)) { current = join8(current, segment); if (isSymlink(current)) return true; } return false; } // src/stale-ctx.ts var STALE_CTX_RE = /extension ctx is stale after session replacement or reload/i; function isStaleCtxError(error) { const message = error instanceof Error ? error.message : typeof error === "string" ? error : ""; return STALE_CTX_RE.test(message); } // src/structured-output.ts import { defineTool as defineTool2 } from "@earendil-works/pi-coding-agent"; var STRUCTURED_OUTPUT_TOOL_NAME = "StructuredOutput"; function createStructuredCapture() { return { called: false }; } function createStructuredOutputTool(compiled, capture) { return defineTool2({ name: STRUCTURED_OUTPUT_TOOL_NAME, label: "Structured Output", description: "Report your final answer. Call this exactly once, with the complete result, and put everything the caller needs inside the arguments \u2014 text written outside this call is discarded. If a call is rejected for not matching the schema, fix the reported fields and call it again.", promptSnippet: "Report your final answer as structured data", promptGuidelines: [ "Your final answer MUST be reported by calling StructuredOutput. Prose outside that call is discarded." ], // The caller's schema *is* the tool's input schema, verbatim — that is what // makes the provider fill the fields. pi types this as TypeBox's `TSchema`, // which v1 defines as an open interface, so a plain JSON Schema satisfies // it without a cast at runtime or a conversion at author time. parameters: compiled.schema, // "prefer", not "require": a provider that cannot constrain sampling should // fall through to validation-and-retry rather than fail the call outright. constrainedSampling: { type: "json_schema", strict: "prefer" }, // Models occasionally send the whole payload as one JSON string instead of // an object. Recovering that costs nothing and saves a whole retry. prepareArguments: (args) => { if (typeof args !== "string") return args; try { return JSON.parse(args); } catch { return args; } }, execute: async (_toolCallId, params) => { capture.called = true; const verdict = compiled.check(params); if (verdict !== true) { capture.lastError = verdict; return { content: [{ type: "text", text: `StructuredOutput did not match the required schema: ${verdict} Call it again with a corrected value.` }], isError: true, details: {} }; } capture.json = JSON.stringify(params); capture.lastError = void 0; return { content: [{ type: "text", text: "Recorded." }], details: {} }; } }); } function structuredRetryPrompt(capture) { const reason = capture.called && capture.lastError !== void 0 ? `Your last ${STRUCTURED_OUTPUT_TOOL_NAME} call did not match the required schema: ${capture.lastError}` : `You did not call ${STRUCTURED_OUTPUT_TOOL_NAME}, so your answer was not recorded.`; return `${reason} Call ${STRUCTURED_OUTPUT_TOOL_NAME} now with your complete final answer. Do not reply with prose.`; } // src/agent-runner.ts var SUBAGENT_TOOL_NAMES = { AGENT: "Agent", WORKFLOW: "SubagentWorkflow", GET_RESULT: "get_subagent_result", STEER: "steer_subagent", STOP: "stop_subagent" }; var BLOCKED_IN_SUBAGENT = /* @__PURE__ */ new Set([SUBAGENT_TOOL_NAMES.WORKFLOW, "Workflow", "workflow"]); function createWorkflowRefusalTool(reason) { return defineTool3({ name: SUBAGENT_TOOL_NAMES.WORKFLOW, label: "SubagentWorkflow", description: "Not available inside a subagent; calling it explains why.", // Open object: whatever arguments the model sends, the refusal is the answer. parameters: Type3.Object({}), execute: async () => { throw new Error(reason); } }); } var EXCLUDED_TOOL_NAMES = Object.values(SUBAGENT_TOOL_NAMES); function extensionCanonicalName(extPath) { const base = basename3(extPath); const name = base === "index.ts" || base === "index.js" ? basename3(dirname3(extPath)) : base.replace(/\.(ts|js)$/, ""); return name.toLowerCase(); } function extensionPackageName(extPath) { if (extPath.startsWith("builtin:")) return void 0; const entry = resolve5(extPath); const indexDir = /^index\.(ts|js)$/.test(basename3(entry)) ? dirname3(entry) : void 0; let dir = dirname3(extPath); for (; ; ) { if (basename3(dir) === "node_modules") return void 0; let pkg; try { pkg = JSON.parse(readFileSync8(join9(dir, "package.json"), "utf-8")); } catch { const parent = dirname3(dir); if (parent === dir) return void 0; dir = parent; continue; } const entries = pkg.pi?.extensions; if (typeof pkg.name === "string" && Array.isArray(entries) && entries.some((e) => { if (typeof e !== "string") return false; const declared = resolve5(dir, e); return declared === entry || declared === indexDir; })) { const short = pkg.name.startsWith("@") ? pkg.name.slice(pkg.name.indexOf("/") + 1) : pkg.name; return short.toLowerCase(); } return void 0; } } function extensionCanonicalNames(extPath) { const canonical = extensionCanonicalName(extPath); const pkg = extensionPackageName(extPath); return pkg && pkg !== canonical ? [canonical, pkg] : [canonical]; } function parseExtensionsSpec(entries, cwd, homeDir = homedir5()) { const names = /* @__PURE__ */ new Set(); const paths = []; let wildcard = false; for (const entry of entries) { if (!entry) continue; if (entry === "*") { wildcard = true; continue; } const isPathEntry = entry.includes("/") || entry.includes("\\") || entry.startsWith("~"); if (!isPathEntry) { names.add(entry.toLowerCase()); continue; } let p = entry; if (p === "~" || p.startsWith("~/") || p.startsWith("~\\")) p = homeDir + p.slice(1); const abs = isAbsolute3(p) ? p : resolve5(cwd, p); paths.push(abs); names.add(extensionCanonicalName(abs)); } return { names, paths, wildcard }; } function parseExtSelectors(entries) { const extNames = /* @__PURE__ */ new Set(); const narrowing = /* @__PURE__ */ new Map(); for (const raw of entries) { if (!raw) continue; const body = raw.slice("ext:".length); const slash = body.indexOf("/"); const name = (slash === -1 ? body : body.slice(0, slash)).trim().toLowerCase(); if (!name) continue; extNames.add(name); if (slash === -1) continue; const tool = body.slice(slash + 1).trim(); if (!tool) continue; let set = narrowing.get(name); if (!set) { set = /* @__PURE__ */ new Set(); narrowing.set(name, set); } set.add(tool); } return { extNames, narrowing }; } function installExtensionToolScope(session, ctx) { const { loader, toolNames, disallowedSet, extNames, narrowing, readmitToolNames, nestedCallGate, workflowError } = ctx; const inScope = () => { const keep = new Set(toolNames.filter((t) => !disallowedSet?.has(t))); const optInActive = extNames.size > 0; for (const extension of loader.getExtensions().extensions) { const canons = extensionCanonicalNames(extension.path); if (optInActive && !canons.some((c) => extNames.has(c))) continue; const narrowed = canons.map((c) => narrowing.get(c)).find(Boolean); for (const name of extension.tools.keys()) { if (narrowed && !narrowed.has(name)) continue; if (disallowedSet?.has(name)) continue; keep.add(name); } } for (const name of EXCLUDED_TOOL_NAMES) keep.delete(name); for (const name of readmitToolNames) keep.add(name); return keep; }; const named = /* @__PURE__ */ new Set([...toolNames, ...readmitToolNames, ...[...narrowing.values()].flatMap((s) => [...s])]); const renarrow = () => { const allowed = inScope(); const current = session.getActiveToolNames(); const active = new Set(current); const next = session.getAllTools().filter(({ name, exposure = "direct" }) => { if (!allowed.has(name)) return false; if (active.has(name)) return true; if (exposure !== "direct" && exposure !== "model-only") return false; return named.has(name) || session.getToolDefinition(name)?.defaultActive !== false; }).map((t) => t.name); if (next.length !== current.length || next.some((n, i) => n !== current[i])) { session.setActiveToolsByName(next); } }; renarrow(); session.subscribe((event) => { if (event.type === "turn_end") renarrow(); }); nestedCallGate.allows = (name) => inScope().has(name); const priorBeforeToolCall = session.agent.beforeToolCall; session.agent.beforeToolCall = async (context, signal) => { if (BLOCKED_IN_SUBAGENT.has(context.toolCall.name)) { return { block: true, reason: workflowError }; } if (!inScope().has(context.toolCall.name)) { return { block: true, reason: `Tool "${context.toolCall.name}" is not available to this subagent.` }; } return priorBeforeToolCall?.(context, signal); }; } var SCOPE_GATE_NAME = "pi-subagents-scope"; function scopeGateExtension(gate) { return { name: SCOPE_GATE_NAME, hidden: true, factory: (ext) => { ext.on("tool_call", (event, ctx) => { if (gate.allows?.(event.toolName) === false) { return { block: true, reason: `Tool "${event.toolName}" is not available to this subagent.` }; } const reason = gate.planReason?.(event.toolName, event.input, ctx.cwd); return reason === void 0 ? void 0 : { block: true, reason }; }); } }; } var defaultMaxTurns; function normalizeMaxTurns(n) { if (n == null || n === 0) return void 0; return Math.max(1, n); } function getDefaultMaxTurns() { return defaultMaxTurns; } function setDefaultMaxTurns(n) { defaultMaxTurns = normalizeMaxTurns(n); } function resolveEffectiveMaxTurns(type, explicit) { return normalizeMaxTurns(explicit ?? getAgentConfig(type)?.maxTurns ?? defaultMaxTurns); } var rememberAgents = true; function getRememberAgents() { return rememberAgents; } function setRememberAgents(b) { rememberAgents = b; } var graceTurns = 5; function getGraceTurns() { return graceTurns; } function setGraceTurns(n) { graceTurns = Math.max(1, n); } var FINAL_REPORT_PROMPT = "You are out of turns and have no tools left. Do NOT call any tool or say what you would do next. Write your complete final report now: everything you found, concrete file paths and line numbers, what you changed or concluded, and anything unfinished or unverified."; function collectResponseText(session) { let text = ""; let laterTool = false; let previousText = ""; let previousLaterTool = false; const unsubscribe = session.subscribe((event) => { if (event.type === "message_start" && event.message.role === "assistant") { if (text.trim()) { previousText = text; previousLaterTool = laterTool; } text = ""; laterTool = false; } if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") { text += event.assistantMessageEvent.delta; } if (event.type === "tool_execution_end") { if (text.trim()) laterTool = true; else if (previousText.trim()) previousLaterTool = true; } }); return { getText: () => text, getPreviousText: () => previousText, hasLaterTool: () => text.trim() ? laterTool : previousLaterTool, unsubscribe }; } function getLastAssistantText(session, startIndex) { for (let i = session.messages.length - 1; i >= startIndex; i--) { const msg = session.messages[i]; if (msg.role !== "assistant") continue; const text = extractText(msg.content).trim(); if (text) return text; } return ""; } function forwardModelCall(event, emit) { if (event.type === "message_start") { if (event.message.role === "assistant") emit({ type: "start" }); } else if (event.type === "message_end") { if (event.message.role === "assistant") emit({ type: "end" }); } else if (event.type === "message_update") { const e = event.assistantMessageEvent; if (e.type === "thinking_delta") emit({ type: "delta", kind: "thinking", chars: e.delta.length }); else if (e.type === "text_delta" || e.type === "toolcall_delta") emit({ type: "delta", kind: "writing", chars: e.delta.length }); else emit({ type: "beat" }); } else if (event.type === "tool_execution_start") { emit({ type: "end" }); } } function endedWithReport(session, startIndex) { for (let i = session.messages.length - 1; i >= startIndex; i--) { const msg = session.messages[i]; if (msg.role !== "assistant") continue; const hasToolCall = msg.content.some((c) => c.type === "toolCall"); const cutOff = msg.stopReason === "aborted" || msg.stopReason === "toolUse" || msg.stopReason === "length"; return !hasToolCall && !cutOff && extractText(msg.content).trim() !== ""; } return false; } var FINAL_REPORT_TOOL_BLOCKED = "No tools are available for the final report. Write the report as text now."; async function forceFinalReport(session, startIndex, signal) { const previousTools = session.getActiveToolNames(); const setActiveTools = session.setActiveToolsByName; const priorBeforeToolCall = session.agent.beforeToolCall; try { await session.waitForIdle?.(); if (signal?.aborted) return false; setActiveTools.call(session, []); session.setActiveToolsByName = () => setActiveTools.call(session, []); session.agent.beforeToolCall = async () => ({ block: true, terminate: true, reason: FINAL_REPORT_TOOL_BLOCKED }); await session.prompt(FINAL_REPORT_PROMPT); } catch { return false; } finally { session.setActiveToolsByName = setActiveTools; session.agent.beforeToolCall = priorBeforeToolCall; session.setActiveToolsByName(previousTools); } return endedWithReport(session, startIndex); } function finalTurnError(session, startIndex) { for (let i = session.messages.length - 1; i >= startIndex; i--) { const msg = session.messages[i]; if (msg.role !== "assistant") continue; if (msg.stopReason === "error") { return msg.errorMessage?.trim() || "provider error with no output"; } if (msg.stopReason === "length" && !extractText(msg.content).trim()) { return "run hit the output token limit before producing any text"; } return void 0; } return void 0; } var STALE_CTX_RETRY_DELAYS_MS = [1e3, 3e3, 9e3]; var STALE_CTX_RETRY_PROMPT = "Your previous step was interrupted by a session reload before it produced output. Continue the task from where you left off."; function sleep(ms, signal, clock) { return new Promise((resolve6) => { if (signal?.aborted) return resolve6(); const done = () => { timer.cancel(); signal?.removeEventListener("abort", done); resolve6(); }; const timer = clock.setTimeout(done, ms); signal?.addEventListener("abort", done, { once: true }); }); } async function retryStaleCtx(session, startIndex, signal, delays = STALE_CTX_RETRY_DELAYS_MS, clock = realClock) { for (const delay of delays) { if (!isStaleCtxError(finalTurnError(session, startIndex))) return; await sleep(delay, signal, clock); if (signal?.aborted) return; await session.prompt(STALE_CTX_RETRY_PROMPT); } } function mayFollowUp(session, startIndex, signal) { return !signal?.aborted && staleCtxOutcome(session, startIndex) === void 0; } function partialProgress(session, startIndex) { const calls = []; for (let i = session.messages.length - 1; i >= startIndex && calls.length < 5; i--) { const msg = session.messages[i]; if (msg.role !== "toolResult") continue; const name = BUILTIN_TOOL_NAMES.includes(msg.toolName) ? msg.toolName : "other tool"; calls.unshift(`${name} (${msg.isError ? "failed" : "completed"})`); } return calls.length ? `Latest activity: ${calls.join(", ")}.` : ""; } function failureText(session, startIndex, text, partial, laterTool, streamed) { if (!text) return partial; if (streamed) return laterTool ? `Earlier progress: ${text} ${partial}` : text; let hasLaterResult = false; for (let i = session.messages.length - 1; i >= startIndex; i--) { const msg = session.messages[i]; if (msg.role === "assistant" && extractText(msg.content).trim() === text) break; if (msg.role === "toolResult") hasLaterResult = true; } return hasLaterResult ? `Earlier progress: ${text} ${partial}` : text; } function staleCtxOutcome(session, startIndex) { const error = finalTurnError(session, startIndex); if (!isStaleCtxError(error)) return void 0; return { failure: `interrupted by a session reload or replacement; the agent's model runtime went stale and retries did not recover it: ${error}`, partial: partialProgress(session, startIndex) }; } function observeRun(session, options) { let turnCount = 0; let currentMessageText = ""; let finalizingTurns = 0; const run = { steered: false, aborted: false, finalizing: false }; const unsubscribe = session.subscribe((event) => { if (event.type === "turn_end") { turnCount++; options.onTurnEnd?.(turnCount); if (run.finalizing) { finalizingTurns++; if (finalizingTurns > 1 || (event.toolResults?.length ?? 0) > 0) { run.aborted = true; session.abort(); } } else if (options.maxTurns != null) { if (!run.steered && turnCount >= options.maxTurns) { run.steered = true; session.steer("You have reached your turn limit. Wrap up immediately \u2014 provide your final answer now."); } else if (run.steered && turnCount >= options.maxTurns + graceTurns) { run.aborted = true; session.abort(); } } } if (options.onModelCall) forwardModelCall(event, options.onModelCall); if (event.type === "message_start") { currentMessageText = ""; } if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") { currentMessageText += event.assistantMessageEvent.delta; options.onTextDelta?.(event.assistantMessageEvent.delta, currentMessageText); } if (event.type === "tool_execution_start") { options.onToolActivity?.({ type: "start", toolName: event.toolName }); } if (event.type === "tool_execution_end") { options.onToolActivity?.({ type: "end", toolName: event.toolName }); } if (event.type === "message_end" && event.message.role === "assistant") { const u = event.message.usage; if (u) options.onAssistantUsage?.({ input: u.input ?? 0, output: u.output ?? 0, cacheWrite: u.cacheWrite ?? 0, cacheRead: u.cacheRead ?? 0, cost: u.cost?.total ?? 0 }, event.message); } if (event.type === "compaction_end" && !event.aborted && event.result) { options.onCompaction?.({ reason: event.reason, tokensBefore: event.result.tokensBefore }); } }); return Object.assign(run, { unsubscribe }); } function forwardAbortSignal(session, signal) { if (!signal) return () => { }; const onAbort = () => session.abort(); signal.addEventListener("abort", onAbort, { once: true }); return () => signal.removeEventListener("abort", onAbort); } function resolveConfiguredSessionDir(sessionDir, cwd, homeDir = homedir5()) { if (!sessionDir) return void 0; if (sessionDir === "~" || sessionDir.startsWith("~/")) return resolve5(homeDir, sessionDir.slice(2)); if (isAbsolute3(sessionDir)) return sessionDir; return resolve5(cwd, sessionDir); } async function runAgent(ctx, type, prompt, options) { const config = getConfig(type); const agentConfig = getAgentConfig(type); const effectiveCwd = options.cwd ?? ctx.cwd; const configCwd = options.configCwd ?? effectiveCwd; const env = await detectEnv(options.pi, effectiveCwd); const parentSystemPrompt = ctx.getSystemPrompt(); const agentDir = resolveAgentDir(options.homeDir); const projectTrusted = options.configCwd !== void 0 && options.configProjectTrusted !== void 0 ? options.configProjectTrusted : ctx.isProjectTrusted(); const settingsManager = SettingsManager4.create(configCwd, agentDir, { projectTrusted }); const extras = {}; if (options.worktreeBase) extras.worktreeBase = options.worktreeBase; if (options.workflow && !options.structuredOutput) extras.workflowChild = true; if (options.planGate?.policy) extras.planMode = true; const isolated = agentConfig?.isolated ?? options.isolated; const extensions = isolated ? false : config.extensions; const excludeExtensions = isolated ? void 0 : config.excludeExtensions; const skills = isolated ? false : config.skills; if (Array.isArray(skills)) { const loaded = await preloadSkills(skills, configCwd, { agentDir, settingsManager, homeDir: options.homeDir }); if (loaded.length > 0) { extras.skillBlocks = loaded; } } let toolNames = getToolNamesForType(type); if (agentConfig?.memory) { const existingNames = new Set(toolNames); const denied = agentConfig.disallowedTools ? new Set(agentConfig.disallowedTools) : void 0; const effectivelyHas = (name) => existingNames.has(name) && !denied?.has(name); const hasWriteTools = effectivelyHas("write") || effectivelyHas("edit"); if (hasWriteTools) { const extraNames = getMemoryToolNames(existingNames); if (extraNames.length > 0) toolNames = [...toolNames, ...extraNames]; extras.memoryBlock = buildMemoryBlock(agentConfig.name, agentConfig.memory, configCwd, options.homeDir); } else { const extraNames = getReadOnlyMemoryToolNames(existingNames); if (extraNames.length > 0) toolNames = [...toolNames, ...extraNames]; extras.memoryBlock = buildReadOnlyMemoryBlock(agentConfig.name, agentConfig.memory, configCwd, options.homeDir); } } const effectiveMaxDepth = options.nestedRuntime?.maxSubagentDepth ?? getMaxSubagentDepth(); const nestedRuntime = options.nestedRuntime && options.nestedRuntime.depth < effectiveMaxDepth ? options.nestedRuntime : void 0; const nestingPossible = Boolean( agentConfig?.allowedSubagents && nestedRuntime && !isolated && hasNestableTypes(agentConfig.allowedSubagents, { homeDir: options.homeDir, configCwd, projectTrusted }) ); const agentAvailable = nestingPossible && !agentConfig?.disallowedTools?.includes("Agent"); if (agentConfig?.allowedSubagents && !agentAvailable) extras.nestingDisabled = true; let systemPrompt; if (agentConfig) { systemPrompt = buildAgentPrompt(agentConfig, effectiveCwd, env, parentSystemPrompt, extras); } else { const fallback = DEFAULT_AGENTS.get("general-purpose"); if (!fallback) throw new Error(`No fallback config available for unknown type "${type}"`); systemPrompt = buildAgentPrompt({ ...fallback, name: type }, effectiveCwd, env, parentSystemPrompt, extras); } const noSkills = skills === false || Array.isArray(skills); const { extNames, narrowing } = parseExtSelectors( isolated ? [] : agentConfig?.extSelectors ?? [] ); const noExtensions = extensions === false; const extensionsSpec = Array.isArray(extensions) ? parseExtensionsSpec(extensions, configCwd, options.homeDir) : void 0; const keepNames = extensionsSpec?.names ?? /* @__PURE__ */ new Set(); const excludeNames = new Set((excludeExtensions ?? []).map((n) => n.toLowerCase())); const hasExcludes = excludeNames.size > 0; const loadAll = extensions === true || extensionsSpec?.wildcard === true; const additionalExtensionPaths = extensionsSpec?.paths.length ? extensionsSpec.paths : void 0; let discoveredNames; const extensionsOverride = noExtensions || loadAll && !hasExcludes ? void 0 : (base) => { discoveredNames = new Set(base.extensions.flatMap((e) => extensionCanonicalNames(e.path))); return { ...base, extensions: base.extensions.filter((e) => { if (e.path === ``) return true; const canons = extensionCanonicalNames(e.path); if (canons.some((n) => excludeNames.has(n))) return false; return loadAll || canons.some((n) => keepNames.has(n)); }) }; }; const sessionSettingsManager = resolve5(effectiveCwd) === resolve5(configCwd) ? settingsManager : Object.assign(SettingsManager4.create(configCwd, agentDir, { projectTrusted }), { isProjectTrusted: () => false }); const nestedCallGate = {}; const loader = createHomeResourceLoader({ settingsManager, // pi's CLI hands its built-in extensions to the loader it builds; this one starts // with none. Forwarded as `builtin:` resources they load as in the main session — // default-on, disabled by `-builtin:` in settings — and the per-agent // allowlist filters them like any other extension. pi's `llama.cpp` built-in is // CLI-only (not exported). Fresh factories per spawn: MCP state lives in the closure. extensionFactories: [ { name: "codemode", factory: createCodemodeExtension(), builtin: true, replaceable: true }, { name: "tool-search", factory: createToolSearchExtension(), builtin: true, replaceable: true }, { name: "mcp", factory: createMcpExtension(), builtin: true, replaceable: true }, // Under `noExtensions` the static allowlist gates the registry itself. ...noExtensions ? [] : [scopeGateExtension(nestedCallGate)] ], // Mirrors pi's CLI: `--no-mcp` keeps MCP out of subagents too, and `--no-extensions` // keeps all the built-ins out. Discovered extensions still follow `extensions:`. disabledBuiltinExtensions: process.argv.some((a) => a === "--no-extensions" || a === "-ne") ? ["codemode", "tool-search", "mcp"] : process.argv.includes("--no-mcp") ? ["mcp"] : void 0, cwd: configCwd, agentDir, noExtensions, additionalExtensionPaths, extensionsOverride, noSkills, noPromptTemplates: true, noThemes: true, noContextFiles: true, systemPromptOverride: () => systemPrompt, appendSystemPromptOverride: () => [] }, options.homeDir); await bindChildResourceLoader(loader).reload(); if (agentConfig?.builtinToolNames?.length) { const knownBuiltins = new Set(BUILTIN_TOOL_NAMES); for (const name of agentConfig.builtinToolNames) { if (!knownBuiltins.has(name)) { options.onToolActivity?.({ type: "end", toolName: `tools-error:tool "${name}" requested by agent "${type}" is not a known built-in` }); } } } if (hasExcludes && noExtensions) { options.onToolActivity?.({ type: "end", toolName: `extension-error:exclude_extensions has no effect for agent "${type}" \u2014 extensions: false loads nothing` }); } if (hasExcludes && discoveredNames) { for (const name of excludeNames) { if (!discoveredNames.has(name)) { options.onToolActivity?.({ type: "end", toolName: `extension-error:exclude_extensions: "${name}" for agent "${type}" did not match any discovered extension` }); } } } if (keepNames.size > 0 || extNames.size > 0) { const survivingNames = new Set( loader.getExtensions().extensions.flatMap((e) => extensionCanonicalNames(e.path)) ); for (const name of keepNames) { if (!survivingNames.has(name)) { options.onToolActivity?.({ type: "end", toolName: excludeNames.has(name) ? `extension-error:extension "${name}" is in both extensions: and exclude_extensions: for agent "${type}" \u2014 exclude wins` : `extension-error:extension "${name}" requested by agent "${type}" was not loaded` }); } } for (const name of extNames) { if (!survivingNames.has(name)) { options.onToolActivity?.({ type: "end", toolName: `extension-error:ext:${name} referenced by agent "${type}" but extension "${name}" is not loaded (check extensions:/exclude_extensions:)` }); } } } const model = options.modelSelection.model; if (options.modelSelection.fallback) options.onModelFallback?.(options.modelSelection.fallback); const thinkingLevel = options.thinkingLevel ?? agentConfig?.thinking; const disallowedSet = agentConfig?.disallowedTools ? new Set(agentConfig.disallowedTools) : void 0; const nestedTools = agentConfig?.allowedSubagents && nestedRuntime && nestingPossible ? createNestedSubagentTools({ manager: nestedRuntime.manager, pi: options.pi, parentAgentId: nestedRuntime.parentAgentId, depth: nestedRuntime.depth, maxSubagentDepth: effectiveMaxDepth, allowedSubagents: agentConfig.allowedSubagents, homeDir: options.homeDir, configCwd, projectTrusted }) : []; const nestedToolNames = new Set(nestedTools.map((tool) => tool.name)); const structuredCapture = options.structuredOutput ? createStructuredCapture() : void 0; const structuredTools = options.structuredOutput && structuredCapture ? [createStructuredOutputTool(options.structuredOutput, structuredCapture)] : []; const structuredToolNames = new Set(structuredTools.map((tool) => tool.name)); const workflowError = agentAvailable ? NESTED_WORKFLOW_ERROR : NESTED_WORKFLOW_NO_AGENT_ERROR; const refusalTools = !noExtensions && !disallowedSet?.has(SUBAGENT_TOOL_NAMES.WORKFLOW) ? [createWorkflowRefusalTool(workflowError)] : []; const readmitToolNames = /* @__PURE__ */ new Set([ ...[...nestedToolNames].filter((name) => !disallowedSet?.has(name)), ...structuredToolNames, ...refusalTools.map((tool) => tool.name) ]); const builtinToolNameSet = new Set(toolNames); let sessionTools; let sessionExcludeTools; if (noExtensions) { sessionTools = [ ...toolNames.filter( (t) => !EXCLUDED_TOOL_NAMES.includes(t) && !disallowedSet?.has(t) ), ...[...nestedToolNames].filter((t) => !disallowedSet?.has(t)), // Not filtered through `disallowedSet`, unlike the nested tools above: // the caller asked for a schema, and removing the only tool that can // satisfy it would make the request unsatisfiable by construction rather // than merely restricted. ...structuredToolNames ]; } else { const denyTools = new Set( EXCLUDED_TOOL_NAMES.filter((t) => !nestedToolNames.has(t) && !readmitToolNames.has(t)) ); for (const name of BUILTIN_TOOL_NAMES) { if (!builtinToolNameSet.has(name)) denyTools.add(name); } if (disallowedSet) { for (const name of disallowedSet) { if (!structuredToolNames.has(name)) denyTools.add(name); } } sessionExcludeTools = [...denyTools]; } const configuredSessionDir = resolveConfiguredSessionDir(agentConfig?.sessionDir, effectiveCwd, options.homeDir); const sessionDirSetting = process.env.PI_CODING_AGENT_SESSION_DIR ?? settingsManager.getSessionDir?.(); const defaultSessionDir = options.homeDir === void 0 ? sessionDirSetting : sessionDirSetting ? normalizeHomePath(sessionDirSetting, options.homeDir) : join9(resolve5(agentDir), "sessions", `--${resolve5(effectiveCwd).replace(/^[/\\\\]/, "").replace(/[/\\\\:]/g, "-")}--`); const persistSession = agentConfig?.persistSession ?? (options.nested ? false : rememberAgents); const sessionManager = options.resumeSessionFile ? SessionManager.open(options.resumeSessionFile, configuredSessionDir ?? defaultSessionDir) : persistSession ? SessionManager.create(effectiveCwd, configuredSessionDir ?? defaultSessionDir, { // Optional metadata — it only nests the subagent under its spawner in // `/resume`. Until `rememberAgents` this ran solely for the rare // `persist_session: true` agent; now it runs for every spawn, so a // context without a session manager (a bare programmatic ctx) must // still persist rather than take the whole spawn down. parentSession: ctx.sessionManager?.getSessionFile?.() }) : SessionManager.inMemory(effectiveCwd); const parentModelRuntime = ctx.modelRegistry.runtime; const sessionOpts = { cwd: effectiveCwd, agentDir, sessionManager, settingsManager: sessionSettingsManager, modelRegistry: ctx.modelRegistry, // `as never` is what keeps this assignable across the supported Pi range: // pre-0.80.8 the field exists only via the `modelRuntime?: unknown` shim // above, while newer Pi types it as `ModelRuntime` — a shape an opaque // `unknown` read off the private facade field can never satisfy. ...parentModelRuntime !== void 0 && { modelRuntime: parentModelRuntime }, model, tools: sessionTools, customTools: [...nestedTools, ...structuredTools, ...refusalTools], resourceLoader: loader }; if (sessionExcludeTools) { sessionOpts.excludeTools = sessionExcludeTools; } if (thinkingLevel) { sessionOpts.thinkingLevel = thinkingLevel; } const { session } = await runInChildSessionContext(() => createAgentSession(sessionOpts)); const baseSessionName = agentConfig?.name ?? type; session.setSessionName( options.agentId ? `${baseSessionName}#${options.agentId.slice(0, 8)}` : baseSessionName ); await session.bindExtensions({ onError: (err) => { options.onToolActivity?.({ type: "end", toolName: `extension-error:${err.extensionPath}` }); } }); if (!noExtensions) { installExtensionToolScope(session, { loader, toolNames, disallowedSet, extNames, narrowing, readmitToolNames, nestedCallGate, workflowError }); } const planGate = options.planGate; if (planGate) { const planReason = (toolName, input, cwd) => planGateReason(planGate, { toolName, input, cwd }, () => session.getAllTools(), readmitToolNames); nestedCallGate.planReason = planReason; const priorBeforeToolCall = session.agent.beforeToolCall; session.agent.beforeToolCall = async (context, signal) => { const reason = planReason(context.toolCall.name, context.args, effectiveCwd); if (reason !== void 0) return { block: true, reason }; return priorBeforeToolCall?.(context, signal); }; } options.onSessionCreated?.(session); const run = observeRun(session, { ...options, maxTurns: resolveEffectiveMaxTurns(type, options.maxTurns) }); const collector = collectResponseText(session); const cleanupAbort = forwardAbortSignal(session, options.signal); let effectivePrompt = prompt; if (options.inheritContext) { const parentContext = buildParentContext(ctx); if (parentContext) { effectivePrompt = parentContext + prompt; } } const startLen = session.messages.length; let structuredRetried = false; try { if (options.signal?.aborted !== true) await session.prompt(effectivePrompt); await retryStaleCtx(session, startLen, options.signal, options.staleRetryDelaysMs, options.clock); if (run.steered && mayFollowUp(session, startLen, options.signal) && !endedWithReport(session, startLen)) { run.finalizing = true; const reported = await forceFinalReport(session, startLen, options.signal); if (reported) run.aborted = false; } if (structuredCapture !== void 0 && structuredCapture.json === void 0 && !run.aborted && mayFollowUp(session, startLen, options.signal)) { structuredRetried = true; await session.prompt(structuredRetryPrompt(structuredCapture)); } } finally { run.unsubscribe(); collector.unsubscribe(); cleanupAbort(); } const stale = staleCtxOutcome(session, startLen); const text = collector.getText().trim() || getLastAssistantText(session, startLen); const structuredFailure = structuredCapture !== void 0 && structuredCapture.json === void 0 ? structuredCapture.lastError !== void 0 ? `The agent's StructuredOutput call did not match the required schema: ${structuredCapture.lastError}` : "The agent did not report its answer through StructuredOutput." : void 0; const failure = stale?.failure ?? finalTurnError(session, startLen) ?? structuredFailure; const streamed = collector.getText().trim() || collector.getPreviousText().trim(); return { responseText: failure ? failureText(session, startLen, streamed || text, stale?.partial ?? partialProgress(session, startLen), collector.hasLaterTool(), Boolean(streamed)) : text, session, aborted: run.aborted, steered: run.steered, failure, ...structuredCapture?.json !== void 0 ? { structuredJson: structuredCapture.json } : {}, ...structuredRetried ? { structuredRetried } : {} }; } async function resumeAgent(session, prompt, options) { const startLen = session.messages.length; const collector = collectResponseText(session); const cleanupAbort = forwardAbortSignal(session, options.signal); const run = observeRun(session, { ...options, maxTurns: resolveEffectiveMaxTurns(options.type, options.maxTurns) }); try { if (options.signal?.aborted !== true) await session.prompt(prompt); await retryStaleCtx(session, startLen, options.signal, options.staleRetryDelaysMs, options.clock); if (run.steered && mayFollowUp(session, startLen, options.signal) && !endedWithReport(session, startLen)) { run.finalizing = true; if (await forceFinalReport(session, startLen, options.signal)) run.aborted = false; } } finally { collector.unsubscribe(); run.unsubscribe(); cleanupAbort(); } const stale = staleCtxOutcome(session, startLen); const failure = stale?.failure ?? finalTurnError(session, startLen); const text = collector.getText().trim() || getLastAssistantText(session, startLen); const streamed = collector.getText().trim() || collector.getPreviousText().trim(); return { text: failure ? failureText(session, startLen, streamed || text, stale?.partial ?? partialProgress(session, startLen), collector.hasLaterTool(), Boolean(streamed)) : text, failure, aborted: run.aborted, steered: run.steered }; } async function steerAgent(session, message) { await session.steer(message); } function getAgentConversation(session) { const parts = []; for (const msg of session.messages) { if (msg.role === "user") { const text = typeof msg.content === "string" ? msg.content : extractText(msg.content); if (text.trim()) parts.push(`[User]: ${text.trim()}`); } else if (msg.role === "assistant") { const textParts = []; const toolCalls = []; for (const c of msg.content) { if (c.type === "text" && c.text) textParts.push(c.text); else if (c.type === "toolCall") toolCalls.push(` Tool: ${c.name ?? c.toolName ?? "unknown"}`); } if (textParts.length > 0) parts.push(`[Assistant]: ${textParts.join("\n")}`); if (toolCalls.length > 0) parts.push(`[Tool Calls]: ${toolCalls.join("\n")}`); } else if (msg.role === "toolResult") { const text = extractText(msg.content); const truncated = text.length > 200 ? text.slice(0, 200) + "..." : text; parts.push(`[Tool Result (${msg.toolName})]: ${truncated}`); } } return parts.join("\n\n"); } // src/mention.ts var MENTION_TRIGGER = /(^|[\s。、?!])@([\w-]*)$/; var MENTION_SEND = /^@([\w-]+)\s+([\s\S]+)$/; var MAX_HANDLE_LENGTH = 64; var RESERVED_HANDLES = /* @__PURE__ */ new Set(["main"]); function isReservedHandle(handle) { return RESERVED_HANDLES.has(handle.toLowerCase()); } function handleBase(type) { const slug = type.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, MAX_HANDLE_LENGTH).replace(/-+$/, ""); return slug || "agent"; } function assignHandle(base, taken) { let candidate = base; let n = 1; while (taken.has(candidate) || RESERVED_HANDLES.has(candidate)) { n++; candidate = `${base}-${n}`; } return candidate; } function resolveHandleToType(handle, types) { const wanted = handle.toLowerCase(); if (RESERVED_HANDLES.has(wanted)) return void 0; return types.find((type) => handleBase(type) === wanted); } function stripAgentPrefix(handle) { const rest = /^agent-(.+)$/i.exec(handle)?.[1]; return rest || void 0; } function describeMention(message) { const oneLine = message.split("\n", 1)[0].replace(/\s+/g, " ").trim(); return oneLine.length > 40 ? `${oneLine.slice(0, 39).trimEnd()}\u2026` : oneLine; } function agentMentionReminder(type) { return ` The user has expressed a desire to invoke the agent "${type}". Please invoke the agent appropriately, passing in the required context to it. `; } function parseMention(text) { const match = MENTION_SEND.exec(text); if (!match) return null; const message = match[2].trim(); return message ? { handle: match[1], message } : null; } // src/process-budget.ts var BUDGET_KEY = /* @__PURE__ */ Symbol.for("pi-subagents:process-budget"); var BUDGET_VERSION = 2; var MAX_PENDING_SUBAGENTS = 128; var DEFAULT_BUDGET_POLICY = { maxActive: 0, nestedReserve: 2, maxDepth: 2 }; var BUDGET_QUEUE_FULL_ERROR = `Subagent queue is full (${MAX_PENDING_SUBAGENTS} waiting for the process-wide maxActiveSubagents limit). Wait for running agents to finish, or do the work directly.`; function freshState() { return { version: BUDGET_VERSION, policy: { ...DEFAULT_BUDGET_POLICY }, pendingPolicy: void 0, active: /* @__PURE__ */ new Set(), waiters: [], pumping: false, repump: false }; } function state() { const g = globalThis; const existing = g[BUDGET_KEY]; if (existing === void 0) { const created = freshState(); g[BUDGET_KEY] = created; return created; } if (existing.version === BUDGET_VERSION) return existing; throw new Error( `[pi-subagents] Incompatible process budget v${String(existing.version)} already loaded (this build uses v${String(BUDGET_VERSION)}). Restart pi before starting more subagents; no private budget will be created.` ); } var topLevel = (policy2) => Math.max(1, policy2.maxDepth); function admissionLimit(policy2, level) { if (policy2.maxActive <= 0) return Number.POSITIVE_INFINITY; return policy2.maxActive - policy2.nestedReserve * (topLevel(policy2) - level); } function isCoherent(policy2) { if (policy2.maxActive <= 0 || topLevel(policy2) === 1) return true; return policy2.nestedReserve >= 1 && admissionLimit(policy2, 1) >= 1; } function relaxes(from, to) { if (to.maxActive <= 0) return true; if (from.maxActive <= 0 || topLevel(from) !== topLevel(to)) return false; for (let level = 1; level <= topLevel(to); level++) { if (admissionLimit(to, level) < admissionLimit(from, level)) return false; } return true; } function getBudgetPolicy() { return { ...state().policy }; } function setBudgetPolicy(next) { const policy2 = { maxActive: Math.max(0, Math.floor(next.maxActive)), nestedReserve: Math.max(0, Math.floor(next.nestedReserve)), maxDepth: Math.max(0, Math.floor(next.maxDepth)) }; if (!isCoherent(policy2)) { console.warn( `[pi-subagents] Ignoring maxActiveSubagents ${String(policy2.maxActive)} with nestedSubagentReserve ${String(policy2.nestedReserve)} at maxSubagentDepth ${String(policy2.maxDepth)}: it could deadlock. Nesting needs a reserve of at least 1 and maxActiveSubagents >= nestedSubagentReserve * (maxSubagentDepth - 1) + 1.` ); return; } const s = state(); if (s.active.size === 0 || relaxes(s.policy, policy2)) { s.policy = policy2; s.pendingPolicy = void 0; pumpBudget(); } else { s.pendingPolicy = policy2; console.warn( `[pi-subagents] Process budget change deferred until all running subagents settle: maxActiveSubagents=${String(policy2.maxActive)}, nestedSubagentReserve=${String(policy2.nestedReserve)}, maxSubagentDepth=${String(policy2.maxDepth)}. The previous policy remains in force; continuous work can delay this indefinitely.` ); } } function assertWithinBudgetDepth(depth) { const { policy: policy2 } = state(); if (policy2.maxActive > 0 && depth > topLevel(policy2)) { throw new Error( `Nested subagent at depth ${String(depth)} exceeds the process budget's depth ${String(topLevel(policy2))} (global maxSubagentDepth). Complete the task directly.` ); } } function admits(s, depth) { const { policy: policy2 } = s; if (policy2.maxActive <= 0) return true; const top = topLevel(policy2); const level = Math.max(1, depth); if (level > top) return false; const atDepth = new Array(top + 1).fill(0); for (const lease of s.active) { const index = Math.min(top, Math.max(1, lease.depth)); atDepth[index] = atDepth[index] + 1; } let atOrAbove = 0; for (let j = 1; j <= top; j++) { atOrAbove += atDepth[j]; if (j >= level && atOrAbove >= admissionLimit(policy2, j)) return false; } return true; } function newLease(s, depth) { const lease = { depth, released: false }; s.active.add(lease); return lease; } function tryAcquireBudget(depth) { const s = state(); if (!admits(s, depth) || s.waiters.some((waiter) => admits(s, waiter.depth) && waiter.ready())) return void 0; return newLease(s, depth); } function budgetHasPendingRoom() { const s = state(); return s.policy.maxActive <= 0 || s.waiters.length < MAX_PENDING_SUBAGENTS; } function enqueueBudget(waiter) { state().waiters.push(waiter); return () => { const s = state(); const i = s.waiters.indexOf(waiter); if (i !== -1) s.waiters.splice(i, 1); }; } function releaseBudget(lease) { if (lease === void 0 || lease.released) return; lease.released = true; const s = state(); s.active.delete(lease); if (s.active.size === 0 && s.pendingPolicy !== void 0) { s.policy = s.pendingPolicy; s.pendingPolicy = void 0; } } function pumpBudget() { const s = state(); if (s.pumping) { s.repump = true; return; } s.pumping = true; try { do { s.repump = false; for (; ; ) { const i = s.waiters.findIndex((w) => admits(s, w.depth) && w.ready()); if (i === -1) break; const waiter = s.waiters.splice(i, 1)[0]; const lease = newLease(s, waiter.depth); try { waiter.grant(lease); } catch { releaseBudget(lease); } } } while (s.repump); } finally { s.pumping = false; } } // src/agent-manager.ts function relabelFromResponse(record, message) { const registry = record.session?.modelRegistry; const physical = describePhysicalModel(message, registry); if (!physical) return; record.invocation ??= {}; Object.assign(record.invocation, physical); if ((record.modelTier?.kind === "routed" || record.modelTier?.kind === "static") && record.modelTier.answered !== physical.modelId) { record.modelTier = { ...record.modelTier, answered: physical.modelId }; if (record.outputFile) appendModelTierEntry(record.outputFile, record.id, record.modelTier); } } function recordWorktreeCleanup(record, result) { record.worktreeResult = result; if (!result.error) return; const note = `Worktree cleanup failed: ${result.error}. Worktree retained at \`${result.path}\`${result.branch ? `; branch \`${result.branch}\` was created` : ""}. Inspect and recover it before removing it.`; record.error = record.error ? `${record.error} ${note}` : note; record.result = record.result ? `${record.result} ${note}` : note; if (record.status !== "stopped") record.status = "error"; } var DEFAULT_MAX_CONCURRENT = 10; var DEFAULT_MAX_CONCURRENT_FOREGROUND = 0; var CONSUMED_RECORD_TTL_MS = 10 * 6e4; var UNCONSUMED_RECORD_TTL_MS = 60 * 6e4; function retentionMs(name, fallbackMs) { const raw = process.env[name]?.trim(); if (!raw) return fallbackMs; const minutes = Number(raw); if (!Number.isFinite(minutes) || minutes < 0) { console.warn(`[pi-subagents] ignoring ${name}="${raw}": expected minutes >= 0`); return fallbackMs; } return minutes * 6e4; } var MAX_SWEEP_INTERVAL_MS = 6e4; var MIN_SWEEP_INTERVAL_MS = 1e3; var MAX_EVICTED_NOTES = 500; function markConsumed(record, now = Date.now()) { record.resultConsumed = true; record.consumedAt = now; } function describeEvicted(note) { const where = note.transcript ? `; transcript: ${note.transcript}` : ""; const disclosure = modelSelectionNote(note); const fallback = disclosure ? ` ${disclosure}` : ""; return `Agent "${note.id}" (${note.description}) ${note.status}, evicted after ${note.evictedAfterMin} min${where}${fallback}`; } var MAX_TOMBSTONES = 100; function assertValidSpawnCwd(cwd) { if (cwd == null) return; if (typeof cwd !== "string" || !isAbsolute4(cwd)) { throw new Error(`SpawnOptions.cwd must be an absolute path: "${String(cwd)}"`); } let isDirectory = false; try { isDirectory = statSync6(cwd).isDirectory(); } catch { throw new Error(`SpawnOptions.cwd does not exist: "${cwd}"`); } if (!isDirectory) { throw new Error(`SpawnOptions.cwd is not a directory: "${cwd}"`); } } function assertReadableCwd(cwd, label) { try { opendirSync(cwd).closeSync(); accessSync(cwd, constants.R_OK | constants.X_OK); } catch (err) { const code = err.code; if (code !== "EACCES" && code !== "EPERM") return; throw new Error( `${label} is not readable (${code}): "${cwd}". Check its permissions; on macOS also check Privacy & Security -> Files & Folders / Full Disk Access for the terminal app (external volumes need it).` ); } } function assertSpawnCwd(cwd, sessionCwd) { assertValidSpawnCwd(cwd); if (cwd == null) assertReadableCwd(sessionCwd, "The session cwd"); else assertReadableCwd(cwd, "SpawnOptions.cwd"); } function isSettled(record) { return record.status !== "running" && record.status !== "queued"; } function occupiesPoolSlot(record) { return !!record.isBackground && isTopLevelAgent(record); } function isTopLevelAgent(record) { return record.parentAgentId === void 0 && record.workflowId === void 0; } function occupiesForegroundSlot(record) { return !!record.blocking && isTopLevelAgent(record); } var CHILD_SHUTDOWN_TIMEOUT_MS = 3e3; async function shutdownChildSession(session) { let deadline; try { const runner = session?.extensionRunner; if (runner?.hasHandlers?.("session_shutdown")) { await Promise.race([ runner.emit({ type: "session_shutdown", reason: "quit" }), new Promise((resolve6) => { deadline = setTimeout(resolve6, CHILD_SHUTDOWN_TIMEOUT_MS); deadline.unref(); }) ]); } } catch { } finally { if (deadline !== void 0) clearTimeout(deadline); } try { session?.dispose?.(); } catch { } } function guardObserver(name, observer) { if (!observer) return void 0; let logged = false; return (...args) => { try { observer(...args); } catch (error) { if (isStaleCtxError(error) || logged) return; logged = true; console.error(`pi-subagents: ${name} observer failed; further failures are not logged`, error); } }; } var AgentManager = class { constructor(onComplete, maxConcurrent = DEFAULT_MAX_CONCURRENT, onStart, onCompact, onUsage, onSteered, clock = realClock, homeDir, onQueuedStop, onReaped) { this.clock = clock; this.homeDir = homeDir; this.onComplete = onComplete; this.onStart = onStart; this.onQueuedStop = guardObserver("queued stop", onQueuedStop); this.onReaped = guardObserver("reaped", onReaped); this.onCompact = guardObserver("compaction", onCompact); this.onUsage = guardObserver("usage", onUsage); this.onSteered = onSteered; this.maxConcurrent = maxConcurrent; const sweepMs = Math.min( MAX_SWEEP_INTERVAL_MS, Math.max(MIN_SWEEP_INTERVAL_MS, Math.min(this.consumedTtlMs, this.unreadTtlMs)) ); this.cleanupInterval = this.clock.setInterval(() => this.cleanup(), sweepMs); this.cleanupInterval.unref?.(); } clock; homeDir; agents = /* @__PURE__ */ new Map(); cleanupInterval; /** `CONSUMED_RECORD_TTL_MS` unless `PI_SUBAGENTS_CONSUMED_TTL_MIN` overrides it. */ consumedTtlMs = retentionMs("PI_SUBAGENTS_CONSUMED_TTL_MIN", CONSUMED_RECORD_TTL_MS); /** `UNCONSUMED_RECORD_TTL_MS` unless `PI_SUBAGENTS_UNREAD_TTL_MIN` overrides it. */ unreadTtlMs = retentionMs("PI_SUBAGENTS_UNREAD_TTL_MIN", UNCONSUMED_RECORD_TTL_MS); onComplete; onStart; onQueuedStop; onReaped; onCompact; onUsage; onSteered; maxConcurrent; maxConcurrentForeground = DEFAULT_MAX_CONCURRENT_FOREGROUND; /** Base repos worktrees were created from — so dispose() can prune them all, * not just the parent repo (caller-supplied cwd can target other repos). */ worktreeRepos = /* @__PURE__ */ new Set(); /** * Startup phases, keyed by agent id. `spawn()` still returns synchronously, * but an agent using worktree isolation is not running yet when it does — * copying the repo is an awaited git call. This is what `awaitStartup` hands * callers that must fail their tool call on a startup failure, and what * `waitForAll` waits on while a record is "running" with no `promise` yet. * Entries are dropped once the run is underway, and kept (rejected) after a * startup failure so a late `awaitStartup` still sees it. */ startups = /* @__PURE__ */ new Map(); /** * Evicted agents that can still be reached by name, keyed by handle. Outlives * the 10-minute record cleanup — that timer exists to bound memory, not to * expire a conversation the user might still want — and is cleared alongside * completed records on session start/switch. */ tombstones = /* @__PURE__ */ new Map(); /** Evicted records by id, oldest first (insertion order). */ evictedNotes = /* @__PURE__ */ new Map(); /** Evicted id -> the id its reopened conversation runs under, so the old id keeps resolving (#330). */ successors = /* @__PURE__ */ new Map(); /** * Agents waiting to start, tagged with the pool they wait on (none for a * start that only waits on the process budget). Each entry is also a waiter * in the process-wide budget queue, which is what actually starts it: the * budget picks the earliest entry, across every manager, whose depth fits * and whose own pool has room, so neither pool can head-of-line-block the * other, and every removal path (`abort`, `abortAll`, `dispose`) stays a * single filter. * * `release` wakes a caller blocked in `spawnAndWait`, and is fired once the * entry's `start` has SETTLED rather than at drain time: startup is async * now, so releasing earlier would wake the caller before `record.promise` * exists and it would read a still-starting agent as one that never ran. * Removing an entry from this array MUST release it — a queued record has no * promise to await, and pi has no tool-execution timeout to bail the caller * out. */ queue = []; /** Number of currently running background agents. */ runningBackground = 0; /** Number of currently running foreground (blocking) agents. */ runningForeground = 0; /** * Put a run under Plan mode's policy when its owning agent's run is (a nested * child) or the parent session is planning right now (everything else, a * workflow stage included). The gate object is kept, since the child's hooks * hold it. */ decidePlanGate(record, query) { const owner = record.parentAgentId === void 0 ? void 0 : this.agents.get(record.parentAgentId); const policy2 = owner?.planGate?.policy ?? query(); record.planGate ??= {}; record.planGate.policy = policy2; if (policy2 || record.invocation?.planMode) { record.invocation ??= {}; record.invocation.planMode = policy2 ? true : void 0; } } /** Spawns and settles, in order: `spawnSeq` / `settleSeq` on lifecycle events. */ lifecycleSequence = 0; /** The next lifecycle sequence number; the host stamps `settleSeq` with it at settle. */ nextSequence() { return ++this.lifecycleSequence; } /** Update the max concurrent background agents limit. */ setMaxConcurrent(n) { this.maxConcurrent = Math.max(1, n); this.drainQueue(); } getMaxConcurrent() { return this.maxConcurrent; } /** Update the max concurrent foreground (blocking) agents limit. 0 = unlimited. */ setMaxConcurrentForeground(n) { this.maxConcurrentForeground = Math.max(0, n); this.drainQueue(); } getMaxConcurrentForeground() { return this.maxConcurrentForeground; } /** * Which pool a spawn is charged to, or undefined for one that is charged to * neither (nested children, detached non-background spawns). * * Nothing here queues when the limit is unset — `poolHasRoom` reports an * unlimited pool as always having room, so that alone is what keeps the * default path identical. The `> 0` guard is belt and braces on top: it also * keeps the counter from churning and the settle path from calling a drain * that would find nothing to do. Both are unobservable, which is why no test * pins them; the observable half — that the default start stays synchronous — * is pinned in `test/foreground-concurrency.test.ts`. */ poolFor(record) { if (occupiesPoolSlot(record)) return "background"; if (this.maxConcurrentForeground > 0 && occupiesForegroundSlot(record)) return "foreground"; return void 0; } poolHasRoom(pool) { return pool === "background" ? this.runningBackground < this.maxConcurrent : this.maxConcurrentForeground === 0 || this.runningForeground < this.maxConcurrentForeground; } /** * Spawn an agent and return its ID immediately (for background use). * If the concurrency limit is reached, the agent is queued. * * The id comes back synchronously, but with `isolation: "worktree"` the agent * is not running yet when it does — the repo copy is an awaited git call. * Callers that must fail a tool call on a startup failure await * `awaitStartup(id)`; everyone else sees it on the record (status "error"). */ spawn(pi, ctx, type, prompt, options) { assertSpawnCwd(options.cwd, ctx.cwd); const selection = options.modelSelection ?? selectModel({ homeDir: options.homeDir ?? this.homeDir, agentType: type, definitionModel: getAgentConfig(type)?.model, paramModel: options.model, parentModel: ctx.model, registry: ctx.modelRegistry, cwd: options.configCwd ?? ctx.cwd, agentLabel: getAgentConfig(type)?.displayName }); if (typeof selection === "string") throw new Error(selection); if (selection.scopeWarning && !options.modelSelection) ctx.ui.notify(selection.scopeWarning, "warning"); options = { ...options, model: selection.model, modelSelection: selection }; const id = randomUUID2().slice(0, 17); const abortController = new AbortController(); const record = { id, type, // Owned children — nested, or a workflow's — are filtered out of every // top-level surface, so no handle: nothing can address them and they must // not consume a name a top-level sibling could otherwise take. handle: !isTopLevelAgent(options) ? void 0 : options.reclaim?.handle ?? assignHandle(handleBase(type), this.takenHandles()), description: options.description, // Reclaimed here, or filled in below from `name` — in which case it must // see the handle this record just took, since both come out of the same // namespace. alias: isTopLevelAgent(options) ? options.reclaim?.alias : void 0, // Overwritten below when the spawn is actually queued; a foreground spawn // that queues flips to "queued" there rather than being guessed at here, // since the pool decision needs the finished record. status: options.isBackground ? "queued" : "running", toolUses: 0, startedAt: this.clock.now(), abortController, lifetimeUsage: { input: 0, output: 0, cacheWrite: 0, cost: 0 }, spawnSeq: this.nextSequence(), compactionCount: 0, // Raw tri-state (not coerced to a boolean): true = background, false = // foreground (has an inline tool-result surface), undefined = caller never // declared it (e.g. a cross-extension RPC spawn). The widget's background- // only filter excludes only explicit `false`, so undefined agents — which // have no inline surface — stay visible instead of vanishing. isBackground: options.isBackground, // Whether anyone is awaiting this agent is a property of the agent, not // of the call that made it — and both settle paths need it long after // `options` has stopped being the interesting object. blocking: options.blocking, invocation: options.invocation, modelFallback: selection.fallback, modelSelection: selection, modelTier: selection.tier ? tierDisclosure(selection.tier) : void 0, previousModelTier: options.previousModelTier, previousModelFallback: options.previousModelFallback, previousId: options.previousId, depth: options.depth ?? 1, parentAgentId: options.parentAgentId, workflowId: options.workflowId, maxSubagentDepth: options.maxSubagentDepth, rootSessionId: options.rootSessionId }; this.decidePlanGate(record, () => queryPlanPolicy(pi.events)); record.planQuery = () => queryPlanPolicy(pi.events, "restrict"); this.agents.set(id, record); if (record.handle !== void 0 && record.alias === void 0 && options.name !== void 0) { record.nameBase = handleBase(options.name); record.alias = assignHandle(record.nameBase, this.takenHandles()); } const args = { pi, ctx, type, prompt, options }; const pool = this.poolFor(record); const waitPool = options.bypassQueue ? void 0 : pool; let lease; try { lease = this.admit(record, waitPool); } catch (err) { this.agents.delete(id); throw err; } try { options.onPrepare?.(id); } catch (err) { this.agents.delete(id); releaseBudget(lease); this.drainQueue(); throw err; } if (lease === void 0) { record.status = "queued"; if (!this.armQueuedAbort(record, options.signal)) return id; let release; record.startGate = new Promise((resolve6) => { release = resolve6; }); const failAs = record.blocking ? "foreground" : "background"; this.enqueueStart(id, record, waitPool, () => this.launch(id, record, args, failAs), () => release()); options.onQueued?.(id, this.queue.filter((e) => e.pool === waitPool).length - 1); return id; } record.budgetLease = lease; this.launch(id, record, args, void 0); return id; } /** * Wire a parent abort signal for a record that is about to be QUEUED. * `startAgent` does this for running agents, and a queued record never gets * there, so without this Esc could not release a queue position. * * Returns false when the signal is ALREADY aborted, in which case the record * is stopped here and must not be enqueued: `addEventListener` never fires on * an aborted signal, so a `spawnAndWait` on it would wait forever — pi has no * tool-execution timeout to bail it out. * * The listener is removable (`record.detachParentAbort`): `startAgent` * replaces it with its own, and `sendToBackground` must be able to take it * off, or the caller that armed it could stop a run it no longer owns. */ armQueuedAbort(record, signal) { if (signal === void 0) return true; if (signal.aborted) { record.status = "stopped"; record.completedAt = this.clock.now(); return false; } this.armParentAbort(record, signal); return true; } /** * Stop `record` when its caller's `signal` aborts, replacing any listener an * earlier stage armed — at most one is live per record, so one call to * `detachParentAbort` cuts the run loose from its caller. */ armParentAbort(record, signal) { this.detachParentAbort(record); if (signal === void 0) return; const onParentAbort = () => this.abort(record.id); signal.addEventListener("abort", onParentAbort, { once: true }); record.detachParentAbort = () => signal.removeEventListener("abort", onParentAbort); } detachParentAbort(record) { record.detachParentAbort?.(); record.detachParentAbort = void 0; } /** * The one admission check every start makes: a lease now when `pool` (if * any) has room and the process budget admits `record`'s depth, else * undefined and the caller queues. Throws, having changed nothing, when the * start could never be admitted (deeper than the budget reserves for) or the * budget's wait queue is full. */ admit(record, pool) { assertWithinBudgetDepth(record.depth); const lease = pool === void 0 || this.poolHasRoom(pool) ? tryAcquireBudget(record.depth) : void 0; if (lease === void 0 && !budgetHasPendingRoom()) throw new Error(BUDGET_QUEUE_FULL_ERROR); return lease; } /** Give back `record`'s budget lease, if it holds one. Callers drain afterwards. */ releaseLease(record) { releaseBudget(record.budgetLease); record.budgetLease = void 0; } /** * Park a start in `queue` and in the process budget. The budget calls * `grant` once the record's depth fits and `pool` (if any) has room; `start` * then runs and `release` fires when it settles. A record that stopped being * "queued" without being dequeued hands the lease straight back. */ enqueueStart(id, record, pool, start, release) { let markLeft; const left = new Promise((resolve6) => { markLeft = resolve6; }); const entry = { id, record, pool, start, release: () => { release(); markLeft(); }, // enqueueBudget only registers; grant cannot run until the next pump, // after this entry has been initialized and published in the queue. cancel: enqueueBudget({ depth: record.depth, ready: () => pool === void 0 || this.poolHasRoom(pool), grant: (lease) => { this.queue = this.queue.filter((e) => e !== entry); if (this.agents.get(id) !== record || record.status !== "queued") { releaseBudget(lease); entry.release(); return; } record.budgetLease = lease; void entry.start().then(() => entry.release(), () => entry.release()); } }), left }; this.queue.push(entry); } /** Add `delta` to the running count of `pool`; no pool, no count. */ chargePool(pool, delta) { if (pool === "background") this.runningBackground += delta; else if (pool === "foreground") this.runningForeground += delta; } /** * Kick off an agent's startup and register it under `startups`. The returned * promise never rejects — the failure is delivered through `awaitStartup`, * and to the record. * * @param failAs - For a start that QUEUED (on a pool or on the budget * alone), how a startup failure is reported: "foreground" when an inline * `spawnAndWait` caller gets it as a throw, else "background". Undefined * for an immediate start. A queued start can begin minutes after `spawn()` * returned, and nobody is awaiting `awaitStartup` by then, so its failure * lives on the record as status "error". An immediate start instead drops * the record, exactly as the throw out of `spawn()` did: no orphan in * `listAgents()`, and the handle goes back. */ launch(id, record, args, failAs) { const startup = this.startAgent(id, record, args).then( () => { this.startups.delete(id); }, (err) => { this.startups.delete(id); try { if (failAs !== void 0) { if (failAs === "foreground") markConsumed(record, this.clock.now()); record.status = "error"; record.error = errorMessage(err); record.completedAt = this.clock.now(); try { this.onComplete?.(record); } catch { } } else { this.agents.delete(id); } } finally { this.releaseLease(record); this.drainQueue(); } throw err; } ); this.startups.set(id, startup); return startup.catch(() => { }); } /** * Resolves once the agent is actually running, and rejects with the startup * failure (strict worktree isolation) that `spawn()` used to throw before the * repo copy became async. Resolves immediately for an agent that is already * running, still queued, or unknown — so callers can await it unconditionally. * * Call it in the same tick as the `spawn()` it belongs to: a failed startup * takes its record (and this entry) with it, exactly as the throw did. */ awaitStartup(id) { return this.startups.get(id) ?? Promise.resolve(); } /** Actually start an agent (called immediately or from queue drain). */ async startAgent(id, record, { pi, ctx, type, prompt, options }) { assertSpawnCwd(options.cwd, ctx.cwd); const customCwd = options.cwd ?? void 0; const baseCwd = customCwd ?? ctx.cwd; record.chargedPool = this.poolFor(record); record.status = "running"; record.startedAt = this.clock.now(); record.startGate = void 0; this.chargePool(record.chargedPool, 1); try { if (options.modelSelection?.tierBinding && !options.modelSelection.tierAdmitted) { const block = await admitModelSelection(options.modelSelection, ctx.modelRegistry, pi.events); record.modelTier = tierDisclosure(options.modelSelection.tier); record.modelFallback = options.modelSelection.fallback; if (block) throw new Error(`${modelSelectionNote(record)} ${describeBlock(block)} The agent was not started.`); if (record.abortController?.signal.aborted || options.signal?.aborted) throw new Error("Agent aborted during model admission."); } if (record.modelTier) { record.invocation ??= {}; Object.assign(record.invocation, describeSelection(options.modelSelection, ctx.modelRegistry)); } } catch (error) { this.chargePool(record.chargedPool, -1); throw error; } const isolation = options.workflowId !== void 0 ? options.isolation : getAgentConfig(type)?.isolation ?? options.isolation; if (isolation === "worktree" && record.planGate?.policy) { this.chargePool(record.chargedPool, -1); throw new Error('Cannot run with isolation: "worktree" while Plan mode is active: a worktree exists to make edits. Omit `isolation`, or leave Plan mode first.'); } let worktreeCwd; if (isolation === "worktree" && isWorktreeIsolationEnabled()) { let wt; try { wt = await createWorktree(pi, baseCwd, id); } catch (err) { this.chargePool(record.chargedPool, -1); const cause = errorMessage(err); const hint = customCwd === void 0 ? " To isolate another repo, pass its path as the `Agent` tool's `cwd`; or omit `isolation`." : " Pass a `cwd` inside a git repo with at least one commit, or omit `isolation`."; throw new Error(`Cannot run with isolation: "worktree": ${cause}.${hint}`); } record.worktree = wt; worktreeCwd = customCwd !== void 0 ? wt.workPath : wt.path; this.worktreeRepos.add(baseCwd); record.invocation ??= {}; record.invocation.isolation = "worktree"; if (record.status !== "running") { this.chargePool(record.chargedPool, -1); recordWorktreeCleanup(record, await cleanupWorktree(pi, baseCwd, wt, options.description)); if (record.worktreeResult?.error) { if (!record.isBackground) markConsumed(record, this.clock.now()); try { this.onComplete?.(record); } catch { } } this.releaseLease(record); this.drainQueue(); return; } } try { this.onStart?.(record); } catch (err) { this.chargePool(record.chargedPool, -1); if (record.worktree) { try { recordWorktreeCleanup(record, await cleanupWorktree(pi, baseCwd, record.worktree, options.description)); } catch { } } if (record.worktreeResult?.error) { const message = err instanceof Error ? err.message : String(err); throw new Error(`${message} ${record.error}`); } throw err; } if (options.signal?.aborted) this.abort(id); else this.armParentAbort(record, options.signal); const detach = () => this.detachParentAbort(record); record.ranThisRun = record.status === "running"; const promise = runAgent(ctx, type, prompt, { pi, clock: this.clock, homeDir: options.homeDir ?? this.homeDir, agentId: id, model: options.modelSelection?.model, modelSelection: record.modelSelection, maxTurns: options.maxTurns, isolated: options.isolated, inheritContext: options.inheritContext, thinkingLevel: options.thinkingLevel, structuredOutput: options.structuredOutput, planGate: record.planGate, resumeSessionFile: options.resumeSessionFile, nested: options.parentAgentId !== void 0, workflow: options.workflowId !== void 0, // Worktree wins for the working dir (the agent must run in the copy — // which, with a custom cwd, was created from that target). Config stays // with the parent project when a caller-supplied cwd is in play; it must // stay undefined otherwise so plain worktree runs keep resolving config // (incl. relative extension paths and memory) inside the worktree copy. cwd: worktreeCwd ?? customCwd, // Set iff a worktree was created (see above) — names the directory the // copy came from, so the prompt can tell the agent not to work there. worktreeBase: worktreeCwd ? baseCwd : void 0, configCwd: options.configCwd ?? (customCwd !== void 0 ? ctx.cwd : void 0), configProjectTrusted: options.configCwd !== void 0 ? options.configProjectTrusted : void 0, signal: record.abortController.signal, onToolActivity: (activity) => { if (activity.type === "end") record.toolUses++; options.onToolActivity?.(activity); }, onTurnEnd: options.onTurnEnd, onTextDelta: options.onTextDelta, onModelCall: options.onModelCall, onAssistantUsage: (usage, message) => { relabelFromResponse(record, message); addUsage(record.lifetimeUsage, usage); this.onUsage?.(record, usage); options.onAssistantUsage?.(usage); }, onCompaction: (info) => { record.compactionCount++; this.onCompact?.(record, info); options.onCompaction?.(info); }, nestedRuntime: { manager: this, parentAgentId: id, depth: record.depth, maxSubagentDepth: record.maxSubagentDepth }, onSessionCreated: (session) => { record.session = session; record.sessionFile = session.sessionManager?.getSessionFile?.(); if (session.model) { record.invocation ??= {}; const requested = record.invocation.requestedThinking ?? record.invocation.thinking; Object.assign( record.invocation, record.modelTier?.kind === "routed" && record.modelTier.admitted ? describeSelection(options.modelSelection, ctx.modelRegistry) : isVirtualModel(session.model) ? describeVirtualModel(session.model) : describeModel(session.model) ); if (session.thinkingLevel) { record.invocation.thinking = session.thinkingLevel; if (requested && requested !== session.thinkingLevel) { record.invocation.requestedThinking = requested; } } } if (record.modelFallback && record.outputFile) appendModelFallbackEntry(record.outputFile, record.id, record.modelFallback); if (record.modelTier && record.outputFile) appendModelTierEntry(record.outputFile, record.id, record.modelTier); if (record.pendingSteers?.length) { for (const msg of record.pendingSteers) { session.steer(msg).catch(() => { }); } record.pendingSteers = void 0; } options.onSessionCreated?.(session); } }).then(async ({ responseText, session, aborted, steered, failure, structuredJson, structuredRetried }) => { this.settleOutcome(record, { text: responseText, failure, aborted, steered }); record.structuredJson = structuredJson; record.structuredRetried = structuredRetried; record.session = session; detach(); if (record.outputCleanup) { try { record.outputCleanup(); } catch { } record.outputCleanup = void 0; } if (record.worktree) { if (options.onBeforeWorktreeCleanup) { try { await options.onBeforeWorktreeCleanup(record.worktree.path); } catch { } } const wtResult = await cleanupWorktree(pi, baseCwd, record.worktree, options.description); recordWorktreeCleanup(record, wtResult); if (!wtResult.error && wtResult.hasChanges && wtResult.branch) { const repo = record.worktree.repoRoot; const repoNote = customCwd !== void 0 ? ` in \`${repo}\`` : ""; record.result = responseText + ` --- Changes saved to branch \`${wtResult.branch}\`${repoNote}. Merge with: \`git merge ${wtResult.branch}\`${customCwd !== void 0 ? ` (run in \`${repo}\`)` : ""}`; } } this.abortOwnedChildren(id); this.settleRun(record, true); return responseText; }).catch(async (err) => { if (record.status !== "stopped") { record.status = "error"; } record.error = errorMessage(err); record.completedAt ??= this.clock.now(); detach(); if (record.outputCleanup) { try { record.outputCleanup(); } catch { } record.outputCleanup = void 0; } if (record.worktree) { try { const wtResult = await cleanupWorktree(pi, baseCwd, record.worktree, options.description); recordWorktreeCleanup(record, wtResult); } catch { } } this.abortOwnedChildren(id); this.settleRun(record, false); return ""; }); record.promise = promise; options.onSpawned?.(id); } /** * The shared tail of both settle paths: release whatever pool slot the run * held, notify, and let the queue drain into the freed slot. * * The decrement lives HERE and nowhere else. `abort()` on a running record * only fires its controller and leaves the run to settle normally, so * decrementing there too would double-free — permanently lifting the limit. * * Foreground agents fire `onComplete` for lifecycle symmetry, with * `resultConsumed` set so the callback skips notifications the inline result * already delivered. * * @param guardCallback swallow a throwing `onComplete` (the success path does; * the error path historically did not, and keeps not doing so). * * Releases `record.chargedPool` — the pool the run was charged to at start * (or moved to by `sendToBackground`), never a recomputed one, so a mid-run * change to `maxConcurrentForeground` can't make the release disagree with * the acquire. */ settleRun(record, guardCallback) { if (!record.isBackground) markConsumed(record, this.clock.now()); record.blocking = false; this.chargePool(record.chargedPool, -1); this.releaseLease(record); try { if (guardCallback) { try { this.onComplete?.(record); } catch { } } else { this.onComplete?.(record); } } finally { this.drainQueue(); } } /** * Stop the nested children a settled parent owns. Nested records are hidden * from the UI and only their owner can consume them, so a child outliving its * parent would burn tokens unseen with no way to reach it. Grandchildren are * covered transitively — each abort lands in that child's own settle path. */ abortOwnedChildren(parentId) { for (const [id, record] of this.agents) { if (record.parentAgentId === parentId) this.abort(id); } } /** * Start queued agents up to each pool's concurrency limit and the process * budget. The budget owns the order (`pumpBudget`): the earliest waiter, in * any manager, whose depth fits and whose own pool has room. Eligibility per * entry rather than `shift`: with one queue serving several limits, a * saturated pool at the head would otherwise stall everything behind it. * Taking the earliest eligible entry keeps FIFO within each pool. */ drainQueue() { pumpBudget(); } /** * Remove queued entries and wake anyone blocked on them. The single point * that enforces "leaving the queue releases the waiter" — a missed release is * an unbounded hang, not a failed call. */ dequeue(pred) { const kept = []; const removed = []; for (const entry of this.queue) (pred(entry) ? removed : kept).push(entry); this.queue = kept; for (const entry of removed) { entry.cancel(); entry.release(); } } /** * Spawn an agent and wait for completion (foreground use). * Charged to the foreground pool (`maxConcurrentForeground`), which is * unlimited by default; never to the background one. * Returns { id, record } so callers can access the agent ID. * * @param onSpawned - Called synchronously once the run is kicked off, before * onSessionCreated fires. */ async spawnAndWait(pi, ctx, type, prompt, options, onSpawned) { const id = this.spawn(pi, ctx, type, prompt, { ...options, isBackground: false, blocking: true, onSpawned }); const record = this.agents.get(id); if (record.status === "queued") await record.startGate; await this.awaitStartup(id); if (record.promise) await record.promise; if (record.promise === void 0 && record.status === "error") { throw new Error(record.error); } return { id, record }; } /** * Hand a live run to the background without restarting it. The session, * promise, in-flight turn, transcript and worktree all continue under the * same id; what changes is who answers for it. The caller's parent-abort * listener comes off (its Esc no longer reaches the run — `abort()` and * `/agents` still do), the slot moves to the background pool, and the run * then settles through the ordinary background path, since `settleRun` * reads the live `isBackground` and `chargedPool`. * * Releasing the caller is the caller's job — the `Agent` tool races its own * wake-up against `spawnAndWait`. This only refuses what it can see: a run * nobody is blocking on (a background or detached spawn, one already handed * off, or a foreground RESUME — `blocking` is cleared when the spawned run * settles, and a resume never charged the slot this would move), and one * that reports through something other than the session (a nested child, a * workflow's agent). * * The background slot is taken even when the pool is full: suspending a * live run is not an option, so it runs over the limit and queued * background work waits for the count to drop, as with `bypassQueue`. */ sendToBackground(id) { const record = this.agents.get(id); if (!record?.blocking || !isTopLevelAgent(record) || record.status !== "running" || !record.promise) return false; this.detachParentAbort(record); this.chargePool(record.chargedPool, -1); record.chargedPool = "background"; this.chargePool(record.chargedPool, 1); record.blocking = false; record.isBackground = true; record.resultConsumed = false; this.drainQueue(); return true; } /** * Resume an existing agent session with a new prompt. */ async resume(id, prompt, signal, options) { const record = this.agents.get(id); if (!record?.session) return void 0; if (record.status === "running" || record.status === "queued") return void 0; this.decidePlanGate(record, record.planQuery); if (options?.isBackground) { const pool = occupiesPoolSlot({ ...record, isBackground: true }) ? "background" : void 0; const lease2 = this.admit(record, pool); record.isBackground = true; record.resultConsumed = false; record.noticeDelivered = void 0; record.ranThisRun = false; record.consumedAt = void 0; record.result = void 0; record.error = void 0; record.completedAt = void 0; record.status = "queued"; const start = () => { try { this.startResume(id, record, prompt, signal, options); } catch (err) { if (occupiesPoolSlot(record)) this.runningBackground--; this.releaseLease(record); record.status = "error"; record.error = errorMessage(err); record.completedAt = this.clock.now(); this.drainQueue(); throw err; } }; if (lease2 === void 0) { this.enqueueStart(id, record, pool, async () => { try { start(); } catch { this.onComplete?.(record); } }, () => { }); } else { record.budgetLease = lease2; start(); } return record; } const lease = this.admit(record, void 0); record.ranThisRun = false; record.noticeDelivered = void 0; record.status = lease === void 0 ? "queued" : "running"; record.budgetLease = lease; record.startedAt = this.clock.now(); record.completedAt = void 0; record.result = void 0; record.error = void 0; const abortController = new AbortController(); record.abortController = abortController; this.armParentAbort(record, signal); if (signal?.aborted) this.abort(id); if (lease === void 0) { let granted = false; if (record.status === "queued") { await new Promise((resolve6) => { this.enqueueStart(id, record, void 0, async () => { granted = true; record.status = "running"; record.startedAt = this.clock.now(); }, resolve6); }); } if (!granted) { if (record.status === "queued") { record.status = "stopped"; record.completedAt = this.clock.now(); } markConsumed(record, this.clock.now()); this.detachParentAbort(record); return record; } } try { record.ranThisRun = record.status === "running"; this.settleOutcome(record, await resumeAgent(record.session, prompt, { clock: this.clock, type: record.type, maxTurns: options?.maxTurns ?? record.invocation?.maxTurns, onTurnEnd: options?.onTurnEnd, onTextDelta: options?.onTextDelta, onModelCall: options?.onModelCall, onToolActivity: (activity) => { if (activity.type === "end") record.toolUses++; options?.onToolActivity?.(activity); }, onAssistantUsage: (usage, message) => { relabelFromResponse(record, message); addUsage(record.lifetimeUsage, usage); this.onUsage?.(record, usage); options?.onAssistantUsage?.(usage); }, onCompaction: (info) => { record.compactionCount++; this.onCompact?.(record, info); options?.onCompaction?.(info); }, signal: abortController.signal })); } catch (err) { this.failResume(record, err); } this.detachParentAbort(record); markConsumed(record, this.clock.now()); this.abortOwnedChildren(id); this.releaseLease(record); this.drainQueue(); return record; } /** * Write a run's outcome onto its record — a spawn's or a resume's, with one * precedence: an external stop keeps "stopped"; a hard abort (turn limit + * grace) is "aborted"; a failed final turn (a provider error pi resolved * instead of rejecting, #144) is an "error", not a completion with an empty * or stale result; otherwise "steered" or "completed". The run's text stays * available in every case. */ settleOutcome(record, { text, failure, aborted, steered }) { if (record.status !== "stopped") { if (aborted) { record.status = "aborted"; } else if (failure) { record.status = "error"; record.error = failure; } else { record.status = steered ? "steered" : "completed"; } } record.result = text; record.completedAt ??= this.clock.now(); } /** A resume whose runner rejected: an error, unless an external stop got there first. */ failResume(record, err) { if (record.status !== "stopped") { record.status = "error"; record.error = errorMessage(err); } record.completedAt ??= this.clock.now(); } /** * Start a background resume run: detached, settling and notifying like * startAgent's background path. Invoked immediately, or from drainQueue when * a concurrency slot frees. The session already exists (resume reuses it), so * there is no onSessionCreated to hang per-run wiring off — callers use * `options.onStarted`, which fires on both the immediate and the drained path. */ startResume(id, record, prompt, parentSignal, options) { if (!record.session) { this.releaseLease(record); this.drainQueue(); return; } record.status = "running"; record.startedAt = this.clock.now(); if (occupiesPoolSlot(record)) this.runningBackground++; this.onStart?.(record); const abortController = new AbortController(); record.abortController = abortController; let detachParentSignal; if (parentSignal) { const onParentAbort = () => this.abort(id); parentSignal.addEventListener("abort", onParentAbort, { once: true }); detachParentSignal = () => parentSignal.removeEventListener("abort", onParentAbort); } try { options.onStarted?.(); } catch { } const settle = () => { detachParentSignal?.(); detachParentSignal = void 0; if (record.outputCleanup) { try { record.outputCleanup(); } catch { } record.outputCleanup = void 0; } this.abortOwnedChildren(id); if (occupiesPoolSlot(record)) this.runningBackground--; this.releaseLease(record); try { this.onComplete?.(record); } catch { } this.drainQueue(); }; record.ranThisRun = true; const promise = resumeAgent(record.session, prompt, { clock: this.clock, type: record.type, maxTurns: options.maxTurns ?? record.invocation?.maxTurns, onTurnEnd: options.onTurnEnd, onTextDelta: options.onTextDelta, onModelCall: options.onModelCall, onToolActivity: (activity) => { if (activity.type === "end") record.toolUses++; options.onToolActivity?.(activity); }, onAssistantUsage: (usage, message) => { relabelFromResponse(record, message); addUsage(record.lifetimeUsage, usage); this.onUsage?.(record, usage); options.onAssistantUsage?.(usage); }, onCompaction: (info) => { record.compactionCount++; this.onCompact?.(record, info); options.onCompaction?.(info); }, signal: abortController.signal }).then((outcome) => { this.settleOutcome(record, outcome); settle(); return outcome.text; }).catch((err) => { this.failResume(record, err); settle(); return ""; }); record.promise = promise; } /** * Send a steering message to an agent from the UI (mirrors the steer_subagent * tool). A live session delivers it now — it interrupts the agent after its * current tool execution and appears as a user message. If the session isn't * ready yet, the message is queued on `pendingSteers` and flushed when the * session is created. Returns false if the agent can't accept steering * (unknown id, or no longer running/queued). Fires `onSteered` on either * accepted path, so the UI viewers, an `@handle` and the RPC all report * the steer the same way without each emitting by hand. The steer tools * bypass this method because they await delivery. */ steer(id, message) { const record = this.agents.get(id); if (!record) return false; if (record.status !== "running" && record.status !== "queued") return false; if (record.session) { record.session.steer(message).catch(() => { }); } else { if (!record.pendingSteers) record.pendingSteers = []; record.pendingSteers.push(message); } this.onSteered?.(record, message); return true; } getRecord(id) { return this.agents.get(id); } /** * Handles held outside this manager, e.g. by live survivors of an orphaned one, which a fresh * spawn must not reuse: a listener keys lifecycle events by handle, so a twin would mix the two up. */ reservedHandles = () => []; /** Handles already in use, so a fresh spawn can pick an unclaimed one. */ takenHandles() { const taken = new Set(this.reservedHandles()); for (const record of this.agents.values()) { if (record.handle) taken.add(record.handle); if (record.alias) taken.add(record.alias); } for (const entry of this.tombstones.values()) { taken.add(entry.handle); if (entry.alias) taken.add(entry.alias); } return taken; } /** * Resolve an `@name` from the prompt. Matches a top-level agent's handle or * alias case-insensitively, then falls back to an exact agent id so * `@` works too. */ resolveMention(name) { const wanted = name.toLowerCase(); for (const record of this.agents.values()) { if (record.parentAgentId !== void 0) continue; if (record.handle === wanted || record.alias === wanted) return { kind: "live", record }; } const byId = this.agents.get(name); if (byId?.parentAgentId === void 0 && byId !== void 0) return { kind: "live", record: byId }; for (const entry of this.tombstones.values()) { if (entry.handle.toLowerCase() === wanted || entry.alias?.toLowerCase() === wanted || entry.id === name) { return { kind: "tombstone", entry }; } } return void 0; } /** * Forget an evicted agent, by handle. For the case where its session file has * gone: the entry can then only ever fail, while still holding the name * against the type that would otherwise start a fresh agent under it. * * A *successful* resume does not drop its tombstone — the live record it * creates already wins in `resolveMention`, and overwrites the entry in place * when it is itself evicted. */ dropTombstone(handle) { this.tombstones.delete(handle); } /** Evicted agents whose conversation can still be reopened, newest first. */ listTombstones() { return [...this.tombstones.values()].sort((a, b) => b.completedAt - a.completedAt); } listAgents() { return [...this.agents.values()].sort( (a, b) => b.startedAt - a.startedAt ); } /** * Stop a running or queued agent; false when it was neither. * * @param by `"parent"` when the agent that spawned it asked (`stop_subagent`); * omitted for a human stop. Written on every stop, so a resumed record never * carries an earlier run's answer. */ abort(id, by) { const record = this.agents.get(id); if (!record) return false; if (record.status === "queued") { this.dequeue((q) => q.id === id); record.stoppedBy = by; this.stopQueued(record); return true; } if (record.status !== "running") return false; record.stoppedBy = by; record.abortController?.abort(); record.status = "stopped"; record.completedAt = this.clock.now(); return true; } /** Mark a dequeued record stopped and tell `onQueuedStop`; the queue entry is already gone. */ stopQueued(record) { record.status = "stopped"; record.completedAt = this.clock.now(); this.onQueuedStop?.(record); } /** Dispose a record's session and remove it from the map. */ removeRecord(id, record) { this.tombstone(record); this.noteEviction(record); const session = record.session; record.session = void 0; this.agents.delete(id); this.startups.delete(id); void shutdownChildSession(session); } /** * Preserve enough of a departing record for `@handle` to reopen its * conversation later. Nothing to keep unless it has both a handle to be * addressed by and a session file to reopen — an in-memory session leaves no * transcript, so the mention would have nothing to continue from. */ tombstone(record) { const entry = this.tombstoneOf(record); if (entry) this.storeTombstone(entry); } /** What `@handle` needs to reopen `record`'s conversation; undefined without a handle and a session file. */ tombstoneOf(record) { if (!record.handle || !record.sessionFile) return void 0; return { handle: record.handle, alias: record.alias, id: record.id, type: record.type, description: record.description, sessionFile: record.sessionFile, completedAt: record.completedAt, ...record.modelTier ? { modelTier: record.modelTier } : {}, ...record.modelFallback ? { modelFallback: record.modelFallback } : {} }; } /** Tombstones for whichever of `ids` are settled here and reopenable, to hand to a session that will never see these records. */ evictionTombstones(ids) { return [...this.agents.values()].filter(isSettled).filter((record) => isTopLevelAgent(record) && ids.includes(record.id)).flatMap((record) => this.tombstoneOf(record) ?? []); } /** * Keep `entry` reopenable by handle, alias and id. Also how an agent that settled in an * orphaned manager (`/new`, `/reload`) stays reopenable here (#330). A name already held * by another live agent, an evicted conversation or a handle reserved for another manager's * survivor stays with its holder (as `takenHandles` has it): two conversations must not * answer to one `@name`. The entry is then not kept and its note says why. */ rememberTombstone(entry) { const names = [entry.handle, ...entry.alias ? [entry.alias] : []]; const reserved = new Set(this.reservedHandles()); const owns = (own, name) => own.id !== entry.id && (name === own.handle || name === own.alias); const taken = names.find( (name) => reserved.has(name) || [...this.agents.values()].some((own) => owns(own, name)) || [...this.tombstones.values()].some((own) => owns(own, name)) ); if (taken !== void 0) { const note = this.evictedNotes.get(entry.id); if (note) note.nameTaken = taken; return; } this.storeTombstone(entry); } storeTombstone(entry) { this.tombstones.set(entry.handle, entry); while (this.tombstones.size > MAX_TOMBSTONES) { const oldest = [...this.tombstones.values()].reduce((a, b) => a.completedAt <= b.completedAt ? a : b); this.tombstones.delete(oldest.handle); } } /** Remember that `record` existed, so its id still answers with something better than "not found". */ noteEviction(record) { if (!isTopLevelAgent(record)) return; this.rememberEvicted(this.evictionNote(record)); } /** Notes for whichever of `ids` are settled here, to hand to a session that will never see these records. */ evictionNotes(ids) { return [...this.agents.values()].filter(isSettled).filter((record) => isTopLevelAgent(record) && ids.includes(record.id)).map((record) => this.evictionNote(record)); } /** What a settled record leaves behind once it is gone from this manager. */ evictionNote(record) { return { id: record.id, type: record.type, description: record.description, status: record.status, evictedAfterMin: Math.max(0, Math.round((this.clock.now() - record.completedAt) / 6e4)), transcript: record.outputFile ?? record.sessionFile, ...record.modelTier ? { modelTier: record.modelTier } : {}, ...record.modelFallback ? { modelFallback: record.modelFallback } : {} }; } /** * Keep `note` addressable by its id, bounded by age. Also how a result handed * over by an orphaned manager (`/new`, `/reload`) stays answerable here: the * record settled in a manager this one never saw (#330). */ rememberEvicted(note) { this.evictedNotes.delete(note.id); this.evictedNotes.set(note.id, note); for (const oldest of this.evictedNotes.keys()) { if (this.evictedNotes.size <= MAX_EVICTED_NOTES) break; this.evictedNotes.delete(oldest); } } /** Record that evicted `id` was reopened as `next`; bounded like the eviction notes. */ linkSuccessor(id, next) { this.successors.delete(id); this.successors.set(id, next); if (this.successors.size > MAX_EVICTED_NOTES) this.successors.delete(this.successors.keys().next().value); } /** Forget a reopen that never started, so `id` resolves to its tombstone again. */ unlinkSuccessor(id) { this.successors.delete(id); } /** The newest id `id` continues under, following every reopen; `id` itself when never reopened. */ latestId(id) { let current = id; for (let next = this.successors.get(current); next !== void 0; next = this.successors.get(current)) current = next; return current; } /** What became of an evicted agent, by id; undefined for an id this session never evicted. */ getEvictedNote(id) { return this.evictedNotes.get(id); } /** * Evict finished records past their window: 10 minutes from the moment the * result was consumed, 60 from completion while nobody has read it. A consumed * record with no stamp (set directly, not through `markConsumed`) is aged from * completion. */ cleanup() { const now = this.clock.now(); for (const [id, record] of this.agents) { if (!isSettled(record)) continue; const { completedAt } = record; const expired = record.resultConsumed ? now - (record.consumedAt ?? completedAt) >= this.consumedTtlMs : now - completedAt >= this.unreadTtlMs; if (!expired) continue; const ran = record.ranThisRun === true && (record.result !== void 0 || record.error !== void 0); this.removeRecord(id, record); const note = record.resultConsumed || record.noticeDelivered || !ran ? void 0 : this.evictedNotes.get(id); if (note) this.onReaped?.(note); } } /** * Remove all completed/stopped/errored records immediately. * Called on session start/switch so tasks from a prior session don't persist. * Pass skipUnconsumed=true to preserve records the LLM hasn't read yet * (resultConsumed=false) — they will be evicted by the cleanup timer instead (60 minutes). */ clearCompleted(skipUnconsumed = false) { for (const [id, record] of this.agents) { if (!isSettled(record)) continue; if (skipUnconsumed && !record.resultConsumed) continue; this.removeRecord(id, record); } this.tombstones.clear(); this.evictedNotes.clear(); this.successors.clear(); } /** Whether any agents are still running or queued. */ hasRunning() { return [...this.agents.values()].some( (r) => r.status === "running" || r.status === "queued" ); } /** * The session's own agents (see `isTopLevelAgent`) still running or queued, * split by whether their completion wakes the parent. A background agent's * settle sends a completion notice that starts a turn, in every join mode; * a foreground one, or an RPC spawn that omits `isBackground`, is marked * consumed at settle and notifies nobody. Owned children report through their owner, so counting * them would double-count the same work. */ ownedPending() { const pending = [...this.agents.values()].filter( (r) => isTopLevelAgent(r) && (r.status === "running" || r.status === "queued") ); const notifying = pending.filter((r) => r.isBackground).length; return { notifying, silent: pending.length - notifying }; } /** * Abort everything that cannot outlive its session and let the rest finish. * Survivors are running top-level background agents and their nested children: * they own their own session and report through a notification. Queued agents * would start later against a stale context, foreground agents belong to a * tool call that is being torn down, and workflow children die with their * workflow, so all of those are aborted. A QUEUED nested child is kept: its * parent is a survivor waiting on it (the process budget can queue one), and * if the parent is stopped instead, its settle aborts the child. * * @returns how many agents keep running. */ detach() { const keepQueued = ({ record }) => record.parentAgentId !== void 0 && record.workflowId === void 0; const dropped = this.queue.filter((entry) => !keepQueued(entry)).map(({ record }) => record); this.dequeue((entry) => !keepQueued(entry)); for (const record of dropped) this.stopQueued(record); let survivors = 0; for (const record of this.agents.values()) { if (record.status !== "running") continue; const outlives = record.workflowId === void 0 && (!!record.isBackground || record.parentAgentId !== void 0); if (outlives) { survivors++; continue; } record.abortController?.abort(); record.status = "stopped"; record.completedAt = this.clock.now(); } return survivors; } /** Abort all running and queued agents immediately. */ abortAll() { let count = 0; const dropped = this.queue.map(({ record }) => record); this.dequeue(() => true); for (const record of dropped) { this.stopQueued(record); count++; } for (const record of this.agents.values()) { if (record.status === "running") { record.abortController?.abort(); record.status = "stopped"; record.completedAt = this.clock.now(); count++; } } return count; } /** Wait for all running and queued agents to complete (including queued ones). */ async waitForAll() { while (true) { this.drainQueue(); const pending = []; for (const record of this.agents.values()) { if (record.status !== "running" && record.status !== "queued") continue; const startup = this.startups.get(record.id); if (startup) pending.push(startup); if (record.promise) pending.push(record.promise); } for (const entry of this.queue) pending.push(entry.left); if (pending.length === 0) break; await Promise.allSettled(pending); } } /** * @param pi - Needed to run `git worktree prune`, which is async now and so * cannot be reached through a stored spawn argument at shutdown. Omitting * it (tests, teardown of a manager that never spawned) skips the prune. */ async dispose(pi) { this.cleanupInterval.cancel(); this.dequeue(() => true); const sessions = [...this.agents.values()].map((record) => record.session); this.agents.clear(); this.startups.clear(); if (pi) { const prune = (repo) => { pruneWorktrees(pi, repo).catch(() => { }); }; prune(process.cwd()); for (const repo of this.worktreeRepos) prune(repo); } await Promise.all(sessions.map((session) => shutdownChildSession(session))); this.drainQueue(); } }; // src/model-call.ts var STALL_MS = 2 * 6e4; var CHARS_PER_TOKEN = 4; function applyModelCallEvent(current, event, now) { switch (event.type) { case "start": return { startedAt: now, lastEventAt: now, kind: "thinking", writtenChars: 0 }; case "end": return void 0; case "beat": return current ? { ...current, lastEventAt: now } : current; case "delta": { const base = current ?? { startedAt: now, lastEventAt: now, kind: "thinking", writtenChars: 0 }; return { ...base, lastEventAt: now, // Once it has started writing, a late thinking block does not flip it back. kind: event.kind === "writing" ? "writing" : base.kind, writtenChars: base.writtenChars + (event.kind === "writing" ? event.chars : 0) }; } } } function formatClock(ms) { const total = Math.max(0, Math.floor(ms / 1e3)); if (total < 60) return `${total}s`; const minutes = Math.floor(total / 60); if (minutes < 60) return `${minutes}m${String(total % 60).padStart(2, "0")}s`; return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}m`; } function describeModelCall(state2, now) { if (!state2) return void 0; const silent = now - state2.lastEventAt; if (silent >= STALL_MS) return `stalled? \xB7 ${formatClock(silent)}`; if (state2.kind === "writing") { const tokens = Math.round(state2.writtenChars / CHARS_PER_TOKEN); return `writing \xB7 ${tokens < 1e3 ? `${tokens}` : `${(tokens / 1e3).toFixed(1).replace(/\.0$/, "")}k`} tok`; } return `thinking \xB7 ${formatClock(now - state2.startedAt)}`; } // src/ui/fallback-flag.ts import { stripTerminalSequences, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui"; function switchedWithinTier(tier) { if (tier.kind !== "routed" && tier.kind !== "static") return false; const baseline = tier.kind === "routed" ? tier.admitted : tier.member; return baseline !== void 0 && tier.answered !== void 0 && tier.answered !== baseline; } var hasFallback = (carrier) => { if (carrier?.modelFallback !== void 0) return true; const tier = carrier?.modelTier; if (!tier) return carrier?.modelNote !== void 0; return tier.kind === "unmapped" || tier.kind === "unavailable" || switchedWithinTier(tier); }; function fallbackFlagText(count = 1, carrier) { const tier = carrier?.modelTier; const suffix = count > 1 ? ` x${count}` : ""; return tier ? `[@${tier.tier}${tier.kind !== "routed" && tier.kind !== "static" ? ` ${tier.kind}` : ""}${suffix}]` : `[fallback${suffix}]`; } function fallbackFlag(theme, carrier, count = 1) { if (carrier?.modelTier) return theme.fg(hasFallback(carrier) ? "warning" : "dim", fallbackFlagText(count, carrier)); return hasFallback(carrier) ? theme.fg("warning", fallbackFlagText(count, carrier)) : ""; } var MINIMAL_FLAGS = ["[fb]", "!"]; function boundedWrappedRows(text, width, maxRows, marker) { const rows = wrapTextWithAnsi(text, width); const budget = Number.isFinite(maxRows) ? Math.max(3, Math.trunc(maxRows)) : 3; if (rows.length <= budget) return rows; const firstCount = Math.max(1, Math.floor((budget - 1) / 2)); const lastCount = budget - firstCount - 1; const omitted = rows.length - firstCount - lastCount; const omission = stripTerminalSequences( truncateToWidth(`${marker} ${omitted} more lines`, width, "") ); return [...rows.slice(0, firstCount), omission, ...rows.slice(-lastCount)]; } function withLeadingFlag(prefix, flag, rest, width) { const lead = flag ? `${prefix}${flag}${rest === "" ? "" : " "}` : prefix; if (!flag || visibleWidth(lead) <= width) { const inner = Math.max(0, width - visibleWidth(lead)); const body = typeof rest === "function" ? rest(inner) : truncateToWidth(rest, inner); return truncateToWidth(lead + body, width); } const flagWidth = visibleWidth(flag); if (flagWidth <= width) { const inner = width - flagWidth - 1; if (inner < 1 || rest === "") return flag; const body = typeof rest === "function" ? rest(inner) : truncateToWidth(rest, inner); return truncateToWidth(`${flag} ${body}`, width); } return MINIMAL_FLAGS.find((m) => visibleWidth(m) <= width) ?? ""; } // src/ui/agent-widget.ts var MAX_WIDGET_LINES = 12; var SPINNER = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"]; var ERROR_STATUSES = /* @__PURE__ */ new Set(["error", "aborted", "steered", "stopped"]); var TOOL_DISPLAY = { read: "reading", bash: "running command", edit: "editing", write: "writing", grep: "searching", find: "finding files", ls: "listing" }; function fgPreservingNestedStyles(theme, color, text) { const styledEmpty = theme.fg(color, ""); const styleStart = styledEmpty.replace(/\u001b\[(?:0|39)m/g, ""); return theme.fg(color, text.replace(/\u001b\[(?:0|39)m/g, (reset) => `${reset}${styleStart}`)); } function formatCompactTokens(count) { const thousands = Number((count / 1e3).toFixed(1)); if (thousands >= 1e3) return `${(count / 1e6).toFixed(1)}M`; if (count >= 1e3) return `${thousands.toFixed(1)}k`; return `${count}`; } function formatTokens(count) { return `${formatCompactTokens(count)} token`; } function formatCost(cost) { if (!(cost > 0)) return ""; if (cost < 1e-4) return "<$0.0001"; if (cost >= 1) return `~$${cost.toFixed(2)}`; const rounded = Number(cost.toFixed(4)); const decimals = (String(rounded).split(".")[1] ?? "").length; return `~$${rounded.toFixed(Math.max(2, decimals))}`; } function formatSessionTokens(tokens, percent, theme, compactions = 0) { const tokenStr = formatTokens(tokens); const annot = []; if (percent !== null) { const color = percent >= 85 ? "error" : percent >= 70 ? "warning" : "dim"; annot.push(theme.fg(color, `${Math.round(percent)}%`)); } if (compactions > 0) { annot.push(theme.fg("dim", `\u21CA${compactions}`)); } if (annot.length === 0) return tokenStr; return `${tokenStr} (${annot.join(" \xB7 ")})`; } function formatTurns(turnCount, maxTurns) { return maxTurns != null ? `\u21BB${turnCount}\u2264${maxTurns}` : `\u21BB${turnCount}`; } function formatMs(ms) { return `${(ms / 1e3).toFixed(1)}s`; } function formatDuration(startedAt, completedAt, now = Date.now()) { if (completedAt) return formatMs(completedAt - startedAt); return `${formatMs(now - startedAt)} (running)`; } function getDisplayName(type) { return getConfig(type).displayName; } function getPromptModeLabel(type) { const config = getConfig(type); return config.promptMode === "append" ? "twin" : void 0; } function buildInvocationTags(invocation) { const tags = []; if (!invocation) return { tags }; const asked = (value, requested) => value && requested && requested !== value ? `${value} (asked ${requested})` : value; const thinking = asked(invocation.thinking, invocation.requestedThinking); if (thinking) tags.push(`thinking: ${thinking}`); if (invocation.isolated) tags.push("isolated"); if (invocation.isolation === "worktree") tags.push("worktree"); if (invocation.planMode) tags.push("plan"); if (invocation.inheritContext) tags.push("inherit context"); if (invocation.runInBackground) tags.push("background"); if (invocation.maxTurns != null) tags.push(`max turns: ${invocation.maxTurns}`); return { modelName: invocation.modelName, modelId: invocation.modelId, tags }; } function compactThinkingTag(tags) { return (tags.find((tag) => tag.startsWith("thinking: ")) ?? "").replace(/^thinking: /, "think:"); } function truncateLine(text, len = 60) { const line = text.trim().split("\n")[0].trimEnd(); if (line.length <= len) return line; return line.slice(0, len) + "\u2026"; } function describeActivity(activeTools, responseText, modelCall, now = Date.now()) { if (activeTools.size > 0) { const groups = /* @__PURE__ */ new Map(); for (const toolName of activeTools.values()) { const action = TOOL_DISPLAY[toolName] ?? toolName; groups.set(action, (groups.get(action) ?? 0) + 1); } const parts = []; for (const [action, count] of groups) { if (count > 1) { parts.push(`${action} ${count} ${action === "searching" ? "patterns" : "files"}`); } else { parts.push(action); } } return parts.join(", ") + "\u2026"; } const call = describeModelCall(modelCall, now); if (call) return call; if (responseText && responseText.trim().length > 0) { return truncateLine(responseText); } return "thinking\u2026"; } var AgentWidget = class _AgentWidget { constructor(manager, agentActivity, mode = () => "all", showCost = () => false, showModel = () => false, clock = realClock) { this.manager = manager; this.agentActivity = agentActivity; this.mode = mode; this.showCost = showCost; this.showModel = showModel; this.clock = clock; } manager; agentActivity; mode; showCost; showModel; clock; uiCtx; widgetFrame = 0; widgetInterval; /** Tracks how many turns each finished agent has survived. Key: agent ID, Value: turns since finished. */ finishedTurnAge = /* @__PURE__ */ new Map(); /** How many extra turns errors/aborted agents linger (completed agents clear after 1 turn). */ static ERROR_LINGER_TURNS = 2; /** Whether the widget callback is currently registered with the TUI. */ widgetRegistered = false; /** Cached TUI reference from widget factory callback, used for requestRender(). */ tui; /** The registered widget component, so a late `dispose()` of a replaced one is ignored. */ component; /** Last status bar text, used to avoid redundant setStatus calls. */ lastStatusText; /** * Agents eligible for the widget, per the current `WidgetMode`: * - `off`: none (the widget's existing empty-state path hides it entirely). * - `background`: drop only agents *known* to be foreground * (`isBackground === false`); keep everything else — background, queued, * scheduled, or RPC-spawned (`undefined`). Keying off the `isBackground` * record flag rather than the UI-only `invocation` snapshot (which only the * Agent-tool path sets), and excluding rather than allow-listing, means * only proven-foreground runs drop out — nothing else silently vanishes. * - `all`: every agent. */ widgetAgents() { const all = this.manager.listAgents().filter(isTopLevelAgent); switch (this.mode()) { case "off": return []; case "background": return all.filter((a) => a.isBackground !== false); default: return all; } } /** Set the UI context (grabbed from first tool execution). */ setUICtx(ctx) { if (ctx !== this.uiCtx) { this.uiCtx = ctx; this.widgetRegistered = false; this.tui = void 0; this.lastStatusText = void 0; } } /** * Called on each new turn (tool_execution_start). * Ages finished agents and clears those that have lingered long enough. */ onTurnStart() { for (const [id, age] of this.finishedTurnAge) { this.finishedTurnAge.set(id, age + 1); } this.update(); } /** Ensure the widget update timer is running. */ ensureTimer() { if (!this.widgetInterval) { this.widgetInterval = this.clock.setInterval(() => this.update(), 80); } } /** Check if a finished agent should still be shown in the widget. */ shouldShowFinished(agentId, status) { const age = this.finishedTurnAge.get(agentId) ?? 0; const maxAge = ERROR_STATUSES.has(status) ? _AgentWidget.ERROR_LINGER_TURNS : 1; return age < maxAge; } /** Record an agent as finished (call when agent completes). */ markFinished(agentId) { if (!this.finishedTurnAge.has(agentId)) { this.finishedTurnAge.set(agentId, 0); } } /** * Drop an agent's finished-age (call when a settled agent starts running * again, i.e. a background resume). markFinished only seeds an age it has not * seen before, so a resumed agent would otherwise keep the age from its * previous run — already past the linger limit, hiding the new run's * completion line entirely. */ markRunning(agentId) { this.finishedTurnAge.delete(agentId); } /** Render a finished agent line. */ renderFinishedLine(a, theme) { const modeLabel = getPromptModeLabel(a.type); const duration = formatMs(a.completedAt - a.startedAt); let icon; let statusText; if (a.status === "completed") { icon = theme.fg("success", "\u2713"); statusText = ""; } else if (a.status === "steered") { icon = theme.fg("warning", "\u2713"); statusText = theme.fg("warning", " (turn limit)"); } else if (a.status === "stopped") { icon = theme.fg("dim", "\u25A0"); statusText = theme.fg("dim", " stopped"); } else if (a.status === "error") { icon = theme.fg("error", "\u2717"); const errMsg = a.error ? `: ${a.error.slice(0, 60)}` : ""; statusText = theme.fg("error", ` error${errMsg}`); } else { icon = theme.fg("error", "\u2717"); statusText = theme.fg("warning", " aborted"); } const parts = []; const activity = this.agentActivity.get(a.id); if (activity) parts.push(formatTurns(activity.turnCount, activity.maxTurns)); if (a.toolUses > 0) parts.push(`${a.toolUses} tool use${a.toolUses === 1 ? "" : "s"}`); const costText = this.showCost() ? formatCost(getLifetimeCost(a.lifetimeUsage)) : ""; if (costText) parts.push(costText); parts.push(duration); const modeTag = modeLabel ? ` ${theme.fg("dim", `(${modeLabel})`)}` : ""; const flag = fallbackFlag(theme, a) ? `${fallbackFlag(theme, a)} ` : ""; return `${icon} ${flag}${renderAgentName(a.type, theme, { fallbackColor: "dim" })}${modeTag} ${theme.fg("dim", a.description)} ${theme.fg("dim", "\xB7")} ${theme.fg("dim", parts.join(" \xB7 "))}${statusText}`; } /** * Render the widget content. Called from the registered widget's render() callback, * reading live state each time instead of capturing it in a closure. */ renderWidget(tui, theme) { const allAgents = this.widgetAgents(); const running = allAgents.filter((a) => a.status === "running"); const queued = allAgents.filter((a) => a.status === "queued"); const finished = allAgents.filter( (a) => a.status !== "running" && a.status !== "queued" && !!a.completedAt && this.shouldShowFinished(a.id, a.status) ); const hasActive = running.length > 0 || queued.length > 0; const hasFinished = finished.length > 0; if (!hasActive && !hasFinished) return []; const w = tui.terminal.columns; const truncate = (line) => truncateToWidth2(line, w); const headingColor = hasActive ? "accent" : "dim"; const headingIcon = hasActive ? "\u25CF" : "\u25CB"; const frame = SPINNER[this.widgetFrame % SPINNER.length]; const finishedLines = []; for (const a of finished) { finishedLines.push(truncate(theme.fg("dim", "\u251C\u2500") + " " + this.renderFinishedLine(a, theme))); } const runningLines = []; for (const a of running) { const modeLabel = getPromptModeLabel(a.type); const modeTag = modeLabel ? ` ${theme.fg("dim", `(${modeLabel})`)}` : ""; const flag = fallbackFlag(theme, a) ? `${fallbackFlag(theme, a)} ` : ""; const elapsed = formatMs(this.clock.now() - a.startedAt); const bg = this.agentActivity.get(a.id); const toolUses = bg?.toolUses ?? a.toolUses; const tokens = getLifetimeTotal(a.lifetimeUsage); const contextPercent = getSessionContextPercent(bg?.session); const tokenText = tokens > 0 ? formatSessionTokens(tokens, contextPercent, theme, a.compactionCount) : ""; const costText = this.showCost() ? formatCost(getLifetimeCost(a.lifetimeUsage)) : ""; const parts = []; if (this.showModel()) { const { modelName, tags } = buildInvocationTags(a.invocation); if (modelName) parts.push(modelName); const thinkingTag = compactThinkingTag(tags); if (thinkingTag) parts.push(thinkingTag); } if (bg) parts.push(formatTurns(bg.turnCount, bg.maxTurns)); if (toolUses > 0) parts.push(`${toolUses} tool use${toolUses === 1 ? "" : "s"}`); if (tokenText) parts.push(tokenText); if (costText) parts.push(costText); parts.push(elapsed); const statsText = parts.join(" \xB7 "); const activity = bg ? describeActivity(bg.activeTools, bg.responseText, bg.modelCall, this.clock.now()) : "thinking\u2026"; runningLines.push([ truncate(theme.fg("dim", "\u251C\u2500") + ` ${theme.fg("accent", frame)} ${flag}${renderAgentName(a.type, theme, { bold: true })}${modeTag} ${theme.fg("muted", a.description)} ${theme.fg("dim", "\xB7")} ${fgPreservingNestedStyles(theme, "dim", statsText)}`), truncate(theme.fg("dim", "\u2502 ") + theme.fg("dim", ` \u23BF ${activity}`)) ]); } const queuedLine = queued.length > 0 ? truncate(theme.fg("dim", "\u251C\u2500") + ` ${theme.fg("muted", "\u25E6")} ${theme.fg("dim", `${queued.length} queued`)}`) : void 0; const maxBody = MAX_WIDGET_LINES - 1; const totalBody = finishedLines.length + runningLines.length * 2 + (queuedLine ? 1 : 0); const lines = [truncate(theme.fg(headingColor, headingIcon) + " " + theme.fg(headingColor, "Agents"))]; if (totalBody <= maxBody) { lines.push(...finishedLines); for (const pair of runningLines) lines.push(...pair); if (queuedLine) lines.push(queuedLine); const last = lines.length - 1; lines[last] = lines[last].replace("\u251C\u2500", "\u2514\u2500"); if (runningLines.length > 0 && !queuedLine) { lines[last - 1] = lines[last - 1].replace("\u251C\u2500", "\u2514\u2500"); lines[last] = lines[last].replace("\u2502 ", " "); } } else { let budget = maxBody - 1; let hiddenRunning = 0; let hiddenFinished = 0; const queuedReserve = queuedLine ? 1 : 0; budget -= queuedReserve; for (const pair of runningLines) { if (budget >= 2) { lines.push(...pair); budget -= 2; } else { hiddenRunning++; } } if (queuedLine) { budget += queuedReserve; lines.push(queuedLine); budget--; } for (const fl of finishedLines) { if (budget >= 1) { lines.push(fl); budget--; } else { hiddenFinished++; } } const overflowParts = []; if (hiddenRunning > 0) overflowParts.push(`${hiddenRunning} running`); if (hiddenFinished > 0) overflowParts.push(`${hiddenFinished} finished`); const overflowText = overflowParts.join(", "); lines.push( truncate(theme.fg("dim", "\u2514\u2500") + ` ${theme.fg("dim", `+${hiddenRunning + hiddenFinished} more (${overflowText})`)}`) ); } return lines; } /** Force an immediate widget update. */ update() { if (!this.uiCtx) return; const allAgents = this.widgetAgents(); let runningCount = 0; let queuedCount = 0; let hasFinished = false; for (const a of allAgents) { if (a.status === "running") { runningCount++; } else if (a.status === "queued") { queuedCount++; } else if (a.completedAt && this.shouldShowFinished(a.id, a.status)) { hasFinished = true; } } const hasActive = runningCount > 0 || queuedCount > 0; if (!hasActive && !hasFinished) { if (this.widgetRegistered) { this.uiCtx.setWidget("agents", void 0); this.widgetRegistered = false; this.tui = void 0; } if (this.lastStatusText !== void 0) { this.uiCtx.setStatus("subagents", void 0); this.lastStatusText = void 0; } if (this.widgetInterval) { this.widgetInterval.cancel(); this.widgetInterval = void 0; } for (const [id] of this.finishedTurnAge) { if (!allAgents.some((a) => a.id === id)) this.finishedTurnAge.delete(id); } return; } let newStatusText; if (hasActive) { const statusParts = []; if (runningCount > 0) statusParts.push(`${runningCount} running`); if (queuedCount > 0) statusParts.push(`${queuedCount} queued`); const total = runningCount + queuedCount; newStatusText = `${statusParts.join(", ")} agent${total === 1 ? "" : "s"}`; } if (newStatusText !== this.lastStatusText) { this.uiCtx.setStatus("subagents", newStatusText); this.lastStatusText = newStatusText; } this.widgetFrame++; if (!this.widgetRegistered) { this.uiCtx.setWidget("agents", (tui, theme) => { this.tui = tui; const component = { render: () => this.renderWidget(tui, theme), invalidate: () => { this.widgetRegistered = false; this.tui = void 0; }, // Core disposes every extension widget on /reload and when plan mode // is entered or left. Without this the flag stayed true, update() only // ever asked a dead component to re-render, and the widget vanished. // Only the live component may reset it: a replaced one is disposed // after its successor registered. dispose: () => { if (this.component !== component) return; this.component = void 0; this.widgetRegistered = false; this.tui = void 0; } }; this.component = component; return component; }, { placement: "aboveEditor" }); this.widgetRegistered = true; } else { this.tui?.requestRender(); } } dispose() { if (this.widgetInterval) { this.widgetInterval.cancel(); this.widgetInterval = void 0; } if (this.uiCtx) { this.uiCtx.setWidget("agents", void 0); this.uiCtx.setStatus("subagents", void 0); } this.widgetRegistered = false; this.component = void 0; this.tui = void 0; this.lastStatusText = void 0; } }; // src/ui/viewer-keys.ts import { matchesKey } from "@earendil-works/pi-tui"; function createViewerKeys(keybindings) { const matches = (data, id, fallback) => keybindings ? keybindings.matches(data, id) : matchesKey(data, fallback); return { scrollUp: (data) => matches(data, "tui.select.up", "up") || matchesKey(data, "k"), scrollDown: (data) => matches(data, "tui.select.down", "down") || matchesKey(data, "j"), pageUp: (data) => matches(data, "tui.select.pageUp", "pageUp") || matchesKey(data, "shift+up"), pageDown: (data) => matches(data, "tui.select.pageDown", "pageDown") || matchesKey(data, "shift+down") }; } // src/ui/conversation-viewer.ts var CHROME_LINES_BASE = 6; var MIN_VIEWPORT = 3; var VIEWPORT_HEIGHT_PCT = 70; var SCROLLBAR_WIDTH = 1; function getConversationOverlayOptions(tui) { return tui.mode === "fullscreen" ? { anchor: "top-left", width: "100%", maxHeight: "100%", margin: 0 } : { anchor: "center", width: "90%", maxHeight: `${VIEWPORT_HEIGHT_PCT}%` }; } var LIVE_TICK_MS = 1e3; var RESULT_MAX_CHARS = 16e3; var MARKDOWN_MODES = ["off", "assistant", "all"]; var MARKDOWN_MODE_LABELS = { off: "raw", assistant: "md", all: "md+" }; var MARKDOWN_OPTIONS = { preserveOrderedListMarkers: true, preserveBackslashEscapes: true }; function resolveMarkdownTheme(th) { try { const piTheme = getMarkdownTheme(); piTheme.heading("probe"); return piTheme; } catch { return fallbackMarkdownTheme(th); } } function fallbackMarkdownTheme(th) { const sgr = (on, off) => (text) => `\x1B[${on}m${text}\x1B[${off}m`; return { heading: (text) => th.bold(th.fg("accent", text)), link: (text) => th.fg("accent", text), linkUrl: (text) => th.fg("muted", text), code: (text) => th.fg("muted", text), codeBlock: (text) => th.fg("muted", text), codeBlockBorder: (text) => th.fg("dim", text), quote: (text) => th.fg("muted", text), quoteBorder: (text) => th.fg("dim", text), hr: (text) => th.fg("dim", text), listBullet: (text) => th.fg("accent", text), bold: (text) => th.bold(text), italic: sgr(3, 23), underline: sgr(4, 24), strikethrough: sgr(9, 29) }; } function capResult(text) { if (text.length <= RESULT_MAX_CHARS) return { text, elided: 0 }; return { text: text.slice(0, RESULT_MAX_CHARS), elided: text.length - RESULT_MAX_CHARS }; } function humanCount(n) { if (n < 1e3) return `${n}`; const thousands = n < 999950; const value = thousands ? n / 1e3 : n / 1e6; return `${value.toFixed(1).replace(/\.0$/, "")}${thousands ? "k" : "M"}`; } function truncationNote(elided) { return `... (truncated, ${humanCount(elided)} more character${elided === 1 ? "" : "s"})`; } var ConversationViewer = class { constructor(tui, session, record, activity, theme, done, onStop, keybindings, onSteer, showCost = false, viewerMarkdown, onMarkdownMode, scrollbarMode = "auto", onBackground, clock = realClock) { this.tui = tui; this.session = session; this.record = record; this.activity = activity; this.theme = theme; this.done = done; this.onStop = onStop; this.onSteer = onSteer; this.showCost = showCost; this.viewerMarkdown = viewerMarkdown; this.onMarkdownMode = onMarkdownMode; this.onBackground = onBackground; this.clock = clock; this.fullscreen = tui.mode === "fullscreen"; this.markdownTheme = resolveMarkdownTheme(theme); this.keys = createViewerKeys(keybindings); this.scrollView = new ScrollView({ render: (width) => this.buildContentLines(width), invalidate: () => { } }, { follow: "end", scrollbar: this.fullscreen ? scrollbarMode : "hidden" }); this.unsubscribe = session.subscribe((event) => { if (this.closed) return; if (this.fullscreen && !this.scrollView.isFollowingEnd && event.type === "message_start" && ["user", "assistant", "toolResult", "bashExecution"].includes(event.message.role)) { this.newMessages++; } this.tui.requestRender(); }); if (record.status === "running" || record.status === "queued") { this.liveTimer = this.clock.setInterval(() => { if (this.closed) return; this.tui.requestRender(); if (this.record.status !== "running" && this.record.status !== "queued") this.stopLiveTimer(); }, LIVE_TICK_MS); this.liveTimer.unref?.(); } } tui; session; record; activity; theme; done; onStop; onSteer; showCost; viewerMarkdown; onMarkdownMode; onBackground; clock; scrollOffset = 0; autoScroll = true; focused = false; fullscreen; viewport; scrollbarGrabOffset; footerTargets = []; latestTarget; newMessages = 0; scrollView; unsubscribe; lastInnerW = 0; closed = false; /** Repaints once a second while the agent runs; see `LIVE_TICK_MS`. */ liveTimer; /** Two-press confirm guard for the stop key, so a stray key can't kill the agent. */ stopArmed = false; keys; /** Steering composer — present while the user is typing a message to the agent. */ composer; /** Resolved once: pi's Markdown theme is fixed for the life of the process. */ markdownTheme; /** Set by the `m` key. Wins over the setting so `m` works without a persist hook. */ markdownModeOverride; /** * One `Markdown` per message, so its own text/width cache does the work. A * fresh instance per render would re-parse the whole transcript on every * keystroke — the component caches, but only across calls to the same object. * Weak so a compacted-away message doesn't pin its render. */ markdownCache = /* @__PURE__ */ new WeakMap(); stopLiveTimer() { this.liveTimer?.cancel(); this.liveTimer = void 0; } close() { this.closed = true; this.done(void 0); } handleInput(data) { if (this.closed) return; if (this.fullscreen && (matchesKey2(data, "ctrl+end") || !this.composer && matchesKey2(data, "end"))) { this.jumpToLatest(); return; } if (this.composer) { this.composer.handleInput(data); this.tui.requestRender(); return; } if (matchesKey2(data, "escape") || matchesKey2(data, "ctrl+c") || matchesKey2(data, "q")) { this.close(); return; } if (matchesKey2(data, "enter") && this.canSteer()) { this.stopArmed = false; this.openComposer(); return; } if (matchesKey2(data, "b") && this.canSendToBackground()) { this.stopArmed = false; this.onBackground?.send(); this.tui.requestRender(); return; } if (matchesKey2(data, "x")) { if (this.isStoppable()) { if (this.stopArmed) { this.stopArmed = false; this.onStop?.(); } else { this.stopArmed = true; } this.tui.requestRender(); } return; } if (matchesKey2(data, "m")) { this.stopArmed = false; const next = MARKDOWN_MODES[(MARKDOWN_MODES.indexOf(this.markdownMode()) + 1) % MARKDOWN_MODES.length]; this.markdownModeOverride = next; this.onMarkdownMode?.(next); this.tui.requestRender(); return; } if (this.stopArmed) this.stopArmed = false; const totalLines = this.buildContentLines(this.lastInnerW).length; const viewportHeight = this.viewportHeight(); if (this.fullscreen) { this.scrollView.updateLayout(totalLines, viewportHeight, () => { if (!this.closed) this.tui.requestRender(); }); if (this.keys.scrollUp(data)) this.scrollView.scrollBy(-1); else if (this.keys.scrollDown(data)) this.scrollView.scrollBy(1); else if (this.keys.pageUp(data)) this.scrollView.scrollBy(-viewportHeight); else if (this.keys.pageDown(data)) this.scrollView.scrollBy(viewportHeight); else if (matchesKey2(data, "home")) this.scrollView.scrollToStart(); return; } const maxScroll = Math.max(0, totalLines - viewportHeight); if (this.keys.scrollUp(data)) { this.scrollOffset = Math.max(0, this.scrollOffset - 1); this.autoScroll = this.scrollOffset >= maxScroll; } else if (this.keys.scrollDown(data)) { this.scrollOffset = Math.min(maxScroll, this.scrollOffset + 1); this.autoScroll = this.scrollOffset >= maxScroll; } else if (this.keys.pageUp(data)) { this.scrollOffset = Math.max(0, this.scrollOffset - viewportHeight); this.autoScroll = false; } else if (this.keys.pageDown(data)) { this.scrollOffset = Math.min(maxScroll, this.scrollOffset + viewportHeight); this.autoScroll = this.scrollOffset >= maxScroll; } else if (matchesKey2(data, "home")) { this.scrollOffset = 0; this.autoScroll = false; } else if (matchesKey2(data, "end")) { this.scrollOffset = maxScroll; this.autoScroll = true; } } jumpToLatest() { this.scrollView.scrollToEnd(); this.newMessages = 0; this.stopArmed = false; this.tui.requestRender(); } handleMouse(event) { if (!this.fullscreen) return { handled: false }; if (this.closed || !this.viewport) return { handled: true, render: false }; const view = this.viewport; const onScrollbar = this.scrollView.scrollbar !== "hidden" && event.x >= view.width - SCROLLBAR_WIDTH && event.x < view.width && event.y >= view.top && event.y < view.top + view.height; if (event.type === "move") { this.scrollView.setScrollbarActive(onScrollbar); return { handled: true, render: false }; } if (event.type === "wheel") { this.stopArmed = false; this.scrollView.scrollBy(event.wheelDelta ?? 0); return { handled: true, render: true }; } if (event.type === "release") { const wasDragging = this.scrollbarGrabOffset !== void 0; this.scrollbarGrabOffset = void 0; this.scrollView.setScrollbarActive(onScrollbar); return { handled: true, render: wasDragging }; } if (event.type === "drag" && this.scrollbarGrabOffset !== void 0) { const travel = view.height - view.thumbHeight; const position = Math.max(0, Math.min(travel, event.y - view.top - this.scrollbarGrabOffset)); this.scrollView.scrollTo(travel > 0 ? Math.round(position / travel * view.maxScroll) : 0); return { handled: true, render: true }; } if (event.type === "press" && event.button === "left") { this.scrollbarGrabOffset = void 0; this.scrollView.setScrollbarActive(onScrollbar); if (this.latestTarget && event.y === this.latestTarget.row && event.x >= this.latestTarget.start && event.x < this.latestTarget.end) { this.jumpToLatest(); return { handled: true, render: true }; } if (event.y === this.tui.terminal.rows - 1) { const target = this.footerTargets.find((t) => event.x >= t.start && event.x < t.end); if (target) { this.handleInput(target.key); return { handled: true, render: true }; } } this.stopArmed = false; if (this.composer && event.y === this.tui.terminal.rows - 2) { this.composer.handleMouse({ ...event, x: event.x - 1, y: 0, width: this.lastInnerW, height: 1 }); return { handled: true, render: true }; } if (onScrollbar && view.maxScroll > 0) { const y = event.y - view.top; if (y >= view.thumbTop && y < view.thumbTop + view.thumbHeight) { this.scrollbarGrabOffset = y - view.thumbTop; return { handled: true, capture: true, render: true }; } this.scrollView.scrollBy(y < view.thumbTop ? -view.height : view.height); this.scrollbarGrabOffset = Math.floor(view.thumbHeight / 2); return { handled: true, capture: true, render: true }; } return { handled: true, render: true }; } return { handled: true, render: false }; } render(width) { this.footerTargets = []; this.latestTarget = void 0; this.viewport = void 0; const rows = Math.max(0, this.tui.terminal.rows); if (!this.fullscreen && width < 6) return []; if (width <= SCROLLBAR_WIDTH + 1) return Array.from({ length: rows }, () => " ".repeat(Math.max(0, width))); const th = this.theme; const innerW = this.fullscreen ? this.scrollView.getContentWidth(width - 1) : width - 4; this.lastInnerW = innerW; const lines = []; const footerActions = []; const pad = (s, len) => { const vis = visibleWidth2(s); return s + " ".repeat(Math.max(0, len - vis)); }; const row = (content, scrollbar) => { if (this.fullscreen) { const contentWidth = width - 1 - (scrollbar ? SCROLLBAR_WIDTH : 0); return " " + truncateToWidth3(content, contentWidth, scrollbar ? "" : "...", true) + (scrollbar ?? ""); } return th.fg("border", "\u2502") + " " + truncateToWidth3(pad(content, innerW), innerW, "...", true) + " " + th.fg("border", "\u2502"); }; const hrTop = th.fg("border", `\u256D${"\u2500".repeat(width - 2)}\u256E`); const hrBot = th.fg("border", `\u2570${"\u2500".repeat(width - 2)}\u256F`); const hrMid = row(th.fg("dim", "\u2500".repeat(innerW))); if (!this.fullscreen) lines.push(hrTop); const modeLabel = getPromptModeLabel(this.record.type); const modeTag = modeLabel ? ` ${th.fg("dim", `(${modeLabel})`)}` : ""; const statusIcon = this.record.status === "running" ? th.fg("accent", "\u25CF") : this.record.status === "completed" ? th.fg("success", "\u2713") : this.record.status === "error" ? th.fg("error", "\u2717") : th.fg("dim", "\u25CB"); const duration = formatDuration(this.record.startedAt, this.record.completedAt, this.clock.now()); const headerParts = [duration]; const toolUses = this.activity?.toolUses ?? this.record.toolUses; if (toolUses > 0) headerParts.unshift(`${toolUses} tool${toolUses === 1 ? "" : "s"}`); const tokens = getLifetimeTotal(this.record.lifetimeUsage); if (tokens > 0) { const percent = getSessionContextPercent(this.activity?.session); headerParts.push(formatSessionTokens(tokens, percent, th, this.record.compactionCount)); } const cost = this.showCost ? formatCost(getLifetimeCost(this.record.lifetimeUsage)) : ""; if (cost) headerParts.push(cost); lines.push(row( `${statusIcon} ${renderAgentName(this.record.type, th, { bold: true })}${modeTag} ${th.fg("muted", this.record.description)} ${th.fg("dim", "\xB7")} ${fgPreservingNestedStyles(th, "dim", headerParts.join(" \xB7 "))}` )); const invocationLine = this.invocationLine(); if (invocationLine) lines.push(row(invocationLine)); lines.push(hrMid); const contentLines = this.fullscreen ? this.scrollView.render(width - 1) : this.buildContentLines(innerW); const viewportHeight = this.viewportHeight(); const maxScroll = Math.max(0, contentLines.length - viewportHeight); if (this.fullscreen) { this.scrollView.updateLayout(contentLines.length, viewportHeight, () => { if (!this.closed) this.tui.requestRender(); }); if (this.scrollView.isFollowingEnd) this.newMessages = 0; } else if (this.autoScroll) { this.scrollOffset = maxScroll; } const visibleStart = this.fullscreen ? this.scrollView.scrollTop : Math.min(this.scrollOffset, maxScroll); const visible = contentLines.slice(visibleStart, visibleStart + viewportHeight); const thumbHeight = Math.min(viewportHeight, Math.max(2, Math.round(viewportHeight * viewportHeight / Math.max(1, contentLines.length)))); const thumbTop = maxScroll > 0 ? Math.round(visibleStart / maxScroll * (viewportHeight - thumbHeight)) : 0; this.viewport = { width, top: lines.length, height: viewportHeight, maxScroll, thumbTop, thumbHeight }; for (let i = 0; i < viewportHeight; i++) { let scrollbar; if (this.scrollView.isScrollbarVisible) { const onThumb = i >= thumbTop && i < thumbTop + thumbHeight; if (onThumb) { scrollbar = th.fg("scrollbarThumb", this.scrollView.isScrollbarActive ? "\u2588" : "\u2503"); } else { scrollbar = th.fg("scrollbarTrack", "\u2502"); } } lines.push(row(visible[i] ?? "", scrollbar)); } if (this.fullscreen && !this.scrollView.isFollowingEnd && maxScroll > 0 && rows >= this.chromeLines()) { const text = this.newMessages > 0 ? `${this.newMessages} new message${this.newMessages === 1 ? "" : "s"}` : "Jump to latest message"; const label = truncateToWidth3(`[ \u2193 ${text} \xB7 Ctrl+End ]`, innerW, "\u2026"); const labelWidth = visibleWidth2(label); const padding = Math.floor((innerW - labelWidth) / 2); this.latestTarget = { row: lines.length, start: padding + 1, end: padding + 1 + labelWidth }; lines.push(row(th.fg("dim", "\u2500".repeat(padding)) + th.fg("accent", label) + th.fg("dim", "\u2500".repeat(innerW - padding - labelWidth)))); } else { lines.push(hrMid); } if (this.composer) { this.composer.focused = this.focused; lines.push(row(this.composer.render(innerW)[0])); footerActions.push({ label: "Enter send", key: "\r" }, { label: "Esc cancel", key: "\x1B" }); const composeHint = th.fg("dim", "Enter send \xB7 Esc cancel"); const composeLeft = th.fg("accent", "\u270E steer"); const composeGap = Math.max(1, innerW - visibleWidth2(composeLeft) - visibleWidth2(composeHint)); lines.push(row(composeLeft + " ".repeat(composeGap) + composeHint)); } else { const sep3 = th.fg("dim", " \xB7 "); if (this.canSteer()) footerActions.push({ label: "Enter steer", key: "\r" }); if (this.canSendToBackground()) footerActions.push({ label: "b bg", key: "b" }); if (this.isStoppable()) { footerActions.push({ label: this.stopArmed ? "x again to STOP" : "x stop", key: "x" }); } footerActions.push({ label: `m ${MARKDOWN_MODE_LABELS[this.markdownMode()]}`, key: "m" }); const actions = footerActions.map((a) => th.fg(a.key === "x" && this.stopArmed ? "error" : "dim", a.label)); footerActions.push({ label: "Esc close", key: "\x1B" }); const footerRight = th.fg("dim", "\u2191\u2193 scroll \xB7 PgUp/PgDn or Shift+\u2191\u2193 \xB7 Esc close"); const scrollPct = contentLines.length <= viewportHeight ? "100%" : `${Math.round((visibleStart + viewportHeight) / contentLines.length * 100)}%`; const count = th.fg("dim", `${contentLines.length} lines \xB7 ${scrollPct}`); const withCount = [count, ...actions].join(sep3); const footerLeft = visibleWidth2(withCount) + visibleWidth2(footerRight) + 1 <= innerW ? withCount : actions.join(sep3); const footerGap = Math.max(1, innerW - visibleWidth2(footerLeft) - visibleWidth2(footerRight)); lines.push(row(footerLeft + " ".repeat(footerGap) + footerRight)); } if (!this.fullscreen) { lines.push(hrBot); return lines; } const footer = lines.pop(); const output = rows > 0 ? [...lines.slice(0, rows - 1), footer] : []; const footerText = stripTerminalSequences2(footer); for (const action of footerActions) { const index = footerText.indexOf(action.label); if (index < 0) continue; const start = visibleWidth2(footerText.slice(0, index)); this.footerTargets.push({ start, end: start + visibleWidth2(action.label), key: action.key }); } return output; } /** Stoppable only when a stop handler exists and the agent is still active. */ isStoppable() { return !!this.onStop && (this.record.status === "running" || this.record.status === "queued"); } /** The mode in force: an `m` press, else the setting, else the default. */ markdownMode() { return this.markdownModeOverride ?? this.viewerMarkdown?.() ?? "assistant"; } /** Wrap `text` literally — the pre-Markdown path, and the fallback from it. */ rawLines(text, width, dim) { const lines = wrapTextWithAnsi2(text, width); return dim ? lines.map((l) => this.theme.fg("dim", l)) : lines; } /** Render `text` as Markdown, reusing this message's component instance. */ markdownLines(msg, text, width, dim) { let entry = this.markdownCache.get(msg); if (!entry) { entry = { md: new Markdown( text, 0, 0, this.markdownTheme, // Keeps result prose visually receded, the way the raw path's // per-line `fg("dim", …)` did. Fenced code is the exception and is // left alone deliberately: pi's theme highlights it with its own // colors, which this would otherwise flatten. dim ? { color: (t) => this.theme.fg("dim", t) } : void 0, MARKDOWN_OPTIONS ), text }; this.markdownCache.set(msg, entry); } else if (entry.text !== text) { const shouldRetry = !text.startsWith(entry.text); entry.md.setText(text); entry.text = text; if (shouldRetry) entry.failed = false; } if (entry.failed) return this.rawLines(text, width, dim); try { return entry.md.render(width); } catch { entry.failed = true; return this.rawLines(text, width, dim); } } /** Steerable only when a steer handler exists and the agent is still active. */ canSteer() { return !!this.onSteer && (this.record.status === "running" || this.record.status === "queued"); } /** * Asked of the owner rather than derived from the record: only the caller * blocked on this run knows it can let go of it, and `blocking` alone also * matches spawns nobody can hand off (the agent generator). */ canSendToBackground() { return this.onBackground?.available() === true; } /** Open the inline steering composer and route subsequent input to it. */ openComposer() { const input = new Input(); input.focused = true; input.onSubmit = (value) => { const message = value.trim(); this.composer = void 0; if (message) this.onSteer?.(message); this.tui.requestRender(); }; input.onEscape = () => { this.composer = void 0; this.tui.requestRender(); }; this.composer = input; this.tui.requestRender(); } invalidate() { } dispose() { this.closed = true; this.scrollView.setScrollbar("hidden"); this.stopLiveTimer(); if (this.unsubscribe) { this.unsubscribe(); this.unsubscribe = void 0; } } // ---- Private ---- viewportHeight() { if (this.fullscreen) return Math.max(0, this.tui.terminal.rows - this.chromeLines()); const maxRows = Math.floor(this.tui.terminal.rows * VIEWPORT_HEIGHT_PCT / 100); return Math.max(MIN_VIEWPORT, maxRows - this.chromeLines()); } chromeLines() { return CHROME_LINES_BASE - (this.fullscreen ? 2 : 0) + (this.invocationLine() ? 1 : 0) + (this.composer ? 1 : 0); } invocationLine() { const { modelName, modelId, tags } = buildInvocationTags(this.record.invocation); const model = modelId ?? modelName; const flag = fallbackFlag(this.theme, this.record); const parts = [...model ? [model] : [], ...tags]; if (parts.length === 0 && !flag) return void 0; return `${this.theme.fg("dim", " \u21B3")} ${flag ? `${flag} ` : ""}${this.theme.fg("dim", parts.join(" \xB7 "))}`; } buildContentLines(width) { if (width <= 0) return []; const th = this.theme; const messages = this.session.messages; const lines = []; if (messages.length === 0) { lines.push(th.fg("dim", "(waiting for first message...)")); return lines; } const mode = this.markdownMode(); let needsSeparator = false; for (const msg of messages) { if (msg.role === "user") { const text = typeof msg.content === "string" ? msg.content : extractText(msg.content); if (!text.trim()) continue; if (needsSeparator) lines.push(th.fg("dim", "\u2500\u2500\u2500")); lines.push(th.fg("accent", "[User]")); for (const line of wrapTextWithAnsi2(text.trim(), width)) { lines.push(line); } } else if (msg.role === "assistant") { const textParts = []; const toolCalls = []; for (const c of msg.content) { if (c.type === "text" && c.text) textParts.push(c.text); else if (c.type === "toolCall") { toolCalls.push(c.name ?? c.toolName ?? "unknown"); } } if (needsSeparator) lines.push(th.fg("dim", "\u2500\u2500\u2500")); lines.push(th.bold("[Assistant]")); if (textParts.length > 0) { const text = textParts.join("\n").trim(); lines.push(...mode === "off" ? this.rawLines(text, width, false) : this.markdownLines(msg, text, width, false)); } for (const name of toolCalls) { lines.push(truncateToWidth3(th.fg("muted", ` [Tool: ${name}]`), width)); } } else if (msg.role === "toolResult") { const { text, elided } = capResult(extractText(msg.content).trim()); if (!text) continue; if (needsSeparator) lines.push(th.fg("dim", "\u2500\u2500\u2500")); lines.push(th.fg("dim", "[Result]")); lines.push(...mode === "all" ? this.markdownLines(msg, text, width, true) : this.rawLines(text, width, true)); if (elided) lines.push(truncateToWidth3(th.fg("dim", truncationNote(elided)), width)); } else if (msg.role === "bashExecution") { const bash = msg; if (needsSeparator) lines.push(th.fg("dim", "\u2500\u2500\u2500")); lines.push(truncateToWidth3(th.fg("muted", ` $ ${bash.command}`), width)); if (bash.output?.trim()) { const { text, elided } = capResult(bash.output.trim()); lines.push(...this.rawLines(text, width, true)); if (elided) lines.push(truncateToWidth3(th.fg("dim", truncationNote(elided)), width)); } } else { continue; } needsSeparator = true; } const streaming = this.session.state?.streamingMessage; if (streaming?.role === "assistant" && !messages.includes(streaming)) { const text = streaming.content.flatMap((c) => c.type === "text" && c.text ? [c.text] : []).join("\n").trim(); if (text) { if (needsSeparator) lines.push(th.fg("dim", "\u2500\u2500\u2500")); lines.push(th.bold("[Assistant]")); lines.push(...this.rawLines(text, width, false)); } } if (this.record.status === "running" && this.activity) { const act = describeActivity(this.activity.activeTools, this.activity.responseText, this.activity.modelCall, this.clock.now()); lines.push(""); lines.push(truncateToWidth3(th.fg("accent", "\u258D ") + th.fg("dim", act), width)); } return lines.map((l) => truncateToWidth3(l, width)); } }; export { abortable, BUILTIN_TOOL_NAMES, isDefaultsDisabled, setDefaultsDisabled, NO_FALLBACK, getFallbackSubagent, setFallbackSubagent, registerAgents, resolveSpawnType, resolveType, getAgentConfig, getAvailableTypes, getAllTypes, getConfig, hasAgentBadge, renderAgentName, errorMessage, resolveAgentDir, setPackageAgentsGate, setPackageWorkflowsGate, getPackageAgentsGate, getPackageWorkflowsGate, setProjectTrusted, isProjectTrusted, invalidatePackageCache, packageNameForPath, isPackageResourceExcluded, packageWorkflowDirs, packageWorkflowFiles, loadCustomAgents, parseAgentFrontmatter, inChildSessionContext, runInChildSessionContext, bindChildResourceLoader, realClock, isUnsafeName, isSymlink, safeReadFile, isolationParam, cwdParam, resolveCwdParam, resolveAgentInvocationConfig, tierDisclosure, parseTierBinding, setModelTiers, configuredTierNames, isTierDisclosure, setModelAliases, setAgentModels, setModelScopeProvider, readEnabledModels, resolveEnabledModels, isScopeModelsEnabled, setScopeModelsEnabled, mayPark, modelRef, checkAdmission, describeBlock, QUOTA_RESTART_GRACE_MS, PARKED_RESUME_DELAY_MS, modelRequest, selectModel, describeSelection, modelIdentityNote, modelSelectionNote, admitModelSelection, getOutputTranscriptDefault, setOutputTranscriptDefault, sessionTaskDir, createOutputFilePath, ensureOutputFile, appendModelFallbackEntry, appendModelTierEntry, writeInitialEntry, streamToOutputFile, getStatusNote, getForegroundOutcomeNote, resumeHint, partialOutputSuffix, getLifetimeTotal, getLifetimeCost, toReportedUsage, PendingUsagePool, getSessionContextPercent, setWorktreeIsolationEnabled, isWorktreeIsolationEnabled, getMaxSubagentDepth, setMaxSubagentDepth, answerPlanGateQueries, planningNow, planSteerBlocked, planSteerRefusal, PLAN_SCHEDULE_REFUSAL, PLAN_PARK_REFUSAL, createHomeResourceLoader, SUBAGENT_TOOL_NAMES, normalizeMaxTurns, getDefaultMaxTurns, setDefaultMaxTurns, resolveEffectiveMaxTurns, getRememberAgents, setRememberAgents, getGraceTurns, setGraceTurns, steerAgent, getAgentConversation, MENTION_TRIGGER, isReservedHandle, handleBase, resolveHandleToType, stripAgentPrefix, describeMention, agentMentionReminder, parseMention, DEFAULT_BUDGET_POLICY, getBudgetPolicy, setBudgetPolicy, markConsumed, describeEvicted, isTopLevelAgent, AgentManager, applyModelCallEvent, formatClock, describeModelCall, hasFallback, fallbackFlagText, fallbackFlag, boundedWrappedRows, withLeadingFlag, SPINNER, fgPreservingNestedStyles, formatCompactTokens, formatTokens, formatCost, formatTurns, formatMs, formatDuration, getDisplayName, getPromptModeLabel, buildInvocationTags, compactThinkingTag, describeActivity, AgentWidget, VIEWPORT_HEIGHT_PCT, getConversationOverlayOptions, RESULT_MAX_CHARS, ConversationViewer }; //# sourceMappingURL=chunk-MSGGFB5Q.ts.map