import { $ as useMcpAuthDispatch, $n as BUILD_AGENT, $t as deriveSessionTitle, A as runOAuthLogin, An as buildUpdateHint, Ar as SUBAGENT_GUIDANCE, B as refreshMcpToolsCatalog, Bn as AUTO_COMPACT_MIN_GROWTH_FRACTION, Bt as CATPPUCCIN_LATTE, C as projectsFilePath, Cn as parseBindingSpec, Cr as COMMUNICATION_DOCTRINE, Ct as listProjectFiles, D as formatPathForCwd, Dn as tryOpenBrowser, Dr as INTERACTION_GUIDANCE_NO_PROMPTS, Dt as SETTINGS_CHOICES, E as writeProjects, En as useCompletion, Er as INTERACTION_GUIDANCE, Et as SETTINGS_CATEGORIES, F as parseMcpsFile, Fn as detectPackageManager, Ft as resolveTheme, G as useMcpToolToggleSet, Gn as readCredentials, Gt as useDiscovery, H as subscribeMcpToolsCache, Hn as detectAuth, Ht as CATPPUCCIN_MOCHA, I as projectUserPaths, In as parseSemver, It as VAPORWAVE_THEME, J as parentServerName, Jn as setProviderCredential, Jt as useConfig, K as buildVisibleMcpRows, Kn as readProviderCredential, Kt as useDiscoveryOptional, L as clearMcpToolsCache, Ln as performInPlaceSelfUpdate, Lt as GRUVBOX_DARK, M as buildMcpServers, Mn as checkForUpdate, Mr as buildBuildSystem, Mt as BUILTIN_THEMES, N as defaultMcpsConfigPaths, Nn as compareSemver, Nr as buildPlanSystem, Nt as DEFAULT_THEME, O as fetchOAuthRedirect, On as bootProfileEnabled, Or as PLAN_MODE_DOCTRINE, Ot as SETTINGS_TOGGLES, P as discoverProjectMcps, Pn as detectLibc, Pr as envSection, Pt as resolveChipColor, Q as McpAuthProvider, Qn as findGitRoot, Qt as createStateStore, R as loadMcpToolsCache, Rn as performSelfUpdate, Rt as GRUVBOX_LIGHT, S as matchesSafelistEntry, Sn as mergeKeybindings, Sr as ACTIONS_WITH_CARE_DOCTRINE, St as shortChord, T as suggestSafelistEntry, Tn as stripJsonComments, Tr as IDENTITY_PREFIX, Tt as DEFAULT_SETTINGS, U as buildToolToggle, Un as applyApiKeyEnv, Ut as createDiscoverySlot, V as saveMcpToolsCache, Vn as shouldAutoCompact, Vt as CATPPUCCIN_MACCHIATO, W as useMcpToolToggleMap, Wn as credentialsPath, Wt as DiscoveryProvider, X as mcpCredentialsPath, Xn as discoverAgentsMd, Xt as resolveStoragePaths, Y as createFileMcpCredentialStore, Yn as writeCredentials, Yt as resolveConfig, Z as patchMcpCredential, Zn as renderAgentsMdBlock, Zt as resolveStorageDirs, _ as useSafeModeQueue, _n as ensureKeybindingsFile, _r as pickActiveRunId, _t as hintsLength, a as useSurfaces, an as saveState, ar as accentColor, at as InteractionsProvider, b as getSafelist, bn as keybindingsPath, br as setTodosForRun, bt as generateSessionTitle, c as useStreamBuffer, cn as sumRunCosts, cr as TODOREAD_TOOL, ct as createInteractionTools, d as discoverProjectSkills, dn as toolResultText, dr as TODO_STATUS_GLYPHS, dt as pendingInteractionsFromTurns, en as eventsFromTurns, er as BUILTIN_AGENTS, et as useMcpAuthState, f as renderSession, fn as updateToolEventOutcomes, fr as TODO_WRITE_COUNTS_METADATA_KEY, ft as serializeInteractionResponse, g as useSafeModeActions, gn as KEYBINDING_KEY_COL_WIDTH, gr as isTodoTool, gt as clipHintsToWidth, h as SafeModeProvider, hn as KEYBINDING_DEF_BY_ACTION, hr as getTodosForRun, ht as EMPTY_HINTS, i as useSelectStyle, in as marginTopFor, ir as PLAN_AGENT, it as ASK_USER_TOOL, j as supportsOAuth, jn as useUpdateCheck, jr as TOKEN_DISCIPLINE_DOCTRINE, jt as useSettings, k as oauthUsesManualCodePaste, kn as bootTick, kr as PLAN_MODE_DOCTRINE_NO_PROMPTS, kt as SettingsProvider, l as buildSkillsConfig, ln as titleFromTurns, lr as TODOS_METADATA_KEY, lt as isInteractionTool, m as writeSessionExport, mn as KEYBINDING_DEFS, mr as getArchivedTodosForRun, mt as useInteractionsQueue, n as ThemeProvider, nn as listSessionMeta, nr as DEFAULT_BUDGET_EXCLUDE_TOOLS, nt as reduceMcpAuth, o as useSyntaxStyles, or as resolveAgentId, ot as PRESENT_PLAN_TOOL, p as resolveSessionExportTarget, pn as DEFAULT_KEYBINDINGS, pr as createTodoTools, pt as useInteractionsActions, q as indexOfServerRow, qn as removeProviderCredential, qt as ConfigProvider, r as useColors, rn as loadState, rr as DEFAULT_PERSIST_EXCLUDE_TOOLS, rt as splitMarkdownCodeBlocks, s as useTheme, sn as stripSpawnTokensLine, sr as singleAgentRegistry, st as buildResumedToolResultsTurn, t as computeTurnAnchors, tn as lastContextSizeFromTurns, tr as DEFAULT_AGENT_ID, tt as getMcpAuthStatus, u as defaultSkillScanPaths, un as toolCallPreview, ur as TODOWRITE_TOOL, ut as makeRequestInteraction, v as IMPLICITLY_SAFE_TOOLS, vn as formatBindingForDisplay, vr as pruneTodosByRun, vt as truncateTrailing, w as readProjects, wn as readKeybindings, wr as DOING_TASKS_DOCTRINE, wt as useEnabledToggleSet, x as isOnSafelist, xn as matchesBinding, xr as useActiveTodos, xt as buildHints, y as addToSafelist, yn as groupBindings, yr as selectActiveTodos, yt as cleanTitle, z as mcpToolsCachePath, zn as resolvePlatformPackage, zt as CATPPUCCIN_FRAPPE } from "./transcript-anchors-B_c7gWot.js";
import { $ as piIdOf, B as anthropicDescriptor, G as getContextWindow, H as credKeyOf, J as modelOptionsFor, K as getModelInfo, Q as openrouterDescriptor, R as BUILTIN_PROVIDERS, U as effectiveContextWindow, V as cerebrasDescriptor, W as enabledModelOptions, X as modelsForDescriptor, Y as modelSupportsReasoning, Z as openaiDescriptor, et as restoreModelOptions, q as localDescriptor, z as OUTPUT_RESERVE_TOKENS } from "./tools-NxnEmzYg.js";
import { t as buildContextBreakdown } from "./context-breakdown-kO-pDsay.js";
import { a as formatTaskStatus, c as shortId, i as formatDuration, n as compactPath, o as formatTaskSummary, r as fmtTokens, s as previewLine, t as ageString } from "./format-BNOXpl-1.js";
import { A as splitLines, B as summarizeOutcomes, C as buildContextualDiff, D as extractEditPayload, E as computeLineDiff, F as mergeApprovalAndBodyOutcomes, G as createFilesCompletionProvider, H as createSkillsCompletionProvider, I as parseEditOutcomesFromResult, J as collectReferences, K as uniqueFilesFromReferences, L as resolveApprovalForPayload, M as tokenize, N as buildEditOutcomesAnnotation, O as filetypeFromPath, P as maskToOutcomeKinds, Q as buildLinearRamp, R as rewriteMultiEditHeader, S as applyEditPayload, T as computeInlineDiff, U as uniqueSkillNamesFromReferences, V as SKILLS_TRIGGER, W as FILES_TRIGGER, X as mergeReferences, Y as findActiveTrigger, Z as blendHsl, _ as isEditErrorResult, a as TOOL_DISPLAY, b as selectableTurnIds, c as finalizeStreamingMarkdown, d as turnContextSize, f as splitPromptSegments, h as indexOfEntry, i as turnAsText, j as summarizeEditPayload, k as previewEditPayload, l as finalizeStreamingMarkdownForOwner, m as filterModelCatalog, n as deleteTurnSafely, o as displayNameFor, p as buildModelCatalog, q as applyInsert, r as truncateTurnsAt, s as formatToolCall, t as countNeighbors, v as isTurnHighlighted, w as buildUnifiedDiff, x as turnSelectionOwnership, y as isVisible, z as stripEditOutcomesAnnotation } from "./turn-operations-DLWN2J7f.js";
//#region src/chat/auto-update-cli.ts
const UPGRADE_HELP = `Usage: zidane upgrade [options]

Update the zidane CLI to the latest release.

Options:
  --check                   Print the latest version and exit (no install).
  --in-place                Download the platform binary directly from npm
                            and atomic-rename over the running binary.
                            Skips the package manager. Refused on Volta.
  --dry-run                 Resolve everything but don't actually install.
  --channel <tag>           dist-tag to query (default: latest).
  --registry <url>          Override the npm registry.
  --package-manager <pm>    Force npm | pnpm | yarn | bun | volta.
  --force                   Run the install even if we're already on latest,
                            or the registry check failed.
  -h, --help                Print this help.

Environment:
  NO_UPDATE_NOTIFIER        Silence the background check (set to "1").
  ZIDANE_NO_UPDATE          Same, project-specific.
`;
/**
* Run the `upgrade` subcommand. Exit code contract:
*   - `0`  — update succeeded, `--check` reported no update, or `--check`
*            reported an update (informational only).
*   - `1`  — update failed (PM exit non-zero, in-place download failed,
*            registry returned non-2xx).
*   - `2`  — argv parse error (unknown flag).
*/
async function runUpdateCommand(options) {
	const out = options.stdout ?? process.stdout;
	const err = options.stderr ?? process.stderr;
	const parsed = parseArgs(options.argv);
	if (parsed.kind === "error") {
		err.write(`zidane upgrade: ${parsed.message}\n`);
		err.write(UPGRADE_HELP);
		return { exitCode: 2 };
	}
	if (parsed.help) {
		out.write(UPGRADE_HELP);
		return { exitCode: 0 };
	}
	const channel = parsed.channel ?? options.defaultChannel ?? "latest";
	const registry = parsed.registry ?? options.registry;
	const status = await checkForUpdate({
		packageName: options.packageName,
		currentVersion: options.currentVersion,
		channel,
		registry,
		cacheDir: options.cacheDir,
		force: true,
		timeoutMs: 8e3
	});
	if (parsed.check) {
		if (status.source === "error") {
			err.write(`Could not check \`${channel}\` (${status.error ?? "unknown error"}). Current: v${options.currentVersion}.\n`);
			return { exitCode: 0 };
		}
		if (!status.latest) {
			err.write(`Could not determine latest version on \`${channel}\`. Current: v${options.currentVersion}.\n`);
			return { exitCode: 0 };
		}
		if (compareSemver(status.latest, options.currentVersion) > 0) out.write(`v${status.latest} is available on \`${channel}\` (current: v${options.currentVersion}).\n`);
		else out.write(`Already on v${options.currentVersion} (latest on \`${channel}\` is v${status.latest}).\n`);
		return { exitCode: 0 };
	}
	if (status.source === "error") {
		err.write(`zidane upgrade: registry check failed (${status.error ?? "unknown error"})\n`);
		if (!parsed.force) {
			err.write("Pass --force to attempt the install anyway.\n");
			return { exitCode: 1 };
		}
	}
	if (status.latest && !parsed.force) {
		if (compareSemver(status.latest, options.currentVersion) <= 0) {
			out.write(`Already on v${options.currentVersion} (latest on \`${channel}\` is v${status.latest}).\n`);
			return { exitCode: 0 };
		}
	}
	if (parsed.inPlace) {
		const platformPkg = resolvePlatformPackage({ prefix: options.platformPackagePrefix ?? `${options.packageName}-` });
		if (!platformPkg) {
			err.write(`No prebuilt binary for ${process.platform}/${process.arch}. Run \`${options.packageName}-upgrade\` via your package manager instead.\n`);
			return { exitCode: 1 };
		}
		out.write(`Downloading ${platformPkg}@${channel}…\n`);
		const result = await performInPlaceSelfUpdate({
			packageName: platformPkg,
			channel,
			registry,
			dryRun: parsed.dryRun
		});
		if (result.status === "success") {
			const verb = parsed.dryRun ? "Would install" : "Installed";
			out.write(`${verb} v${result.installedVersion} at ${result.binaryPath}.\n`);
			return { exitCode: 0 };
		}
		err.write(`In-place update failed: ${result.reason ?? "unknown error"}\n`);
		if (result.status === "refused") err.write("Falling back to package-manager path (drop --in-place to retry).\n");
		return { exitCode: 1 };
	}
	const detected = detectPackageManager({
		packageName: options.packageName,
		channel
	});
	if (detected.note) out.write(`${detected.note}\n`);
	out.write(`Running: ${detected.argv.join(" ")}\n`);
	if (parsed.dryRun) return { exitCode: 0 };
	const result = await performSelfUpdate({
		packageName: options.packageName,
		channel,
		packageManager: parsed.packageManager ?? "auto"
	});
	if (result.spawnError) {
		err.write(`Failed to launch \`${result.command.argv[0]}\`: ${result.spawnError}\n`);
		err.write("Is the package manager installed and on $PATH?\n");
		return { exitCode: 1 };
	}
	return { exitCode: result.exitCode ?? 1 };
}
function parseArgs(argv) {
	let check = false;
	let inPlace = false;
	let dryRun = false;
	let force = false;
	let help = false;
	let channel;
	let registry;
	let packageManager;
	for (let i = 0; i < argv.length; i++) {
		const a = argv[i];
		switch (a) {
			case "--check":
				check = true;
				break;
			case "--in-place":
			case "--inplace":
				inPlace = true;
				break;
			case "--dry-run":
			case "--dryrun":
				dryRun = true;
				break;
			case "--force":
				force = true;
				break;
			case "-h":
			case "--help":
				help = true;
				break;
			case "--channel":
				channel = argv[++i];
				if (!channel) return {
					kind: "error",
					message: "--channel requires a value"
				};
				break;
			case "--registry":
				registry = argv[++i];
				if (!registry) return {
					kind: "error",
					message: "--registry requires a value"
				};
				break;
			case "--package-manager":
			case "--pm": {
				const v = argv[++i];
				if (!v) return {
					kind: "error",
					message: "--package-manager requires a value"
				};
				if (v !== "npm" && v !== "pnpm" && v !== "yarn" && v !== "bun" && v !== "volta") return {
					kind: "error",
					message: `unknown package manager: ${v}`
				};
				packageManager = v;
				break;
			}
			default: return {
				kind: "error",
				message: `unknown argument: ${a}`
			};
		}
	}
	return {
		kind: "ok",
		check,
		inPlace,
		dryRun,
		force,
		help,
		channel,
		registry,
		packageManager
	};
}
//#endregion
export { ACTIONS_WITH_CARE_DOCTRINE, ASK_USER_TOOL, AUTO_COMPACT_MIN_GROWTH_FRACTION, BUILD_AGENT, BUILTIN_AGENTS, BUILTIN_PROVIDERS, BUILTIN_THEMES, CATPPUCCIN_FRAPPE, CATPPUCCIN_LATTE, CATPPUCCIN_MACCHIATO, CATPPUCCIN_MOCHA, COMMUNICATION_DOCTRINE, ConfigProvider, DEFAULT_AGENT_ID, DEFAULT_BUDGET_EXCLUDE_TOOLS, DEFAULT_KEYBINDINGS, DEFAULT_PERSIST_EXCLUDE_TOOLS, DEFAULT_SETTINGS, DEFAULT_THEME, DOING_TASKS_DOCTRINE, DiscoveryProvider, EMPTY_HINTS, FILES_TRIGGER, GRUVBOX_DARK, GRUVBOX_LIGHT, IDENTITY_PREFIX, IMPLICITLY_SAFE_TOOLS, INTERACTION_GUIDANCE, INTERACTION_GUIDANCE_NO_PROMPTS, InteractionsProvider, KEYBINDING_DEFS, KEYBINDING_DEF_BY_ACTION, KEYBINDING_KEY_COL_WIDTH, McpAuthProvider, OUTPUT_RESERVE_TOKENS, PLAN_AGENT, PLAN_MODE_DOCTRINE, PLAN_MODE_DOCTRINE_NO_PROMPTS, PRESENT_PLAN_TOOL, SETTINGS_CATEGORIES, SETTINGS_CHOICES, SETTINGS_TOGGLES, SKILLS_TRIGGER, SUBAGENT_GUIDANCE, SafeModeProvider, SettingsProvider, TODOREAD_TOOL, TODOS_METADATA_KEY, TODOWRITE_TOOL, TODO_STATUS_GLYPHS, TODO_WRITE_COUNTS_METADATA_KEY, TOKEN_DISCIPLINE_DOCTRINE, TOOL_DISPLAY, ThemeProvider, VAPORWAVE_THEME, accentColor, addToSafelist, ageString, anthropicDescriptor, applyApiKeyEnv, applyEditPayload, applyInsert, blendHsl, bootProfileEnabled, bootTick, buildBuildSystem, buildContextBreakdown, buildContextualDiff, buildEditOutcomesAnnotation, buildHints, buildLinearRamp, buildMcpServers, buildModelCatalog, buildPlanSystem, buildResumedToolResultsTurn, buildSkillsConfig, buildToolToggle, buildUnifiedDiff, buildUpdateHint, buildVisibleMcpRows, cerebrasDescriptor, checkForUpdate, cleanTitle, clearMcpToolsCache, clipHintsToWidth, collectReferences, compactPath, compareSemver, computeInlineDiff, computeLineDiff, computeTurnAnchors, countNeighbors, createDiscoverySlot, createFileMcpCredentialStore, createFilesCompletionProvider, createInteractionTools, createSkillsCompletionProvider, createStateStore, createTodoTools, credKeyOf, credentialsPath, defaultMcpsConfigPaths, defaultSkillScanPaths, deleteTurnSafely, deriveSessionTitle, detectAuth, detectLibc, detectPackageManager, discoverAgentsMd, discoverProjectMcps, discoverProjectSkills, displayNameFor, effectiveContextWindow, enabledModelOptions, ensureKeybindingsFile, envSection, eventsFromTurns, extractEditPayload, fetchOAuthRedirect, filetypeFromPath, filterModelCatalog, finalizeStreamingMarkdown, finalizeStreamingMarkdownForOwner, findActiveTrigger, findGitRoot, fmtTokens, formatBindingForDisplay, formatDuration, formatPathForCwd, formatTaskStatus, formatTaskSummary, formatToolCall, generateSessionTitle, getArchivedTodosForRun, getContextWindow, getMcpAuthStatus, getModelInfo, getSafelist, getTodosForRun, groupBindings, hintsLength, indexOfEntry, indexOfServerRow, isEditErrorResult, isInteractionTool, isOnSafelist, isTodoTool, isTurnHighlighted, isVisible, keybindingsPath, lastContextSizeFromTurns, listProjectFiles, listSessionMeta, loadMcpToolsCache, loadState, localDescriptor, makeRequestInteraction, marginTopFor, maskToOutcomeKinds, matchesBinding, matchesSafelistEntry, mcpCredentialsPath, mcpToolsCachePath, mergeApprovalAndBodyOutcomes, mergeKeybindings, mergeReferences, modelOptionsFor, modelSupportsReasoning, modelsForDescriptor, oauthUsesManualCodePaste, openaiDescriptor, openrouterDescriptor, parentServerName, parseBindingSpec, parseEditOutcomesFromResult, parseMcpsFile, parseSemver, patchMcpCredential, pendingInteractionsFromTurns, performInPlaceSelfUpdate, performSelfUpdate, piIdOf, pickActiveRunId, previewEditPayload, previewLine, projectUserPaths, projectsFilePath, pruneTodosByRun, readCredentials, readKeybindings, readProjects, readProviderCredential, reduceMcpAuth, refreshMcpToolsCatalog, removeProviderCredential, renderAgentsMdBlock, renderSession, resolveAgentId, resolveApprovalForPayload, resolveChipColor, resolveConfig, resolvePlatformPackage, resolveSessionExportTarget, resolveStorageDirs, resolveStoragePaths, resolveTheme, restoreModelOptions, rewriteMultiEditHeader, runOAuthLogin, runUpdateCommand, saveMcpToolsCache, saveState, selectActiveTodos, selectableTurnIds, serializeInteractionResponse, setProviderCredential, setTodosForRun, shortChord, shortId, shouldAutoCompact, singleAgentRegistry, splitLines, splitMarkdownCodeBlocks, splitPromptSegments, stripEditOutcomesAnnotation, stripJsonComments, stripSpawnTokensLine, subscribeMcpToolsCache, suggestSafelistEntry, sumRunCosts, summarizeEditPayload, summarizeOutcomes, supportsOAuth, titleFromTurns, tokenize, toolCallPreview, toolResultText, truncateTrailing, truncateTurnsAt, tryOpenBrowser, turnAsText, turnContextSize, turnSelectionOwnership, uniqueFilesFromReferences, uniqueSkillNamesFromReferences, updateToolEventOutcomes, useActiveTodos, useColors, useCompletion, useConfig, useDiscovery, useDiscoveryOptional, useEnabledToggleSet, useInteractionsActions, useInteractionsQueue, useMcpAuthDispatch, useMcpAuthState, useMcpToolToggleMap, useMcpToolToggleSet, useSafeModeActions, useSafeModeQueue, useSelectStyle, useSettings, useStreamBuffer, useSurfaces, useSyntaxStyles, useTheme, useUpdateCheck, writeCredentials, writeProjects, writeSessionExport };

//# sourceMappingURL=chat.js.map