import { r as utf8ByteLength } from "./utils-ngQzYzZD.js";
import { i as styleReplacementForVia, n as resolveOldString } from "./edit-utils-EGosADZq.js";
import { t as effectiveInputFromTurn } from "./stats-DAKBEKjc.js";
import { Fzf } from "fzf";
//#region src/chat/color-gradient.ts
/** Parse `#rrggbb` (case-insensitive) into `[r, g, b]` 0–255 integers. */
function parseHex(hex) {
	const h = hex.replace("#", "");
	return [
		Number.parseInt(h.slice(0, 2), 16),
		Number.parseInt(h.slice(2, 4), 16),
		Number.parseInt(h.slice(4, 6), 16)
	];
}
/** Convert sRGB 0–255 → HSL 0–1. */
function rgbToHsl(r, g, b) {
	r /= 255;
	g /= 255;
	b /= 255;
	const max = Math.max(r, g, b);
	const min = Math.min(r, g, b);
	const l = (max + min) / 2;
	if (max === min) return [
		0,
		0,
		l
	];
	const d = max - min;
	const s = l > .5 ? d / (2 - max - min) : d / (max + min);
	let h;
	if (max === r) h = (g - b) / d + (g < b ? 6 : 0);
	else if (max === g) h = (b - r) / d + 2;
	else h = (r - g) / d + 4;
	return [
		h / 6,
		s,
		l
	];
}
/** Convert HSL 0–1 → sRGB 0–255. Standard piecewise formula. */
function hslToRgb(h, s, l) {
	if (s === 0) return [
		l * 255,
		l * 255,
		l * 255
	];
	const hue2rgb = (p, q, t) => {
		if (t < 0) t += 1;
		if (t > 1) t -= 1;
		if (t < 1 / 6) return p + (q - p) * 6 * t;
		if (t < 1 / 2) return q;
		if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
		return p;
	};
	const q = l < .5 ? l * (1 + s) : l + s - l * s;
	const p = 2 * l - q;
	return [
		hue2rgb(p, q, h + 1 / 3) * 255,
		hue2rgb(p, q, h) * 255,
		hue2rgb(p, q, h - 1 / 3) * 255
	];
}
function toHex(rgb) {
	const pad = (v) => Math.round(Math.max(0, Math.min(255, v))).toString(16).padStart(2, "0");
	return `#${pad(rgb[0])}${pad(rgb[1])}${pad(rgb[2])}`;
}
/**
* Blend two hex colors in HSL space with shortest-path hue interpolation.
* `t` ∈ [0, 1]; `t=0` returns `from`, `t=1` returns `to`.
*/
function blendHsl(from, to, t) {
	const [r1, g1, b1] = parseHex(from);
	const [r2, g2, b2] = parseHex(to);
	const [h1, s1, l1] = rgbToHsl(r1, g1, b1);
	const [h2, s2, l2] = rgbToHsl(r2, g2, b2);
	let dh = h2 - h1;
	if (dh > .5) dh -= 1;
	else if (dh < -.5) dh += 1;
	return toHex(hslToRgb((h1 + dh * t + 1) % 1, s1 + (s2 - s1) * t, l1 + (l2 - l1) * t));
}
/**
* Static gradient ramp of length `n` going from `from` (index 0) to
* `to` (index n-1) in HSL space. For the cycling A→B→A→B ramp the
* throbber uses, see `buildCycleRamp` in `src/tui/crush-throbber.tsx`.
*/
function buildLinearRamp(from, to, n) {
	if (n <= 0) return [];
	if (n === 1) return [blendHsl(from, to, .5)];
	const ramp = [];
	for (let i = 0; i < n; i++) ramp.push(blendHsl(from, to, i / (n - 1)));
	return ramp;
}
//#endregion
//#region src/chat/completion-core.ts
/**
* Resolve the provider trigger active at `cursor`, or `null` when none fits.
*
* Rules:
*   - The trigger character must sit at position 0 of the buffer OR be
*     preceded by whitespace. This prevents `http://` from triggering the
*     `/`-bound skills provider mid-URL.
*   - The cursor must be at or past the trigger position.
*   - Nothing between the trigger and the cursor may be whitespace (the
*     query is one contiguous token).
*   - The query length is bounded — `maxQueryLength` defaults to 64 — so
*     a runaway buffer scan can't pin the renderer.
*/
function findActiveTrigger(text, cursor, providers, options = {}) {
	if (providers.length === 0) return null;
	const max = options.maxQueryLength ?? 64;
	const safeCursor = Math.max(0, Math.min(cursor, text.length));
	const isWhitespace = (ch) => ch === void 0 ? false : /\s/.test(ch);
	for (let i = safeCursor - 1; i >= 0 && safeCursor - i <= max + 1; i--) {
		const ch = text[i];
		if (isWhitespace(ch)) return null;
		const provider = providers.find((p) => p.trigger === ch);
		if (!provider) continue;
		const before = i > 0 ? text[i - 1] : "";
		if (before !== "" && !isWhitespace(before)) continue;
		return {
			provider,
			query: text.slice(i + 1, safeCursor),
			span: {
				start: i,
				end: safeCursor
			}
		};
	}
	return null;
}
/**
* Replace `[span.start, span.end)` in `text` with `insertText`. Returns the
* mutated text and the new cursor position (end of insertion).
*/
function applyInsert(text, span, insertText) {
	return {
		text: text.slice(0, span.start) + insertText + text.slice(span.end),
		cursor: span.start + insertText.length
	};
}
/**
* Merge reference lists from multiple providers into one ordered list with
* earlier-start-wins disambiguation when spans overlap. Ties broken by
* insertion order. Spans are sorted ascending so renderers can walk them
* sequentially with a cursor through the source string.
*/
function mergeReferences(refs) {
	const sorted = [...refs].sort((a, b) => a.start - b.start);
	const merged = [];
	let lastEnd = -1;
	for (const ref of sorted) {
		if (ref.start < lastEnd) continue;
		merged.push(ref);
		lastEnd = ref.end;
	}
	return merged;
}
/**
* Collect every provider's references in one pass. Convenience wrapper —
* the TUI textarea component calls this on every keystroke to highlight
* in-prompt mentions.
*/
function collectReferences(text, providers, cursor = text.length) {
	const ctx = {
		text,
		cursor
	};
	const refs = [];
	for (const p of providers) for (const ref of p.parseReferences(text, ctx)) refs.push(ref);
	return mergeReferences(refs);
}
//#endregion
//#region src/chat/completion-files.ts
/** Trigger character — `@` is the conventional file-mention prefix in chat UIs. */
const FILES_TRIGGER = "@";
/** Cap on returned items. Keeps the popover compact + render-cheap. */
const DEFAULT_RESULT_LIMIT = 50;
/** Identity formatter — preserves the discovery path verbatim. */
const IDENTITY_FORMAT = (entry) => entry.path;
/**
* Rank-and-slice a file catalog against a query. Hoisted to a module
* helper so both the sync and async branches of `suggest()` share one
* implementation (the async branch hits this once the lazy directory
* walk resolves; sync branch hits it on every keystroke thereafter).
*
* `formatPath` rewrites the catalog's project-root-relative path into
* the form the host wants emitted into the prompt (typically CWD-rel
* or absolute when launched from a project subdir — see
* `formatPathForCwd` in `path-display.ts`). Falls back to the raw
* `entry.path` when omitted.
*/
function scoreFiles(catalog, query, limit, formatPath) {
	const q = query.trim().toLowerCase();
	const fuzzyHits = q.length > 0 ? new Set(new Fzf([...catalog], {
		selector: (f) => f.name,
		casing: "case-insensitive"
	}).find(q).map((r) => r.item)) : null;
	const scored = [];
	for (const file of catalog) {
		const display = formatPath(file);
		const name = file.name.toLowerCase();
		const path = display.toLowerCase();
		if (q.length === 0) {
			scored.push({
				entry: file,
				display,
				rank: 5
			});
			continue;
		}
		if (name === q) {
			scored.push({
				entry: file,
				display,
				rank: 0
			});
			continue;
		}
		if (name.startsWith(q)) {
			scored.push({
				entry: file,
				display,
				rank: 1
			});
			continue;
		}
		if (name.includes(q)) {
			scored.push({
				entry: file,
				display,
				rank: 2
			});
			continue;
		}
		if (path.includes(q)) {
			scored.push({
				entry: file,
				display,
				rank: 3
			});
			continue;
		}
		if (fuzzyHits?.has(file)) {
			scored.push({
				entry: file,
				display,
				rank: 4
			});
			continue;
		}
	}
	scored.sort((a, b) => {
		if (a.rank !== b.rank) return a.rank - b.rank;
		return a.display.localeCompare(b.display);
	});
	return scored.slice(0, limit).map(({ entry, display }) => ({
		id: display,
		label: entry.name,
		description: parentDir(entry.path),
		insertText: `@${display} `,
		data: entry
	}));
}
/**
* Build an `@`-prefixed files completion provider against a *live* catalog.
*
* The factory captures a getter so the catalog can be re-scanned (cwd
* change, manual refresh) without re-instantiating the provider — the
* App keeps one provider for the lifetime of the prompt block and just
* mutates the underlying state.
*
* `limit` caps the result list so the popover stays bounded on huge
* monorepos. Filtering is substring on `path` + `name`, case-insensitive,
* with an fzf-scored basename fuzzy fallback so small typos / omissions
* (`lop.ts` → `loop.ts`) still surface results; ranking prefers (in
* order): exact name match, name prefix, name substring, path substring,
* basename fuzzy match, alphabetical.
*/
function createFilesCompletionProvider(opts) {
	const limit = opts.limit ?? DEFAULT_RESULT_LIMIT;
	const formatPath = opts.formatPath ?? IDENTITY_FORMAT;
	return {
		id: "files",
		trigger: "@",
		label: "Files",
		suggest(query) {
			if (opts.ensureCatalog) {
				const pending = opts.ensureCatalog();
				if (opts.getCatalog().length === 0) return pending.then((loaded) => scoreFiles(loaded, query, limit, formatPath));
			}
			return scoreFiles(opts.getCatalog(), query, limit, formatPath);
		},
		parseReferences(text, _ctx) {
			const catalog = opts.getCatalog();
			if (catalog.length === 0) return [];
			const byPath = /* @__PURE__ */ new Map();
			for (const file of catalog) byPath.set(formatPath(file), file);
			const refs = [];
			for (const m of text.matchAll(/(^|\s)@(\S+)/g)) {
				const rawCandidate = m[2];
				const stripped = byPath.has(rawCandidate) ? rawCandidate : rawCandidate.replace(/[.,;:)\]}!?]+$/, "");
				const file = byPath.get(stripped);
				if (!file) continue;
				const start = m.index + m[1].length;
				const trimmedLen = 1 + stripped.length;
				refs.push({
					providerId: "files",
					start,
					end: start + trimmedLen,
					itemId: stripped,
					data: file
				});
			}
			return refs;
		}
	};
}
/** Return the parent directory of a forward-slashed path, or `''` for root entries. */
function parentDir(path) {
	const lastSlash = path.lastIndexOf("/");
	return lastSlash <= 0 ? "" : path.slice(0, lastSlash);
}
/**
* Walk a reference list and return the deduplicated set of files in
* first-mention order — input to "attach these files to the prompt"
* downstream logic.
*/
function uniqueFilesFromReferences(references) {
	const out = [];
	const seen = /* @__PURE__ */ new Set();
	for (const ref of references) {
		if (ref.providerId !== "files") continue;
		if (seen.has(ref.itemId)) continue;
		seen.add(ref.itemId);
		out.push(ref.data);
	}
	return out;
}
//#endregion
//#region src/chat/completion-skills.ts
/** Trigger character — slash-commands convention. */
const SKILLS_TRIGGER = "/";
/** Valid skill-name shape (matches the parser): lowercase alnum + dashes. */
const SKILL_NAME_RX = /^[a-z0-9][a-z0-9-]*$/;
/**
* Filter + rank visible skills against a query. Hoisted to a module
* helper so the sync and async branches of `suggest()` share one
* implementation (the async branch hits this once the lazy SKILL.md
* scan resolves; sync branch hits it on every keystroke thereafter).
*/
function scoreSkills(catalog, query) {
	const q = query.trim().toLowerCase();
	const valid = catalog.filter((skill) => SKILL_NAME_RX.test(skill.name));
	const fuzzyHits = q.length > 0 ? new Set(new Fzf(valid, {
		selector: (s) => s.name,
		casing: "case-insensitive"
	}).find(q).map((r) => r.item)) : null;
	const scored = [];
	for (const skill of valid) {
		const name = skill.name.toLowerCase();
		const desc = skill.description.toLowerCase();
		if (q.length === 0) {
			scored.push({
				skill,
				rank: 4
			});
			continue;
		}
		if (name.startsWith(q)) {
			scored.push({
				skill,
				rank: 0
			});
			continue;
		}
		if (name.includes(q)) {
			scored.push({
				skill,
				rank: 1
			});
			continue;
		}
		if (desc.includes(q)) {
			scored.push({
				skill,
				rank: 2
			});
			continue;
		}
		if (fuzzyHits?.has(skill)) {
			scored.push({
				skill,
				rank: 3
			});
			continue;
		}
	}
	scored.sort((a, b) => {
		if (a.rank !== b.rank) return a.rank - b.rank;
		return a.skill.name.localeCompare(b.skill.name);
	});
	return scored.map(({ skill }) => ({
		id: skill.name,
		label: skill.name,
		description: skill.description,
		insertText: `/${skill.name} `,
		data: skill
	}));
}
/**
* Build a slash-command completion provider against a *live* skills
* catalog. The factory captures a getter so the catalog can change across
* renders (toggles, reload) without re-instantiating the provider.
*
* Pass `getEnabled` to additionally hide skills the user has toggled off
* — when undefined, every catalog entry is offered.
*/
function createSkillsCompletionProvider(opts) {
	const visible = () => {
		const all = opts.getCatalog();
		const enabled = opts.getEnabled?.();
		if (enabled === void 0) return [...all];
		const allow = new Set(enabled);
		return all.filter((s) => allow.has(s.name));
	};
	return {
		id: "skills",
		trigger: "/",
		label: "Skills",
		suggest(query) {
			if (opts.ensureCatalog) {
				const pending = opts.ensureCatalog();
				if (opts.getCatalog().length === 0) return pending.then(() => scoreSkills(visible(), query));
			}
			return scoreSkills(visible(), query);
		},
		parseReferences(text, _ctx) {
			const catalog = visible();
			if (catalog.length === 0) return [];
			const byName = /* @__PURE__ */ new Map();
			for (const skill of catalog) byName.set(skill.name, skill);
			const refs = [];
			for (const m of text.matchAll(/(^|\s)(\/([a-z0-9][a-z0-9-]*))/g)) {
				const name = m[3];
				const skill = byName.get(name);
				if (!skill) continue;
				const start = m.index + m[1].length;
				refs.push({
					providerId: "skills",
					start,
					end: start + m[2].length,
					itemId: skill.name,
					data: skill
				});
			}
			return refs;
		}
	};
}
/**
* Walk a parsed prompt for skill references and return the deduplicated
* list of skill names — input to `agent.activateSkill(name)` calls on
* submit.
*/
function uniqueSkillNamesFromReferences(references) {
	const out = [];
	const seen = /* @__PURE__ */ new Set();
	for (const ref of references) {
		if (ref.providerId !== "skills") continue;
		if (seen.has(ref.itemId)) continue;
		seen.add(ref.itemId);
		out.push(ref.itemId);
	}
	return out;
}
//#endregion
//#region src/chat/edit-approval.ts
/**
* Convert a per-hunk approval mask into an `EditOutcome[]`. `true` →
* `applied`; `false` → `denied` with the supplied reason.
*
* Length is `Math.max(mask.length, fallbackLength)` so callers passing a
* shorter mask still get a fully-populated array — missing entries
* default to applied, matching the "no decision => keep" convention.
*/
function maskToOutcomeKinds(mask, fallbackLength, deniedReason = "denied by user") {
	const len = Math.max(mask.length, fallbackLength);
	const out = [];
	for (let i = 0; i < len; i++) {
		const keep = i < mask.length ? mask[i] : true;
		out.push(keep ? { kind: "applied" } : {
			kind: "denied",
			reason: deniedReason
		});
	}
	return out;
}
function resolveApprovalForPayload(decision, payload) {
	const total = payload.hunks.length;
	if (decision === "deny") {
		const outcomes = Array.from({ length: total }, () => ({
			kind: "denied",
			reason: "denied by user"
		}));
		return {
			outcomes,
			shouldBlock: true,
			syntheticEvent: {
				...payload,
				outcomes
			}
		};
	}
	if (typeof decision === "object" && decision.kind === "partial") {
		const outcomes = maskToOutcomeKinds(decision.mask, total);
		return {
			outcomes,
			shouldBlock: !outcomes.some((o) => o.kind === "applied"),
			syntheticEvent: {
				...payload,
				outcomes
			}
		};
	}
	return {
		outcomes: Array.from({ length: total }, () => ({ kind: "applied" })),
		shouldBlock: false,
		syntheticEvent: null
	};
}
/** Sentinel tags used by {@link buildEditOutcomesAnnotation} / parser. */
const ANNOTATION_OPEN = "<edit-outcomes>";
const ANNOTATION_CLOSE = "</edit-outcomes>";
const OUTCOME_KIND_RE = /^applied|denied|skipped|failed$/;
const OUTCOME_LINE_RE = /^#(\d+) (applied|denied|skipped|failed)(?:: ?(.*))?$/;
/**
* Render an `EditOutcome[]` as the wire-format annotation block. Returns
* the body to APPEND to a tool result; callers join with a leading
* `\n\n` separator. Idempotent on missing reasons — bare `applied` lines
* stay terse.
*/
function buildEditOutcomesAnnotation(outcomes) {
	const lines = [ANNOTATION_OPEN];
	for (let i = 0; i < outcomes.length; i++) {
		const o = outcomes[i];
		if (!OUTCOME_KIND_RE.test(o.kind)) continue;
		const reason = o.reason ? `: ${o.reason}` : "";
		lines.push(`#${i + 1} ${o.kind}${reason}`);
	}
	lines.push(ANNOTATION_CLOSE);
	return lines.join("\n");
}
/**
* Parse an `<edit-outcomes>…</edit-outcomes>` annotation block out of a
* tool result body. Returns the outcomes keyed by 1-based hunk index, or
* `null` when the block is missing / malformed.
*
* Anchored on the explicit tag pair so the parser doesn't false-positive
* on natural prose that happens to contain `#1 applied`.
*/
function parseEditOutcomesFromResult(result) {
	const text = typeof result === "string" ? result : result.filter((b) => b.type === "text").map((b) => b.text).join("\n");
	if (!text) return null;
	const openIdx = text.indexOf(`\n${ANNOTATION_OPEN}\n`);
	const startIdx = openIdx >= 0 ? openIdx + 1 : text.startsWith(`${ANNOTATION_OPEN}\n`) ? 0 : -1;
	if (startIdx < 0) return null;
	const closeNeedle = `\n${ANNOTATION_CLOSE}`;
	const closeIdx = text.indexOf(closeNeedle, startIdx);
	if (closeIdx < 0) return null;
	const body = text.slice(startIdx + 15 + 1, closeIdx);
	const found = [];
	for (const line of body.split("\n")) {
		if (line.length === 0) continue;
		const m = OUTCOME_LINE_RE.exec(line);
		if (!m) return null;
		const idx = Number.parseInt(m[1], 10);
		if (!Number.isFinite(idx) || idx < 1) return null;
		const kind = m[2];
		const reason = m[3]?.trim();
		found.push({
			idx,
			outcome: {
				kind,
				...reason ? { reason } : {}
			}
		});
	}
	if (found.length === 0) return null;
	const maxIdx = Math.max(...found.map((f) => f.idx));
	const outcomes = Array.from({ length: maxIdx }, () => ({ kind: "applied" }));
	for (const { idx, outcome } of found) outcomes[idx - 1] = outcome;
	return outcomes;
}
/**
* Strip the first `<edit-outcomes>…</edit-outcomes>` block out of a tool
* result body, returning the surrounding text. Used by the
* `tool:transform` hook to peel a body-emitted annotation before
* re-appending the merged (approval ∪ body) version — otherwise the
* result would carry two annotation blocks and
* {@link parseEditOutcomesFromResult} would only see the first.
*
* Anchored on the same `\n<edit-outcomes>\n` / start-of-string newline
* shape the parser uses, so prose that incidentally mentions
* `<edit-outcomes>` (e.g. a model summarizing its own format) isn't
* mistakenly stripped. Trims a single leading `\n\n` separator when
* present so successive strips don't leave dangling blank lines.
* Idempotent on inputs that don't contain a properly-anchored block.
*/
function stripEditOutcomesAnnotation(text) {
	const newlineNeedle = `\n${ANNOTATION_OPEN}\n`;
	const newlineIdx = text.indexOf(newlineNeedle);
	let openIdx;
	if (newlineIdx >= 0) openIdx = newlineIdx + 1;
	else if (text.startsWith(`${ANNOTATION_OPEN}\n`)) openIdx = 0;
	else return text;
	const closeIdx = text.indexOf(ANNOTATION_CLOSE, openIdx);
	if (closeIdx < 0) return text;
	const blockEnd = closeIdx + 16;
	const sepStart = openIdx >= 2 && text.slice(openIdx - 2, openIdx) === "\n\n" ? openIdx - 2 : openIdx;
	return text.slice(0, sepStart) + text.slice(blockEnd);
}
/**
* Merge body-side outcomes (keyed against the approved subset the tool
* actually ran on, in subset-position order) into approval-side outcomes
* (1:1 with the model's ORIGINAL `edits` list, with `denied` entries for
* every hunk the user dropped).
*
* Algorithm: walk the approval array; every `applied` placeholder
* corresponds to one approved hunk that the body ran. Consume body's
* outcomes in order against those placeholders. Non-`applied` approval
* entries (`denied`, `skipped`) stay untouched — they describe gate-
* level decisions the body never saw.
*
* Pure. Returns a fresh array; never mutates either input.
*
* Edge cases:
*  - `body` is empty / shorter than the approved count → remaining
*    approval `applied` placeholders stay as `applied` (the body ran
*    happily; absence of a body entry means nothing failed).
*  - `body` longer than approved count → trailing body entries are
*    ignored. Shouldn't happen in practice (body sees the rebound
*    subset), but the guard keeps the merge total-pure.
*/
function mergeApprovalAndBodyOutcomes(approval, body) {
	if (!body || body.length === 0) return approval.slice();
	const out = [];
	let bi = 0;
	for (const entry of approval) if (entry.kind === "applied" && bi < body.length) {
		out.push(body[bi]);
		bi++;
	} else out.push(entry);
	return out;
}
/**
* Rewrite a `multi_edit` body header so the totals reflect the model's
* ORIGINAL edit list (the merged outcomes count) instead of the subset
* the body actually saw after gate rebinding. Without this, a partially
* approved call surfaces a misleading `applied 2 of 2 edits` (subset
* counts) on the wire even when the original was `applied 2 of 3`.
*
* Three body-side shapes are handled (matching `multi_edit`'s emit):
*   1. `Edited <path>: applied N edits (R replacements).`
*   2. `Edited <path>: applied N of M edits (R replacements).`
*   3. `multi_edit error: no edits applied to <path> (M attempted).`
*
* The replacements count is preserved verbatim — it's a body-side stat
* the chat layer can't recompute. When the first line doesn't look like
* any of the three shapes (e.g. an unrelated error preamble bubbled up),
* the text is returned unchanged.
*/
function rewriteMultiEditHeader(text, merged, path) {
	const newlineIdx = text.indexOf("\n");
	const firstLine = newlineIdx < 0 ? text : text.slice(0, newlineIdx);
	const rest = newlineIdx < 0 ? "" : text.slice(newlineIdx);
	const successMatch = firstLine.match(/^Edited .+: applied \d+(?: of \d+)? edits? \((\d+) replacement/);
	const isFailedShape = firstLine.startsWith("multi_edit error: no edits applied to ") && firstLine.endsWith(" attempted).");
	if (!successMatch && !isFailedShape) return text;
	const replacements = successMatch ? Number.parseInt(successMatch[1], 10) || 0 : 0;
	const applied = summarizeOutcomes(merged).applied;
	const total = merged.length;
	let newHeader;
	if (applied === total) newHeader = `Edited ${path}: applied ${total} edit${total === 1 ? "" : "s"} (${replacements} replacement${replacements === 1 ? "" : "s"}).`;
	else if (applied > 0) newHeader = `Edited ${path}: applied ${applied} of ${total} edits (${replacements} replacement${replacements === 1 ? "" : "s"}).`;
	else newHeader = `multi_edit error: no edits applied to ${path} (${total} attempted).`;
	return newHeader + rest;
}
/**
* Aggregate counts for the transcript's summary badge (`3 applied · 1
* denied · 1 skipped`). Exported so renderers don't reimplement the
* tally. Pure / O(n).
*/
function summarizeOutcomes(outcomes) {
	const counts = {
		applied: 0,
		denied: 0,
		skipped: 0,
		failed: 0,
		pending: 0
	};
	if (!outcomes) return {
		...counts,
		total: 0
	};
	for (const o of outcomes) counts[o.kind] += 1;
	return {
		...counts,
		total: outcomes.length
	};
}
//#endregion
//#region src/chat/edit-diff.ts
function extractEditPayload(name, input, priorContent) {
	const path = input.path;
	if (typeof path !== "string" || path === "") return void 0;
	if (name === "edit") {
		const oldString = input.old_string;
		const newString = input.new_string;
		if (typeof oldString !== "string" || typeof newString !== "string") return void 0;
		return {
			tool: "edit",
			path,
			hunks: [{
				oldString,
				newString,
				...input.replace_all === true ? { replaceAll: true } : {}
			}],
			...priorContent !== void 0 ? { priorContent } : {}
		};
	}
	if (name === "multi_edit") {
		const steps = input.edits;
		if (!Array.isArray(steps) || steps.length === 0) return void 0;
		const hunks = [];
		for (const raw of steps) {
			if (typeof raw?.old_string !== "string" || typeof raw?.new_string !== "string") return void 0;
			hunks.push({
				oldString: raw.old_string,
				newString: raw.new_string,
				...raw.replace_all === true ? { replaceAll: true } : {}
			});
		}
		return {
			tool: "multi_edit",
			path,
			hunks,
			...priorContent !== void 0 ? { priorContent } : {}
		};
	}
	if (name === "write_file") {
		const content = input.content;
		if (typeof content !== "string") return void 0;
		return {
			tool: "write_file",
			path,
			hunks: [{
				oldString: priorContent ?? "",
				newString: content
			}],
			...priorContent !== void 0 ? { priorContent } : {}
		};
	}
}
function computeLineDiff(oldString, newString) {
	const oldLines = splitLines(oldString);
	const newLines = splitLines(newString);
	const n = oldLines.length;
	const m = newLines.length;
	const lcs = Array.from({ length: n + 1 }, () => Array.from({ length: m + 1 }).fill(0));
	for (let i = 0; i < n; i++) for (let j = 0; j < m; j++) lcs[i + 1][j + 1] = oldLines[i] === newLines[j] ? lcs[i][j] + 1 : Math.max(lcs[i][j + 1], lcs[i + 1][j]);
	const out = [];
	let i = n;
	let j = m;
	while (i > 0 || j > 0) {
		if (i > 0 && j > 0 && oldLines[i - 1] === newLines[j - 1]) {
			out.push({
				op: "context",
				text: oldLines[i - 1]
			});
			i--;
			j--;
			continue;
		}
		if (j > 0 && (i === 0 || lcs[i][j - 1] >= lcs[i - 1][j])) {
			out.push({
				op: "add",
				text: newLines[j - 1]
			});
			j--;
			continue;
		}
		out.push({
			op: "remove",
			text: oldLines[i - 1]
		});
		i--;
	}
	out.reverse();
	return out;
}
/**
* Split a string into lines preserving empty lines but dropping the
* implicit trailing `""` produced by a final `\n`. Exported only for
* its tests — callers should use `computeLineDiff`.
*/
function splitLines(s) {
	if (s === "") return [];
	const parts = s.split("\n");
	if (parts[parts.length - 1] === "") parts.pop();
	return parts;
}
function computeInlineDiff(oldLine, newLine) {
	const oldTokens = tokenize(oldLine);
	const newTokens = tokenize(newLine);
	const n = oldTokens.length;
	const m = newTokens.length;
	const lcs = Array.from({ length: n + 1 }, () => Array.from({ length: m + 1 }).fill(0));
	for (let i = 0; i < n; i++) for (let j = 0; j < m; j++) lcs[i + 1][j + 1] = oldTokens[i] === newTokens[j] ? lcs[i][j] + 1 : Math.max(lcs[i][j + 1], lcs[i + 1][j]);
	const oldSegments = [];
	const newSegments = [];
	let i = n;
	let j = m;
	while (i > 0 || j > 0) {
		if (i > 0 && j > 0 && oldTokens[i - 1] === newTokens[j - 1]) {
			pushSegment(oldSegments, {
				text: oldTokens[i - 1],
				changed: false
			});
			pushSegment(newSegments, {
				text: newTokens[j - 1],
				changed: false
			});
			i--;
			j--;
			continue;
		}
		if (j > 0 && (i === 0 || lcs[i][j - 1] >= lcs[i - 1][j])) {
			pushSegment(newSegments, {
				text: newTokens[j - 1],
				changed: true
			});
			j--;
			continue;
		}
		pushSegment(oldSegments, {
			text: oldTokens[i - 1],
			changed: true
		});
		i--;
	}
	oldSegments.reverse();
	newSegments.reverse();
	return {
		oldSegments,
		newSegments
	};
}
/**
* Coalesce adjacent same-state segments so the renderer emits one
* `<span>` per run instead of one per token — keeps the React tree
* shallow on dense lines without changing the visual output.
*
* Walking direction is reverse (we push during the reverse walk, then
* the caller reverses the array), so we coalesce against the *tail*.
*/
function pushSegment(buf, seg) {
	const tail = buf[buf.length - 1];
	if (tail && tail.changed === seg.changed) tail.text = seg.text + tail.text;
	else buf.push(seg);
}
/**
* Tokenize on word / non-word boundaries. Each run of `\w+` is one
* token; each run of `\W+` (whitespace, punctuation) is another. This
* gives the right granularity for renames (`oldName` → `newName`) and
* for symbol swaps (`+ → -`) without exploding into per-char segments.
*
* Exported only for its tests.
*/
function tokenize(s) {
	if (s === "") return [];
	const out = [];
	for (const match of s.matchAll(/\w+|\W+/g)) out.push(match[0]);
	return out;
}
/**
* Apply the payload's hunks against `priorContent` and return the
* resulting file body. Mirrors the agent's tool-side semantics:
*   - `replaceAll === true`  → `String.replaceAll`
*   - otherwise              → first-occurrence `String.replace`
*
* Hunks are applied in order — a `multi_edit` later hunk operates on
* the output of the earlier ones, just like the actual tool.
*/
function applyEditPayload(payload, priorContent) {
	let out = priorContent;
	for (const hunk of payload.hunks) out = hunk.replaceAll ? out.replaceAll(hunk.oldString, hunk.newString) : out.replace(hunk.oldString, hunk.newString);
	return out;
}
/**
* Like `buildUnifiedDiff` but operating against the full file content
* so the diff carries *real* file line numbers and configurable
* surrounding context.
*
* Strategy:
*   1. Apply the payload to `priorContent` → `newContent`.
*   2. Run `computeLineDiff` over the whole file.
*   3. Group non-context ops into hunks, padding each with up to
*      `contextLines` of context above and below. Adjacent hunks
*      whose context regions touch are merged so we don't emit two
*      `@@` headers separated by zero context lines.
*
* The output line numbers in the `@@` header are 1-based and reflect
* the change's position in the actual file — what the user expects
* when reading a diff alongside their editor.
*
* For `write_file` creating a new file (priorContent === ''), this
* falls back to the same `--- /dev/null` convention as
* `buildUnifiedDiff`.
*/
function buildContextualDiff(payload, priorContent, contextLines = 3) {
	const newContent = applyEditPayload(payload, priorContent);
	const isNewFile = priorContent === "";
	const ops = computeLineDiff(priorContent, newContent);
	const oldLineFor = [];
	const newLineFor = [];
	let ol = 1;
	let nl = 1;
	for (const op of ops) {
		oldLineFor.push(ol);
		newLineFor.push(nl);
		if (op.op !== "add") ol++;
		if (op.op !== "remove") nl++;
	}
	const hunks = [];
	for (let i = 0; i < ops.length; i++) {
		if (ops[i].op === "context") continue;
		const start = Math.max(0, i - contextLines);
		const end = Math.min(ops.length - 1, i + contextLines);
		const last = hunks[hunks.length - 1];
		if (last && start <= last[1] + 1) last[1] = Math.max(last[1], end);
		else hunks.push([start, end]);
	}
	if (hunks.length === 0) return "";
	const parts = [];
	parts.push(isNewFile ? "--- /dev/null" : `--- a/${payload.path}`);
	parts.push(`+++ b/${payload.path}`);
	for (const [start, end] of hunks) {
		const slice = ops.slice(start, end + 1);
		const oldCount = slice.filter((l) => l.op !== "add").length;
		const newCount = slice.filter((l) => l.op !== "remove").length;
		const oldStart = oldCount === 0 ? Math.max(0, oldLineFor[start] - 1) : oldLineFor[start];
		const newStart = newCount === 0 ? Math.max(0, newLineFor[start] - 1) : newLineFor[start];
		parts.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`);
		for (const line of slice) {
			const prefix = line.op === "add" ? "+" : line.op === "remove" ? "-" : " ";
			parts.push(`${prefix}${line.text}`);
		}
	}
	return `${parts.join("\n")}\n`;
}
/**
* Build a per-hunk digest used by the compact diff view.
*
* Strategy:
*  - When `priorContent` is present and the payload describes a real
*    file transformation, compute the contextual diff once, then walk
*    the LCS ops splitting at runs of `add` / `remove` to anchor each
*    summary entry to the **real** file line. This guarantees the
*    summary's `L<n>` matches what the user sees in their editor.
*  - Otherwise, fall back to per-hunk LCS over the (oldString,
*    newString) snippet pair. Line numbers are absent because the
*    snippet has no file position.
*/
function summarizeEditPayload(payload) {
	const prior = payload.priorContent;
	if (prior !== void 0) return summarizeOpsByHunk(computeLineDiff(prior, applyEditPayload(payload, prior)));
	const hunks = [];
	let totalAdded = 0;
	let totalRemoved = 0;
	for (const hunk of payload.hunks) {
		const ops = computeLineDiff(hunk.oldString, hunk.newString);
		let added = 0;
		let removed = 0;
		let firstOld;
		let firstNew;
		for (const op of ops) if (op.op === "add") {
			added++;
			if (firstNew === void 0) firstNew = op.text;
		} else if (op.op === "remove") {
			removed++;
			if (firstOld === void 0) firstOld = op.text;
		}
		totalAdded += added;
		totalRemoved += removed;
		hunks.push({
			added,
			removed,
			...firstOld !== void 0 ? { firstOld } : {},
			...firstNew !== void 0 ? { firstNew } : {}
		});
	}
	return {
		totalAdded,
		totalRemoved,
		hunks
	};
}
/**
* Walk an LCS op stream and emit one summary entry per *run* of
* non-context ops, with the new-file line number where each run
* starts. Adjacent add/remove ops collapse into the same entry —
* matches git's hunk grouping at zero context.
*/
function summarizeOpsByHunk(ops) {
	const hunks = [];
	let totalAdded = 0;
	let totalRemoved = 0;
	let nl = 1;
	let i = 0;
	while (i < ops.length) {
		if (ops[i].op === "context") {
			nl++;
			i++;
			continue;
		}
		const runStartLine = nl;
		let added = 0;
		let removed = 0;
		let firstOld;
		let firstNew;
		while (i < ops.length && ops[i].op !== "context") {
			const cur = ops[i];
			if (cur.op === "add") {
				added++;
				if (firstNew === void 0) firstNew = cur.text;
				nl++;
			} else {
				removed++;
				if (firstOld === void 0) firstOld = cur.text;
			}
			i++;
		}
		totalAdded += added;
		totalRemoved += removed;
		hunks.push({
			line: runStartLine,
			added,
			removed,
			...firstOld !== void 0 ? { firstOld } : {},
			...firstNew !== void 0 ? { firstNew } : {}
		});
	}
	return {
		totalAdded,
		totalRemoved,
		hunks
	};
}
function previewEditPayload(payload, priorContent, contextLines = 3) {
	const resolution = [];
	const resolvedHunks = [];
	const perHunkDiff = [];
	let running = priorContent;
	for (const hunk of payload.hunks) {
		if (hunk.oldString === "" || hunk.oldString === running) {
			resolution.push({
				resolved: true,
				via: "exact",
				occurrences: 1
			});
			resolvedHunks.push(hunk);
			perHunkDiff.push(buildContextualDiff({
				...payload,
				hunks: [hunk]
			}, running, contextLines));
			running = hunk.newString;
			continue;
		}
		const match = resolveOldString(running, hunk.oldString);
		if (!match) {
			resolution.push({ resolved: false });
			resolvedHunks.push(hunk);
			perHunkDiff.push("");
			continue;
		}
		const ambiguous = match.occurrences > 1 && !hunk.replaceAll;
		const styledNew = styleReplacementForVia(hunk.newString, match.via, match.actual);
		const resolvedHunk = {
			oldString: match.actual,
			newString: styledNew,
			...hunk.replaceAll ? { replaceAll: true } : {}
		};
		resolution.push({
			resolved: !ambiguous,
			via: match.via,
			occurrences: match.occurrences,
			...ambiguous ? { ambiguous: true } : {}
		});
		resolvedHunks.push(resolvedHunk);
		perHunkDiff.push(ambiguous ? "" : buildContextualDiff({
			...payload,
			hunks: [resolvedHunk]
		}, running, contextLines));
		if (!ambiguous) running = hunk.replaceAll ? running.replaceAll(match.actual, styledNew) : running.replace(match.actual, styledNew);
	}
	const resolvedPayload = {
		...payload,
		hunks: resolvedHunks
	};
	const applicableHunks = resolvedHunks.filter((_, i) => resolution[i].resolved);
	return {
		diffText: applicableHunks.length === 0 ? "" : buildContextualDiff({
			...payload,
			hunks: applicableHunks
		}, priorContent, contextLines),
		resolution,
		perHunkDiff,
		resolvedPayload
	};
}
function buildUnifiedDiff(payload) {
	const parts = [];
	const isNewFile = payload.tool === "write_file" && payload.hunks[0]?.oldString === "";
	parts.push(isNewFile ? `--- /dev/null` : `--- a/${payload.path}`);
	parts.push(`+++ b/${payload.path}`);
	for (const hunk of payload.hunks) {
		const lines = computeLineDiff(hunk.oldString, hunk.newString);
		const oldCount = lines.filter((l) => l.op !== "add").length;
		const newCount = lines.filter((l) => l.op !== "remove").length;
		const oldStart = oldCount === 0 ? 0 : 1;
		const newStart = newCount === 0 ? 0 : 1;
		parts.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`);
		for (const line of lines) {
			const prefix = line.op === "add" ? "+" : line.op === "remove" ? "-" : " ";
			parts.push(`${prefix}${line.text}`);
		}
	}
	return `${parts.join("\n")}\n`;
}
const FILETYPE_BY_EXT = {
	ts: "typescript",
	mts: "typescript",
	cts: "typescript",
	tsx: "tsx",
	js: "javascript",
	mjs: "javascript",
	cjs: "javascript",
	jsx: "jsx",
	py: "python",
	pyi: "python",
	rs: "rust",
	go: "go",
	json: "json",
	jsonc: "json",
	sh: "bash",
	bash: "bash",
	zsh: "bash",
	yaml: "yaml",
	yml: "yaml",
	html: "html",
	htm: "html",
	css: "css",
	md: "markdown",
	markdown: "markdown"
};
function filetypeFromPath(path) {
	const cleaned = path.split(/[?#]/, 1)[0];
	const lastDot = cleaned.lastIndexOf(".");
	if (lastDot === -1 || lastDot === cleaned.length - 1) return void 0;
	return FILETYPE_BY_EXT[cleaned.slice(lastDot + 1).toLowerCase()];
}
//#endregion
//#region src/chat/turn-selection.ts
/** Tools whose `tool-result` event is suppressed when `showEditDiffs` is on. */
const EDIT_TOOL_NAMES = new Set([
	"edit",
	"multi_edit",
	"write_file"
]);
/**
* Recognize a tool-result body as carrying NON-success information so the
* renderer doesn't suppress it under `showEditDiffs`. Three categories:
*
*   - `edit` → "Edit error: …"
*   - `write_file` permission errors wrapped by the loop → "Tool failed: …"
*   - `multi_edit` → legacy single-line error `multi_edit error: …`, OR
*     a result carrying an `<edit-outcomes>…</edit-outcomes>` annotation
*     block. The TUI only appends the annotation when at least one hunk
*     was NOT applied, so its mere presence is the signal — the result
*     body needs to stay visible next to the diff so the user can read
*     denial / skip / failure reasons longer than the per-hunk badge.
*   - Fully-denied gate emit (`[fully denied] <edit-outcomes>…`) likewise
*     stays visible.
*
* Exported for unit-testability of the visibility matrix.
*/
function isEditErrorResult(text) {
	if (text.startsWith("Edit error:")) return true;
	if (text.startsWith("Tool failed:")) return true;
	if (text.startsWith("multi_edit error:")) return true;
	if (text.startsWith("[fully denied]")) return true;
	if (text.includes("\n<edit-outcomes>\n") || text.startsWith("<edit-outcomes>\n")) return true;
	return false;
}
/**
* Per-event visibility — filters honor user toggles and the
* `hideSubagentOutput` setting. When subagent output is hidden:
*   - Child-agent events are filtered down to the `spawn-start` /
*     `spawn-end` markers so the user still sees "🌱 working… 🌳 done".
*   - The parent's `tool-result` for `spawn` is hidden too. Its body
*     duplicates `spawn-end`'s stats line *and* the parent's next
*     markdown turn; showing it again produces an extra
*     `┃ [sub-agent child-1] Completed …` block users just want gone.
*
* Renderer-agnostic — returns plain `boolean` so TUI / GUI consumers
* can filter events identically.
*/
function isVisible(event, settings) {
	if (settings.hideSubagentOutput) {
		if ((event.depth ?? 0) > 0) return event.kind === "spawn-start" || event.kind === "spawn-end";
		if (event.kind === "tool-result" && event.tool === "spawn") return false;
	}
	if (settings.showEditDiffs && event.kind === "tool-result" && event.tool && EDIT_TOOL_NAMES.has(event.tool) && !isEditErrorResult(event.text)) return false;
	switch (event.kind) {
		case "thinking": return settings.showThinking;
		case "tool": return settings.toolCallDisplay !== "hidden";
		case "tool-result": return settings.showToolResults;
		default: return true;
	}
}
/**
* Build the `resultTurnId → owningAssistantTurnId` map used by the select-
* turn mode to coalesce a tool-call's surrounding turns into ONE navigation
* stop.
*
* Protocol shape: every `tool_call` block in an assistant turn is closed by
* a matching `tool_result` block in the *next* user turn (the agent loop's
* history validator depends on this). When the next user turn's only events
* are `tool-result`s — i.e. it's pure plumbing for the prior assistant
* turn — we map it back to that assistant turn here. The select-turn nav
* index ({@link selectableTurnIds}) skips owned turns, and the renderer's
* highlight gate ({@link isTurnHighlighted}) extends the selection accent
* from the assistant turn to the events of any turn it owns. Net effect:
*
*   - Navigation never lands the cursor on a result-only turn whose own
*     events may be hidden by `showToolResults: false` — the cursor
*     wouldn't be visible.
*   - Selecting an assistant turn highlights the call AND its result as
*     one unit, matching the user's mental model of "one message".
*
* Owner-lookup is conservative: result-only turns with no matching prior
* assistant turn (orphaned — usually because the parent was deleted)
* stay selectable so the user can act on them via the turn-details modal.
*
* Subagent (`childId` set) events are ignored — they live in a separate
* conversation tree.
*/
function turnSelectionOwnership(events) {
	const orderedTurnIds = [];
	const eventKindsByTurn = /* @__PURE__ */ new Map();
	for (const e of events) {
		if (!e.turnId) continue;
		if (e.childId) continue;
		if (!eventKindsByTurn.has(e.turnId)) {
			orderedTurnIds.push(e.turnId);
			eventKindsByTurn.set(e.turnId, []);
		}
		eventKindsByTurn.get(e.turnId).push(e.kind);
	}
	const ownership = /* @__PURE__ */ new Map();
	let lastToolEmitterTurnId = null;
	for (const tid of orderedTurnIds) {
		const kinds = eventKindsByTurn.get(tid);
		if (kinds.length > 0 && kinds.every((k) => k === "tool-result")) {
			if (lastToolEmitterTurnId) ownership.set(tid, lastToolEmitterTurnId);
			continue;
		}
		if (kinds.includes("tool")) lastToolEmitterTurnId = tid;
	}
	return ownership;
}
/**
* Render-time check: should `event` paint with the selection accent?
*
* `true` when the event's own turn is selected, OR when the selected turn
* `owns` the event's turn via {@link turnSelectionOwnership} (the call and
* its tool-result rows highlight together). `false` when nothing is
* selected or the relationship doesn't apply.
*
* Pure. Renderer-agnostic — the TUI's `<Transcript>` uses it; a GUI's
* equivalent walks the same rule.
*/
function isTurnHighlighted(event, selectedTurnId, ownership) {
	if (selectedTurnId === null || !event.turnId) return false;
	if (event.turnId === selectedTurnId) return true;
	return ownership.get(event.turnId) === selectedTurnId;
}
/**
* Deduplicated, in-order list of **parent-conversation** turn ids that appear
* in a rendered transcript — the navigation index for the TUI's select-turn
* mode. Three classes of turns are deliberately skipped:
*
*   - **Subagent turns** (`childId` set). Nested execution detail; the
*     user's mental model of a "message" is the conversational exchange,
*     not each spawn turn. Also filtered out by `isVisible` under
*     `hideSubagentOutput: true` — selecting them would highlight nothing.
*   - **Result-only turns** — see {@link turnSelectionOwnership}. These get
*     coalesced into the assistant turn that emitted their tool_calls.
*   - **Settings-hidden turns** (when `settings` is supplied). A turn whose
*     every event fails {@link isVisible} would render no rows — landing
*     the cursor there hides it from the user entirely. The check is opt-
*     in so SDK callers without a Settings object keep the legacy
*     "everything visible" behavior.
*
* Synthetic events (separator, spawn-start, spawn-end) have no `turnId` and
* are skipped naturally.
*/
function selectableTurnIds(events, settings) {
	const ownership = turnSelectionOwnership(events);
	const visibleCount = settings ? /* @__PURE__ */ new Map() : null;
	if (settings && visibleCount) for (const e of events) {
		if (!e.turnId || e.childId) continue;
		if (!isVisible(e, settings)) continue;
		visibleCount.set(e.turnId, (visibleCount.get(e.turnId) ?? 0) + 1);
	}
	const seen = /* @__PURE__ */ new Set();
	const ordered = [];
	for (const e of events) {
		if (!e.turnId) continue;
		if (e.childId) continue;
		if (seen.has(e.turnId)) continue;
		if (ownership.has(e.turnId)) continue;
		if (visibleCount && (visibleCount.get(e.turnId) ?? 0) === 0) continue;
		seen.add(e.turnId);
		ordered.push(e.turnId);
	}
	return ordered;
}
//#endregion
//#region src/chat/model-catalog.ts
/**
* Build the unified catalog from a list of available providers.
*
* Provider order is preserved (callers typically pass the picker order
* — alphabetical, auth-detection order, etc.); model order inside each
* provider matches whatever `modelsFor` returns. The current selection
* (when set) is bubbled to the top of its provider's section so it
* shows first without disturbing relative ordering elsewhere.
*
* `modelsFor` is injected (not imported from `./providers`) so the same
* helper works with hosts that supply their own model resolver via
* `ResolvedConfig.modelsFor`.
*/
function buildModelCatalog(opts) {
	const entries = [];
	for (const provider of opts.providers) {
		const models = opts.modelsFor(provider.key);
		if (models.length === 0) continue;
		let ordered = models;
		if (opts.current?.providerKey === provider.key) {
			const idx = models.findIndex((m) => m.id === opts.current?.modelId);
			if (idx > 0) {
				const next = models.slice();
				const [active] = next.splice(idx, 1);
				next.unshift(active);
				ordered = next;
			}
		}
		for (const model of ordered) entries.push({
			providerKey: provider.key,
			providerLabel: provider.label,
			model,
			searchCorpus: buildSearchCorpus(provider, model)
		});
	}
	return entries;
}
/**
* Filter `catalog` by a user query. Empty / whitespace-only queries
* pass everything through unchanged (`O(1)` short-circuit). Multi-term
* queries (space-separated) require EVERY term to appear somewhere in
* the entry's search corpus — so `"claude opus"` matches `claude-opus-4`
* regardless of how the words are interleaved with provider names.
*
* Match is case-insensitive (the corpus is pre-lowercased; the query
* is lowercased once per call).
*/
function filterModelCatalog(catalog, query) {
	const trimmed = query.trim().toLowerCase();
	if (!trimmed) return catalog.slice();
	const terms = trimmed.split(/\s+/);
	return catalog.filter((entry) => terms.every((t) => entry.searchCorpus.includes(t)));
}
/**
* Find a catalog entry's index by its `{providerKey, modelId}` tuple.
* Returns `-1` when not present. Useful when re-rendering the picker
* (a query just narrowed the list, where did the selection land?).
*/
function indexOfEntry(catalog, target) {
	if (!target) return -1;
	return catalog.findIndex((e) => e.providerKey === target.providerKey && e.model.id === target.modelId);
}
function buildSearchCorpus(provider, model) {
	return [
		provider.key,
		provider.label,
		model.id,
		model.name ?? "",
		model.provider ?? ""
	].join(" ").toLowerCase();
}
//#endregion
//#region src/chat/prompt-segments.ts
/**
* Split a prompt buffer into word-sized atomic segments suitable for a
* flex-row + flex-wrap renderer (TUI) or a `display: inline` flow with
* inline-block chips (GUI). Each chip becomes one segment (atomic —
* never broken across rows); each plain run is split into "word +
* trailing space" units so wraps land at clean word boundaries.
*
* Robust to:
*   - Overlapping refs — sorted by start; later refs that overlap are
*     dropped via the first-wins rule.
*   - Out-of-bounds refs — dropped entirely when `end > text.length` or
*     `start >= text.length`. Partial clipping would silently truncate
*     a chip's label; the caller is in a better position to surface the
*     mismatch (typically a stale `refs` array referencing a previous text).
*   - Whitespace-only plain runs — emitted as their own plain segment
*     so chip-adjacent-to-chip cases keep the original spacing.
*
* Word splitter rationale: `\S+\s*` keeps trailing whitespace attached
* to its preceding word so wrap boundaries land between words (cleanly).
* A leading-whitespace-only segment is captured by `\s+` so we don't
* drop it entirely when the plain run starts with a space.
*/
function splitPromptSegments(text, refs) {
	const sorted = [...refs].filter((r) => r.end > r.start && r.start < text.length && r.end <= text.length).sort((a, b) => a.start - b.start);
	const out = [];
	let cursor = 0;
	for (const ref of sorted) {
		if (ref.start < cursor) continue;
		if (ref.start > cursor) {
			const matches = text.slice(cursor, ref.start).match(/\S+\s*|\s+/g) ?? [];
			for (const m of matches) out.push({
				kind: "plain",
				text: m
			});
		}
		out.push({
			kind: "chip",
			text: text.slice(ref.start, ref.end),
			providerId: ref.providerId
		});
		cursor = ref.end;
	}
	if (cursor < text.length) {
		const matches = text.slice(cursor).match(/\S+\s*|\s+/g) ?? [];
		for (const m of matches) out.push({
			kind: "plain",
			text: m
		});
	}
	return out;
}
//#endregion
//#region src/chat/streaming-pure.ts
const PARENT_OWNER = "parent";
function ownerOf(event) {
	return event.childId ?? PARENT_OWNER;
}
/** Flip any trailing streaming markdown blocks (any owner) to finalized. */
function finalizeStreamingMarkdown(events) {
	let changed = false;
	const next = events.map((e) => {
		if (e.kind === "markdown" && e.streaming) {
			changed = true;
			return {
				...e,
				streaming: false
			};
		}
		return e;
	});
	return changed ? next : events;
}
/** Flip the trailing streaming markdown block for one specific owner. */
function finalizeStreamingMarkdownForOwner(events, owner) {
	for (let i = events.length - 1; i >= 0; i--) {
		const e = events[i];
		if (e.kind !== "markdown") continue;
		if (!e.streaming) continue;
		if (ownerOf(e) !== owner) continue;
		const next = events.slice();
		next[i] = {
			...e,
			streaming: false
		};
		return next;
	}
	return events;
}
/**
* Effective context size for a single turn.
*
* `usage.input` is misleading on its own when prompt caching is active: providers
* (Anthropic, OpenRouter→Anthropic, Gemini) report `input` as the *new uncached*
* tokens only — the cached prefix shows up in `cacheRead`, and newly-cached
* tokens in `cacheCreation`. The model still saw all three buckets, so the real
* context-window utilization is their sum.
*
* Non-caching providers leave `cacheRead`/`cacheCreation` undefined, so this
* collapses to plain `input` for them.
*/
function turnContextSize(usage) {
	return effectiveInputFromTurn(usage);
}
//#endregion
//#region src/chat/tool-formatters.ts
/**
* Per-tool display metadata + one-line formatters consumed by any
* surface that renders a `tool` event in `'formatted'` mode (see
* `Settings.toolCallDisplay`).
*
* Each native tool gets a curated entry — a `displayName` verb that
* reads in sentence case (e.g. "Read", "Shell") and a `format` callback
* that pulls the most informative bits out of the model's raw input to
* a single scannable line. Unknown tools (MCP servers, host-added
* tools, future zidane additions) fall back to {@link formatToolCall}
* returning `null` — the renderer then shows a minimal `↳ <name>` line.
*
* Renderer-agnostic: returns plain data (`{ target, meta }`) so the
* TUI's React/OpenTUI surface and any future GUI consumer can paint
* the same shape in their own style. Lives in `zidane/chat` because
* it has no rendering concerns; the TUI just consumes it.
*/
const TOOL_DISPLAY = {
	read_file: {
		displayName: "Read",
		format: (input) => {
			const path = stringField(input, "path");
			if (!path) return null;
			const meta = [];
			const offset = numberField(input, "offset");
			const limit = numberField(input, "limit");
			if (offset !== void 0 && limit !== void 0 && limit > 0) meta.push(`L${offset}–${offset + limit - 1}`);
			else if (offset !== void 0) meta.push(`from L${offset}`);
			else if (limit !== void 0 && limit > 0) meta.push(`${limit} lines`);
			return {
				target: path,
				meta
			};
		}
	},
	list_files: {
		displayName: "List",
		format: (input) => {
			return { target: stringField(input, "path") ?? "." };
		}
	},
	glob: {
		displayName: "Glob",
		format: (input) => {
			const pattern = stringField(input, "pattern");
			if (!pattern) return null;
			const meta = [];
			const limit = numberField(input, "limit");
			if (limit !== void 0) meta.push(`limit ${limit}`);
			return {
				target: pattern,
				meta
			};
		}
	},
	grep: {
		displayName: "Grep",
		format: (input) => {
			const pattern = stringField(input, "pattern");
			if (!pattern) return null;
			const target = `/${pattern}/`;
			const meta = [];
			const path = stringField(input, "path");
			if (path && path !== ".") meta.push(`in ${path}`);
			const glob = stringField(input, "glob");
			if (glob) meta.push(glob);
			const type = stringField(input, "type");
			if (type) meta.push(`type:${type}`);
			if (input["-i"] === true) meta.push("case-insensitive");
			const mode = stringField(input, "output_mode");
			if (mode && mode !== "files_with_matches") meta.push(mode);
			return {
				target,
				meta
			};
		}
	},
	shell: {
		displayName: (input) => input?.run_in_background === true ? "Shell (background)" : "Shell",
		format: (input) => {
			const command = stringField(input, "command");
			if (!command) return null;
			const description = stringField(input, "description");
			const line = { target: truncate(command, 200) };
			if (description && description.trim() !== "") line.meta = [truncate(description, 100)];
			return line;
		}
	},
	shell_kill: {
		displayName: "Kill task",
		format: (input) => {
			const taskId = stringField(input, "task_id");
			if (!taskId) return null;
			return { target: taskId };
		}
	},
	wait_task: {
		displayName: "Wait for task",
		format: (input) => {
			const taskId = stringField(input, "task_id");
			if (!taskId) return null;
			const timeoutMs = input.timeout_ms;
			return {
				target: taskId,
				meta: typeof timeoutMs === "number" ? [`${Math.round(timeoutMs / 1e3)}s timeout`] : []
			};
		}
	},
	edit: {
		displayName: "Edit",
		format: (input) => {
			const path = stringField(input, "path");
			if (!path) return null;
			return {
				target: path,
				meta: input.replace_all === true ? ["replace all"] : []
			};
		}
	},
	multi_edit: {
		displayName: "Multi-edit",
		format: (input) => {
			const path = stringField(input, "path");
			if (!path) return null;
			const edits = Array.isArray(input.edits) ? input.edits.length : 0;
			return {
				target: path,
				meta: edits > 0 ? [`${edits} hunk${edits === 1 ? "" : "s"}`] : []
			};
		}
	},
	write_file: {
		displayName: "Write",
		format: (input) => {
			const path = stringField(input, "path");
			if (!path) return null;
			const content = stringField(input, "content");
			const meta = [];
			if (content !== void 0) {
				const bytes = utf8ByteLength(content);
				meta.push(`${formatBytes(bytes)}`);
			}
			return {
				target: path,
				meta
			};
		}
	},
	spawn: {
		displayName: "Agent",
		format: (input) => {
			const task = stringField(input, "task");
			if (!task) return null;
			return { target: truncate(task, 120) };
		}
	},
	tool_search: {
		displayName: "Search tools",
		format: (input) => {
			const query = stringField(input, "query");
			const names = Array.isArray(input.names) ? input.names.length : 0;
			if (query) return { target: `“${query}”` };
			if (names > 0) return { target: `${names} tool${names === 1 ? "" : "s"}` };
			return null;
		}
	},
	skills_use: {
		displayName: (input) => {
			return (input ? stringField(input, "mode") : void 0) === "deactivate" ? "Disable skill" : "Enable skill";
		},
		format: (input) => {
			const name = stringField(input, "name");
			if (!name) return null;
			return { target: name };
		}
	},
	skills_read: {
		displayName: "Read skill",
		format: (input) => {
			const name = stringField(input, "name");
			const path = stringField(input, "path");
			if (!name) return null;
			return { target: path ? `${name}/${path}` : name };
		}
	},
	skills_run_script: {
		displayName: "Run script",
		format: (input) => {
			const name = stringField(input, "name");
			const script = stringField(input, "script");
			if (!name || !script) return null;
			const meta = [`skill ${name}`];
			const args = Array.isArray(input.args) ? input.args : null;
			if (args && args.length > 0) meta.push(truncate(args.map(String).join(" "), 80));
			return {
				target: script,
				meta
			};
		}
	},
	todowrite: {
		displayName: "Todos",
		format: (input) => {
			const todos = Array.isArray(input.todos) ? input.todos : null;
			if (!todos) return null;
			const counts = {
				pending: 0,
				in_progress: 0,
				completed: 0,
				cancelled: 0
			};
			for (const t of todos) {
				if (!t || typeof t !== "object") continue;
				const status = t.status;
				if (typeof status === "string" && status in counts) counts[status] += 1;
			}
			const meta = [];
			if (counts.completed) meta.push(`${counts.completed} done`);
			if (counts.in_progress) meta.push(`${counts.in_progress} in progress`);
			if (counts.pending) meta.push(`${counts.pending} pending`);
			if (counts.cancelled) meta.push(`${counts.cancelled} cancelled`);
			return {
				target: `${todos.length} item${todos.length === 1 ? "" : "s"}`,
				meta
			};
		}
	},
	todoread: {
		displayName: "Todos",
		format: () => ({ target: "read" })
	},
	ask_user: {
		displayName: "Ask user",
		format: (input) => {
			const questions = Array.isArray(input.questions) ? input.questions.length : 0;
			if (questions === 0) return null;
			return { target: `${questions} question${questions === 1 ? "" : "s"}` };
		}
	},
	present_plan: {
		displayName: "Present plan",
		format: (input) => {
			const title = stringField(input, "title");
			if (!title) return null;
			return { target: title };
		}
	}
};
/**
* Resolve the display verb for a tool. Native tools use their curated
* entry from {@link TOOL_DISPLAY}; everything else gets a sentence-case
* version of the raw name (`my_host_tool` → `My host tool`) so an MCP /
* host tool still reads cleanly in the transcript without shouting
* Title Case at every word.
*
* MCP convention: every tool surfaced by `mcp/connectMcpServers` is
* namespaced as `mcp_<server>_<tool>` (see `src/mcp/index.ts`). The
* `mcp_` prefix is plumbing — strip it before casing so the label
* reads as `Github create issue` instead of `Mcp github create issue`.
* The server name leads, which doubles as a free visual grouping
* affordance ("everything starting with `Github` came from the github
* MCP server").
*/
function displayNameFor(name, input) {
	const entry = TOOL_DISPLAY[name];
	if (entry) return typeof entry.displayName === "function" ? entry.displayName(input) : entry.displayName;
	return sentenceCase(name.startsWith("mcp_") ? name.slice(4) : name);
}
/**
* Run a tool's curated formatter and return the result, or `null` when
* no formatter is registered / the input shape doesn't match. Renderer
* decides what to do with `null` — typically: show `↳ <displayName>`
* with no target / meta tail.
*/
function formatToolCall(name, input) {
	const entry = TOOL_DISPLAY[name];
	if (!entry) return null;
	try {
		return entry.format(input);
	} catch {
		return null;
	}
}
function stringField(input, key) {
	const v = input[key];
	return typeof v === "string" && v.length > 0 ? v : void 0;
}
function numberField(input, key) {
	const v = input[key];
	return typeof v === "number" && Number.isFinite(v) ? v : void 0;
}
/** `snake_case` / `kebab-case` / lowercase → `Sentence case`. */
function sentenceCase(s) {
	const words = s.split(/[-_\s]+/).filter(Boolean).map((w) => w.toLowerCase());
	if (words.length === 0) return "";
	words[0] = (words[0][0]?.toUpperCase() ?? "") + words[0].slice(1);
	return words.join(" ");
}
/**
* Collapse internal whitespace (including newlines) to single spaces
* and clip to `max` columns with a trailing `…`. The whitespace
* normalisation is the load-bearing bit — tool input strings like a
* shell heredoc or a multi-line Python `-c` script otherwise render
* across several rows in the transcript even though the `↳ Tool …`
* line is meant to be a single-line scannable summary.
*/
function truncate(s, max) {
	const clean = s.replace(/\s+/g, " ").trim();
	return clean.length <= max ? clean : `${clean.slice(0, max - 1)}…`;
}
function formatBytes(bytes) {
	if (bytes < 1024) return `${bytes} B`;
	if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
	return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
//#endregion
//#region src/chat/turn-operations.ts
/**
* Fork — keep every turn up to and including `turnId`, then strip any
* `tool_call` blocks left without a matching `tool_result` in the slice.
*
* Semantics:
*   - Include the selected turn ("branch from HERE" mental model — the
*     user wants the selected message to be the latest in the fork).
*   - If the selected turn is an assistant turn with unresolved
*     `tool_call` blocks (their `tool_result`s live in turns AFTER the
*     slice), strip those calls. Otherwise the fork would post an
*     assistant turn with no matching tool results, breaking the next
*     provider call.
*   - Drop turns that become empty (all blocks stripped).
*
* Returns `null` when `turnId` doesn't exist in `turns` — caller should
* surface a "turn not found" error rather than silently no-op.
*/
function truncateTurnsAt(turns, turnId) {
	const idx = turns.findIndex((t) => t.id === turnId);
	if (idx === -1) return null;
	return stripOrphanToolBlocks(turns.slice(0, idx + 1));
}
/**
* Delete — remove the turn with `turnId` and any tool blocks left
* orphaned by the removal. Returns `null` when `turnId` doesn't exist.
*
* Strategy:
*   1. Drop the target turn.
*   2. Scan the remaining turns for `tool_call`s without a matching
*      `tool_result` (orphaned by removing the user turn that carried
*      the result), and `tool_result`s without a matching `tool_call`
*      (orphaned by removing the assistant turn that issued the call).
*      Strip both sides.
*   3. Drop turns whose content is now empty.
*
* This guarantees the resulting history is protocol-clean — a follow-up
* `agent.run()` against the modified session can post turns without the
* provider rejecting the history.
*/
function deleteTurnSafely(turns, turnId) {
	const idx = turns.findIndex((t) => t.id === turnId);
	if (idx === -1) return null;
	return stripOrphanToolBlocks([...turns.slice(0, idx), ...turns.slice(idx + 1)]);
}
/**
* Walk a turn list and remove any tool blocks whose counterpart is
* missing. Drops turns left empty. Used by `truncateTurnsAt` (which can
* leave `tool_call`s orphaned when their results are past the cut) and
* `deleteTurnSafely` (which can orphan either side of a pair).
*
* Pure / total: returns a new array; never throws.
*/
function stripOrphanToolBlocks(turns) {
	const callIds = /* @__PURE__ */ new Set();
	const resultIds = /* @__PURE__ */ new Set();
	for (const turn of turns) for (const block of turn.content) if (block.type === "tool_call") callIds.add(block.id);
	else if (block.type === "tool_result") resultIds.add(block.callId);
	const result = [];
	for (const turn of turns) {
		const filtered = [];
		for (const block of turn.content) {
			if (block.type === "tool_call") {
				if (!resultIds.has(block.id)) continue;
			} else if (block.type === "tool_result") {
				if (!callIds.has(block.callId)) continue;
			}
			filtered.push(block);
		}
		if (filtered.length === 0) continue;
		result.push(filtered.length === turn.content.length ? turn : {
			...turn,
			content: filtered
		});
	}
	return result;
}
/**
* Serialize a turn's content to a clean text representation suited for
* the clipboard. Joins text + thinking blocks verbatim; tool calls and
* tool results get bracketed labels so the user can paste a readable
* record of what happened without losing structure.
*
* Empty turns return `''`.
*/
function turnAsText(turn) {
	const parts = [];
	for (const block of turn.content) if (block.type === "text" && block.text.trim()) parts.push(block.text);
	else if (block.type === "thinking" && block.text.trim()) parts.push(`[thinking]\n${block.text}`);
	else if (block.type === "tool_call") parts.push(`[tool call · ${block.name}]\n${stringifyArgs(block.input)}`);
	else if (block.type === "tool_result") parts.push(`[tool result]\n${typeof block.output === "string" ? block.output : JSON.stringify(block.output, null, 2)}`);
	else if (block.type === "compact-summary") parts.push(`[compaction summary · ${block.replacesTurnIds.length} turn${block.replacesTurnIds.length === 1 ? "" : "s"}]\n${block.summary}`);
	return parts.join("\n\n");
}
function stringifyArgs(input) {
	try {
		return JSON.stringify(input, null, 2);
	} catch {
		return String(input);
	}
}
/**
* Count turns before / after the one identified by `turnId` in the
* given list. Returns `null` when the id is missing. Used to label the
* turn-details modal with `N before · M after`.
*/
function countNeighbors(turnIds, turnId) {
	const idx = turnIds.indexOf(turnId);
	if (idx === -1) return null;
	return {
		before: idx,
		after: turnIds.length - 1 - idx
	};
}
//#endregion
export { splitLines as A, summarizeOutcomes as B, buildContextualDiff as C, extractEditPayload as D, computeLineDiff as E, mergeApprovalAndBodyOutcomes as F, createFilesCompletionProvider as G, createSkillsCompletionProvider as H, parseEditOutcomesFromResult as I, collectReferences as J, uniqueFilesFromReferences as K, resolveApprovalForPayload as L, tokenize as M, buildEditOutcomesAnnotation as N, filetypeFromPath as O, maskToOutcomeKinds as P, buildLinearRamp as Q, rewriteMultiEditHeader as R, applyEditPayload as S, computeInlineDiff as T, uniqueSkillNamesFromReferences as U, SKILLS_TRIGGER as V, FILES_TRIGGER as W, mergeReferences as X, findActiveTrigger as Y, blendHsl as Z, isEditErrorResult as _, TOOL_DISPLAY as a, selectableTurnIds as b, finalizeStreamingMarkdown as c, turnContextSize as d, splitPromptSegments as f, EDIT_TOOL_NAMES as g, indexOfEntry as h, turnAsText as i, summarizeEditPayload as j, previewEditPayload as k, finalizeStreamingMarkdownForOwner as l, filterModelCatalog as m, deleteTurnSafely as n, displayNameFor as o, buildModelCatalog as p, applyInsert as q, truncateTurnsAt as r, formatToolCall as s, countNeighbors as t, ownerOf as u, isTurnHighlighted as v, buildUnifiedDiff as w, turnSelectionOwnership as x, isVisible as y, stripEditOutcomesAnnotation as z };

//# sourceMappingURL=turn-operations-DLWN2J7f.js.map