//#region src/errors.ts
/**
* Thrown when the model or provider signals that the context window was exceeded.
* Downstream consumers should catch this, prune history, and retry.
*/
var AgentContextExceededError = class extends Error {
	code = "context_exceeded";
	provider;
	providerCode;
	constructor(message, options) {
		super(message, options.cause !== void 0 ? { cause: options.cause } : void 0);
		this.name = "AgentContextExceededError";
		this.provider = options.provider;
		this.providerCode = options.providerCode;
	}
};
/**
* Thrown when the provider returns a non-context error (auth, rate limit, server error, etc.).
* Catch-all for unclassified provider failures.
*/
var AgentProviderError = class extends Error {
	code = "provider_error";
	provider;
	providerCode;
	/**
	* Whether a retry with backoff is likely to succeed. See
	* {@link ClassifiedError.retryable}. Absent when the provider did not
	* classify the error — callers should treat absent as "don't retry".
	*/
	retryable;
	constructor(message, options) {
		super(message, options.cause !== void 0 ? { cause: options.cause } : void 0);
		this.name = "AgentProviderError";
		this.provider = options.provider;
		this.providerCode = options.providerCode;
		this.retryable = options.retryable;
	}
};
/**
* Thrown when a run is aborted by the consumer via `agent.abort()` or an external `AbortSignal`.
*/
var AgentAbortedError = class extends Error {
	code = "aborted";
	constructor(message = "Agent run aborted", options) {
		super(message, options?.cause !== void 0 ? { cause: options.cause } : void 0);
		this.name = "AgentAbortedError";
	}
};
/**
* Thrown by the loop when a run's cumulative cost, token consumption, or
* wall-clock elapsed time crosses a ceiling configured on
* {@link AgentBehavior.maxCostUsd} / {@link AgentBehavior.maxTotalTokens} /
* {@link AgentBehavior.maxWallMs}. Acts as a programmable circuit
* breaker for unattended runs — without this, the only built-in safety net
* is {@link AgentBehavior.maxTurns}, which doesn't bound a single very
* expensive turn (large context, deep reasoning).
*
* The breach is checked **after** each turn completes (post-`turn:after`),
* so the run may exceed the budget by one turn's worth of usage before
* tripping. Callers wanting a tighter pre-turn estimate should layer their
* own check on top of the `usage` hook.
*
* The harness treats this the same way as {@link AgentAbortedError}: the
* session run is finalized as `'aborted'`, persisted stats reflect what
* was actually consumed, and the parent agent re-throws so a caller's
* `try`/`catch` can branch on `err instanceof AgentBudgetExceededError`
* without string-sniffing.
*/
var AgentBudgetExceededError = class extends Error {
	code = "budget_exceeded";
	/** Which ceiling tripped. `'cost'` → `maxCostUsd`, `'tokens'` → `maxTotalTokens`, `'wallClock'` → `maxWallMs`. */
	limit;
	/** The configured cap (USD for `cost`, total tokens for `tokens`, ms for `wallClock`). */
	limitValue;
	/** Actual consumed value at the moment the cap was crossed (same units as `limitValue`). */
	actualValue;
	constructor(options) {
		const unit = options.limit === "cost" ? "USD" : options.limit === "wallClock" ? "ms" : "tokens";
		super(`Agent run exceeded ${options.limit} budget: ${options.actualValue} ${unit} > ${options.limitValue} ${unit}`, options.cause !== void 0 ? { cause: options.cause } : void 0);
		this.name = "AgentBudgetExceededError";
		this.limit = options.limit;
		this.limitValue = options.limitValue;
		this.actualValue = options.actualValue;
	}
};
/**
* Thrown by the pre-send pairing repair when {@link AgentBehavior.strictToolPairing}
* is `true` and {@link ensureToolResultPairing} would otherwise patch over
* corruption. Strict mode opts into fail-fast for training-data collectors and
* any consumer that prefers to bail out rather than ship a transcript carrying
* a {@link SYNTHETIC_TOOL_RESULT_PLACEHOLDER}.
*
* The `repairs` field carries every repair the loop would have made — useful
* for postmortems and for surfacing exactly which transcripts were rejected.
*
* Note: callers consuming the chat layer (TUI/SDK presets) typically leave
* `strictToolPairing` off so user-facing sessions auto-heal instead of
* crashing.
*/
var AgentToolPairingError = class extends Error {
	code = "tool_pairing_corruption";
	/** Provider whose wire format the corruption would have hit. */
	provider;
	/** Upstream error code when the corruption was detected from a 400 response. */
	providerCode;
	/**
	* Repairs the harness would have performed had strict mode been off.
	* Preserves the full diagnostic so consumers can route to telemetry,
	* `/rewind` flows, or training-data quarantine without re-walking the
	* transcript.
	*/
	repairs;
	constructor(options) {
		super(options.message, options.cause !== void 0 ? { cause: options.cause } : void 0);
		this.name = "AgentToolPairingError";
		this.provider = options.provider;
		this.providerCode = options.providerCode;
		this.repairs = options.repairs;
	}
};
/**
* Thrown (well — constructed; attach via the `tool:gate` block signal) when the
* union of `allowed-tools` across active skills does not permit a tool call.
*
* Produced by the allowed-tools middleware registered on `tool:gate` /
* `mcp:tool:gate`. The gate's `block = true` + `reason` carry the same message
* so consumers that don't look at this typed error still get a useful string.
*/
var AgentToolNotAllowedError = class extends Error {
	code = "tool_not_allowed";
	/** Canonical tool name the agent tried to call. */
	toolName;
	/** Aliased / wire name the LLM saw. */
	displayName;
	/** Flattened union of `allowedTools` patterns across active skills. */
	allowedUnion;
	/** Names of the skills currently active when the block fired. */
	activeSkills;
	constructor(options) {
		const sample = options.activeSkills[0];
		const hint = sample !== void 0 ? ` To use this tool, call \`skills_use\` with \`mode: "deactivate"\` and the active skill name (e.g. "${sample}") to lift its restriction — or ask the user to switch agent profile.` : "";
		const msg = `Tool "${options.displayName}" is not in the allowed-tools union of the active skill(s) [${options.activeSkills.join(", ")}]. Union: [${options.allowedUnion.join(" ")}].${hint}`;
		super(msg, options.cause !== void 0 ? { cause: options.cause } : void 0);
		this.name = "AgentToolNotAllowedError";
		this.toolName = options.toolName;
		this.displayName = options.displayName;
		this.allowedUnion = options.allowedUnion;
		this.activeSkills = options.activeSkills;
	}
};
/**
* Regex patterns matching common "context window exceeded" messages across providers.
*
* Use {@link matchesContextExceeded} to test a free-form error message against them.
* Provider authors can also compose these into their own `classifyError` fallbacks.
*/
const CONTEXT_EXCEEDED_MESSAGE_PATTERNS = [
	/context[_\s]length[_\s]exceeded/i,
	/maximum context length/i,
	/prompt is too long/i,
	/context window/i
];
/**
* Regex patterns matching provider-side tool-call / tool-result adjacency
* rejections. The local pre-send repair pass should prevent these, so a
* provider still returning one is a typed `tool_pairing_corruption` signal.
*/
const TOOL_PAIRING_ERROR_PATTERNS = [
	/tool_use[^a-z0-9]+ids?[^a-z0-9]+were[^a-z0-9]+found[^a-z0-9]+without[^a-z0-9]+tool_result/i,
	/tool_result[^a-z0-9]+must[^a-z0-9]+be[^a-z0-9]+preceded[^a-z0-9]+by[^a-z0-9]+a[^a-z0-9]+tool_call/i,
	/unexpected[^a-z0-9]+tool_result[^a-z0-9]+block/i,
	/tool_use[^a-z0-9]+block.*requires.*tool_result/i,
	/tool_calls?[^a-z0-9]+must[^a-z0-9]+be[^a-z0-9]+followed[^a-z0-9]+by[^a-z0-9]+tool/i,
	/tool_call_id[^a-z0-9]+(?:missing|mismatch|invalid)/i,
	/tool_call_id[^a-z0-9]+not[^a-z0-9]+found/i
];
/**
* Return true when `message` matches any of the known "context window exceeded"
* phrasings. Safe for `''` / non-strings (returns false).
*/
function matchesContextExceeded(message) {
	if (typeof message !== "string" || message.length === 0) return false;
	return CONTEXT_EXCEEDED_MESSAGE_PATTERNS.some((re) => re.test(message));
}
/**
* Return true when `message` matches a known tool-call / tool-result pairing
* rejection. Safe for `''` / non-strings (returns false).
*/
function matchesToolPairingError(message) {
	if (typeof message !== "string" || message.length === 0) return false;
	return TOOL_PAIRING_ERROR_PATTERNS.some((re) => re.test(message));
}
/**
* Shared entry guard for provider `classifyError` paths. Returns:
*   - `'not-object'` when `err` is null/undefined or not an object — the caller
*     should `return null` (nothing to classify).
*   - `'aborted'` when `err.name === 'AbortError'` — the caller should return
*     `{ kind: 'aborted' }`.
*   - `null` when `err` is a classifiable object that is not an abort.
*
* Collapses the byte-identical `if (!err || typeof err !== 'object') return null`
* + `if (err.name === 'AbortError') return { kind: 'aborted' }` prelude every
* provider repeated; per-provider classification past this point differs.
*/
function classifyErrorPrelude(err) {
	if (!err || typeof err !== "object") return "not-object";
	if (err.name === "AbortError") return "aborted";
	return null;
}
/**
* HTTP status retry rule shared by provider `classifyError` paths: `429` (rate
* limit) and `5xx` except `501 Not Implemented` are safe to retry with backoff;
* every other 4xx (bad request, auth, not found) is terminal.
*
* Note: `compact/compact.ts` deliberately uses a plain `>=500 && <600` test for
* a different decision and is intentionally not routed through this.
*/
function isRetryableHttpStatus(status) {
	if (status === 429) return true;
	if (status >= 500 && status !== 501) return true;
	return false;
}
/**
* Extract a printable message from an unknown thrown value.
*
* Standardizes the `err instanceof Error ? err.message : String(err)` idiom
* that every `catch (err)` block was reaching for.
*/
function errorMessage(err) {
	if (err instanceof Error) return err.message;
	return String(err);
}
/**
* Convert a `ClassifiedError` + underlying cause into the matching typed error instance.
*/
function toTypedError(classification, provider, cause) {
	const message = classification.message ?? errorMessage(cause);
	if (classification.kind === "context_exceeded") return new AgentContextExceededError(message, {
		provider,
		providerCode: classification.providerCode,
		cause
	});
	if (classification.kind === "aborted") return new AgentAbortedError(message, { cause });
	if (classification.kind === "tool_pairing_corruption") return new AgentToolPairingError({
		message,
		provider,
		providerCode: classification.providerCode,
		repairs: [],
		cause
	});
	return new AgentProviderError(message, {
		provider,
		providerCode: classification.providerCode,
		retryable: classification.retryable,
		cause
	});
}
//#endregion
export { AgentToolNotAllowedError as a, classifyErrorPrelude as c, matchesContextExceeded as d, matchesToolPairingError as f, AgentProviderError as i, errorMessage as l, AgentBudgetExceededError as n, AgentToolPairingError as o, toTypedError as p, AgentContextExceededError as r, CONTEXT_EXCEEDED_MESSAGE_PATTERNS as s, AgentAbortedError as t, isRetryableHttpStatus as u };

//# sourceMappingURL=errors-DkR6GPJw.js.map