import { n as estimateTokens, r as utf8ByteLength } from "./utils-ngQzYzZD.js";
import { o as ensureEndsWithUserMessage, s as ensureToolResultPairing } from "./messages-C_1AmSpk.js";
import { i as toolOutputByteLength } from "./types-BiobHM1D.js";
import { t as getReadState } from "./read-state-BFqpQRc5.js";
import { c as McpOAuthProvider, o as createTolerantClient, s as sseToJsonFetchIfNeeded } from "./mcp-tevNihk_.js";
import { createServer } from "node:http";
//#region src/compact/errors.ts
/**
* Typed errors thrown by the compaction helper.
*
* Lives in its own file so both the runner and the pure messages module
* can import without circular dependencies.
*/
/**
* Raised when the caller's inputs make compaction meaningless before any
* API call is attempted. Common cases:
*   - empty `turns`
*   - `keepTurns >= turns.length` (no older content to summarize)
*   - `'from'` / `'up_to'` anchor id not found in `turns`
*   - the resolved `toSummarize` slice has no text-bearing content
*
* Synchronous — thrown from `compactConversation()` before the provider
* call so the caller can recover without a network round-trip.
*/
var CompactInvalidInputError = class extends Error {
	constructor(message) {
		super(message);
		this.name = "CompactInvalidInputError";
	}
};
/**
* Raised when the provider rejects the compaction request with
* `prompt_too_long` (or an equivalent) and the head-truncation retry
* budget has been exhausted. Callers can inspect `ptlRetries` to log
* how far the retry loop got before giving up.
*/
var CompactPromptTooLongError = class extends Error {
	ptlRetries;
	constructor(message, ptlRetries) {
		super(message);
		this.ptlRetries = ptlRetries;
		this.name = "CompactPromptTooLongError";
	}
};
//#endregion
//#region src/compact/messages.ts
/**
* Partition `turns` into `(toSummarize, preserved)` according to `scope`.
*
* Throws {@link CompactInvalidInputError} on degenerate inputs so the
* caller doesn't pay for a doomed provider call:
*   - empty `turns`
*   - `scope: 'tail'` with `keepTurns >= turns.length` (nothing to summarize)
*   - `scope: { from | up_to }` with an anchor id that isn't in `turns`
*   - the resulting `toSummarize` slice contains no text-bearing content
*     (only system turns or empty content)
*
* Pure. Returns references to the original `SessionTurn` objects — the
* caller can compare by identity (=== Object.is) to confirm.
*/
function sliceForCompaction(turns, scope, keepTurns) {
	if (turns.length === 0) throw new CompactInvalidInputError("No turns to compact.");
	let toSummarize;
	let preserved;
	if (scope === "full") {
		toSummarize = turns;
		preserved = [];
	} else if (scope === "tail") {
		const keep = Math.max(0, keepTurns);
		if (keep >= turns.length) throw new CompactInvalidInputError(`Nothing to compact: keepTurns (${keep}) covers the entire conversation (${turns.length} turns).`);
		const safeCut = findSafeRoundBoundary(turns, turns.length - keep);
		toSummarize = turns.slice(0, safeCut);
		preserved = turns.slice(safeCut);
	} else if (scope.kind === "from") {
		const idx = turns.findIndex((t) => t.id === scope.turnId);
		if (idx < 0) throw new CompactInvalidInputError(`Anchor turn not found: "${scope.turnId}".`);
		const safeIdx = findSafeRoundBoundary(turns, idx);
		preserved = turns.slice(0, safeIdx);
		toSummarize = turns.slice(safeIdx);
	} else {
		const idx = turns.findIndex((t) => t.id === scope.turnId);
		if (idx < 0) throw new CompactInvalidInputError(`Anchor turn not found: "${scope.turnId}".`);
		const safeCut = findSafeRoundBoundary(turns, idx + 1);
		toSummarize = turns.slice(0, safeCut);
		preserved = turns.slice(safeCut);
	}
	if (toSummarize.length === 0) throw new CompactInvalidInputError("Compaction scope resolved to zero turns.");
	if (!hasTextBearingContent(toSummarize)) throw new CompactInvalidInputError("Compaction scope contains no text-bearing turns to summarize.");
	return {
		toSummarize,
		preserved
	};
}
/**
* Replace every attachment block in `turns` with a short text marker.
*
* Covers two shapes:
*   - Top-level `{ type: 'image', ... }` content blocks on user turns.
*   - Image entries inside `tool_result.output` array form (multimodal
*     tool results — e.g. an MCP browser screenshot).
*
* Unconditional by design: even on vision-capable models, the summary
* call doesn't benefit from raw image bytes (the model can't refer to
* them after the summary lands), and stripping uniformly avoids
* `prompt_too_long` on image-heavy sessions.
*
* Returns a fresh array; input turns / blocks are never mutated.
*/
function stripImagesFromTurns(turns) {
	return turns.map((turn) => stripImagesFromTurn(turn));
}
function stripImagesFromTurn(turn) {
	let touched = false;
	const nextContent = [];
	for (const block of turn.content) {
		if (block.type === "image") {
			touched = true;
			nextContent.push({
				type: "text",
				text: "[image]"
			});
			continue;
		}
		if (block.type === "document") {
			touched = true;
			nextContent.push({
				type: "text",
				text: "[document]"
			});
			continue;
		}
		if (block.type === "tool_result" && Array.isArray(block.output)) {
			const flat = stripAttachmentsFromToolResult(block.output);
			if (flat) {
				touched = true;
				nextContent.push({
					...block,
					output: flat
				});
				continue;
			}
		}
		nextContent.push(block);
	}
	return touched ? {
		...turn,
		content: nextContent
	} : turn;
}
/**
* Return a fresh `ToolResultContent[]` with images flattened to `[image]`
* text placeholders, or `null` when no image blocks were present (caller
* keeps the original input). Returning a new mutable array — never the
* input — keeps the `tool_result.output` slot's mutable type contract
* satisfied without leaky `as`-casts at the call site.
*/
function stripAttachmentsFromToolResult(parts) {
	let touched = false;
	const out = [];
	for (const part of parts) if (part.type === "image") {
		touched = true;
		out.push({
			type: "text",
			text: "[image]"
		});
	} else if (part.type === "document") {
		touched = true;
		out.push({
			type: "text",
			text: "[document]"
		});
	} else out.push(part);
	return touched ? out : null;
}
/**
* Drop the oldest "round" from `turns` and return a fresh array. Used by
* the PTL retry path to shrink the prompt one round at a time.
*
* A round is a contiguous `[user, assistant?, tool_results?]` group. The
* function walks forward from index 0, advances through the user turn
* and any trailing assistant + tool-result turns belonging to the same
* exchange, and returns the remainder.
*
* Adjacency-safe: when the oldest user turn carries `tool_result` blocks
* answering an assistant turn ahead of it (rare — happens during
* resume), the function keeps walking until the next clean boundary so
* the resulting array still respects every provider's `tool_use ↔
* tool_result` adjacency rule.
*
* Returns `turns` unchanged when only one round (or less) remains — the
* caller is expected to interpret that as "cannot shrink further" and
* give up the retry loop.
*/
function truncateHeadForPtlRetry(turns) {
	if (turns.length <= 1) return turns.slice();
	const firstUserIdx = turns.findIndex((t) => t.role === "user");
	if (firstUserIdx < 0) return turns.slice();
	let cursor = firstUserIdx + 1;
	while (cursor < turns.length) {
		const turn = turns[cursor];
		if (turn.role === "assistant") {
			cursor++;
			continue;
		}
		if (turn.role === "user" && isToolResultsOnlyTurn(turn)) {
			cursor++;
			continue;
		}
		break;
	}
	if (cursor >= turns.length) return turns.slice();
	return turns.slice(cursor);
}
function isToolResultsOnlyTurn(turn) {
	if (turn.content.length === 0) return false;
	return turn.content.every((block) => block.type === "tool_result");
}
/**
* Walk `proposedCut` backward to the nearest position where splitting at
* that index produces a round-boundary-clean partition — i.e. neither
* half breaks the `tool_use ↔ tool_result` adjacency rule that every
* provider (most strictly Anthropic) enforces.
*
* The hazardous case: the proposed cut lands BETWEEN an assistant turn
* carrying `tool_call` blocks and the user turn carrying the matching
* `tool_result` blocks. Then `toSummarize` ends with an orphan
* `tool_use` (provider 400 on the summarization request) AND `preserved`
* starts with an orphan `tool_result` (provider 400 on the next live
* agent run against the wire-level cutoff output).
*
* Algorithm: keep walking `cut` backward as long as `turns[cut - 1]`
* is an assistant turn with at least one `tool_call` block. The walk
* stops when:
*  - we reach `cut = 0` (slice would be empty; caller's existing
*    "scope resolved to zero turns" guard handles it), or
*  - the trailing turn is user-role (clean — model emits no pending
*    tool_use from user turns), or
*  - the trailing turn is assistant text without tool_use (clean —
*    text-only response is a complete round).
*
* Returning the adjusted cut over-preserves the tail relative to the
* caller's request — `keepTurns` is interpreted as the MINIMUM number
* of turns kept verbatim, not the exact count.
*/
function findSafeRoundBoundary(turns, proposedCut) {
	let cut = Math.max(0, Math.min(turns.length, proposedCut));
	while (cut > 0 && hasPendingToolUse(turns[cut - 1])) cut--;
	return cut;
}
/** Does this turn end with any unanswered `tool_use` blocks? */
function hasPendingToolUse(turn) {
	if (turn.role !== "assistant") return false;
	for (const block of turn.content) if (block.type === "tool_call") return true;
	return false;
}
function hasTextBearingContent(turns) {
	for (const turn of turns) {
		if (turn.role === "system") continue;
		for (const block of turn.content) {
			if (block.type === "text" && block.text.trim().length > 0) return true;
			if (block.type === "tool_call" || block.type === "tool_result") return true;
		}
	}
	return false;
}
/**
* Maximum length of an anchor turn's textual preview, in characters. Long
* enough to give the model recognizable context (the first paragraph of
* a typical user message), short enough that it doesn't blow the
* cache-stability invariant for the prompt prefix.
*/
const ANCHOR_PREVIEW_MAX_CHARS = 200;
/**
* Extract the first ~200 chars of text-bearing content from a turn — the
* preview surfaced in `from` / `up_to` direction prompts so the model
* knows where the slice begins.
*/
function anchorPreviewFor(turn) {
	for (const block of turn.content) if (block.type === "text" && block.text.trim().length > 0) {
		const flat = block.text.replace(/\s+/g, " ").trim();
		return flat.length > 200 ? `${flat.slice(0, 199)}…` : flat;
	}
	return "(no preview available)";
}
/**
* Build a synthetic `SessionTurn` carrying a single `compact-summary`
* block, ready to append to a session.
*
* The turn's role is `'user'` so it sits at a conversational boundary
* the way the model expects. The caller is responsible for
* `session.appendTurns([turn])`. The id is freshly generated via
* `crypto.randomUUID()` so collisions are statistically impossible.
*
* Typical use after running `compactConversation`:
*
* ```ts
* const result = await compactConversation({ provider, turns })
* const turn = summaryToTurn({
*   summary: result.summary,
*   replacesTurnIds: result.summarizedTurnIds,
*   model: result.model,
*   usage: result.usage,
* })
* await session.appendTurns([turn])
* ```
*/
function summaryToTurn(input) {
	const compactedAt = input.compactedAt ?? Date.now();
	return {
		id: crypto.randomUUID(),
		role: "user",
		content: [{
			type: "compact-summary",
			replacesTurnIds: input.replacesTurnIds,
			summary: input.summary,
			model: input.model,
			usage: input.usage,
			compactedAt
		}],
		createdAt: compactedAt
	};
}
//#endregion
//#region src/compact/prompt.ts
/**
* No-tools guard. The runner sends `tools: []` to the provider already,
* but some models still hallucinate tool-call intent on a long
* conversation. The prose guard is cheap insurance.
*/
const NO_TOOLS_PREAMBLE = `CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.

- Do NOT use Read, Bash, Grep, Glob, Edit, Write, or ANY other tool.
- You already have all the context you need in the conversation above.
- Tool calls will be REJECTED and will waste your only turn — you will fail the task.
- Your entire response must be plain text: an <analysis> block followed by a <summary> block.`;
/**
* Body shared by every direction. Lays out the 9-section scaffold,
* mirrors Claude Code's `BASE_COMPACT_PROMPT` so a model already trained
* on the layout produces the same shape.
*/
const BASE_INSTRUCTIONS = `Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.

This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.

Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:

1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
   - The user's explicit requests and intents
   - Your approach to addressing the user's requests
   - Key decisions, technical concepts and code patterns
   - Specific details like file names, full code snippets, function signatures, file edits
   - Errors that you ran into and how you fixed them
   - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
2. Double-check for technical accuracy and completeness.

Your summary, wrapped in <summary> tags, must include the following sections:

1. Primary Request and Intent
2. Key Technical Concepts
3. Files and Code Sections (with paths; include code snippets only when load-bearing)
4. Errors and fixes
5. Problem Solving
6. All user messages (list ALL non-tool user messages, verbatim)
7. Pending Tasks
8. Current Work
9. Optional Next Step (include direct quotes from the most recent conversation when relevant)`;
/** Trailer prompting the model to begin. Same on every direction. */
const TRAILER = "Provide your <analysis> and <summary> now.";
const FULL_BLURB = `## Scope
The conversation above is being summarized in full. Capture every section the user might need to resume from a fresh context.`;
const TAIL_BLURB = `## Scope
Summarize the conversation above. The most recent turns will be preserved verbatim alongside your summary, so prioritize older context that would otherwise be lost.`;
const FROM_BLURB = `## Scope
Summarize the conversation FROM the marked anchor onward (the recent portion). Everything before the anchor will be preserved verbatim.

Anchor turn (preview):
%ANCHOR_PREVIEW%`;
const UP_TO_BLURB = `## Scope
Summarize the conversation UP TO the marked anchor (the older portion). Everything from the anchor onward will be preserved verbatim — your summary's job is to compress the prior context the user can no longer scroll back to.

Anchor turn (preview):
%ANCHOR_PREVIEW%`;
/** Compose the full prompt with a custom direction-blurb. Internal helper. */
function compose(blurb) {
	return [
		NO_TOOLS_PREAMBLE,
		BASE_INSTRUCTIONS,
		blurb,
		TRAILER
	].join("\n\n");
}
function buildFullCompactPrompt() {
	return compose(FULL_BLURB);
}
function buildTailCompactPrompt() {
	return compose(TAIL_BLURB);
}
function buildFromCompactPrompt(anchorPreview) {
	return compose(FROM_BLURB.replace("%ANCHOR_PREVIEW%", anchorPreview));
}
function buildUpToCompactPrompt(anchorPreview) {
	return compose(UP_TO_BLURB.replace("%ANCHOR_PREVIEW%", anchorPreview));
}
/**
* Default public builder. Dispatches by direction to the four named
* builders. Throws when `from` / `up_to` are passed without an
* `anchorPreview` — those scopes only make sense with an anchor and a
* silent fallback would produce a prompt that doesn't tell the model
* where the slice begins.
*/
const buildCompactPrompt = (opts) => {
	switch (opts.direction) {
		case "full": return buildFullCompactPrompt();
		case "tail": return buildTailCompactPrompt();
		case "from": {
			const preview = opts.anchorPreview ?? "";
			if (preview.length === 0) throw new Error("buildCompactPrompt: `anchorPreview` is required for direction \"from\".");
			return buildFromCompactPrompt(preview);
		}
		case "up_to": {
			const preview = opts.anchorPreview ?? "";
			if (preview.length === 0) throw new Error("buildCompactPrompt: `anchorPreview` is required for direction \"up_to\".");
			return buildUpToCompactPrompt(preview);
		}
	}
};
//#endregion
//#region src/compact/compact.ts
/**
* Directive appended as the trailing user message when the conversation
* to summarize ends with an assistant turn. Mirrors the system-prompt
* TRAILER text so the model gets the same imperative cue from both
* surfaces — system instruction + final user message.
*
* Compaction-specific: paired with the compaction system prompt. Other
* call-sites of {@link ensureEndsWithUserMessage} pass their own directive
* (or the neutral `DEFAULT_USER_TAIL_DIRECTIVE`) so unrelated codepaths
* don't inject a "give me a summary" cue into a regular turn.
*/
const SUMMARY_USER_DIRECTIVE = "Provide your <analysis> and <summary> now.";
/** Default `keepTurns` for `scope: 'tail'`. Matches `AgentBehavior.compactKeepTurns`. */
const DEFAULT_KEEP_TURNS = 4;
/** Default max output tokens for the summary call. */
const DEFAULT_MAX_OUTPUT_TOKENS = 2e4;
/** Default PTL retry budget. */
const DEFAULT_MAX_PTL_RETRIES = 3;
/** Maximum transient-error retries before giving up. Independent of PTL. */
const TRANSIENT_RETRY_BUDGET = 2;
async function compactConversation(opts) {
	const slice = sliceForCompaction(opts.turns, opts.scope ?? "tail", opts.keepTurns ?? DEFAULT_KEEP_TURNS);
	const direction = scopeToDirection(opts.scope ?? "tail");
	const anchorPreview = direction === "from" || direction === "up_to" ? anchorPreviewFor(anchorTurnFor(slice, opts.scope)) : void 0;
	const systemPrompt = (opts.prompt ?? buildCompactPrompt)({
		direction,
		...anchorPreview !== void 0 ? { anchorPreview } : {}
	});
	const model = opts.model ?? opts.provider.meta.defaultModel;
	const maxOutputTokens = opts.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS;
	const maxPtlRetries = Math.max(0, opts.maxPtlRetries ?? DEFAULT_MAX_PTL_RETRIES);
	let workingTurns = stripImagesFromTurns(slice.toSummarize);
	let ptlRetries = 0;
	let transientRetries = 0;
	let attempt = 0;
	while (true) {
		attempt++;
		const kind = ptlRetries > 0 ? "ptl-retry" : transientRetries > 0 ? "transient-retry" : "initial";
		opts.onAttempt?.({
			attempt,
			kind
		});
		try {
			const messages = ensureEndsWithUserMessage(ensureToolResultPairing(turnsToMessages(workingTurns)), opts.provider, SUMMARY_USER_DIRECTIVE);
			const { summary, usage } = await runOnce({
				provider: opts.provider,
				model,
				system: systemPrompt,
				messages,
				maxTokens: maxOutputTokens,
				...opts.thinking !== void 0 ? { thinking: opts.thinking } : {},
				...opts.signal !== void 0 ? { signal: opts.signal } : {}
			});
			const workingIds = new Set(workingTurns.map((t) => t.id));
			const droppedDueToPtl = [];
			if (ptlRetries > 0) {
				for (const t of slice.toSummarize) if (!workingIds.has(t.id)) droppedDueToPtl.push(t.id);
			}
			return {
				summary,
				usage: {
					...usage,
					modelId: usage.modelId ?? model
				},
				model,
				ptlRetries,
				summarizedTurnIds: workingTurns.map((t) => t.id),
				droppedDueToPtl,
				preservedTurns: slice.preserved,
				beforeBytes: bytesIn(workingTurns),
				afterBytes: utf8ByteLength(summary)
			};
		} catch (err) {
			if (isAbortError(err, opts.signal)) throw err;
			if (isPromptTooLongError(err)) {
				if (ptlRetries >= maxPtlRetries) throw new CompactPromptTooLongError(`Compaction failed: prompt_too_long after ${ptlRetries} retries.`, ptlRetries);
				const truncated = truncateHeadForPtlRetry(workingTurns);
				if (truncated.length === workingTurns.length) throw new CompactPromptTooLongError(`Compaction failed: prompt_too_long and conversation cannot be shrunk further.`, ptlRetries);
				workingTurns = truncated;
				ptlRetries++;
				continue;
			}
			if (isTransientError(err) && transientRetries < TRANSIENT_RETRY_BUDGET) {
				transientRetries++;
				continue;
			}
			throw err;
		}
	}
}
/**
* Single provider call. Strips the `<analysis>` block and returns the
* post-trim summary text along with the usage report.
*
* Why not just use `result.text`: some providers stream deltas without
* emitting a concatenated `text` field at the end (or set it to an
* empty string when the stream finished via tool-call). Accumulating
* deltas in `text` and falling back to `result.text` mirrors
* `generateSessionTitle` and handles every adapter shape.
*/
async function runOnce(opts) {
	let streamed = "";
	const result = await opts.provider.stream({
		model: opts.model,
		system: opts.system,
		tools: [],
		messages: opts.messages,
		maxTokens: opts.maxTokens,
		...opts.thinking !== void 0 ? { thinking: opts.thinking } : {},
		...opts.signal !== void 0 ? { signal: opts.signal } : {}
	}, { onText: (delta) => {
		streamed += delta;
	} });
	let summary = stripAnalysisBlock(streamed.length > 0 ? streamed : result.text).trim();
	if (summary.length === 0) {
		const thinking = collectThinkingText(result.assistantMessage);
		if (thinking.length > 0) summary = stripAnalysisBlock(thinking).trim();
	}
	if (summary.length === 0) throw new Error("Compaction failed: provider returned no summary text.");
	return {
		summary,
		usage: result.usage
	};
}
/**
* Concatenate every `thinking`-block's text from an assistant message.
*
* Reasoning models route their output through provider-specific
* "thinking" channels (Anthropic native thinking, OpenAI o-series
* reasoning, OpenAI-compat `reasoning_content`, OpenRouter
* `reasoning_details`). All of them surface as `{ type: 'thinking', text }`
* blocks on the normalized `SessionMessage.content` by the time the
* provider's `stream()` returns. Walking the blocks is provider-agnostic
* — works for every adapter without bespoke per-provider handling.
*
* Returns the empty string when no thinking blocks are present, so the
* caller's "did we get anything?" check stays a single `.length === 0`.
*/
function collectThinkingText(message) {
	const parts = [];
	for (const block of message.content) if (block.type === "thinking" && typeof block.text === "string" && block.text.length > 0) parts.push(block.text);
	return parts.join("\n");
}
/**
* Extract the summary text from the provider's response, peeling off
* any envelope the model wrapped it in.
*
* The compact prompt asks for `<analysis>...</analysis><summary>...</summary>`
* but real models drift from the format. This function tries four
* extraction paths in order of strictness:
*
*  1. **Strict path** — strip `<analysis>...</analysis>` blocks and
*     extract the `<summary>...</summary>` envelope. Matches the
*     prompt-following ideal.
*  2. **Loose path** — same strip, but accept whatever's outside the
*     `<analysis>` tags as the summary (no `<summary>` envelope
*     required). Handles models that drop the wrapper but keep the
*     analysis.
*  3. **Analysis-as-summary fallback** — when the entire response is a
*     single `<analysis>` block (model conflated the two concepts),
*     return the analysis content. Better than failing the compaction
*     and forcing the user to retry.
*  4. **Raw passthrough** — no recognized envelope. Return the text
*     as-is and let `runOnce`'s empty-check decide whether to throw.
*
* Matches Claude Code's `formatCompactSummary` for path (1) + (2) and
* adds (3) as a graceful-degradation layer we ran into in the wild
* (smaller / non-Anthropic models sometimes produce analysis-only).
*/
function stripAnalysisBlock(text) {
	const analysisStripped = text.replace(/<analysis>[\s\S]*?<\/analysis>/g, "");
	const summaryMatch = analysisStripped.match(/<summary>([\s\S]*?)<\/summary>/);
	if (summaryMatch) return summaryMatch[1];
	if (analysisStripped.trim().length > 0) return analysisStripped;
	const analysisMatch = text.match(/<analysis>([\s\S]*?)<\/analysis>/);
	if (analysisMatch) return analysisMatch[1];
	return text;
}
/**
* Convert turns into the wire-level `SessionMessage[]` shape. Drops
* system turns (rare; they'd confuse a summary call), and inlines any
* pre-existing `compact-summary` markers as plain text so the
* provider's wire converter doesn't have to know about zidane's
* internal block type.
*
* Inlining (instead of dropping) is intentional: a session already
* compacted once still contains the prior summary as load-bearing
* context. Surfacing it as `[Previous compaction summary]\n…` lets the
* new summarization integrate it instead of forgetting it.
*/
function turnsToMessages(turns) {
	const out = [];
	for (const turn of turns) {
		if (turn.role === "system") continue;
		const content = [];
		for (const block of turn.content) {
			if (block.type === "compact-summary") {
				content.push({
					type: "text",
					text: `[Previous compaction summary]\n${block.summary}`
				});
				continue;
			}
			if (block.type === "thinking") continue;
			content.push(block);
		}
		if (content.length === 0) continue;
		out.push({
			role: turn.role,
			content
		});
	}
	return out;
}
function scopeToDirection(scope) {
	if (scope === "full" || scope === "tail") return scope;
	return scope.kind;
}
function anchorTurnFor(slice, scope) {
	if (typeof scope === "string") throw new Error("anchorTurnFor: scope must be object form");
	if (scope.kind === "from") return slice.toSummarize[0];
	return slice.toSummarize[slice.toSummarize.length - 1];
}
function bytesIn(turns) {
	let total = 0;
	for (const turn of turns) for (const block of turn.content) if (block.type === "text") total += utf8ByteLength(block.text);
	else if (block.type === "tool_result") total += toolOutputByteLength(block.output);
	else if (block.type === "tool_call") total += utf8ByteLength(JSON.stringify(block.input));
	else if (block.type === "thinking") total += utf8ByteLength(block.text);
	return total;
}
/**
* Provider-agnostic predicate for the "prompt is too long" rejection.
* Inspects error code, type, status, and message substring — every
* provider names this case differently but the message is recognizable.
*/
function isPromptTooLongError(err) {
	if (!err || typeof err !== "object") return false;
	const e = err;
	if (typeof e.code === "string" && /prompt[_ ]too[_ ]long/i.test(e.code)) return true;
	if (typeof e.status === "number" && (e.status === 413 || e.status === 400)) {
		const message = typeof e.message === "string" ? e.message : "";
		if (/prompt[_ ]too[_ ]long|context[_ ]length|maximum[_ ]context|too many tokens/i.test(message)) return true;
	}
	if (typeof e.message === "string" && /prompt[_ ]too[_ ]long|context[_ ]length[_ ]exceeded|context window/i.test(e.message)) return true;
	const nested = e.error ?? {};
	if (typeof nested.type === "string" && nested.type === "invalid_request_error") {
		const message = typeof nested.message === "string" ? nested.message : "";
		if (/prompt[_ ]too[_ ]long|too long|context window/i.test(message)) return true;
	}
	return false;
}
/**
* Transient network / 5xx errors worth retrying once or twice.
*/
function isTransientError(err) {
	if (!err || typeof err !== "object") return false;
	const e = err;
	if (typeof e.status === "number" && e.status >= 500 && e.status < 600) return true;
	if (typeof e.code === "string" && /ECONNRESET|ETIMEDOUT|ENETUNREACH|EAI_AGAIN|fetch failed/i.test(e.code)) return true;
	if (typeof e.message === "string" && /socket hang up|fetch failed|network error|terminated|ECONNRESET|read ETIMEDOUT/i.test(e.message)) return true;
	return false;
}
function isAbortError(err, signal) {
	if (signal?.aborted) return true;
	if (!err || typeof err !== "object") return false;
	const e = err;
	if (e.name === "AbortError") return true;
	if (typeof e.message === "string" && /aborted/i.test(e.message)) return true;
	return false;
}
//#endregion
//#region src/compact/restore.ts
const DEFAULT_FILE_TOKEN_BUDGET = 5e4;
const DEFAULT_FILE_TOKEN_PER_FILE_CAP = 5e3;
const DEFAULT_MAX_FILES_TO_RESTORE = 5;
const DEFAULT_SKILL_TOKEN_BUDGET = 25e3;
const DEFAULT_SKILL_TOKEN_PER_SKILL_CAP = 5e3;
/** Default canonical tool names — `rewriteMessagesToWire` handles aliasing. */
const DEFAULT_READ_FILE_TOOL_NAME = "read_file";
const DEFAULT_SKILLS_USE_TOOL_NAME = "skills_use";
/**
* Convert a raw read-state map into a deduped, path-ranked list ready for
* restoration. Multiple entries for the same path (different
* `(offset, limit, maxBytes)` slices) collapse to one — keeping the most
* recent `mtimeMs`.
*
* Filters out entries whose key doesn't share the given `cwd` prefix:
* those came from a different execution context and can't be read back
* through this agent's handle.
*
* Pure. Most callers want {@link selectFilesFromSession}, which wraps
* `getReadState(session)` + this function in one call so the host
* doesn't have to reach into the tools layer.
*/
function selectFilesFromReadState(readState, cwd) {
	const prefix = `${cwd}::`;
	const byPath = /* @__PURE__ */ new Map();
	for (const [key, entry] of readState) {
		if (!key.startsWith(prefix)) continue;
		const path = key.slice(prefix.length);
		if (path.length === 0) continue;
		const prior = byPath.get(path) ?? -Infinity;
		if (entry.mtimeMs > prior) byPath.set(path, entry.mtimeMs);
	}
	return Array.from(byPath, ([path, mtimeMs]) => ({
		path,
		mtimeMs
	})).sort((a, b) => b.mtimeMs - a.mtimeMs);
}
/**
* Session-aware convenience: extract recently-read files directly from
* a {@link Session} via its per-session read-state map.
*
* Hosts (TUI / SDK consumers) typically have a `Session` and a `cwd`
* (the active agent's `handle.cwd`) on hand — this wrapper saves them
* from reaching into `src/tools/read-state.ts` directly. Returns an
* empty list when no read state has been recorded yet (fresh session,
* or `behavior.dedupReads === false`).
*
* Equivalent to:
*
* ```ts
* const state = getReadState(session)
* return state ? selectFilesFromReadState(state, cwd) : []
* ```
*/
function selectFilesFromSession(session, cwd) {
	const state = getReadState(session);
	return state ? selectFilesFromReadState(state, cwd) : [];
}
/**
* Pick the top `maxFiles` from `files` (descending by `mtimeMs`),
* dropping any whose path appears in `excludePaths`.
*
* Stable for equal mtimes — files with the same timestamp retain their
* input order. Pure.
*/
function selectRecentFiles(files, opts) {
	const excluded = new Set(opts.excludePaths ?? []);
	return files.filter((f) => !excluded.has(f.path)).slice().sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, Math.max(0, opts.maxFiles));
}
/**
* Format a file's contents to match `read_file`'s output shape — 1-indexed
* line numbers separated by tabs, identical to what the model has seen
* from real `read_file` calls. Applies the per-file token cap by truncating
* at the nearest line boundary; appends a footer pointing at the next
* offset so the model can re-read the rest if needed.
*/
function formatFileForRestoration(content, perFileTokenCap) {
	const totalBytes = utf8ByteLength(content);
	const allLines = content.split("\n");
	const totalLines = allLines.length;
	const numbered = [];
	let runningChars = 0;
	const charCap = Math.max(1, perFileTokenCap) * 4;
	let truncatedAt = -1;
	let midLineCut = false;
	for (let i = 0; i < allLines.length; i++) {
		const numberedLine = `${i + 1}\t${allLines[i]}`;
		const lineCharCost = numberedLine.length + (i < allLines.length - 1 ? 1 : 0);
		if (runningChars + lineCharCost > charCap) {
			if (numbered.length === 0) {
				const cutTo = Math.max(1, charCap - `${i + 1}\t`.length);
				numbered.push(`${i + 1}\t${allLines[i].slice(0, cutTo)}`);
				midLineCut = true;
			}
			truncatedAt = i;
			break;
		}
		numbered.push(numberedLine);
		runningChars += lineCharCost;
	}
	const body = numbered.join("\n");
	if (truncatedAt < 0) return {
		body,
		truncated: false,
		estimatedTokens: estimateTokens(body)
	};
	const truncated = body + `\n\n…truncated at ${midLineCut ? `line ${truncatedAt + 1} (mid-line)` : `line ${truncatedAt}`} (post-compact restoration cap: ${perFileTokenCap} tokens). File has ${totalLines} lines, ${totalBytes} bytes total — ${midLineCut ? `mid-line cut prevents a precise offset — re-read with offset=${truncatedAt + 1} and a larger maxBytes` : `re-read with offset=${truncatedAt + 1} to continue`}.`;
	return {
		body: truncated,
		truncated: true,
		estimatedTokens: estimateTokens(truncated)
	};
}
/**
* Format a skill's instructions for restoration. Skills are plain markdown
* — no line numbering, no wrapping XML envelope (the model already
* understands the format from real `skills_use` calls). Truncation cuts
* at a line boundary when possible; appends a marker so the model knows
* the body is incomplete.
*/
function formatSkillForRestoration(instructions, perSkillTokenCap) {
	const charCap = Math.max(1, perSkillTokenCap) * 4;
	if (instructions.length <= charCap) return {
		body: instructions,
		truncated: false,
		estimatedTokens: estimateTokens(instructions)
	};
	const lastNewline = instructions.slice(0, charCap).lastIndexOf("\n");
	const cutoff = lastNewline > 0 ? lastNewline : charCap;
	const truncatedBody = `${instructions.slice(0, cutoff).trimEnd()}\n\n…[truncated post-compact at ${perSkillTokenCap} tokens; full skill body lives at the skill's location]`;
	return {
		body: truncatedBody,
		truncated: true,
		estimatedTokens: estimateTokens(truncatedBody)
	};
}
/**
* Build the synthetic turns to append after a `compact-summary` marker.
*
* Returns a `PostCompactAttachments` envelope; the caller is responsible
* for `session.appendTurns([summaryTurn, ...result.turns])`. The two
* synthetic turns are always emitted together (or both omitted when
* nothing was restored) so the `tool_use ↔ tool_result` adjacency
* invariant holds regardless of caller code path.
*
* Failure isolation: a single file's read failure never blocks the rest
* of restoration — that file is skipped silently and processing
* continues. The returned `restoredFiles` count reflects what actually
* landed in the synthesized turns.
*/
async function buildPostCompactAttachments(opts) {
	const fileTokenBudget = opts.fileTokenBudget ?? DEFAULT_FILE_TOKEN_BUDGET;
	const fileTokenPerFileCap = opts.fileTokenPerFileCap ?? DEFAULT_FILE_TOKEN_PER_FILE_CAP;
	const maxFilesToRestore = opts.maxFilesToRestore ?? DEFAULT_MAX_FILES_TO_RESTORE;
	const skillTokenBudget = opts.skillTokenBudget ?? DEFAULT_SKILL_TOKEN_BUDGET;
	const skillTokenPerSkillCap = opts.skillTokenPerSkillCap ?? DEFAULT_SKILL_TOKEN_PER_SKILL_CAP;
	const readFileToolName = opts.readFileToolName ?? DEFAULT_READ_FILE_TOOL_NAME;
	const skillsUseToolName = opts.skillsUseToolName ?? DEFAULT_SKILLS_USE_TOOL_NAME;
	const candidateFiles = opts.recentFiles && opts.recentFiles.length > 0 ? selectRecentFiles(opts.recentFiles, {
		maxFiles: maxFilesToRestore,
		...opts.excludePaths ? { excludePaths: opts.excludePaths } : {}
	}) : [];
	const candidateSkills = opts.activeSkills ?? [];
	const fileCalls = [];
	let fileBudgetUsed = 0;
	if (candidateFiles.length > 0 && opts.execution && opts.handle) for (let i = 0; i < candidateFiles.length; i++) {
		const file = candidateFiles[i];
		let content;
		try {
			content = await opts.execution.readFile(opts.handle, file.path);
		} catch {
			continue;
		}
		const formatted = formatFileForRestoration(content, fileTokenPerFileCap);
		if (fileBudgetUsed + formatted.estimatedTokens > fileTokenBudget) break;
		fileBudgetUsed += formatted.estimatedTokens;
		fileCalls.push({
			callId: `compact-restore-file-${i}`,
			path: file.path,
			body: formatted.body,
			estimatedTokens: formatted.estimatedTokens
		});
	}
	const skillCalls = [];
	let skillBudgetUsed = 0;
	for (let i = 0; i < candidateSkills.length; i++) {
		const active = candidateSkills[i];
		const instructions = active.skill.instructions ?? "";
		if (instructions.trim().length === 0) continue;
		const formatted = formatSkillForRestoration(instructions, skillTokenPerSkillCap);
		if (skillBudgetUsed + formatted.estimatedTokens > skillTokenBudget) break;
		skillBudgetUsed += formatted.estimatedTokens;
		skillCalls.push({
			callId: `compact-restore-skill-${i}`,
			name: active.skill.name,
			body: formatted.body,
			estimatedTokens: formatted.estimatedTokens
		});
	}
	if (fileCalls.length === 0 && skillCalls.length === 0) return {
		turns: [],
		restoredFiles: 0,
		restoredSkills: 0,
		estimatedTokens: 0
	};
	const assistantBlocks = [];
	const userBlocks = [];
	for (const fc of fileCalls) {
		assistantBlocks.push({
			type: "tool_call",
			id: fc.callId,
			name: readFileToolName,
			input: { path: fc.path }
		});
		userBlocks.push({
			type: "tool_result",
			callId: fc.callId,
			output: fc.body
		});
	}
	for (const sc of skillCalls) {
		assistantBlocks.push({
			type: "tool_call",
			id: sc.callId,
			name: skillsUseToolName,
			input: { name: sc.name }
		});
		userBlocks.push({
			type: "tool_result",
			callId: sc.callId,
			output: sc.body
		});
	}
	const now = Date.now();
	const tag = opts.runId ? { runId: opts.runId } : {};
	return {
		turns: [{
			id: crypto.randomUUID(),
			role: "assistant",
			content: assistantBlocks,
			createdAt: now,
			...tag
		}, {
			id: crypto.randomUUID(),
			role: "user",
			content: userBlocks,
			createdAt: now + 1,
			...tag
		}],
		restoredFiles: fileCalls.length,
		restoredSkills: skillCalls.length,
		estimatedTokens: fileBudgetUsed + skillBudgetUsed
	};
}
//#endregion
//#region src/logger.ts
/**
* Build a Logger from a sink. Stateless and cheap; create one per agent
* (or per app) and use `.with()` to attach correlation ids per-call.
*/
function createLogger(sink, baseAttributes = {}) {
	function emit(level, message, attrs) {
		try {
			sink.emit({
				level,
				timestamp: Date.now(),
				message,
				attrs: attrs ? {
					...baseAttributes,
					...attrs
				} : { ...baseAttributes }
			});
		} catch {}
	}
	return {
		debug: (m, a) => emit("debug", m, a),
		info: (m, a) => emit("info", m, a),
		warn: (m, a) => emit("warn", m, a),
		error: (m, a) => emit("error", m, a),
		with: (extra) => createLogger(sink, {
			...baseAttributes,
			...extra
		}),
		baseAttributes
	};
}
const LEVEL_ORDER = {
	debug: 0,
	info: 1,
	warn: 2,
	error: 3
};
/**
* Human-readable terminal sink. Renders each record as
* `<ISO timestamp> <LEVEL> <message> <attrs as kv pairs>`.
*
* Honors `process.stderr` by default so log lines don't interleave with
* the agent's stdout-bound output (chat responses, JSON results).
*/
function consoleSink(options = {}) {
	const min = LEVEL_ORDER[options.minLevel ?? "info"];
	const stream = options.stream ?? process.stderr;
	return { emit(record) {
		if (LEVEL_ORDER[record.level] < min) return;
		const ts = new Date(record.timestamp).toISOString();
		const kv = Object.entries(record.attrs).filter(([, v]) => v !== void 0).map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ");
		stream.write(`${ts} ${record.level.toUpperCase().padEnd(5)} ${record.message}${kv ? ` ${kv}` : ""}\n`);
	} };
}
/**
* One-JSON-object-per-line sink. Suitable for piping into log aggregators
* (Datadog Agent, Fluent Bit, Loki, Vector) that expect JSONL.
*/
function jsonSink(options = {}) {
	const min = LEVEL_ORDER[options.minLevel ?? "info"];
	const stream = options.stream ?? process.stderr;
	return { emit(record) {
		if (LEVEL_ORDER[record.level] < min) return;
		try {
			stream.write(`${JSON.stringify(record)}\n`);
		} catch {}
	} };
}
/**
* Install a bundle of hook handlers that emit a structured line per
* relevant lifecycle event, automatically attaching correlation ids
* (`runId`, `turnId`, `callId`, `childId`, `depth`, `agentName`).
*
* @example
* ```ts
* const logger = createLogger(consoleSink({ minLevel: 'debug' }), { service: 'tui' })
* const lh = createLoggingHooks({ logger })
* const uninstall = lh.install(agent.hooks)
* try { await agent.run({ prompt }) }
* finally { uninstall() }
* ```
*/
function createLoggingHooks(options) {
	const root = options.logger;
	const includeLifecycle = options.includeLifecycle ?? true;
	const minLevel = LEVEL_ORDER[options.level ?? "info"];
	/**
	* Wrap a Logger so emissions below `minLevel` are dropped before they
	* hit the sink. Lets us gate harness chatter without forcing every
	* `LogSink` to re-implement level filtering. Preserves `.with()`
	* composition (children inherit the filter).
	*/
	function gateLevel(logger) {
		const skip = (level) => LEVEL_ORDER[level] < minLevel;
		const wrap = (l) => ({
			debug: (m, a) => {
				if (!skip("debug")) l.debug(m, a);
			},
			info: (m, a) => {
				if (!skip("info")) l.info(m, a);
			},
			warn: (m, a) => {
				if (!skip("warn")) l.warn(m, a);
			},
			error: (m, a) => {
				if (!skip("error")) l.error(m, a);
			},
			with: (extra) => wrap(l.with(extra)),
			baseAttributes: l.baseAttributes
		});
		return wrap(logger);
	}
	return { install(hooks) {
		const unregisters = [];
		const gatedRoot = gateLevel(root);
		let runLogger = gatedRoot;
		let turnLogger = gatedRoot;
		unregisters.push(hooks.hook("agent:start", (ctx) => {
			runLogger = gatedRoot.with({
				runId: ctx.runId,
				...ctx.parentRunId ? { parentRunId: ctx.parentRunId } : {},
				depth: ctx.depth,
				...ctx.agentName ? { agentName: ctx.agentName } : {}
			});
			turnLogger = runLogger;
			if (includeLifecycle) runLogger.debug("agent run started");
		}));
		unregisters.push(hooks.hook("agent:done", (stats) => {
			runLogger.info("agent run completed", {
				turns: stats.turns,
				totalIn: stats.totalIn,
				totalOut: stats.totalOut,
				...typeof stats.cost === "number" ? { cost: stats.cost } : {},
				elapsedMs: stats.elapsed,
				...typeof stats.timeTillFirstTokenMs === "number" ? { ttftMs: stats.timeTillFirstTokenMs } : {}
			});
		}));
		unregisters.push(hooks.hook("agent:abort", () => {
			runLogger.warn("agent run aborted");
		}));
		unregisters.push(hooks.hook("turn:before", (ctx) => {
			turnLogger = runLogger.with({
				turnId: ctx.turnId,
				turn: ctx.turn
			});
			if (includeLifecycle) turnLogger.debug("turn started");
		}));
		unregisters.push(hooks.hook("turn:after", (ctx) => {
			turnLogger.debug("turn ended", {
				inputTokens: ctx.usage.input,
				outputTokens: ctx.usage.output,
				...ctx.usage.finishReason ? { finishReason: ctx.usage.finishReason } : {},
				...ctx.usage.modelId ? { modelId: ctx.usage.modelId } : {},
				...typeof ctx.usage.timeToFirstTokenMs === "number" ? { ttftMs: ctx.usage.timeToFirstTokenMs } : {}
			});
		}));
		unregisters.push(hooks.hook("stream:error", (ctx) => {
			turnLogger.error("stream error", {
				message: ctx.err instanceof Error ? ctx.err.message : String(ctx.err),
				...ctx.statusCode !== void 0 ? { statusCode: ctx.statusCode } : {},
				...ctx.requestId !== void 0 ? { requestId: ctx.requestId } : {}
			});
		}));
		unregisters.push(hooks.hook("tool:before", (ctx) => {
			if (!includeLifecycle) return;
			turnLogger.debug("tool started", {
				toolName: ctx.name,
				displayName: ctx.displayName,
				callId: ctx.callId
			});
		}));
		unregisters.push(hooks.hook("tool:after", (ctx) => {
			if (!includeLifecycle) return;
			turnLogger.debug("tool ended", {
				toolName: ctx.name,
				callId: ctx.callId,
				outputBytes: ctx.outputBytes
			});
		}));
		unregisters.push(hooks.hook("tool:error", (ctx) => {
			turnLogger.error("tool error", {
				toolName: ctx.name,
				callId: ctx.callId,
				message: ctx.error.message
			});
		}));
		unregisters.push(hooks.hook("tool:dispatched", (ctx) => {
			const isAnomaly = ctx.outcome === "gate-block" || ctx.outcome === "unknown" || ctx.outcome === "invalid-input";
			if (!isAnomaly && !includeLifecycle) return;
			turnLogger[isAnomaly ? "warn" : "debug"]("tool dispatched", {
				toolName: ctx.name,
				callId: ctx.callId,
				outcome: ctx.outcome,
				...ctx.reason ? { reason: ctx.reason } : {}
			});
		}));
		unregisters.push(hooks.hook("validation:reject", (ctx) => {
			turnLogger.warn("tool input rejected", {
				toolName: ctx.name,
				callId: ctx.callId,
				reason: ctx.reason
			});
		}));
		unregisters.push(hooks.hook("budget:exceeded", (ctx) => {
			turnLogger.warn("byte budget exceeded", {
				bytes: ctx.bytes,
				budget: ctx.budget
			});
		}));
		unregisters.push(hooks.hook("tool-budget:exceeded", (ctx) => {
			turnLogger.warn("tool budget exceeded", {
				toolName: ctx.tool,
				count: ctx.count,
				max: ctx.max,
				mode: ctx.mode
			});
		}));
		unregisters.push(hooks.hook("mcp:bootstrap:end", (ctx) => {
			if (ctx.ok) {
				if (includeLifecycle) runLogger.debug("mcp bootstrap ok", {
					server: ctx.name,
					transport: ctx.transport,
					durationMs: ctx.durationMs,
					toolCount: ctx.toolCount,
					...ctx.lazy ? { lazy: true } : {},
					...ctx.cached ? { cached: true } : {}
				});
			} else runLogger.warn("mcp bootstrap failed", {
				server: ctx.name,
				transport: ctx.transport,
				durationMs: ctx.durationMs,
				message: ctx.error.message
			});
		}));
		unregisters.push(hooks.hook("mcp:error", (ctx) => {
			runLogger.error("mcp error", {
				server: ctx.name,
				message: ctx.error.message
			});
		}));
		unregisters.push(hooks.hook("mcp:warn", (ctx) => {
			runLogger.warn("mcp warn", {
				server: ctx.name,
				message: ctx.message
			});
		}));
		unregisters.push(hooks.hook("mcp:auth:required", (ctx) => {
			runLogger.warn("mcp auth required", {
				server: ctx.name,
				transport: ctx.transport,
				reason: ctx.reason
			});
		}));
		unregisters.push(hooks.hook("mcp:tool:error", (ctx) => {
			turnLogger.error("mcp tool error", {
				server: ctx.server,
				tool: ctx.displayName,
				callId: ctx.callId,
				message: ctx.error.message
			});
		}));
		unregisters.push(hooks.hook("spawn:before", (ctx) => {
			if (!includeLifecycle) return;
			runLogger.debug("spawn started", {
				childId: ctx.id,
				depth: ctx.depth
			});
		}));
		unregisters.push(hooks.hook("spawn:complete", (ctx) => {
			runLogger.info("spawn completed", {
				childId: ctx.id,
				...ctx.depth ? { depth: ctx.depth } : {},
				status: ctx.status ?? "completed",
				turns: ctx.stats.turns,
				totalIn: ctx.stats.totalIn,
				totalOut: ctx.stats.totalOut,
				...typeof ctx.stats.cost === "number" ? { cost: ctx.stats.cost } : {}
			});
		}));
		unregisters.push(hooks.hook("spawn:error", (ctx) => {
			runLogger.error("spawn error", {
				childId: ctx.id,
				...ctx.depth ? { depth: ctx.depth } : {},
				message: ctx.error.message
			});
		}));
		let disposed = false;
		return function uninstall() {
			if (disposed) return;
			disposed = true;
			for (const un of unregisters) try {
				un();
			} catch {}
		};
	} };
}
//#endregion
//#region src/mcp/oauth-callback.ts
const DEFAULT_PATH = "/callback";
const DEFAULT_HOST = "127.0.0.1";
const SUCCESS_HTML = `<!doctype html>
<html><head><meta charset="utf-8"><title>Logged in</title>
<style>body{font:14px/1.5 -apple-system,system-ui,sans-serif;margin:6rem auto;max-width:28rem;text-align:center;color:#1d1d1f}.ok{color:#1f8a4c;font-weight:600}</style>
</head><body>
<p class="ok">Logged in.</p>
<p>You can close this tab and return to the terminal.</p>
</body></html>`;
function errorHtml(message) {
	return `<!doctype html>
<html><head><meta charset="utf-8"><title>Login failed</title>
<style>body{font:14px/1.5 -apple-system,system-ui,sans-serif;margin:6rem auto;max-width:28rem;text-align:center;color:#1d1d1f}.err{color:#c43c2c;font-weight:600}</style>
</head><body>
<p class="err">Login failed.</p>
<p>${message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</p>
<p>You can close this tab and return to the terminal.</p>
</body></html>`;
}
/**
* Start a one-shot OAuth callback server. The returned handle's `redirectUri`
* should be passed to the authorization server as the `redirect_uri` query
* parameter; `promise` resolves once the user finishes the browser flow.
*
* Always `await handle.close()` in a `finally` block — even on success, the
* server stays open until told to shut down (so it can serve the
* "you can close this tab" page).
*/
async function startOAuthCallback(opts = {}) {
	const path = opts.path ?? DEFAULT_PATH;
	const host = opts.host ?? DEFAULT_HOST;
	const port = opts.port ?? 0;
	if (!path.startsWith("/")) throw new Error(`OAuth callback path must start with "/" (got: ${JSON.stringify(path)})`);
	if (opts.signal?.aborted) throw new Error("OAuth callback aborted");
	let resolveResult;
	let rejectResult;
	const promise = new Promise((resolve, reject) => {
		resolveResult = resolve;
		rejectResult = reject;
	});
	promise.catch(() => {});
	let settled = false;
	const resolveOnce = (value) => {
		if (settled) return;
		settled = true;
		resolveResult(value);
	};
	const rejectOnce = (error) => {
		if (settled) return;
		settled = true;
		rejectResult(error);
	};
	const server = createServer((req, res) => {
		const url = new URL(req.url ?? "/", `http://${host}`);
		if (url.pathname !== path) {
			res.writeHead(404, { "content-type": "text/plain" });
			res.end("Not Found");
			return;
		}
		const htmlHeaders = {
			"content-type": "text/html; charset=utf-8",
			"cache-control": "no-store"
		};
		const error = url.searchParams.get("error");
		if (error) {
			const desc = url.searchParams.get("error_description") ?? error;
			res.writeHead(400, htmlHeaders);
			res.end(errorHtml(desc));
			rejectOnce(/* @__PURE__ */ new Error(`OAuth authorization failed: ${desc}`));
			return;
		}
		const code = url.searchParams.get("code");
		if (!code) {
			res.writeHead(400, { "content-type": "text/plain" });
			res.end("Missing \"code\" query parameter.");
			return;
		}
		const state = url.searchParams.get("state") ?? void 0;
		res.writeHead(200, htmlHeaders);
		res.end(SUCCESS_HTML);
		resolveOnce({
			code,
			state
		});
	});
	server.on("error", (err) => {
		rejectOnce(err instanceof Error ? err : new Error(String(err)));
	});
	await new Promise((resolve, reject) => {
		server.once("error", reject);
		server.listen(port, host, () => {
			server.off("error", reject);
			resolve();
		});
	});
	const addr = server.address();
	if (!addr || typeof addr === "string") {
		server.close();
		throw new Error("OAuth callback server did not bind to a TCP port");
	}
	let closing;
	let closeServer;
	const onAbort = () => {
		rejectOnce(/* @__PURE__ */ new Error("OAuth callback aborted"));
		closeServer();
	};
	closeServer = () => {
		if (closing) return closing;
		closing = new Promise((resolve) => {
			server.closeAllConnections?.();
			server.close(() => {
				opts.signal?.removeEventListener("abort", onAbort);
				if (opts.signal?.aborted) rejectOnce(/* @__PURE__ */ new Error("OAuth callback aborted"));
				else rejectOnce(/* @__PURE__ */ new Error("OAuth callback server closed"));
				resolve();
			});
		});
		return closing;
	};
	opts.signal?.addEventListener("abort", onAbort, { once: true });
	return {
		redirectUri: `http://${host}:${addr.port}${path}`,
		promise,
		close: closeServer
	};
}
//#endregion
//#region src/mcp/login.ts
const DEFAULT_LOGIN_TIMEOUT_MS = 5 * 6e4;
/**
* Run the full interactive OAuth flow for `config`. Only supports `sse` and
* `streamable-http` transports — `stdio` MCP servers don't speak OAuth.
*
* Throws on:
*   - Wrong transport.
*   - Abort signal.
*   - Browser-side error (user denied, server rejected, etc.).
*   - Code exchange failure.
*   - Post-exchange connect failure.
*
* Always closes the loopback callback server before returning, success or
* failure.
*/
async function loginMcpServer(config, options) {
	if (config.transport !== "sse" && config.transport !== "streamable-http") throw new Error(`MCP OAuth: cannot login for transport "${config.transport}" — only sse / streamable-http are supported`);
	if (!config.url) throw new Error(`MCP OAuth: server "${config.name}" is missing a url`);
	const hooks = options.hooks;
	let callback;
	try {
		callback = await startOAuthCallback({
			signal: options.signal,
			path: options.callbackPath
		});
		const handle = callback;
		const provider = new McpOAuthProvider({
			name: config.name,
			store: options.store,
			redirectUri: handle.redirectUri,
			clientName: options.clientName,
			scope: options.scope,
			onAuthorizationUrl: async (url) => {
				await hooks?.callHook("mcp:auth:url", {
					name: config.name,
					url: url.toString()
				});
				await options.onAuthorizationUrl?.(url);
			}
		});
		const transport = await createInteractiveTransport(config, provider);
		const client = await createTolerantClient({
			name: "zidane",
			version: "1.0.0"
		});
		let needsAuth = false;
		try {
			await client.connect(transport);
		} catch (err) {
			if (!isUnauthorizedError(err)) {
				await client.close().catch(() => {});
				throw err;
			}
			needsAuth = true;
		}
		if (needsAuth) {
			const { code } = await raceLoginCallback(handle, options.timeoutMs ?? DEFAULT_LOGIN_TIMEOUT_MS, options.signal);
			await transport.finishAuth(code);
			await transport.close().catch(() => {});
			const freshTransport = await createInteractiveTransport(config, provider);
			await client.connect(freshTransport);
		}
		const { tools } = await client.listTools();
		await client.close();
		const tokens = provider.tokens();
		if (!tokens) throw new Error(`MCP OAuth: login for "${config.name}" returned no tokens (server may have rejected the exchange silently)`);
		await hooks?.callHook("mcp:auth:success", { name: config.name });
		return {
			tokens,
			tools
		};
	} catch (err) {
		const error = err instanceof Error ? err : new Error(String(err));
		await hooks?.callHook("mcp:auth:error", {
			name: config.name,
			error
		});
		throw error;
	} finally {
		await callback?.close();
	}
}
/**
* Build an `sse` / `streamable-http` transport pre-wired with `authProvider`.
* Mirrors the bootstrap-side `createTransport` shape but inlined here so the
* login flow doesn't depend on the bootstrap module's private export.
*/
async function createInteractiveTransport(config, authProvider) {
	if (config.transport === "sse") {
		const { SSEClientTransport } = await import("@modelcontextprotocol/sdk/client/sse.js");
		return new SSEClientTransport(new URL(config.url), {
			requestInit: config.headers ? { headers: config.headers } : void 0,
			authProvider
		});
	}
	const { StreamableHTTPClientTransport } = await import("@modelcontextprotocol/sdk/client/streamableHttp.js");
	return new StreamableHTTPClientTransport(new URL(config.url), {
		requestInit: config.headers ? { headers: config.headers } : void 0,
		fetch: sseToJsonFetchIfNeeded(),
		authProvider
	});
}
function isUnauthorizedError(err) {
	if (!err || typeof err !== "object") return false;
	const e = err;
	if (e.name === "UnauthorizedError" || e.constructor?.name === "UnauthorizedError") return true;
	return typeof e.message === "string" && e.message.toLowerCase().startsWith("unauthorized");
}
/**
* Wait on the callback handle, with a hard timeout AND honor the external
* abort signal. Unlike `callback.promise` alone, this provides a deterministic
* failure mode for "user opened the browser then walked away" — the modal
* doesn't hang forever waiting for a redirect that may never come.
*/
async function raceLoginCallback(handle, timeoutMs, signal) {
	if (signal?.aborted) throw new Error("OAuth login aborted");
	let timer;
	let onAbort;
	try {
		return await new Promise((resolve, reject) => {
			timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`OAuth login timed out after ${timeoutMs}ms`)), timeoutMs);
			if (signal) {
				onAbort = () => reject(/* @__PURE__ */ new Error("OAuth login aborted"));
				signal.addEventListener("abort", onAbort, { once: true });
			}
			handle.promise.then(resolve, reject);
		});
	} finally {
		if (timer) clearTimeout(timer);
		if (signal && onAbort) signal.removeEventListener("abort", onAbort);
	}
}
//#endregion
export { stripImagesFromTurns as C, CompactPromptTooLongError as D, CompactInvalidInputError as E, sliceForCompaction as S, truncateHeadForPtlRetry as T, buildFullCompactPrompt as _, createLoggingHooks as a, ANCHOR_PREVIEW_MAX_CHARS as b, selectFilesFromReadState as c, compactConversation as d, BASE_INSTRUCTIONS as f, buildFromCompactPrompt as g, buildCompactPrompt as h, createLogger as i, selectFilesFromSession as l, TRAILER as m, startOAuthCallback as n, jsonSink as o, NO_TOOLS_PREAMBLE as p, consoleSink as r, buildPostCompactAttachments as s, loginMcpServer as t, selectRecentFiles as u, buildTailCompactPrompt as v, summaryToTurn as w, anchorPreviewFor as x, buildUpToCompactPrompt as y };

//# sourceMappingURL=login-0jP1pnSJ.js.map