// @ts-nocheck var __defProp = Object.defineProperty; var __getOwnPropNames = Object.getOwnPropertyNames; var __esm = (fn, res, err) => function __init() { if (err) throw err[0]; try { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; } catch (e) { throw err = [e], e; } }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; // ../pi-core/src/duration.ts function formatDuration(ms) { if (!Number.isFinite(ms) || ms <= 0) return "0s"; if (ms < 1e3) return `${Math.floor(ms)}ms`; if (ms < 6e4) return `${(ms / 1e3).toFixed(1).replace(/\.0$/, "")}s`; const totalMinutes = Math.floor(ms / 6e4); if (ms < 36e5) { const seconds = Math.floor(ms / 1e3) % 60; return `${totalMinutes}m ${String(seconds).padStart(2, "0")}s`; } const hours = Math.floor(ms / 36e5); return `${hours}h ${String(totalMinutes % 60).padStart(2, "0")}m`; } var init_duration = __esm({ "../pi-core/src/duration.ts"() { "use strict"; } }); // ../pi-core/src/render-kit.ts function resolveFrames(name, fallback) { try { const frames = getRenderKit()?.icon?.(name); if (Array.isArray(frames) && frames.length > 0 && [...frames].every((frame) => typeof frame === "string")) return frames; } catch { } return fallback ?? nativeFrames[name]; } function resolveIcon(name, fallback) { try { const icon = getRenderKit()?.icon?.(name); if (typeof icon === "string") return icon; } catch { } return fallback ?? nativeIcons[name]; } function resolveStatusGlyph(status, fallback) { try { const glyph = getRenderKit()?.statusGlyph(unstyledTheme, status); if (typeof glyph === "string") return glyph; } catch { } return fallback ?? nativeStatusGlyphs[status]; } function resolveStaticRunningGlyph() { return resolveStatusGlyph("running"); } function getToolElapsedMs(options) { const context = options.context; const state = context?.state; if (options.elapsedMs !== void 0) { const elapsedMs2 = Number.isFinite(options.elapsedMs) ? Math.max(0, options.elapsedMs) : void 0; if (state && terminalFooterGlyphs[options.status] && elapsedMs2 !== void 0) { state.completedElapsedMs = elapsedMs2; } return elapsedMs2; } if (!state) return void 0; if (context.executionStarted && (options.status === "running" || options.status === "in_progress") && state.startedAt === void 0) { state.startedAt = Date.now(); } if (typeof state.completedElapsedMs === "number" && Number.isFinite(state.completedElapsedMs)) { return Math.max(0, state.completedElapsedMs); } if (typeof state.startedAt !== "number" || !Number.isFinite(state.startedAt)) { return void 0; } const elapsedMs = Math.max(0, Date.now() - state.startedAt); if (terminalFooterGlyphs[options.status]) state.completedElapsedMs = elapsedMs; return elapsedMs; } function renderToolFooter(kit, theme, options) { if (kit?.toolFooter) return kit.toolFooter(theme, options); const elapsedMs = getToolElapsedMs(options); const elapsed = elapsedMs === void 0 ? "" : formatDuration(Math.floor(elapsedMs / 1e3) * 1e3); const terminalGlyph = terminalFooterGlyphs[options.status]; const status = terminalGlyph ?? (options.status === "in_progress" ? "running" : options.status); const summary2 = typeof options.summary === "string" ? [options.summary] : options.summary ?? []; return [status, elapsed, ...terminalGlyph ? summary2 : []].filter(Boolean).join(" \xB7 "); } function registration() { try { const record = shared7[registryKey5]; if (record && typeof record.token === "symbol" && record.owner !== null && (typeof record.owner === "object" || typeof record.owner === "function")) return record; } catch { } return void 0; } function getRenderKit() { try { const kit = registration()?.kit; if (kit?.version === RENDER_KIT_VERSION && (!("resolveToolRenderers" in kit) || typeof kit.resolveToolRenderers === "function") && (!("toolFooter" in kit) || typeof kit.toolFooter === "function") && (!("icon" in kit) || typeof kit.icon === "function") && [ "card", "collapse", "cachedComponent", "indicator", "statusGlyph", "widgetHeading", "treeRow", "fg" ].every( (method) => typeof kit[method] === "function" )) return kit; } catch { } return void 0; } function detachRenderContext(context) { return context && typeof context === "object" ? { ...context, lastComponent: void 0 } : context; } function createKitRenderMemo() { let cached; return { render(width, build) { const kit = getRenderKit(); if (!cached || cached.width !== width || cached.kit !== kit) { cached = { width, kit, lines: build(kit) }; } return cached.lines; }, invalidate() { cached = void 0; } }; } var nativeIcons, nativeFrames, nativeStatusGlyphs, unstyledTheme, terminalFooterGlyphs, RENDER_KIT_VERSION, registryKey5, shared7; var init_render_kit = __esm({ "../pi-core/src/render-kit.ts"() { "use strict"; init_duration(); nativeIcons = { branch: "\u2442", folder: "dir", model: "\u25CF", effort: "\u25D0", context: "ctx", cost: "$", elapsed: "\u25F7", tokensIn: "\u2191", tokensOut: "\u2193", cache: "cache", throughput: "tok/s", agent: "\u{F08C7}", tool: "*", bash: "$", read: "read", write: "write", edit: "edit", search: "search", file: "file", separator: "\xB7", ellipsis: "\u2026", arrowUp: "\u2191", arrowDown: "\u2193", arrowLeft: "\u2190", arrowRight: "\u2192", selection: "\u203A", selectionSelected: "\u25CF", selectionUnselected: "\u25CB", taskInProgress: "\u25C7", separatorHeavy: "\u2503", boxTopLeft: "\u256D", boxTopRight: "\u256E", boxVertical: "\u2502", boxBottomLeft: "\u2570", boxBottomRight: "\u256F", boxHorizontal: "\u2500", boxTDown: "\u252C", boxTUp: "\u2534", boxTRight: "\u251C", boxTLeft: "\u2524", boxCross: "\u253C", close: "\u2715", scrollUp: "\u2191", scrollDown: "\u2193", ready: "\u25B2", warning: "\u26A0" }; nativeFrames = { spinnerFrames: Object.freeze([ "\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F" ]), workingFrames: Object.freeze(["\u25B3", "\u25ED", "\u25B2", "\u25EE"]) }; nativeStatusGlyphs = { pending: "\u25CB", queued: "\u25CB", in_progress: "\u25D0", running: "\u25D0", completed: "\u2713", failed: "\u2717", timedOut: "\u25F7", resolved: "\u21BB", expectedExit: "\u2713", cancelled: "\u25A0", interrupted: "\u25A0", stopping: "\u25A0", deleted: "\u2298", blocked: "\u2298", unknown: "?" }; unstyledTheme = { fg: (_role, text) => text, bold: (text) => text, strikethrough: (text) => text }; terminalFooterGlyphs = { completed: "\u2713", deleted: "\u2713", failed: "\u2717", timedOut: "\u25F7", resolved: "\u21BB", expectedExit: "\u2713", cancelled: "\u2717", interrupted: "\u2717", blocked: "\u2717" }; RENDER_KIT_VERSION = 1; registryKey5 = /* @__PURE__ */ Symbol.for( `thoth-agents.pi-core.render-kit.v${RENDER_KIT_VERSION}` ); shared7 = globalThis; } }); // ../pi-core/src/panel-frame.ts function panelFg(theme, role, text) { if (!theme) return text; return getRenderKit()?.fg(theme, role, text) ?? theme.fg(role, text); } function createPanelFrame(options) { const { text, theme } = options; const icon = (name) => resolveIcon(glyphs[name][0], glyphs[name][1]); const horizontal = (count) => icon("horizontal").repeat(Math.max(0, count)); const border = (parts, tone = options.borderTone ?? "border") => panelFg( theme, tone, parts.map( (part) => typeof part === "string" ? icon(part) : horizontal(part.horizontal) ).join("") ); const line = (...parts) => parts.map((part) => typeof part === "string" ? part : border(part)).join(""); return { border, line, /** Pre-styled columns, with shared rails and independently measured widths. */ cells(cells, padding = 1) { const space = " ".repeat(padding); return border(["vertical"]) + cells.map( (cell) => `${space}${text.pad(cell.text, cell.width)}${space}${border(["vertical"])}` ).join(""); }, /** Junctions between padded columns, or a full-width top/bottom rule. */ rule(widths, kind = "divider") { const ends = kind === "top" ? ["topLeft", "topRight", "tDown"] : kind === "bottom" ? ["bottomLeft", "bottomRight", "tUp"] : ["tRight", "tLeft", "cross"]; const parts = [ends[0]]; widths.forEach((width, index) => { if (index) parts.push(ends[2]); parts.push({ horizontal: width + 2 }); }); parts.push(ends[1]); return border(parts); }, /** Single-span title, with an optional leading stroke for native cards. */ titled(title, width, leading = 0) { const label = text.clip(` ${title} `, Math.max(0, width - 2 - leading)); return panelFg( theme, "accent", `${icon("topLeft")}${horizontal(leading)}${label}${horizontal(width - 2 - leading - text.measure(label))}${icon("topRight")}` ); } }; } function renderPanelCard(options) { const kit = getRenderKit(); const { title, body, width, theme, text } = options; const frame = createPanelFrame({ theme, text, borderTone: "accent" }); const rows = kit ? kit.card(theme, { title, body }, width) : [ frame.titled(title, width, 1), ...body(Math.max(1, width - 4)).map( (line) => frame.cells([{ text: line, width: Math.max(0, width - 4) }]) ), frame.border([ "bottomLeft", { horizontal: Math.max(0, width - 2) }, "bottomRight" ]) ]; return rows.slice(0, options.maxHeight ?? Infinity).map((line) => text.pad(line, width)); } var glyphs; var init_panel_frame = __esm({ "../pi-core/src/panel-frame.ts"() { "use strict"; init_render_kit(); glyphs = { topLeft: ["boxTopLeft", "\u256D"], topRight: ["boxTopRight", "\u256E"], bottomLeft: ["boxBottomLeft", "\u2570"], bottomRight: ["boxBottomRight", "\u256F"], horizontal: ["boxHorizontal", "\u2500"], vertical: ["boxVertical", "\u2502"], tDown: ["boxTDown", "\u252C"], tUp: ["boxTUp", "\u2534"], tRight: ["boxTRight", "\u251C"], tLeft: ["boxTLeft", "\u2524"], cross: ["boxCross", "\u253C"] }; } }); // ../pi-core/src/panel-primitives.ts var panel_primitives_exports = {}; __export(panel_primitives_exports, { padPanelText: () => padPanelText, panelFg: () => panelFg, panelHintRow: () => panelHintRow, panelViewport: () => panelViewport, panelVisibleWidth: () => panelVisibleWidth, renderPanelFrame: () => renderPanelFrame, renderPanelRow: () => renderPanelRow, truncatePanelText: () => truncatePanelText }); import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; function panelHintRow(text) { return { text, tone: "muted" }; } function truncatePanelText(text, width) { const cells = Math.max(0, Math.floor(width)); if (!cells) return ""; const normalized = text.replace(/\r?\n|\r/g, " ").replace(/\t/g, " "); return truncateToWidth(normalized, cells, resolveIcon("ellipsis", "\u2026")); } function padPanelText(text, width) { const clipped = truncatePanelText(text, width); return clipped + " ".repeat(Math.max(0, Math.floor(width) - visibleWidth(clipped))); } function renderPanelRow(row, width, theme) { const item = typeof row === "string" ? { text: row } : row; const text = truncatePanelText(item.text, width); const content = panelFg( theme, item.selected ? "accent" : item.tone ?? "text", text ); const padded = padPanelText(content, width); return item.selected ? theme?.bg?.("selectedBg", padded) ?? padded : padded; } function renderPanelFrame(options) { const width = Math.max(1, Math.floor(options.width)); const height = Math.max(1, Math.floor(options.maxHeight ?? Infinity)); if (height < 3) return [truncatePanelText(options.title, width)]; if (width < 4) { return [ options.title, ...options.rows.map((row) => typeof row === "string" ? row : row.text) ].slice(0, height).map((row) => truncatePanelText(row, width)); } const frame = createPanelFrame({ theme: options.theme, text: { clip: truncatePanelText, pad: padPanelText, measure: visibleWidth } }); const top = frame.titled(options.title, width); const bottom = frame.rule([width - 4], "bottom"); const body = options.rows.slice(0, height - 2).map( (row) => frame.cells([ { text: renderPanelRow(row, width - 4, options.theme), width: width - 4 } ]) ); return [top, ...body, bottom].map((row) => truncatePanelText(row, width)); } function panelViewport(count, cursor, budget, maxRows = Infinity) { const length = Math.max(0, Math.floor(count)); const available = Math.max(0, Math.min(length, Math.floor(budget))); if (!available) return { start: 0, end: 0 }; const cap = Math.max(0, Math.floor(maxRows)); if (!cap) return { start: 0, end: 0 }; const showRange = length > Math.min(available, cap) && available > 1; const size = Math.min(cap, available - Number(showRange)); const selected = Math.max(0, Math.min(Math.floor(cursor), length - 1)); const start = Math.max( 0, Math.min(selected - Math.floor(size / 2), length - size) ); const end = start + size; return { start, end, ...showRange ? { notice: `Showing ${start + 1}\u2013${end} of ${length}` } : {} }; } var panelVisibleWidth; var init_panel_primitives = __esm({ "../pi-core/src/panel-primitives.ts"() { "use strict"; init_panel_frame(); init_render_kit(); init_panel_frame(); panelVisibleWidth = visibleWidth; } }); // ../pi-core/src/animation-clock.ts var registryKey = /* @__PURE__ */ Symbol.for("thoth.pi-core.animation-clock.v3"); var shared = globalThis; var localClock = createClock(); function createClock() { return { version: 3, level: "full", tick: 0, listeners: /* @__PURE__ */ new Set(), levelListeners: /* @__PURE__ */ new Set(), timer: void 0 }; } function isAnimationLevel(level) { return level === "full" || level === "reduced" || level === "minimal" || level === "off"; } function animationClock() { try { if (shared[registryKey] === void 0) shared[registryKey] = createClock(); const clock = shared[registryKey]; if (clock?.version === 3 && isAnimationLevel(clock.level) && Number.isSafeInteger(clock.tick) && clock.tick >= 0 && [clock.listeners, clock.levelListeners].every( (listeners) => listeners instanceof Set && [...listeners].every((listener) => typeof listener === "function") ) && ["timer", "level", "tick"].every( (field2) => Object.getOwnPropertyDescriptor(clock, field2)?.writable === true ) && (clock.timer === void 0 || typeof clock.timer === "object" && clock.timer !== null && typeof clock.timer.unref === "function" && typeof clock.timer.hasRef === "function")) return clock; } catch { } return localClock; } function isAnimationEffectEnabled(kind, level = getAnimationLevel()) { switch (level) { case "full": return true; case "reduced": return kind !== "ambient"; case "minimal": return kind === "primary"; case "off": return false; } } function getAnimationPeriodMs(level = getAnimationLevel()) { return level === "off" ? void 0 : 100; } function scheduleTick(clock) { const period = getAnimationPeriodMs(clock.level); if (clock.timer !== void 0 || !clock.listeners.size || period === void 0) return; const delay = Math.min(period, period - Date.now() % period + 1); clock.timer = setTimeout(() => { clock.timer = void 0; const now = Date.now(); const tick = ++clock.tick; scheduleTick(clock); for (const listener of [...clock.listeners]) { if (!clock.listeners.has(listener)) continue; try { listener(now, tick); } catch { } } }, delay); clock.timer.unref?.(); } function getAnimationLevel() { return animationClock().level; } function subscribeAnimationLevel(listener) { const clock = animationClock(); const subscription = (level) => listener(level); clock.levelListeners.add(subscription); return () => { clock.levelListeners.delete(subscription); }; } function subscribeAnimationClock(listener) { const clock = animationClock(); const subscription = (now, tick) => listener(now, tick); clock.listeners.add(subscription); scheduleTick(clock); return () => { clock.listeners.delete(subscription); if (!clock.listeners.size) { clearTimeout(clock.timer); clock.timer = void 0; } }; } // ../pi-core/src/animation-steps.ts function subscribeAnimationSteps({ kind, intendedMs, onStep }) { let frame = 0; let removeClock; let refreshTimer; function stop() { removeClock?.(); removeClock = void 0; clearInterval(refreshTimer); refreshTimer = void 0; } function schedule() { stop(); if (!isAnimationEffectEnabled(kind)) { refreshTimer = setInterval(() => { onStep({ frame: void 0, static: true, now: Date.now() }); }, 1e3); refreshTimer.unref?.(); return; } const ticksPerStep = Math.max(1, Math.round(intendedMs / 100)); let ticks = 0; removeClock = subscribeAnimationClock((now) => { if (++ticks < ticksPerStep) return; ticks = 0; onStep({ frame: frame++, static: false, now }); }); } const removeLevel = subscribeAnimationLevel(schedule); schedule(); return () => { removeLevel(); stop(); }; } // ../pi-core/src/validation.ts function isRecord(value3) { return typeof value3 === "object" && value3 !== null && !Array.isArray(value3); } function isNonEmptyString(value3) { return typeof value3 === "string" && value3.length > 0; } function isNonNegativeInteger(value3) { return typeof value3 === "number" && Number.isSafeInteger(value3) && value3 >= 0; } // ../pi-core/src/channels.ts function defineChannel(definition) { return definition; } function publish(events, channel, snapshot2) { events.emit(channel.name, { v: channel.version, source: snapshot2.source, sessionId: snapshot2.sessionId, at: Date.now(), data: snapshot2.data }); } function onRequest(events, requestChannel, options) { return subscribe(events, requestChannel, { sessionId: options.sessionId, onSnapshot: options.onRequest }); } function subscribe(events, channel, options) { return events.on(channel.name, (value3) => { if (!isEnvelope(value3, channel, options.sessionId)) return; options.onSnapshot(value3); }); } function isEnvelope(value3, channel, sessionId) { try { return isRecord(value3) && value3.v === channel.version && isNonEmptyString(value3.source) && isNonEmptyString(value3.sessionId) && (sessionId === void 0 || value3.sessionId === sessionId) && typeof value3.at === "number" && Number.isFinite(value3.at) && value3.at >= 0 && channel.validate(value3.data); } catch { return false; } } // ../pi-core/src/background.ts var backgroundStatuses = [ "running", "succeeded", "failed", "cancelled", "timed_out" ]; var BACKGROUND_PROGRESS_MAX_LENGTH = 200; function isBackgroundSnapshot(value3) { try { if (!isExactRecord(value3, ["tasks", "counts"]) || !Array.isArray(value3.tasks)) return false; for (const task of value3.tasks) { if (!isBackgroundTask(task)) return false; } const { counts } = value3; return isExactRecord(counts, backgroundStatuses) && backgroundStatuses.every((status) => isNonNegativeInteger(counts[status])); } catch { return false; } } function isExactRecord(value3, allowedKeys) { if (!isRecord(value3)) return false; const prototype = Object.getPrototypeOf(value3); return (prototype === Object.prototype || prototype === null) && Reflect.ownKeys(value3).every( (key3) => typeof key3 === "string" && allowedKeys.includes(key3) ); } function isOptionalTimestamp(value3) { return value3 === void 0 || isNonNegativeInteger(value3); } function isProgress(value3) { return typeof value3 === "number" && Number.isFinite(value3) || typeof value3 === "string" && value3.length <= BACKGROUND_PROGRESS_MAX_LENGTH; } function isBackgroundTask(value3) { return isExactRecord(value3, [ "id", "name", "kind", "status", "createdAt", "startedAt", "endedAt", "deadlineAt", "lastCheckedAt", "lastProgressAt", "stopRequestedAt", "dismissedAt", "exitCode", "signal", "progress", "dismissed" ]) && isNonEmptyString(value3.id) && (value3.name === void 0 || typeof value3.name === "string") && (value3.kind === "process" || value3.kind === "command_watch") && backgroundStatuses.some((status) => status === value3.status) && isNonNegativeInteger(value3.createdAt) && isNonNegativeInteger(value3.startedAt) && isOptionalTimestamp(value3.endedAt) && isOptionalTimestamp(value3.deadlineAt) && isOptionalTimestamp(value3.lastCheckedAt) && isOptionalTimestamp(value3.lastProgressAt) && isOptionalTimestamp(value3.stopRequestedAt) && isOptionalTimestamp(value3.dismissedAt) && (value3.exitCode === void 0 || value3.exitCode === null || typeof value3.exitCode === "number" && Number.isSafeInteger(value3.exitCode)) && (value3.signal === void 0 || value3.signal === null || isNonEmptyString(value3.signal)) && (value3.progress === void 0 || isProgress(value3.progress)) && (value3.dismissed === void 0 || typeof value3.dismissed === "boolean"); } var BACKGROUND_STATE_CHANNEL = defineChannel({ name: "thoth:background:state", version: 1, validate: isBackgroundSnapshot }); function isBackgroundStateRequest(value3) { try { return isExactRecord(value3, []); } catch { return false; } } var BACKGROUND_STATE_REQUEST = defineChannel({ name: "thoth:background:state:request", version: 1, validate: isBackgroundStateRequest }); // ../pi-core/src/owned-overlay.ts var handlesKey = /* @__PURE__ */ Symbol.for("thoth.pi-core.owned-overlay-handles"); var sessionsKey = /* @__PURE__ */ Symbol.for("thoth.pi-core.owned-overlay-sessions"); var shared2 = globalThis; function ownedSessions() { try { shared2[sessionsKey] ??= { version: 1, sessions: /* @__PURE__ */ new WeakMap() }; const value3 = shared2[sessionsKey]; if (value3?.version === 1 && value3.sessions instanceof WeakMap) return value3.sessions; } catch { } return void 0; } function settleOwnedOverlays(ctx) { const sessions = ownedSessions(); const ui = ctx.ui; const pending = sessions?.get(ui); sessions?.delete(ui); for (const cancel of pending ?? []) cancel(); } function ownedHandles() { try { shared2[handlesKey] ??= { version: 1, tuis: /* @__PURE__ */ new WeakMap() }; const value3 = shared2[handlesKey]; if (value3?.version === 1 && value3.tuis instanceof WeakMap) return value3.tuis; } catch { } return void 0; } function isComponent(value3) { return typeof value3 === "object" && value3 !== null && "render" in value3 && typeof value3.render === "function" && "invalidate" in value3 && typeof value3.invalidate === "function"; } function readTuiFocus(tui) { try { const runtime = tui; const value3 = runtime.getFocusedComponent ? runtime.getFocusedComponent() : runtime.focusedComponent; const focused = isComponent(value3) ? value3 : void 0; const stack = runtime.overlayStack; if (!Array.isArray(stack) || !stack.every( (entry) => typeof entry === "object" && entry !== null && isComponent(entry.component) && (entry.preFocus === null || isComponent(entry.preFocus)) )) return { focused }; return { focused, overlays: stack }; } catch { return {}; } } function children(component) { const value3 = component.children; return Array.isArray(value3) ? value3 : []; } function parentOf(root, target) { for (const child of children(root)) { if (child === target) return root; const parent = parentOf(child, target); if (parent) return parent; } return void 0; } var EDITOR_SLOT = /* @__PURE__ */ Symbol.for("thoth.pi-core.owned-overlay.v1"); function editorSlotAtOpen(tui) { const { focused, overlays } = readTuiFocus(tui); const visited = /* @__PURE__ */ new Set(); let current = focused ?? null; while (current && !visited.has(current)) { visited.add(current); const parent = parentOf(tui, current); if (parent) return parent; const overlay = overlays?.find(({ component }) => component === current); if (!overlay) return void 0; try { const metadata = current[EDITOR_SLOT]; if (typeof metadata === "object" && metadata !== null && "version" in metadata && metadata.version === 1 && "tui" in metadata && metadata.tui === tui && "editorSlot" in metadata && isComponent(metadata.editorSlot) && parentOf(tui, metadata.editorSlot)) return metadata.editorSlot; } catch { return void 0; } current = overlay.preFocus; } return void 0; } function retainEditorSlot(component, tui, editorSlot) { if (!editorSlot) return; try { Object.defineProperty(component, EDITOR_SLOT, { configurable: true, value: { version: 1, tui, editorSlot } }); } catch { } } function visible(tui, entry) { const runtime = tui; return runtime.isOverlayVisible?.(entry) ?? entry.hidden !== true; } function acquireEditorSlotFocus(tui, target) { const handles = ownedHandles()?.get(tui); const { focused, overlays } = readTuiFocus(tui); const displaced = overlays?.find( (entry) => visible(tui, entry) && (entry.component === focused || focused && parentOf(entry.component, focused)) ); const handle = displaced && handles?.get(displaced.component); for (const entry of (overlays ?? []).slice().reverse()) { if (visible(tui, entry)) handles?.get(entry.component)?.unfocus({ target }); } tui.setFocus?.(target); if (!displaced || !handle) return void 0; return () => { const current = readTuiFocus(tui); if (current.focused === target && ownedHandles()?.get(tui)?.get(displaced.component) === handle && current.overlays?.includes(displaced) && visible(tui, displaced) && !handle.isHidden()) handle.focus(); }; } function focusedForeignOverlay(tui) { const { focused, overlays } = readTuiFocus(tui); return focused && overlays?.some( (entry) => visible(tui, entry) && (entry.component === focused || parentOf(entry.component, focused)) ) ? focused : void 0; } function overlayFocusRestorer(tui) { const focused = focusedForeignOverlay(tui); return () => { if (focused && readTuiFocus(tui).overlays?.some( (entry) => visible(tui, entry) && (entry.component === focused || parentOf(entry.component, focused)) )) tui.setFocus(focused); }; } function preservingOverlayFocus(tui, action) { const restore = overlayFocusRestorer(tui); try { action(); } finally { restore(); } } function repairFocus(tui, editorSlot) { const { focused, overlays } = readTuiFocus(tui); if (!focused || !overlays || !editorSlot || focused === tui || parentOf(tui, focused) || overlays.some( ({ component }) => component === focused || parentOf(component, focused) )) return; const target = editorSlotFocusTarget(tui); if (target) { acquireEditorSlotFocus(tui, target); return; } const candidates = children(editorSlot).filter( (component) => typeof component.handleInput === "function" ); if (candidates.length !== 1 || !parentOf(tui, editorSlot)) return; tui.setFocus(candidates[0]); } function openOwnedOverlay(ctx, factory, options) { const ui = ctx.ui; let handle; let closed = false; let hidden = false; let liveTui; let liveComponent; let hideOwned = () => { }; let cancelOwned = () => { }; let untrack = () => { }; const result = ui.custom( (tui, theme, keybindings, done) => { liveTui = tui; const editorSlot = editorSlotAtOpen(tui); hideOwned = () => { if (!handle || hidden) return; hidden = true; if (liveComponent) ownedHandles()?.get(tui)?.delete(liveComponent); try { handle.hide(); } finally { repairFocus(tui, editorSlot); } }; const close = (result2) => { if (closed) return; closed = true; untrack(); const originalHide = tui.hideOverlay; tui.hideOverlay = hideOwned; try { done(result2); } finally { tui.hideOverlay = originalHide; hideOwned(); } }; cancelOwned = () => close(void 0); const sessions = ownedSessions(); if (sessions) { const pending = sessions.get(ui) ?? /* @__PURE__ */ new Set(); sessions.set(ui, pending); pending.add(cancelOwned); untrack = () => { pending.delete(cancelOwned); if (!pending.size && sessions.get(ui) === pending) sessions.delete(ui); }; } const created = factory(tui, theme, keybindings, close); const retain = (component) => { liveComponent = component; retainEditorSlot(component, tui, editorSlot); return component; }; return isComponent(created) ? retain(created) : created.then(retain); }, { ...options, overlay: true, onHandle(ownedHandle) { handle = ownedHandle; const hide = ownedHandle.hide.bind(ownedHandle); ownedHandle.hide = () => { if (closed) hide(); else cancelOwned(); }; if (liveTui && liveComponent) { const registry5 = ownedHandles(); if (registry5) { let handles = registry5.get(liveTui); if (!handles) { handles = /* @__PURE__ */ new Map(); registry5.set(liveTui, handles); } handles.set(liveComponent, ownedHandle); } } if (closed) hideOwned(); options?.onHandle?.(handle); } } ); void result.then( () => untrack(), () => untrack() ); return result; } // ../pi-core/src/editor-slot.ts var registryKey2 = /* @__PURE__ */ Symbol.for("thoth.pi-core.editor-slot"); var shared3 = globalThis; function registry(initialize = true) { try { if (initialize) { shared3[registryKey2] ??= { version: 1, sessions: /* @__PURE__ */ new WeakMap(), tuis: /* @__PURE__ */ new WeakMap() }; } const value3 = shared3[registryKey2]; if (value3?.version === 1 && value3.sessions instanceof WeakMap && value3.tuis instanceof WeakMap) { if (initialize && !("isEditorReplaced" in value3) && Object.isExtensible(value3)) { value3.isEditorReplaced = function(tui) { return this.tuis.get(tui)?.isEditorReplaced?.() === true; }; } return value3; } } catch { } return void 0; } function isEditorReplaced(tui) { try { return registry(false)?.isEditorReplaced?.(tui) === true; } catch { return false; } } function editorSlotFocusTarget(tui) { return registry()?.tuis.get(tui)?.focusTarget(); } function registerEditorSlot(ctx, contribution, defaultFactory) { const state = registry(); if (!state) return void 0; const session = ctx.sessionManager ?? ctx.ui; const existing = state.sessions.get(session); if (existing) return existing.register(contribution); const ui = ctx.ui; if (typeof ui.getEditorComponent !== "function" || typeof ui.setEditorComponent !== "function" || typeof ui.onTerminalInput !== "function" || typeof ui.setWidget !== "function") return void 0; const previousFactory = ui.getEditorComponent(); const baseFactory = previousFactory ?? defaultFactory; if (!baseFactory) return void 0; const contributions = /* @__PURE__ */ new Map(); let runtime; let invocations = 0; let restoreOverlayFocus = () => { }; const replacement = () => { for (const entry of [...contributions.values()].reverse()) { const component = entry.replacement?.(); if (component) return component; } return void 0; }; const factory = (liveTui, theme, keys) => { invocations++; if (runtime) return runtime.mounted; restoreOverlayFocus = overlayFocusRestorer(liveTui); const retained = baseFactory(liveTui, theme, keys); const mounted2 = new Proxy(retained, { get(target, property) { if (property === "render") return (width) => (replacement() ?? target).render(width); if (property === "handleInput") return (data) => (replacement() ?? target).handleInput?.(data); if (property === "invalidate") return () => { target.invalidate(); replacement()?.invalidate(); }; const value3 = Reflect.get(target, property, target); return typeof value3 === "function" && !(typeof property === "string" && property.startsWith("on")) ? value3.bind(target) : value3; }, set(target, property, value3) { return Reflect.set(target, property, value3, target); } }); runtime = { tui: liveTui, keybindings: keys, mounted: mounted2 }; return mounted2; }; ui.setEditorComponent(factory); restoreOverlayFocus(); if (!runtime) { if (ui.getEditorComponent() === factory) ui.setEditorComponent(previousFactory); return void 0; } const { tui, keybindings, mounted } = runtime; const active = () => ui.getEditorComponent() === factory && invocations === 1; const owner = { supportsDecorativeOverlays: true, focusTarget: () => active() ? mounted : void 0, isEditorReplaced: () => active() && replacement() !== void 0, register(entry) { if (contributions.has(entry.key)) throw new Error( `Editor slot contribution already registered: ${entry.key}` ); contributions.set(entry.key, entry); let disposed = false; let restoreFocus; const releaseDisplacedFocus = () => { restoreFocus?.(); restoreFocus = void 0; }; const handle = { tui, keybindings, refresh: () => tui.requestRender(), acquireFocus: () => { if (!disposed && active()) restoreFocus = acquireEditorSlotFocus(tui, mounted) ?? restoreFocus; }, releaseFocus: () => { releaseDisplacedFocus(); if (!disposed && active() && !focusedForeignOverlay(tui)) acquireEditorSlotFocus(tui, mounted); }, isRootEditorInputActive: () => active() && !replacement() && tui.getFocusedComponent?.() === mounted && !hasBlockingOverlay(tui), dispose() { if (disposed) return; disposed = true; releaseDisplacedFocus(); contributions.delete(entry.key); try { if (entry.aboveEditor) ui.setWidget(entry.key, void 0); } finally { if (contributions.size) tui.requestRender(); else { removeInput(); state.sessions.delete(session); state.tuis.delete(tui); if (ui.getEditorComponent() === factory) preservingOverlayFocus( tui, () => ui.setEditorComponent(previousFactory) ); } } } }; try { if (entry.aboveEditor) ui.setWidget(entry.key, entry.aboveEditor, { placement: "aboveEditor" }); return handle; } catch (error) { handle.dispose(); throw error; } } }; state.sessions.set(session, owner); state.tuis.set(tui, owner); const removeInput = ui.onTerminalInput((data) => { for (const entry of [...contributions.values()].reverse()) { const result = entry.handleInput?.(data); if (result?.consume || result?.data !== void 0) return result; } return void 0; }); return owner.register(contribution); } // ../pi-core/src/work-panel-state.ts var WORK_PANEL_VERSION = 2; var registryKey3 = /* @__PURE__ */ Symbol.for("thoth.pi-core.work-panel"); var shared4 = globalThis; function workPanelRegistry(create = true) { try { if (create && shared4[registryKey3] === void 0) { shared4[registryKey3] = { version: WORK_PANEL_VERSION, providers: /* @__PURE__ */ new Map(), hosts: /* @__PURE__ */ new Map(), revisions: /* @__PURE__ */ new Map(), listeners: /* @__PURE__ */ new Set(), lifecycle: { sessions: /* @__PURE__ */ new WeakMap(), listeners: /* @__PURE__ */ new WeakMap() } }; } const state = shared4[registryKey3]; if (state?.version === WORK_PANEL_VERSION && state.providers instanceof Map && state.hosts instanceof Map && state.revisions instanceof Map && state.listeners instanceof Set && state.lifecycle?.sessions instanceof WeakMap && state.lifecycle.listeners instanceof WeakMap) return state; } catch { } return void 0; } // ../pi-core/src/decorative-overlay.ts var key = /* @__PURE__ */ Symbol.for("thoth.pi-core.decorative-overlays.v1"); var shared5 = globalThis; function decorations(tui) { shared5[key] ??= /* @__PURE__ */ new WeakMap(); const registry5 = shared5[key]; let state = registry5.get(tui); if (!state) { state = { components: /* @__PURE__ */ new WeakSet(), owners: /* @__PURE__ */ new WeakMap() }; registry5.set(tui, state); } return state; } function overlayEntries(tui) { const stack = tui.overlayStack; if (!Array.isArray(stack)) return void 0; if (!stack.every( (entry) => entry && typeof entry === "object" && entry.component && typeof entry.component.render === "function" && typeof entry.component.invalidate === "function" && typeof entry.hidden === "boolean" && (entry.options === void 0 || entry.options && typeof entry.options === "object" && (entry.options.visible === void 0 || typeof entry.options.visible === "function")) )) return void 0; return stack; } function hasBlockingOverlay(tui) { try { const stack = overlayEntries(tui); if (stack) return stack.some( (entry) => !entry.hidden && (!entry.options?.visible || entry.options.visible(tui.terminal.columns, tui.terminal.rows)) && !decorations(tui).components.has(entry.component) ); } catch { } try { return tui.hasOverlay?.() !== false; } catch { return true; } } // ../pi-core/src/index.ts init_duration(); // ../pi-core/src/provider-limits.ts var registryKey4 = /* @__PURE__ */ Symbol.for("thoth.pi-core.provider-limits.v1"); var shared6 = globalThis; function registry2() { try { if (shared6[registryKey4] === void 0) { shared6[registryKey4] = { version: 1, entries: /* @__PURE__ */ new Map(), listeners: /* @__PURE__ */ new Set() }; } const state = shared6[registryKey4]; if (state?.version !== 1 || !(state.entries instanceof Map) || !(state.listeners instanceof Set)) return void 0; for (const [key3, value3] of state.entries) { const entry = parseEntry(value3); if (!entry || key3 !== entryKey(entry)) return void 0; } for (const listener of state.listeners) { if (typeof listener !== "function") return void 0; } return state; } catch { return void 0; } } function entryKey(entry) { return JSON.stringify([entry.provider, entry.window]); } var entryKeys = [ "provider", "window", "status", "utilization", "resetsAt", "observedAt", "windowType", "overageInUse", "overageEnabled", "isUsingOverage", "sessionId" ]; function parseEntry(value3) { if (!isRecord(value3)) return void 0; const prototype = Object.getPrototypeOf(value3); const keys = Reflect.ownKeys(value3); if (prototype !== Object.prototype && prototype !== null || !keys.every( (key3) => typeof key3 === "string" && entryKeys.some((allowed) => allowed === key3) )) return void 0; const entry = Object.fromEntries( keys.map((key3) => [key3, value3[key3]]) ); if (!isNonEmptyString(entry.provider) || !isNonEmptyString(entry.window) || !isNonEmptyString(entry.sessionId) || !["allowed", "allowed_warning", "rejected"].some( (status) => status === entry.status ) || !isNonNegativeInteger(entry.observedAt) || entry.resetsAt !== void 0 && !isNonNegativeInteger(entry.resetsAt) || entry.utilization !== void 0 && !(typeof entry.utilization === "number" && Number.isFinite(entry.utilization) && entry.utilization >= 0 && entry.utilization <= 1) || entry.windowType !== void 0 && !isNonEmptyString(entry.windowType) || !["overageInUse", "overageEnabled", "isUsingOverage"].every( (key3) => entry[key3] === void 0 || typeof entry[key3] === "boolean" )) return void 0; return Object.freeze(entry); } function subscribeProviderLimits(listener) { try { const state = registry2(); if (!state || typeof listener !== "function") return () => { }; const subscription = (entry) => listener(entry); state.listeners.add(subscription); return () => { try { state.listeners.delete(subscription); } catch { } }; } catch { return () => { }; } } // ../pi-core/src/index.ts init_render_kit(); // ../pi-core/src/session-liveness.ts var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@agegr/pi-web/session-liveness/v1"); var noop = () => { }; var nonblank = (value3) => typeof value3 === "string" && value3.trim().length > 0; function getOrInstallSessionLivenessRegistry() { const shared13 = globalThis; const existing = shared13[REGISTRY_KEY]; if (existing !== void 0) { const registry6 = existing; return registry6 && typeof registry6 === "object" && registry6.version === 1 && typeof registry6.register === "function" && typeof registry6.hasActiveProvider === "function" ? registry6 : void 0; } const providers = /* @__PURE__ */ new Map(); const registry5 = { version: 1, register(provider) { if (!provider || typeof provider !== "object" || !nonblank(provider.name) || !nonblank(provider.sessionId) || provider.sessionFile !== void 0 && !nonblank(provider.sessionFile) || typeof provider.isActive !== "function") throw new Error("Session liveness provider is invalid"); const key3 = Symbol(String(provider.name)); providers.set(key3, provider); let released = false; return () => { if (released) return; released = true; providers.delete(key3); }; }, hasActiveProvider(session) { const identifiers = new Set( [session.sessionId, session.sessionFile].filter(Boolean) ); for (const provider of providers.values()) { if (!identifiers.has(provider.sessionId) && !(provider.sessionFile && identifiers.has(provider.sessionFile))) continue; try { if (provider.isActive() !== false) return true; } catch { return true; } } return false; } }; shared13[REGISTRY_KEY] = registry5; return registry5; } function registerSessionLivenessProvider(provider) { return getOrInstallSessionLivenessRegistry()?.register(provider) ?? noop; } // ../pi-core/src/subagents.ts var subagentStatuses = [ "queued", "running", "stopping", "completed", "failed", "cancelled", "interrupted" ]; var subagentEfforts = [ "off", "minimal", "low", "medium", "high", "xhigh", "max" ]; var SUBAGENT_PREVIEW_MAX_LENGTH = 800; function isSubagentsSnapshot(value3) { try { if (!isExactRecord2(value3, ["tasks", "history", "counts", "totals"]) || !Array.isArray(value3.tasks) || !Array.isArray(value3.history) || value3.history.length > 100) return false; for (const tasks of [value3.tasks, value3.history]) { for (const task of tasks) { if (!isSubagentTask(task)) return false; } } const { counts, totals } = value3; return isCounts(counts) && isExactRecord2(totals, [...subagentStatuses, "total"]) && isNonNegativeInteger(totals.total) && subagentStatuses.every((status) => isNonNegativeInteger(totals[status])); } catch { return false; } } function isExactRecord2(value3, allowedKeys) { if (!isRecord(value3)) return false; const prototype = Object.getPrototypeOf(value3); return (prototype === Object.prototype || prototype === null) && Reflect.ownKeys(value3).every( (key3) => typeof key3 === "string" && allowedKeys.includes(key3) ); } function isCounts(value3) { return isExactRecord2(value3, subagentStatuses) && subagentStatuses.every((status) => isNonNegativeInteger(value3[status])); } function isOptionalString(value3) { return value3 === void 0 || typeof value3 === "string"; } function isOptionalTimestamp2(value3) { return value3 === void 0 || isNonNegativeInteger(value3); } function isNonNegativeNumber(value3) { return typeof value3 === "number" && Number.isFinite(value3) && value3 >= 0; } function isTaskUsage(value3) { return isExactRecord2(value3, ["input", "output", "cost"]) && (value3.input === void 0 || isNonNegativeInteger(value3.input)) && (value3.output === void 0 || isNonNegativeInteger(value3.output)) && (value3.cost === void 0 || isNonNegativeNumber(value3.cost)); } function isSubagentTask(value3) { return isExactRecord2(value3, [ "id", "agent", "displayName", "mode", "status", "model", "effort", "createdAt", "startedAt", "endedAt", "lastActivityAt", "usage", "preview" ]) && isNonEmptyString(value3.id) && isNonEmptyString(value3.agent) && isOptionalString(value3.displayName) && (value3.mode === "task" || value3.mode === "background") && subagentStatuses.some((status) => status === value3.status) && isOptionalString(value3.model) && (value3.effort === void 0 || subagentEfforts.some((effort) => effort === value3.effort)) && isNonNegativeInteger(value3.createdAt) && isOptionalTimestamp2(value3.startedAt) && isOptionalTimestamp2(value3.endedAt) && isOptionalTimestamp2(value3.lastActivityAt) && (value3.usage === void 0 || isTaskUsage(value3.usage)) && (value3.preview === void 0 || typeof value3.preview === "string" && value3.preview.length <= SUBAGENT_PREVIEW_MAX_LENGTH); } var SUBAGENTS_STATE_CHANNEL = defineChannel({ name: "thoth:subagents:state", version: 2, validate: isSubagentsSnapshot }); function isSubagentsStateRequest(value3) { try { return isExactRecord2(value3, []); } catch { return false; } } function isSubagentsUsageRequest(value3) { return isSubagentsStateRequest(value3); } var SUBAGENTS_STATE_REQUEST = defineChannel({ name: "thoth:subagents:state:request", version: 1, validate: isSubagentsStateRequest }); function isSubagentsUsageSnapshot(value3) { try { return isExactRecord2(value3, ["totalCost", "runCount"]) && isNonNegativeNumber(value3.totalCost) && isNonNegativeInteger(value3.runCount); } catch { return false; } } var SUBAGENTS_USAGE_CHANNEL = defineChannel({ name: "thoth:subagents:usage", version: 1, validate: isSubagentsUsageSnapshot }); var SUBAGENTS_USAGE_REQUEST = defineChannel({ name: "thoth:subagents:usage:request", version: 1, validate: isSubagentsUsageRequest }); // ../pi-core/src/todo.ts var todoStatuses = [ "pending", "in_progress", "completed", "deleted" ]; function isTodoSnapshot(value3) { try { if (!isRecord(value3)) return false; const { tasks, nextId, counts } = value3; if (!Array.isArray(tasks) || !isTaskId(nextId) || !isRecord(counts)) return false; for (const task of tasks) { if (!isTodoTask(task)) return false; } return todoStatuses.every((status) => isNonNegativeInteger(counts[status])); } catch { return false; } } function isTaskId(value3) { return isNonNegativeInteger(value3) && value3 > 0; } function isOptionalString2(value3) { return value3 === void 0 || typeof value3 === "string"; } function isTodoTask(value3) { if (!isRecord(value3) || !isTaskId(value3.id) || typeof value3.subject !== "string" || !todoStatuses.some((status) => status === value3.status) || !Array.isArray(value3.blockedBy) || !isOptionalString2(value3.description) || !isOptionalString2(value3.activeForm) || !isOptionalString2(value3.owner)) return false; for (const id of value3.blockedBy) { if (!isTaskId(id)) return false; } return true; } var TODO_STATE_CHANNEL = defineChannel({ name: "thoth:todo:state", version: 1, validate: isTodoSnapshot }); function isTodoStateRequest(value3) { try { if (!isRecord(value3)) return false; const prototype = Object.getPrototypeOf(value3); return (prototype === Object.prototype || prototype === null) && Reflect.ownKeys(value3).length === 0; } catch { return false; } } var TODO_STATE_REQUEST = defineChannel({ name: "thoth:todo:state:request", version: 1, validate: isTodoStateRequest }); // ../pi-core/src/tool-registry.ts var TOOL_DEFINITION_REGISTRY_VERSION = 1; var registryKey6 = /* @__PURE__ */ Symbol.for( `thoth-agents.pi-core.tool-definitions.v${TOOL_DEFINITION_REGISTRY_VERSION}` ); var shared8 = globalThis; function isPublication(publication, name) { const definition = publication?.definition; return typeof publication?.token === "symbol" && definition?.name === name && (definition.renderCall === void 0 || typeof definition.renderCall === "function") && (definition.renderResult === void 0 || typeof definition.renderResult === "function") && (definition.renderShell === void 0 || definition.renderShell === "default" || definition.renderShell === "self"); } function registry3() { try { if (shared8[registryKey6] === void 0) shared8[registryKey6] = { entries: /* @__PURE__ */ new Map(), version: 0 }; const state = shared8[registryKey6]; if (!state || !(state.entries instanceof Map) || !Number.isSafeInteger(state.version) || state.version < 0) return void 0; for (const [name, publications] of state.entries) { if (typeof name !== "string" || !Array.isArray(publications) || !publications.every((publication) => isPublication(publication, name))) return void 0; } return state; } catch { return void 0; } } function publishToolDefinitions(definitions) { const state = registry3(); if (!state) return { publish() { }, withdraw() { } }; const entries = state.entries; const token = /* @__PURE__ */ Symbol("tool-definition-publication"); const names = /* @__PURE__ */ new Set(); let live = true; const handle = { publish(more) { if (!live || !more.length) return; for (const definition of more) { names.add(definition.name); const publications = (entries.get(definition.name) ?? []).filter( (publication) => publication.token !== token ); publications.push({ token, definition }); entries.set(definition.name, publications); } state.version++; }, withdraw() { if (!live) return; live = false; for (const name of names) { const remaining = (entries.get(name) ?? []).filter( (publication) => publication.token !== token ); if (remaining.length) entries.set(name, remaining); else entries.delete(name); } if (names.size) state.version++; names.clear(); } }; handle.publish(definitions); return handle; } function getPublishedToolDefinition(name) { return registry3()?.entries.get(name)?.at(-1)?.definition; } function getToolDefinitionRegistryVersion() { return registry3()?.version ?? 0; } // ../pi-core/src/ui-preferences.ts var key2 = /* @__PURE__ */ Symbol.for("thoth.pi-core.ui-preferences.v1"); var shared9 = globalThis; function registry4() { shared9[key2] ??= { owners: /* @__PURE__ */ new Map(), listeners: /* @__PURE__ */ new Set() }; return shared9[key2]; } function getUIPreferences() { return { absorbedWorkPanelSources: [ ...new Set( [...registry4().owners.values()].flatMap((entry) => { try { return !entry.isActive || entry.isActive() ? entry.absorbedWorkPanelSources : []; } catch { return []; } }) ) ] }; } function subscribeUIPreferences(listener) { registry4().listeners.add(listener); return () => { registry4().listeners.delete(listener); }; } // ../pi-core/src/panel-key.ts var panelKeySequences = { up: ["\x1B[A", "\x1BOA"], down: ["\x1B[B", "\x1BOB"], right: ["\x1B[C", "\x1BOC"], left: ["\x1B[D", "\x1BOD"], home: ["\x1B[H", "\x1B[1~", "\x1BOH", "\x1B[7~"], end: ["\x1B[F", "\x1B[4~", "\x1BOF", "\x1B[8~"], pageUp: ["\x1B[5~"], pageDown: ["\x1B[6~"], enter: ["\r", "\n", "\x1BOM"], escape: ["\x1B", ""], backspace: ["\x7F", "\b"], space: [" "], "ctrl+u": [""] }; function matchesPanelKey(data, key3, nativeMatcher) { return nativeMatcher?.(data, key3) ?? data === panelKeySequences[key3][0]; } // ../pi-core/src/work-panel-host.ts init_render_kit(); // ../pi-core/src/work-panel-detail.ts init_panel_frame(); init_render_kit(); // ../pi-core/src/work-panel-render.ts init_render_kit(); // ../pi-core/src/work-panel-counts.ts init_render_kit(); function formatCompactWorkCounts({ kind, summary: summary2, queuedGlyph = "queued", width, room, measure }) { if (!summary2) return void 0; const { running, queued, completed, failed, cancelled, total } = summary2; if (kind === "other" || [running, queued, completed, failed, cancelled, total].every( (count) => count === void 0 )) return summary2.text || void 0; const parts = [ { status: "running", role: "accent", count: running ?? 0 }, { status: "queued", role: "dim", count: width >= 36 ? queued ?? 0 : 0 }, { status: "completed", role: "success", count: completed ?? 0 }, { status: "failed", role: "error", count: failed ?? 0 }, { status: "cancelled", role: "muted", count: cancelled ?? 0 } ]; const kept = parts.filter((part) => part.count > 0).map(({ status, role, count }) => ({ status, role, text: `${resolveStatusGlyph(status === "queued" ? queuedGlyph : status)}${count}` })); for (const status of ["cancelled", "queued"]) { if (measure(kept.map((part) => part.text).join(" ")) <= room) break; const index = kept.findIndex((part) => part.status === status); if (index >= 0) kept.splice(index, 1); } return kept.map(({ text, role }) => ({ text, role })); } // ../pi-core/src/work-panel-render.ts var WORK_PANEL_ANIMATION_INTERVAL_MS = 100; var DONE_LINGER_MS = 1e4; var FAILED_MIN_LINGER_MS = 3e4; function isSelectablePanelRow(entry) { return entry.sectionSummary === true || !entry.row.summary; } function safely(read, fallback) { try { return read(); } catch { return fallback; } } function singleLine(text) { return text.replace(/[\r\n\t]+/g, " ").trim(); } function panelCloseLabel(entry) { if (!entry || entry.parent || entry.sectionSummary) return ""; return safely(() => singleLine(entry.provider.armCloseLabel(entry.row)), ""); } function panelSections(providers, now, lifecycle2) { const sections = []; for (const provider of [...providers].sort( (a, b) => a.priority - b.priority || a.label.localeCompare(b.label) )) { const rows = safely(() => provider.listRows(now), []); const parent = safely(() => provider.parentRow?.(now), void 0); if (provider.retention !== "prompt" && !rows.length && !parent) continue; if (!safely(() => provider.showSection?.(rows, now) ?? true, false)) continue; if (provider.retention === "prompt") { const items = rows.filter((row) => !row.summary); const semanticCounts = compactSummaryCounts({ provider, rows: [], summaryRows: items }); const counts = { done: semanticCounts.completed, failed: semanticCounts.failed, cancelled: semanticCounts.cancelled }; const done = new Set( items.filter((row) => itemState(row) === "done" && lingers(row, now)).sort((a, b) => (b.endedAt ?? 0) - (a.endedAt ?? 0)).slice(0, 3) ); const eligible = items.filter( (row) => itemState(row) === "running" || itemState(row) === "failed" && (endedInEpoch(row, lifecycle2?.epochStartedAt ?? now) || lingers(row, now)) || done.has(row) ); if (!eligible.length) { if (!counts.done && !counts.failed && !counts.cancelled) continue; sections.push({ provider, collapsed: true, counts, summaryRows: items, rows: [ { provider, row: { id: "history", primary: provider.label, summary: true }, key: JSON.stringify([provider.id, null]), sectionSummary: true } ] }); continue; } sections.push({ provider, counts, summaryRows: items, rows: eligible.map((row) => ({ provider, row, key: JSON.stringify([provider.id, row.id]) })) }); continue; } sections.push({ provider, rows: [ ...parent ? [{ row: parent, parent: true }] : [], ...rows.filter((row) => row.expiresAt === void 0 || row.expiresAt > now).map((row) => ({ row })) ].map((entry) => ({ ...entry, provider, key: JSON.stringify([provider.id, entry.row.id]) })) }); } return sections.filter((section) => section.rows.length).map((section) => { if (section.collapsed) return section; const { provider } = section; return { ...section, rows: [ ...provider.selectableHeading ? [ { provider, row: { id: "heading", primary: provider.label, summary: true }, key: JSON.stringify([provider.id, null, "heading"]), sectionHeading: true, sectionSummary: true } ] : [], ...section.rows.map((entry) => ({ ...entry, key: entry.row.compact?.completedSummary ? overflowKey(provider, "overflow-drop-first") : entry.key, sectionSummary: (entry.row.summary || entry.row.compact?.completedSummary) && provider.selectableSummary ? true : void 0 })) ] }; }); } function panelLingerEndsAt(row) { if (row.endedAt === void 0 || !Number.isFinite(row.endedAt)) return void 0; const state = itemState(row); if (state === "done") return row.endedAt + DONE_LINGER_MS; if (state === "failed") return row.endedAt + FAILED_MIN_LINGER_MS; return void 0; } function lingers(row, now) { const endsAt = panelLingerEndsAt(row); return endsAt !== void 0 && now < endsAt; } function endedInEpoch(row, epochStartedAt) { return row.endedAt !== void 0 && Number.isFinite(row.endedAt) && row.endedAt >= epochStartedAt; } function itemState(row) { if (["queued", "stopping"].includes(row.status ?? "")) return "running"; if (row.state) return row.state; const status = workPanelRenderStatus(row); if (status === "running" || status === "in_progress") return "running"; if (status === "failed" || row.status === "timed_out") return "failed"; if (status === "completed") return "done"; return void 0; } function sectionSummarySegments(section, width, room, measure) { const summary2 = safely(() => section.provider.summary?.(), void 0); if (typeof summary2 === "string") return [{ text: singleLine(summary2), role: "meta" }]; const numeric = summary2 && [ summary2.running, summary2.queued, summary2.completed, summary2.failed, summary2.cancelled, summary2.total ].some((count) => count !== void 0); if (!numeric) { if (summary2?.segments) return summary2.segments; if (summary2?.text !== void 0) return [{ text: singleLine(summary2.text), role: "meta" }]; } const formatted = formatCompactWorkCounts({ kind: section.provider.id === "todos" ? "todos" : "work", queuedGlyph: section.provider.id === "todos" ? "pending" : void 0, summary: compactSummaryCounts(section, summary2), width, room, measure }); if (typeof formatted === "string") return [{ text: formatted, role: "meta" }]; if (formatted === void 0) return void 0; return formatted.flatMap( (part, index) => index ? [{ text: " ", role: "meta" }, part] : [part] ); } function sectionTitle(provider) { return singleLine(provider.label).replace( new RegExp("\\b\\p{L}", "gu"), (letter) => letter.toUpperCase() ); } function compactSummaryCounts(section, summary2 = safely(() => section.provider.summary?.(), void 0)) { const counts = typeof summary2 === "object" ? summary2 : void 0; const items = section.summaryRows ?? section.rows.filter((entry) => !entry.parent && !entry.row.summary).map(({ row }) => row); const fallback = { running: 0, queued: 0, failed: 0, cancelled: 0, completed: 0 }; for (const row of items) { const semantic = workPanelRenderStatus(row); const status = semantic === "unknown" && row.status === "timed_out" ? "timedOut" : semantic; switch (status) { case "running": case "in_progress": case "stopping": fallback.running++; break; case "pending": if (section.provider.id === "todos") fallback.queued++; break; case "queued": fallback.queued++; break; case "failed": case "timedOut": fallback.failed++; break; case "cancelled": case "interrupted": fallback.cancelled++; break; case "completed": case "expectedExit": fallback.completed++; break; case "resolved": break; } } return { running: counts?.running ?? fallback.running, queued: counts?.queued ?? fallback.queued, failed: counts?.failed ?? fallback.failed, cancelled: counts?.cancelled ?? fallback.cancelled, completed: counts?.completed ?? fallback.completed, total: counts?.total }; } function overflowCounts(provider, items, chosen) { const hidden = items.filter((entry) => !chosen.includes(entry)); if (items.some(({ row }) => row.compact)) { const preferred2 = hidden.reduce( (sum, { row }) => sum + (row.compact?.counts.completed ?? 0), 0 ); const other2 = hidden.reduce( (sum, { row }) => sum + (row.compact?.counts.queued ?? 0) + (row.compact?.counts.running ?? 0), 0 ); return { preferred: preferred2, other: other2, lines: Number(preferred2 > 0) + Number(other2 > 0) }; } const preferred = provider.droppedSummary ? hidden.filter(({ row }) => row.dropFirst).length : 0; const other = hidden.length - preferred; return { preferred, other, lines: Number(preferred > 0) + Number(other > 0) }; } function overflowKey(provider, id) { return JSON.stringify([provider.id, null, id]); } function overflowRows(provider, items, chosen, combine = false, selectedKey) { const { preferred, other } = overflowCounts(provider, items, chosen); const compact = items.some(({ row }) => row.compact); let rows = [ ...preferred ? [ { id: "overflow-drop-first", primary: safely( () => compact ? `+${preferred} done` : singleLine(provider.droppedSummary?.(preferred) ?? ""), "" ) || `+${preferred} more`, summary: true } ] : [], ...other ? [ { id: "overflow-more", primary: `+${other} ${compact ? "pending" : "more"}`, summary: true } ] : [] ]; if (compact) rows.reverse(); if (combine && rows.length > 1) { rows = [ { id: selectedKey === overflowKey(provider, "overflow-more") ? "overflow-more" : "overflow-drop-first", primary: rows.map((row) => row.primary).join(` ${resolveIcon("separator", "\xB7")} `), summary: true } ]; } return rows.map((row) => ({ provider, row, key: overflowKey(provider, row.id), sectionSummary: provider.selectableSummary })); } var segmentRoles = { primary: "toolTitle", secondary: "text", meta: "dim", dim: "dim", accent: "accent", warning: "warning", error: "error", success: "success", muted: "muted", completed: "dim" }; function glyphRole(row, status) { if (row.statusGlyphRole) return row.statusGlyphRole; if (status === "expectedExit") return "dim"; if (row.statusTone === "muted") return "muted"; if (status === "running" || status === "in_progress") return "accent"; if (status === "failed") return "error"; if (status === "timedOut") return "warning"; if (status === "resolved") return "muted"; if (status === "completed") return "success"; if (["cancelled", "interrupted", "deleted"].includes(status)) return "muted"; if (status === "blocked" || status === "stopping") return "warning"; return "secondary"; } var nativeGlyphs = { running: "\u25D0", in_progress: "\u25D0", completed: "\u2713", failed: "\u2717", timedOut: "\u25F7", resolved: "\u21BB", expectedExit: "\u2713", pending: "\u25CB", queued: "\u25CB", stopping: "\u25A0", cancelled: "\u25A0", interrupted: "\u25A0", deleted: "\u2298", blocked: "\u2298", unknown: "?" }; var shrinkOrder = [ "secondary", "primary", "dim", "completed", "muted", "meta", "accent", "success", "warning", "error" ]; var segmentText = (segments) => segments.map(({ text }) => text).join(""); var defaultMeasure = (text) => ( // biome-ignore lint/suspicious/noControlCharactersInRegex: optional-peer fallback measures ANSI-styled headings. [...text.replace(/\x1b\[[0-9;]*m/g, "")].length ); function truncateData(text, width, measure, ellipsis = resolveIcon("ellipsis", "\u2026")) { if (measure(text) <= width) return text; if (width <= 0) return ""; let prefix = ""; const suffix = measure(ellipsis) <= width ? ellipsis : ""; for (const character of text) { if (measure(prefix + character + suffix) > width) break; prefix += character; } return prefix + suffix; } var isFlexibleRole = (role) => role === "secondary" || role === "warning" || role === "error"; var itemWidth = (item, measure) => measure(item.lead?.text ?? "") + measure(item.body.text); function plainSegment({ compact: _compact, ...segment }, text = segment.text) { return { ...segment, text }; } var columnsIdentity = (identity) => identity.map( (part) => part.compact === void 0 ? part : { ...part, text: part.compact } ); function identityItems(segments) { const separator = ` ${resolveIcon("separator", "\xB7")} `; const items = []; for (let index = 0; index < segments.length; index++) { const part = segments[index]; const next = segments[index + 1]; if (part.role === "meta" && part.text === separator && next && isFlexibleRole(next.role)) { if (next.role === "secondary" && next.text === "") items.push({ body: plainSegment(next) }); else items.push({ lead: plainSegment(part), body: plainSegment(next) }); index++; } else if (isFlexibleRole(part.role) && part.text.length > separator.length && part.text.startsWith(separator)) { items.push({ lead: { text: separator, role: "meta" }, body: plainSegment(part, part.text.slice(separator.length)) }); } else if (part.role === "secondary" && part.text === separator) items.push({ body: plainSegment(part, "") }); else items.push({ body: plainSegment(part) }); } return items; } function shrinkItem(item, target, measure) { const { lead, body } = item; if (!lead) { body.text = truncateData(body.text, target, measure); return; } if (body.role === "secondary" && target <= measure(lead.text)) { body.text = ""; item.lead = void 0; return; } const fitted = truncateData(lead.text + body.text, target, measure); if (fitted.startsWith(lead.text)) body.text = fitted.slice(lead.text.length); else { lead.text = fitted; body.text = ""; } } var flattenItems = (items) => items.flatMap(({ lead, body }) => lead ? [lead, body] : [body]); function truncateSegments(segments, width, measure, ellipsis) { if (width <= 0 || segmentText(segments) === "") return []; if (measure(segmentText(segments)) <= width) return segments.map((segment) => ({ ...segment })); const room = Math.max(0, width - measure(ellipsis)); const kept = []; let used = 0; for (const segment of segments) { const left = room - used; if (left <= 0) break; const text = truncateData(segment.text, left, measure, ""); kept.push({ ...segment, text }); used += measure(text); if (text !== segment.text) break; } while (kept.length > 1 && kept.at(-1)?.role === "meta") kept.pop(); if (ellipsis && measure(ellipsis) <= width) { if (!kept.length) kept.push({ text: "", role: segments[0].role }); kept.at(-1).text += ellipsis; } return kept.filter((segment) => segment.text !== ""); } function fitIdentity(segments, width, measure) { const items = identityItems(segments); const attention = items.filter( ({ body }) => body.role === "warning" || body.role === "error" ); if (attention.length && width <= attention.reduce((sum, item) => sum + itemWidth(item, measure), 0)) { const sequence = flattenItems(attention); if (sequence[0]?.role === "meta") sequence.shift(); return truncateSegments(sequence, width, measure, ""); } const total = items.reduce((sum, item) => sum + itemWidth(item, measure), 0); let excess = total - width; for (const role of shrinkOrder) { for (const item of items) { if (excess <= 0) break; if (item.body.role !== role) continue; const before = itemWidth(item, measure); shrinkItem(item, Math.max(0, before - excess), measure); excess -= before - itemWidth(item, measure); } } return flattenItems(items); } function fitIdentityKeepName(segments, width, measure) { const separator = ` ${resolveIcon("separator", "\xB7")} `; const items = identityItems(segments); const attention = items.filter( ({ body }) => body.role === "warning" || body.role === "error" ); const names = items.filter(({ body }) => body.role === "primary"); if (!attention.length || !names.length) return fitIdentity(segments, width, measure); const nameText = names.map(({ body }) => body.text).join(""); const attentionWidth = attention.reduce( (sum, item) => sum + itemWidth(item, measure), 0 ); if (measure(nameText) + attentionWidth <= width) return fitIdentity(segments, width, measure); const nameWidth = Math.min(measure(nameText), width); const room = width - nameWidth - measure(separator); const result = [ { text: truncateData(nameText, nameWidth, measure), role: "primary" } ]; if (room > 0) { const sequence = flattenItems(attention); if (sequence[0]?.role === "meta") sequence.shift(); result.push( { text: separator, role: "meta" }, ...truncateSegments( sequence, room, measure, resolveIcon("ellipsis", "\u2026") ) ); } return result; } function wrapSegments(segments, width, measure) { if (width <= 0) return []; const lines = []; let current = []; for (const segment of segments) { for (const text of segment.text) { if (measure(current.map((cell) => cell.text).join("") + text) > width) { let space = current.length - 1; while (space >= 0 && !/\s/u.test(current[space].text)) space -= 1; if (space >= 0) { lines.push(current.slice(0, space)); current = current.slice(space + 1); } else { lines.push(current); current = []; } } if (current.length || !/\s/u.test(text)) current.push({ text, role: segment.role }); } } if (current.length) lines.push(current); return lines.filter((line) => line.length).map((line) => { while (line.length && /\s/u.test(line.at(-1)?.text ?? "")) line.pop(); const parts = []; for (const cell of line) { const previous = parts.at(-1); if (previous?.role === cell.role) previous.text += cell.text; else parts.push({ ...cell }); } return parts; }); } var metricNumberWidths = { tools: 3, tokens: 5, context: 6, speed: 3, cost: 6, elapsed: 7 }; var reservationCell = "\0"; var visibleSegments = (parts) => parts.map((part) => ({ ...part, text: part.text.replaceAll(reservationCell, "") })); function reservedMetricSegments(group, continuation = false) { const parts = continuation ? group.continuation ?? group.segments : group.segments; if (!group.key || group.key === "model") return parts.map((part) => ({ ...part })); const reserved = metricNumberWidths[group.key]; const valuePattern = group.key === "elapsed" ? /\d+(?:\.\d+)?(?:ms|[smh])(?: \d+[smh])?|\?/g : /\d+(?:\.\d+)?[kKmM%]?|\?/g; return parts.map((part) => ({ ...part, text: part.text.replace( valuePattern, (value3) => value3 + reservationCell.repeat(Math.max(0, reserved - value3.length)) ) })); } function columnMetricSegments(group) { const parts = reservedMetricSegments(group); if (group.key !== "elapsed") return parts; const text = segmentText(parts).replace(/^[^\d?]+/, ""); return [{ text, role: parts.at(-1)?.role ?? "meta" }]; } var gridOrder = [ "tools", "tokens", "context", "speed", "cost", "elapsed", "model" ]; function createWorkPanelMetricGrid(rows, measure = defaultMeasure) { const widths = /* @__PURE__ */ new Map(); for (const row of rows) for (const group of row.metrics ?? []) { if (!group.key) continue; const width = group.key === "model" ? 16 : measure( segmentText(reservedMetricSegments(group)).replaceAll( reservationCell, " " ) ); widths.set(group.key, Math.max(widths.get(group.key) ?? 0, width)); } return gridOrder.filter((key3) => widths.has(key3)).map((key3) => ({ key: key3, width: widths.get(key3) ?? 0 })); } function gridContent(row, identity, width, measure, grid) { if (width <= 0) return { text: "", segments: [] }; const cells = grid.map((column) => { const group = row.metrics?.find(({ key: key3 }) => key3 === column.key); let parts = group ? reservedMetricSegments(group).map((part) => ({ ...part, text: part.text.replaceAll(reservationCell, " ") })) : []; if (column.key === "model") parts = fitIdentity(parts, column.width, measure); const padding = Math.max(0, column.width - measure(segmentText(parts))); return { parts: [...parts, { text: " ".repeat(padding), role: "meta" }], width: column.width }; }); const gutter = { text: " ", role: "meta" }; const total = cells.reduce((sum, cell) => sum + cell.width, 0) + Math.max(0, cells.length - 1); const minimum = 24; if (cells.length && total + 1 + minimum <= width) { const segments2 = fitIdentity(identity, width - total - 1, measure); segments2.push({ text: " ".repeat(width - total - measure(segmentText(segments2))), role: "meta" }); cells.forEach((cell, index) => { segments2.push(...index ? [gutter, ...cell.parts] : cell.parts); }); return { text: segmentText(segments2), segments: segments2 }; } const segments = fitIdentity(identity, width, measure); const lines = []; let line = []; let used = 0; for (const cell of cells) { if (used && used + 1 + cell.width > width) { lines.push(line); line = []; used = 0; } if (cell.width > width) { let chunk = []; let chunkWidth = 0; for (const part of cell.parts) for (const character of part.text) { const size = measure(character); if (chunkWidth + size > width) { lines.push(chunk); chunk = []; chunkWidth = 0; } const last = chunk.at(-1); if (last?.role === part.role) last.text += character; else chunk.push({ text: character, role: part.role }); chunkWidth += size; } if (chunk.length) lines.push(chunk); } else { if (used) line.push(gutter); line.push(...cell.parts); used += (used ? 1 : 0) + cell.width; } } if (line.length) lines.push(line); return { text: segmentText(segments), segments, extraRows: lines.map(segmentText), extraSegments: lines }; } var contentGutter = () => getRenderKit() ? 7 : 4; var terminalStatuses = /* @__PURE__ */ new Set([ "completed", "failed", "timedOut", "cancelled", "interrupted", "deleted", "resolved", "expectedExit" ]); var MODEL_COLUMN_WIDTH = 10; var MIN_SUMMARY_CELLS = 12; var columnPriority = [ "elapsed", "context", "cost", "summary", "speed", "tokens", "tools", "warnings", "model" ]; function identityDemand(identity, measure) { const items = identityItems(identity); const separator = measure(` ${resolveIcon("separator", "\xB7")} `); const widthOf = (role) => items.filter(({ body }) => role(body.role)).reduce((sum, item) => sum + itemWidth(item, measure), 0); const summary2 = widthOf((role) => role === "secondary"); return { base: widthOf((role) => role !== "secondary" && !isFlexibleRole(role)), summary: summary2 ? Math.min(summary2, separator + MIN_SUMMARY_CELLS) : 0, warnings: widthOf((role) => role === "warning" || role === "error") }; } var columnDisplayOrder = [ "model", "tools", "tokens", "context", "speed", "cost", "elapsed" ]; var secondLinePriority = [ "context", "cost", "speed", "tokens", "tools", "warnings", "model" ]; function attentionSegments(identity) { const sequence = flattenItems( identityItems(identity).filter( ({ body }) => body.role === "warning" || body.role === "error" ) ); if (sequence[0]?.role === "meta") sequence.shift(); return sequence; } function createWorkPanelColumnPlan(rows, width, measure = defaultMeasure, options = {}) { const available = Math.max(0, width - contentGutter()); const separator = measure(` ${resolveIcon("separator", "\xB7")} `); const widths = /* @__PURE__ */ new Map(); const demands = []; let warningWidth = 0; for (const row of rows) { const identity = columnsIdentity( row.identity ?? row.segments ?? [{ text: row.primary, role: "primary" }] ); demands.push(identityDemand(identity, measure)); warningWidth = Math.max( warningWidth, measure(segmentText(attentionSegments(identity))) ); for (const group of row.metrics ?? []) { if (!group.key) continue; const size = group.key === "model" ? MODEL_COLUMN_WIDTH : measure( segmentText(columnMetricSegments(group)).replaceAll( reservationCell, " " ) ); widths.set(group.key, Math.max(widths.get(group.key) ?? 0, size)); } } if (options.lines === 2) { const kept2 = []; let used = 0; for (const element of secondLinePriority) { const size = element === "warnings" ? warningWidth : widths.get(element) ?? 0; if (!size) continue; if (used + (kept2.length ? separator : 0) + size > available) break; used += (kept2.length ? separator : 0) + size; kept2.push(element); } const columns = [ ...widths.has("elapsed") ? [{ key: "elapsed", width: widths.get("elapsed") ?? 0 }] : [], ...kept2.flatMap( (element) => element === "warnings" ? [] : [{ key: element, width: widths.get(element) ?? 0 }] ) ]; return Object.assign(columns, { warnings: kept2.includes("warnings"), lines: 2, warningWidth }); } const kept = /* @__PURE__ */ new Set(); const fits = () => { const columns = [...widths].filter(([key3]) => kept.has(key3)).reduce((sum, [, size]) => sum + size + separator, 0); return demands.every( (demand) => demand.base + (kept.has("summary") ? demand.summary : 0) + (kept.has("warnings") ? demand.warnings : 0) + columns <= available ); }; for (const element of columnPriority) { const present = element === "summary" || element === "warnings" || widths.has(element); if (!present) continue; kept.add(element); if (element !== "elapsed" && !fits()) { kept.delete(element); break; } } return Object.assign( columnDisplayOrder.filter((key3) => kept.has(key3) && widths.has(key3)).map((key3) => ({ key: key3, width: widths.get(key3) ?? 0 })), { warnings: kept.has("warnings") } ); } function withoutAttention(identity) { return flattenItems( identityItems(identity).filter( ({ body }) => body.role !== "warning" && body.role !== "error" ) ); } var MIN_VISIBLE_SUMMARY_CELLS = 4; function dropTinySummary(fitted, identity, measure) { const summaryOf = (items2) => items2.findIndex(({ body: body2 }) => body2.role === "secondary"); const original = identityItems(identity); const originalSummary = original[summaryOf(original)]?.body.text; const items = identityItems(fitted); const index = summaryOf(items); const body = items[index]?.body; if (!body || body.text === "" || body.text === originalSummary || measure(body.text) >= MIN_VISIBLE_SUMMARY_CELLS) return [...fitted]; return flattenItems(items.filter((_, position) => position !== index)); } function contextRole(text) { const percent = Number(text.match(/(\d+(?:\.\d+)?)%/)?.[1]); if (percent > 90) return "error"; return percent > 70 ? "warning" : "dim"; } function columnSegments(key3, parts, row, status, width, measure, lineTwo) { const text = segmentText(parts); if (lineTwo?.finished) return [ { text: key3 === "model" ? truncateData(text, width, measure) : text, role: "dim" } ]; switch (key3) { case "model": return [ { text: truncateData(text, width, measure), role: "muted" } ]; case "tokens": return parts.some(({ direction }) => direction) ? parts.map(({ text: part, direction }) => ({ text: part, role: direction === "in" ? "accent" : direction === "out" ? "success" : "meta" })) : [{ text, role: "accent" }]; case "cost": return [{ text, role: "warning" }]; case "context": return [{ text, role: lineTwo ? contextRole(text) : "dim" }]; case "elapsed": { const role = glyphRole(row, status); return [ { text, role: role === "success" || role === "secondary" ? "dim" : role } ]; } default: return [{ text, role: "dim" }]; } } function responsiveContent(row, width, measure, metricLayout = "greedy", metricGrid) { const identity = row.identity ?? row.segments ?? [{ text: row.primary, role: "primary" }]; const identityUnits = identityItems(identity); const columnsIdentityText = columnsIdentity(identity); if (metricLayout === "grid" && (row.metrics ?? []).every((group) => group.key)) return gridContent( row, identity, width, measure, metricGrid ?? createWorkPanelMetricGrid([row], measure) ); const separator = { text: ` ${resolveIcon("separator", "\xB7")} `, role: "meta" }; const joinGroups = (groups2) => groups2.flatMap( (group, index) => index ? [separator, ...group] : [...group] ); const planningMeasure = (text) => measure(text.replaceAll(reservationCell, " ")); const groups = (row.metrics ?? []).filter( (group) => metricLayout === "columns" || !group.columnsOnly ); const metrics = groups.map((group) => reservedMetricSegments(group)); const metricSegments = joinGroups(metrics); const inlineWidth = width - planningMeasure(segmentText(metricSegments)) - measure(separator.text); const minIdentity = identityUnits.filter(({ body }) => body.role !== "secondary").reduce((sum, item) => sum + itemWidth(item, measure), 0) + (identityUnits.some( ({ lead, body }) => body.role === "secondary" && (lead || body.text) ) ? measure(separator.text) + 1 : 0); if (metricLayout === "columns" && groups.every((group) => group.key)) { const status = workPanelRenderStatus(row); const plan = metricGrid ?? createWorkPanelColumnPlan([row], width + contentGutter(), measure); const columnFor = (column, align = "right", lineTwo = false) => { const group = groups.find(({ key: key3 }) => key3 === column.key); const parts = group && !(lineTwo && group.pending) ? columnSegments( column.key, visibleSegments(columnMetricSegments(group)), row, status, column.width, measure, lineTwo ? { finished: terminalStatuses.has(status) } : void 0 ) : []; const padding = Math.max(0, column.width - measure(segmentText(parts))); return { present: Boolean(group), blank: Boolean(lineTwo && group?.pending), parts: align === "left" ? [...parts, { text: " ".repeat(padding), role: "meta" }] : [{ text: " ".repeat(padding), role: "meta" }, ...parts] }; }; if (plan.lines === 2) { const terminal2 = terminalStatuses.has(status); const elapsed = plan.find(({ key: key3 }) => key3 === "elapsed"); const elapsedParts = elapsed ? columnFor(elapsed).parts : []; const identityWidth2 = Math.max( 0, width - (elapsed ? elapsed.width + measure(separator.text) : 0) ); const admitted2 = withoutAttention(columnsIdentityText); const segments3 = dropTinySummary( fitIdentity(admitted2, identityWidth2, measure), admitted2, measure ).map( (part) => terminal2 && part.role === "secondary" ? { ...part, role: "muted" } : part ); const gap2 = Math.max(0, identityWidth2 - measure(segmentText(segments3))); if (gap2) segments3.push({ text: " ".repeat(gap2), role: "meta" }); if (elapsed) segments3.push(separator, ...elapsedParts); const slots = []; const warningSlot = () => { const text = attentionSegments(columnsIdentityText); const padding = Math.max( 0, (plan.warningWidth ?? 0) - measure(segmentText(text)) ); return { present: text.length > 0, parts: [ ...text, { text: " ".repeat(padding), role: "meta" } ] }; }; let warningsPlaced = plan.warnings !== true; for (const column of plan) { if (column.key === "elapsed") continue; if (!warningsPlaced && column.key === "model") { slots.push(warningSlot()); warningsPlaced = true; } slots.push(columnFor(column, "left", true)); } if (!warningsPlaced) slots.push(warningSlot()); if (!slots.some((slot) => slot.present)) return { text: segmentText(segments3), segments: segments3 }; const blankSeparator = { text: " ".repeat(measure(separator.text)), role: "meta" }; const second = slots.flatMap( (slot, index) => index ? [ slot.blank || slots.slice(0, index).every(({ blank }) => blank) ? blankSeparator : separator, ...slot.parts ] : [...slot.parts] ); return { text: segmentText(segments3), segments: segments3, extraRows: [segmentText(second)], extraSegments: [second], keepBlankRows: true }; } const columns = plan.map((column) => columnFor(column).parts); const columnWidth = columns.length ? plan.reduce((sum, { width: w }) => sum + w, 0) + measure(separator.text) * (columns.length - 1) : 0; const identityWidth = Math.max( 0, width - columnWidth - (columns.length ? measure(separator.text) : 0) ); const terminal = terminalStatuses.has(status); const admitted = withoutAttention(columnsIdentityText); const columnsFit = plan.warnings === false ? admitted : columnsIdentityText; const segments2 = dropTinySummary( fitIdentityKeepName(columnsFit, identityWidth, measure), columnsFit, measure ).map( (part) => terminal && part.role === "secondary" ? { ...part, role: "muted" } : part ); const gap = Math.max(0, identityWidth - measure(segmentText(segments2))); if (gap) segments2.push({ text: " ".repeat(gap), role: "meta" }); if (columns.length) segments2.push(separator, ...joinGroups(columns)); return { text: segmentText(segments2), segments: segments2 }; } const inline = metrics.length > 0 && inlineWidth >= minIdentity; const visibleMetrics = visibleSegments(metricSegments); const actualInlineWidth = width - measure(segmentText(visibleMetrics)) - measure(separator.text); const segments = fitIdentity( identity, inline ? actualInlineWidth : width, measure ); if (inline) segments.push(separator, ...visibleMetrics); const continuations = []; if (!inline) { for (const group of groups) { const parts = reservedMetricSegments(group, true); const previous = continuations.at(-1); const joined = previous ? [...previous, separator, ...parts] : [...parts]; if (previous && planningMeasure(segmentText(joined)) <= width) continuations[continuations.length - 1] = joined; else continuations.push([...parts]); } } const extraSegments = continuations.flatMap( (parts) => wrapSegments(parts, width, planningMeasure).map(visibleSegments) ); return { text: segmentText(segments), segments, extraRows: extraSegments.map(segmentText), extraSegments }; } function panelContentReader(width, measure = defaultMeasure, metricLayout = "greedy", metricGrid) { const kit = getRenderKit(); const contents = /* @__PURE__ */ new Map(); function contentFor(entry) { let content = contents.get(entry); if (!content) { content = (entry.row.identity || entry.row.metrics) && // Flat `segments` rows keep their legacy host presentation outside the columns layout. !(metricLayout !== "columns" && entry.row.segments) ? responsiveContent( entry.row, Math.max(0, width - (kit ? 7 : 4)), measure, metricLayout, metricGrid ) : { text: [entry.row.name, entry.row.primary, entry.row.elapsed].filter(Boolean).join(` ${resolveIcon("separator", "\xB7")} `), segments: entry.row.segments ?? [ ...entry.row.name ? [ { text: entry.row.name, role: "primary" }, { text: ` ${resolveIcon("separator", "\xB7")} `, role: "meta" } ] : [], { text: entry.row.primary, role: entry.row.name ? "secondary" : "primary" }, ...entry.row.elapsed ? [ { text: ` ${resolveIcon("separator", "\xB7")} ${entry.row.elapsed}`, role: "meta" } ] : [] ], extraRows: entry.row.extraRows, extraSegments: entry.row.extraSegments }; contents.set(entry, content); } return content; } return contentFor; } function withCompactHeadings(section, chosen) { const keys = new Set( chosen.filter(({ row }) => row.compact?.depth).map(({ row }) => row.compact?.group?.key) ); return section.rows.filter( (entry) => chosen.includes(entry) || entry.row.compact?.heading && keys.has(entry.row.compact.group?.key) ); } function compactPriority(a, b) { const rank = (entry) => entry.row.compact?.counts.running ? 0 : entry.row.compact?.counts.queued ? 1 : 2; return rank(a) - rank(b) || (rank(a) === 1 ? (a.row.compact?.taskId ?? Infinity) - (b.row.compact?.taskId ?? Infinity) : 0); } function overflowLineCount(plan, chosen = plan.chosen) { if (plan.hideOverflow) return 0; const { lines } = overflowCounts(plan.section.provider, plan.items, chosen); return plan.combineOverflow ? Math.min(1, lines) : lines; } function planOverflowRows(plan, selectedKey) { return plan.hideOverflow ? [] : overflowRows( plan.section.provider, plan.items, plan.chosen, plan.combineOverflow, selectedKey ); } function planPanelSections(sections, remaining, blockCost, selectedKey) { const visible2 = []; let minimumCost = 0; for (const section of sections) { const cost2 = section.collapsed ? 1 : 2; if (minimumCost + cost2 > remaining) break; visible2.push(section); minimumCost += cost2; } const selectedSection = sections.find( (section) => section.rows.some((entry) => entry.key === selectedKey) || ["overflow-drop-first", "overflow-more"].some( (id) => overflowKey(section.provider, id) === selectedKey ) ); if (selectedSection && visible2.length && !visible2.includes(selectedSection)) { visible2[visible2.length - 1] = selectedSection; visible2.sort((a, b) => sections.indexOf(a) - sections.indexOf(b)); } const plans = visible2.map((section) => { const items = section.collapsed ? [] : section.rows.filter(({ row }) => !row.summary && !row.compact?.heading); const summaries = section.rows.filter( (entry) => entry.row.summary && !entry.sectionHeading ); const selectedGroup = section.rows.find( (entry) => entry.key === selectedKey && entry.row.compact?.heading )?.row.compact?.group?.key; const selectedIndex = items.findIndex( ({ key: key3, row }) => !row.compact?.completedSummary && (key3 === selectedKey || selectedGroup !== void 0 && row.compact?.group?.key === selectedGroup) ); const ordered = items.some(({ row }) => row.compact) ? [...items].sort(compactPriority) : items; const initial = selectedIndex >= 0 ? items[selectedIndex] : ordered.find(({ row }) => !row.dropFirst) ?? ordered[0]; return { section, items, summaries, chosen: initial ? [initial] : [], selectedIndex, combineOverflow: items.some(({ row }) => row.compact), hideOverflow: false }; }); const chosenCost = (plan, chosen = plan.chosen) => withCompactHeadings(plan.section, chosen).reduce( (sum, entry) => sum + blockCost(entry), 0 ); const cost = (plan) => plan.section.collapsed ? 1 : 1 + chosenCost(plan) + plan.summaries.length + overflowLineCount(plan); const totalCost = () => plans.reduce((sum, plan) => sum + cost(plan), 0); while (plans.length > 1 && totalCost() > remaining) { let removable = plans.length - 1; if (plans[removable]?.section === selectedSection) removable -= 1; plans.splice(removable, 1); } const only = plans.length === 1 ? plans[0] : void 0; if (only && cost(only) > remaining) { only.combineOverflow = true; if (cost(only) > remaining) { const overflowSelected = ["overflow-drop-first", "overflow-more"].some( (id) => overflowKey(only.section.provider, id) === selectedKey ); const { preferred } = overflowCounts( only.section.provider, only.items, only.chosen ); if (overflowSelected || preferred > 0 || only.section.provider.selectableSummary) only.chosen = []; else only.hideOverflow = true; } } for (const dropFirst of [false, true]) { for (const capped of [true, false]) { let added; do { added = false; for (const plan of plans) { const cap = Math.max( 1, Math.floor(plan.section.provider.rowCap ?? 3) ); if (capped && plan.chosen.length >= cap) continue; const start = Math.max(0, plan.selectedIndex - cap + 1); const candidates = [ ...plan.items.slice(start), ...plan.items.slice(0, start) ]; if (plan.items.some(({ row }) => row.compact)) candidates.sort(compactPriority); const next = candidates.find( (entry) => Boolean(entry.row.dropFirst) === dropFirst && !plan.chosen.includes(entry) ); if (!next) continue; const delta = chosenCost(plan, [...plan.chosen, next]) - chosenCost(plan) + overflowLineCount(plan, [...plan.chosen, next]) - overflowLineCount(plan); if (totalCost() + delta > remaining) continue; plan.chosen.push(next); added = true; } } while (added); } } for (const plan of plans) { if (plan.chosen.length < plan.items.length) plan.chosen = plan.chosen.filter( ({ row }) => !row.compact?.completedSummary ); } return plans; } function panelOverflowEntries(sections, width, _now, budget, selectedKey, measure = defaultMeasure) { const contentFor = panelContentReader(width, measure); const blockCost = (entry) => 1 + (keptExtraRows(contentFor(entry)).length ?? 0); const hasHint = sections.some( (section) => section.rows.some(isSelectablePanelRow) ); const remaining = Math.max(0, budget - Number(hasHint)); return new Map( planPanelSections(sections, remaining, blockCost, selectedKey).map( (plan) => [plan.section.provider.id, planOverflowRows(plan, selectedKey)] ) ); } function segmentStyler(theme, clip2, measure) { const kit = getRenderKit(); const fg = (role, text) => kit ? kit.fg(theme, role, text) : theme.fg(role, text); const styleSegments = (segments, available = Infinity) => { const parts = segments.map((segment) => { const text = segment.text.replace(/[\r\n\t]+/g, " "); return { ...segment, text, width: measure(text) }; }); let excess = parts.reduce((sum, part) => sum + part.width, 0) - available; for (const role of shrinkOrder) { for (const part of parts) { if (excess <= 0) break; if (part.role !== role) continue; const removed = Math.min(part.width, excess); part.width -= removed; excess -= removed; } } return parts.map(({ text, role, width: partWidth }) => { const clipped = partWidth < measure(text) ? clip2(text, partWidth) : text; const styled = fg(segmentRoles[role], clipped); if (role === "completed") return theme.strikethrough?.(styled) ?? styled; return role === "primary" && theme.bold ? theme.bold(styled) : styled; }).join(""); }; return styleSegments; } function keptExtraRows(content, grid = false) { return (content.extraRows ?? []).filter( (extra) => grid || content.keepBlankRows || extra.trim() ); } function renderWorkPanelRow(row, options) { const { width, theme, clip: clip2 } = options; if (!(width > 0)) return []; const kit = getRenderKit(); const measure = options.measure ?? defaultMeasure; const fg = (role, text) => kit ? kit.fg(theme, role, text) : theme.fg(role, text); const styleSegments = segmentStyler(theme, clip2, measure); const contentFor = panelContentReader( width, measure, options.metricLayout, options.metricGrid ); const entry = { row }; const status = workPanelRenderStatus(row); const staticAnimation = !isAnimationEffectEnabled("secondary"); const frame = options.animationFrame ?? 0; const indicator = !row.summary && !staticAnimation ? kit?.indicator(theme, void 0, { status, frame }) : void 0; const semanticGlyph = workPanelStatusGlyph(row); const running = status === "running" || status === "in_progress"; const frames = resolveFrames("spinnerFrames"); const native = semanticGlyph && running ? frames[frame % frames.length] : nativeGlyphs[status]; const glyph = semanticGlyph === "taskInProgress" ? resolveIcon("taskInProgress", "\u25C7") : running ? staticAnimation ? resolveStaticRunningGlyph() : indicator?.glyph ?? native : resolveStatusGlyph(status, native); const content = contentFor(entry); const depth = Math.max(0, Math.floor(row.compact?.depth ?? 0)); const body = content.segments ? styleSegments( content.segments, Math.max(0, width - (kit ? 7 : 4) - depth * 2) ) : singleLine(content.text); const styledGlyph = row.summary || row.compact?.heading ? "" : `${fg(segmentRoles[glyphRole(row, status)], glyph)} `; return [ kit ? kit.treeRow( theme, { text: `${styledGlyph}${body}`, selected: options.selected === true, depth, last: options.last === true }, width ) : `${options.selected === true ? fg("accent", `${resolveIcon("selection", "\u203A")} `) : " "}${" ".repeat(depth)}${styledGlyph}${body}`, ...keptExtraRows(content, options.metricLayout === "grid").map( (extra, index) => content.extraSegments?.[index] ? `${kit ? " " : " "}${styleSegments(content.extraSegments[index])}` : fg("dim", `${kit ? " " : " "}${singleLine(extra)}`) ) ].map((line) => clip2(line, width)); } function renderPanel(sections, width, now, theme, clip2, options = {}) { if (!(width > 0)) return []; width = Math.floor(width); const kit = getRenderKit(); const fg = (role, text) => kit ? kit.fg(theme, role, text) : theme.fg(role, text); const measure = options.measure ?? defaultMeasure; const styleSegments = segmentStyler(theme, clip2, measure); if (options.summary) { if (!sections.length) return []; return [ clip2( sections.map((section) => { const label = sectionTitle(section.provider); const title = fg("toolTitle", label); const counter = styleSegments( sectionSummarySegments( section, width, width - measure(label) - 1, measure ) ?? [] ); return counter ? `${title} ${counter}` : title; }).join(fg("dim", ` ${resolveIcon("separator", "\xB7")} `)), width ) ]; } const hint = sections.some( (section) => section.rows.some(isSelectablePanelRow) ) ? options.hint : void 0; const budget = Math.max(0, Math.floor(options.budget ?? 12)); const remaining = Math.max(0, budget - (hint ? 1 : 0)); const contentFor = panelContentReader(width, measure); const blockCost = (entry) => 1 + (keptExtraRows(contentFor(entry)).length ?? 0); const plans = planPanelSections( sections, remaining, blockCost, options.selectedKey ); const lines = []; for (const plan of plans) { const { provider, rows } = plan.section; const chosen = withCompactHeadings(plan.section, plan.chosen).sort( (a, b) => rows.indexOf(a) - rows.indexOf(b) ); const entries = [...chosen, ...plan.summaries]; const blocks = entries.map((entry, index) => { return renderWorkPanelRow(entry.row, { width, now, theme, clip: clip2, measure, animationFrame: options.animationFrame, selected: isSelectablePanelRow(entry) && options.selectedKey === entry.key, last: entry.row.compact?.depth ? entries[index + 1]?.row.compact?.group?.key !== entry.row.compact.group?.key : index === entries.length - 1 && plan.chosen.length === plan.items.length }); }); const title = sectionTitle(provider); const selectedSummary = rows.some( (entry) => (plan.section.collapsed || entry.sectionHeading) && entry.key === options.selectedKey ); const separator = resolveIcon("separator", "\xB7"); const chromeWidth = measure(`\u25C6 ${separator} `) + (selectedSummary ? measure(`${resolveIcon("selection", "\u203A")} `) : 0); const counter = styleSegments( sectionSummarySegments( plan.section, width, width - measure(title) - chromeWidth, measure ) ?? [ { text: `${rows.filter((entry) => !entry.sectionHeading).length} items`, role: "meta" } ] ); const heading = kit ? kit.widgetHeading( theme, { title, suffix: `${separator} ${counter}` }, Math.max(0, width - (selectedSummary ? 2 : 0)) ) : `${fg("accent", "\u25C6")} ${fg("toolTitle", title)} ${fg("dim", `${separator} `)}${counter}`; const sectionLines = [ selectedSummary ? `${fg("accent", `${resolveIcon("selection", "\u203A")} `)}${heading}` : heading ]; if (plan.section.collapsed) { lines.push(...sectionLines); continue; } const overflow = planOverflowRows(plan, options.selectedKey); const more = overflow.length > 0 && remaining - lines.length >= 2; const bodyBudget = Math.max( 0, remaining - lines.length - 1 - (more ? overflow.length : 0) ); sectionLines.push(...blocks.flat().slice(0, bodyBudget)); if (more) sectionLines.push( ...overflow.map( (entry) => `${options.selectedKey === entry.key && isSelectablePanelRow(entry) ? fg("accent", `${resolveIcon("selection", "\u203A")} `) : " "}${fg("dim", entry.row.primary)}` ) ); lines.push(...sectionLines); } if (hint && budget) lines.push(fg("dim", hint)); return lines.slice(0, budget).map((line) => clip2(line, width)); } function workPanelRenderStatus(row) { const semanticGlyph = workPanelStatusGlyph(row); if (semanticGlyph && semanticGlyph !== "taskInProgress") return semanticGlyph; if (row.statusTone === "running") return "running"; if (row.statusTone === "success") return "completed"; if (row.statusTone === "failed") return "failed"; if (row.statusTone === "warning") return "blocked"; return renderStatuses.includes(row.status ?? "") ? row.status : "unknown"; } var renderStatuses = [ "pending", "queued", "in_progress", "running", "completed", "failed", "timedOut", "resolved", "expectedExit", "cancelled", "interrupted", "stopping", "deleted", "blocked", "unknown" ]; function workPanelStatusGlyph(row) { const glyph = row.statusGlyph; return glyph === "taskInProgress" || renderStatuses.includes(glyph ?? "") ? glyph : void 0; } // ../pi-core/src/work-panel-detail.ts var hasValue = (value3) => value3 !== void 0 && !["", "-", "\u2013", "\u2014"].includes(value3.trim()); function statusRole(detail) { if (detail.statusTone === "muted") return "muted"; switch (workPanelRenderStatus(detail)) { case "running": case "in_progress": return "accent"; case "failed": return "error"; case "completed": return "success"; case "cancelled": case "interrupted": case "deleted": return "muted"; case "blocked": case "stopping": return "warning"; default: return "text"; } } function createWorkPanelDetail(options) { let closed = false; let focused = false; let detailKey; let detail = null; let logTailLines = 25; const expanded = /* @__PURE__ */ new Map(); let foldTarget; let foldExpanded = false; let timer; const EVIDENCE = "__evidence__"; function readDetail(entry) { const snapshot2 = safely( () => entry.provider.detail(entry.row.id, Date.now(), { logTailLines }), null ) ?? { id: entry.row.id, title: entry.row.name ?? entry.row.id, subtitle: entry.row.primary, status: entry.row.status, metadata: [], evidence: { label: "details", text: entry.row.secondary ?? "(no details)" } }; return { ...snapshot2, status: hasValue(snapshot2.status) ? snapshot2.status : void 0, subtitle: hasValue(snapshot2.subtitle) ? snapshot2.subtitle : void 0, metadata: snapshot2.metadata.filter((item) => hasValue(item.value)), foldedSections: snapshot2.foldedSections?.filter( (section) => hasValue(section.text) ) }; } function refreshDetail() { const entry = options.selected(); if (!entry) { dismiss(); return; } detail = readDetail(entry); if (detailKey !== entry.key) { detailKey = entry.key; expanded.clear(); foldTarget = void 0; } } function stopTimer() { if (timer) clearTimeout(timer); timer = void 0; } function tick() { stopTimer(); if (closed) return; refreshDetail(); if (closed) return; options.requestRender(); if (detail?.status === "running" || detail?.status === "in_progress" || detail?.status === "orphaned") { timer = setTimeout(tick, 1e4); timer.unref?.(); } } function dispose() { closed = true; stopTimer(); options.clearCloseArm(); } function dismiss() { if (closed) return; dispose(); options.done(); } const openingDetails = options.rows().map((entry) => ({ entry, detail: readDetail(entry) })); function hintFor(entry, foldable) { const close = panelCloseLabel(entry); return [ `${resolveIcon("arrowUp", "\u2191")}${resolveIcon("arrowDown", "\u2193")} move`, foldable ? "Enter expand/collapse" : "", close ? `x ${close}` : "", entry?.provider.supportsLogTail ? "l 10/25" : "", "Esc back" ].filter(Boolean).join(` ${resolveIcon("separator", "\xB7")} `); } const plain = (_role, text) => text; function fieldsFor(snapshot2, fg = plain) { const field2 = (label, value3, role = "text") => fg("dim", `${singleLine(label)} ${resolveIcon("separator", "\xB7")} `) + fg(role, singleLine(value3)); return [ ...snapshot2.status ? [field2("status", snapshot2.status, statusRole(snapshot2))] : [], ...snapshot2.subtitle ? [fg("text", singleLine(snapshot2.subtitle))] : [], ...snapshot2.metadata.map((item) => field2(item.label, item.value)) ]; } function blocksFor(snapshot2, tail, width, fg = plain) { const empty = !snapshot2.evidence.text.trim(); const evidence = options.wrap( fg( empty ? "dim" : "text", empty ? snapshot2.evidence.emptyText ?? "(no output yet)" : snapshot2.evidence.text ), Math.max(1, width) ); return [ ...(snapshot2.foldedSections ?? []).map((section) => ({ id: section.id, label: singleLine(section.label), rows: options.wrap(fg("text", section.text), Math.max(1, width)), preview: singleLine( section.collapsedText ?? section.text.split(/\r?\n/)[0] ?? "" ), defaultExpanded: section.expandedByDefault ?? false })), { id: EVIDENCE, label: singleLine(snapshot2.evidence.label), rows: tail ? evidence.slice(-logTailLines) : evidence, preview: singleLine(snapshot2.evidence.text.split(/\r?\n/)[0] ?? ""), defaultExpanded: tail } ]; } const expandedBody = (snapshot2, entry, width) => [ ...fieldsFor(snapshot2), ...blocksFor( snapshot2, entry.provider.supportsLogTail === true, width ).flatMap((block) => [block.label, ...block.rows]) ]; const widthCap = Math.max(0, Math.floor(options.width())); const heightCap = Math.max(0, Math.floor(options.height())); const openingWidth = Math.min( widthCap, Math.max( 4, ...openingDetails.flatMap(({ entry, detail: detail2 }) => [ options.measure(singleLine(detail2.title)) + 5, options.measure( hintFor( entry, expandedBody(detail2, entry, Math.max(1, widthCap - 4)).length > heightCap - 3 ) ) + 4, ...expandedBody(detail2, entry, Number.MAX_SAFE_INTEGER).map( (row) => options.measure(row) + 4 ) ]) ) ); const frameText = { clip: options.clip, pad: options.pad, measure: options.measure }; const openingHeight = Math.min( heightCap, Math.max( 2, ...openingDetails.map(({ entry, detail: detail2 }) => { const body = (innerWidth) => [ ...expandedBody(detail2, entry, innerWidth), hintFor(entry, false) ]; return renderPanelCard({ title: singleLine(detail2.title), body, width: openingWidth, theme: options.theme, text: frameText }).length; }) ) ); tick(); return { get width() { return Math.min(openingWidth, options.width()); }, get focused() { return focused; }, set focused(value3) { const lostFocus = focused && !value3; focused = value3; if (lostFocus && !closed) void Promise.resolve().then(() => { if (!closed && !focused) options.onFocusLost(); }); }, render(width) { if (closed) return []; refreshDetail(); if (!detail || closed) return []; width = Math.max(0, Math.floor(width)); if (!width) return []; const kit = getRenderKit(); const fg = (role, text) => kit ? kit.fg(options.theme, role, text) : options.theme.fg(role, text); const heading = (title) => fg( "accent", options.theme.bold?.(singleLine(title)) ?? singleLine(title) ); const snapshot2 = detail; const budget = Math.max( 0, Math.min(openingHeight, Math.floor(options.height())) ); const body = (innerWidth) => { foldTarget = void 0; if (budget < 3) return []; const detail2 = snapshot2; innerWidth = Math.max(1, innerWidth); const lines = fieldsFor(detail2, fg); const entry = options.selected(); const tail = entry?.provider.supportsLogTail === true; const blocks = blocksFor(detail2, tail, innerWidth, fg); const evidenceRows = blocks.at(-1)?.rows ?? []; const available = Math.max(0, budget - 3); const metadataRows = lines.length; let evidenceCollapsed = false; const reservedRows = blocks.reduce( (sum, block) => sum + Math.min(2, block.rows.length + 1), 0 ); for (const block of blocks) { const otherRows = reservedRows - Math.min(2, block.rows.length + 1); const foldable = block.rows.length + 1 > Math.max(1, available - metadataRows - otherRows); const isExpanded = !foldable || (expanded.get(block.id) ?? block.defaultExpanded); if (foldable && !foldTarget) { foldTarget = block.id; foldExpanded = isExpanded; } if (isExpanded) lines.push(heading(block.label), ...block.rows); else { const previewWidth = Math.max( 0, innerWidth - options.measure(block.label) - options.measure( ` ${resolveIcon("separator", "\xB7")} ${resolveIcon("separator", "\xB7")} folded` ) ); lines.push( `${heading(block.label)}${fg("dim", ` ${resolveIcon("separator", "\xB7")} `)}${fg("text", options.clip(block.preview, previewWidth))}${fg("dim", ` ${resolveIcon("separator", "\xB7")} folded`)}` ); if (block.id === EVIDENCE) evidenceCollapsed = true; } } const headerRows = lines.length - (evidenceCollapsed ? 1 : evidenceRows.length + 1); const hint = hintFor(entry, foldTarget !== void 0); let content = lines.slice(0, available); if (tail && !evidenceCollapsed && lines.length > available && available) { const headCount = Math.min(headerRows, Math.max(0, available - 2)); const tailCount = available - headCount; content = [ ...lines.slice(0, headCount), ...tailCount > 1 ? [heading(detail2.evidence.label)] : [], ...evidenceRows.slice(-(tailCount > 1 ? tailCount - 1 : tailCount)) ]; } return [ ...content, ...Array(Math.max(0, available - content.length)).fill(""), fg("dim", hint) ]; }; return renderPanelCard({ title: singleLine(detail.title), body, width, maxHeight: budget, theme: options.theme, text: frameText }); }, handleInput(data) { if (closed) return; if (options.matches(data, "escape") || options.matches(data, "left") || options.matches(data, "right")) { dismiss(); return; } if (options.matches(data, "up") || options.matches(data, "down")) { options.clearCloseArm(); const rows = options.rows(); const index = rows.findIndex( (entry) => entry.key === options.selected()?.key ); const next = rows[Math.max( 0, Math.min( rows.length - 1, index + (options.matches(data, "up") ? -1 : 1) ) )]; if (next) options.select(next); tick(); } else if (data === "x" || data === "X") { const entry = options.selected(); if (entry) options.closeItem(entry); refreshDetail(); } else if (options.matches(data, "enter") && foldTarget) { foldExpanded = !foldExpanded; expanded.set(foldTarget, foldExpanded); } else if ((data === "l" || data === "L") && options.selected()?.provider.supportsLogTail) { logTailLines = logTailLines === 25 ? 10 : 25; refreshDetail(); } else return; options.requestRender(); }, invalidate() { }, dispose, dismiss }; } // ../pi-core/src/work-panel-lifecycle.ts var CANDIDATE_LIMIT = 4; function isBusy(ctx) { return typeof ctx.isIdle === "function" && !ctx.isIdle(); } function notify(key3) { for (const listener of workPanelRegistry()?.lifecycle.listeners.get(key3) ?? []) listener(); } function lifecycle(ctx) { const sessions = workPanelRegistry()?.lifecycle.sessions; if (!sessions) return void 0; const key3 = ctx.sessionManager; const sessionId = key3.getSessionId(); let current = sessions.get(key3); if (current?.sessionId !== sessionId) { current?.dispose?.(); current = { sessionId, state: { epoch: 0, epochStartedAt: Date.now(), busy: isBusy(ctx) }, candidates: [] }; sessions.set(key3, current); } return current; } function getWorkPanelLifecycle(ctx) { const current = lifecycle(ctx); return current ? { ...current.state } : { epoch: 0, epochStartedAt: Date.now(), busy: isBusy(ctx) }; } function onWorkPanelLifecycleChanged(ctx, listener) { const state = workPanelRegistry()?.lifecycle; if (!state) return () => { }; const key3 = ctx.sessionManager; const listeners = state.listeners.get(key3) ?? /* @__PURE__ */ new Set(); state.listeners.set(key3, listeners); listeners.add(listener); return () => { listeners.delete(listener); if (!listeners.size) state.listeners.delete(key3); }; } function bindWorkPanelLifecycle(pi, ctx) { const state = workPanelRegistry()?.lifecycle; const current = lifecycle(ctx); if (!state || !current || current.dispose) return () => { }; const key3 = ctx.sessionManager; const removers = []; let disposed = false; const dispose = () => { if (disposed) return; disposed = true; for (const remove of removers.splice(0)) remove(); current.candidates.length = 0; current.dispose = void 0; if (state.sessions.get(key3) === current) state.sessions.delete(key3); notify(key3); }; current.dispose = dispose; const active = (eventCtx) => { if (disposed || eventCtx.sessionManager !== key3) return false; if (key3.getSessionId() !== current.sessionId) { dispose(); return false; } return true; }; const refreshBusy = (_event, eventCtx) => { if (!active(eventCtx)) return; current.state = { ...current.state, busy: isBusy(eventCtx) }; notify(key3); }; removers.push( pi.on("input", (event, eventCtx) => { if (!active(eventCtx) || !["interactive", "rpc"].includes(event.source) || !eventCtx.isIdle() || !event.text.trim()) return; current.candidates.push(event.text); current.candidates = current.candidates.slice(-CANDIDATE_LIMIT); }), pi.on("before_agent_start", (event, eventCtx) => { if (!active(eventCtx) || !("prompt" in event)) return; const index = current.candidates.indexOf(event.prompt); if (index < 0) return; current.candidates.splice(index, 1); current.state = { ...current.state, epoch: current.state.epoch + 1, epochStartedAt: Date.now() }; notify(key3); }), pi.on("agent_start", refreshBusy), pi.on("agent_settled", refreshBusy), pi.on("session_start", (_event, eventCtx) => { active(eventCtx); }), pi.on("session_shutdown", (_event, eventCtx) => { if (eventCtx.sessionManager !== key3) return; try { settleOwnedOverlays(eventCtx); } finally { dispose(); } }) ); return dispose; } // ../pi-core/src/work-panel-host.ts var WIDGET_KEY = "thoth-work-panel"; var CLOSE_KEY = "thoth-work-panel-close"; var CLOSE_ARM_MS = 3e3; function createWorkPanelHost(ctx, providers, onDispose) { let agent; let toolkit; let primitives; let loaded = false; let disposed = false; let installed = false; let requestRender; let requestProviderRender; let slot; let removeLifecycle; let tui; let focused = false; let selectedKey; let closeArm; let closeTimer; let suspended = false; let dismissDetail; let retentionTimer; let removeAnimation; let animationFrame = 0; let providerDirty = false; let statusCue; let panelWidth; let panelTui; const editorOccupied = () => { const liveTui = panelTui ?? tui; return liveTui ? isEditorReplaced(liveTui) : false; }; const panelBudget = () => Math.min( 12, Math.max( 0, Math.floor((panelTui?.terminal.rows ?? tui?.terminal.rows ?? 24) / 2) ) ); function refreshStatusCue(count, force = false) { const next = count > 0 && !focused && !suspended && !editorOccupied() ? `${resolveIcon("arrowLeft", "\u2190")} work ${resolveIcon("separator", "\xB7")} ${count}` : void 0; if (!force && next === statusCue) return; statusCue = next; ctx.ui.setStatus(WIDGET_KEY, next); } const clip2 = (text, width) => toolkit?.truncateToWidth( text, Math.max(0, width), resolveIcon("ellipsis", "...") ) ?? [...text].slice(0, Math.max(0, width)).join(""); const measure = (text) => primitives?.panelVisibleWidth(text) ?? toolkit?.visibleWidth(text) ?? [...text].length; const pad = (text, width) => { const clipped = clip2(text, width); const cells = measure(clipped); if (primitives && cells <= width && !/[\r\n\t]/.test(clipped)) return primitives.padPanelText(clipped, width); return clipped + " ".repeat(Math.max(0, width - cells)); }; const sections = () => { const absorbed = new Set(getUIPreferences().absorbedWorkPanelSources); return panelSections( providers().filter((provider) => !absorbed.has(provider.id)), Date.now(), getWorkPanelLifecycle(ctx) ); }; function rows() { const current = sections(); const overflow = current.some(({ provider }) => provider.selectableSummary) ? panelOverflowEntries( current, panelWidth ?? panelTui?.terminal.columns ?? tui?.terminal.columns ?? 100, Date.now(), panelBudget(), focused ? selectedKey : void 0, measure ) : /* @__PURE__ */ new Map(); const all = current.flatMap((section) => [ ...section.rows.filter( ({ row }) => !row.compact?.completedSummary || !overflow.get(section.provider.id)?.length ), ...overflow.get(section.provider.id) ?? [] ]).filter(isSelectablePanelRow); if (!all.some((entry) => entry.key === selectedKey)) selectedKey = all[0]?.key; if (!all.length) releaseFocus(); return all; } const selected = () => rows().find((entry) => entry.key === selectedKey); function clearCloseArm() { if (closeTimer) clearTimeout(closeTimer); closeTimer = void 0; if (!closeArm) return; closeArm = void 0; ctx.ui.setStatus(CLOSE_KEY, void 0); } function releaseFocus() { focused = false; clearCloseArm(); } function handleClose(entry) { const label = panelCloseLabel(entry); if (!label) return; const now = Date.now(); if (closeArm?.key === entry.key && now >= closeArm.at && now < closeArm.at + CLOSE_ARM_MS) { clearCloseArm(); safely(() => entry.provider.close(entry.row.id), void 0); refreshNow(); return; } clearCloseArm(); closeArm = { key: entry.key, at: now }; ctx.ui.setStatus( CLOSE_KEY, `Press x again to ${label} ${singleLine(entry.row.name ?? entry.row.primary)}` ); closeTimer = setTimeout(() => { clearCloseArm(); refreshNow(); }, CLOSE_ARM_MS); closeTimer.unref?.(); } const matches = (data, key3) => matchesPanelKey(data, key3, toolkit?.matchesKey); function sourceRows(provider) { const now = Date.now(); const parent = safely(() => provider.parentRow?.(now), void 0); return [ ...parent ? [{ row: parent, parent: true }] : [], ...safely(() => provider.listRows(now), []).map((row) => ({ row, parent: false })) ].map((entry) => ({ ...entry, provider, key: JSON.stringify([provider.id, entry.row.id]), sectionSummary: entry.row.summary && provider.selectableSummary })); } function open(entry, liveCtx = ctx, includeHidden = false) { if (disposed || !installed || suspended || entry.sectionSummary && !entry.provider.openHistory) return Promise.resolve("unavailable"); suspended = true; const sectionRows = () => includeHidden ? sourceRows(entry.provider).filter((entry2) => !entry2.row.summary) : rows().filter( (row) => row.provider.id === entry.provider.id && !row.sectionSummary ); const sectionSelected = () => { const all = sectionRows(); const current = all.find((row) => row.key === selectedKey) ?? all[0]; if (current) selectedKey = current.key; return current; }; let detailComponent; let detailFinished = false; const show = () => { if (entry.sectionSummary) return entry.provider.openHistory?.(liveCtx); if (entry.provider.open) return entry.provider.open(entry.row.id, liveCtx); return openOwnedOverlay( liveCtx, (detailTui, theme, _keybindings, close) => { const component = createWorkPanelDetail({ rows: sectionRows, selected: sectionSelected, select(next) { selectedKey = next.key; refreshNow(); }, closeItem: handleClose, clearCloseArm, done: () => { try { close(); } finally { finished(); } }, onFocusLost: () => { if (detailTui.getFocusedComponent?.() !== component) component.dismiss(); }, requestRender: () => detailTui.requestRender(), theme, height: () => Math.max(0, Math.floor(detailTui.terminal.rows * 0.8)), width: () => Math.min(100, Math.floor(detailTui.terminal.columns * 0.9)), clip: clip2, pad, wrap: (text, width) => toolkit?.wrapTextWithAnsi(text, Math.max(1, width)) ?? text.split(/\r?\n/), measure, matches }); detailComponent = component; dismissDetail = () => component.dismiss(); return component; }, { overlayOptions: () => ({ width: detailComponent?.width ?? 0, maxHeight: "80%", anchor: "center" }) } ); }; const finished = () => { if (detailFinished) return; detailFinished = true; suspended = false; dismissDetail = void 0; safely(releaseFocus, void 0); safely(refreshNow, void 0); }; try { releaseFocus(); refreshNow(); return Promise.resolve(show()).then( () => { finished(); return "ok"; }, () => { finished(); return "unavailable"; } ); } catch { finished(); return Promise.resolve("unavailable"); } } function rootEditorInputActive() { return !disposed && !suspended && slot?.isRootEditorInputActive() === true; } function handleInput(data) { if (editorOccupied() || !rootEditorInputActive() || ctx.ui.getEditorText?.() !== "") { if (focused) { releaseFocus(); refreshNow(); } return void 0; } const all = rows(); if (!all.length) return void 0; if (!focused) { if (!matches(data, "left")) return void 0; focused = true; } else if (matches(data, "up") || matches(data, "down")) { clearCloseArm(); const index = all.findIndex((entry) => entry.key === selectedKey); selectedKey = all[Math.max( 0, Math.min(all.length - 1, index + (matches(data, "up") ? -1 : 1)) )]?.key; } else if (matches(data, "escape") || matches(data, "right")) { releaseFocus(); } else if (matches(data, "enter")) { const entry = selected(); if (entry?.sectionSummary && !entry.provider.openHistory) return void 0; if (entry) void open(entry); } else if (data === "x" || data === "X") { const entry = selected(); if (entry?.sectionSummary) return void 0; if (entry) handleClose(entry); } else return void 0; refreshNow(); return { consume: true }; } function stopRetentionTimer() { if (retentionTimer) clearTimeout(retentionTimer); retentionTimer = void 0; } function scheduleRender() { stopRetentionTimer(); const now = Date.now(); let delay = Infinity; let animating = false; for (const { provider, rows: rows2 } of sections()) { if (rows2.some( ({ row }) => ["running", "in_progress"].includes(workPanelRenderStatus(row)) )) { animating = true; } for (const { row } of rows2) { const expiresAt = provider.retention === "prompt" ? panelLingerEndsAt(row) : row.expiresAt; if (expiresAt !== void 0 && expiresAt > now) delay = Math.min(delay, expiresAt - now); } } if (animating) { removeAnimation ??= subscribeAnimationSteps({ kind: "secondary", intendedMs: WORK_PANEL_ANIMATION_INTERVAL_MS, onStep(step) { if (!step.static) animationFrame++; if (providerDirty) refreshNow(true); else { scheduleRender(); requestRender?.(); } } }); } else { removeAnimation?.(); removeAnimation = void 0; } if (Number.isFinite(delay)) { retentionTimer = setTimeout(refreshNow, delay); retentionTimer.unref?.(); } } function refreshNow(providerChange = false) { if (disposed) return; if (!installed && loaded && providers().length) install(); if (!installed) return; providerDirty = false; const count = rows().length; scheduleRender(); refreshStatusCue(count, !providerChange); if (providerChange && !suspended) requestProviderRender?.(); else requestRender?.(); } const host = { supportsUIPreferences: true, sessionId: ctx.sessionManager.getSessionId(), holders: 0, ready: Promise.resolve(), isRootEditorInputActive: () => installed ? rootEditorInputActive() : void 0, invokeAction(liveCtx, provider, rowId, action) { if (disposed || !installed || suspended || !safely( () => action === "close" || liveCtx.hasUI && liveCtx.mode === "tui" && typeof liveCtx.ui.custom === "function", false )) return Promise.resolve("unavailable"); if (action === "history") { return open( { provider, row: { id: "history", primary: provider.label, summary: true }, key: JSON.stringify([provider.id, null]), sectionSummary: true }, liveCtx ); } const entry = sourceRows(provider).find(({ row }) => row.id === rowId); if (!entry) return Promise.resolve("missing"); if (!isSelectablePanelRow(entry)) return Promise.resolve("unavailable"); if (action === "open") { selectedKey = entry.key; return open(entry, liveCtx, true); } if (action !== "close" || !panelCloseLabel(entry)) return Promise.resolve("unavailable"); clearCloseArm(); const result = safely(() => { provider.close(entry.row.id); return "ok"; }, "unavailable"); refreshNow(); return Promise.resolve(result); }, refresh() { if (disposed) return; if (removeAnimation && isAnimationEffectEnabled("secondary")) providerDirty = true; else refreshNow(true); }, dispose() { if (disposed) return; disposed = true; releaseFocus(); stopRetentionTimer(); removeAnimation?.(); removeAnimation = void 0; dismissDetail?.(); slot?.dispose(); removeLifecycle?.(); removePreferences(); removeLevel(); if (installed) { ctx.ui.setStatus(WIDGET_KEY, void 0); } onDispose(); } }; function install() { if (disposed || workPanelRegistry(false)?.hosts.get(ctx.sessionManager) !== host || !providers().length) return; const DefaultEditor = agent?.CustomEditor; const defaultFactory = DefaultEditor ? (liveTui, theme, keybindings) => new DefaultEditor(liveTui, theme, keybindings, { embedWorkingStatus: true }) : void 0; slot = registerEditorSlot( ctx, { key: WIDGET_KEY, handleInput, aboveEditor: (widgetTui, theme) => { panelTui = widgetTui; requestRender = () => widgetTui.requestRender(); let renderedLines; let renderedStatusCue; let occupied = false; let renderedOccupied; const render = (width) => { panelWidth = width; occupied = editorOccupied(); if (occupied) { releaseFocus(); refreshStatusCue(0); return renderPanel(sections(), width, Date.now(), theme, clip2, { summary: true }); } refreshStatusCue(rows().length); const entry = selected(); const label = panelCloseLabel(entry); return renderPanel(sections(), width, Date.now(), theme, clip2, { measure: primitives?.panelVisibleWidth ?? toolkit?.visibleWidth, selectedKey: focused ? selectedKey : void 0, budget: panelBudget(), animationFrame, hint: focused ? [ !entry?.sectionSummary || rows().length > 1 ? `${resolveIcon("arrowUp", "\u2191")}${resolveIcon("arrowDown", "\u2193")} move` : "", entry?.sectionSummary ? entry.provider.openHistory ? entry.provider.retention === "prompt" ? "Enter history" : "Enter open" : "" : "Enter open", label ? `x ${label}` : "", "Esc back" ].filter(Boolean).join(` ${resolveIcon("separator", "\xB7")} `) : `${resolveIcon("arrowLeft", "\u2190")} interact` }); }; requestProviderRender = () => { const lines = render(panelWidth ?? widgetTui.terminal.columns); const changed = renderedOccupied !== occupied || renderedStatusCue !== statusCue || renderedLines?.length !== lines.length || lines.some((line, index) => line !== renderedLines?.[index]); renderedLines = lines; renderedStatusCue = statusCue; renderedOccupied = occupied; if (changed) requestRender?.(); }; return { render(width) { renderedLines = render(width); renderedStatusCue = statusCue; renderedOccupied = occupied; return renderedLines; }, invalidate() { } }; } }, defaultFactory ); if (!slot) return; tui = slot.tui; installed = true; } const removeLevel = subscribeAnimationLevel(() => refreshNow()); const removePreferences = subscribeUIPreferences(refreshNow); removeLifecycle = onWorkPanelLifecycleChanged(ctx, refreshNow); host.ready = (async () => { [agent, toolkit, primitives] = await Promise.all([ import("@earendil-works/pi-coding-agent").catch(() => void 0), import("@earendil-works/pi-tui").catch(() => void 0), Promise.resolve().then(() => (init_panel_primitives(), panel_primitives_exports)).catch(() => void 0) ]); loaded = true; refreshNow(); })().catch(() => { host.dispose(); }); return host; } // ../pi-core/src/work-panel.ts function notifyRegistry(id) { for (const listener of [...workPanelRegistry(false)?.listeners ?? []]) safely(() => listener(id), void 0); } function refresh() { for (const host of workPanelRegistry()?.hosts.values() ?? []) host.refresh(); } function isWorkPanelRootEditorInputActive(ctx) { const host = workPanelRegistry(false)?.hosts.get(ctx?.sessionManager); if (!host || host.sessionId !== ctx.sessionManager.getSessionId()) return void 0; return host.isRootEditorInputActive(); } function registerWorkPanelProvider(owner, provider) { if (provider.version !== WORK_PANEL_VERSION) return () => { }; const state = workPanelRegistry(); if (!state) return () => { }; const previous = state.providers.get(provider.id); safely(() => previous?.unsubscribe?.(), void 0); safely(() => previous?.removeShutdown?.(), void 0); const revision = (state.revisions.get(provider.id) ?? 0) + 1; state.revisions.set(provider.id, revision); const registration2 = { provider, revision }; state.providers.set(provider.id, registration2); if ("on" in owner) { registration2.removeShutdown = owner.on( "session_shutdown", (_event, ctx) => { const host = state.hosts.get(ctx.sessionManager); host?.dispose(); } ); } notifyRegistry(provider.id); if (state.providers.get(provider.id) !== registration2) return () => { }; registration2.unsubscribe = safely( () => provider.onVisibleChanged?.(() => { if (state.providers.get(provider.id) !== registration2) return; registration2.revision += 1; state.revisions.set(provider.id, registration2.revision); notifyRegistry(provider.id); refresh(); }), void 0 ); if (state.providers.get(provider.id) !== registration2) { safely(() => registration2.unsubscribe?.(), void 0); return () => { }; } refresh(); let removed = false; return () => { if (removed) return; removed = true; if (state.providers.get(provider.id) !== registration2) return; state.providers.delete(provider.id); safely(() => registration2.unsubscribe?.(), void 0); safely(() => registration2.removeShutdown?.(), void 0); notifyRegistry(provider.id); if (!state.providers.size) { for (const host of [...state.hosts.values()]) host.dispose(); } else refresh(); }; } async function ensureWorkPanel(ctx) { if (!ctx.hasUI || ctx.mode !== "tui") return () => { }; const state = workPanelRegistry(); if (!state) return () => { }; const key3 = ctx.sessionManager; const sessionId = ctx.sessionManager.getSessionId(); let host = state.hosts.get(key3); if (host && host.sessionId !== sessionId) { host.dispose(); host = void 0; } if (!host) { host = createWorkPanelHost( ctx, () => [...state.providers.values()].map(({ provider }) => provider), () => { if (state.hosts.get(key3) === host) state.hosts.delete(key3); } ); state.hosts.set(key3, host); } const held = host; held.holders += 1; await held.ready; let released = false; return () => { if (released) return; released = true; held.holders -= 1; if (!held.holders) held.dispose(); }; } // src/atelier-metadata.ts import { createHash } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; var ATELIER_METADATA_ENTRY = "pi-atelier:subagent-metadata"; function safeString(value3) { return typeof value3 === "string" && value3.trim().length > 0 ? value3 : void 0; } function finiteNonNegative(value3) { return typeof value3 === "number" && Number.isFinite(value3) && value3 >= 0; } function numericTimestamp(value3) { return typeof value3 === "number" && Number.isFinite(value3) && value3 >= 0; } function normalizeSessionFile(value3) { const file = safeString(value3); return file ? path.resolve(file) : void 0; } function captureAtelierSessionOwner(ctx) { let sessionId; let sessionFile; try { sessionId = safeString(ctx?.sessionManager?.getSessionId?.()) ?? safeString(ctx?.sessionId); } catch { sessionId = safeString(ctx?.sessionId); } try { sessionFile = normalizeSessionFile(ctx?.sessionManager?.getSessionFile?.()); } catch { sessionFile = void 0; } const ownerId = sessionId ?? sessionFile; return ownerId ? { sessionId: ownerId, ...sessionFile ? { sessionFile } : {} } : void 0; } function artifactRootFor(owner, cwd) { return owner.sessionFile ? path.join(path.dirname(owner.sessionFile), "subagent-artifacts") : path.join(path.resolve(cwd), ".pi", "subagents", "artifacts"); } function runIdFor(taskId2, owner) { const hash = createHash("sha256").update(`${owner.sessionId}\0${taskId2}`).digest("hex").slice(0, 32); return `subagent_${hash}`; } function sanitizedMessage(message) { const usage = message.usage; const safeUsage = {}; for (const key3 of [ "input", "output", "cacheRead", "cacheWrite", "totalTokens" ]) { if (finiteNonNegative(usage?.[key3])) safeUsage[key3] = usage[key3]; } if (finiteNonNegative(usage?.cost?.total)) safeUsage.cost = { total: usage.cost.total }; return { role: "assistant", ...typeof message.timestamp === "number" || typeof message.timestamp === "string" ? { timestamp: message.timestamp } : {}, usage: safeUsage }; } function messageIdentity(message, safeMessage2) { if (message.id) return `id:${message.id}`; if (message.timestamp !== void 0) return `timestamp:${JSON.stringify([message.timestamp, safeMessage2.usage])}`; return void 0; } var AtelierMetadataWriter = class { constructor(options = {}) { this.options = options; } options; createRun(input) { if (!input.owner?.sessionId) return void 0; const root = this.options.artifactRoot ?? artifactRootFor(input.owner, input.cwd); return new AtelierMetadataRun({ taskId: input.taskId, owner: input.owner, artifactRoot: root, appendEntry: this.options.appendEntry, getCurrentOwner: this.options.getCurrentOwner }); } }; var AtelierMetadataRun = class { runId; asyncDir; statusPath; eventsPath; owner; steps = []; stepUsage = /* @__PURE__ */ new Map(); availableMetadataPaths = /* @__PURE__ */ new Set(); appendEntry; getCurrentOwner; state = "queued"; startedAt = Date.now(); referenceDirty = true; statusAvailable = false; constructor(input) { this.owner = input.owner; this.runId = runIdFor(input.taskId, input.owner); this.asyncDir = path.join(input.artifactRoot, this.runId); this.statusPath = path.join(this.asyncDir, "status.json"); this.eventsPath = path.join(this.asyncDir, "events.jsonl"); this.appendEntry = input.appendEntry; this.getCurrentOwner = input.getCurrentOwner; this.loadStatus(); this.writeStatus(); } beginStep(input) { const index = this.steps.length; const startedAt = numericTimestamp(input.startedAt) ? input.startedAt : Date.now(); this.steps.push({ agent: input.agent, status: "running", startedAt }); this.stepUsage.set(index, { totals: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, complete: { input: true, output: true, cacheRead: true, cacheWrite: true }, cost: 0, costComplete: true, messages: 0, seen: /* @__PURE__ */ new Set(), model: safeString(input.model) }); if (index === 0) this.startedAt = startedAt; const metadataPath = this.metadataPath(input.agent, index); this.referenceDirty = true; this.writeStatus(); return { index, metadataPath }; } recordAssistantMessage(stepIndex, agent, message, observedAt = Date.now()) { const step = this.steps[stepIndex]; const usage = this.stepUsage.get(stepIndex); if (!step || !usage || step.agent !== agent || message.role !== "assistant") return; const safeMessage2 = sanitizedMessage(message); const identity = messageIdentity(message, safeMessage2); if (identity && usage.seen.has(identity)) return; if (identity) usage.seen.add(identity); usage.messages += 1; for (const key3 of ["input", "output", "cacheRead", "cacheWrite"]) { const value3 = message.usage?.[key3]; if (finiteNonNegative(value3)) usage.totals[key3] += value3; else usage.complete[key3] = false; } const cost = message.usage?.cost?.total; if (finiteNonNegative(cost)) usage.cost += cost; else usage.costComplete = false; try { fs.mkdirSync(this.asyncDir, { recursive: true }); fs.appendFileSync( this.eventsPath, `${JSON.stringify({ type: "message_end", subagentSource: "child", subagentRunId: this.runId, subagentStepIndex: stepIndex, subagentAgent: agent, observedAt: numericTimestamp(observedAt) ? observedAt : Date.now(), message: safeMessage2 })} `, "utf8" ); } catch { } this.writeMetadata(stepIndex, agent, this.metadataPath(agent, stepIndex)); } finishStep(stepIndex, status, input = {}) { const step = this.steps[stepIndex]; const usage = this.stepUsage.get(stepIndex); if (!step) return; step.status = status; if (usage) { usage.model = safeString(input.model) ?? usage.model; if (Number.isFinite(input.exitCode)) usage.exitCode = input.exitCode; this.writeMetadata( stepIndex, step.agent, this.metadataPath(step.agent, stepIndex) ); } this.writeStatus(); } setState(status) { this.state = status; this.writeStatus(); } loadStatus() { try { const raw = JSON.parse( fs.readFileSync(this.statusPath, "utf8") ); if (raw.runId !== this.runId || raw.sessionId !== this.owner.sessionId || !Array.isArray(raw.steps)) return; const recoveredSteps = raw.steps.flatMap((value3) => { if (!value3 || typeof value3 !== "object") return []; const step = value3; if (!safeString(step.agent) || !safeString(step.status) || !numericTimestamp(step.startedAt)) return []; return [ { agent: step.agent, status: step.status, startedAt: step.startedAt } ]; }); this.steps.push(...recoveredSteps); if (safeString(raw.state)) this.state = raw.state; if (numericTimestamp(raw.startedAt)) this.startedAt = raw.startedAt; } catch { } } metadataPath(agent, stepIndex) { const safeAgent = agent.replace(/[^\w.-]/g, "_") || "agent"; return path.join( this.asyncDir, `${this.runId}_${safeAgent}_${stepIndex}_meta.json` ); } writeMetadata(stepIndex, agent, metadataPath) { const usage = this.stepUsage.get(stepIndex); if (!usage || usage.messages === 0) return; const artifactUsage = {}; for (const key3 of ["input", "output", "cacheRead", "cacheWrite"]) { if (usage.complete[key3]) artifactUsage[key3] = usage.totals[key3]; } if (usage.costComplete) artifactUsage.cost = usage.cost; const metadata = { runId: this.runId, agent, usage: artifactUsage, timestamp: Date.now(), ...usage.model ? { model: usage.model } : {}, ...usage.exitCode !== void 0 ? { exitCode: usage.exitCode } : {} }; try { fs.mkdirSync(this.asyncDir, { recursive: true }); fs.writeFileSync( metadataPath, `${JSON.stringify(metadata, null, 2)} `, "utf8" ); this.availableMetadataPaths.add(metadataPath); this.referenceDirty = true; this.syncReference(); } catch { } } writeStatus() { const status = { runId: this.runId, mode: "single", state: this.state, sessionId: this.owner.sessionId, startedAt: this.startedAt, steps: this.steps.map(({ agent, status: stepStatus, startedAt }) => ({ agent, status: stepStatus, startedAt })) }; try { fs.mkdirSync(this.asyncDir, { recursive: true }); fs.writeFileSync( this.statusPath, `${JSON.stringify(status, null, 2)} `, "utf8" ); this.statusAvailable = true; this.syncReference(); } catch { this.statusAvailable = false; } } syncReference() { if (!this.statusAvailable || !this.referenceDirty || !this.appendEntry) return; let current; try { current = this.getCurrentOwner?.(); } catch { return; } if (!current || current.sessionId !== this.owner.sessionId) return; try { this.appendEntry(ATELIER_METADATA_ENTRY, { runIds: [this.runId], paths: [...this.availableMetadataPaths], asyncDirs: [this.asyncDir] }); this.referenceDirty = false; } catch { } } }; // src/config.ts import fs3 from "node:fs"; import { createRequire } from "node:module"; import os2 from "node:os"; import path3 from "node:path"; import { getPackageDir, parseFrontmatter as parseYamlFrontmatter } from "@earendil-works/pi-coding-agent"; // src/debug.ts import fs2 from "node:fs"; import os from "node:os"; import path2 from "node:path"; var DEBUG_CONFIG_CACHE_MS = 1e3; var debugEnabledCache = /* @__PURE__ */ new Map(); function isSubagentsDebugEnabled(cwd) { if (!cwd) return false; try { const agentDir2 = process.env.PI_CODING_AGENT_DIR || path2.join(os.homedir(), ".pi", "agent"); const key3 = JSON.stringify([path2.resolve(cwd), path2.resolve(agentDir2)]); const now = Date.now(); const cached = debugEnabledCache.get(key3); if (cached && now >= cached.checkedAt && now - cached.checkedAt < DEBUG_CONFIG_CACHE_MS) { return cached.enabled; } let enabled = false; try { enabled = readSubagentsConfig(cwd).debug === true; } catch { } debugEnabledCache.set(key3, { enabled, checkedAt: now }); return enabled; } catch { return false; } } var DEBUG_LOG_RELATIVE_PATH = ".pi/subagents-debug.log"; function ensureDebugLogGitignored(root) { try { if (!fs2.existsSync(path2.join(root, ".git"))) return; const gitignorePath = path2.join(root, ".gitignore"); let current = ""; try { current = fs2.readFileSync(gitignorePath, "utf8"); } catch { } const lines = current.split(/\r?\n/).map((line) => line.trim()); if (lines.includes(DEBUG_LOG_RELATIVE_PATH)) return; const prefix = current.length > 0 && !current.endsWith("\n") ? "\n" : ""; fs2.appendFileSync(gitignorePath, `${prefix}${DEBUG_LOG_RELATIVE_PATH} `); } catch { } } function writeSubagentsDebugLog(cwd, scope, data) { const root = cwd ?? process.cwd(); if (!isSubagentsDebugEnabled(root)) return; try { const file = path2.join(root, DEBUG_LOG_RELATIVE_PATH); fs2.mkdirSync(path2.dirname(file), { recursive: true, mode: 448 }); ensureDebugLogGitignored(root); fs2.appendFileSync( file, `${(/* @__PURE__ */ new Date()).toISOString()} ${scope} ${JSON.stringify(data, (_key, value3) => value3 instanceof Error ? { name: value3.name, message: value3.message, stack: value3.stack } : value3).slice(0, 4e3)} ` ); } catch { } } // src/config.ts var DEFAULT_TOOLS = [ "read", "bash", "edit", "write", "grep", "find", "ls", "mem_recall", "mem_get" ]; var OPENAI_FAST_PACKAGE = "@thoth-agents/pi-openai-fast"; var DEFAULT_LIFECYCLE_PASSTHROUGH = [ "@thoth-agents/pi-claude-bridge", "@thoth-agents/pi-antigravity-bridge", "@thoth-agents/pi-junie-bridge", "@thoth-agents/pi-background-tasks", OPENAI_FAST_PACKAGE ]; var DEFAULT_MAX_CONCURRENCY = 5; var DEFAULT_TIMEOUT_MS = 20 * 60 * 1e3; var DEFAULT_TIMEOUT_WARNING_MS = 18e4; var DEFAULT_MAX_TOTAL_TIMEOUT_MS = 36e5; var DEFAULT_MAX_TIMEOUT_EXTENSIONS = 3; var DEFAULT_STALL_TIMEOUT_MS = 4 * 60 * 1e3; var DEFAULT_TOOL_STALL_TIMEOUT_MS = 9e5; var DEFAULT_STALL_SUSPEND_MAX_MS = 15 * 60 * 1e3; var DEFAULT_ASK_TIMEOUT_MS = 10 * 60 * 1e3; var DEFAULT_BACKGROUND_HANDOFF_SHORTCUT = "ctrl+h"; var DEFAULT_HISTORY_PANEL_SHORTCUT = "ctrl+,"; var DEFAULT_HISTORY_DETAIL_RETENTION_DAYS = 14; var DEFAULT_DETAIL_CANCEL_SHORTCUT = "x"; var DEFAULT_RENDER_DEBUG_LOG_PATH = path3.join( os2.tmpdir(), "pi-subagents-render.jsonl" ); function sanitizeTools(tools) { return tools.map(String).filter((tool) => !tool.startsWith("subagent_")); } var AMBIGUOUS_TOOLS_ISSUE = "choose either comma-separated inline tools or a multiline YAML tools list, not both"; function parseInlineTools(value3) { return value3.split(",").map((item) => item.trim().replace(/^['"]|['"]$/g, "")).filter(Boolean); } var DISALLOWED_TOOLS_ISSUE = "disallowed_tools must be a comma-separated string or YAML list of exact tool names (no globs or nested values)"; var UNSUPPORTED_YAML_ISSUE = "agent frontmatter does not support YAML anchors, aliases, merge keys or tags"; var yaml = (() => { try { return createRequire(path3.join(getPackageDir(), "package.json"))( "yaml" ); } catch { return void 0; } })(); function parseDisallowedTools(value3) { if (value3 === void 0 || value3 === "") return []; const names = typeof value3 === "string" ? value3.split(",") : value3; if (!Array.isArray(names) || names.some( (name) => typeof name !== "string" || !/^[a-zA-Z0-9_.:-]+$/.test(name.trim()) )) return void 0; return [...new Set(names.map((name) => name.trim()))]; } function parseYamlMapping(raw) { if (!yaml) throw new Error( "YAML frontmatter validation is unavailable: could not load the host Pi YAML parser; definitions with frontmatter are disabled" ); const document = yaml.parseDocument(raw); yaml.visit(document, (_key, node) => { if (yaml.isAlias(node) || yaml.isNode(node) && (node.anchor || node.tag) || yaml.isPair(node) && yaml.isScalar(node.key) && node.key.value === "<<") throw new Error(UNSUPPORTED_YAML_ISSUE); }); if (document.errors.length) throw document.errors[0]; if (!yaml.isMap(document.contents)) throw new Error("Expected a YAML mapping"); const { frontmatter: data, body } = parseYamlFrontmatter(`--- ${raw} ---`); if (body) throw new Error("Expected the entire YAML frontmatter"); if (!isPlainObject(data)) throw new Error("Expected a YAML mapping"); const denials = document.get("disallowed_tools", true); if (yaml.isScalar(denials) && denials.value === null && denials.source === "") data.disallowed_tools = []; return data; } function validateDefinitionFrontmatter(data) { const issues = []; for (const field2 of [ "name", "description", "effort", "thinking_level", "thinkingLevel" ]) { if (Object.hasOwn(data, field2) && typeof data[field2] !== "string") issues.push(`${field2} must be a YAML string`); } if (Object.hasOwn(data, "model") && typeof data.model !== "string" && !(isPlainObject(data.model) && typeof data.model.provider === "string" && typeof data.model.id === "string")) issues.push( "model must be a string or a mapping with string provider and id" ); if (Object.hasOwn(data, "tools")) { if (typeof data.tools !== "string" && !(Array.isArray(data.tools) && data.tools.every((tool) => typeof tool === "string"))) issues.push( "tools must be a comma-separated string or YAML list of strings" ); else if (typeof data.tools === "string" && parseInlineTools(data.tools).some((tool) => /\s/.test(tool))) issues.push(AMBIGUOUS_TOOLS_ISSUE); } if (Object.hasOwn(data, "skills") && !(Array.isArray(data.skills) && data.skills.every( (skill) => typeof skill === "string" && skill.trim().length > 0 ))) issues.push( "skills must be a YAML list of non-empty names or glob patterns" ); return issues; } function parseFrontmatterWithIssues(text) { const normalized = text.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n"); if (!normalized.startsWith("---")) return { data: {}, body: text, issues: [] }; if (!/^---[^\S\n]*(?:#[^\n]*)?(?:\n|$)/.test(normalized)) return { data: {}, body: text, issues: [ "invalid YAML frontmatter opening; use --- followed only by whitespace or a comment" ] }; const closing = /\n---[^\S\n]*(?:#[^\n]*)?(?=\n|$)/.exec(normalized); if (!closing) return { data: {}, body: text, issues: ["unterminated YAML frontmatter; close it with ---"] }; const raw = normalized.slice(4, closing.index); const body = normalized.slice(closing.index + closing[0].length).replace(/^\n/, ""); try { const data = parseYamlMapping(raw); const issues = validateDefinitionFrontmatter(data); if (typeof data.tools === "string") data.tools = parseInlineTools(data.tools); return { data, body, issues }; } catch (error) { const message = error instanceof Error ? error.message : String(error); return { data: {}, body, issues: [ yaml ? `YAML frontmatter must parse as a mapping with unique keys: ${message}. For a wildcard, quote it: tools: "*"; for values containing ": ", quote the value (e.g. description: "worker: x")` : message ] }; } } function agentDir() { return process.env.PI_CODING_AGENT_DIR || path3.join(os2.homedir(), ".pi", "agent"); } function subagentsConfigPath(dir = agentDir()) { return path3.join(dir, "subagents.json"); } function readJson(file) { try { return JSON.parse(fs3.readFileSync(file, "utf8")); } catch { return {}; } } function isPlainObject(value3) { if (typeof value3 !== "object" || value3 === null || Array.isArray(value3)) return false; const prototype = Object.getPrototypeOf(value3); return prototype === Object.prototype || prototype === null; } function positiveNumber(value3, fallback) { const parsed = Number(value3); return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; } function positiveInteger(value3, fallback) { return Math.max(1, Math.floor(positiveNumber(value3, fallback))); } function parseModel(value3) { if (!value3 || value3 === "default") return void 0; if (typeof value3 === "string") { const separator = value3.indexOf("/"); if (separator === -1) return void 0; const provider = value3.slice(0, separator).trim(); const id = value3.slice(separator + 1).trim(); return provider && id ? { provider, id } : void 0; } if (isPlainObject(value3) && typeof value3.provider === "string" && typeof value3.id === "string") { const provider = value3.provider.trim(); const id = value3.id.trim(); return provider && id ? { provider, id } : void 0; } return void 0; } var THINKING_EFFORTS = /* @__PURE__ */ new Set([ "off", "minimal", "low", "medium", "high", "xhigh", "max" ]); function parseEffort(value3) { if (!value3 || value3 === "default") return void 0; const effort = String(value3).trim().toLowerCase(); return THINKING_EFFORTS.has(effort) ? effort : void 0; } function parseSessionResources(value3) { const resources = String(value3 ?? "lean").trim().toLowerCase(); return resources === "full" ? "full" : "lean"; } function parseLifecyclePassthrough(value3) { if (value3 === void 0) return [...DEFAULT_LIFECYCLE_PASSTHROUGH]; if (!Array.isArray(value3)) { console.warn( "subagents: lifecycle_passthrough must be an array of package names; ignored." ); return []; } const names = value3.filter( (name) => typeof name === "string" ); if (names.length !== value3.length) console.warn( "subagents: non-string lifecycle_passthrough entries ignored." ); if (names.includes("thoth-agents")) console.warn( "subagents: lifecycle_passthrough cannot include thoth-agents (adaptive-root prompt injector); ignored." ); return names.filter((name) => name !== "thoth-agents"); } function parseCtrlShortcut(value3, fallback) { const shortcut = String(value3 ?? fallback).trim().toLowerCase(); return /^(?:ctrl\+(?:[a-z]|,)|ctrl\+shift\+[a-z])$/.test(shortcut) ? shortcut : fallback; } var SHORTCUT_MODIFIERS = /* @__PURE__ */ new Set(["ctrl", "shift", "alt", "super"]); var SHORTCUT_KEYS = /* @__PURE__ */ new Set([ "escape", "esc", "enter", "return", "tab", "space", "backspace", "delete", "insert", "clear", "home", "end", "pageup", "pagedown", "up", "down", "left", "right", "`", "-", "=", "[", "]", "\\", ";", "'", ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+", "|", "~", "{", "}", ":", "<", ">", "?" ]); function parseModifiedShortcut(value3, fallback) { const shortcut = String(value3 ?? fallback).trim().toLowerCase(); const parts = shortcut.split("+"); if (parts.length < 2) return fallback; const key3 = parts.at(-1) ?? ""; const modifiers = parts.slice(0, -1); const hasValidModifiers = modifiers.length > 0 && modifiers.every((modifier) => SHORTCUT_MODIFIERS.has(modifier)); const hasValidKey = /^[a-z0-9]$/.test(key3) || /^f(?:[1-9]|1[0-2])$/.test(key3) || SHORTCUT_KEYS.has(key3); return hasValidModifiers && hasValidKey ? shortcut : fallback; } function parseDetailShortcut(value3) { const shortcut = String(value3 ?? DEFAULT_DETAIL_CANCEL_SHORTCUT).trim().toLowerCase(); if (/^[a-z]$/.test(shortcut)) return shortcut; return /^(?:ctrl\+(?:[a-z]|,)|ctrl\+shift\+[a-z])$/.test(shortcut) ? shortcut : DEFAULT_DETAIL_CANCEL_SHORTCUT; } function parseBackgroundHandoffShortcut(value3) { return parseCtrlShortcut(value3, DEFAULT_BACKGROUND_HANDOFF_SHORTCUT); } function parseBoolean(value3, fallback = false) { if (value3 === void 0 || value3 === null) return fallback; if (typeof value3 === "boolean") return value3; const normalized = String(value3).trim().toLowerCase(); if (["1", "true", "yes", "on"].includes(normalized)) return true; if (["0", "false", "no", "off"].includes(normalized)) return false; return fallback; } function parseRenderDebugPartial(value3) { if (!isPlainObject(value3)) return {}; const partial = {}; if (value3.enabled === true) partial.enabled = true; else if (value3.enabled === false) partial.enabled = false; if (typeof value3.path === "string" && value3.path.trim()) partial.path = value3.path.trim(); return partial; } function parseRenderDebugConfig(globalRaw, projectRaw) { const globalPartial = parseRenderDebugPartial( globalRaw.render_debug ?? globalRaw.renderDebug ); const projectPartial = parseRenderDebugPartial( projectRaw.render_debug ?? projectRaw.renderDebug ); const merged = { ...globalPartial, ...projectPartial }; if (merged.enabled !== true) return void 0; return { enabled: true, path: merged.path ?? DEFAULT_RENDER_DEBUG_LOG_PATH }; } function readSubagentsConfig(cwd) { const globalRaw = readJson(subagentsConfigPath()); const projectRaw = readJson(path3.join(cwd, ".pi", "subagents.json")); const raw = { ...globalRaw, ...projectRaw }; const timeoutMs = positiveInteger(raw.timeout_ms, DEFAULT_TIMEOUT_MS); const stallTimeoutMs = positiveInteger( raw.stall_timeout_ms, DEFAULT_STALL_TIMEOUT_MS ); const warningMs = positiveInteger( raw.timeout_warning_ms, DEFAULT_TIMEOUT_WARNING_MS ); return { timeout_warning_ms: warningMs < timeoutMs ? warningMs : 0, max_total_timeout_ms: Math.max( timeoutMs, positiveInteger(raw.max_total_timeout_ms, DEFAULT_MAX_TOTAL_TIMEOUT_MS) ), max_timeout_extensions: positiveInteger( raw.max_timeout_extensions, DEFAULT_MAX_TIMEOUT_EXTENSIONS ), default_model: parseModel(raw.default_model), default_effort: parseEffort( raw.default_effort ?? raw.default_thinking_level ?? raw.thinkingLevel ), timeout_ms: positiveInteger(raw.timeout_ms, DEFAULT_TIMEOUT_MS), stall_timeout_ms: stallTimeoutMs, tool_stall_timeout_ms: Math.max( stallTimeoutMs, positiveInteger(raw.tool_stall_timeout_ms, DEFAULT_TOOL_STALL_TIMEOUT_MS) ), stall_suspend_max_ms: positiveInteger( raw.stall_suspend_max_ms, DEFAULT_STALL_SUSPEND_MAX_MS ), max_concurrency: positiveInteger( raw.max_concurrency, DEFAULT_MAX_CONCURRENCY ), default_tools: sanitizeTools( Array.isArray(raw.default_tools) ? raw.default_tools.map(String) : DEFAULT_TOOLS ), session_resources: parseSessionResources( raw.session_resources ?? raw.sessionResources ), lean_skills: typeof raw.lean_skills === "boolean" ? raw.lean_skills : true, lifecycle_passthrough: parseLifecyclePassthrough(raw.lifecycle_passthrough), background_handoff_shortcut: parseBackgroundHandoffShortcut( raw.background_handoff_shortcut ?? raw.backgroundHandoffShortcut ), history_detail_retention_days: typeof raw.history_detail_retention_days === "number" && Number.isFinite(raw.history_detail_retention_days) && raw.history_detail_retention_days >= 0 ? raw.history_detail_retention_days : DEFAULT_HISTORY_DETAIL_RETENTION_DAYS, history_panel_shortcut: parseModifiedShortcut( raw.history_panel_shortcut ?? raw.historyPanelShortcut, DEFAULT_HISTORY_PANEL_SHORTCUT ), detail_cancel_shortcut: parseDetailShortcut( raw.detail_cancel_shortcut ?? raw.detailCancelShortcut ), enable_ask_orchestrator: parseBoolean(raw.enable_ask_orchestrator, true), enable_notify_orchestrator: parseBoolean( raw.enable_notify_orchestrator, true ), ask_timeout_ms: Number.isInteger(raw.ask_timeout_ms) && raw.ask_timeout_ms > 0 ? raw.ask_timeout_ms : DEFAULT_ASK_TIMEOUT_MS, enable_continue: parseBoolean( raw.enable_continue ?? raw.enableContinue, false ), debug: parseBoolean(raw.debug, false), render_debug: parseRenderDebugConfig(globalRaw, projectRaw) }; } function resolveEffectiveSubagentMode(input) { return input.invocationMode ?? "background"; } function loadSubagentsFromDir(dir, scope, onBlocked) { if (!fs3.existsSync(dir)) return []; return fs3.readdirSync(dir).filter((f) => f.endsWith(".md")).sort().flatMap((file) => { const filePath = path3.join(dir, file); const name = path3.basename(file, ".md").trim().toLowerCase(); let text; try { text = fs3.readFileSync(filePath, "utf8"); } catch (error) { const message = error instanceof Error ? error.message : String(error); onBlocked?.({ name, filePath, issues: [`could not read definition: ${message}`] }); return []; } const { data, body, issues } = parseFrontmatterWithIssues(text); if (typeof data.name === "string" && data.name.trim().toLowerCase() !== name) issues.push( `name must match the filename identity "${name}"; rename the file to ${data.name.trim()}.md or change name to "${name}"` ); if (issues.length > 0) { onBlocked?.({ name, filePath, issues }); return []; } const disallowedTools = parseDisallowedTools(data.disallowed_tools); if (!disallowedTools) { onBlocked?.({ name, filePath, issues: [DISALLOWED_TOOLS_ISSUE] }); return []; } const description = String(data.description || `${name} subagent`).trim(); const tools = sanitizeTools( Array.isArray(data.tools) ? data.tools.map(String) : [] ); return [ { name, description, filePath, instructions: body.trim(), model: parseModel(data.model), effort: parseEffort( data.effort ?? data.thinking_level ?? data.thinkingLevel ), tools, disallowed_tools: disallowedTools, skills: Array.isArray(data.skills) ? data.skills.map((skill) => skill.trim()) : void 0, scope } ]; }); } function agentsDirSources(cwd) { const globalAgentDir = agentDir(); return [ { scope: "global", kind: "agents", dir: path3.join(globalAgentDir, "agents") }, { scope: "global", kind: "subagents", dir: path3.join(globalAgentDir, "subagents") }, { scope: "project", kind: "agents", dir: path3.join(cwd, ".pi", "agents") }, { scope: "project", kind: "subagents", dir: path3.join(cwd, ".pi", "subagents") } ]; } function blockedSubagentWarning(blocked) { return `Subagent "${blocked.name}" in ${blocked.filePath} has invalid frontmatter: ${blocked.issues.join("; ")}. The subagent was not loaded.`; } function subagentSourceWarnings(cwd) { const warnings = []; const onBlocked = (blocked) => warnings.push(blockedSubagentWarning(blocked)); for (const scope of ["global", "project"]) { const sources = agentsDirSources(cwd).filter( (source) => source.scope === scope ); const agentsSource = sources.find((source) => source.kind === "agents"); const subagentsSource = sources.find( (source) => source.kind === "subagents" ); const agents = loadSubagentsFromDir( agentsSource.dir, agentsSource.scope, onBlocked ); const subagents = loadSubagentsFromDir( subagentsSource.dir, subagentsSource.scope, onBlocked ); const subagentNames = new Map( subagents.map((definition) => [definition.name, definition]) ); for (const agent of agents) { const subagent = subagentNames.get(agent.name); if (!subagent) continue; warnings.push( `Duplicate subagent name "${agent.name}" found in ${scope} agents and subagents directories; using subagents definition (${subagent.filePath}).` ); } } return warnings; } function parseToolOverlay(value3, onInvalid) { if (!isPlainObject(value3)) { onInvalid?.("expected an object with optional add/remove arrays"); return void 0; } const parsePatterns = (key3) => { if (!Object.hasOwn(value3, key3)) return []; const entries = value3[key3]; if (!Array.isArray(entries)) { onInvalid?.(`${key3} must be an array`); return []; } return entries.filter((entry) => { if (typeof entry === "string" && entry.trim() && entry.trim() !== "@active") return true; onInvalid?.(`${key3} contains an invalid tool pattern`); return false; }); }; return { add: parsePatterns("add"), remove: parsePatterns("remove") }; } function readProjectToolOverlays(cwd) { const raw = readJson(path3.join(cwd, ".pi", "subagents.json")); const overlays = /* @__PURE__ */ Object.create(null); const diagnostic = (field2, message) => writeSubagentsDebugLog(cwd, "tool-overlay", { field: field2, message }); if (!isPlainObject(raw) || !Object.hasOwn(raw, "agents")) return overlays; if (!isPlainObject(raw.agents)) { diagnostic("agents", "expected an object"); return overlays; } for (const [name, agent] of Object.entries(raw.agents)) { if (!isPlainObject(agent)) { diagnostic(`agents.${name}`, "expected an object"); continue; } if (!Object.hasOwn(agent, "tools")) continue; const overlay = parseToolOverlay( agent.tools, (message) => diagnostic(`agents.${name}.tools`, message) ); if (overlay) overlays[name] = overlay; } return overlays; } function loadSubagents(cwd) { const { default_tools: defaultTools } = readSubagentsConfig(cwd); const overlays = readProjectToolOverlays(cwd); const byName = /* @__PURE__ */ new Map(); for (const source of agentsDirSources(cwd)) { const blockedNames = /* @__PURE__ */ new Set(); const definitions = loadSubagentsFromDir( source.dir, source.scope, (blocked) => blockedNames.add(blocked.name) ); for (const agent of definitions) { if (!agent.tools.length) agent.tools = [...defaultTools]; if (overlays[agent.name]) agent.toolOverlay = overlays[agent.name]; if (!blockedNames.has(agent.name)) byName.set(agent.name, agent); } for (const name of blockedNames) byName.delete(name); } return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)); } // src/history.ts import fs5 from "node:fs"; import { createRequire as createRequire3 } from "node:module"; import os3 from "node:os"; import path5 from "node:path"; // src/interaction-channel.ts var INTERACTION_CHANNEL_KEY = /* @__PURE__ */ Symbol.for("pi.subagents.interactionChannel"); var INTERACTION_RESPONSE_CHANNEL_KEY = /* @__PURE__ */ Symbol.for( "pi.subagents.interactionResponses" ); function requestRegistry() { const holder = globalThis; const existing = holder[INTERACTION_CHANNEL_KEY]; if (existing instanceof Map) return existing; const registry5 = /* @__PURE__ */ new Map(); holder[INTERACTION_CHANNEL_KEY] = registry5; return registry5; } function responseRegistry() { const holder = globalThis; const existing = holder[INTERACTION_RESPONSE_CHANNEL_KEY]; if (existing instanceof Map) return existing; const registry5 = /* @__PURE__ */ new Map(); holder[INTERACTION_RESPONSE_CHANNEL_KEY] = registry5; return registry5; } function isRecord2(value3) { return typeof value3 === "object" && value3 !== null && !Array.isArray(value3); } function requestIdFrom(value3) { const requestId = value3.requestId ?? value3.request_id; return typeof requestId === "string" && requestId.length > 0 ? requestId : void 0; } function promptFrom(value3) { return isRecord2(value3.prompt) ? value3.prompt : void 0; } function findInteractionRequest(value3, seen) { if (!isRecord2(value3) || seen.has(value3)) return void 0; seen.add(value3); const directRequestId = requestIdFrom(value3); if (value3.type === "interaction_required" && directRequestId) { return { ...value3, type: "interaction_required", requestId: directRequestId, kind: typeof value3.kind === "string" && value3.kind.length > 0 ? value3.kind : "custom", prompt: promptFrom(value3), requester: isRecord2(value3.requester) ? value3.requester : void 0 }; } const handle = value3.handle; if (typeof handle === "string") { const resolved = resolveInteractionRequest(handle); if (resolved) return resolved; } for (const child of Object.values(value3)) { const found = findInteractionRequest(child, seen); if (found) return found; } return void 0; } function interactionRequestFromCandidate(value3) { return findInteractionRequest(value3, /* @__PURE__ */ new Set()); } function resolveInteractionRequest(handle) { return requestRegistry().get(handle)?.payload; } function consumeLatestInteractionRequest(options = {}) { const maxAgeMs = options.maxAgeMs ?? 3e4; const now = Date.now(); const candidates = [...requestRegistry().entries()].map(([handle, published]) => ({ handle, published, timestamp: Date.parse(published.createdAt) })).filter( ({ published, timestamp: timestamp2 }) => Number.isFinite(timestamp2) && now - timestamp2 <= maxAgeMs && (!options.origin || published.payload.origin === options.origin) ).sort((a, b) => b.timestamp - a.timestamp); const latest = candidates[0]; if (!latest) return void 0; requestRegistry().delete(latest.handle); return latest.published.payload; } function publishInteractionResponse(response) { const normalized = { responder: "parent", answeredAt: (/* @__PURE__ */ new Date()).toISOString(), ...response, type: "interaction_response" }; responseRegistry().set(normalized.requestId, normalized); return normalized; } var INTERACTION_TRANSPORT_MARKER = "interaction_required:"; function sanitizeInteractionTransportText(text) { if (!text || !text.includes(INTERACTION_TRANSPORT_MARKER)) return text; return text.replace( /interaction_required:[^\r\n]*/g, "[interaction request hidden]" ); } // src/error-metadata.ts var MESSAGE_LIMIT = 1024; var CODE_LIMIT = 128; var SOURCE_LIMIT = 256; var LAST_ACTIVITY_LIMIT = 512; var DETAILS_KEY_LIMIT = 64; var DETAILS_VALUE_LIMIT = 512; var DETAILS_LIMIT = 16; var ATTEMPTS_LIMIT = 2; var CAUSE_DEPTH_LIMIT = 2; var RETRYABLE_DEFAULTS = { total_timeout: false, stall_timeout: false, cancelled: false, interrupted: false, empty_response_no_tools: false, empty_response_after_tools: false, context_overflow: false, provider_api_error: true, provider_auth_error: false, provider_rate_limit: true, provider_network_error: true, tool_failure: false, fallback_failed: false, unknown_fallback: false, malformed_thrown_value: false, serialization_failure: false, unknown: false }; var CATEGORY_SET = new Set( Object.keys(RETRYABLE_DEFAULTS) ); var PHASE_SET = /* @__PURE__ */ new Set([ "runner_invoke", "runner_session", "assistant_final", "tool_execution", "manager", "user", "serializer" ]); var ROLE_SET = /* @__PURE__ */ new Set(["primary", "fallback"]); function limitCodePoints(value3, limit) { if (value3 === void 0) return void 0; const chars = Array.from(value3); return chars.length > limit ? `${chars.slice(0, Math.max(0, limit - 1)).join("")}\u2026` : value3; } function asciiSafe(value3, limit) { if (!value3) return void 0; const bounded = limitCodePoints(value3.replace(/[^\x20-\x7E]+/g, "_"), limit); return bounded || void 0; } function redactText(value3, limit) { if (!value3) return void 0; let text = sanitizeInteractionTransportText(String(value3)).replace( /\x1b\[[0-?]*[ -/]*[@-~]/g, "" ); text = text.replace( /authorization\s*:\s*bearer\s+[A-Za-z0-9._-]+/gi, "Authorization: [redacted]" ).replace(/bearer\s+[A-Za-z0-9._-]+/gi, "Bearer [redacted]").replace(/\b(sk|pk|rk)-[A-Za-z0-9._-]+\b/g, "[redacted]").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, "[redacted]").replace( /(?:^|\s)(?:\/[A-Za-z0-9._-]+)+/g, (match) => match.replace(/\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*/g, "[redacted]") ).replace( /\b(?:prompt|system prompt|user prompt|prompt text)\s*:[^|\n\r]*/gi, "[redacted]" ).replace(/\b(?:system|user|assistant)\s*:[^|\n\r]*/gi, "[redacted]").replace(/SECRET_FILE_BODY[\w-]*/g, "[redacted]").replace(/file contents?[^|\n\r]*/gi, "[redacted]").replace(/[\x00-\x1F\x7F-\x9F]/g, " ").replace(/\s+/g, " ").trim(); return limitCodePoints(text, limit); } function normalizeCategory(value3) { return typeof value3 === "string" && CATEGORY_SET.has(value3) ? value3 : "unknown"; } function normalizePhase(value3) { return typeof value3 === "string" && PHASE_SET.has(value3) ? value3 : void 0; } function normalizeRole(value3) { return typeof value3 === "string" && ROLE_SET.has(value3) ? value3 : void 0; } function normalizeUsage(value3) { if (!value3 || typeof value3 !== "object") return void 0; const usage = value3; return { input: Number(usage.input ?? 0), output: Number(usage.output ?? 0), cacheRead: Number(usage.cacheRead ?? 0), cacheWrite: Number(usage.cacheWrite ?? 0), cost: Number(usage.cost ?? 0), contextTokens: Number(usage.contextTokens ?? 0), turns: Number(usage.turns ?? 0) }; } function normalizeDetails(value3) { if (!value3 || typeof value3 !== "object" || Array.isArray(value3)) return void 0; const details = {}; for (const [rawKey, rawValue] of Object.entries(value3).slice( 0, DETAILS_LIMIT )) { const key3 = asciiSafe(rawKey, DETAILS_KEY_LIMIT); const text = redactText( typeof rawValue === "string" ? rawValue : JSON.stringify(rawValue), DETAILS_VALUE_LIMIT ); if (!key3 || !text) continue; details[key3] = text; } return Object.keys(details).length ? details : void 0; } function safeMessage(category, details) { switch (category) { case "total_timeout": return details?.timeout_ms ? `timed out after ${details.timeout_ms}ms` : "timed out"; case "stall_timeout": { const budgetMs = details?.stall_budget_ms ?? details?.stall_timeout_ms; const base = details?.stall_suspend_reason && details.stall_suspend_max_ms ? `Subagent stalled during ${limitCodePoints(details.stall_suspend_reason, 32)} for ${limitCodePoints(details.stall_suspend_max_ms, 32)}ms without final response.` : budgetMs ? `Subagent stalled for ${limitCodePoints(budgetMs, 32)}ms without final response.` : "Subagent stalled without final response."; if (!details?.last_session_event_type) return base; const diagnostics = [ ...details.stall_budget_kind && details.stall_budget_ms ? [ `budget=${limitCodePoints(details.stall_budget_kind, 16)}`, `budget_ms=${limitCodePoints(details.stall_budget_ms, 32)}` ] : [], `last_event=${limitCodePoints(details.last_session_event_type, 80)}`, `last_event_age_ms=${limitCodePoints(details.ms_since_last_session_event, 32) ?? "unknown"}`, `active_tools=${limitCodePoints(details.active_tools, 512) ?? "none"}`, `settled_after_last_start=${limitCodePoints(details.settled_after_last_start, 8) ?? "unknown"}`, `outstanding_orchestrator_questions=${limitCodePoints(details.outstanding_orchestrator_questions, 32) ?? "unknown"}` ].join("; "); return redactText(`${base} Diagnostics: ${diagnostics}`, MESSAGE_LIMIT) ?? base; } case "cancelled": return `Subagent cancelled: ${details?.cancel_reason ?? "cancelled"}`; case "interrupted": return `Subagent interrupted: ${details?.interrupt_reason ?? "interrupted"}`; case "empty_response_no_tools": return "Subagent finished without a final response."; case "empty_response_after_tools": return "Subagent completed tool execution but did not produce a final response."; case "fallback_failed": return "Subagent fallback failed."; case "unknown_fallback": return "Subagent fallback unavailable after model failure."; case "serialization_failure": return "Subagent error metadata could not be serialized safely."; default: return category.replace(/_/g, " "); } } function normalizeErrorMetadata(input) { try { return normalizeErrorMetadataInternal(input, 0); } catch { return { version: 1, category: "serialization_failure", message: "Subagent error metadata could not be serialized safely.", retryable: false, phase: "serializer", partial_result_available: false }; } } function normalizeErrorMetadataInternal(input, depth) { const category = normalizeCategory(input?.category); const details = normalizeDetails(input?.details); const message = redactText( typeof input?.message === "string" ? input.message : safeMessage(category, details), MESSAGE_LIMIT ) ?? safeMessage(category, details); const attempts = Array.isArray(input?.attempts) ? input.attempts.slice(0, ATTEMPTS_LIMIT).map((attempt, index) => { const normalized = normalizeErrorMetadataInternal(attempt, depth + 1); const role = normalizeRole(attempt?.role) ?? (index === 0 ? "primary" : "fallback"); return { ...normalized, role }; }) : void 0; const cause = depth < CAUSE_DEPTH_LIMIT && input?.cause ? normalizeErrorMetadataInternal(input.cause, depth + 1) : void 0; return { version: 1, category, message, retryable: typeof input?.retryable === "boolean" ? input.retryable : RETRYABLE_DEFAULTS[category], phase: normalizePhase(input?.phase), code: asciiSafe( typeof input?.code === "string" ? input.code : category, CODE_LIMIT ), role: normalizeRole(input?.role), source: input?.source ? { provider: redactText(input.source.provider, SOURCE_LIMIT), model: redactText(input.source.model, SOURCE_LIMIT), tool: redactText(input.source.tool, SOURCE_LIMIT), operation: redactText(input.source.operation, SOURCE_LIMIT) } : void 0, cause, attempts: attempts?.length ? attempts : void 0, usage_at_failure: normalizeUsage(input?.usage_at_failure), last_activity: redactText(input?.last_activity, LAST_ACTIVITY_LIMIT), partial_result_available: Boolean(input?.partial_result_available), task_id: redactText(input?.task_id, SOURCE_LIMIT), parent_session_id: redactText(input?.parent_session_id, SOURCE_LIMIT), details }; } function deriveErrorString(metadata) { const normalized = normalizeErrorMetadata(metadata); return safeMessage(normalized.category, normalized.details) === "unknown" ? normalized.message : safeMessage(normalized.category, normalized.details); } var CONTEXT_OVERFLOW_PATTERNS = [ /\bcontext_length_exceeded\b/, /\bcontext_overflow\b/, /maximum context length is \d+ tokens\. however, you requested \d+ tokens/, /\bprompt is too long: \d+ tokens > \d+ maximum\b/, /\bthe input token count \(\d+\) exceeds the maximum number of tokens allowed \(\d+\)/ ]; function classifyThrownError(error, context = {}) { const rawMessage = error instanceof Error ? error.message : typeof error === "string" ? error : error && typeof error === "object" && typeof error.message === "string" ? String(error.message) : String(error); const message = rawMessage || "Unknown subagent failure"; const lower = message.toLowerCase(); const nonRetryableApiFailure = lower.includes("prompt-capture:") || lower.includes("mcp tool parameters must be an object schema"); const errorClass = error instanceof Error ? error.constructor.name : typeof error; let category = "unknown"; if (nonRetryableApiFailure) category = "provider_api_error"; else if (!(error instanceof Error) && typeof error !== "string") category = "malformed_thrown_value"; else if (/auth|api key|invalid key|unauthori[sz]ed|forbidden|401|403|credential/.test( lower )) category = "provider_auth_error"; else if (CONTEXT_OVERFLOW_PATTERNS.some((pattern) => pattern.test(lower))) category = "context_overflow"; else if (/rate.?limit|quota|429|too many requests/.test(lower)) category = "provider_rate_limit"; else if (/\b(?:econnreset|enotfound|etimedout|network|socket|connection|timeout|timed out)\b/.test( lower )) category = "provider_network_error"; else if (error instanceof Error) category = "provider_api_error"; return normalizeErrorMetadata({ category, message, retryable: nonRetryableApiFailure ? false : context.retryable, phase: context.phase, source: { provider: context.provider, model: context.model, operation: context.operation }, partial_result_available: false, details: { error_class: errorClass } }); } function classifyAssistantFailure(input) { if (input.stopReason === "error" || input.errorMessage) { return classifyThrownError( new Error(input.errorMessage ?? "Assistant error"), { phase: "assistant_final", provider: input.provider, model: input.model, operation: "session.prompt" } ); } if (input.sawToolActivity) { return normalizeErrorMetadata({ category: "empty_response_after_tools", message: "Subagent completed tool execution but did not produce a final response.", phase: "assistant_final", partial_result_available: false }); } return normalizeErrorMetadata({ category: "empty_response_no_tools", message: "Subagent finished without a final response.", phase: "assistant_final", partial_result_available: false }); } function enrichErrorMetadata(metadata, snapshot2) { return normalizeErrorMetadata({ ...metadata, usage_at_failure: snapshot2.usage_at_failure ?? metadata.usage_at_failure, last_activity: snapshot2.last_activity ?? metadata.last_activity, partial_result_available: snapshot2.partial_result_available ?? metadata.partial_result_available, task_id: snapshot2.task_id ?? metadata.task_id, parent_session_id: snapshot2.parent_session_id ?? metadata.parent_session_id }); } function serializeErrorMetadata(metadata) { try { return JSON.stringify( normalizeErrorMetadata(metadata) ); } catch { return JSON.stringify( normalizeErrorMetadata({ category: "serialization_failure", message: "Subagent error metadata could not be serialized safely.", phase: "serializer", partial_result_available: false }) ); } } function parseErrorMetadata(json) { try { if (typeof json !== "string" || !json.trim()) return void 0; return normalizeErrorMetadata( JSON.parse(json) ); } catch { return void 0; } } function safeErrorMetadataDetails(metadata) { const normalized = normalizeErrorMetadata(metadata); return { version: normalized.version, category: normalized.category, message: normalized.message, retryable: normalized.retryable, phase: normalized.phase, code: normalized.code, source: normalized.source, partial_result_available: normalized.partial_result_available, details: normalized.details }; } var SubagentStructuredError = class extends Error { error_metadata; constructor(metadata) { const normalized = normalizeErrorMetadata(metadata); super(deriveErrorString(normalized)); this.name = "SubagentStructuredError"; this.error_metadata = normalized; } }; // src/thread-view.ts import fs4 from "node:fs"; import { createRequire as createRequire2 } from "node:module"; import path4 from "node:path"; import { pathToFileURL } from "node:url"; // src/render/text-width.ts import { stripTerminalSequences as piStripAnsi, truncateToWidth as piTruncateToWidth, visibleWidth as piVisibleWidth, wrapTextWithAnsi as piWrapTextWithAnsi } from "@earendil-works/pi-tui"; var TERMINAL_ESCAPE_RE = /\u001b\][^\u001b\u0007]*(?:\u001b\\|\u0007)|\u001b\[[0-?]*[ -/]*[@-~]/g; function stripAnsi(text) { if (typeof piStripAnsi === "function") { return piStripAnsi(text); } return text.replace(TERMINAL_ESCAPE_RE, ""); } function visibleWidth2(text) { if (typeof piVisibleWidth === "function") { return piVisibleWidth(text); } return [...stripAnsi(text)].length; } function truncateToWidth2(text, width, ellipsis = "\u2026") { if (width <= 0) return ""; if (typeof piTruncateToWidth === "function") { const result = piTruncateToWidth(text, width, ellipsis); return text.includes("\x1B") ? result : stripAnsi(result); } if (visibleWidth2(text) <= width) return text; const ellWidth = visibleWidth2(ellipsis); if (width <= ellWidth) return ellipsis.slice(0, Math.max(0, width)); const targetWidth = width - ellWidth; let output = ""; let vis = 0; for (let i = 0; i < text.length; ) { if (text[i] === "\x1B") { const match = text.slice(i).match(TERMINAL_ESCAPE_RE); if (match && match.index === 0) { output += match[0]; i += match[0].length; continue; } } const codePoint = text.codePointAt(i); const char = String.fromCodePoint(codePoint); if (vis + 1 > targetWidth) break; output += char; vis += 1; i += char.length; } return `${output}${ellipsis}`; } function wrapLineToWidth(line, width) { const max = Math.max(1, width); if (!line) return [""]; if (typeof piWrapTextWithAnsi === "function") { const result = piWrapTextWithAnsi(line, max); return result.length ? result : [""]; } if (visibleWidth2(line) <= max) return [line]; const tokens = line.match( /\u001b\][^\u001b\u0007]*(?:\u001b\\|\u0007)|\u001b\[[0-?]*[ -/]*[@-~]|[\s\S]/gu ) ?? []; const lines = []; let current = []; let used = 0; let lastBreak = -1; const visibleTokenWidth = (token) => /^\u001b/.test(token) ? 0 : 1; const recompute = () => { used = current.reduce((sum, token) => sum + visibleTokenWidth(token), 0); lastBreak = -1; for (let index = 0; index < current.length; index += 1) if (!/^\u001b/.test(current[index]) && /\s/.test(current[index])) lastBreak = index; }; const pushLine = (tokensToPush) => { const text = tokensToPush.join("").replace(/\s+$/u, ""); lines.push(text); }; for (const token of tokens) { current.push(token); used += visibleTokenWidth(token); if (!/^\u001b/.test(token) && /\s/.test(token)) lastBreak = current.length - 1; if (used <= max) continue; if (lastBreak >= 0) { pushLine(current.slice(0, lastBreak)); current = current.slice(lastBreak + 1); recompute(); continue; } pushLine(current.slice(0, -1)); current = [token]; recompute(); } if (current.length || !lines.length) lines.push(current.join("")); return lines.filter( (entry, index, all) => entry.length > 0 || index === 0 && all.length === 1 ); } // src/thread-view.ts var DEFAULT_TEXT_LIMIT = 4e3; var DEFAULT_MAX_ITEMS = 200; var DEFAULT_RENDER_WIDTH = 100; var require2 = createRequire2(import.meta.url); var injectedPiComponents; var piComponents; function isRecord3(value3) { return typeof value3 === "object" && value3 !== null && !Array.isArray(value3); } function isOptionalString3(value3) { return value3 === void 0 || typeof value3 === "string"; } function isPayload(value3) { if (!isRecord3(value3) || typeof value3.isError !== "boolean" || !Array.isArray(value3.content)) return false; return value3.content.every( (part) => isRecord3(part) && typeof part.type === "string" && isOptionalString3(part.text) && isOptionalString3(part.data) && isOptionalString3(part.mimeType) ); } function isAssistantItem(item) { if (!isRecord3(item.message) || item.message.role !== "assistant" || !Array.isArray(item.message.content)) return false; return item.message.content.every((part) => { if (!isRecord3(part) || typeof part.type !== "string") return false; if (part.type === "text") return typeof part.text === "string"; if (part.type === "thinking") return isOptionalString3(part.text) && isOptionalString3(part.thinking); if (part.type === "toolCall") return typeof part.id === "string" && typeof part.name === "string" && "arguments" in part; return false; }); } function isToolItem(item) { return typeof item.name === "string" && ["pending", "running", "completed", "failed", "partial"].includes( String(item.status) ) && (item.result === void 0 || isPayload(item.result)); } function isToolResultItem(item) { return isPayload(item.result) && isOptionalString3(item.name); } function isBashItem(item) { return typeof item.command === "string" && isOptionalString3(item.output) && (item.exitCode === void 0 || typeof item.exitCode === "number") && (item.status === void 0 || ["running", "completed", "failed", "cancelled"].includes( String(item.status) )); } function isCustomItem(item) { return typeof item.customType === "string" && isOptionalString3(item.fallbackText); } function isThreadItem(value3) { if (!isRecord3(value3) || typeof value3.type !== "string") return false; if (!isOptionalString3(value3.id)) return false; switch (value3.type) { case "attempt": return Number.isInteger(value3.attempt) && Number(value3.attempt) > 0; case "assistant": return isAssistantItem(value3); case "user": return typeof value3.text === "string" && (value3.label === void 0 || [ "delegated_task", "continuation", "context", "prompt", "user", "queued" ].includes(String(value3.label))); case "tool": return isToolItem(value3); case "tool_result": return isToolResultItem(value3); case "bash": return isBashItem(value3); case "custom": return isCustomItem(value3); case "status": return typeof value3.text === "string" && (value3.severity === void 0 || ["info", "success", "warning"].includes(String(value3.severity))); case "error": return typeof value3.text === "string"; default: return false; } } function isValidThreadSnapshot(value3) { return isRecord3(value3) && value3.version === 1 && ["events", "session_messages", "mixed"].includes(String(value3.source)) && isOptionalString3(value3.created_at) && isOptionalString3(value3.updated_at) && Array.isArray(value3.items) && value3.items.every(isThreadItem); } function boundText(text, limit) { if (text === void 0) return void 0; if (text.length <= limit) return text; return `${text.slice(0, Math.max(0, limit - 1))}\u2026`; } function boundUnknown(value3, limit) { if (typeof value3 === "string") return boundText(value3, limit); if (Array.isArray(value3)) return value3.slice(0, 50).map((entry) => boundUnknown(entry, limit)); if (!isRecord3(value3)) return value3; return Object.fromEntries( Object.entries(value3).slice(0, 50).map(([key3, entry]) => [key3, boundUnknown(entry, limit)]) ); } function boundPayload(payload, limit) { return { ...payload, details: boundUnknown(payload.details, limit), preview: boundText(payload.preview, limit), content: payload.content.map((part) => ({ ...part, text: boundText(part.text, limit), data: boundText(part.data, limit) })) }; } function boundItem(item, limit) { switch (item.type) { case "attempt": return item; case "assistant": return { ...item, message: { ...item.message, content: item.message.content.map((part) => { if (part.type === "text") return { ...part, text: boundText(part.text, limit) ?? "" }; if (part.type === "thinking") return { ...part, text: boundText(part.text, limit), thinking: boundText(part.thinking ?? part.text, limit) }; return part; }) } }; case "user": return { ...item, text: boundText(item.text, limit) ?? "" }; case "tool": return { ...item, arguments: boundUnknown(item.arguments, limit), result: item.result ? boundPayload(item.result, limit) : void 0 }; case "tool_result": return { ...item, result: boundPayload(item.result, limit) }; case "bash": return { ...item, command: boundText(item.command, limit) ?? "", output: boundText(item.output, limit) }; case "custom": return { ...item, fallbackText: boundText(item.fallbackText, limit) }; case "status": return { ...item, text: boundText(item.text, limit) ?? "" }; case "error": return { ...item, text: boundText(item.text, limit) ?? "" }; } } function boundThreadSnapshot(value3, options = {}) { if (!isValidThreadSnapshot(value3)) return void 0; const limit = Math.max(1, options.textLimit ?? DEFAULT_TEXT_LIMIT); const maxItems = Math.max(0, options.maxItems ?? DEFAULT_MAX_ITEMS); const items = value3.items.length <= maxItems ? value3.items : maxItems === 0 ? [] : maxItems === 1 ? value3.items.slice(0, 1) : [value3.items[0], ...value3.items.slice(-(maxItems - 1))]; return { ...value3, items: items.map((item) => boundItem(item, limit)) }; } function payloadText(payload) { return payload.preview || payload.content.map((part) => part.text || part.data || "").filter(Boolean).join("\n"); } function jsonPreview(value3, limit = 240) { if (value3 === void 0) return ""; let text; try { text = JSON.stringify(value3); } catch { text = String(value3); } return getRenderKit()?.icon ? truncateToWidth2(text, limit, resolveIcon("ellipsis", "\u2026")) : boundText(text, limit) ?? ""; } function runningPiEntrypoint() { if (!process.argv[1]) return void 0; const resolved = path4.resolve(process.argv[1]); try { return fs4.realpathSync(resolved); } catch { return resolved; } } function findRunningPiPackageRoot() { let current = runningPiEntrypoint(); if (!current) return void 0; if (!fs4.existsSync(current)) return void 0; current = fs4.statSync(current).isDirectory() ? current : path4.dirname(current); while (true) { const packageJson = path4.join(current, "package.json"); if (fs4.existsSync(packageJson)) { try { const parsed = JSON.parse(fs4.readFileSync(packageJson, "utf8")); if (parsed.name === "@earendil-works/pi-coding-agent") return current; } catch { } } const parent = path4.dirname(current); if (parent === current) return void 0; current = parent; } } function registerSubagentExternalToolDefinition(name, definition, owner) { if (!name || !definition) return; const registrations = externalToolDefinitions.get(name) ?? /* @__PURE__ */ new Map(); registrations.delete(owner); registrations.set(owner, definition); externalToolDefinitions.set(name, registrations); toolComponentCacheByTask.clear(); } function withdrawSubagentExternalToolDefinitions(owner) { for (const [name, registrations] of externalToolDefinitions) { registrations.delete(owner); if (registrations.size === 0) externalToolDefinitions.delete(name); } toolComponentCacheByTask.clear(); } function withdrawSubagentExternalToolDefinitionsByIdentity(definitions) { const withdrawn = new Set(definitions); if (withdrawn.size === 0) return; for (const [name, registrations] of externalToolDefinitions) { for (const [owner, definition] of registrations) { if (withdrawn.has(definition)) registrations.delete(owner); } if (registrations.size === 0) externalToolDefinitions.delete(name); } toolComponentCacheByTask.clear(); } function externalToolDefinition(name) { const registrations = externalToolDefinitions.get(name); return registrations ? [...registrations.values()].at(-1) : void 0; } function hasToolRenderer(definition) { return isRecord3(definition) && (typeof definition.renderCall === "function" || typeof definition.renderResult === "function" || definition.renderShell === "self"); } function toolRenderers(definition) { if (!isRecord3(definition) || !hasToolRenderer(definition)) return void 0; const { renderCall, renderResult, renderShell } = definition; return { renderCall, renderResult, renderShell }; } function sourcePathFromToolInfo(info) { if (!isRecord3(info) || !isRecord3(info.sourceInfo)) return void 0; const rawPath = typeof info.sourceInfo.path === "string" ? info.sourceInfo.path : void 0; if (!rawPath || rawPath.startsWith("<")) return void 0; const baseDir = typeof info.sourceInfo.baseDir === "string" ? info.sourceInfo.baseDir : void 0; return path4.isAbsolute(rawPath) ? rawPath : baseDir ? path4.resolve(baseDir, rawPath) : path4.resolve(rawPath); } function createToolCapturePi(captured) { return { registerTool: (tool) => { captured.push(tool); }, registerCommand: () => void 0, registerShortcut: () => void 0, registerFlag: () => void 0, registerMessageRenderer: () => void 0, registerMarkdownTransformer: () => void 0, registerEntryRenderer: () => void 0, on: () => void 0, events: { on: () => void 0, emit: () => void 0 }, getFlag: () => void 0, getActiveTools: () => [], getAllTools: () => [], setActiveTools: () => void 0, sendMessage: () => void 0, sendUserMessage: () => void 0, appendEntry: () => void 0, exec: async () => ({ stdout: "", stderr: "", code: 0, killed: false }) }; } function loadExternalToolSource(sourcePath) { if (externalToolSourcesLoaded.has(sourcePath)) return; externalToolSourcesLoaded.add(sourcePath); if (!fs4.existsSync(sourcePath)) return; const packageRoot = findRunningPiPackageRoot(); if (!packageRoot) return; try { const piRequire = createRequire2(path4.join(packageRoot, "package.json")); const { createJiti } = piRequire("jiti"); const jiti = createJiti(path4.join(packageRoot, "package.json"), { moduleCache: true, interopDefault: true, alias: { "@earendil-works/pi-coding-agent": packageRoot, "@earendil-works/pi-tui": path4.join( packageRoot, "node_modules", "@earendil-works", "pi-tui", "dist", "index.js" ) } }); const mod = jiti(sourcePath); const register = mod?.default ?? mod; if (typeof register !== "function") return; const captured = []; const maybePromise = register(createToolCapturePi(captured)); if (maybePromise && typeof maybePromise.then === "function") return; for (const tool of captured) { if (isRecord3(tool) && typeof tool.name === "string") { externalToolSourceDefinitions.set(tool.name, tool); toolComponentCacheByTask.clear(); } } } catch { } } function resolveSubagentExternalToolDefinitionFromInfo(name, info) { const kit = refreshToolDefinitionCaches(); const published = getPublishedToolDefinition(name); if (published) return published; if (hasToolRenderer(info)) return info; const existing = externalToolDefinition(name) ?? externalToolSourceDefinitions.get(name); if (existing) return existing; if (kit) return void 0; const sourcePath = sourcePathFromToolInfo(info); if (sourcePath) loadExternalToolSource(sourcePath); return externalToolSourceDefinitions.get(name); } function renderableToolDefinition(name, candidates, cwd, kit) { if (kit) { const definition = candidates.find(isRecord3) ?? builtInToolDefinition(name, cwd); const base = isRecord3(definition) ? definition : { name }; const downstream = candidates.find(hasToolRenderer) ?? base; const renderers = kit.resolveToolRenderers ? kit.resolveToolRenderers(name, () => toolRenderers(downstream)) : toolRenderers(downstream); return { ...base, ...renderers }; } for (const candidate of candidates) { if (!candidate) continue; if (hasToolRenderer(candidate)) return candidate; const rehydrated = resolveSubagentExternalToolDefinitionFromInfo( name, candidate ); if (hasToolRenderer(rehydrated)) return rehydrated; } return candidates.find(Boolean) ?? builtInToolDefinition(name, cwd); } function hasUsablePiComponents(value3) { return isRecord3(value3) && (typeof value3.ToolExecutionComponent === "function" || typeof value3.AssistantMessageComponent === "function" || typeof value3.UserMessageComponent === "function" || typeof value3.createReadToolDefinition === "function" || typeof value3.createBashToolDefinition === "function"); } function loadPiComponents() { if (injectedPiComponents !== void 0) return injectedPiComponents; if (piComponents !== void 0) return piComponents; const candidates = [ () => { const packageRoot = findRunningPiPackageRoot(); return packageRoot ? require2(packageRoot) : void 0; }, () => { const entrypoint = runningPiEntrypoint(); if (!entrypoint) return void 0; return createRequire2(entrypoint)( "@earendil-works/pi-coding-agent" ); }, () => require2("@earendil-works/pi-coding-agent") ]; for (const candidate of candidates) { try { const loaded = candidate(); if (hasUsablePiComponents(loaded)) { piComponents = loaded; return piComponents; } } catch { } } return void 0; } async function importPiComponentCandidate(filePath) { if (!filePath || !fs4.existsSync(filePath)) return void 0; try { const loaded = await import(pathToFileURL(filePath).href); return hasUsablePiComponents(loaded) ? loaded : void 0; } catch { return void 0; } } async function loadPiComponentsAsync() { const packageRoot = findRunningPiPackageRoot(); if (packageRoot) { const chunksDir = path4.join(packageRoot, "dist", "bundle", "chunks"); try { if (fs4.existsSync(chunksDir)) { for (const entry of fs4.readdirSync(chunksDir)) { if (!entry.endsWith(".js")) continue; const loaded = await importPiComponentCandidate( path4.join(chunksDir, entry) ); if (loaded) return loaded; } } } catch { } try { const parsed = JSON.parse( fs4.readFileSync(path4.join(packageRoot, "package.json"), "utf8") ); const loaded = await importPiComponentCandidate( path4.join(packageRoot, parsed.main ?? "dist/index.js") ); if (loaded) return loaded; } catch { } } const spec = "@earendil-works/pi-coding-agent"; try { const loaded = await import(spec); if (hasUsablePiComponents(loaded)) return loaded; } catch { } return void 0; } async function preloadPiComponentsForSubagentRendering() { if (piComponents !== void 0 && hasUsablePiComponents(piComponents)) return true; const loaded = await loadPiComponentsAsync(); if (loaded) { piComponents = loaded; builtInToolDefinitionCache.clear(); toolComponentCacheByTask.clear(); return true; } if (loadPiComponents()) return true; return false; } function debugLog(context, scope, data) { writeSubagentsDebugLog(context?.cwd, scope, data); } function renderComponent(component, width) { if (!component || typeof component.render !== "function") return void 0; const lines = component.render(width); return Array.isArray(lines) ? lines.filter((line) => typeof line === "string").flatMap((line) => line.replace(/\r\n?/g, "\n").split("\n")) : void 0; } function fitsWidth(context, text, width) { try { if (context.visibleWidth(text) <= width) return true; } catch { } return visibleWidth2(text) <= width; } function safeTruncate(context, text, width = DEFAULT_RENDER_WIDTH) { if (fitsWidth(context, text, width)) return text; if (getRenderKit()?.icon) return truncateToWidth2(text, width, resolveIcon("ellipsis", "\u2026")); try { return context.truncateToWidth(text, width); } catch { return truncateToWidth2(text, width, resolveIcon("ellipsis", "\u2026")); } } function truncateLines(context, lines, width = DEFAULT_RENDER_WIDTH) { const out = []; for (const text of lines) for (const line of text.split(/\r?\n|\r/)) out.push( fitsWidth(context, line, width) ? line : getRenderKit()?.icon ? truncateToWidth2(line, width, resolveIcon("ellipsis", "\u2026")) : context.truncateToWidth(line, width) ); return out; } function assistantText(item) { const lines = []; for (const part of item.message.content) { if (part.type === "text" && part.text.trim()) lines.push(part.text); else if (part.type === "thinking" && (part.thinking ?? part.text)?.trim()) lines.push(`thinking: ${part.thinking ?? part.text}`); } if (item.message.errorMessage) lines.push(`error: ${item.message.errorMessage}`); return lines; } function renderAssistantItem(item, context, width) { const visibleContent = item.message.content.filter( (part) => part.type !== "toolCall" ); if (!visibleContent.length && !item.message.errorMessage) return []; const displayItem = visibleContent.length === item.message.content.length ? item : { ...item, message: { ...item.message, content: visibleContent } }; const componentCtor = loadPiComponents()?.AssistantMessageComponent; if (typeof componentCtor === "function") { try { const markdownTheme = loadPiComponents()?.getMarkdownTheme?.() ?? context.theme; const rendered = renderComponent( new componentCtor( displayItem.message, context.hideThinkingBlock ?? false, markdownTheme, "Thinking..." ), width ); if (rendered?.some((line) => line.trim())) return rendered; } catch (error) { debugLog(context, "assistant_component_error", { error }); } } return assistantText(displayItem); } function userItemTitle(item) { if (item.label === "context") return "orchestrator context"; if (item.label === "delegated_task") return "delegated task"; if (item.label === "continuation") return "continuation prompt"; if (item.label === "queued") return "queued live message"; return void 0; } function isFullDelegatedTask(item, context) { return context.includeFullDelegatedTask === true && item.type === "user" && (item.id === "delegated-prompt" || item.label === "delegated_task"); } function renderUserItem(item, context, width) { const title = userItemTitle(item); const displayText = title ? `## ${title} ${item.text}` : item.text; const componentCtor = loadPiComponents()?.UserMessageComponent; if (typeof componentCtor === "function") { try { const markdownTheme = loadPiComponents()?.getMarkdownTheme?.() ?? context.theme; const rendered = renderComponent( new componentCtor(displayText, markdownTheme), width ); if (rendered?.some((line) => line.trim())) { return isFullDelegatedTask(item, context) ? rendered.flatMap((line) => wrapLineToWidth(line, width)) : rendered; } } catch (error) { debugLog(context, "user_component_error", { error, label: item.label }); } } if (!isFullDelegatedTask(item, context)) { return title ? [title, item.text] : [`${item.label ?? "user"}: ${item.text}`]; } const textLines = item.text.split(/\r?\n/).flatMap((line) => wrapLineToWidth(line, width)); return title ? [title, ...textLines] : textLines.map((line) => `${item.label ?? "user"}: ${line}`); } function renderAttemptItem(item, context, width) { const label = `attempt ${item.attempt}`; const dividerWidth = Math.max( 0, Math.min(12, Math.floor((width - label.length - 2) / 2)) ); const text = `${"\u2500".repeat(dividerWidth)} ${label} ${"\u2500".repeat(dividerWidth)}`.trim(); return [ context.theme?.fg?.("accent", context.theme?.bold?.(text) ?? text) ?? text ]; } var builtInToolDefinitionCache = /* @__PURE__ */ new Map(); var externalToolDefinitions = /* @__PURE__ */ new Map(); var runtimeToolDefinitionsByTask = /* @__PURE__ */ new Map(); var externalToolSourceDefinitions = /* @__PURE__ */ new Map(); var externalToolSourcesLoaded = /* @__PURE__ */ new Set(); var toolComponentCacheByTask = /* @__PURE__ */ new Map(); var cachedToolRegistryVersion = getToolDefinitionRegistryVersion(); var cachedToolRenderKit = getRenderKit(); function refreshToolDefinitionCaches() { const version = getToolDefinitionRegistryVersion(); const kit = getRenderKit(); if (version !== cachedToolRegistryVersion || kit !== cachedToolRenderKit) { cachedToolRegistryVersion = version; cachedToolRenderKit = kit; toolComponentCacheByTask.clear(); builtInToolDefinitionCache.clear(); externalToolSourceDefinitions.clear(); externalToolSourcesLoaded.clear(); } return kit; } function registerSubagentRuntimeToolDefinition(taskId2, name, definition) { if (!taskId2 || !name || !definition) return; let byName = runtimeToolDefinitionsByTask.get(taskId2); if (!byName) { byName = /* @__PURE__ */ new Map(); runtimeToolDefinitionsByTask.set(taskId2, byName); } byName.set(name, definition); } function runtimeToolDefinition(taskId2, name) { return taskId2 ? runtimeToolDefinitionsByTask.get(taskId2)?.get(name) : void 0; } function builtInToolDefinition(name, cwd) { const key3 = `${cwd}\0${name}`; if (builtInToolDefinitionCache.has(key3)) return builtInToolDefinitionCache.get(key3); const pi = loadPiComponents(); const factoryByName = { read: "createReadToolDefinition", bash: "createBashToolDefinition", edit: "createEditToolDefinition", write: "createWriteToolDefinition", grep: "createGrepToolDefinition", find: "createFindToolDefinition", ls: "createLsToolDefinition" }; const factoryName = factoryByName[name]; if (!factoryName) return void 0; const createSpecificToolDefinition = pi?.[factoryName]; if (typeof createSpecificToolDefinition === "function") { try { const definition = createSpecificToolDefinition(cwd); builtInToolDefinitionCache.set(key3, definition); return definition; } catch { } } const createToolDefinition = pi?.createToolDefinition; if (typeof createToolDefinition !== "function") return void 0; try { const definition = createToolDefinition(name, cwd); builtInToolDefinitionCache.set(key3, definition); return definition; } catch { return void 0; } } function argString(value3) { return typeof value3 === "string" ? value3.trim() : value3 === void 0 || value3 === null ? "" : String(value3).trim(); } function pathRangeSummary(input) { const file = argString(input.path ?? input.file_path ?? input.file); if (!file) return ""; const offset = Number(input.offset ?? 1); const limit = Number(input.limit); if (Number.isFinite(limit) && limit > 0) return `${file}:${Number.isFinite(offset) && offset > 0 ? offset : 1}-${(Number.isFinite(offset) && offset > 0 ? offset : 1) + limit - 1}`; if (Number.isFinite(offset) && offset > 1) return `${file}:${offset}`; return file; } function memoryArgumentSummary(name, input) { if (name === "memory_search") return argString(input.query); if (name === "memory_recall") return [argString(input.context), argString(input.query)].filter(Boolean).join(` ${resolveIcon("separator", "\xB7")} `); if (name === "memory_get" || name === "memory_update" || name === "memory_archive") return argString(input.id); if (name === "memory_list") return [ argString(input.scope), argString(input.kind), argString(input.project_name) ].filter(Boolean).join(` ${resolveIcon("separator", "\xB7")} `); if (name === "memory_add") return argString(input.title ?? input.summary ?? input.kind); if (name === "memory_project_profile") return argString(input.action); if (name === "memory_session_start") return argString(input.title); if (name === "memory_session_prompt_add" || name === "memory_session_finish") return argString(input.session_id); if (name === "memory_migrate_project") return input.dry_run === false ? "apply" : "dry run"; if (name === "memory_export" || name === "memory_import") return argString(input.path); return argString( input.query ?? input.id ?? input.action ?? input.kind ?? input.title ?? input.summary ); } function toolArgumentSummary(name, args) { const input = isRecord3(args) ? args : {}; if (name === "read") return pathRangeSummary(input); if (name === "edit" || name === "write") return argString(input.path ?? input.file_path ?? input.file); if (name === "bash") return argString(input.command).split("\n")[0] ?? ""; if (name.startsWith("memory_")) return memoryArgumentSummary(name, input); if (["grep", "find", "ls"].includes(name)) return [ argString(input.pattern ?? input.query ?? input.name), argString(input.path ?? input.cwd) ].filter(Boolean).join(` ${resolveIcon("separator", "\xB7")} `); return jsonPreview(args); } function isActiveToolStatus(status) { return status === "pending" || status === "running" || status === "partial"; } function cachedToolComponent(item, context, componentCtor, toolDefinition) { const cacheId = item.tool_call_id ?? item.id; const shouldReuse = Boolean( context.taskId && cacheId && (isActiveToolStatus(item.status) || toolComponentCacheByTask.get(context.taskId)?.has(cacheId)) ); if (!shouldReuse) return new componentCtor( item.name, cacheId ?? item.name, item.arguments, { showImages: context.showImages, imageWidthCells: context.imageWidthCells }, toolDefinition, context.tui, context.cwd ); let taskCache = toolComponentCacheByTask.get(context.taskId); if (!taskCache) { taskCache = /* @__PURE__ */ new Map(); toolComponentCacheByTask.set(context.taskId, taskCache); } let component = taskCache.get(cacheId); if (!component) { component = new componentCtor( item.name, cacheId ?? item.name, item.arguments, { showImages: context.showImages, imageWidthCells: context.imageWidthCells }, toolDefinition, context.tui, context.cwd ); taskCache.set(cacheId, component); } return component; } function renderToolItem(item, context, width) { const kit = refreshToolDefinitionCaches(); const published = getPublishedToolDefinition(item.name); const toolDefinition = !kit && published ? published : renderableToolDefinition( item.name, [ published, hasToolRenderer(published) ? void 0 : context.getToolDefinition?.(item.name), externalToolDefinition(item.name), externalToolSourceDefinitions.get(item.name), runtimeToolDefinition(context.taskId, item.name) ], context.cwd, kit ); const componentCtor = loadPiComponents()?.ToolExecutionComponent; if (typeof componentCtor === "function" && context.tui && toolDefinition) { try { const component = cachedToolComponent( item, context, componentCtor, toolDefinition ); component.markExecutionStarted?.(); component.setArgsComplete?.(); if (item.result) component.updateResult?.(item.result, isActiveToolStatus(item.status)); component.setExpanded?.(context.toolOutputExpanded ?? false); const rendered = renderComponent(component, width); if (rendered?.some((line) => line.trim())) return rendered; debugLog(context, "tool_component_empty_fallback", { name: item.name, status: item.status, width, hasToolDefinition: Boolean(toolDefinition), hasTui: Boolean(context.tui) }); } catch (error) { debugLog(context, "tool_component_error_fallback", { error, name: item.name, status: item.status, width, hasToolDefinition: Boolean(toolDefinition), hasTui: Boolean(context.tui) }); } } else { debugLog(context, "tool_component_unavailable_fallback", { name: item.name, status: item.status, hasComponentCtor: typeof componentCtor === "function", hasToolDefinition: Boolean(toolDefinition), hasTui: Boolean(context.tui) }); } const result = item.result ? payloadText(item.result) : ""; const args = toolArgumentSummary(item.name, item.arguments); const state = item.result?.isError && !isActiveToolStatus(item.status) ? "failed" : item.status; const fallback = [ `${item.name} ${state}${args ? ` ${resolveIcon("separator", "\xB7")} ${args}` : ""}`, ...result ? [result] : [] ]; debugLog(context, "tool_fallback_rendered", { name: item.name, status: item.status, fallbackPreview: fallback.join("\n").slice(0, 1e3) }); return fallback; } function renderBashItem(item, context, width) { const status = item.cancelled ? "cancelled" : item.status ?? (item.exitCode && item.exitCode !== 0 ? "failed" : "completed"); const adapted = { type: "tool", id: item.id, tool_call_id: item.tool_call_id, name: "bash", arguments: { command: item.command }, status: status === "cancelled" ? "failed" : status === "running" ? "running" : status === "failed" ? "failed" : "completed", result: item.output || item.exitCode !== void 0 || item.fullOutputPath || item.truncated ? { content: item.output ? [{ type: "text", text: item.output }] : [], details: { exitCode: item.exitCode, cancelled: item.cancelled, truncated: item.truncated, fullOutputPath: item.fullOutputPath, legacy_snapshot: true }, isError: status === "failed" || status === "cancelled", preview: item.output } : void 0 }; return renderToolItem(adapted, context, width); } function renderCustomItem(item, context, width) { const renderer = context.getMessageRenderer?.(item.customType); const componentCtor = loadPiComponents()?.CustomMessageComponent; if (typeof componentCtor === "function" && renderer) { try { const markdownTheme = loadPiComponents()?.getMarkdownTheme?.() ?? context.theme; const component = new componentCtor( { type: item.customType, content: item.content, display: item.display }, renderer, markdownTheme ); component.setExpanded?.(context.toolOutputExpanded ?? false); const rendered = renderComponent(component, width); if (rendered?.some((line) => line.trim())) return rendered; } catch (error) { debugLog(context, "custom_component_error", { error, customType: item.customType, hasRenderer: Boolean(renderer) }); } } return [ `custom ${item.customType}${item.fallbackText ? `: ${item.fallbackText}` : ""}` ]; } function renderItem(item, context, width) { switch (item.type) { case "attempt": return renderAttemptItem(item, context, width); case "assistant": return renderAssistantItem(item, context, width); case "user": return renderUserItem(item, context, width); case "tool": return renderToolItem(item, context, width); case "tool_result": return [ `tool result${item.name ? ` ${item.name}` : ""}${item.result.isError ? " failed" : ""}`, payloadText(item.result) ].filter(Boolean); case "bash": return renderBashItem(item, context, width); case "custom": return renderCustomItem(item, context, width); case "status": return [`${item.severity ?? "info"}: ${item.text}`]; case "error": return [`error: ${item.text}`]; } } function isRenderableSnapshotRoot(value3) { return isRecord3(value3) && value3.version === 1 && ["events", "session_messages", "mixed"].includes(String(value3.source)) && Array.isArray(value3.items); } function malformedItemText(item) { if (isRecord3(item) && typeof item.type === "string") return `malformed thread item: ${item.type}`; return "malformed thread item"; } function closesLegacyAttempt(item) { if (item.type === "error") return true; if (item.type !== "assistant") return false; const hasText = item.message.content.some( (part) => part.type === "text" && part.text.trim() ); const hasToolCall = item.message.content.some( (part) => part.type === "toolCall" ); return hasText && !hasToolCall; } function delegatedTaskText(text) { const marker = "## delegated task"; const index = text.lastIndexOf(marker); return index >= 0 ? text.slice(index + marker.length).trim() : text; } function normalizeLegacyAttemptPrefix(items, preserveDelegatedTaskText = false) { const users = items.filter( (item) => item.type === "user" ); const delegated = users.find((item) => item.label === "delegated_task"); const context = users.find((item) => item.label === "context"); const continuations = users.filter((item) => item.label === "continuation"); const supportedUsers = users.every( (item) => item.label === "delegated_task" || item.label === "context" || item.label === "continuation" ); if (!delegated || !supportedUsers) return items; const outputItems = items.filter((item) => item.type !== "user"); const chunks = []; let current = []; for (const item of outputItems) { current.push(item); if (closesLegacyAttempt(item)) { chunks.push(current); current = []; } } if (current.length) chunks.push(current); const attemptCount = continuations.length + 1; while (chunks.length < attemptCount) chunks.push([]); if (chunks.length > attemptCount) return items; const normalized = []; for (let index = 0; index < attemptCount; index++) { const attempt = index + 1; normalized.push({ type: "attempt", id: `attempt-${attempt}`, attempt }); if (index === 0) { if (context) normalized.push(context); normalized.push({ ...delegated, text: preserveDelegatedTaskText ? delegated.text : delegatedTaskText(delegated.text) }); } else { normalized.push(continuations[index - 1]); } normalized.push(...chunks[index]); } return normalized; } function normalizeAttemptItems(items, preserveDelegatedTaskText = false) { const firstAttempt = items.findIndex((item) => item.type === "attempt"); if (firstAttempt === 0) return items; if (firstAttempt < 0) return normalizeLegacyAttemptPrefix(items, preserveDelegatedTaskText); return [ ...normalizeLegacyAttemptPrefix( items.slice(0, firstAttempt), preserveDelegatedTaskText ), ...items.slice(firstAttempt) ]; } function renderThreadBodyItems(snapshot2, context) { if (!isRenderableSnapshotRoot(snapshot2)) return []; const width = Math.max( 1, Math.floor(context.renderWidth ?? DEFAULT_RENDER_WIDTH) ); const renderedItems = []; for (const rawItem of normalizeAttemptItems( snapshot2.items, context.includeFullDelegatedTask ).slice(0, DEFAULT_MAX_ITEMS)) { try { if (!isThreadItem(rawItem)) { renderedItems.push({ item: rawItem, lines: [safeTruncate(context, malformedItemText(rawItem), width)] }); continue; } const limit = isFullDelegatedTask(rawItem, context) ? Number.POSITIVE_INFINITY : DEFAULT_TEXT_LIMIT; const item = boundItem(rawItem, limit); renderedItems.push({ item: rawItem, lines: truncateLines(context, renderItem(item, context, width), width) }); } catch { renderedItems.push({ item: rawItem, lines: [safeTruncate(context, "thread item unavailable", width)] }); } } return renderedItems; } // src/types.ts var TERMINAL_STATUSES = [ "completed", "failed", "cancelled", "interrupted" ]; function isTerminalStatus(status) { return TERMINAL_STATUSES.includes(status); } // src/history.ts var HISTORY_CONNECTIONS_KEY = /* @__PURE__ */ Symbol.for( "pi.subagents.historyConnections.v1" ); var shared10 = globalThis; shared10[HISTORY_CONNECTIONS_KEY] ??= /* @__PURE__ */ new Map(); var historyPaths = shared10[HISTORY_CONNECTIONS_KEY]; function historyState(file) { const key3 = process.platform === "win32" ? file.toLowerCase() : file; let state = historyPaths.get(key3); if (!state) { state = { stores: /* @__PURE__ */ new Set(), pruning: /* @__PURE__ */ new Set(), pausedPruning: /* @__PURE__ */ new Set(), compacting: false }; historyPaths.set(key3, state); } state.pausedPruning ??= /* @__PURE__ */ new Set(); return state; } function historyFileBytes(file) { return [file, `${file}-wal`].reduce((total, name) => { try { return total + fs5.statSync(name).size; } catch (error) { if (error.code !== "ENOENT") throw error; return total; } }, 0); } var require3 = createRequire3(import.meta.url); function loadDbConstructor() { try { const { DatabaseSync } = require3("node:sqlite"); if (DatabaseSync) return DatabaseSync; } catch { } const { Database } = require3("bun:sqlite"); if (Database) return Database; throw new Error( "No supported sqlite runtime is available. Expected node:sqlite or bun:sqlite." ); } function resolveSubagentsHistoryHome(env = process.env) { if (env.PI_SUBAGENTS_HISTORY_HOME) return path5.resolve(env.PI_SUBAGENTS_HISTORY_HOME); const xdg = env.XDG_DATA_HOME; return xdg ? path5.join(xdg, "pi", "subagents") : path5.join(os3.homedir(), ".local", "share", "pi", "subagents"); } function resolveSubagentHistoryDbPath(env = process.env) { if (env.PI_SUBAGENTS_HISTORY_DB_PATH) return path5.resolve(env.PI_SUBAGENTS_HISTORY_DB_PATH); return path5.join( resolveSubagentsHistoryHome(env), "subagents-history.sqlite" ); } function value(text) { return text ?? null; } function snapshotJson(snapshot2) { const bounded = boundThreadSnapshot(snapshot2); return bounded ? JSON.stringify(bounded) : null; } function parseSnapshotJson(text) { if (typeof text !== "string" || !text.trim()) return void 0; try { return boundThreadSnapshot(JSON.parse(text)); } catch { return void 0; } } var RUNTIME_HISTORY_FIELDS = [ ["runtime_context_tokens", "contextTokens"], ["runtime_context_window", "contextWindow"], ["runtime_context_percent", "contextPercent"], ["runtime_tool_uses", "toolUses"] ]; var RUNTIME_HISTORY_COLUMNS = RUNTIME_HISTORY_FIELDS.map( ([column]) => column ).join(", "); function finiteNonnegative(value3) { return typeof value3 === "number" && Number.isFinite(value3) && value3 >= 0 ? value3 : void 0; } var TIMEOUT_COLUMNS = [ "timeout_started_at", "timeout_deadline_at", "timeout_extensions_used", "timeout_deadline_generation", "timeout_max_extensions", "timeout_continue_enabled" ]; var TIMEOUT_HISTORY_COLUMNS = `progress_updates_json, ${TIMEOUT_COLUMNS.join(", ")}`; var SESSION_TASK_METADATA_COLUMNS = ` id, display_name, cwd, agent, mode, status, task, context, created_at, attempt, session_id, nested_session_path, started_at, ended_at, last_activity_at, last_activity, output_preview, usage_input, usage_output, usage_cache_read, usage_cache_write, usage_cost, usage_context_tokens, usage_turns, generation_output_tokens, generation_ms, ${RUNTIME_HISTORY_COLUMNS}, model, effort, model_source, effort_source, fallback_used, error, error_metadata_json, error_category, pi_retry_attempts, pending_message_count, undelivered_message_count, dropped_tools_json, ${TIMEOUT_HISTORY_COLUMNS} `; function ensureColumn(db, table, column, definition) { const hasColumn = () => { const columns = db.prepare(`PRAGMA table_info(${table})`).all(); return columns.some((row) => row.name === column); }; if (hasColumn()) return; try { db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`); } catch (error) { try { if (hasColumn()) return; } catch { } throw error; } } var HISTORY_BUSY_TIMEOUT_MS = 2e3; var PRUNE_BUSY_TIMEOUT_MS = 50; var PRUNE_BACKGROUND_BUSY_TIMEOUT_MS = 10; var PRUNE_SLICE_BUDGET_MS = 15; function isSqliteBusy(error) { const sqliteError = error; return Boolean( sqliteError && (/SQLITE_(BUSY|LOCKED)/.test(sqliteError.code ?? "") || typeof sqliteError.errcode === "number" && [5, 6].includes(sqliteError.errcode & 255) || /database (?:is )?(?:busy|locked)|database table is locked/i.test( sqliteError.message ?? "" )) ); } function configureHistoryDb(db, busyTimeoutMs) { db.exec(`PRAGMA busy_timeout = ${busyTimeoutMs}`); try { db.exec("PRAGMA journal_mode = WAL"); } catch { } try { db.exec("PRAGMA synchronous = NORMAL"); } catch { } } function ensureAttemptColumns(db) { ensureColumn( db, "subagent_task_attempts", "generation_output_tokens", "INTEGER" ); ensureColumn(db, "subagent_task_attempts", "generation_ms", "REAL"); ensureColumn(db, "subagent_task_attempts", "display_name", "TEXT"); ensureColumn(db, "subagent_task_attempts", "cwd", "TEXT"); ensureColumn(db, "subagent_task_attempts", "agent", "TEXT"); ensureColumn(db, "subagent_task_attempts", "mode", "TEXT"); ensureColumn(db, "subagent_task_attempts", "status", "TEXT"); ensureColumn(db, "subagent_task_attempts", "task", "TEXT"); ensureColumn(db, "subagent_task_attempts", "context", "TEXT"); ensureColumn(db, "subagent_task_attempts", "created_at", "TEXT"); ensureColumn(db, "subagent_task_attempts", "session_id", "TEXT"); ensureColumn(db, "subagent_task_attempts", "nested_session_path", "TEXT"); ensureColumn(db, "subagent_task_attempts", "started_at", "TEXT"); ensureColumn(db, "subagent_task_attempts", "ended_at", "TEXT"); ensureColumn(db, "subagent_task_attempts", "last_activity_at", "TEXT"); ensureColumn(db, "subagent_task_attempts", "last_activity", "TEXT"); ensureColumn(db, "subagent_task_attempts", "output_preview", "TEXT"); ensureColumn(db, "subagent_task_attempts", "prompt", "TEXT"); ensureColumn(db, "subagent_task_attempts", "continuation_prompt", "TEXT"); ensureColumn(db, "subagent_task_attempts", "system_prompt", "TEXT"); ensureColumn(db, "subagent_task_attempts", "transcript", "TEXT"); ensureColumn(db, "subagent_task_attempts", "usage_input", "INTEGER"); ensureColumn(db, "subagent_task_attempts", "usage_output", "INTEGER"); ensureColumn(db, "subagent_task_attempts", "usage_cache_read", "INTEGER"); ensureColumn(db, "subagent_task_attempts", "usage_cache_write", "INTEGER"); ensureColumn(db, "subagent_task_attempts", "usage_cost", "REAL"); ensureColumn(db, "subagent_task_attempts", "usage_context_tokens", "INTEGER"); ensureColumn(db, "subagent_task_attempts", "usage_turns", "INTEGER"); ensureColumn(db, "subagent_task_attempts", "model", "TEXT"); ensureColumn(db, "subagent_task_attempts", "effort", "TEXT"); ensureColumn(db, "subagent_task_attempts", "model_source", "TEXT"); ensureColumn(db, "subagent_task_attempts", "effort_source", "TEXT"); ensureColumn(db, "subagent_task_attempts", "fallback_used", "INTEGER"); ensureColumn(db, "subagent_task_attempts", "error", "TEXT"); ensureColumn(db, "subagent_task_attempts", "error_metadata_json", "TEXT"); ensureColumn(db, "subagent_task_attempts", "error_category", "TEXT"); ensureColumn(db, "subagent_task_attempts", "result", "TEXT"); ensureColumn(db, "subagent_task_attempts", "thread_snapshot_json", "TEXT"); ensureColumn(db, "subagent_task_attempts", "pi_retry_attempts", "INTEGER"); ensureColumn(db, "subagent_task_attempts", "dropped_tools_json", "TEXT"); ensureColumn( db, "subagent_task_attempts", "pending_message_count", "INTEGER" ); ensureColumn( db, "subagent_task_attempts", "undelivered_message_count", "INTEGER" ); } function upsertTaskRecord(db, table, cwd, task) { const includeExecutionDetail = table === "subagent_tasks"; let errorMetadataJson = null; let errorCategory = null; if (task.error_metadata !== void 0) { try { errorMetadataJson = serializeErrorMetadata(task.error_metadata); errorCategory = parseErrorMetadata(errorMetadataJson)?.category ?? null; } catch { errorMetadataJson = null; errorCategory = null; } } const baseColumns = table === "subagent_tasks" ? "id, display_name, cwd, agent, mode, status, task, context, created_at, attempt, session_id, nested_session_path, started_at, ended_at, last_activity_at, last_activity, output_preview, prompt, continuation_prompt, system_prompt, transcript, usage_input, usage_output, usage_cache_read, usage_cache_write, usage_cost, usage_context_tokens, usage_turns, generation_output_tokens, generation_ms, model, effort, model_source, effort_source, fallback_used, error, error_metadata_json, error_category, result, thread_snapshot_json, pi_retry_attempts, pending_message_count, undelivered_message_count, dropped_tools_json" : "task_id, attempt, display_name, cwd, agent, mode, status, task, context, created_at, session_id, nested_session_path, started_at, ended_at, last_activity_at, last_activity, output_preview, prompt, continuation_prompt, system_prompt, transcript, usage_input, usage_output, usage_cache_read, usage_cache_write, usage_cost, usage_context_tokens, usage_turns, generation_output_tokens, generation_ms, model, effort, model_source, effort_source, fallback_used, error, error_metadata_json, error_category, result, thread_snapshot_json, pi_retry_attempts, pending_message_count, undelivered_message_count, dropped_tools_json"; const columns = `${baseColumns}, ${TIMEOUT_HISTORY_COLUMNS}, ${RUNTIME_HISTORY_COLUMNS}`; const placeholders = new Array(columns.split(",").length).fill("?").join(", "); const update = table === "subagent_tasks" ? `display_name=excluded.display_name, status=excluded.status, attempt=excluded.attempt, session_id=excluded.session_id, nested_session_path=excluded.nested_session_path, started_at=excluded.started_at, ended_at=excluded.ended_at, last_activity_at=excluded.last_activity_at, last_activity=excluded.last_activity, output_preview=excluded.output_preview, prompt=excluded.prompt, continuation_prompt=excluded.continuation_prompt, system_prompt=excluded.system_prompt, transcript=excluded.transcript, usage_input=excluded.usage_input, usage_output=excluded.usage_output, usage_cache_read=excluded.usage_cache_read, usage_cache_write=excluded.usage_cache_write, usage_cost=excluded.usage_cost, usage_context_tokens=excluded.usage_context_tokens, usage_turns=excluded.usage_turns, generation_output_tokens=excluded.generation_output_tokens, generation_ms=excluded.generation_ms, model=excluded.model, effort=excluded.effort, model_source=excluded.model_source, effort_source=excluded.effort_source, fallback_used=excluded.fallback_used, error=excluded.error, error_metadata_json=excluded.error_metadata_json, error_category=excluded.error_category, result=excluded.result, thread_snapshot_json=excluded.thread_snapshot_json, pi_retry_attempts=excluded.pi_retry_attempts, pending_message_count=excluded.pending_message_count, undelivered_message_count=excluded.undelivered_message_count, dropped_tools_json=excluded.dropped_tools_json` : `display_name=excluded.display_name, status=excluded.status, session_id=excluded.session_id, nested_session_path=excluded.nested_session_path, started_at=excluded.started_at, ended_at=excluded.ended_at, last_activity_at=excluded.last_activity_at, last_activity=excluded.last_activity, output_preview=excluded.output_preview, prompt=excluded.prompt, continuation_prompt=excluded.continuation_prompt, system_prompt=excluded.system_prompt, transcript=excluded.transcript, usage_input=excluded.usage_input, usage_output=excluded.usage_output, usage_cache_read=excluded.usage_cache_read, usage_cache_write=excluded.usage_cache_write, usage_cost=excluded.usage_cost, usage_context_tokens=excluded.usage_context_tokens, usage_turns=excluded.usage_turns, generation_output_tokens=excluded.generation_output_tokens, generation_ms=excluded.generation_ms, model=excluded.model, effort=excluded.effort, model_source=excluded.model_source, effort_source=excluded.effort_source, fallback_used=excluded.fallback_used, error=excluded.error, error_metadata_json=excluded.error_metadata_json, error_category=excluded.error_category, result=excluded.result, thread_snapshot_json=excluded.thread_snapshot_json, pi_retry_attempts=excluded.pi_retry_attempts, pending_message_count=excluded.pending_message_count, undelivered_message_count=excluded.undelivered_message_count, dropped_tools_json=excluded.dropped_tools_json`; const identity = table === "subagent_tasks" ? "id" : "task_id, attempt"; db.prepare(` INSERT INTO ${table} (${columns}) VALUES (${placeholders}) ON CONFLICT(${identity}) DO UPDATE SET ${update}, progress_updates_json=excluded.progress_updates_json, ${TIMEOUT_COLUMNS.map((column) => `${column}=excluded.${column}`).join(", ")}, ${RUNTIME_HISTORY_FIELDS.map(([column]) => `${column}=excluded.${column}`).join(", ")} `).run( ...table === "subagent_tasks" ? [task.id] : [task.id, task.attempt ?? 1], value(task.display_name), cwd, task.agent, task.mode, task.status, task.task, value(task.context), task.created_at, ...table === "subagent_tasks" ? [task.attempt ?? 1] : [], value(task.session_id), value(task.nested_session_path), value(task.started_at), value(task.ended_at), value(task.last_activity_at), value(task.last_activity), value(task.output_preview), value(task.prompt), value(task.continuation_prompt), includeExecutionDetail ? value(task.system_prompt) : null, includeExecutionDetail ? value(task.transcript) : null, task.usage?.input ?? null, task.usage?.output ?? null, task.usage?.cacheRead ?? null, task.usage?.cacheWrite ?? null, task.usage?.cost ?? null, task.usage?.contextTokens ?? null, task.usage?.turns ?? null, task.runtime_metrics?.generationOutputTokens ?? null, task.runtime_metrics?.generationMs ?? null, value(task.model), value(task.effort), value(task.model_source), value(task.effort_source), task.fallback_used === void 0 ? null : task.fallback_used ? 1 : 0, value(task.error), errorMetadataJson, errorCategory, value(task.result), includeExecutionDetail ? snapshotJson(task.thread_snapshot) : null, task.pi_retry_attempts ?? null, task.pending_message_count ?? null, task.undelivered_message_count ?? null, task.dropped_tools === void 0 ? null : JSON.stringify(task.dropped_tools), task.progress_updates === void 0 ? null : JSON.stringify(task.progress_updates.slice(-5)), ...TIMEOUT_COLUMNS.map((column) => { const field2 = task[column]; return field2 === void 0 ? null : typeof field2 === "boolean" ? Number(field2) : field2; }), ...RUNTIME_HISTORY_FIELDS.map( ([, field2]) => finiteNonnegative(task.runtime_metrics?.[field2]) ?? null ) ); } function initializeHistorySchema(db) { db.exec(` CREATE TABLE IF NOT EXISTS subagent_tasks ( id TEXT PRIMARY KEY, display_name TEXT, cwd TEXT NOT NULL, agent TEXT NOT NULL, mode TEXT NOT NULL, status TEXT NOT NULL, task TEXT NOT NULL, context TEXT, created_at TEXT NOT NULL, attempt INTEGER, session_id TEXT, nested_session_path TEXT, started_at TEXT, ended_at TEXT, last_activity_at TEXT, last_activity TEXT, output_preview TEXT, prompt TEXT, continuation_prompt TEXT, system_prompt TEXT, transcript TEXT, usage_input INTEGER, usage_output INTEGER, usage_cache_read INTEGER, usage_cache_write INTEGER, usage_cost REAL, usage_context_tokens INTEGER, usage_turns INTEGER, model TEXT, effort TEXT, model_source TEXT, effort_source TEXT, fallback_used INTEGER, error TEXT, error_metadata_json TEXT, error_category TEXT, result TEXT, thread_snapshot_json TEXT, pi_retry_attempts INTEGER, pending_message_count INTEGER, undelivered_message_count INTEGER ); CREATE TABLE IF NOT EXISTS subagent_task_attempts ( task_id TEXT NOT NULL, attempt INTEGER NOT NULL, display_name TEXT, cwd TEXT NOT NULL, agent TEXT NOT NULL, mode TEXT NOT NULL, status TEXT NOT NULL, task TEXT NOT NULL, context TEXT, created_at TEXT NOT NULL, session_id TEXT, nested_session_path TEXT, started_at TEXT, ended_at TEXT, last_activity_at TEXT, last_activity TEXT, output_preview TEXT, prompt TEXT, continuation_prompt TEXT, system_prompt TEXT, transcript TEXT, usage_input INTEGER, usage_output INTEGER, usage_cache_read INTEGER, usage_cache_write INTEGER, usage_cost REAL, usage_context_tokens INTEGER, usage_turns INTEGER, model TEXT, effort TEXT, model_source TEXT, effort_source TEXT, fallback_used INTEGER, error TEXT, error_metadata_json TEXT, error_category TEXT, result TEXT, thread_snapshot_json TEXT, pi_retry_attempts INTEGER, pending_message_count INTEGER, undelivered_message_count INTEGER, PRIMARY KEY (task_id, attempt) ); CREATE TABLE IF NOT EXISTS subagent_events ( id INTEGER PRIMARY KEY AUTOINCREMENT, task_id TEXT NOT NULL, attempt INTEGER, cwd TEXT NOT NULL, created_at TEXT NOT NULL, status TEXT NOT NULL, activity TEXT NOT NULL, output_preview TEXT, FOREIGN KEY(task_id) REFERENCES subagent_tasks(id) ); CREATE INDEX IF NOT EXISTS idx_subagent_tasks_created ON subagent_tasks(created_at DESC); CREATE INDEX IF NOT EXISTS idx_subagent_tasks_session_status ON subagent_tasks(cwd, session_id, status, id); CREATE INDEX IF NOT EXISTS idx_subagent_tasks_session_cost ON subagent_tasks(cwd, session_id, usage_cost DESC, created_at DESC, id DESC); CREATE INDEX IF NOT EXISTS idx_subagent_events_task ON subagent_events(task_id, created_at); CREATE INDEX IF NOT EXISTS idx_subagent_attempts_task ON subagent_task_attempts(task_id, attempt); `); ensureColumn(db, "subagent_tasks", "generation_output_tokens", "INTEGER"); ensureColumn(db, "subagent_tasks", "generation_ms", "REAL"); ensureColumn(db, "subagent_tasks", "display_name", "TEXT"); ensureColumn(db, "subagent_tasks", "attempt", "INTEGER"); ensureColumn(db, "subagent_tasks", "nested_session_path", "TEXT"); ensureColumn(db, "subagent_tasks", "continuation_prompt", "TEXT"); ensureColumn(db, "subagent_tasks", "system_prompt", "TEXT"); ensureColumn(db, "subagent_tasks", "error_metadata_json", "TEXT"); ensureColumn(db, "subagent_tasks", "error_category", "TEXT"); ensureColumn(db, "subagent_tasks", "pi_retry_attempts", "INTEGER"); ensureColumn(db, "subagent_tasks", "dropped_tools_json", "TEXT"); ensureColumn(db, "subagent_tasks", "pending_message_count", "INTEGER"); ensureColumn(db, "subagent_tasks", "undelivered_message_count", "INTEGER"); ensureAttemptColumns(db); for (const table of ["subagent_tasks", "subagent_task_attempts"]) { for (const [column] of RUNTIME_HISTORY_FIELDS) ensureColumn(db, table, column, "REAL"); ensureColumn(db, table, "progress_updates_json", "TEXT"); for (const column of TIMEOUT_COLUMNS) ensureColumn(db, table, column, "INTEGER"); } ensureColumn(db, "subagent_events", "attempt", "INTEGER"); } var SubagentHistoryStore = class _SubagentHistoryStore { dbs = /* @__PURE__ */ new Map(); closed = false; close() { if (this.closed && this.dbs.size === 0) return; this.closed = true; const errors = []; for (const [file, db] of this.dbs) { try { this.closeDb(file, db); } catch (error) { errors.push(error); } } if (errors.length) throw new AggregateError( errors, "Failed to close subagent history databases." ); } db(_cwd, busyTimeoutMs = HISTORY_BUSY_TIMEOUT_MS) { if (this.closed) throw new Error("Subagent history store is closed."); const file = resolveSubagentHistoryDbPath(); if (historyState(file).compacting) throw new Error( "Subagent history is busy: explicit compaction is running." ); const existing = this.dbs.get(file); if (existing) return existing; fs5.mkdirSync(path5.dirname(file), { recursive: true, mode: 448 }); try { fs5.chmodSync(path5.dirname(file), 448); } catch { } const Database = loadDbConstructor(); const db = new Database(file); try { fs5.chmodSync(file, 384); } catch { } try { configureHistoryDb(db, busyTimeoutMs); initializeHistorySchema(db); this.dbs.set(file, db); historyState(file).stores.add(this); return db; } catch (error) { db.close(); throw error; } } closeDb(file, db) { db.close(); this.dbs.delete(file); historyState(file).stores.delete(this); } /** Explicit only. Suspend local users, then hold SQLite exclusion until close. */ static async compactHistory({ olderThanMs }) { if (olderThanMs !== void 0) new Date(olderThanMs).toISOString(); const file = resolveSubagentHistoryDbPath(); const state = historyState(file); if (state.compacting) throw new Error( "History compaction refused: compaction is already running." ); state.compacting = true; let db; let acquired = false; try { for (const paused of state.pausedPruning) paused.abort(); await Promise.allSettled([...state.pruning]); const beforeBytes = historyFileBytes(file); for (const store of [...state.stores]) { for (const [storeFile, connection2] of store.dbs) if (historyState(storeFile) === state) store.closeDb(storeFile, connection2); } fs5.mkdirSync(path5.dirname(file), { recursive: true, mode: 448 }); const Database = loadDbConstructor(); db = new Database(file); db.exec("PRAGMA locking_mode = EXCLUSIVE"); db.exec(`PRAGMA busy_timeout = ${PRUNE_BUSY_TIMEOUT_MS}`); db.exec("BEGIN IMMEDIATE"); db.exec("COMMIT"); acquired = true; initializeHistorySchema(db); const connection = db; const pruned = olderThanMs === void 0 ? void 0 : await _SubagentHistoryStore.pruneOnDb( { olderThanMs }, () => connection ); if (pruned?.busy) throw new Error("History pruning could not finish."); db.exec("VACUUM"); db.close(); db = void 0; return { beforeBytes, afterBytes: historyFileBytes(file), pruned }; } catch (error) { if (!acquired && isSqliteBusy(error)) throw new Error( "History compaction refused: another process or connection has the database open or locked. Close other Pi sessions and retry. No history data was changed.", { cause: error } ); throw new Error( `History compaction failed: ${error instanceof Error ? error.message : String(error)}. VACUUM can need up to twice the database size in free disk space; check free space and filesystem permissions. Pruning may already have completed.`, { cause: error } ); } finally { try { db?.close(); } finally { state.compacting = false; } } } upsertTask(cwd, task) { const db = this.db(cwd); upsertTaskRecord(db, "subagent_tasks", cwd, task); upsertTaskRecord(db, "subagent_task_attempts", cwd, task); } /** Clear heavy columns, never task outcomes. olderThanMs is an epoch-ms cutoff. */ async pruneExecutionDetail(options) { const state = historyState(resolveSubagentHistoryDbPath()); if (state.compacting) return { tasksCleared: 0, attemptsCleared: 0, eventsDeleted: 0, busy: true }; const controller = new AbortController(); const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal; const waitUntilIdle = options.waitUntilIdle; const pass = _SubagentHistoryStore.pruneOnDb( { ...options, signal, waitUntilIdle: waitUntilIdle ? (signal2) => { const pause = waitUntilIdle(signal2); if (!pause) return; state.pausedPruning.add(controller); if (state.compacting) controller.abort(); return pause.finally( () => state.pausedPruning.delete(controller) ); } : void 0 }, () => this.db("", PRUNE_BACKGROUND_BUSY_TIMEOUT_MS), true ); state.pruning.add(pass); try { return await pass; } finally { state.pruning.delete(pass); } } static async pruneOnDb({ olderThanMs, batchSize, now = () => performance.now(), waitUntilIdle, signal = new AbortController().signal }, openDb, background = false) { const cutoff = new Date(olderThanMs).toISOString(); if (batchSize !== void 0 && (!Number.isInteger(batchSize) || batchSize < 1)) throw new Error("Pruning batchSize must be a positive integer."); const counts = { tasksCleared: 0, attemptsCleared: 0, eventsDeleted: 0, busy: false }; const pauseForIdle = () => { signal.throwIfAborted(); return waitUntilIdle?.(signal); }; let db; try { for (let pause = pauseForIdle(); pause; pause = pauseForIdle()) await pause; signal.throwIfAborted(); db = openDb(); db.exec( `PRAGMA busy_timeout = ${background ? PRUNE_BACKGROUND_BUSY_TIMEOUT_MS : PRUNE_BUSY_TIMEOUT_MS}` ); const detailPredicate = "thread_snapshot_json IS NOT NULL OR transcript IS NOT NULL OR system_prompt IS NOT NULL"; db.exec(` CREATE INDEX IF NOT EXISTS idx_subagent_tasks_retention_detail ON subagent_tasks(status, last_activity_at, ended_at, started_at, created_at, id) WHERE ${detailPredicate}; CREATE INDEX IF NOT EXISTS idx_subagent_task_attempts_retention_detail ON subagent_task_attempts(task_id, attempt) WHERE ${detailPredicate}; `); const detailBatches = [ { table: "subagent_tasks", keys: ["id"], count: "tasksCleared", args: [...TERMINAL_STATUSES, cutoff], predicate: `(${detailPredicate}) AND status IN (${TERMINAL_STATUSES.map(() => "?").join(", ")}) AND julianday(COALESCE(last_activity_at, ended_at, started_at, created_at)) < julianday(?)` }, { table: "subagent_task_attempts", keys: ["task_id", "attempt"], count: "attemptsCleared", args: [], predicate: `(${detailPredicate})` } ]; const connection = db; const batches = detailBatches.map((batch) => { const select = connection.prepare(` SELECT ${batch.keys.join(", ")} FROM ${batch.table} WHERE ${batch.predicate} LIMIT ? `); return { count: batch.count, initialSize: batchSize ?? 1, maxSize: batchSize ?? 100, selectBatch(size) { const candidates = select.all(...batch.args, size); const placeholders = `(${batch.keys.map(() => "?").join(", ")})`; const keyPredicate = candidates.length ? `(${batch.keys.join(", ")}) IN (${candidates.map(() => placeholders).join(", ")})` : "0"; return { statement: connection.prepare(` UPDATE ${batch.table} SET thread_snapshot_json = NULL, transcript = NULL, system_prompt = NULL WHERE ${keyPredicate} AND ${batch.predicate} `), args: [ ...candidates.flatMap( (row) => batch.keys.map((key3) => row[key3]) ), ...batch.args ], candidateCount: candidates.length }; } }; }); const events = db.prepare( "DELETE FROM subagent_events WHERE id IN (SELECT id FROM subagent_events LIMIT ?)" ); const eventBatch = { count: "eventsDeleted", initialSize: batchSize ?? 100, maxSize: batchSize ?? 1e4, selectBatch: (size) => ({ statement: events, args: [size], candidateCount: void 0 }) }; const changes = db.prepare("SELECT changes() AS count"); for (const batch of [...batches, eventBatch]) { let size = batch.initialSize; while (true) { for (let pause = pauseForIdle(); pause; pause = pauseForIdle()) await pause; signal.throwIfAborted(); const startedAt = now(); const selected = batch.selectBatch(size); signal.throwIfAborted(); let changed; db.exec("BEGIN IMMEDIATE"); try { selected.statement.run(...selected.args); changed = changes.all()[0].count; db.exec("COMMIT"); counts[batch.count] += changed; } catch (error) { db.exec("ROLLBACK"); throw error; } const elapsed = now() - startedAt; await new Promise((resolve3) => { const finish = () => { clearTimeout(timer); signal.removeEventListener("abort", finish); resolve3(); }; const timer = setTimeout( finish, Math.max(PRUNE_SLICE_BUDGET_MS, elapsed) ); if (background) timer.unref(); signal.addEventListener("abort", finish, { once: true }); if (signal.aborted) finish(); }); signal.throwIfAborted(); if ((selected.candidateCount ?? changed) < size) break; if (elapsed > PRUNE_SLICE_BUDGET_MS) size = Math.max(1, Math.floor(size / 2)); else if (elapsed < PRUNE_SLICE_BUDGET_MS / 2) size = Math.min(batch.maxSize, size * 2); } } } catch (error) { if (signal.aborted && error === signal.reason) counts.aborted = true; else if (isSqliteBusy(error)) counts.busy = true; else throw error; } finally { db?.exec(`PRAGMA busy_timeout = ${HISTORY_BUSY_TIMEOUT_MS}`); } return counts; } getTask(cwd, id, options = {}) { const rows = this.db(cwd).prepare(` SELECT * FROM subagent_tasks WHERE cwd = ? AND id = ? LIMIT 1 `).all(cwd, id); return rows.length ? rowToTask(rows[0], options) : void 0; } listTasks(cwd, limit = 100, options = {}) { return this.db(cwd).prepare(` SELECT * FROM subagent_tasks WHERE cwd = ? ORDER BY COALESCE(last_activity_at, started_at, created_at) DESC, created_at DESC, id DESC LIMIT ? `).all(cwd, limit).map((row) => rowToTask(row, options)); } listSessionTasks(cwd, sessionId, limit = 100, options = {}) { return this.db(cwd).prepare(` SELECT * FROM subagent_tasks WHERE cwd = ? AND session_id = ? ORDER BY COALESCE(last_activity_at, started_at, created_at) DESC, created_at DESC, id DESC LIMIT ? `).all(cwd, sessionId, limit).map((row) => rowToTask(row, options)); } /** Uncapped counts and overlap identities from the same persisted snapshot. */ snapshotSessionTaskCounts(cwd, sessionId) { const rows = this.db(cwd).prepare(` SELECT status, COUNT(*) AS count, json_group_array(id) AS ids FROM subagent_tasks WHERE cwd = ? AND session_id = ? GROUP BY status `).all(cwd, sessionId); const counts = {}; const statusesById = /* @__PURE__ */ new Map(); for (const row of rows) { counts[row.status] = row.count; for (const id of JSON.parse(row.ids)) statusesById.set(id, row.status); } return { counts, statusesById }; } listSessionTaskMetadata(cwd, sessionId, limit = 100) { return this.db(cwd).prepare(` SELECT ${SESSION_TASK_METADATA_COLUMNS} FROM subagent_tasks WHERE cwd = ? AND session_id = ? ORDER BY COALESCE(last_activity_at, started_at, created_at) DESC, created_at DESC, id DESC LIMIT ? `).all(cwd, sessionId, limit).map((row) => rowToTask(row, { includeSnapshots: false })); } /** Bounded terminal candidates for discovery, independent of launch/activity. */ listSessionTaskMetadataByCompletion(cwd, sessionId, limit = 100) { return this.db(cwd).prepare(` SELECT ${SESSION_TASK_METADATA_COLUMNS} FROM subagent_tasks WHERE cwd = ? AND session_id = ? AND status IN ('completed', 'failed', 'cancelled', 'interrupted') ORDER BY ended_at DESC, id DESC LIMIT ? `).all(cwd, sessionId, limit).map((row) => rowToTask(row, { includeSnapshots: false })); } /** Separate cost ranking: recency-based history readers remain unchanged. */ listSessionTaskMetadataByCost(cwd, sessionId) { return this.db(cwd).prepare(` SELECT ${SESSION_TASK_METADATA_COLUMNS} FROM subagent_tasks WHERE cwd = ? AND session_id = ? ORDER BY usage_cost DESC, created_at DESC, id DESC LIMIT 100 `).all(cwd, sessionId).map((row) => rowToTask(row, { includeSnapshots: false })); } listTasksByStatus(cwd, statuses, options = {}) { if (!statuses.length) return []; const placeholders = statuses.map(() => "?").join(", "); return this.db(cwd).prepare(` SELECT * FROM subagent_tasks WHERE cwd = ? AND status IN (${placeholders}) ORDER BY COALESCE(last_activity_at, started_at, created_at) DESC, created_at DESC, id DESC `).all(cwd, ...statuses).map((row) => rowToTask(row, options)); } listTaskAttempts(cwd, taskId2, options = {}) { return this.db(cwd).prepare(` SELECT task_id AS id, display_name, cwd, agent, mode, status, task, context, created_at, attempt, session_id, nested_session_path, started_at, ended_at, last_activity_at, last_activity, output_preview, prompt, continuation_prompt, system_prompt, transcript, usage_input, usage_output, usage_cache_read, usage_cache_write, usage_cost, usage_context_tokens, usage_turns, generation_output_tokens, generation_ms, ${RUNTIME_HISTORY_COLUMNS}, model, effort, model_source, effort_source, fallback_used, error, error_metadata_json, error_category, result, thread_snapshot_json, pi_retry_attempts, pending_message_count, undelivered_message_count, dropped_tools_json, ${TIMEOUT_HISTORY_COLUMNS} FROM subagent_task_attempts WHERE cwd = ? AND task_id = ? ORDER BY attempt ASC `).all(cwd, taskId2).map((row) => rowToTask(row, options)); } }; function parseDroppedTools(text) { if (typeof text !== "string") return void 0; try { const names = JSON.parse(text); return Array.isArray(names) && names.every((name) => typeof name === "string") ? names : void 0; } catch { return void 0; } } function parseProgressUpdates(raw) { if (typeof raw !== "string") return void 0; try { const updates = JSON.parse(raw); if (!Array.isArray(updates)) return void 0; return updates.filter( (update) => typeof update?.message === "string" && typeof update?.created_at === "string" ).slice(-5).map((update) => ({ message: update.message, created_at: update.created_at })); } catch { return void 0; } } function rowToTask(row, options = {}) { const runtimeMetrics = {}; if (row.generation_output_tokens != null && row.generation_ms != null) { runtimeMetrics.generationOutputTokens = row.generation_output_tokens; runtimeMetrics.generationMs = row.generation_ms; } for (const [column, field2] of RUNTIME_HISTORY_FIELDS) { const metric = finiteNonnegative(row[column]); if (metric !== void 0) runtimeMetrics[field2] = metric; } return { id: row.id, display_name: row.display_name ?? void 0, agent: row.agent, mode: row.mode, status: row.status, task: row.task, context: row.context ?? void 0, created_at: row.created_at, attempt: row.attempt ?? 1, session_id: row.session_id ?? void 0, nested_session_path: row.nested_session_path ?? void 0, started_at: row.started_at ?? void 0, ended_at: row.ended_at ?? void 0, last_activity_at: row.last_activity_at ?? void 0, last_activity: row.last_activity ?? void 0, output_preview: row.output_preview ?? void 0, prompt: row.prompt ?? void 0, continuation_prompt: row.continuation_prompt ?? void 0, system_prompt: row.system_prompt ?? void 0, transcript: row.transcript ?? void 0, usage: row.usage_input == null && row.usage_output == null && row.usage_cache_read == null && row.usage_cache_write == null && row.usage_cost == null && row.usage_context_tokens == null && row.usage_turns == null ? void 0 : { input: row.usage_input ?? 0, output: row.usage_output ?? 0, cacheRead: row.usage_cache_read ?? 0, cacheWrite: row.usage_cache_write ?? 0, cost: row.usage_cost ?? 0, contextTokens: row.usage_context_tokens ?? 0, turns: row.usage_turns ?? 0 }, runtime_metrics: Object.keys(runtimeMetrics).length ? runtimeMetrics : void 0, model: row.model ?? void 0, effort: row.effort ?? void 0, model_source: row.model_source ?? void 0, effort_source: row.effort_source ?? void 0, fallback_used: row.fallback_used === null || row.fallback_used === void 0 ? void 0 : Boolean(row.fallback_used), error: row.error ?? void 0, error_metadata: parseErrorMetadata(row.error_metadata_json), result: row.result ?? void 0, thread_snapshot: options.includeSnapshots === false ? void 0 : parseSnapshotJson(row.thread_snapshot_json), pi_retry_attempts: row.pi_retry_attempts ?? void 0, dropped_tools: parseDroppedTools(row.dropped_tools_json), progress_updates: parseProgressUpdates(row.progress_updates_json), timeout_started_at: row.timeout_started_at ?? void 0, timeout_deadline_at: row.timeout_deadline_at ?? void 0, timeout_extensions_used: row.timeout_extensions_used ?? void 0, timeout_deadline_generation: row.timeout_deadline_generation ?? void 0, timeout_max_extensions: row.timeout_max_extensions ?? void 0, timeout_continue_enabled: row.timeout_continue_enabled == null ? void 0 : Boolean(row.timeout_continue_enabled), pending_message_count: row.pending_message_count === null || row.pending_message_count === void 0 ? void 0 : row.pending_message_count, undelivered_message_count: row.undelivered_message_count === null || row.undelivered_message_count === void 0 ? void 0 : row.undelivered_message_count }; } // src/manager.ts import { Buffer as Buffer2 } from "node:buffer"; import { randomUUID as randomUUID2 } from "node:crypto"; import fs10 from "node:fs"; // src/continuation-mode.ts function resolveContinuationEffectiveMode(input) { return input.explicitMode ?? "background"; } // src/model-profiles/store.ts import { randomUUID } from "node:crypto"; import fs6 from "node:fs"; import os4 from "node:os"; import path6 from "node:path"; function modelProfilePaths({ cwd, agentDir: agentDir2 }) { return { global: path6.join( agentDir2 ?? process.env.PI_CODING_AGENT_DIR ?? path6.join(os4.homedir(), ".pi", "agent"), "thoth", "profiles.json" ), project: path6.join(cwd, ".pi", "thoth", "profiles.json") }; } function isObject(value3) { return !!value3 && typeof value3 === "object" && !Array.isArray(value3); } function validateName(value3, writable = false) { if (typeof value3 !== "string" || !value3.trim()) throw new Error("Profile name must be non-empty"); const result = value3.trim(); if (writable && result === "default") throw new Error("default is a reserved virtual profile"); return result; } function parseOverride(value3, label) { if (!isObject(value3)) throw new Error(`Invalid override for ${label}`); const model = parseModel(value3.model); const effort = parseEffort(value3.effort); if (value3.model !== void 0 && !model) throw new Error(`Invalid model for ${label}; expected provider/id`); if (value3.effort !== void 0 && !effort) throw new Error(`Invalid effort for ${label}`); return { ...value3, ...model ? { model } : {}, ...effort ? { effort } : {} }; } function parseProfile(value3) { if (!isObject(value3) || !isObject(value3.agents)) throw new Error("Profile must contain an agents object"); const agents = /* @__PURE__ */ Object.create(null); for (const [key3, entry] of Object.entries(value3.agents)) { const agent = key3.trim().toLowerCase(); if (!agent || !isObject(entry) || Object.hasOwn(agents, agent)) throw new Error(`Invalid or duplicate agent: ${key3}`); agents[agent] = parseOverride(entry, agent); } return { ...value3, agents, ...value3.orchestrator !== void 0 ? { orchestrator: parseOverride(value3.orchestrator, "orchestrator") } : {} }; } function parseModelProfilesDocument(raw) { if (!isObject(raw) || raw.version !== 1 || !isObject(raw.profiles)) throw new Error("Expected version 1 and a profiles object"); const profiles = /* @__PURE__ */ Object.create(null); for (const [key3, value3] of Object.entries(raw.profiles)) { const normalized = validateName(key3, true); if (Object.hasOwn(profiles, normalized)) throw new Error(`Duplicate profile: ${normalized}`); profiles[normalized] = parseProfile(value3); } return { ...raw, version: 1, ...raw.active !== void 0 ? { active: validateName(raw.active) } : {}, profiles }; } function serializeOverride(entry) { return { ...entry, ...entry.model ? { model: `${entry.model.provider}/${entry.model.id}` } : {} }; } function serializeProfile(value3) { const agents = Object.fromEntries( Object.entries(value3.agents).map(([agent, entry]) => [ agent, serializeOverride(entry) ]) ); return { ...value3, agents, ...value3.orchestrator ? { orchestrator: serializeOverride(value3.orchestrator) } : {} }; } var ModelProfileStore = class { paths; constructor(options) { this.paths = modelProfilePaths(options); } read(scope) { const file = this.paths[scope]; try { return parseModelProfilesDocument( JSON.parse(fs6.readFileSync(file, "utf8")) ); } catch (error) { if (error?.code === "ENOENT") return { version: 1, profiles: /* @__PURE__ */ Object.create(null) }; throw new Error(`Cannot read model profiles ${file}: ${error.message}`, { cause: error }); } } write(scope, document) { const validated = parseModelProfilesDocument(document); const serialized = { ...validated, profiles: Object.fromEntries( Object.entries(validated.profiles).map(([key3, value3]) => [ key3, serializeProfile(value3) ]) ) }; const file = this.paths[scope]; fs6.mkdirSync(path6.dirname(file), { recursive: true }); const temp = `${file}.${randomUUID()}.tmp`; try { fs6.writeFileSync(temp, `${JSON.stringify(serialized, null, 2)} `, { encoding: "utf8", flag: "wx" }); fs6.renameSync(temp, file); } finally { if (fs6.existsSync(temp)) fs6.unlinkSync(temp); } } save(scope, profileName, value3) { const key3 = validateName(profileName, true); const document = this.read(scope); const next = parseProfile(value3); const existing = document.profiles[key3]; for (const [agent, entry] of Object.entries(next.agents)) { const previous = { ...existing?.agents[agent] }; delete previous.model; delete previous.effort; next.agents[agent] = { ...previous, ...entry }; } document.profiles[key3] = { ...existing, ...next }; this.write(scope, document); } create(scope, profileName, value3) { const key3 = validateName(profileName, true); if (Object.hasOwn(this.read(scope).profiles, key3)) throw new Error(`Profile already exists: ${key3}`); this.save(scope, key3, value3); } lookup(profileName, sourceScope) { const key3 = validateName(profileName); if (key3 === "default") return { profile: { agents: {} } }; for (const scope of sourceScope ? [sourceScope] : ["project", "global"]) { const value3 = this.read(scope).profiles[key3]; if (value3) return { profile: value3, scope }; } return void 0; } clone(source, scope, target, sourceScope) { const found = this.lookup(source, sourceScope); if (!found) throw new Error(`Profile not found: ${source}`); this.create(scope, target, found.profile); } rename(scope, source, target) { const from = validateName(source, true); const to = validateName(target, true); const document = this.read(scope); if (!Object.hasOwn(document.profiles, from)) throw new Error(`Profile not found: ${from}`); if (Object.hasOwn(document.profiles, to)) throw new Error(`Profile already exists: ${to}`); document.profiles[to] = document.profiles[from]; delete document.profiles[from]; if (document.active === from) document.active = to; this.write(scope, document); } delete(scope, profileName) { const key3 = validateName(profileName, true); const document = this.read(scope); if (!Object.hasOwn(document.profiles, key3)) throw new Error(`Profile not found: ${key3}`); delete document.profiles[key3]; const clearedActive = document.active === key3; if (clearedActive) delete document.active; this.write(scope, document); return { clearedActive }; } setActive(scope, profileName) { const document = this.read(scope); if (profileName !== void 0) { const key3 = validateName(profileName); if (key3 !== "default" && !(scope === "global" ? Object.hasOwn(document.profiles, key3) : this.lookup(key3))) throw new Error(`Profile not found: ${key3}`); document.active = key3; } else delete document.active; this.write(scope, document); } setGlobalActive(profileName) { this.setActive("global", profileName); } setProjectPin(profileName) { this.setActive("project", profileName); } resolve(sessionSelection) { const warnings = []; const documents = {}; for (const scope of ["global", "project"]) { try { documents[scope] = this.read(scope); } catch (error) { warnings.push(String(error)); documents[scope] = { version: 1, profiles: /* @__PURE__ */ Object.create(null) }; } } for (const [level, key3] of [ ["session", sessionSelection], ["project", documents.project.active], ["global", documents.global.active] ]) { if (!key3) continue; if (key3 === "default") return { name: "default", profile: { agents: {} }, warnings }; const scope = Object.hasOwn(documents.project.profiles, key3) ? "project" : "global"; const value3 = documents[scope].profiles[key3]; if (value3 && (level !== "global" || Object.hasOwn(documents.global.profiles, key3))) return { name: key3, scope, profile: value3, warnings }; warnings.push(`Missing ${level} model profile "${key3}"; falling back.`); } return { name: "default", profile: { agents: {} }, warnings }; } }; // src/profile-resolver.ts function modelLabel(model) { return `${model.provider}/${model.id}`; } function effortFromCtx(ctx) { const effort = ctx?.pi?.getThinkingLevel?.() ?? ctx?.getThinkingLevel?.() ?? ctx?.thinkingLevel; return typeof effort === "string" ? effort : void 0; } function modelFromCtx(ctx) { const model = ctx?.model; if (!model || typeof model !== "object") return void 0; const provider = typeof model.provider === "string" ? model.provider : void 0; const id = typeof model.id === "string" ? model.id : typeof model.name === "string" ? model.name : void 0; return provider && id ? { provider, id } : void 0; } function profileSourceLabel(source, value3, format) { return value3 === void 0 ? "unresolved" : `${source}: ${format(value3)}`; } function field(source, value3, format) { return { value: value3, source, label: profileSourceLabel(source, value3, format) }; } function resolveModel(definition, config, ctx) { const profile = ctx?.modelProfile?.profile.agents[definition.name]; if (profile?.model) return field("profile", profile.model, modelLabel); if (definition.model) return field("definition", definition.model, modelLabel); if (config.default_model) return field("default", config.default_model, modelLabel); const orchestratorModel = modelFromCtx(ctx); if (orchestratorModel) return field("orchestrator", orchestratorModel, modelLabel); return field("unresolved", void 0, modelLabel); } function resolveEffort(definition, config, ctx) { const profile = ctx?.modelProfile?.profile.agents[definition.name]; if (profile?.effort) return field("profile", profile.effort, String); if (definition.effort) return field("definition", definition.effort, String); if (config.default_effort) return field("default", config.default_effort, String); const orchestratorEffort = effortFromCtx(ctx); if (orchestratorEffort) return field("orchestrator", orchestratorEffort, String); return field("unresolved", void 0, String); } function resolveDefaultSubagentProfile(input) { const definition = { ...input.definition, name: input.agentName.trim().toLowerCase() }; const ctx = { ...input.ctx, modelProfile: void 0 }; return { agent: definition.name, model: resolveModel(definition, input.config, ctx), effort: resolveEffort(definition, input.config, ctx) }; } function resolveEffectiveSubagentProfile(input) { const definition = { ...input.definition, name: input.agentName.trim().toLowerCase() }; const selection = input.ctx?.modelProfile ?? new ModelProfileStore({ cwd: input.ctx?.cwd ?? process.cwd(), agentDir: input.ctx?.agentDir }).resolve(input.ctx?.sessionModelProfile); const ctx = { ...input.ctx, modelProfile: selection }; const model = resolveModel(definition, input.config, ctx); const effort = resolveEffort(definition, input.config, ctx); for (const resolved of [model, effort]) if (resolved.source === "profile") resolved.label = resolved.label.replace( "profile:", `profile (${selection.name}):` ); return { agent: definition.name, model, effort, profileName: selection.name, warnings: selection.warnings }; } // src/runner/prompt.ts function buildPrompt(_definition, task, context, _tools = _definition.tools) { return [ context ? `## orchestrator context ${context}` : "", `## delegated task ${task}` ].filter(Boolean).join("\n\n"); } // src/runner/sdk-runner.ts import fs9 from "node:fs"; import path9 from "node:path"; // src/tool-patterns.ts function composeToolSelection(patterns, registeredToolNames, overlay) { const expanded = expandToolPatterns( [...patterns, ...overlay?.add ?? []], registeredToolNames ); const removals = overlay?.remove ?? []; return expanded.filter( (name) => !removals.some((pattern) => matchesToolPattern(name, pattern)) ); } function resolveEffectiveToolSelection(patterns, registeredToolNames, disallowedTools, enableAskOrchestrator, enableNotifyOrchestrator, overlay) { const expanded = composeToolSelection(patterns, registeredToolNames, overlay); if (enableAskOrchestrator) expanded.push("ask_orchestrator"); if (enableNotifyOrchestrator) expanded.push("notify_orchestrator"); const denied = new Set(disallowedTools); return [...new Set(expanded)].filter( (name) => (enableAskOrchestrator || name !== "ask_orchestrator") && (enableNotifyOrchestrator || name !== "notify_orchestrator") && !denied.has(name) && !name.startsWith("subagent_") ); } function hasToolGlob(pattern) { return pattern.includes("*"); } function wildcardToRegExp(pattern) { const source = pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*"); return new RegExp(`^${source}$`); } function matchesToolPattern(toolName, pattern) { return hasToolGlob(pattern) ? wildcardToRegExp(pattern).test(toolName) : toolName === pattern; } function expandToolPatterns(patterns, registeredToolNames) { if (patterns.includes("@active")) throw new Error( "The '@active' tool selector was removed; use exact tool names. '*' is an ordinary glob over all registered tools (active and inactive)." ); const registered = [...new Set(registeredToolNames ?? [])]; const expanded = []; const add = (name) => { if (name.startsWith("subagent_") || expanded.includes(name)) return; expanded.push(name); }; for (const pattern of patterns) { if (hasToolGlob(pattern)) { for (const toolName of registered) { if (matchesToolPattern(toolName, pattern)) add(toolName); } continue; } add(pattern); } return expanded; } // src/runner/session-teardown.ts var SHUTDOWN_TIMEOUT_MS = 5e3; var BACKGROUND_SHUTDOWN_TIMEOUT_MS = 1e4; var teardowns = /* @__PURE__ */ new WeakMap(); var backgroundShutdownHandlers = /* @__PURE__ */ new WeakMap(); function registerChildBackgroundShutdown(session, handlers) { backgroundShutdownHandlers.set(session, [...handlers]); } async function boundedCleanup(cleanup, timeoutMs) { let timer; try { await Promise.race([ Promise.resolve().then(cleanup), new Promise((resolve3) => { timer = setTimeout(resolve3, timeoutMs); }) ]); } catch { } finally { if (timer !== void 0) clearTimeout(timer); } } function teardownSubagentSession(session) { if (!session) return Promise.resolve(); const existing = teardowns.get(session); if (existing) return existing; const teardown = Promise.resolve().then(async () => { try { const runner = session.extensionRunner; const event = { type: "session_shutdown", reason: "quit" }; const handlers = backgroundShutdownHandlers.get(session) ?? []; backgroundShutdownHandlers.delete(session); for (const handler of handlers) { await boundedCleanup( () => handler(event, runner?.createContext?.()), BACKGROUND_SHUTDOWN_TIMEOUT_MS ); } if (runner?.hasHandlers?.("session_shutdown")) { await boundedCleanup(() => runner.emit(event), SHUTDOWN_TIMEOUT_MS); } } catch { } finally { try { const definitions = session.extensionRunner?.getAllRegisteredTools?.().map((tool) => tool.definition); withdrawSubagentExternalToolDefinitionsByIdentity(definitions ?? []); } finally { await session.dispose?.(); } } }); teardowns.set(session, teardown); return teardown; } // src/runner/snapshot-builder.ts function isFiniteNonNegative(value3) { return typeof value3 === "number" && Number.isFinite(value3) && value3 >= 0; } function assistantAccountingMessage(message) { if (message?.role !== "assistant") return void 0; const usage = {}; for (const key3 of [ "input", "output", "cacheRead", "cacheWrite", "totalTokens" ]) { if (isFiniteNonNegative(message.usage?.[key3])) usage[key3] = message.usage[key3]; } if (isFiniteNonNegative(message.usage?.cost?.total)) usage.cost = { total: message.usage.cost.total }; return { role: "assistant", ...typeof message.id === "string" ? { id: message.id } : {}, ...typeof message.timestamp === "number" || typeof message.timestamp === "string" ? { timestamp: message.timestamp } : {}, ...Object.keys(usage).length ? { usage } : {} }; } var SubagentRuntimeMetricsTracker = class { turns = 0; compactions = 0; generationOutputTokens = 0; generationMs = 0; generationStart; compacting = false; runtimeMetrics = { turns: 0, compactions: 0 }; lifetimeUsage; seenEvents = /* @__PURE__ */ new WeakSet(); constructor(session) { this.refresh(session); } observe(event, session, observedAt = Date.now()) { if (!event || typeof event !== "object" || this.seenEvents.has(event)) return this.snapshot(); this.seenEvents.add(event); if (event.type === "compaction_start") { this.compacting = true; this.generationStart = void 0; } if (event.type === "compaction_end") this.compacting = false; if (event.type === "message_start" && event.message?.role === "assistant" && !this.compacting) this.generationStart = { at: observedAt, id: event.message.id }; if (event.type === "message_end" && event.message?.role === "assistant") { const start = this.generationStart; this.generationStart = void 0; const elapsed = start ? observedAt - start.at : 0; if (start && !this.compacting && elapsed > 0 && Number.isFinite(elapsed) && (!start.id || !event.message.id || start.id === event.message.id) && isFiniteNonNegative(event.message.usage?.output)) { this.generationOutputTokens += event.message.usage.output; this.generationMs += elapsed; } } if (event.type === "turn_end") this.turns += 1; if (event.type === "compaction_end" && !event.aborted && event.result != null) { this.compactions += 1; this.clearContextOccupancy(); } if ([ "message_end", "tool_execution_start", "tool_execution_end", "turn_end", "compaction_end" ].includes(event.type)) this.refresh(session); return this.snapshot(); } clearContextOccupancy() { const runtimeMetrics = { ...this.runtimeMetrics }; delete runtimeMetrics.contextTokens; delete runtimeMetrics.contextPercent; this.runtimeMetrics = runtimeMetrics; if (this.lifetimeUsage) this.lifetimeUsage = { ...this.lifetimeUsage, contextTokens: 0 }; } snapshot() { return { runtime_metrics: { ...this.runtimeMetrics, turns: this.turns, compactions: this.compactions, generationOutputTokens: this.generationOutputTokens, generationMs: this.generationMs }, ...this.lifetimeUsage ? { usage: { ...this.lifetimeUsage, turns: this.turns } } : {} }; } refresh(session) { let context; let stats; try { context = session?.getContextUsage?.(); } catch { } try { stats = session?.getSessionStats?.(); } catch { } const runtimeMetrics = { turns: this.turns, compactions: this.compactions }; if (isFiniteNonNegative(context?.tokens)) runtimeMetrics.contextTokens = context.tokens; else if (this.runtimeMetrics.contextTokens !== void 0) runtimeMetrics.contextTokens = this.runtimeMetrics.contextTokens; if (isFiniteNonNegative(context?.contextWindow) && context.contextWindow > 0) runtimeMetrics.contextWindow = context.contextWindow; else if (this.runtimeMetrics.contextWindow !== void 0) runtimeMetrics.contextWindow = this.runtimeMetrics.contextWindow; if (isFiniteNonNegative(context?.percent)) runtimeMetrics.contextPercent = context.percent; else if (this.runtimeMetrics.contextPercent !== void 0) runtimeMetrics.contextPercent = this.runtimeMetrics.contextPercent; if (isFiniteNonNegative(stats?.toolCalls)) runtimeMetrics.toolUses = stats.toolCalls; this.runtimeMetrics = runtimeMetrics; const tokens = stats?.tokens; if (!["input", "output", "cacheRead", "cacheWrite"].every( (key3) => isFiniteNonNegative(tokens?.[key3]) )) return; this.lifetimeUsage = { input: tokens.input, output: tokens.output, cacheRead: tokens.cacheRead, cacheWrite: tokens.cacheWrite, cost: isFiniteNonNegative(stats.cost) ? stats.cost : this.lifetimeUsage?.cost ?? 0, contextTokens: isFiniteNonNegative(context?.tokens) ? context.tokens : this.lifetimeUsage?.contextTokens ?? 0, turns: this.turns }; } }; function shortJson(value3, limit = 900) { try { const text = JSON.stringify( value3, (_key, val) => typeof val === "string" && val.length > 300 ? `${val.slice(0, 300)}\u2026` : val ); return text.length > limit ? `${text.slice(0, limit)}\u2026` : text; } catch { return "[unserializable]"; } } var SNAPSHOT_TEXT_LIMIT = 4e3; var INITIAL_USER_LABELS = /* @__PURE__ */ new Set([ "delegated_task", "continuation", "context", "prompt" ]); function truncateSnapshotText(text, limit = SNAPSHOT_TEXT_LIMIT) { if (text === void 0) return void 0; const sanitized = sanitizeInteractionTransportText(text); return sanitized.length > limit ? `${sanitized.slice(0, limit - 1)}\u2026` : sanitized; } function eventToolCallId(event) { return event?.toolCallId ?? event?.tool_call_id ?? event?.toolUseId ?? event?.id; } function resultTextFromContent(content) { if (!Array.isArray(content)) return void 0; const text = content.map((part) => { if (!part || typeof part !== "object") return ""; const record = part; return typeof record.text === "string" ? record.text : typeof record.data === "string" ? record.data : ""; }).filter(Boolean).join("\n"); return text || void 0; } function textFromUnknown(value3) { if (typeof value3 === "string") return value3; if (Array.isArray(value3)) return resultTextFromContent(value3); if (!value3 || typeof value3 !== "object") return void 0; const record = value3; return typeof record.text === "string" ? record.text : typeof record.message === "string" ? record.message : resultTextFromContent(record.content); } function steeringQueueTexts(event) { const steering = Array.isArray(event?.steering) ? event.steering : Array.isArray(event?.queue_update?.steering) ? event.queue_update.steering : Array.isArray(event?.queueUpdate?.steering) ? event.queueUpdate.steering : []; return steering.map((entry) => truncateSnapshotText(textFromUnknown(entry))).filter( (text) => Boolean(text?.trim()) ); } function userMessageStartText(event) { if (event?.type !== "message_start" || event?.message?.role !== "user") return void 0; return truncateSnapshotText( textFromUnknown(event.message?.content) ?? textFromUnknown(event.message?.text) ?? textFromUnknown(event.message) ); } function isInitialUserItem(item) { return item.type === "user" && INITIAL_USER_LABELS.has(item.label ?? "user"); } function boundUnknown2(value3, limit = SNAPSHOT_TEXT_LIMIT) { if (typeof value3 === "string") return truncateSnapshotText(value3, limit); if (Array.isArray(value3)) return value3.slice(0, 50).map((entry) => boundUnknown2(entry, limit)); if (!value3 || typeof value3 !== "object") return value3; return Object.fromEntries( Object.entries(value3).slice(0, 50).map(([key3, entry]) => [key3, boundUnknown2(entry, limit)]) ); } function resultPayload(result, isError = false) { let text = ""; let details; if (typeof result === "string") { text = result; details = result; } else if (result && typeof result === "object") { const record = result; details = boundUnknown2(record.details ?? record); const candidate = resultTextFromContent(record.content) ?? record.output ?? record.text ?? record.error ?? record.stderr ?? record.stdout; text = typeof candidate === "string" ? candidate : shortJson(result, SNAPSHOT_TEXT_LIMIT); } else if (result !== void 0) { text = String(result); details = String(result); } const bounded = truncateSnapshotText(text, SNAPSHOT_TEXT_LIMIT) ?? ""; return { content: bounded ? [{ type: "text", text: bounded }] : [], details, isError, preview: bounded }; } function parseRawToolJson(text) { const trimmed = text.trim(); if (!trimmed || !(trimmed.startsWith("{") && trimmed.endsWith("}") || trimmed.startsWith("[") && trimmed.endsWith("]"))) return void 0; try { const parsed = JSON.parse(trimmed); if (!parsed || typeof parsed !== "object") return void 0; return { kind: Array.isArray(parsed) ? "array" : "object", keys: Array.isArray(parsed) ? [] : Object.keys(parsed).slice(0, 20) }; } catch { return void 0; } } var ThreadSnapshotBuilder = class { constructor(prompt, context, cwd, seedSnapshot, promptLabel = "delegated_task", attempt = 1) { this.cwd = cwd; this.createdAt = seedSnapshot?.created_at ?? (/* @__PURE__ */ new Date()).toISOString(); if (isValidThreadSnapshot(seedSnapshot)) this.items.push( ...seedSnapshot.items.map((item) => structuredClone(item)) ); this.currentAttemptStart = this.items.length; this.items.push({ type: "attempt", id: `attempt-${attempt}`, attempt }); if (promptLabel !== "continuation" && context?.trim()) this.items.push({ type: "user", id: "delegated-context", label: "context", text: truncateSnapshotText(context) ?? "" }); if (prompt?.trim()) this.items.push({ type: "user", id: promptLabel === "continuation" ? `continuation-prompt-${attempt}` : "delegated-prompt", label: promptLabel, text: truncateSnapshotText(prompt) ?? "" }); } cwd; createdAt; items = []; toolIndex = /* @__PURE__ */ new Map(); currentAttemptStart; streamingAssistantSequence = 0; steeringSequence = 0; steeringRecords = []; update(event) { const now = (/* @__PURE__ */ new Date()).toISOString(); if (event?.type === "message_end" && event.message?.role === "assistant") { const content = event.message.content; let text = typeof content === "string" ? content : ""; let thinking = ""; if (Array.isArray(content)) { for (const part of content) { if (part?.type === "text" && typeof part.text === "string") text += part.text; if (part?.type === "thinking") { const block = typeof part.thinking === "string" ? part.thinking : part.text; if (typeof block === "string") thinking += block; } } } if (!text && !thinking) return { snapshotChanged: false }; this.appendAssistantBlock(text, thinking); return { snapshotChanged: true }; } if (event?.type === "queue_update") { return this.projectQueuedSteering(event) ? { snapshotChanged: true, activityMessage: "live steering queue updated" } : { snapshotChanged: false }; } if (event?.type === "message_start" && event?.message?.role === "user") { return this.consumeQueuedSteering(event) ? { snapshotChanged: true, activityMessage: "live steering message consumed" } : { snapshotChanged: false }; } if (event?.type === "auto_retry_start" || event?.type === "auto_retry_end" || event?.type === "agent_settled") { const text = event.type === "auto_retry_start" ? "auto retry start" : event.type === "auto_retry_end" ? "auto retry end" : "agent settled (awaiting result)"; this.items.push({ type: "status", text, severity: "info" }); return { snapshotChanged: true }; } if (event?.type === "tool_execution_start") { const name = event.toolName ?? event.name ?? "tool"; const tool_call_id = eventToolCallId(event); this.dropTrailingRawToolJson(name, tool_call_id); const item = { type: "tool", id: tool_call_id, tool_call_id, name, arguments: boundUnknown2(event.args ?? event.input ?? {}), status: "running", started_at: now }; this.toolIndex.set( tool_call_id ?? `item-${this.items.length}`, this.items.length ); this.items.push(item); return { snapshotChanged: true }; } if (event?.type === "tool_execution_end") { const id = eventToolCallId(event); const name = event.toolName ?? event.name ?? "tool"; const index = id ? this.toolIndex.get(id) : void 0; const payload = resultPayload( event.result ?? event.output ?? event.error, Boolean(event.isError) ); if (index === void 0) { this.items.push({ type: "tool_result", id, tool_call_id: id, name, result: payload }); return { snapshotChanged: true }; } const item = this.items[index]; if (item.type === "tool") { item.status = event.isError ? "failed" : "completed"; item.result = payload; item.ended_at = now; } return { snapshotChanged: true }; } return { snapshotChanged: false }; } snapshot(source = "events") { return boundThreadSnapshot( { version: 1, created_at: this.createdAt, updated_at: (/* @__PURE__ */ new Date()).toISOString(), source, items: this.items }, { textLimit: SNAPSHOT_TEXT_LIMIT } ); } finalize(messages) { const messageItems = assistantItemsFromMessages(messages); const priorItems = this.items.slice(0, this.currentAttemptStart); const currentItems = this.items.slice(this.currentAttemptStart); const initialItems = currentItems.filter( (item) => item.type === "attempt" || isInitialUserItem(item) ); const finalMessagesAlreadyHaveThinking = messageItems.some( (item) => item.type === "assistant" && item.message.content.some((part) => part.type === "thinking") ); const eventItems = currentItems.filter((item) => item.type !== "attempt" && !isInitialUserItem(item)).map( (item) => finalizeEventItem( item, messageItems.length > 0, finalMessagesAlreadyHaveThinking ) ).filter((item) => Boolean(item)); const currentAttemptItems = [ ...initialItems, ...messageItems.length ? interleaveMessagesWithToolRows(messageItems, eventItems) : eventItems ]; const items = [...priorItems, ...currentAttemptItems]; const source = messageItems.length && eventItems.length ? "mixed" : messageItems.length ? "session_messages" : "events"; return boundThreadSnapshot( { version: 1, created_at: this.createdAt, updated_at: (/* @__PURE__ */ new Date()).toISOString(), source, items }, { textLimit: SNAPSHOT_TEXT_LIMIT } ); } dropTrailingRawToolJson(toolName, toolCallId) { const item = this.items.at(-1); if (item?.type !== "assistant" || !item.id?.startsWith("streaming-assistant-")) return; const textParts = item.message.content.filter( (part) => part.type === "text" ); if (item.message.content.some((part) => part.type !== "text") || !textParts.length) return; const text = textParts.map((part) => part.text).join(""); const parsed = parseRawToolJson(text); if (!parsed) return; this.items.pop(); writeSubagentsDebugLog(this.cwd, "live_raw_tool_json_dropped", { toolName, toolCallId, jsonKind: parsed.kind, keys: parsed.keys, textLength: text.length }); } /** Preserve the delta-built row grouping, but append only completed blocks. */ appendAssistantBlock(text, thinking) { const last = this.items.at(-1); let item = last?.type === "assistant" && last.id?.startsWith("streaming-assistant-") ? last : void 0; if (!item) { item = { type: "assistant", id: `streaming-assistant-${++this.streamingAssistantSequence}`, message: { role: "assistant", content: [] } }; this.items.push(item); } const content = item.message.content; if (thinking) { let part = content.find((part2) => part2.type === "thinking"); if (!part) { part = { type: "thinking", text: "", thinking: "" }; const firstText = content.findIndex((part2) => part2.type === "text"); if (firstText >= 0) content.splice(firstText, 0, part); else content.push(part); } const combined = truncateSnapshotText( `${part.thinking ?? part.text ?? ""}${thinking}` ) ?? ""; part.text = combined; part.thinking = combined; } if (text) { let part = content.find((part2) => part2.type === "text"); if (!part) { part = { type: "text", text: "" }; content.push(part); } part.text = truncateSnapshotText(`${part.text}${text}`) ?? ""; } } projectQueuedSteering(event) { const pendingByText = /* @__PURE__ */ new Map(); for (const record of this.steeringRecords) { if (record.state !== "queued") continue; const entries = pendingByText.get(record.text) ?? []; entries.push(record); pendingByText.set(record.text, entries); } let changed = false; for (const text of steeringQueueTexts(event)) { const pending = pendingByText.get(text); if (pending?.length) { pending.shift(); continue; } changed = true; const record = { id: `steering-${++this.steeringSequence}`, text, state: "queued" }; this.steeringRecords.push(record); this.items.push({ type: "user", id: record.id, label: "queued", text: record.text }); } return changed; } consumeQueuedSteering(event) { const text = userMessageStartText(event); if (!text) return false; const record = this.steeringRecords.find( (entry) => entry.state === "queued" && entry.text === text ); if (!record) return false; record.state = "consumed"; const index = this.items.findIndex( (item) => item.type === "user" && item.id === record.id ); if (index >= 0) this.items.splice(index, 1); this.items.push({ type: "user", id: record.id, label: "user", text: record.text }); return true; } }; function assistantToolCallIds(item) { const ids = /* @__PURE__ */ new Set(); if (item.type !== "assistant") return ids; for (const part of item.message.content) if (part.type === "toolCall") ids.add(part.id); return ids; } function toolRowId(item) { if (item.type === "tool" || item.type === "tool_result") return item.tool_call_id ?? item.id; if (item.type === "bash") return item.tool_call_id ?? item.id; return void 0; } function interleaveMessagesWithToolRows(messageItems, eventItems) { const used = /* @__PURE__ */ new Set(); const ordered = []; const deferredMessages = []; for (const messageItem of messageItems) { const ids = assistantToolCallIds(messageItem); if (!ids.size) { deferredMessages.push(messageItem); continue; } for (let index = 0; index < eventItems.length; index++) { if (used.has(index)) continue; const id = toolRowId(eventItems[index]); if (id && ids.has(id)) break; ordered.push(eventItems[index]); used.add(index); } ordered.push(messageItem); for (let index = 0; index < eventItems.length; index++) { if (used.has(index)) continue; const id = toolRowId(eventItems[index]); if (id && ids.has(id)) { ordered.push(eventItems[index]); used.add(index); } } } for (let index = 0; index < eventItems.length; index++) if (!used.has(index)) ordered.push(eventItems[index]); ordered.push(...deferredMessages); return ordered; } function assistantItemsFromMessages(messages) { const items = []; for (const msg of messages) { if (msg?.role !== "assistant") continue; if (typeof msg.content === "string") { if (msg.content.trim()) items.push({ type: "assistant", message: { role: "assistant", content: [ { type: "text", text: truncateSnapshotText(msg.content) ?? "" } ], usage: msg.usage } }); continue; } if (!Array.isArray(msg.content)) continue; const content = msg.content.flatMap((part) => { if (part?.type === "text" && typeof part.text === "string") return [ { type: "text", text: truncateSnapshotText(part.text) ?? "" } ]; if (part?.type === "thinking") { const thinking = typeof part.thinking === "string" ? part.thinking : typeof part.text === "string" ? part.text : ""; return thinking ? [ { type: "thinking", text: truncateSnapshotText(thinking), thinking: truncateSnapshotText(thinking) } ] : []; } if ((part?.type === "toolCall" || part?.type === "tool_call") && typeof part.name === "string") return [ { type: "toolCall", id: String( part.id ?? part.toolCallId ?? part.tool_call_id ?? part.name ), name: part.name, arguments: part.arguments ?? part.args ?? part.input ?? {} } ]; return []; }); if (content.length) items.push({ type: "assistant", id: msg.id, message: { role: "assistant", content, stopReason: msg.stopReason, errorMessage: msg.errorMessage, usage: msg.usage } }); } return items; } function finalizeEventItem(item, hasFinalMessages, finalMessagesAlreadyHaveThinking) { if (item.type !== "assistant" || !hasFinalMessages) return item; if (finalMessagesAlreadyHaveThinking) return void 0; const thinkingContent = item.message.content.filter( (part) => part.type === "thinking" && Boolean((part.thinking ?? part.text)?.trim()) ).map((part) => ({ type: "thinking", text: truncateSnapshotText(part.text), thinking: truncateSnapshotText(part.thinking ?? part.text) })); return thinkingContent.length ? { ...item, message: { ...item.message, content: thinkingContent } } : void 0; } // src/runner/tool-stall-budget.ts var DECLARED_TIMEOUT_GRACE_MS = 3e4; function resolveToolStallBudget(toolName, args, toolBudgetMs, maxTotalTimeoutMs) { if (!args || typeof args !== "object") return toolBudgetMs; const values = args; const declared = [ values.timeout_seconds, ...toolName === "bash" || toolName === "powershell" ? [values.timeout] : [] ].filter( (value3) => typeof value3 === "number" && Number.isFinite(value3) && value3 > 0 ); if (!declared.length) return toolBudgetMs; return Math.min( maxTotalTimeoutMs, Math.max( toolBudgetMs, ...declared.map((seconds) => seconds * 1e3 + DECLARED_TIMEOUT_GRACE_MS) ) ); } // src/runner/event-processing.ts function emptyUsage() { return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 }; } function addUsage(total, usage) { return { input: total.input + (usage?.input ?? 0), output: total.output + (usage?.output ?? 0), cacheRead: total.cacheRead + (usage?.cacheRead ?? 0), cacheWrite: total.cacheWrite + (usage?.cacheWrite ?? 0), cost: total.cost + (usage?.cost?.total ?? usage?.cost ?? 0), contextTokens: usage?.totalTokens ?? total.contextTokens, turns: total.turns }; } function summarizeInteractionCarrier(value3) { if (!value3 || typeof value3 !== "object") return { type: typeof value3 }; const record = value3; return { keys: Object.keys(record), hasInteractionRequest: Object.hasOwn(record, "interactionRequest"), hasInteractionRequestSnake: Object.hasOwn(record, "interaction_request"), details: record.details && typeof record.details === "object" ? summarizeInteractionCarrier(record.details) : void 0 }; } function shortJson2(value3, limit = 900) { try { const text = JSON.stringify( value3, (_key, val) => typeof val === "string" && val.length > 300 ? `${val.slice(0, 300)}\u2026` : val ); return text.length > limit ? `${text.slice(0, limit)}\u2026` : text; } catch { return "[unserializable]"; } } function debugLog2(cwd, scope, data) { writeSubagentsDebugLog(cwd, scope, data); } function formatToolCall(name, args) { const input = args ?? {}; if (name === "read") { const file = input.path ?? input.file_path ?? input.file ?? ""; const offset = input.offset ?? 1; const limit = input.limit; const range = limit ? `:${offset}-${offset + limit - 1}` : offset && offset !== 1 ? `:${offset}` : ""; return `read ${file}${range}`.trim(); } if (name === "bash") return `bash ${String(input.command ?? "").split("\n")[0] ?? ""}`.trim(); if (name === "edit") return `edit ${input.path ?? input.file_path ?? ""}`.trim(); if (name === "write") return `write ${input.path ?? input.file_path ?? ""}`.trim(); if (name.startsWith("memory_")) return name; return `${name} ${shortJson2(input)}`.trim(); } function eventTranscript(event) { if (event?.type === "message_end" && event.message?.role === "assistant") return sanitizeInteractionTransportText( assistantMessageText(event.message, "") ); if (event?.type === "tool_execution_start") { const name = event.toolName ?? "tool"; return ` ${formatToolCall(name, event.args ?? event.input ?? {})} `; } if (event?.type === "tool_execution_end") { const result = event.result ?? event.output ?? event.error; const summary2 = result !== void 0 ? ` ${sanitizeInteractionTransportText(shortJson2(result, 500))} ` : ""; return `${summary2} ${event.isError ? "failed" : "done"} `; } if (event?.type === "message_start" && event.message?.role === "assistant") return "\n\nPreparing for response\n\n"; if (event?.type === "auto_retry_start") return "\n\nauto retry start\n"; if (event?.type === "auto_retry_end") return "\n\nauto retry end\n"; if (event?.type === "agent_settled") return "\n\nagent settled (awaiting result)\n"; return ""; } function activityMessage(event, transcriptChunk) { if (!transcriptChunk.trim()) return void 0; if (event?.type === "message_start" && event.message?.role === "assistant") return "preparing response"; if (event?.type === "tool_execution_start") return formatToolCall( event.toolName ?? "tool", event.args ?? event.input ?? {} ); if (event?.type === "tool_execution_end") return event.isError ? "tool failed" : "tool completed"; if (event?.type === "auto_retry_start") return "auto retry start"; if (event?.type === "auto_retry_end") return "auto retry end"; if (event?.type === "agent_settled") return "agent settled (awaiting result)"; return void 0; } function extractStructuredInteractionRequest(value3) { return interactionRequestFromCandidate(value3); } function lastAssistantFailure(messages) { for (let index = messages.length - 1; index >= 0; index--) { const message = messages[index]; if (message?.role !== "assistant") continue; if (message?.stopReason === "error" || message?.stopReason === "aborted" || typeof message?.errorMessage === "string") { return { stopReason: message.stopReason, errorMessage: message.errorMessage }; } } return void 0; } function eventToolCallId2(event) { return event?.toolCallId ?? event?.tool_call_id ?? event?.toolUseId ?? event?.id; } function toolDefinitionFromSession(session, name) { if (!name) return void 0; const direct = session.getToolDefinition?.(name); if (direct) return direct; try { const allTools = session.getAllTools?.(); if (Array.isArray(allTools)) { const info = allTools.find((tool) => tool?.name === name); return info ? resolveSubagentExternalToolDefinitionFromInfo(name, info) ?? info : void 0; } } catch { } return void 0; } function activityLabel(kind, toolNames = []) { if (kind === "thinking") return "thinking"; if (kind === "streaming_response") return "streaming response"; const suffix = toolNames.join(", "); if (kind === "tool_running") return `running tool: ${suffix}`; if (kind === "tool_completed") return `tool completed: ${suffix}`; return `tool failed: ${suffix}`; } var LiveActivityReducer = class { trail = []; activeTools = /* @__PURE__ */ new Map(); current; project() { if (!this.trail.length && !this.current) return void 0; return { trail: this.trail.slice(-3), current: this.current }; } thinking() { return this.push({ kind: "thinking", label: activityLabel("thinking") }); } streaming() { return this.push({ kind: "streaming_response", label: activityLabel("streaming_response") }); } toolStart(id, name) { if (id) this.activeTools.set(id, name); return this.emitRunningTools(); } toolEnd(id, name, failed) { if (id) this.activeTools.delete(id); this.push({ kind: failed ? "tool_failed" : "tool_completed", label: activityLabel(failed ? "tool_failed" : "tool_completed", [name]), tool_names: [name] }); return this.activeTools.size ? this.emitRunningTools() : this.project(); } emitRunningTools() { const toolNames = [...this.activeTools.values()]; return this.push({ kind: "tool_running", label: activityLabel("tool_running", toolNames), tool_names: toolNames }); } push(next) { const last = this.trail.at(-1); if (!last || last.label !== next.label || last.kind !== next.kind) { this.trail.push(next); if (this.trail.length > 3) this.trail = this.trail.slice(-3); } this.current = next; return this.project(); } }; function failingToolNames(snapshot2) { if (!snapshot2?.items?.length) return []; const names = /* @__PURE__ */ new Set(); for (const item of snapshot2.items) { if (item.type === "tool" && item.status === "failed" && item.name) names.add(item.name); if (item.type === "tool_result" && item.result?.isError && item.name) names.add(item.name); if (item.type === "bash" && item.status === "failed") names.add("bash"); } return [...names].slice(0, 3); } function collectFinalizedAssistantText(messages) { for (let index = messages.length - 1; index >= 0; index--) { const message = messages[index]; if (message?.role !== "assistant") continue; if (message?.stopReason === "error" || message?.stopReason === "aborted" || typeof message?.errorMessage === "string") return ""; return assistantMessageText(message).trim(); } return ""; } async function promptWithInactivity(session, prompt, stallTimeoutMs, signal, onActivity, delegatedContext, cwd, systemPrompt, taskId2, promptLabel = "delegated_task", displayPrompt = prompt, attempt = 1, onQueuedMessageStart, previousSnapshot, onQuestionPendingChange, stallSuspendMaxMs = DEFAULT_STALL_SUSPEND_MAX_MS, toolStallTimeoutMs = DEFAULT_TOOL_STALL_TIMEOUT_MS, maxTotalTimeoutMs = DEFAULT_MAX_TOTAL_TIMEOUT_MS) { let output = ""; const snapshotBuilder = new ThreadSnapshotBuilder( displayPrompt, delegatedContext, cwd, previousSnapshot, promptLabel, attempt ); const liveActivity = new LiveActivityReducer(); let latestInteractionRequest; const seenInteractionRequests = /* @__PURE__ */ new Set(); const runtimeMetricsTracker = new SubagentRuntimeMetricsTracker(session); let usage = runtimeMetricsTracker.snapshot().usage ?? emptyUsage(); let transcript = `${systemPrompt ? `# system prompt ${systemPrompt} ` : ""}# ${promptLabel === "continuation" ? "continuation prompt" : "delegated prompt"} ${prompt} # subagent execution `; let lastActivity = Date.now(); let lastSessionEventAt = lastActivity; let lastSessionEventType = "none"; let settledAfterLastStart = false; let stallDetails; let stalled = false; let compactionStartedAt; let retryBackoffStartedAt; const initialMessagesLength = promptLabel === "continuation" && Array.isArray(session.messages) ? session.messages.length : 0; let sawToolActivity = false; let piRetryAttempts = 0; let sawInitialUserMessage = false; const activeToolCalls = /* @__PURE__ */ new Map(); const refreshInactivityBudget = (now = Date.now()) => { lastActivity = now; for (const tool of activeToolCalls.values()) tool.lastUpdate = now; }; const emitActivity = (activity) => { const snapshot2 = runtimeMetricsTracker.snapshot(); usage = snapshot2.usage ?? { ...usage, turns: snapshot2.runtime_metrics.turns ?? usage.turns }; onActivity?.({ ...activity, usage, runtime_metrics: snapshot2.runtime_metrics }); }; emitActivity({ persist: false, message: "session started", prompt, system_prompt: systemPrompt, transcript, thread_snapshot: snapshotBuilder.snapshot(), pi_retry_attempts: piRetryAttempts, live_activity: liveActivity.project() }); const reportInteractionRequest = (request2, thread_snapshot) => { if (seenInteractionRequests.has(request2.requestId)) return; seenInteractionRequests.add(request2.requestId); latestInteractionRequest = request2; debugLog2(cwd, "interaction_bridge_payload_detected", { requestId: request2.requestId, kind: request2.kind, origin: request2.origin, requester: request2.requester, hasPrompt: Boolean(request2.prompt), hasPayload: request2.payload !== void 0 }); emitActivity({ persist: true, message: "interaction required", output, transcript, thread_snapshot: thread_snapshot ?? snapshotBuilder.snapshot(), interaction_request: request2, pi_retry_attempts: piRetryAttempts, live_activity: liveActivity.project() }); }; const unsubscribe = session.subscribe?.((event) => { lastActivity = Date.now(); lastSessionEventAt = lastActivity; lastSessionEventType = typeof event?.type === "string" ? event.type : "unknown"; if (event?.type === "agent_start") settledAfterLastStart = false; if (event?.type === "agent_settled") settledAfterLastStart = true; const observedAt = lastActivity; if (retryBackoffStartedAt !== void 0) { retryBackoffStartedAt = void 0; refreshInactivityBudget(observedAt); } if (event?.type === "auto_retry_start") retryBackoffStartedAt = observedAt; if (event?.type === "compaction_start") compactionStartedAt ??= observedAt; if (event?.type === "compaction_end" && compactionStartedAt !== void 0) { compactionStartedAt = void 0; refreshInactivityBudget(observedAt); } debugLog2(cwd, "runner_event", { type: event?.type, messageRole: event?.message?.role, assistantEventType: event?.assistantMessageEvent?.type, hasDelta: typeof event?.assistantMessageEvent?.delta === "string", toolName: event?.toolName, toolCallId: event?.toolCallId, isError: event?.isError, resultKeys: event?.result && typeof event.result === "object" ? Object.keys(event.result) : void 0, interactionCarrier: event?.type === "tool_execution_end" ? summarizeInteractionCarrier(event?.result) : void 0 }); if (event?.type === "message_update") return; if (event?.type === "tool_execution_update") { const toolCallId2 = eventToolCallId2(event); const toolCall = toolCallId2 && activeToolCalls.get(toolCallId2); if (toolCall) toolCall.lastUpdate = observedAt; const request2 = extractStructuredInteractionRequest( event.partialResult ); if (request2) reportInteractionRequest(request2); return; } if (event?.type === "auto_retry_start") piRetryAttempts += 1; if (event?.type === "message_start" && event?.message?.role === "user") { if (sawInitialUserMessage) onQueuedMessageStart?.(); sawInitialUserMessage = true; } if (typeof event?.type === "string" && event.type.startsWith("tool_execution_")) { sawToolActivity = true; registerSubagentRuntimeToolDefinition( taskId2, event?.toolName, toolDefinitionFromSession(session, event?.toolName) ); const toolCallId2 = eventToolCallId2(event); if (event.type === "tool_execution_start" && toolCallId2) activeToolCalls.set(toolCallId2, { name: event.toolName ?? event.name ?? "tool", startTime: observedAt, lastUpdate: observedAt, budgetMs: resolveToolStallBudget( event.toolName ?? event.name ?? "tool", event.args, Math.max(toolStallTimeoutMs, stallTimeoutMs), maxTotalTimeoutMs ) }); if (event.type === "tool_execution_end" && toolCallId2) activeToolCalls.delete(toolCallId2); } const runtimeSnapshot = runtimeMetricsTracker.observe( event, session, observedAt ); usage = runtimeSnapshot.usage ?? { ...usage, turns: runtimeSnapshot.runtime_metrics.turns ?? usage.turns }; const snapshotUpdate = snapshotBuilder.update(event); const thread_snapshot = snapshotBuilder.snapshot(); const transcriptChunk = eventTranscript(event); transcript += transcriptChunk; const interactionRequest = extractStructuredInteractionRequest( event?.result ?? event ); if (interactionRequest) { reportInteractionRequest(interactionRequest, thread_snapshot); } else if (event?.type === "tool_execution_end" && event?.isError) { const latest = consumeLatestInteractionRequest({ origin: "subagent" }); if (latest) { debugLog2(cwd, "interaction_bridge_payload_recovered_from_channel", { requestId: latest.requestId, kind: latest.kind, origin: latest.origin, requester: latest.requester, hasPrompt: Boolean(latest.prompt), hasPayload: latest.payload !== void 0, carrier: summarizeInteractionCarrier(event.result) }); reportInteractionRequest(latest, thread_snapshot); } else { debugLog2(cwd, "interaction_bridge_payload_missing", { toolName: event.toolName, carrier: summarizeInteractionCarrier(event.result) }); } } if (snapshotUpdate.activityMessage) { emitActivity({ persist: false, message: snapshotUpdate.activityMessage, output, transcript, thread_snapshot, interaction_request: latestInteractionRequest, pi_retry_attempts: piRetryAttempts, live_activity: liveActivity.project() }); } if (event?.type === "message_end" && event.message?.role === "assistant" && !runtimeSnapshot.usage) usage = addUsage(usage, event.message.usage); const assistant_message = event?.type === "message_end" ? assistantAccountingMessage(event.message) : void 0; if (assistant_message) output += transcriptChunk; const message = activityMessage(event, transcriptChunk) ?? (event?.type === "turn_end" ? "turn completed" : event?.type === "compaction_start" ? "context compaction started" : event?.type === "compaction_end" ? event.aborted ? "context compaction aborted" : "context compacted" : void 0); if (!message && !assistant_message) return; const toolCallId = eventToolCallId2(event); const toolName = event?.toolName ?? event?.name ?? "tool"; let projection = liveActivity.project(); if (event?.type === "tool_execution_start") projection = liveActivity.toolStart(toolCallId, toolName); else if (event?.type === "tool_execution_end") projection = liveActivity.toolEnd( toolCallId, toolName, Boolean(event?.isError) ); else if (assistant_message) projection = transcriptChunk.trim() ? liveActivity.streaming() : liveActivity.thinking(); emitActivity({ persist: event?.type === "tool_execution_end" || event?.type === "turn_end", message: message ?? "assistant message completed", ...assistant_message ? { output } : {}, transcript, thread_snapshot, interaction_request: latestInteractionRequest, pi_retry_attempts: piRetryAttempts, live_activity: projection, ...assistant_message ? { assistant_message, observed_at: observedAt } : {} }); }) ?? (() => { }); let questionPending = false; let outstandingQuestions = 0; const unsubscribePending = onQuestionPendingChange?.((pending, count) => { if (questionPending && !pending) { refreshInactivityBudget(); } questionPending = pending; outstandingQuestions = count ?? Number(pending); }); const interval = setInterval( () => { if (stalled) return; const stalledAt = Date.now(); const suspension = compactionStartedAt !== void 0 ? { reason: "compaction", startedAt: compactionStartedAt } : retryBackoffStartedAt !== void 0 ? { reason: "auto_retry", startedAt: retryBackoffStartedAt } : void 0; let budgetKind = "session"; let budgetMs = stallTimeoutMs; if (suspension) { if (stalledAt - suspension.startedAt <= stallSuspendMaxMs) return; } else { if (questionPending) return; if (activeToolCalls.size === 0) { if (stalledAt - lastActivity <= stallTimeoutMs) return; } else { const expiredTool = [...activeToolCalls.values()].find( (tool) => stalledAt - tool.lastUpdate > tool.budgetMs ); if (!expiredTool) return; budgetKind = "tool"; budgetMs = expiredTool.budgetMs; } } stallDetails = { stall_timeout_ms: String(stallTimeoutMs), ...!suspension ? { stall_budget_kind: budgetKind, stall_budget_ms: String(budgetMs) } : {}, ...suspension ? { stall_suspend_max_ms: String(stallSuspendMaxMs), stall_suspend_reason: suspension.reason, ms_since_stall_suspend_start: String( stalledAt - suspension.startedAt ) } : {}, ms_since_last_session_event: String(stalledAt - lastSessionEventAt), last_session_event_type: lastSessionEventType, active_tools: [...activeToolCalls.values()].map( (tool) => `${tool.name} (${stalledAt - tool.lastUpdate}ms since update)` ).join(", ") || "none", settled_after_last_start: String(settledAfterLastStart), outstanding_orchestrator_questions: String(outstandingQuestions) }; stalled = true; const stallMessage = suspension ? `stalled during ${suspension.reason} for ${stallSuspendMaxMs}ms; aborting session` : `stalled for ${budgetMs}ms (${budgetKind} budget); aborting session`; transcript += ` --- stall --- ${stallMessage} `; emitActivity({ persist: false, message: stallMessage, output, transcript, thread_snapshot: snapshotBuilder.snapshot(), interaction_request: latestInteractionRequest, pi_retry_attempts: piRetryAttempts, live_activity: liveActivity.project() }); session.abort?.().catch?.(() => { }); }, Math.min(5e3, Math.max(500, stallTimeoutMs / 4)) ); try { let promptError; try { if (signal.aborted) throw new Error("Subagent was aborted"); await session.prompt(prompt); } catch (error) { promptError = error; } runtimeMetricsTracker.refresh(session); const finalRuntimeSnapshot = runtimeMetricsTracker.snapshot(); usage = finalRuntimeSnapshot.usage ?? { ...usage, turns: finalRuntimeSnapshot.runtime_metrics.turns ?? usage.turns }; const currentMessages = (session.messages ?? []).slice( initialMessagesLength ); const thread_snapshot = snapshotBuilder.finalize(currentMessages); debugLog2(cwd, "runner_final_snapshot", { source: thread_snapshot?.source, items: thread_snapshot?.items.map((item) => ({ type: item.type, label: item.label, name: item.name, status: item.status, assistantContent: item.type === "assistant" ? item.message.content.map((part) => part.type) : void 0 })) }); if (stalled) { const metadata = normalizeErrorMetadata({ category: "stall_timeout", phase: "runner_session", partial_result_available: Boolean( output.trim() || thread_snapshot?.items?.length ), details: stallDetails }); transcript += ` # subagent failure ${metadata.message}`; emitActivity({ persist: false, message: `failed: ${metadata.message}`, output: "", transcript, usage, thread_snapshot, interaction_request: latestInteractionRequest, pi_retry_attempts: piRetryAttempts, live_activity: liveActivity.project() }); throw new SubagentStructuredError(metadata); } const assistantFailure = lastAssistantFailure(currentMessages); if (assistantFailure) { const metadata = assistantFailure.stopReason === "aborted" ? normalizeErrorMetadata({ category: "interrupted", phase: "assistant_final", message: "Assistant aborted without a final response.", partial_result_available: false, details: { interrupt_reason: "assistant_aborted" } }) : classifyAssistantFailure({ ...assistantFailure, sawToolActivity }); if (metadata) { transcript += ` # subagent failure ${metadata.message}`; emitActivity({ persist: false, message: `failed: ${metadata.message}`, output: "", transcript, usage, thread_snapshot, interaction_request: latestInteractionRequest, pi_retry_attempts: piRetryAttempts, live_activity: liveActivity.project() }); throw new SubagentStructuredError(metadata); } } const finalizedAssistantText = collectFinalizedAssistantText(currentMessages); if (promptError && finalizedAssistantText) { transcript += ` # final assistant text ${finalizedAssistantText}`; emitActivity({ persist: false, message: "collected final response", output: finalizedAssistantText, transcript, usage, thread_snapshot, interaction_request: latestInteractionRequest, pi_retry_attempts: piRetryAttempts, live_activity: liveActivity.project() }); return { result: finalizedAssistantText, usage, runtime_metrics: finalRuntimeSnapshot.runtime_metrics, thread_snapshot, interaction_request: latestInteractionRequest }; } if (promptError) throw promptError; const messageText = collectAssistantText(currentMessages); const streamedFallback = sawToolActivity ? "" : output.trim(); const collected = sanitizeInteractionTransportText( messageText || streamedFallback ); if (!collected.trim()) { const toolNames = failingToolNames(thread_snapshot); const metadata = toolNames.length ? normalizeErrorMetadata({ category: "tool_failure", phase: "tool_execution", message: "Subagent terminated after tool failure without a final response.", partial_result_available: false, source: { tool: toolNames[0], operation: "tool_execution" }, details: { tool_names: toolNames.join(", "), tool_status: "failed" } }) : classifyAssistantFailure({ sawToolActivity }) ?? normalizeErrorMetadata({ category: sawToolActivity ? "empty_response_after_tools" : "empty_response_no_tools", phase: "assistant_final", message: sawToolActivity ? "Subagent completed tool execution but did not produce a final response." : "Subagent finished without a final response.", partial_result_available: false }); transcript += ` # subagent failure ${metadata.message}`; emitActivity({ persist: false, message: `failed: ${metadata.message}`, output: "", transcript, usage, thread_snapshot, interaction_request: latestInteractionRequest, pi_retry_attempts: piRetryAttempts, live_activity: liveActivity.project() }); throw new SubagentStructuredError(metadata); } transcript += ` # final assistant text ${collected}`; emitActivity({ persist: false, message: "collected final response", output: collected, transcript, usage, thread_snapshot, interaction_request: latestInteractionRequest, pi_retry_attempts: piRetryAttempts, live_activity: liveActivity.project() }); return { result: collected, usage, runtime_metrics: finalRuntimeSnapshot.runtime_metrics, thread_snapshot, interaction_request: latestInteractionRequest }; } finally { clearInterval(interval); unsubscribePending?.(); unsubscribe(); await teardownSubagentSession(session); } } function assistantMessageText(message, separator = "\n") { const content = message?.content; if (typeof content === "string") return content; if (!Array.isArray(content)) return ""; return content.filter((part) => part?.type === "text" && typeof part.text === "string").map((part) => part.text).join(separator); } function collectAssistantText(messages) { for (let index = messages.length - 1; index >= 0; index--) { const msg = messages[index]; if (msg?.role !== "assistant") continue; const text = assistantMessageText(msg).trim(); if (text) return text; } return ""; } function structuredMetadataFromError(error, context) { if (error instanceof SubagentStructuredError) return error.error_metadata; return classifyThrownError(error, context); } // src/runner/interaction-session-registry.ts var SUBAGENT_INTERACTION_SESSION_REGISTRY_KEY = /* @__PURE__ */ Symbol.for( "pi.subagents.interactionSessions" ); function getInteractionSessionRegistry() { const globalRecord = globalThis; globalRecord[SUBAGENT_INTERACTION_SESSION_REGISTRY_KEY] ??= /* @__PURE__ */ new Map(); return globalRecord[SUBAGENT_INTERACTION_SESSION_REGISTRY_KEY]; } // src/runner/lean-resources.ts import fs8 from "node:fs"; import path8 from "node:path"; // src/runner/orca-managed-extensions.ts import fs7 from "node:fs"; import path7 from "node:path"; var MARKER = "@orca-managed-pi-extension"; var PREFIX_BYTES = 4096; var cache = /* @__PURE__ */ new Map(); var loggedExclusions = /* @__PURE__ */ new Set(); function isOrcaManaged(file, cwd) { try { const stat = fs7.statSync(file); const { mtimeMs, size } = stat; const cached = cache.get(file); if (cached?.mtimeMs === mtimeMs && cached.size === size) return cached.managed; if (!stat.isFile()) { cache.set(file, { mtimeMs, size, managed: false }); return false; } const fd = fs7.openSync(file, "r"); let managed; try { const prefix = Buffer.alloc(Math.min(size, PREFIX_BYTES)); const bytes = fs7.readSync(fd, prefix, 0, prefix.length, 0); managed = prefix.toString("utf8", 0, bytes).includes(MARKER); } finally { fs7.closeSync(fd); } cache.set(file, { mtimeMs, size, managed }); return managed; } catch (error) { writeSubagentsDebugLog(cwd, "orca_extension_read_error", { file, error }); return false; } } function excludeOrcaManagedExtensions(paths, cwd) { const newlyExcluded = []; const kept = paths.filter((entry) => { if (entry.startsWith("builtin:")) return true; const file = path7.resolve(cwd, entry); if (!isOrcaManaged(file, cwd)) return true; if (!loggedExclusions.has(file)) { loggedExclusions.add(file); newlyExcluded.push(file); } return false; }); if (newlyExcluded.length) writeSubagentsDebugLog(cwd, "orca_extensions_excluded", { paths: newlyExcluded }); return kept; } // src/runner/lean-resources.ts async function leanResources(sdk, cwd, agentDir2, ctx, enabled, filter, diagnostic) { const SettingsManager = sdk.SettingsManager; const parentCwd = ctx?.sessionManager?.getCwd?.() ?? ctx?.cwd; let withinParent = false; try { if (typeof parentCwd !== "string") throw new Error("Parent project root unavailable"); const canonicalParent = fs8.realpathSync.native(parentCwd); const canonicalChild = fs8.realpathSync.native(cwd); const normalizeCase = (value3) => process.platform === "win32" ? value3.toLowerCase() : value3; const relative = path8.relative( normalizeCase(canonicalParent), normalizeCase(canonicalChild) ); withinParent = relative !== ".." && !relative.startsWith(`..${path8.sep}`) && !path8.isAbsolute(relative); if (!withinParent) diagnostic( "Child project is outside the canonical parent project; using persisted trust only." ); } catch (error) { diagnostic( `Canonical project containment unavailable; using persisted trust only: ${String(error)}` ); } let trusted = false; try { if (withinParent) { const trust = ctx?.isProjectTrusted?.() ?? ctx?.settingsManager?.isProjectTrusted?.(); trusted = trust === true; if (typeof trust !== "boolean") diagnostic( "Parent project trust API unavailable; project skills excluded." ); } else if (typeof sdk.ProjectTrustStore === "function") { trusted = new sdk.ProjectTrustStore(agentDir2).get(cwd) === true; } else { diagnostic("ProjectTrustStore unavailable; project skills excluded."); } } catch (error) { diagnostic( `Project trust unavailable; project skills excluded: ${String(error)}` ); } let settingsManager; if (typeof SettingsManager?.create === "function") { settingsManager = SettingsManager.create(cwd, agentDir2, { projectTrusted: trusted }); if (typeof settingsManager.setProjectTrusted === "function") settingsManager.setProjectTrusted(trusted); else { diagnostic( "SettingsManager trust API unavailable; project resources excluded." ); trusted = false; settingsManager = SettingsManager.inMemory( settingsManager.getGlobalSettings?.() ?? {}, { projectTrusted: false } ); } const parentGlobal = ctx?.settingsManager?.getGlobalSettings?.(); if (parentGlobal && typeof SettingsManager.fromStorage === "function") { const snapshots = { global: JSON.stringify({ ...settingsManager.getGlobalSettings(), ...parentGlobal }), project: JSON.stringify( trusted ? settingsManager.getProjectSettings() : {} ) }; settingsManager = SettingsManager.fromStorage( { withLock(scope, update) { const next = update(snapshots[scope]); if (next !== void 0) snapshots[scope] = next; } }, { projectTrusted: trusted } ); } } else { diagnostic( "Child settings discovery unavailable; project resources excluded." ); trusted = false; settingsManager = SettingsManager.inMemory( ctx?.settingsManager?.getGlobalSettings?.() ?? {}, { projectTrusted: false } ); } let resolved = { extensions: [], skills: [] }; if (typeof sdk.DefaultPackageManager === "function") { try { const packages = new sdk.DefaultPackageManager({ cwd, agentDir: agentDir2, settingsManager }); if (typeof packages.resolve !== "function" || packages.resolve.length < 1) { diagnostic( "Offline package resolver missing skip-handler API; child catalog omitted." ); } else { resolved = await packages.resolve(async (source) => { diagnostic( `Missing package skipped (offline child discovery): ${source}` ); return "skip"; }); } } catch (error) { diagnostic( `Offline child resource discovery failed; affected entries omitted: ${String(error)}` ); } } else { diagnostic( "DefaultPackageManager unavailable; child skill catalog omitted." ); } const loaderSettings = SettingsManager.inMemory( { ...settingsManager.getSettings(), packages: [], extensions: [], skills: [], prompts: [], themes: [] }, { projectTrusted: trusted } ); const enabledPaths = (entries) => entries.filter( (entry) => entry.enabled && (trusted || entry.metadata.scope !== "project") ).map((entry) => entry.path); return { settingsManager, loaderSettings, additionalExtensionPaths: excludeOrcaManagedExtensions( enabledPaths(resolved.extensions), cwd ), additionalSkillPaths: enabled ? enabledPaths(resolved.skills) : [], skillsOverride: (base) => { const visible2 = enabled ? base.skills.filter((skill) => !skill.disableModelInvocation) : []; if (enabled && filter) { for (const pattern of filter) { if (!visible2.some((skill) => path8.matchesGlob(skill.name, pattern))) diagnostic(`Skill filter matched no visible skill: ${pattern}`); } } return { ...base, skills: filter ? visible2.filter( (skill) => filter.some((pattern) => path8.matchesGlob(skill.name, pattern)) ) : visible2 }; } }; } // src/runner/orchestrator-tool.ts import { Type } from "typebox"; var parameters = Type.Object( { message: Type.String({ minLength: 1 }) }, { additionalProperties: false } ); function createAskOrchestratorTool(channel) { return { name: "ask_orchestrator", exposure: "model-only", label: "Ask Orchestrator", description: "Ask the owning orchestrator a blocking alignment question. Returns the orchestrator reply. This is not a human question or delegation tool.", parameters, async execute(_id, params, signal) { if (!channel) throw new Error("ask_orchestrator has no owning task channel."); if (signal?.aborted) throw new Error("ask_orchestrator call cancelled."); const reply = await channel.askQuestion(params.message, signal); return { content: [{ type: "text", text: reply }], details: {} }; } }; } function createNotifyOrchestratorTool(channel) { return { name: "notify_orchestrator", exposure: "model-only", label: "Notify Orchestrator", description: "Report progress to the owning orchestrator without waiting for a reply or triggering a root turn.", parameters, async execute(_id, params, signal) { if (!channel) throw new Error("notify_orchestrator has no owning task channel."); if (signal?.aborted) throw new Error("notify_orchestrator call cancelled."); channel.reportProgress(params.message); return { content: [{ type: "text", text: "Progress recorded." }], details: {} }; } }; } // src/runner/pi-sdk-module.ts var moduleName = "@earendil-works/pi-coding-agent"; var MIN_PI_VERSION = [1, 5, 0]; var piSdkModulePromise; function loadPiSdkModule() { piSdkModulePromise ??= import(moduleName); return piSdkModulePromise; } function parseVersion(text) { if (!text) return void 0; const match = text.trim().match(/^(\d+)\.(\d+)\.(\d+)/); return match ? match.slice(1).map(Number) : void 0; } function versionGte(version, minimum) { for (let index = 0; index < minimum.length; index += 1) { const current = version[index] ?? 0; const required = minimum[index] ?? 0; if (current > required) return true; if (current < required) return false; } return true; } function detectPiRuntimeSupport(version) { const detected = typeof version === "string" && version.trim() ? version.trim() : "unknown"; const parsed = parseVersion(detected); return { detected_pi_version: detected, supported: Boolean(parsed && versionGte(parsed, MIN_PI_VERSION)), required_pi_version: ">=1.5.0" }; } // src/runner/sdk-runner.ts function modelLabel2(model) { if (!model) return void 0; return `${model.provider ?? "unknown"}/${model.id ?? model.name ?? "unknown"}`; } function modelRefLabel(ref) { return ref ? `${ref.provider}/${ref.id}` : void 0; } function resolveModel2(ctx, ref) { if (!ref) return void 0; return ctx?.modelRuntime?.getModel?.(ref.provider, ref.id) ?? ctx?.modelRegistry?.find?.(ref.provider, ref.id); } function namesFromTools(value3) { if (!Array.isArray(value3)) return void 0; return value3.map( (tool) => typeof tool === "string" ? tool : tool?.name ).filter( (name) => typeof name === "string" && name.length > 0 ); } function readToolNames(context, methodNames) { for (const methodName of methodNames) { for (const source of [context?.pi, context]) { const getter = source?.[methodName]; if (typeof getter !== "function") continue; try { const names = namesFromTools(getter.call(source)); if (names) return names; } catch { } } } return void 0; } function resolveConfiguredTools(patterns, context, disallowedTools, enableAskOrchestrator, enableNotifyOrchestrator, overlay) { const registered = [...patterns, ...overlay?.add ?? []].some(hasToolGlob) ? readToolNames(context, ["getAllTools"]) : void 0; try { const permitted = resolveEffectiveToolSelection( patterns, registered, disallowedTools, enableAskOrchestrator, enableNotifyOrchestrator, overlay ); if (!permitted.length) throw new Error( "The effective permitted tool selection is empty. Check tools, disallowed_tools and orchestrator tool flags." ); return permitted; } catch (error) { throw new NonRetryableSubagentError(error.message); } } function verifyChildToolSelection(session, selectedToolNames) { const registered = readToolNames(session, ["getAllTools"]); if (!registered) throw new NonRetryableSubagentError( "The child Pi session cannot verify selected tools. Upgrade the Pi SDK to expose getAllTools(), then retry." ); const registeredNames = new Set(registered); const selectedNames = new Set(selectedToolNames); const missing = selectedToolNames.filter( (name) => !registeredNames.has(name) ); const unexpected = registered.filter((name) => !selectedNames.has(name)); if (unexpected.length || missing.length && missing.length === selectedToolNames.length) { const details = [ missing.length ? `missing implementation: ${missing.join(", ")}` : "", unexpected.length ? `unexpectedly registered: ${unexpected.join(", ")}` : "" ].filter(Boolean); throw new NonRetryableSubagentError( `Selected tools are unavailable in the child session (${details.join("; ")}). Check that their extensions are installed and loadable by the child session.` ); } return missing; } var SUBAGENT_ALLOWED_EXTENSION_EVENTS = /* @__PURE__ */ new Set([ "tool_call", "tool_result", "user_bash" ]); var NonRetryableSubagentError = class extends SubagentStructuredError { nonRetryable = true; constructor(message) { super({ version: 1, category: "unknown", message, retryable: false, phase: "runner_session", partial_result_available: false }); } }; function isNonRetryableSubagentError(error) { return Boolean( error && typeof error === "object" && error.nonRetryable ); } var SUBAGENT_OBSERVE_ONLY_EVENTS = /* @__PURE__ */ new Set([ "before_agent_start", "agent_start", "turn_start", "context", "context_with_system", "input", "before_provider_request", "before_provider_headers" ]); function cloneEventData(value3, seen = /* @__PURE__ */ new Map()) { if (value3 === null || typeof value3 !== "object") return value3; if (seen.has(value3)) return seen.get(value3); if (value3 instanceof Map) { const clone = /* @__PURE__ */ new Map(); seen.set(value3, clone); for (const [key3, entry] of value3) clone.set(cloneEventData(key3, seen), cloneEventData(entry, seen)); return clone; } if (value3 instanceof Set) { const clone = /* @__PURE__ */ new Set(); seen.set(value3, clone); for (const entry of value3) clone.add(cloneEventData(entry, seen)); return clone; } const prototype = Object.getPrototypeOf(value3); if (Array.isArray(value3) || prototype === Object.prototype || prototype === null) { const clone = Array.isArray(value3) ? new Array(value3.length) : Object.create(prototype); seen.set(value3, clone); for (const key3 of Object.keys(value3)) Object.defineProperty(clone, key3, { value: cloneEventData(value3[key3], seen), enumerable: true, configurable: true, writable: true }); return clone; } if (value3 instanceof Date || value3 instanceof RegExp || value3 instanceof ArrayBuffer || ArrayBuffer.isView(value3)) { const clone = structuredClone(value3); seen.set(value3, clone); return clone; } return value3; } function extensionPackageName(resolvedPath, cache2) { if (typeof resolvedPath !== "string") return void 0; try { let dir = path9.dirname(fs9.realpathSync(resolvedPath)); const visited = []; let name; while (true) { if (cache2.has(dir)) { name = cache2.get(dir); break; } visited.push(dir); const manifestPath = path9.join(dir, "package.json"); try { fs9.lstatSync(manifestPath); } catch (error) { if (error.code !== "ENOENT") break; const parent = path9.dirname(dir); if (parent === dir) break; dir = parent; continue; } try { const manifest = JSON.parse(fs9.readFileSync(manifestPath, "utf8")); name = typeof manifest?.name === "string" ? manifest.name : void 0; } catch { } break; } for (const directory of visited) cache2.set(directory, name); return name; } catch { return void 0; } } function isolateSubagentExtensions(base, packages, backgroundShutdown) { const listedPackages = new Set(packages); const packageNames = /* @__PURE__ */ new Map(); const providerOwners = new Set( (base?.runtime?.pendingProviderRegistrations ?? []).map( (registration2) => registration2.extensionPath ) ); return { ...base, extensions: (base?.extensions ?? []).map((extension) => { const name = extensionPackageName(extension.resolvedPath, packageNames); const passthrough = name !== void 0 && name !== "thoth-agents" && listedPackages.has(name); const handlers = /* @__PURE__ */ new Map(); for (const [event, callbacks] of extension.handlers ?? /* @__PURE__ */ new Map()) { if (passthrough && name === "@thoth-agents/pi-background-tasks" && event === "session_shutdown") { backgroundShutdown.push(...callbacks); } else if (passthrough && event === "before_provider_request") { handlers.set( event, callbacks.map( (handler) => (event2, ctx) => handler(cloneEventData(event2), ctx) ) ); } else if (passthrough && SUBAGENT_OBSERVE_ONLY_EVENTS.has(event)) { handlers.set( event, callbacks.map((handler) => async (event2, ctx) => { await handler(cloneEventData(event2), ctx); }) ); } else if (passthrough || SUBAGENT_ALLOWED_EXTENSION_EVENTS.has(event) || event === "session_shutdown" && providerOwners.has(extension.path)) { handlers.set(event, callbacks); } } return { ...extension, handlers, commands: /* @__PURE__ */ new Map(), flags: /* @__PURE__ */ new Map(), shortcuts: /* @__PURE__ */ new Map() }; }) }; } function registerInteractionSubagentSession(session, definition, taskId2, parentPiSessionId) { const sessionId = session?.sessionManager?.getSessionId?.() ?? session?.sessionId; if (typeof sessionId !== "string" || sessionId.length === 0) return () => void 0; const registry5 = getInteractionSessionRegistry(); const previous = registry5.get(sessionId); registry5.set(sessionId, { origin: "subagent", requester: { subagentName: definition.name, description: definition.description, taskId: taskId2 }, parent: parentPiSessionId ? { piSessionId: parentPiSessionId } : void 0 }); return () => { if (previous) registry5.set(sessionId, previous); else registry5.delete(sessionId); }; } function resolveNestedSessionsHome() { const home = path9.join(resolveSubagentsHistoryHome(), "sessions"); fs9.mkdirSync(home, { recursive: true, mode: 448 }); try { fs9.chmodSync(home, 448); } catch { } return home; } function sessionPathFromManager(sessionManager, fallback) { const direct = sessionManager?.getSessionFile?.() ?? sessionManager?.path ?? sessionManager?.sessionPath ?? fallback; return typeof direct === "string" && direct.length > 0 ? direct : void 0; } function secureSessionPath(sessionPath) { if (!sessionPath) return; try { fs9.mkdirSync(path9.dirname(sessionPath), { recursive: true, mode: 448 }); fs9.chmodSync(path9.dirname(sessionPath), 448); } catch { } try { fs9.chmodSync(sessionPath, 384); } catch { } } async function secureSessionPathWhenReady(sessionPath, attempts = 10, delayMs = 10) { if (!sessionPath) return; secureSessionPath(sessionPath); for (let attempt = 0; attempt < attempts; attempt += 1) { try { if (fs9.existsSync(sessionPath)) { fs9.chmodSync(sessionPath, 384); return; } } catch { } if (attempt < attempts - 1) await new Promise((resolve3) => setTimeout(resolve3, delayMs)); } } function versionFromPiSdk(piSdk) { try { return piSdk?.VERSION; } catch { return void 0; } } async function emitChildSessionStart(session, onActivity) { const errors = []; let unsubscribe; try { const runner = session.extensionRunner; if (!runner) throw new Error("Child Pi session has no extension runner."); unsubscribe = runner.onError((error) => errors.push(error)); await runner.emit({ type: "session_start", reason: "startup" }); } catch (error) { errors.push(error); } finally { unsubscribe?.(); } for (const error of errors) { onActivity?.({ diagnostic: true, message: `session_start handler error${error?.extensionPath ? ` (${error.extensionPath})` : ""}: ${error?.error ?? error?.message ?? String(error)}` }); } } function selectedBuiltinExtensionFactories(piSdk, tools) { return [ ...tools.includes("codemode") ? [piSdk.createCodemodeExtension({ mode: "on" })] : [], ...tools.includes("tool_search") ? [piSdk.createToolSearchExtension()] : [] ]; } async function createSession(model, cwd, tools, effort, config, ctx, systemPrompt, nestedSessionPath, onActivity, orchestratorChannel, skillFilter) { const piSdk = await loadPiSdkModule(); const { createAgentSession, SessionManager } = piSdk; const sessionDir = resolveNestedSessionsHome(); const sessionManager = nestedSessionPath ? await SessionManager.open(nestedSessionPath, sessionDir, cwd) : typeof SessionManager.create === "function" ? await SessionManager.create(cwd, sessionDir, { cwd }) : SessionManager.inMemory(cwd); const resolvedSessionPath = sessionPathFromManager( sessionManager, nestedSessionPath ); await secureSessionPathWhenReady(resolvedSessionPath); const options = { cwd, model, thinkingLevel: effort, tools, customTools: [ ...tools.includes("ask_orchestrator") ? [createAskOrchestratorTool(orchestratorChannel)] : [], ...tools.includes("notify_orchestrator") ? [createNotifyOrchestratorTool(orchestratorChannel)] : [] ], sessionManager }; const modelRuntime = ctx?.modelRuntime ?? await piSdk.ModelRuntime.create({ allowModelNetwork: false }); options.modelRuntime = modelRuntime; if (ctx?.settingsManager) options.settingsManager = ctx.settingsManager; const backgroundShutdown = []; const DefaultResourceLoader = piSdk.DefaultResourceLoader; const agentDir2 = typeof piSdk.getAgentDir === "function" ? piSdk.getAgentDir() : void 0; if (config.session_resources === "lean") { if (typeof DefaultResourceLoader !== "function") throw new Error( "Subagent lean session resources require DefaultResourceLoader from Pi SDK." ); const diagnostic = (message) => onActivity?.({ diagnostic: true, message }); const resources = await leanResources( piSdk, cwd, agentDir2, ctx, config.lean_skills !== false, skillFilter, diagnostic ); options.settingsManager = resources.settingsManager; const lifecyclePassthrough = (config.lifecycle_passthrough ?? DEFAULT_LIFECYCLE_PASSTHROUGH).filter( (name) => model?.api === "pi-virtual" || name !== OPENAI_FAST_PACKAGE ); const resourceLoader = new DefaultResourceLoader({ cwd, agentDir: agentDir2, settingsManager: resources.loaderSettings, noExtensions: true, extensionFactories: selectedBuiltinExtensionFactories(piSdk, tools), additionalExtensionPaths: resources.additionalExtensionPaths, additionalSkillPaths: resources.additionalSkillPaths, skillsOverride: resources.skillsOverride, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true, systemPromptOverride: () => systemPrompt, appendSystemPromptOverride: () => [], extensionsOverride: (base) => isolateSubagentExtensions( base, lifecyclePassthrough, backgroundShutdown ) }); await resourceLoader.reload(); for (const entry of resourceLoader.getSkills?.().diagnostics ?? []) diagnostic( `Skill discovery: ${entry.message}${entry.path ? ` (${entry.path})` : ""}` ); options.agentDir = agentDir2; options.resourceLoader = resourceLoader; } else { const settingsManager = ctx?.settingsManager ?? piSdk.SettingsManager.create(cwd, agentDir2); await settingsManager.reload(); const packages = new piSdk.DefaultPackageManager({ cwd, agentDir: agentDir2, settingsManager }); const resolved = await packages.resolve(); const resourceLoader = new DefaultResourceLoader({ cwd, agentDir: agentDir2, settingsManager, noExtensions: true, extensionFactories: selectedBuiltinExtensionFactories(piSdk, tools), additionalExtensionPaths: excludeOrcaManagedExtensions( resolved.extensions.filter((entry) => entry.enabled).map((entry) => entry.path), cwd ) }); await resourceLoader.reload(); options.settingsManager = settingsManager; options.agentDir = agentDir2; options.resourceLoader = resourceLoader; } const created = await createAgentSession(options); registerChildBackgroundShutdown(created.session, backgroundShutdown); let droppedTools; try { if (!ctx?.modelRuntime) { const childProviders = new Set(modelRuntime.getRegisteredProviderIds()); for (const providerId of ctx?.modelRegistry?.getRegisteredProviderIds?.() ?? []) { if (childProviders.has(providerId)) continue; const providerConfig = ctx.modelRegistry.getRegisteredProviderConfig(providerId); const nativeProvider = ctx.modelRegistry.getRegisteredNativeProvider(providerId); if (providerConfig) modelRuntime.registerProvider(providerId, providerConfig); else if (nativeProvider) modelRuntime.registerNativeProvider(nativeProvider); else throw new NonRetryableSubagentError( `Cannot replay parent provider ${providerId} through public registry APIs.` ); } await modelRuntime.refresh({ allowNetwork: false }); } droppedTools = verifyChildToolSelection(created.session, tools); await emitChildSessionStart(created.session, onActivity); } catch (error) { await teardownSubagentSession(created.session); throw error; } return { ...created, dropped_tools: droppedTools, nested_session_path: resolvedSessionPath, pi_version: versionFromPiSdk(piSdk) }; } function createSessionAbortBridge(session, signal) { let abortPromise; const abortSession = async () => { if (!abortPromise) { abortPromise = Promise.resolve(session?.abort?.()).then( () => void 0, () => void 0 ); } await abortPromise; }; const onAbort = () => { void abortSession(); }; signal.addEventListener("abort", onAbort, { once: true }); return { abortSession, dispose() { signal.removeEventListener("abort", onAbort); } }; } function selectedModel(input) { const ref = input.profile.model.value; if (!ref) return input.ctx?.model; if (input.profile.model.source === "orchestrator") return input.ctx?.model ?? resolveModel2(input.ctx, ref); const resolved = resolveModel2(input.ctx, ref); if (!resolved) throw new Error( `Subagent ${input.definition.name} could not resolve selected model ${modelRefLabel(ref)} (${input.profile.model.source}).` ); return resolved; } function providerFromModel(model) { return typeof model?.provider === "string" ? model.provider : void 0; } function createLiveSteeringBridge(session, piVersion) { const runtime = detectPiRuntimeSupport(piVersion); const canSteer = typeof session?.steer === "function"; return { detected_pi_version: runtime.detected_pi_version, supported: runtime.supported && canSteer, async steer(message) { if (!canSteer) throw new Error( "Live steering is unavailable for this nested session." ); return await session.steer(message); } }; } var sdkSubagentRunner = async ({ definition, task, taskId: taskId2, parentPiSessionId, context, cwd, ctx, config, signal, effectiveProfile, nested_session_path, continuation, registerLiveBridge, clearLiveBridge, onQueuedMessageStart, orchestratorChannel, onActivity }) => { if (config.session_resources === "lean") { const diagnostics = []; const reportActivity = onActivity; onActivity = (activity) => { if (activity.diagnostic) diagnostics.push(activity.message); const transcript = diagnostics.length && (activity.transcript || activity.diagnostic) ? `# child resource diagnostics ${diagnostics.join("\n")} ${activity.transcript ?? ""}` : activity.transcript; reportActivity?.({ ...activity, transcript }); }; } const profile = effectiveProfile ?? resolveEffectiveSubagentProfile({ agentName: definition.name, definition, config, ctx: { ...ctx, cwd } }); for (const warning of profile.warnings ?? []) onActivity?.({ message: warning, diagnostic: true }); const preferred = selectedModel({ ctx, definition, profile }); const effort = profile.effort.value; const configuredTools = definition.tools?.length ? definition.tools : config.default_tools; const tools = resolveConfiguredTools( configuredTools, ctx, definition.disallowed_tools ?? [], config.enable_ask_orchestrator !== false, config.enable_notify_orchestrator !== false, definition.toolOverlay ); const systemPrompt = definition.instructions; const prompt = continuation?.prompt ?? buildPrompt(definition, task, context, tools); onActivity?.({ persist: true, message: continuation ? "continuation prompt prepared" : "orchestrator prompt prepared", prompt, system_prompt: systemPrompt, transcript: `# system prompt ${systemPrompt} # ${continuation ? "continuation prompt" : "delegated prompt"} ${prompt} `, effort }); async function attempt(model) { onActivity?.({ persist: true, notify_orchestrator_available: false, message: `starting ${definition.name} with model ${modelLabel2(model) ?? "unknown"}${effort ? ` effort ${effort}` : ""}`, prompt, system_prompt: systemPrompt, effort }); const { session, nested_session_path: resolvedNestedSessionPath, pi_version: piVersion, dropped_tools } = await createSession( model, cwd, tools, effort, config, ctx, systemPrompt, nested_session_path, onActivity, orchestratorChannel, definition.skills ); const abortBridge = createSessionAbortBridge(session, signal); let unregisterInteractionSession = () => { }; try { registerLiveBridge?.(createLiveSteeringBridge(session, piVersion)); onActivity?.({ persist: true, message: "nested session ready", notify_orchestrator_available: tools.includes("notify_orchestrator") && !dropped_tools.includes("notify_orchestrator"), dropped_tools, nested_session_path: resolvedNestedSessionPath }); unregisterInteractionSession = registerInteractionSubagentSession( session, definition, taskId2, parentPiSessionId ?? ctx?.sessionManager?.getSessionId?.() ); if (signal.aborted) { await abortBridge.abortSession(); throw new Error("Subagent was aborted"); } const effectiveSystemPrompt = typeof session.systemPrompt === "string" ? session.systemPrompt : systemPrompt; const { result, usage, runtime_metrics, thread_snapshot, interaction_request } = await promptWithInactivity( session, prompt, config.stall_timeout_ms, signal, onActivity, context, cwd, effectiveSystemPrompt, taskId2, continuation ? "continuation" : "delegated_task", continuation?.prompt ?? task, continuation?.attempt ?? 1, onQueuedMessageStart, continuation?.previous_snapshot, orchestratorChannel?.onPendingChange, config.stall_suspend_max_ms, config.tool_stall_timeout_ms, config.max_total_timeout_ms ); if (signal.aborted) { await abortBridge.abortSession(); throw new Error("Subagent was aborted"); } await secureSessionPathWhenReady(resolvedNestedSessionPath); return { result, dropped_tools, usage, runtime_metrics, thread_snapshot, interaction_request, system_prompt: effectiveSystemPrompt, nested_session_path: resolvedNestedSessionPath }; } catch (error) { if (signal.aborted) await abortBridge.abortSession(); await secureSessionPathWhenReady(resolvedNestedSessionPath); throw error instanceof SubagentStructuredError ? error : new SubagentStructuredError( structuredMetadataFromError(error, { phase: "runner_invoke", provider: providerFromModel(model), model: modelLabel2(model), operation: "session.prompt" }) ); } finally { try { orchestratorChannel?.close("child session shutdown"); clearLiveBridge?.(); abortBridge.dispose(); unregisterInteractionSession(); } finally { await teardownSubagentSession(session); } } } try { const { result, dropped_tools, usage, runtime_metrics, thread_snapshot, interaction_request, system_prompt, nested_session_path: resolvedNestedSessionPath } = await attempt(preferred); return { result, dropped_tools, usage, runtime_metrics, thread_snapshot, interaction_request, system_prompt, nested_session_path: resolvedNestedSessionPath, model: modelLabel2(preferred) ?? modelRefLabel(profile.model.value), effort, fallback_used: false }; } catch (error) { if (signal.aborted) throw new Error("Subagent was aborted"); const preferredLabel = modelLabel2(preferred) ?? modelRefLabel(profile.model.value) ?? "unknown"; const primaryFailure = structuredMetadataFromError(error, { phase: isNonRetryableSubagentError(error) ? "runner_session" : "runner_invoke", provider: providerFromModel(preferred), model: preferredLabel, operation: "session.prompt" }); throw new SubagentStructuredError(primaryFailure); } }; // src/manager.ts var MAX_TIMER_DELAY_MS = 2147483647; function nowIso() { return (/* @__PURE__ */ new Date()).toISOString(); } function atelierStatus(status) { return status === "stopping" ? "interrupted" : status; } function taskId(agent) { return `subtask_${agent}_${Date.now()}_${randomUUID2().replace(/-/g, "").slice(0, 8)}`; } function taskActivityTime(task) { return task.last_activity_at ?? task.started_at ?? task.created_at; } function compareBinaryTextDesc(a, b) { return Buffer2.compare(Buffer2.from(b, "utf8"), Buffer2.from(a, "utf8")); } function compareTasksByRecentActivity(a, b) { return compareBinaryTextDesc(taskActivityTime(a), taskActivityTime(b)) || compareBinaryTextDesc(a.created_at, b.created_at) || compareBinaryTextDesc(a.id, b.id); } function subagentAuditLog(cwd, event, data) { writeSubagentsDebugLog(cwd, event, data); } function interactionLogFields(request2) { if (!request2) return { hasInteractionRequest: false }; return { hasInteractionRequest: true, requestId: request2.requestId, kind: request2.kind, origin: request2.origin, reasonCode: request2.reasonCode, riskLevel: request2.riskLevel, requester: request2.requester, hasPrompt: Boolean(request2.prompt), hasPayload: request2.payload !== void 0 }; } function compactOutput(text, limit = 800) { const normalized = sanitizeInteractionTransportText(text).replace(/\s+/g, " ").trim(); return normalized.length > limit ? `\u2026${normalized.slice(-limit)}` : normalized; } var MAX_DISPLAY_NAME_LENGTH = 80; function normalizeDisplayName(raw) { if (typeof raw !== "string") return void 0; const sanitized = sanitizeInteractionTransportText(raw).replace(/\s+/g, " ").trim(); if (!sanitized) return void 0; return sanitized.slice(0, MAX_DISPLAY_NAME_LENGTH); } function resolveDisplayNameInput(displayNameRaw, nameRaw) { const displayCandidate = normalizeDisplayName(displayNameRaw); if (displayCandidate) return displayCandidate; return normalizeDisplayName(nameRaw); } function isSqliteBusyError(error) { if (!error || typeof error !== "object") return false; const candidate = error; return candidate.code === "ERR_SQLITE_ERROR" && (candidate.errcode === 5 || candidate.errstr === "database is locked" || candidate.message === "database is locked"); } function modelRefLabel2(model) { return model ? `${model.provider}/${model.id}` : void 0; } function sessionIdFromContext(ctx) { const direct = ctx?.sessionManager?.getSessionId?.() ?? ctx?.sessionId; if (typeof direct === "string" && direct.length > 0) return direct; const file = ctx?.sessionManager?.getSessionFile?.(); return typeof file === "string" && file.length > 0 ? file : void 0; } function sanitizeUnknown(value3) { if (typeof value3 === "string") return sanitizeInteractionTransportText(value3); if (Array.isArray(value3)) return value3.map((item) => sanitizeUnknown(item)); if (!value3 || typeof value3 !== "object") return value3; return Object.fromEntries( Object.entries(value3).map(([key3, entry]) => [ key3, sanitizeUnknown(entry) ]) ); } function hasPartialResult(task) { return Boolean( task.output_preview || task.result || task.thread_snapshot || task.progress_updates?.length ); } function enrichTerminalMetadata(task, parentSessionId, metadata) { return enrichErrorMetadata(metadata, { usage_at_failure: task.usage, last_activity: task.last_activity, partial_result_available: hasPartialResult(task), task_id: task.id, parent_session_id: parentSessionId }); } function stopDispositionFromReason(reason) { if (reason === "Pi session shutdown") { return { status: "interrupted", metadata: { category: "interrupted", message: `Subagent interrupted: ${reason}`, phase: "manager", retryable: false, partial_result_available: false, details: { interrupt_reason: reason } }, fallbackError: `Subagent interrupted: ${reason}` }; } const phase = reason === "parent abort" ? "manager" : "user"; return { status: "cancelled", metadata: { category: "cancelled", message: `Subagent cancelled: ${reason}`, phase, retryable: false, partial_result_available: false, details: { cancel_reason: reason } }, fallbackError: `Subagent cancelled: ${reason}` }; } function resolveContinuationProfile(definition, config, ctx, input) { const resolved = resolveEffectiveSubagentProfile({ agentName: definition.name, definition, config, ctx }); const model = input.model === void 0 ? resolved.model : (() => { const parsed = parseModel(input.model); if (!parsed) throw new Error( `Invalid model override for continuation: ${input.model}` ); return { value: parsed, source: "orchestrator", label: profileSourceLabel( "orchestrator", parsed, (value3) => `${value3.provider}/${value3.id}` ) }; })(); const effort = input.effort === void 0 ? resolved.effort : (() => { const parsed = parseEffort(input.effort); if (!parsed) throw new Error( `Invalid effort override for continuation: ${input.effort}` ); return { value: parsed, source: "orchestrator", label: profileSourceLabel("orchestrator", parsed, String) }; })(); return { ...resolved, model, effort }; } function interactionPromptMessage(request2) { const prompt = request2.prompt ?? {}; const lines = [ prompt.title ?? `Subagent interaction: ${request2.kind}`, "", prompt.message ?? request2.reason ?? "A subagent requested main-thread interaction." ]; const requester = request2.requester?.subagentName ?? request2.requester?.subagentId; if (requester) lines.push("", `Requested by: ${requester}`); if (prompt.safeTarget) lines.push("", `Target: ${prompt.safeTarget}`); if (prompt.safeCommandSummary) lines.push("", `Command: ${prompt.safeCommandSummary}`); if (prompt.workspaceRoot) lines.push("", `Workspace: ${prompt.workspaceRoot}`); if (prompt.limitations?.length) lines.push("", ...prompt.limitations); if (request2.payload !== void 0) lines.push("", "Payload:", JSON.stringify(request2.payload, null, 2)); if (request2.response?.instructions) lines.push("", "Expected response:", request2.response.instructions); return lines.join("\n"); } function editorInitialValue(request2) { return JSON.stringify( { kind: request2.kind, prompt: request2.prompt, payload: request2.payload, response: request2.response }, null, 2 ); } function parseEditorResponse(raw, request2) { if (request2.response?.expected === "json") return JSON.parse(raw); return raw; } async function promptMainThreadForInteraction(ctx, request2) { const prompt = request2.prompt ?? {}; const message = interactionPromptMessage(request2); const choices = Array.isArray(prompt.choices) ? prompt.choices.filter( (choice) => typeof choice === "string" ) : []; if (choices.length && typeof ctx?.ui?.select === "function") { const value3 = await ctx.ui.select(message, choices); return { type: "interaction_response", requestId: request2.requestId, status: value3 === void 0 ? "cancelled" : "answered", value: value3 }; } if (request2.kind === "confirm" && typeof ctx?.ui?.confirm === "function") { const value3 = await ctx.ui.confirm( prompt.title ?? "Subagent interaction", message ); return { type: "interaction_response", requestId: request2.requestId, status: "answered", value: Boolean(value3) }; } if (request2.kind === "input" && typeof ctx?.ui?.input === "function") { const value3 = await ctx.ui.input( message, prompt.placeholder ?? prompt.defaultValue ?? "" ); return { type: "interaction_response", requestId: request2.requestId, status: value3 === void 0 ? "cancelled" : "answered", value: value3 }; } if (typeof ctx?.ui?.editor === "function") { try { const value3 = await ctx.ui.editor(message, editorInitialValue(request2)); if (value3 === void 0) return { type: "interaction_response", requestId: request2.requestId, status: "cancelled" }; return { type: "interaction_response", requestId: request2.requestId, status: "answered", value: parseEditorResponse(value3, request2) }; } catch (error) { return { type: "interaction_response", requestId: request2.requestId, status: "failed", error: error instanceof Error ? error.message : String(error) }; } } throw new Error( `Subagent interaction ${request2.requestId} (${request2.kind}) requires main-thread UI support for select, confirm, input, or editor.` ); } function createLimiter(max) { let active = 0; const queue = []; return { async acquire() { if (active < max) { active += 1; return; } await new Promise((resolve3) => queue.push(resolve3)); active += 1; }, release() { active = Math.max(0, active - 1); queue.shift()?.(); } }; } var ACTIVITY_UPDATE_FLUSH_MS = 150; var SESSION_TASK_CACHE_MS = 1500; var MAX_PENDING_MESSAGES = 16; var MAX_MESSAGE_BYTES = 16 * 1024; var MAX_PENDING_MESSAGE_BYTES = 64 * 1024; function utf8ByteLength(text) { return Buffer2.byteLength(text, "utf8"); } function closeLiveState(task, state) { const pendingCount = state ? Math.max(0, state.pendingMessages.length - state.pendingConsumption) : task.pending_message_count ?? 0; task.pending_message_count = 0; task.undelivered_message_count = (task.undelivered_message_count ?? 0) + pendingCount; if (!state) return; state.pendingMessages = []; state.pendingBytes = 0; state.pendingConsumption = 0; state.bridgeReady = true; delete state.bridge; } function summarizeTask(task) { const { transcript, thread_snapshot, system_prompt, ...summary2 } = task; return summary2; } var SubagentManager = class { constructor(runner = sdkSubagentRunner, history = new SubagentHistoryStore(), onTerminalBackgroundTask, onInteractionPromptActive, atelierMetadata, onAssistantMessage, onOrchestratorQuestion, onTimeoutAttention, onTimeoutBackgroundHandoff) { this.runner = runner; this.history = history; this.onTerminalBackgroundTask = onTerminalBackgroundTask; this.onInteractionPromptActive = onInteractionPromptActive; this.atelierMetadata = atelierMetadata; this.onAssistantMessage = onAssistantMessage; this.onOrchestratorQuestion = onOrchestratorQuestion; this.onTimeoutAttention = onTimeoutAttention; this.onTimeoutBackgroundHandoff = onTimeoutBackgroundHandoff; } runner; history; onTerminalBackgroundTask; onInteractionPromptActive; atelierMetadata; onAssistantMessage; onOrchestratorQuestion; onTimeoutAttention; onTimeoutBackgroundHandoff; deadlines = /* @__PURE__ */ new Map(); tasks = /* @__PURE__ */ new Map(); taskCwds = /* @__PURE__ */ new Map(); attemptRetention = /* @__PURE__ */ new WeakMap(); releasedTasks = /* @__PURE__ */ new WeakSet(); controllers = /* @__PURE__ */ new Map(); limiters = /* @__PURE__ */ new Map(); pendingUpdates = /* @__PURE__ */ new Map(); sessionTaskCache = /* @__PURE__ */ new Map(); runnerSettlements = /* @__PURE__ */ new Map(); stopDispositions = /* @__PURE__ */ new Map(); liveStates = /* @__PURE__ */ new Map(); taskUpdateListeners = /* @__PURE__ */ new Set(); pendingQuestions = /* @__PURE__ */ new Map(); acknowledgedResults = /* @__PURE__ */ new Map(); resultCandidates = /* @__PURE__ */ new Map(); askTimeouts = /* @__PURE__ */ new Map(); questionListeners = /* @__PURE__ */ new Set(); questionPendingListeners = /* @__PURE__ */ new Map(); closePromise; closing = false; atelierRuns = /* @__PURE__ */ new Map(); atelierRun(taskId2, cwd, owner) { if (!owner) return void 0; const key3 = `${taskId2}\0${owner.sessionId}`; const existing = this.atelierRuns.get(key3); if (existing) return existing; const run = this.atelierMetadata?.createRun({ taskId: taskId2, owner, cwd }); if (run) this.atelierRuns.set(key3, run); return run; } close() { if (this.closePromise) return this.closePromise; this.closing = true; this.closePromise = Promise.resolve().then(async () => { this.cancelRunning("Pi session shutdown"); await Promise.all( [...this.runnerSettlements.values()].map( (settlement) => settlement.catch(() => void 0) ) ); this.history.close?.(); }); return this.closePromise; } sessionModelProfile; setSessionModelProfile(profile) { this.sessionModelProfile = profile; } getSessionModelProfile() { return this.sessionModelProfile; } profileContext(ctx, cwd) { const modelProfile = new ModelProfileStore({ cwd, agentDir: ctx?.agentDir }).resolve(this.sessionModelProfile); for (const warning of modelProfile.warnings) ctx?.ui?.notify?.(warning, "warning"); return { ...ctx, cwd, modelProfile }; } listAgents(cwd, ctx = {}) { ctx = this.profileContext(ctx, cwd); const config = readSubagentsConfig(cwd); return loadSubagents(cwd).map((definition) => { const profile = resolveEffectiveSubagentProfile({ agentName: definition.name, definition, config, ctx }); return { name: definition.name, description: definition.description, filePath: definition.filePath, tools: definition.tools, model: profile.model.value, effort: profile.effort.value, profileName: profile.profileName, warnings: profile.warnings }; }); } listTasks(cwd) { const active = [...this.tasks.values()].sort(compareTasksByRecentActivity); if (!cwd) return active; const activeIds = new Set(active.map((task) => task.id)); const persisted = this.history.listTasks(cwd).filter((task) => !activeIds.has(task.id)); return [...active, ...persisted].sort(compareTasksByRecentActivity); } listActiveSessionTasks(cwd, sessionId) { return [...this.tasks.values()].filter( (task) => (!cwd || this.taskCwds.get(task.id) === cwd) && (!sessionId || task.session_id === sessionId) ).sort(compareTasksByRecentActivity); } snapshotSessionTaskCounts(cwd, sessionId) { return sessionId ? this.history.snapshotSessionTaskCounts(cwd, sessionId) : { counts: {}, statusesById: /* @__PURE__ */ new Map() }; } /** Separate bounded completion-ranked input; overlays keep activity ranking. */ listWorkPanelSessionTasks(cwd, sessionId) { if (!cwd || !sessionId) return []; return this.cachedPersistedSessionTasks(cwd, sessionId, true); } listSessionTasks(cwd, sessionId) { const active = this.listActiveSessionTasks(cwd, sessionId); if (!cwd || !sessionId) return active; const activeIds = new Set(active.map((task) => task.id)); const persisted = this.cachedPersistedSessionTasks(cwd, sessionId).filter( (task) => !activeIds.has(task.id) ); return [...active, ...persisted].sort(compareTasksByRecentActivity); } listSessionHistoryByCost(cwd, sessionId) { return this.history.listSessionTaskMetadataByCost(cwd, sessionId); } onTaskUpdate(listener) { this.taskUpdateListeners.add(listener); return () => { this.taskUpdateListeners.delete(listener); }; } /** Awaited before parent delivery; task-mode handoff must use this hook. */ onQuestion(listener) { this.questionListeners.add(listener); return () => { this.questionListeners.delete(listener); }; } onQuestionPendingChange(taskId2, listener) { let listeners = this.questionPendingListeners.get(taskId2); if (!listeners) { listeners = /* @__PURE__ */ new Set(); this.questionPendingListeners.set(taskId2, listeners); } listeners.add(listener); const count = this.pendingQuestions.get(taskId2)?.size ?? 0; listener(count > 0, count); return () => { listeners.delete(listener); if (!listeners.size) this.questionPendingListeners.delete(taskId2); }; } publishPendingQuestions(task) { const entries = [...this.pendingQuestions.get(task.id)?.values() ?? []]; task.pending_questions = entries.map(({ question }) => ({ request_id: question.request_id, message: question.message, created_at: question.created_at })); for (const listener of this.questionPendingListeners.get(task.id) ?? []) listener(entries.length > 0, entries.length); const cwd = this.taskCwds.get(task.id); if (cwd) this.record(cwd, task, task.last_activity ?? "running"); this.notifyTaskUpdate(task.id, void 0, true); } isQuestionPending(taskId2, requestId) { return this.pendingQuestions.get(taskId2)?.has(requestId) ?? false; } stageResultAcknowledgment(toolCallId, task, content) { if (!isTerminalStatus(task.status)) return; this.resultCandidates.set(toolCallId, { taskId: task.id, attempt: task.attempt ?? 1, content: JSON.stringify(content) }); } confirmResultAcknowledgments(messages) { for (const message of messages) { const candidate = this.resultCandidates.get(message.toolCallId); if (!candidate) continue; this.resultCandidates.delete(message.toolCallId); const task = message.details?.task; if (message.role !== "toolResult" || message.toolName !== "subagent_result" || message.isError !== false || task?.id !== candidate.taskId || (task.attempt ?? 1) !== candidate.attempt || JSON.stringify(message.content) !== candidate.content) continue; let attempts = this.acknowledgedResults.get(candidate.taskId); if (!attempts) { attempts = /* @__PURE__ */ new Set(); this.acknowledgedResults.set(candidate.taskId, attempts); } attempts.add(candidate.attempt); } } clearResultAcknowledgmentCandidates() { this.resultCandidates.clear(); } resetResultAcknowledgments() { this.clearResultAcknowledgmentCandidates(); this.acknowledgedResults.clear(); } isResultAcknowledged(task) { return this.acknowledgedResults.get(task.id)?.has(task.attempt ?? 1) ?? false; } async deliverQuestion(task, question) { for (const listener of this.questionListeners) await listener(task, question); if (this.pendingQuestions.get(task.id)?.has(question.request_id)) await this.onOrchestratorQuestion?.(task, question); } async askOrchestrator(taskId2, message, signal) { const task = this.tasks.get(taskId2); if (!task) throw new Error(`Subagent task not found: ${taskId2}`); if (this.closing) throw new Error("ask_orchestrator unavailable: parent session shutdown."); if (task.status !== "running") throw new Error( `ask_orchestrator unavailable: task ${taskId2} is not running.` ); if (!this.askTimeouts.has(taskId2)) throw new Error("ask_orchestrator is disabled for this task."); const taskSignal = this.controllers.get(taskId2)?.signal; if (signal?.aborted || taskSignal?.aborted) throw new Error("ask_orchestrator question cancelled."); const text = sanitizeInteractionTransportText(message ?? ""); if (!text.trim()) throw new Error("ask_orchestrator message must not be empty."); const question = { task_id: taskId2, agent: task.agent, request_id: randomUUID2(), message: text, created_at: nowIso() }; const timeoutMs = this.askTimeouts.get(taskId2) ?? DEFAULT_ASK_TIMEOUT_MS; return new Promise((resolve3, reject) => { let settled = false; const settle = (result) => { if (settled) return; settled = true; clearTimeout(timer); signal?.removeEventListener("abort", onAbort); taskSignal?.removeEventListener("abort", onAbort); const pending2 = this.pendingQuestions.get(taskId2); pending2?.delete(question.request_id); if (!pending2?.size) this.pendingQuestions.delete(taskId2); task.last_activity = result instanceof Error ? "orchestrator question rejected" : "orchestrator question answered"; task.last_activity_at = nowIso(); this.publishPendingQuestions(task); if (result instanceof Error) reject(result); else resolve3(result); }; const onAbort = () => settle( new Error( `ask_orchestrator question ${question.request_id} cancelled: ${task.stop_reason ?? "task cancellation"}` ) ); const timer = setTimeout( () => settle( new Error( `ask_orchestrator question ${question.request_id} timed out after ${timeoutMs}ms without an orchestrator reply.` ) ), timeoutMs ); let pending = this.pendingQuestions.get(taskId2); if (!pending) { pending = /* @__PURE__ */ new Map(); this.pendingQuestions.set(taskId2, pending); } pending.set(question.request_id, { question, settle }); signal?.addEventListener("abort", onAbort, { once: true }); taskSignal?.addEventListener("abort", onAbort, { once: true }); task.last_activity = "awaiting orchestrator reply"; task.last_activity_at = question.created_at; this.publishPendingQuestions(task); void this.deliverQuestion(task, question).catch( (error) => settle( new Error( `ask_orchestrator question delivery failed: ${error instanceof Error ? error.message : String(error)}` ) ) ); }); } replyToQuestion(sessionId, taskId2, requestId, message) { const task = this.tasks.get(taskId2); if (!task) throw new Error(`Subagent task not found: ${taskId2}`); if (!sessionId) throw new Error( "Unable to verify the calling Pi session for this reply." ); if (!task.session_id || task.session_id !== sessionId) throw new Error( "Only the exact originating parent Pi session may reply to this task." ); const pending = this.pendingQuestions.get(taskId2); if (!pending?.size) throw new Error( `No pending question for task ${taskId2}; the request is unknown or stale.` ); if (requestId === void 0 && pending.size !== 1) throw new Error( `Ambiguous reply: task ${taskId2} has ${pending.size} pending questions; specify request_id.` ); const entry = requestId === void 0 ? pending.values().next().value : pending.get(requestId); if (!entry) throw new Error(`Unknown or stale question request_id: ${requestId}`); const text = sanitizeInteractionTransportText(message ?? ""); if (!text.trim()) throw new Error( "Orchestrator replies must not be empty or whitespace-only." ); entry.settle(text); return { task_id: taskId2, request_id: entry.question.request_id, status: "replied" }; } reportProgress(taskId2, message) { const task = this.tasks.get(taskId2); if (!task) throw new Error(`Subagent task not found: ${taskId2}`); if (this.closing || task.status !== "running") throw new Error( "notify_orchestrator progress unavailable: task is not running." ); const text = sanitizeInteractionTransportText(message ?? ""); if (!text.trim()) throw new Error("notify_orchestrator message must not be empty."); const created_at = nowIso(); task.progress_updates = [ ...task.progress_updates ?? [], { message: text, created_at } ].slice(-5); task.last_activity = `progress: ${compactOutput(text)}`; task.last_activity_at = created_at; const cwd = this.taskCwds.get(taskId2); if (cwd) this.record(cwd, task, task.last_activity); this.notifyTaskUpdate(taskId2, void 0, true); } rejectPendingQuestions(taskId2, reason) { for (const entry of [ ...this.pendingQuestions.get(taskId2)?.values() ?? [] ]) entry.settle( new Error( `ask_orchestrator question ${entry.question.request_id} rejected: ${reason}` ) ); } getTaskCwd(id) { return this.taskCwds.get(id); } getTask(id, cwd) { const task = this.tasks.get(id); if (task && !this.releasedTasks.has(task)) return task; const taskCwd = this.taskCwds.get(id) ?? cwd; if (!taskCwd) return task; try { const hydrated = this.history.getTask(taskCwd, id); if (!task) return hydrated; if (!hydrated || (hydrated.attempt ?? 1) !== (task.attempt ?? 1)) return task; return { ...task, transcript: hydrated.transcript, thread_snapshot: hydrated.thread_snapshot, system_prompt: hydrated.system_prompt }; } catch { return task; } } retainResults(tasks) { for (const task of tasks) { const retention = this.attemptRetention.get(task); if (retention) retention.consumers += 1; } return () => { for (const task of tasks) { const retention = this.attemptRetention.get(task); if (retention) retention.consumers -= 1; this.releaseTask(task); } }; } releaseTask(task) { const retention = this.attemptRetention.get(task); if (!retention?.settled || !retention.durable || retention.persistenceFailed || retention.consumers || !isTerminalStatus(task.status) || retention.attempt !== (task.attempt ?? 1) || this.tasks.get(task.id) !== task) return; const summary2 = summarizeTask(task); this.releasedTasks.add(summary2); this.tasks.set(task.id, summary2); } reconcileOrphanedTasks(cwd) { const orphaned = this.history.listTasksByStatus(cwd, ["queued", "running"]); const interruptedAt = nowIso(); const reconciled = []; for (const task of orphaned) { const updated = { ...task, status: "interrupted", stop_reason: "orphaned active state at startup", last_activity_at: interruptedAt, last_activity: "interrupted at startup", ended_at: interruptedAt, pending_message_count: 0, pending_questions: [], undelivered_message_count: (task.undelivered_message_count ?? 0) + (task.pending_message_count ?? 0) }; updated.error_metadata = enrichTerminalMetadata( updated, updated.session_id, normalizeErrorMetadata({ category: "interrupted", message: "Subagent interrupted: orphaned active state at startup", phase: "manager", retryable: false, partial_result_available: hasPartialResult(updated), details: { interrupt_reason: "orphaned active state at startup" } }) ); updated.error = deriveErrorString(updated.error_metadata); this.record( cwd, updated, updated.last_activity ?? "interrupted at startup" ); reconciled.push(updated); } return reconciled; } cancelRunning(reason = "cancelled") { return [...this.tasks.values()].filter( (task) => task.status === "queued" || task.status === "running" || task.status === "stopping" ).map((task) => this.cancel(task.id, reason)); } sendToBackground(ids, reason) { const changed = []; for (const id of ids) { const task = this.tasks.get(id); const cwd = this.taskCwds.get(id); if (!task || !cwd) continue; if (task.mode === "background") continue; if (task.status !== "queued" && task.status !== "running" && !(reason === "attention" && task.status === "stopping")) continue; task.mode = "background"; task.effective_mode = "background"; this.record(cwd, task, task.last_activity ?? "running"); changed.push(task); } return changed; } hasRunning() { return [...this.tasks.values()].some( (task) => task.status === "queued" || task.status === "running" || task.status === "stopping" ); } registerLiveBridge(taskId2, bridge, parentSessionId, attempt) { const task = this.tasks.get(taskId2); const current = this.liveStates.get(taskId2); if (current && current.attempt > attempt) return; const state = current && current.attempt === attempt ? current : { attempt, parentSessionId, bridgeReady: false, pendingMessages: [], pendingBytes: 0, pendingConsumption: 0 }; state.parentSessionId = parentSessionId; state.attempt = attempt; state.bridge = bridge; state.bridgeReady = true; this.liveStates.set(taskId2, state); if (task) this.flushPendingLiveMessages(task, state); } clearLiveBridge(taskId2, attempt) { const state = this.liveStates.get(taskId2); if (!state) return; if (attempt !== void 0 && state.attempt !== attempt) return; state.bridgeReady = true; delete state.bridge; } closeTaskLiveState(task, reason = task.stop_reason ?? "child session shutdown") { this.rejectPendingQuestions(task.id, reason); const state = this.liveStates.get(task.id); closeLiveState(task, state); this.liveStates.delete(task.id); } flushPendingLiveMessages(task, state) { if (!state.bridgeReady || !state.bridge?.supported) return; for (const entry of [...state.pendingMessages]) { if (entry.forwarded) continue; void this.forwardLiveMessage(task, state, entry, true); } task.pending_message_count = state.pendingMessages.length; } async forwardLiveMessage(task, state, entry, alreadyAccepted = false) { entry.forwarded = true; let disposition; try { disposition = await state.bridge.steer(entry.message); } catch { if (this.removeLiveMessage(task, state, entry)) { if (alreadyAccepted) task.undelivered_message_count = (task.undelivered_message_count ?? 0) + 1; this.drainConsumedLiveMessages(task, state); this.recordLiveMessageOutcome(task, "rejected"); } return "rejected"; } if (disposition === "handled" && this.removeLiveMessage(task, state, entry)) { this.drainConsumedLiveMessages(task, state); this.recordLiveMessageOutcome(task, "handled by input extension"); } if (disposition === "queued" && this.liveStates.get(task.id) === state) { entry.acknowledged = true; this.drainConsumedLiveMessages(task, state); } return disposition; } recordLiveMessageOutcome(task, outcome) { task.last_activity = `live steering message ${outcome}`; task.last_activity_at = nowIso(); const cwd = this.taskCwds.get(task.id); if (cwd) this.record(cwd, task, task.last_activity); } removeLiveMessage(task, state, entry) { if (this.liveStates.get(task.id) !== state) return false; const index = state.pendingMessages.indexOf(entry); if (index < 0) return false; state.pendingMessages.splice(index, 1); state.pendingBytes = Math.max(0, state.pendingBytes - entry.bytes); task.pending_message_count = state.pendingMessages.length; return true; } consumeQueuedMessage(taskId2) { const task = this.tasks.get(taskId2); const state = this.liveStates.get(taskId2); if (!task || !state || !state.pendingMessages.length) return; const forwardedCount = state.pendingMessages.filter( (entry) => entry.forwarded ).length; if (state.pendingConsumption >= forwardedCount) return; state.pendingConsumption += 1; this.drainConsumedLiveMessages(task, state); } drainConsumedLiveMessages(task, state) { while (state.pendingConsumption > 0) { const entry = state.pendingMessages.find((entry2) => entry2.forwarded); if (!entry) { state.pendingConsumption = 0; break; } if (!entry.acknowledged) break; if (!this.removeLiveMessage(task, state, entry)) break; state.pendingConsumption -= 1; } } clearDeadline(taskId2, remove = true) { const state = this.deadlines.get(taskId2); if (state?.warning) clearTimeout(state.warning); if (state?.ceiling) clearTimeout(state.ceiling); if (remove) this.deadlines.delete(taskId2); } isAttentionCurrent(taskId2, attempt, generation) { const task = this.tasks.get(taskId2); return Boolean( task && task.status === "running" && (task.attempt ?? 1) === attempt && task.timeout_deadline_generation === generation && this.deadlines.has(taskId2) ); } /** Read-only active deadline defaults for operational UI; validation stays in extendDeadline. */ getDeadlineExtension(taskId2) { const state = this.deadlines.get(taskId2); const task = this.tasks.get(taskId2); if (!state || !task) return void 0; return { incrementMs: state.config.timeout_ms, remaining: Math.max( 0, (state.config.max_timeout_extensions ?? DEFAULT_MAX_TIMEOUT_EXTENSIONS) - (task.timeout_extensions_used ?? 0) ) }; } extendDeadline(taskId2, extraMs, ownerSession) { const task = this.tasks.get(taskId2); if (!task) throw new Error(`Subagent task not found: ${taskId2}`); if (!ownerSession || task.session_id !== ownerSession) throw new Error( "Only the exact originating parent Pi session may extend this task." ); if (task.status !== "running") throw new Error( `Subagent task ${taskId2} is not running (${task.status}).` ); const state = this.deadlines.get(taskId2); if (!state) throw new Error("Subagent task has no active execution deadline."); const { config } = state; const extra = extraMs === void 0 ? config.timeout_ms : extraMs; if (!Number.isFinite(extra) || extra <= 0 || !Number.isInteger(extra)) throw new Error("extra_ms must be a positive integer."); if ((task.timeout_extensions_used ?? 0) >= (config.max_timeout_extensions ?? DEFAULT_MAX_TIMEOUT_EXTENSIONS)) throw new Error("Maximum timeout extension count exhausted."); const previous = task.timeout_deadline_at; if (Date.now() >= previous) throw new Error("The execution deadline has already elapsed."); const deadline = Math.min( previous + extra, task.timeout_started_at + Math.max( config.timeout_ms, config.max_total_timeout_ms ?? DEFAULT_MAX_TOTAL_TIMEOUT_MS ) ); if (deadline <= previous) throw new Error("Maximum total timeout ceiling already reached."); task.timeout_deadline_at = deadline; task.timeout_extensions_used = (task.timeout_extensions_used ?? 0) + 1; task.timeout_deadline_generation = (task.timeout_deadline_generation ?? 1) + 1; state.arm(); const cwd = this.taskCwds.get(taskId2); if (cwd) this.record(cwd, task, `deadline extended by ${deadline - previous}ms`); this.notifyTaskUpdate(taskId2, void 0, true); return { task_id: taskId2, added_ms: deadline - previous, deadline_at: deadline, extensions_used: task.timeout_extensions_used, extensions_remaining: (config.max_timeout_extensions ?? DEFAULT_MAX_TIMEOUT_EXTENSIONS) - task.timeout_extensions_used }; } armDeadline(task, config, cwd, expire) { let state = this.deadlines.get(task.id); if (!state) { state = { config, expire, arm: () => { } }; this.deadlines.set(task.id, state); } state.expire = expire; const deadlineState = state; state.arm = () => { this.clearDeadline(task.id, false); const attempt = task.attempt ?? 1; const generation = task.timeout_deadline_generation; const remaining = task.timeout_deadline_at - Date.now(); deadlineState.ceiling = setTimeout( () => { if (!this.isAttentionCurrent(task.id, attempt, generation)) return; if (Date.now() < task.timeout_deadline_at) deadlineState.arm(); else deadlineState.expire(); }, Math.min(MAX_TIMER_DELAY_MS, Math.max(0, remaining)) ); const lead = config.timeout_warning_ms ?? DEFAULT_TIMEOUT_WARNING_MS; if (lead > 0 && lead < config.timeout_ms && deadlineState.warnedGeneration !== generation) { deadlineState.warning = setTimeout( () => { if (!this.isAttentionCurrent(task.id, attempt, generation)) return; if (Date.now() < task.timeout_deadline_at - lead) { deadlineState.arm(); return; } deadlineState.warnedGeneration = generation; void (async () => { if (task.mode === "task") { try { await this.onTimeoutBackgroundHandoff?.(task.id); } catch { } } if (!this.isAttentionCurrent(task.id, attempt, generation)) return; if (task.notify_orchestrator_available === true) { try { void this.sendMessage({ task_id: task.id, session_id: task.session_id, message: 'Please report a concise checkpoint (done, pending, touched files) through notify_orchestrator({ message: "..." }), then continue working. This is a checkpoint request, not a stop instruction.' }).catch(() => { }); } catch { } } if (!this.isAttentionCurrent(task.id, attempt, generation)) return; try { this.onTimeoutAttention?.(task, cwd, attempt, generation); } catch { } })(); }, Math.min(MAX_TIMER_DELAY_MS, Math.max(0, remaining - lead)) ); } }; state.arm(); } async sendMessage(input) { const task = this.tasks.get(input.task_id); if (!task) { return { status: "rejected", task_id: input.task_id, reason: "unknown_task", message: `Subagent task not found: ${input.task_id}` }; } if (!input.session_id) { return { status: "rejected", task_id: input.task_id, reason: "caller_identity_unavailable", message: "Unable to verify the calling Pi session for this live message request." }; } if (task.status !== "running") { return { status: "rejected", task_id: input.task_id, reason: "not_running", message: `Subagent task ${input.task_id} is not currently running.` }; } if ((task.effective_mode ?? task.mode) !== "background") { return { status: "rejected", task_id: input.task_id, reason: "not_background", message: `Subagent task ${input.task_id} is not currently running in background mode.` }; } const liveState = this.liveStates.get(input.task_id); if (!liveState || !liveState.parentSessionId || liveState.parentSessionId !== input.session_id) { return { status: "rejected", task_id: input.task_id, reason: "not_owner", message: "Only the exact originating parent Pi session may message this live background task." }; } if (liveState.bridgeReady && !liveState.bridge) { return { status: "rejected", task_id: input.task_id, reason: "missing_live_session", message: `Subagent task ${input.task_id} has no live session available for steering.` }; } if (liveState.bridgeReady && liveState.bridge && !liveState.bridge.supported) { return { status: "rejected", task_id: input.task_id, reason: "unsupported_runtime", required_pi_version: ">=1.5.0", detected_pi_version: liveState.bridge.detected_pi_version, message: `Live background messaging requires Pi runtime >=1.5.0; detected ${liveState.bridge.detected_pi_version}.` }; } const message = sanitizeInteractionTransportText(input.message ?? ""); if (!message.trim()) { return { status: "rejected", task_id: input.task_id, reason: "empty_message", message: "Live background messages must not be empty or whitespace-only." }; } const messageBytes = utf8ByteLength(message); if (messageBytes > MAX_MESSAGE_BYTES) { return { status: "rejected", task_id: input.task_id, reason: "message_too_large", message: "Live background messages must be at most 16 KiB of UTF-8 text." }; } if (liveState.pendingMessages.length >= MAX_PENDING_MESSAGES) { return { status: "rejected", task_id: input.task_id, reason: "queue_count_limit", message: "This subagent already has 16 pending live messages queued." }; } if (liveState.pendingBytes + messageBytes > MAX_PENDING_MESSAGE_BYTES) { return { status: "rejected", task_id: input.task_id, reason: "queue_bytes_limit", message: "This subagent already has too much queued live-message text pending." }; } const entry = { message, bytes: messageBytes, forwarded: false, acknowledged: false }; liveState.pendingMessages.push(entry); liveState.pendingBytes += messageBytes; task.pending_message_count = liveState.pendingMessages.length; if (liveState.bridgeReady && liveState.bridge?.supported) { const disposition = await this.forwardLiveMessage(task, liveState, entry); if (disposition === "handled") { return { status: "handled", task_id: input.task_id, pending_message_count: liveState.pendingMessages.length, message: "Message handled by an input extension; this does not prove model consumption." }; } if (disposition === "rejected") { return { status: "rejected", task_id: input.task_id, reason: "enqueue_failed", message: "The live steering queue rejected this message before it could be accepted." }; } } return { status: "queued", task_id: input.task_id, pending_message_count: liveState.pendingMessages.length, message: "Message accepted into the steering queue; this does not prove model consumption." }; } limiter(cwd, maxConcurrency) { const key3 = `${cwd}:${maxConcurrency}`; let limiter = this.limiters.get(key3); if (!limiter) { limiter = createLimiter(maxConcurrency); this.limiters.set(key3, limiter); } return limiter; } async run(input, ctx, parentSignal, onTaskUpdate) { const cwd = ctx?.cwd ?? process.cwd(); ctx = this.profileContext(ctx, cwd); const agents = input.agents?.length ? input.agents : input.agent ? [input.agent] : []; if (!agents.length) throw new Error("subagent_run requires agent or agents."); const explicitMode = input.mode; const config = readSubagentsConfig(cwd); const definitions = new Map( loadSubagents(cwd).map((definition) => [definition.name, definition]) ); const limiter = this.limiter(cwd, config.max_concurrency); const displayName = resolveDisplayNameInput(input.display_name, input.name); let ids = []; const notifyUpdate = () => onTaskUpdate?.(ids.map((id) => this.tasks.get(id)).filter(Boolean)); ids = agents.map((agent) => { const definition = definitions.get(agent.toLowerCase()); if (!definition) throw new Error(`Subagent not found: ${agent}`); return this.startOne( definition, input.task, input.context, explicitMode, ctx, config, parentSignal, notifyUpdate, limiter, displayName ); }); notifyUpdate(); const launched = ids.map((id) => this.tasks.get(id)).filter(Boolean); const releaseResults = this.retainResults(launched); try { const waitedTaskIds = launched.filter((task) => task.effective_mode === "task").map((task) => task.id); const backgroundTaskIds = launched.filter((task) => task.effective_mode === "background").map((task) => task.id); const resolvedMode = explicitMode ?? (waitedTaskIds.length && backgroundTaskIds.length ? "mixed" : backgroundTaskIds.length ? "background" : "task"); if (resolvedMode === "background" && explicitMode === "background") { return { mode: resolvedMode, task_ids: ids, waited_task_ids: waitedTaskIds, background_task_ids: backgroundTaskIds }; } await Promise.all(waitedTaskIds.map((id) => this.wait(id))); if (parentSignal?.aborted) throw new Error("Subagent run aborted"); const results = launched; return { mode: resolvedMode, task_ids: ids, waited_task_ids: waitedTaskIds, background_task_ids: backgroundTaskIds, members: results.map((task) => ({ task_id: task.id, agent: task.agent, effective_mode: task.effective_mode ?? task.mode, state: task.status })), results }; } finally { releaseResults(); } } async continueTask(input, ctx, parentSignal, onTaskUpdate) { const cwd = ctx?.cwd ?? process.cwd(); const taskCwd = this.taskCwds.get(input.task_id) ?? cwd; ctx = this.profileContext(ctx, taskCwd); const existing = this.getTask(input.task_id, taskCwd); if (!existing) throw new Error(`Subagent task not found: ${input.task_id}`); if (!readSubagentsConfig(taskCwd).enable_continue) throw new Error("Subagent task is not available."); if (existing.status !== "stopping" && !isTerminalStatus(existing.status)) throw new Error( "Only completed, failed, or cancelled subagent tasks can continue." ); await this.awaitRunnerCleanup(existing.id); const latest = this.getTask(input.task_id, taskCwd) ?? existing; if (!isTerminalStatus(latest.status)) throw new Error( "Only completed, failed, or cancelled subagent tasks can continue." ); if (!latest.nested_session_path || !fs10.existsSync(latest.nested_session_path)) { throw new Error( `Subagent task ${input.task_id} is missing or unreadable nested session file: ${latest.nested_session_path ?? "unknown"}` ); } const config = readSubagentsConfig(taskCwd); const definitions = new Map( loadSubagents(taskCwd).map((definition2) => [definition2.name, definition2]) ); const definition = definitions.get(latest.agent.toLowerCase()); if (!definition) throw new Error( `Subagent definition not found for continuation: ${latest.agent}` ); try { this.history.upsertTask(taskCwd, { ...latest, attempt: latest.attempt ?? 1 }); } catch { } const effectiveProfile = resolveContinuationProfile( definition, config, ctx, input ); const effectiveMode = resolveContinuationEffectiveMode({ explicitMode: input.mode }); const continuationPrompt = sanitizeInteractionTransportText(input.prompt); const continuationSessionId = sessionIdFromContext(ctx); this.liveStates.delete(latest.id); const task = { ...latest, mode: effectiveMode, effective_mode: effectiveMode, status: "queued", attempt: (latest.attempt ?? 1) + 1, session_id: continuationSessionId, last_activity_at: nowIso(), last_activity: "queued", timeout_started_at: void 0, timeout_deadline_at: void 0, timeout_extensions_used: void 0, timeout_deadline_generation: void 0, timeout_max_extensions: void 0, timeout_continue_enabled: void 0, progress_updates: void 0, started_at: void 0, ended_at: void 0, output_preview: void 0, continuation_prompt: continuationPrompt, dropped_tools: void 0, notify_orchestrator_available: void 0, transcript: void 0, model: modelRefLabel2(effectiveProfile.model.value), effort: effectiveProfile.effort.value, model_source: effectiveProfile.model.source, effort_source: effectiveProfile.effort.source, fallback_used: void 0, error: void 0, error_metadata: void 0, result: void 0, interaction_request: void 0, pending_message_count: 0, undelivered_message_count: 0 }; this.launchAttempt({ definition, taskText: latest.task, context: latest.context, task, ctx: { ...ctx, cwd: taskCwd }, config, effectiveProfile, parentSessionId: continuationSessionId, nestedSessionPath: latest.nested_session_path, previousSnapshot: latest.thread_snapshot, continuationPrompt, parentSignal, onTaskUpdate: () => onTaskUpdate?.([this.tasks.get(task.id)].filter(Boolean)), limiter: this.limiter(taskCwd, config.max_concurrency) }); const releaseResults = this.retainResults([task]); try { if (effectiveMode === "background") return { mode: effectiveMode, task_ids: [task.id] }; await this.wait(task.id); if (parentSignal?.aborted) throw new Error("Subagent continuation aborted"); return { mode: effectiveMode, task_ids: [task.id], results: [task] }; } finally { releaseResults(); } } cancel(id, reason = "cancelled") { const task = this.tasks.get(id); if (!task) throw new Error(`Subagent task not found: ${id}`); if (isTerminalStatus(task.status)) return task; const disposition = stopDispositionFromReason(reason); const cwd = this.taskCwds.get(id); if (task.status === "queued") { task.status = disposition.status; task.stop_reason = reason; task.last_activity = reason; task.last_activity_at = nowIso(); task.ended_at = task.last_activity_at; task.error_metadata = enrichTerminalMetadata( task, task.session_id, normalizeErrorMetadata({ ...disposition.metadata, partial_result_available: hasPartialResult(task) }) ); task.error = deriveErrorString(task.error_metadata); delete task.live_activity; task.pending_message_count = 0; task.undelivered_message_count = task.undelivered_message_count ?? 0; if (cwd) this.record(cwd, task, task.last_activity); return task; } if (task.status === "stopping") return task; this.stopDispositions.set(id, disposition); this.transitionToStopping(task, reason, cwd); this.notifyTaskUpdate(id, void 0, true); this.controllers.get(id)?.abort(); return task; } transitionToStopping(task, reason, cwd) { if (task.status === "stopping" || isTerminalStatus(task.status)) return; this.clearDeadline(task.id); this.closeTaskLiveState(task, reason); task.status = "stopping"; task.stop_reason = reason; task.last_activity = reason; task.last_activity_at = nowIso(); task.ended_at = void 0; delete task.interaction_request; if (cwd) this.record(cwd, task, reason); } finalizeStop(task, parentSessionId, cwd, onTaskUpdate) { const disposition = this.stopDispositions.get(task.id) ?? stopDispositionFromReason(task.stop_reason ?? "cancelled"); this.closeTaskLiveState(task); task.status = disposition.status; task.last_activity_at = nowIso(); task.ended_at = task.last_activity_at; task.error_metadata = enrichTerminalMetadata( task, parentSessionId, normalizeErrorMetadata({ ...disposition.metadata, partial_result_available: hasPartialResult(task) }) ); task.error = deriveErrorString(task.error_metadata); delete task.live_activity; task.last_activity = disposition.status === "failed" ? `failed: ${task.error}` : task.stop_reason ?? task.error; delete task.interaction_request; this.stopDispositions.delete(task.id); this.record(cwd, task, task.last_activity); this.notifyTaskUpdate(task.id, onTaskUpdate, true); } startOne(definition, taskText, context, mode, ctx, config, parentSignal, onTaskUpdate, limiter = createLimiter(1), displayName) { if (this.closing) throw new Error("Subagent manager is closing."); const session_id = sessionIdFromContext(ctx); const effectiveProfile = resolveEffectiveSubagentProfile({ agentName: definition.name, definition, config, ctx }); const effectiveMode = resolveEffectiveSubagentMode({ invocationMode: mode }); const task = { id: taskId(definition.name), display_name: displayName, agent: definition.name, mode: effectiveMode, effective_mode: effectiveMode, status: "queued", task: taskText, context, model: modelRefLabel2(effectiveProfile.model.value), effort: effectiveProfile.effort.value, model_source: effectiveProfile.model.source, effort_source: effectiveProfile.effort.source, pending_message_count: 0, created_at: nowIso(), attempt: 1, session_id, last_activity_at: nowIso(), last_activity: "queued" }; this.launchAttempt({ definition, taskText, context, task, ctx, config, effectiveProfile, parentSessionId: session_id, parentSignal, onTaskUpdate, limiter }); return task.id; } launchAttempt(input) { const { definition, taskText, context, task, ctx, config, effectiveProfile, parentSessionId, nestedSessionPath, previousSnapshot, continuationPrompt, parentSignal, onTaskUpdate, limiter } = input; const cwd = ctx?.cwd ?? process.cwd(); const id = task.id; const atelierOwner = captureAtelierSessionOwner(ctx); const atelierRun = this.atelierRun(id, cwd, atelierOwner); let atelierStepIndex; const metricBaseline = { turns: task.runtime_metrics?.turns ?? 0, compactions: task.runtime_metrics?.compactions ?? 0, generationOutputTokens: task.runtime_metrics?.generationOutputTokens ?? ((task.attempt ?? 1) === 1 ? 0 : void 0), generationMs: task.runtime_metrics?.generationMs ?? ((task.attempt ?? 1) === 1 ? 0 : void 0) }; const controller = new AbortController(); task.notify_orchestrator_available = void 0; const retention = { attempt: task.attempt ?? 1, settled: false, durable: false, consumers: 0, persistenceFailed: false }; this.attemptRetention.set(task, retention); this.tasks.set(id, task); this.taskCwds.set(id, cwd); this.controllers.set(id, controller); if (config.enable_ask_orchestrator !== false) this.askTimeouts.set(id, config.ask_timeout_ms ?? DEFAULT_ASK_TIMEOUT_MS); this.liveStates.set(id, { attempt: task.attempt ?? 1, parentSessionId, bridgeReady: false, pendingMessages: [], pendingBytes: 0, pendingConsumption: 0 }); const abortFromParent = () => this.cancel(id, "parent abort"); if (parentSignal?.aborted) abortFromParent(); else parentSignal?.addEventListener("abort", abortFromParent, { once: true }); this.record(cwd, task, "queued"); this.notifyTaskUpdate(id, onTaskUpdate, true); const run = async () => { let timedOut = false; let acquired = false; let activeRunnerSettlement; try { await limiter.acquire(); acquired = true; if (controller.signal.aborted || isTerminalStatus(task.status)) return; task.status = "running"; task.started_at = nowIso(); task.timeout_started_at = Date.parse(task.started_at); task.timeout_deadline_at = task.timeout_started_at + config.timeout_ms; task.timeout_extensions_used = 0; task.timeout_deadline_generation = 1; task.timeout_max_extensions = config.max_timeout_extensions ?? DEFAULT_MAX_TIMEOUT_EXTENSIONS; if (atelierRun) { atelierStepIndex = atelierRun.beginStep({ agent: definition.name, model: task.model, startedAt: Date.now() }).index; atelierRun.setState("running"); } task.last_activity_at = task.started_at; task.last_activity = "started"; this.record(cwd, task, "started"); this.notifyTaskUpdate(id, onTaskUpdate, true); let interactionsHandled = 0; let result; const runnerMetricOffset = { turns: 0, compactions: 0, generationOutputTokens: 0, generationMs: 0 }; while (true) { const runnerMetricHighwater = { turns: 0, compactions: 0, generationOutputTokens: 0, generationMs: 0 }; const updateRunnerMetrics = (metrics) => { if (!metrics) return; for (const key3 of [ "turns", "compactions", "generationOutputTokens", "generationMs" ]) { if (metrics[key3] !== void 0) runnerMetricHighwater[key3] = Math.max( runnerMetricHighwater[key3], metrics[key3] ); } task.runtime_metrics = { ...metrics }; for (const key3 of [ "turns", "compactions", "generationOutputTokens", "generationMs" ]) { if (metrics[key3] !== void 0 || key3 === "generationOutputTokens" || key3 === "generationMs") task.runtime_metrics[key3] = metricBaseline[key3] === void 0 ? void 0 : metricBaseline[key3] + runnerMetricOffset[key3] + runnerMetricHighwater[key3]; } }; const runnerPromise = this.runner({ definition, task: taskText, taskId: id, parentPiSessionId: parentSessionId, context, cwd, ctx, config, signal: controller.signal, effectiveProfile, nested_session_path: nestedSessionPath, continuation: continuationPrompt ? { prompt: continuationPrompt, attempt: task.attempt ?? 1, previous_snapshot: previousSnapshot } : void 0, registerLiveBridge: (bridge) => this.registerLiveBridge( id, bridge, parentSessionId, task.attempt ?? 1 ), clearLiveBridge: () => this.clearLiveBridge(id, task.attempt ?? 1), onQueuedMessageStart: () => this.consumeQueuedMessage(id), orchestratorChannel: config.enable_ask_orchestrator !== false || config.enable_notify_orchestrator !== false ? { askQuestion: (message, signal) => this.askOrchestrator(id, message, signal), reportProgress: (message) => this.reportProgress(id, message), onPendingChange: (listener) => this.onQuestionPendingChange(id, listener), close: (reason) => this.rejectPendingQuestions(id, reason) } : void 0, onActivity: (activity) => { if (activity.assistant_message && atelierRun && atelierStepIndex !== void 0) { atelierRun.recordAssistantMessage( atelierStepIndex, definition.name, activity.assistant_message, activity.observed_at ); } if (activity.assistant_message) this.onAssistantMessage?.( parentSessionId, id, activity.assistant_message ); updateRunnerMetrics(activity.runtime_metrics); if (task.status === "stopping" || isTerminalStatus(task.status)) return; task.last_activity_at = nowIso(); if (activity.live_activity) task.live_activity = activity.live_activity; task.last_activity = activity.live_activity?.current?.label ?? activity.message; if (activity.output) task.output_preview = compactOutput(activity.output); if (activity.prompt) { if (continuationPrompt) task.continuation_prompt = sanitizeInteractionTransportText( activity.prompt ); else task.prompt = sanitizeInteractionTransportText( activity.prompt ); } if (activity.system_prompt) task.system_prompt = sanitizeInteractionTransportText( activity.system_prompt ); if (activity.transcript) task.transcript = sanitizeInteractionTransportText( activity.transcript ); if (activity.usage) task.usage = activity.usage; if (activity.effort) task.effort = activity.effort; if (activity.thread_snapshot) task.thread_snapshot = sanitizeUnknown( activity.thread_snapshot ); if (activity.interaction_request) task.interaction_request = activity.interaction_request; if (activity.nested_session_path) task.nested_session_path = activity.nested_session_path; if (activity.notify_orchestrator_available !== void 0) task.notify_orchestrator_available = activity.notify_orchestrator_available; if (activity.dropped_tools !== void 0) task.dropped_tools = [...activity.dropped_tools]; if (activity.pi_retry_attempts !== void 0) task.pi_retry_attempts = activity.pi_retry_attempts; const importantActivity = activity.diagnostic === true || activity.dropped_tools !== void 0 || activity.message === "interaction required" || Boolean(activity.interaction_request) || Boolean(activity.thread_snapshot) && !activity.message.startsWith("streaming "); if (activity.persist !== false && (activity.persist === true || activity.diagnostic === true || activity.dropped_tools !== void 0 || activity.message === "interaction required" || Boolean(activity.interaction_request))) this.record(cwd, task, activity.message); this.notifyTaskUpdate(id, onTaskUpdate, importantActivity); } }); runnerPromise.catch(() => { }); activeRunnerSettlement = runnerPromise.then( () => void 0, () => void 0 ); const timeoutPromise = new Promise((_resolve, reject) => { this.armDeadline(task, config, cwd, () => { const elapsed = task.timeout_deadline_at - task.timeout_started_at; timedOut = true; this.stopDispositions.set(id, { status: "failed", metadata: { category: "total_timeout", message: `timed out after ${elapsed}ms`, phase: "manager", retryable: false, partial_result_available: hasPartialResult(task), details: { timeout_ms: String(elapsed) } }, fallbackError: `timed out after ${elapsed}ms` }); this.transitionToStopping( task, `timed out after ${elapsed}ms`, cwd ); this.notifyTaskUpdate(id, onTaskUpdate, true); controller.abort(); reject(new Error(`timed out after ${elapsed}ms`)); }); }); const abortPromise = new Promise((_resolve, reject) => { if (controller.signal.aborted) reject(new Error("Subagent was aborted")); else controller.signal.addEventListener( "abort", () => reject(new Error("Subagent was aborted")), { once: true } ); }); result = await Promise.race([ runnerPromise, timeoutPromise, abortPromise ]); await activeRunnerSettlement; activeRunnerSettlement = void 0; updateRunnerMetrics(result?.runtime_metrics); for (const key3 of [ "turns", "compactions", "generationOutputTokens", "generationMs" ]) runnerMetricOffset[key3] += runnerMetricHighwater[key3]; if (task.status === "stopping") { this.finalizeStop(task, parentSessionId, cwd, onTaskUpdate); return; } if (isTerminalStatus(task.status)) return; const interactionRequest = result.interaction_request; if (!interactionRequest) break; subagentAuditLog(cwd, "interaction_bridge_request_detected", { taskId: id, agent: definition.name, ...interactionLogFields(interactionRequest) }); if (task.mode === "background") { subagentAuditLog(cwd, "interaction_bridge_background_blocked", { taskId: id, agent: definition.name, ...interactionLogFields(interactionRequest) }); throw new Error( "Subagent interaction requires main-thread handling; rerun in task mode to answer it." ); } interactionsHandled += 1; if (interactionsHandled > 5) throw new Error("Subagent interaction retry limit exceeded."); task.result = sanitizeInteractionTransportText(result.result); task.output_preview = compactOutput(result.result); task.transcript = sanitizeInteractionTransportText( `${task.transcript ?? ""} # interaction request surfaced to orchestrator ${result.result}`.trim() ); task.last_activity = "interaction required; awaiting main-thread response"; task.last_activity_at = nowIso(); task.usage = result.usage ?? task.usage; if (result.system_prompt ?? task.system_prompt) task.system_prompt = sanitizeInteractionTransportText( result.system_prompt ?? task.system_prompt ); task.model = result.model; task.effort = result.effort ?? task.effort; task.fallback_used = result.fallback_used; if (result.thread_snapshot) task.thread_snapshot = sanitizeUnknown(result.thread_snapshot); if (result.dropped_tools !== void 0) task.dropped_tools = [...result.dropped_tools]; if (result.nested_session_path) task.nested_session_path = result.nested_session_path; task.interaction_request = interactionRequest; this.record(cwd, task, task.last_activity); this.notifyTaskUpdate(id, onTaskUpdate, true); subagentAuditLog(cwd, "interaction_bridge_prompt_main_thread", { taskId: id, agent: definition.name, ...interactionLogFields(interactionRequest) }); this.onInteractionPromptActive?.(true); let response; try { response = publishInteractionResponse( await Promise.race([ promptMainThreadForInteraction(ctx, interactionRequest), abortPromise ]) ); } finally { this.onInteractionPromptActive?.(false); } subagentAuditLog(cwd, "interaction_bridge_user_response", { taskId: id, agent: definition.name, requestId: interactionRequest.requestId, status: response.status }); if (response.status === "cancelled") throw new Error( `Subagent interaction cancelled by main user: ${interactionRequest.requestId}` ); if (response.status === "failed") throw new Error( `Subagent interaction failed: ${response.error ?? interactionRequest.requestId}` ); task.last_activity = "interaction answered by main user; retrying subagent"; delete task.interaction_request; task.last_activity_at = nowIso(); this.record(cwd, task, task.last_activity); this.notifyTaskUpdate(id, onTaskUpdate, true); } if (!result) throw new Error("Subagent finished without a result."); const finalResult = sanitizeInteractionTransportText( result.result ?? "" ); if (!finalResult.trim()) throw new Error("Subagent finished without a final response."); this.stopDispositions.delete(id); this.closeTaskLiveState(task); task.status = "completed"; delete task.stop_reason; delete task.live_activity; task.result = finalResult; task.output_preview = compactOutput(finalResult); task.transcript = sanitizeInteractionTransportText( `${task.transcript ?? ""} # response sent to orchestrator ${finalResult}`.trim() ); task.last_activity = "completed"; task.last_activity_at = nowIso(); task.usage = result.usage ?? task.usage; if (result.system_prompt ?? task.system_prompt) task.system_prompt = sanitizeInteractionTransportText( result.system_prompt ?? task.system_prompt ); task.model = result.model; task.effort = result.effort ?? task.effort; task.fallback_used = result.fallback_used; if (result.thread_snapshot) task.thread_snapshot = sanitizeUnknown(result.thread_snapshot); if (result.dropped_tools !== void 0) task.dropped_tools = [...result.dropped_tools]; if (result.nested_session_path) task.nested_session_path = result.nested_session_path; delete task.interaction_request; task.ended_at = task.last_activity_at; this.record(cwd, task, "completed"); this.notifyTaskUpdate(id, onTaskUpdate, true); if (task.mode === "background") { ctx?.ui?.notify?.( `Subagent ${definition.name} completed: ${id}`, "info" ); this.onTerminalBackgroundTask?.(task, cwd); } } catch (error) { if (task.status === "stopping") { await activeRunnerSettlement?.catch(() => void 0); activeRunnerSettlement = void 0; this.finalizeStop(task, parentSessionId, cwd, onTaskUpdate); if (task.mode === "background") this.onTerminalBackgroundTask?.(task, cwd); return; } if (isTerminalStatus(task.status)) return; this.stopDispositions.delete(id); task.status = "failed"; delete task.live_activity; delete task.stop_reason; const metadata = timedOut ? normalizeErrorMetadata({ category: "total_timeout", message: `timed out after ${config.timeout_ms}ms`, phase: "manager", retryable: false, partial_result_available: hasPartialResult(task), details: { timeout_ms: String(config.timeout_ms) } }) : error instanceof SubagentStructuredError ? error.error_metadata : classifyThrownError(error, { phase: "manager" }); task.error_metadata = enrichTerminalMetadata( task, parentSessionId, metadata ); task.error = timedOut || error instanceof SubagentStructuredError ? deriveErrorString(task.error_metadata) : error instanceof Error ? error.message : String(error); this.closeTaskLiveState(task); task.last_activity = `failed: ${task.error}`; task.last_activity_at = nowIso(); task.ended_at = task.last_activity_at; this.record(cwd, task, task.last_activity); this.notifyTaskUpdate(id, onTaskUpdate, true); ctx?.ui?.notify?.( `Subagent ${definition.name} failed: ${task.error}`, "warning" ); if (task.mode === "background") this.onTerminalBackgroundTask?.(task, cwd); } finally { this.clearDeadline(id); this.rejectPendingQuestions( id, task.stop_reason ?? "child session shutdown" ); this.askTimeouts.delete(id); await activeRunnerSettlement?.catch(() => void 0); const finalAtelierStatus = atelierStatus(task.status); if (atelierRun) { if (atelierStepIndex !== void 0) atelierRun.finishStep(atelierStepIndex, finalAtelierStatus, { model: task.model }); atelierRun.setState(finalAtelierStatus); } if (acquired) limiter.release(); this.clearLiveBridge(id, task.attempt ?? 1); parentSignal?.removeEventListener("abort", abortFromParent); this.controllers.delete(id); } }; const settlement = run().finally(() => { this.runnerSettlements.delete(id); retention.settled = true; this.releaseTask(task); }); this.runnerSettlements.set(id, settlement); void settlement; } async awaitRunnerCleanup(taskId2) { const pending = this.runnerSettlements.get(taskId2); if (!pending) return; await pending.catch(() => void 0); } cachedPersistedSessionTasks(cwd, sessionId, byCompletion = false) { const key3 = `${cwd}\0${sessionId}${byCompletion ? "\0completion" : ""}`; const cached = this.sessionTaskCache.get(key3); if (cached && cached.expiresAt > Date.now()) return cached.tasks; try { const listMetadata = this.history.listSessionTaskMetadata; const tasks = byCompletion ? this.history.listSessionTaskMetadataByCompletion(cwd, sessionId, 100) : typeof listMetadata === "function" ? listMetadata.call(this.history, cwd, sessionId, 100) : this.history.listSessionTasks(cwd, sessionId, 100, { includeSnapshots: false }); this.sessionTaskCache.set(key3, { expiresAt: Date.now() + SESSION_TASK_CACHE_MS, tasks }); return tasks; } catch (error) { if (isSqliteBusyError(error)) return cached?.tasks ?? []; throw error; } } invalidateSessionTaskCache(cwd, task) { if (task.session_id) { this.sessionTaskCache.delete(`${cwd}\0${task.session_id}`); this.sessionTaskCache.delete(`${cwd}\0${task.session_id}\0completion`); } } record(cwd, task, activity) { try { this.invalidateSessionTaskCache(cwd, task); this.history.upsertTask(cwd, task); const retention = this.attemptRetention.get(task); if (retention && isTerminalStatus(task.status)) retention.durable = true; return true; } catch (error) { const retention = this.attemptRetention.get(task); if (isTerminalStatus(task.status) && !retention?.persistenceFailed) { if (retention) retention.persistenceFailed = true; console.error( `[pi-subagents] Failed to persist terminal task ${task.id} (attempt ${task.attempt ?? 1}); keeping execution detail in memory:`, error ); } return false; } } notifyTaskUpdate(taskId2, onTaskUpdate, immediate = false) { const notify2 = () => { onTaskUpdate?.(); for (const listener of this.taskUpdateListeners) listener(); }; const task = this.tasks.get(taskId2); if (!immediate && task && (task.status === "stopping" || isTerminalStatus(task.status))) return; if (immediate) { const pending = this.pendingUpdates.get(taskId2); if (pending) clearTimeout(pending); this.pendingUpdates.delete(taskId2); notify2(); return; } if (!onTaskUpdate && !this.taskUpdateListeners.size) return; if (this.pendingUpdates.has(taskId2)) return; const timer = setTimeout(() => { this.pendingUpdates.delete(taskId2); notify2(); }, ACTIVITY_UPDATE_FLUSH_MS); timer.unref?.(); this.pendingUpdates.set(taskId2, timer); } async wait(id) { const task = this.tasks.get(id); if (!task) throw new Error(`Subagent task not found: ${id}`); const releaseResult = this.retainResults([task]); try { while (!isTerminalStatus(task.status)) await new Promise((resolve3) => setTimeout(resolve3, 50)); } finally { releaseResult(); } } }; // src/model-profiles/orchestrator.ts async function applyProfileOrchestrator(pi, ctx, profile) { const orchestrator = profile.orchestrator; if (!orchestrator) return { status: "untouched", message: "Session model left untouched." }; if (orchestrator.model) { const { provider, id } = orchestrator.model; const unavailable = () => ({ status: "unavailable", message: `Orchestrator ${provider}/${id} unavailable; session model and effort left unchanged.` }); try { const model = ctx.modelRegistry.find(provider, id); if (!model || !await pi.setModel(model)) return unavailable(); } catch { return unavailable(); } } if (orchestrator.effort) { pi.setThinkingLevel(orchestrator.effort); const actual = pi.getThinkingLevel(); if (actual !== orchestrator.effort) return { status: "clamped", message: `Orchestrator effort ${orchestrator.effort} clamped to ${actual}.` }; } return { status: "applied", message: "Profile orchestrator applied." }; } // src/model-profiles/session.ts var SESSION_MODEL_PROFILE_ENTRY = "thoth-subagent-model-profile"; var SessionModelProfile = class { constructor(appendEntry) { this.appendEntry = appendEntry; } appendEntry; selection; get() { return this.selection; } set(profile) { if (profile !== void 0 && !profile.trim()) throw new Error("Profile name must be non-empty"); if (!this.appendEntry) throw new Error("Pi appendEntry API is unavailable"); const selection = profile?.trim(); this.appendEntry(SESSION_MODEL_PROFILE_ENTRY, { profile: selection ?? null }); this.selection = selection; } restore(entries) { this.selection = void 0; for (const entry of entries) { if (entry?.type !== "custom" || entry.customType !== SESSION_MODEL_PROFILE_ENTRY) continue; const profile = entry.data?.profile; if (profile === null) this.selection = void 0; else if (typeof profile === "string" && profile.trim()) this.selection = profile.trim(); } } }; // src/model-profiles/command.ts import { getSupportedThinkingLevels } from "@earendil-works/pi-ai"; import { Input } from "@earendil-works/pi-tui"; // ../pi-core/src/panel-clipboard.ts import { stripVTControlCharacters } from "node:util"; function copyToClipboardOsc52(write, text, options = {}) { if (!write) return "unsupported"; const encoded = Buffer.from(stripVTControlCharacters(text), "utf8").toString( "base64" ); if (encoded.length > (options.maxBytes ?? 1e5)) return "too-large"; write(`\x1B]52;c;${encoded}\x07`); return "ok"; } // ../pi-core/src/panel-input.ts import { matchesKey as matchesNativeKey } from "@earendil-works/pi-tui"; function matchesPanelKey2(data, key3) { return matchesPanelKey(data, key3, matchesNativeKey); } function rawMouse(data) { if (!data.startsWith("\x1B[")) return void 0; const payload = data.slice(2); const sgr = payload.match(/^<(\d+);(\d+);(\d+)M$/); const urxvt = payload.match(/^(\d+);(\d+);(\d+)M$/); const match = sgr ?? urxvt; if (match) { const rawButton = Number(match[1]); return { button: urxvt && rawButton >= 32 ? rawButton - 32 : rawButton, col: Number(match[2]) - 1, row: Number(match[3]) - 1 }; } if (data.startsWith("\x1B[M") && data.length >= 6) { return { button: data.charCodeAt(3) - 32, col: data.charCodeAt(4) - 33, row: data.charCodeAt(5) - 33 }; } return void 0; } function panelMouseWheelDelta(data) { const mouse = rawMouse(data); if (!mouse || (mouse.button & 64) === 0) return void 0; return (mouse.button & 1) === 0 ? -1 : 1; } function panelMouseClick(data) { const mouse = rawMouse(data); if (!mouse) return void 0; const isLeftClick = mouse.button === 0 || data.startsWith("\x1B[M") && (mouse.button & 64) === 0 && (mouse.button & 3) === 0; if (!isLeftClick) return void 0; return { type: "click", row: mouse.row, col: mouse.col }; } function normalizePanelKey(data, matchesKey2) { if (matchesNativeKey(data, "ctrl+c")) return "escape"; const keys = Object.keys(panelKeySequences); const raw = keys.find((key3) => panelKeySequences[key3].includes(data)); return raw ?? keys.find((key3) => matchesKey2?.(data, key3) || matchesPanelKey2(data, key3)) ?? data; } // ../pi-core/src/panel-discard.ts init_panel_primitives(); var PanelDiscardConfirmation = class { active = false; request(dirty) { this.active = dirty; return dirty ? "confirm" : "cancel"; } handleInput(data) { if (!this.active) return void 0; const key3 = normalizePanelKey(data); const result = key3.toLowerCase() === "d" ? "discard" : key3 === "escape" || key3.toLowerCase() === "k" ? "resume" : void 0; if (result) this.active = false; return result; } rows() { return [panelHintRow("d discard and close \xB7 k or esc keep editing")]; } }; // ../pi-core/src/panel.ts init_panel_frame(); // ../pi-core/src/panel-host.ts var MOUSE_USERS = /* @__PURE__ */ Symbol.for("thoth.pi-core.panel-mouse.v1"); function acquireMouse(tui) { const terminal = tui.terminal; if (tui.mode === "fullscreen" || typeof terminal?.write !== "function") return () => { }; const users = terminal[MOUSE_USERS] ?? 0; if (!users) terminal.write("\x1B[?1000h\x1B[?1006h"); terminal[MOUSE_USERS] = users + 1; let released = false; return () => { if (released) return; released = true; terminal[MOUSE_USERS] = Math.max(0, (terminal[MOUSE_USERS] ?? 1) - 1); if (!terminal[MOUSE_USERS] && tui.mode !== "fullscreen") terminal.write("\x1B[?1006l\x1B[?1000l"); }; } async function openPanelOverlay(ctx, factory, options) { let releaseMouse = () => { }; try { return await openOwnedOverlay( ctx, (tui, theme, keys, close) => { releaseMouse = acquireMouse(tui); const created = factory( tui, theme, keys, (result) => { try { close(result); } finally { releaseMouse(); } }, { maxHeight: () => Math.max(1, Math.floor(tui.terminal.rows * 0.9)), requestRender: () => tui.requestRender() } ); const retain = (component) => { const dispose = component.dispose; component.dispose = () => { try { dispose?.call(component); } finally { releaseMouse(); } }; return component; }; return created instanceof Promise ? created.then(retain) : retain(created); }, { ...options, overlayOptions: options?.overlayOptions ?? { anchor: "center", width: "96%", maxHeight: "90%" } } ); } finally { releaseMouse(); } } // ../pi-core/src/panel-list-editor.ts init_panel_primitives(); init_render_kit(); var value2 = (text) => typeof text === "function" ? text() : text; var ListEditor = class { constructor(options) { this.options = options; } options; selected = 0; overviewIndex = 0; picker; filter = ""; confirmation = new PanelDiscardConfirmation(); completed = false; saving = false; failedSave = false; error; warning; pending() { return this.options.pendingCount?.() ?? this.options.overview.rows().filter((row) => row.dirty).length; } view() { return this.picker ?? this.options.overview; } rows() { const view = this.view(); const rows = view.rows(); const query = this.filter.trim().toLowerCase(); const filter = view.filter; if (!filter || !query) return rows; return rows.filter((row) => { if (filter.matches) return filter.matches(row, query); const text = filter.text?.(row) ?? (typeof row.label === "string" ? row.label : row.id); return text.toLowerCase().includes(query); }); } openPicker(view, initialIndex = 0) { if (!this.picker) this.overviewIndex = this.selected; this.picker = view; this.selected = initialIndex; this.filter = ""; this.invalidate(); } showOverview() { if (!this.picker) return; this.picker = void 0; this.selected = this.overviewIndex; this.filter = ""; this.invalidate(); } getState() { return { view: this.confirmation.active ? "discard" : this.picker ? "picker" : "overview", selectedIndex: this.selected, filter: this.filter, pendingCount: this.pending(), completed: this.completed, saving: this.saving, error: this.error, warning: this.warning }; } move(delta, wrap = true) { const length = this.rows().length; const next = this.selected + delta; this.selected = length && wrap && this.view().navigation === "wrap" ? (next % length + length) % length : Math.max(0, Math.min(next, length - 1)); } updateFilter(next) { this.filter = next; this.selected = 0; } cancel() { this.completed = true; this.options.onCancel(); } save() { this.saving = true; this.error = void 0; this.warning = void 0; const apply = (result2) => { this.saving = false; this.failedSave = result2?.success === false; if (this.failedSave) { this.error = result2?.error ?? "Saving changes failed."; this.warning = result2?.warning; } else { this.completed = true; this.options.onSaved?.(); } this.invalidate(); }; const fail2 = (error) => apply({ success: false, error: error instanceof Error ? error.message : String(error) }); let result; try { result = this.options.onSave(); } catch (error) { fail2(error); return; } if (result && "then" in result) void result.then(apply, fail2); else apply(result); } handleInput(data) { if (this.completed || this.saving) return; const key3 = normalizePanelKey(data, this.options.matchesKey); if (this.confirmation.active) { if (this.confirmation.handleInput(key3) === "discard") this.cancel(); this.invalidate(); return; } const view = this.view(); const wheel = panelMouseWheelDelta(data); const printable = data.length > 0 && [...data].every((char) => char >= " " && char !== "\x7F"); if (wheel) this.move(wheel, false); else if (key3 === "up" || key3 === "k") this.move(-1); else if (key3 === "down" || key3 === "j") this.move(1); else if (view.filter && key3 === "backspace") this.updateFilter([...this.filter].slice(0, -1).join("")); else if (view.filter && key3 === "ctrl+u") this.updateFilter(""); else if (key3 === "home" || view.homeEndAliases !== false && key3 === "g" && !this.filter) this.selected = 0; else if (key3 === "end" || view.homeEndAliases !== false && key3 === "G" && !this.filter) this.selected = Math.max(0, this.rows().length - 1); else if (view.filter && printable) this.updateFilter(this.filter + data); else if (view.onAction?.(key3, this.rows()[this.selected], this) !== true) { if (this.picker && (key3 === "enter" || key3 === "escape" || key3 === "q")) this.showOverview(); else if (!this.picker && (key3 === "escape" || key3 === "q")) { if (this.confirmation.request(this.pending() > 0 || this.failedSave) === "cancel") this.cancel(); } else if (!this.picker && key3.toLowerCase() === "s") this.save(); } this.options.requestRender?.(); } render(width) { const view = this.view(); const rows = this.rows(); if (this.confirmation.active) return renderPanelFrame({ title: "Discard unsaved draft?", rows: this.confirmation.rows(), width, maxHeight: this.options.maxHeight?.(), theme: this.options.theme }); this.selected = Math.max(0, Math.min(this.selected, rows.length - 1)); const height = Math.max( 1, Math.floor(this.options.maxHeight?.() ?? Infinity) ); const budget = Math.max(0, height - 2); const context = { layout: width >= (this.options.wideBreakpoint ?? 84) ? "wide" : "compact", width: Math.max(0, width - 8), index: this.selected, selected: true, filter: this.filter }; const count = this.pending(); const messages = [ ...this.saving ? [panelHintRow("Saving\u2026")] : [], ...this.error ? [{ text: `Save failed: ${this.error}`, tone: "error" }] : [], ...this.warning ? [{ text: this.warning, tone: "warning" }] : [] ]; const header = [ ...!this.picker ? [ panelHintRow( `pending: ${count ? `${count} change${count === 1 ? "" : "s"}` : "none"}` ) ] : [], panelHintRow( value2( view.hints ?? (this.picker ? "\u2191/\u2193/j/k move \xB7 enter select \xB7 esc/q back" : "\u2191/\u2193/j/k move \xB7 enter edit \xB7 s save \xB7 esc/q cancel") ) ), ...view.filter ? [ panelHintRow( `search: ${this.filter || view.filter.placeholder || "(type to filter)"}` ) ] : [], ...view.header?.(context) ?? [] ]; const keptMessages = messages.slice(0, Math.max(0, budget - 1)); const headerBudget = Math.max(0, budget - keptMessages.length - 1); const hintIndex = this.picker ? 0 : 1; const keptHeader = header.length <= headerBudget ? header : header.slice(hintIndex, hintIndex + headerBudget); const available = Math.max( 0, budget - keptMessages.length - keptHeader.length ); const viewport = panelViewport( rows.length, this.selected, available, view.maxVisibleRows ); const choices = rows.slice(viewport.start, viewport.end).map((row, offset) => { const index = viewport.start + offset; const selected = index === this.selected; const label = typeof row.label === "function" ? row.label({ ...context, index, selected }) : row.label; return { text: `${selected ? resolveIcon("selection", "\u203A") : " "} ${row.dirty ? "*" : " "} ${label}`, selected }; }); if (!rows.length && available > 0) { choices.push( panelHintRow(this.filter ? "No matching rows" : "No rows available") ); } const body = [ ...keptHeader, ...keptMessages, ...choices, ...viewport.notice ? [panelHintRow(viewport.notice)] : [] ]; body.push( ...(view.footer?.(context) ?? []).slice( 0, Math.max(0, budget - body.length) ) ); return renderPanelFrame({ title: value2(view.title), rows: body, width, maxHeight: height, theme: this.options.theme }); } invalidate() { this.options.requestRender?.(); } }; function createListEditor(options) { return new ListEditor(options); } // ../pi-core/src/panel.ts init_panel_primitives(); // src/ui/theme.ts function agentIcon() { return resolveIcon("agent", "\u{F08C7}"); } var BOX_CHARS = { get topLeft() { return resolveIcon("boxTopLeft", "\u256D"); }, get topRight() { return resolveIcon("boxTopRight", "\u256E"); }, get vertical() { return resolveIcon("boxVertical", "\u2502"); }, get bottomLeft() { return resolveIcon("boxBottomLeft", "\u2570"); }, get bottomRight() { return resolveIcon("boxBottomRight", "\u256F"); }, get horizontal() { return resolveIcon("boxHorizontal", "\u2500"); } }; function themeFg(theme, role, text) { const kit = getRenderKit(); return kit ? kit.fg(theme, role, text) : theme?.fg?.(role, text) ?? text; } function themeBg(theme, role, text) { return theme?.bg?.(role, text) ?? text; } function themeBold(theme, text) { return theme?.bold?.(text) ?? text; } function themeAccent(theme, text) { return themeFg(theme, "accent", text); } function themeDim(theme, text) { return themeFg(theme, "dim", text); } function themeSuccess(theme, text) { return themeFg(theme, "success", text); } function themeWarning(theme, text) { return themeFg(theme, "warning", text); } function themeError(theme, text) { return themeFg(theme, "error", text); } function themeTitle(theme, text) { return themeFg(theme, "toolTitle", themeBold(theme, text)); } function themeStatus(theme, status, customLabel) { const label = customLabel ?? status; switch (status.toLowerCase()) { case "completed": case "done": case "success": return themeSuccess(theme, label); case "failed": case "error": return themeError(theme, label); case "queued": case "cancelled": case "interrupted": case "stopping": return themeWarning(theme, label); case "running": return themeAccent(theme, label); default: return themeDim(theme, label); } } function padToWidth(text, width) { const clipped = truncateToWidth2(text, width, ""); return `${clipped}${" ".repeat(Math.max(0, width - visibleWidth2(clipped)))}`; } function frameBox(title, lines, width, options) { const borderFn = options?.borderFn ?? ((text) => text); const safeWidth = Math.max(1, Math.floor(width || 1)); if (safeWidth < 10) { const all = title ? [title, ...lines] : lines; return all.map( (l) => truncateToWidth2(l, safeWidth, resolveIcon("ellipsis", "\u2026")) ); } const innerWidth = safeWidth - 2; const contentWidth = Math.max(1, innerWidth - 2); let top; if (title) { const maxTitleWidth = Math.max(0, innerWidth - 4); const clippedTitle = truncateToWidth2( title, maxTitleWidth, resolveIcon("ellipsis", "\u2026") ); const titleVisWidth = visibleWidth2(clippedTitle); const filler = Math.max(0, innerWidth - titleVisWidth - 3); top = `${borderFn(BOX_CHARS.topLeft + BOX_CHARS.horizontal)} ${clippedTitle} ${borderFn(BOX_CHARS.horizontal.repeat(filler))}${borderFn(BOX_CHARS.topRight)}`; } else { top = `${borderFn(BOX_CHARS.topLeft)}${borderFn(BOX_CHARS.horizontal.repeat(innerWidth))}${borderFn(BOX_CHARS.topRight)}`; } const flatLines = lines.flatMap((l) => l.split("\n")); const middle = flatLines.map( (l) => `${borderFn(BOX_CHARS.vertical)} ${padToWidth(l, contentWidth)} ${borderFn(BOX_CHARS.vertical)}` ); const bottom = `${borderFn(BOX_CHARS.bottomLeft)}${borderFn(BOX_CHARS.horizontal.repeat(innerWidth))}${borderFn(BOX_CHARS.bottomRight)}`; return [top, ...middle, bottom]; } // src/model-profiles/data.ts function globalSubagentsConfigPath(agentDir2) { return modelProfilePaths({ cwd: process.cwd(), agentDir: agentDir2 }).global; } function modelKey(model) { return `${model.provider}/${model.id}`; } function modelFromAny(raw) { const provider = typeof raw?.provider === "string" ? raw.provider : typeof raw?.provider?.id === "string" ? raw.provider.id : typeof raw?.provider?.name === "string" ? raw.provider.name : void 0; const id = typeof raw?.id === "string" ? raw.id : typeof raw?.model === "string" ? raw.model : typeof raw?.name === "string" ? raw.name : void 0; if (!provider || !id) return void 0; const name = typeof raw.name === "string" && raw.name.trim() ? raw.name.trim() : void 0; return { provider, id, label: String(raw?.label ?? raw?.displayName ?? id), ...name ? { name } : {} }; } function groupAvailableModelsByProvider(rawModels = []) { const grouped = {}; for (const raw of rawModels) { const model = modelFromAny(raw); if (!model) continue; grouped[model.provider] ??= []; if (!grouped[model.provider].some((existing) => existing.id === model.id)) grouped[model.provider].push(model); } for (const models of Object.values(grouped)) models.sort((a, b) => a.id.localeCompare(b.id)); return Object.fromEntries( Object.entries(grouped).sort(([a], [b]) => a.localeCompare(b)) ); } function availableModelSet(rawModels = []) { return new Set( Object.values(groupAvailableModelsByProvider(rawModels)).flat().map((model) => modelKey(model)) ); } function buildAgentRows(ctx = {}) { const cwd = ctx.cwd ?? process.cwd(); const config = readSubagentsConfig(cwd); const byName = /* @__PURE__ */ new Map(); for (const definition of loadSubagents(cwd)) byName.set(definition.name, definition); return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)).map((definition) => { const resolved = resolveDefaultSubagentProfile({ agentName: definition.name, definition, config, ctx }); return { key: definition.name.trim().toLowerCase(), name: definition.name, description: definition.description, scope: definition.scope ?? "global", defaultModel: resolved.model.value, defaultEffort: resolved.effort.value }; }); } // src/model-profiles/editor.ts var DEFAULT_PROFILE = "default"; var entryKey2 = (scope, name) => scope ? `${scope}:${name}` : DEFAULT_PROFILE; function cloneAgent(profile = {}) { return { ...profile.model ? { model: { ...profile.model } } : {}, ...profile.effort ? { effort: profile.effort } : {} }; } function cloneAgents(agents) { return Object.fromEntries( Object.entries(agents).map(([name, agent]) => [name, cloneAgent(agent)]) ); } var cloneOrchestrator = (orchestrator) => { const copy = cloneAgent(orchestrator); return copy.model || copy.effort ? copy : void 0; }; var signature = (agents, orchestrator) => JSON.stringify([ Object.entries(agents).map(([name, agent]) => [ name, agent.model ? `${agent.model.provider}/${agent.model.id}` : null, agent.effort ?? null ]).sort(([a], [b]) => String(a).localeCompare(String(b))), orchestrator?.model ? `${orchestrator.model.provider}/${orchestrator.model.id}` : null, orchestrator?.effort ?? null ]); function extrasOf(profile) { const { agents: _agents, orchestrator: _orchestrator, ...extras } = profile; return extras; } var isDraft = (entry) => !!entry.scope && !entry.base; function isEntryDirty(entry) { if (!entry.scope) return false; return !entry.base || signature(entry.agents, entry.orchestrator) !== signature(entry.base, entry.baseOrchestrator); } var ModelProfileWorkspace = class { constructor(store, rows, session = {}) { this.store = store; this.rows = rows; this.session = session; this.reload(); } store; rows; session; saved = []; drafts = []; edits = /* @__PURE__ */ new Map(); /** Persisted `active` names, cached so rendering never touches the disk. */ active = {}; get canUseSession() { return typeof this.session.set === "function"; } get sessionSelection() { return this.session.get?.(); } /** Re-read both files; drafts and unsaved edits survive when still valid. */ reload() { const documents = { global: this.store.read("global"), project: this.store.read("project") }; const next = []; for (const scope of ["project", "global"]) { const names = Object.keys(documents[scope].profiles).sort( (a, b) => a.localeCompare(b) ); for (const name of names) { const profile = documents[scope].profiles[name]; const key3 = entryKey2(scope, name); const edited = this.edits.get(key3); next.push({ key: key3, name, scope, agents: cloneAgents(edited?.agents ?? profile.agents), base: cloneAgents(profile.agents), orchestrator: cloneOrchestrator( edited ? edited.orchestrator : profile.orchestrator ), baseOrchestrator: cloneOrchestrator(profile.orchestrator), extras: extrasOf(profile), shadowed: scope === "global" && Object.hasOwn(documents.project.profiles, name) }); } } for (const key3 of [...this.edits.keys()]) if (!next.some((entry) => entry.key === key3)) this.edits.delete(key3); this.saved = next; this.active = { project: documents.project.active, global: documents.global.active }; } /** Default first, then project profiles, then global ones. */ entries() { return [this.defaultEntry(), ...this.saved, ...this.drafts]; } defaultEntry() { return { key: DEFAULT_PROFILE, name: DEFAULT_PROFILE, agents: this.defaultAgents(), extras: {}, shadowed: false }; } /** Full copy of the `default` effective model/effort for every listed agent. */ defaultAgents() { return Object.fromEntries( this.rows.map((row) => [ row.key, { ...row.defaultModel ? { model: { ...row.defaultModel } } : {}, ...row.defaultEffort ? { effort: row.defaultEffort } : {} } ]) ); } pendingCount() { return this.entries().filter(isEntryDirty).length; } /** Effective values: explicit profile value, else the default value. */ valuesFor(entry, row) { const own = entry.scope ? entry.agents[row.key] : void 0; return { model: own?.model ?? row.defaultModel, effort: own?.effort ?? row.defaultEffort }; } pointers() { return { session: this.sessionSelection, ...this.active }; } /** Mirrors ModelProfileStore.resolve from cached data. */ effective() { const pointers = this.pointers(); for (const level of ["session", "project", "global"]) { const name = pointers[level]; if (!name) continue; if (name === DEFAULT_PROFILE) return { name }; const global = this.saved.find( (e) => e.name === name && e.scope === "global" ); if (level === "global" && !global) continue; const hit = this.saved.find((e) => e.name === name && e.scope === "project") ?? global; if (hit) return { name, scope: hit.scope }; } return { name: DEFAULT_PROFILE }; } /** Which pointers resolve to this entry, and whether it is the effective one. */ markers(entry) { const pointers = this.pointers(); const resolvesHere = (pointer) => { if (pointers[pointer] !== entry.name || isDraft(entry)) return false; if (!entry.scope) return true; if (pointer === "global") return entry.scope === "global"; return entry.scope === "project" || !entry.shadowed; }; const effective = this.effective(); return { session: resolvesHere("session"), project: resolvesHere("project"), global: resolvesHere("global"), effective: effective.name === entry.name && effective.scope === entry.scope && !isDraft(entry) }; } agentFor(name) { const key3 = name.trim().toLowerCase(); if (!this.rows.some((row) => row.key === key3)) throw new Error(`Unknown subagent: ${name}`); return key3; } assertEditable(entry) { if (!entry.scope) throw new Error( "The default profile is read-only. Create a new profile from it to edit." ); } validateNewName(name, scope) { const value3 = name.trim(); if (!value3) throw new Error("Profile name must be non-empty"); if (value3 === DEFAULT_PROFILE) throw new Error("default is a reserved virtual profile"); if (this.entries().some((e) => e.scope === scope && e.name === value3)) throw new Error(`Profile already exists in ${scope} scope: ${value3}`); return value3; } /** * New draft from `source` (default => full copy of default values). Nothing * is written until `save`. */ createDraft(source, name, scope) { const value3 = this.validateNewName(name, scope); const agents = this.defaultAgents(); for (const [agent, own] of Object.entries( source.scope ? source.agents : {} )) agents[agent] = { ...agents[agent], ...cloneAgent(own) }; const draft = { key: entryKey2(scope, value3), name: value3, scope, agents, orchestrator: source.scope ? cloneOrchestrator(source.orchestrator) : void 0, extras: { ...source.extras }, shadowed: false }; this.drafts.push(draft); return draft; } edit(entry, agentName, edit) { this.assertEditable(entry); const key3 = this.agentFor(agentName); const row = this.rows.find((item) => item.key === key3); const agent = cloneAgent(entry.agents[key3]); if (edit.reset === "model") agent.model = cloneModel(row.defaultModel); if (edit.reset === "effort") agent.effort = row.defaultEffort; if (edit.model) agent.model = { ...edit.model }; if (edit.effort) agent.effort = edit.effort; if (!agent.model) delete agent.model; if (!agent.effort) delete agent.effort; entry.agents[key3] = agent; if (!isDraft(entry)) this.trackEdits(entry); } /** Stage an orchestrator edit; reset clears the field back to the session's. */ editOrchestrator(entry, edit) { this.assertEditable(entry); const next = cloneAgent(entry.orchestrator); if (edit.reset === "model") delete next.model; if (edit.reset === "effort") delete next.effort; if (edit.model) next.model = { ...edit.model }; if (edit.effort) next.effort = edit.effort; this.stageOrchestrator(entry, next); } /** Replace the orchestrator wholesale (e.g. a session capture). */ setOrchestrator(entry, orchestrator) { this.assertEditable(entry); this.stageOrchestrator(entry, orchestrator); } stageOrchestrator(entry, orchestrator) { entry.orchestrator = cloneOrchestrator(orchestrator); if (!isDraft(entry)) this.trackEdits(entry); } /** Persisted orchestrator of the effective profile (what activation applies). */ effectiveOrchestrator() { const { name, scope } = this.effective(); return this.saved.find((e) => e.name === name && e.scope === scope)?.baseOrchestrator; } trackEdits(entry) { if (isEntryDirty(entry)) this.edits.set(entry.key, { agents: entry.agents, orchestrator: entry.orchestrator }); else this.edits.delete(entry.key); } /** Persist a draft or edited profile as a self-contained copy. Returns the file. */ save(entry) { this.assertEditable(entry); const scope = entry.scope; const agents = cloneAgents(entry.agents); for (const row of this.rows) agents[row.key] = { ...row.defaultModel ? { model: { ...row.defaultModel } } : {}, ...row.defaultEffort ? { effort: row.defaultEffort } : {}, ...cloneAgent(agents[row.key]) }; const value3 = { ...entry.extras, agents, // Explicit undefined: store.save merges with the file, so omission would keep it. orchestrator: entry.orchestrator }; if (isDraft(entry)) this.store.create(scope, entry.name, value3); else this.store.save(scope, entry.name, value3); this.drafts = this.drafts.filter((draft) => draft !== entry); this.edits.delete(entry.key); this.reload(); return this.store.paths[scope]; } /** Rename a draft in memory, or a saved profile in its file. */ rename(entry, name) { this.assertEditable(entry); const scope = entry.scope; const value3 = this.validateNewName(name, scope); if (isDraft(entry)) { entry.name = value3; entry.key = entryKey2(scope, value3); return; } const pointers = this.pointerTargets(entry); const edited = this.edits.get(entry.key); this.store.rename(scope, entry.name, value3); this.edits.delete(entry.key); if (edited) this.edits.set(entryKey2(scope, value3), edited); if (pointers.includes("project") && scope === "global") this.store.setProjectPin(value3); if (pointers.includes("session")) this.session.set?.(value3); this.reload(); } /** Pointers that resolve to this entry (global active only for global ones). */ pointerTargets(entry) { const markers = this.markers(entry); return ["session", "project", "global"].filter( (pointer) => markers[pointer] ); } /** Remove a draft, or delete a saved profile and clear pointers to it. */ delete(entry) { this.assertEditable(entry); if (isDraft(entry)) { this.drafts = this.drafts.filter((draft) => draft !== entry); return []; } const scope = entry.scope; const cleared = this.pointerTargets(entry); this.store.delete(scope, entry.name); if (cleared.includes("project") && scope === "global") this.store.setProjectPin(void 0); if (cleared.includes("session")) this.session.set?.(void 0); this.edits.delete(entry.key); this.reload(); return cleared; } /** Select (or, when already selected, clear) a profile for one pointer. */ activate(entry, pointer, toggle = true) { if (isDraft(entry)) throw new Error("Save the draft before using it."); if (entry.shadowed && pointer !== "global") throw new Error( `Global ${entry.name} is shadowed by the local profile; select that one.` ); if (pointer === "global" && entry.scope === "project") throw new Error("Global active must be a global profile."); const already = toggle && this.markers(entry)[pointer]; const next = already ? void 0 : entry.name; if (pointer === "session") { if (!this.session.set) throw new Error("Session selection is unavailable here."); this.session.set(next); } else if (pointer === "project") this.store.setProjectPin(next); else this.store.setGlobalActive(next); this.reload(); return next ? "set" : "cleared"; } }; function cloneModel(model) { return model ? { ...model } : void 0; } // src/model-profiles/formatting.ts var SIDEBAR_MIN_WIDTH = 90; function sidebarWidthFor(width) { return width >= SIDEBAR_MIN_WIDTH ? Math.max(18, Math.min(30, Math.floor(width * 0.25))) : 0; } function scopeTag(entry) { if (!entry.scope) return ""; return entry.scope === "project" ? "(local)" : "(global)"; } function markerLetters(markers) { return [ markers.session ? "S" : "", markers.project ? "P" : "", markers.global ? "G" : "" ].filter(Boolean).join(""); } function profileEntryLabel(entry, markers, verbose = false) { const shadow = entry.shadowed ? verbose ? " [shadowed]" : "~" : ""; return [ `${markers.effective ? "\u25CF" : " "} ${markerLetters(markers).padEnd(3)}`, `${entry.name}${isEntryDirty(entry) && !isDraft(entry) ? "*" : ""}`, scopeTag(entry) + shadow, isDraft(entry) ? "[draft]" : "" ].filter(Boolean).join(" "); } var PROFILE_LEGEND = [ "markers (not keys)", "\u25CF effective", "S session", "P pin G global", "~ shadowed" ]; function renderProfileSidebar(input) { const budget = Math.max(0, input.height - 2); const legend = budget >= input.rows.length + PROFILE_LEGEND.length + 1 ? PROFILE_LEGEND.map((text) => panelHintRow(text)) : []; const listBudget = Math.max(0, budget - legend.length); const viewport = panelViewport(input.rows.length, input.selected, listBudget); const visible2 = input.rows.slice(viewport.start, viewport.end).map( (row, offset) => typeof row === "string" ? { text: row, selected: viewport.start + offset === input.selected } : { ...row, selected: viewport.start + offset === input.selected } ); const body = [ ...visible2, ...viewport.notice ? [panelHintRow(viewport.notice)] : [] ]; while (legend.length && body.length < budget - legend.length) body.push(""); body.push(...legend); return renderPanelFrame({ title: "Profiles", rows: body, width: input.width, maxHeight: input.height, theme: input.theme }); } function joinColumns(left, right, leftWidth, rightWidth) { const height = Math.max(left.length, right.length); return Array.from( { length: height }, (_, index) => padPanelText(left[index] ?? "", leftWidth) + padPanelText(right[index] ?? "", rightWidth) ); } function describeEntry(entry, markers, theme) { if (!entry.scope) return `default ${themeDim(theme, "(read-only: definitions / config / session model)")}`; const parts = [ `${entry.name} ${scopeTag(entry)}`, entry.shadowed ? "shadowed by local profile" : "", isDraft(entry) ? "draft: unsaved" : isEntryDirty(entry) ? "unsaved edits" : "", markers.session ? "session" : "", markers.project ? "project pin" : "", markers.global ? "global active" : "", markers.effective ? "effective" : "" ].filter(Boolean); return parts.join(` ${resolveIcon("separator", "\xB7")} `); } function buildNonTuiModelProfilesMessage(workspace, agentDir2) { const lines = [ `Subagent model profiles are edited in the Pi TUI (/subagents-model). Profiles live in ${globalSubagentsConfigPath(agentDir2)} and /.pi/thoth/profiles.json.` ]; if (workspace) for (const entry of workspace.entries()) { const markers = workspace.markers(entry); lines.push(` ${profileEntryLabel(entry, markers, true)}`.trimEnd()); } return lines.join("\n"); } var ORCHESTRATOR_ROW_ID = "\0orchestrator"; var SESSION_MODEL_TEXT = "session model"; var SESSION_EFFORT_TEXT = "session"; function orchestratorValueText(orchestrator, modelText) { return { model: orchestrator?.model ? modelText(orchestrator.model) : SESSION_MODEL_TEXT, effort: orchestrator?.effort ?? SESSION_EFFORT_TEXT }; } function orchestratorDrift(expected, live) { const differs = expected?.model && live.model && (expected.model.provider !== live.model.provider || expected.model.id !== live.model.id) || expected?.effort && live.effort && expected.effort !== live.effort; if (!expected || !differs) return void 0; const describe = (model, effort) => [model && `${model.provider}/${model.id}`, effort].filter(Boolean).join(" "); return `drift: session ${describe(expected.model && live.model, expected.effort && live.effort)} \u2260 profile ${describe(expected.model, expected.effort)}`; } // src/model-profiles/command.ts var FALLBACK_EFFORT_CHOICES = [ "inherit", "off", "minimal", "low", "medium", "high", "xhigh", "max" ]; function buildEffortChoices(modelRef, currentEffort, availableModels, ctx = {}) { let model; if (modelRef) { const matches = (candidate) => candidate?.provider === modelRef.provider && candidate?.id === modelRef.id; const lookups = [ () => ctx.modelRuntime?.getModel?.(modelRef.provider, modelRef.id), () => ctx.modelRegistry?.find?.(modelRef.provider, modelRef.id), () => availableModels.find(matches), () => matches(ctx.model) ? ctx.model : void 0 ]; for (const lookup of lookups) { try { const candidate = lookup(); if (candidate && typeof candidate.reasoning === "boolean") { model = candidate; break; } } catch { } } } const supported = model ? ["inherit", ...getSupportedThinkingLevels(model)] : FALLBACK_EFFORT_CHOICES; const choices = supported.map((value3) => ({ value: value3, label: value3 })); if (currentEffort && !supported.includes(currentEffort)) choices.push({ value: currentEffort, label: `${currentEffort} (current; unsupported, clamped by Pi)` }); return choices; } var POINTER_LABEL = { session: "session selection", project: "project pin", global: "global active" }; function activationMessage(pointer, entry, result) { if (result === "cleared") return `Cleared the ${POINTER_LABEL[pointer]} (${entry.name}).`; const target = { session: "Session now uses", project: "Project pinned to", global: "Global active profile is" }[pointer]; const note = isEntryDirty(entry) ? " Unsaved edits are not applied." : ""; return `${target} ${entry.name}.${note}`; } function createSubagentModelProfilesModal(input) { const { workspace } = input; const availableByProvider = groupAvailableModelsByProvider( input.availableModels ?? [] ); const providerNames = Object.keys(availableByProvider); const availableKeys = availableModelSet(input.availableModels ?? []); let profileIndex = 0; let prompt; let status; let stacked = true; const entries = () => workspace.entries(); const current = () => { const all = entries(); profileIndex = Math.max(0, Math.min(profileIndex, all.length - 1)); return all[profileIndex]; }; const selectKey = (key3) => { profileIndex = Math.max( 0, entries().findIndex((entry) => entry.key === key3) ); }; const rowOf = (key3) => workspace.rows.find((row) => row.key === key3); const notify2 = (text, tone = "success") => { status = { text, tone }; }; const attempt = (action) => { try { action(); } catch (error) { notify2(error instanceof Error ? error.message : String(error), "error"); } }; const moveHint = () => `${resolveIcon("arrowUp", "\u2191")}/${resolveIcon("arrowDown", "\u2193")}/j/k move`; const separator = () => ` ${resolveIcon("separator", "\xB7")} `; const modelText = (model) => { if (!model) return "unresolved"; const label = `${model.provider}/${model.id}`; return availableKeys.size && !availableKeys.has(modelKey(model)) ? `${label} (unavailable)` : label; }; const modelRowLabel = (model) => { const saved = `${model.provider}/${model.id}`; return model.name && model.name !== model.id ? `${model.name} \u2014 ${saved}` : `${model.label} (${saved})`; }; const choose = (title, header, choices, onPick) => editor.openPicker({ title, hints: () => ["choose", "enter: select", "esc/q: back"].join(separator()), header: () => header, rows: () => choices, onAction: (key3, choice) => { if (key3 !== "enter") return false; editor.showOverview(); if (choice) attempt(() => onPick(choice.id)); return true; } }); const askName = (title, value3, submit) => { const nameInput = new Input({ prompt: "name: " }); nameInput.setValue(value3); nameInput.handleInput(""); prompt = { title, input: nameInput, submit: (name) => { const trimmed = name.trim(); if (!trimmed) return "Profile name must be non-empty"; if (trimmed === DEFAULT_PROFILE) return "default is a reserved virtual profile"; prompt = void 0; attempt(() => submit(trimmed)); return void 0; } }; }; const startDraft = (source, verb) => askName( `${verb} profile from ${source.name}`, "", (name) => choose( `Scope for ${name}`, [ `Where should ${name} be stored? Nothing is written until you press s.` ], [ { id: "project", label: "project (local) \u2014 .pi/thoth/profiles.json" }, { id: "global", label: "global \u2014 shared by every project" } ], (scope) => { const draft = workspace.createDraft( source, name, scope ); selectKey(draft.key); notify2( `Draft ${draft.name} ${scopeTag(draft)} created from ${source.name}; press s to save.`, "warning" ); } ) ); const liveModel = () => { const model = input.session?.model?.(); return model ? { provider: model.provider, id: model.id } : void 0; }; const targetFor = (entry, id) => { if (id === ORCHESTRATOR_ROW_ID) return { name: "orchestrator", get values() { return entry.orchestrator ?? {}; }, fallbackModel: liveModel(), resetModel: "reset to session model", resetEffort: "reset to session effort", apply: (edit) => workspace.editOrchestrator(entry, edit) }; const row = rowOf(id); return row && { name: row.name, get values() { return workspace.valuesFor(entry, row); }, resetModel: "reset to default model", resetEffort: "reset to default effort", apply: (edit) => workspace.edit(entry, row.key, edit) }; }; const applyEdit = (target, edit) => attempt(() => target.apply(edit)); const effortPicker = (entry, target) => { const { values } = target; const choices = buildEffortChoices( values.model ?? target.fallbackModel, values.effort, input.availableModels ?? [], input.modelContext ); editor.openPicker( { title: "Choose effort", hints: () => ["choose effort", "enter: select", "esc/q: back"].join(separator()), header: () => [ `profile: ${entry.name}${separator()}agent: ${target.name}` ], rows: () => choices.map((choice) => ({ id: choice.value, label: choice.value === "inherit" ? target.resetEffort : choice.label })), onAction: (key3, choice) => { if (key3 !== "enter") return false; const effort = choices.find( (item) => item.value === choice?.id )?.value; if (effort === "inherit") applyEdit(target, { reset: "effort" }); else if (effort) applyEdit(target, { effort }); editor.showOverview(); return true; } }, Math.max( 0, choices.findIndex((choice) => choice.value === values.effort) ) ); }; const modelPicker = (entry, target, provider, thenEffort) => { const models = availableByProvider[provider] ?? []; const modelsById = new Map( models.map((model) => [`${model.provider}/${model.id}`, model]) ); const searchText = (id) => { const model = modelsById.get(id); return [model?.name, model?.label, id].filter((part) => !!part).join(" "); }; editor.openPicker({ title: "Choose model", maxVisibleRows: 10, hints: () => [ moveHint(), "type search", "backspace delete", "ctrl+u clear", "enter select", "esc back" ].join(separator()), filter: { placeholder: "(type to filter)", text: (choice) => searchText(choice.id) }, rows: () => models.map((model) => ({ id: `${model.provider}/${model.id}`, label: modelRowLabel(model) })), header: ({ filter }) => { const query = filter.trim().toLowerCase(); const count = [...modelsById.keys()].filter( (id) => searchText(id).toLowerCase().includes(query) ).length; return [ `Select ${provider} model for ${target.name} in ${entry.name}`, `provider: ${provider}${separator()}${filter ? `${count}/${models.length} match${count === 1 ? "" : "es"}` : `${models.length} model${models.length === 1 ? "" : "s"}`}` ]; }, onAction: (key3, choice) => { if (key3 !== "enter") return false; const model = choice && modelsById.get(choice.id); if (model) applyEdit(target, { model: { provider: model.provider, id: model.id } }); editor.showOverview(); if (model && thenEffort) effortPicker(entry, target); return true; } }); }; const providerPicker = (entry, target, thenEffort) => editor.openPicker({ title: "Choose model provider", maxVisibleRows: 10, hints: () => ["choose provider", "enter: select", "esc/q: back"].join(separator()), header: () => [ `Select model provider for ${target.name} in ${entry.name}`, ...!providerNames.length ? ["No available models found; reset remains available."] : [] ], rows: () => [ { id: "reset", label: target.resetModel }, ...providerNames.map((provider) => ({ id: `provider:${provider}`, label: provider })) ], onAction: (key3, choice) => { if (key3 !== "enter") return false; if (choice?.id === "reset") { applyEdit(target, { reset: "model" }); editor.showOverview(); if (thenEffort) effortPicker(entry, target); } else if (choice) modelPicker( entry, target, choice.id.slice("provider:".length), thenEffort ); return true; } }); const editAgent = (agent, mode) => { const entry = current(); const target = targetFor(entry, agent); if (!target) return; if (!entry.scope) return offerDraftFromDefault(entry, `edit ${target.name}`); if (mode === "effort") effortPicker(entry, target); else providerPicker(entry, target, mode === "both"); }; const offerDraftFromDefault = (entry, purpose) => choose( "default is read-only", [ "Edits need a profile of their own.", `Create a new profile from default to ${purpose}?` ], [ { id: "yes", label: "Create a new profile from default" }, { id: "no", label: "Cancel" } ], (id) => { if (id === "yes") startDraft(entry, "New"); } ); const captureSession = () => { const entry = current(); if (!entry.scope) return offerDraftFromDefault(entry, "capture the session model"); const model = liveModel(); if (!model) throw new Error("No current session model to capture."); const effort = input.session?.effort?.(); workspace.setOrchestrator(entry, { model, ...effort ? { effort } : {} }); notify2( `Orchestrator of ${entry.name} set to ${modelKey(model)}${effort ? ` ${effort}` : ""}; press s to save.`, "warning" ); }; const save = () => { const entry = current(); if (!entry.scope) throw new Error("default is read-only; nothing to save."); if (!isDraft(entry) && !isEntryDirty(entry)) { notify2(`No unsaved changes in ${entry.name}.`, "warning"); return; } const file = workspace.save(entry); selectKey(entry.key); notify2(`Saved ${entry.name} ${scopeTag(entry)} to ${file}.`); }; const rename = () => { const entry = current(); if (!entry.scope) throw new Error("default cannot be renamed."); askName(`Rename ${entry.name}`, entry.name, (name) => { const key3 = `${entry.scope}:${name}`; workspace.rename(entry, name); selectKey(key3); notify2(`Renamed ${entry.name} to ${name}.`); }); }; const remove = () => { const entry = current(); if (!entry.scope) throw new Error("default cannot be deleted."); const pointers = isDraft(entry) ? [] : workspace.pointerTargets(entry); choose( `Delete ${entry.name}?`, [ isDraft(entry) ? `${entry.name} is an unsaved draft and will be discarded.` : `${entry.name} ${scopeTag(entry)} will be removed from its file.`, ...pointers.length ? [ `This clears: ${pointers.map((pointer) => POINTER_LABEL[pointer]).join(", ")}.` ] : [] ], [ { id: "yes", label: `Delete ${entry.name}` }, { id: "no", label: "Keep it" } ], (id) => { if (id !== "yes") return; const cleared = workspace.delete(entry); profileIndex = Math.max(0, profileIndex - 1); notify2( `Deleted ${entry.name}.${cleared.length ? ` Cleared ${cleared.map((pointer) => POINTER_LABEL[pointer]).join(", ")}.` : ""}`, cleared.length ? "warning" : "success" ); } ); }; const use = (pointer) => { const entry = current(); const message = activationMessage( pointer, entry, workspace.activate(entry, pointer) ); notify2(message); input.session?.applyOrchestrator?.().then( (outcome) => { const warn = outcome.status === "unavailable" || outcome.status === "clamped"; notify2(`${message} ${outcome.message}`, warn ? "warning" : "success"); input.tui?.requestRender?.(); }, (error) => { notify2( `${message} ${error instanceof Error ? error.message : String(error)}`, "error" ); input.tui?.requestRender?.(); } ); }; const tableColumns = (context) => { const effort = 10; const name = Math.max(12, Math.min(22, Math.floor(context.width * 0.28))); return { name, effort, model: Math.max(8, context.width - name - effort - 4) }; }; const tableLabel = (name, model, effort, context) => { if (context.layout === "compact") return `${name}${separator()}${model}${separator()}${effort}`; const columns = tableColumns(context); return `${padPanelText(name, columns.name)} ${padPanelText(model, columns.model)} ${padPanelText(effort, columns.effort)}`; }; const agentLabel = (row, context) => { const values = workspace.valuesFor(current(), row); return tableLabel( row.name, modelText(values.model), values.effort ?? "unresolved", context ); }; const orchestratorLabel = (context) => { const text = orchestratorValueText(current().orchestrator, modelText); return tableLabel("orchestrator", text.model, text.effort, context); }; const orchestratorDirty = () => { const entry = current(); const a = entry.orchestrator; const b = entry.baseOrchestrator; return !!entry.base && (a?.model?.provider !== b?.model?.provider || a?.model?.id !== b?.model?.id || a?.effort !== b?.effort); }; const driftRows = () => { const text = orchestratorDrift(workspace.effectiveOrchestrator(), { model: liveModel(), effort: input.session?.effort?.() }); return text ? [{ text, tone: "warning" }] : []; }; const rowDirty = (row) => { const entry = current(); if (!entry.base) return false; const a = entry.agents[row.key]; const b = entry.base[row.key]; return a?.model?.provider !== b?.model?.provider || a?.model?.id !== b?.model?.id || a?.effort !== b?.effort; }; const sidebarRows = () => entries().map((entry) => ({ text: profileEntryLabel(entry, workspace.markers(entry)) })); const stackedProfileRows = () => { const all = sidebarRows(); const size = Math.min(3, all.length); const start = Math.max( 0, Math.min(profileIndex - Math.floor(size / 2), all.length - size) ); return all.slice(start, start + size).map((row, offset) => { const selected = start + offset === profileIndex; return { text: `${selected ? resolveIcon("selection", "\u203A") : " "} ${row.text}`, selected }; }); }; const editor = createListEditor({ wideBreakpoint: 60, maxHeight: input.maxHeight, theme: input.theme, pendingCount: () => workspace.pendingCount(), requestRender: () => input.tui?.requestRender?.(), overview: { title: "Subagent model profiles", maxVisibleRows: 12, homeEndAliases: false, hints: () => [ `${resolveIcon("arrowLeft", "\u2190")}/${resolveIcon("arrowRight", "\u2192")} profile`, `${resolveIcon("arrowUp", "\u2191")}/${resolveIcon("arrowDown", "\u2193")} agent`, "enter edit", "m model", "e effort", "esc/q close" ].join(separator()), header: (context) => { const entry = current(); const total = entries().length; return [ panelHintRow( ["n new", "c clone", "s save", "r rename", "d delete"].join( separator() ) ), panelHintRow( ["u session", "g global", "p pin", "o capture session model"].join( separator() ) ), { text: `profile ${profileIndex + 1}/${total}${separator()}${describeEntry(entry, workspace.markers(entry), input.theme)}` }, ...driftRows(), ...stacked ? stackedProfileRows() : [], panelHintRow( context.layout === "wide" ? ` ${padPanelText("agent", tableColumns(context).name)} ${padPanelText("model", tableColumns(context).model)} ${padPanelText("effort", tableColumns(context).effort)}` : `agent ${separator().trim()} model ${separator().trim()} effort` ) ]; }, rows: () => [ { id: ORCHESTRATOR_ROW_ID, dirty: orchestratorDirty(), label: orchestratorLabel }, ...workspace.rows.map((row) => ({ id: row.key, dirty: rowDirty(row), label: (context) => agentLabel(row, context) })) ], footer: ({ index }) => { const row = workspace.rows[index - 1]; const values = row && workspace.valuesFor(current(), row); const detail = index === 0 ? `selected: ${themeAccent(input.theme, "orchestrator")}${separator()}applied on activation and new sessions; unset keeps the session model` : row && values ? `selected: ${themeAccent(input.theme, row.name)}${separator()}model: ${modelText(values.model)}${separator()}effort: ${values.effort ?? "unresolved"}` : "selected: (none)"; return [ ...status ? [{ text: status.text, tone: status.tone }] : [], detail ]; }, onAction: (key3, choice) => { key3 = key3.toLowerCase(); if (key3 === "left") profileIndex = Math.max(0, profileIndex - 1); else if (key3 === "right") profileIndex = Math.min(entries().length - 1, profileIndex + 1); else if (key3 === "enter") editAgent(choice?.id, "both"); else if (key3 === "m") editAgent(choice?.id, "model"); else if (key3 === "e") editAgent(choice?.id, "effort"); else if (key3 === "o") attempt(captureSession); else if (key3 === "n") startDraft(entries()[0], "New"); else if (key3 === "c") attempt(() => startDraft(current(), "Clone")); else if (key3 === "s") attempt(save); else if (key3 === "r") attempt(rename); else if (key3 === "d") attempt(remove); else if (key3 === "u") attempt(() => use("session")); else if (key3 === "g") attempt(() => use("global")); else if (key3 === "p") attempt(() => use("project")); else return false; return true; } }, // Profile saves belong to onAction; the shell must never complete on save. onSave: () => ({ success: false, error: "Use s to save the selected profile without closing." }), onCancel: () => input.done({ action: "close", discarded: workspace.pendingCount() }) }); const renderPrompt = (active, width) => { const rows = [ panelHintRow("type a name \xB7 ctrl+u clear \xB7 enter confirm \xB7 esc cancel"), ...active.input.render(Math.max(0, width - 4)), ...active.error ? [{ text: active.error, tone: "error" }] : [] ]; return renderPanelFrame({ title: active.title, rows, width, maxHeight: input.maxHeight?.(), theme: input.theme }); }; const promptInput = (active, data) => { const key3 = normalizePanelKey(data); if (key3 === "escape") prompt = void 0; else if (key3 === "enter") active.error = active.submit(active.input.getValue()); else if (key3 === "ctrl+u") active.input.setValue(""); else active.input.handleInput(data); input.tui?.requestRender?.(); }; return { render: (width) => { if (prompt) return renderPrompt(prompt, width); const side = editor.getState().view === "overview" ? sidebarWidthFor(width) : 0; stacked = side === 0; if (!side) return editor.render(width); const main = editor.render(width - side); return joinColumns( renderProfileSidebar({ rows: sidebarRows(), selected: profileIndex, width: side, height: main.length, theme: input.theme }), main, side, width - side ); }, handleInput: (data) => { if (prompt) return promptInput(prompt, data); const key3 = data === "enter" ? "\r" : data === "esc" || data === "escape" ? "\x1B" : data; status = void 0; editor.handleInput(key3); }, invalidate: () => editor.invalidate() }; } function sessionAccessors(ctx) { return { model: () => ctx.getSessionModel?.(), effort: () => ctx.getSessionThinkingLevel?.(), applyOrchestrator: typeof ctx.applyEffectiveProfileOrchestrator === "function" ? () => ctx.applyEffectiveProfileOrchestrator() : void 0 }; } async function getAvailableModels(ctx) { try { const available = await ctx?.modelRegistry?.getAvailable?.(); return Array.isArray(available) ? available : []; } catch { return []; } } function entryChoice(workspace, entry) { const markers = workspace.markers(entry); const detail = workspace.rows.map((row) => { const values = workspace.valuesFor(entry, row); return `${row.name}=${values.model ? `${values.model.provider}/${values.model.id}` : "?"}`; }).join(", "); return `${profileEntryLabel(entry, markers, true)}${detail ? ` \u2014 ${detail}` : ""}`; } async function selectActivation(ctx, workspace) { const entries = workspace.entries(); const labels = entries.map((entry2) => entryChoice(workspace, entry2)); const picked = await ctx.ui.select("Select model profile:", [ ...labels, "Cancel" ]); const entry = entries[labels.indexOf(picked)]; if (!entry) return "Cancelled. No model profile changes."; const actions = [ ...workspace.canUseSession ? [["Use for this session", "session"]] : [], ["Set as global active", "global"], ["Pin to this project", "project"] ]; const action = await ctx.ui.select(`Use ${entry.name}:`, [ ...actions.map(([label]) => label), "Cancel" ]); const pointer = actions.find(([label]) => label === action)?.[1]; if (!pointer) return "Cancelled. No model profile changes."; const message = activationMessage( pointer, entry, workspace.activate(entry, pointer, false) ); const outcome = await ctx.applyEffectiveProfileOrchestrator?.(); return outcome ? `${message} ${outcome.message}` : message; } async function runSubagentModelsCommand(ctx = {}) { const agentDir2 = ctx?.agentDir; const hasCustomUi = typeof ctx?.ui?.custom === "function"; const hasSelectUi = typeof ctx?.ui?.select === "function"; const cwd = ctx.cwd ?? process.cwd(); let workspace; try { workspace = new ModelProfileWorkspace( new ModelProfileStore({ cwd, agentDir: agentDir2 }), buildAgentRows({ ...ctx, cwd }), { get: ctx.getSessionModelProfile, set: ctx.setSessionModelProfile } ); } catch (error) { const message = error instanceof Error ? error.message : String(error); ctx.ui?.notify?.(message, "error"); return message; } if (!hasCustomUi && !hasSelectUi) return buildNonTuiModelProfilesMessage(workspace, agentDir2); if (hasCustomUi) { const ui = ctx.ui; const availableModels = await getAvailableModels(ctx); const result = await openPanelOverlay( ctx, (tui, theme, _keybindings, done, host) => createSubagentModelProfilesModal({ workspace, session: sessionAccessors(ctx), availableModels, modelContext: ctx, tui, theme, maxHeight: host.maxHeight, done }) ); if (result === void 0) return "Closed model profiles."; const discarded = result.discarded ?? 0; const message = discarded ? `Closed model profiles; discarded ${discarded} unsaved draft${discarded === 1 ? "" : "s"}/edit${discarded === 1 ? "" : "s"}.` : "Closed model profiles."; ui.notify?.(message, discarded ? "warning" : "info"); return message; } try { const message = await selectActivation(ctx, workspace); ctx.ui.notify?.(message, "info"); return message; } catch (error) { const message = error instanceof Error ? error.message : String(error); ctx.ui.notify?.(message, "error"); return message; } } // src/continuation-availability.ts function continuationAvailable(cwd, pi) { if (!readSubagentsConfig(cwd).enable_continue) return false; if (typeof pi?.getAllTools !== "function") return true; return pi.getAllTools().some( (tool) => (typeof tool === "string" ? tool : tool?.name) === "subagent_continue" ); } // src/render/icon-aware-component.ts function iconAwareRenderer(build) { return (...args) => { if (args.length > 3) args[3] = detachRenderContext(args[3]); let kit = getRenderKit(); let component = build(...args); const current = () => { const next = getRenderKit(); if (next !== kit) { kit = next; component = build(...args); } return component; }; return { render(width) { return current().render(width); }, invalidate() { current().invalidate(); }, handleMouse(event) { return current().handleMouse?.(event); } }; }; } // src/render/timeout-context.ts import fs11 from "node:fs"; var TIMEOUT_PREVIEW_LIMIT = 2e3; var TIMEOUT_PROGRESS_LIMIT = 1e3; function timeoutWorkingContext(task) { const progress = (task.progress_updates ?? []).slice(-5); return [ "Latest progress/checkpoint updates:", ...progress.length ? progress.map( (update) => `- ${update.created_at}: ${update.message.slice(-TIMEOUT_PROGRESS_LIMIT)}` ) : ["- No progress/checkpoint updates received."], "Output preview tail (partial, not a final result):", task.output_preview?.slice(-TIMEOUT_PREVIEW_LIMIT) || "(none)" ].join("\n"); } function totalTimeoutResult(task, continueAvailable) { if (task.error_metadata?.category !== "total_timeout") return void 0; return [ task.error ?? task.error_metadata.message, timeoutPartialContext(task, continueAvailable) ].join("\n\n"); } function timeoutPartialContext(task, continueAvailable) { const nestedAvailable = Boolean( task.nested_session_path && fs11.existsSync(task.nested_session_path) ); return [ "## Partial context (total timeout)", timeoutWorkingContext(task), `Extensions used: ${task.timeout_extensions_used ?? 0}`, `Nested session: ${nestedAvailable ? "available" : "unavailable"}`, `subagent_continue: ${continueAvailable ? "enabled" : "disabled"}` ].join("\n"); } // src/render/tool-selection-warning.ts function toolSelectionWarning(task, compact = false) { if (!task.dropped_tools?.length) return void 0; const names = task.dropped_tools.join(", "); return compact ? `\u26A0 Dropped tools: ${names}` : `Warning: Dropped tools unavailable in the child session (missing implementation: ${names}).`; } // src/render/tools/expansion-hint.ts function resolveExpandHint(action = "to expand", context) { const key3 = context?.keyText?.("app.tools.expand") ?? ""; return key3 ? `${key3} ${action}` : ""; } // src/render/tools/formatting.ts var SUBAGENT_RESUME_GUIDANCE = [ "## optional resume", "This task can be resumed with `subagent_continue` by sending a continuation prompt with the same `task_id`.", "Ask the user before resuming. The user may keep the currently configured model and effort or explicitly choose a different model, effort, or both for the next attempt.", "Do not resume or override the model or effort without the user's explicit decision. Never switch models automatically." ].join("\n"); function appendSubagentResumeGuidance(text, tasks, continueAvailable) { return continueAvailable && tasks.some( (task) => task.status === "failed" || task.status === "cancelled" || task.status === "interrupted" || task.status === "stopping" ) ? `${text} ${SUBAGENT_RESUME_GUIDANCE}` : text; } function clip(text, limit = 240, ui = false) { if (!text) return ""; const normalized = text.replace(/\s+/g, " ").trim(); return truncateToWidth2( normalized, limit, ui ? resolveIcon("ellipsis", "\u2026") : "\u2026" ); } function formatTokens(count) { if (count < 1e3) return count.toString(); if (count < 1e4) return `${(count / 1e3).toFixed(1)}k`; if (count < 1e6) return `${Math.round(count / 1e3)}k`; return `${(count / 1e6).toFixed(1)}M`; } function formatDuration2(milliseconds) { if (!Number.isFinite(milliseconds) || milliseconds <= 0) return "0s"; if (milliseconds < 1e3) return `${Math.floor(milliseconds)}ms`; if (milliseconds < 6e4) return `${(milliseconds / 1e3).toFixed(1).replace(/\.0$/, "")}s`; const minutes = Math.floor(milliseconds / 6e4); if (milliseconds < 36e5) { const seconds = Math.floor(milliseconds / 1e3) % 60; return `${minutes}m ${String(seconds).padStart(2, "0")}s`; } const hours = Math.floor(milliseconds / 36e5); return `${hours}h ${String(minutes % 60).padStart(2, "0")}m`; } function generationSpeed(metrics) { const output = metrics?.generationOutputTokens; const milliseconds = metrics?.generationMs; if (typeof output !== "number" || !Number.isFinite(output) || output <= 0 || typeof milliseconds !== "number" || !Number.isFinite(milliseconds) || milliseconds <= 0) return void 0; const speed = output * 1e3 / milliseconds; return Number.isFinite(speed) ? speed : void 0; } function formatUsage(task, ui = false) { const usage = task.usage; if (!usage) return ""; const parts = []; if (usage.turns) parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`); if (usage.input) parts.push( `${ui ? resolveIcon("tokensIn", "\u2191") : "\u2191"}${formatTokens(usage.input)}` ); if (usage.output) parts.push( `${ui ? resolveIcon("tokensOut", "\u2193") : "\u2193"}${formatTokens(usage.output)}` ); if (usage.cacheRead) parts.push(`R${formatTokens(usage.cacheRead)}`); if (usage.cacheWrite) parts.push(`W${formatTokens(usage.cacheWrite)}`); if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`); if (usage.contextTokens) parts.push(`ctx:${formatTokens(usage.contextTokens)}`); return parts.join(" "); } function modelEffortLine(task, ui = false) { return [ `model: ${task.model ?? "default/current"}`, `effort: ${task.effort ?? "default/current"}` ].join(` ${ui ? resolveIcon("separator", "\xB7") : "\xB7"} `); } function formatTaskLabel(task, ui = false) { if (!task) return "subagent"; const displayName = task.display_name?.trim(); if (displayName) return displayName; const taskSnippet = clip(task.task, 40, ui); return taskSnippet ? `${task.agent} ${ui ? resolveIcon("separator", "\xB7") : "\xB7"} ${taskSnippet}` : task.agent || "subagent"; } function formatTaskSummary(task) { if (!task) return ""; const displayName = task.display_name?.trim(); if (displayName) return displayName; const snippet = clip(task.task, 120, true); return snippet ? `${task.agent}: ${snippet}` : task.agent ?? ""; } function hasAgentResponse(task, result) { if (typeof result?.details?.full_result === "string" && result.details.full_result.trim().length > 0) { return true; } if (typeof task?.result === "string" && task.result.trim().length > 0) { return true; } return false; } function taskResponseText(task, result) { if (typeof result?.details?.full_result === "string" && result.details.full_result.trim().length > 0) { return result.details.full_result; } if (typeof task?.result === "string" && task.result.trim().length > 0) { return task.result; } return ""; } function formatOrchestratorUpdates(task, ui = false) { return [ ...(task.pending_questions ?? []).map( (question) => `pending question ${ui ? resolveIcon("separator", "\xB7") : "\xB7"} request_id: ${question.request_id} ${ui ? resolveIcon("separator", "\xB7") : "\xB7"} ${clip(question.message, 240, ui)}` ), ...(task.progress_updates ?? []).slice(-5).map((update) => `progress: ${clip(update.message, 240, ui)}`) ]; } function formatTask(task) { const when = task.last_activity_at ?? task.started_at ?? task.created_at; const usage = formatUsage(task); const taskLabel = formatTaskLabel(task); const lines = [ `task: ${taskLabel} \xB7 task_id: ${task.id} \xB7 status: ${task.status} \xB7 attempt: ${task.attempt ?? 1}`, task.effective_mode ? `effective mode: ${task.effective_mode}` : void 0, modelEffortLine(task), toolSelectionWarning(task), usage ? `usage: ${usage}` : void 0, task.status === "queued" || task.status === "running" || task.status === "stopping" ? `pending messages: ${task.pending_message_count ?? 0}` : `undelivered messages: ${task.undelivered_message_count ?? 0}`, `last: ${task.last_activity ?? "n/a"}${when ? ` at ${when}` : ""}`, ...formatOrchestratorUpdates(task) ].filter(Boolean); const response = taskResponseText(task); if (response) { lines.push(`preview: ${clip(response)}`); } else if (task.error) { lines.push(`error: ${clip(task.error)}`); } return lines.join("\n"); } function formatTaskListItem(task, context) { const when = task.last_activity_at ?? task.started_at ?? task.created_at; const usage = formatUsage(task, true); const taskLabel = formatTaskLabel(task, true); const hasResp = hasAgentResponse(task); const hasPreview = Boolean(task.output_preview || hasResp); const hint = resolveExpandHint("to expand", context); const lines = [ `subagent: ${task.agent} ${resolveIcon("separator", "\xB7")} task: ${taskLabel} ${resolveIcon("separator", "\xB7")} status: ${task.status} ${resolveIcon("separator", "\xB7")} attempt: ${task.attempt ?? 1}`, modelEffortLine(task, true), ...formatOrchestratorUpdates(task, true), usage ? `usage: ${usage}` : void 0, `last: ${task.last_activity ?? "n/a"}${when ? ` at ${when}` : ""}`, hasPreview ? `preview: collapsed${hint ? ` ${resolveIcon("separator", "\xB7")} ${hint}` : ""}` : void 0, task.error ? `error: ${clip(task.error, 240, true)}` : void 0 ].filter(Boolean); return lines.join("\n"); } function formatTaskListSummary(tasks, context) { if (!tasks.length) return "Listed 0 subagent task(s)."; const mostRecent = tasks[0]; const hint = resolveExpandHint("to expand", context); return [ `Listed ${tasks.length} subagent task(s).`, `Most recent: ${formatTaskLabel(mostRecent)} \xB7 task_id: ${mostRecent.id} \xB7 model: ${mostRecent.model ?? "default/current"} \xB7 effort: ${mostRecent.effort ?? "default/current"} \xB7 status: ${mostRecent.status}`, ...hint ? [`List view: collapsed \xB7 ${hint}`] : [], ...tasks.flatMap((task) => { const updates = formatOrchestratorUpdates(task); return updates.length ? [`task_id: ${task.id}`, ...updates] : []; }) ].join("\n"); } function formatTaskListRender(tasks, expanded, context) { if (!tasks.length) return "Listed 0 subagent task(s)."; if (expanded) return `Listed ${tasks.length} subagent task(s): ${tasks.map((task) => formatTaskListItem(task, context)).join("\n\n")}`; const mostRecent = tasks[0]; const recentLabel = formatTaskLabel(mostRecent, true); return [ `most recent: ${recentLabel} ${resolveIcon("separator", "\xB7")} status: ${mostRecent.status}`, resolveExpandHint("to expand", context) ].join("\n"); } function formatTaskModeContent(tasks, continueAvailable) { const content = [ `Completed ${tasks.length} subagent task(s):`, ...tasks.map((task) => { const responseText = taskResponseText(task); return [ formatTask(task), responseText ? ` # response from ${formatTaskLabel(task)} ${responseText}` : void 0 ].filter(Boolean).join("\n"); }) ].join("\n\n"); return appendSubagentResumeGuidance(content, tasks, continueAvailable); } function backgroundLaunchContent(tasksOrIds, verb = "Sent") { const lines = tasksOrIds.map((item) => { if (typeof item === "object" && item !== null) { return `- ${formatTaskLabel(item)} \xB7 task_id: ${item.id}`; } const raw = String(item); const match = raw.match(/^subtask_([^_]+)_/); const label = match ? match[1] : raw; return `- ${label} \xB7 task_id: ${raw}`; }); return [ `${verb} ${tasksOrIds.length} subagent task(s) to background:`, ...lines, "", "Background behavior:", "- Do not call subagent_status or subagent_result just to wait.", "- The subagent will notify this chat automatically when it finishes.", "- Keep the chat available so the user can continue asking questions while it runs." ].join("\n"); } // src/render/tools/progress.ts var RUNNING_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"]; function statusGlyph(status, frame = 0, ui = true) { if (status === "running") { if (!isAnimationEffectEnabled("secondary")) return resolveStaticRunningGlyph(); const frames = ui ? resolveFrames("spinnerFrames", RUNNING_FRAMES) : RUNNING_FRAMES; const index = Number.isFinite(frame) ? Math.floor(frame) : 0; return frames[(index % frames.length + frames.length) % frames.length]; } switch (status) { case "completed": return ui ? resolveStatusGlyph("completed", "\u2713") : "\u2713"; case "failed": return ui ? resolveStatusGlyph("failed", "\u2717") : "\u2717"; case "cancelled": case "interrupted": case "stopping": return ui ? resolveStatusGlyph(status, "\u25A0") : "\u25A0"; case "queued": return ui ? resolveStatusGlyph("queued", "\u25CB") : "\u25CB"; default: return ui ? resolveStatusGlyph("unknown", "?") : "?"; } } function progressText(tasks, frame = 0, options = {}) { const spinner = statusGlyph("running", frame, options.ui === true); const active = tasks.find((task) => task.status === "running") ?? tasks[0]; if (!active) return `${spinner} Starting subagent${options.ui ? resolveIcon("ellipsis", "\u2026") : "\u2026"}`; const usage = [formatUsage(active, options.ui), options.runtime].filter(Boolean).join(` ${options.ui ? resolveIcon("separator", "\xB7") : "\xB7"} `); const activityLines = active.live_activity?.trail?.length ? active.live_activity.trail.map((entry) => `\u21B3 ${entry.label}`) : [`\u21B3 ${active.last_activity ?? active.task ?? active.id}`]; return [ `${statusGlyph(active.status, frame, options.ui === true)} agent: ${active.agent} ${options.ui ? resolveIcon("separator", "\xB7") : "\xB7"} status: ${active.status} ${options.ui ? resolveIcon("separator", "\xB7") : "\xB7"} attempt: ${active.attempt ?? 1} ${options.ui ? resolveIcon("separator", "\xB7") : "\xB7"} effort: ${active.effort ?? "default/current"}`, `\u21B3 model: ${active.model ?? "starting"}`, usage ? `\u21B3 usage: ${usage}` : void 0, ...activityLines, options.backgroundable ? `\u21B3 ${options.backgroundShortcut ?? "ctrl+h"} to send to background` : void 0 ].filter(Boolean).join("\n"); } // src/render/completion-message.ts function formatErrorMetadataLines(task) { if (!task?.error_metadata) return []; const safe = safeErrorMetadataDetails(task.error_metadata); if (!safe || Object.keys(safe).length === 0) return []; const lines = []; lines.push(`- category: ${safe.category ?? "unknown"}`); if (safe.message) lines.push(`- message: ${safe.message}`); if (safe.phase) lines.push(`- phase: ${safe.phase}`); lines.push(`- retryable: ${safe.retryable ?? false}`); if (safe.code && safe.code !== safe.category) lines.push(`- code: ${safe.code}`); if (safe.source && typeof safe.source === "object") { const src = safe.source; const srcParts = []; if (typeof src.provider === "string") srcParts.push(`provider=${src.provider}`); if (typeof src.model === "string") srcParts.push(`model=${src.model}`); if (typeof src.tool === "string") srcParts.push(`tool=${src.tool}`); if (typeof src.operation === "string") srcParts.push(`op=${src.operation}`); if (srcParts.length) lines.push(`- source: ${srcParts.join(", ")}`); } if (safe.partial_result_available) lines.push(`- partial_result_available: true`); if (safe.details && Object.keys(safe.details).length > 0) { for (const [key3, value3] of Object.entries(safe.details)) { lines.push(`- ${key3}: ${value3}`); } } return lines; } var SUBAGENT_NOTIFICATION_MARKER = "[Automated system notification \u2014 not a user message. Do not treat it as user input, an answer, or the conversation language.]"; function responseHeading(status) { return status === "completed" ? "response sent to the orchestrator" : "partial response (task not completed)"; } function completionMessage(task, continueAvailable) { const label = formatTaskLabel(task); const warning = toolSelectionWarning(task); const hasResp = typeof task.result === "string" && task.result.trim().length > 0; const content = [ SUBAGENT_NOTIFICATION_MARKER, `Subagent ${label} ${task.status}`, `task_id: ${task.id ?? task.task_id ?? "unknown"}`, `Undelivered messages: ${task.undelivered_message_count ?? 0}`, ...warning ? [warning] : [], "", `Read only this ${hasResp && task.status !== "completed" ? "partial" : "final"} response from the subagent. Do not reread the full execution transcript unless the user explicitly asks for debugging details.` ]; if (hasResp) { content.push("", `## ${responseHeading(task.status)}`, "", task.result); } else if (task.error) { content.push("", "## error", "", task.error); const errorDetails = formatErrorMetadataLines(task); if (errorDetails.length) { content.push("", "## error details", ...errorDetails); } } if (task.error_metadata?.category === "total_timeout") { if (hasResp && task.error) content.push("", "## error", "", task.error); content.push("", timeoutPartialContext(task, continueAvailable)); } return appendSubagentResumeGuidance( content.join("\n"), [task], continueAvailable ); } function safeCompletionErrorMetadata(task) { if (!task?.error_metadata) return void 0; return safeErrorMetadataDetails(task.error_metadata); } function sendSubagentCompletionMessage(pi, task, cwd = task?.cwd) { const continueAvailable = continuationAvailable(cwd ?? process.cwd(), pi); pi.sendMessage?.( { customType: "subagent-completion", content: completionMessage({ ...task, cwd }, continueAvailable), display: true, details: { full_result: totalTimeoutResult(task, continueAvailable) ?? task.result ?? task.error ?? task.output_preview, task: { id: task.id, agent: task.agent, status: task.status, mode: task.mode, effective_mode: task.effective_mode, model: task.model, effort: task.effort, usage: task.usage, result: task.result, error: task.error, undelivered_message_count: task.undelivered_message_count ?? 0, dropped_tools: task.dropped_tools, error_metadata: safeCompletionErrorMetadata(task) } } }, { triggerTurn: true, deliverAs: "followUp" } ); } var renderSubagentCompletionMessage = iconAwareRenderer( function renderSubagentCompletionMessage2(message, options, theme) { const details = message.details ?? {}; const task = details.task ?? details; const status = task.status ?? "completed"; const failed = status === "failed" || status === "cancelled"; const expanded = Boolean(options?.expanded); const expandHint = resolveExpandHint("to expand", options); const rawResponse = details.full_result ?? task.result; const hasResp = typeof rawResponse === "string" && rawResponse.trim().length > 0; const responseText = hasResp ? rawResponse : ""; const archPrefix = themeStatus(theme, status, statusGlyph(status)); const taskLabel = formatTaskLabel(task, true); const titleLabel = themeFg( theme, failed ? "error" : "customMessageLabel", `[subagent] ${taskLabel} ${resolveIcon("separator", "\xB7")} ${status}` ); const title = `${archPrefix} ${titleLabel}`.trim(); const sections = []; if (!expanded) { sections.push( { text: `subagent: ${task.agent ?? "subagent"} ${resolveIcon("separator", "\xB7")} model: ${task.model ?? "default/current"} ${resolveIcon("separator", "\xB7")} effort: ${task.effort ?? "default/current"} ${resolveIcon("separator", "\xB7")} status: ${status}`, style: "dim" }, ...expandHint ? [{ text: expandHint, style: "dim" }] : [] ); } else { sections.push({ text: `subagent: ${task.agent ?? "subagent"} ${resolveIcon("separator", "\xB7")} model: ${task.model ?? "default/current"} ${resolveIcon("separator", "\xB7")} effort: ${task.effort ?? "default/current"} ${resolveIcon("separator", "\xB7")} status: ${status}`, style: "dim" }); if (task.attempt) { sections.push({ text: `attempt: ${task.attempt}`, style: "dim" }); } if (hasResp && responseText) { sections.push( { text: BOX_CHARS.horizontal.repeat(24), style: "dim" }, { text: responseHeading(task.status), style: "heading" }, ...String(responseText).split("\n").map((line) => ({ text: line, style: "body" })) ); } else if (failed && task.error) { sections.push( { text: BOX_CHARS.horizontal.repeat(24), style: "dim" }, { text: "error", style: "heading" }, ...String(task.error).split("\n").map((line) => ({ text: line, style: "body" })) ); const errorDetails = formatErrorMetadataLines(task); if (errorDetails.length) { sections.push( { text: "", style: "dim" }, { text: "error details", style: "heading" }, ...errorDetails.map((line) => ({ text: line, style: "body" })) ); } } } const color = (section, text) => { if (section.style === "label") return themeFg(theme, failed ? "error" : "customMessageLabel", text); if (section.style === "status") return themeFg(theme, failed ? "error" : "success", text); if (section.style === "dim") return themeDim(theme, text); if (section.style === "heading") return themeTitle(theme, text); if (section.style === "body") return themeFg(theme, "customMessageText", text); return text; }; const memo = createKitRenderMemo(); const nativeFallback = []; const renderLines = (width, kit) => { const safeWidth = Math.max(1, Math.floor(width || 1)); if (kit) { const divider = sections.findIndex( (section) => section.text === BOX_CHARS.horizontal.repeat(24) ); const styledRows = (items, contentWidth2) => items.flatMap( (section) => wrapLineToWidth(section.text, contentWidth2).map( (line) => color(section, line) ) ); return kit.card( theme, { title, isSuccess: task.status === "completed", isError: failed, body: (contentWidth2) => styledRows( divider < 0 ? sections : sections.slice(0, divider), contentWidth2 ), sections: divider < 0 ? void 0 : [ { title: sections[divider + 1]?.text, rows: (contentWidth2) => styledRows(sections.slice(divider + 2), contentWidth2) } ], wrap: true }, safeWidth ); } if (safeWidth < 10) { return [ title, ...sections.flatMap((s) => wrapLineToWidth(s.text, safeWidth)) ].map( (l) => truncateToWidth2(l, safeWidth, `${resolveIcon("ellipsis", "\u2026")}`) ); } const innerWidth = safeWidth - 2; const contentWidth = Math.max(1, innerWidth - 2); const borderFn = (t) => themeFg(theme, "accent", t); const maxTitleWidth = Math.max(0, innerWidth - 4); const clippedTitle = truncateToWidth2( title, maxTitleWidth, `${resolveIcon("ellipsis", "\u2026")}` ); const titleVisWidth = visibleWidth2(clippedTitle); const filler = Math.max(0, innerWidth - titleVisWidth - 3); const top = `${borderFn(BOX_CHARS.topLeft)}${borderFn(BOX_CHARS.horizontal)} ${clippedTitle} ${borderFn(BOX_CHARS.horizontal.repeat(filler))}${borderFn(BOX_CHARS.topRight)}`; const middle = sections.flatMap( (section) => wrapLineToWidth(section.text, contentWidth).map((line) => { const styled = color(section, line); const lineVisWidth = visibleWidth2(line); const rightPadding = " ".repeat( Math.max(0, contentWidth - lineVisWidth) ); return `${borderFn(BOX_CHARS.vertical)} ${styled}${rightPadding} ${borderFn(BOX_CHARS.vertical)}`; }) ); const bottom = `${borderFn(BOX_CHARS.bottomLeft)}${borderFn(BOX_CHARS.horizontal.repeat(innerWidth))}${borderFn(BOX_CHARS.bottomRight)}`; return [top, ...middle, bottom]; }; return { invalidate() { memo.invalidate(); }, render(width) { const lines = memo.render( width, (kit) => kit ? renderLines(width, kit) : nativeFallback ); return lines === nativeFallback ? renderLines(width) : lines; } }; } ); // src/render/attention-message.ts function attentionMessage(task) { const used = task.timeout_extensions_used ?? 0; return [ SUBAGENT_NOTIFICATION_MARKER, `Subagent timeout attention \u2014 task_id: ${task.id}`, `Remaining time: ${Math.max(0, (task.timeout_deadline_at ?? Date.now()) - Date.now())}ms`, `Extensions used: ${used}; remaining: ${Math.max(0, (task.timeout_max_extensions ?? 3) - used)}`, timeoutWorkingContext(task), "subagent_extend grants more time within the configured bounds; silence lets the execution ceiling apply.", "Checkpoint steering is best-effort; only the updates above are confirmed received." ].join("\n"); } function sendSubagentAttentionMessage(pi, task) { const content = attentionMessage(task); pi.sendMessage?.( { customType: "subagent-attention", content, display: true, details: { task: { id: task.id, agent: task.agent, status: task.status }, full_result: content } }, { triggerTurn: true, deliverAs: "followUp" } ); } function renderSubagentAttentionMessage(message, options, theme) { return renderSubagentCompletionMessage( { ...message, details: { ...message.details, task: { ...message.details?.task, status: "attention" } } }, options, theme ); } // src/render/tools/components.ts import { Box, stripTerminalSequences } from "@earendil-works/pi-tui"; // src/tools/result-details.ts function taskFromDetails(result) { return result?.details?.tasks?.[0] ?? result?.details?.results?.[0] ?? result?.details?.task; } function sessionIdFromToolContext(ctx) { const direct = ctx?.sessionManager?.getSessionId?.() ?? ctx?.sessionId; if (typeof direct === "string" && direct.length > 0) return direct; const file = ctx?.sessionManager?.getSessionFile?.(); return typeof file === "string" && file.length > 0 ? file : void 0; } function compactErrorMetadataForDetails(task) { if (!task.error_metadata) return void 0; return safeErrorMetadataDetails(task.error_metadata); } function orchestratorDetails(task, continueAvailable) { const pending = task.pending_questions ?? []; return { pending_question_count: pending.length, pending_questions: pending.map(({ request_id, message, created_at }) => ({ request_id, message, created_at })), ...task.error_metadata?.category === "total_timeout" ? { partial_context: timeoutPartialContext(task, continueAvailable) } : {}, progress_updates: (task.progress_updates ?? []).slice(-5).map(({ message, created_at }) => ({ message, created_at })) }; } function compactTaskForToolResult(task, continueAvailable, options = {}) { const error_metadata = compactErrorMetadataForDetails(task); const taskPreview = task.task?.length > TIMEOUT_PREVIEW_LIMIT ? task.task.replace(/\s+/g, " ").trim() : task.task; return { id: task.id, display_name: task.display_name, agent: task.agent, mode: task.mode, effective_mode: task.effective_mode, status: task.status, task: taskPreview?.slice(0, TIMEOUT_PREVIEW_LIMIT), context: task.context?.slice(0, TIMEOUT_PREVIEW_LIMIT), prompt: task.prompt?.slice(0, TIMEOUT_PREVIEW_LIMIT), continuation_prompt: task.continuation_prompt?.slice( 0, TIMEOUT_PREVIEW_LIMIT ), created_at: task.created_at, attempt: task.attempt, session_id: task.session_id, nested_session_path: task.nested_session_path, dropped_tools: task.dropped_tools, notify_orchestrator_available: task.notify_orchestrator_available, started_at: task.started_at, ended_at: task.ended_at, last_activity_at: task.last_activity_at, last_activity: task.last_activity, output_preview: task.output_preview, pending_message_count: task.pending_message_count, undelivered_message_count: task.undelivered_message_count, timeout_started_at: task.timeout_started_at, timeout_deadline_at: task.timeout_deadline_at, timeout_extensions_used: task.timeout_extensions_used, timeout_deadline_generation: task.timeout_deadline_generation, timeout_max_extensions: task.timeout_max_extensions, timeout_continue_enabled: task.timeout_continue_enabled, live_activity: task.live_activity, usage: task.usage, runtime_metrics: task.runtime_metrics, model: task.model, effort: task.effort, model_source: task.model_source, effort_source: task.effort_source, fallback_used: task.fallback_used, interaction_request: task.interaction_request, stop_reason: task.stop_reason, pi_retry_attempts: task.pi_retry_attempts, ...orchestratorDetails(task, continueAvailable), ...options.includeResult !== false ? { result: task.result } : {}, ...options.includeError !== false ? { error: task.error } : {}, ...error_metadata ? { error_metadata } : {} }; } function compactTaskWithoutFinalText(task, continueAvailable) { return compactTaskForToolResult(task, continueAvailable, { includeResult: false, includeError: false }); } function compactResultDetails(details, continueAvailable) { return { ...details, task: details.task ? compactTaskForToolResult(details.task, continueAvailable) : details.task, tasks: Array.isArray(details.tasks) ? details.tasks.map( (task) => compactTaskForToolResult(task, continueAvailable) ) : details.tasks, results: Array.isArray(details.results) ? details.results.map( (task) => compactTaskForToolResult(task, continueAvailable) ) : details.results }; } // src/render/tools/components.ts function emptyComponent() { return { invalidate() { }, render(_width) { return []; } }; } function firstLineOf(text) { return text?.split(/\r?\n/).map((line) => line.trim()).find(Boolean); } function boxedComponent(linesOrText, options) { const memo = createKitRenderMemo(); const nativeFallback = []; const renderLines = (width, kit) => { const theme = options?.theme; const rawLines = Array.isArray(linesOrText) ? linesOrText.flatMap((line) => line.split("\n")) : linesOrText.split("\n"); const safeWidth = Math.max(1, Math.floor(width || 1)); const status = options?.status ?? (options?.context?.isPartial ? "running" : options?.context?.isError ? "failed" : "completed"); const indicator = status === "running" && !isAnimationEffectEnabled("secondary") ? { glyph: resolveStaticRunningGlyph() } : kit?.indicator(theme, options?.context, { status, frame: options?.animationFrame }); const workingGlyph = (text) => indicator && status === "running" ? text.replace( /^((?:\u001b\[[0-9;]*m)*)[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]/u, (_match, style) => `${style}${indicator.glyph}` ) : text; const title = workingGlyph(options?.title ?? ""); const rows = (contentWidth) => rawLines.flatMap((line, index) => { const text = index === options?.workingRow ? workingGlyph(line) : line; return options?.wrapped ? wrapLineToWidth(text, contentWidth) : [truncateToWidth2(text, contentWidth, resolveIcon("ellipsis", "\u2026"))]; }); if (kit) { const toolSurface = !options?.message && typeof options?.expanded === "boolean"; const failedLine = status === "failed" ? firstLineOf(stripTerminalSequences(options?.error ?? "")) : void 0; const row = toolSurface ? { title: options?.compact?.title ?? options?.label ?? stripTerminalSequences(title), body: failedLine ? [failedLine] : options?.compact?.body ?? rawLines, summary: options?.compact?.summary?.join( ` ${resolveIcon("separator", "\xB7")} ` ), tail: options?.compact?.tail } : void 0; const footer = options?.message ? void 0 : renderToolFooter(kit, theme, { status, context: options?.context }); return kit.card( theme, { ...toolSurface ? { surface: "tool", expanded: options?.expanded, row } : {}, title, body: rows, status: options?.message ? void 0 : status, context: options?.message ? void 0 : options?.context ?? {}, footer, isError: options?.context?.isError, isSuccess: options?.isSuccess === true || void 0, wrap: options?.wrapped }, safeWidth ); } if (options?.message) return frameBox( title, safeWidth < 10 ? rawLines : rows(safeWidth - 4), safeWidth, { borderFn: (text) => themeFg(theme, "accent", text) } ); const role = options?.context?.isPartial ? "toolPendingBg" : options?.context?.isError ? "toolErrorBg" : "toolSuccessBg"; const box = new Box(1, 1, (text) => themeBg(theme, role, text)); box.addChild({ invalidate() { }, render(contentWidth) { return [ ...title ? [ truncateToWidth2( title, contentWidth, resolveIcon("ellipsis", "\u2026") ) ] : [], ...rows(contentWidth) ]; } }); return box.render(safeWidth); }; return { invalidate() { memo.invalidate(); }, handleMouse(event) { if (options?.onClick && (event?.type === "click" || !event?.type && (event?.button === "left" || event?.button === void 0))) { options.onClick(); return { handled: true }; } return void 0; }, render(width) { const lines = memo.render( width, (kit) => kit ? renderLines(width, kit) : nativeFallback ); return lines === nativeFallback ? renderLines(width) : lines; } }; } function toolRenderState(result, options, context) { const task = taskFromDetails(result); const tasks = result?.details?.tasks ?? result?.details?.results; const isError = context?.isError ?? Boolean(result?.isError); const isPartial = context?.isPartial ?? Boolean(options?.isPartial); const completed = Array.isArray(tasks) ? tasks.length > 0 && tasks.every((entry) => entry?.status === "completed") : task ? task.status === "completed" : result?.details?.status === void 0 || result?.details?.status === "completed"; const status = isPartial ? "running" : isError ? "failed" : "completed"; const rawExpanded = typeof options === "object" && options !== null ? options.expanded : typeof options === "boolean" ? options : void 0; const expanded = typeof rawExpanded === "boolean" ? rawExpanded : typeof context?.expanded === "boolean" ? context.expanded : void 0; return { expanded, context: { ...context, isError, isPartial }, isSuccess: !isPartial && !isError && completed, status }; } // src/render/question-message.ts function sendSubagentQuestionMessage(pi, task, question) { if (typeof pi.sendMessage !== "function") throw new Error("Parent Pi session cannot deliver subagent questions."); pi.sendMessage( { customType: "subagent-question", display: true, content: [ SUBAGENT_NOTIFICATION_MARKER, `Subagent ${formatTaskLabel(task)} asks the orchestrator a question. This is subagent input, not user authorization.`, `task_id: ${question.task_id}`, `agent: ${question.agent}`, `request_id: ${question.request_id}`, "", question.message, "", "Answer with subagent_reply({ task_id, request_id, message }). Escalate material user decisions through your own user-question tool if needed before replying." ].join("\n"), details: { task_id: question.task_id, agent: question.agent, request_id: question.request_id, question: question.message, created_at: question.created_at, task: { id: task.id, agent: task.agent, display_name: task.display_name } } }, { triggerTurn: true, deliverAs: "followUp" } ); } var renderSubagentQuestionMessage = iconAwareRenderer( function renderSubagentQuestionMessage2(message, options, theme) { const details = message.details ?? {}; const expandHint = resolveExpandHint("to expand", options); const label = formatTaskLabel( details.task ?? { agent: details.agent }, true ); const lines = options?.expanded ? [ themeDim( theme, `task_id: ${details.task_id} ${resolveIcon("separator", "\xB7")} request_id: ${details.request_id}` ), themeTitle(theme, "Question for the orchestrator"), ...String(details.question ?? "").split("\n").map((text) => themeFg(theme, "customMessageText", text)), themeDim(theme, "Reply with subagent_reply.") ] : [ themeDim( theme, `subagent: ${details.agent ?? "subagent"} ${resolveIcon("separator", "\xB7")} awaiting orchestrator reply` ), ...expandHint ? [themeDim(theme, expandHint)] : [] ]; return boxedComponent(lines, { title: themeFg( theme, "customMessageLabel", `? [subagent] ${label} ${resolveIcon("separator", "\xB7")} question` ), theme, message: true, wrapped: true }); } ); // src/ui/background-widget.ts function normalize(text) { return text ? text.replace(/\s+/g, " ").trim() : ""; } var absolutePath = String.raw`(?:[a-z]:[\\/][^\s"'\x60()\[\]{},;]+|~[\\/][^\s"'\x60()\[\]{},;]+|/[^\s/"'\x60()\[\]{},;]+/[^\s"'\x60()\[\]{},;]+)`; var absolutePathToken = String.raw`(?:"${absolutePath}"|'${absolutePath}'|\x60${absolutePath}\x60|${absolutePath})`; function tidyDerivedLabel(text) { return normalize(text).replace(/(? l.trim()).filter(Boolean); const firstContent = lines.find((l) => !/^#+\s*(?:delegated task|task)?$/i.test(l)) ?? lines[0] ?? ""; const clean = firstContent.replace(/^#+\s*(?:delegated task:?|task:?)?\s*/i, "").trim(); let content = (clean || firstContent).replace( new RegExp( String.raw`\brepo\s+root\b(?:\s+${absolutePathToken})?(?:\s*\(git worktree[^)]*(?:\)|$))?[.;,]?`, "gi" ), "" ).replace( new RegExp(String.raw`(?<=^|[\s("'\x60])${absolutePathToken}`, "gi"), " " ); content = tidyDerivedLabel(content); let change = ""; let envelope = /^(PHASE|CHANGE):\s*([^/]*?)\s*(?:\/\s*|$)/i.exec(content); while (envelope) { if (envelope[1].toUpperCase() === "CHANGE") change = tidyDerivedLabel(envelope[2]); content = content.slice(envelope[0].length); envelope = /^(PHASE|CHANGE):\s*([^/]*?)\s*(?:\/\s*|$)/i.exec(content); } content = tidyDerivedLabel(content); const summary2 = tidyDerivedLabel( change ? `${change}${content ? ` \xB7 ${content}` : ""}` : content ); if (!summary2) return ""; return truncateToWidth2(summary2, maxLen, `${resolveIcon("ellipsis", "\u2026")}`); } // src/task-state-events.ts var ACTIVITY_PUBLICATION_INTERVAL_MS = 150; var COALESCIBLE_SUMMARY_KEYS = /* @__PURE__ */ new Set([ "lastActivityAt", "usage", "preview" ]); function completeCounts(counts = {}) { return { queued: counts.queued ?? 0, running: counts.running ?? 0, stopping: counts.stopping ?? 0, completed: counts.completed ?? 0, failed: counts.failed ?? 0, cancelled: counts.cancelled ?? 0, interrupted: counts.interrupted ?? 0 }; } function timestamp(value3) { return value3 === void 0 ? void 0 : Date.parse(value3); } function summarizeTask2(task) { return { id: task.id, agent: task.agent, displayName: task.display_name?.trim() ? task.display_name : formatTaskSummary2(task) || task.agent, mode: task.mode, status: task.status, model: task.model, effort: task.effort, createdAt: Date.parse(task.created_at), startedAt: timestamp(task.started_at), endedAt: timestamp(task.ended_at), lastActivityAt: timestamp(task.last_activity_at), usage: task.usage === void 0 ? void 0 : { input: task.usage.input, output: task.usage.output, cost: task.usage.cost }, preview: task.output_preview?.slice(0, SUBAGENT_PREVIEW_MAX_LENGTH) }; } function hasImmediateSummaryChange(current, previous) { if (!previous) return true; const keys = Object.keys({ ...previous, ...current }); return keys.some( (key3) => !COALESCIBLE_SUMMARY_KEYS.has(key3) && !Object.is(current[key3], previous[key3]) ); } var SubagentsStatePublisher = class { constructor(events, source) { this.events = events; this.source = source; this.offTaskUpdate = source.onTaskUpdate(() => this.onTaskUpdate()); this.offRequest = onRequest(events, SUBAGENTS_STATE_REQUEST, { // Unready requests are answered together by the next readiness broadcast; // never read another session's tasks to answer them early. onRequest: ({ sessionId }) => { if (this.session?.sessionId === sessionId) this.publish(); } }); } events; source; session; offRequest; offTaskUpdate; publishedTasks = /* @__PURE__ */ new Map(); lastPublishedAt = 0; publicationTimer; startSession(cwd, sessionId) { this.session = sessionId ? { cwd, sessionId } : void 0; this.publish(); } dispose() { this.offRequest(); this.offTaskUpdate(); this.clearPublicationTimer(); this.session = void 0; } onTaskUpdate() { if (!this.session) return; const { cwd, sessionId } = this.session; const tasks = this.source.listActiveSessionTasks(cwd, sessionId).map(summarizeTask2); const immediateChange = tasks.length !== this.publishedTasks.size || tasks.some( (task) => hasImmediateSummaryChange(task, this.publishedTasks.get(task.id)) ); if (immediateChange) { this.publish(tasks); return; } if (this.publicationTimer !== void 0) return; const delay = this.lastPublishedAt + ACTIVITY_PUBLICATION_INTERVAL_MS - Date.now(); if (delay <= 0) { this.publish(tasks); return; } this.publicationTimer = setTimeout(() => this.publish(), delay); this.publicationTimer.unref?.(); } clearPublicationTimer() { if (this.publicationTimer === void 0) return; clearTimeout(this.publicationTimer); this.publicationTimer = void 0; } publish(activeTasks) { this.clearPublicationTimer(); if (!this.session) return; const { cwd, sessionId } = this.session; const tasks = activeTasks ?? this.source.listActiveSessionTasks(cwd, sessionId).map(summarizeTask2); const liveIds = new Set(tasks.map(({ id }) => id)); const history = this.source.listSessionHistoryByCost(cwd, sessionId).filter((task) => !liveIds.has(task.id)).map(summarizeTask2); const counts = completeCounts(); for (const task of tasks) counts[task.status]++; const persistedCounts = completeCounts( this.source.snapshotSessionTaskCounts(cwd, sessionId).counts ); const totals = { ...persistedCounts, total: Object.values(persistedCounts).reduce( (sum, count) => sum + count, 0 ) }; this.publishedTasks = new Map(tasks.map((task) => [task.id, task])); this.lastPublishedAt = Date.now(); publish(this.events, SUBAGENTS_STATE_CHANNEL, { sessionId, source: "@thoth-agents/pi-subagents", data: { tasks, history, counts, totals } }); } }; // src/tools/background-handoff-state.ts var QUESTION_HANDOFF_GUIDANCE = "A question is pending. Answer with `subagent_reply` using the task_id and request_id from the question notification."; function withBackgroundHandoffBarrier(execute) { return (...args) => { let markToolReturned; const toolReturned = new Promise((resolve3) => { markToolReturned = resolve3; }); const result = execute(toolReturned, ...args); void result.then(markToolReturned, markToolReturned); return result; }; } var activeClaudeBackgroundHandoffs = /* @__PURE__ */ new Set(); var pendingQuestionHandoffs = /* @__PURE__ */ new Set(); var backgroundHandoffSequence = 0; function parentSessionIdFromContext(ctx) { const direct = ctx?.sessionManager?.getSessionId?.() ?? ctx?.sessionId; if (typeof direct === "string" && direct.length > 0) return direct; const file = ctx?.sessionManager?.getSessionFile?.(); return typeof file === "string" && file.length > 0 ? file : void 0; } function belongsToQuestionSession(entry, question) { return entry.manager === question.manager && (question.parentSessionId ? entry.parentSessionId === question.parentSessionId : entry.getTaskIds().includes(question.taskId)); } function joinQuestionHandoff(entry, question) { question.entries.add(entry); if (entry.handoff(question.reason).length) question.backgrounded = true; } function sendTasksToBackground(ctx, manager, getTaskIds, onBackground, reason) { const backgrounded = manager.sendToBackground(getTaskIds(), reason); if (!backgrounded.length) return []; ctx?.ui?.notify?.( backgrounded.length === 1 ? `Sent subagent to background: ${backgrounded[0].id}` : `Sent ${backgrounded.length} subagent task(s) to background.`, "info" ); onBackground(backgrounded); return backgrounded; } function triggerClaudeBackgroundHandoff() { const candidates = [...activeClaudeBackgroundHandoffs].filter((entry) => entry.hasActiveTask()).sort((a, b) => b.createdAt - a.createdAt); for (const entry of candidates) { if (entry.handoff().length) return true; } return false; } async function triggerTaskBackgroundHandoff(manager, taskId2, reason) { const question = { manager, parentSessionId: manager.getTask(taskId2, manager.getTaskCwd(taskId2))?.session_id, taskId: taskId2, entries: /* @__PURE__ */ new Set(), backgrounded: false, reason }; pendingQuestionHandoffs.add(question); try { for (const entry of activeClaudeBackgroundHandoffs) { if (belongsToQuestionSession(entry, question)) joinQuestionHandoff(entry, question); } let pendingCount; do { pendingCount = question.entries.size; await Promise.allSettled( [...question.entries].map((entry) => entry.toolReturned) ); } while (question.entries.size !== pendingCount); return question.backgrounded; } finally { pendingQuestionHandoffs.delete(question); } } function ctrlShortcutToTerminalInput(shortcut) { const match = shortcut.trim().toLowerCase().match(/^ctrl\+([a-z])$/); if (!match) return void 0; const code = match[1].charCodeAt(0) - 96; return code >= 1 && code <= 26 ? String.fromCharCode(code) : void 0; } function installBackgroundHandoffShortcut(ctx, manager, getTaskIds, onBackground, toolReturned, onUnpublishedAttentionHandoff) { const shortcut = readSubagentsConfig(ctx?.cwd ?? process.cwd()).background_handoff_shortcut ?? "ctrl+h"; const terminalInput = ctrlShortcutToTerminalInput(shortcut); const parentSessionId = parentSessionIdFromContext(ctx); let backgroundRequested = false; const handoff = (reason) => { backgroundRequested = true; const tasks = sendTasksToBackground( ctx, manager, getTaskIds, onBackground, reason ); if (reason === "attention" && !getTaskIds().length) { onUnpublishedAttentionHandoff?.(); } return tasks; }; const unsubscribeTaskUpdate = manager.onTaskUpdate(() => { if (backgroundRequested) handoff(); }); const entry = { createdAt: ++backgroundHandoffSequence, manager, parentSessionId, getTaskIds, toolReturned, handoff, hasActiveTask: () => getTaskIds().some((id) => { const task = manager.getTask(id, ctx?.cwd ?? process.cwd()); return Boolean( task && task.mode !== "background" && (task.status === "queued" || task.status === "running") ); }) }; activeClaudeBackgroundHandoffs.add(entry); for (const question of pendingQuestionHandoffs) { if (belongsToQuestionSession(entry, question)) joinQuestionHandoff(entry, question); } const unsubscribeQuestion = manager.onQuestion(async (task) => { await triggerTaskBackgroundHandoff(manager, task.id); }); const unsubscribe = terminalInput ? ctx?.ui?.onTerminalInput?.((data) => { if (data !== terminalInput || isWorkPanelRootEditorInputActive(ctx) === false) return void 0; return handoff().length ? { consume: true } : void 0; }) : void 0; return () => { const cleanup = () => { activeClaudeBackgroundHandoffs.delete(entry); unsubscribeQuestion(); unsubscribeTaskUpdate(); }; void toolReturned.then(cleanup, cleanup); if (typeof unsubscribe === "function") unsubscribe(); }; } // src/tools/subagent-cancel.ts import { Type as Type2 } from "typebox"; // src/render/tools/subagent-cancel.ts function renderSubagentCancelCall(_args, _theme) { return emptyComponent(); } var renderSubagentCancelResult = iconAwareRenderer( function renderSubagentCancelResult2(result, options, theme, context) { const renderState = toolRenderState(result, options, context); const { expanded } = options ?? {}; const task = taskFromDetails(result); const failed = Boolean(renderState.context.isError); const archPrefix = themeFg(theme, "accent", agentIcon()); if (!task) { const title2 = `${archPrefix} ${themeTitle(theme, failed ? `subagent cancel ${resolveIcon("separator", "\xB7")} failed` : "subagent cancel")}`; const text = result?.content?.[0]?.text ?? ""; return boxedComponent( [failed ? themeError(theme, text) : themeDim(theme, text)], { title: title2, label: "subagent cancel", error: text, theme, ...renderState, wrapped: true } ); } const label = formatTaskLabel(task, true); const status = themeStatus(theme, task.status ?? "stopping"); const modeSuffix = task.mode === "background" || task.effective_mode === "background" ? " (background)" : ""; const title = `${archPrefix} ${themeTitle(theme, `subagent cancel ${resolveIcon("separator", "\xB7")} ${label} ${resolveIcon("separator", "\xB7")} ${task.status ?? "stopping"}${modeSuffix}`)}`; const lines = [ `subagent: ${themeAccent(theme, task.agent)} ${resolveIcon("separator", "\xB7")} model: ${task.model ?? "default/current"} ${resolveIcon("separator", "\xB7")} effort: ${themeAccent(theme, task.effort ?? "default/current")} ${resolveIcon("separator", "\xB7")} status: ${status}` ]; if (expanded) { const usage = formatUsage(task, true); lines.push( themeDim(theme, modelEffortLine(task, true)), usage ? themeDim(theme, `usage: ${usage}`) : "", themeDim(theme, "task_id is available to the agent in tool details") ); } else { lines.push(themeDim(theme, resolveExpandHint("to expand", context))); } return boxedComponent(lines.filter(Boolean), { title, label: "subagent cancel", error: task.error || result?.content?.[0]?.text, compact: { summary: [formatTaskSummary(task), task.model, task.effort].filter( Boolean ) }, theme, ...renderState, wrapped: true }); } ); // src/tools/tool-response.ts function ok(text, details = {}) { return { content: [{ type: "text", text }], details }; } function fail(error) { const msg = error instanceof Error ? error.message : String(error); return { content: [{ type: "text", text: msg }], details: { error: msg }, isError: true }; } // src/tools/subagent-cancel.ts function createSubagentCancelTool(manager, pi) { return { name: "subagent_cancel", label: "Subagent Cancel", description: "Cancel a running task.", parameters: Type2.Object({ task_id: Type2.String() }), renderShell: "self", async execute(_id, params, _signal, _onUpdate, ctx) { try { const available = continuationAvailable(ctx?.cwd ?? process.cwd(), pi); const task = manager.cancel(params.task_id); return ok( appendSubagentResumeGuidance(formatTask(task), [task], available), { task: compactTaskForToolResult(task, available) } ); } catch (e) { return fail(e); } }, renderCall: renderSubagentCancelCall, renderResult: renderSubagentCancelResult }; } // src/tools/subagent-continue.ts import { Type as Type4 } from "typebox"; // src/render-debug.ts import crypto from "node:crypto"; import fs12 from "node:fs"; import os5 from "node:os"; import path10 from "node:path"; var DEFAULT_RENDER_DEBUG_LOG_PATH2 = path10.join( os5.tmpdir(), "pi-subagents-render.jsonl" ); function sha256(value3) { return `sha256:${crypto.createHash("sha256").update(value3).digest("hex")}`; } function pickTerminal(env) { return { term: env.TERM, colorterm: env.COLORTERM, term_program: env.TERM_PROGRAM, inside_tmux: Boolean(env.TMUX), inside_herdr: Boolean(env.HERDR || env.HERDR_SESSION) }; } function sanitizeState(state) { if (!state) return void 0; return { task_count: typeof state.taskCount === "number" ? state.taskCount : void 0, selected_index: typeof state.selectedIndex === "number" ? state.selectedIndex : void 0, selected_status: state.selectedStatus, scroll_offset: typeof state.scrollOffset === "number" ? state.scrollOffset : void 0, follow_tail: typeof state.followTail === "boolean" ? state.followTail : void 0, has_usage: typeof state.hasUsage === "boolean" ? state.hasUsage : void 0, configured_max_lines: typeof state.configuredMaxLines === "number" ? state.configuredMaxLines : void 0, rendered_line_count: typeof state.renderedLineCount === "number" ? state.renderedLineCount : void 0, body_height: typeof state.bodyHeight === "number" ? state.bodyHeight : void 0, max_visible_width: typeof state.maxVisibleWidth === "number" ? state.maxVisibleWidth : void 0, width_violation_count: typeof state.widthViolationCount === "number" ? state.widthViolationCount : void 0 }; } function createSubagentsRenderLogger(input) { const config = input.config; const panelInstanceId = crypto.randomUUID(); if (!config?.enabled) { return { enabled: false, panelInstanceId, log: () => void 0 }; } const env = input.env ?? process.env; const terminal = pickTerminal(env); let sequence = 0; return { enabled: true, panelInstanceId, log: (event) => { try { const record = { schema_version: 1, event: event.event, timestamp: (/* @__PURE__ */ new Date()).toISOString(), sequence: ++sequence, panel_instance_id: panelInstanceId, session_id_hash: input.sessionId ? sha256(input.sessionId) : void 0, reason: event.reason, render_cycle: event.renderCycle, duration_ms: typeof event.durationMs === "number" ? Number(event.durationMs.toFixed(3)) : void 0, dimensions: event.dimensions ? { stdout_columns: event.dimensions.stdoutColumns, stdout_rows: event.dimensions.stdoutRows, render_width: event.dimensions.renderWidth } : void 0, state: sanitizeState(event.state), input: event.input ? { category: event.input.category, action: event.input.action } : void 0, terminal }; fs12.mkdirSync(path10.dirname(config.path), { recursive: true, mode: 448 }); fs12.appendFileSync(config.path, `${JSON.stringify(record)} `, "utf8"); } catch { } } }; } // ../pi-core/src/history-panel.ts import { truncateToWidth as truncateToWidth3 } from "@earendil-works/pi-tui"; // ../pi-core/src/history-panel-input.ts var RAW_KEYS = { enter: ["\r", "\n"], backspace: ["\x7F", "\b"], escape: ["\x1B"], "ctrl+c": [""], "ctrl+o": [""], "ctrl+t": [""], "ctrl+w": [""], q: ["q", "Q"], up: ["\x1B[A"], down: ["\x1B[B"], right: ["\x1B[C"], left: ["\x1B[D"], pageUp: ["\x1B[5~"], pageDown: ["\x1B[6~"], home: ["\x1B[H", "\x1B[1~", "\x1BOH"], end: ["\x1B[F", "\x1B[4~", "\x1BOF"] }; var KEYBINDINGS = { escape: ["app.interrupt", "tui.select.cancel"], "ctrl+c": ["tui.select.cancel"], up: ["tui.select.up", "tui.editor.cursorUp"], down: ["tui.select.down", "tui.editor.cursorDown"], right: ["tui.editor.cursorRight"], left: ["tui.editor.cursorLeft"], pageUp: ["tui.select.pageUp", "tui.editor.pageUp"], pageDown: ["tui.select.pageDown", "tui.editor.pageDown"], home: ["tui.editor.cursorLineStart"], end: ["tui.editor.cursorLineEnd"] }; function createHistoryPanelKeyMatcher(keybindings, extraBindings = {}) { return (data, key3) => (extraBindings[key3] ?? KEYBINDINGS[key3])?.some( (binding) => keybindings?.matches?.(data, binding) ) === true || (RAW_KEYS[key3]?.includes(data) ?? data === key3); } // ../pi-core/src/history-panel.ts init_panel_frame(); init_panel_primitives(); init_render_kit(); var plainTheme = { fg: (_role, text) => text }; var matchesRawKey = createHistoryPanelKeyMatcher(); var HistoryPanel = class { constructor(adapter, options) { this.adapter = adapter; this.options = options; this.initialSelectedId = options.initialSelectedId; this.resetContentScroll(); const interval = options.refreshMs ?? 1e3; if (options.requestRender && Number.isFinite(interval) && interval > 0) { this.refreshTimer = setInterval( () => options.requestRender?.(), interval ); this.refreshTimer.unref?.(); } } adapter; options; viewItemId; explicitView; activeView; tabHits = []; viewScroll = /* @__PURE__ */ new Map(); selected = 0; selectedKey; collapsed = /* @__PURE__ */ new Set(); filterQuery = ""; filterVisible = false; filtering = false; rowGroupMap = /* @__PURE__ */ new Map(); helpOpen = false; helpScroll = 0; scroll = 0; sidebarScroll = 0; followTail = true; lastMaxScroll = 0; seenLineCount; lastSelectedIndex = -1; initialSelectedId; lastContentItemId; rowItemMap = /* @__PURE__ */ new Map(); contentRowItemMap = /* @__PURE__ */ new Map(); disposed = false; lastIsSplit = true; lastSidebarWidth = 26; lastRenderWidth = 100; lastListStartRow = -1; lastListEndRow = -1; closeArm; pendingAction; actionNotice; refreshTimer; cachedRenderKit = getRenderKit(); cachedToolRegistryVersion = getToolDefinitionRegistryVersion(); lastRenderMetrics; invalidate() { this.adapter.invalidate?.(); this.rowItemMap.clear(); this.contentRowItemMap.clear(); this.rowGroupMap.clear(); this.closeArm = void 0; } listRows() { const all = this.adapter.items(); const items = this.filterVisible && this.adapter.matchesFilter ? all.filter( (item) => this.adapter.matchesFilter?.(item, this.filterQuery) ) : all; let rows; if (this.adapter.groupOf) { const groups = /* @__PURE__ */ new Map(); for (const item of items) { const group = this.adapter.groupOf(item); if (`item:${this.adapter.id(item)}` === this.selectedKey) this.collapsed.delete(group.id); const bucket = groups.get(group.id) ?? { group, members: [] }; bucket.members.push(item); groups.set(group.id, bucket); } rows = [...groups.values()].sort((a, b) => a.group.order - b.group.order).flatMap(({ group, members }) => [ { key: `group:${group.id}`, group, members }, ...this.collapsed.has(group.id) ? [] : members.map((item) => ({ key: `item:${this.adapter.id(item)}`, item })) ]); } else rows = items.map((item) => ({ key: `item:${this.adapter.id(item)}`, item })); if (this.initialSelectedId) { this.selectedKey = `item:${this.initialSelectedId}`; const index = rows.findIndex((row) => row.key === this.selectedKey); if (index >= 0) this.selected = index; this.initialSelectedId = void 0; } if (this.selectedKey === void 0) { this.selected = Math.max( 0, rows.findIndex((row) => row.item !== void 0) ); } else if (this.adapter.groupOf || this.adapter.matchesFilter) { const index = rows.findIndex((row) => row.key === this.selectedKey); if (index >= 0) this.selected = index; } this.selected = Math.max(0, Math.min(this.selected, rows.length - 1)); this.selectedKey = rows[this.selected]?.key; return rows; } moveSelection(delta) { const rows = this.listRows(); this.selected = Math.max( 0, Math.min(rows.length - 1, this.selected + delta) ); this.selectedKey = rows[this.selected]?.key; this.resetContentScroll(); } toggleGroup(id) { if (this.collapsed.has(id)) this.collapsed.delete(id); else this.collapsed.add(id); this.closeArm = void 0; this.resetContentScroll(); } fg(role, text) { return panelFg(this.options.theme ?? plainTheme, role, text); } measure(text) { try { const measured = this.options.visibleWidth?.(text); if (measured !== void 0 && Number.isFinite(measured) && measured >= 0) return measured; } catch { } return panelVisibleWidth(text); } clip(text, width) { if (width <= 0) return ""; const normalized = text.replace(/\r?\n|\r/g, " ").replace(/\t/g, " "); if (this.measure(normalized) <= width) return normalized; const clipped = !getRenderKit()?.icon && this.options.truncateToWidth ? this.options.truncateToWidth(normalized, width) : truncatePanelText(normalized, width); return this.measure(clipped) <= width ? clipped : truncateToWidth3(clipped, width, resolveIcon("ellipsis", "\u2026")); } pad(text, width) { if (!this.options.visibleWidth && !this.options.truncateToWidth) return padPanelText(text, width); const clipped = this.clip(text, width); return clipped + " ".repeat(Math.max(0, width - this.measure(clipped))); } context(width, split, count, index = this.selected) { return { width, index, count, selected: index === this.selected, layout: split ? "wide" : "narrow" }; } keepSelectionVisible(count, height) { if (this.selected !== this.lastSelectedIndex) { if (this.selected < this.sidebarScroll) this.sidebarScroll = this.selected; if (this.selected >= this.sidebarScroll + height) this.sidebarScroll = this.selected - height + 1; this.lastSelectedIndex = this.selected; } this.sidebarScroll = Math.max( 0, Math.min(Math.max(0, count - height), this.sidebarScroll) ); } currentView(item) { const id = this.adapter.id(item); if (id !== this.viewItemId) { this.viewItemId = id; this.explicitView = void 0; this.activeView = void 0; this.viewScroll.clear(); } const views = this.adapter.views?.(item) ?? []; const next = views.find( (view) => view.id === (this.explicitView ?? this.adapter.defaultView?.(item)) ) ?? views[0]; if (next?.id !== this.activeView?.id) { if (this.activeView) this.viewScroll.set(this.activeView.id, { scroll: this.scroll, followTail: this.followTail, seenLineCount: this.seenLineCount }); this.activeView = next; const saved = next && this.viewScroll.get(next.id); this.scroll = saved ? saved.scroll : 0; this.followTail = saved ? saved.followTail : next?.followTail === true; this.seenLineCount = saved ? saved.seenLineCount : void 0; } return next; } selectView(id) { const item = this.selectedItem(); if (!item) return; this.currentView(item); this.explicitView = id; this.currentView(item); } content(item, width, height) { const view = this.currentView(item); const rendered = view && this.adapter.renderView ? this.adapter.renderView(item, view.id, width) : this.adapter.renderContent(item, width); const rows = rendered.flatMap((line) => { const entry = typeof line === "string" ? { text: line } : line; return entry.text.split(/\r?\n|\r/).map((text) => ({ ...entry, text: this.clip(text, width) })); }); if (this.followTail || this.seenLineCount === void 0) this.seenLineCount = rows.length; this.seenLineCount = Math.min( this.seenLineCount ?? rows.length, rows.length ); this.lastMaxScroll = Math.max(0, rows.length - height); this.scroll = this.followTail ? this.lastMaxScroll : Math.min(this.scroll, this.lastMaxScroll); return { rows: rows.slice(this.scroll, this.scroll + height), total: rows.length }; } itemCell(items, index, width, split, row) { const entry = items[index]; if (!entry) return ""; if (entry.group) { this.rowGroupMap.set(row, entry.group.id); const count = String(entry.members.length); const labelWidth = Math.max(0, width - this.measure(count) - 1); const disclosure = resolveIcon( this.collapsed.has(entry.group.id) ? "arrowRight" : "arrowDown" ); const label2 = `${index === this.selected ? this.fg("warning", disclosure) : disclosure} ${entry.group.label}`; return `${this.fg("mdHeading", this.pad(label2, labelWidth))} ${this.fg("dim", count)}`; } const item = entry.item; this.rowItemMap.set(row, this.adapter.id(item)); const label = this.clip( this.adapter.renderItemLabel( item, this.context(width, split, items.length, index) ), width ); return this.fg(index === this.selected ? "warning" : "dim", label); } matches(data, key3) { return this.options.matchesKey?.(data, key3) === true || matchesRawKey(data, key3); } handleInput(data) { if (this.disposed) return; this.applyInput(data); if (!this.disposed) this.options.requestRender?.(); } applyInput(data) { if (this.pendingAction) { const pending = this.pendingAction; if (this.matches(data, "escape")) this.pendingAction = void 0; else if (this.matches(data, "enter")) { this.pendingAction = void 0; const item = this.selectedItem(); const action2 = item && this.adapter.id(item) === pending.id ? this.adapter.actions?.(item).find((action3) => action3.key === pending.key && action3.eligible) : void 0; if (item && action2) this.runAction(item, action2); } return; } if (this.filtering) { if (this.matches(data, "escape")) { this.filtering = false; this.filterVisible = false; this.filterQuery = ""; } else if (this.matches(data, "enter")) this.filtering = false; else if (this.matches(data, "backspace") || data === "\x7F" || data === "\b") this.filterQuery = [...this.filterQuery].slice(0, -1).join(""); else if (this.matches(data, "down")) this.moveSelection(1); else if (this.matches(data, "up")) this.moveSelection(-1); else if (data && [...data].every((char) => char >= " " && char !== "\x7F")) this.filterQuery += data; this.closeArm = void 0; return; } if (!this.helpOpen && data === "/" && this.adapter.matchesFilter) { this.filterVisible = true; this.filtering = true; this.closeArm = void 0; return; } if (!this.helpOpen && this.filterVisible && this.matches(data, "escape")) { this.filterVisible = false; this.filterQuery = ""; return; } if (data === "?" || this.helpOpen && this.matches(data, "escape")) { this.helpOpen = !this.helpOpen; this.helpScroll = 0; return; } if (this.helpOpen) { if (this.matches(data, "down") || this.matches(data, "pageDown")) this.helpScroll++; if (this.matches(data, "up") || this.matches(data, "pageUp")) this.helpScroll = Math.max(0, this.helpScroll - 1); return; } if (this.matches(data, "escape") || this.matches(data, "ctrl+c") || this.matches(data, "q")) { this.dismiss(); return; } const selectedRow = this.listRows()[this.selected]; if (selectedRow?.item !== void 0 && /^[1-5]$/.test(data)) { const view = this.adapter.views?.(selectedRow.item)?.[Number(data) - 1]; if (view) { this.selectView(view.id); return; } } if (selectedRow?.group && (this.matches(data, "enter") || data === " ")) { this.toggleGroup(selectedRow.group.id); return; } if (this.adapter.handleInput?.(data, this)) { this.closeArm = void 0; return; } const actionItem = this.selectedItem(); const action = actionItem && this.adapter.actions?.(actionItem).find((action2) => action2.eligible && this.matches(data, action2.key)); if (actionItem && action) { this.startAction(actionItem, action); return; } if (this.matches(data, this.options.closeKey ?? "x")) { this.closeSelectedItem(); return; } this.closeArm = void 0; const wheel = panelMouseWheelDelta(data); if (wheel !== void 0) { this.scrollBy(wheel); return; } const click = panelMouseClick(data); if (click) { this.applyMouse(click); return; } if (this.matches(data, "right") || this.matches(data, "left")) { const delta = this.matches(data, "right") ? 1 : -1; this.moveSelection(delta); return; } if (this.matches(data, "down")) this.scrollBy(1); else if (this.matches(data, "up")) this.scrollBy(-1); else if (this.matches(data, "pageDown")) this.scrollBy(12); else if (this.matches(data, "pageUp")) this.scrollBy(-12); else if (this.matches(data, "home") || this.adapter.views && data === "g") { this.scroll = 0; this.followTail = false; } else if (this.matches(data, "end") || this.adapter.views && data === "G") { this.scroll = Number.MAX_SAFE_INTEGER; this.followTail = true; } } scrollBy(delta) { this.scroll = Math.max(0, this.scroll + delta); this.followTail = delta < 0 ? false : this.scroll >= this.lastMaxScroll; } handleMouse(event) { if (this.disposed) return void 0; const result = this.applyMouse(event); if (!this.disposed && result && result.render !== false) this.options.requestRender?.(); return result; } applyMouse(event) { if (this.helpOpen || this.pendingAction) return { handled: true, render: false }; this.closeArm = void 0; const col = event.col ?? event.x ?? 0; const row = event.row ?? event.y ?? 0; if (event.type === "wheel") { const delta = Number(event.wheelDelta ?? 0); if (!Number.isFinite(delta) || delta === 0) return void 0; const sidebar = this.lastIsSplit ? col <= this.lastSidebarWidth + 2 && event.col !== void 0 : this.lastListStartRow >= 0 && row >= this.lastListStartRow && row <= this.lastListEndRow; if (sidebar) this.sidebarScroll = Math.max( 0, Math.min(this.listRows().length - 1, this.sidebarScroll + delta) ); else this.scrollBy(delta); return { handled: true, render: true }; } if (event.type !== "click" && (event.type || event.button !== "left" && event.button !== void 0)) return void 0; if (row === 0 && col >= Math.max(0, this.lastRenderWidth - 16)) { this.dismiss(); return { handled: true, render: true }; } const tab = this.tabHits.find( (hit) => hit.row === row && col >= hit.start && col < hit.end ); if (tab) { this.selectView(tab.id); return { handled: true, focus: true, render: true }; } const groupId = this.rowGroupMap.get(row); const inList = this.lastIsSplit ? (event.col !== void 0 || event.x !== void 0) && col <= this.lastSidebarWidth + 2 : row >= this.lastListStartRow && row <= this.lastListEndRow; if (groupId && inList) { const rows = this.listRows(); this.selected = rows.findIndex((entry) => entry.group?.id === groupId); this.selectedKey = rows[this.selected]?.key; this.toggleGroup(groupId); return { handled: true, focus: true, render: true }; } const id = (inList ? this.rowItemMap : this.contentRowItemMap).get(row); if (id) { const previous = this.selected; if (this.selectItem(id)) return { handled: true, focus: true, render: previous !== this.selected }; } return { handled: true, focus: true }; } startAction(item, action) { try { const prompt = action.confirm?.(item); if (prompt) this.pendingAction = { id: this.adapter.id(item), key: action.key, prompt }; else this.runAction(item, action); } catch (error) { this.actionFailed(action.label, error); } } showNotice(notice) { if (this.disposed || !notice || typeof notice !== "object" || !("text" in notice) || typeof notice.text !== "string") return; const role = "role" in notice ? notice.role : void 0; this.actionNotice = { text: notice.text, role: role === "success" || role === "warning" || role === "error" ? role : "warning", expiresAt: (this.options.now ?? Date.now)() + (this.options.noticeMs ?? 3e3) }; this.options.requestRender?.(); } actionFailed(label, error) { this.showNotice({ text: `\u2717 ${label[0].toUpperCase() + label.slice(1)} failed: ${error instanceof Error ? error.message : String(error)}`, role: "error" }); } runAction(item, action) { try { const outcome = action.run(item); if (outcome && typeof outcome === "object" && "then" in outcome) { void Promise.resolve(outcome).then( (notice) => { if (notice) this.showNotice(notice); if (!this.disposed) this.options.requestRender?.(); }, (error) => this.actionFailed(action.label, error) ); } else if (outcome) this.showNotice(outcome); } catch (error) { this.actionFailed(action.label, error); } } /** May also be called by an extension-owned shortcut. */ closeSelectedItem() { if (this.disposed || this.filtering) return; const item = this.selectedItem(); if (this.pendingAction) return; const action = item && this.adapter.actions?.(item).find( (action2) => action2.key === (this.options.closeKey ?? "x") && action2.eligible ); if (item && action) { this.startAction(item, action); this.options.requestRender?.(); return; } if (!item || !this.adapter.close || this.adapter.canClose?.(item) === false) { this.closeArm = void 0; return; } const id = this.adapter.id(item); if (this.options.confirmClose !== false && (this.closeArm?.id !== id || this.closeArm.expiresAt < Date.now())) { this.closeArm = { id, expiresAt: Date.now() + (this.options.closeConfirmationMs ?? 1500) }; return; } this.closeArm = void 0; this.adapter.close(item); } confirmationHint() { const item = this.selectedItem(); if (!this.closeArm || !item || this.closeArm.id !== this.adapter.id(item) || this.closeArm.expiresAt < Date.now() || this.adapter.canClose?.(item) === false) { this.closeArm = void 0; return void 0; } return this.options.closeConfirmationHint ?? `${this.options.closeKey ?? "x"} again to close`; } selectItem(id) { const item = this.adapter.items().find((item2) => this.adapter.id(item2) === id); if (item === void 0) return false; if (this.adapter.groupOf) this.collapsed.delete(this.adapter.groupOf(item).id); const key3 = `item:${id}`; const rows = this.listRows(); const index = rows.findIndex((row) => row.key === key3); if (index < 0) return false; this.selected = index; this.selectedKey = key3; this.closeArm = void 0; this.resetContentScroll(); return true; } resetContentScroll() { this.seenLineCount = void 0; this.scroll = 0; this.followTail = this.options.contentScroll !== "top"; } render(width) { const kit = getRenderKit(); const version = getToolDefinitionRegistryVersion(); if (kit !== this.cachedRenderKit || version !== this.cachedToolRegistryVersion) { this.cachedRenderKit = kit; this.cachedToolRegistryVersion = version; this.invalidate(); } const outputWidth = Number.isFinite(width) ? Math.max(0, Math.floor(width)) : 40; const w = Math.max(40, outputWidth); const configured = typeof this.options.maxLines === "function" ? this.options.maxLines() : this.options.maxLines ?? 42; const maxLines = Math.max( 12, Math.floor(Number.isFinite(configured) ? configured : 42) ); const split = w >= 90; const sidebarWidth = split ? Math.max(18, Math.min(30, Math.floor(w * 0.25))) : 0; this.lastIsSplit = split; this.lastSidebarWidth = sidebarWidth; this.lastRenderWidth = outputWidth; this.lastListStartRow = -1; this.lastListEndRow = -1; const rightWidth = split ? Math.max(16, w - sidebarWidth - 7) : Math.max(16, w - 4); const items = this.listRows(); this.rowItemMap.clear(); this.contentRowItemMap.clear(); this.rowGroupMap.clear(); this.tabHits = []; const b = (text) => this.fg("accent", text); const dim = (text) => this.fg("dim", text); const title = this.fg( "toolTitle", this.options.theme?.bold?.(this.options.title) ?? this.options.title ); const leftTitle = `${b(this.options.titleIcon?.() ?? resolveIcon("agent", "\u{F08C7}"))} ${title}`; const close = this.fg( "dim", `${resolveIcon("close")}${outputWidth < 30 ? "" : " Close"}` ); const frame = createPanelFrame({ theme: this.options.theme ?? plainTheme, borderTone: "accent", text: { clip: (text, width2) => this.clip(text, width2), pad: (text, width2) => this.pad(text, width2), measure: (text) => this.measure(text) } }); const closeWidth = this.measure(close); const rows = []; const top = () => { const topWidth = Math.max(6, outputWidth); const label = this.clip( leftTitle, Math.max(0, topWidth - closeWidth - 9) ); return frame.line( ["topLeft", "horizontal"], ` ${label} `, [ { horizontal: Math.max( 0, topWidth - this.measure(label) - closeWidth - 8 ) } ], ` ${close} `, ["horizontal", "topRight"] ); }; const cell = (text) => frame.cells([{ text, width: rightWidth }]); const selectedRow = items[this.selected]; const item = selectedRow?.item; const itemId = selectedRow?.key; const activeView = item === void 0 ? void 0 : this.currentView(item); if (item === void 0) this.activeView = void 0; const tabs = (row, start) => { let text = ""; for (const [index, view] of (item === void 0 ? [] : this.adapter.views?.(item) ?? []).slice(0, 5).entries()) { const active = view.id === activeView?.id; const label = active ? `[${index + 1} ${view.label}]` : w < 62 ? ` ${index + 1} ` : ` ${index + 1} ${view.label} `; const from = start + this.measure(text); const accent = this.fg( "accent", this.options.theme?.bold?.(label) ?? label ); const styled = active ? this.options.theme?.bg?.("selectedBg", accent) ?? accent : dim(label); text += styled; this.tabHits.push({ row, start: from, end: Math.min(start + rightWidth, from + this.measure(label)), id: view.id }); } return text; }; if (this.options.contentScroll === "top" && itemId !== this.lastContentItemId) this.resetContentScroll(); if (itemId !== this.lastContentItemId) this.seenLineCount = void 0; this.lastContentItemId = itemId; if (selectedRow === void 0 && !this.filterVisible) { rows.push( top(), frame.cells([ { text: dim( this.options.emptyText ?? "No items recorded in this session yet." ), width: w - 4 } ]) ); while (rows.length < maxLines - 1) rows.push(frame.cells([{ text: "", width: w - 4 }])); rows.push(this.footer(frame, outputWidth, 0, maxLines - 2)); return this.finishRender(rows, outputWidth, maxLines, maxLines - 2); } const header = (item === void 0 ? { variableRows: true } : this.adapter.renderHeader?.( item, this.context(rightWidth, split, items.length) )) ?? {}; const listLabel = this.options.listLabel ?? "items"; const summary2 = maxLines >= 16 ? this.adapter.renderListSummary?.(split ? sidebarWidth : rightWidth) : void 0; const filterRow = this.filterVisible ? this.filterRow(split ? sidebarWidth : rightWidth) : void 0; const contentForSelection = (height) => { if (item !== void 0) return this.content(item, rightWidth, height); const lines = selectedRow?.group ? [ selectedRow.group.label, `Total: ${selectedRow.members.length}`, ...this.adapter.renderGroupOverview?.(selectedRow.members) ?? [] ] : [this.fg("dim", "No matches")]; return { rows: lines.slice(0, height).map((text) => ({ text })), total: lines.length }; }; let bodyHeight; if (split) { const sidebarTitle = this.clip(leftTitle, Math.max(0, sidebarWidth - 3)); const fillLeft = Math.max( 0, sidebarWidth + 2 - this.measure(sidebarTitle) - 3 ); const leftTop = frame.line( ["topLeft", "horizontal"], ` ${sidebarTitle} `, [{ horizontal: fillLeft }], ["tDown"] ); const selectedItemIndex = item === void 0 ? -1 : this.adapter.items().findIndex( (entry) => this.adapter.id(entry) === this.adapter.id(item) ); const badge = `${b(item === void 0 ? selectedRow?.group?.label ?? "No matches" : `${selectedItemIndex + 1}/${this.adapter.items().length}`)}${header.badge ? ` ${header.badge}` : ""}`; const clippedBadge = this.clip( badge, Math.max(0, rightWidth - closeWidth - 5) ); const fill = Math.max( 0, rightWidth - 4 - this.measure(clippedBadge) - closeWidth ); rows.push( frame.line( leftTop, ["horizontal"], ` ${clippedBadge} `, [{ horizontal: fill }], ` ${close} `, ["horizontal", "topRight"] ) ); const splitCell = (left, right) => frame.cells([ { text: left, width: sidebarWidth }, { text: right, width: rightWidth } ]); const metadata = header.variableRows ? header.wideRows ?? [] : Array.from({ length: 2 }, (_, i) => header.wideRows?.[i] ?? ""); const headerRows = metadata.slice(0, Math.max(0, maxLines - 8)); const headerHeight = Math.max( headerRows.length, filterRow !== void 0 ? 3 : summary2 !== void 0 ? 2 : 1 ); for (let i = 0; i < headerHeight; i++) { rows.push( splitCell( i === 0 ? `${b(`${listLabel} 1-${items.length}/${items.length}`)} ` : i === 1 ? summary2 ?? "" : i === 2 ? filterRow ?? "" : "", headerRows[i] ?? "" ) ); } if (activeView) rows.push(splitCell("", tabs(rows.length, sidebarWidth + 5))); rows.push(frame.rule([sidebarWidth, rightWidth])); const height = Math.max(5, maxLines - rows.length - 1); bodyHeight = height; this.keepSelectionVisible(items.length, height); const content = contentForSelection(height); for (let i = 0; i < height; i++) { const row = rows.length; const left = this.itemCell( items, this.sidebarScroll + i, sidebarWidth, true, row ); const entry = content.rows[i]; if (entry?.itemId) this.contentRowItemMap.set(row, entry.itemId); rows.push(splitCell(left, entry?.text ?? "")); } rows.push(this.footer(frame, outputWidth, content.total, height)); } else { rows.push(top()); for (const metadata of (header.narrowRows ?? []).slice( 0, header.variableRows ? Math.max(0, maxLines - 8 - (filterRow !== void 0 ? 1 : 0)) : 2 )) rows.push(cell(metadata)); if (activeView) rows.push(cell(tabs(rows.length, 2))); rows.push(frame.rule([rightWidth])); const available = Math.max( 4, maxLines - rows.length - 2 - (summary2 !== void 0 ? 1 : 0) - (filterRow !== void 0 ? 1 : 0) ); const listHeight = Math.min( items.length, Math.max(1, Math.min(4, Math.floor(available * 0.35))) ); const height = Math.max(2, available - listHeight); bodyHeight = height; this.keepSelectionVisible(items.length, listHeight); const content = contentForSelection(height); for (let i = 0; i < height; i++) { const entry = content.rows[i]; if (entry?.itemId) this.contentRowItemMap.set(rows.length, entry.itemId); rows.push(cell(entry?.text ?? "")); } const listPosition = `[${this.sidebarScroll + 1}-${Math.min(items.length, this.sidebarScroll + listHeight)}/${items.length}] `; const arrows = items.length > listHeight ? `${resolveIcon("scrollUp", "\u25B2")}/${resolveIcon("scrollDown", "\u25BC")} ` : ""; const label = `${listLabel} ${listPosition}${arrows}`; rows.push( frame.line(["tRight", "horizontal"], ` ${dim(label)} `, [ { horizontal: Math.max(0, w - this.measure(label) - 5) }, "tLeft" ]) ); if (summary2 !== void 0) rows.push(cell(summary2)); if (filterRow !== void 0) rows.push(cell(filterRow)); this.lastListStartRow = rows.length; for (let i = 0; i < listHeight; i++) rows.push( cell( this.itemCell( items, this.sidebarScroll + i, rightWidth, false, rows.length ) ) ); this.lastListEndRow = rows.length - 1; rows.push(this.footer(frame, outputWidth, content.total, height)); } return this.finishRender(rows, outputWidth, maxLines, bodyHeight); } filterRow(width) { const total = this.adapter.items().length; const count = this.adapter.items().filter( (item) => this.adapter.matchesFilter?.(item, this.filterQuery) ).length; const suffix = `${count}/${total}`; const label = `${this.fg("accent", "/")} ${this.filterQuery}${this.filtering ? "\u2588" : ""}`; const room = Math.max(0, width - this.measure(suffix) - 1); return `${this.pad(label, room)} ${this.fg("dim", suffix)}`; } bindings() { if (this.filtering) return [ { key: "Enter", label: "keep", group: "panel" }, { key: "Esc", label: "clear", group: "panel" }, { key: `${resolveIcon("arrowUp")}/${resolveIcon("arrowDown")}`, label: "results", group: "navigate" } ]; const item = this.selectedItem(); const hints = [ { key: `${resolveIcon("arrowLeft", "\u2190")}/${resolveIcon("arrowRight", "\u2192")}`, label: "select", group: "navigate" }, { key: `${resolveIcon("arrowUp", "\u2191")}/${resolveIcon("arrowDown", "\u2193")}`, label: "scroll", group: "navigate" }, { key: "PgUp/PgDn", label: "page", group: "navigate", priority: 10 }, { key: "Home/End", label: "top/bottom", group: "navigate", priority: 0 }, ...this.adapter.views ? [ { key: "1-5", label: "view", group: "views" }, { key: "g/G", label: "top/bottom", group: "navigate" } ] : [], ...this.adapter.hints?.(item, this.getRenderDebugState()) ?? [], ...item ? this.adapter.actions?.(item).map((action) => ({ key: action.key, label: action.label, eligible: action.eligible, group: "actions" })) ?? [] : [], ...this.adapter.matchesFilter ? [{ key: "/", label: "filter", group: "panel" }] : [], ...this.listRows()[this.selected]?.group ? [{ key: "Enter/Space", label: "collapse", group: "panel" }] : [], { key: "Esc", label: this.filterVisible ? "clear" : "close", group: "panel", priority: 20 }, { key: "ctrl+c", label: "close", group: "panel", footer: false }, { key: "q", label: "close", group: "panel", footer: false }, { key: "?", label: "help", group: "panel" } ]; return hints.filter( (hint) => item !== void 0 || hint.group === "panel" || this.listRows().length > 0 && hint.group === "navigate" ); } footer(frame, width, total, height) { const unseen = Math.max(0, total - (this.seenLineCount ?? total)); const position = total > height || this.activeView !== void 0 ? `${this.fg("dim", `line ${this.followTail ? total : this.scroll + 1}/${total}`)}${(!this.activeView || this.activeView.followTail) && this.followTail ? ` ${this.fg("success", `${resolveIcon("selectionSelected")} live`)}` : (!this.activeView || this.activeView.followTail) && unseen ? ` ${this.fg("accent", `${resolveIcon("arrowDown", "\u2193")} ${unseen} new`)}` : ""}` : ""; const available = Math.max( 0, width - 6 - (position ? this.measure(position) + 2 : 0) ); const hints = this.helpOpen ? [ { key: "Esc", label: "close help", group: "panel" }, { key: "?", label: "close help", group: "panel" }, { key: `${resolveIcon("arrowUp", "\u2191")}/${resolveIcon("arrowDown", "\u2193")}`, label: "scroll help", group: "navigate" }, { key: "PgUp/PgDn", label: "scroll help", group: "navigate" } ] : this.bindings().filter( (hint) => hint.eligible !== false && hint.footer !== false ); const join3 = () => hints.map( (hint) => `${this.fg("accent", hint.key)} ${this.fg("dim", hint.label)}` ).join(this.fg("dim", ` ${resolveIcon("separator", "\xB7")} `)); if (this.actionNotice && this.actionNotice.expiresAt <= (this.options.now ?? Date.now)()) this.actionNotice = void 0; const confirmation = this.helpOpen ? void 0 : this.pendingAction ? this.fg("warning", this.pendingAction.prompt) : this.actionNotice ? this.fg(this.actionNotice.role, this.actionNotice.text) : this.confirmationHint(); const priority = (hint) => hint.key === "?" ? 1e3 : hint.group === "actions" ? 900 : hint.priority ?? 50; let text = confirmation ?? join3(); while (this.measure(text) > available && hints.length) { const lowest = Math.min(...hints.map(priority)); hints.splice( hints.findIndex((hint) => priority(hint) === lowest), 1 ); text = confirmation ?? join3(); if (confirmation) break; } return frame.line( ["bottomLeft", "horizontal"], ` ${this.clip(text, available)} `, [{ horizontal: Math.max(0, available - this.measure(text)) }], position ? ` ${position} ` : "", ["horizontal", "bottomRight"] ); } finishRender(rows, width, maxLines, bodyHeight) { if (this.helpOpen) { const boxWidth = Math.min(width, 56); const frame = createPanelFrame({ theme: this.options.theme ?? plainTheme, borderTone: "accent", text: { clip: (text, w) => this.clip(text, w), pad: (text, w) => this.pad(text, w), measure: (text) => this.measure(text) } }); const body = []; const bindings = this.bindings(); for (const [group, label] of [ ["navigate", "Navigate"], ["views", "Views"], ["actions", "Actions"], ["panel", "Panel"] ]) { const entries = bindings.filter( (hint) => (hint.group ?? "actions") === group ); if (!entries.length) continue; body.push(this.fg("toolTitle", label)); for (const hint of entries) { body.push( `${this.fg(hint.eligible === false ? "dim" : "accent", this.pad(hint.key, 12))}${this.fg("dim", hint.label)}` ); } } const capacity = Math.max(1, rows.length - 4); this.helpScroll = Math.min( this.helpScroll, Math.max(0, body.length - capacity) ); const box = [ frame.titled("Keyboard shortcuts", boxWidth, 1), ...body.slice(this.helpScroll, this.helpScroll + capacity).map((text) => frame.cells([{ text, width: boxWidth - 4 }])), frame.rule([boxWidth - 4], "bottom") ]; const top = Math.max(0, Math.floor((rows.length - box.length) / 2)); const left = " ".repeat(Math.max(0, Math.floor((width - boxWidth) / 2))); box.forEach((line, i) => { rows[top + i] = left + line; }); } const lines = rows.map((row) => this.clip(row, width)); const widths = lines.map((line) => this.measure(line)); this.lastRenderMetrics = { configuredMaxLines: maxLines, renderWidth: width, renderedLineCount: lines.length, bodyHeight, maxVisibleWidth: Math.max(0, ...widths), widthViolationCount: widths.filter((value3) => value3 > width).length }; return lines; } getRenderDebugState() { const item = this.selectedItem(); return { itemCount: this.adapter.items().length, selectedIndex: item ? this.adapter.items().findIndex( (entry) => this.adapter.id(entry) === this.adapter.id(item) ) : -1, selectedId: item ? this.adapter.id(item) : void 0, scrollOffset: this.scroll, followTail: this.followTail, viewId: this.activeView?.id, clickableRowCount: this.rowItemMap.size + this.contentRowItemMap.size + this.rowGroupMap.size, ...this.lastRenderMetrics }; } selectedItem() { return this.listRows()[this.selected]?.item; } dismiss() { if (this.disposed) return; if (this.options.disposeOnClose !== false) this.dispose(); this.options.onClose(); } dispose() { this.disposed = true; this.closeArm = void 0; if (this.refreshTimer) clearInterval(this.refreshTimer); this.refreshTimer = void 0; } }; // src/ui/panel-input.ts function createSubagentsPanelKeyMatcher(keybindings) { return createHistoryPanelKeyMatcher(keybindings, { "ctrl+o": ["app.tools.expand"], "ctrl+t": ["app.thinking.toggle"], detailCancel: ["subagents.detail.cancel"] }); } function classifySubagentsPanelInput(data, matchesPanelKey3) { if (matchesPanelKey3(data, "escape") || matchesPanelKey3(data, "ctrl+c") || matchesPanelKey3(data, "q")) return { category: "lifecycle", action: "close" }; if (matchesPanelKey3(data, "ctrl+o") || data === "") return { category: "display", action: "toggle_expand" }; if (matchesPanelKey3(data, "ctrl+t") || data === "") return { category: "display", action: "toggle_thinking" }; if (matchesPanelKey3(data, "detailCancel")) return { category: "task", action: "cancel_selected" }; const wheel = panelMouseWheelDelta(data); if (wheel === -1) return { category: "scroll", action: "up" }; if (wheel === 1) return { category: "scroll", action: "down" }; if (matchesPanelKey3(data, "right")) return { category: "navigation", action: "right" }; if (matchesPanelKey3(data, "left")) return { category: "navigation", action: "left" }; if (matchesPanelKey3(data, "down")) return { category: "navigation", action: "down" }; if (matchesPanelKey3(data, "up")) return { category: "navigation", action: "up" }; if (matchesPanelKey3(data, "pageDown")) return { category: "scroll", action: "page_down" }; if (matchesPanelKey3(data, "pageUp")) return { category: "scroll", action: "page_up" }; if (matchesPanelKey3(data, "home")) return { category: "scroll", action: "home" }; if (matchesPanelKey3(data, "end")) return { category: "scroll", action: "end" }; return { category: "other", action: "unmatched" }; } // src/ui/subagents-history-panel.ts import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util"; import { wrapTextWithAnsi } from "@earendil-works/pi-tui"; var statusRoles = { queued: "dim", running: "accent", stopping: "warning", completed: "success", failed: "error", cancelled: "muted", interrupted: "warning" }; function relativeTime(timestamp2) { const elapsed = Date.now() - Date.parse(timestamp2 ?? ""); if (!Number.isFinite(elapsed)) return ""; const seconds = Math.max(0, Math.floor(elapsed / 1e3)); if (seconds < 60) return `${seconds}s`; if (seconds < 3600) return `${Math.floor(seconds / 60)}m`; if (seconds < 86400) return `${Math.floor(seconds / 3600)}h`; return `${Math.floor(seconds / 86400)}d`; } function formatListDuration(task, roundSeconds = false) { if (task.status === "queued") return ""; const start = Date.parse(task.started_at ?? task.created_at); const end = task.ended_at ? Date.parse(task.ended_at) : Date.now(); if (!Number.isFinite(start) || !Number.isFinite(end)) return ""; const seconds = Math.max( 0, Math[roundSeconds ? "round" : "floor"]((end - start) / 1e3) ); if (seconds < 60) return `${seconds}s`; const minutes = Math.floor(seconds / 60); if (minutes < 60) return `${minutes}m`; const hours = Math.floor(minutes / 60); const label = `${hours}h${minutes % 60 || ""}${minutes % 60 ? "m" : ""}`; return label.length <= 4 ? label : `${hours}h`.slice(0, 4); } function formatListCost(cost) { if (cost === void 0 || !Number.isFinite(cost) || cost <= 0) return ""; for (const decimals of [2, 1, 0]) { const label = `$${cost.toFixed(decimals)}`; if (label.length <= 5) return label; } for (const [divisor, suffix] of [ [1e3, "k"], [1e6, "m"], [1e9, "b"] ]) { const label = `$${Math.round(cost / divisor)}${suffix}`; if (label.length <= 5) return label; } return ">$99b"; } function formatTokens2(count) { if (count < 1e3) return count.toString(); if (count < 1e4) return `${(count / 1e3).toFixed(1)}k`; if (count < 1e6) return `${Math.round(count / 1e3)}k`; return `${(count / 1e6).toFixed(1)}M`; } function formatTimeout(milliseconds) { if (!Number.isFinite(milliseconds) || milliseconds === void 0 || milliseconds <= 0) return void 0; let seconds = Math.max(1, Math.round(milliseconds / 1e3)); const hours = Math.floor(seconds / 3600); seconds %= 3600; const minutes = Math.floor(seconds / 60); seconds %= 60; return [ hours ? `${hours}h` : "", minutes ? `${minutes}m` : "", seconds ? `${seconds}s` : "" ].filter(Boolean).join(""); } function formatUsage2(usage) { if (!usage) return ""; const parts = []; if (usage.turns) parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`); if (usage.input) parts.push(`${resolveIcon("tokensIn", "\u2191")}${formatTokens2(usage.input)}`); if (usage.output) parts.push(`${resolveIcon("tokensOut", "\u2193")}${formatTokens2(usage.output)}`); if (usage.cacheRead) parts.push(`R${formatTokens2(usage.cacheRead)}`); if (usage.cacheWrite) parts.push(`W${formatTokens2(usage.cacheWrite)}`); if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`); if (usage.contextTokens) parts.push(`ctx:${formatTokens2(usage.contextTokens)}`); return parts.join(" "); } function normalizeTerminalErrorText(text) { return text?.replace(/\s+/g, " ").trim().toLowerCase() ?? ""; } function hasEquivalentSnapshotError(snapshot2, errorText) { const normalized = normalizeTerminalErrorText(errorText); if (!normalized) return false; return snapshot2.items.some((item) => { if (item.type === "error") return normalizeTerminalErrorText(item.text) === normalized; if (item.type === "assistant") return normalizeTerminalErrorText(item.message.errorMessage) === normalized; return false; }); } function snapshotHasActiveTools(snapshot2) { if (!snapshot2?.items?.length) return false; return snapshot2.items.some( (item) => item.type === "tool" && ["pending", "running", "partial"].includes(item.status) || item.type === "bash" && (item.status === void 0 || item.status === "running") ); } var SubagentsHistoryPanel = class { constructor(tasksProvider, theme, done, matchesKey2, visibleWidth3, nativeTruncateToWidth, renderContext = {}, maxLinesProvider = 42, taskResolver, initialSelectedTaskId, cancelSelectedTask, detailCancelShortcut = "x", displayOptions = {}) { this.tasksProvider = tasksProvider; this.theme = theme; this.visibleWidth = visibleWidth3; this.nativeTruncateToWidth = nativeTruncateToWidth; this.renderContext = renderContext; this.taskResolver = taskResolver; this.detailCancelShortcut = detailCancelShortcut; this.displayOptions = displayOptions; const adapter = { actions: (task) => this.actionsFor(task, cancelSelectedTask), views: (task) => { const tools = this.toolsFor(this.resolveTaskForBody(task)); return [ { id: "result", label: "Result" }, { id: "transcript", label: "Transcript", followTail: true }, { id: "prompt", label: "Prompt" }, { id: "tools", label: `Tools (${tools.length} \u2717${tools.filter((tool) => this.toolFailed(tool)).length})` }, { id: "metrics", label: "Metrics" } ]; }, defaultView: (task) => isTerminalStatus(task.status) ? "result" : "transcript", renderView: (task, view, width) => this.viewFor(task, view, width), items: () => [...this.tasks()].sort( (a, b) => Date.parse(b.created_at) - Date.parse(a.created_at) ), id: (task) => task.id, groupOf: (task) => this.groupFor(task), renderGroupOverview: (tasks) => { const counts = /* @__PURE__ */ new Map(); let cost = 0; for (const task of tasks) { counts.set(task.status, (counts.get(task.status) ?? 0) + 1); const taskCost = task.usage?.cost ?? 0; if (Number.isFinite(taskCost) && taskCost > 0) cost += taskCost; } return [ [...counts].map(([status, count]) => `${status}: ${count}`).join(" \xB7 "), `Total cost: $${cost.toFixed(2)}` ]; }, matchesFilter: (task, query) => [task.display_name ?? "", task.agent, task.status].some( (value3) => value3.toLowerCase().includes(query.toLowerCase()) ), renderItemLabel: (task, context) => this.itemLabel(task, context), renderListSummary: (width) => this.listSummary(width), renderHeader: (task, context) => this.headerFor(task, context), hints: (task, state) => [ { key: "i", label: "details", group: "views", priority: 100, eligible: task !== void 0 }, { key: "ctrl+o", label: "expand", group: "views", eligible: state.viewId === "transcript" }, { key: "ctrl+t", label: "thinking", group: "views", eligible: state.viewId === "transcript" } ], renderContent: (task, width) => this.contentFor(task, width), handleInput: (data, panel) => { if (data === "i" && panel.selectedItem()) { this.detailsExpanded = !this.detailsExpanded; if (this.detailsExpanded) panel.handleInput("\x1B[H"); return true; } if (panel.getRenderDebugState().viewId !== "transcript") return false; if (matchesKey2(data, "ctrl+o") || data === "") { this.toolOutputExpanded = !this.toolOutputExpanded; return true; } if (matchesKey2(data, "ctrl+t") || data === "") { this.hideThinkingBlock = !this.hideThinkingBlock; return true; } return false; }, invalidate: () => { this.bodyCache.clear(); this.hydratedTasks.clear(); } }; this.panel = new HistoryPanel(adapter, { title: "subagents", listLabel: "executions", emptyText: "No subagent tasks recorded in this session yet.", theme: { fg: (role, text) => theme?.fg?.(role, text) ?? text, bold: (text) => theme?.bold?.(text) ?? text, bg: (role, text) => theme?.bg?.(role, text) ?? text }, onClose: done, disposeOnClose: false, maxLines: maxLinesProvider, initialSelectedId: initialSelectedTaskId ?? this.tasks()[0]?.id, matchesKey: (data, key3) => key3 === this.detailCancelShortcut && matchesKey2(data, "detailCancel") || matchesKey2(data, key3), visibleWidth: visibleWidth3, truncateToWidth: this.truncateToWidth, closeKey: this.detailCancelShortcut, // The overlay host owns its refresh timer and render requests. refreshMs: 0, requestRender: this.displayOptions.requestRender, titleIcon: agentIcon }); } tasksProvider; theme; visibleWidth; nativeTruncateToWidth; renderContext; taskResolver; detailCancelShortcut; displayOptions; panel; toolOutputExpanded = false; hideThinkingBlock = false; detailsExpanded = false; hydratedTasks = /* @__PURE__ */ new Map(); bodyCache = /* @__PURE__ */ new Map(); truncateToWidth = (text, width) => getRenderKit()?.icon ? truncateToWidth2(text, width, resolveIcon("ellipsis", "\u2026")) : this.nativeTruncateToWidth(text, width); invalidate() { this.panel.invalidate(); } dispose() { this.panel.dispose(); } handleMouse(event) { return this.panel.handleMouse(event); } handleInput(data) { this.panel.handleInput(data); } render(width) { return this.panel.render(width); } cancelSelectedActiveTask() { this.panel.closeSelectedItem(); } getRenderDebugState() { const state = this.panel.getRenderDebugState(); const task = this.panel.selectedItem(); return { taskCount: state.itemCount, selectedIndex: state.selectedIndex, selectedStatus: task?.status, scrollOffset: state.scrollOffset, followTail: state.followTail, hasUsage: Boolean(task?.usage), configuredMaxLines: state.configuredMaxLines, renderWidth: state.renderWidth, renderedLineCount: state.renderedLineCount, bodyHeight: state.bodyHeight, maxVisibleWidth: state.maxVisibleWidth, widthViolationCount: state.widthViolationCount, clickableRowCount: state.clickableRowCount }; } effectiveTimeoutMs(task) { const start = task.timeout_started_at ?? Date.parse(task.started_at ?? ""); const deadline = task.timeout_deadline_at; if (deadline !== void 0 && Number.isFinite(deadline) && Number.isFinite(start) && deadline > start) return deadline - start; const configured = this.displayOptions.timeoutMs; const increment = this.displayOptions.extensionForTask?.( task.id )?.incrementMs; return configured === void 0 ? void 0 : configured + (task.timeout_extensions_used ?? 0) * (increment ?? 0); } needsAttention(task) { if (isTerminalStatus(task.status)) return false; if (task.pending_questions?.length || task.status === "stopping") return true; if (task.status !== "running") return false; const start = task.timeout_started_at ?? Date.parse(task.started_at ?? ""); const deadline = task.timeout_deadline_at; return deadline !== void 0 && Number.isFinite(deadline) && Number.isFinite(start) && deadline > start && deadline - Date.now() < (deadline - start) * 0.2; } groupFor(task) { if (this.needsAttention(task)) return { id: "attention", label: "Needs attention", order: 0 }; if (task.status === "running" || task.status === "queued") return { id: "running", label: "Running", order: 1 }; if (task.status === "completed") return { id: "completed", label: "Completed", order: 2 }; return { id: "failed", label: "Failed", order: 3 }; } listSummary(width) { let attention = 0; let live = 0; let completed = 0; let failed = 0; let cost = 0; for (const task of this.tasks()) { if (this.needsAttention(task)) attention++; if (task.status === "completed") completed++; else if (task.status === "failed" || task.status === "cancelled" || task.status === "interrupted") failed++; else if (!this.needsAttention(task)) live++; const taskCost = task.usage?.cost ?? 0; if (Number.isFinite(taskCost) && taskCost > 0) cost += taskCost; } const groups = [ { count: live, status: "running", role: "accent" }, { count: completed, status: "completed", role: "success" }, { count: failed, status: "failed", role: "error" } ]; const parts = groups.map( ({ count, status, role }) => count ? themeFg(this.theme, role, `${resolveStatusGlyph(status)}${count}`) : "" ); parts.push( attention ? themeFg( this.theme, "warning", `${resolveIcon("warning")}${attention}` ) : "" ); let costText = cost > 0 ? `$${cost.toFixed(2)}` : ""; const join3 = () => [parts.filter(Boolean).join(" "), costText].filter(Boolean).join(` ${resolveIcon("separator", "\xB7")} `); if (this.visibleWidth(join3()) > width) costText = ""; for (const index of [1, 0]) { if (this.visibleWidth(join3()) <= width) break; parts[index] = ""; } return join3(); } itemLabel(task, context) { const selection = context.selected ? resolveIcon("selection", "\u203A") : " "; const statusGlyph2 = task.status === "stopping" ? resolveIcon("ready", "\u25B2") : task.status === "interrupted" ? resolveIcon("elapsed", "\u25F7") : resolveStatusGlyph(task.status); const attention = this.needsAttention(task) && task.status !== "stopping"; const glyph = themeFg( this.theme, attention ? "warning" : statusRoles[task.status] ?? "dim", attention ? resolveIcon("warning") : statusGlyph2 ); const name = task.display_name?.trim() || task.agent; const prefix = `${selection}${glyph} `; const duration = formatListDuration(task).padStart(4); const cost = context.width >= 24 ? ` ${formatListCost(task.usage?.cost).padStart(5)}` : ""; const nameWidth = Math.max( 0, context.width - this.visibleWidth(prefix) - 5 - cost.length ); const clippedName = truncateToWidth2( name, nameWidth, resolveIcon("ellipsis", "\u2026") ); const padding = " ".repeat( Math.max(0, nameWidth - this.visibleWidth(clippedName)) ); return `${prefix}${clippedName}${padding} ${duration}${cost}`; } contextFor(task) { let window = task.runtime_metrics?.contextWindow; try { window ??= this.displayOptions.contextWindowForTask?.(task); } catch { } if (window === void 0 || !Number.isFinite(window) || window <= 0) window = void 0; const tokens = task.runtime_metrics?.contextTokens ?? task.usage?.contextTokens; const measuredPercent = task.runtime_metrics?.contextPercent; const percent = window !== void 0 && tokens !== void 0 ? tokens / window * 100 : measuredPercent !== void 0 && Number.isFinite(measuredPercent) ? measuredPercent : void 0; return { window, tokens, percent }; } headerFor(task, context) { const current = this.resolveTaskForBody(task); const width = context.width; const fg = (role2, text) => themeFg(this.theme, role2, text); const sep = ` ${resolveIcon("separator", "\xB7")} `; const role = statusRoles[current.status] ?? "dim"; const glyph = fg( role, resolveStatusGlyph( current.status === "interrupted" ? "blocked" : current.status ) ); const usage = current.usage; const { window, percent } = this.contextFor(current); const knownWindow = window !== void 0 && percent !== void 0; const percentText = percent === void 0 ? "" : `${Math.round(percent)}%`; const contextRole2 = (percent ?? 0) > 90 ? "error" : (percent ?? 0) > 70 ? "warning" : "success"; const ascii = resolveIcon("boxHorizontal", "\u2500") === "-"; let barCells = knownWindow ? 10 : 0; let relative = isTerminalStatus(current.status) && current.ended_at ? relativeTime(current.ended_at) : ""; let turns = usage?.turns === void 0 ? "" : `${usage.turns} turns`; let effort = current.effort ?? "default/current"; let model = current.model ?? "default/current"; let agent = current.agent; let name = current.display_name?.trim() || current.agent; const cost = `$${(usage?.cost ?? 0).toFixed(2)}`; const duration = formatListDuration(current, true) || "0s"; const active = current.status === "running"; const effectiveMs = this.effectiveTimeoutMs(current); const timeout = formatTimeout(effectiveMs); const nearDeadline = current.timeout_deadline_at !== void 0 && effectiveMs !== void 0 && current.timeout_deadline_at - Date.now() < effectiveMs * 0.2; let timeoutSuffix = active && timeout ? ` ${fg(nearDeadline ? "warning" : "dim", `/ ${timeout}`)}` : ""; const activityAge = active ? relativeTime(current.last_activity_at) : ""; const elapsedActivity = Date.now() - Date.parse(current.last_activity_at ?? ""); const stalled = active && this.displayOptions.stallTimeoutMs !== void 0 && elapsedActivity > this.displayOptions.stallTimeoutMs; let activity = activityAge ? stalled ? fg("warning", `${resolveIcon("warning", "\u26A0")} stalled ${activityAge}`) : fg("dim", `last activity ${activityAge} ago`) : ""; const line1 = () => `${glyph} ${name}${agent ? ` ${agent}` : ""}${sep}${fg(role, current.status)}${relative ? ` ${relative} ago` : ""}${active ? " " : sep}${duration}${timeoutSuffix}${activity ? sep + activity : ""}`; const line2 = () => { const filled = Math.max( 0, Math.min(barCells, Math.round((percent ?? 0) / 100 * barCells)) ); const bar = barCells ? (ascii ? "#" : "\u2588").repeat(filled) + (ascii ? "-" : "\u2591").repeat(barCells - filled) : ""; const ctx = [bar, percentText].filter(Boolean).join(" "); return ` ${[model, effort, turns, ctx ? `ctx ${fg(contextRole2, ctx)}` : ""].filter(Boolean).join(sep)}`; }; const fits = () => this.visibleWidth(line1()) + 1 + this.visibleWidth(cost) <= width && this.visibleWidth(line2()) <= width; while (!fits() && barCells > 6) barCells--; if (!fits()) relative = ""; if (!fits()) turns = ""; if (!fits()) effort = ""; while (!fits() && this.visibleWidth(model) > 12) { model = truncateToWidth2( model, this.visibleWidth(model) - 1, resolveIcon("ellipsis", "\u2026") ); } if (!fits()) agent = ""; if (!fits()) barCells = 0; if (!fits()) timeoutSuffix = ""; if (this.visibleWidth(line1()) - this.visibleWidth(name) + this.visibleWidth(resolveIcon("ellipsis", "\u2026")) + 1 + this.visibleWidth(cost) > width) activity = ""; const availableName = Math.max( 1, width - this.visibleWidth(line1()) + this.visibleWidth(name) - 1 - this.visibleWidth(cost) ); name = truncateToWidth2( name, availableName, resolveIcon("ellipsis", "\u2026") ); const first = line1(); const rows = [ first + " ".repeat( Math.max( 1, width - this.visibleWidth(first) - this.visibleWidth(cost) ) ) + cost, line2() ]; const warning = this.displayOptions.providerLimits?.warningText(current.id); if (warning) rows.push(fg("warning", `limit: ${warning}`)); return { variableRows: true, wideRows: rows, narrowRows: rows }; } detailsFor(task, width) { const usage = task.usage; const fields = [ ["Input", formatTokens2(usage?.input ?? 0)], ["Output", formatTokens2(usage?.output ?? 0)], ["Cache read", formatTokens2(usage?.cacheRead ?? 0)], ["Cache write", formatTokens2(usage?.cacheWrite ?? 0)] ]; const lines = []; const field2 = (label, value3, columns2) => { const valueWidth = Math.max(1, columns2 - 12); const wrapped = this.wrap(value3, valueWidth); return wrapped.map( (value4, index) => themeDim(this.theme, (index ? "" : label).padEnd(12)) + value4 ); }; const columns = width >= 70 ? 2 : 1; const columnWidth = columns === 2 ? Math.floor((width - 2) / 2) : width; const cells = fields.map( ([label, value3]) => field2(label, value3, columnWidth) ); for (let i = 0; i < cells.length; i += columns) { const left = cells[i] ?? []; const right = columns === 2 ? cells[i + 1] ?? [] : []; for (let row = 0; row < Math.max(left.length, right.length); row++) { const text = left[row] ?? ""; lines.push( columns === 1 ? text : text + " ".repeat( Math.max(0, columnWidth - this.visibleWidth(text)) + 2 ) + (right[row] ?? "") ); } } const { window: contextWindow, tokens, percent } = this.contextFor(task); const context = `${formatTokens2(tokens ?? 0)}${contextWindow ? ` / ${formatTokens2(contextWindow)}` : ""}${percent === void 0 ? "" : ` (${Math.round(percent)}%)`}`; lines.push(...field2("Context", context, width)); const timeout = formatTimeout(this.effectiveTimeoutMs(task)); const remaining = task.timeout_deadline_at === void 0 ? void 0 : task.timeout_deadline_at <= Date.now() ? "0s" : formatTimeout(task.timeout_deadline_at - Date.now()); const extensions = task.timeout_extensions_used === void 0 ? void 0 : `extended ${task.timeout_extensions_used}${task.timeout_max_extensions === void 0 ? "" : `/${task.timeout_max_extensions}`}`; const timeoutParts = [ timeout, remaining ? `${remaining.replace(/(?<=[hm])(?=\d)/g, " ")} left` : void 0, extensions ].filter(Boolean); if (timeoutParts.length) lines.push( ...field2( "Timeout", timeoutParts.join(` ${resolveIcon("separator", "\xB7")} `), width ) ); if (task.session_id) lines.push(...field2("Session", task.session_id, width)); lines.push(...field2("Task", task.task, width), ""); return lines.map((text) => ({ text })); } toolsFor(task) { return isValidThreadSnapshot(task.thread_snapshot) ? task.thread_snapshot.items.filter( (item) => item.type === "tool" || item.type === "bash" ) : []; } toolFailed(tool) { return tool.status === "failed" || tool.status === "cancelled" || (tool.type === "bash" ? tool.exitCode !== void 0 && tool.exitCode !== 0 || tool.cancelled === true : tool.result?.isError === true); } /** Shared unwrapped Result text: rendering and clipboard must never diverge. */ resultText(task) { if (!isTerminalStatus(task.status)) return "Still running \u2014 no result yet. Press 2 for the live Transcript."; return ["failed", "cancelled", "interrupted"].includes(task.status) ? `\u2717 Failed \u2014 ${task.error || task.result || task.status}` : task.result || "No result recorded."; } actionsFor(task, cancel) { const current = this.resolveTaskForBody(task); const name = current.display_name || current.agent; const extension = this.displayOptions.extensionForTask?.(current.id); const session = this.displayOptions.currentSessionId; return [ ...this.detailCancelShortcut ? [ { key: this.detailCancelShortcut, label: "cancel active", eligible: current.status === "queued" || current.status === "running", confirm: () => `\u26A0 Cancel ${name}? Stops the running task. Enter confirm \xB7 Esc keep`, run: () => { cancel?.(current.id); } } ] : [], { key: "e", label: "extend", eligible: current.status === "running" && !!session && current.session_id === session && current.timeout_deadline_at !== void 0 && !!extension && extension.remaining > 0 && !!this.displayOptions.extendDeadline, confirm: () => `\u26A0 Extend ${name} by ${formatTimeout(extension?.incrementMs)}? ${extension?.remaining} extensions left. Enter confirm \xB7 Esc back`, run: () => Promise.resolve( this.displayOptions.extendDeadline?.( current.id, void 0, session ) ).then(() => { }) }, { key: "y", label: "copy", eligible: isTerminalStatus(current.status) && !!stripVTControlCharacters2( current.error || current.result || "" ).trim(), run: () => { const result = copyToClipboardOsc52( this.displayOptions.clipboardWrite, this.resultText(current) ); return result === "ok" ? { text: "\u2713 Result copied", role: "success" } : { text: result === "too-large" ? "\u26A0 Result too large to copy" : "\u26A0 Copy not supported by this terminal", role: "warning" }; } } ]; } viewFor(task, view, width) { const current = this.resolveTaskForBody(task); return [ ...this.detailsExpanded ? this.detailsFor(current, width) : [], ...this.viewBodyFor(current, view, width) ]; } viewBodyFor(current, view, width) { const lines = (text, role) => this.wrap(text, width).map((text2) => ({ text: role ? themeFg(this.theme, role, text2) : text2 })); if (view === "result") { const questions = !isTerminalStatus(current.status) ? current.pending_questions ?? [] : []; const pending = questions.length ? [ "\u26A0 Waiting for an answer from the main chat", ...questions.map((question) => question.message), "Reply in the main chat with root \u2014 this panel is read-only." ].flatMap( (text) => this.wrap(text, Math.max(1, width - 2)).map((text2) => ({ text: themeFg( this.theme, "warning", `${resolveIcon("boxVertical", "\u2502")} ${text2}` ) })) ) : []; const failed = ["failed", "cancelled", "interrupted"].includes( current.status ); return [ ...pending, ...lines(this.resultText(current), failed ? "error" : void 0) ]; } if (view === "prompt") return lines( [ current.task, current.context ? ` Context ${current.context}` : "" ].filter(Boolean).join("\n") ); if (view === "metrics") { const { window: contextWindow, tokens, percent } = this.contextFor(current); const fields = [ ["Status", current.status], ["Agent", current.agent], ["Model", current.model ?? "default/current"], ["Effort", current.effort ?? "default/current"], [ "Turns", String(current.usage?.turns ?? current.runtime_metrics?.turns ?? 0) ], ["Started", current.started_at ?? "\u2014"], ["Ended", current.ended_at ?? "\u2014"], ["Duration", formatListDuration(current) || "\u2014"], ["Timeout", formatTimeout(this.effectiveTimeoutMs(current)) ?? "\u2014"], [ "Extensions", `${current.timeout_extensions_used ?? 0}/${current.timeout_max_extensions ?? "\u2014"}` ], ["Input", formatTokens2(current.usage?.input ?? 0)], ["Output", formatTokens2(current.usage?.output ?? 0)], ["Cache read", formatTokens2(current.usage?.cacheRead ?? 0)], ["Cache write", formatTokens2(current.usage?.cacheWrite ?? 0)], ["Cost", `$${(current.usage?.cost ?? 0).toFixed(4)}`], [ "Context", `${formatTokens2(tokens ?? 0)}${contextWindow ? ` / ${formatTokens2(contextWindow)}` : ""}${percent === void 0 ? "" : ` (${Math.round(percent)}%)`}` ], ["Session", current.session_id ?? "\u2014"], ["Task id", current.id] ]; return fields.flatMap( ([label, value3]) => this.wrap(value3, Math.max(1, width - 14)).map((text, index) => ({ text: themeDim(this.theme, (index ? "" : label).padEnd(14)) + text })) ); } if (view === "transcript" && current.transcript?.trim()) return this.contentFor(current, width); if (!isValidThreadSnapshot(current.thread_snapshot)) return [ ...lines( `${resolveStatusGlyph("deleted")} Execution detail no longer retained`, "warning" ), ...lines( "It was pruned by history retention or never recorded.", "dim" ), ...lines( "Result (1), Prompt (3) and Metrics (5) show what was kept.", "dim" ) ]; if (view === "transcript") return this.contentFor(current, width); const tools = this.toolsFor(current).map((tool, index) => ({ tool, index })); const started = (entry) => { const timestamp2 = entry.tool.type === "tool" ? Date.parse(entry.tool.started_at ?? "") : NaN; return Number.isFinite(timestamp2) ? timestamp2 : Infinity; }; tools.sort( (a, b) => Number(this.toolFailed(b.tool)) - Number(this.toolFailed(a.tool)) || started(a) - started(b) || a.index - b.index ); const targetWidth = Math.max(1, width - 30); const cell = (text, cells) => { const clipped = this.truncateToWidth(text.replace(/\s+/g, " "), cells); return clipped + " ".repeat(Math.max(0, cells - this.visibleWidth(clipped))); }; const row = (status, name, target, duration, exit) => `${cell(status, 2)} ${cell(name, 12)} ${cell(target, targetWidth)} ${duration.padStart(7)} ${exit.padStart(5)}`; return [ { text: themeDim( this.theme, row("St", "Tool", "Target", "Duration", "Exit") ) }, { text: themeDim( this.theme, resolveIcon("boxHorizontal", "\u2500").repeat(width) ) }, ...tools.map(({ tool }) => { const failed = this.toolFailed(tool); const duration = tool.type === "tool" && Number.isFinite(Date.parse(tool.started_at ?? "")) && Number.isFinite(Date.parse(tool.ended_at ?? "")) ? formatDuration2( Math.max( 0, Date.parse(tool.ended_at ?? "") - Date.parse(tool.started_at ?? "") ) ) : "\u2014"; const name = tool.type === "bash" ? "bash" : tool.name; const target = toolArgumentSummary( name, tool.type === "bash" ? { command: tool.command } : tool.arguments ); const status = resolveStatusGlyph( failed ? "failed" : tool.status === "partial" ? "running" : tool.status ?? "running" ); const prefix = `${themeFg(this.theme, failed ? "error" : tool.status === "completed" ? "success" : "accent", cell(status, 2))} ${cell(name, 12)} ${themeDim(this.theme, cell(target, targetWidth))} ${duration.padStart(7)} `; const exit = tool.type === "bash" && tool.exitCode !== void 0 ? themeFg( this.theme, tool.exitCode === 0 ? "success" : "error", String(tool.exitCode).padStart(5) ) : " ".repeat(5); return { text: prefix + exit }; }) ]; } contentFor(task, width) { const currentTask = this.resolveTaskForBody(task); const structured = isValidThreadSnapshot(currentTask.thread_snapshot); const body = this.bodyEntriesFor(currentTask, width); const entries = structured ? body : this.wrapWithTaskIds(body, width); return [ ...entries.map(({ text, taskId: taskId2 }) => ({ text: structured ? text : this.renderFlowLine(text, width), itemId: taskId2 })) ]; } tasks() { return typeof this.tasksProvider === "function" ? this.tasksProvider() : this.tasksProvider; } renderFlowLine(raw, width) { const th = this.theme; if (raw.startsWith("Preparing for response") || /^\*\*.+\*\*$/.test(raw)) { const clipped = this.truncateToWidth(raw, width); const text = th?.bold?.(clipped) ?? clipped; return th?.fg?.("dim", text) ?? text; } if (this.isToolLikeLine(raw)) { const border = (t) => themeFg(th, "accent", t); const prefix = border(`${BOX_CHARS.vertical} `); const maxTextWidth = Math.max(0, width - 2); const clipped = this.truncateToWidth(raw, maxTextWidth); const text = th?.fg?.("toolTitle", clipped) ?? clipped; return `${prefix}${text}`; } if (raw.startsWith("done") || raw.startsWith("completed")) { const clipped = this.truncateToWidth(raw, width); return th?.fg?.("success", clipped) ?? clipped; } if (raw.startsWith("failed") || raw.startsWith("error")) { const clipped = this.truncateToWidth(raw, width); return th?.fg?.("error", clipped) ?? clipped; } if (raw.startsWith("# ") || raw.startsWith("## ") || raw.startsWith("### ")) { const border = (t) => themeFg(th, "accent", t); const titleText = raw.replace(/^#+\s*/, ""); const maxTitle = Math.max(4, width - 8); const clippedTitle = this.truncateToWidth(titleText, maxTitle); const heading = th?.bold?.(th?.fg?.("mdHeading", clippedTitle) ?? clippedTitle) ?? clippedTitle; const leftFrame = `${border(BOX_CHARS.topLeft + BOX_CHARS.horizontal + " ")}${heading} `; const leftVisWidth = this.visibleWidth(leftFrame); const rightCorner = border(BOX_CHARS.topRight); const rightVisWidth = this.visibleWidth(rightCorner); const filler = Math.max(0, width - leftVisWidth - rightVisWidth); const framed = `${leftFrame}${border(BOX_CHARS.horizontal.repeat(filler))}${rightCorner}`; return framed; } if (raw.startsWith(" ")) { const clipped = this.truncateToWidth(raw, width); return th?.fg?.("dim", clipped) ?? clipped; } return this.truncateToWidth(raw, width); } taskSignature(task) { const { thread_snapshot: snapshot2, transcript: _transcript, ...metadata } = task; return JSON.stringify([ metadata, snapshot2?.updated_at, snapshot2?.items?.length ]); } resolveTaskForBody(task) { if (task.thread_snapshot || !this.taskResolver) return task; const signature2 = this.taskSignature(task); const cached = this.hydratedTasks.get(task.id); if (cached?.signature === signature2) return cached.task; const hydrated = this.taskResolver(task.id) ?? task; this.hydratedTasks.set(task.id, { signature: signature2, task: hydrated }); return hydrated; } bodyCacheKey(task, width) { return [ "transcript", JSON.stringify(task), width, this.toolOutputExpanded ? "expanded" : "collapsed", this.hideThinkingBlock ? "thinking-hidden" : "thinking-visible" ].join("|"); } resolveTaskIdFromSnapshotItem(item, tasks) { if (!item) return void 0; const directId = item.taskId ?? item.task_id ?? item.subagentTaskId ?? item.subtaskId; if (typeof directId === "string" && directId.trim()) return directId.trim(); const details = item.result?.details; if (details) { if (typeof details.task?.id === "string" && details.task.id.trim()) return details.task.id.trim(); if (typeof details.task_id === "string" && details.task_id.trim()) return details.task_id.trim(); if (typeof details.taskId === "string" && details.taskId.trim()) return details.taskId.trim(); if (Array.isArray(details.tasks) && details.tasks[0]?.id) return String(details.tasks[0].id).trim(); if (Array.isArray(details.task_ids) && details.task_ids[0]) return String(details.task_ids[0]).trim(); } const resultTaskId = item.result?.task_id ?? item.result?.taskId ?? item.result?.task?.id; if (typeof resultTaskId === "string" && resultTaskId.trim()) return resultTaskId.trim(); const argsTaskId = item.arguments?.task_id ?? item.arguments?.taskId ?? item.arguments?.task?.id; if (typeof argsTaskId === "string" && argsTaskId.trim()) return argsTaskId.trim(); const toolName = typeof item.name === "string" ? item.name : ""; const isSubagentTool = toolName === "subagent_run" || toolName === "subagent_continue" || toolName === "subagent" || toolName.startsWith("subagent"); if (isSubagentTool || item.type === "subagent") { const agentCandidate = item.arguments?.agent ?? item.arguments?.name; if (typeof agentCandidate === "string" && agentCandidate.trim()) { const found = tasks.find( (t) => t.id === agentCandidate || t.agent === agentCandidate || t.display_name === agentCandidate ); if (found) return found.id; } const taskCandidate = item.arguments?.task; if (typeof taskCandidate === "string" && taskCandidate.trim()) { const found = tasks.find( (t) => t.task === taskCandidate || t.display_name === taskCandidate ); if (found) return found.id; } } return void 0; } resolveTaskIdFromFlowLine(line, tasks) { const trimmed = line.trim(); if (!trimmed) return { cleanLine: line }; if (trimmed.startsWith("subagent:") || trimmed.startsWith("model:") || trimmed.startsWith("usage:") || trimmed.startsWith("#") || trimmed.startsWith("Preparing for response") || trimmed.startsWith("done") || trimmed.startsWith("completed") || trimmed.startsWith("failed") || trimmed.startsWith("error")) { return { cleanLine: line }; } let cleanLine = line; let taskId2; const rawIdMatch = line.match(/\b(subtask_[a-zA-Z0-9_-]+)\b/); if (rawIdMatch) { taskId2 = rawIdMatch[1]; cleanLine = cleanLine.replace(/\s*[([]?subtask_[a-zA-Z0-9_-]+[)\]]?/g, "").replace(/\s{2,}/g, " ").trimEnd(); } if (!taskId2) { if (trimmed === "main") { const found = tasks.find((t) => t.id === "main" || t.agent === "main"); if (found) taskId2 = found.id; } const subagentMatch = trimmed.match(/^subagent\s+([^\s:]+)/); if (subagentMatch) { const agentName = subagentMatch[1]; const found = tasks.find( (t) => t.id === agentName || t.agent === agentName || t.display_name === agentName ); if (found) taskId2 = found.id; } const bulletMatch = trimmed.match(/^(?:󰣇|●|○)\s+([^\s:]+)/); if (bulletMatch) { const agentName = bulletMatch[1]; const found = tasks.find( (t) => t.id === agentName || t.agent === agentName || t.display_name === agentName ); if (found) taskId2 = found.id; } if (!taskId2) { for (const t of tasks) { if (t.agent && (trimmed.startsWith(`${t.agent} `) || trimmed.startsWith(`${t.agent}:`) || trimmed === t.agent)) { taskId2 = t.id; break; } if (t.display_name && (trimmed.startsWith(`${t.display_name} `) || trimmed.startsWith(`${t.display_name}:`) || trimmed === t.display_name)) { taskId2 = t.id; break; } } } } return { cleanLine, taskId: taskId2 }; } wrapWithTaskIds(entries, width) { const out = []; for (const entry of entries) { const wrappedTexts = this.wrap(entry.text, width); for (const text of wrappedTexts) { out.push({ text, taskId: entry.taskId }); } } return out; } executionFlowEntriesFor(task) { const rawFlow = this.executionFlowFor(task); const rawLines = rawFlow.split("\n"); const tasks = this.tasks(); return rawLines.map((line) => { const { cleanLine, taskId: taskId2 } = this.resolveTaskIdFromFlowLine(line, tasks); return { text: cleanLine, taskId: taskId2 }; }); } bodyEntriesFor(task, width) { const activeSnapshot = isValidThreadSnapshot(task.thread_snapshot) ? task.thread_snapshot : void 0; const allowCache = !snapshotHasActiveTools(activeSnapshot); const cacheKey = this.bodyCacheKey(task, width); if (allowCache) { const cached = this.bodyCache.get(cacheKey); if (cached) return cached; } let entries; if (activeSnapshot) { const snapshotItems = [...activeSnapshot.items]; const delegatedPromptIndex = snapshotItems.findIndex((item) => { if (item.type !== "user") return false; const label = item.label; return item.id === "delegated-prompt" || label === "delegated_task"; }); if (delegatedPromptIndex >= 0) { const item = snapshotItems[delegatedPromptIndex]; if (item?.type === "user") { snapshotItems[delegatedPromptIndex] = { ...item, label: "delegated_task", text: task.task }; } } else { let insertionIndex = snapshotItems[0]?.type === "attempt" ? 1 : 0; while (true) { const item = snapshotItems[insertionIndex]; if (item?.type !== "user" || item.label !== "context") break; insertionIndex++; } snapshotItems.splice(insertionIndex, 0, { type: "user", id: "delegated-prompt", label: "delegated_task", text: task.task }); } const snapshotToRender = { ...activeSnapshot, items: snapshotItems }; const context = { ...this.renderContext, theme: this.renderContext.theme ?? this.theme, cwd: this.renderContext.cwd ?? process.cwd(), taskId: task.id, visibleWidth: this.renderContext.visibleWidth ?? this.visibleWidth, truncateToWidth: getRenderKit()?.icon ? this.truncateToWidth : this.renderContext.truncateToWidth ?? this.truncateToWidth, renderWidth: width, toolOutputExpanded: this.toolOutputExpanded, hideThinkingBlock: this.hideThinkingBlock, includeFullDelegatedTask: true }; const renderedItems = renderThreadBodyItems(snapshotToRender, context); const renderedLines = renderedItems.flatMap((item) => item.lines); const rawLines = renderedLines.length ? renderedLines : [""]; const knownTasks = this.tasks(); if (renderedItems.length <= 1) { const taskId2 = renderedItems[0] ? this.resolveTaskIdFromSnapshotItem( renderedItems[0].item, knownTasks ) : void 0; entries = rawLines.map((text) => { const resolved = taskId2 ? { cleanLine: text, taskId: taskId2 } : this.resolveTaskIdFromFlowLine(text, knownTasks); return { text: resolved.cleanLine, taskId: resolved.taskId }; }); } else { const itemSlices = renderedItems.map(({ item, lines }) => ({ lines, taskId: this.resolveTaskIdFromSnapshotItem(item, knownTasks) })); const flatLines = itemSlices.flatMap((slice) => slice.lines); if (flatLines.length === rawLines.length && flatLines.join("\n") === rawLines.join("\n")) { entries = itemSlices.flatMap( (slice) => slice.lines.map((text) => { const resolved = slice.taskId ? { cleanLine: text, taskId: slice.taskId } : this.resolveTaskIdFromFlowLine(text, knownTasks); return { text: resolved.cleanLine, taskId: resolved.taskId }; }) ); } else { entries = rawLines.map((lineText) => { const resolved = this.resolveTaskIdFromFlowLine( lineText, knownTasks ); return { text: resolved.cleanLine, taskId: resolved.taskId }; }); } } if ((task.status === "failed" || task.status === "cancelled") && task.error && !hasEquivalentSnapshotError(activeSnapshot, task.error)) { entries.push({ text: "" }, { text: "# error" }, { text: task.error }); } entries = entries.flatMap( (entry) => entry.text.split(/\r?\n|\r/).map((text) => ({ ...entry, text: truncateToWidth2(text.replace(/\t/g, " "), width) })) ); } else { entries = this.executionFlowEntriesFor(task); } if (!allowCache) return entries; this.bodyCache.set(cacheKey, entries); if (this.bodyCache.size > 50) { const oldest = this.bodyCache.keys().next().value; if (oldest !== void 0) this.bodyCache.delete(oldest); } return entries; } executionFlowFor(task) { const usage = formatUsage2(task.usage); const hasResp = typeof task.result === "string" && task.result.trim().length > 0; const parts = [ `subagent: ${task.agent} ${resolveIcon("separator", "\xB7")} status: ${task.status} ${resolveIcon("separator", "\xB7")} attempt: ${task.attempt ?? 1} ${resolveIcon("separator", "\xB7")} effort: ${task.effort ?? "default/current"}`, `model: ${task.model ?? "default/current"}`, usage ? `usage: ${usage}` : void 0, "", hasResp ? "Preparing for response" : void 0, hasResp ? "" : void 0, ["# delegated task", task.task].join("\n"), task.context ? ["", "# context", task.context].join("\n") : void 0, task.continuation_prompt ? ["", "# continuation prompt", task.continuation_prompt].join("\n") : void 0, usage ? ["", "# usage", usage].join("\n") : void 0, task.transcript ? ["", "# execution", this.cleanTranscript(task.transcript)].join("\n") : void 0, task.error ? ["", "# error", task.error].join("\n") : void 0, isTerminalStatus(task.status) && !task.thread_snapshot && !task.transcript ? "execution detail expired (final response and task metadata retained)" : void 0, hasResp ? ["", "# response sent to orchestrator", task.result].join("\n") : void 0, !task.transcript && !hasResp && !task.error ? [ "", "# activity", `${task.last_activity ?? "queued"}${task.output_preview ? ` ${task.output_preview}` : ""}` ].join("\n") : void 0 ].filter(Boolean); return parts.join("\n").trim(); } cleanTranscript(transcript) { return transcript.replace(/^# orchestrator prompt[\s\S]*?## delegated task\n/m, "").replace(/\n# final assistant text[\s\S]*$/m, "").replace(/\n# response sent to orchestrator[\s\S]*$/m, "").split("\n").filter((line) => !this.isNoiseLine(line)).join("\n").replace(/\n{3,}/g, "\n\n").trim(); } isToolLikeLine(raw) { return raw.startsWith("subagent ") || raw.startsWith("memory_") || raw.startsWith("read ") || raw.startsWith("bash ") || raw.startsWith("edit ") || raw.startsWith("write ") || raw.startsWith("tool "); } isNoiseLine(raw) { const line = raw.trim(); if (!line) return false; if ([ "agent_start", "message_start", "message_update", "message_end", "turn_start", "turn_end" ].includes(line)) return true; if (/^\{.*\}$/.test(line)) return true; return false; } wrap(text, width) { return wrapTextWithAnsi(text.replace(/\t/g, " "), Math.max(1, width)); } }; // src/ui/panel-overlay.ts function currentSessionId(ctx) { const direct = ctx?.sessionManager?.getSessionId?.() ?? ctx?.sessionId; if (typeof direct === "string" && direct.length > 0) return direct; const file = ctx?.sessionManager?.getSessionFile?.(); return typeof file === "string" && file.length > 0 ? file : void 0; } function contextWindowForTask(ctx, task) { const label = task.model; const current = ctx?.model; const currentLabel = current?.provider && current?.id ? `${current.provider}/${current.id}` : void 0; let model = !label || label === "default/current" || label === currentLabel ? current : void 0; if (!model && label) { const separator = label.indexOf("/"); if (separator > 0) model = ctx?.modelRegistry?.find?.( label.slice(0, separator), label.slice(separator + 1) ); } const contextWindow = Number(model?.contextWindow); return Number.isFinite(contextWindow) && contextWindow > 0 ? contextWindow : void 0; } function setMouseTracking(tui, enabled) { if (tui?.mode === "fullscreen") return; const write = tui?.terminal?.write?.bind(tui.terminal); if (typeof write !== "function") return; write(enabled ? "\x1B[?1000h\x1B[?1006h" : "\x1B[?1006l\x1B[?1000l"); } function toolFromRegistry(registry5, name) { if (!registry5) return void 0; if (typeof registry5.get === "function") return registry5.get(name); if (Array.isArray(registry5)) return registry5.find((tool) => tool?.name === name); if (typeof registry5 === "object") return registry5[name]; return void 0; } function toolsFromAccessor(owner, name) { if (typeof owner?.getAllTools !== "function") return void 0; try { const info = toolFromRegistry(owner.getAllTools(), name); if (getRenderKit()) return info; return info ? resolveSubagentExternalToolDefinitionFromInfo(name, info) ?? info : void 0; } catch { return void 0; } } function hasToolRenderers(tool) { if (!tool || typeof tool !== "object") return false; const definition = tool; return typeof definition.renderCall === "function" || typeof definition.renderResult === "function" || definition.renderShell === "self"; } function resolveRegisteredToolDefinition(ctx, pi, name) { const published = getPublishedToolDefinition(name); const kit = getRenderKit(); if (published && (!kit || hasToolRenderers(published))) return published; if (kit) { const candidates = [ published, ctx?.pi?.getToolDefinition?.(name), pi?.getToolDefinition?.(name), ctx?.getToolDefinition?.(name), toolFromRegistry(ctx?.pi?.tools, name), toolFromRegistry(pi?.tools, name), toolFromRegistry(ctx?.tools, name), toolsFromAccessor(ctx?.pi, name), toolsFromAccessor(pi, name), toolsFromAccessor(ctx, name) ]; const rendered = candidates.find(hasToolRenderers); if (published && rendered) { const { renderCall, renderResult, renderShell } = rendered; return { ...published, renderCall, renderResult, renderShell }; } return rendered ?? candidates.find(Boolean); } return ctx?.pi?.getToolDefinition?.(name) ?? pi?.getToolDefinition?.(name) ?? ctx?.getToolDefinition?.(name) ?? toolsFromAccessor(ctx?.pi, name) ?? toolsFromAccessor(pi, name) ?? toolsFromAccessor(ctx, name) ?? toolFromRegistry(ctx?.pi?.tools, name) ?? toolFromRegistry(pi?.tools, name) ?? toolFromRegistry(ctx?.tools, name); } var activePanelOpener; var lastPanelOpenTime = 0; function registerSubagentsPanelOpener(opener) { activePanelOpener = opener; lastPanelOpenTime = 0; } function openSubagentsPanel(taskId2) { const now = Date.now(); if (now - lastPanelOpenTime < 600) return; lastPanelOpenTime = now; if (activePanelOpener) { void activePanelOpener(taskId2); } } function getPanelTasks(manager, cwd, sessionId, completedLimit = 100) { const all = manager.listSessionTasks(cwd, sessionId); const active = all.filter( (t) => t.status === "running" || t.status === "queued" || t.status === "stopping" ); const completed = all.filter( (t) => t.status !== "running" && t.status !== "queued" && t.status !== "stopping" ); const activeIds = new Set(active.map((t) => t.id)); const completedCapped = completed.slice(0, completedLimit); const includedIds = /* @__PURE__ */ new Set([ ...activeIds, ...completedCapped.map((t) => t.id) ]); return all.filter((t) => includedIds.has(t.id)); } async function showSubagentsPanel(input) { const { ctx, pi, manager, selectedTaskId, providerLimits, setActivePanelCancelSelected, setActivePanelRequestRender } = input; const cwd = ctx?.cwd ?? process.cwd(); const sessionId = currentSessionId(ctx); let refresh2; let disposePanel; try { await openOwnedOverlay( ctx, (tui, theme, _keybindings, closeOverlay) => { setMouseTracking(tui, true); const config = readSubagentsConfig(cwd); const renderLogger = createSubagentsRenderLogger({ cwd, sessionId, config: config.render_debug }); let nextRenderReason = "initial"; let renderCycle = 0; const close = () => { disposePanel?.(); if (refresh2) clearInterval(refresh2); renderLogger.log({ event: "panel_disposed" }); setMouseTracking(tui, false); closeOverlay(); }; const baseMatchesKey = createSubagentsPanelKeyMatcher(_keybindings); const panel = new SubagentsHistoryPanel( () => getPanelTasks(manager, cwd, sessionId), theme, close, (data, key3) => { if (key3 !== "detailCancel") return baseMatchesKey(data, key3); const detailShortcut = config.detail_cancel_shortcut ?? "x"; return baseMatchesKey(data, detailShortcut) || baseMatchesKey(data, "detailCancel") || detailShortcut === "ctrl+w" && _keybindings?.matches?.(data, "tui.editor.deleteWordBackward"); }, visibleWidth2, truncateToWidth2, { theme, tui, cwd, visibleWidth: visibleWidth2, truncateToWidth: truncateToWidth2, getToolDefinition: (name) => resolveRegisteredToolDefinition(ctx, pi, name), getMessageRenderer: (customType) => ctx?.pi?.getMessageRenderer?.(customType) ?? ctx?.pi?.customMessageRenderers?.get?.(customType) ?? ctx?.customMessageRenderers?.get?.(customType), showImages: ctx?.showImages, imageWidthCells: ctx?.imageWidthCells }, () => Math.max(12, tui?.terminal?.rows ?? process.stdout.rows ?? 42), (id) => manager.getTask(id, cwd), selectedTaskId, (id) => manager.cancel(id, "cancelled from subagents detail view"), config.detail_cancel_shortcut ?? "x", { providerLimits, currentSessionId: sessionId, extensionForTask: (id) => manager.getDeadlineExtension?.(id), extendDeadline: (id, extra, session) => manager.extendDeadline(id, extra, session), clipboardWrite: tui?.terminal?.write?.bind(tui.terminal), requestRender: () => tui.requestRender?.(), timeoutMs: config.timeout_ms, stallTimeoutMs: config.stall_timeout_ms, contextWindowForTask: (task) => contextWindowForTask(ctx, task) } ); const unsubscribeLimits = providerLimits?.onChange( () => tui.requestRender?.() ); disposePanel = () => { unsubscribeLimits?.(); panel.dispose(); }; renderLogger.log({ event: "panel_created" }); renderLogger.log({ event: "render_requested", reason: nextRenderReason }); setActivePanelCancelSelected( () => () => panel.cancelSelectedActiveTask() ); setActivePanelRequestRender(() => () => { nextRenderReason = "external"; renderLogger.log({ event: "render_requested", reason: nextRenderReason }); tui.requestRender?.(); }); refresh2 = setInterval(() => { nextRenderReason = "interval"; renderLogger.log({ event: "render_requested", reason: nextRenderReason }); tui.requestRender?.(); }, 1e3); return { render: (width) => { const reason = nextRenderReason; const currentRenderCycle = ++renderCycle; renderLogger.log({ event: "render_started", reason, renderCycle: currentRenderCycle, dimensions: { stdoutColumns: process.stdout.columns, stdoutRows: process.stdout.rows, renderWidth: width } }); const startedAt = process.hrtime.bigint(); const lines = panel.render(width); const durationMs = Number(process.hrtime.bigint() - startedAt) / 1e6; renderLogger.log({ event: "render_completed", reason, renderCycle: currentRenderCycle, durationMs, dimensions: { stdoutColumns: process.stdout.columns, stdoutRows: process.stdout.rows, renderWidth: width }, state: panel.getRenderDebugState() }); nextRenderReason = "external"; return lines; }, invalidate: () => panel.invalidate(), handleMouse: (event) => { nextRenderReason = "mouse"; renderLogger.log({ event: "render_requested", reason: nextRenderReason }); return panel.handleMouse(event); }, handleInput: (data) => { renderLogger.log({ event: "input_received", input: classifySubagentsPanelInput(data, baseMatchesKey) }); nextRenderReason = "input"; renderLogger.log({ event: "render_requested", reason: nextRenderReason }); panel.handleInput(data); } }; }, { overlayOptions: { anchor: "top-left", width: "100%", maxHeight: "100%", margin: 0 } } ); } finally { disposePanel?.(); setActivePanelCancelSelected(void 0); setActivePanelRequestRender(void 0); if (refresh2) clearInterval(refresh2); } } // src/render/tools/subagent-run.ts function renderSubagentTaskCall(_agent, _mode, _theme, _detail) { return emptyComponent(); } function renderSubagentRunCall(_args, _theme) { return emptyComponent(); } function formatRuntimeMetrics(task) { const speed = generationSpeed(task.runtime_metrics); const started = Date.parse(task.started_at ?? ""); const isLive = task.status === "queued" || task.status === "running" || task.status === "stopping"; const ended = isLive ? Date.now() : Date.parse(task.ended_at ?? ""); const elapsed = Math.max(0, ended - started); return { speed: speed !== void 0 ? `${Math.round(speed)} tok/s` : "", elapsed: Number.isFinite(started) && Number.isFinite(ended) ? formatDuration2(isLive ? Math.floor(elapsed / 1e3) * 1e3 : elapsed) : "" }; } function compactRunRow(task, statusLabel, resumedSuffix) { const cost = typeof task?.usage?.cost === "number" && task.usage.cost > 0 ? `$${task.usage.cost.toFixed(2)}` : void 0; return { title: "subagent", summary: [ `${formatTaskSummary(task)}${resumedSuffix}`, statusLabel, task?.model, task?.effort, cost ].filter(Boolean) }; } var renderSubagentRunResult = iconAwareRenderer( function renderSubagentRunResult2(result, options = {}, theme, context) { const renderState = toolRenderState(result, options, context); const { expanded, isPartial } = options ?? {}; const task = taskFromDetails(result); const isBg = task?.mode === "background" || task?.effective_mode === "background" || result?.details?.mode === "background"; const isRunning = task?.status === "running" || task?.status === "queued"; const isLaunched = isBg && isRunning && !renderState.context.isPartial && !renderState.context.isError; if (isLaunched) { renderState.status = "completed"; renderState.isSuccess = true; } const statusLabel = isLaunched ? "launched" : task?.status ?? (renderState.context.isError ? "failed" : "completed"); const runtime = task && (isPartial || !isBg) ? formatRuntimeMetrics(task) : void 0; const archPrefix = themeStatus( theme, isLaunched ? "completed" : statusLabel, isBg && isRunning ? isLaunched ? resolveStatusGlyph("completed", "\u2913") : !isAnimationEffectEnabled("secondary") ? resolveStaticRunningGlyph() : getRenderKit()?.indicator(theme, void 0, { status: "running", frame: result?.details?.frame ?? 0 }).glyph ?? "\u2913" : statusGlyph(statusLabel, result?.details?.frame ?? 0) ); const bgSuffix = isBg ? " (background)" : ""; const resumedSuffix = options?.resumedAttempt != null ? ` ${resolveIcon("separator", "\xB7")} resumed #${options.resumedAttempt}` : ""; if (isPartial) { const frame = result?.details?.frame ?? 0; const backgroundable = Boolean(result?.details?.backgroundable); const raw = progressText(task ? [task] : [], frame, { ui: true, backgroundable, backgroundShortcut: result?.details?.backgroundShortcut, runtime: isBg ? void 0 : runtime?.speed }); const lines = raw.split("\n"); const currentActivityIndex = task?.live_activity?.trail?.length ? lines.length - (backgroundable ? 2 : 1) : -1; const styled = lines.map((line, index) => { if (index === 0) return themeWarning(theme, line); if (index === currentActivityIndex) return themeBold(theme, themeAccent(theme, line)); return themeDim(theme, line); }).filter(Boolean); const agentOrName = task?.display_name || task?.agent || "subagent"; const title2 = `${archPrefix} ${themeTitle(theme, `subagent ${resolveIcon("separator", "\xB7")} ${agentOrName} ${resolveIcon("separator", "\xB7")} running${bgSuffix}`)}`; return boxedComponent(styled, { title: title2, theme, ...renderState, compact: { title: "subagent", summary: [`${formatTaskSummary(task)}${resumedSuffix}${bgSuffix}`], body: task?.live_activity?.trail?.length ? [lines[currentActivityIndex] ?? ""] : lines.slice(1) }, workingRow: 0, animationFrame: result?.details?.frame, wrapped: true, onClick: task?.id ? () => openSubagentsPanel(task.id) : void 0 }); } const failed = Boolean( renderState.context.isError || task?.status === "failed" || task?.status === "cancelled" ); const isExpanded = Boolean(expanded); const status = isLaunched ? themeSuccess(theme, "launched") : task ? themeStatus(theme, task.status ?? (failed ? "failed" : "done")) : failed ? themeError(theme, "failed") : themeSuccess(theme, "done"); const taskLabel = `${formatTaskLabel(task, true)}${resumedSuffix}`; const hasResp = hasAgentResponse(task, result); const responseText = taskResponseText(task, result); let title; if (isRunning) { const agentOrName = task?.display_name || task?.agent || "subagent"; title = `${archPrefix} ${themeTitle(theme, `subagent ${resolveIcon("separator", "\xB7")} ${agentOrName}${resumedSuffix} ${resolveIcon("separator", "\xB7")} ${statusLabel}${bgSuffix}`)}`; } else if (!isExpanded) { const titleLabel = failed ? themeError( theme, `[subagent] ${taskLabel} ${resolveIcon("separator", "\xB7")} ${statusLabel}` ) : themeTitle( theme, `[subagent] ${taskLabel} ${resolveIcon("separator", "\xB7")} ${statusLabel}` ); title = `${archPrefix} ${titleLabel}`.trim(); } else if (hasResp) { title = `${archPrefix} ${themeTitle(theme, `subagent result ${resolveIcon("separator", "\xB7")} ${taskLabel}`)}`; } else { title = `${archPrefix} ${themeTitle(theme, `subagent ${resolveIcon("separator", "\xB7")} ${taskLabel}`)}`; } const usage = task ? formatUsage(task, true) : ""; const usageLine = [ usage ? `usage: ${usage}` : void 0, runtime?.speed, runtime?.elapsed ? `\u29D7 elapsed ${runtime.elapsed}` : void 0 ].filter(Boolean).join(` ${resolveIcon("separator", "\xB7")} `); const compactError = failed ? firstLineOf( task?.error || (renderState.context.isError ? result?.content?.[0]?.text : void 0) ) : void 0; const compactDetail = compactError ?? firstLineOf(hasResp ? responseText : void 0) ?? firstLineOf(task?.output_preview) ?? firstLineOf(task?.last_activity); const compact = { ...compactRunRow(task, statusLabel, resumedSuffix), body: compactDetail ? [compactError ? themeError(theme, compactDetail) : compactDetail] : [] }; if (!isRunning && !isExpanded) { const costSuffix = typeof task?.usage?.cost === "number" && task.usage.cost > 0 ? ` ${resolveIcon("separator", "\xB7")} $${task.usage.cost.toFixed(2)}` : ""; const metaLine = themeDim( theme, `subagent: ${task?.agent ?? "subagent"} ${resolveIcon("separator", "\xB7")} model: ${task?.model ?? "default/current"} ${resolveIcon("separator", "\xB7")} effort: ${task?.effort ?? "default/current"} ${resolveIcon("separator", "\xB7")} status: ${statusLabel}${costSuffix}` ); const collapsedLines = [metaLine]; if (failed) { const errorRaw = task?.error || (renderState.context.isError && typeof result?.content?.[0]?.text === "string" ? result.content[0].text : void 0); if (errorRaw) { const firstLine = errorRaw.split("\n")[0]?.trim(); if (firstLine) { collapsedLines.push(themeError(theme, firstLine)); } } } collapsedLines.push( themeDim(theme, resolveExpandHint("to expand", context)) ); return boxedComponent(collapsedLines, { title, theme, ...renderState, compact, wrapped: false, onClick: task?.id ? () => openSubagentsPanel(task.id) : void 0 }); } const historyShortcut = readSubagentsConfig(process.cwd()).history_panel_shortcut ?? "ctrl+,"; const detailsHint = `(click to view execution) ${resolveIcon("separator", "\xB7")} (${historyShortcut} or /subagents for details)`; const metaLines = task ? [ `subagent: ${themeAccent(theme, task.agent)} ${resolveIcon("separator", "\xB7")} status: ${status} ${resolveIcon("separator", "\xB7")} attempt: ${themeAccent(theme, String(task.attempt ?? 1))} ${resolveIcon("separator", "\xB7")} effort: ${themeAccent(theme, task.effort ?? "default/current")}`, themeDim(theme, `model: ${task.model ?? "default/current"}`), usageLine ? themeDim(theme, usageLine) : void 0, themeDim(theme, detailsHint) ].filter(Boolean) : [status, themeDim(theme, detailsHint)]; const contentLines = [...metaLines]; if (hasResp && responseText) { contentLines.push( themeTitle(theme, "Subagent response"), ...responseText.split("\n") ); } else if (failed && task?.error) { contentLines.push( themeError(theme, "Subagent error"), ...task.error.split("\n") ); } return boxedComponent(contentLines, { title, theme, ...renderState, compact, wrapped: true, onClick: task?.id ? () => openSubagentsPanel(task.id) : void 0 }); } ); // src/render/tools/subagent-continue.ts function renderSubagentContinueCall(args, theme, task) { const attempt = task ? (task.attempt ?? 1) + 1 : "next"; const detail = task ? `continue ${resolveIcon("separator", "\xB7")} attempt: ${attempt} ${resolveIcon("separator", "\xB7")} ${formatTaskLabel(task, true)}` : `continue ${resolveIcon("separator", "\xB7")} attempt: ${attempt}`; const mode = resolveContinuationEffectiveMode({ explicitMode: args?.mode }); return renderSubagentTaskCall(task?.agent ?? "continue", mode, theme, detail); } var renderSubagentContinueResult = iconAwareRenderer( function renderSubagentContinueResult2(result, options, theme, context) { const task = taskFromDetails(result); return renderSubagentRunResult( result, { ...options, resumedAttempt: task ? task.attempt ?? 1 : void 0 }, theme, context ); } ); // src/tools/subagent-run.ts import { Type as Type3 } from "typebox"; function installDoubleEscapeCancel(ctx, manager, onCancel, getTaskIds = () => []) { let lastEscapeAt = 0; const unsubscribe = ctx?.ui?.onTerminalInput?.((data) => { if (isWorkPanelRootEditorInputActive(ctx) === false) { lastEscapeAt = 0; return void 0; } if (data !== "\x1B") return void 0; const now = Date.now(); const isDoubleEscape = now - lastEscapeAt <= 600; lastEscapeAt = now; if (!isDoubleEscape) return { consume: true }; onCancel(); const ids = getTaskIds(); const cancelled = ids.length ? ids.map((id) => { try { return manager.cancel(id, "cancelled by double escape"); } catch { return void 0; } }).filter(Boolean) : manager.cancelRunning("cancelled by double escape"); ctx?.abort?.(); ctx?.ui?.notify?.( cancelled.length ? `Cancelled ${cancelled.length} subagent task(s).` : "Requested subagent/main cancellation.", "warning" ); lastEscapeAt = 0; return { consume: true }; }); return typeof unsubscribe === "function" ? unsubscribe : () => { }; } function createSubagentRunTool(manager, pi) { return { name: "subagent_run", label: "Subagent Run", description: "Delegate a task to exactly one markdown-defined subagent.", promptSnippet: "Omit mode: background by default.", promptGuidelines: [ "mode=task only when the user explicitly asks to wait for completion.", "After background launch/continuation, respond immediately; wait for the automatic completion notification. No sleeping, polling status, or fetching results just to wait.", "Replies, steering, and extensions require current Pi session task ownership." ], parameters: Type3.Object({ agent: Type3.String(), task: Type3.String(), name: Type3.Optional(Type3.String()), display_name: Type3.Optional(Type3.String()), context: Type3.Optional(Type3.String()), mode: Type3.Optional( Type3.Unsafe({ type: "string", enum: ["task", "background"] }) ) }), renderShell: "self", execute: withBackgroundHandoffBarrier( async (toolReturned, _id, params, _signal, onUpdate, ctx) => { if (Array.isArray(params?.agents) || typeof params?.agent !== "string" || !params.agent.trim()) { return fail( "subagent_run accepts exactly one agent. Use the `agent` string parameter, not `agents`." ); } let cancelledByDoubleEscape = false; let frame = 0; let active = true; let latestTasks = []; const cwd = ctx?.cwd ?? process.cwd(); const availability = () => continuationAvailable(cwd, pi); const subagentsConfig = readSubagentsConfig(cwd); const effectiveMode = resolveEffectiveSubagentMode({ invocationMode: params.mode }); const isBackground = effectiveMode === "background"; const canBackgroundInTaskMode = effectiveMode === "task"; const backgroundShortcut = subagentsConfig.background_handoff_shortcut ?? "ctrl+h"; let resolveBackground; const backgroundPromise = canBackgroundInTaskMode ? new Promise( (resolve3) => { resolveBackground = resolve3; } ) : void 0; let heartbeat; const stopHeartbeat = () => { heartbeat?.(); heartbeat = void 0; }; const syncHeartbeat = () => { const hasActiveForegroundTask = active && !isBackground && !_signal?.aborted && latestTasks.some( (task) => task.mode === "task" && (task.status === "queued" || task.status === "running" || task.status === "stopping") ); if (!hasActiveForegroundTask) { stopHeartbeat(); return; } if (heartbeat !== void 0) return; const removeSteps = subscribeAnimationSteps({ kind: "secondary", intendedMs: 200, onStep(step) { syncHeartbeat(); if (!heartbeat) return; if (step.frame !== void 0) frame = step.frame + 1; emit(); } }); const removeLevel = subscribeAnimationLevel(() => emit()); heartbeat = () => { removeSteps(); removeLevel(); }; }; const emit = () => { if (!active || isBackground || _signal?.aborted) return; const currentFrame = isAnimationEffectEnabled("secondary") ? frame : void 0; try { onUpdate?.({ content: [ { type: "text", text: progressText(latestTasks, currentFrame, { backgroundable: canBackgroundInTaskMode, backgroundShortcut }) } ], details: { tasks: latestTasks.map( (task) => compactTaskForToolResult(task, availability(), { includeResult: false }) ), frame: currentFrame, backgroundable: canBackgroundInTaskMode, backgroundShortcut } }); } catch { active = false; } syncHeartbeat(); }; const uninstallCancel = isBackground ? () => { } : installDoubleEscapeCancel( ctx, manager, () => { cancelledByDoubleEscape = true; }, () => latestTasks.map((task) => task.id) ); const uninstallBackground = canBackgroundInTaskMode ? installBackgroundHandoffShortcut( ctx, manager, () => latestTasks.map((task) => task.id), (tasks) => { active = false; stopHeartbeat(); resolveBackground?.({ mode: "background", task_ids: tasks.map((task) => task.id) }); }, toolReturned ) : () => { }; try { if (!isBackground) _signal?.addEventListener("abort", stopHeartbeat, { once: true }); emit(); const runPromise = manager.run( params, { ...ctx, pi }, _signal, isBackground ? void 0 : (tasks) => { latestTasks = tasks; emit(); } ); const result = backgroundPromise ? await Promise.race([runPromise, backgroundPromise]) : await runPromise; if (cancelledByDoubleEscape) throw new Error("Subagent run cancelled by double escape"); const available = availability(); if (!("results" in result)) { const launchedTasks = result.task_ids.map((id) => manager.getTask(id, ctx?.cwd ?? process.cwd())).filter(Boolean); const details2 = compactResultDetails( { ...result, tasks: launchedTasks }, available ); const tasksForLaunch2 = latestTasks.length ? latestTasks : launchedTasks.length ? launchedTasks : result.task_ids; const response = ok( [ backgroundLaunchContent(tasksForLaunch2, "Sent"), !isBackground && launchedTasks.some((task) => task.pending_questions?.length) ? QUESTION_HANDOFF_GUIDANCE : void 0 ].filter(Boolean).join("\n\n"), details2 ); return isBackground ? response : { ...response, terminate: true }; } const failedTasks = (result.results ?? []).filter( (task) => task.status === "failed" || task.status === "cancelled" ); const tasksForLaunch = latestTasks.length ? latestTasks : result.results ?? result.task_ids; const text = result.mode === "background" ? backgroundLaunchContent(tasksForLaunch, "Started") : formatTaskModeContent(result.results ?? [], available); const details = compactResultDetails(result, available); const failureText = appendSubagentResumeGuidance( `${failedTasks.length} subagent task(s) failed or were cancelled. ${failedTasks.map(formatTask).join("\n\n")}`, failedTasks, available ); return failedTasks.length ? { ...fail(failureText), details } : ok(text, details); } catch (e) { if (!cancelledByDoubleEscape) return fail(e); const message = e instanceof Error ? e.message : String(e); return fail( appendSubagentResumeGuidance( message, latestTasks.length ? latestTasks : [{ status: "cancelled" }], availability() ) ); } finally { active = false; stopHeartbeat(); if (!isBackground) _signal?.removeEventListener("abort", stopHeartbeat); uninstallCancel(); uninstallBackground(); } } ), renderCall: renderSubagentRunCall, renderResult: renderSubagentRunResult }; } // src/tools/subagent-continue.ts function createSubagentContinueTool(manager, pi) { return { name: "subagent_continue", label: "Subagent Continue", description: "Continue a completed, failed, or cancelled task in its exact persisted nested Pi session, keeping task_id.", promptSnippet: "Omit mode: background by default. Use mode=task only when explicitly asked to wait. Supply model or effort only after an explicit user decision. Never auto-switch models.", parameters: Type4.Object({ task_id: Type4.String(), prompt: Type4.String(), mode: Type4.Optional( Type4.Unsafe({ type: "string", enum: ["task", "background"] }) ), model: Type4.Optional(Type4.String()), effort: Type4.Optional( Type4.Unsafe({ type: "string", enum: ["off", "minimal", "low", "medium", "high", "xhigh"] }) ) }), renderShell: "self", execute: withBackgroundHandoffBarrier( async (toolReturned, _id, params, _signal, onUpdate, ctx) => { let cancelledByDoubleEscape = false; let frame = 0; let active = true; let latestTasks = []; const cwd = ctx?.cwd ?? process.cwd(); const availability = () => continuationAvailable(cwd, pi); const config = readSubagentsConfig(cwd); const effectiveMode = resolveContinuationEffectiveMode({ explicitMode: params.mode }); const continuationInput = { ...params }; const isBackground = effectiveMode === "background"; const canBackgroundInTaskMode = effectiveMode === "task"; const backgroundShortcut = config.background_handoff_shortcut ?? "ctrl+h"; let resolveBackground; const backgroundPromise = canBackgroundInTaskMode ? new Promise( (resolve3) => { resolveBackground = resolve3; } ) : void 0; let heartbeat; const stopHeartbeat = () => { heartbeat?.(); heartbeat = void 0; }; const syncHeartbeat = () => { const hasActiveForegroundTask = active && !isBackground && !_signal?.aborted && latestTasks.some( (task) => task.mode === "task" && (task.status === "queued" || task.status === "running" || task.status === "stopping") ); if (!hasActiveForegroundTask) { stopHeartbeat(); return; } if (heartbeat !== void 0) return; const removeSteps = subscribeAnimationSteps({ kind: "secondary", intendedMs: 200, onStep(step) { syncHeartbeat(); if (!heartbeat) return; if (step.frame !== void 0) frame = step.frame + 1; emit(); } }); const removeLevel = subscribeAnimationLevel(() => emit()); heartbeat = () => { removeSteps(); removeLevel(); }; }; const emit = () => { if (!active || isBackground || _signal?.aborted) return; const currentFrame = isAnimationEffectEnabled("secondary") ? frame : void 0; try { onUpdate?.({ content: [ { type: "text", text: progressText(latestTasks, currentFrame, { backgroundable: canBackgroundInTaskMode, backgroundShortcut }) } ], details: { tasks: latestTasks.map( (task) => compactTaskForToolResult(task, availability(), { includeResult: false }) ), frame: currentFrame, backgroundable: canBackgroundInTaskMode, backgroundShortcut } }); } catch { active = false; } syncHeartbeat(); }; const uninstallCancel = isBackground ? () => { } : installDoubleEscapeCancel( ctx, manager, () => { cancelledByDoubleEscape = true; }, () => latestTasks.map((task) => task.id) ); const uninstallBackground = canBackgroundInTaskMode ? installBackgroundHandoffShortcut( ctx, manager, () => latestTasks.map((task) => task.id), (tasks) => { active = false; stopHeartbeat(); resolveBackground?.({ mode: "background", task_ids: tasks.map((task) => task.id) }); }, toolReturned, () => { continuationInput.mode = "background"; active = false; stopHeartbeat(); resolveBackground?.({ mode: "background", task_ids: [params.task_id] }); } ) : () => { }; try { if (!isBackground) _signal?.addEventListener("abort", stopHeartbeat, { once: true }); emit(); const continuePromise = manager.continueTask( continuationInput, { ...ctx, pi }, _signal, isBackground ? void 0 : (tasks2) => { latestTasks = tasks2; emit(); } ); const result = backgroundPromise ? await Promise.race([continuePromise, backgroundPromise]) : await continuePromise; if (cancelledByDoubleEscape) throw new Error("Subagent continuation cancelled by double escape"); const available = availability(); if (!("results" in result)) { const response = ok( [ backgroundLaunchContent(result.task_ids, "Continued"), !isBackground && result.task_ids.some( (id) => manager.getTask(id)?.pending_questions?.length ) ? QUESTION_HANDOFF_GUIDANCE : void 0 ].filter(Boolean).join("\n\n"), compactResultDetails( { ...result, tasks: result.task_ids.map((id) => manager.getTask(id, cwd)).filter(Boolean) }, available ) ); return isBackground ? response : { ...response, terminate: true }; } const tasks = result.results ?? []; const text = formatTaskModeContent(tasks, available); const details = compactResultDetails( { task: tasks[0], ...result }, available ); return tasks.some( (task) => task.status === "failed" || task.status === "cancelled" ) ? { ...fail(text), details } : ok(text, details); } catch (e) { const task = manager.getTask(params.task_id, cwd); const tasks = task ? [task] : latestTasks; const available = availability(); const message = e instanceof Error ? e.message : String(e); const response = fail( cancelledByDoubleEscape ? appendSubagentResumeGuidance( message, tasks.length ? tasks : [{ status: "cancelled" }], available ) : e ); return { ...response, details: compactResultDetails( { ...response.details, tasks }, available ) }; } finally { active = false; stopHeartbeat(); if (!isBackground) _signal?.removeEventListener("abort", stopHeartbeat); uninstallCancel(); uninstallBackground(); } } ), renderCall: (args, theme) => renderSubagentContinueCall( args, theme, args?.task_id ? manager.getTask(args.task_id, process.cwd()) : void 0 ), renderResult: renderSubagentContinueResult }; } // src/tools/subagent-extend.ts import { Type as Type5 } from "typebox"; // src/render/tools/subagent-extend.ts function renderSubagentExtendCall(_args, _theme) { return emptyComponent(); } var renderSubagentExtendResult = iconAwareRenderer( function renderSubagentExtendResult2(result, options, theme, context) { const renderState = toolRenderState(result, options, context); const failed = Boolean(renderState.context.isError); const { expanded } = options ?? {}; const details = result?.details ?? {}; const archPrefix = themeFg(theme, "accent", agentIcon()); const title = `${archPrefix} ${themeTitle(theme, failed ? `subagent extend ${resolveIcon("separator", "\xB7")} failed` : "subagent extend")}`; if (failed || !details.task_id) { const text = result?.content?.[0]?.text ?? details.error ?? ""; return boxedComponent( [failed ? themeError(theme, text) : themeDim(theme, text)], { title, label: "subagent extend", error: text, theme, ...renderState, wrapped: true } ); } const lines = [ `task_id: ${details.task_id}`, `added: ${details.added_ms}ms ${resolveIcon("separator", "\xB7")} extensions remaining: ${details.extensions_remaining}` ]; if (expanded) { lines.push( themeDim(theme, `extensions used: ${details.extensions_used}`), themeDim(theme, `deadline_at: ${details.deadline_at}`) ); } else { lines.push(themeDim(theme, resolveExpandHint("to expand", context))); } return boxedComponent(lines, { title, label: "subagent extend", compact: { summary: [details.task_id], tail: [ `+${details.added_ms}ms`, `${details.extensions_remaining} left` ], body: [] }, theme, ...renderState, wrapped: true }); } ); // src/tools/subagent-extend.ts function createSubagentExtendTool(manager) { return { name: "subagent_extend", label: "Subagent Extend", description: "Extend a running task within its total time ceiling and extension count; require evidence of useful progress.", parameters: Type5.Object({ task_id: Type5.String(), extra_ms: Type5.Optional(Type5.Integer({ minimum: 1 })) }), renderShell: "self", async execute(_id, params, _signal, _onUpdate, ctx) { try { const result = manager.extendDeadline( params.task_id, params.extra_ms, sessionIdFromToolContext(ctx) ); return ok( `Extended ${result.task_id} by ${result.added_ms}ms; extensions remaining: ${result.extensions_remaining}.`, result ); } catch (error) { return fail(error); } }, renderCall: renderSubagentExtendCall, renderResult: renderSubagentExtendResult }; } // src/tools/subagent-list-agents.ts import { Type as Type6 } from "typebox"; // src/render/tools/subagent-list-agents.ts function modelLabel3(model) { return model ? `${model.provider}/${model.id}` : "default/current"; } function summary(agent, ui = false) { return `${agent.name} ${ui ? resolveIcon("separator", "\xB7") : "\xB7"} model: ${modelLabel3(agent.model)} ${ui ? resolveIcon("separator", "\xB7") : "\xB7"} effort: ${agent.effort ?? "default/current"}${agent.profileName && agent.profileName !== "default" ? ` \xB7 profile: ${agent.profileName}` : ""}${agent.warnings?.length ? ` \xB7 warning: ${agent.warnings.join(" ")}` : ""}`; } function formatSubagentList(agents, includeTools) { if (!agents.length) return "No subagents available."; return agents.map( (agent) => includeTools ? `${summary(agent)} \xB7 tools: ${agent.tools.join(", ") || "none"}` : summary(agent) ).join("\n"); } var renderSubagentListResult = iconAwareRenderer( function renderSubagentListResult2(result, options, theme, context) { const renderState = toolRenderState(result, options, context); const expanded = Boolean( typeof options === "object" && options !== null ? options.expanded : options ); const agents = Array.isArray(result?.details?.agents) ? result.details.agents : []; const archPrefix = themeFg(theme, "accent", agentIcon()); const title = `${archPrefix} ${themeTitle(theme, agents.length ? `subagents ${resolveIcon("separator", "\xB7")} ${agents.length} available` : "subagents")}`; const compact = { summary: agents.length ? [`${agents.length} available`] : [] }; const error = result?.content?.[0]?.text; if (!agents.length) { return boxedComponent([themeDim(theme, "No subagents available.")], { title, label: "subagents", error, compact, theme, ...renderState, wrapped: true }); } if (expanded) { const lines2 = agents.flatMap((agent) => [ summary(agent, true), themeDim(theme, ` tools: ${agent.tools.join(", ") || "none"}`) ]); return boxedComponent(lines2, { title, label: "subagents", error, compact, theme, ...renderState, wrapped: true }); } const names = agents.map((a) => a.name); const sample = names.slice(0, 5).join(", "); const summaryLine = agents.length > 5 ? `agents: ${sample}, ${resolveIcon("ellipsis", "\u2026")} (${agents.length} total)` : `agents: ${sample}`; const lines = [ summaryLine, themeDim(theme, resolveExpandHint("to expand", context)) ]; return boxedComponent(lines, { title, label: "subagents", error, compact, theme, ...renderState, wrapped: true }); } ); // src/tools/subagent-list-agents.ts function createSubagentListAgentsTool(manager) { return { name: "subagent_list_agents", label: "Subagent List Agents", description: "List available markdown-defined subagents.", promptSnippet: "Sources: global/project agents and subagents directories.", parameters: Type6.Object({}), async execute(_id, _params, _signal, _onUpdate, ctx) { try { const agents = manager.listAgents(ctx?.cwd ?? process.cwd(), ctx); return ok(formatSubagentList(agents, true), { agents }); } catch (e) { return fail(e); } }, renderShell: "self", renderCall: () => emptyComponent(), renderResult: renderSubagentListResult }; } // src/tools/subagent-list-tasks.ts import { Type as Type7 } from "typebox"; // src/render/tools/subagent-list-tasks.ts var renderSubagentListTasksResult = iconAwareRenderer( function renderSubagentListTasksResult2(result, options, theme, context) { const renderState = toolRenderState(result, options, context); const isExpanded = Boolean( typeof options === "object" && options !== null ? options.expanded : options ); const tasks = Array.isArray(result?.details?.tasks) ? result.details.tasks : []; const archPrefix = themeFg(theme, "accent", agentIcon()); const title = `${archPrefix} ${themeTitle(theme, tasks.length ? `subagent tasks ${resolveIcon("separator", "\xB7")} ${tasks.length} listed` : "subagent tasks")}`; const text = formatTaskListRender(tasks, isExpanded, context); const lines = isExpanded ? text.split("\n") : (theme?.fg?.("dim", text) ?? text).split("\n"); return boxedComponent(lines, { title, label: "subagent tasks", compact: { summary: tasks.length ? [`${tasks.length} listed`] : [] }, error: result?.content?.[0]?.text, theme, ...renderState, wrapped: true }); } ); // src/tools/subagent-list-tasks.ts function createSubagentListTasksTool(manager, pi) { return { name: "subagent_list_tasks", label: "Subagent List Tasks", description: "List delegated subagent tasks.", parameters: Type7.Object({}), async execute(_id, _params, _signal, _onUpdate, ctx) { try { const available = continuationAvailable(ctx?.cwd ?? process.cwd(), pi); const cwd = ctx?.cwd ?? process.cwd(); const tasks = manager.listSessionTasks( cwd, sessionIdFromToolContext(ctx) ); const compactTasks = tasks.map( (task) => compactTaskWithoutFinalText(task, available) ); return ok(formatTaskListSummary(tasks), { tasks: compactTasks }); } catch (e) { return fail(e); } }, renderShell: "self", renderCall: () => emptyComponent(), renderResult: renderSubagentListTasksResult }; } // src/tools/subagent-reply.ts import { Type as Type8 } from "typebox"; // src/render/tools/subagent-reply.ts function renderSubagentReplyCall() { return emptyComponent(); } var renderSubagentReplyResult = iconAwareRenderer( function renderSubagentReplyResult2(result, options, theme, context) { const renderState = toolRenderState(result, options, context); const expanded = Boolean( typeof options === "object" && options !== null ? options.expanded : options ); const details = result?.details ?? {}; const rejected = Boolean(renderState.context.isError); const status = rejected ? "rejected" : "replied"; const text = result?.content?.[0]?.text ?? ""; const lines = [ details.task_id ? themeDim(theme, `task_id: ${details.task_id}`) : void 0, expanded && details.request_id ? themeDim(theme, `request_id: ${details.request_id}`) : void 0, rejected ? themeError(theme, text) : expanded ? text : themeDim(theme, clip(text, 60, true)), !expanded ? themeDim(theme, resolveExpandHint("to expand", context)) : void 0 ].filter(Boolean); return boxedComponent(lines, { title: `${themeFg(theme, "accent", agentIcon())} ${themeTitle(theme, `subagent reply ${resolveIcon("separator", "\xB7")} ${status}`)}`, label: "subagent reply", error: text, compact: { summary: [status, clip(firstLineOf(text) ?? "", 60, true)].filter( Boolean ), body: [] }, theme, ...renderState, wrapped: true }); } ); // src/tools/subagent-reply.ts function createSubagentReplyTool(manager) { return { name: "subagent_reply", label: "Subagent Reply", description: "Answer a pending ask_orchestrator question. Omit request_id only if the task has exactly one pending question.", parameters: Type8.Object({ task_id: Type8.String(), request_id: Type8.Optional(Type8.String()), message: Type8.String() }), renderShell: "self", renderCall: renderSubagentReplyCall, renderResult: renderSubagentReplyResult, async execute(_id, params, _signal, _onUpdate, ctx) { try { const result = manager.replyToQuestion( sessionIdFromToolContext(ctx), params.task_id, params.request_id, params.message ); return ok( `Replied to task_id: ${result.task_id} \xB7 request_id: ${result.request_id}`, result ); } catch (error) { return fail(error); } } }; } // src/tools/subagent-result.ts import { Type as Type9 } from "typebox"; // src/render/tools/subagent-result.ts var renderSubagentResult = iconAwareRenderer( function renderSubagentResult2(result, options, theme, context) { const renderState = toolRenderState(result, options, context); const { expanded } = options ?? {}; const task = taskFromDetails(result); const failed = Boolean( renderState.context.isError || task?.status === "failed" || task?.status === "cancelled" ); const isRunning = task?.status === "running" || task?.status === "queued"; const hasResp = hasAgentResponse(task, result); const responseText = taskResponseText(task, result); const archPrefix = task ? themeStatus(theme, task.status, statusGlyph(task.status)) : themeFg(theme, "accent", agentIcon()); if (!task) { const text = theme.fg?.( failed ? "error" : "dim", result?.content?.[0]?.text ?? "" ) ?? result?.content?.[0]?.text ?? ""; const titleText = hasResp ? "Subagent result" : "Subagent"; const title2 = `${archPrefix} ${theme.fg?.("toolTitle", titleText) ?? titleText}`; return boxedComponent([text], { title: title2, label: titleText, error: result?.content?.[0]?.text, theme, ...renderState, wrapped: true }); } const status = failed ? theme.fg?.("error", task.status) ?? task.status : theme.fg?.("success", task.status) ?? task.status; const taskLabel = formatTaskLabel(task, true); const isBg = task.mode === "background" || task.effective_mode === "background" || result?.details?.mode === "background"; const bgSuffix = isBg ? " (background)" : ""; let title; let label; if (isRunning) { const agentOrName = task.display_name || task.agent || "subagent"; label = `Subagent ${resolveIcon("separator", "\xB7")} ${agentOrName} ${resolveIcon("separator", "\xB7")} ${task.status}${bgSuffix}`; } else if (hasResp) { label = `Subagent result ${resolveIcon("separator", "\xB7")} ${taskLabel}`; } else { label = `Subagent ${resolveIcon("separator", "\xB7")} ${taskLabel}`; } title = `${archPrefix} ${theme.fg?.("toolTitle", label) ?? label}`; if (!expanded) { const metaLine = `subagent: ${theme.fg?.("accent", task.agent) ?? task.agent} ${resolveIcon("separator", "\xB7")} model: ${task.model ?? "default/current"} ${resolveIcon("separator", "\xB7")} effort: ${task.effort ?? "default/current"} ${resolveIcon("separator", "\xB7")} status: ${status}`; const expandHint = resolveExpandHint("to expand", context); const lines = [metaLine, theme.fg?.("dim", expandHint) ?? expandHint]; const compactError = failed ? firstLineOf( task.error || (renderState.context.isError ? result?.content?.[0]?.text : void 0) ) : void 0; const compactDetail = compactError ?? firstLineOf(responseText); return boxedComponent(lines, { title, theme, ...renderState, label: hasResp && !isRunning ? "Subagent result" : "Subagent", error: compactError, compact: { summary: [formatTaskSummary(task), task.model, task.effort].filter( Boolean ), body: compactDetail ? [ compactError ? theme.fg?.("error", compactDetail) ?? compactDetail : compactDetail ] : [] }, wrapped: true }); } const usage = formatUsage(task, true); const summaryLines = [ `subagent: ${theme.fg?.("accent", task.agent) ?? task.agent} ${resolveIcon("separator", "\xB7")} status: ${status} ${resolveIcon("separator", "\xB7")} attempt: ${task.attempt ?? 1}`, theme.fg?.("dim", modelEffortLine(task, true)) ?? modelEffortLine(task, true), usage ? theme.fg?.("dim", `usage: ${usage}`) ?? `usage: ${usage}` : void 0, task.undelivered_message_count ? theme.fg?.( "dim", `undelivered messages: ${task.undelivered_message_count}` ) ?? `undelivered messages: ${task.undelivered_message_count}` : void 0 ].filter(Boolean); const contentLines = [...summaryLines]; if (hasResp && responseText) { contentLines.push( theme.fg?.("toolTitle", "Subagent response") ?? "Subagent response", ...responseText.split("\n") ); } else if (failed && task.error) { contentLines.push( theme.fg?.("error", "Subagent error") ?? "Subagent error", ...task.error.split("\n") ); } return boxedComponent(contentLines, { title, theme, ...renderState, wrapped: true, onClick: task?.id ? () => openSubagentsPanel(task.id) : void 0 }); } ); // src/tools/subagent-result.ts function createSubagentResultTool(manager, pi) { return { name: "subagent_result", label: "Subagent Result", description: "Read a task result.", parameters: Type9.Object({ task_id: Type9.String() }), renderShell: "self", async execute(toolCallId, params, _signal, _onUpdate, ctx) { try { const task = manager.getTask(params.task_id, ctx?.cwd ?? process.cwd()); if (!task) throw new Error("Subagent task not found"); const continueAvailable = continuationAvailable( ctx?.cwd ?? process.cwd(), pi ); const fullResult = totalTimeoutResult(task, continueAvailable) ?? task.result ?? task.error ?? task.output_preview ?? formatTask(task); const content = [toolSelectionWarning(task), fullResult].filter(Boolean).join("\n\n"); const response = ok(content, { task: compactTaskForToolResult(task, continueAvailable), full_result: fullResult }); manager.stageResultAcknowledgment(toolCallId, task, response.content); return response; } catch (e) { return fail(e); } }, renderCall: () => emptyComponent(), renderResult: renderSubagentResult }; } // src/tools/subagent-send-message.ts import { Type as Type10 } from "typebox"; // src/render/tools/subagent-send-message.ts function renderSubagentSendMessageCall(_args, _theme) { return emptyComponent(); } var renderSubagentSendMessageResult = iconAwareRenderer( function renderSubagentSendMessageResult2(result, options, theme, context) { const renderState = toolRenderState(result, options, context); const expanded = Boolean( typeof options === "object" && options !== null ? options.expanded : options ); const details = result?.details ?? {}; const status = details?.status ?? (renderState.context.isError ? "rejected" : "queued"); const isRejected = status === "rejected" || Boolean(renderState.context.isError); const archPrefix = themeFg(theme, "accent", agentIcon()); const statusStyled = isRejected ? themeError(theme, status) : themeSuccess(theme, status); const title = `${archPrefix} ${themeTitle(theme, `subagent send message ${resolveIcon("separator", "\xB7")} ${status}`)}`; const taskId2 = details?.task_id; const errorText = result?.content?.[0]?.text ?? details?.reason; const msgText = details?.message ?? result?.content?.[0]?.text ?? ""; if (!expanded) { const lines = [ taskId2 ? `task_id: ${taskId2} ${resolveIcon("separator", "\xB7")} status: ${statusStyled}` : `status: ${statusStyled}`, msgText ? themeDim(theme, `message: ${clip(msgText, 60, true)}`) : void 0, themeDim(theme, resolveExpandHint("to expand", context)) ].filter(Boolean); return boxedComponent(lines, { title, label: "subagent send message", error: isRejected ? errorText : void 0, compact: { summary: [ status, taskId2, msgText ? clip(firstLineOf(msgText) ?? "", 60, true) : void 0 ].filter(Boolean), body: [] }, theme, ...renderState, wrapped: true }); } const metaLines = [ taskId2 ? `task_id: ${taskId2} ${resolveIcon("separator", "\xB7")} status: ${statusStyled}` : `status: ${statusStyled}`, details?.reason ? themeDim(theme, `reason: ${details.reason}`) : void 0, details?.pending_message_count !== void 0 ? themeDim(theme, `pending messages: ${details.pending_message_count}`) : void 0 ].filter(Boolean); const contentLines = [...metaLines]; if (msgText) { contentLines.push( themeTitle(theme, "Message"), ...String(msgText).split("\n") ); } return boxedComponent(contentLines, { title, label: "subagent send message", error: isRejected ? errorText : void 0, theme, ...renderState, wrapped: true }); } ); // src/tools/subagent-send-message.ts function createSubagentSendMessageTool(manager) { return { name: "subagent_send_message", label: "Subagent Send Message", description: "Queue live steering for a running background task.", parameters: Type10.Object({ task_id: Type10.String(), message: Type10.String() }), renderShell: "self", async execute(_id, params, _signal, _onUpdate, ctx) { try { const result = await manager.sendMessage({ task_id: params.task_id, message: params.message, session_id: sessionIdFromToolContext(ctx) }); const text = `${result.status}: ${result.message}`; return ok(text, result); } catch (error) { return fail(error); } }, renderCall: renderSubagentSendMessageCall, renderResult: renderSubagentSendMessageResult }; } // src/tools/subagent-status.ts import { Type as Type11 } from "typebox"; // src/render/tools/subagent-status.ts function renderSubagentStatusCall(_args, _theme) { return emptyComponent(); } var renderSubagentStatusResult = iconAwareRenderer( function renderSubagentStatusResult2(result, options, theme, context) { const renderState = toolRenderState(result, options, context); const expanded = Boolean( typeof options === "object" && options !== null ? options.expanded : options ); const task = taskFromDetails(result); const failed = Boolean( renderState.context.isError || task?.status === "failed" || task?.status === "cancelled" ); const archPrefix = task ? themeStatus(theme, task.status, statusGlyph(task.status)) : themeFg(theme, "accent", agentIcon()); if (!task) { const title2 = `${archPrefix} ${themeTitle(theme, failed ? `subagent status ${resolveIcon("separator", "\xB7")} failed` : "subagent status")}`; const text = result?.content?.[0]?.text ?? (failed ? "Subagent task not found" : ""); return boxedComponent( [failed ? themeError(theme, text) : themeDim(theme, text)], { title: title2, label: "subagent status", error: text, theme, ...renderState, wrapped: true } ); } const taskLabel = formatTaskLabel(task, true); const statusText = task.status ?? (failed ? "failed" : "unknown"); const status = failed ? themeError(theme, statusText) : themeStatus(theme, statusText); const isBg = task.mode === "background" || task.effective_mode === "background" || result?.details?.mode === "background"; const bgSuffix = isBg ? " (background)" : ""; const label = `subagent status ${resolveIcon("separator", "\xB7")} ${taskLabel} ${resolveIcon("separator", "\xB7")} ${statusText}${bgSuffix}`; const title = `${archPrefix} ${themeTitle(theme, label)}`; if (!expanded) { const metaLine = `subagent: ${themeAccent(theme, task.agent)} ${resolveIcon("separator", "\xB7")} model: ${task.model ?? "default/current"} ${resolveIcon("separator", "\xB7")} effort: ${themeAccent(theme, task.effort ?? "default/current")} ${resolveIcon("separator", "\xB7")} status: ${status}`; const lines = [ metaLine, themeDim(theme, resolveExpandHint("to expand", context)) ]; const compactError = failed ? firstLineOf( task.error || (renderState.context.isError ? result?.content?.[0]?.text : void 0) ) : void 0; return boxedComponent(lines, { title, theme, ...renderState, label: "subagent status", error: compactError, compact: { summary: [formatTaskSummary(task), task.model, task.effort].filter( Boolean ), body: compactError ? [themeError(theme, compactError)] : [] }, wrapped: true }); } const usage = formatUsage(task, true); const when = task.last_activity_at ?? task.started_at ?? task.created_at; const metaLines = [ `subagent: ${themeAccent(theme, task.agent)} ${resolveIcon("separator", "\xB7")} status: ${status} ${resolveIcon("separator", "\xB7")} attempt: ${themeAccent(theme, String(task.attempt ?? 1))} ${resolveIcon("separator", "\xB7")} effort: ${themeAccent(theme, task.effort ?? "default/current")}`, themeDim(theme, `model: ${task.model ?? "default/current"}`), usage ? themeDim(theme, `usage: ${usage}`) : void 0, task.pending_message_count ? themeDim(theme, `pending messages: ${task.pending_message_count}`) : void 0, task.undelivered_message_count ? themeDim( theme, `undelivered messages: ${task.undelivered_message_count}` ) : void 0, task.last_activity ? themeDim( theme, `last: ${task.last_activity}${when ? ` at ${when}` : ""}` ) : void 0 ].filter(Boolean); const contentLines = [...metaLines]; const hasResp = hasAgentResponse(task, result); const responseText = taskResponseText(task, result); if (hasResp && responseText) { contentLines.push( themeTitle(theme, "Subagent response"), ...responseText.split("\n") ); } else if (failed && task.error) { contentLines.push( themeError(theme, "Subagent error"), ...task.error.split("\n") ); } else if (task.output_preview) { contentLines.push( themeDim(theme, `preview: ${clip(task.output_preview, 240, true)}`) ); } return boxedComponent(contentLines, { title, theme, ...renderState, wrapped: true, onClick: task?.id ? () => openSubagentsPanel(task.id) : void 0 }); } ); // src/tools/subagent-status.ts function createSubagentStatusTool(manager, pi) { return { name: "subagent_status", label: "Subagent Status", description: "Get task status.", parameters: Type11.Object({ task_id: Type11.String() }), renderShell: "self", async execute(_id, params, _signal, _onUpdate, ctx) { try { const available = continuationAvailable(ctx?.cwd ?? process.cwd(), pi); const task = manager.getTask(params.task_id, ctx?.cwd ?? process.cwd()); if (!task) throw new Error("Subagent task not found"); return ok(formatTask(task), { task: compactTaskForToolResult(task, available) }); } catch (e) { return fail(e); } }, renderCall: renderSubagentStatusCall, renderResult: renderSubagentStatusResult }; } // src/tools/registry.ts function registerSubagentTools(pi, manager, cwd = process.cwd()) { const registerTool = (tool) => { pi.registerTool({ ...tool, exposure: "model-only" }); }; const config = readSubagentsConfig(cwd); registerTool(createSubagentListAgentsTool(manager)); registerTool(createSubagentRunTool(manager, pi)); if (config.enable_continue) registerTool(createSubagentContinueTool(manager, pi)); registerTool(createSubagentStatusTool(manager, pi)); registerTool(createSubagentResultTool(manager, pi)); registerTool(createSubagentListTasksTool(manager, pi)); registerTool(createSubagentCancelTool(manager, pi)); registerTool(createSubagentSendMessageTool(manager)); registerTool(createSubagentExtendTool(manager)); if (config.enable_ask_orchestrator) registerTool(createSubagentReplyTool(manager)); } // src/tools-panel/config.ts import { existsSync, readdirSync, readFileSync } from "node:fs"; import { homedir } from "node:os"; import { join as join2, resolve as resolve2 } from "node:path"; // src/tools-panel/frontmatter.ts import { createRequire as createRequire4 } from "node:module"; import { join } from "node:path"; import { getPackageDir as getPackageDir2 } from "@earendil-works/pi-coding-agent"; var yaml2 = (() => { try { return createRequire4(join(getPackageDir2(), "package.json"))( "yaml" ); } catch { return void 0; } })(); var { isAlias, isMap, isScalar, isSeq, parseDocument } = yaml2 ?? {}; function parseFrontmatter(content) { if (!yaml2) throw new Error( "YAML frontmatter validation is unavailable; no files were changed." ); const match = /^(?:\uFEFF)?---[^\S\r\n]*(?:#[^\r\n]*)?\r?\n([\s\S]*?)\r?\n---[^\S\r\n]*(?:#[^\r\n]*)?(?=\r?\n|$)/.exec( content ); if (!match) throw new Error("Subagent has malformed frontmatter."); const source = match[1] ?? ""; const blockStart = /^(?:\uFEFF)?---[^\S\r\n]*(?:#[^\r\n]*)?\r?\n/.exec( content )?.[0].length; if (blockStart === void 0) throw new Error("Subagent has malformed frontmatter."); const document = parseDocument(source, { keepSourceTokens: true, merge: false, strict: true, stringKeys: true, uniqueKeys: true }); const mapping = document.contents; if (isMap(mapping)) { for (const name of ["tools", "disallowed_tools"]) { const occurrences = mapping.items.filter( ({ key: key3 }) => isScalar(key3) && key3.value === name ); if (occurrences.length > 1) throw new Error(`Duplicate ${name} fields in Subagent frontmatter.`); } } const problem = document.errors[0] ?? document.warnings[0]; if (problem) throw new Error(`Invalid Subagent YAML frontmatter: ${problem.message}`); if (!isMap(mapping)) throw new Error("Subagent frontmatter must be a YAML mapping."); assertSupportedYamlFeatures(mapping); return { source, blockStart, mapping }; } function assertSupportedYamlFeatures(node) { if (isAlias(node)) throw new Error( "Unsupported YAML aliases in Subagent frontmatter; replace aliases with explicit values." ); if (isScalar(node)) { if (node.anchor) throw new Error( "Unsupported YAML anchors in Subagent frontmatter; replace anchors with explicit values." ); if (node.tag) throw new Error( "Unsupported YAML tags in Subagent frontmatter; use standard untagged values." ); return; } if (isSeq(node)) { if (node.anchor) throw new Error( "Unsupported YAML anchors in Subagent frontmatter; replace anchors with explicit values." ); if (node.tag) throw new Error( "Unsupported YAML tags in Subagent frontmatter; use standard untagged values." ); for (const item of node.items) assertSupportedYamlFeatures(item); return; } if (isMap(node)) { if (node.anchor) throw new Error( "Unsupported YAML anchors in Subagent frontmatter; replace anchors with explicit values." ); if (node.tag) throw new Error( "Unsupported YAML tags in Subagent frontmatter; use standard untagged values." ); for (const { key: key3, value: value3 } of node.items) { if (isScalar(key3) && key3.value === "<<") throw new Error( "Unsupported YAML merge keys in Subagent frontmatter; replace merges with explicit values." ); assertSupportedYamlFeatures(key3); assertSupportedYamlFeatures(value3); } } } function fieldPair(mapping, name) { return mapping.items.find(({ key: key3 }) => isScalar(key3) && key3.value === name); } function scalarString(node, name, source) { if (!isScalar(node) || typeof node.value !== "string") throw new Error(`${name} must be a YAML string scalar.`); const range = node.range; if (!range || !node.srcToken || range[0] < 0 || range[1] < range[0] || range[2] < range[1] || range[2] > source.length) throw new Error( `Cannot safely read ${name} without its YAML source range.` ); const raw = source.slice(range[0], range[1]); if (/[\r\n]/.test(raw) || /[\r\n]/.test(node.value)) throw new Error( `Malformed ${name} scalar continuation in Subagent frontmatter.` ); return node.value; } function sourceRange(node, source) { if (!node || typeof node !== "object" || !("range" in node)) throw new Error( "Cannot safely edit this Subagent YAML value without source ranges." ); const range = node.range; const sourceTokens = "srcToken" in node ? node.srcToken : void 0; if (!Array.isArray(range) || !sourceTokens || range.length < 3 || !range.every(Number.isInteger) || range[0] < 0 || range[1] < range[0] || range[2] < range[1] || range[2] > source.length) throw new Error( "Cannot safely edit this Subagent YAML value using its source range." ); let end = range[1]; if (isSeq(node) && !node.flow) { const trailingNewline = source.slice(range[0], end).match(/\r?\n$/)?.[0]; if (trailingNewline) end -= trailingNewline.length; } return [range[0], end]; } function validateTools(tools) { if (!Array.isArray(tools) || tools.length === 0) throw new Error("Select at least one Subagent tool name or glob."); if (tools.includes("@active")) throw new Error( "Subagent tool selector @active is no longer supported; select exact tool names instead." ); const seen = /* @__PURE__ */ new Set(); for (const tool of tools) { if (typeof tool !== "string" || !tool || tool.trim() !== tool || /[\s,]/.test(tool)) throw new Error(`Invalid Subagent tool name or glob: ${String(tool)}.`); const normalized = tool.toLowerCase(); if (!/[*?[\]{}]/.test(tool) && normalized.startsWith("subagent_")) throw new Error(`Pi delegation tool names are not allowed: ${tool}.`); if (seen.has(tool)) throw new Error(`Duplicate Subagent tool name: ${tool}.`); seen.add(tool); } } function parseToolsField(mapping, source) { const pair = fieldPair(mapping, "tools"); if (!pair) return { present: false }; if (pair.value === null) throw new Error("The tools field must contain an explicit list."); let tools; if (isSeq(pair.value)) { tools = pair.value.items.map((item) => scalarString(item, "tools", source)); } else if (isScalar(pair.value)) { tools = scalarString(pair.value, "tools", source).split(",").map((tool) => tool.trim()); } else { throw new Error("The tools field must be a string or a list of strings."); } if (tools.length) validateTools(tools); return { present: true, tools }; } function parseDisallowedToolsField(mapping, source) { const pair = fieldPair(mapping, "disallowed_tools"); if (!pair) return void 0; if (isScalar(pair.value) && pair.value.value === null && pair.value.source === "") return []; const value3 = isSeq(pair.value) ? pair.value.items.map( (item) => scalarString(item, "disallowed_tools", source) ) : scalarString(pair.value, "disallowed_tools", source); const names = typeof value3 === "string" ? value3 === "" ? [] : value3.split(",") : value3; const tools = names.map((name) => name.trim()); for (const tool of tools) { if (!/^[a-zA-Z0-9_.:-]+$/.test(tool)) throw new Error( `disallowed_tools must contain exact Subagent tool names: ${tool}.` ); } return [...new Set(tools)]; } function readToolsFields(content) { if (!/^(?:\uFEFF)?---/.test(content)) return {}; const { mapping, source } = parseFrontmatter(content); const parsedTools = parseToolsField(mapping, source); const disallowedTools = parseDisallowedToolsField(mapping, source); return { ...parsedTools.present ? { tools: parsedTools.tools } : {}, ...disallowedTools !== void 0 ? { disallowedTools } : {} }; } function replaceToolsField(content, tools) { if (!/^(?:\uFEFF)?---/.test(content)) { const newline = content.includes("\r\n") ? "\r\n" : "\n"; return `---${newline}tools: ${JSON.stringify(tools.join(", "))}${newline}---${newline}${content}`; } const parsed = parseFrontmatter(content); const pair = fieldPair(parsed.mapping, "tools"); const rendered = JSON.stringify(tools.join(", ")); if (!pair) { if (parsed.mapping.flow) throw new Error( "Cannot safely add tools to a flow-style Subagent frontmatter mapping." ); const newline = parsed.source.match(/\r?\n/)?.[0] ?? (content.includes("\r\n") ? "\r\n" : "\n"); return `${content.slice(0, parsed.blockStart)}tools: ${rendered}${newline}${content.slice(parsed.blockStart)}`; } if (pair.value === null) throw new Error("The tools field must contain an explicit list."); let [start, end] = sourceRange(pair.value, parsed.source); let replacement = rendered; const explicitKey = pair.srcToken && "explicitKey" in pair.srcToken && pair.srcToken.explicitKey === true; if (isSeq(pair.value) && !pair.value.flow && !explicitKey) { const [keyStart, keyEnd] = sourceRange(pair.key, parsed.source); start = keyStart; replacement = `${parsed.source.slice(keyStart, keyEnd)}: ${rendered}`; } const next = content.slice(0, parsed.blockStart + start) + replacement + content.slice(parsed.blockStart + end); const verifiedTools = readToolsFields(next).tools; if (JSON.stringify(verifiedTools) !== JSON.stringify(tools)) throw new Error( "Cannot safely replace the tools field without changing its parsed value." ); return next; } function nonToolsDifferences(copy, global) { const fields = (content) => { if (!/^(?:\uFEFF)?---/.test(content)) return { data: {}, body: content }; const parsed = parseFrontmatter(content); const closing = content.slice(parsed.blockStart + parsed.source.length).match(/^\r?\n---[^\r\n]*(?:\r?\n|$)/); return { data: parsed.mapping.toJSON(), body: content.slice( parsed.blockStart + parsed.source.length + (closing?.[0].length ?? 0) ) }; }; const left = fields(copy); const right = fields(global); const differences = []; const frontmatter = []; for (const key3 of /* @__PURE__ */ new Set([ ...Object.keys(left.data), ...Object.keys(right.data) ])) { if (key3 === "tools" || JSON.stringify(left.data[key3]) === JSON.stringify(right.data[key3])) continue; if (key3 === "description") differences.push("description differs"); else frontmatter.push(key3); } if (frontmatter.length) differences.push(`frontmatter: ${frontmatter.join(", ")}`); if (left.body !== right.body) differences.push("instructions (body) differ"); return differences; } // src/tools-panel/registry.ts var toolsPanelRegistryKey = /* @__PURE__ */ Symbol.for( "thoth-agents.pi-subagents.tools-panel.v1" ); var shared11 = globalThis; function getToolsPanelRegistry() { try { const registry5 = shared11[toolsPanelRegistryKey]; return registry5?.version === 1 ? registry5 : void 0; } catch { return void 0; } } function getToolsPanelAdapter() { try { const adapter = getToolsPanelRegistry()?.adapter; return adapter?.version === 1 && typeof adapter.appliesTo === "function" && typeof adapter.validate === "function" && (adapter.defaultTools === void 0 || typeof adapter.defaultTools === "function") ? adapter : void 0; } catch { return void 0; } } function publishToolsPanelCapability() { shared11[toolsPanelRegistryKey] = { ...getToolsPanelRegistry(), version: 1, capability: { version: 1, command: "subagents-tools" } }; } // src/tools-panel/write.ts import { randomUUID as randomUUID3 } from "node:crypto"; import fs13 from "node:fs"; import { dirname, parse, resolve } from "node:path"; function lstatIfPresent(path11) { try { return fs13.lstatSync(path11); } catch (error) { if (error.code === "ENOENT") return void 0; throw error; } } function snapshot(path11) { const present = lstatIfPresent(path11); if (!present) return { exists: false }; const stat = fs13.lstatSync(path11, { bigint: true }); return { exists: true, dev: stat.dev, ino: stat.ino, size: Number(stat.size), mtimeMs: Number(stat.mtimeMs), content: fs13.readFileSync(path11) }; } function snapshotsEqual(left, right) { return left.exists === right.exists && left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && (left.content === void 0 ? right.content === void 0 : right.content !== void 0 && left.content.equals(right.content)); } function assertSafeDefinitionPath(path11) { const absolute = resolve(path11); const root = parse(absolute).root; const ancestors = []; let cursor = dirname(absolute); while (cursor !== root) { ancestors.push(cursor); cursor = dirname(cursor); } ancestors.push(root); for (const ancestor of ancestors.reverse()) { const stat = lstatIfPresent(ancestor); if (!stat) continue; if (stat.isSymbolicLink()) throw new Error(`Subagent path has a symlinked parent: ${ancestor}`); if (!stat.isDirectory()) throw new Error(`Subagent path parent is not a directory: ${ancestor}`); } const target = lstatIfPresent(absolute); if (!target) return; if (target.isSymbolicLink()) throw new Error(`Subagent target is a symlink: ${absolute}`); if (!target.isFile()) throw new Error(`Subagent target is not a regular file: ${absolute}`); } function writeDefinitionText(path11, content, expectedBefore) { assertSafeDefinitionPath(path11); const before = snapshot(path11); if (expectedBefore !== void 0 && (expectedBefore === null ? before.exists : !before.content?.equals(Buffer.from(expectedBefore)))) throw new Error(`Subagent target changed since preflight: ${path11}`); const desired = Buffer.from(content); if (before.content?.equals(desired)) return false; fs13.mkdirSync(dirname(path11), { recursive: true }); assertSafeDefinitionPath(path11); const nonce = `${process.pid}-${randomUUID3()}`; const temporaryPath = `${path11}.tmp-${nonce}`; const backupPath = `${path11}.bak-${nonce}`; fs13.writeFileSync(temporaryPath, desired, { flag: "wx" }); try { assertSafeDefinitionPath(path11); if (!snapshotsEqual(before, snapshot(path11))) throw new Error(`Subagent target changed before replacement: ${path11}`); if (before.exists) fs13.copyFileSync(path11, backupPath, fs13.constants.COPYFILE_EXCL); const maxAttempts = process.platform === "win32" ? 11 : 1; for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { assertSafeDefinitionPath(path11); if (!snapshotsEqual(before, snapshot(path11))) throw new Error(`Subagent target changed before replacement: ${path11}`); try { fs13.renameSync(temporaryPath, path11); break; } catch (error) { const code = error.code; if (process.platform !== "win32" || !["EPERM", "EACCES", "EBUSY"].includes(code ?? "")) throw error; if (attempt === maxAttempts) throw new Error( `Cannot replace subagent file ${path11} (${code}) after bounded retries. The original file was not replaced. Close applications holding this file, check its permissions, and reopen /subagents-tools.`, { cause: error } ); Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100); } } } catch (error) { fs13.rmSync(temporaryPath, { force: true }); throw error; } return true; } function writeProjectOverlayText(cwd, content, expected) { const path11 = resolve(cwd, ".pi", "subagents.json"); assertSafeDefinitionPath(path11); if (content === null) { if (snapshot(path11).exists) throw new Error(`Subagent target changed since preflight: ${path11}`); return false; } return writeDefinitionText(path11, content, expected); } function retireDefinitionText(path11, expected, io = fs13) { assertSafeDefinitionPath(path11); const before = snapshot(path11); if (!before.content?.equals(Buffer.from(expected))) throw new Error(`Subagent target changed since preflight: ${path11}`); const backup = `${path11}.bak-${process.pid}-${randomUUID3()}`; fs13.writeFileSync(backup, "", { flag: "wx" }); const reservation = snapshot(backup); try { const maxAttempts = process.platform === "win32" ? 11 : 1; for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { assertSafeDefinitionPath(path11); assertSafeDefinitionPath(backup); if (!snapshotsEqual(before, snapshot(path11))) throw new Error(`Subagent target changed before retirement: ${path11}`); if (!snapshotsEqual(reservation, snapshot(backup))) throw new Error(`Subagent backup reservation changed: ${backup}`); try { io.renameSync(path11, backup); return backup; } catch (error) { const code = error.code; if (process.platform !== "win32" || !["EPERM", "EACCES", "EBUSY"].includes(code ?? "") || attempt === maxAttempts) throw error; Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100); } } throw new Error(`Cannot retire subagent file: ${path11}`); } catch (error) { if (snapshotsEqual(reservation, snapshot(backup))) fs13.rmSync(backup); throw error; } } // src/tools-panel/config.ts function globalDefinitions(cwd) { const global = /* @__PURE__ */ new Map(); for (const source of agentsDirSources(cwd).filter( (source2) => source2.scope === "global" )) { const blocked = /* @__PURE__ */ new Set(); for (const definition of loadSubagentsFromDir( source.dir, source.scope, (entry) => blocked.add(entry.name) )) global.set(definition.name, definition); for (const name of blocked) global.delete(name); } const defaults = readSubagentsConfig(cwd).default_tools; for (const definition of global.values()) if (!definition.tools.length) definition.tools = [...defaults]; return [...global.values()].sort((a, b) => a.name.localeCompare(b.name)); } function readToolsConfig(cwd) { const resolved = loadSubagents(cwd); const config = readSubagentsConfig(cwd); const snapshot2 = { enableAskOrchestrator: config.enable_ask_orchestrator, enableNotifyOrchestrator: config.enable_notify_orchestrator, cwd: resolve2(cwd), piRoot: resolve2( process.env.PI_CODING_AGENT_DIR || join2(homedir(), ".pi", "agent") ), roles: [], contents: {} }; const adapter = getToolsPanelAdapter(); const collect = (definitions) => { const roles = []; const contents = {}; const adapters = {}; for (const definition of definitions) { const target = { role: definition.name, filePath: resolve2(definition.filePath), scope: definition.scope ?? "global" }; assertSafeDefinitionPath(target.filePath); const content = readFileSync(target.filePath, "utf8"); const fields = readToolsFields(content); const managed = adapter?.appliesTo(target, content) ? adapter : void 0; managed?.validate(target, content); const defaults = managed?.defaultTools?.(target, content); if (defaults) validateTools(defaults); contents[target.role] = content; if (managed) adapters[target.role] = managed; roles.push({ ...target, // Preserve explicit entries even when runtime filtering excludes them. tools: [...fields.tools?.length ? fields.tools : definition.tools], ...defaults ? { defaultTools: [...defaults] } : {}, disallowedTools: fields.disallowedTools ?? [], ...definition.toolOverlay ? { overlay: structuredClone(definition.toolOverlay) } : {} }); } return { roles, contents, adapters }; }; const global = collect(globalDefinitions(cwd)); snapshot2.globalRoles = global.roles; snapshot2.globalContents = global.contents; snapshot2.globalAdapters = global.adapters; Object.assign(snapshot2, collect(resolved)); for (const role of snapshot2.globalRoles) { const winner = snapshot2.roles.find((entry) => entry.role === role.role); if (winner?.scope === "project") role.shadowedBy = winner.filePath; } const configPath = join2(snapshot2.cwd, ".pi", "subagents.json"); assertSafeDefinitionPath(configPath); try { snapshot2.projectConfigContent = readFileSync(configPath, "utf8"); } catch (error) { if (error.code !== "ENOENT") throw error; snapshot2.projectConfigContent = null; } const raw = snapshot2.projectConfigContent === null ? {} : JSON.parse(snapshot2.projectConfigContent); snapshot2.initialScope = raw.agents && typeof raw.agents === "object" && Object.keys(raw.agents).length > 0 || snapshot2.globalRoles.some((role) => role.shadowedBy) ? "project" : "global"; return snapshot2; } function currentContent(snapshot2, target) { assertSafeDefinitionPath(target.filePath); const content = readFileSync(target.filePath, "utf8"); readToolsFields(content); const registered = getToolsPanelAdapter(); const adapter = snapshot2.adapters?.[target.role] ?? (registered?.appliesTo(target, content) ? registered : void 0); adapter?.validate(target, content); return content; } function saveToolsConfig(snapshot2, inputs) { if (snapshot2.editScope === "project") return saveProjectToolsConfig(snapshot2, inputs); if (snapshot2.editScope === "global" && snapshot2.globalRoles) { const globalSnapshot = { ...snapshot2, roles: snapshot2.globalRoles, contents: snapshot2.globalContents ?? {}, adapters: snapshot2.globalAdapters }; const result = saveDefinitionToolsConfig(globalSnapshot, inputs, true); const roles = structuredClone(snapshot2.roles); const contents = { ...snapshot2.contents }; for (const name of result.changedRoles) { const effective = roles.find((role) => role.role === name); const global = result.snapshot.roles.find((role) => role.role === name); const content = result.snapshot.contents[name]; if (effective && global && effective.filePath === global.filePath && content !== void 0) { effective.tools = [...global.tools]; contents[name] = content; } } return { ...result, snapshot: { ...snapshot2, globalRoles: result.snapshot.roles, globalContents: result.snapshot.contents, roles, contents } }; } return saveDefinitionToolsConfig(snapshot2, inputs); } function saveDefinitionToolsConfig(snapshot2, inputs, globalOnly = false) { const nextSnapshot = { ...snapshot2, roles: structuredClone(snapshot2.roles), contents: { ...snapshot2.contents } }; const changedRoles = []; try { const resolved = globalOnly ? globalDefinitions(snapshot2.cwd) : loadSubagents(snapshot2.cwd); const seen = /* @__PURE__ */ new Set(); const preflight = []; for (const input of inputs) { if (seen.has(input.role)) throw new Error(`Duplicate subagent: ${input.role}`); seen.add(input.role); validateTools(input.tools); const target = snapshot2.roles.find(({ role }) => role === input.role); const expected = snapshot2.contents[input.role]; if (!target || expected === void 0) throw new Error(`Missing definition snapshot: ${input.role}`); if (!resolved.some( (definition) => definition.name === input.role && resolve2(definition.filePath) === target.filePath )) throw new Error( `Subagent resolution changed since opening: ${input.role}. Reopen the editor.` ); if (currentContent(snapshot2, target) !== expected) throw new Error( `Subagent changed since opening: ${input.role}. Reopen the editor before saving.` ); preflight.push({ input, target, expected }); } for (const { input, target, expected } of preflight) { if (JSON.stringify(target.tools) === JSON.stringify(input.tools)) continue; const next = replaceToolsField(expected, input.tools); if (currentContent(snapshot2, target) !== expected) throw new Error( `Subagent changed before saving: ${input.role}. Reopen the editor.` ); if (writeDefinitionText(target.filePath, next, expected)) changedRoles.push(input.role); nextSnapshot.contents[input.role] = next; nextSnapshot.roles = nextSnapshot.roles.map( (role) => role.role === input.role ? { ...role, tools: [...input.tools] } : role ); } return { success: true, changedRoles, snapshot: nextSnapshot }; } catch (error) { return { success: false, changedRoles, snapshot: nextSnapshot, error: error instanceof Error ? error.message : String(error) }; } } function saveProjectToolsConfig(snapshot2, inputs, writeOverlay = writeProjectOverlayText) { try { const current = readToolsConfig(snapshot2.cwd); for (const { role } of inputs) { if (JSON.stringify(selectionDependencies(current, role)) !== JSON.stringify(selectionDependencies(snapshot2, role))) throw new Error( `Subagent resolution or configuration changed since opening: ${role}. Reopen the editor.` ); } const expected = snapshot2.projectConfigContent ?? null; const raw = expected === null ? {} : JSON.parse(expected); if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("Project subagents.json must be an object."); const agents = raw.agents ?? {}; if (!agents || typeof agents !== "object" || Array.isArray(agents)) throw new Error("Project agents must be an object."); const changedRoles = []; const roles = structuredClone(snapshot2.roles); const seen = /* @__PURE__ */ new Set(); for (const input of inputs) { if (seen.has(input.role)) throw new Error(`Duplicate subagent: ${input.role}`); seen.add(input.role); const role = roles.find((role2) => role2.role === input.role); if (!role) throw new Error(`Missing definition snapshot: ${input.role}`); const overlay = input.overlay ?? { add: [], remove: [] }; const parsed = parseToolOverlay(overlay, (message) => { throw new Error(message); }); if (!parsed) throw new Error("Invalid overlay"); if (JSON.stringify(role.overlay ?? { add: [], remove: [] }) === JSON.stringify(overlay)) continue; const agent = agents[input.role] ?? {}; if (!agent || typeof agent !== "object" || Array.isArray(agent)) throw new Error(`Invalid agent: ${input.role}`); if (overlay.add.length || overlay.remove.length) agent.tools = { ...agent.tools, add: [...overlay.add], remove: [...overlay.remove] }; else delete agent.tools; if (Object.keys(agent).length) agents[input.role] = agent; else delete agents[input.role]; role.overlay = structuredClone(overlay); changedRoles.push(input.role); } if (Object.keys(agents).length) raw.agents = agents; else delete raw.agents; const content = changedRoles.length ? `${JSON.stringify(raw, null, 2)} ` : expected; writeOverlay(snapshot2.cwd, content, expected); return { success: true, changedRoles, snapshot: { ...snapshot2, roles, projectConfigContent: content } }; } catch (error) { return { success: false, changedRoles: [], snapshot: snapshot2, error: error instanceof Error ? error.message : String(error) }; } } function selectionDependencies(snapshot2, name) { const role = snapshot2.roles.find((role2) => role2.role === name); return { piRoot: snapshot2.piRoot, role: role && { filePath: role.filePath, scope: role.scope, tools: role.tools, disallowedTools: role.disallowedTools }, content: snapshot2.contents[name], ask: snapshot2.enableAskOrchestrator ?? true, notify: snapshot2.enableNotifyOrchestrator ?? true }; } function conversionDependencies(snapshot2, name, inventory) { return JSON.stringify({ selection: selectionDependencies(snapshot2, name), global: snapshot2.globalRoles?.find((role) => role.role === name), globalContent: snapshot2.globalContents?.[name], projectConfig: snapshot2.projectConfigContent ?? null, inventory: [...new Set(inventory)].sort() }); } function prepareToolsConversion(snapshot2, name, inventory) { const copy = snapshot2.roles.find((role) => role.role === name); const global = snapshot2.globalRoles?.find((role) => role.role === name); if (copy?.scope !== "project" || !global) return { eligible: false, error: "Conversion requires a project copy with a global counterpart." }; for (const source of agentsDirSources(snapshot2.cwd).filter( (source2) => source2.scope === "project" )) { if (!existsSync(source.dir)) continue; if (readdirSync(source.dir).some( (file) => file.endsWith(".md") && file.slice(0, -3).trim().toLowerCase() === name && resolve2(source.dir, file) !== copy.filePath )) return { eligible: false, error: "Cannot convert: another same-name project definition would remain." }; } const copySelection = new Set(composeToolSelection(copy.tools, inventory)); const overlay = { add: copy.tools.filter((entry) => !global.tools.includes(entry)), remove: composeToolSelection(global.tools, inventory).filter( (name2) => !copySelection.has(name2) ) }; const effective = (role, selection) => resolveEffectiveToolSelection( role.tools, inventory, role.disallowedTools, snapshot2.enableAskOrchestrator ?? true, snapshot2.enableNotifyOrchestrator ?? true, selection ).sort(); const before = JSON.stringify(effective(copy, copy.overlay)); if (JSON.stringify(effective(global, overlay)) !== before) return { eligible: false, error: "Cannot convert: global plus candidate changes the effective selection." }; if (JSON.stringify(effective(copy, overlay)) !== before) return { eligible: false, error: "Cannot convert: intermediate copy plus candidate changes the effective selection." }; const copyContent = snapshot2.contents[name]; const globalContent = snapshot2.globalContents?.[name]; if (copyContent === void 0 || globalContent === void 0) return { eligible: false, error: "Missing definition content snapshot; reopen /subagents-tools." }; return { eligible: true, overlay, differences: nonToolsDifferences(copyContent, globalContent), dependencies: conversionDependencies(snapshot2, name, inventory) }; } function convertToolsDefinition(snapshot2, name, inventory, io = {}) { let written = false; let retired = false; let failure; let refreshed = snapshot2; try { const plan = io.plan ?? prepareToolsConversion(snapshot2, name, inventory); if (!plan.eligible) throw new Error(plan.error); const copy = snapshot2.roles.find((role) => role.role === name); const global = snapshot2.globalRoles?.find((role) => role.role === name); const copyContent = snapshot2.contents[name]; if (!copy || !global || copyContent === void 0) throw new Error("Missing definition snapshot; reopen /subagents-tools."); for (const [target, expected] of [ [copy, snapshot2.contents[name]], [global, snapshot2.globalContents?.[name]] ]) { assertSafeDefinitionPath(target.filePath); if (expected === void 0 || readFileSync(target.filePath, "utf8") !== expected) throw new Error( `Subagent target changed since preflight: ${target.filePath}` ); } const current = readToolsConfig(snapshot2.cwd); const currentPlan = prepareToolsConversion(current, name, inventory); if (!currentPlan.eligible || currentPlan.dependencies !== plan.dependencies || JSON.stringify(currentPlan.overlay) !== JSON.stringify(plan.overlay) || JSON.stringify(currentPlan.differences) !== JSON.stringify(plan.differences)) throw new Error( "Conversion inputs changed since preflight; reopen /subagents-tools." ); const result = saveProjectToolsConfig( snapshot2, [{ role: name, tools: copy.tools, overlay: plan.overlay }], io.writeOverlay ); if (!result.success) throw new Error(result.error ?? "Overlay write failed."); written = true; refreshed = result.snapshot; (io.retire ?? retireDefinitionText)(copy.filePath, copyContent); retired = true; } catch (error) { failure = `${written ? "Partial state: project overlay was written; project copy was not retired. " : ""}${error instanceof Error ? error.message : String(error)}`; } try { refreshed = readToolsConfig(snapshot2.cwd); } catch (error) { failure = `${failure ?? (retired ? "Conversion completed; backup retained." : "No conversion completed.")} Snapshot refresh failed; reopen /subagents-tools: ${error instanceof Error ? error.message : String(error)}`; } return { success: !failure, changedRoles: written ? [name] : [], snapshot: refreshed, error: failure }; } // src/tools-panel/panel.ts import { Input as Input2, matchesKey, wrapTextWithAnsi as wrapTextWithAnsi2 } from "@earendil-works/pi-tui"; var ORCHESTRATOR_NOTES = [ "ask_orchestrator: child-provided; subject to enable_ask_orchestrator and disallowed_tools.", "notify_orchestrator: child-provided; subject to enable_notify_orchestrator and disallowed_tools." ]; var sameTools = (left, right) => JSON.stringify(left) === JSON.stringify(right); function isEligibleTool(name) { if (/[*?[\]{}]/.test(name)) return false; try { validateTools([name]); return true; } catch { return false; } } function createToolsPanel(options) { let baseline = options.snapshot; let scope = baseline.initialScope ?? "global"; const drafts = { global: structuredClone(baseline.globalRoles ?? baseline.roles), project: structuredClone(baseline.roles).map((role) => ({ ...role, overlay: role.overlay ?? { add: [], remove: [] } })) }; let draft = drafts[scope]; let overviewRows; let pickerRows; let pendingChanges; let globalRoleNames = new Set(baseline.globalRoles?.map((role) => role.role)); const selections = /* @__PURE__ */ new Map(); const invalidateDerived = () => { overviewRows = void 0; pickerRows = void 0; pendingChanges = void 0; globalRoleNames = new Set(baseline.globalRoles?.map((role) => role.role)); selections.clear(); }; let blocked; let changedRoles = []; let failedSave = false; let selectedRole = 0; let entryInput; const confirmation = new PanelDiscardConfirmation(); let conversion; let conversionMessage; let confirmationOffset = 0; let confirmationLineCount = 0; const renderConversion = (width) => { const plan = conversion?.plan; const theme = options.theme; const inner = Math.max(1, width - 4); const globCount = (entry) => { const count = registeredNames.filter( (name) => matchesToolPattern(name, entry) ).length; return ` ${panelFg(theme, "muted", `\xB7 ${count} ${count === 1 ? "match" : "matches"}`)}`; }; const section = (title, tone, marker, entries, suffix = () => "") => entries.length ? [ panelFg(theme, tone, theme?.bold?.(title) ?? title), ...entries.flatMap( (entry) => wrapTextWithAnsi2(entry, Math.max(1, inner - 4)).map( (text, index, parts) => ` ${index ? " " : panelFg(theme, tone, marker)} ${text}${index === parts.length - 1 ? suffix(entry) : ""}` ) ) ] : []; const add = plan?.overlay.add ?? []; const remove = plan?.overlay.remove ?? []; const withGlobCount = (entry) => hasToolGlob(entry) ? globCount(entry) : ""; const lines = [ ...section("Will add to overlay", "success", "+", add, withGlobCount), ...section("Will remove from tools", "error", "\u2212", remove), ...section( "Lost from project copy (kept in .bak)", "warning", "!", plan?.differences ?? [] ), ...add.length || remove.length ? [] : [panelFg(theme, "muted", "No tool changes.")], panelFg( theme, "dim", "Future tools matched by global globs will now apply." ) ]; confirmationLineCount = lines.length; const height = options.maxHeight?.(); const budget = height === void 0 ? lines.length : Math.max(1, height - 3); const footer = `${panelFg(theme, "warning", "d convert (discards project copy)")}${panelFg(theme, "muted", " \xB7 k/esc cancel \xB7 \u2191/\u2193 scroll")}`; return renderPanelFrame({ title: `Convert project copy \xB7 ${conversion?.role}`, rows: [ ...lines.slice(confirmationOffset, confirmationOffset + budget), footer ], width, maxHeight: height, theme }); }; const convertible = (role) => scope === "project" && role?.scope === "project" && globalRoleNames.has(role.role); const editableNames = /* @__PURE__ */ new Set(); const tools = options.discoveredTools.filter((tool) => { if (tool.name === "ask_orchestrator" || tool.name === "notify_orchestrator" || !isEligibleTool(tool.name) || editableNames.has(tool.name)) return false; editableNames.add(tool.name); return true; }); const changed = (role, editScope = scope) => { const original = (editScope === "global" ? baseline.globalRoles ?? baseline.roles : baseline.roles).find((entry) => entry.role === role.role); return editScope === "project" ? JSON.stringify(role.overlay ?? { add: [], remove: [] }) !== JSON.stringify(original?.overlay ?? { add: [], remove: [] }) : !sameTools(role.tools, original?.tools ?? []); }; const registeredNames = [ ...new Set(options.discoveredTools.map((tool) => tool.name)) ]; const manualEntries = (role) => role.tools.filter((name) => !editableNames.has(name)); const matchDetail = (entry) => { const count = registeredNames.filter( (name) => matchesToolPattern(name, entry) ).length; const caseMatches = count ? [] : registeredNames.filter( (name) => matchesToolPattern(name.toLowerCase(), entry.toLowerCase()) ); const countHint = count ? `${count} ${count === 1 ? "match" : "matches"}` : "0 matches (expected if tool/server is not registered)"; const caseHint = caseMatches.length ? ` \xB7 Case-sensitive; check: ${caseMatches.join(", ")}` : ""; return `${countHint}${caseHint}`; }; const manualLabel = (entry) => `Manual entries \xB7 ${entry} \xB7 ${matchDetail(entry)}`; const baseTools = (role) => role.scope === "global" ? drafts.global.find((entry) => entry.role === role.role)?.tools ?? role.tools : role.tools; const effective = (role) => scope === "project" ? composeToolSelection( baseTools(role), registeredNames, role.overlay ).filter((name) => !role.disallowedTools.includes(name)) : role.tools; const selection = (role) => { let cached = selections.get(role); if (!cached) { const names = effective(role); cached = { names: new Set(names), count: names.length, summary: names.join(", ") || "(none)", base: baseTools(role).join(", "), manual: manualEntries(role).join(", ") }; selections.set(role, cached); } return cached; }; const summary2 = (role) => selection(role).summary; const reset = (role) => { if (scope === "project") role.overlay = { add: [], remove: [] }; else if (role.defaultTools) role.tools = [...role.defaultTools]; invalidateDerived(); }; const defaultsHint = (role) => scope === "project" ? " \xB7 r clear overlay" : role?.defaultTools ? " \xB7 r defaults" : ""; const overlayRows = (role) => ["add", "remove"].flatMap( (lane) => (role.overlay?.[lane] ?? []).map((entry, index) => ({ id: `${lane}:${index}`, label: `${lane} \xB7 ${entry}${hasToolGlob(entry) ? ` \xB7 ${matchDetail(entry)}` : ""}` })) ); const toolRows = (role) => pickerRows ??= [ ...tools.map((tool) => ({ id: tool.name, label: `${selection(role).names.has(tool.name) ? "[x]" : "[ ]"} ${tool.name}${tool.active ? "" : " (inactive)"}${tool.description ? ` \xB7 ${tool.description}` : ""}` })), ...scope === "project" ? overlayRows(role) : role.tools.flatMap( (entry, index) => editableNames.has(entry) ? [] : [ { id: `manual:${index}`, label: manualLabel(entry) } ] ) ]; const toggleProject = (role, name) => { role.overlay ??= { add: [], remove: [] }; const overlay = role.overlay; blocked = void 0; if (effective(role).includes(name)) { overlay.add = overlay.add.filter((entry) => entry !== name); if (effective(role).includes(name)) overlay.remove.push(name); } else { const blocking = overlay.remove.find( (pattern) => pattern !== name && matchesToolPattern(name, pattern) ); if (blocking) { blocked = `Blocked by remove pattern: ${blocking}`; return; } overlay.remove = overlay.remove.filter((entry) => entry !== name); if (!effective(role).includes(name)) overlay.add.push(name); } }; const entryTarget = (row) => { if (!row) return void 0; const [lane, index] = row.id.split(":"); if (lane !== "manual" && lane !== "add" && lane !== "remove") return void 0; return { lane: lane === "manual" ? void 0 : lane, index: Number(index) }; }; const openRole = (editor2) => { selectedRole = editor2.getState().selectedIndex; const role = draft[selectedRole]; if (!role) return; blocked = void 0; pickerRows = void 0; editor2.openPicker({ title: `Choose tools \xB7 ${role.role} \xB7 ${scope === "project" ? "Project" : "Global"}`, hints: () => `\u2191/\u2193/j/k move \xB7 space toggle \xB7 p scope \xB7 a add${entryTarget(toolRows(role)[editor2.getState().selectedIndex]) ? " \xB7 e edit" : ""} \xB7 d/delete remove${defaultsHint(role)} \xB7 enter/esc/q back`, navigation: "wrap", maxVisibleRows: 10, header: () => [ { text: `row: ${role.role} \xB7 ${selection(role).count} selected`, tone: "accent" }, ...scope === "project" ? [panelHintRow(`Base (read-only): ${selection(role).base}`)] : [], ...blocked ? [panelHintRow(blocked)] : [], ...ORCHESTRATOR_NOTES.map((note) => panelHintRow(note)) ], rows: () => toolRows(role), footer: () => { const index = editor2.getState().selectedIndex; const row = toolRows(role)[index]; const target = entryTarget(row); const selected = tools[index]?.name ?? (scope === "global" && target ? role.tools[target.index] : row?.label); return [{ text: `selected: ${selected ?? "(none)"}`, tone: "accent" }]; }, onAction: (key3, row) => { if (key3 === "p" || key3 === "tab") { switchScope(editor2); return true; } if (key3 === "a" || scope === "project" && key3 === "x") { entryInput = { input: new Input2({ prompt: key3 === "x" ? "remove: " : "add: " }), lane: key3 === "x" ? "remove" : "add" }; return true; } const target = entryTarget(row); if (key3 === "e" && target) { const entries = scope === "project" ? role.overlay?.[target.lane ?? "add"] : role.tools; const input = new Input2({ prompt: "edit: " }); input.handleInput( `\x1B[200~${entries?.[target.index] ?? ""}\x1B[201~` ); entryInput = { input, ...target }; return true; } if ((key3 === "d" || matchesKey(key3, "delete")) && target) { if (scope === "project") role.overlay?.[target.lane ?? "add"].splice(target.index, 1); else role.tools.splice(target.index, 1); invalidateDerived(); return true; } if (key3 === "space" && row && editableNames.has(row.id)) { if (scope === "project") toggleProject(role, row.id); else role.tools = role.tools.includes(row.id) ? role.tools.filter((name) => name !== row.id) : [...role.tools, row.id]; invalidateDerived(); return true; } if (key3.toLowerCase() === "r") { reset(role); return true; } return false; } }); }; const switchScope = (editor2) => { const inPicker = editor2.getState().view === "picker"; if (inPicker) editor2.showOverview(); scope = scope === "global" ? "project" : "global"; draft = drafts[scope]; invalidateDerived(); blocked = void 0; if (inPicker) openRole(editor2); }; const editor = createListEditor({ wideBreakpoint: 84, maxHeight: options.maxHeight, theme: options.theme, requestRender: options.requestRender, pendingCount: () => pendingChanges ??= drafts.global.filter((role) => changed(role, "global")).length + drafts.project.filter((role) => changed(role, "project")).length, onCancel: () => options.onDone({ kind: "cancelled" }), onSaved: () => options.onDone({ kind: "saved", changedRoles }), onSave: () => { for (const editScope of ["global", "project"]) { if (!drafts[editScope].some((role) => changed(role, editScope)) && !failedSave) continue; const result = options.save( { ...baseline, editScope }, structuredClone(drafts[editScope]) ); baseline = result.snapshot; invalidateDerived(); changedRoles = [.../* @__PURE__ */ new Set([...changedRoles, ...result.changedRoles])]; failedSave = !result.success; if (!result.success) return { success: false, error: result.error, warning: changedRoles.length ? `Already changed: ${changedRoles.join(", ")}` : void 0 }; } return { success: true }; }, overview: { title: "Subagent tools", hints: () => `\u2191/\u2193/j/k move \xB7 enter/e edit \xB7 p scope${defaultsHint(draft[editor.getState().selectedIndex])}${convertible(draft[editor.getState().selectedIndex]) ? " \xB7 c convert" : ""} \xB7 s save \xB7 esc/q cancel`, header: ({ layout }) => [ ...conversionMessage ? [panelHintRow(conversionMessage)] : [], panelHintRow( `Scope: ${scope === "project" ? "Project" : "Global"} \xB7 p switch \xB7 target: ${scope === "project" ? "project tools overlay" : "global definition tools"}` ), layout === "wide" ? `${"agent".padEnd(18)} ${"selected tools".padEnd(18)} tools` : "agent \xB7 selected tools" ], rows: () => overviewRows ??= draft.map((role) => { const selected = selection(role); return { id: role.role, dirty: changed(role), label: ({ layout }) => layout === "wide" ? `${role.role.padEnd(16)} ${`${selected.count} selected`.padEnd(18)} ${selected.summary}` : `${role.role} \xB7 ${selected.count} selected \xB7 ${selected.summary}` }; }), footer: () => { const role = draft[editor.getState().selectedIndex]; return [ { text: `selected: ${role?.role ?? "(none)"} \xB7 tools: ${role ? summary2(role) : "(none)"}`, tone: "accent" }, ...scope === "global" && role?.shadowedBy ? [ panelHintRow( `Warning: project copy hides this global change: ${role.shadowedBy}` ) ] : [], panelHintRow(`Global directory: ${baseline.piRoot}`), panelHintRow("Ambient root tools are unchanged."), panelHintRow( "Native settings or project definitions may override these global definitions." ), panelHintRow( "Child specialists do not inherit root tools automatically." ), ...ORCHESTRATOR_NOTES.map((note) => panelHintRow(note)), ...role ? [ panelHintRow(`Definition: ${role.scope} \xB7 ${role.filePath}`), ...selection(role).manual.length ? [ panelHintRow( `Manual entries: ${selection(role).manual} (edit in picker)` ) ] : [] ] : [] ]; }, onAction: (key3, _row, editor2) => { if (key3 === "c") { const role = draft[editor2.getState().selectedIndex]; if (!convertible(role) || !role) return true; if (drafts.global.some((role2) => changed(role2, "global")) || drafts.project.some((role2) => changed(role2, "project"))) { conversionMessage = "Save or discard unsaved tool edits before conversion."; return true; } try { const plan = prepareToolsConversion( baseline, role.role, registeredNames ); if (plan.eligible) { conversion = { role: role.role, plan }; confirmationOffset = 0; confirmation.request(true); } else conversionMessage = plan.error; } catch (error) { conversionMessage = error instanceof Error ? error.message : String(error); } return true; } if (key3 === "p" || key3 === "tab") { switchScope(editor2); return true; } if (key3 === "enter" || key3 === "e") { openRole(editor2); return true; } if (key3.toLowerCase() === "r") { const role = draft[editor2.getState().selectedIndex]; if (role) reset(role); return true; } return false; } } }); return { render: (width) => conversion ? renderConversion(width) : entryInput ? renderPanelFrame({ title: `${entryInput.index === void 0 ? "Add" : "Edit"} tool entry \xB7 ${draft[selectedRole]?.role}`, rows: [ panelHintRow( "type a name or glob \xB7 ctrl+u clear \xB7 enter confirm \xB7 esc cancel" ), ...entryInput.input.render(Math.max(0, width - 4)), ...entryInput.error ? [{ text: entryInput.error, tone: "error" }] : [] ], width, maxHeight: options.maxHeight?.(), theme: options.theme }) : editor.render(width), handleInput: (data) => { if (conversion) { const key4 = normalizePanelKey(data); if (key4 === "down" || key4 === "j") confirmationOffset = Math.min( Math.max(0, confirmationLineCount - 1), confirmationOffset + 1 ); else if (key4 === "up") confirmationOffset = Math.max(0, confirmationOffset - 1); else { const action = confirmation.handleInput(data); if (action === "discard") { const result = convertToolsDefinition( baseline, conversion.role, options.getRegisteredToolNames?.() ?? registeredNames, { plan: conversion.plan } ); baseline = result.snapshot; drafts.global = structuredClone( baseline.globalRoles ?? baseline.roles ); drafts.project = structuredClone(baseline.roles).map((role) => ({ ...role, overlay: role.overlay ?? { add: [], remove: [] } })); draft = drafts[scope]; invalidateDerived(); changedRoles = [ .../* @__PURE__ */ new Set([...changedRoles, ...result.changedRoles]) ]; conversionMessage = result.success ? "Converted project copy to tools overlay. Backup retained beside the definition." : result.error; conversion = void 0; } else if (action === "resume") conversion = void 0; } options.requestRender?.(); return; } const active = entryInput; if (!active) { return editor.handleInput( matchesKey(data, "tab") ? "tab" : matchesKey(data, "p") ? "p" : data ); } const key3 = normalizePanelKey(data); if (key3 === "escape") entryInput = void 0; else if (key3 === "enter") { const candidate = active.input.getValue().trim(); const role = draft[selectedRole]; if (!candidate && active.index !== void 0) active.error = "Empty entry: use d/Delete to remove it."; else if (!candidate || !role) entryInput = void 0; else { try { const entries = scope === "project" ? role.overlay?.[active.lane ?? "add"] ?? [] : role.tools; validateTools([candidate]); if (candidate !== entries[active.index ?? -1]) { if (entries.some( (entry, index) => entry === candidate && index !== active.index )) throw new Error(`Duplicate Subagent tool name: ${candidate}.`); if (active.index !== void 0) entries[active.index] = candidate; else entries.push(candidate); invalidateDerived(); } entryInput = void 0; } catch (error) { active.error = error instanceof Error ? error.message : String(error); } } } else if (key3 === "ctrl+u") active.input.setValue(""); else active.input.handleInput(data); options.requestRender?.(); }, invalidate: () => editor.invalidate(), getState: () => { const state = editor.getState(); return { scope, screen: state.view === "picker" ? "tools" : state.view, selectedRole: state.view === "picker" ? selectedRole : state.selectedIndex, draft: structuredClone(draft), error: state.error, changedRoles: [...changedRoles] }; } }; } // src/tools-panel/command.ts function registerToolsCommand(pi, options = {}) { if (typeof pi.registerCommand !== "function") return () => { }; pi.registerCommand("subagents-tools", { description: "Edit subagent definition tools", handler: async (_args, ctx) => { const ui = ctx.ui; if (ctx.mode !== "tui") { ui.notify( "/subagents-tools requires interactive TUI mode; no files were changed.", "error" ); return; } if (typeof pi.getAllTools !== "function" || typeof pi.getActiveTools !== "function") { ui.notify( "Tool discovery is unavailable in this Pi environment; no files were changed.", "error" ); return; } try { const snapshot2 = (options.read ?? readToolsConfig)( ctx.cwd ?? process.cwd() ); const active = new Set(pi.getActiveTools()); const getAllTools = pi.getAllTools.bind(pi); const discoveredTools = getAllTools().map( (tool) => ({ ...tool, active: active.has(tool.name) }) ); const result = await openPanelOverlay( ctx, (_tui, theme, _keys, done, host) => createToolsPanel({ snapshot: snapshot2, discoveredTools, getRegisteredToolNames: () => getAllTools().map((tool) => tool.name), save: options.save ?? saveToolsConfig, onDone: done, theme, ...host }) ); if (result?.kind === "saved") { const detail = result.changedRoles.length ? ` Updated: ${result.changedRoles.join(", ")}.` : " No file content changed."; ui.notify( `Saved subagent tools.${detail} Saved settings apply on subsequent specialist discovery; running children and the ambient root are unchanged. Project overlays and project definitions can override global selections.`, "info" ); } } catch (error) { ui.notify( `Unable to open subagent tools: ${error instanceof Error ? error.message : String(error)}`, "error" ); } } }); publishToolsPanelCapability(); let warned = false; return (ctx) => { if (warned || typeof pi.getCommands !== "function") return; const owners = pi.getCommands().filter( (command) => (!command.source || command.source === "extension") && /^subagents-tools(?::\d+)?$/.test(command.name) ); if (owners.length < 2 || typeof ctx?.ui?.notify !== "function") return; warned = true; ctx.ui.notify( "Duplicate /subagents-tools owners detected. Upgrade thoth-agents and @thoth-agents/pi-subagents (>=0.3.0) together, then /reload; the command now belongs to pi-subagents.", "warning" ); }; } // src/ui/provider-limit-cache.ts var MAX_OBSERVATIONS = 512; function formatResetTime(timestamp2) { const date = new Date(timestamp2); return `${date.getHours().toString().padStart(2, "0")}:${date.getMinutes().toString().padStart(2, "0")}`; } var SubagentProviderLimitCache = class { entries = /* @__PURE__ */ new Map(); unsubscribe; listeners = /* @__PURE__ */ new Set(); resetTimer; constructor() { this.unsubscribe = subscribeProviderLimits((entry) => { const metadata = getInteractionSessionRegistry().get(entry.sessionId); const taskId2 = metadata?.requester?.taskId; if (metadata?.origin !== "subagent" || typeof taskId2 !== "string" || !taskId2) return; const key3 = JSON.stringify([taskId2, entry.provider, entry.window]); this.entries.delete(key3); this.entries.set(key3, { taskId: taskId2, entry }); if (this.entries.size > MAX_OBSERVATIONS) { const oldest = this.entries.keys().next().value; if (oldest !== void 0) this.entries.delete(oldest); } this.scheduleReset(); this.notify(); }); } warningText(taskId2, now = Date.now()) { const warnings = []; for (const observation of this.entries.values()) { const entry = observation.entry; if (observation.taskId !== taskId2 || entry.status === "allowed" || entry.resetsAt !== void 0 && entry.resetsAt <= now) continue; const status = entry.status === "rejected" ? "rate limited" : "rate limit warning"; const reset = entry.resetsAt === void 0 ? "" : ` \xB7 reset ${formatResetTime(entry.resetsAt)}`; warnings.push(`${entry.provider}/${entry.window}: ${status}${reset}`); } return warnings.length ? warnings.join("; ") : void 0; } onChange(notify2) { this.listeners.add(notify2); return () => { this.listeners.delete(notify2); }; } notify() { for (const listener of [...this.listeners]) { if (!this.listeners.has(listener)) continue; try { listener(); } catch { } } } scheduleReset() { if (this.resetTimer) clearTimeout(this.resetTimer); this.resetTimer = void 0; const now = Date.now(); let next = Infinity; for (const [key3, { entry }] of this.entries) { if (entry.resetsAt === void 0) continue; if (entry.resetsAt <= now) this.entries.delete(key3); else next = Math.min(next, entry.resetsAt); } if (next === Infinity) return; this.resetTimer = setTimeout( () => { this.scheduleReset(); this.notify(); }, Math.min(next - now, 2147483647) ); this.resetTimer.unref?.(); } dispose() { this.unsubscribe(); if (this.resetTimer) clearTimeout(this.resetTimer); this.resetTimer = void 0; this.listeners.clear(); this.entries.clear(); } }; // src/ui/work-panel-provider.ts function taskState(task) { if (["queued", "stopping", "running"].includes(task.status)) return "running"; return task.status === "completed" ? "done" : "failed"; } function taskRenderStatus(task) { if (task.status === "cancelled" || task.status === "interrupted") return "cancelled"; if (task.status === "failed" && task.error_metadata?.category === "total_timeout") return "timedOut"; return task.status; } function completionTime(task) { const endedAt = task.ended_at ? Date.parse(task.ended_at) : NaN; return Number.isFinite(endedAt) ? endedAt : void 0; } function finiteNonnegative2(value3) { return typeof value3 === "number" && Number.isFinite(value3) && value3 >= 0; } function taskRow(task, now, limitWarning) { const summary2 = formatTaskSummary2(task); const status = taskRenderStatus(task); const separator = ` ${resolveIcon("separator", "\xB7")} `; const metrics = task.runtime_metrics; const speed = generationSpeed(metrics); const started = task.started_at ? Date.parse(task.started_at) : NaN; const ended = task.ended_at ? Date.parse(task.ended_at) : NaN; const end = task.status === "running" || task.status === "stopping" ? now : ended; const kit = getRenderKit(); const ascii = resolveIcon("tokensIn", "\u2191") === "^"; const label = (icon, text) => ascii || !kit ? text : resolveIcon(icon); const live = taskState(task) === "running"; const parts = []; if (task.model?.trim()) { const modelId = task.model.trim().split("/").at(-1) ?? task.model.trim(); const model = modelId.match(/(?:^|-)claude-(sonnet|opus|haiku)(?:-|$)/i)?.[1] ?? modelId; const effort = task.effort && { off: "off", minimal: "min", low: "lo", medium: "med", high: "hi", xhigh: "xhi", max: "max" }[task.effort]; parts.push({ key: "model", columnsOnly: true, segments: [{ text: effort ? `${model}\xB7${effort}` : model, role: "meta" }] }); } const add = (key3, prefix, value3, pending = false) => { parts.push({ key: key3, ...pending ? { pending } : {}, segments: [ { text: prefix, role: "meta" }, { text: value3, role: "meta" } ] }); }; if (finiteNonnegative2(metrics?.toolUses)) add("tools", `${label("tool", "tools")} `, String(metrics.toolUses)); else if (live) add("tools", `${label("tool", "tools")} `, "?", true); const tokens = []; for (const [value3, icon, text, direction] of [ [task.usage?.input, "tokensIn", "in ", "in"], [task.usage?.output, "tokensOut", "out ", "out"] ]) { if (!finiteNonnegative2(value3) && !live) continue; if (tokens.length) tokens.push({ text: " ", role: "meta" }); tokens.push( { text: ascii ? text : resolveIcon(icon), role: "meta", direction }, { text: finiteNonnegative2(value3) ? formatTokens(value3) : "?", role: "meta", direction } ); } if (tokens.length) parts.push({ key: "tokens", ...live && !task.usage?.input && !task.usage?.output ? { pending: true } : {}, segments: tokens }); if (finiteNonnegative2(metrics?.contextPercent)) add( "context", `${label("context", "ctx")} `, `${metrics.contextPercent.toFixed(1)}%` ); else if (live) add("context", `${label("context", "ctx")} `, "?", true); if (speed !== void 0 || live) { const value3 = speed === void 0 ? "?" : String(Math.round(speed)); if (!kit) parts.push({ key: "speed", ...speed === void 0 ? { pending: true } : {}, segments: [{ text: `${value3} tok/s`, role: "meta" }] }); else add( "speed", `${label("throughput", "tok/s")} `, value3, speed === void 0 ); } if (finiteNonnegative2(task.usage?.cost)) add( "cost", label("cost", "$"), task.usage.cost.toFixed(2), live && task.usage.cost === 0 ); if (Number.isFinite(started) && Number.isFinite(end)) add( "elapsed", `${label("elapsed", "elapsed")} `, formatDuration2(Math.floor(Math.max(0, end - started) / 1e3) * 1e3) ); else if (live) add("elapsed", `${label("elapsed", "elapsed")} `, "?"); const agentName = task.agent.replace(/\s+/g, " ").trim(); const compactName = agentName.replace(/^thoth-(?=.)/, ""); const warning = (task.status === "running" || task.status === "queued") && task.dropped_tools?.length ? `${resolveIcon("warning", "\u26A0")} ${task.dropped_tools.length} dropped` : ""; return { id: task.id, name: task.agent, primary: summary2, status, state: taskState(task), endedAt: completionTime(task), sortStartedAt: Date.parse(task.created_at), statusGlyph: status, identity: [ { text: agentName, // The sidebar drops the redundant bundled-specialist prefix; the host keeps `text`. ...compactName && compactName !== agentName ? { compact: compactName } : {}, role: "primary" }, ...summary2 ? [ { text: separator, role: "meta" }, { text: summary2, role: "secondary" } ] : [], ...[warning, limitWarning].flatMap( (text) => text ? [ { text: separator, role: "meta" }, { text, role: "warning" } ] : [] ) ], metrics: parts }; } function createSubagentsWorkPanelProvider(source) { let historyTasks = source.listCompletionRankedSessionTasks?.() ?? []; const terminalSignature = () => JSON.stringify( source.listTasks().filter((task) => taskState(task) !== "running").map((task) => [task.id, task.status, task.ended_at]) ); let lastTerminalSignature = terminalSignature(); const refreshHistory = () => { const signature2 = terminalSignature(); if (signature2 === lastTerminalSignature) return; lastTerminalSignature = signature2; historyTasks = source.listCompletionRankedSessionTasks?.() ?? []; }; const dismissed = /* @__PURE__ */ new Set(); const listeners = /* @__PURE__ */ new Set(); const taskById = (id) => source.listTasks().find((task) => task.id === id); const visibleTasks = () => source.listTasks().filter((task) => { if (taskState(task) === "running") dismissed.delete(task.id); return !dismissed.has(task.id); }); const discoveryTasks = () => { const live = visibleTasks(); const liveIds = new Set(source.listTasks().map((task) => task.id)); const merged = [ ...live, ...historyTasks.filter( (task) => !liveIds.has(task.id) && !dismissed.has(task.id) && taskState(task) !== "running" ) ]; return [ ...merged.filter((task) => taskState(task) === "running"), ...merged.filter((task) => taskState(task) !== "running").sort( (a, b) => (completionTime(b) ?? 0) - (completionTime(a) ?? 0) || Buffer.compare( Buffer.from(b.id, "utf8"), Buffer.from(a.id, "utf8") ) ).slice(0, 5) ]; }; const rank = (task) => task.status === "running" ? 0 : task.status === "queued" ? 1 : 2; return { version: WORK_PANEL_VERSION, id: "subagents", label: "Agents", priority: 10, retention: "prompt", visibleCount: () => visibleTasks().length, refreshIntervalMs: 100, summary: () => { const tasks = source.listTasks(); const counts = { ...source.persistedCounts?.counts }; for (const task of tasks) { const persistedStatus = source.persistedCounts?.statusesById.get( task.id ); if (persistedStatus) counts[persistedStatus] = (counts[persistedStatus] ?? 0) - 1; counts[task.status] = (counts[task.status] ?? 0) + 1; } const count = (status) => counts[status] ?? 0; const parts = [ { text: `${count("running")} running`, role: "meta" } ]; for (const status of [ "queued", "stopping", "completed", "failed", "cancelled", "interrupted" ]) { const total = count(status); if (total) parts.push( { text: ` ${resolveIcon("separator", "\xB7")} `, role: "meta" }, { text: `${total} ${status}`, role: status === "failed" ? "error" : "meta" } ); } return { text: parts.map(({ text }) => text).join(""), segments: parts, running: count("running") + count("stopping"), queued: count("queued"), completed: count("completed"), failed: count("failed"), cancelled: count("cancelled") + count("interrupted"), total: Object.values(counts).reduce((sum, total) => sum + total, 0) }; }, listRows: (now, options) => (options?.includeHistory ? discoveryTasks() : visibleTasks().sort( (a, b) => rank(a) - rank(b) || Buffer.compare( Buffer.from(b.created_at ?? "", "utf8"), Buffer.from(a.created_at ?? "", "utf8") ) || Buffer.compare( Buffer.from(b.id, "utf8"), Buffer.from(a.id, "utf8") ) )).map( (task) => taskRow(task, now, source.providerLimits?.warningText(task.id, now)) ), detail: () => null, armCloseLabel: (row) => { const task = taskById(row.id); if (!task) return ""; if (task.status === "running") return "cancel"; return taskState(task) === "running" ? "" : "dismiss"; }, close: (id) => { const task = taskById(id); if (!task) return; if (task.status === "running") { source.cancel(id, "cancelled from work panel"); return { action: "cancel", providerId: "subagents", id }; } if (taskState(task) === "running" || dismissed.has(id)) return; dismissed.add(id); for (const notify2 of listeners) notify2(); return { action: "dismissed", providerId: "subagents", id }; }, open: source.open, openHistory: source.openHistory, onVisibleChanged: (notify2) => { listeners.add(notify2); const unsubscribe = source.onTaskUpdate(() => { refreshHistory(); notify2(); }); const unsubscribeLimits = source.providerLimits?.onChange(notify2); return () => { listeners.delete(notify2); unsubscribeLimits?.(); unsubscribe(); }; } }; } // src/usage-events.ts function messageIdentity2(message) { if (message.id) return `id:${message.id}`; if (message.timestamp === void 0) return void 0; const usage = message.usage; return `timestamp:${JSON.stringify([ message.timestamp, usage?.input, usage?.output, usage?.cacheRead, usage?.cacheWrite, usage?.totalTokens, usage?.cost?.total ])}`; } function messageTimestamp(message) { const timestamp2 = typeof message.timestamp === "string" ? Date.parse(message.timestamp) : message.timestamp; return typeof timestamp2 === "number" && Number.isFinite(timestamp2) ? timestamp2 : void 0; } var usageEntryType = "thoth:subagent-usage"; var persistIntervalMs = 5e3; function isNonNegativeCost(value3) { return typeof value3 === "number" && Number.isFinite(value3) && value3 >= 0; } function isStringArray(value3) { return Array.isArray(value3) && value3.every((key3) => typeof key3 === "string" && key3.length > 0); } function isPersistedUsage(value3, parentSessionId) { if (!value3 || typeof value3 !== "object") return false; const data = value3; if (data.version !== 1 || data.parentSessionId !== parentSessionId || !isNonNegativeCost(data.totalCost) || !Array.isArray(data.runs) || data.runCount !== data.runs.length) return false; const runIds = /* @__PURE__ */ new Set(); return data.runs.every((run) => { if (!run || typeof run.runId !== "string" || !run.runId || runIds.has(run.runId) || !isNonNegativeCost(run.totalCost) || run.throughTimestamp !== null && (typeof run.throughTimestamp !== "number" || !Number.isFinite(run.throughTimestamp)) || !isStringArray(run.throughKeys) || !isStringArray(run.untimedKeys)) return false; runIds.add(run.runId); return true; }); } var SubagentUsageEvents = class { constructor(events, appendEntry) { this.events = events; this.appendEntry = appendEntry; this.sessionReady = !appendEntry; this.offRequest = onRequest(events, SUBAGENTS_USAGE_REQUEST, { onRequest: ({ sessionId }) => { if (this.sessionReady) this.publish(sessionId); else this.pendingRequests.add(sessionId); } }); } events; appendEntry; parents = /* @__PURE__ */ new Map(); activeSessionId; lastPersistedAt = Number.NEGATIVE_INFINITY; persistTimer; sessionReady; pendingRequests = /* @__PURE__ */ new Set(); offRequest; startSession(parentSessionId, entries) { if (this.persistTimer) clearTimeout(this.persistTimer); this.persistTimer = void 0; this.lastPersistedAt = Number.NEGATIVE_INFINITY; this.activeSessionId = parentSessionId; if (parentSessionId && !this.parents.has(parentSessionId)) this.restoreParent(parentSessionId, entries); this.sessionReady = true; if (parentSessionId) this.publish(parentSessionId); for (const requestedParent of this.pendingRequests) { if (requestedParent !== parentSessionId) this.publish(requestedParent); } this.pendingRequests.clear(); } flush() { if (this.persistTimer) clearTimeout(this.persistTimer); this.persistTimer = void 0; if (!this.appendEntry || !this.activeSessionId) return; const parent = this.parents.get(this.activeSessionId); if (!parent?.dirty) return; this.appendEntry(usageEntryType, { version: 1, parentSessionId: this.activeSessionId, totalCost: parent.totalCost, runCount: parent.runs.size, runs: Array.from(parent.runs, ([runId, run]) => ({ runId, totalCost: run.totalCost, throughTimestamp: run.throughTimestamp, throughKeys: [...run.throughKeys], untimedKeys: [...run.untimedKeys] })) }); parent.dirty = false; this.lastPersistedAt = Date.now(); } recordAssistantMessage(parentSessionId, runId, message) { if (!parentSessionId) return; let parent = this.parents.get(parentSessionId); if (!parent) { parent = { totalCost: 0, runs: /* @__PURE__ */ new Map(), dirty: false }; this.parents.set(parentSessionId, parent); } let run = parent.runs.get(runId); if (!run) { run = { totalCost: 0, seen: /* @__PURE__ */ new Set(), throughTimestamp: null, throughKeys: /* @__PURE__ */ new Set(), untimedKeys: /* @__PURE__ */ new Set(), restoredThroughTimestamp: null }; parent.runs.set(runId, run); } const identity = messageIdentity2(message); const timestamp2 = messageTimestamp(message); if (identity && run.seen.has(identity) || timestamp2 !== void 0 && run.restoredThroughTimestamp !== null && timestamp2 < run.restoredThroughTimestamp) return; if (identity) run.seen.add(identity); if (timestamp2 !== void 0) { if (run.throughTimestamp === null || timestamp2 > run.throughTimestamp) { run.throughTimestamp = timestamp2; run.throughKeys.clear(); } if (identity && timestamp2 === run.throughTimestamp) run.throughKeys.add(identity); } else if (identity) { run.untimedKeys.add(identity); } const cost = message.usage?.cost?.total; if (isNonNegativeCost(cost)) { parent.totalCost += cost; run.totalCost += cost; } parent.dirty = true; this.publish(parentSessionId); this.scheduleFlush(parentSessionId); } dispose() { try { this.flush(); } finally { this.offRequest(); this.pendingRequests.clear(); this.parents.clear(); this.activeSessionId = void 0; } } restoreParent(parentSessionId, entries) { for (let index = entries.length - 1; index >= 0; index--) { const entry = entries[index]; if (entry.type !== "custom" || entry.customType !== usageEntryType) continue; const data = entry.data; if (!isPersistedUsage(data, parentSessionId)) continue; this.parents.set(parentSessionId, { totalCost: data.totalCost, runs: new Map( data.runs.map((run) => [ run.runId, { totalCost: run.totalCost, seen: /* @__PURE__ */ new Set([...run.throughKeys, ...run.untimedKeys]), throughTimestamp: run.throughTimestamp, throughKeys: new Set(run.throughKeys), untimedKeys: new Set(run.untimedKeys), restoredThroughTimestamp: run.throughTimestamp } ]) ), dirty: false }); return; } } scheduleFlush(parentSessionId) { if (!this.appendEntry || parentSessionId !== this.activeSessionId) return; const delay = this.lastPersistedAt + persistIntervalMs - Date.now(); if (delay <= 0) this.flush(); else if (!this.persistTimer) { this.persistTimer = setTimeout(() => this.flush(), delay); this.persistTimer.unref?.(); } } publish(parentSessionId) { const parent = this.parents.get(parentSessionId); publish(this.events, SUBAGENTS_USAGE_CHANNEL, { source: "@thoth-agents/pi-subagents", sessionId: parentSessionId, data: { totalCost: parent?.totalCost ?? 0, runCount: parent?.runs.size ?? 0 } }); } }; // src/extension/subagents-extension.ts var HISTORY_PRUNE_INTERVAL_MS = 60 * 60 * 1e3; var HISTORY_PRUNE_DELAY_MS = 3e4; var HISTORY_PRUNE_KEY = /* @__PURE__ */ Symbol.for("pi.subagents.historyPruning.v1"); var shared12 = globalThis; shared12[HISTORY_PRUNE_KEY] ??= { lastRunAt: -Infinity, pending: false, managers: /* @__PURE__ */ new Set(), idleWaiters: /* @__PURE__ */ new Set() }; var historyPruning = shared12[HISTORY_PRUNE_KEY]; historyPruning.managers ??= /* @__PURE__ */ new Set(); historyPruning.idleWaiters ??= /* @__PURE__ */ new Set(); function waitForHistoryIdle(signal) { if (signal.aborted || !hasActiveHistoryTasks()) return; return new Promise((resolve3) => { const finish = () => { historyPruning.idleWaiters.delete(check); signal.removeEventListener("abort", finish); resolve3(); }; const check = () => { if (!hasActiveHistoryTasks()) finish(); }; historyPruning.idleWaiters.add(check); signal.addEventListener("abort", finish, { once: true }); if (signal.aborted) finish(); }); } function hasActiveHistoryTasks() { return [...historyPruning.managers].some( (manager) => manager.listTasks().some( (task) => task.status === "queued" || task.status === "running" || task.status === "stopping" ) ); } function notifyHistoryActivity() { for (const check of historyPruning.idleWaiters) check(); } function currentSessionId2(ctx) { const direct = ctx?.sessionManager?.getSessionId?.() ?? ctx?.sessionId; if (typeof direct === "string" && direct.length > 0) return direct; const file = ctx?.sessionManager?.getSessionFile?.(); return typeof file === "string" && file.length > 0 ? file : void 0; } function isStaleContextError(error) { const message = error instanceof Error ? error.message : String(error ?? ""); return message.includes("extension ctx is stale") || message.includes("stale after session replacement or reload"); } function subagentsExtension(pi) { const providerLimits = new SubagentProviderLimitCache(); const definitions = []; const toolDefinitionOwner = /* @__PURE__ */ Symbol("subagentsExtension"); let publication; const originalRegisterTool = typeof pi.registerTool === "function" ? pi.registerTool.bind(pi) : void 0; if (originalRegisterTool) { pi.registerTool = (tool) => { registerSubagentExternalToolDefinition( tool?.name, tool, toolDefinitionOwner ); const result = originalRegisterTool(tool); definitions.push(tool); publication?.publish([tool]); return result; }; } pi.registerMessageRenderer?.( "subagent-completion", renderSubagentCompletionMessage ); pi.registerMessageRenderer?.( "subagent-attention", renderSubagentAttentionMessage ); pi.registerMessageRenderer?.( "subagent-question", renderSubagentQuestionMessage ); let activeSessionId; let unregisterLiveness; let rootRunActive = false; let notificationCtx; let cancelHistoryPruning; const notificationOutbox = []; const deliverNotification = (send) => { if (rootRunActive || notificationCtx?.signal) notificationOutbox.push(send); else send(); }; let activeSessionOwner; const usageEvents = pi.events ? new SubagentUsageEvents( pi.events, typeof pi.appendEntry === "function" ? (customType, data) => pi.appendEntry(customType, data) : void 0 ) : void 0; const manager = new SubagentManager( void 0, void 0, (task, cwd) => { const taskSessionId = typeof task?.session_id === "string" && task.session_id.length > 0 ? task.session_id : void 0; if (taskSessionId && taskSessionId !== activeSessionId) return; const completion = summarizeTask(task); deliverNotification(() => { if (taskSessionId && taskSessionId !== activeSessionId) return; if (manager.isResultAcknowledged(completion)) return; try { sendSubagentCompletionMessage(pi, completion, cwd); } catch (error) { if (!isStaleContextError(error)) throw error; } }); }, void 0, new AtelierMetadataWriter({ appendEntry: (customType, data) => { pi.appendEntry?.(customType, data); }, getCurrentOwner: () => activeSessionOwner }), (parentSessionId, taskId2, message) => usageEvents?.recordAssistantMessage(parentSessionId, taskId2, message), (task, question) => { if (!task.session_id || task.session_id !== activeSessionId) throw new Error( "The originating parent Pi session is no longer active." ); const pending = summarizeTask(task); deliverNotification(() => { if (pending.session_id !== activeSessionId) return; if (!manager.isQuestionPending(pending.id, question.request_id)) return; try { sendSubagentQuestionMessage(pi, pending, question); } catch (error) { if (isStaleContextError(error)) throw new Error( "Parent Pi session shutdown or replacement prevents question delivery." ); throw error; } }); }, (task, cwd, attempt, generation) => { const sessionId = task.session_id; const taskId2 = task.id; if (!sessionId || sessionId !== activeSessionId) return; deliverNotification(() => { if (sessionId !== activeSessionId || !manager.isAttentionCurrent(taskId2, attempt, generation)) return; const current = manager.getTask(taskId2, cwd); if (!current || current.session_id !== sessionId) return; try { sendSubagentAttentionMessage(pi, summarizeTask(current)); } catch (error) { if (!isStaleContextError(error)) throw error; } }); }, (taskId2) => triggerTaskBackgroundHandoff(manager, taskId2, "attention") ); historyPruning.managers.add(manager); const releaseHistoryActivity = manager.onTaskUpdate(notifyHistoryActivity); const sessionModelProfile = new SessionModelProfile( typeof pi.appendEntry === "function" ? (type, data) => pi.appendEntry(type, data) : void 0 ); const setSessionModelProfile = (profile) => { sessionModelProfile.set(profile); manager.setSessionModelProfile(sessionModelProfile.get()); }; registerSubagentTools(pi, manager, process.cwd()); const taskStateEvents = pi.events ? new SubagentsStatePublisher(pi.events, manager) : void 0; let panelCtx; let unregisterWorkPanel; let releaseWorkPanel; let releaseWorkPanelLifecycle; let workPanelGeneration = 0; let activePanelCancelSelected; let activePanelRequestRender; const openPanel = async (ctx, selectedTaskId) => { await preloadPiComponentsForSubagentRendering(); await showSubagentsPanel({ ctx, pi, manager, selectedTaskId, providerLimits, setActivePanelCancelSelected: (fn) => { activePanelCancelSelected = fn; }, setActivePanelRequestRender: (fn) => { activePanelRequestRender = fn; } }); }; const clearWorkPanel = () => { workPanelGeneration += 1; unregisterWorkPanel?.(); unregisterWorkPanel = void 0; releaseWorkPanel?.(); releaseWorkPanel = void 0; releaseWorkPanelLifecycle?.(); releaseWorkPanelLifecycle = void 0; panelCtx = void 0; }; pi.on?.("turn_end", (event, ctx) => { if (currentSessionId2(ctx) === activeSessionId) manager.confirmResultAcknowledgments(event.toolResults ?? []); }); pi.on?.("agent_start", (_event, ctx) => { if (currentSessionId2(ctx) === activeSessionId) rootRunActive = true; }); pi.on?.("agent_settled", (_event, ctx) => { if (currentSessionId2(ctx) !== activeSessionId) return; manager.clearResultAcknowledgmentCandidates(); while (notificationOutbox.length) { const send = notificationOutbox.shift(); try { send?.(); } catch (error) { console.error( "[pi-subagents] Failed to deliver parent notification:", error ); } } rootRunActive = false; }); pi.on?.("session_start", async (event, ctx) => { if (notificationCtx !== ctx) void cancelHistoryPruning?.(); notificationOutbox.length = 0; rootRunActive = false; notificationCtx = ctx; manager.resetResultAcknowledgments(); sessionModelProfile.restore( ctx?.sessionManager?.getBranch?.() ?? ctx?.sessionManager?.getEntries?.() ?? [] ); manager.setSessionModelProfile(sessionModelProfile.get()); checkToolsOwnership(ctx); if (ctx.hasUI && !publication) publication = publishToolDefinitions(definitions); void preloadPiComponentsForSubagentRendering(); clearWorkPanel(); const sessionId = currentSessionId2(ctx); unregisterLiveness?.(); unregisterLiveness = void 0; if (typeof sessionId === "string" && sessionId.trim().length > 0) { const cwd2 = ctx.cwd; try { unregisterLiveness = registerSessionLivenessProvider({ name: "thoth-agents/pi-subagents", sessionId, sessionFile: ctx.sessionManager?.getSessionFile?.(), isActive: () => manager.listActiveSessionTasks(cwd2, sessionId).some( (task) => (task.effective_mode ?? task.mode) === "background" && (task.status === "queued" || task.status === "running" || task.status === "stopping") ) }); } catch (error) { console.error( "[pi-subagents] Failed to register session liveness provider:", error ); } } activeSessionId = sessionId; activeSessionOwner = captureAtelierSessionOwner(ctx); usageEvents?.startSession( activeSessionId, ctx?.sessionManager?.getEntries?.() ?? ctx?.sessionManager?.getBranch?.() ?? [] ); const cwd = ctx?.cwd ?? process.cwd(); manager.reconcileOrphanedTasks(cwd); taskStateEvents?.startSession(cwd, sessionId); const store = new ModelProfileStore({ cwd, agentDir: ctx?.agentDir }); for (const warning of [ ...subagentSourceWarnings(cwd), ...store.resolve(sessionModelProfile.get()).warnings ]) ctx?.ui?.notify?.(warning, "warning"); const history = ctx?.sessionManager?.getEntries?.(); const isNew = event?.reason === "new" || event?.reason === "startup" && Array.isArray(history) && !history.some((entry) => entry.type === "message"); if (isNew) { const outcome = await applyProfileOrchestrator( pi, ctx, store.resolve().profile ); if (outcome.status === "unavailable" || outcome.status === "clamped") ctx?.ui?.notify?.(outcome.message, "warning"); } panelCtx = ctx; registerSubagentsPanelOpener( (taskId2) => openPanel(panelCtx ?? ctx, taskId2) ); if (ctx.hasUI && ctx.mode === "tui") { releaseWorkPanelLifecycle = bindWorkPanelLifecycle(pi, ctx); const generation = workPanelGeneration; unregisterWorkPanel = registerWorkPanelProvider( ctx, createSubagentsWorkPanelProvider({ listTasks: () => manager.listActiveSessionTasks(cwd, sessionId), listCompletionRankedSessionTasks: () => manager.listWorkPanelSessionTasks(cwd, sessionId), persistedCounts: manager.snapshotSessionTaskCounts(cwd, sessionId), providerLimits, onTaskUpdate: (notify2) => manager.onTaskUpdate(notify2), cancel: (id, reason) => manager.cancel(id, reason), open: (id, liveCtx) => openPanel(liveCtx, id), openHistory: (liveCtx) => openPanel(liveCtx), theme: () => ctx.ui.theme }) ); const release = await ensureWorkPanel(ctx); if (generation !== workPanelGeneration) release(); else releaseWorkPanel = release; } if (!historyPruning.pending && Date.now() - historyPruning.lastRunAt >= HISTORY_PRUNE_INTERVAL_MS) { historyPruning.pending = true; const controller = new AbortController(); const previousLastRunAt = historyPruning.lastRunAt; let started = false; let aborted = false; let resolveDone = () => { }; const done = new Promise((resolve3) => { resolveDone = resolve3; }); const finish = () => { if (aborted || controller.signal.aborted) historyPruning.lastRunAt = previousLastRunAt; historyPruning.pending = false; cancelHistoryPruning = void 0; resolveDone(); }; const timer = setTimeout(async () => { started = true; try { if (controller.signal.aborted || notificationCtx !== ctx) return; const days = readSubagentsConfig(cwd).history_detail_retention_days ?? DEFAULT_HISTORY_DETAIL_RETENTION_DAYS; if (days === 0) return; historyPruning.lastRunAt = Date.now(); const history2 = new SubagentHistoryStore(); try { const result = await history2.pruneExecutionDetail({ olderThanMs: Date.now() - days * 864e5, waitUntilIdle: waitForHistoryIdle, signal: controller.signal }); aborted = result.aborted === true; } finally { history2.close(); } } catch (error) { console.error( "[pi-subagents] Failed to prune history execution detail:", error ); } finally { finish(); } }, HISTORY_PRUNE_DELAY_MS); timer.unref(); cancelHistoryPruning = () => { controller.abort(); if (!started) { clearTimeout(timer); finish(); } return done; }; } }); if (usageEvents && typeof pi.appendEntry === "function") pi.on?.("agent_end", () => usageEvents.flush()); pi.on?.("session_shutdown", async () => { unregisterLiveness?.(); unregisterLiveness = void 0; const canceledHistoryPruning = cancelHistoryPruning?.(); notificationOutbox.length = 0; rootRunActive = false; notificationCtx = void 0; manager.resetResultAcknowledgments(); publication?.withdraw(); publication = void 0; withdrawSubagentExternalToolDefinitions(toolDefinitionOwner); definitions.length = 0; activeSessionId = void 0; activeSessionOwner = void 0; registerSubagentsPanelOpener(void 0); clearWorkPanel(); taskStateEvents?.dispose(); try { await manager.close(); } catch (error) { console.error( "[pi-subagents] Failed to close subagent history during session shutdown:", error ); } finally { await canceledHistoryPruning; releaseHistoryActivity(); historyPruning.managers.delete(manager); notifyHistoryActivity(); providerLimits.dispose(); usageEvents?.dispose(); } }); if (taskStateEvents) { for (const event of ["session_tree", "session_compact"]) pi.on?.(event, (_event, ctx) => { taskStateEvents.startSession( ctx?.cwd ?? process.cwd(), currentSessionId2(ctx) ); }); } const historyPanelShortcut = readSubagentsConfig(process.cwd()).history_panel_shortcut ?? "ctrl+,"; pi.registerShortcut?.(historyPanelShortcut, { description: "Show subagent history panel", handler: (ctx) => openPanel(ctx) }); const detailCancelShortcut = readSubagentsConfig(process.cwd()).detail_cancel_shortcut ?? "x"; if (detailCancelShortcut.startsWith("ctrl+")) { pi.registerShortcut?.(detailCancelShortcut, { description: "Cancel selected running subagent from the active subagents detail panel", handler: async () => { activePanelCancelSelected?.(); activePanelRequestRender?.(); } }); } const backgroundHandoffShortcut = readSubagentsConfig(process.cwd()).background_handoff_shortcut ?? "ctrl+h"; pi.registerShortcut?.(backgroundHandoffShortcut, { description: "Send running subagent task to background", handler: async () => { triggerClaudeBackgroundHandoff(); } }); pi.registerCommand?.("subagents", { description: "Show subagent history panel", handler: (_args, ctx) => openPanel({ ...ctx, pi }) }); pi.registerCommand?.("subagents-history-compact", { description: "Prune expired execution detail and compact subagent history", handler: async (_args, ctx) => { ctx?.ui?.notify?.( "Compacting subagent history. VACUUM can need up to twice the database size in free disk space.", "warning" ); try { const days = readSubagentsConfig(ctx?.cwd ?? process.cwd()).history_detail_retention_days ?? DEFAULT_HISTORY_DETAIL_RETENTION_DAYS; const result = await SubagentHistoryStore.compactHistory({ olderThanMs: days === 0 ? void 0 : Date.now() - days * 864e5 }); ctx?.ui?.notify?.( `History compacted (database + WAL): ${result.beforeBytes.toLocaleString("en-US")} bytes \u2192 ${result.afterBytes.toLocaleString("en-US")} bytes.`, "info" ); } catch (error) { ctx?.ui?.notify?.( error instanceof Error ? error.message : String(error), "error" ); } } }); pi.registerCommand?.("subagents-model", { description: "Configure subagent model profiles", handler: async (_args, ctx) => ( // Preserve native context getters instead of freezing them with a spread. runSubagentModelsCommand( Object.assign(Object.create(ctx), { pi, getSessionModel: () => ctx.model, getSessionThinkingLevel: () => pi.getThinkingLevel(), getSessionModelProfile: () => sessionModelProfile.get(), setSessionModelProfile, applyEffectiveProfileOrchestrator: () => { const store = new ModelProfileStore({ cwd: ctx.cwd ?? process.cwd(), agentDir: ctx.agentDir }); return applyProfileOrchestrator( pi, ctx, store.resolve(sessionModelProfile.get()).profile ); } }) ) ) }); const checkToolsOwnership = registerToolsCommand(pi); } export { completionMessage, createSubagentsPanelKeyMatcher, createSubagentsWorkPanelProvider, subagentsExtension as default, renderSubagentCompletionMessage, resolveRegisteredToolDefinition, sendSubagentCompletionMessage };