agent-afk 5.87.0 → 5.87.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  var WS=Object.defineProperty;var we=(t,e)=>()=>(t&&(e=t(t=0)),e);var $d=(t,e)=>{for(var n in e)WS(t,n,{get:e[n],enumerable:!0})};function ho(t){return go.find(e=>e.name===t)}function Ea(t){return process.env[t]!==void 0}var go,b,P=we(()=>{"use strict";go=[{name:"AFK_COMPACT_KEEP_LAST_TURNS",description:"Number of recent turns the compactor keeps verbatim during /compact. Default tuned in compact-handler.ts.",type:"number",required:!1,example:"6",category:"model"},{name:"AFK_COMPACT_MODEL",description:"Override the model used by the /compact summarizer. Falls back to a cheap default (haiku-class).",type:"string",required:!1,example:"claude-haiku-4-5",category:"model"},{name:"AFK_COMPACT_SHRINK_FRACTION",description:"Context-fullness fraction (0\u20131, exclusive) at/above which /compact and auto-compaction relax the keep-window so a short-but-full session (few turns, huge tool exchanges) can still be summarized instead of no-oping on turn count. Default 0.7 (see shared/compaction.ts DEFAULT_COMPACT_SHRINK_THRESHOLD).",type:"number",required:!1,example:"0.8",category:"model"},{name:"AFK_DEFAULT_SUBAGENT_MODEL",description:"Override the default model used when a subagent is dispatched without an explicit model.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_DIAGNOSE_BASELINE",description:"Kill switch for /diagnose reproducer baseline execution. When set to '0', the /diagnose skill skips executing the detected reproducer command for a ground-truth baseline; default enabled (runs). Set to '0' to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_DISABLE_PROMPT_CACHE",description:"Disable Anthropic prompt caching when set to 1/true/yes/on. Unset = caching enabled.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_DISABLE_BASH_INTERPRETER_GUARD",description:"Skip ONLY the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) when set to 1, leaving the rest of path-approval intact. Applies on interactive surfaces (REPL/Telegram), where the denylist is active but your workflow legitimately runs interpreter one-liners. The restricted-root substring check is unaffected. Default: denylist active on interactive surfaces; headless already fails open (opt in with AFK_FORCE_BASH_INTERPRETER_GUARD=1). To disable all of path-approval + bash restriction instead, use AFK_DISABLE_PATH_APPROVAL=1.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_DISABLE_PATH_APPROVAL",description:"Skip the path-approval + bash-restriction hooks entirely when set to 1. Use for headless flows that need wide-open file access (CI scripts, batch jobs). Default: hooks enabled. Note: on headless surfaces (afk chat, daemon) no grant manager is wired, so the interpreter denylist (python -c, node -e, sh -c, ...) fails OPEN by default \u2014 opt headless flows into it with AFK_FORCE_BASH_INTERPRETER_GUARD=1, or set this var to 1 to disable all of path-approval.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_FORCE_BASH_INTERPRETER_GUARD",description:"Apply the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) even on headless surfaces (afk chat, daemon) where no grant manager is wired. By default the denylist fires only on interactive surfaces (REPL/Telegram), failing open on headless so legitimate automation is not hard-blocked with no recourse. Set to 1 to opt headless flows back into the guard. Overridden by AFK_DISABLE_BASH_INTERPRETER_GUARD=1. Default: off (headless fails open).",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_EFFORT",description:"Effort hint guiding adaptive-thinking depth, forwarded as Anthropic output_config.effort (model-gated; ignored where unsupported). Accepts low | medium | high | xhigh | max.",type:"string",required:!1,example:"medium",category:"model"},{name:"AFK_MAX_BUDGET_USD",description:"Cumulative USD budget ceiling for the session. Aborts the turn when the running cost crosses this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_NESTING_DEPTH",description:"Maximum sub-agent/skill nesting depth; 0 disables nested delegation entirely (the agent, skill, AND compose tools all refuse). A top-level session is depth 0, so the default 3 permits three generations of forked descendants (depth 1 \u2192 2 \u2192 3) and refuses the agent and skill tools at depth 3. Resolved once at the root of each session and propagated down through child AgentConfig, so descendants inherit the root value rather than re-reading the environment. Raise with care: depth is a fan-out exponent (a width-N wave at depth D reaches ~N^D concurrent children), so values above 4 invite provider rate-limit (429) cascades. Accepted range 0-6; unset, empty, unparseable, negative, or out-of-range input falls back to the default. An explicit programmatic maxDepth (SubagentExecutorContext / SkillExecutorContext) still wins.",type:"number",required:!1,default:"3",example:"2",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. Falls back to provider default when unset.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Deprecated and inert: not read by the generation path. Use AFK_MAX_OUTPUT_TOKENS (or --max-output-tokens) to cap per-response output tokens; falls back to the model output ceiling when unset.",type:"number",required:!1,default:"4096",example:"8192",category:"model"},{name:"AFK_MAX_TOOL_USE_ITERATIONS",description:"Opt-in ceiling on tool-use rounds per turn for TOP-LEVEL (non-subagent) sessions, on both providers. Mirrors the maxToolUseIterations config key / max_tool_use_iterations tool param. Unset, non-numeric, or <=0 means unlimited (the default \u2014 zero behavior change): a top-level turn ends only when the model stops calling tools, the abort signal fires, the provider errors, or the dollar budget trips. A positive integer N makes top-level turns wind down gracefully after N tool rounds (one tools-stripped final round). An explicit config/CLI value wins over this env default. Does NOT affect subagent forks \u2014 they keep their own non-zero anti-hang default (SUBAGENT_DEFAULT_MAX_TOOL_USE_ITERATIONS) regardless of this var.",type:"number",required:!1,default:"0",example:"150",category:"model"},{name:"AFK_MEMORY_EVIDENCE_GATE",description:'Opt-in (set to 1) evidence gate for durable memory writes. When enabled, a codebase fact (memory_update category "convention") stored without an `evidence` citation is recalled as [unverified], and memory_search results carry a verification verdict. User preferences and agent reflections are never gated. Default off \u2014 memory behaves identically to legacy when unset.',type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_MICROCOMPACT_KEEP_LAST",description:"Number of the most-recent tool_result blocks that tool-result microcompaction keeps intact regardless of size, so the agent does not lose the tool output it is actively reasoning over. Older results are the safe ones to trim. Default 4 (see shared/compaction.ts DEFAULT_MICROCOMPACT_KEEP_LAST). Values <= 0 protect nothing.",type:"number",required:!1,default:"4",example:"3",category:"model"},{name:"AFK_MICROCOMPACT_TOOL_RESULT_BYTES",description:"Byte threshold (tool_result content length) at/above which a tool_result block becomes a microcompaction candidate. When /compact and auto-compaction would otherwise no-op on a short-but-full session, microcompaction clears large/old tool_result CONTENT in place (largest first) \u2014 replacing it with a short placeholder, never removing the block \u2014 to reclaim context deterministically (no LLM call). Blocks below this size are left intact. Default 2048 (see shared/compaction.ts DEFAULT_MICROCOMPACT_TOOL_RESULT_BYTES).",type:"number",required:!1,default:"2048",example:"4096",category:"model"},{name:"AFK_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), fixed-identity aliases (opus, sonnet, haiku, fable), or full model IDs. Migration: AFK_MODEL=sonnet now pins the fixed Sonnet identity rather than following a rebound medium tier.",type:"string",required:!1,default:"medium",example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_TTFB_TIMEOUT_MS",description:"Per-request time-to-first-token timeout (ms) for the anthropic-direct streaming loop. Bounds how long a single model call may stall BEFORE its first streamed CONTENT token (a text/thinking delta or tool_use); the connection-level message_start and keep-alive pings do NOT count. Once a content token streams, the timer is cleared and the rest of the response is governed instead by the progress-aware AFK_MODEL_STALL_TIMEOUT_MS window, so a normal slow call (below the bound) and any actively-streaming extended-thinking response are never aborted. NOTE: a request whose FIRST token takes longer than the bound \u2014 e.g. a very large opus_1m prefill \u2014 is aborted, retried once, then surfaces as an error (raise this value or set 0 for such workloads); this trims the degrading-call tail instead of a silent ~10-min hang on the SDK default. Default 180000 (180s \u2248 2\xD7 the measured p99 ttfb). Set to 0 to disable.",type:"number",required:!1,default:"180000",example:"120000",category:"model"},{name:"AFK_MODEL_STALL_TIMEOUT_MS",description:"Progress-aware POST-first-byte stall window (ms) for the anthropic-direct streaming loop. Bounds how long a stream that has ALREADY produced content may then go completely silent. Every streamed output event resets the window, so this is NOT a total-round cap: a legitimately long, actively-streaming round (large code emission, extended thinking) survives indefinitely, while a stream wedged mid-flight is aborted and surfaces as a real terminal error instead of hanging. Complements AFK_MODEL_TTFB_TIMEOUT_MS, which governs only the window BEFORE the first token; this one takes over after it. Default 1200000 (20min) \u2014 above the 18.5min maximum post-first-byte stream duration observed across 86,076 rounds in 12,381 local traces (p99 122s, p99.9 234s), so no healthy round trips it. Set to 0 to disable (issue #762).",type:"number",required:!1,default:"1200000",example:"600000",category:"model"},{name:"AFK_SUBAGENT_TIMEOUT_MS",description:"Foreground forked-subagent wall-clock budget in ms; 0 disables the cap; explicit per-fork config.timeoutMs and the 60-min background mode still win. Bounds how long a single forked child turn may run before `withTimeout` aborts its controller (cascading through the AbortGraph to descendants) and the parent receives a legible TimeoutError tool_result instead of hanging. Default 2700000 (45 min \u2248 headroom over the longest healthy review/research agent observed in production). Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to opt a whole session back into unbounded child turns. Does NOT affect the background dispatch budget (SUBAGENT_BACKGROUND_TIMEOUT_MS) or a per-fork config.timeoutMs \u2014 both take precedence.",type:"number",required:!1,default:"2700000",example:"3600000",category:"model"},{name:"AFK_SUBAGENT_IDLE_TIMEOUT_MS",description:"Forked-subagent progress-aware idle-watchdog window in ms; 0 disables the watchdog; an explicit per-fork config.idleTimeoutMs still wins. Fires when a forked child produces no observable output event for this window, aborting the same controller the wall-clock timeout targets so partial output is preserved and the run classifies as a failure. This is distinct from AFK_SUBAGENT_TIMEOUT_MS, the blunt wall-clock that bounds total turn time: the idle watchdog is the tighter first-to-fire bound and never fires while the stream is legitimately parked on a provider-communicated backoff (OAuth pause, or a rate-limit event carrying a retry-after), extending the deadline for the pause window instead. Default 480000 (8 min) clears the worst-case transient-429 backoff the watchdog is currently blind to (about 363s) with roughly 2 min of margin, while staying materially tighter than the 45-min wall-clock. Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to disable the idle watchdog for a whole session (the wall-clock still applies). v1 applies to forked sub-agent turns only, not top-level or daemon sessions.",type:"number",required:!1,default:"480000",example:"300000",category:"model"},{name:"AFK_VISION_MODELS",description:'Comma-separated override for image (vision) capability detection on the openai-compatible provider. Each token force-enables a model id by exact or substring match (e.g. "qwen2.5-vl" matches a local VL id); prefix a token with "!" to force-disable. Use to send images to a local vision-language model AFK does not recognise by name, or to blacklist a mis-detected id. Built-in detection already covers gpt-4o/4.1/5.x, o1/o3/o4-mini, Claude, and common VL families.',type:"string",required:!1,example:"qwen2.5-vl,!gpt-4o-mini",category:"model"},{name:"AFK_MODEL_LOCAL",description:'Bind the "local" capability tier (cheapest/fastest, user-configured) to a model id. Overrides afk.config.json models.local. Point at a local Ollama, LM Studio, or any OpenAI-compatible shim.',type:"string",required:!1,example:"llama3.2:3b",category:"model"},{name:"AFK_MODEL_LOCAL_API_KEY",description:'Per-slot API key for the "local" tier. Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LOCAL_BASE_URL",description:'Per-slot endpoint base URL for the "local" tier. Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:11434/v1",category:"model"},{name:"AFK_MODEL_LARGE",description:'Bind the "large" capability tier (most capable) to a model id/alias. Overrides afk.config.json models.large.',type:"string",required:!1,example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-5",category:"model"},{name:"AFK_MODEL_MEDIUM_API_KEY",description:'Per-slot API key for the "medium" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_MEDIUM_BASE_URL",description:'Per-slot endpoint base URL for the "medium" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_SMALL",description:'Bind the "small" capability tier (cheap/fast) to a model id/alias. Overrides afk.config.json models.small.',type:"string",required:!1,example:"gpt-4o-mini",category:"model"},{name:"AFK_MODEL_SMALL_API_KEY",description:'Per-slot API key for the "small" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_SMALL_BASE_URL",description:'Per-slot endpoint base URL for the "small" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_OVERLOAD_PAUSE_MS",description:"Wall-clock ceiling (ms) for the bounded pause after a mid-stream overload (529) exhausts its retry budget. Overrides the per-surface default for ALL surfaces: 0 disables the pause (fail fast). Interactive surfaces (cli/repl/telegram) default to 600000; daemon/cron default to 0 so an always-on runner never silently parks on upstream capacity.",type:"number",required:!1,example:"600000",category:"model"},{name:"AFK_PROMPT_CACHE_TTL",description:"TTL for Anthropic prompt-cache blocks. Accepts 5m or 1h.",type:"string",required:!1,default:"1h",example:"1h",category:"model"},{name:"AFK_SUGGEST_ENABLED",description:"Enable the LLM-backed ghost-text suggestion tier in the interactive REPL. Set to 1/true/yes/on to activate. Off by default.",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_GHOST",description:"Enable REPL ghost-text inline suggestions (Tier-1 history/dropdown + optional Tier-2 LLM). 1 = on (default), 0 = off. Set 0/false/off/no to disable all ghost text. Tier-2 LLM is separately gated by AFK_SUGGEST_ENABLED.",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_MODEL",description:"Override the small model used for REPL ghost-text suggestions. Falls back to AFK_COMPACT_MODEL or haiku-class for anthropic, or the session model for other providers.",type:"string",required:!1,category:"model"},{name:"AFK_TASK_BUDGET",description:"Per-task token budget ceiling. Aborts when cumulative usage would exceed it.",type:"number",required:!1,default:"100000",example:"200000",category:"model"},{name:"AFK_TEMPERATURE",description:"Numeric temperature override for model sampling. Provider default if unset.",type:"number",required:!1,example:"0.7",category:"model"},{name:"AFK_THINKING",description:"Extended-thinking mode. Accepts adaptive | disabled | enabled:<N> | enabled:max. Defaults to the model-appropriate mode when unset (adaptive on current models).",type:"string",required:!1,default:"adaptive",example:"adaptive",category:"model"},{name:"AFK_THINKING_UI",description:"Default thinking-display mode for the interactive REPL: summary | live | digest | off. Display-only \u2014 controls how extended-thinking blocks render, never whether thinking runs (cost/latency unaffected). Overridden per-launch by --thinking-ui and mutable mid-session via /thinking. Precedence: --thinking-ui flag > this env > interactive.thinkingUi config > live. Invalid values are ignored.",type:"string",required:!1,default:"live",example:"digest",category:"misc"},{name:"AFK_TIMEOUT_MS",description:"Per-turn timeout in milliseconds. Provider/SDK default if unset.",type:"number",required:!1,example:"120000",category:"model"},{name:"CLAUDE_MODEL",description:"Legacy alias for AFK_MODEL \u2014 supported for back-compat with pre-AFK_* deployments.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_SYSTEM_PROMPT",description:'Raw operator-overlay prompt. Highest-priority overlay (over afk.config.json and AFK.md). Appended on top of the framework base (prompts/system-prompt.md) under an "# Operator configuration" header \u2014 it augments, never replaces, the base.',type:"string",required:!1,example:"You are a helpful agent.",category:"model"},{name:"AFK_DUMP_PROMPT",description:"Write the resolved system prompt to a file at startup. Accepts a path or 1 for default location.",type:"string",required:!1,example:"/tmp/afk-prompt.txt",category:"debug"},{name:"ANTHROPIC_API_KEY",description:"Anthropic API key. Tier-1 credential \u2014 overrides keychain OAuth and CLAUDE_CODE_OAUTH_TOKEN.",type:"string",required:!1,category:"auth",secret:!0},{name:"CLAUDE_CODE_OAUTH_TOKEN",description:"Claude Code OAuth token. Tier-2 credential \u2014 used when ANTHROPIC_API_KEY is unset; falls back to keychain.",type:"string",required:!1,category:"auth",secret:!0},{name:"OPENAI_API_KEY",description:"OpenAI API key for the openai-compatible provider (gpt-*, o1*, o3*, o4* models).",type:"string",required:!1,category:"auth",secret:!0},{name:"CODEX_API_KEY",description:"Fallback OpenAI API key for the openai-compatible provider, read after OPENAI_API_KEY. Legacy name from the removed @openai/codex-sdk integration \u2014 prefer OPENAI_API_KEY.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_LOCAL_API_KEY",description:"Placeholder API key for local Anthropic-compatible servers (vllm-mlx, etc.). Set when AFK_LOCAL_BASE_URL is configured.",type:"string",required:!1,default:"local",example:"local",category:"auth",secret:!0},{name:"AFK_LOCAL_BASE_URL",description:"Base URL for a self-hosted Anthropic-compatible server. When set, routes traffic away from api.anthropic.com.",type:"string",required:!1,example:"http://127.0.0.1:8080",category:"model"},{name:"AFK_OPENAI_BASE_URL",description:"Base URL override for the OpenAI-compatible provider. Used for local shims (mlx_lm.server, Ollama, vLLM, LM Studio). The OpenAI SDK appends `/chat/completions` itself \u2014 a value ending in `/chat/completions` will be stripped at config-load time with a one-shot warning.",type:"string",required:!1,example:"http://127.0.0.1:8000/v1",category:"model"},{name:"AFK_OPENAI_USE_RESPONSES",description:"Opt the OpenAI-compatible provider into the OpenAI Responses API instead of Chat Completions for API-key sessions. Truthy values: 1, true, yes, on. The ChatGPT-subscription OAuth path uses Responses automatically regardless of this flag.",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_OPENAI_CHATGPT_OAUTH",description:"Opt into using ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. Off by default. READ-ONLY: AFK never refreshes these tokens \u2014 re-run `codex` when the access token expires. Routes requests over the Responses API to the private ChatGPT backend (chatgpt.com/backend-api).",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_PROVIDER",description:"Force provider selection (anthropic | anthropic-direct | openai | openai-compatible | openai-codex). Overrides the model-name heuristic. Same surface as the --provider CLI flag; CLI flag wins when both are set.",type:"string",required:!1,example:"openai-compatible",category:"model"},{name:"EXA_API_KEY",description:"Exa (exa.ai) search API key, enabling web_scrape search mode. Free tier (20k requests/month) available at https://exa.ai. When unset, search mode returns an actionable error; markdown and raw modes are unaffected.",type:"string",required:!1,category:"auth",secret:!0},{name:"TELEGRAM_BOT_TOKEN",description:"Telegram bot token from @BotFather. Required to run the Telegram bot surface.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_BOT_TOKEN",description:"Alternative env var name for the Telegram bot token, accepted by the setup wizard.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_ALLOWED_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs allowed to interact with the bot. Required when the bot is running.",type:"string",required:!1,example:"123456789,987654321",category:"telegram"},{name:"AFK_TELEGRAM_TAG_ONLY_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs where the bot answers only when addressed (a reply to the bot, an @mention of the bot, or a text_mention resolving to the bot). Slash-commands are unaffected; chats not listed behave as usual. The afk.config.json telegram.tagOnlyChats block takes precedence. Requires Telegram privacy mode OFF (BotFather /setprivacy Disable) for non-addressed group messages to reach the bot.",type:"string",required:!1,example:"-100987654321,123456789",category:"telegram"},{name:"AFK_TELEGRAM_PRIMARY_CHAT_ID",description:"Default chat ID for outbound notifications (primary-mode routing). When unset, notifications go to the first private/DM chat in AFK_TELEGRAM_ALLOWED_CHAT_IDS. The afk.config.json telegram.notify block takes precedence.",type:"string",required:!1,example:"123456789",category:"telegram"},{name:"AFK_TELEGRAM_NOTIFY_MODE",description:"Outbound notification fan-out: primary (default \u2014 one chat), broadcast (every allowed chat), or custom (afk.config.json telegram.notify.targets). The afk.config.json telegram.notify.mode takes precedence.",type:"string",required:!1,example:"broadcast",category:"telegram"},{name:"TELEGRAM_DATA_DIR",description:"Override the directory where Telegram bot state is stored. Defaults to ~/.afk/state/telegram/.",type:"string",required:!1,category:"telegram"},{name:"TELEGRAM_VERBOSE",description:"Set to a truthy value ('1'/'true'/'yes'/'on', case-insensitive) to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"true",category:"telegram"},{name:"AFK_TELEGRAM_TRACE",description:"Set to 1 to dump raw bridge traffic between the agent and the Telegram bot \u2014 debugging only.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_TELEGRAM_CWD",description:"Override the working directory used by the Telegram bot when spawning agent sessions.",type:"string",required:!1,category:"telegram"},{name:"AFK_HOME",description:"Override the AFK home directory. Default: ~/.afk/.",type:"string",required:!1,default:"~/.afk",example:"/opt/afk",category:"paths"},{name:"AFK_STATE_DIR",description:"Override the entire AFK state tier (sessions/, todos/, transcripts/, memory/, daemon/, etc.), not just one subdirectory. Must be an absolute path (not /). Default: $AFK_HOME/state/.",type:"string",required:!1,category:"paths"},{name:"AFK_FRAMEWORK_DIR",description:"Override the AFK agent-framework directory used for telemetry and briefs. Default: $AFK_HOME/agent-framework/.",type:"string",required:!1,category:"paths"},{name:"AFK_COMPANION_PRIMER",description:'Opt-in: absolute path to a single companion-primer file. When set, its content is bounded (capped, fenced as <companion-primer>) and appended to the system prompt at session start for top-level sessions (chat/REPL/telegram/daemon), as lower-authority "reflections, not facts" context. Unset (default) = no-op. Only the one named file is ever read \u2014 never a directory or repo walk.',type:"string",required:!1,example:"/Users/me/Projects/afk-companion/PRIMER.md",category:"paths"},{name:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_ON_EXIT",description:"Clean-worktree quit policy for interactive --worktree sessions: ask, keep, or remove.",type:"string",required:!1,example:"ask",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Opt-in to loading + spawning MCP servers declared in <cwd>/.mcp.json. Fail-closed: when unset (or 0), project-local servers are NOT spawned; set to a truthy value (1/true/yes/on) to load them. A project-local .mcp.json spawns arbitrary commands on session start, so it is off by default to prevent code execution when entering an untrusted repo (issue #571). Skipped servers are listed in a startup warning with the opt-in instruction.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BG_AUTO_DELIVER",description:"Auto-deliver background subagent results into the model context on the next user turn (interactive REPL). On by default. Set to 0, false, off, or no (case-insensitive) to disable, restoring the manual /bgsub:join retrieval flow.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_PLAIN_OUTPUT",description:"Force the interactive REPL to fully behave like a non-TTY surface for rendering purposes, even when stdout/stdin ARE a TTY: append-only plain-stdout output instead of the TerminalCompositor live overlay (both the persistent between-turn compositor AND the per-turn StreamRenderer overlay), AND the input surface downgrades to the simple non-TTY line reader instead of the fancy compositor-backed input box. Same code path already used for non-TTY surfaces (pipes, CI). Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM scroll regions misbehave \u2014 trades the live overlay and fancy input UX for reliability. Opt-in \u2014 default TTY behavior (live overlay + fancy input) is unchanged unless this var is set. Truthy values: 1, true (case-insensitive).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_GOBLIN_SPINNER",description:"Goblin-themed working spinner (olive frames + goblin verbs) while the agent runs tools. 1 = on (default), 0 = classic dim spinner.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_TERM_TITLE",description:'Set the terminal/tab title (OSC 2) to reflect afk state \u2014 "afk \u2014 <cwd> \xB7 running" during a turn, "afk \u2014 <cwd>" when idle, cleared on exit. 1 = on (default when stdout is a TTY), 0 = leave the title alone. TTY-only.',type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_NOTIFY",description:"Emit a desktop completion notification (OSC 9) on turn completion, for terminals that map OSC 9 to system notifications (iTerm2, kitty, WezTerm). Opt-in and off by default (intrusive). 1 = on. TTY-only.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_THEME",description:"TUI color palette for the interactive REPL and all CLI rendering: dark | light | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark. Overridden per-launch by --theme and mutable mid-session via /theme. Precedence: --theme flag > this env > config theme > auto-detect > dark. Invalid values are ignored (dark).",type:"string",required:!1,default:"dark",example:"light",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_CAPTURE_SUBAGENT_PROMPTS",description:"Opt-in: when set to 1, every prompt a parent session sends to a subagent is written as a redacted markdown file under state/witness/<label>/prompts/. Off by default because nothing prunes the witness tree and prompts may carry secrets the regex redactor cannot catch (connection strings, PEM blocks, PII).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless on every AFK surface \u2014 the CLI entrypoint reports surface `afk`, which is in the headless set \u2014 so watching the agent work in a visible window is opt-in via `AFK_BROWSER_HEADLESS=0`, not implied by running the REPL. Note headed and headless use different chromium downloads (`chromium-*` vs `chromium_headless_shell-*`).",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_ALLOWED_DOMAINS",description:"Comma-separated allowlist of URL host globs. When set, browser_open and any navigation that targets a host outside the list returns status: blocked_by_policy. Unset means no allowlist (permissive). Patterns use simple `*` glob matching against the URL host. Combines with AFK_BROWSER_BLOCKED_DOMAINS \u2014 block wins.",type:"string",required:!1,example:"github.com,*.atlassian.net",category:"browser"},{name:"AFK_BROWSER_BLOCKED_DOMAINS",description:"Comma-separated blocklist of URL host globs. Browser navigation that matches any entry returns status: blocked_by_policy regardless of the allowlist.",type:"string",required:!1,example:"*.ads.example.com",category:"browser"},{name:"AFK_BROWSER_DOM_SNAPSHOTS",description:"Phase 2 opt-in: when set to 1, every browser_act writes a gzipped DOM snapshot sidecar under ~/.afk/state/witness/<sid>/browser/dom-snapshots/. Off by default because snapshots are large; useful for post-mortem analysis of failed actions.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_BACKEND",description:"Select the browser provider backend. Phase 1 supports only `playwright`. Reserved for future `cdp` / `mcp` adapters. Unset defaults to `playwright`.",type:"string",required:!1,example:"playwright",category:"browser"},{name:"AFK_BROWSER_CONFIG",description:"Absolute path to an alternate browser config file. Overrides the default ~/.afk/config/browser.json lookup. Useful for per-project overrides in CI.",type:"string",required:!1,example:"/path/to/browser.json",category:"browser"},{name:"AFK_BROWSER_DEFAULT_PROFILE",description:"Name of the persistent session-vault profile the agent reuses for browser sessions. The context restores its login from (and saves it back to) ~/.afk/state/browser/<profile>/storageState.json, so a human runs `afk browser login --profile <name>` once and the agent reuses that authenticated session across unattended runs. Unset defaults to `default` (a fresh, empty profile \u2014 identical to pre-vault behavior). Allowed charset: [A-Za-z0-9_-], max 128 chars.",type:"string",required:!1,example:"work",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_READ_DENYLIST",description:"Colon-separated list of additional absolute paths the read_file/grep/glob/list_directory tools refuse to read, and that the bash-restriction hook refuses to let a shell command reference on interactive surfaces (REPL, Telegram) \u2014 on headless surfaces (afk chat, daemon) bash fails open regardless of this list. A leading ~/ is expanded (~user/ is not \u2014 spell those absolutely). Built-in credential entries (~/.ssh, ~/.aws, ~/.afk/config, \u2026) always apply on top and cannot be removed. One built-in exception exists: ~/.afk/config/mcp.json (the MCP registry) IS readable \u2014 paths listed here outrank that carve-out, so set this to ~/.afk/config/mcp.json if your registry holds inline secrets rather than ${VAR} placeholders.",type:"string",required:!1,example:"/Users/me/project/.env:/Users/me/secrets",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_WEB_ALLOW_PRIVATE_HOSTS",description:"Opt out of the web_scrape SSRF egress guard. When unset (default) the guard is ACTIVE: the markdown, raw, and headless-render paths refuse loopback (127/8, ::1), link-local (169.254/16 \u2014 including the 169.254.169.254 cloud instance-metadata endpoint), RFC1918 (10/8, 172.16/12, 192.168/16), carrier-grade NAT (100.64/10), IPv6 unique-local (fc00::/7), 0.0.0.0/8, and the IPv4-mapped/compatible IPv6 forms of all of those. Hostnames are resolved and the RESOLVED addresses are classified (DNS-rebinding guard), and the check is re-applied on every redirect hop. Set to 1/true to allow private-host access \u2014 needed only to scrape a local dev server. Enabling it restores a model-reachable SSRF path (issue #575).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"VISUAL",description:"Standard POSIX env var naming the user's preferred full-screen editor (with optional flags). Consulted FIRST by the /editor slash command (and its key chord) to compose a long prompt externally; takes precedence over EDITOR. No fallback editor is assumed \u2014 if neither VISUAL nor EDITOR is set, /editor prints a hint instead of guessing.",type:"string",required:!1,example:"nvim",category:"process"},{name:"EDITOR",description:"Standard POSIX env var naming the user's preferred editor (with optional flags). Consulted by the /editor slash command AFTER VISUAL, as the standard fallback. No default editor is assumed when both are unset \u2014 /editor prints a hint telling the user to set one.",type:"string",required:!1,example:"vim",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],b={get AFK_COMPACT_KEEP_LAST_TURNS(){return process.env.AFK_COMPACT_KEEP_LAST_TURNS},get AFK_COMPACT_MODEL(){return process.env.AFK_COMPACT_MODEL},get AFK_COMPACT_SHRINK_FRACTION(){return process.env.AFK_COMPACT_SHRINK_FRACTION},get AFK_COMPANION_PRIMER(){return process.env.AFK_COMPANION_PRIMER},get AFK_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_NESTING_DEPTH(){return process.env.AFK_MAX_NESTING_DEPTH},get AFK_MAX_OUTPUT_TOKENS(){return process.env.AFK_MAX_OUTPUT_TOKENS},get AFK_MAX_TOKENS(){return process.env.AFK_MAX_TOKENS},get AFK_MAX_TOOL_USE_ITERATIONS(){return process.env.AFK_MAX_TOOL_USE_ITERATIONS},get AFK_MEMORY_EVIDENCE_GATE(){return process.env.AFK_MEMORY_EVIDENCE_GATE},get AFK_MICROCOMPACT_KEEP_LAST(){return process.env.AFK_MICROCOMPACT_KEEP_LAST},get AFK_MICROCOMPACT_TOOL_RESULT_BYTES(){return process.env.AFK_MICROCOMPACT_TOOL_RESULT_BYTES},get AFK_MODEL(){return process.env.AFK_MODEL},get AFK_MODEL_TTFB_TIMEOUT_MS(){return process.env.AFK_MODEL_TTFB_TIMEOUT_MS},get AFK_MODEL_STALL_TIMEOUT_MS(){return process.env.AFK_MODEL_STALL_TIMEOUT_MS},get AFK_MODEL_LARGE(){return process.env.AFK_MODEL_LARGE},get AFK_MODEL_LARGE_API_KEY(){return process.env.AFK_MODEL_LARGE_API_KEY},get AFK_MODEL_LARGE_BASE_URL(){return process.env.AFK_MODEL_LARGE_BASE_URL},get AFK_MODEL_LOCAL(){return process.env.AFK_MODEL_LOCAL},get AFK_MODEL_LOCAL_API_KEY(){return process.env.AFK_MODEL_LOCAL_API_KEY},get AFK_MODEL_LOCAL_BASE_URL(){return process.env.AFK_MODEL_LOCAL_BASE_URL},get AFK_MODEL_MEDIUM(){return process.env.AFK_MODEL_MEDIUM},get AFK_MODEL_MEDIUM_API_KEY(){return process.env.AFK_MODEL_MEDIUM_API_KEY},get AFK_MODEL_MEDIUM_BASE_URL(){return process.env.AFK_MODEL_MEDIUM_BASE_URL},get AFK_MODEL_SMALL(){return process.env.AFK_MODEL_SMALL},get AFK_MODEL_SMALL_API_KEY(){return process.env.AFK_MODEL_SMALL_API_KEY},get AFK_MODEL_SMALL_BASE_URL(){return process.env.AFK_MODEL_SMALL_BASE_URL},get AFK_VISION_MODELS(){return process.env.AFK_VISION_MODELS},get AFK_OVERLOAD_PAUSE_MS(){return process.env.AFK_OVERLOAD_PAUSE_MS},get AFK_PROMPT_CACHE_TTL(){return process.env.AFK_PROMPT_CACHE_TTL},get AFK_SUGGEST_ENABLED(){return process.env.AFK_SUGGEST_ENABLED},get AFK_SUGGEST_GHOST(){return process.env.AFK_SUGGEST_GHOST},get AFK_SUGGEST_MODEL(){return process.env.AFK_SUGGEST_MODEL},get AFK_SUBAGENT_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_TIMEOUT_MS},get AFK_SUBAGENT_IDLE_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_IDLE_TIMEOUT_MS},get AFK_TASK_BUDGET(){return process.env.AFK_TASK_BUDGET},get AFK_TEMPERATURE(){return process.env.AFK_TEMPERATURE},get AFK_THINKING(){return process.env.AFK_THINKING},get AFK_THINKING_UI(){return process.env.AFK_THINKING_UI},get AFK_TIMEOUT_MS(){return process.env.AFK_TIMEOUT_MS},get CLAUDE_MODEL(){return process.env.CLAUDE_MODEL},get AFK_SYSTEM_PROMPT(){return process.env.AFK_SYSTEM_PROMPT},get AFK_DUMP_PROMPT(){return process.env.AFK_DUMP_PROMPT},get ANTHROPIC_API_KEY(){return process.env.ANTHROPIC_API_KEY},get CLAUDE_CODE_OAUTH_TOKEN(){return process.env.CLAUDE_CODE_OAUTH_TOKEN},get OPENAI_API_KEY(){return process.env.OPENAI_API_KEY},get CODEX_API_KEY(){return process.env.CODEX_API_KEY},get AFK_LOCAL_API_KEY(){return process.env.AFK_LOCAL_API_KEY},get AFK_LOCAL_BASE_URL(){return process.env.AFK_LOCAL_BASE_URL},get AFK_OPENAI_BASE_URL(){return process.env.AFK_OPENAI_BASE_URL},get AFK_OPENAI_USE_RESPONSES(){return process.env.AFK_OPENAI_USE_RESPONSES},get AFK_OPENAI_CHATGPT_OAUTH(){return process.env.AFK_OPENAI_CHATGPT_OAUTH},get AFK_PROVIDER(){return process.env.AFK_PROVIDER},get EXA_API_KEY(){return process.env.EXA_API_KEY},get TELEGRAM_BOT_TOKEN(){return process.env.TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_BOT_TOKEN(){return process.env.AFK_TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_ALLOWED_CHAT_IDS(){return process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS},get AFK_TELEGRAM_TAG_ONLY_CHAT_IDS(){return process.env.AFK_TELEGRAM_TAG_ONLY_CHAT_IDS},get AFK_TELEGRAM_PRIMARY_CHAT_ID(){return process.env.AFK_TELEGRAM_PRIMARY_CHAT_ID},get AFK_TELEGRAM_NOTIFY_MODE(){return process.env.AFK_TELEGRAM_NOTIFY_MODE},get TELEGRAM_DATA_DIR(){return process.env.TELEGRAM_DATA_DIR},get TELEGRAM_VERBOSE(){return process.env.TELEGRAM_VERBOSE},get AFK_TELEGRAM_TRACE(){return process.env.AFK_TELEGRAM_TRACE},get AFK_TELEGRAM_CWD(){return process.env.AFK_TELEGRAM_CWD},get AFK_HOME(){return process.env.AFK_HOME},get AFK_STATE_DIR(){return process.env.AFK_STATE_DIR},get AFK_FRAMEWORK_DIR(){return process.env.AFK_FRAMEWORK_DIR},get HOME(){return process.env.HOME},get PATH(){return process.env.PATH},get AFK_DAEMON_CWD(){return process.env.AFK_DAEMON_CWD},get AFK_DAEMON_TASK(){return process.env.AFK_DAEMON_TASK},get AFK_DAEMON_TASK_ID(){return process.env.AFK_DAEMON_TASK_ID},get AFK_DAEMON_HOST(){return process.env.AFK_DAEMON_HOST},get AFK_SESSIONSTART_COOLDOWN_MS(){return process.env.AFK_SESSIONSTART_COOLDOWN_MS},get AFK_WORKTREE_AUTONAME(){return process.env.AFK_WORKTREE_AUTONAME},get AFK_WORKTREE_BRANCH_PREFIX(){return process.env.AFK_WORKTREE_BRANCH_PREFIX},get AFK_WORKTREE_BASE(){return process.env.AFK_WORKTREE_BASE},get AFK_WORKTREE_ON_EXIT(){return process.env.AFK_WORKTREE_ON_EXIT},get AFK_WORKTREE_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BG_AUTO_DELIVER(){return process.env.AFK_BG_AUTO_DELIVER},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_PLAIN_OUTPUT(){return process.env.AFK_PLAIN_OUTPUT},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},get AFK_GOBLIN_SPINNER(){return process.env.AFK_GOBLIN_SPINNER},get AFK_TERM_TITLE(){return process.env.AFK_TERM_TITLE},get AFK_NOTIFY(){return process.env.AFK_NOTIFY},get AFK_SHOW_DIFFS(){return process.env.AFK_SHOW_DIFFS},get AFK_SKILL_STREAM_VERBOSE(){return process.env.AFK_SKILL_STREAM_VERBOSE},get FORCE_COLOR(){return process.env.FORCE_COLOR},get NO_COLOR(){return process.env.NO_COLOR},get AFK_THEME(){return process.env.AFK_THEME},get COLORFGBG(){return process.env.COLORFGBG},get AFK_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get AFK_CAPTURE_SUBAGENT_PROMPTS(){return process.env.AFK_CAPTURE_SUBAGENT_PROMPTS},get DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_BROWSER_DEFAULT_PROFILE(){return process.env.AFK_BROWSER_DEFAULT_PROFILE},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_READ_DENYLIST(){return process.env.AFK_READ_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_WEB_ALLOW_PRIVATE_HOSTS(){return process.env.AFK_WEB_ALLOW_PRIVATE_HOSTS},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get VISUAL(){return process.env.VISUAL},get EDITOR(){return process.env.EDITOR},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let e of go){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(b,e.name);n&&Object.defineProperty(b,e.name,{...n,enumerable:!1})}})()});function KS(){return b.AFK_DEBUG==="1"||b.DEBUG==="1"}function T(...t){KS()&&console.log(...t)}var Z=we(()=>{"use strict";P()});import{existsSync as Bd,mkdirSync as GS,renameSync as qS,cpSync as zS,rmSync as JS}from"fs";import{join as j,dirname as _a,basename as VS,isAbsolute as Aa}from"path";import{homedir as jd}from"os";import{fileURLToPath as YS}from"url";function oe(){let t=b.AFK_HOME;if(t!==void 0&&t!==""){if(!Aa(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return j(jd(),".afk")}function Ae(){let t=b.AFK_FRAMEWORK_DIR;if(t!==void 0&&t!==""){if(!Aa(t)||t==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${t}`);return t}return j(oe(),"agent-framework")}function yo(){return j(Ae(),"forge-telemetry.jsonl")}function Wd(){return j(Ae(),"briefs")}function Kd(){return j(Ae(),"facets")}function Un(){return j(oe(),"skills")}function Xt(){return j(oe(),"plugins")}function Gd(t=process.cwd()){return j(t,".afk")}function qd(t=process.cwd()){return j(Gd(t),"skills")}function zd(t=process.cwd()){return j(Gd(t),"plugins")}function Jd(t=process.cwd()){return j(t,".afk","plans")}function bo(){return j(Xt(),".index.json")}function Ta(){return j($n(),"schedules.json")}function Vd(){let t=YS(import.meta.url),e=_a(t);return j(e,"bundled-plugins")}function $n(){return j(oe(),"config")}function fe(){let t=b.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!Aa(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return j(oe(),"state")}function Se(){return j(fe(),"sessions")}function wo(){return j(fe(),"presence")}function So(){return j(fe(),"memory")}function vo(){return j(fe(),"session-grants.jsonl")}function Yd(){return j(oe(),"farms")}function Xd(t){return j(Yd(),t)}function ko(t){if(!XS.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function xa(t){return ko(t),j(fe(),"witness",t)}function Qd(t){return j(xa(t),"prompts")}function Eo(t){return!t||t.startsWith("in-memory:")?null:VS(_a(t))}function Zd(t="default"){return j(fe(),"daemon",`agent-afk@${t}`)}function eu(){return j(fe(),"worktree-sweep.lock")}function _o(){return j(fe(),"worktree-roots.json")}function Ra(){return j($n(),"afk.env")}function Qt(){return j($n(),"afk.config.json")}function Ao(){return j(jd(),".afk.config.json")}function QS(){return j(oe(),"sessions")}function ZS(t,e){if(t!==e&&Bd(t)&&!Bd(e))try{GS(_a(e),{recursive:!0});try{qS(t,e)}catch(n){if(n.code==="EXDEV")try{zS(t,e,{recursive:!0}),JS(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
2
2
  `)}}}catch{}}function tu(){ZS(QS(),Se())}function Ia(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>Hd)throw new Error(`Invalid browser profile: exceeds ${Hd} chars`);if(!ev.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function tv(){return j(fe(),"browser")}function nv(t){return Ia(t),j(tv(),t)}function Ca(t){return j(nv(t),"storageState.json")}function Bn(t){return typeof t=="string"&&t.length>0&&t.length<=ov&&rv.test(t)}function Hn(t){if(!Bn(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return j(Se(),t)}function To(t){return j(Hn(t),"events.jsonl")}function nu(t){return j(Hn(t),"session.key")}var XS,ev,Hd,rv,ov,L=we(()=>{"use strict";P();XS=/^[a-zA-Z0-9_-]+$/;ev=/^[A-Za-z0-9_-]+$/,Hd=128;rv=/^[A-Za-z0-9_-]+$/,ov=128});import{readFileSync as jT}from"node:fs";import{join as WT}from"path";function KT(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Jf(t,e){return KT(e).test(t)}function zT(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(GT.has(e))return!0;if(qT.has(e))return!1}return!1}function Vf(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function JT(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function Yf(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Ia(e),e}function VT(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function YT(t){try{return jT(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function XT(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=Yf(e.defaultProfile)),n}function Xf(t){let e=t?.env??b,n=t?.readFileSync??YT,r=t?.surface??e.AGENT_SURFACE,o=zT(e.AFK_BROWSER_HEADLESS,r),s=Vf(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Vf(e.AFK_BROWSER_BLOCKED_DOMAINS),a=VT(e.AFK_BROWSER_DOM_SNAPSHOTS),l=JT(e.AFK_BROWSER_BACKEND),c=Yf(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():WT($n(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(h){throw new Error(`Failed to parse browser config at ${p}: ${String(h)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=XT(d,m);return g.configPath=p,g}function vs(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(Jf(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Jf(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var GT,qT,ks=we(()=>{"use strict";P();L();GT=new Set(["daemon","subagent","telegram","afk"]),qT=new Set(["repl","interactive","cli"])});import{existsSync as QT,readFileSync as ZT}from"node:fs";import{createRequire as ex}from"node:module";import{dirname as tx,join as nx}from"node:path";function em(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<ox&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function be(t){let e=em(t);return Zf.some(n=>e.includes(n))}function sx(){try{let e=ex(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(ZT(e,"utf8"));if(typeof n!="object"||n===null)return;let r=n.bin,o=typeof r=="string"?r:typeof r=="object"&&r!==null?r.playwright:void 0;if(typeof o!="string"||o.length===0)return;let s=nx(tx(e),o);return QT(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function vr(){return Qf??=sx()??rx,Qf}function Bl(t){return t.includes("install chromium")}function Oe(t,e){let n=em(t),r=e?.latched===!0?` ${ix}`:"";if(n.includes("Executable doesn't exist")){let o="";return e?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":e?.headless===!1&&(o=" This launch was headed, which needs the full `chromium-*` build \u2014 the headless shell alone does not satisfy it."),`browser tools require the Playwright chromium binary. Install via: ${vr()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${vr()}). Or pick a different tool.${r}`}function Hl(t,e,n=!1){if(!be(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
3
3
 
4
- ${Oe(t,{headless:e,latched:n})}`,{cause:t})}var Zf,rx,ox,Qf,ix,jl=we(()=>{"use strict";Zf=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],rx="pnpm exec playwright install chromium",ox=4;ix="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Ht from"node:fs";import Es from"node:path";import{randomBytes as ax}from"node:crypto";import{chromium as lx}from"playwright";function cx(){try{return"5.87.0"}catch{}try{let t=Es.resolve(import.meta.dirname,"../../../package.json"),e=Ht.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var dx,_s,tm=we(()=>{"use strict";jl();L();Z();dx=cx(),_s=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=lx.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Hl(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){s=l,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let c=await a.content();if(s!==void 0)throw s;let d=a.url(),u=l!==null?l.status():null;return{html:c,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${dx}`}}loadStorageState(e){let n=Ca(e);try{if(!Ht.existsSync(n))return;let r=JSON.parse(Ht.readFileSync(n,"utf8"));return T("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){T("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Ca(e);if(!Ht.existsSync(r))return;let o=await n.storageState(),s=Es.join(Es.dirname(r),`.${Es.basename(r)}.${process.pid}.${ax(4).toString("hex")}.tmp`);Ht.writeFileSync(s,JSON.stringify(o),{mode:384}),Ht.chmodSync(s,384),Ht.renameSync(s,r),T("[browser/vault] saved session",{profile:e,file:r})}catch(r){T("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as ux}from"crypto";function nm(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&px.test(t.label))}function rm(t){return ux("sha256").update(t,"utf8").digest("hex").slice(0,8)}function om(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var px,As=we(()=>{"use strict";px=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as fx}from"node:crypto";function mx(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function gx(t,e,n){return`el_${fx("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function hx(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function sm(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function am(t,e){let n=t.role??"",r=t.name??"";im.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])am(s,e)}async function yx(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},lm).catch(()=>[])}async function bx(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},lm).catch(()=>[])}function wx(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Ts(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=wx(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=yx(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,y=!1;u!==null?(h=[],am(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await bx(t)).filter(W=>im.has(W.role??"")));let w=new Map;for(let A of p){let W=sm(A.name),te=w.get(W);(!te||te.bbox.w===0&&A.bbox.w>0)&&w.set(W,A)}let k=h.map(A=>({ax:A,dom:w.get(sm(A.name??""))})),S=r?k:k.filter(A=>A.dom?A.dom.bbox.w>0||A.dom.bbox.h>0:!0);S.sort((A,W)=>{let te=A.dom?.bbox.y??0,D=W.dom?.bbox.y??0;if(te!==D)return te-D;let B=A.dom?.bbox.x??0,M=W.dom?.bbox.x??0;return B-M}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=S.slice(0,n).map((A,W)=>{let te=A.ax.role??"generic",D=A.ax.name??"",B=gx(te,D,W),M=A.dom?.bbox??{x:0,y:0,w:0,h:0},C=A.dom?.type??null,K=null;A.ax.value!==void 0&&A.ax.value!==null&&(K=String(A.ax.value)),A.ax.checked!==void 0&&(K=String(A.ax.checked)),nm({role:te,kind:C})&&(K="[redacted]");let N={disabled:A.ax.disabled??!1};A.ax.checked!==void 0&&(N.checked=A.ax.checked===!0||A.ax.checked==="mixed"),A.ax.selected!==void 0&&(N.selected=A.ax.selected),A.ax.expanded!==void 0&&(N.expanded=A.ax.expanded);let z;A.dom?.testId?z=`[data-testid="${A.dom.testId}"]`:A.dom?.id&&(z=`#${A.dom.id}`);let X={id:B,role:te,label:mx(D),kind:C,value:K,state:N,bbox:M};return z!==void 0&&(X.selector=z),X}),R="idle";try{let A=await t.evaluate(()=>document.readyState);A==="loading"?R="loading":A==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let O=hx(f),v=`obs_${e.observationCounter.toString(36)}`,I=new Date().toISOString();return{observationId:v,url:m,title:g,textSummary:O,interactive:E,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:I}}var im,lm,cm=we(()=>{"use strict";As();im=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);lm="a[href], button, input, select, textarea, [role], [tabindex], label"});async function dm(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Wl(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>dm(t,s)))).filter(o=>o!==null)}async function Sx(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Kl(t,e,n){switch(e.kind){case"element_id":return vx(t,e,n);case"selector":return kx(t,e);case"semantic":return Ex(t,e)}}async function vx(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Wl(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function kx(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Wl(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function Ex(t,e){return e.role!==void 0?_x(t,e.text,e.role):Ax(t,e.text,e)}async function _x(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Wl(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Ax(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:s,count:l});let u=await Sx(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let h=p[g];if(h===void 0)continue;let y=await dm(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,k=0;for(let S=0;S<w.length;S++)k=k*31+w.charCodeAt(S)>>>0;f.push({...y,id:`el_${k.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var um=we(()=>{"use strict"});async function Gl(t,e,n,r){let o=t.url();if(o===n)return null;let s=vs(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var pm=we(()=>{"use strict";ks()});import{randomBytes as Tx}from"crypto";import{mkdir as xx,stat as Rx,writeFile as Ix}from"fs/promises";import{join as ql}from"path";import{gzip as Cx}from"zlib";import{promisify as Px}from"util";function Mx(t){return ql(xa(t),"browser")}function Ox(t){return ql(Mx(t),"screenshots")}function Dx(){return new Date().toISOString().replace(/[:.]/g,"-")}function Fx(){return Tx(3).toString("hex")}async function zl(t,e,n){if(e.length>fm)throw new Error(`writeScreenshotSidecar: buffer exceeds ${fm} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=Ox(t);await xx(r,{recursive:!0});let o=`${Dx()}-${Fx()}-${n}.png`,s=ql(r,o);await Ix(s,e);let{size:i}=await Rx(s);return{path:s,bytes:i}}var jj,fm,mm=we(()=>{"use strict";L();As();jj=Px(Cx);fm=5*1024*1024});var hm={};$d(hm,{PlaywrightProvider:()=>Jl});function gm(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var Jl,ym=we(()=>{"use strict";tm();cm();um();ks();pm();mm();Jl=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new _s(e)}async open(e){let n=vs(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await Gl(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await Ts(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Ts(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await Kl(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${gm(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){c=h}else c=g}let u=await Gl(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Ts(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Kl(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${gm(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await zl(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await zl(n,o,r);return s}catch{return null}}}});var Wt={};$d(Wt,{__resetBrowserRegistryForTests:()=>Bx,browserProviderActive:()=>Ux,closeBrowserProvider:()=>Vl,getBrowserProvider:()=>Nx,peekBrowserProvider:()=>$x});function bm(){Promise.resolve(Vl()).then(()=>{process.exit(130)})}function wm(){Promise.resolve(Vl()).then(()=>{process.exit(143)})}function Sm(){Ke=null}function Lx(){xs||(process.on("SIGINT",bm),process.on("SIGTERM",wm),process.on("exit",Sm),xs=!0)}function vm(){xs&&(process.removeListener("SIGINT",bm),process.removeListener("SIGTERM",wm),process.removeListener("exit",Sm),xs=!1)}async function Nx(t){return Ke!==null?Ke:(jt!==null||(jt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(ym(),hm)),n=Xf(t),r=new e(n);return Lx(),Ke=r,jt=null,r})()),jt)}async function Vl(){if(Ke===null)return;let t=Ke;Ke=null,jt=null,vm(),await t.shutdown()}function Ux(){return Ke!==null}function $x(){return Ke}function Bx(){Ke=null,jt=null,vm()}var Ke,jt,xs,Kt=we(()=>{"use strict";ks();Ke=null,jt=null,xs=!1});Z();P();L();Z();import{randomBytes as gv}from"node:crypto";import{mkdir as hv,writeFile as yv}from"node:fs/promises";import{join as bv}from"node:path";P();import{mkdirSync as sv,appendFileSync as iv,existsSync as av}from"fs";import{resolve as lv}from"path";import{dirname as cv}from"path";var dv=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
4
+ ${Oe(t,{headless:e,latched:n})}`,{cause:t})}var Zf,rx,ox,Qf,ix,jl=we(()=>{"use strict";Zf=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],rx="pnpm exec playwright install chromium",ox=4;ix="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Ht from"node:fs";import Es from"node:path";import{randomBytes as ax}from"node:crypto";import{chromium as lx}from"playwright";function cx(){try{return"5.87.1"}catch{}try{let t=Es.resolve(import.meta.dirname,"../../../package.json"),e=Ht.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var dx,_s,tm=we(()=>{"use strict";jl();L();Z();dx=cx(),_s=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=lx.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Hl(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){s=l,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let c=await a.content();if(s!==void 0)throw s;let d=a.url(),u=l!==null?l.status():null;return{html:c,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${dx}`}}loadStorageState(e){let n=Ca(e);try{if(!Ht.existsSync(n))return;let r=JSON.parse(Ht.readFileSync(n,"utf8"));return T("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){T("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Ca(e);if(!Ht.existsSync(r))return;let o=await n.storageState(),s=Es.join(Es.dirname(r),`.${Es.basename(r)}.${process.pid}.${ax(4).toString("hex")}.tmp`);Ht.writeFileSync(s,JSON.stringify(o),{mode:384}),Ht.chmodSync(s,384),Ht.renameSync(s,r),T("[browser/vault] saved session",{profile:e,file:r})}catch(r){T("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as ux}from"crypto";function nm(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&px.test(t.label))}function rm(t){return ux("sha256").update(t,"utf8").digest("hex").slice(0,8)}function om(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var px,As=we(()=>{"use strict";px=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as fx}from"node:crypto";function mx(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function gx(t,e,n){return`el_${fx("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function hx(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function sm(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function am(t,e){let n=t.role??"",r=t.name??"";im.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])am(s,e)}async function yx(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},lm).catch(()=>[])}async function bx(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},lm).catch(()=>[])}function wx(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Ts(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=wx(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=yx(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,y=!1;u!==null?(h=[],am(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await bx(t)).filter(W=>im.has(W.role??"")));let w=new Map;for(let A of p){let W=sm(A.name),te=w.get(W);(!te||te.bbox.w===0&&A.bbox.w>0)&&w.set(W,A)}let k=h.map(A=>({ax:A,dom:w.get(sm(A.name??""))})),S=r?k:k.filter(A=>A.dom?A.dom.bbox.w>0||A.dom.bbox.h>0:!0);S.sort((A,W)=>{let te=A.dom?.bbox.y??0,D=W.dom?.bbox.y??0;if(te!==D)return te-D;let B=A.dom?.bbox.x??0,M=W.dom?.bbox.x??0;return B-M}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=S.slice(0,n).map((A,W)=>{let te=A.ax.role??"generic",D=A.ax.name??"",B=gx(te,D,W),M=A.dom?.bbox??{x:0,y:0,w:0,h:0},C=A.dom?.type??null,K=null;A.ax.value!==void 0&&A.ax.value!==null&&(K=String(A.ax.value)),A.ax.checked!==void 0&&(K=String(A.ax.checked)),nm({role:te,kind:C})&&(K="[redacted]");let N={disabled:A.ax.disabled??!1};A.ax.checked!==void 0&&(N.checked=A.ax.checked===!0||A.ax.checked==="mixed"),A.ax.selected!==void 0&&(N.selected=A.ax.selected),A.ax.expanded!==void 0&&(N.expanded=A.ax.expanded);let z;A.dom?.testId?z=`[data-testid="${A.dom.testId}"]`:A.dom?.id&&(z=`#${A.dom.id}`);let X={id:B,role:te,label:mx(D),kind:C,value:K,state:N,bbox:M};return z!==void 0&&(X.selector=z),X}),R="idle";try{let A=await t.evaluate(()=>document.readyState);A==="loading"?R="loading":A==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let O=hx(f),v=`obs_${e.observationCounter.toString(36)}`,I=new Date().toISOString();return{observationId:v,url:m,title:g,textSummary:O,interactive:E,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:I}}var im,lm,cm=we(()=>{"use strict";As();im=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);lm="a[href], button, input, select, textarea, [role], [tabindex], label"});async function dm(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Wl(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>dm(t,s)))).filter(o=>o!==null)}async function Sx(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Kl(t,e,n){switch(e.kind){case"element_id":return vx(t,e,n);case"selector":return kx(t,e);case"semantic":return Ex(t,e)}}async function vx(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Wl(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function kx(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Wl(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function Ex(t,e){return e.role!==void 0?_x(t,e.text,e.role):Ax(t,e.text,e)}async function _x(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Wl(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Ax(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:s,count:l});let u=await Sx(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let h=p[g];if(h===void 0)continue;let y=await dm(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,k=0;for(let S=0;S<w.length;S++)k=k*31+w.charCodeAt(S)>>>0;f.push({...y,id:`el_${k.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var um=we(()=>{"use strict"});async function Gl(t,e,n,r){let o=t.url();if(o===n)return null;let s=vs(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var pm=we(()=>{"use strict";ks()});import{randomBytes as Tx}from"crypto";import{mkdir as xx,stat as Rx,writeFile as Ix}from"fs/promises";import{join as ql}from"path";import{gzip as Cx}from"zlib";import{promisify as Px}from"util";function Mx(t){return ql(xa(t),"browser")}function Ox(t){return ql(Mx(t),"screenshots")}function Dx(){return new Date().toISOString().replace(/[:.]/g,"-")}function Fx(){return Tx(3).toString("hex")}async function zl(t,e,n){if(e.length>fm)throw new Error(`writeScreenshotSidecar: buffer exceeds ${fm} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=Ox(t);await xx(r,{recursive:!0});let o=`${Dx()}-${Fx()}-${n}.png`,s=ql(r,o);await Ix(s,e);let{size:i}=await Rx(s);return{path:s,bytes:i}}var jj,fm,mm=we(()=>{"use strict";L();As();jj=Px(Cx);fm=5*1024*1024});var hm={};$d(hm,{PlaywrightProvider:()=>Jl});function gm(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var Jl,ym=we(()=>{"use strict";tm();cm();um();ks();pm();mm();Jl=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new _s(e)}async open(e){let n=vs(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await Gl(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await Ts(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Ts(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await Kl(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${gm(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){c=h}else c=g}let u=await Gl(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Ts(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Kl(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${gm(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await zl(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await zl(n,o,r);return s}catch{return null}}}});var Wt={};$d(Wt,{__resetBrowserRegistryForTests:()=>Bx,browserProviderActive:()=>Ux,closeBrowserProvider:()=>Vl,getBrowserProvider:()=>Nx,peekBrowserProvider:()=>$x});function bm(){Promise.resolve(Vl()).then(()=>{process.exit(130)})}function wm(){Promise.resolve(Vl()).then(()=>{process.exit(143)})}function Sm(){Ke=null}function Lx(){xs||(process.on("SIGINT",bm),process.on("SIGTERM",wm),process.on("exit",Sm),xs=!0)}function vm(){xs&&(process.removeListener("SIGINT",bm),process.removeListener("SIGTERM",wm),process.removeListener("exit",Sm),xs=!1)}async function Nx(t){return Ke!==null?Ke:(jt!==null||(jt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(ym(),hm)),n=Xf(t),r=new e(n);return Lx(),Ke=r,jt=null,r})()),jt)}async function Vl(){if(Ke===null)return;let t=Ke;Ke=null,jt=null,vm(),await t.shutdown()}function Ux(){return Ke!==null}function $x(){return Ke}function Bx(){Ke=null,jt=null,vm()}var Ke,jt,xs,Kt=we(()=>{"use strict";ks();Ke=null,jt=null,xs=!1});Z();P();L();Z();import{randomBytes as gv}from"node:crypto";import{mkdir as hv,writeFile as yv}from"node:fs/promises";import{join as bv}from"node:path";P();import{mkdirSync as sv,appendFileSync as iv,existsSync as av}from"fs";import{resolve as lv}from"path";import{dirname as cv}from"path";var dv=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
5
5
  `,uv=/key|token|secret|password|credential|auth/i,pv=[[/sk-ant-[A-Za-z0-9_\-]{8,200}/g,t=>`<REDACTED sk-ant length=${t[0].length}>`],[/sk-(?!ant-)[A-Za-z0-9_\-]{20,200}/g,t=>`<REDACTED sk- length=${t[0].length}>`],[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,t=>`<REDACTED Bearer length=${t[0].length}>`],[/AKIA[A-Z0-9]{16}/g,t=>`<REDACTED AKIA length=${t[0].length}>`],[/xox[baprs]-[A-Za-z0-9\-]{10,200}/g,t=>`<REDACTED xox token length=${t[0].length}>`],[/\d{8,12}:[A-Za-z0-9_\-]{35}/g,t=>`<REDACTED Telegram token length=${t[0].length}>`],[/([A-Za-z_]{3,}(?:[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]|[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll])[A-Za-z_]*)=([^\s]{16,})/g,t=>`${t[1]}=<REDACTED length=${t[2].length}>`],[/([A-Z_]{3,}(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=([^\s]{16,})/g,t=>`${t[1]}=<REDACTED length=${t[2].length}>`]];function Ma(t){let e=t;for(let[n,r]of pv)e=e.replace(n,(...o)=>{let s=o.slice(0,o.length-2);return r(s)});return e}function Pa(t){return typeof t=="string"?Ma(t):Array.isArray(t)?t.map(Pa):t}function fv(t){if(t===null||typeof t!="object")return t;let e=t,n={...e},r=e.env;if(r&&typeof r=="object"){let o={};for(let[s,i]of Object.entries(r))uv.test(s)&&typeof i=="string"?o[s]=`<REDACTED length=${i.length}>`:o[s]=i;n.env=o}return"system"in e&&(n.system=Pa(e.system)),"systemPrompt"in e&&(n.systemPrompt=Pa(e.systemPrompt)),n}function mv(t){if(t==null)return{kind:"undefined",note:"SDK uses minimal prompt; claude_code preset NOT loaded"};if(typeof t=="string")return{kind:"custom-string",note:"SDK uses this string as full system prompt; claude_code preset NOT loaded"};if(Array.isArray(t))return{kind:"custom-string-array",note:"SDK uses array as full system prompt with cache boundaries; claude_code preset NOT loaded"};if(typeof t=="object"){let e=t;if(e.type==="preset"&&e.preset==="claude_code"){let n={kind:"preset-claude-code",note:"claude_code preset loaded"};return typeof e.append=="string"&&(n.append={length:e.append.length}),e.excludeDynamicSections===!0&&(n.excludeDynamicSections=!0),n}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}function ru(t){let e=b.AFK_DUMP_PROMPT;if(!e||e===""||e==="0"||e.toLowerCase()==="false")return;process.stderr.write(`[--dump-prompt] WARNING: dump may contain secrets from system prompt or messages. Inspect before sharing.
6
6
  `);let n=t.options,r=typeof n=="object"&&n!==null?n.systemPrompt:void 0,o=mv(r),s={timestamp:new Date().toISOString(),prompt:t.prompt,options:fv(t.options),provenance:t.provenance,resolution:o};if(e==="1"||e.toLowerCase()==="true"||e.toLowerCase()==="stderr"){let l=JSON.stringify(s,null,2)+`
7
7
  `;process.stderr.write(l);return}let i=lv(e),a=cv(i);try{sv(a,{recursive:!0});let c=(!av(i)?dv:"")+JSON.stringify(s)+`
@@ -13,7 +13,7 @@ ${Oe(t,{headless:e,latched:n})}`,{cause:t})}var Zf,rx,ox,Qf,ix,jl=we(()=>{"use s
13
13
  `);function ja(t){return t!=="autonomous"?null:{type:"text",text:Fo}}function Wa(t,e="all"){switch(e){case"self":return{self:t.getSelf()};case"tools":return{tools:t.getTools()};case"subagents":return{subagents:t.getSubagents()};case"workspace":return{workspace:t.getWorkspace()};default:return{self:t.getSelf(),tools:t.getTools(),subagents:t.getSubagents(),workspace:t.getWorkspace()}}}function Ka(t){return t==="self"||t==="tools"||t==="subagents"||t==="workspace"||t==="all"?t:"all"}function qn(t){let n=[`- Working directory: ${t.cwd.replace(/[\r\n]/g," ")}`];n.push(`- Date: ${Lo(t.now??new Date,t.timeZone)}`);let r=typeof t.sessionId=="string"&&t.sessionId.length>0?t.sessionId.slice(0,8):null,o=t.surface&&t.surface!=="unknown"?t.surface:null,s=typeof t.depth=="number"?typeof t.maxDepth=="number"?`depth ${t.depth}/${t.maxDepth}`:`depth ${t.depth}`:null,i=[o,s].filter(a=>typeof a=="string");if(r!==null||i.length>0){let a=["- Session:"];r!==null&&a.push(r),i.length>0&&a.push(`(${i.join(", ")})`),n.push(a.join(" "))}if(t.workspace!==void 0&&t.workspace!==null){let a=t.workspace;if(a.branch!==null||a.headSha!==null){let l=a.branch??"(detached)",c=a.headSha!==null?` @ ${a.headSha}`:"",d;a.dirty===null?d="":a.dirty?d=` (${a.dirtyCount!==null?a.dirtyCount:"?"} dirty)`:d=" (clean)",n.push(`- Workspace: ${l}${c}${d}`)}}return`# Environment
14
14
  ${n.join(`
15
15
  `)}`}function Lo(t,e){try{let n=e??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",r=new Intl.DateTimeFormat("en-CA",{timeZone:n,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(t),o=i=>r.find(a=>a.type===i)?.value??"";return`${new Intl.DateTimeFormat("en-US",{timeZone:n,weekday:"long"}).format(t)}, ${o("year")}-${o("month")}-${o("day")} (${n})`}catch{return t.toISOString().slice(0,10)}}import{spawnSync as Ov}from"child_process";var Dv={branch:null,headSha:null,dirty:null,dirtyCount:null,remoteUrl:null};function No(t,e,n=!1){try{let r=Ov("git",e,{cwd:t,encoding:"utf8",maxBuffer:4096,shell:!1});if(r.status!==0||r.signal!==null||r.error!==void 0)return null;let o=typeof r.stdout=="string"?r.stdout.trim():null;return o===null?null:o.length>0||n?o:null}catch{return null}}function Ga(t){let e=No(t,["rev-parse","--short","HEAD"]);if(e===null)return{...Dv};let n=No(t,["symbolic-ref","--short","HEAD"]),r=No(t,["status","--porcelain"],!0),o=!1,s=0;if(r!==null){let a=r.split(`
16
- `).filter(l=>l.trim().length>0);o=a.length>0,s=a.length}else o=null,s=null;let i=No(t,["remote","get-url","origin"]);return{branch:n,headSha:e,dirty:o,dirtyCount:s,remoteUrl:i}}function zn(t){return{getSelf(){return{sessionId:t.sessionId??null,surface:Lv(t.surface),parentSessionId:t.parentSessionId??null,depth:t.depth??null,maxDepth:t.maxDepth??null,phaseRole:t.phaseRole??null,cwd:t.cwd,model:{provider:t.providerName,name:t.modelName},permissionMode:Fv(t.permissionMode)}},getTools(){return{enabled:t.getEnabledToolNames(),mcpServers:Nv(t.getMcpTools())}},getSubagents(){return t.getSubagents()},getWorkspace(){return Ga(t.cwd)}}}function Fv(t){switch(t){case"bypassPermissions":case"acceptEdits":case"dontAsk":case"auto":return"elevated";default:return"default"}}function Lv(t){switch(t){case"cli":case"repl":case"daemon":case"telegram":case"subagent":return t;default:return"unknown"}}function Nv(t){let e=new Map;for(let n of t){if(!n.name.startsWith("mcp__"))continue;let r=n.name.split("__");if(r.length<3)continue;let o=r[1];typeof o!="string"||o.length===0||e.set(o,(e.get(o)??0)+1)}return[...e.entries()].map(([n,r])=>({name:n,toolCount:r})).sort((n,r)=>n.name.localeCompare(r.name))}var Ne={name:"get_runtime_state",category:"other",concurrencySafe:!0,description:"Inspect what the runtime knows about this session: identity (sessionId, surface, depth, parent), tool affordances (currently-enabled tool names and MCP server summary), delegation state (active subagent handles, background jobs), and git workspace state (branch, HEAD SHA, dirty count, remote URL). Returns a compact JSON snapshot.\n\nUse when uncertain about: your current nesting depth, whether a tool you want is actually available right now, what MCP servers are wired, whether earlier subagents you dispatched are still running, or what git branch / commit the session started on.\n\nViews:\n- `self` \u2014 identity + model + permissions + cwd only\n- `tools` \u2014 enabled tool names + MCP server summary only\n- `subagents` \u2014 active subagent handles + background jobs only\n- `workspace` \u2014 git state (branch, headSha, dirty, dirtyCount, remoteUrl)\n- `all` \u2014 union of the four above (default)\n\nThis is a read-only, in-memory inspection. It does not probe the file system or network. Fields the runtime does not know (e.g. depth for a top-level session) come back as `null` rather than synthesised defaults.",input_schema:{type:"object",properties:{view:{type:"string",enum:["self","tools","subagents","workspace","all"],description:'Which slice of state to return. Defaults to "all". Use a narrower view when only one slice is needed to keep the response compact.'}},required:[]}},Re=[Ne.name];function on(t){return async(e,n)=>{let r=e&&typeof e=="object"?Ka(e.view):"all",o=Wa(t,r);return{content:JSON.stringify(o)}}}function Jn(t,e){let n=on(e),r=t,o=Array.isArray(r.toolDefs)?r.toolDefs:null,s={async execute(i){return i.name==="get_runtime_state"?n(i.input,i.signal):t.execute(i)}};if(o!==null){let i=o.some(a=>a.name==="get_runtime_state");s.toolDefs=i?o:[...o,Ne]}return s}L();import{mkdir as IL,writeFile as Tu,unlink as CL,readdir as Uv,readFile as za}from"fs/promises";import{unlinkSync as $v,existsSync as Bv,mkdirSync as Hv,writeFileSync as jv}from"fs";import{join as xu}from"path";function Au(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function qa(t){return typeof t!="number"||!Number.isInteger(t)||t<=0?"unknown":Au(t)?"alive":"dead"}var Ru=1;function $o(t){return xu(wo(),`${t}.json`)}var Uo=new Map;function Iu(t,e){let r=(Uo.get(t)??Promise.resolve()).then(e,e);return Uo.set(t,r),r.catch(()=>{}).then(()=>{Uo.get(t)===r&&Uo.delete(t)}),r}function Wv(t){let e={schemaVersion:Ru,heartbeatAt:new Date().toISOString(),...t};return JSON.stringify(e,null,2)}function Ja(t){try{Hv(wo(),{recursive:!0,mode:448}),jv($o(t.sessionId),Wv(t),{encoding:"utf8",mode:384})}catch{}}async function Va(t,e){return Iu(t,async()=>{try{let n=$o(t),r=await za(n,"utf8"),o=JSON.parse(r);e?o.blockedSince=new Date().toISOString():delete o.blockedSince,await Tu(n,JSON.stringify(o,null,2),{encoding:"utf8",mode:384})}catch{}})}async function Cu(t,e){return Iu(t,async()=>{try{let n=$o(t),r=await za(n,"utf8"),o=JSON.parse(r);o.cwd=e,await Tu(n,JSON.stringify(o,null,2),{encoding:"utf8",mode:384})}catch{}})}function Vn(t){try{let e=$o(t);Bv(e)&&$v(e)}catch{}}function Kv(t,e){if(typeof t!="string")return null;let n=Date.parse(t);return Number.isNaN(n)?null:e-n}async function Bo(){let t=wo(),e;try{e=await Uv(t)}catch{return[]}let n=Date.now(),r=[];for(let o of e){if(!o.endsWith(".json"))continue;let s=xu(t,o);try{let i=await za(s,"utf8"),a=JSON.parse(i);if(a!==null&&typeof a=="object"&&"sessionId"in a&&typeof a.sessionId=="string"){let l=a,c=a;r.push({...l,path:s,liveness:qa(c.pid),heartbeatAgeMs:Kv(c.heartbeatAt,n)})}}catch{}}return r}async function Yn(t={}){let e=await Bo(),{maxHeartbeatAgeMs:n}=t;return e.filter(r=>!(r.liveness==="dead"||n!==void 0&&r.heartbeatAgeMs!==null&&r.heartbeatAgeMs>n))}var Pu=`# Environment
16
+ `).filter(l=>l.trim().length>0);o=a.length>0,s=a.length}else o=null,s=null;let i=No(t,["remote","get-url","origin"]);return{branch:n,headSha:e,dirty:o,dirtyCount:s,remoteUrl:i}}function zn(t){return{getSelf(){return{sessionId:t.sessionId??null,surface:Lv(t.surface),parentSessionId:t.parentSessionId??null,depth:t.depth??null,maxDepth:t.maxDepth??null,phaseRole:t.phaseRole??null,cwd:t.getCwd(),model:{provider:t.providerName,name:t.modelName},permissionMode:Fv(t.permissionMode)}},getTools(){return{enabled:t.getEnabledToolNames(),mcpServers:Nv(t.getMcpTools())}},getSubagents(){return t.getSubagents()},getWorkspace(){return Ga(t.getCwd())}}}function Fv(t){switch(t){case"bypassPermissions":case"acceptEdits":case"dontAsk":case"auto":return"elevated";default:return"default"}}function Lv(t){switch(t){case"cli":case"repl":case"daemon":case"telegram":case"subagent":return t;default:return"unknown"}}function Nv(t){let e=new Map;for(let n of t){if(!n.name.startsWith("mcp__"))continue;let r=n.name.split("__");if(r.length<3)continue;let o=r[1];typeof o!="string"||o.length===0||e.set(o,(e.get(o)??0)+1)}return[...e.entries()].map(([n,r])=>({name:n,toolCount:r})).sort((n,r)=>n.name.localeCompare(r.name))}var Ne={name:"get_runtime_state",category:"other",concurrencySafe:!0,description:"Inspect what the runtime knows about this session: identity (sessionId, surface, depth, parent), tool affordances (currently-enabled tool names and MCP server summary), delegation state (active subagent handles, background jobs), and git workspace state (branch, HEAD SHA, dirty count, remote URL). Returns a compact JSON snapshot.\n\nUse when uncertain about: your current nesting depth, whether a tool you want is actually available right now, what MCP servers are wired, whether earlier subagents you dispatched are still running, or what git branch / commit the session started on.\n\nViews:\n- `self` \u2014 identity + model + permissions + cwd only\n- `tools` \u2014 enabled tool names + MCP server summary only\n- `subagents` \u2014 active subagent handles + background jobs only\n- `workspace` \u2014 git state (branch, headSha, dirty, dirtyCount, remoteUrl)\n- `all` \u2014 union of the four above (default)\n\nThis is a read-only, in-memory inspection. It does not probe the file system or network. Fields the runtime does not know (e.g. depth for a top-level session) come back as `null` rather than synthesised defaults.",input_schema:{type:"object",properties:{view:{type:"string",enum:["self","tools","subagents","workspace","all"],description:'Which slice of state to return. Defaults to "all". Use a narrower view when only one slice is needed to keep the response compact.'}},required:[]}},Re=[Ne.name];function on(t){return async(e,n)=>{let r=e&&typeof e=="object"?Ka(e.view):"all",o=Wa(t,r);return{content:JSON.stringify(o)}}}function Jn(t,e){let n=on(e),r=t,o=Array.isArray(r.toolDefs)?r.toolDefs:null,s={async execute(i){return i.name==="get_runtime_state"?n(i.input,i.signal):t.execute(i)}};if(o!==null){let i=o.some(a=>a.name==="get_runtime_state");s.toolDefs=i?o:[...o,Ne]}return s}L();import{mkdir as IL,writeFile as Tu,unlink as CL,readdir as Uv,readFile as za}from"fs/promises";import{unlinkSync as $v,existsSync as Bv,mkdirSync as Hv,writeFileSync as jv}from"fs";import{join as xu}from"path";function Au(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function qa(t){return typeof t!="number"||!Number.isInteger(t)||t<=0?"unknown":Au(t)?"alive":"dead"}var Ru=1;function $o(t){return xu(wo(),`${t}.json`)}var Uo=new Map;function Iu(t,e){let r=(Uo.get(t)??Promise.resolve()).then(e,e);return Uo.set(t,r),r.catch(()=>{}).then(()=>{Uo.get(t)===r&&Uo.delete(t)}),r}function Wv(t){let e={schemaVersion:Ru,heartbeatAt:new Date().toISOString(),...t};return JSON.stringify(e,null,2)}function Ja(t){try{Hv(wo(),{recursive:!0,mode:448}),jv($o(t.sessionId),Wv(t),{encoding:"utf8",mode:384})}catch{}}async function Va(t,e){return Iu(t,async()=>{try{let n=$o(t),r=await za(n,"utf8"),o=JSON.parse(r);e?o.blockedSince=new Date().toISOString():delete o.blockedSince,await Tu(n,JSON.stringify(o,null,2),{encoding:"utf8",mode:384})}catch{}})}async function Cu(t,e){return Iu(t,async()=>{try{let n=$o(t),r=await za(n,"utf8"),o=JSON.parse(r);o.cwd=e,await Tu(n,JSON.stringify(o,null,2),{encoding:"utf8",mode:384})}catch{}})}function Vn(t){try{let e=$o(t);Bv(e)&&$v(e)}catch{}}function Kv(t,e){if(typeof t!="string")return null;let n=Date.parse(t);return Number.isNaN(n)?null:e-n}async function Bo(){let t=wo(),e;try{e=await Uv(t)}catch{return[]}let n=Date.now(),r=[];for(let o of e){if(!o.endsWith(".json"))continue;let s=xu(t,o);try{let i=await za(s,"utf8"),a=JSON.parse(i);if(a!==null&&typeof a=="object"&&"sessionId"in a&&typeof a.sessionId=="string"){let l=a,c=a;r.push({...l,path:s,liveness:qa(c.pid),heartbeatAgeMs:Kv(c.heartbeatAt,n)})}}catch{}}return r}async function Yn(t={}){let e=await Bo(),{maxHeartbeatAgeMs:n}=t;return e.filter(r=>!(r.liveness==="dead"||n!==void 0&&r.heartbeatAgeMs!==null&&r.heartbeatAgeMs>n))}var Pu=`# Environment
17
17
  - Working directory: `,Ya="- Date: ";function Xn(t,e,n){let r=t.lastIndexOf(Pu);if(r===-1)return t;let o=t.indexOf(`
18
18
  `,r+Pu.length);if(o===-1)return t;let s=o+1;if(!t.startsWith(Ya,s))return t;let i=t.indexOf(`
19
19
  `,s),a=i===-1?t.length:i,l=t.slice(s+Ya.length,a),c=Lo(e??new Date,n);return l===c?t:t.slice(0,s+Ya.length)+c+t.slice(a)}function Qn(t,e=()=>{}){let n=new Set;if(!t)return n;for(let r of t.split(",")){let o=r.trim();if(o){if(!/^-?\d+$/.test(o)){e("[allowlist] Ignoring non-numeric chat ID:",o);continue}n.add(Number(o))}}return n}function Mu(t,e){return e.has(t)}function Xa(t,e=()=>{}){return async(n,r)=>{let o=n.chat?.id;if(o===void 0||!t.has(o)){e("[allowlist] Rejecting update from chat:",o??"<unknown>");return}await r()}}import{config as cN,parse as dN}from"dotenv";L();import{execFileSync as Ou}from"child_process";import{existsSync as Gv,readFileSync as qv,writeFileSync as zv}from"fs";import{homedir as Du,userInfo as Fu}from"os";import{join as Lu}from"path";var Jv="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Vv="https://platform.claude.com/v1/oauth/token",Yv=300*1e3;function ve(){let t=Nu();if(t===void 0)return;let e=Uu(t);if(e!==void 0){if(e.expiresAt!==void 0&&e.expiresAt<=Date.now()){process.stderr.write("agent-afk: Claude Code OAuth token in keychain is expired. Run `claude login` to refresh.\n");return}return e.accessToken}}async function Qa(){let t=Nu();if(t===void 0)return;let e=Uu(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+Yv)return e.accessToken;if(!e.refreshToken){process.stderr.write("agent-afk: OAuth token expired and no refresh token available. Run `claude login` to refresh.\n");return}let n=await Xv(e.refreshToken);if(!n){process.stderr.write("agent-afk: OAuth token refresh failed. Run `claude login` to refresh.\n");return}try{let r={};try{r=JSON.parse(t)}catch{}let o=r.claudeAiOauth??{};r.claudeAiOauth={...o,accessToken:n.accessToken,expiresAt:n.expiresAt,...n.refreshToken!==void 0?{refreshToken:n.refreshToken}:{}},Qv(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
@@ -941,7 +941,7 @@ ${o}`:o}function oC(t){let e=t.systemPrompt;if(e!==void 0){if(typeof e=="string"
941
941
  --
942
942
  ${y.content}`,isError:!0,...y.truncated===!0?{truncated:!0}:{}}),p.push({call:h,result:y});let k=u.get(h.id),S=typeof k=="number"?Date.now()-k:0,x=y.truncated===!0||y.content.includes("[output truncated");Rt(o,si({toolUseId:h.id,name:h.name,result:y,truncated:x,durationMs:S,subagentId:a})),yield{type:"tool.output",toolUseId:h.id,toolName:h.name,content:y.content,...y.isError===!0?{isError:!0}:{},...y.truncated===!0?{truncated:!0}:{},...y.incomplete===!0?{incomplete:!0}:{},...y.incompleteReason?{incompleteReason:y.incompleteReason}:{},...typeof y.batchIndex=="number"&&typeof y.batchSize=="number"?{batchIndex:y.batchIndex,batchSize:y.batchSize}:{},...y.failureClass?{failureClass:y.failureClass}:{},sessionId:i},y.render?.diff&&(yield{type:"tool.diff",toolUseId:h.id,diff:y.render.diff,sessionId:i})}}s.push(sh(t.assistantText,l,t.reasoningText));for(let m of ih(p))s.push(m);let f=ah(p,{vision:n});return f&&s.push(f),p.find(m=>m.result.failureClass===cn)?.result}var vt="tool_use_loop_capped";var ii="You have reached your tool-use budget for this turn. Do not request any more tools \u2014 give your final answer now using only the information already gathered.";function ai(t){return t!==void 0&&t>0?Math.floor(t):0}function li(t,e){return e>0&&t>=e}function ci(t,e){return e>0?`round ${t}/${e}`:`round ${t}`}import PC from"openai";var MC=null;function OC(t){let e={apiKey:t.apiKey};return t.baseURL!==void 0&&(e.baseURL=t.baseURL),t.defaultHeaders!==void 0&&(e.defaultHeaders=t.defaultHeaders),new PC(e)}function Ph(){return MC??OC}function Be(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=setTimeout(n,t);r.unref(),e.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}async function*Mc(t,e){let n=0;for(;;){let r=zs(),o=Date.now(),s,i=null;for(let d=0;;d++)try{s=await e.createStream(t.controller.signal);break}catch(u){if(t.controller.signal.aborted)return null;if(ti(u)&&d<Th){let p=Pc(u),f=p??Cc(d);if(U(t.traceWriter,{phase:"rate_limit",durationMs:f,resolvedModel:t.currentModel,metadata:{source:"connection",reason:p!==void 0?"retry-after":"backoff",attempt:d}}),await Be(f,t.controller.signal),t.controller.signal.aborted)return null;continue}i=u;break}if(i!==null)return yield{type:"error",error:e.clarifyError(i)},null;let a=null,l=!1;try{for await(let d of En(s,t.controller.signal)){if(t.isClosed())return null;for(let u of e.translate(d,r))l||(l=!0,U(t.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-o,resolvedModel:t.currentModel})),yield u}}catch(d){if(t.controller.signal.aborted)return null;if(ni(d)&&n<xh){n++,yield{type:"stream.retry",sessionId:t.initSessionId};let u=Pc(d),p=u??Cc(n-1);if(U(t.traceWriter,{phase:"rate_limit",durationMs:p,resolvedModel:t.currentModel,metadata:{source:"stream",reason:u!==void 0?"retry-after":"backoff",attempt:n}}),await Be(p,t.controller.signal),t.controller.signal.aborted)return null;continue}a=d}if(a!==null)return yield{type:"error",error:e.clarifyError(a)},null;if(t.controller.signal.aborted)return null;let c=nh(r)&&r.toolCallsByIndex.size>0;return r.finishReason===null&&r.assistantText.length===0&&!c?(yield{type:"error",error:new He("the model stream ended without a finish_reason and without a dispatchable response (no visible answer text and no complete tool call): the response was empty or cut off before any usable content arrived. The turn is incomplete.")},null):{state:r,events:[],text:r.assistantText,needsToolDispatch:c}}}var Oc="openai-compatible",LC=new Set([400,404,405,415,422,501]);function NC(t){if(t instanceof Nr||ti(t)||ni(t))return!1;let e=Ur(t);return e!==void 0&&LC.has(e)}var di=class{client;opts;initSessionId;toolDispatcher;onPermissionMode;openAITools;wireMode;traceWriter;priorTurns=[];currentModel;currentPermissionMode;responsesCompactionUnavailable=!1;abort=new wn;closed=!1;lastUsage=null;autoCompactThreshold;constructor(e){if(this.opts=e,this.initSessionId=e.synthesizedSessionId,this.currentModel=e.model,this.currentPermissionMode=Ic(e.config.permissionMode),this.toolDispatcher=e.toolDispatcher,this.onPermissionMode=e.onPermissionMode,this.traceWriter=e.traceWriter,this.autoCompactThreshold=bn(e.config.autoCompact),this.toolDispatcher){let o=this.toolDispatcher;Array.isArray(o.toolDefs)&&o.toolDefs.length>0&&(this.openAITools=rh(o.toolDefs))}let n=(e.useResponsesApi??!1)||ch(b.AFK_OPENAI_USE_RESPONSES),r=dh(e.auth,n);if(this.wireMode=r.mode,e.auth.apiKey===null)this.client=null;else{let o=Ph(),s={apiKey:e.auth.apiKey},i=r.baseURL??e.baseURL;i!==void 0&&(s.baseURL=i),r.headers!==void 0&&(s.defaultHeaders=r.headers),this.client=o(s)}}activeOpenAITools(){if(!this.openAITools)return;if(this.currentPermissionMode==="plan")return this.openAITools;let e=this.openAITools.filter(n=>n.function.name!==Ve);return e.length>0?e:void 0}async*[Symbol.asyncIterator](){if(yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.currentModel,permissionMode:this.currentPermissionMode,cwd:process.cwd(),tools:this.openAITools?this.openAITools.map(r=>r.function.name):[],slashCommands:[],skills:[],plugins:[],mcpServers:this.opts.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:this.opts.auth.source,version:Oc}},this.opts.auth.apiKey===null){yield{type:"error",error:new Error(wc(this.opts.auth))};return}let n=this.opts.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let r=await Promise.race([n.next(),this.abort.closedPromise]);if(r===vc)break;let o=r;if(o.done)break;if(yield*this.runTurn(o.value.content),this.autoCompactThreshold!==void 0&&!this.closed){let s=this.lastUsage,i=qt(this.currentModel);if(s!==null&&i>0){let a=$e(s);if(Pr(a,i,this.autoCompactThreshold))try{await this.opts.config.hookRegistry?.dispatch({event:"PreCompact",sessionId:this.initSessionId,trigger:"auto"}),await this.compactHistory("token_threshold")}catch(l){if(!(l instanceof G))throw l}}}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}async*runTurn(e){let n=this.abort.begin();if(n.signal.aborted)return;let r=Date.now(),o=FC(),s=n.signal.aborted?Date.now():null,i=()=>{s===null&&(s=Date.now())};this.traceWriter&&!n.signal.aborted&&n.signal.addEventListener("abort",i,{once:!0}),U(this.traceWriter,{phase:"loop_start"});try{yield*this._runTurnInner(e,n,r,o)}finally{n.signal.removeEventListener("abort",i),s!==null&&n.signal.reason==="interrupted"&&U(this.traceWriter,{phase:"interrupt_halt",durationMs:Date.now()-s,metadata:{provider:"openai-compatible"}}),U(this.traceWriter,{phase:"loop_end",durationMs:Date.now()-r})}}async*_runTurnInner(e,n,r,o){let s=Gg(this.currentModel);this.priorTurns.push({role:"user",content:Qg(e,{vision:s,model:this.currentModel})});let i={stopReason:null,resultSubtype:"success",isError:!1},a="",l="",c=ai(this.opts.config.maxToolUseIterations),d=!1,u=0,p=0;for(;;){if(n.signal.aborted){this.abort.clear(n),yield*this.finishTurn(i,r);return}let f=yield*this.runIteration(n,s,d);if(f===null){this.abort.clear(n),(n.signal.aborted||this.closed)&&(yield*this.finishTurn(i,r));return}let m=th(f.state);if(i=Tr(i,m),i.contextWindowTokens=(m.inputTokens??0)+(m.outputTokens??0),this.lastUsage=i,f.text.length>0&&(a=f.text),l=f.state.reasoningText,!f.needsToolDispatch||d)break;let g=yield*this.dispatchAndAppend(f.state,n.signal,s);if(g){this.abort.clear(n),yield{type:"error",error:new Zt(g.content)};return}u+=1;{let h=Js(f.state);p+=h.length;let y=h.at(-1),w=y?.name,k;try{k=y?JSON.parse(y.argumentsRaw||"{}"):void 0}catch{k=void 0}let S=y?`${y.name}${St(y.name,k)}`:"unknown";yield{type:"progress",progress:{taskId:o,description:"Working",summary:`${ci(u,c)}: ${S}`,lastToolName:w,totalTokens:i.totalTokens??0,toolUses:p,durationMs:Date.now()-r},sessionId:this.initSessionId}}if(n.signal.aborted){this.abort.clear(n),yield*this.finishTurn(i,r);return}if(li(u,c)){d=!0;continue}}if(this.abort.clear(n),a.length>0){let f={role:"assistant",content:a};l.length>0&&(f.reasoning_content=l),this.priorTurns.push(f)}yield{type:"assistant.message",text:a,sessionId:this.initSessionId},yield*this.finishTurn(d?{...i,stopReason:vt}:i,r)}*finishTurn(e,n){this.lastUsage=e,yield{type:"turn.completed",usage:{...e,durationMs:Date.now()-n},sessionId:this.initSessionId}}clarifyResponsesError(e,n){let r=e instanceof Error?e:new Error(String(e));if(!n||(e&&typeof e=="object"&&"status"in e?e.status:void 0)!==400&&!/\b400\b/.test(r.message))return r;let s,i=e?.error;if(i&&typeof i=="object"){let a=i;typeof a.detail=="string"?s=a.detail:typeof a.message=="string"&&(s=a.message)}return new Error(`ChatGPT/Codex backend rejected model "${this.currentModel}" (HTTP 400). A ChatGPT subscription only serves certain OpenAI models on this backend (gpt-5.6 and gpt-5.5 work; gpt-5, gpt-5.1, gpt-5.2 and *-codex do not). `+(s?`Backend said: ${s}`:"No error body was returned."))}async*runIteration(e,n,r=!1){let o=Zg({config:this.opts.config,...this.opts.config.resumeHistory!==void 0?{resumeHistory:this.opts.config.resumeHistory}:{},priorTurns:this.priorTurns,vision:n});if(o[0]?.role==="system"){let a=this.currentPermissionMode==="plan"?Do:this.currentPermissionMode==="autonomous"?Fo:null;a!==null&&(o[0]={...o[0],content:o[0].content+`
943
943
 
944
- `+a})}r&&o.push({role:"user",content:ii});let s=r?void 0:this.activeOpenAITools(),i={controller:e,traceWriter:this.traceWriter,initSessionId:this.initSessionId,currentModel:this.currentModel,isClosed:()=>this.closed};if(this.wireMode==="responses"){let a=this.opts.auth.source==="chatgpt-oauth";if(a&&Ir(this.currentModel))return yield{type:"error",error:new Error(`Model "${this.currentModel}" can't run on a ChatGPT subscription \u2014 the ChatGPT/Codex backend only supports OpenAI gpt-5.x models. This usually means a subagent or skill requested a Claude model. Pass a gpt-5.x model to it (e.g. model: "gpt-5.5"); for an auto-dispatched agent you can't pass a model to (e.g. git-investigator), set AFK_DEFAULT_SUBAGENT_MODEL to a gpt-5.x id. Or run it on a provider configured with the matching API key.`)},null;let l=Zs({model:this.currentModel,messages:o,activeTools:s,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort,isChatGptBackend:a});return yield*Mc(i,{createStream:async c=>await this.client.responses.create(l,{signal:c}),translate:(c,d)=>Vs(c,d,this.initSessionId),clarifyError:c=>this.clarifyResponsesError(c,a)})}else{let a=kh({model:this.currentModel,messages:o,activeTools:s,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort});return yield*Mc(i,{createStream:async l=>await this.client.chat.completions.create(a,{signal:l}),translate:(l,c)=>eh(l,c,this.initSessionId),clarifyError:l=>l instanceof Error?l:new Error(String(l))})}}async*dispatchAndAppend(e,n,r){return yield*Ch({state:e,signal:n,vision:r,toolDispatcher:this.toolDispatcher,traceWriter:this.traceWriter,priorTurns:this.priorTurns,sessionId:this.initSessionId,subagentId:this.opts.config.subagentId})}async interrupt(){this.abort.requestAbort("interrupted")}async compact(){return this.compactHistory("manual")}async compactHistory(e){let n=this.priorTurns.length;if(this.opts.auth.apiKey===null)return{compacted:!1,reason:"no-usable-auth",messagesBefore:n,messagesAfter:n};if(this.wireMode==="responses"&&this.responsesCompactionUnavailable){let s=kn(b.AFK_MICROCOMPACT_TOOL_RESULT_BYTES,b.AFK_MICROCOMPACT_KEEP_LAST),{blocksCleared:i,bytesReclaimed:a}=xc(this.priorTurns,s);return i>0?{compacted:!1,reason:"microcompacted",messagesBefore:n,messagesAfter:this.priorTurns.length,microcompaction:{blocksCleared:i,bytesReclaimed:a}}:{compacted:!1,reason:"responses-compaction-unavailable",messagesBefore:n,messagesAfter:n}}let r=b.AFK_COMPACT_MODEL??this.currentModel,o=Mr($e(this.lastUsage??{}),qt(this.currentModel));return bh({priorTurns:this.priorTurns,usedFraction:o,shrinkAtFraction:yh(),summarize:(s,i)=>this.wireMode==="responses"?this.summarizeViaResponses(s,i,r):ei({client:this.client,model:r,system:Or,user:Lr(s),maxTokens:1024,signal:i}),isClosed:this.closed,isIdle:this.abort.isIdle(),beginAbort:()=>this.abort.begin(),clearAbort:s=>this.abort.clear(s),trigger:e,traceWriter:this.traceWriter})}async summarizeViaResponses(e,n,r){try{return await _h({client:this.client,model:r,system:Or,user:Lr(e),isChatGptBackend:this.opts.auth.source==="chatgpt-oauth",maxTokens:1024,signal:n})}catch(o){if(!n.aborted&&NC(o)){this.responsesCompactionUnavailable=!0;let s=Ur(o);U(this.traceWriter,{phase:"compaction_disabled",metadata:{wire:"responses",reason:"responses-compaction-unavailable",error:o instanceof Error?o.message:String(o),...s!==void 0?{status:s}:{}}})}throw o}}async setModel(e){e!==void 0&&(this.currentModel=me(e)??e)}async setPermissionMode(e){this.currentPermissionMode=Ic(e);let n=Le(this.currentPermissionMode);this.toolDispatcher?.setAllowAll?.(n),this.onPermissionMode?.(this.currentPermissionMode)}setCwd(e){this.toolDispatcher?.setResolveBase?.(e)}async supportedCommands(){return ui()}async supportedModels(){return[{value:"gpt-5.6",displayName:"GPT-5.6 (Sol)",description:"OpenAI flagship \u2014 alias for gpt-5.6-sol"},{value:"gpt-5.6-sol",displayName:"GPT-5.6 Sol",description:"Frontier capability"},{value:"gpt-5.6-terra",displayName:"GPT-5.6 Terra",description:"Balanced intelligence/cost"},{value:"gpt-5.6-luna",displayName:"GPT-5.6 Luna",description:"Fast, high-volume workloads"},{value:"gpt-5.5",displayName:"GPT-5.5",description:"Prior flagship (ChatGPT backend)"},{value:"gpt-4o",displayName:"GPT-4o",description:"OpenAI flagship multimodal"},{value:"gpt-4o-mini",displayName:"GPT-4o mini",description:"Fast/cheap GPT-4o"},{value:"gpt-4.1",displayName:"GPT-4.1",description:"Long-context GPT-4"},{value:"gpt-4.1-mini",displayName:"GPT-4.1 mini",description:"Fast 4.1 variant"},{value:"o1",displayName:"o1",description:"Reasoning model"},{value:"o1-mini",displayName:"o1 mini",description:"Fast reasoning"},{value:"o3-mini",displayName:"o3 mini",description:"Newer reasoning, faster"}]}async supportedAgents(){return[]}async getContextUsage(){let e=this.lastUsage,n=Rr(this.currentModel),r;if(e&&n>0){let i=$e(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=Cr(e);return{tools:[],agents:[],isAutoCompactEnabled:this.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.opts.mcpManager?this.opts.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{authSource:this.opts.auth.source}}async rewindFiles(e,n){return{canRewind:!1,error:`${Oc} provider does not support file checkpoint rewind yet.`}}close(){this.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed(),T(`\u{1F7E2} ${Oc}: closed`)}};function Mh(t,e,n={}){let r=wt(t.apiKey,n.authDeps,t.forceChatgptOAuth??!1),o=n.sessionIdOverride??t.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=typeof t.model=="string"?t.model:"gpt-4o-mini",i=me(s)??s,a={auth:r,model:i,synthesizedSessionId:o,promptStream:e,config:t};return n.baseURL!==void 0&&(a.baseURL=n.baseURL),n.toolDispatcher!==void 0&&(a.toolDispatcher=n.toolDispatcher),n.onPermissionMode!==void 0&&(a.onPermissionMode=n.onPermissionMode),n.mcpManager!==void 0&&(a.mcpManager=n.mcpManager),n.useResponsesApi!==void 0&&(a.useResponsesApi=n.useResponsesApi),t.traceWriter!==void 0&&(a.traceWriter=t.traceWriter),new di(a)}import{randomUUID as $C}from"node:crypto";Z();var Fc=new Set,Oh=!1,Dh=null,Fh=null,Lh=null;function Dc(){for(let t of Fc)Vn(t)}function UC(){if(Oh)return;Oh=!0,Dh=()=>Dc(),process.on("exit",Dh);let t=process.listenerCount("SIGINT")>0;Fh=()=>{Dc(),t||process.exit(130)},process.on("SIGINT",Fh);let e=process.listenerCount("SIGTERM")>0;Lh=()=>{Dc(),e||process.exit(143)},process.on("SIGTERM",Lh)}function Nh(t){UC(),Fc.add(t)}function Uh(t){Fc.delete(t)}function Lc(t,e){return(t===void 0||t===0)&&e===void 0}var BC=new Set(["cli"]);function $r(t){let e=t.sessionId??t.resume;if(e!==void 0)return{id:e,memoized:t.memoized};if(!Lc(t.depth,t.parentSessionId))return{id:void 0,memoized:t.memoized};if(t.surface===void 0||!BC.has(t.surface))return{id:void 0,memoized:t.memoized};let n=t.memoized??$C();return{id:n,memoized:n}}function Br(t){let e=t.sessionId;if(!Lc(t.depth,t.parentSessionId)||e===void 0)return t.currentPresenceSessionId;if(t.currentPresenceSessionId===e)return e;let n=t.currentPresenceSessionId;n!==null&&(T(`\u2691 presence: advertised id changed ${n} \u2192 ${e} \u2014 rewriting`),Uh(n),Vn(n));let r=t.runtimeStateSource.getWorkspace();return Ja({sessionId:e,surface:t.surface,actor:Ws(t.depth),cwd:t.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:t.providerName,name:t.model},workspace:r,pid:process.pid}),Nh(e),e}var Nc="openai-compatible",Ge=class{name=Nc;providerOpts;memoryStore;schemas;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_presenceSessionId=null;_mintedSessionId=null;constructor(e={}){this.providerOpts=e,this.memoryStore=e.memoryStore??new et;let n=[...Ie];e.subagentExecutor&&n.push(e.subagentExecutor.describeAgentTool?.()??Qe),e.skillExecutor&&n.push(gt),e.composeExecutor&&n.push(ht),e.readOnlyMemory===!0?n.push(ln):n.push(...yt),n.push(Ne);for(let r of e.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);this.schemas=n}query(e){let n=e.config,r=n.permissionMode??"default";this._currentPermissionMode=r,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let o,s=typeof n.model=="string"?n.model:String(n.model),i=zn({surface:this.providerOpts.surface??"cli",cwd:n.cwd??process.cwd(),modelName:s,providerName:Nc,permissionMode:r,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>o instanceof Pe?o.toolDefs.map(w=>w.name):[],getMcpTools:()=>this.providerOpts.mcpManager?.getMcpTools()??[],getSubagents:()=>this.providerOpts.subagentExecutor?this.providerOpts.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});o=this.providerOpts.tools?Jn(this.providerOpts.tools,i):this.buildDispatcher(r,{...n.cwd!==void 0?{cwd:n.cwd}:{},...this._sharedReadRoots!==void 0?{readRoots:this._sharedReadRoots}:{},...this._sharedWriteRoots!==void 0?{writeRoots:this._sharedWriteRoots}:{},...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.subagentId!==void 0?{subagentId:n.subagentId}:{},...n.subagentToolOutputCapBytes!==void 0?{subagentToolOutputCapBytes:n.subagentToolOutputCapBytes}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},runtimeStateSource:i,...n.isSkillDispatch?{isSkillDispatch:!0}:{},...n.isNonInteractive?{isNonInteractive:!0}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{},...n.planExitControls!==void 0?{planExitControls:n.planExitControls}:{}});let a=$r({sessionId:n.sessionId,resume:n.resume,depth:n.depth,parentSessionId:n.parentSessionId,surface:this.providerOpts.surface??"cli",memoized:this._mintedSessionId});this._mintedSessionId=a.memoized;let l={};a.id!==void 0&&(l.sessionIdOverride=a.id);let c=n.openaiBaseUrl??this.providerOpts.baseURL;c!==void 0&&(l.baseURL=c),l.toolDispatcher=o,l.onPermissionMode=w=>{this._currentPermissionMode=w},this.providerOpts.mcpManager!==void 0&&(l.mcpManager=this.providerOpts.mcpManager),this._presenceSessionId=Br({depth:n.depth,parentSessionId:n.parentSessionId,sessionId:a.id,currentPresenceSessionId:this._presenceSessionId,runtimeStateSource:i,surface:this.providerOpts.surface??"cli",cwd:n.cwd,providerName:Nc,model:s});let d=qn({cwd:n.cwd??process.cwd(),...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:i.getWorkspace()}),u=Ks(n.isSkillDispatch),p=Gs(this.providerOpts.readOnlyMemory),f=this.providerOpts.skillExecutor?pi(void 0,{...typeof n.cwd=="string"&&n.cwd.length>0?{cwd:n.cwd}:{},...typeof n.skillDispatchName=="string"&&n.skillDispatchName.length>0?{excludeName:n.skillDispatchName}:{}}):"",m=typeof n.hotMemory=="string"?n.hotMemory:"",g=typeof n.systemPrompt=="string"?n.systemPrompt:void 0,h=[u];g!==void 0&&g.length>0&&h.push(g),h.push(p),m.length>0&&h.push(m),h.push(d),f.length>0&&h.push(f);let y={...n,systemPrompt:h.join(`
944
+ `+a})}r&&o.push({role:"user",content:ii});let s=r?void 0:this.activeOpenAITools(),i={controller:e,traceWriter:this.traceWriter,initSessionId:this.initSessionId,currentModel:this.currentModel,isClosed:()=>this.closed};if(this.wireMode==="responses"){let a=this.opts.auth.source==="chatgpt-oauth";if(a&&Ir(this.currentModel))return yield{type:"error",error:new Error(`Model "${this.currentModel}" can't run on a ChatGPT subscription \u2014 the ChatGPT/Codex backend only supports OpenAI gpt-5.x models. This usually means a subagent or skill requested a Claude model. Pass a gpt-5.x model to it (e.g. model: "gpt-5.5"); for an auto-dispatched agent you can't pass a model to (e.g. git-investigator), set AFK_DEFAULT_SUBAGENT_MODEL to a gpt-5.x id. Or run it on a provider configured with the matching API key.`)},null;let l=Zs({model:this.currentModel,messages:o,activeTools:s,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort,isChatGptBackend:a});return yield*Mc(i,{createStream:async c=>await this.client.responses.create(l,{signal:c}),translate:(c,d)=>Vs(c,d,this.initSessionId),clarifyError:c=>this.clarifyResponsesError(c,a)})}else{let a=kh({model:this.currentModel,messages:o,activeTools:s,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort});return yield*Mc(i,{createStream:async l=>await this.client.chat.completions.create(a,{signal:l}),translate:(l,c)=>eh(l,c,this.initSessionId),clarifyError:l=>l instanceof Error?l:new Error(String(l))})}}async*dispatchAndAppend(e,n,r){return yield*Ch({state:e,signal:n,vision:r,toolDispatcher:this.toolDispatcher,traceWriter:this.traceWriter,priorTurns:this.priorTurns,sessionId:this.initSessionId,subagentId:this.opts.config.subagentId})}async interrupt(){this.abort.requestAbort("interrupted")}async compact(){return this.compactHistory("manual")}async compactHistory(e){let n=this.priorTurns.length;if(this.opts.auth.apiKey===null)return{compacted:!1,reason:"no-usable-auth",messagesBefore:n,messagesAfter:n};if(this.wireMode==="responses"&&this.responsesCompactionUnavailable){let s=kn(b.AFK_MICROCOMPACT_TOOL_RESULT_BYTES,b.AFK_MICROCOMPACT_KEEP_LAST),{blocksCleared:i,bytesReclaimed:a}=xc(this.priorTurns,s);return i>0?{compacted:!1,reason:"microcompacted",messagesBefore:n,messagesAfter:this.priorTurns.length,microcompaction:{blocksCleared:i,bytesReclaimed:a}}:{compacted:!1,reason:"responses-compaction-unavailable",messagesBefore:n,messagesAfter:n}}let r=b.AFK_COMPACT_MODEL??this.currentModel,o=Mr($e(this.lastUsage??{}),qt(this.currentModel));return bh({priorTurns:this.priorTurns,usedFraction:o,shrinkAtFraction:yh(),summarize:(s,i)=>this.wireMode==="responses"?this.summarizeViaResponses(s,i,r):ei({client:this.client,model:r,system:Or,user:Lr(s),maxTokens:1024,signal:i}),isClosed:this.closed,isIdle:this.abort.isIdle(),beginAbort:()=>this.abort.begin(),clearAbort:s=>this.abort.clear(s),trigger:e,traceWriter:this.traceWriter})}async summarizeViaResponses(e,n,r){try{return await _h({client:this.client,model:r,system:Or,user:Lr(e),isChatGptBackend:this.opts.auth.source==="chatgpt-oauth",maxTokens:1024,signal:n})}catch(o){if(!n.aborted&&NC(o)){this.responsesCompactionUnavailable=!0;let s=Ur(o);U(this.traceWriter,{phase:"compaction_disabled",metadata:{wire:"responses",reason:"responses-compaction-unavailable",error:o instanceof Error?o.message:String(o),...s!==void 0?{status:s}:{}}})}throw o}}async setModel(e){e!==void 0&&(this.currentModel=me(e)??e)}async setPermissionMode(e){this.currentPermissionMode=Ic(e);let n=Le(this.currentPermissionMode);this.toolDispatcher?.setAllowAll?.(n),this.onPermissionMode?.(this.currentPermissionMode)}setCwd(e){this.toolDispatcher?.setResolveBase?.(e)}async supportedCommands(){return ui()}async supportedModels(){return[{value:"gpt-5.6",displayName:"GPT-5.6 (Sol)",description:"OpenAI flagship \u2014 alias for gpt-5.6-sol"},{value:"gpt-5.6-sol",displayName:"GPT-5.6 Sol",description:"Frontier capability"},{value:"gpt-5.6-terra",displayName:"GPT-5.6 Terra",description:"Balanced intelligence/cost"},{value:"gpt-5.6-luna",displayName:"GPT-5.6 Luna",description:"Fast, high-volume workloads"},{value:"gpt-5.5",displayName:"GPT-5.5",description:"Prior flagship (ChatGPT backend)"},{value:"gpt-4o",displayName:"GPT-4o",description:"OpenAI flagship multimodal"},{value:"gpt-4o-mini",displayName:"GPT-4o mini",description:"Fast/cheap GPT-4o"},{value:"gpt-4.1",displayName:"GPT-4.1",description:"Long-context GPT-4"},{value:"gpt-4.1-mini",displayName:"GPT-4.1 mini",description:"Fast 4.1 variant"},{value:"o1",displayName:"o1",description:"Reasoning model"},{value:"o1-mini",displayName:"o1 mini",description:"Fast reasoning"},{value:"o3-mini",displayName:"o3 mini",description:"Newer reasoning, faster"}]}async supportedAgents(){return[]}async getContextUsage(){let e=this.lastUsage,n=Rr(this.currentModel),r;if(e&&n>0){let i=$e(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=Cr(e);return{tools:[],agents:[],isAutoCompactEnabled:this.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.opts.mcpManager?this.opts.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{authSource:this.opts.auth.source}}async rewindFiles(e,n){return{canRewind:!1,error:`${Oc} provider does not support file checkpoint rewind yet.`}}close(){this.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed(),T(`\u{1F7E2} ${Oc}: closed`)}};function Mh(t,e,n={}){let r=wt(t.apiKey,n.authDeps,t.forceChatgptOAuth??!1),o=n.sessionIdOverride??t.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=typeof t.model=="string"?t.model:"gpt-4o-mini",i=me(s)??s,a={auth:r,model:i,synthesizedSessionId:o,promptStream:e,config:t};return n.baseURL!==void 0&&(a.baseURL=n.baseURL),n.toolDispatcher!==void 0&&(a.toolDispatcher=n.toolDispatcher),n.onPermissionMode!==void 0&&(a.onPermissionMode=n.onPermissionMode),n.mcpManager!==void 0&&(a.mcpManager=n.mcpManager),n.useResponsesApi!==void 0&&(a.useResponsesApi=n.useResponsesApi),t.traceWriter!==void 0&&(a.traceWriter=t.traceWriter),new di(a)}import{randomUUID as $C}from"node:crypto";Z();var Fc=new Set,Oh=!1,Dh=null,Fh=null,Lh=null;function Dc(){for(let t of Fc)Vn(t)}function UC(){if(Oh)return;Oh=!0,Dh=()=>Dc(),process.on("exit",Dh);let t=process.listenerCount("SIGINT")>0;Fh=()=>{Dc(),t||process.exit(130)},process.on("SIGINT",Fh);let e=process.listenerCount("SIGTERM")>0;Lh=()=>{Dc(),e||process.exit(143)},process.on("SIGTERM",Lh)}function Nh(t){UC(),Fc.add(t)}function Uh(t){Fc.delete(t)}function Lc(t,e){return(t===void 0||t===0)&&e===void 0}var BC=new Set(["cli"]);function $r(t){let e=t.sessionId??t.resume;if(e!==void 0)return{id:e,memoized:t.memoized};if(!Lc(t.depth,t.parentSessionId))return{id:void 0,memoized:t.memoized};if(t.surface===void 0||!BC.has(t.surface))return{id:void 0,memoized:t.memoized};let n=t.memoized??$C();return{id:n,memoized:n}}function Br(t){let e=t.sessionId;if(!Lc(t.depth,t.parentSessionId)||e===void 0)return t.currentPresenceSessionId;if(t.currentPresenceSessionId===e)return e;let n=t.currentPresenceSessionId;n!==null&&(T(`\u2691 presence: advertised id changed ${n} \u2192 ${e} \u2014 rewriting`),Uh(n),Vn(n));let r=t.runtimeStateSource.getWorkspace();return Ja({sessionId:e,surface:t.surface,actor:Ws(t.depth),cwd:t.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:t.providerName,name:t.model},workspace:r,pid:process.pid}),Nh(e),e}var Nc="openai-compatible",Ge=class{name=Nc;providerOpts;memoryStore;schemas;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_presenceSessionId=null;_mintedSessionId=null;constructor(e={}){this.providerOpts=e,this.memoryStore=e.memoryStore??new et;let n=[...Ie];e.subagentExecutor&&n.push(e.subagentExecutor.describeAgentTool?.()??Qe),e.skillExecutor&&n.push(gt),e.composeExecutor&&n.push(ht),e.readOnlyMemory===!0?n.push(ln):n.push(...yt),n.push(Ne);for(let r of e.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);this.schemas=n}query(e){let n=e.config,r=n.permissionMode??"default";this._currentPermissionMode=r,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let o,s=typeof n.model=="string"?n.model:String(n.model),i=zn({surface:this.providerOpts.surface??"cli",getCwd:()=>n.cwd??process.cwd(),modelName:s,providerName:Nc,permissionMode:r,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>o instanceof Pe?o.toolDefs.map(w=>w.name):[],getMcpTools:()=>this.providerOpts.mcpManager?.getMcpTools()??[],getSubagents:()=>this.providerOpts.subagentExecutor?this.providerOpts.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});o=this.providerOpts.tools?Jn(this.providerOpts.tools,i):this.buildDispatcher(r,{...n.cwd!==void 0?{cwd:n.cwd}:{},...this._sharedReadRoots!==void 0?{readRoots:this._sharedReadRoots}:{},...this._sharedWriteRoots!==void 0?{writeRoots:this._sharedWriteRoots}:{},...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.subagentId!==void 0?{subagentId:n.subagentId}:{},...n.subagentToolOutputCapBytes!==void 0?{subagentToolOutputCapBytes:n.subagentToolOutputCapBytes}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},runtimeStateSource:i,...n.isSkillDispatch?{isSkillDispatch:!0}:{},...n.isNonInteractive?{isNonInteractive:!0}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{},...n.planExitControls!==void 0?{planExitControls:n.planExitControls}:{}});let a=$r({sessionId:n.sessionId,resume:n.resume,depth:n.depth,parentSessionId:n.parentSessionId,surface:this.providerOpts.surface??"cli",memoized:this._mintedSessionId});this._mintedSessionId=a.memoized;let l={};a.id!==void 0&&(l.sessionIdOverride=a.id);let c=n.openaiBaseUrl??this.providerOpts.baseURL;c!==void 0&&(l.baseURL=c),l.toolDispatcher=o,l.onPermissionMode=w=>{this._currentPermissionMode=w},this.providerOpts.mcpManager!==void 0&&(l.mcpManager=this.providerOpts.mcpManager),this._presenceSessionId=Br({depth:n.depth,parentSessionId:n.parentSessionId,sessionId:a.id,currentPresenceSessionId:this._presenceSessionId,runtimeStateSource:i,surface:this.providerOpts.surface??"cli",cwd:n.cwd,providerName:Nc,model:s});let d=qn({cwd:n.cwd??process.cwd(),...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:i.getWorkspace()}),u=Ks(n.isSkillDispatch),p=Gs(this.providerOpts.readOnlyMemory),f=this.providerOpts.skillExecutor?pi(void 0,{...typeof n.cwd=="string"&&n.cwd.length>0?{cwd:n.cwd}:{},...typeof n.skillDispatchName=="string"&&n.skillDispatchName.length>0?{excludeName:n.skillDispatchName}:{}}):"",m=typeof n.hotMemory=="string"?n.hotMemory:"",g=typeof n.systemPrompt=="string"?n.systemPrompt:void 0,h=[u];g!==void 0&&g.length>0&&h.push(g),h.push(p),m.length>0&&h.push(m),h.push(d),f.length>0&&h.push(f);let y={...n,systemPrompt:h.join(`
945
945
 
946
946
  `)};return Mh(y,e.prompt,l)}buildDispatcher(e,n){let r=hn(e,n.cwd),o=fr(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[d,u]of o)this.providerOpts.readOnlyMemory===!0&&d!=="memory_search"||r.set(d,u);n.runtimeStateSource&&r.set("get_runtime_state",on(n.runtimeStateSource));for(let d of this.providerOpts.customTools??[])r.has(d.schema.name)||r.set(d.schema.name,d.handler);let s=n.planExitControls;s&&r.set(Ve,Vo(s));let i=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[d,u]of this.providerOpts.mcpManager.getMcpHandlers())r.set(d,u);let a=n.isSkillDispatch?this.schemas.filter(d=>d.name!=="ask_question"&&d.name!=="terminal_font_size"):n.isNonInteractive?this.schemas.filter(d=>d.name!=="ask_question"):this.schemas,l={handlers:r,schemas:[...a,...i,...s?[Jo]:[]],hookRegistry:es(n.hookRegistry,this.providerOpts.hookRegistry)},c=ns(this.providerOpts.mcpManager?ts(this.providerOpts.permissions,this.providerOpts.mcpManager.getMcpToolWireNames()):this.providerOpts.permissions,(this.providerOpts.customTools??[]).map(d=>d.schema.name));return c!==void 0&&(l.permissions=c),this.providerOpts.subagentExecutor!==void 0&&(l.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(l.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(l.composeExecutor=this.providerOpts.composeExecutor),this.providerOpts.canUseTool!==void 0&&(l.canUseTool=this.providerOpts.canUseTool),n.cwd!==void 0&&(l.cwd=n.cwd),n.readRoots!==void 0&&(l.readRoots=n.readRoots),n.writeRoots!==void 0&&(l.writeRoots=n.writeRoots),n.sessionId!==void 0&&(l.sessionId=n.sessionId),n.parentSessionId!==void 0&&(l.parentSessionId=n.parentSessionId),n.subagentId!==void 0&&(l.subagentId=n.subagentId),n.subagentToolOutputCapBytes!==void 0&&(l.maxOutputBytes=n.subagentToolOutputCapBytes),n.traceWriter!==void 0&&(l.traceWriter=n.traceWriter),this.providerOpts.readOnlyBash===!0&&(l.readOnlyBash=!0),l.allowAll=Le(e),l.sessionGrantManager=this,new Pe(l)}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e)}}grantManager=new mt({getReadRoots:()=>this._sharedReadRoots,getWriteRoots:()=>this._sharedWriteRoots,ensureInitialized:()=>this.ensureSharedRoots(),getProtectedRoot:()=>this._initialResolveBase,getAllowAll:()=>Le(this._currentPermissionMode)});addReadRoot(e,n="slash",r){this.grantManager.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.grantManager.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.grantManager.revokeRoot(e,n,r)}getGrants(){return this.grantManager.getGrants()}close(){this.memoryStore.close()}async complete(e){let n={model:e.model??"gpt-4o-mini",system:e.system,user:e.user,maxTokens:e.maxTokens??64};e.apiKey!==void 0&&(n.apiKey=e.apiKey);let r=e.baseUrl??this.providerOpts.baseURL;return r!==void 0&&(n.baseURL=r),e.signal&&(n.signal=e.signal),ei(n)}},Uc=new Ge;var HC=new Set(["Agent","Task","agent"]),jC=new Set(["Skill","skill"]),WC=new Set(["Compose","compose"]),Qq=new Set([...HC,...WC,...jC]);var $c=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search",...Re],$h=[...$c,"web_scrape","agent"];function qC(t){return typeof t=="string"&&t.startsWith("sk-ant-")}function Bh(t){let{childModel:e,configApiKey:n,parentApiKey:r,parentProvider:o}=t;if(n!==void 0&&n.length>0)return n;if(r===void 0)return;let s=o??(qC(r)?"anthropic-direct":void 0);if(s!==void 0)return J(e)===s?r:void 0}Z();import{existsSync as zC,readdirSync as JC,readFileSync as VC,statSync as YC}from"fs";import{join as XC}from"path";var QC={read:"read_file",edit:"edit_file",write:"write_file",bash:"bash",grep:"grep",glob:"glob",ls:"list_directory",list:"list_directory",webfetch:"web_scrape",websearch:"web_scrape",webbrowse:"web_scrape"};function mi(t,e){let n=t.trim();if(n.length===0)return;if(e.has(n))return n;let r=QC[n.toLowerCase()];if(r!==void 0&&e.has(r))return r}function fi(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1).trim():e}function Hh(t,e){let n=t.trim();if(n.length>0)return n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1).split(",").map(i=>fi(i)).filter(i=>i.length>0):fi(n).split(",").map(s=>fi(s)).filter(s=>s.length>0);let r=[];for(let o of e){let s=o.trim();if(s.startsWith("- "))r.push(fi(s.slice(2)));else break}return r}function Bc(t,e){let n=[];function r(o,s=0){if(s>10||!zC(o))return;let i;try{i=JC(o)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=XC(o,a),c;try{c=YC(l)}catch{continue}if(c.isFile()&&a==="SKILL.md"){let d=ZC(l,e);d.name&&n.push(d)}else c.isDirectory()&&r(l,s+1)}}return r(t),n}function ZC(t,e){try{let n=VC(t,"utf-8");if(!n.startsWith(`---
947
947
  `))return{};let r=n.slice(4),o=r.indexOf(`
@@ -1067,7 +1067,7 @@ ${e}`:s,a=new q({parentAbortSignal:n?.abortSignal,...r?.traceWriter!==void 0?{tr
1067
1067
 
1068
1068
  `+t},{role:"assistant",content:Fr}]},countChars:CO};function PO(t){if(typeof t=="string")return zt(t);if(Array.isArray(t)){let e=0;for(let n of t)n.type==="text"&&"text"in n&&(e+=zt(n.text));return e}return 0}function MO(t){if(typeof t=="string")return vn(t);if(Array.isArray(t)){for(let e of t)if(e.type==="text"&&"text"in e)return vn(e.text)}return!1}var OO={listToolResults(t){let e=[];for(let n of t){if(n.role!=="user"||!Array.isArray(n.content))continue;let r=n.content;for(let o of r){if(o.type!=="tool_result")continue;let s=o;e.push({byteLength:PO(s.content),isPlaceholder:MO(s.content),clear(i){s.content=i}})}}return e}};function Ob(t,e){return Xs(t,OO,e??{})}function Db(t,e,n,r){return Ec(t,e,Ui,n,r)}function Fb(t,e,n){let r=_c(t,Ui);return{model:e,max_tokens:n,system:Or,messages:[{role:"user",content:Lr(r)}],stream:!0}}function Lb(t,e,n){return Ac(t,e,n,Ui)}function Nb(t,e,n){return Tc(t,e,n,Ui)}function Ub(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function $b(t){if(typeof t=="string")return t.length>320?t.slice(0,317)+"...":t;if(Array.isArray(t)){let e=[];for(let r of t)r.type==="text"&&"text"in r&&e.push(r.text);let n=e.join(" ");return n.length>320?n.slice(0,317)+"...":n}return""}P();var FO=2,LO="claude-haiku-4-5-20251001",NO=1024;async function Hb(t){let{state:e,abort:n,retry:r,initSessionId:o,traceWriter:s}=t,i=e.messages.length;if(e.closed)return{compacted:!1,reason:"session-closed",messagesBefore:i,messagesAfter:i};if(!n.isIdle())return{compacted:!1,reason:"turn-in-flight",messagesBefore:i,messagesAfter:i};let a=UO(),l=Mr($e(e.lastUsage??{}),qt(e.requestedModel)),c=Db(e.messages,a,l,$O());if(c<0)return Bb(e,i,"history-too-short");if(c===0)return Bb(e,i,"nothing-to-summarize");let d=e.messages.slice(0,c),u=HO(),p=Fb(d,u,NO),f=n.begin(),m;try{if(f.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let w=ct(r.authMode,o,DO()),k=r.client,S=await Promise.resolve(k.messages.create(p,{headers:w,signal:f.signal}));m=await jO(S)}catch(w){return f.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i}:{compacted:!1,reason:"summarization-failed: "+(w instanceof Error?w.message:String(w)),messagesBefore:i,messagesAfter:i}}finally{n.clear(f)}if(m.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:i,messagesAfter:i};let g=Nb(e.messages,c,m),h=Lb(e.messages,c,m);e.messages.splice(0,e.messages.length,...h);let y=e.messages.length;return Io(s,{trigger:"manual",preCompactionMessages:d,summary:m,keptTailCount:i-c,keepLastNConfig:a,messagesBefore:i,messagesAfter:y,tokensSavedEstimate:g}),{compacted:!0,messagesBefore:i,messagesAfter:y,tokensSavedEstimate:g}}function UO(){let t=b.AFK_COMPACT_KEEP_LAST_TURNS;if(t!==void 0&&t.length>0){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return FO}function $O(){let t=b.AFK_COMPACT_SHRINK_FRACTION;if(t!==void 0&&t.length>0){let e=Number.parseFloat(t);if(Number.isFinite(e)&&e>0&&e<1)return e}return Sn}function Bb(t,e,n){let r=BO(),{blocksCleared:o,bytesReclaimed:s}=Ob(t.messages,r);return o>0?{compacted:!1,reason:"microcompacted",messagesBefore:e,messagesAfter:t.messages.length,microcompaction:{blocksCleared:o,bytesReclaimed:s}}:{compacted:!1,reason:n,messagesBefore:e,messagesAfter:e}}function BO(){return kn(b.AFK_MICROCOMPACT_TOOL_RESULT_BYTES,b.AFK_MICROCOMPACT_KEEP_LAST)}function HO(){let t=b.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?me(t)??t:LO}async function jO(t){let e="";for await(let n of t)if(n.type==="content_block_delta"){let r=n.delta;r.type==="text_delta"&&typeof r.text=="string"&&(e+=r.text)}return e}var jb=72;function ld(t){if(typeof t=="string")return t;let e=[];for(let n of t)n.type==="text"&&typeof n.text=="string"&&e.push(n.text);return e.join(" ")}function Wb(t){return t.role!=="user"?!1:ld(t.content).trim().length>0}function WO(t){let e=t.replace(/\s+/g," ").trim();return e.length<=jb?e:e.slice(0,jb-1)+"\u2026"}function Kb(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];r&&Wb(r)&&e.push({turnIndex:n,preview:WO(ld(r.content))})}return e.reverse()}function Gb(t,e){let{state:n,abort:r}=t,o=n.messages.length;if(n.closed)return{rewound:!1,reason:"session-closed",messagesBefore:o,messagesAfter:o};if(!r.isIdle())return{rewound:!1,reason:"turn-in-flight",messagesBefore:o,messagesAfter:o};if(!Number.isInteger(e)||e<0||e>=o)return{rewound:!1,reason:"invalid-target",messagesBefore:o,messagesAfter:o};let s=n.messages[e];if(!s||!Wb(s))return{rewound:!1,reason:"invalid-target",messagesBefore:o,messagesAfter:o};let i=ld(s.content);return n.messages.splice(e),Mi(n.messages),{rewound:!0,reloadText:i,messagesBefore:o,messagesAfter:n.messages.length}}var KO=[{value:"claude-sonnet-5",displayName:"Claude Sonnet 5",description:"Latest balanced Claude \u2014 recommended default"},{value:"claude-opus-5",displayName:"Claude Opus 5",description:"Highest-capability Claude for agentic coding"},{value:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",description:"Fastest, cheapest Claude"}],$i=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;baseUrl;maxToolUseIterations;traceWriter;subagentId;state;abort;retry;cwdDependentsFactory;onPermissionMode;mcpManager;hookRegistry;throttleQueue;constructor(e){this.initSessionId=e.sessionId??qb(),this.promptStream=e.promptStream,this.maxTokens=e.maxTokens,this.tools=e.tools,this.systemPrefix=e.systemPrefix,this.thinking=e.thinking,e.effort!==void 0&&(this.effort=e.effort),e.baseUrl!==void 0&&(this.baseUrl=e.baseUrl),e.maxToolUseIterations!==void 0&&(this.maxToolUseIterations=e.maxToolUseIterations),this.traceWriter=e.traceWriter,e.subagentId!==void 0&&(this.subagentId=e.subagentId),this.cwdDependentsFactory=e.cwdDependentsFactory,this.onPermissionMode=e.onPermissionMode,this.mcpManager=e.mcpManager,e.hookRegistry!==void 0&&(this.hookRegistry=e.hookRegistry),e.throttleQueue!==void 0&&(this.throttleQueue=e.throttleQueue),this.retry=new Ni({client:e.client,authMode:e.authMode,initSessionId:this.initSessionId,...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.tokenRefresher?{tokenRefresher:e.tokenRefresher}:{},autoResumeOnUsageLimit:e.autoResumeOnUsageLimit??!0,...e.surface!==void 0?{surface:e.surface}:{}}),this.state=sb({model:e.model,...e.requestedModel!==void 0?{requestedModel:e.requestedModel}:{},permissionMode:e.permissionMode??"default",userSystem:e.userSystem,toolDispatcher:e.toolDispatcher,...e.initialMessages?{initialMessages:e.initialMessages}:{},...e.autoCompactThreshold!==void 0?{autoCompactThreshold:e.autoCompactThreshold}:{}}),this.abort=new wn}async*[Symbol.asyncIterator](){yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.state.currentModel,permissionMode:this.state.currentPermissionMode,cwd:process.cwd(),tools:[],slashCommands:[],skills:[],plugins:[],mcpServers:this.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:this.retry.authMode,version:"anthropic-direct-v1"}};let n=this.promptStream[Symbol.asyncIterator]();try{for(;!this.state.closed;){let r=await Promise.race([n.next(),this.abort.closedPromise]);if(r==="__closed__")break;let o=r;if(o.done)break;let s=o.value,i=this.abort.begin();if(i.signal.aborted){this.abort.clear(i);return}Mi(this.state.messages),this.state.messages.push({role:"user",content:s.content});let a=this.composeSystem(),l=ct(this.retry.authMode,this.initSessionId,qb(),this.effort!==void 0,Oo({...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{}})),c={client:this.retry.client,messages:this.state.messages,system:a,tools:this.state.currentPermissionMode==="plan"?this.tools:this.tools?.filter(u=>u.name!==Ve)??null,toolDispatcher:this.state.toolDispatcher,model:this.state.currentModel,maxTokens:this.maxTokens,headers:l,signal:i.signal,ctx:{sessionId:this.initSessionId},...this.thinking!==void 0?{thinking:this.thinking}:{},...this.effort!==void 0?{effort:this.effort}:{},...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{},...this.maxToolUseIterations!==void 0?{maxToolUseIterations:this.maxToolUseIterations}:{},...this.traceWriter?{traceWriter:this.traceWriter}:{},...this.subagentId!==void 0?{subagentId:this.subagentId}:{},...this.throttleQueue?{throttleQueue:this.throttleQueue}:{},onUsageProgress:u=>{this.state.lastUsage=u}},d=!1;try{for await(let u of this.retry.turnWithRetries(c,()=>this.state.closed)){if(this.state.closed)return;u.type==="turn.completed"&&(this.state.lastUsage=u.usage,this.abort.clear(i)),(u.type==="turn.completed"||u.type==="error")&&(d=!0),yield u}}catch(u){if(this.state.closed)return;if(i.signal.aborted){this.abort.clear(i),d||(yield this.makeInterruptedTurnEvent());continue}yield{type:"error",error:u instanceof Error?u:new Error(String(u))};return}finally{this.abort.clear(i)}if(this.state.closed)return;if(i.signal.aborted){d||(yield this.makeInterruptedTurnEvent());continue}if(this.state.autoCompactThreshold!==void 0&&!this.state.closed){let u=this.state.lastUsage,p=qt(this.state.requestedModel);if(u!==null&&p>0){let f=$e(u);if(Pr(f,p,this.state.autoCompactThreshold))try{this.hookRegistry&&await this.hookRegistry.dispatch({event:"PreCompact",sessionId:this.initSessionId,trigger:"auto"}),await this.compact()}catch(m){if(!(m instanceof G))throw m}}}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}composeSystem(){this.state.userSystem&&(this.state.userSystem=Xn(this.state.userSystem));let e=this.systemPrefix,n=this.state.userSystem,r=[];e&&e.length>0&&r.push(...e),n&&n.length>0&&r.push({type:"text",text:n});let o=Ha(this.state.currentPermissionMode);o!==null&&r.push(o);let s=ja(this.state.currentPermissionMode);return s!==null&&r.push(s),r.length===0?null:Kn({baseUrl:this.baseUrl})?ku(r,Gn()):r}async interrupt(){this.abort.requestAbort("interrupted")}makeInterruptedTurnEvent(){return{type:"turn.completed",usage:{stopReason:"interrupted",resultSubtype:"interrupted",isError:!1},sessionId:this.initSessionId}}async setModel(e){e!==void 0&&e.length>0&&(this.state.requestedModel=e,this.state.currentModel=me(e)??e)}async setPermissionMode(e){this.state.currentPermissionMode=e;let n=Le(e);this.state.toolDispatcher.setAllowAll?.(n),this.onPermissionMode?.(e)}setCwd(e){if(this.state.toolDispatcher.setResolveBase?.(e),!this.cwdDependentsFactory)return;let{userSystem:n,dispatcher:r}=this.cwdDependentsFactory(e);this.state.userSystem=n,this.state.toolDispatcher=r}async supportedCommands(){return ui()}async supportedModels(){return KO.map(e=>({...e}))}async supportedAgents(){return[]}async getContextUsage(){let e=this.state.lastUsage,n=Rr(this.state.requestedModel),r;if(e&&n>0){let i=$e(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=Cr(e);return{tools:[],agents:[],isAutoCompactEnabled:this.state.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.mcpManager?this.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{subscriptionType:this.retry.authMode==="oauth"?"claude-subscription":"api-key"}}async reauth(){return this.retry.forceClientRefresh()}async rewindFiles(e,n){return{canRewind:!1,error:"anthropic-direct provider does not support file checkpoint rewind"}}async compact(){return Hb({state:this.state,abort:this.abort,retry:this.retry,initSessionId:this.initSessionId,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}listRewindTargets(){return Kb(this.state.messages)}async rewindConversation(e){return Gb({state:this.state,abort:this.abort},e)}close(){this.state.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed()}};var GO=t=>/opus-4-(7|[89])/.test(t),qO=t=>GO(t)||/(claude-)?(opus|sonnet)-5/.test(t),Bi=new Set,zO=.25;function cd(t,e){let n=qs(e),r=t.maxOutputTokens;if(typeof r=="number"&&Number.isFinite(r)&&r>0){let o=Math.floor(r);if(o>n){let s=`max:${e}:${o}`;return Bi.has(s)||(Bi.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${e} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function zb(t){if(!t||t.length===0)return;let e=[];for(let n of t)n.user.length>0&&e.push({role:"user",content:n.user}),n.assistant.length>0&&e.push({role:"assistant",content:n.assistant});return e.length>0?e:void 0}function dd(t,e,n){switch(t.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&qO(n))return{type:"adaptive",display:"summarized"};let r=Math.floor(e*zO),o=Math.max(1024,e-1-r),s=t.budgetTokens!==void 0&&Number.isFinite(t.budgetTokens)?Math.floor(t.budgetTokens):void 0,i=Math.min(Math.max(s??o,1024),o);if(s!==void 0&&s>o){let a=`think:${n??"default"}:${s}:${e}`;Bi.has(a)||(Bi.add(a),console.warn(`[afk] thinking budgetTokens ${s} leaves too little of max_tokens ${e} for the reply; clamping to ${o}.`))}return{type:"enabled",budget_tokens:i,display:"summarized"}}}}function ud(t,e){if(t!==void 0)return t;let n=e.toLowerCase();if(/(claude-)?(opus|sonnet)-(4-[678]|5)/.test(n))return"max"}function Jb(t,e,n){let r=hn(e,n?.cwd),o=fr(t.memoryStore,void 0,t.surface);for(let[a,l]of o)t.readOnlyMemory&&a!=="memory_search"||r.set(a,l);n?.runtimeStateSource&&r.set("get_runtime_state",on(n.runtimeStateSource));for(let a of t.customTools)r.has(a.schema.name)||r.set(a.schema.name,a.handler);if(t.mcpManager){t.getMcpToolsCache()||t.setMcpToolsCache(t.mcpManager.getMcpTools()),t.getMcpHandlersCache()||t.setMcpHandlersCache(t.mcpManager.getMcpHandlers());for(let[a,l]of t.getMcpHandlersCache())r.set(a,l)}let s=t.getMcpToolsCache()??[],i=n?.planExitControls;return i&&r.set(Ve,Vo(i)),new Pe({handlers:r,sessionGrantManager:t.sessionGrantManager,allowAll:Le(e),schemas:[...t.schemas,...s,...i?[Jo]:[]],hookRegistry:es(n?.hookRegistry,t.hookRegistry),permissions:ns(t.mcpManager?ts(t.permissions,t.mcpManager.getMcpToolWireNames()):t.permissions,t.customTools.map(a=>a.schema.name)),subagentExecutor:t.subagentExecutor,skillExecutor:t.skillExecutor,composeExecutor:t.composeExecutor,...t.canUseTool!==void 0?{canUseTool:t.canUseTool}:{},cwd:n?.cwd,readRoots:n?.readRoots,writeRoots:n?.writeRoots,...n?.env!==void 0?{env:n.env}:{},sessionId:n?.sessionId,parentSessionId:n?.parentSessionId,...n?.subagentId!==void 0?{subagentId:n.subagentId}:{},...n?.subagentToolOutputCapBytes!==void 0?{maxOutputBytes:n.subagentToolOutputCapBytes}:{},...n?.traceWriter?{traceWriter:n.traceWriter}:{},readOnlyBash:t.readOnlyBash})}var JO=null;function pd(){return JO}P();P();function Vb(t){let e=typeof t.baseUrl=="string"&&t.baseUrl.length>0,n=e?t.apiKey&&t.apiKey.length>0?t.apiKey:b.AFK_LOCAL_API_KEY||"local":t.apiKey&&t.apiKey.length>0?t.apiKey:b.ANTHROPIC_API_KEY||b.CLAUDE_CODE_OAUTH_TOKEN||"";return{localMode:e,token:n}}function Hi(t,e,n){let r=qn({cwd:e,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:n.surface,...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:n.workspace}),o=[t.toolBase];return t.userSystem&&o.push(t.userSystem),o.push(t.memoryPrompt),t.hotMemory.length>0&&o.push(t.hotMemory),o.push(r),t.manifest.length>0&&o.push(t.manifest),o.join(`
1069
1069
 
1070
- `)}function Yb(t){return e=>{let n=t.getCurrentCwd();if(t.sharedReadRoots&&n!==void 0&&n!==e){let s=t.sharedReadRoots.indexOf(n);s!==-1?t.sharedReadRoots[s]=e:t.sharedReadRoots.includes(e)||t.sharedReadRoots.push(e)}if(t.sharedWriteRoots&&n!==void 0&&n!==e){let s=t.sharedWriteRoots.indexOf(n);s!==-1?t.sharedWriteRoots[s]=e:t.sharedWriteRoots.includes(e)||t.sharedWriteRoots.push(e)}t.setCurrentCwd(e),t.subagentExecutor?.setCwd(e),t.skillExecutor?.setCwd(e),t.composeExecutor?.setCwd(e);let r=Hi(t.stableSystemPrefix,e,{surface:t.surface,sessionId:t.config.sessionId,depth:t.config.depth,maxDepth:t.config.maxDepth,workspace:t.runtimeStateSource.getWorkspace()}),o=t.buildDispatcher(t.getCurrentPermissionMode(),{cwd:e,readRoots:t.sharedReadRoots,writeRoots:t.sharedWriteRoots,...t.config.env!==void 0?{env:t.config.env}:{},sessionId:t.config.sessionId,parentSessionId:t.config.parentSessionId,traceWriter:t.config.traceWriter,runtimeStateSource:t.runtimeStateSource,hookRegistry:t.config.hookRegistry,planExitControls:t.config.planExitControls});return{userSystem:r,dispatcher:o}}}function Xb(t){let{config:e,surface:n}=t,r,o=zn({surface:n,cwd:e.cwd??process.cwd(),modelName:t.model,providerName:t.providerName,permissionMode:t.permissionMode,...e.sessionId!==void 0?{sessionId:e.sessionId}:{},...e.parentSessionId!==void 0?{parentSessionId:e.parentSessionId}:{},...e.depth!==void 0?{depth:e.depth}:{},...e.maxDepth!==void 0?{maxDepth:e.maxDepth}:{},...e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},getEnabledToolNames:()=>r instanceof Pe?r.toolDefs.map(l=>l.name):[],getMcpTools:t.getMcpTools,getSubagents:t.getSubagents}),s=$r({sessionId:e.sessionId,resume:e.resume,depth:e.depth,parentSessionId:e.parentSessionId,surface:n,memoized:t.getMintedSessionId()});t.setMintedSessionId(s.memoized),t.setPresenceSessionId(Br({depth:e.depth,parentSessionId:e.parentSessionId,sessionId:s.id,currentPresenceSessionId:t.getPresenceSessionId(),runtimeStateSource:o,surface:n,cwd:e.cwd,providerName:t.providerName,model:t.model})),r=t.externalTools?Jn(t.externalTools,o):t.buildDispatcher(t.permissionMode,{cwd:e.cwd,readRoots:t.sharedReadRoots,writeRoots:t.sharedWriteRoots,...e.env!==void 0?{env:e.env}:{},sessionId:e.sessionId,parentSessionId:e.parentSessionId,...e.subagentId!==void 0?{subagentId:e.subagentId}:{},...e.subagentToolOutputCapBytes!==void 0?{subagentToolOutputCapBytes:e.subagentToolOutputCapBytes}:{},traceWriter:e.traceWriter,runtimeStateSource:o,hookRegistry:e.hookRegistry,planExitControls:e.planExitControls});let i=r instanceof Pe?[...r.toolDefs]:[...Ie,Ne],a=e.isSkillDispatch?i.filter(l=>l.name!=="ask_question"&&l.name!=="terminal_font_size"):e.isNonInteractive?i.filter(l=>l.name!=="ask_question"):i;return{queryDispatcher:r,runtimeStateSource:o,toolDefs:a,resolvedSessionId:s.id}}var VO=new Set([429,503,529]);function fd(t,e=fetch,n,r){return!t&&!n&&!r?e:async(o,s)=>{let i=await e(o,s);if(r)try{r(i.headers)}catch{}if(VO.has(i.status)){let a=Jt({headers:i.headers});if(n)try{n({status:i.status,...a!==void 0?{retryAfterMs:a}:{}})}catch{}if(t){let l={status:i.status,reason:i.status===429?"rate-limit":"overloaded",source:"sdk-fetch"};a!==void 0&&(l.retryAfterMs=a),U(t,{phase:"rate_limit",...a!==void 0?{durationMs:a}:{},metadata:l})}}return i}}var ji=class{items=[];waiter=null;attempts=0;push(e){this.attempts+=1;let n={status:e.status,attempt:this.attempts,...e.retryAfterMs!==void 0?{retryAfterMs:e.retryAfterMs}:{}};this.items.push(n);let r=this.waiter;this.waiter=null,r&&r()}takeAll(){return this.items.length===0?[]:this.items.splice(0,this.items.length)}waitForItem(){return this.items.length>0?Promise.resolve():new Promise(e=>{this.waiter=e})}resetAttempts(){this.attempts=0}};function Qb(t){if(t===null)return;let e=Number(t);if(Number.isFinite(e))return Math.min(1,Math.max(0,e))}var YO=Date.UTC(2100,0,1)/1e3;function Zb(t){if(t===null)return;let e=Number(t);if(!(!Number.isFinite(e)||e<0||e>YO))return new Date(e*1e3)}function tw(t){try{let e=Qb(t.get("anthropic-ratelimit-unified-5h-utilization")),n=Zb(t.get("anthropic-ratelimit-unified-5h-reset")),r=Qb(t.get("anthropic-ratelimit-unified-7d-utilization")),o=Zb(t.get("anthropic-ratelimit-unified-7d-reset"));return e===void 0&&r===void 0?void 0:{...e!==void 0?{fiveHourUtilization:e}:{},...n!==void 0?{fiveHourResetsAt:n}:{},...r!==void 0?{sevenDayUtilization:r}:{},...o!==void 0?{sevenDayResetsAt:o}:{},observedAt:new Date}}catch{return}}var ew,XO=new Set;function Wi(t){return t===void 0?void 0:Math.round(t*100)}function nw(t){let e=ew,n=e===void 0||Wi(e.fiveHourUtilization)!==Wi(t.fiveHourUtilization)||Wi(e.sevenDayUtilization)!==Wi(t.sevenDayUtilization);if(ew=t,!!n)for(let r of XO)try{r()}catch{}}function rw(t){let{config:e,localMode:n,authMode:r,factory:o}=t,s=!n&&e.traceWriter?new ji:void 0,i=n?void 0:u=>{let p=tw(u);p!==void 0&&nw(p)},a=jn(t.token,r,e.baseUrl,n?void 0:fd(e.traceWriter,void 0,s?u=>s.push(u):void 0,i)),l=o?o(a):t.createClient(a),c=n?null:uu(r),d;return r==="oauth"&&!n&&(d=async()=>{let u=await Qa();if(!u)return null;let p=jn(u,"oauth",e.baseUrl,fd(e.traceWriter,void 0,s?f=>s.push(f):void 0,i));return o?o(p):t.createClient(p)}),{client:l,throttleQueue:s,systemPrefix:c,...d!==void 0?{tokenRefresher:d}:{}}}function ow(t){let{config:e,cwd:n}=t,r=t.hasSkillExecutor?pi(void 0,{cwd:n,...typeof e.skillDispatchName=="string"&&e.skillDispatchName.length>0?{excludeName:e.skillDispatchName}:{}}):"",o=Ks(e.isSkillDispatch),s=Gs(t.readOnlyMemory),i={surface:t.surface,sessionId:e.sessionId,depth:e.depth,maxDepth:e.maxDepth,workspace:t.runtimeStateSource.getWorkspace()},a={toolBase:o,memoryPrompt:s,hotMemory:e.hotMemory??"",manifest:r,userSystem:t.userSystem};return{stableSystemPrefix:a,toolSystemAppend:Hi(a,n,i)}}var Ki="anthropic-direct",sw="claude-sonnet-5",Et=class{name=Ki;externalTools;memoryStore;providerFactory;skillExecutor;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;composeExecutor;surface;declaredSurface;readOnlyMemory;readOnlyBash;mcpManager;customTools;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_currentCwd;_mcpToolsCache=null;_mcpHandlersCache=null;_presenceSessionId=null;_mintedSessionId=null;constructor(e={}){let n=[...Ie];e.subagentExecutor&&n.push(e.subagentExecutor.describeAgentTool?.()??Qe),e.skillExecutor&&n.push(gt),e.composeExecutor&&n.push(ht),e.readOnlyMemory===!0?n.push(ln):n.push(...yt),n.push(Ne);for(let r of e.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);if(this.memoryStore=e.memoryStore??new et,this.externalTools=e.tools,this.skillExecutor=e.skillExecutor,this.schemas=n,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.canUseTool=e.canUseTool,this.subagentExecutor=e.subagentExecutor,this.composeExecutor=e.composeExecutor,this.surface=e.surface??"cli",this.declaredSurface=e.surface,this.readOnlyMemory=e.readOnlyMemory===!0,this.readOnlyBash=e.readOnlyBash===!0,this.customTools=e.customTools??[],this.mcpManager=e.mcpManager,e.mcpManager){let r=e.mcpManager.onToolsRefreshed;e.mcpManager.onToolsRefreshed=o=>{this._mcpToolsCache=null,this._mcpHandlersCache=null,r?.(o)}}e.clientFactory&&(this.providerFactory=e.clientFactory)}buildDispatcher(e,n){return Jb({memoryStore:this.memoryStore,surface:this.surface,readOnlyMemory:this.readOnlyMemory,readOnlyBash:this.readOnlyBash,customTools:this.customTools,mcpManager:this.mcpManager,schemas:this.schemas,hookRegistry:this.hookRegistry,permissions:this.permissions,canUseTool:this.canUseTool,subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,sessionGrantManager:this,getMcpToolsCache:()=>this._mcpToolsCache,setMcpToolsCache:r=>{this._mcpToolsCache=r},getMcpHandlersCache:()=>this._mcpHandlersCache,setMcpHandlersCache:r=>{this._mcpHandlersCache=r}},e,n)}close(){this.memoryStore.close()}async complete(e){let n=e.apiKey&&e.apiKey.length>0?e.apiKey:b.ANTHROPIC_API_KEY||b.CLAUDE_CODE_OAUTH_TOKEN||"";if(!n)throw new Error(`${Ki} complete() requires an API key or OAuth token (config apiKey, ANTHROPIC_API_KEY, or CLAUDE_CODE_OAUTH_TOKEN)`);let r={token:n,model:e.model??sw,system:e.system,user:e.user,maxTokens:e.maxTokens??64};e.signal&&(r.signal=e.signal);let o=this.providerFactory??pd();return o&&(r.clientFactory=o),vu(r)}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e),e&&!this._currentCwd&&(this._currentCwd=e)}}grantManager=new mt({getReadRoots:()=>this._sharedReadRoots,getWriteRoots:()=>this._sharedWriteRoots,ensureInitialized:()=>this.ensureSharedRoots(),getProtectedRoot:()=>this._initialResolveBase,getAllowAll:()=>Le(this._currentPermissionMode)});addReadRoot(e,n="slash",r){this.grantManager.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.grantManager.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.grantManager.revokeRoot(e,n,r)}getGrants(){return this.grantManager.getGrants()}query(e){let n=e.config,{localMode:r,token:o}=Vb(n);if(!o||o.length===0)throw new Error(`${Ki} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=Co(o),{client:i,throttleQueue:a,systemPrefix:l,tokenRefresher:c}=rw({config:n,token:o,authMode:s,localMode:r,factory:this.providerFactory??pd(),createClient:v=>new QO(v)}),d=ZO(n.systemPrompt),u=typeof n.model=="string"&&n.model.length>0?me(n.model)??n.model:sw,p=cd(n,u),f=n.permissionMode??"default";this._currentPermissionMode=f,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let{queryDispatcher:m,runtimeStateSource:g,toolDefs:h,resolvedSessionId:y}=Xb({config:n,model:u,permissionMode:f,surface:this.surface,providerName:Ki,externalTools:this.externalTools,sharedReadRoots:this._sharedReadRoots,sharedWriteRoots:this._sharedWriteRoots,getMcpTools:()=>this.mcpManager?.getMcpTools()??[],getSubagents:()=>this.subagentExecutor?this.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]},getMintedSessionId:()=>this._mintedSessionId,setMintedSessionId:v=>{this._mintedSessionId=v},getPresenceSessionId:()=>this._presenceSessionId,setPresenceSessionId:v=>{this._presenceSessionId=v},buildDispatcher:(v,I)=>this.buildDispatcher(v,I)}),w=n.cwd||process.cwd(),{stableSystemPrefix:k,toolSystemAppend:S}=ow({config:n,cwd:w,surface:this.surface,readOnlyMemory:this.readOnlyMemory,hasSkillExecutor:!!this.skillExecutor,runtimeStateSource:g,userSystem:d});ru({prompt:e.prompt,options:{model:u,maxTokens:p,system:S},provenance:{systemPrompt:{source:n.systemPromptSource??"none",shape:typeof n.systemPrompt=="string"?"string":Array.isArray(n.systemPrompt)?"string[]":n.systemPrompt!=null?"preset":"undefined",...typeof n.systemPrompt=="string"?{length:n.systemPrompt.length}:{}},...n.apiKey?{apiKey:{source:"config"}}:{}}});let x=y,E=zb(n.resumeHistory),R=this.externalTools?void 0:Yb({stableSystemPrefix:k,config:n,surface:this.surface,runtimeStateSource:g,getCurrentCwd:()=>this._currentCwd,setCurrentCwd:v=>{this._currentCwd=v},getCurrentPermissionMode:()=>this._currentPermissionMode,sharedReadRoots:this._sharedReadRoots,sharedWriteRoots:this._sharedWriteRoots,subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,buildDispatcher:(v,I)=>this.buildDispatcher(v,I)}),O=ud(n.effort,u);return new $i({client:i,authMode:r?"api-key":s,promptStream:e.prompt,toolDispatcher:m,...x!==void 0?{sessionId:x}:{},...E!==void 0?{initialMessages:E}:{},model:u,requestedModel:typeof n.model=="string"&&n.model.length>0?n.model:u,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:p,tools:h,userSystem:S,systemPrefix:l,tokenRefresher:c,...n.thinking!==void 0?{thinking:dd(n.thinking,p,u)}:{},...O!==void 0?{effort:O}:{},...r?{baseUrl:n.baseUrl}:{},...n.traceWriter?{traceWriter:n.traceWriter}:{},...n.subagentId!==void 0?{subagentId:n.subagentId}:{},...n.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:n.autoResumeOnUsageLimit}:{},surface:this.declaredSurface,...n.maxToolUseIterations!==void 0?{maxToolUseIterations:n.maxToolUseIterations}:{},...R!==void 0?{cwdDependentsFactory:R}:{},onPermissionMode:v=>{this._currentPermissionMode=v},...this.mcpManager!==void 0?{mcpManager:this.mcpManager}:{},...bn(n.autoCompact)!==void 0?{autoCompactThreshold:bn(n.autoCompact)}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{},...a!==void 0?{throttleQueue:a}:{}})}};function ZO(t){if(t===void 0)return null;if(typeof t=="string")return t.length>0?t:null;if(typeof t=="object"&&t!==null&&"append"in t){let e=t.append;return e&&e.length>0?e:null}return null}var e0=new Et;P();var t0=new Set([...Object.keys(Ba),"auto"]);function n0(t){if(!t)return;let e=t.trim().toLowerCase();if(e){if(e==="anthropic"||e==="anthropic-direct")return"anthropic-direct";if(e==="openai"||e==="openai-compatible"||e==="openai-codex")return"openai-compatible"}}function J(t,e){let n=e?.explicit??b.AFK_PROVIDER,r=e?.openaiBaseUrl??b.AFK_OPENAI_BASE_URL,o=n0(n);if(o)return o;let s=Pt(t,e?.slots);if(s.provider==="anthropic")return"anthropic-direct";if(s.provider==="openai"||s.provider==="chatgpt-oauth")return"openai-compatible";let i=s.id.trim().toLowerCase();return i&&(t0.has(i)||i.startsWith("claude-")||i.startsWith("claude_")||i.startsWith("local-")||i.startsWith("local_"))?"anthropic-direct":i&&(i.startsWith("gpt-")||i.startsWith("gpt_")||Gt(i)||i.startsWith("codex-")||i.startsWith("codex_")||i==="codex"||i.startsWith("deepseek-")||i.startsWith("deepseek_")||i.startsWith("mistral-")||i.startsWith("mistral_")||i.startsWith("mixtral-")||i.startsWith("mixtral_")||i.startsWith("llama-")||i.startsWith("llama_")||i.startsWith("qwen-")||i.startsWith("qwen_")||i.includes("/"))||s.baseUrl&&s.baseUrl.trim()||r&&r.trim()?"openai-compatible":"anthropic-direct"}function Gi(t,e,n){let r=J(t,e),o=n?.customTools,s=n?.canUseTool,i={...o!==void 0&&o.length>0?{customTools:o}:{},...s!==void 0?{canUseTool:s}:{}};switch(r){case"openai-compatible":case"openai-codex":return new Ge(i);default:return new Et(i)}}var Rn=class{pendingResolve=null;bufferedMessages=[];getSessionId;constructor(e){this.getSessionId=e}pushUserMessage(e){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:e,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessages.push(e)}createIterable(){let e=this;return{[Symbol.asyncIterator](){return{next(){if(e.bufferedMessages.length>0){let n=e.bufferedMessages.shift(),r=e.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{e.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}};function qi(t,e){let n=e??nn(),r=rn(t.model,n);if(!r){t.forceChatgptOAuth=!1;return}let o=n[r],s=o.provider==="anthropic"?"anthropic-direct":o.provider==="openai"||o.provider==="chatgpt-oauth"?"openai-compatible":J(t.model,e?{slots:e}:void 0);t.forceChatgptOAuth=o.provider==="chatgpt-oauth",o.apiKey!==void 0?t.apiKey=o.apiKey:(s==="openai-compatible"||o.baseUrl!==void 0)&&(t.apiKey=void 0),o.baseUrl!==void 0&&(s==="openai-compatible"?t.openaiBaseUrl=o.baseUrl:t.baseUrl=o.baseUrl)}Z();function r0(t){return typeof t=="string"?t:t.map(e=>{let n=e;return n.type==="text"&&typeof n.text=="string"?n.text:""}).filter(e=>e.length>0).join(`
1070
+ `)}function Yb(t){return e=>{let n=t.getCurrentCwd();if(t.sharedReadRoots&&n!==void 0&&n!==e){let s=t.sharedReadRoots.indexOf(n);s!==-1?t.sharedReadRoots[s]=e:t.sharedReadRoots.includes(e)||t.sharedReadRoots.push(e)}if(t.sharedWriteRoots&&n!==void 0&&n!==e){let s=t.sharedWriteRoots.indexOf(n);s!==-1?t.sharedWriteRoots[s]=e:t.sharedWriteRoots.includes(e)||t.sharedWriteRoots.push(e)}t.setCurrentCwd(e),t.subagentExecutor?.setCwd(e),t.skillExecutor?.setCwd(e),t.composeExecutor?.setCwd(e);let r=Hi(t.stableSystemPrefix,e,{surface:t.surface,sessionId:t.config.sessionId,depth:t.config.depth,maxDepth:t.config.maxDepth,workspace:t.runtimeStateSource.getWorkspace()}),o=t.buildDispatcher(t.getCurrentPermissionMode(),{cwd:e,readRoots:t.sharedReadRoots,writeRoots:t.sharedWriteRoots,...t.config.env!==void 0?{env:t.config.env}:{},sessionId:t.config.sessionId,parentSessionId:t.config.parentSessionId,traceWriter:t.config.traceWriter,runtimeStateSource:t.runtimeStateSource,hookRegistry:t.config.hookRegistry,planExitControls:t.config.planExitControls});return{userSystem:r,dispatcher:o}}}function Xb(t){let{config:e,surface:n}=t,r,o=zn({surface:n,getCwd:t.getCwd,modelName:t.model,providerName:t.providerName,permissionMode:t.permissionMode,...e.sessionId!==void 0?{sessionId:e.sessionId}:{},...e.parentSessionId!==void 0?{parentSessionId:e.parentSessionId}:{},...e.depth!==void 0?{depth:e.depth}:{},...e.maxDepth!==void 0?{maxDepth:e.maxDepth}:{},...e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},getEnabledToolNames:()=>r instanceof Pe?r.toolDefs.map(l=>l.name):[],getMcpTools:t.getMcpTools,getSubagents:t.getSubagents}),s=$r({sessionId:e.sessionId,resume:e.resume,depth:e.depth,parentSessionId:e.parentSessionId,surface:n,memoized:t.getMintedSessionId()});t.setMintedSessionId(s.memoized),t.setPresenceSessionId(Br({depth:e.depth,parentSessionId:e.parentSessionId,sessionId:s.id,currentPresenceSessionId:t.getPresenceSessionId(),runtimeStateSource:o,surface:n,cwd:e.cwd,providerName:t.providerName,model:t.model})),r=t.externalTools?Jn(t.externalTools,o):t.buildDispatcher(t.permissionMode,{cwd:e.cwd,readRoots:t.sharedReadRoots,writeRoots:t.sharedWriteRoots,...e.env!==void 0?{env:e.env}:{},sessionId:e.sessionId,parentSessionId:e.parentSessionId,...e.subagentId!==void 0?{subagentId:e.subagentId}:{},...e.subagentToolOutputCapBytes!==void 0?{subagentToolOutputCapBytes:e.subagentToolOutputCapBytes}:{},traceWriter:e.traceWriter,runtimeStateSource:o,hookRegistry:e.hookRegistry,planExitControls:e.planExitControls});let i=r instanceof Pe?[...r.toolDefs]:[...Ie,Ne],a=e.isSkillDispatch?i.filter(l=>l.name!=="ask_question"&&l.name!=="terminal_font_size"):e.isNonInteractive?i.filter(l=>l.name!=="ask_question"):i;return{queryDispatcher:r,runtimeStateSource:o,toolDefs:a,resolvedSessionId:s.id}}var VO=new Set([429,503,529]);function fd(t,e=fetch,n,r){return!t&&!n&&!r?e:async(o,s)=>{let i=await e(o,s);if(r)try{r(i.headers)}catch{}if(VO.has(i.status)){let a=Jt({headers:i.headers});if(n)try{n({status:i.status,...a!==void 0?{retryAfterMs:a}:{}})}catch{}if(t){let l={status:i.status,reason:i.status===429?"rate-limit":"overloaded",source:"sdk-fetch"};a!==void 0&&(l.retryAfterMs=a),U(t,{phase:"rate_limit",...a!==void 0?{durationMs:a}:{},metadata:l})}}return i}}var ji=class{items=[];waiter=null;attempts=0;push(e){this.attempts+=1;let n={status:e.status,attempt:this.attempts,...e.retryAfterMs!==void 0?{retryAfterMs:e.retryAfterMs}:{}};this.items.push(n);let r=this.waiter;this.waiter=null,r&&r()}takeAll(){return this.items.length===0?[]:this.items.splice(0,this.items.length)}waitForItem(){return this.items.length>0?Promise.resolve():new Promise(e=>{this.waiter=e})}resetAttempts(){this.attempts=0}};function Qb(t){if(t===null)return;let e=Number(t);if(Number.isFinite(e))return Math.min(1,Math.max(0,e))}var YO=Date.UTC(2100,0,1)/1e3;function Zb(t){if(t===null)return;let e=Number(t);if(!(!Number.isFinite(e)||e<0||e>YO))return new Date(e*1e3)}function tw(t){try{let e=Qb(t.get("anthropic-ratelimit-unified-5h-utilization")),n=Zb(t.get("anthropic-ratelimit-unified-5h-reset")),r=Qb(t.get("anthropic-ratelimit-unified-7d-utilization")),o=Zb(t.get("anthropic-ratelimit-unified-7d-reset"));return e===void 0&&r===void 0?void 0:{...e!==void 0?{fiveHourUtilization:e}:{},...n!==void 0?{fiveHourResetsAt:n}:{},...r!==void 0?{sevenDayUtilization:r}:{},...o!==void 0?{sevenDayResetsAt:o}:{},observedAt:new Date}}catch{return}}var ew,XO=new Set;function Wi(t){return t===void 0?void 0:Math.round(t*100)}function nw(t){let e=ew,n=e===void 0||Wi(e.fiveHourUtilization)!==Wi(t.fiveHourUtilization)||Wi(e.sevenDayUtilization)!==Wi(t.sevenDayUtilization);if(ew=t,!!n)for(let r of XO)try{r()}catch{}}function rw(t){let{config:e,localMode:n,authMode:r,factory:o}=t,s=!n&&e.traceWriter?new ji:void 0,i=n?void 0:u=>{let p=tw(u);p!==void 0&&nw(p)},a=jn(t.token,r,e.baseUrl,n?void 0:fd(e.traceWriter,void 0,s?u=>s.push(u):void 0,i)),l=o?o(a):t.createClient(a),c=n?null:uu(r),d;return r==="oauth"&&!n&&(d=async()=>{let u=await Qa();if(!u)return null;let p=jn(u,"oauth",e.baseUrl,fd(e.traceWriter,void 0,s?f=>s.push(f):void 0,i));return o?o(p):t.createClient(p)}),{client:l,throttleQueue:s,systemPrefix:c,...d!==void 0?{tokenRefresher:d}:{}}}function ow(t){let{config:e,cwd:n}=t,r=t.hasSkillExecutor?pi(void 0,{cwd:n,...typeof e.skillDispatchName=="string"&&e.skillDispatchName.length>0?{excludeName:e.skillDispatchName}:{}}):"",o=Ks(e.isSkillDispatch),s=Gs(t.readOnlyMemory),i={surface:t.surface,sessionId:e.sessionId,depth:e.depth,maxDepth:e.maxDepth,workspace:t.runtimeStateSource.getWorkspace()},a={toolBase:o,memoryPrompt:s,hotMemory:e.hotMemory??"",manifest:r,userSystem:t.userSystem};return{stableSystemPrefix:a,toolSystemAppend:Hi(a,n,i)}}var Ki="anthropic-direct",sw="claude-sonnet-5",Et=class{name=Ki;externalTools;memoryStore;providerFactory;skillExecutor;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;composeExecutor;surface;declaredSurface;readOnlyMemory;readOnlyBash;mcpManager;customTools;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_currentCwd;_mcpToolsCache=null;_mcpHandlersCache=null;_presenceSessionId=null;_mintedSessionId=null;constructor(e={}){let n=[...Ie];e.subagentExecutor&&n.push(e.subagentExecutor.describeAgentTool?.()??Qe),e.skillExecutor&&n.push(gt),e.composeExecutor&&n.push(ht),e.readOnlyMemory===!0?n.push(ln):n.push(...yt),n.push(Ne);for(let r of e.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);if(this.memoryStore=e.memoryStore??new et,this.externalTools=e.tools,this.skillExecutor=e.skillExecutor,this.schemas=n,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.canUseTool=e.canUseTool,this.subagentExecutor=e.subagentExecutor,this.composeExecutor=e.composeExecutor,this.surface=e.surface??"cli",this.declaredSurface=e.surface,this.readOnlyMemory=e.readOnlyMemory===!0,this.readOnlyBash=e.readOnlyBash===!0,this.customTools=e.customTools??[],this.mcpManager=e.mcpManager,e.mcpManager){let r=e.mcpManager.onToolsRefreshed;e.mcpManager.onToolsRefreshed=o=>{this._mcpToolsCache=null,this._mcpHandlersCache=null,r?.(o)}}e.clientFactory&&(this.providerFactory=e.clientFactory)}buildDispatcher(e,n){return Jb({memoryStore:this.memoryStore,surface:this.surface,readOnlyMemory:this.readOnlyMemory,readOnlyBash:this.readOnlyBash,customTools:this.customTools,mcpManager:this.mcpManager,schemas:this.schemas,hookRegistry:this.hookRegistry,permissions:this.permissions,canUseTool:this.canUseTool,subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,sessionGrantManager:this,getMcpToolsCache:()=>this._mcpToolsCache,setMcpToolsCache:r=>{this._mcpToolsCache=r},getMcpHandlersCache:()=>this._mcpHandlersCache,setMcpHandlersCache:r=>{this._mcpHandlersCache=r}},e,n)}close(){this.memoryStore.close()}async complete(e){let n=e.apiKey&&e.apiKey.length>0?e.apiKey:b.ANTHROPIC_API_KEY||b.CLAUDE_CODE_OAUTH_TOKEN||"";if(!n)throw new Error(`${Ki} complete() requires an API key or OAuth token (config apiKey, ANTHROPIC_API_KEY, or CLAUDE_CODE_OAUTH_TOKEN)`);let r={token:n,model:e.model??sw,system:e.system,user:e.user,maxTokens:e.maxTokens??64};e.signal&&(r.signal=e.signal);let o=this.providerFactory??pd();return o&&(r.clientFactory=o),vu(r)}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e),e&&!this._currentCwd&&(this._currentCwd=e)}}grantManager=new mt({getReadRoots:()=>this._sharedReadRoots,getWriteRoots:()=>this._sharedWriteRoots,ensureInitialized:()=>this.ensureSharedRoots(),getProtectedRoot:()=>this._initialResolveBase,getAllowAll:()=>Le(this._currentPermissionMode)});addReadRoot(e,n="slash",r){this.grantManager.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.grantManager.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.grantManager.revokeRoot(e,n,r)}getGrants(){return this.grantManager.getGrants()}query(e){let n=e.config,{localMode:r,token:o}=Vb(n);if(!o||o.length===0)throw new Error(`${Ki} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=Co(o),{client:i,throttleQueue:a,systemPrefix:l,tokenRefresher:c}=rw({config:n,token:o,authMode:s,localMode:r,factory:this.providerFactory??pd(),createClient:v=>new QO(v)}),d=ZO(n.systemPrompt),u=typeof n.model=="string"&&n.model.length>0?me(n.model)??n.model:sw,p=cd(n,u),f=n.permissionMode??"default";this._currentPermissionMode=f,this.ensureSharedRoots(n.cwd),n.cwd&&(this._currentCwd=n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let{queryDispatcher:m,runtimeStateSource:g,toolDefs:h,resolvedSessionId:y}=Xb({config:n,model:u,permissionMode:f,surface:this.surface,providerName:Ki,externalTools:this.externalTools,sharedReadRoots:this._sharedReadRoots,sharedWriteRoots:this._sharedWriteRoots,getCwd:()=>this._currentCwd||n.cwd||process.cwd(),getMcpTools:()=>this.mcpManager?.getMcpTools()??[],getSubagents:()=>this.subagentExecutor?this.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]},getMintedSessionId:()=>this._mintedSessionId,setMintedSessionId:v=>{this._mintedSessionId=v},getPresenceSessionId:()=>this._presenceSessionId,setPresenceSessionId:v=>{this._presenceSessionId=v},buildDispatcher:(v,I)=>this.buildDispatcher(v,I)}),w=n.cwd||process.cwd(),{stableSystemPrefix:k,toolSystemAppend:S}=ow({config:n,cwd:w,surface:this.surface,readOnlyMemory:this.readOnlyMemory,hasSkillExecutor:!!this.skillExecutor,runtimeStateSource:g,userSystem:d});ru({prompt:e.prompt,options:{model:u,maxTokens:p,system:S},provenance:{systemPrompt:{source:n.systemPromptSource??"none",shape:typeof n.systemPrompt=="string"?"string":Array.isArray(n.systemPrompt)?"string[]":n.systemPrompt!=null?"preset":"undefined",...typeof n.systemPrompt=="string"?{length:n.systemPrompt.length}:{}},...n.apiKey?{apiKey:{source:"config"}}:{}}});let x=y,E=zb(n.resumeHistory),R=this.externalTools?void 0:Yb({stableSystemPrefix:k,config:n,surface:this.surface,runtimeStateSource:g,getCurrentCwd:()=>this._currentCwd,setCurrentCwd:v=>{this._currentCwd=v},getCurrentPermissionMode:()=>this._currentPermissionMode,sharedReadRoots:this._sharedReadRoots,sharedWriteRoots:this._sharedWriteRoots,subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,buildDispatcher:(v,I)=>this.buildDispatcher(v,I)}),O=ud(n.effort,u);return new $i({client:i,authMode:r?"api-key":s,promptStream:e.prompt,toolDispatcher:m,...x!==void 0?{sessionId:x}:{},...E!==void 0?{initialMessages:E}:{},model:u,requestedModel:typeof n.model=="string"&&n.model.length>0?n.model:u,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:p,tools:h,userSystem:S,systemPrefix:l,tokenRefresher:c,...n.thinking!==void 0?{thinking:dd(n.thinking,p,u)}:{},...O!==void 0?{effort:O}:{},...r?{baseUrl:n.baseUrl}:{},...n.traceWriter?{traceWriter:n.traceWriter}:{},...n.subagentId!==void 0?{subagentId:n.subagentId}:{},...n.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:n.autoResumeOnUsageLimit}:{},surface:this.declaredSurface,...n.maxToolUseIterations!==void 0?{maxToolUseIterations:n.maxToolUseIterations}:{},...R!==void 0?{cwdDependentsFactory:R}:{},onPermissionMode:v=>{this._currentPermissionMode=v},...this.mcpManager!==void 0?{mcpManager:this.mcpManager}:{},...bn(n.autoCompact)!==void 0?{autoCompactThreshold:bn(n.autoCompact)}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{},...a!==void 0?{throttleQueue:a}:{}})}};function ZO(t){if(t===void 0)return null;if(typeof t=="string")return t.length>0?t:null;if(typeof t=="object"&&t!==null&&"append"in t){let e=t.append;return e&&e.length>0?e:null}return null}var e0=new Et;P();var t0=new Set([...Object.keys(Ba),"auto"]);function n0(t){if(!t)return;let e=t.trim().toLowerCase();if(e){if(e==="anthropic"||e==="anthropic-direct")return"anthropic-direct";if(e==="openai"||e==="openai-compatible"||e==="openai-codex")return"openai-compatible"}}function J(t,e){let n=e?.explicit??b.AFK_PROVIDER,r=e?.openaiBaseUrl??b.AFK_OPENAI_BASE_URL,o=n0(n);if(o)return o;let s=Pt(t,e?.slots);if(s.provider==="anthropic")return"anthropic-direct";if(s.provider==="openai"||s.provider==="chatgpt-oauth")return"openai-compatible";let i=s.id.trim().toLowerCase();return i&&(t0.has(i)||i.startsWith("claude-")||i.startsWith("claude_")||i.startsWith("local-")||i.startsWith("local_"))?"anthropic-direct":i&&(i.startsWith("gpt-")||i.startsWith("gpt_")||Gt(i)||i.startsWith("codex-")||i.startsWith("codex_")||i==="codex"||i.startsWith("deepseek-")||i.startsWith("deepseek_")||i.startsWith("mistral-")||i.startsWith("mistral_")||i.startsWith("mixtral-")||i.startsWith("mixtral_")||i.startsWith("llama-")||i.startsWith("llama_")||i.startsWith("qwen-")||i.startsWith("qwen_")||i.includes("/"))||s.baseUrl&&s.baseUrl.trim()||r&&r.trim()?"openai-compatible":"anthropic-direct"}function Gi(t,e,n){let r=J(t,e),o=n?.customTools,s=n?.canUseTool,i={...o!==void 0&&o.length>0?{customTools:o}:{},...s!==void 0?{canUseTool:s}:{}};switch(r){case"openai-compatible":case"openai-codex":return new Ge(i);default:return new Et(i)}}var Rn=class{pendingResolve=null;bufferedMessages=[];getSessionId;constructor(e){this.getSessionId=e}pushUserMessage(e){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:e,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessages.push(e)}createIterable(){let e=this;return{[Symbol.asyncIterator](){return{next(){if(e.bufferedMessages.length>0){let n=e.bufferedMessages.shift(),r=e.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{e.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}};function qi(t,e){let n=e??nn(),r=rn(t.model,n);if(!r){t.forceChatgptOAuth=!1;return}let o=n[r],s=o.provider==="anthropic"?"anthropic-direct":o.provider==="openai"||o.provider==="chatgpt-oauth"?"openai-compatible":J(t.model,e?{slots:e}:void 0);t.forceChatgptOAuth=o.provider==="chatgpt-oauth",o.apiKey!==void 0?t.apiKey=o.apiKey:(s==="openai-compatible"||o.baseUrl!==void 0)&&(t.apiKey=void 0),o.baseUrl!==void 0&&(s==="openai-compatible"?t.openaiBaseUrl=o.baseUrl:t.baseUrl=o.baseUrl)}Z();function r0(t){return typeof t=="string"?t:t.map(e=>{let n=e;return n.type==="text"&&typeof n.text=="string"?n.text:""}).filter(e=>e.length>0).join(`
1071
1071
  `)}function o0(t,e,n,r){let o=n&&n!==r?` (provider ${n} \u2192 ${r})`:"";return`[System context \u2014 not from the user. Your model was switched at the start of this turn: ${t} \u2192 ${e}${o}. Earlier turns in this conversation were produced by ${t}; the history carried across the switch is plain text only, so any prior tool calls and extended reasoning are now prose \u2014 treat their structure as lost, not authoritative.]`}function s0(t,e){return typeof t=="string"?t.length>0?`${e}
1072
1072
 
1073
1073
  ${t}`:e:[{type:"text",text:e},...t]}var zi=class{outerIterator;baseConfig;deps;currentModel;currentPermissionMode;currentCwd;startupFamily;active;activeModel;closed=!1;shadowHistory;pendingUserText;pendingAssistantText="";lastSessionId;constructor(e,n){this.outerIterator=e.prompt[Symbol.asyncIterator](),this.baseConfig=e.config,this.deps=n,this.currentModel=typeof e.config.model=="string"?e.config.model:void 0,this.currentPermissionMode=e.config.permissionMode,this.currentCwd=e.config.cwd,this.startupFamily=n.providerNameForModel(this.currentModel),this.shadowHistory=[...e.config.resumeHistory??[]]}resolveInner(e){let n=this.deps.resolveProvider(e),r={...this.baseConfig};r.model=e??this.baseConfig.model;let o=n.name===this.startupFamily&&this.baseConfig.apiKey!==void 0?this.baseConfig.apiKey:this.deps.resolveApiKey(e);o!==void 0?r.apiKey=o:delete r.apiKey,qi(r);let s=[n.name,r.baseUrl??"",r.openaiBaseUrl??"",r.apiKey??"",r.forceChatgptOAuth?"chatgpt-oauth":""].join("\0");return{provider:n,innerConfig:r,signature:s}}buildInner(e,n){let{provider:r,innerConfig:o,signature:s}=this.resolveInner(e),i=new Rn(()=>this.lastSessionId);this.currentPermissionMode!==void 0&&(o.permissionMode=this.currentPermissionMode),this.currentCwd!==void 0&&(o.cwd=this.currentCwd),n&&(o.resumeHistory=[...this.shadowHistory]);let a=r.query({prompt:i.createIterable(),config:o});return{family:r.name,signature:s,query:a,iterator:a[Symbol.asyncIterator](),input:i}}async closeActive(){let e=this.active;if(e){this.active=void 0;try{await e.iterator.return?.(void 0)}catch{}try{await e.query.close()}catch{}}}observeEvent(e){e.type==="assistant.message"&&(this.pendingAssistantText+=(this.pendingAssistantText?`