agent-afk 5.115.3 → 5.115.4

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/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var JZ=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var Fo=(e,t)=>{for(var n in t)JZ(e,n,{get:t[n],enumerable:!0})};function dt(){let e=k.AFK_PLAIN_OUTPUT;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"}function Da(e){return $d.find(t=>t.name===e)}function k0(e){return $d.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function Dd(e){return process.env[e]!==void 0}function eT(e){let t=process.env[e];return t===void 0||t===""?void 0:t}var $d,k,j=y(()=>{"use strict";$d=[{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_CONCURRENT_SAFE_TOOL_CALLS",description:"Maximum concurrency-safe tool calls run simultaneously within one dispatcher batch. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"4",category:"model"},{name:"AFK_MAX_CONCURRENT_SUBAGENT_CALLS",description:"Maximum subagent calls run simultaneously from one compose/DAG layer or skill wave. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"2",category:"model"},{name:"AFK_MAX_CONCURRENT_BACKGROUND_JOBS",description:"Maximum background subagent jobs running simultaneously in one registry. Default 10; accepted range 1-64; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"10",example:"5",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. When unset, falls back to the model output ceiling (AFK's own per-model limit, 64k\u2013128k \u2014 NOT a small provider default), so every request advertises the full ceiling by default. An over-ceiling value is clamped down with a warning.",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-ROUND time-to-first-token budget (ms) for the anthropic-direct streaming loop. Bounds how long a round 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. The budget is divided into 3 shorter first-byte ATTEMPTS (each ~2/3 of this value, so the worst-case wall time per round is unchanged from the previous 2-attempt regime while a transient stall gets 3 chances instead of 2). NOTE: a request whose FIRST token takes longer than the per-attempt bound \u2014 e.g. a very large opus_1m prefill \u2014 is aborted and re-driven, then surfaces as an error once the budget is spent (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), i.e. 3 \xD7 120s. 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_PROMPT",description:"Enable LLM-generated empty-prompt suggestions \u2014 a proposed next action shown as ghost text when the prompt is blank, accepted with Tab or Right-arrow. Fires only after a turn has completed in the session: the startup prompt (and the prompt right after /clear) is left clean because there is no session context to ground a proposal in. Set to 1/true/yes/on to activate. Off by default. Requires AFK_SUGGEST_ENABLED (it reuses the same suggestion model and provider).",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:"TMUX",description:"OS-level tmux session identifier. Set automatically by tmux to the socket path and session info (e.g. /tmp/tmux-501/default,12345,0) inside any tmux pane. Not set by AFK. Read by configureColor() to detect a tmux environment; for truecolor support on Node \u2264 24, set FORCE_COLOR=3 in your shell or ~/.afk/config/afk.env.",type:"string",required:!1,example:"/tmp/tmux-501/default,12345,0",category:"process"},{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_WEB_PORT",description:"Port for the `afk web` browser surface. Defaults to 4141; falls back to an ephemeral port when taken. Overridden by --port.",type:"number",required:!1,example:"4141",category:"daemon"},{name:"AFK_WEB_HOST",description:"Bind address for the `afk web` browser surface. Defaults to 127.0.0.1. Unlike the daemon control surface, a non-loopback bind is REFUSED unless AFK_WEB_TOKEN (or --token) is also set, because this surface can submit prompts and approve tool use. Overridden by --host.",type:"string",required:!1,example:"127.0.0.1",category:"daemon"},{name:"AFK_WEB_TOKEN",description:"Bearer token for the `afk web` surface. When unset, a random per-run token is minted and printed in the startup URL. Setting this explicitly is also what permits a non-loopback bind.",type:"string",required:!1,category:"daemon",secret:!0},{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_GOBLIN_MASCOT",description:"Reacting goblin mini-sprite in the reserved footer band while the agent runs tools (3 rows, animated). 1 = on, unset/0 = off (default). Claims terminal rows, so it is opt-in.",type:"boolean",required:!1,example:"1",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 | umber | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark; umber matches the Umber terminal, is dark-only, and is never chosen by auto. 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:"AFK_TEXT_MEASURE",description:"Maximum line length (columns) for unbordered streamed text in the interactive REPL: assistant prose, thinking blocks, tool-lane text, and subagent text. Display-only \u2014 affects wrapping, never behavior. Bordered elements (cards, error boxes) already cap at 100; this applies the same ceiling to the unbordered surfaces, which previously scaled to the full terminal width. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable capping and restore full-width wrapping. Unparseable or below-minimum values fall back to the default. No-op on terminals at or below the measure, so narrow terminals are unaffected.",type:"string",required:!1,default:"100",example:"full",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:"COLORTERM",description:"OS-level terminal color-depth hint. Accepted values: truecolor or 24bit (24-bit color), 256color (256-color). Set by the outer terminal emulator, not by AFK. Read by chalk's supports-color to set its initial color level; also read by configureColor() to recommend FORCE_COLOR=3 for tmux truecolor users on Node \u2264 24.",type:"string",required:!1,example:"truecolor",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_WITNESS_RETENTION_DISABLE",description:"Disable the witness-tree retention sweep entirely, so no session directory is ever evicted.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_MAX_AGE_DAYS",description:"Evict a witness session directory once its newest content is older than this many days. Default 30.",type:"number",required:!1,default:"30",category:"debug"},{name:"AFK_WITNESS_MAX_BYTES",description:"Aggregate byte cap for the witness tree; oldest session directories are evicted first once exceeded. Default 2147483648 (2 GiB).",type:"number",required:!1,default:"2147483648",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:"AFK_CAPTURE_SUBAGENT_OUTPUT",description:"Opt-in: when set to 1, a subagent's conversational OUTPUT (assistant text plus each tool call with its arguments) is appended incrementally to a redacted markdown transcript under state/witness/<label>/outputs/. Flushed at every tool-call boundary, so a child killed by a timeout still leaves a usable partial record \u2014 the case where final-message capture yields nothing. Off by default for the same reasons as AFK_CAPTURE_SUBAGENT_PROMPTS (unpruned witness tree, best-effort regex redaction).",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"}],k={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_CONCURRENT_BACKGROUND_JOBS(){return process.env.AFK_MAX_CONCURRENT_BACKGROUND_JOBS},get AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS(){return process.env.AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS},get AFK_MAX_CONCURRENT_SUBAGENT_CALLS(){return process.env.AFK_MAX_CONCURRENT_SUBAGENT_CALLS},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_PROMPT(){return process.env.AFK_SUGGEST_PROMPT},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 TMUX(){return process.env.TMUX},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_WEB_PORT(){return process.env.AFK_WEB_PORT},get AFK_WEB_HOST(){return process.env.AFK_WEB_HOST},get AFK_WEB_TOKEN(){return process.env.AFK_WEB_TOKEN},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_GOBLIN_MASCOT(){return process.env.AFK_GOBLIN_MASCOT},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 AFK_TEXT_MEASURE(){return process.env.AFK_TEXT_MEASURE},get COLORFGBG(){return process.env.COLORFGBG},get COLORTERM(){return process.env.COLORTERM},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_WITNESS_RETENTION_DISABLE(){return process.env.AFK_WITNESS_RETENTION_DISABLE},get AFK_WITNESS_MAX_AGE_DAYS(){return process.env.AFK_WITNESS_MAX_AGE_DAYS},get AFK_WITNESS_MAX_BYTES(){return process.env.AFK_WITNESS_MAX_BYTES},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 AFK_CAPTURE_SUBAGENT_OUTPUT(){return process.env.AFK_CAPTURE_SUBAGENT_OUTPUT},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 t of $d){if(!t.secret)continue;let n=Object.getOwnPropertyDescriptor(k,t.name);n&&Object.defineProperty(k,t.name,{...n,enumerable:!1})}})()});import{existsSync as T0,mkdirSync as YZ,renameSync as XZ,cpSync as QZ,rmSync as ZZ}from"fs";import{join as te,dirname as kf,basename as eee,isAbsolute as tT}from"path";import{homedir as nT}from"os";import{fileURLToPath as x0}from"url";function ve(){let e=k.AFK_HOME;if(e!==void 0&&e!==""){if(!tT(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return te(nT(),".afk")}function Pt(){let e=k.AFK_FRAMEWORK_DIR;if(e!==void 0&&e!==""){if(!tT(e)||e==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${e}`);return e}return te(ve(),"agent-framework")}function pr(){return te(Pt(),"forge-telemetry.jsonl")}function A0(){return te(Pt(),"routing-decisions.jsonl")}function C0(){return te(Pt(),"briefs")}function _0(){return te(Pt(),"facets")}function Fd(){return te(ve(),"skills")}function Je(){return te(ve(),"plugins")}function I0(e=process.cwd()){return te(e,".afk")}function Tf(e=process.cwd()){return te(I0(e),"skills")}function Ef(e=process.cwd()){return te(I0(e),"plugins")}function Rf(e=process.cwd()){return te(e,".afk","plans")}function Te(){return te(Je(),".index.json")}function rT(){return te(Hn(),"schedules.json")}function Jr(){return te(Je(),"cache")}function Ld(e){return te(Jr(),e)}function Fa(){let e=x0(import.meta.url),t=kf(e);return te(t,"bundled-plugins")}function P0(){let e=x0(import.meta.url),t=kf(e);return te(t,"web-ui-assets")}function Hn(){return te(ve(),"config")}function Ee(){let e=k.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!tT(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return te(ve(),"state")}function La(){return te(ve(),"cache")}function Lo(){return te(ve(),"logs")}function tt(){return te(Ee(),"sessions")}function xf(){return te(Ee(),"presence")}function oT(){return te(Ee(),"todos")}function Nd(){return te(Ee(),"transcripts")}function Af(){return te(Ee(),"memory")}function Mt(){return te(Ee(),"queue")}function Cf(){return te(Ee(),"session-grants.jsonl")}function Bd(){return te(Hn(),"permissions.json")}function M0(){return te(ve(),"farms")}function iT(e){return te(M0(),e)}function _f(e){if(!tee.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function Wn(){return te(Ee(),"witness")}function sn(e){return _f(e),te(Wn(),e)}function O0(e){return te(sn(e),"inbound-attachments")}function $0(e){return te(sn(e),"prompts")}function D0(e){return te(sn(e),"outputs")}function Na(e){return!e||e.startsWith("in-memory:")?null:eee(kf(e))}function sT(){return te(Ee(),"receipts")}function If(e="default"){return te(Ee(),"daemon",`agent-afk@${e}`)}function F0(){return te(Ee(),"worktree-sweep.lock")}function Pf(){return te(Ee(),"worktree-roots.json")}function jt(){return te(Hn(),"afk.env")}function an(){return te(Hn(),"afk.config.json")}function aT(){return te(Hn(),"settings.json")}function L0(e=process.cwd()){return te(e,".afk","settings.json")}function Mf(){return te(ve(),"AFK.md")}function Of(e=process.cwd()){return te(e,"AFK.md")}function N0(){return te(nT(),".afk.env")}function $f(){return te(nT(),".afk.config.json")}function nee(){return te(ve(),"sessions")}function ree(){return te(ve(),"todos")}function oee(){return te(ve(),"transcripts")}function lT(e,t){if(e!==t&&T0(e)&&!T0(t))try{YZ(kf(t),{recursive:!0});try{XZ(e,t)}catch(n){if(n.code==="EXDEV")try{QZ(e,t,{recursive:!0}),ZZ(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
2
+ var JZ=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var Fo=(e,t)=>{for(var n in t)JZ(e,n,{get:t[n],enumerable:!0})};function dt(){let e=k.AFK_PLAIN_OUTPUT;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"}function Da(e){return $d.find(t=>t.name===e)}function k0(e){return $d.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function Dd(e){return process.env[e]!==void 0}function eT(e){let t=process.env[e];return t===void 0||t===""?void 0:t}var $d,k,j=y(()=>{"use strict";$d=[{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_CONCURRENT_SAFE_TOOL_CALLS",description:"Maximum concurrency-safe tool calls run simultaneously within one dispatcher batch. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"4",category:"model"},{name:"AFK_MAX_CONCURRENT_SUBAGENT_CALLS",description:"Maximum subagent calls run simultaneously from one compose/DAG layer or skill wave. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"2",category:"model"},{name:"AFK_MAX_CONCURRENT_BACKGROUND_JOBS",description:"Maximum background subagent jobs running simultaneously in one registry. Default 10; accepted range 1-64; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"10",example:"5",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. When unset, falls back to the model output ceiling (AFK's own per-model limit, 64k\u2013128k \u2014 NOT a small provider default), so every request advertises the full ceiling by default. An over-ceiling value is clamped down with a warning.",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-ROUND time-to-first-token budget (ms) for the anthropic-direct streaming loop. Bounds how long a round 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. The budget is divided into 3 shorter first-byte ATTEMPTS (each ~2/3 of this value, so the worst-case wall time per round is unchanged from the previous 2-attempt regime while a transient stall gets 3 chances instead of 2). NOTE: a request whose FIRST token takes longer than the per-attempt bound \u2014 e.g. a very large opus_1m prefill \u2014 is aborted and re-driven, then surfaces as an error once the budget is spent (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), i.e. 3 \xD7 120s. 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_PROMPT",description:"Enable LLM-generated empty-prompt suggestions \u2014 a proposed next action shown as ghost text when the prompt is blank, accepted with Tab or Right-arrow. Fires only after a turn has completed in the session: the startup prompt (and the prompt right after /clear) is left clean because there is no session context to ground a proposal in. Set to 1/true/yes/on to activate. Off by default. Requires AFK_SUGGEST_ENABLED (it reuses the same suggestion model and provider).",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 | max | 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:"TMUX",description:"OS-level tmux session identifier. Set automatically by tmux to the socket path and session info (e.g. /tmp/tmux-501/default,12345,0) inside any tmux pane. Not set by AFK. Read by configureColor() to detect a tmux environment; for truecolor support on Node \u2264 24, set FORCE_COLOR=3 in your shell or ~/.afk/config/afk.env.",type:"string",required:!1,example:"/tmp/tmux-501/default,12345,0",category:"process"},{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_WEB_PORT",description:"Port for the `afk web` browser surface. Defaults to 4141; falls back to an ephemeral port when taken. Overridden by --port.",type:"number",required:!1,example:"4141",category:"daemon"},{name:"AFK_WEB_HOST",description:"Bind address for the `afk web` browser surface. Defaults to 127.0.0.1. Unlike the daemon control surface, a non-loopback bind is REFUSED unless AFK_WEB_TOKEN (or --token) is also set, because this surface can submit prompts and approve tool use. Overridden by --host.",type:"string",required:!1,example:"127.0.0.1",category:"daemon"},{name:"AFK_WEB_TOKEN",description:"Bearer token for the `afk web` surface. When unset, a random per-run token is minted and printed in the startup URL. Setting this explicitly is also what permits a non-loopback bind.",type:"string",required:!1,category:"daemon",secret:!0},{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_GOBLIN_MASCOT",description:"Reacting goblin mini-sprite in the reserved footer band while the agent runs tools (3 rows, animated). 1 = on, unset/0 = off (default). Claims terminal rows, so it is opt-in.",type:"boolean",required:!1,example:"1",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 | umber | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark; umber matches the Umber terminal, is dark-only, and is never chosen by auto. 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:"AFK_TEXT_MEASURE",description:"Maximum line length (columns) for unbordered streamed text in the interactive REPL: assistant prose, thinking blocks, tool-lane text, and subagent text. Display-only \u2014 affects wrapping, never behavior. Bordered elements (cards, error boxes) already cap at 100; this applies the same ceiling to the unbordered surfaces, which previously scaled to the full terminal width. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable capping and restore full-width wrapping. Unparseable or below-minimum values fall back to the default. No-op on terminals at or below the measure, so narrow terminals are unaffected.",type:"string",required:!1,default:"100",example:"full",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:"COLORTERM",description:"OS-level terminal color-depth hint. Accepted values: truecolor or 24bit (24-bit color), 256color (256-color). Set by the outer terminal emulator, not by AFK. Read by chalk's supports-color to set its initial color level; also read by configureColor() to recommend FORCE_COLOR=3 for tmux truecolor users on Node \u2264 24.",type:"string",required:!1,example:"truecolor",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_WITNESS_RETENTION_DISABLE",description:"Disable the witness-tree retention sweep entirely, so no session directory is ever evicted.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_MAX_AGE_DAYS",description:"Evict a witness session directory once its newest content is older than this many days. Default 30.",type:"number",required:!1,default:"30",category:"debug"},{name:"AFK_WITNESS_MAX_BYTES",description:"Aggregate byte cap for the witness tree; oldest session directories are evicted first once exceeded. Default 2147483648 (2 GiB).",type:"number",required:!1,default:"2147483648",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:"AFK_CAPTURE_SUBAGENT_OUTPUT",description:"Opt-in: when set to 1, a subagent's conversational OUTPUT (assistant text plus each tool call with its arguments) is appended incrementally to a redacted markdown transcript under state/witness/<label>/outputs/. Flushed at every tool-call boundary, so a child killed by a timeout still leaves a usable partial record \u2014 the case where final-message capture yields nothing. Off by default for the same reasons as AFK_CAPTURE_SUBAGENT_PROMPTS (unpruned witness tree, best-effort regex redaction).",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"}],k={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_CONCURRENT_BACKGROUND_JOBS(){return process.env.AFK_MAX_CONCURRENT_BACKGROUND_JOBS},get AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS(){return process.env.AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS},get AFK_MAX_CONCURRENT_SUBAGENT_CALLS(){return process.env.AFK_MAX_CONCURRENT_SUBAGENT_CALLS},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_PROMPT(){return process.env.AFK_SUGGEST_PROMPT},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 TMUX(){return process.env.TMUX},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_WEB_PORT(){return process.env.AFK_WEB_PORT},get AFK_WEB_HOST(){return process.env.AFK_WEB_HOST},get AFK_WEB_TOKEN(){return process.env.AFK_WEB_TOKEN},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_GOBLIN_MASCOT(){return process.env.AFK_GOBLIN_MASCOT},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 AFK_TEXT_MEASURE(){return process.env.AFK_TEXT_MEASURE},get COLORFGBG(){return process.env.COLORFGBG},get COLORTERM(){return process.env.COLORTERM},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_WITNESS_RETENTION_DISABLE(){return process.env.AFK_WITNESS_RETENTION_DISABLE},get AFK_WITNESS_MAX_AGE_DAYS(){return process.env.AFK_WITNESS_MAX_AGE_DAYS},get AFK_WITNESS_MAX_BYTES(){return process.env.AFK_WITNESS_MAX_BYTES},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 AFK_CAPTURE_SUBAGENT_OUTPUT(){return process.env.AFK_CAPTURE_SUBAGENT_OUTPUT},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 t of $d){if(!t.secret)continue;let n=Object.getOwnPropertyDescriptor(k,t.name);n&&Object.defineProperty(k,t.name,{...n,enumerable:!1})}})()});import{existsSync as T0,mkdirSync as YZ,renameSync as XZ,cpSync as QZ,rmSync as ZZ}from"fs";import{join as te,dirname as kf,basename as eee,isAbsolute as tT}from"path";import{homedir as nT}from"os";import{fileURLToPath as x0}from"url";function ve(){let e=k.AFK_HOME;if(e!==void 0&&e!==""){if(!tT(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return te(nT(),".afk")}function Pt(){let e=k.AFK_FRAMEWORK_DIR;if(e!==void 0&&e!==""){if(!tT(e)||e==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${e}`);return e}return te(ve(),"agent-framework")}function pr(){return te(Pt(),"forge-telemetry.jsonl")}function A0(){return te(Pt(),"routing-decisions.jsonl")}function C0(){return te(Pt(),"briefs")}function _0(){return te(Pt(),"facets")}function Fd(){return te(ve(),"skills")}function Je(){return te(ve(),"plugins")}function I0(e=process.cwd()){return te(e,".afk")}function Tf(e=process.cwd()){return te(I0(e),"skills")}function Ef(e=process.cwd()){return te(I0(e),"plugins")}function Rf(e=process.cwd()){return te(e,".afk","plans")}function Te(){return te(Je(),".index.json")}function rT(){return te(Hn(),"schedules.json")}function Jr(){return te(Je(),"cache")}function Ld(e){return te(Jr(),e)}function Fa(){let e=x0(import.meta.url),t=kf(e);return te(t,"bundled-plugins")}function P0(){let e=x0(import.meta.url),t=kf(e);return te(t,"web-ui-assets")}function Hn(){return te(ve(),"config")}function Ee(){let e=k.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!tT(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return te(ve(),"state")}function La(){return te(ve(),"cache")}function Lo(){return te(ve(),"logs")}function tt(){return te(Ee(),"sessions")}function xf(){return te(Ee(),"presence")}function oT(){return te(Ee(),"todos")}function Nd(){return te(Ee(),"transcripts")}function Af(){return te(Ee(),"memory")}function Mt(){return te(Ee(),"queue")}function Cf(){return te(Ee(),"session-grants.jsonl")}function Bd(){return te(Hn(),"permissions.json")}function M0(){return te(ve(),"farms")}function iT(e){return te(M0(),e)}function _f(e){if(!tee.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function Wn(){return te(Ee(),"witness")}function sn(e){return _f(e),te(Wn(),e)}function O0(e){return te(sn(e),"inbound-attachments")}function $0(e){return te(sn(e),"prompts")}function D0(e){return te(sn(e),"outputs")}function Na(e){return!e||e.startsWith("in-memory:")?null:eee(kf(e))}function sT(){return te(Ee(),"receipts")}function If(e="default"){return te(Ee(),"daemon",`agent-afk@${e}`)}function F0(){return te(Ee(),"worktree-sweep.lock")}function Pf(){return te(Ee(),"worktree-roots.json")}function jt(){return te(Hn(),"afk.env")}function an(){return te(Hn(),"afk.config.json")}function aT(){return te(Hn(),"settings.json")}function L0(e=process.cwd()){return te(e,".afk","settings.json")}function Mf(){return te(ve(),"AFK.md")}function Of(e=process.cwd()){return te(e,"AFK.md")}function N0(){return te(nT(),".afk.env")}function $f(){return te(nT(),".afk.config.json")}function nee(){return te(ve(),"sessions")}function ree(){return te(ve(),"todos")}function oee(){return te(ve(),"transcripts")}function lT(e,t){if(e!==t&&T0(e)&&!T0(t))try{YZ(kf(t),{recursive:!0});try{XZ(e,t)}catch(n){if(n.code==="EXDEV")try{QZ(e,t,{recursive:!0}),ZZ(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
3
3
  `)}}}catch{}}function B0(){lT(nee(),tt())}function U0(){lT(ree(),oT())}function j0(){lT(oee(),Nd())}function cT(){return te(Ee(),"repl-history.jsonl")}function see(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(e.length>E0)throw new Error(`Invalid jobId: exceeds ${E0} chars`);if(!iee.test(e))throw new Error(`Invalid jobId: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function Ud(){return te(Ee(),"bg")}function Xi(e){return see(e),te(Ud(),e)}function Df(e){return te(Xi(e),"events.jsonl")}function dT(e){return te(Xi(e),"meta.json")}function jd(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(e.length>R0)throw new Error(`Invalid browser profile: exceeds ${R0} chars`);if(!aee.test(e))throw new Error(`Invalid browser profile: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function uT(){return te(Ee(),"browser")}function pT(e){return jd(e),te(uT(),e)}function Hd(e){return te(pT(e),"storageState.json")}function Yr(e){return typeof e=="string"&&e.length>0&&e.length<=cee&&lee.test(e)}function Wd(e){if(!Yr(e))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(e)}`);return te(tt(),e)}function Ba(e){return te(Wd(e),"events.jsonl")}function mT(e){return te(Wd(e),"session.key")}function Kd(){return te(Ee(),"mcp","server-status.json")}var tee,iee,E0,aee,R0,lee,cee,K=y(()=>{"use strict";j();tee=/^[a-zA-Z0-9_-]+$/;iee=/^[A-Za-z0-9_-]+$/,E0=128;aee=/^[A-Za-z0-9_-]+$/,R0=128;lee=/^[A-Za-z0-9_-]+$/,cee=128});import{randomBytes as dee}from"node:crypto";import{mkdirSync as uee,renameSync as pee,rmSync as H0,writeFileSync as mee}from"node:fs";import{dirname as fee,isAbsolute as gee,join as hee}from"node:path";function Ff(){return hee(Ee(),"last-cwd")}function W0(){try{H0(Ff(),{force:!0})}catch{}}function K0(e){if(!gee(e))throw new Error(`recordCdIntent: target must be an absolute path, got ${JSON.stringify(e)}`);if(/[\n\r\0]/.test(e))throw new Error(`recordCdIntent: target must not contain newline/CR/NUL, got ${JSON.stringify(e)}`);try{let t=Ff();uee(fee(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${dee(6).toString("hex")}`;try{mee(n,e,{encoding:"utf8",mode:384}),pee(n,t)}catch(r){try{H0(n,{force:!0})}catch{}throw r}}catch{}}function G0(){let e=k.AFK_SHELL_WRAPPER;return e==="1"||e==="true"}var Lf=y(()=>{"use strict";j();K()});import Q from"chalk";var z0,yee,bee,V0,J0,Y0,m,U=y(()=>{"use strict";z0={brand:Q.hex("#E67E4C"),mint:Q.hex("#5FE3A1"),goblin:Q.hex("#9CB04A"),user:Q.cyan,caret:Q.hex("#7AA2F7"),tool:Q.hex("#DCDCAA"),chrome:Q.hex("#B0B8C2"),syntaxString:Q.italic.hex("#8AB07A"),toolArg:Q.dim.white,thinking:Q.italic.hex("#9B8FB5"),success:Q.green,error:Q.red,warning:Q.yellow,plan:Q.hex("#9F7CE0"),bypass:Q.bold.hex("#FF6AC1"),meta:Q.blackBright,info:Q.hex("#5BA8FF"),fileRef:Q.hex("#56B5A8"),heading:Q.bold.white,label:Q.dim,dim:Q.dim,bold:Q.bold,italic:Q.italic,diffAdd:Q.green,diffRemove:Q.red,diffHunk:Q.blackBright},yee={brand:Q.hex("#C0562A"),mint:Q.hex("#1B9E63"),goblin:Q.hex("#6B7D2A"),user:Q.hex("#0E7490"),caret:Q.hex("#3B5BDB"),tool:Q.hex("#7A6E00"),chrome:Q.hex("#5A6470"),syntaxString:Q.italic.hex("#3F7A3F"),toolArg:Q.hex("#6B7280"),thinking:Q.italic.hex("#6D5B8E"),success:Q.hex("#2E7D32"),error:Q.hex("#C62828"),warning:Q.hex("#B8860B"),plan:Q.hex("#7048C0"),bypass:Q.bold.hex("#D6297F"),meta:Q.hex("#6B7280"),info:Q.hex("#1D6FD6"),fileRef:Q.hex("#0F766E"),heading:Q.bold.hex("#1F2937"),label:Q.dim,dim:Q.dim,bold:Q.bold,italic:Q.italic,diffAdd:Q.hex("#2E7D32"),diffRemove:Q.hex("#C62828"),diffHunk:Q.hex("#6B7280")},bee={brand:Q.hex("#FF9B5A"),mint:Q.hex("#B4FCC3"),goblin:Q.hex("#A5AC55"),user:Q.hex("#42CBC8"),caret:Q.hex("#9DBEFC"),tool:Q.hex("#F7D179"),chrome:Q.hex("#D3CDC5"),syntaxString:Q.italic.hex("#96C182"),toolArg:Q.dim.hex("#D3CDC5"),thinking:Q.italic.hex("#B49EC4"),success:Q.hex("#8AE49E"),error:Q.hex("#EF7F74"),warning:Q.hex("#D7AA32"),plan:Q.hex("#AE93DE"),bypass:Q.bold.hex("#FFACE9"),meta:Q.hex("#AAA19B"),info:Q.hex("#739EF0"),fileRef:Q.hex("#80E5E2"),heading:Q.bold.hex("#F9F6F2"),label:Q.dim,dim:Q.dim,bold:Q.bold,italic:Q.italic,diffAdd:Q.hex("#8AE49E"),diffRemove:Q.hex("#EF7F74"),diffHunk:Q.hex("#AAA19B")},V0=z0,J0=yee,Y0=bee,m={...z0}});function X0(){return{keyword:m.brand,built_in:m.brand,literal:m.brand,tag:m.brand,string:m.syntaxString,regexp:m.syntaxString,attr:m.syntaxString,comment:m.meta,meta:m.meta,quote:m.meta,number:m.warning,function:m.tool,title:m.tool,class:m.tool,"selector-tag":m.tool}}var Q0=y(()=>{"use strict";U()});import See from"chalk";import{createEmphasize as wee,common as vee}from"emphasize";function eO(){mr.clear()}function Ree(e){let t=mr.get(e);if(t!==void 0)return mr.delete(e),mr.set(e,t),t}function xee(e,t){if(mr.has(e)&&mr.delete(e),mr.set(e,t),mr.size>Eee){let n=mr.keys().next().value;n!==void 0&&mr.delete(n)}}function tO(e,t){if(See.level===0||e.length>kee)return e;let n=e.length<Tee,r=n?`${t} ${e}`:"";if(n){let i=Ree(r);if(i!==void 0)return i}let o;try{if(!t||!Z0.registered(t))o=e;else{let i=Z0.highlight(t,e,X0());o=typeof i?.value=="string"?i.value:e}}catch{o=e}return n&&xee(r,o),o}var Z0,kee,Tee,Eee,mr,gT=y(()=>{"use strict";Q0();Z0=wee(vee),kee=2048,Tee=512,Eee=32,mr=new Map});function oO(){return rO}function fr(e){Object.assign(m,nO[e]),eO(),rO=e}function No(e){if(e==null)return;let t=e.trim().toLowerCase();return t==="auto"||Nf.includes(t)?t:void 0}function Aee(){let e=k.COLORFGBG;if(!e)return"dark";let t=e.split(";"),n=t[t.length-1]?.trim();if(!n)return"dark";let r=Number.parseInt(n,10);return Number.isInteger(r)&&(r===7||r>=9)?"light":"dark"}function gr(e){return e==="auto"?Aee():e!==void 0?e:"dark"}function Bf(e){let t=No(e);if(t!==void 0)return t;throw new Error(`Invalid --theme value: ${e}. Expected ${[...Nf,"auto"].join("|")}`)}function Uf(e,t){if(e!==void 0)return e;let n=No(k.AFK_THEME);return n!==void 0?n:t}var nO,Nf,rO,Ua=y(()=>{"use strict";U();gT();j();nO={dark:V0,light:J0,umber:Y0},Nf=Object.keys(nO),rO="dark"});var kt,ut,jf,Ae,hr,yr,ja,Hf,Ue=y(()=>{"use strict";kt=class extends Error{constructor(t){super(t),this.name="AbortError"}},ut=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},jf=class extends ut{constructor(t,n){super(t,n),this.name="IdleWatchdogError"}},Ae=class extends Error{constructor(n,r,o,i){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",i?.cause!==void 0&&(this.cause=i.cause)}event;reason;cause},hr=class extends Error{constructor(t){super(t),this.name="StreamIncompleteError"}},yr=class extends Error{constructor(n,r,o){super(o??`Budget ceiling reached: $${n.toFixed(4)} cumulative >= $${r.toFixed(4)} limit`);this.runningCostUsd=n;this.maxBudgetUsd=r;this.name="BudgetExceededError"}runningCostUsd;maxBudgetUsd},ja=class extends Error{constructor(t){super(t),this.name="DenialCircuitBreakerError"}},Hf=class extends Error{constructor(n,r,o){super(o??`${n} provider does not support AgentConfig.${r}.`);this.provider=n;this.field=r;this.name="UnsupportedProviderConfigError"}provider;field}});import Cee from"string-width";function Le(e){return e.replace(hT,"")}function Z(e){return Cee(e)}function Wa(e){return e.length===0?[]:aO?Array.from(aO.segment(e),t=>t.segment):Array.from(e)}function _ee(e){let t=[],n=0,r;for(hT.lastIndex=0;(r=hT.exec(e))!==null;){if(r.index>n)for(let o of Wa(e.slice(n,r.index)))t.push({type:"text",value:o});t.push({type:"ansi",value:r[0]}),n=r.index+r[0].length}if(n<e.length)for(let o of Wa(e.slice(n)))t.push({type:"text",value:o});return t}function pt(e,t){let n=Math.max(0,t-Z(e));return e+" ".repeat(n)}function Iee(e,t){let n=Math.max(0,t-Z(e));return" ".repeat(n)+e}function yT(e,t,n="left"){let r=Math.max(0,t-Z(e));if(r===0)return e;if(n==="right")return Iee(e,t);if(n==="center"){let o=Math.floor(r/2);return" ".repeat(o)+e+" ".repeat(r-o)}return pt(e,t)}function se(e,t,n="\u2026"){if(t<=0)return"";if(Z(e)<=t)return e;let r=Z(n),o=Math.max(0,t-r),i=0,s="",a=!1,l=!1;for(let c of _ee(e)){if(c.type==="ansi"){s+=c.value,a=!0;let u=Pee.exec(c.value);u&&(l=(u[1]??"").length>0);continue}let d=i+Z(c.value);if(d>o)break;s+=c.value,i=d}return s+n+(l?Mee:"")+(a?"\x1B[0m":"")}function lO(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.trunc(e))):0}function bT(e,t){let n=lO(t,e.length);if(n===0||e.length===0)return 0;let r=0;for(let o of Wa(e)){let i=r+o.length;if(i>=n)return r;r=i}return r}function Qi(e,t){let n=lO(t,e.length);if(n>=e.length||e.length===0)return e.length;let r=0;for(let o of Wa(e)){let i=r+o.length;if(r>=n||n>r&&n<i)return i;r=i}return e.length}var hT,aO,Pee,Mee,ye=y(()=>{"use strict";hT=/\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P^_X][^\x1B]*\x1B\\|[@-OQ-WYZ\\\-])/g,aO=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;Pee=/^\x1b\]8;[^;\x07\x1b]*;(.*?)(?:\x07|\x1b\\)$/s,Mee="\x1B]8;;\x1B\\"});function oe(){let e=process.stdout.columns;return typeof e=="number"&&e>0?e:80}function Oee(){for(let e of Wf)try{e()}catch{}}function $ee(){for(let e of Kf)try{e()}catch{}}function Dee(){Zi!==null&&clearTimeout(Zi),Zi=setTimeout(()=>{Zi=null,Oee()},150)}function ST(){$ee(),Dee()}function Fee(e){return Wf.add(e),Ka||(process.stdout.on("resize",ST),Ka=!0),()=>{Wf.delete(e),cO()}}function Lee(e){return Kf.add(e),Ka||(process.stdout.on("resize",ST),Ka=!0),()=>{Kf.delete(e),cO()}}function cO(){Wf.size===0&&Kf.size===0&&(Ka&&(process.stdout.off("resize",ST),Ka=!1),Zi!==null&&(clearTimeout(Zi),Zi=null))}var Wf,Kf,Ka,Zi,We,Ce=y(()=>{"use strict";Wf=new Set,Kf=new Set,Ka=!1,Zi=null;We={subscribe:Fee,subscribeImmediate:Lee}});import dO from"wrap-ansi";function fe(e,t,n={}){if(!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY)return e;let r=Math.floor(t);return e.replaceAll(`\r
4
4
  `,`
5
5
  `).split(`
@@ -314,7 +314,7 @@ ${o}`,paths:[t,n]}:o!==null?i={content:o,paths:[n]}:r!==null?i={content:r,paths:
314
314
 
315
315
  ${t}`}var Mae,rR=y(()=>{"use strict";Mae=new Set(["script","style","noscript","template","svg"])});function Dae(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new Error("aborted"));return}let o=()=>{clearTimeout(i),r(t?.reason??new Error("aborted"))},i=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})})}function pL(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function Fae(e,t){let n=e.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,t)}async function mL(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??Dae,l=n.signal??void 0,c;for(let d=0;d<=o;d++){if(l?.aborted)throw l.reason??new Error("aborted");try{let u=await e(t,n);if(!$ae.has(u.status)||d===o)return u;let p=Fae(u,s)??pL(d,i,s);B("[web/retryFetch] retrying",{url:t,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,l)}catch(u){if(l?.aborted||(c=u,d===o))throw u;let p=pL(d,i,s);B("[web/retryFetch] retrying after error",{url:t,attempt:d,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var $ae,fL=y(()=>{"use strict";me();$ae=new Set([429,502,503,504])});import{BlockList as Lae,isIP as iR}from"node:net";import{lookup as Nae}from"node:dns/promises";import{Agent as Bae}from"undici";function hL(){let e=k.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return e==="1"||e==="true"}function Wae(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function oR(e){let t=iR(e);return t===0?!1:Hae.check(e,t===4?"ipv4":"ipv6")}async function yL(e){return Nae(e,{all:!0,verbatim:!0})}async function sR(e,t={}){if(t.allowPrivateHosts??hL())return{allowed:!0};let n;try{n=new URL(e)}catch{return{allowed:!1,reason:`"${e}" is not a valid absolute URL`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{allowed:!1,reason:`protocol "${n.protocol}" not supported (http/https only)`};let r=Wae(n.hostname),o=(a,l)=>`refusing to fetch ${l} \u2014 internal/private address ${a} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`;if(iR(r)!==0)return oR(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let i=t.lookupFn??yL,s;try{s=await i(r)}catch{return{allowed:!0}}for(let a of s)if(oR(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function Fu(e,t={}){let n=await sR(e,t);if(!n.allowed)throw new Yn(n.reason)}async function ch(e,t,n={},r={}){let o={...r.lookupFn!==void 0?{lookupFn:r.lookupFn}:{},...r.allowPrivateHosts!==void 0?{allowPrivateHosts:r.allowPrivateHosts}:{}},i=t;for(let s=0;s<=gL;s++){await Fu(i,o);let a={...n,redirect:"manual",...e===globalThis.fetch&&!(r.allowPrivateHosts??hL())?{dispatcher:Kae}:{}},l=await mL(e,i,a,r.retry??{});if(!Gae.has(l.status))return l;let c=l.headers.get("location");if(c===null||c.trim()==="")return l;let d;try{d=new URL(c,l.url||i).toString()}catch{return l}await l.body?.cancel().catch(()=>{}),i=d}throw new Yn(`too many redirects (>${gL}) starting from ${t}`)}var Uae,jae,Hae,Yn,Kae,gL,Gae,aR=y(()=>{"use strict";j();fL();Uae=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.168.0.0",16]],jae=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],Hae=(()=>{let e=new Lae;for(let[t,n]of Uae)e.addSubnet(t,n,"ipv4");for(let[t,n]of jae)e.addSubnet(t,n,"ipv6");return e})(),Yn=class extends Error{constructor(t){super(t),this.name="EgressBlockedError"}};Kae=new Bae({connect:{lookup(e,t,n){yL(e).then(r=>{let o=r.find(s=>oR(s.address));if(o!==void 0){n(new Yn(`refusing to connect to ${e} (resolved) \u2014 internal/private address ${o.address} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`),"",0);return}let i=r[0];if(i===void 0){n(new Error(`DNS lookup returned no addresses for ${e}`),"",0);return}n(null,i.address,iR(i.address))},r=>n(r,"",0))}}});gL=20,Gae=new Set([301,302,303,307,308])});import{readFileSync as qae}from"node:fs";import{join as zae}from"path";function Vae(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function bL(e,t){return Vae(t).test(e)}function Xae(e,t){if(e!==void 0){let n=e.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(t!==void 0){if(Jae.has(t))return!0;if(Yae.has(t))return!1}return!1}function SL(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function Qae(e){if(e===void 0||e===""||e==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${e}`)}function wL(e){let t=e===void 0||e.trim()===""?"default":e.trim();return jd(t),t}function Zae(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function ele(e){try{return qae(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function tle(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return typeof t.defaultProfile=="string"&&(n.defaultProfile=wL(t.defaultProfile)),n}function vL(e){let t=e?.env??k,n=e?.readFileSync??ele,r=e?.surface??t.AGENT_SURFACE,o=Xae(t.AFK_BROWSER_HEADLESS,r),i=SL(t.AFK_BROWSER_ALLOWED_DOMAINS),s=SL(t.AFK_BROWSER_BLOCKED_DOMAINS),a=Zae(t.AFK_BROWSER_DOM_SNAPSHOTS),l=Qae(t.AFK_BROWSER_BACKEND),c=wL(t.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:i,blockedDomains:s,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=t.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():zae(Hn(),"browser.json"),f=n(p);if(f===void 0)return d;let g;try{g=JSON.parse(f)}catch(b){throw new Error(`Failed to parse browser config at ${p}: ${String(b)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${p} must be a JSON object`);let h=tle(d,g);return h.configPath=p,h}function dh(e,t){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${e}`}}for(let r of t.blockedDomains)if(bL(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>bL(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Jae,Yae,uh=y(()=>{"use strict";j();K();Jae=new Set(["daemon","subagent","telegram","afk"]),Yae=new Set(["repl","interactive","cli"])});import{existsSync as nle,readFileSync as rle}from"node:fs";import{createRequire as ole}from"node:module";import{dirname as ile,join as sle}from"node:path";function EL(e){if(typeof e=="string")return e;let t=[],n=e;for(let r=0;r<lle&&n instanceof Error;r++)t.push(n.message),n=n.cause;return t.length>0?t.join(" | "):String(e)}function Yt(e){let t=EL(e);return TL.some(n=>t.includes(n))}function cle(){try{let t=ole(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(rle(t,"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 i=sle(ile(t),o);return nle(i)?`node ${/\s/.test(i)?`"${i}"`:i} install chromium`:void 0}catch{return}}function Lu(){return kL??=cle()??ale,kL}function lR(e){return e.includes("install chromium")}function An(e,t){let n=EL(e),r=t?.latched===!0?` ${dle}`:"";if(n.includes("Executable doesn't exist")){let o="";return t?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":t?.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: ${Lu()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${Lu()}). Or pick a different tool.${r}`}function Nu(e,t,n=!1){if(!Yt(e))return e;let r=e instanceof Error?e.message:String(e);return new Error(`${r}
316
316
 
317
- ${An(e,{headless:t,latched:n})}`,{cause:e})}var TL,ale,lle,kL,dle,ph=y(()=>{"use strict";TL=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],ale="pnpm exec playwright install chromium",lle=4;dle="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 Ts from"node:fs";import mh from"node:path";import{randomBytes as ule}from"node:crypto";import{chromium as ple}from"playwright";function mle(){try{return"5.115.3"}catch{}try{let e=mh.resolve(import.meta.dirname,"../../../package.json"),t=Ts.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var fle,fh,RL=y(()=>{"use strict";ph();K();me();fle=mle(),fh=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(t){this.config=t}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(t){this.launchFailure={error:t}}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=ple.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,this.clearLaunchFailure(),t)).catch(t=>{this.launchPromise=void 0;let n=Nu(t,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){i=l,await a.abort("blockedbyclient")}});let s=()=>{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",s,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw i??p}if(i!==void 0)throw i;let c=await a.content();if(i!==void 0)throw i;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",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);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(t){this.clearLaunchFailure();let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),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 t=[...this.sessions.keys()];if(await Promise.all(t.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/${fle}`}}loadStorageState(t){let n=Hd(t);try{if(!Ts.existsSync(n))return;let r=JSON.parse(Ts.readFileSync(n,"utf8"));return B("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){B("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Hd(t);if(!Ts.existsSync(r))return;let o=await n.storageState(),i=mh.join(mh.dirname(r),`.${mh.basename(r)}.${process.pid}.${ule(4).toString("hex")}.tmp`);Ts.writeFileSync(i,JSON.stringify(o),{mode:384}),Ts.chmodSync(i,384),Ts.renameSync(i,r),B("[browser/vault] saved session",{profile:t,file:r})}catch(r){B("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as gle}from"crypto";function xL(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&hle.test(e.label))}function AL(e){return gle("sha256").update(e,"utf8").digest("hex").slice(0,8)}function CL(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var hle,gh=y(()=>{"use strict";hle=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as yle}from"node:crypto";function ble(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function Sle(e,t,n){return`el_${yle("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function wle(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function _L(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function PL(e,t){let n=e.role??"",r=e.name??"";IL.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])PL(i,t)}async function vle(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let i=o.getBoundingClientRect(),s=o;if(i.width===0&&i.height===0){let d=window.getComputedStyle(s);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(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},ML).catch(()=>[])}async function kle(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let i of r){let s=i.tagName.toLowerCase(),a=i.getAttribute("role")??"",l=i.getAttribute("aria-label")??i.getAttribute("placeholder")??(i.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[s]??"");if(s==="input"){let h=i.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in i?i.value:void 0,u=d!==void 0?String(d):void 0,p=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:p};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},ML).catch(()=>[])}function Tle(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function hh(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=Tle(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=vle(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,p,f,g,h]=await Promise.all([s,a,l,c,d]),b,S=!1;u!==null?(b=[],PL(u,b)):(o.push("observation skipped accessibility tree (returned null)"),S=!0,b=(await kle(e)).filter($=>IL.has($.role??"")));let w=new Map;for(let P of p){let $=_L(P.name),q=w.get($);(!q||q.bbox.w===0&&P.bbox.w>0)&&w.set($,P)}let v=b.map(P=>({ax:P,dom:w.get(_L(P.name??""))})),E=r?v:v.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);E.sort((P,$)=>{let q=P.dom?.bbox.y??0,F=$.dom?.bbox.y??0;if(q!==F)return q-F;let H=P.dom?.bbox.x??0,G=$.dom?.bbox.x??0;return H-G}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=E.slice(0,n).map((P,$)=>{let q=P.ax.role??"generic",F=P.ax.name??"",H=Sle(q,F,$),G=P.dom?.bbox??{x:0,y:0,w:0,h:0},I=P.dom?.type??null,L=null;P.ax.value!==void 0&&P.ax.value!==null&&(L=String(P.ax.value)),P.ax.checked!==void 0&&(L=String(P.ax.checked)),xL({role:q,kind:I})&&(L="[redacted]");let O={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(O.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(O.selected=P.ax.selected),P.ax.expanded!==void 0&&(O.expanded=P.ax.expanded);let D;P.dom?.testId?D=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(D=`#${P.dom.id}`);let W={id:H,role:q,label:ble(F),kind:I,value:L,state:O,bbox:G};return D!==void 0&&(W.selector=D),W}),M="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?M="loading":P==="interactive"?M="navigating":M="idle"}catch{M="navigating"}M!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),S&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let _=wle(f),x=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:x,url:g,title:h,textSummary:_,interactive:A,status:{httpStatus:t.httpStatus??null,loadingState:M,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var IL,ML,OL=y(()=>{"use strict";gh();IL=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);ML="a[href], button, input, select, textarea, [role], [tabindex], label"});async function $L(e,t){try{let n=await e.nth(t).evaluate(s=>{let a=s,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}:${t}`,o=0;for(let s=0;s<r.length;s++)o=o*31+r.charCodeAt(s)>>>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 cR(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>$L(e,i)))).filter(o=>o!==null)}async function Ele(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let i=0;i<o;i++){let s;try{s=await r.nth(i).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(s)||(t.add(s),n.push({key:s,locator:r,index:i}))}return n}async function dR(e,t,n){switch(t.kind){case"element_id":return Rle(e,t,n);case"selector":return xle(e,t);case"semantic":return Ale(e,t)}}async function Rle(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),i=await o.count();if(i===0)return{outcome:"not_found",query:t};if(i===1)return{outcome:"resolved",locator:o};let s=await cR(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function xle(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await cR(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function Ale(e,t){return t.role!==void 0?Cle(e,t.text,t.role):_le(e,t.text,t)}async function Cle(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let i=await cR(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function _le(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),i=e.getByLabel(t,{exact:!1}),[s,a,l]=await Promise.all([r.count(),o.count(),i.count()]);if(s+a+l===0)return{outcome:"not_found",query:n};let d=[];s>0&&d.push({loc:r,count:s}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:i,count:l});let u=await Ele(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=u.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let S=await $L(b.locator,b.index);if(S!==null){let w=`${S.role}:${S.label}:${h}`,v=0;for(let E=0;E<w.length;E++)v=v*31+w.charCodeAt(E)>>>0;f.push({...S,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var DL=y(()=>{"use strict"});async function uR(e,t,n,r){let o=e.url();if(o===n)return null;let i=dh(o,t);if(i.allowed)return null;try{await e.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:i.reason}}var FL=y(()=>{"use strict";uh()});import{randomBytes as Ile}from"crypto";import{mkdir as Ple,stat as Mle,writeFile as Ole}from"fs/promises";import{join as pR}from"path";import{gzip as $le}from"zlib";import{promisify as Dle}from"util";function Fle(e){return pR(sn(e),"browser")}function Lle(e){return pR(Fle(e),"screenshots")}function Nle(){return new Date().toISOString().replace(/[:.]/g,"-")}function Ble(){return Ile(3).toString("hex")}async function mR(e,t,n){if(t.length>LL)throw new Error(`writeScreenshotSidecar: buffer exceeds ${LL} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=Lle(e);await Ple(r,{recursive:!0});let o=`${Nle()}-${Ble()}-${n}.png`,i=pR(r,o);await Ole(i,t);let{size:s}=await Mle(i);return{path:i,bytes:s}}var C2e,LL,NL=y(()=>{"use strict";K();gh();C2e=Dle($le);LL=5*1024*1024});var UL={};Fo(UL,{PlaywrightProvider:()=>fR});function BL(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var fR,jL=y(()=>{"use strict";RL();OL();DL();uh();FL();NL();fR=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new fh(t)}async open(t){let n=dh(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await uR(o,this.config,t.url,()=>this.close({sessionId:r}));if(u!==null)return u}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let d=await hh(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(t){let{sessionId:n}=t,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),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await hh(r,{observationCounter:o.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,s.interactive,s.url,s.title,"browser_observe"),s}async act(t){let{sessionId:n}=t,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),i=r.url(),s=t.timeoutMs??3e4,a=await dR(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${BL(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":await l.fill(t.value??"");break;case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(b){c=b}else c=h}let u=await uR(r,this.config,i,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await hh(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal,requestGuard:t.requestGuard})}async screenshot(t){let{sessionId:n}=t,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),i;if(t.target!==void 0){let d=await dR(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${BL(t.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await d.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await mR(n,i,"browser_screenshot"),l=0,c=0;if(t.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:s,bytes:a,width:l,height:c,dataBase64:i.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);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(t){let n=this.sessions.get(t);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(t,r),r}updateSessionFromObservation(t,n,r,o,i){t.knownElements=new Map(n.map(s=>[s.id,s])),t.currentUrl=r,t.currentTitle=o,t.lastAction=i,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:i}=await mR(n,o,r);return i}catch{return null}}}});var Rs={};Fo(Rs,{__resetBrowserRegistryForTests:()=>Kle,browserProviderActive:()=>Hle,closeBrowserProvider:()=>gR,getBrowserProvider:()=>jle,peekBrowserProvider:()=>Wle});function HL(){Promise.resolve(gR()).then(()=>{process.exit(130)})}function WL(){Promise.resolve(gR()).then(()=>{process.exit(143)})}function KL(){Ar=null}function Ule(){yh||(process.on("SIGINT",HL),process.on("SIGTERM",WL),process.on("exit",KL),yh=!0)}function GL(){yh&&(process.removeListener("SIGINT",HL),process.removeListener("SIGTERM",WL),process.removeListener("exit",KL),yh=!1)}async function jle(e){return Ar!==null?Ar:(Es!==null||(Es=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(jL(),UL)),n=vL(e),r=new t(n);return Ule(),Ar=r,Es=null,r})()),Es)}async function gR(){if(Ar===null)return;let e=Ar;Ar=null,Es=null,GL(),await e.shutdown()}function Hle(){return Ar!==null}function Wle(){return Ar}function Kle(){Ar=null,Es=null,GL()}var Ar,Es,yh,xs=y(()=>{"use strict";uh();Ar=null,Es=null,yh=!1});async function qL(e,t){try{return await cL(e,t)}catch(n){return B("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function Yle(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(xs(),Rs));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function zL(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??Yle,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let u=await ch(n,e,{headers:Jle,signal:t.signal},o);l=u.status,a=u.url||e;let p=u.headers.get("content-type")??"";if(u.ok){if(Vle.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await u.text();if(zle.test(p)&&!qle.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await qL(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(u){if(t.signal.aborted||u instanceof Yn||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;c=u}if(!(i===null||i.textLength<200)&&i!==null){let u=nR({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await Fu(e,o);let u=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>Fu(f,o)});u.finalUrl!==e&&/^https?:\/\//i.test(u.finalUrl)&&await Fu(u.finalUrl,o);let p=await qL(u.html,u.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||p.textLength>=i.textLength){let f=nR({html:u.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:u.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(u){if(t.signal.aborted||u instanceof Yn)throw u;if(i===null){let p=u instanceof Error?u.message:String(u),f=c instanceof Error?c.message:`HTTP ${l??"error"}`,g=new Error(`web_scrape could not retrieve ${e}: fetch failed (${f}) and render failed (${p}).`);throw g.cause=u,g}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${l??"error"}).`)}var qle,zle,Vle,Jle,VL=y(()=>{"use strict";dL();rR();aR();me();qle=/(text\/html|application\/xhtml\+xml)/i,zle=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,Vle=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,Jle={"User-Agent":"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/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function Zle(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(Xle,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),Qle),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=Pe(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let c=i.statusText?` ${i.statusText}`:"";throw new Error(`Exa Search HTTP ${i.status}${c}${l}`)}let s;try{s=await i.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(s.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function JL(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?Zle({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function YL(e,t){if(t.length===0)return`# Search results for "${e}"
317
+ ${An(e,{headless:t,latched:n})}`,{cause:e})}var TL,ale,lle,kL,dle,ph=y(()=>{"use strict";TL=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],ale="pnpm exec playwright install chromium",lle=4;dle="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 Ts from"node:fs";import mh from"node:path";import{randomBytes as ule}from"node:crypto";import{chromium as ple}from"playwright";function mle(){try{return"5.115.4"}catch{}try{let e=mh.resolve(import.meta.dirname,"../../../package.json"),t=Ts.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var fle,fh,RL=y(()=>{"use strict";ph();K();me();fle=mle(),fh=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(t){this.config=t}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(t){this.launchFailure={error:t}}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=ple.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,this.clearLaunchFailure(),t)).catch(t=>{this.launchPromise=void 0;let n=Nu(t,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){i=l,await a.abort("blockedbyclient")}});let s=()=>{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",s,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw i??p}if(i!==void 0)throw i;let c=await a.content();if(i!==void 0)throw i;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",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);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(t){this.clearLaunchFailure();let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),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 t=[...this.sessions.keys()];if(await Promise.all(t.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/${fle}`}}loadStorageState(t){let n=Hd(t);try{if(!Ts.existsSync(n))return;let r=JSON.parse(Ts.readFileSync(n,"utf8"));return B("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){B("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Hd(t);if(!Ts.existsSync(r))return;let o=await n.storageState(),i=mh.join(mh.dirname(r),`.${mh.basename(r)}.${process.pid}.${ule(4).toString("hex")}.tmp`);Ts.writeFileSync(i,JSON.stringify(o),{mode:384}),Ts.chmodSync(i,384),Ts.renameSync(i,r),B("[browser/vault] saved session",{profile:t,file:r})}catch(r){B("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as gle}from"crypto";function xL(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&hle.test(e.label))}function AL(e){return gle("sha256").update(e,"utf8").digest("hex").slice(0,8)}function CL(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var hle,gh=y(()=>{"use strict";hle=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as yle}from"node:crypto";function ble(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function Sle(e,t,n){return`el_${yle("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function wle(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function _L(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function PL(e,t){let n=e.role??"",r=e.name??"";IL.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])PL(i,t)}async function vle(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let i=o.getBoundingClientRect(),s=o;if(i.width===0&&i.height===0){let d=window.getComputedStyle(s);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(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},ML).catch(()=>[])}async function kle(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let i of r){let s=i.tagName.toLowerCase(),a=i.getAttribute("role")??"",l=i.getAttribute("aria-label")??i.getAttribute("placeholder")??(i.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[s]??"");if(s==="input"){let h=i.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in i?i.value:void 0,u=d!==void 0?String(d):void 0,p=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:p};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},ML).catch(()=>[])}function Tle(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function hh(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=Tle(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=vle(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,p,f,g,h]=await Promise.all([s,a,l,c,d]),b,S=!1;u!==null?(b=[],PL(u,b)):(o.push("observation skipped accessibility tree (returned null)"),S=!0,b=(await kle(e)).filter($=>IL.has($.role??"")));let w=new Map;for(let P of p){let $=_L(P.name),q=w.get($);(!q||q.bbox.w===0&&P.bbox.w>0)&&w.set($,P)}let v=b.map(P=>({ax:P,dom:w.get(_L(P.name??""))})),E=r?v:v.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);E.sort((P,$)=>{let q=P.dom?.bbox.y??0,F=$.dom?.bbox.y??0;if(q!==F)return q-F;let H=P.dom?.bbox.x??0,G=$.dom?.bbox.x??0;return H-G}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=E.slice(0,n).map((P,$)=>{let q=P.ax.role??"generic",F=P.ax.name??"",H=Sle(q,F,$),G=P.dom?.bbox??{x:0,y:0,w:0,h:0},I=P.dom?.type??null,L=null;P.ax.value!==void 0&&P.ax.value!==null&&(L=String(P.ax.value)),P.ax.checked!==void 0&&(L=String(P.ax.checked)),xL({role:q,kind:I})&&(L="[redacted]");let O={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(O.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(O.selected=P.ax.selected),P.ax.expanded!==void 0&&(O.expanded=P.ax.expanded);let D;P.dom?.testId?D=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(D=`#${P.dom.id}`);let W={id:H,role:q,label:ble(F),kind:I,value:L,state:O,bbox:G};return D!==void 0&&(W.selector=D),W}),M="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?M="loading":P==="interactive"?M="navigating":M="idle"}catch{M="navigating"}M!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),S&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let _=wle(f),x=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:x,url:g,title:h,textSummary:_,interactive:A,status:{httpStatus:t.httpStatus??null,loadingState:M,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var IL,ML,OL=y(()=>{"use strict";gh();IL=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);ML="a[href], button, input, select, textarea, [role], [tabindex], label"});async function $L(e,t){try{let n=await e.nth(t).evaluate(s=>{let a=s,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}:${t}`,o=0;for(let s=0;s<r.length;s++)o=o*31+r.charCodeAt(s)>>>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 cR(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>$L(e,i)))).filter(o=>o!==null)}async function Ele(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let i=0;i<o;i++){let s;try{s=await r.nth(i).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(s)||(t.add(s),n.push({key:s,locator:r,index:i}))}return n}async function dR(e,t,n){switch(t.kind){case"element_id":return Rle(e,t,n);case"selector":return xle(e,t);case"semantic":return Ale(e,t)}}async function Rle(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),i=await o.count();if(i===0)return{outcome:"not_found",query:t};if(i===1)return{outcome:"resolved",locator:o};let s=await cR(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function xle(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await cR(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function Ale(e,t){return t.role!==void 0?Cle(e,t.text,t.role):_le(e,t.text,t)}async function Cle(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let i=await cR(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function _le(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),i=e.getByLabel(t,{exact:!1}),[s,a,l]=await Promise.all([r.count(),o.count(),i.count()]);if(s+a+l===0)return{outcome:"not_found",query:n};let d=[];s>0&&d.push({loc:r,count:s}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:i,count:l});let u=await Ele(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=u.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let S=await $L(b.locator,b.index);if(S!==null){let w=`${S.role}:${S.label}:${h}`,v=0;for(let E=0;E<w.length;E++)v=v*31+w.charCodeAt(E)>>>0;f.push({...S,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var DL=y(()=>{"use strict"});async function uR(e,t,n,r){let o=e.url();if(o===n)return null;let i=dh(o,t);if(i.allowed)return null;try{await e.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:i.reason}}var FL=y(()=>{"use strict";uh()});import{randomBytes as Ile}from"crypto";import{mkdir as Ple,stat as Mle,writeFile as Ole}from"fs/promises";import{join as pR}from"path";import{gzip as $le}from"zlib";import{promisify as Dle}from"util";function Fle(e){return pR(sn(e),"browser")}function Lle(e){return pR(Fle(e),"screenshots")}function Nle(){return new Date().toISOString().replace(/[:.]/g,"-")}function Ble(){return Ile(3).toString("hex")}async function mR(e,t,n){if(t.length>LL)throw new Error(`writeScreenshotSidecar: buffer exceeds ${LL} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=Lle(e);await Ple(r,{recursive:!0});let o=`${Nle()}-${Ble()}-${n}.png`,i=pR(r,o);await Ole(i,t);let{size:s}=await Mle(i);return{path:i,bytes:s}}var C2e,LL,NL=y(()=>{"use strict";K();gh();C2e=Dle($le);LL=5*1024*1024});var UL={};Fo(UL,{PlaywrightProvider:()=>fR});function BL(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var fR,jL=y(()=>{"use strict";RL();OL();DL();uh();FL();NL();fR=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new fh(t)}async open(t){let n=dh(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await uR(o,this.config,t.url,()=>this.close({sessionId:r}));if(u!==null)return u}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let d=await hh(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(t){let{sessionId:n}=t,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),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await hh(r,{observationCounter:o.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,s.interactive,s.url,s.title,"browser_observe"),s}async act(t){let{sessionId:n}=t,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),i=r.url(),s=t.timeoutMs??3e4,a=await dR(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${BL(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":await l.fill(t.value??"");break;case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(b){c=b}else c=h}let u=await uR(r,this.config,i,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await hh(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal,requestGuard:t.requestGuard})}async screenshot(t){let{sessionId:n}=t,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),i;if(t.target!==void 0){let d=await dR(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${BL(t.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await d.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await mR(n,i,"browser_screenshot"),l=0,c=0;if(t.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:s,bytes:a,width:l,height:c,dataBase64:i.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);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(t){let n=this.sessions.get(t);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(t,r),r}updateSessionFromObservation(t,n,r,o,i){t.knownElements=new Map(n.map(s=>[s.id,s])),t.currentUrl=r,t.currentTitle=o,t.lastAction=i,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:i}=await mR(n,o,r);return i}catch{return null}}}});var Rs={};Fo(Rs,{__resetBrowserRegistryForTests:()=>Kle,browserProviderActive:()=>Hle,closeBrowserProvider:()=>gR,getBrowserProvider:()=>jle,peekBrowserProvider:()=>Wle});function HL(){Promise.resolve(gR()).then(()=>{process.exit(130)})}function WL(){Promise.resolve(gR()).then(()=>{process.exit(143)})}function KL(){Ar=null}function Ule(){yh||(process.on("SIGINT",HL),process.on("SIGTERM",WL),process.on("exit",KL),yh=!0)}function GL(){yh&&(process.removeListener("SIGINT",HL),process.removeListener("SIGTERM",WL),process.removeListener("exit",KL),yh=!1)}async function jle(e){return Ar!==null?Ar:(Es!==null||(Es=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(jL(),UL)),n=vL(e),r=new t(n);return Ule(),Ar=r,Es=null,r})()),Es)}async function gR(){if(Ar===null)return;let e=Ar;Ar=null,Es=null,GL(),await e.shutdown()}function Hle(){return Ar!==null}function Wle(){return Ar}function Kle(){Ar=null,Es=null,GL()}var Ar,Es,yh,xs=y(()=>{"use strict";uh();Ar=null,Es=null,yh=!1});async function qL(e,t){try{return await cL(e,t)}catch(n){return B("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function Yle(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(xs(),Rs));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function zL(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??Yle,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let u=await ch(n,e,{headers:Jle,signal:t.signal},o);l=u.status,a=u.url||e;let p=u.headers.get("content-type")??"";if(u.ok){if(Vle.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await u.text();if(zle.test(p)&&!qle.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await qL(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(u){if(t.signal.aborted||u instanceof Yn||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;c=u}if(!(i===null||i.textLength<200)&&i!==null){let u=nR({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await Fu(e,o);let u=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>Fu(f,o)});u.finalUrl!==e&&/^https?:\/\//i.test(u.finalUrl)&&await Fu(u.finalUrl,o);let p=await qL(u.html,u.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||p.textLength>=i.textLength){let f=nR({html:u.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:u.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(u){if(t.signal.aborted||u instanceof Yn)throw u;if(i===null){let p=u instanceof Error?u.message:String(u),f=c instanceof Error?c.message:`HTTP ${l??"error"}`,g=new Error(`web_scrape could not retrieve ${e}: fetch failed (${f}) and render failed (${p}).`);throw g.cause=u,g}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${l??"error"}).`)}var qle,zle,Vle,Jle,VL=y(()=>{"use strict";dL();rR();aR();me();qle=/(text\/html|application\/xhtml\+xml)/i,zle=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,Vle=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,Jle={"User-Agent":"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/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function Zle(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(Xle,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),Qle),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=Pe(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let c=i.statusText?` ${i.statusText}`:"";throw new Error(`Exa Search HTTP ${i.status}${c}${l}`)}let s;try{s=await i.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(s.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function JL(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?Zle({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function YL(e,t){if(t.length===0)return`# Search results for "${e}"
318
318
 
319
319
  (no results)`;let n=[`# Search results for "${e}"`,""];return t.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
320
320
  `).trimEnd()}var Xle,Qle,XL=y(()=>{"use strict";Vn();Xle="https://api.exa.ai/search",Qle=10});function bh(e){if(e instanceof Error&&e.name==="TimeoutError")return"timeout";let t=e instanceof Error?e.message:String(e);return/Timeout\s+\d+\s*ms exceeded/i.test(t)?"timeout":void 0}var As=y(()=>{"use strict";ph()});function ice(e){if(!e||typeof e!="object")return{error:"Invalid input: expected an object"};let t=e,n=t.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,i;if(r==="search"){if(typeof t.query!="string"||t.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};i=t.query}else{if(typeof t.url!="string"||t.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let l;try{l=new URL(t.url)}catch{return{error:`Invalid input: "${t.url}" is not a valid absolute URL`}}if(l.protocol!=="http:"&&l.protocol!=="https:")return{error:`Invalid input: protocol "${l.protocol}" not supported (http/https only)`};o=l.toString()}let s=ece;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};s=Math.min(t.timeout_ms,tce)}let a=nce;if(t.max_bytes!==void 0){if(typeof t.max_bytes!="number"||!Number.isFinite(t.max_bytes)||t.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(t.max_bytes,rce)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function hR(e,t){return Buffer.byteLength(e,"utf8")<=t?{content:e,truncated:!1}:{content:Zr(e,t),truncated:!0}}function sce(e={}){let t=e.fetchFn??globalThis.fetch,n=e.env??process.env,r=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{};return async(o,i)=>{if(typeof t!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=ice(o);if("error"in s)return{content:s.error,isError:!0};if(i.aborted){let u=i.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let a=new AbortController,l=()=>{a.abort(i.reason)},c,d=()=>{let u=a.signal.reason;return u instanceof Error?u.message:String(u??"aborted")};try{if(i.addEventListener("abort",l,{once:!0}),c=setTimeout(()=>{a.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs),s.url!==void 0){let p=await sR(s.url,r);if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(!p.allowed)return{content:`web_scrape blocked: ${p.reason}`,isError:!0}}if(s.mode==="raw"){let p;try{let h={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};p=await ch(t,s.url,h,r)}catch(h){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:h instanceof Yn?{content:`web_scrape blocked: ${h.message}`,isError:!0}:{content:`web_scrape network error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}if(!p.ok)return{content:`web_scrape HTTP ${p.status} ${p.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let f;try{f=await p.text()}catch(h){return{content:`web_scrape read error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}let g=hR(f,s.maxBytes);return{content:g.content,...g.truncated?{truncated:!0}:{}}}if(s.mode==="markdown")try{let p=await zL(s.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:s.timeoutMs,signal:a.signal,...e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{}});if(p.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0};let f=hR(uL(p.markdown,p.advisory),s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(p instanceof Yn)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),g=Yt(p)&&!lR(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${Lu()}\`)`:"";return{content:`web_scrape markdown error: ${f}${g}`,isError:!0}}let u=JL({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in u)return{content:u.error,isError:!0};try{let p=await u.search(s.query,{limit:oce,timeoutMs:s.timeoutMs,signal:a.signal}),f=hR(YL(s.query,p),s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:{content:`web_scrape search error (${u.name}): ${p instanceof Error?p.message:String(p)}`,isError:!0}}}finally{c!==void 0&&clearTimeout(c),i.removeEventListener("abort",l)}}}var ece,tce,nce,rce,oce,QL,ZL=y(()=>{"use strict";VL();XL();aR();zo();rR();As();ece=3e4,tce=12e4,nce=1e5,rce=1e6,oce=10;QL=sce()});import{existsSync as tN,mkdirSync as ace,readFileSync as lce,renameSync as cce,unlinkSync as dce,writeFileSync as uce}from"node:fs";import{dirname as eN,join as pce}from"node:path";import{randomBytes as mce}from"node:crypto";function Cn(e){let t=e??rT();if(!tN(t))return[];try{let n=lce(t,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);return console.error(`[schedule-store] failed to parse ${t}: ${r}`),[]}}function Cs(e,t){let n=t??rT();ace(eN(n),{recursive:!0});let r=pce(eN(n),`.schedules.json.${process.pid}.${mce(4).toString("hex")}.tmp`),o=JSON.stringify(e,null,2);try{uce(r,o,"utf-8"),cce(r,n)}catch(i){try{tN(r)&&dce(r)}catch{}throw i}}function Sh(e,t){let n=Cn(t),r=n.map(l=>l.id),o=fce(e.name),i=gce(o,r),s=new Date().toISOString(),a={...e,notifyOn:e.notifyOn??"failure",id:i,createdAt:s,updatedAt:s};return n.push(a),Cs(n,t),a}function wh(e,t){let n=Cn(t),r=n.length,o=n.filter(i=>i.id!==e);return o.length===r?!1:(Cs(o,t),!0)}function Bu(e,t){return Cn(t).find(n=>n.id===e)}function fce(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function gce(e,t){if(!t.includes(e))return e;let n=2;for(;t.includes(`${e}-${n}`);)n+=1;return`${e}-${n}`}function nN(e){return{taskId:e.id,command:e.command,trigger:e.trigger??"cron",...e.cron!==void 0?{cronExpression:e.cron}:{},...e.notifyOn!==void 0?{notifyOn:e.notifyOn}:{},...e.notifyChat!==void 0?{notifyChat:e.notifyChat}:{}}}var vh=y(()=>{"use strict";K()});import{existsSync as hce,readFileSync as yce}from"node:fs";import{join as bce}from"node:path";async function Xn(e,t,n){let r;try{let o=bce(If("default"),"port");if(!hce(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=yce(o,"utf-8").trim();if(r=parseInt(i,10),Number.isNaN(r))return{synced:!1,detail:"daemon-not-detected (invalid port file)"}}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let o=await fetch(`http://localhost:${r}${t}`,{method:e,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return o.ok?{synced:!0,detail:"synced"}:e==="POST"&&o.status===409?{synced:!0,detail:"already-registered"}:e==="DELETE"&&o.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${o.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}var Qo,yR=y(()=>{"use strict";K();Qo="Change saved to schedules.json, but a running daemon (if any) did not pick it up \u2014 it will apply on the next daemon (re)start."});import{existsSync as Sce}from"node:fs";import{readFile as wce}from"node:fs/promises";var rN,oN,iN,sN,aN=y(()=>{"use strict";vh();K();yR();rN=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected object",isError:!0};let n=e;if(typeof n.name!="string"||!n.name)return{content:"Invalid input: name required",isError:!0};if(typeof n.command!="string"||!n.command)return{content:"Invalid input: command required",isError:!0};if(typeof n.cron!="string"||!n.cron)return{content:"Invalid input: cron required",isError:!0};let r=n.cron.trim().split(/\s+/);if(r.length!==5&&r.length!==6)return{content:"Invalid input: cron must be a 5 or 6-field expression",isError:!0};let o=n.notifyChat;if(o!==void 0&&typeof o!="number"&&typeof o!="string")return{content:"Invalid input: notifyChat must be a number (chat id) or string (chat id or alias name)",isError:!0};let i=Sh({name:n.name,command:n.command,cron:n.cron,trigger:n.trigger??"cron",notifyOn:n.notifyOn,...o!==void 0?{notifyChat:o}:{},enabled:typeof n.enabled=="boolean"?n.enabled:!0}),s=i.enabled?await Xn("POST","/tasks",{taskId:i.id,command:i.command,cron:i.cron,trigger:i.trigger,notifyOn:i.notifyOn,...i.notifyChat!==void 0?{notifyChat:i.notifyChat}:{}}):await Xn("DELETE",`/tasks/${i.id}`);return{content:JSON.stringify({id:i.id,name:i.name,cron:i.cron,enabled:i.enabled,daemonSynced:s.synced,syncDetail:s.detail,...s.synced?{}:{syncNote:Qo}})}},oN=async(e,t)=>{let n=Cn();return{content:JSON.stringify(n.map(r=>({id:r.id,name:r.name,cron:r.cron,trigger:r.trigger,enabled:r.enabled,notifyOn:r.notifyOn})))}},iN=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected object",isError:!0};let n=e;if(typeof n.taskId!="string"||!n.taskId)return{content:"Invalid input: taskId required",isError:!0};let r=n.taskId,o=typeof n.limit=="number"?Math.min(Math.max(1,n.limit),50):10,i=pr();if(!Sce(i))return{content:JSON.stringify([])};let s;try{let c=await wce(i);s=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=s.split(`
@@ -1491,7 +1491,7 @@ ${pq}
1491
1491
 
1492
1492
  ${r}`}function Zt(e=process.cwd()){let t=uq(),n=Xe(void 0,e),r=n.systemPrompt,o=n.systemPromptSource,i=t!==void 0&&t.trim().length>0,s=r!==void 0&&r.trim().length>0,a;return i&&s?a=`framework+${o??"unknown"}`:i?a="framework":s?a=o??"unknown":a="none",{prompt:mq(t,r),source:a}}var pq,fq=y(()=>{"use strict";At();pq=`# Operator configuration
1493
1493
 
1494
- The instructions below come from this operator's configuration (AFK.md, afk.config.json, or AFK_SYSTEM_PROMPT). Treat them as refinements layered on top of the operating posture above \u2014 follow them unless they conflict with the Priorities or Constraints already stated.`});function qs(e,t){let n=e;if(n===void 0&&t?.model!==void 0&&ie(t.model,{...t.openaiBaseUrl!==void 0?{openaiBaseUrl:t.openaiBaseUrl}:{}})==="openai-compatible"&&(n="openai-compatible"),n===void 0)return;if(!gq.includes(n))throw new Error(`Invalid --provider value: ${n}. Expected one of: ${gq.join(", ")}`);let r=()=>{let o=[...Gt,...gs,...ht,pn];return t?.subagentExecutor&&o.push("agent"),t?.skillExecutor&&o.push("skill"),t?.composeExecutor&&o.push("compose"),t?.mcpManager&&o.push(...t.mcpManager.getMcpToolWireNames()),o};if(n==="anthropic"||n==="anthropic-direct")return new et({permissions:{allowedTools:r()},subagentExecutor:t?.subagentExecutor,skillExecutor:t?.skillExecutor,composeExecutor:t?.composeExecutor,...t?.memoryStore!==void 0?{memoryStore:t.memoryStore}:{},...t?.mcpManager!==void 0?{mcpManager:t.mcpManager}:{},...t?.fastModeController!==void 0?{fastModeController:t.fastModeController}:{}});if(n==="openai"||n==="openai-compatible")return new fn({permissions:{allowedTools:r()},...t?.subagentExecutor!==void 0?{subagentExecutor:t.subagentExecutor}:{},...t?.skillExecutor!==void 0?{skillExecutor:t.skillExecutor}:{},...t?.composeExecutor!==void 0?{composeExecutor:t.composeExecutor}:{},...t?.memoryStore!==void 0?{memoryStore:t.memoryStore}:{},...t?.mcpManager!==void 0?{mcpManager:t.mcpManager}:{},...t?.openaiBaseUrl!==void 0?{baseURL:t.openaiBaseUrl}:{}})}var gq,hq=y(()=>{"use strict";je();pp();cn();Dt();$t();Ps();gq=["anthropic","anthropic-direct","openai-codex","openai","openai-compatible"]});function Dn(){return en(at())}function aS(){return Eu()}function en(e){return Be(e)}function at(){let e=k.AFK_MODEL??k.CLAUDE_MODEL;return!e||e.length===0?"medium":e}function mc(e){let t=k.AFK_DEFAULT_SUBAGENT_MODEL;return t&&t.length>0?t:typeof e=="string"&&ie(e)==="openai-compatible"?e:"medium"}function ki(e){if(e===void 0)return;if(e==="adaptive")return{type:"adaptive"};if(e==="disabled")return{type:"disabled"};if(e==="enabled:max")return{type:"enabled",budgetTokens:Number.POSITIVE_INFINITY};let t=/^enabled:(\d+)$/.exec(e);if(t){let n=parseInt(t[1],10);if(Number.isNaN(n))throw new Error(`Invalid thinking budget: ${e}`);return{type:"enabled",budgetTokens:n}}throw new Error(`Invalid --thinking value: ${e}. Expected 'adaptive' | 'disabled' | 'enabled:<N>' | 'enabled:max'`)}function Ti(e){if(e!==void 0){if(yq.includes(e))return e;throw new Error(`Invalid --effort value: ${e}. Expected one of: ${yq.join(", ")}`)}}function fc(){return ki(k.AFK_THINKING)}function gc(){return Ti(k.AFK_EFFORT)}function hc(e){if(e===void 0)return;if(e===""||e==="NaN")throw new Error(`Invalid --max-budget-usd value: ${JSON.stringify(e)}. Expected a non-negative number.`);let t=Number(e);if(!Number.isFinite(t))throw new Error(`Invalid --max-budget-usd value: ${JSON.stringify(e)}. Expected a non-negative number.`);if(t<0)throw new Error(`Invalid --max-budget-usd value: ${JSON.stringify(e)}. Must be non-negative.`);return t}function $C(){return hc(k.AFK_MAX_BUDGET_USD)}function DC(){return hc(k.AFK_TASK_BUDGET)}function yc(e){if(e===void 0)return;if(e==="max")return Number.POSITIVE_INFINITY;if(e===""||e==="NaN")throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(e)}. Expected a positive integer or 'max'.`);if(!/^\d+$/.test(e))throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(e)}. Expected a positive integer or 'max'.`);let t=Number(e);if(!Number.isFinite(t)||!Number.isInteger(t)||t<=0)throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(e)}. Must be a positive integer.`);return t}function Kp(){return yc(k.AFK_MAX_OUTPUT_TOKENS)}function cSe(e){if(e===void 0)return;let t=Number(e);if(!(!Number.isFinite(t)||t<=0))return Math.floor(t)}function bc(){return cSe(k.AFK_MAX_TOOL_USE_ITERATIONS)}function bq(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.addReadRoot=="function"&&typeof t.addWriteRoot=="function"&&typeof t.revokeRoot=="function"&&typeof t.getGrants=="function"}var yq,lt=y(()=>{"use strict";je();Ht();j();fq();hq();yq=["low","medium","high","xhigh","max"]});function Sc(e,t,n="one-shot"){if(!e)return e;let r=[e];return t&&r.push(dSe),pSe.has(n)&&r.push(uSe),r.join(`
1494
+ The instructions below come from this operator's configuration (AFK.md, afk.config.json, or AFK_SYSTEM_PROMPT). Treat them as refinements layered on top of the operating posture above \u2014 follow them unless they conflict with the Priorities or Constraints already stated.`});function qs(e,t){let n=e;if(n===void 0&&t?.model!==void 0&&ie(t.model,{...t.openaiBaseUrl!==void 0?{openaiBaseUrl:t.openaiBaseUrl}:{}})==="openai-compatible"&&(n="openai-compatible"),n===void 0)return;if(!gq.includes(n))throw new Error(`Invalid --provider value: ${n}. Expected one of: ${gq.join(", ")}`);let r=()=>{let o=[...Gt,...gs,...ht,pn];return t?.subagentExecutor&&o.push("agent"),t?.skillExecutor&&o.push("skill"),t?.composeExecutor&&o.push("compose"),t?.mcpManager&&o.push(...t.mcpManager.getMcpToolWireNames()),o};if(n==="anthropic"||n==="anthropic-direct")return new et({permissions:{allowedTools:r()},subagentExecutor:t?.subagentExecutor,skillExecutor:t?.skillExecutor,composeExecutor:t?.composeExecutor,...t?.memoryStore!==void 0?{memoryStore:t.memoryStore}:{},...t?.mcpManager!==void 0?{mcpManager:t.mcpManager}:{},...t?.fastModeController!==void 0?{fastModeController:t.fastModeController}:{}});if(n==="openai"||n==="openai-compatible")return new fn({permissions:{allowedTools:r()},...t?.subagentExecutor!==void 0?{subagentExecutor:t.subagentExecutor}:{},...t?.skillExecutor!==void 0?{skillExecutor:t.skillExecutor}:{},...t?.composeExecutor!==void 0?{composeExecutor:t.composeExecutor}:{},...t?.memoryStore!==void 0?{memoryStore:t.memoryStore}:{},...t?.mcpManager!==void 0?{mcpManager:t.mcpManager}:{},...t?.openaiBaseUrl!==void 0?{baseURL:t.openaiBaseUrl}:{}})}var gq,hq=y(()=>{"use strict";je();pp();cn();Dt();$t();Ps();gq=["anthropic","anthropic-direct","openai-codex","openai","openai-compatible"]});function Dn(){return en(at())}function aS(){return Eu()}function en(e){return Be(e)}function at(){let e=k.AFK_MODEL??k.CLAUDE_MODEL;return!e||e.length===0?"medium":e}function mc(e){let t=k.AFK_DEFAULT_SUBAGENT_MODEL;return t&&t.length>0?t:typeof e=="string"&&ie(e)==="openai-compatible"?e:"medium"}function ki(e){if(e===void 0)return;if(e==="adaptive")return{type:"adaptive"};if(e==="disabled")return{type:"disabled"};if(e==="max"||e==="enabled:max")return{type:"enabled",budgetTokens:Number.POSITIVE_INFINITY};let t=/^enabled:(\d+)$/.exec(e);if(t){let n=parseInt(t[1],10);if(Number.isNaN(n))throw new Error(`Invalid thinking budget: ${e}`);return{type:"enabled",budgetTokens:n}}throw new Error(`Invalid --thinking value: ${e}. Expected 'adaptive' | 'disabled' | 'max' | 'enabled:<N>' | 'enabled:max'`)}function Ti(e){if(e!==void 0){if(yq.includes(e))return e;throw new Error(`Invalid --effort value: ${e}. Expected one of: ${yq.join(", ")}`)}}function fc(){return ki(k.AFK_THINKING)}function gc(){return Ti(k.AFK_EFFORT)}function hc(e){if(e===void 0)return;if(e===""||e==="NaN")throw new Error(`Invalid --max-budget-usd value: ${JSON.stringify(e)}. Expected a non-negative number.`);let t=Number(e);if(!Number.isFinite(t))throw new Error(`Invalid --max-budget-usd value: ${JSON.stringify(e)}. Expected a non-negative number.`);if(t<0)throw new Error(`Invalid --max-budget-usd value: ${JSON.stringify(e)}. Must be non-negative.`);return t}function $C(){return hc(k.AFK_MAX_BUDGET_USD)}function DC(){return hc(k.AFK_TASK_BUDGET)}function yc(e){if(e===void 0)return;if(e==="max")return Number.POSITIVE_INFINITY;if(e===""||e==="NaN")throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(e)}. Expected a positive integer or 'max'.`);if(!/^\d+$/.test(e))throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(e)}. Expected a positive integer or 'max'.`);let t=Number(e);if(!Number.isFinite(t)||!Number.isInteger(t)||t<=0)throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(e)}. Must be a positive integer.`);return t}function Kp(){return yc(k.AFK_MAX_OUTPUT_TOKENS)}function cSe(e){if(e===void 0)return;let t=Number(e);if(!(!Number.isFinite(t)||t<=0))return Math.floor(t)}function bc(){return cSe(k.AFK_MAX_TOOL_USE_ITERATIONS)}function bq(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.addReadRoot=="function"&&typeof t.addWriteRoot=="function"&&typeof t.revokeRoot=="function"&&typeof t.getGrants=="function"}var yq,lt=y(()=>{"use strict";je();Ht();j();fq();hq();yq=["low","medium","high","xhigh","max"]});function Sc(e,t,n="one-shot"){if(!e)return e;let r=[e];return t&&r.push(dSe),pSe.has(n)&&r.push(uSe),r.join(`
1495
1495
 
1496
1496
  `)}var dSe,uSe,pSe,cS=y(()=>{"use strict";dSe='[skill-routing: active]\n\nRoute recurring work through registered skills instead of rolling ad-hoc solutions:\n\n- Before non-trivial implementation (multi-file edits, new features, config/build changes \u2014 anything that writes) \u2192 `/ground-state` first. Do NOT substitute inline `git status`/`get_runtime_state` \u2014 the skill triangulates git + infra + prior-session memory in parallel, which the inline checks miss. If `/ground-state` dispatch fails (depth limit, unavailable), fall back to inline checks AND note the coverage gap.\n- Bugs, failing tests, or regressions \u2192 `/diagnose`\n- High-stakes sub-agent output that will drive edits or commits \u2192 `/shadow-verify` before acting\n- Refactor needing parallel waves \u2192 `/parallelize`\n- Parallel or dependent multi-task work \u2192 `compose` tool (DAG of subagent nodes)\n- Greenfield feature where a written spec would genuinely help (novel scope, multi-day work, or external stakeholders involved) \u2192 `/mint`\n\nDo NOT reach for `/mint` for: bug fixes (use `/diagnose`), refactors with known shape, single-feature edits, work already spec\'d in chat, or anything where the spec/approve pause would feel like ceremony. Implement directly in those cases.\n\nCommon composed sequences \u2014 reach for these when the task shape matches:\n\n- Bug with failing test and non-trivial fix \u2192 `/diagnose` \u2192 `/shadow-verify` on the proposed fix\n- Refactor needing parallel waves \u2192 plan \u2192 `/parallelize` \u2192 build waves\n- Diagnose + fix in parallel \u2192 `compose` with two independent nodes\n- Research \u2192 implement \u2192 verify pipeline \u2192 `compose` with edges: research\u2192implement\u2192verify\n- Multiple independent investigations \u2192 `compose` with N nodes, no edges\n\nReach for context-isolated investigators when the task is exploratory:\n\n- Map an unfamiliar module before editing \u2192 `/gather` or `/research`\n- Re-derive a load-bearing claim independently \u2192 `/shadow-verify`\n- Audit a diff before merge \u2192 `/review`\n- Generate alternatives before committing to a plan \u2192 `/devils-advocate`\n\nOr dispatch a raw `agent` call when no skill matches but the work is parallelizable, verification-heavy, or would otherwise consume substantial inline context.\n\nSkip orchestration for: single-line edits, trivial Q&A, and direct tool calls the user explicitly requested. The goal is leverage, not ceremony. If a skill would add overhead without adding value, don\'t invoke it.\n\nDefault to acting autonomously. `ask_question` is a last resort, not a first move \u2014 every question blocks on the operator, who is often away from keyboard.\n\nBefore you ask, you MUST exhaust the tools you have: read the files, check git, search the codebase and docs, inspect runtime state. If any tool can get you the answer, use the tool \u2014 never ask the operator for something you can discover yourself. When a wrong guess would be cheap or reversible, make a reasonable assumption, proceed, and state the assumption instead of asking.\n\n**Answerability \u2014 a question only helps if a human will actually answer it:**\n\n`surface` (from `get_runtime_state`, view `"self"`) is a partial signal, not a guarantee:\n- `daemon`, or any session started by a scheduler, cron job, or another agent, has no human watching \u2014 never block on `ask_question` here.\n- `cli` is ambiguous: the interactive REPL and the Telegram bot can reach a human, but one-shot `chat` runs and sub-agent forks report the same `cli` and have no elicitation handler \u2014 there `ask_question` returns `{ action: \'decline\' }` instantly.\n- Even when a handler exists, the operator is usually away, so a blocking question can stall until the turn aborts.\n\nSo treat `ask_question` as best-effort: a `decline` or `cancel` result means "no answer is coming," not a failure to abort the task on. When you cannot be sure a human will answer, instead of asking:\n1. **Proceed on a stated assumption** \u2014 pick the most reasonable interpretation, act on it, and record the assumption in your Done/Blocked terminal state for async review.\n2. **Emit a Blocked artifact** \u2014 if no safe assumption exists and proceeding would be irreversible, end the turn with a **Blocked** terminal state naming exactly what the operator must supply before the next run.\n\nReserve `ask_question` for the narrow set of things no tool can resolve: a genuinely ambiguous requirement whose readings lead to materially different work, a decision with significant or irreversible consequences, or context that lives only in the operator\'s head (a preference, a secret, an external constraint):\n\n- Question types: `text` (open-ended), `confirm` (yes/no), `choice` (single pick from list), `multi_choice` (multi-pick), `number` (numeric with optional bounds). When `allow_custom: true`, the result may include `custom_value` instead of `value` \u2014 check `content.custom_value !== undefined` to detect a free-form answer.\n- Ask one focused question at a time. Do NOT ask multiple questions in a single call, and do NOT stack several ask_question calls across a turn \u2014 fold the genuine unknowns into the single most decision-relevant question.\n- Do NOT use when the user has already provided sufficient context \u2014 infer and proceed instead.\n- The result `action` will be `accept` (answered), `cancel` (user interrupted), `decline` (no handler), or `skip` (optional question skipped).\n- `allow_custom` (choice/multi_choice only): opt-in to a free-form entry affordance. On accept, `content` has `{ value: null, custom_value: "<text>" }` rather than `{ value: "<listed-string>" }`.\n- After a `cancel` or `decline`, stop and tell the user what information you need \u2014 do not loop and re-ask.',uSe=`[end-of-turn protocol]
1497
1497
 
@@ -1740,7 +1740,7 @@ ${o}`}}}return{...e,systemPrompt:o}}Ot();st();lt();cn();Dt();$t();Ps();function
1740
1740
  `),this.client=a,this.connected=!0,this.pendingAuthTransport=void 0;let l=await PS(this.client.listTools(),i,()=>new Error(`MCP server "${this.serverName}" listTools timed out after ${i}ms`),()=>a.close().catch(()=>{})),c=this.client.getServerVersion();return{tools:l.tools,serverInfo:c?{name:c.name,version:c.version}:void 0}}async listTools(){if(!this.client)throw new Error(`McpClient(${this.serverName}): not connected`);let t=this.config.timeout??e_;return(await PS(this.client.listTools(),t,()=>new Error(`MCP server "${this.serverName}" listTools timed out after ${t}ms`))).tools}async refreshTools(){return this.listTools()}async callTool(t,n,r){if(!this.client)return{content:`MCP server "${this.serverName}" is not connected`,isError:!0};if(r.aborted)return{content:"Tool call aborted",isError:!0};let o=this.config.timeout??e_,i;try{i=await this.client.callTool({name:t,arguments:n??{}},Bwe,{signal:r,timeout:o})}catch(s){let a=s instanceof Error?s.message:String(s);return{content:`MCP tool "${this.serverName}.${t}" failed: ${a}`,isError:!0}}return Uwe(i)}async finishAuth(t){if(!this.pendingAuthTransport)throw new Error(`McpClient(${this.serverName}): no pending OAuth transport \u2014 server is not in oauth_pending state`);await this.pendingAuthTransport.finishAuth(t)}async disconnect(){if(this.pendingAuthTransport=void 0,!this.client)return;let t=this.client;this.client=void 0,this.connected=!1;try{await t.close()}catch{}}};function Uwe(e){let t=[];for(let r of e.content??[])if(r.type==="text")t.push(r.text);else if(r.type==="image")t.push(`[image block: mimeType=${r.mimeType}, ${r.data.length} bytes base64]`);else if(r.type==="resource"){let o="resource"in r&&typeof r.resource=="object"?r.resource.uri??"(unknown)":"(unknown)";t.push(`[resource block: ${o}]`)}else t.push(`[unknown block: ${JSON.stringify(r)}]`);let n=t.join(`
1741
1741
  `);return{content:n.length===0?"(empty tool result)":n,...e.isError?{isError:!0}:{}}}function jwe(e,t,n){let r=t.type??(t.command?"stdio":"streamable-http");return{primary:AS(e,t,n),fallback:r==="streamable-http"?()=>AS(e,{...t,type:"sse"},n):null}}function Hwe(e){return e instanceof yz&&(e.code===404||e.code===405)}function Wwe(e){return e instanceof yz?e.code:void 0}function PS(e,t,n,r){let o=null,i=new Promise((s,a)=>{o=setTimeout(()=>{if(r!==void 0)try{let l=r();l&&typeof l.then=="function"&&l.catch(()=>{})}catch{}a(n())},t)});return Promise.race([e,i]).finally(()=>{o!==null&&clearTimeout(o)})}import{createHash as Kwe}from"node:crypto";var bz="mcp__",Sz="__",n_=64,Gwe=6;function Qp(e){if(e.length===0)return"_";let n=e.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_{2,}/g,"_");return n.length===0?"_":n}function qwe(e){return Kwe("sha256").update(e).digest("hex").slice(0,Gwe)}function wz(e,t){let n=Qp(e),r=Qp(t),o=`${bz}${n}${Sz}${r}`;if(o.length<=n_)return o;let s=`${`${bz}${qwe(e)}${Sz}`}${r}`;return s.length<=n_?s:s.slice(0,n_)}function Zp(e){let t=new Map,n=new Map;for(let{serverName:o,toolNames:i}of e)for(let s of i){let a=wz(o,s),l={serverName:o,originalToolName:s},c=t.get(a);if(c===void 0){t.set(a,l);continue}if(c.serverName===o&&c.originalToolName===s)continue;let d=n.get(a)??[c];d.push(l),n.set(a,d)}let r=[];for(let[o,i]of n)r.push({wireName:o,pairs:i});return{tools:t,conflicts:r}}pe();var Ro=class e{records;nameRegistry;onToolsRefreshed;constructor(t){this.records=t;let n=[];for(let[o,i]of t)i.state.status==="connected"&&n.push({serverName:o,toolNames:i.tools.map(s=>s.name)});let r=Zp(n);if(r.conflicts.length>0){let o=r.conflicts.map(i=>{let s=i.pairs.map(a=>`${a.serverName}.${a.originalToolName}`).join(", ");return` ${i.wireName} \u2190 ${s}`});throw new Error(`MCP tool name conflicts (rename one of the servers in mcp.json):
1742
1742
  ${o.join(`
1743
- `)}`)}this.nameRegistry=r.tools}static async fromConfig(t,n={}){if(n.warnings&&n.warnings.length>0)for(let c of n.warnings)console.warn(`[mcp] ${c}`);let r=new Map,o=[],i={manager:void 0};for(let[c,d]of Object.entries(t)){let u=Qp(c);if(u!==c&&console.warn(`[mcp] server name "${c}" sanitized to "${u}" for wire encoding`),d.disabled){r.set(c,{client:void 0,tools:[],state:{serverName:c,config:d,status:"disabled",toolCount:0}});continue}let f={client:void 0,tools:[],state:{serverName:c,config:d,status:"connecting",toolCount:0}};r.set(c,f);let g=new Cc(c,d);f.client=g,g.onTransportError=b=>{f.state.status="error",f.state.error=MS(b.message,200),console.warn(`[mcp:${c}] transport error: ${b.message}`)},g.onToolListChanged=()=>{i.manager?.refreshServer(c).catch(b=>{let S=b instanceof Error?b.message:String(b);console.warn(`[mcp:${c}] refreshServer failed: ${S}`)})};let h=(async()=>{let b=Date.now();re(n.traceWriter,{phase:"mcp_server_start",metadata:{server:c}});let S="error",w=0;try{let{tools:v,serverInfo:E}=await g.connect();f.tools=v,f.state.status="connected",f.state.toolCount=v.length,f.state.lastListedAt=Date.now(),S="connected",w=v.length;let T=E?`${E.name}@${E.version}`:"unknown";console.log(`[mcp:${c}] connected (${T}) \u2014 ${v.length} tool(s)`)}catch(v){if(v instanceof t_){f.state.status="oauth_pending",S="oauth_pending",console.log(`[mcp:${c}] OAuth authorization required \u2014 check Telegram or stderr for the auth URL`);return}let E=v instanceof Error?v.message:String(v);if(f.state.status="error",f.state.error=MS(E,200),d.alwaysLoad===!0)throw new Error(`MCP server "${c}" is marked alwaysLoad but failed to connect: ${E}`);console.warn(`[mcp:${c}] connect failed: ${E}`)}finally{re(n.traceWriter,{phase:"mcp_server_done",durationMs:Date.now()-b,metadata:{server:c,status:S,toolCount:w}})}})();o.push(h)}let a=(await Promise.allSettled(o)).find(c=>c.status==="rejected");if(a){for(let c of r.values())c.client&&await c.client.disconnect().catch(()=>{});throw a.reason}let l=new e(r);return i.manager=l,l}getMcpTools(){let t=[];for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let i=this.records.get(r);if(!i||i.state.status!=="connected")continue;let s=i.tools.find(a=>a.name===o);s&&t.push(zwe(n,s))}return t}getMcpHandlers(){let t=new Map;for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let i=this.records.get(r);!i||i.state.status!=="connected"||t.set(n,async(s,a)=>i.client?i.client.callTool(o,s,a):{content:`MCP server "${r}" is not connected`,isError:!0})}return t}async refreshServer(t){let n=this.records.get(t);if(!n||!n.client||n.state.status!=="connected")throw new Error(`McpManager.refreshServer("${t}"): server is not connected`);let r=await n.client.refreshTools();for(let[i,s]of this.nameRegistry)s.serverName===t&&this.nameRegistry.delete(i);let o=Zp([{serverName:t,toolNames:r.map(i=>i.name)}]);if(o.conflicts.length>0)for(let i of o.conflicts){let s=i.pairs.map(a=>`${a.serverName}.${a.originalToolName}`).join(", ");console.warn(`[mcp:${t}] wire-name conflict after refresh \u2014 skipping: ${i.wireName} \u2190 ${s}`)}for(let[i,s]of o.tools)this.nameRegistry.set(i,s);n.tools=r,n.state.toolCount=r.length,n.state.lastListedAt=Date.now(),console.log(`[mcp:${t}] tool list refreshed \u2014 ${r.length} tool(s)`),this.onToolsRefreshed?.(t)}getServerStates(){return[...this.records.values()].map(t=>({...t.state}))}getMcpToolWireNames(){return[...this.nameRegistry.keys()]}async completeAuth(t,n){let r=this.records.get(t);if(!r)throw new Error(`McpManager.completeAuth("${t}"): server not found`);if(r.state.status!=="oauth_pending")throw new Error(`McpManager.completeAuth("${t}"): server is not in oauth_pending state (current status: ${r.state.status})`);if(!r.client)throw new Error(`McpManager.completeAuth("${t}"): no client record \u2014 server was never connected`);await r.client.finishAuth(n),await r.client.disconnect().catch(s=>{let a=s instanceof Error?s.message:String(s);console.warn(`[mcp:${t}] completeAuth disconnect warning: ${a}`)});let o=new Cc(t,r.state.config);o.onTransportError=s=>{r.state.status="error",r.state.error=MS(s.message,200),console.warn(`[mcp:${t}] transport error: ${s.message}`)},o.onToolListChanged=()=>{this.refreshServer(t).catch(s=>{let a=s instanceof Error?s.message:String(s);console.warn(`[mcp:${t}] refreshServer failed: ${a}`)})},r.state.status="connecting",r.state.error=void 0,r.client=o;try{let{tools:s,serverInfo:a}=await o.connect();r.tools=s,r.state.status="connected",r.state.toolCount=s.length,r.state.lastListedAt=Date.now();let l=a?`${a.name}@${a.version}`:"unknown";console.log(`[mcp:${t}] OAuth complete \u2014 connected (${l}) \u2014 ${s.length} tool(s)`)}catch(s){let a=s instanceof Error?s.message:String(s);throw r.state.status="error",r.state.error=MS(a,200),new Error(`McpManager.completeAuth("${t}"): reconnect failed: ${a}`)}for(let[s,a]of this.nameRegistry)a.serverName===t&&this.nameRegistry.delete(s);let i=Zp([{serverName:t,toolNames:r.tools.map(s=>s.name)}]);for(let[s,a]of i.tools)this.nameRegistry.set(s,a);this.onToolsRefreshed?.(t)}hasAnyConnected(){for(let t of this.records.values())if(t.state.status==="connected")return!0;return!1}size(){return this.records.size}async disconnectAll(){let t=[];for(let[n,r]of this.records)r.client&&t.push(r.client.disconnect().catch(o=>{let i=o instanceof Error?o.message:String(o);console.warn(`[mcp:${n}] disconnect error: ${i}`)}));await Promise.all(t)}};function zwe(e,t){let n=t.description??`MCP tool ${t.name}`;return{name:e,description:n,input_schema:t.inputSchema}}function MS(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}j();K();Vn();import{existsSync as _c,lstatSync as Vwe,readFileSync as Jwe,readdirSync as Ywe,realpathSync as vz}from"node:fs";import{isAbsolute as Xwe,join as em,relative as Qwe}from"node:path";function Zs(){return em(Hn(),"mcp.json")}function Tz(e=process.cwd()){let t=em(e,".mcp.json");if(!_c(t))return t;try{let n=vz(e),r=vz(t),o=Qwe(n,r);return o.startsWith("..")||Xwe(o)?null:t}catch{return null}}var Zwe=5;function r_(e=Je()){if(!_c(e))return[];let t=[];return Ez(e,e,0,t,new Set),t}function Ez(e,t,n,r,o){if(n>Zwe||o.has(t))return;o.add(t);let i=em(t,".claude-plugin","plugin.json");if(_c(i)){let a=em(t,".claude-plugin","mcp.json");_c(a)&&r.push(a);return}let s;try{s=Ywe(t)}catch{return}for(let a of s){if(a.startsWith("."))continue;let l=em(t,a),c;try{c=Vwe(l)}catch{continue}c.isDirectory()&&Ez(e,l,n+1,r,o)}}function eve(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return{ok:!1,error:`server "${e}" must be an object`};let n=t,r=n.type;if(r===void 0)if(typeof n.command=="string")r="stdio";else if(typeof n.url=="string")r="streamable-http";else return{ok:!1,error:`server "${e}" has no \`command\` or \`url\`; cannot infer transport`};if(r==="stdio"){if(typeof n.command!="string"||n.command.length===0)return{ok:!1,error:`stdio server "${e}" requires non-empty \`command\``}}else if(r==="streamable-http"||r==="sse"){if(typeof n.url!="string"||n.url.length===0)return{ok:!1,error:`${r} server "${e}" requires non-empty \`url\``}}else return{ok:!1,error:`server "${e}" has unsupported \`type\`: ${String(r)}`};let o={type:r};if(typeof n.command=="string"&&(o.command=n.command),Array.isArray(n.args)&&(o.args=n.args.filter(i=>typeof i=="string")),n.env!==void 0&&typeof n.env=="object"&&n.env!==null){let i={};for(let[s,a]of Object.entries(n.env))typeof a=="string"&&(i[s]=a);o.env=i}if(typeof n.url=="string"&&(o.url=n.url),n.headers!==void 0&&typeof n.headers=="object"&&n.headers!==null){let i={};for(let[s,a]of Object.entries(n.headers))typeof a=="string"&&(i[s]=a);o.headers=i}return typeof n.oauth=="boolean"&&(o.oauth=n.oauth),typeof n.disabled=="boolean"&&(o.disabled=n.disabled),typeof n.alwaysLoad=="boolean"&&(o.alwaysLoad=n.alwaysLoad),typeof n.timeout=="number"&&n.timeout>0&&(o.timeout=n.timeout),{ok:!0,config:o}}function Qs(e){if(!_c(e))return{mcpServers:{},sources:[],warnings:[]};let t=[],n;try{n=JSON.parse(Jwe(e,"utf-8"))}catch(s){let a=s instanceof Error?s.message:String(s);return t.push(`mcp.json at ${e}: parse error \u2014 ${a}`),{mcpServers:{},sources:[e],warnings:t}}if(n===null||typeof n!="object"||Array.isArray(n))return t.push(`mcp.json at ${e}: top-level must be an object`),{mcpServers:{},sources:[e],warnings:t};let o=n.mcpServers;if(o==null||typeof o!="object")return{mcpServers:{},sources:[e],warnings:t};let i={};for(let[s,a]of Object.entries(o)){let l=eve(s,a);l.ok?i[s]=l.config:t.push(`mcp.json at ${e}: skipping ${l.error}`)}return{mcpServers:i,sources:[e],warnings:t}}function tve(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function kz(e,t){let n=Pe(e);return n.length>t?n.slice(0,t)+"\u2026":n}function ea(e={}){let t=[],n=[];if(e.importedMcpConfigs&&e.importedMcpConfigs.length>0)for(let a of e.importedMcpConfigs)t.push({path:a,loaded:Qs(a)});if(e.pluginsRoot!==null){let a=e.pluginsRoot,l=a?r_(a):r_();for(let c of l)t.push({path:c,loaded:Qs(c)})}if(!e.skipUserGlobal){let a=Zs();t.push({path:a,loaded:Qs(a)})}if(!e.skipProjectLocal){let a=Tz(e.cwd);if(a===null)n.push("mcp: refusing to load project-local .mcp.json \u2014 it resolves outside the working directory (symlink or path traversal).");else if(_c(a))if(tve(k.AFK_ALLOW_PROJECT_MCP))t.push({path:a,loaded:Qs(a)}),n.push(`mcp: loaded project-local config from ${a} (AFK_ALLOW_PROJECT_MCP is set).`);else{let l=Qs(a),c=Object.entries(l.mcpServers);if(c.length>0){let d=c.map(([u,p])=>{let f=p.command?[p.command,...p.args??[]].join(" "):p.url??"(no transport)";return`${kz(u,64)} \u2192 ${kz(f,160)}`}).join("; ");n.push(`mcp: skipped ${c.length} project-local server(s) from ${a} \u2014 not spawned: [${d}]. Set AFK_ALLOW_PROJECT_MCP=1 to load ${c.length===1?"it":`these ${c.length}`} if you trust this directory.`)}}}e.cliOverride!==void 0&&t.push({path:e.cliOverride,loaded:Qs(e.cliOverride)});let r=new Map,o=[...n],i=[];for(let a of t){for(let l of a.loaded.warnings)o.push(l);if(a.loaded.sources.length>0)for(let l of a.loaded.sources)i.includes(l)||i.push(l);for(let[l,c]of Object.entries(a.loaded.mcpServers)){let d=r.get(l);d&&o.push(`mcp: server "${l}" defined in ${d.source} is overridden by ${a.path}`),r.set(l,{config:c,source:a.path})}}let s={};for(let[a,l]of r)s[a]=l.config;return{mcpServers:s,sources:i,warnings:o}}IS();function Ic(e,t){return t instanceof Date?t.toISOString():t instanceof Error?{message:t.message,name:t.name}:t}io();pe();function ove(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}var Rz=10*1024*1024;function xz(){return new Promise((e,t)=>{let n=[],r=0;if(process.stdin.readableEnded){e("");return}let o=i=>{if(r+=i.length,r>Rz){process.stdin.destroy(new Error(`stdin exceeds ${Rz}-byte limit`));return}n.push(i)};process.stdin.on("data",o),process.stdin.once("end",()=>{process.stdin.removeListener("data",o),e(Buffer.concat(n).toString("utf-8").replace(/\n+$/,""))}),process.stdin.once("error",i=>{process.stdin.removeListener("data",o),t(i)}),process.stdin.resume()})}function Az(e,t){return new Promise((n,r)=>{let o=e.write(t,i=>{i?r(i):o&&n()});if(!o){let i=()=>{e.removeListener("error",s),n()},s=a=>{e.removeListener("drain",i),r(a)};e.once("drain",i),e.once("error",s)}})}function Iz(e){e.command("chat").description("Send a message to the agent").argument("[message]","Message to send; use `-` or omit to read from stdin").option("-m, --model <model>","Model to use. Short aliases: opus|opus_1m|sonnet|sonnet_1m|haiku. Any other value (e.g. `auto` for cursor-api-proxy, or a full `claude-*` ID) passes through to the SDK/proxy untouched.",at()).option("-s, --stream","[no-op] reserved; use --format stream-json for headless streaming",!1).option("-f, --format <format>","Output format (text|json|stream-json)","text").option("--max-turns <number>","Maximum conversation turns","10").option("--thinking <mode>","Thinking mode: 'adaptive' | 'disabled' | 'enabled:<N>'","enabled:max").option("--effort <level>","Effort level: low|medium|high|xhigh|max").option("--theme <mode>","TUI color palette: dark|light|umber|auto. Default dark. umber matches the Umber terminal (dark-only). Also: AFK_THEME env, or theme in afk.config.json.",Bf).option("--max-budget-usd <usd>","Hard session cost ceiling in USD. Env: AFK_MAX_BUDGET_USD").option("--task-budget <tokens>","Soft per-task token budget. Env: AFK_TASK_BUDGET").option("--max-output-tokens <n|max>","Per-response output cap ('max' = model ceiling). Env: AFK_MAX_OUTPUT_TOKENS").option("--provider <name>","Provider to use: anthropic|anthropic-direct|openai|openai-compatible. Default: auto-selected by model").option("--dump-prompt [path]",'Dump resolved SDK prompt+options+provenance to file (default: ~/.afk/logs/prompt-dump-<ISO>.json) or "stderr"').option("-w, --worktree [branch]","Create a git worktree for an isolated one-shot. Optional value sets the branch name; otherwise auto-named. On clean exit (no uncommitted changes) the worktree and branch are auto-removed; on dirty exit the worktree is preserved. Mirrors `afk interactive -w`.").option("--worktree-base <ref>","Base git ref for the worktree created by --worktree. Default: the remote's default branch (origin/main), fetched fresh. Pass HEAD to base on your local checkout instead. Also: AFK_WORKTREE_BASE.").option("--mcp-config <path>","Path to an additional MCP config file (highest priority \u2014 merges over ~/.afk/config/mcp.json, project-local .mcp.json, and plugin-contributed configs). File format identical to mcp.json.").option("--resume <id>","Resume a persisted session by id").option("--continue","Continue the most recent persisted session in cwd").option("--session-id <uuid>","Assign a specific UUID to this session (creates new; errors if already exists)").option("--post <targets>","Headless publish of the final assistant message: github, telegram, or github,telegram").option("--post-pr <ref>","PR number, URL, or branch for --post github (defaults to the current-branch PR)").option("--dangerously-skip-permissions","Force bypass mode (already the default for new installs): skip path-approval prompts; read/write ANY path with no confirmation (permissionMode=bypassPermissions). Disable persistently with `afk config set permissionMode default`. Does not affect ask_question.").action(async(t,n)=>{if(n.resume&&n.continue){process.stderr.write(`Error: --resume and --continue are mutually exclusive
1743
+ `)}`)}this.nameRegistry=r.tools}static async fromConfig(t,n={}){if(n.warnings&&n.warnings.length>0)for(let c of n.warnings)console.warn(`[mcp] ${c}`);let r=new Map,o=[],i={manager:void 0};for(let[c,d]of Object.entries(t)){let u=Qp(c);if(u!==c&&console.warn(`[mcp] server name "${c}" sanitized to "${u}" for wire encoding`),d.disabled){r.set(c,{client:void 0,tools:[],state:{serverName:c,config:d,status:"disabled",toolCount:0}});continue}let f={client:void 0,tools:[],state:{serverName:c,config:d,status:"connecting",toolCount:0}};r.set(c,f);let g=new Cc(c,d);f.client=g,g.onTransportError=b=>{f.state.status="error",f.state.error=MS(b.message,200),console.warn(`[mcp:${c}] transport error: ${b.message}`)},g.onToolListChanged=()=>{i.manager?.refreshServer(c).catch(b=>{let S=b instanceof Error?b.message:String(b);console.warn(`[mcp:${c}] refreshServer failed: ${S}`)})};let h=(async()=>{let b=Date.now();re(n.traceWriter,{phase:"mcp_server_start",metadata:{server:c}});let S="error",w=0;try{let{tools:v,serverInfo:E}=await g.connect();f.tools=v,f.state.status="connected",f.state.toolCount=v.length,f.state.lastListedAt=Date.now(),S="connected",w=v.length;let T=E?`${E.name}@${E.version}`:"unknown";console.log(`[mcp:${c}] connected (${T}) \u2014 ${v.length} tool(s)`)}catch(v){if(v instanceof t_){f.state.status="oauth_pending",S="oauth_pending",console.log(`[mcp:${c}] OAuth authorization required \u2014 check Telegram or stderr for the auth URL`);return}let E=v instanceof Error?v.message:String(v);if(f.state.status="error",f.state.error=MS(E,200),d.alwaysLoad===!0)throw new Error(`MCP server "${c}" is marked alwaysLoad but failed to connect: ${E}`);console.warn(`[mcp:${c}] connect failed: ${E}`)}finally{re(n.traceWriter,{phase:"mcp_server_done",durationMs:Date.now()-b,metadata:{server:c,status:S,toolCount:w}})}})();o.push(h)}let a=(await Promise.allSettled(o)).find(c=>c.status==="rejected");if(a){for(let c of r.values())c.client&&await c.client.disconnect().catch(()=>{});throw a.reason}let l=new e(r);return i.manager=l,l}getMcpTools(){let t=[];for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let i=this.records.get(r);if(!i||i.state.status!=="connected")continue;let s=i.tools.find(a=>a.name===o);s&&t.push(zwe(n,s))}return t}getMcpHandlers(){let t=new Map;for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let i=this.records.get(r);!i||i.state.status!=="connected"||t.set(n,async(s,a)=>i.client?i.client.callTool(o,s,a):{content:`MCP server "${r}" is not connected`,isError:!0})}return t}async refreshServer(t){let n=this.records.get(t);if(!n||!n.client||n.state.status!=="connected")throw new Error(`McpManager.refreshServer("${t}"): server is not connected`);let r=await n.client.refreshTools();for(let[i,s]of this.nameRegistry)s.serverName===t&&this.nameRegistry.delete(i);let o=Zp([{serverName:t,toolNames:r.map(i=>i.name)}]);if(o.conflicts.length>0)for(let i of o.conflicts){let s=i.pairs.map(a=>`${a.serverName}.${a.originalToolName}`).join(", ");console.warn(`[mcp:${t}] wire-name conflict after refresh \u2014 skipping: ${i.wireName} \u2190 ${s}`)}for(let[i,s]of o.tools)this.nameRegistry.set(i,s);n.tools=r,n.state.toolCount=r.length,n.state.lastListedAt=Date.now(),console.log(`[mcp:${t}] tool list refreshed \u2014 ${r.length} tool(s)`),this.onToolsRefreshed?.(t)}getServerStates(){return[...this.records.values()].map(t=>({...t.state}))}getMcpToolWireNames(){return[...this.nameRegistry.keys()]}async completeAuth(t,n){let r=this.records.get(t);if(!r)throw new Error(`McpManager.completeAuth("${t}"): server not found`);if(r.state.status!=="oauth_pending")throw new Error(`McpManager.completeAuth("${t}"): server is not in oauth_pending state (current status: ${r.state.status})`);if(!r.client)throw new Error(`McpManager.completeAuth("${t}"): no client record \u2014 server was never connected`);await r.client.finishAuth(n),await r.client.disconnect().catch(s=>{let a=s instanceof Error?s.message:String(s);console.warn(`[mcp:${t}] completeAuth disconnect warning: ${a}`)});let o=new Cc(t,r.state.config);o.onTransportError=s=>{r.state.status="error",r.state.error=MS(s.message,200),console.warn(`[mcp:${t}] transport error: ${s.message}`)},o.onToolListChanged=()=>{this.refreshServer(t).catch(s=>{let a=s instanceof Error?s.message:String(s);console.warn(`[mcp:${t}] refreshServer failed: ${a}`)})},r.state.status="connecting",r.state.error=void 0,r.client=o;try{let{tools:s,serverInfo:a}=await o.connect();r.tools=s,r.state.status="connected",r.state.toolCount=s.length,r.state.lastListedAt=Date.now();let l=a?`${a.name}@${a.version}`:"unknown";console.log(`[mcp:${t}] OAuth complete \u2014 connected (${l}) \u2014 ${s.length} tool(s)`)}catch(s){let a=s instanceof Error?s.message:String(s);throw r.state.status="error",r.state.error=MS(a,200),new Error(`McpManager.completeAuth("${t}"): reconnect failed: ${a}`)}for(let[s,a]of this.nameRegistry)a.serverName===t&&this.nameRegistry.delete(s);let i=Zp([{serverName:t,toolNames:r.tools.map(s=>s.name)}]);for(let[s,a]of i.tools)this.nameRegistry.set(s,a);this.onToolsRefreshed?.(t)}hasAnyConnected(){for(let t of this.records.values())if(t.state.status==="connected")return!0;return!1}size(){return this.records.size}async disconnectAll(){let t=[];for(let[n,r]of this.records)r.client&&t.push(r.client.disconnect().catch(o=>{let i=o instanceof Error?o.message:String(o);console.warn(`[mcp:${n}] disconnect error: ${i}`)}));await Promise.all(t)}};function zwe(e,t){let n=t.description??`MCP tool ${t.name}`;return{name:e,description:n,input_schema:t.inputSchema}}function MS(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}j();K();Vn();import{existsSync as _c,lstatSync as Vwe,readFileSync as Jwe,readdirSync as Ywe,realpathSync as vz}from"node:fs";import{isAbsolute as Xwe,join as em,relative as Qwe}from"node:path";function Zs(){return em(Hn(),"mcp.json")}function Tz(e=process.cwd()){let t=em(e,".mcp.json");if(!_c(t))return t;try{let n=vz(e),r=vz(t),o=Qwe(n,r);return o.startsWith("..")||Xwe(o)?null:t}catch{return null}}var Zwe=5;function r_(e=Je()){if(!_c(e))return[];let t=[];return Ez(e,e,0,t,new Set),t}function Ez(e,t,n,r,o){if(n>Zwe||o.has(t))return;o.add(t);let i=em(t,".claude-plugin","plugin.json");if(_c(i)){let a=em(t,".claude-plugin","mcp.json");_c(a)&&r.push(a);return}let s;try{s=Ywe(t)}catch{return}for(let a of s){if(a.startsWith("."))continue;let l=em(t,a),c;try{c=Vwe(l)}catch{continue}c.isDirectory()&&Ez(e,l,n+1,r,o)}}function eve(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return{ok:!1,error:`server "${e}" must be an object`};let n=t,r=n.type;if(r===void 0)if(typeof n.command=="string")r="stdio";else if(typeof n.url=="string")r="streamable-http";else return{ok:!1,error:`server "${e}" has no \`command\` or \`url\`; cannot infer transport`};if(r==="stdio"){if(typeof n.command!="string"||n.command.length===0)return{ok:!1,error:`stdio server "${e}" requires non-empty \`command\``}}else if(r==="streamable-http"||r==="sse"){if(typeof n.url!="string"||n.url.length===0)return{ok:!1,error:`${r} server "${e}" requires non-empty \`url\``}}else return{ok:!1,error:`server "${e}" has unsupported \`type\`: ${String(r)}`};let o={type:r};if(typeof n.command=="string"&&(o.command=n.command),Array.isArray(n.args)&&(o.args=n.args.filter(i=>typeof i=="string")),n.env!==void 0&&typeof n.env=="object"&&n.env!==null){let i={};for(let[s,a]of Object.entries(n.env))typeof a=="string"&&(i[s]=a);o.env=i}if(typeof n.url=="string"&&(o.url=n.url),n.headers!==void 0&&typeof n.headers=="object"&&n.headers!==null){let i={};for(let[s,a]of Object.entries(n.headers))typeof a=="string"&&(i[s]=a);o.headers=i}return typeof n.oauth=="boolean"&&(o.oauth=n.oauth),typeof n.disabled=="boolean"&&(o.disabled=n.disabled),typeof n.alwaysLoad=="boolean"&&(o.alwaysLoad=n.alwaysLoad),typeof n.timeout=="number"&&n.timeout>0&&(o.timeout=n.timeout),{ok:!0,config:o}}function Qs(e){if(!_c(e))return{mcpServers:{},sources:[],warnings:[]};let t=[],n;try{n=JSON.parse(Jwe(e,"utf-8"))}catch(s){let a=s instanceof Error?s.message:String(s);return t.push(`mcp.json at ${e}: parse error \u2014 ${a}`),{mcpServers:{},sources:[e],warnings:t}}if(n===null||typeof n!="object"||Array.isArray(n))return t.push(`mcp.json at ${e}: top-level must be an object`),{mcpServers:{},sources:[e],warnings:t};let o=n.mcpServers;if(o==null||typeof o!="object")return{mcpServers:{},sources:[e],warnings:t};let i={};for(let[s,a]of Object.entries(o)){let l=eve(s,a);l.ok?i[s]=l.config:t.push(`mcp.json at ${e}: skipping ${l.error}`)}return{mcpServers:i,sources:[e],warnings:t}}function tve(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function kz(e,t){let n=Pe(e);return n.length>t?n.slice(0,t)+"\u2026":n}function ea(e={}){let t=[],n=[];if(e.importedMcpConfigs&&e.importedMcpConfigs.length>0)for(let a of e.importedMcpConfigs)t.push({path:a,loaded:Qs(a)});if(e.pluginsRoot!==null){let a=e.pluginsRoot,l=a?r_(a):r_();for(let c of l)t.push({path:c,loaded:Qs(c)})}if(!e.skipUserGlobal){let a=Zs();t.push({path:a,loaded:Qs(a)})}if(!e.skipProjectLocal){let a=Tz(e.cwd);if(a===null)n.push("mcp: refusing to load project-local .mcp.json \u2014 it resolves outside the working directory (symlink or path traversal).");else if(_c(a))if(tve(k.AFK_ALLOW_PROJECT_MCP))t.push({path:a,loaded:Qs(a)}),n.push(`mcp: loaded project-local config from ${a} (AFK_ALLOW_PROJECT_MCP is set).`);else{let l=Qs(a),c=Object.entries(l.mcpServers);if(c.length>0){let d=c.map(([u,p])=>{let f=p.command?[p.command,...p.args??[]].join(" "):p.url??"(no transport)";return`${kz(u,64)} \u2192 ${kz(f,160)}`}).join("; ");n.push(`mcp: skipped ${c.length} project-local server(s) from ${a} \u2014 not spawned: [${d}]. Set AFK_ALLOW_PROJECT_MCP=1 to load ${c.length===1?"it":`these ${c.length}`} if you trust this directory.`)}}}e.cliOverride!==void 0&&t.push({path:e.cliOverride,loaded:Qs(e.cliOverride)});let r=new Map,o=[...n],i=[];for(let a of t){for(let l of a.loaded.warnings)o.push(l);if(a.loaded.sources.length>0)for(let l of a.loaded.sources)i.includes(l)||i.push(l);for(let[l,c]of Object.entries(a.loaded.mcpServers)){let d=r.get(l);d&&o.push(`mcp: server "${l}" defined in ${d.source} is overridden by ${a.path}`),r.set(l,{config:c,source:a.path})}}let s={};for(let[a,l]of r)s[a]=l.config;return{mcpServers:s,sources:i,warnings:o}}IS();function Ic(e,t){return t instanceof Date?t.toISOString():t instanceof Error?{message:t.message,name:t.name}:t}io();pe();function ove(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}var Rz=10*1024*1024;function xz(){return new Promise((e,t)=>{let n=[],r=0;if(process.stdin.readableEnded){e("");return}let o=i=>{if(r+=i.length,r>Rz){process.stdin.destroy(new Error(`stdin exceeds ${Rz}-byte limit`));return}n.push(i)};process.stdin.on("data",o),process.stdin.once("end",()=>{process.stdin.removeListener("data",o),e(Buffer.concat(n).toString("utf-8").replace(/\n+$/,""))}),process.stdin.once("error",i=>{process.stdin.removeListener("data",o),t(i)}),process.stdin.resume()})}function Az(e,t){return new Promise((n,r)=>{let o=e.write(t,i=>{i?r(i):o&&n()});if(!o){let i=()=>{e.removeListener("error",s),n()},s=a=>{e.removeListener("drain",i),r(a)};e.once("drain",i),e.once("error",s)}})}function Iz(e){e.command("chat").description("Send a message to the agent").argument("[message]","Message to send; use `-` or omit to read from stdin").option("-m, --model <model>","Model to use. Short aliases: opus|opus_1m|sonnet|sonnet_1m|haiku. Any other value (e.g. `auto` for cursor-api-proxy, or a full `claude-*` ID) passes through to the SDK/proxy untouched.",at()).option("-s, --stream","[no-op] reserved; use --format stream-json for headless streaming",!1).option("-f, --format <format>","Output format (text|json|stream-json)","text").option("--max-turns <number>","Maximum conversation turns","10").option("--thinking <mode>","Thinking mode: 'adaptive' | 'disabled' | 'max' | 'enabled:<N>'","enabled:max").option("--effort <level>","Effort level: low|medium|high|xhigh|max").option("--theme <mode>","TUI color palette: dark|light|umber|auto. Default dark. umber matches the Umber terminal (dark-only). Also: AFK_THEME env, or theme in afk.config.json.",Bf).option("--max-budget-usd <usd>","Hard session cost ceiling in USD. Env: AFK_MAX_BUDGET_USD").option("--task-budget <tokens>","Soft per-task token budget. Env: AFK_TASK_BUDGET").option("--max-output-tokens <n|max>","Per-response output cap ('max' = model ceiling). Env: AFK_MAX_OUTPUT_TOKENS").option("--provider <name>","Provider to use: anthropic|anthropic-direct|openai|openai-compatible. Default: auto-selected by model").option("--dump-prompt [path]",'Dump resolved SDK prompt+options+provenance to file (default: ~/.afk/logs/prompt-dump-<ISO>.json) or "stderr"').option("-w, --worktree [branch]","Create a git worktree for an isolated one-shot. Optional value sets the branch name; otherwise auto-named. On clean exit (no uncommitted changes) the worktree and branch are auto-removed; on dirty exit the worktree is preserved. Mirrors `afk interactive -w`.").option("--worktree-base <ref>","Base git ref for the worktree created by --worktree. Default: the remote's default branch (origin/main), fetched fresh. Pass HEAD to base on your local checkout instead. Also: AFK_WORKTREE_BASE.").option("--mcp-config <path>","Path to an additional MCP config file (highest priority \u2014 merges over ~/.afk/config/mcp.json, project-local .mcp.json, and plugin-contributed configs). File format identical to mcp.json.").option("--resume <id>","Resume a persisted session by id").option("--continue","Continue the most recent persisted session in cwd").option("--session-id <uuid>","Assign a specific UUID to this session (creates new; errors if already exists)").option("--post <targets>","Headless publish of the final assistant message: github, telegram, or github,telegram").option("--post-pr <ref>","PR number, URL, or branch for --post github (defaults to the current-branch PR)").option("--dangerously-skip-permissions","Force bypass mode (already the default for new installs): skip path-approval prompts; read/write ANY path with no confirmation (permissionMode=bypassPermissions). Disable persistently with `afk config set permissionMode default`. Does not affect ask_question.").action(async(t,n)=>{if(n.resume&&n.continue){process.stderr.write(`Error: --resume and --continue are mutually exclusive
1744
1744
  `),process.exitCode=1;return}if(n.sessionId!==void 0&&(n.resume||n.continue)){process.stderr.write(`Error: --session-id is mutually exclusive with --resume and --continue
1745
1745
  `),process.exitCode=1;return}if(n.sessionId!==void 0&&!ove(n.sessionId)){process.stderr.write(`Error: --session-id must be a UUID (got: ${n.sessionId})
1746
1746
  `),process.exitCode=1;return}if(n.sessionId!==void 0&&Js(n.sessionId)!==void 0){process.stderr.write(`Error: session already exists: ${n.sessionId} \u2014 use --resume to continue it
@@ -1864,7 +1864,7 @@ ${E}
1864
1864
  ${T}`})}return{fileBlocks:l,warnings:c}}function X3(e){let t=e.replace(/\s+/g," ").trim();return t.length<=60?t:`${t.slice(0,59)}\u2026`}async function Q3(e,t,n){let r=t?.peekQueuedText(),o=r!==void 0?{text:r.text,claimed:!1}:void 0;r!==void 0&&t?.reserveQueued?.(r);let i;try{i=await e.promoteActiveForeground(o)}catch(s){throw r!==void 0&&t?.releaseQueued?.(r),s}if(o?.claimed===!0&&t!==null&&r!==void 0){try{await n?.(o.text)}catch{}return t.dropQueued(r),{jobs:i,flushedText:o.text,flushedPreview:r.preview}}return r!==void 0&&t?.releaseQueued?.(r),{jobs:i}}yw();async function Z3(e,t,n,r,o="summary",i,s){let a=kJ(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0),Mc(process.stdout,tm(process.cwd(),!0));let l="",c=0,d=!1,u=!1,p=!1,f=!1,g=!1,h,b=!1,S=!1,w={abort:null},v=0,E=3e3,T=[],A=new Map,M=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,_=()=>{let F=r.subagentControl;F?.hasPromotableForeground()&&Q3(F,x,r.onQueuedUserMessage).then(({jobs:H,flushedText:G,flushedPreview:I})=>{let L=(i??{fn:console.log}).fn;for(let O of H)L(m.dim(` \u2192 subagent backgrounded as ${O.jobId}: ${O.label}`));G!==void 0&&L(m.dim(` \u2192 queued message sent to this turn: ${X3(I??G)}`))}).catch(()=>{})},x=r.getCompositor?r.getCompositor():null,C=()=>new nd({out:rd(i),thinkingMode:o,...M?{activeSkillName:M}:{},onCancel:()=>{t.interrupt().catch(F=>{Ke()&&console.error(" "+m.error("session.interrupt() failed:"),F)})},...r.subagentControl?{onBackground:_}:{},...s?.history?{history:s.history}:{},...s?.autocompleteState?{autocompleteState:s.autocompleteState}:{},...s?.promptText!==void 0?{promptText:s.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...x?{compositor:x}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),P=C(),$=async()=>{if(!f){f=!0;try{await P.dispose()}catch{}}},q=async()=>{await P.arm();let F=P.getCompositor();if(i&&F){let H=F;i.fn=G=>H.commitAbove(G),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.(F),r.setInterruptNotifier?.(H=>P.setInterrupting(H)),r.rearmStatus?.()};try{x?x.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{b=!0,P.setSoftStopping(!0),t.interrupt().catch(D=>{Ke()&&console.error(" "+m.error("soft-stop session.interrupt() failed:"),D)});let O=r.subagentControl;O?.hasActiveForeground()&&O.cancelActiveForeground().catch(D=>{Ke()&&console.error(" "+m.error("soft-stop cancelActiveForeground() failed:"),D)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{S=!0,t.interrupt().catch(O=>{Ke()&&console.error(" "+m.error("pause-interrupt session.interrupt() failed:"),O)})}),await q(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(_);let{fileBlocks:F,warnings:H}=Y3(e.text,{rootDir:process.cwd()});for(let O of H)(i??{fn:console.log}).fn(m.dim(` @-file: ${O}`));if(e.attachments.length>0&&(await t.waitForInitialization(),t.sessionId===void 0))throw new Error("CLI session initialized without a session id");let G=F.length>0||e.attachments.length>0?await J3(e.text,e.attachments,void 0,F,t.sessionId):e.text,I=t.sendMessageStream(G);if(await Ml((O,D)=>{P.process(O,D)},async()=>{for await(let O of I){if(b||S)break;if(O.type==="chunk"&&O.chunk.type==="content"?(l=d?z3(l,O.chunk.content):l+O.chunk.content,d=!1,u=!0):O.type==="message"&&!u&&(l=O.message.content),O.type==="stream_retry"&&(l=l.slice(0,c),d=l.length>0),O.type==="chunk"&&O.chunk.type==="tool_use_detail"){let D=O.chunk,W={toolName:D.toolName,toolUseId:D.toolUseId,input:D.toolInput,...D.toolInputRaw!==void 0&&{inputRaw:D.toolInputRaw}};A.set(D.toolUseId,W),T.push(W)}else if(O.type==="chunk"&&O.chunk.type==="tool_result"){let D=O.chunk;c=l.length,d=!0;let W=A.get(D.toolUseId);if(W&&(W.result=D.content,W.isError=D.isError,A.delete(D.toolUseId)),r.onContextProgress){let ne=Date.now();if(ne-v>=E){v=ne;try{let ee=r.onContextProgress();ee instanceof Promise&&await ee}catch(ee){Ke()&&console.error(" "+m.error("onContextProgress (status refresh) failed:"),ee)}}}}if(O.type==="paused"){if(r.setPausedState?.(!0),await $(),x&&O.autoResume===!0){let D=new AbortController;w.abort=D;let W=O.resetsAt?O.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,ne=W?`Keep waiting \u2014 auto-resumes at ${W}`:"Keep waiting \u2014 auto-resume in progress",ee="Switch model / provider (type /model after)",X="Stop waiting",le=[m.warning(" \u23F3 Usage limit reached.")+(W?m.dim(` Auto-resumes at ${W}.`):""),m.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];Bn(x,{header:le,options:[ne,ee,X],signal:D.signal,initialIndex:0}).then(z=>{if(w.abort=null,!z)return;let ke=z[0];ke===void 0||ke===ne||(S=!0,ke===ee&&(i??{fn:console.log}).fn(m.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(ce=>{Ke()&&console.error(" "+m.error("picker pause-interrupt session.interrupt() failed:"),ce)}))}).catch(z=>{Ke()&&console.error(" "+m.error("picker promise rejected:"),z)})}else(i??{fn:console.log}).fn(RO({reason:O.reason,...O.resetsAt!==void 0?{resetsAt:O.resetsAt}:{},...O.accountId!==void 0?{accountId:O.accountId}:{},...O.autoResume!==void 0?{autoResume:O.autoResume}:{}}));continue}if(O.type==="resumed"){r.setPausedState?.(!1),w.abort?.abort(),w.abort=null;let D=O.hotSwapped&&O.accountId?`\u25B6 Resumed on ${O.accountId}`:"\u25B6 Resumed";l="",c=0,d=!1,u=!1,T.length=0,A.clear(),g=!1,h=void 0,p=!1,P=C(),f=!1,await q(),(i??{fn:console.log}).fn(m.success(D));continue}if(O.type==="error"){await $(),Ja(Ha(O.error)),p=!0;continue}P.process(O),O.type==="done"&&(g=!0,h=O.metadata)}}),await $(),b){let O=i?i.fn:console.log,D=x?x.getPendingCount():0,W=D>0?` \xB7 ${D} queued`:"";O(m.warning(`\u23F8 Stopped${W} \u2014 work so far kept.`)+m.dim(" Send a message to continue.")),O("")}if(S){let O=i?i.fn:console.log;O(m.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),O("")}if(g&&!b&&!S){Xs(n,a,l,h,T),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),Pc(process.stdout),Dz(process.stdout,"afk: turn complete");let O=W=>{i?i.fn(W):console.log(W)},D=Zv(l);if(D){O(V3(D)),O("");let W=x5(T);if(r.onTerminalState)try{r.onTerminalState(D,{doneHasCorroboratingEvidence:W})}catch{}if(n.permissionMode==="autonomous"){let ne=D.kind==="done"&&$u().verifyDone===!0&&!W;C5(D,void 0,{unverified:ne})}}if(cIe(h,n,O),r.onAfterTurn){let W=r.onAfterTurn();W instanceof Promise&&await W.catch(()=>{})}}}catch(F){await $(),p||Ja(Ha(F))}finally{await $(),Mc(process.stdout,tm(process.cwd(),!1)),i&&(i.fn=i.idleFn,i.suppressSubagentCompletion=!1),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setPausedState?.(!1),r.setPauseInterruptHandler?.(null),w.abort?.abort(),w.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}function lIe(e,t){let n=Math.round(e*100),r=he(t);if(e>=1){let o=Math.round((e-1)*t);return{tier:"over",text:` context OVER ${Math.round(t/1e3)}k tok by ~${he(o)} tok \u2014 model output may be silently truncated`}}return e>=.95?{tier:"near",text:` context ${n}% used of ${r} \u2014 near limit; output may soon truncate (consider /clear or a fresh session)`}:e>=.8?{tier:"caution",text:` context ${n}% used of ${r} \u2014 approaching limit`}:e>.5?{tier:"normal",text:` context ${n}% used of ${r}`}:{tier:"quiet",text:null}}function cIe(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(_e(e.durationMs)),e.totalCostUsd!==void 0&&r.push(wt(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),i=Number(e.usage?.output_tokens??0);o+i>0&&r.push(he(o+i)+" tok"),r.length>0&&n(m.dim(" \u25E6 "+r.join(" \xB7 ")));let s=CI(t),a=nt(t.model),l=lIe(s,a);if(l.text!==null){let d=l.tier==="over"||l.tier==="near"?m.error:l.tier==="caution"?m.warning:m.dim;n(d(l.text))}let c=q3(qw(ay()),new Date,{autoResume:eL()});if(c.text!==null){let d=c.tier==="over"||c.tier==="near"?m.error:c.tier==="caution"?m.warning:m.dim;n(d(c.text))}n("")}Ri();var dIe=5e3,uIe=3,pIe="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function mIe(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(m.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function eX(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,mascotBar:d,verdictLedger:u,shellPassthrough:p,bgResultNotifier:f}=s,g=null,h=[];e.session.current.waitForInitialization().then(async _=>{Ke()&&(g=uv(_)),await _m(e.session.current),Ke()&&(h=TI())}).catch(()=>{});let b=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,S,w=!1,v=!1,E,T,A,M=0;for(f.onInjectable=()=>{M>=uIe||!o.isAwaitingInput()||!o.bufferIsEmpty()||(M++,Pc(process.stdout),b={text:pIe,attachments:[]},o.abortPendingRead())};;){if(g&&(e.replRenderer.writeLine(g),e.replRenderer.writeLine(""),g=null),h.length>0){for(let I of h)e.replRenderer.writeLine(I);e.replRenderer.writeLine(""),h=[]}let _=p.drainNotifications();for(let{job:I,result:L}of _){let O=L.errorReason===void 0?"\u2713":"\u2717",D=L.errorReason==="abort"?"killed":L.errorReason==="timeout"?"timed out":L.errorReason==="signal-killed"?"killed by signal":`exit ${L.exitCode??0}`,W=Math.max(0,Math.round(L.durationMs/100)/10);e.replRenderer.writeLine(m.dim(` ${O} [${I.id}] ${D} \xB7 ${W}s \xB7 `)+I.command)}let x=f.drainNotifications();for(let{job:I}of x){let L=I.status==="completed"?"\u2713":I.status==="failed"?"\u2717":"\u2298",O=I.endedAt!==void 0?Math.max(0,Math.round((I.endedAt-I.startedAt)/100)/10):0,D=se(I.label,60);e.replRenderer.writeLine(m.dim(` ${L} [${I.jobId}] subagent ${I.status} \xB7 ${O}s \xB7 `)+D)}let C=l.renderIfChanged(e.stats.sessionId);if(C.length>0){for(let I of C)e.replRenderer.writeLine(I);e.replRenderer.writeLine("")}let P,$;if(b===void 0){let I=await e.session.current.takePendingPlanExitSeed();I!==void 0&&(e.stats.permissionMode=I.mode,b={text:I.message,attachments:[]})}if(b!==void 0){let I=b;b=void 0;let L=ud(e.stats.permissionMode),O=na({buffer:I.text,promptText:L,isTTY:!!process.stdout.isTTY,attachmentSummary:Kc([...I.attachments])});e.replRenderer.writeLine(O),P=I.text.trim(),$=I.attachments}else{let I=S;S=void 0;let L=await o.readLine({promptFn:()=>ud(e.stats.permissionMode),...I!==void 0?{initialBuffer:I}:{},primePromptSuggestion:!0,onSigint:r,onShiftTab:()=>{Vv(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});P=L.text.trim(),$=L.attachments}if(!P&&$.length===0)continue;if(P.startsWith("!")){let I=/^(0|false|off|no)$/i.test(k.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!I&&(w||(w=!0,e.replRenderer.writeLine(m.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await p.dispatch(P))){e.statusLine.rearm();continue}}let q=!1;if(P.startsWith("/")){let I=await Nz(P,e.slashCtx,$);if(I.handled){if(I.result==="exit"){await e.resolveWorktreeDisposition?.(!0),e.rl.close();return}if((P==="/clear"||P.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(m.dim(` transcript: ${t.path()}`)),u.reset(),E=void 0),I.result!==null&&typeof I.result=="object"&&"kind"in I.result&&I.result.kind==="submit"){b={text:I.result.message,attachments:$??[]},e.statusLine.rearm();continue}if(I.result!==null&&typeof I.result=="object"&&"kind"in I.result&&I.result.kind==="prefill"){S=I.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}q=!0}a.push(P),await mIe(e,P);let F=P;if(q){let I=i_(P);if(I){let L=I.name.replace(/^\//,"").split(":").pop()??"";if(L&&bI(L)){let O={skillName:L,rawArgs:I.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},D=e.session.current.sessionId,W=ma(D),ne=Date.now();B(`[afk trace] preflight.start commandName=${L}`);let ee=!1,X=await pa(O,{cwd:e.stats.cwd??process.cwd(),artifactDir:W},le=>{Ke()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${L}) failed: `)+(le instanceof Error?le.message:String(le)))});ee=X!==null,B(`[afk trace] preflight.end commandName=${L} durationMs=${Date.now()-ne} success=${ee}`),F=vI(X?.manifestBlock,P)}}}let H=p.drainInjections();H.length>0&&(F=H+F);let G=f.drainInjections();if(G.length>0&&(F=G+F),E!==void 0&&(F=E+`
1865
1865
 
1866
1866
  `+F,E=void 0),e.hookRegistry)try{let I={event:"UserPromptSubmit",prompt:F,sessionId:e.stats.sessionId},L=await e.hookRegistry.dispatch(I);L.injectContext&&(F=L.injectContext+F)}catch(I){if(I instanceof Ae){e.replRenderer.writeLine(m.warning("\u2298 Turn blocked by hook")+(I.reason?m.dim(`: ${Pe(I.reason)}`):"")),e.statusLine.rearm();continue}if(I instanceof wr){e.replRenderer.writeLine(m.warning("\u2298 Turn blocked by hook")+m.dim(`: handler timed out after ${I.timeoutMs}ms`)),e.statusLine.rearm();continue}throw I}if(T=void 0,A=void 0,await Z3({text:F,attachments:$},e.session.current,e.stats,{setInFlight(I){n.turnInFlight=I},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(I){await t.appendUser(I)},async onQueuedUserMessage(I){await t.appendQueuedUser(I)},async onTurnComplete(I,L){if(await t.appendTurn(I,L),e.stats.sessionId)try{Ei(e.stats)}catch(O){v||(v=!0,e.replRenderer.writeLine(m.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(O instanceof Error?O.message:String(O))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:(I,L)=>{u?.push(I),T=I.kind,A=L?.doneHasCorroboratingEvidence},setActiveCompositor:I=>{n.activeCompositor=I},setInterruptNotifier:I=>{n.notifyInterrupting=I},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:I=>o.setBackgroundHandler(I),setSoftStopHandler:i,setPausedState:I=>o.setPausedState(I),setPauseInterruptHandler:I=>o.setPauseInterruptHandler(I),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(lr(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:(I,L)=>{c.repaint(I),d?.onStage(I,L)}}:{}},e.stats.thinkingUi??e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(ud(e.stats.permissionMode))),e.hookRegistry)try{let I=await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId,...T!==void 0?{terminalState:T}:{},...A!==void 0?{doneHasCorroboratingEvidence:A}:{}},void 0,dIe);I.injectContext&&I.injectContext.trim().length>0&&(E=I.injectContext)}catch(I){if(I instanceof kt)throw I;I instanceof wr?(B("[stop hook] handler timed out"),e.completionWriter.fn(m.dim(" [stop hook] timed out"))):I instanceof Ae?e.completionWriter.fn(m.dim(` [stop hook] blocked: ${Pe(I.reason??"no reason given")}`)):B("[stop hook] unexpected error: "+String(I))}}}function fIe(e,t){if(e!==void 0){let n=e.toLowerCase();return!(n==="0"||n==="false"||n==="off"||n==="no")}return typeof t=="boolean"?t:!0}async function tX(e,t,n,r){let o=await w3(),i=new zv({rl:e.rl,history:o,statusLine:e.statusLine}),s=fIe(k.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await A3(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar,getMascotBar:()=>a?.mascotBar});a=K3(e,n),await eX(e,t,n,r,i,l,a,o),await e.resolveWorktreeDisposition?.(!0)}finally{n.tryAbortShellForeground=null,a?.shellPassthrough.drainOnExit(),a?.bgResultNotifier.dispose(),a?.loopStageBar.stop(),a?.mascotBar.stop(),a?.bgStatusBar.stop(),a?.verdictLedger.stop(),a?.contextPane.dispose();let l=c=>console.log(c);e.completionWriter.fn=l,e.completionWriter.idleFn=l,await i.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}xu();Tl();import{execFile as gIe}from"node:child_process";import{dirname as hIe,isAbsolute as yIe,resolve as bIe}from"node:path";import{promisify as SIe}from"node:util";var nX=SIe(gIe),wIe=3e3,vIe=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function kIe(){let t=(await nX("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=yIe(t)?t:bIe(process.cwd(),t);return hIe(n)}async function rX(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await kIe()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),wIe)});try{let o=In({execFile:nX,repoRoot:t,dryRun:!1,scope:"interactive",bypassSoftLaunch:!0}),i=await Promise.race([o,r]);if(i==="timeout")return{ran:!1,removedCount:0,skippedReason:"timeout"};let s=i;return s.warnings.some(c=>c.toLowerCase().includes("contested"))?{ran:!1,removedCount:0,skippedReason:"lock-contested"}:{ran:!0,removedCount:s.candidates.filter(c=>vIe.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}rg();xu();import{promises as TIe}from"node:fs";import{dirname as EIe,join as sX}from"node:path";import{randomBytes as RIe}from"node:crypto";var xIe=["Generate a 2-4 word kebab-case slug describing this work request.","Rules:","- ASCII lowercase letters and digits only, separated by single hyphens","- 2 to 4 hyphen-separated words","- Maximum 30 characters total","- No prefix, no quotes, no punctuation other than hyphens","- Output ONLY the slug \u2014 no explanation, no preamble","Examples: fix-cleanup-race, add-telegram-allowlist, refactor-prompt-loader, debug-flaky-test"].join(`
1867
- `),oX=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,eM=30,AIe=1024,CIe=8e3,_Ie="haiku";async function IIe(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=$Ie(n,AIe),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??CIe),s=t.signal?DIe([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await tl({token:t.token,model:t.model??_Ie,system:xIe,user:r,maxTokens:32,signal:s})}catch(u){let p=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(i)}let l=PIe(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=EIe(t.worktreePath);return await MIe(l,c)}function PIe(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(oX.test(t)&&t.length<=eM)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(i=>i.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let i=1;i<r.length;i++){let s=`${o}-${r[i]}`;if(s.length>eM)break;o=s}return oX.test(o)?o:null}async function MIe(e,t){if(!await OIe(sX(t,e)))return e;let n=RIe(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,eM-5)}-${n}`}async function OIe(e){try{return await TIe.access(e),!0}catch{return!1}}function $Ie(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function DIe(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function aX(e){let t,n,r=sX(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await IIe(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),i=t??"unknown",s=n;if(o!==null){let l=`${th(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return iX(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){i="create-failed",s=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return iX(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:i,...s!==void 0?{detail:s}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function iX(e,t){e&&e.setCwd(t),FIe(t)}function FIe(e){try{process.chdir(e)}catch{}}lt();At();Ua();Hr();K();import{spawn as cX}from"child_process";import{existsSync as dX,mkdirSync as jIe,readFileSync as uX,unlinkSync as lX,writeFileSync as pX}from"fs";import{get as HIe}from"https";import{join as mX}from"path";import{readFileSync as LIe}from"fs";import{dirname as NIe,join as BIe}from"path";import{fileURLToPath as UIe}from"url";function Gr(){try{return"5.115.3"}catch{}try{let e=NIe(UIe(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(LIe(BIe(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}U();j();var WIe=64*1024,KIe=10800*1e3,GIe=800,qIe=3600*1e3,zIe="update-check.json",VIe="pending-update.json";function tM(){return mX(La(),zIe)}function qm(){return mX(La(),VIe)}function nM(){let e=La();dX(e)||jIe(e,{recursive:!0})}function fX(e,t){let n=a=>a.split(/[-+]/,1)[0]??a,r=a=>a.includes("-"),o=n(e).split(".").map(Number),i=n(t).split(".").map(Number),s=Math.max(o.length,i.length);for(let a=0;a<s;a++){let l=o[a]??0,c=i[a]??0;if(c>l)return!0;if(c<l)return!1}return r(e)&&!r(t)}function gX(){try{let e=uX(tM(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function hX(){try{nM();let e=`
1867
+ `),oX=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,eM=30,AIe=1024,CIe=8e3,_Ie="haiku";async function IIe(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=$Ie(n,AIe),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??CIe),s=t.signal?DIe([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await tl({token:t.token,model:t.model??_Ie,system:xIe,user:r,maxTokens:32,signal:s})}catch(u){let p=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(i)}let l=PIe(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=EIe(t.worktreePath);return await MIe(l,c)}function PIe(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(oX.test(t)&&t.length<=eM)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(i=>i.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let i=1;i<r.length;i++){let s=`${o}-${r[i]}`;if(s.length>eM)break;o=s}return oX.test(o)?o:null}async function MIe(e,t){if(!await OIe(sX(t,e)))return e;let n=RIe(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,eM-5)}-${n}`}async function OIe(e){try{return await TIe.access(e),!0}catch{return!1}}function $Ie(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function DIe(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function aX(e){let t,n,r=sX(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await IIe(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),i=t??"unknown",s=n;if(o!==null){let l=`${th(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return iX(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){i="create-failed",s=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return iX(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:i,...s!==void 0?{detail:s}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function iX(e,t){e&&e.setCwd(t),FIe(t)}function FIe(e){try{process.chdir(e)}catch{}}lt();At();Ua();Hr();K();import{spawn as cX}from"child_process";import{existsSync as dX,mkdirSync as jIe,readFileSync as uX,unlinkSync as lX,writeFileSync as pX}from"fs";import{get as HIe}from"https";import{join as mX}from"path";import{readFileSync as LIe}from"fs";import{dirname as NIe,join as BIe}from"path";import{fileURLToPath as UIe}from"url";function Gr(){try{return"5.115.4"}catch{}try{let e=NIe(UIe(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(LIe(BIe(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}U();j();var WIe=64*1024,KIe=10800*1e3,GIe=800,qIe=3600*1e3,zIe="update-check.json",VIe="pending-update.json";function tM(){return mX(La(),zIe)}function qm(){return mX(La(),VIe)}function nM(){let e=La();dX(e)||jIe(e,{recursive:!0})}function fX(e,t){let n=a=>a.split(/[-+]/,1)[0]??a,r=a=>a.includes("-"),o=n(e).split(".").map(Number),i=n(t).split(".").map(Number),s=Math.max(o.length,i.length);for(let a=0;a<s;a++){let l=o[a]??0,c=i[a]??0;if(c>l)return!0;if(c<l)return!1}return r(e)&&!r(t)}function gX(){try{let e=uX(tM(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function hX(){try{nM();let e=`
1868
1868
  const https = require('https');
1869
1869
  const fs = require('fs');
1870
1870
  const url = 'https://registry.npmjs.org/agent-afk/latest';
@@ -1887,7 +1887,7 @@ ${T}`})}return{fileBlocks:l,warnings:c}}function X3(e){let t=e.replace(/\s+/g,"
1887
1887
  ${m.warning(m.bold("Update available:"))} ${m.dim(e.currentVersion)} \u2192 ${m.bold(e.latestVersion)}
1888
1888
  ${m.dim("Run `npm install -g agent-afk` to update")}
1889
1889
  `)}var tk=/^\d+\.\d+\.\d+(-[\da-z.]+)?$/i;function rM(e){if(tk.test(e))try{nM(),pX(qm(),JSON.stringify({targetVersion:e,triggeredAt:Date.now()}))}catch{}}function nk(e){if(tk.test(e))try{nM(),pX(tM(),JSON.stringify({latestVersion:e,checkedAt:Date.now()}))}catch{}}function rk(e=5e3,t="https://registry.npmjs.org/agent-afk/latest"){return new Promise(n=>{let r=!1,o=s=>{r||(r=!0,n(s))},i=(s,a)=>{try{let l=HIe(s,{headers:{Accept:"application/json"}},c=>{if((c.statusCode===301||c.statusCode===302)&&typeof c.headers.location=="string"&&a>0){c.resume(),i(c.headers.location,a-1);return}if(c.statusCode!==200){c.resume(),o(void 0);return}let d="",u=0,p=!1;c.on("data",f=>{if(!p){if(u+=f.byteLength,u>WIe){p=!0,l.destroy(),o(void 0);return}d+=f.toString("utf-8")}}),c.on("end",()=>{if(!p){try{let f=JSON.parse(d);if(typeof f.version=="string"&&tk.test(f.version)){o(f.version);return}}catch{}o(void 0)}})});l.on("error",()=>o(void 0)),l.setTimeout(e,()=>{l.destroy(),o(void 0)})}catch{o(void 0)}};i(t,3)})}function oM(e){if(tk.test(e)&&!dX(qm()))try{rM(e),cX("npm",["install","-g",`agent-afk@${e}`],{detached:!0,stdio:"ignore"}).unref()}catch{}}function wX(){try{let e=uX(qm(),"utf-8"),t=JSON.parse(e);if(typeof t.targetVersion!="string")return;let n=Gr();if(n===t.targetVersion){lX(qm()),process.stderr.write(`${m.success(m.bold(`Updated to agent-afk v${n}`))}
1890
- `);return}let r=typeof t.triggeredAt=="number"?t.triggeredAt:0;Date.now()-r>qIe&&lX(qm())}catch{}}ya();function kX(e){let t=e.isTTY?"ask":"remove",n=e.cli!==void 0?"CLI flag":e.env!==void 0?"AFK_WORKTREE_ON_EXIT":"interactive.worktreeOnExit",r=e.cli??e.env??e.config;return r===void 0?t:r==="ask"||r==="keep"||r==="remove"?r:(e.console.warn(`Ignoring unrecognised ${n} worktree exit policy ${JSON.stringify(r)}; expected ask, keep, or remove.`),t)}var JIe="Keep worktree and cd into it on exit",vX="Delete worktree and branch";async function TX(e){if(e.turnCount<=0||!e.hasWorktree)return"remove";if(e.policy!=="ask"||!e.isTTY||e.picker===void 0)return e.policy==="remove"?"remove":e.policy==="keep"?"keep-locked":"keep-unlocked";try{let t=await e.picker({header:["Keep this worktree?",""],options:[JIe,vX]});return t===null?"keep-locked":t[0]===vX?"remove":"keep-locked"}catch(t){return e.console.warn(`Could not ask how to handle the worktree (${t instanceof Error?t.message:String(t)}); keeping it.`),"keep-locked"}}function YIe(e,t){return e===void 0||e.length===0||e.startsWith("/")||e.startsWith("-")?!1:!t.commands.some(n=>n.name()===e||n.aliases().includes(e))}function EX(e,t){let n=e,r=n.unknownOption.bind(n);n.unknownOption=function(i){let s=n.args[0];if(YIe(s,t)){n.error(`error: unknown command '${s}'`,{code:"commander.unknownCommand"});return}r(i)}}yw();var ok=null;function AX(e,t){ok={updateInfo:e,pendingMessage:t}}function QIe(e){if(e==="summary"||e==="live"||e==="digest"||e==="off")return e;throw new Error(`Invalid --thinking-ui value: ${e}. Expected summary|live|digest|off`)}function ZIe(e,t){switch(e){case"empty-message":case"slash-command":return;case"slug-generator-error":return t?`slug generation failed: ${t}`:"slug generation failed";case"invalid-slug-output":return t?`model returned invalid slug: ${JSON.stringify(t)}`:"model returned invalid slug";case"create-failed":return t?`named worktree create failed: ${t}`:"named worktree create failed";default:return"unknown reason"}}function ePe(e,t){if(e.worktreeAutoname===!1)return!1;let n=k.AFK_WORKTREE_AUTONAME;if(n!==void 0){let r=n.toLowerCase();return!(r==="0"||r==="false"||r==="off"||r==="no")}return typeof t.interactive?.worktreeAutoname=="boolean"?t.interactive.worktreeAutoname:!0}function tPe(e,t){if(e.thinkingUi!==void 0)return e.thinkingUi;let n=k.AFK_THINKING_UI;if(n!==void 0){let o=n.trim().toLowerCase();if(o==="summary"||o==="live"||o==="digest"||o==="off")return o}let r=t.interactive?.thinkingUi;return r!==void 0?r:"live"}function nPe(){return"/help \xB7 /model \xB7 @ for files \xB7 Shift+Tab mode \xB7 Esc to interrupt \xB7 /exit to quit"}function CX(e){let t=e.command("interactive",{isDefault:!0}).description("Start interactive chat session").argument("[input...]",'Optional first message \u2014 or a /slash-command \u2014 auto-submitted as the opening turn. E.g. `afk "what does this project do"` or `afk /review`. A bare `afk` starts an empty REPL.').option("-m, --model <model>","Model to use. Short aliases: opus|opus_1m|sonnet|sonnet_1m|haiku. Any other value (e.g. `auto` for cursor-api-proxy, or a full `claude-*` ID) passes through to the SDK/proxy untouched.",at()).option("--max-turns <number>","Maximum conversation turns","100").option("--thinking <mode>","Thinking mode: 'adaptive' | 'disabled' | 'enabled:<N>'","enabled:max").option("--thinking-ui <mode>","Thinking display mode: summary|live|digest|off. Default live. Also: AFK_THINKING_UI env, or interactive.thinkingUi in afk.config.json.",QIe).option("--theme <mode>","TUI color palette: dark|light|umber|auto. Default dark. umber matches the Umber terminal (dark-only). Also: AFK_THEME env, or theme in afk.config.json. Toggle live with /theme.",Bf).option("--effort <level>","Effort level: low|medium|high|xhigh|max").option("--max-output-tokens <n|max>","Per-response output cap ('max' = model ceiling). Env: AFK_MAX_OUTPUT_TOKENS").option("--resume <id>","Resume a persisted SDK session by id").option("--continue","Continue the most recent persisted session in cwd").option("--debug","Show SDK init metadata on startup; enables /debug command",!1).option("-w, --worktree [branch]","Create a git worktree for an isolated session. Optional value sets the branch name; otherwise auto-named. On clean interactive exit, choose whether to keep or delete it; dirty worktrees are always preserved.").option("--worktree-on-exit <ask|keep|remove>","Clean-worktree quit policy. Default: ask on TTY, remove otherwise. Also: AFK_WORKTREE_ON_EXIT, or interactive.worktreeOnExit in afk.config.json.").option("--no-worktree-autoname","Disable mid-session rename of auto-named worktrees from the first user message via haiku. Default on. Also: AFK_WORKTREE_AUTONAME=0, or interactive.worktreeAutoname:false in afk.config.json.").option("--worktree-base <ref>","Base git ref for the worktree created by --worktree. Default: the remote's default branch (origin/main), fetched fresh. Pass HEAD to base on your local checkout instead. Also: AFK_WORKTREE_BASE, or interactive.worktreeBase in afk.config.json.").option("--no-shell-passthrough","Disable the ! shell-passthrough feature. When set, inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Also: AFK_SHELL_PASSTHROUGH set to 0, false, off, or no.").option("--provider <name>","Provider to use: anthropic|anthropic-direct|openai|openai-compatible. Default: auto-selected by model").option("--dump-prompt [path]",'Dump resolved SDK prompt+options+provenance to file (default: ~/.afk/logs/prompt-dump-<ISO>.json) or "stderr"').option("--dangerously-skip-permissions","Force bypass mode (already the default for new installs): skip path-approval prompts; read/write ANY path with no confirmation. Toggle live with Shift+Tab (permission-mode cycle); disable persistently with `afk config set permissionMode default`. Does not affect ask_question.").option("--mcp-config <path>","Path to an additional MCP config file (highest priority \u2014 merges over ~/.afk/config/mcp.json, project-local .mcp.json, and plugin-contributed configs). File format identical to mcp.json.").option("--plain","Force the session to fully behave like a non-TTY surface for rendering: append-only plain-stdout output instead of the live-overlay renderer (no persistent or per-turn compositor), AND the input surface downgrades to the simple line reader \u2014 even when stdout/stdin ARE a TTY. Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM reserved rows misbehave. Also: AFK_PLAIN_OUTPUT=1. Non-TTY sessions (pipes, CI) already use this path by default.").action(async(n,r)=>{if(r.debug&&(process.env.AFK_DEBUG="1"),r.plain&&(process.env.AFK_PLAIN_OUTPUT="1"),r.dumpPrompt!==void 0){let X=r.dumpPrompt===!0?Ea.join(xX.homedir(),".afk","logs",`prompt-dump-${new Date().toISOString().replace(/[:.]/g,"-")}.json`):String(r.dumpPrompt);process.env.AFK_DUMP_PROMPT=X,r.provider!==void 0&&r.provider!=="anthropic"&&r.provider!=="anthropic-direct"&&console.error(`[--dump-prompt] WARNING: active provider (${r.provider}) does not support prompt dumping. No file will be written.`)}let o=RX({text:"Initializing interactive session...",...Pm}).start();if(r.resume||r.continue)try{let X=Rc({resume:r.resume,continue:r.continue});if(X&&!X.stored){o.fail("Session not found"),process.stderr.write(`Error: session not found: ${JSON.stringify(r.resume)}
1890
+ `);return}let r=typeof t.triggeredAt=="number"?t.triggeredAt:0;Date.now()-r>qIe&&lX(qm())}catch{}}ya();function kX(e){let t=e.isTTY?"ask":"remove",n=e.cli!==void 0?"CLI flag":e.env!==void 0?"AFK_WORKTREE_ON_EXIT":"interactive.worktreeOnExit",r=e.cli??e.env??e.config;return r===void 0?t:r==="ask"||r==="keep"||r==="remove"?r:(e.console.warn(`Ignoring unrecognised ${n} worktree exit policy ${JSON.stringify(r)}; expected ask, keep, or remove.`),t)}var JIe="Keep worktree and cd into it on exit",vX="Delete worktree and branch";async function TX(e){if(e.turnCount<=0||!e.hasWorktree)return"remove";if(e.policy!=="ask"||!e.isTTY||e.picker===void 0)return e.policy==="remove"?"remove":e.policy==="keep"?"keep-locked":"keep-unlocked";try{let t=await e.picker({header:["Keep this worktree?",""],options:[JIe,vX]});return t===null?"keep-locked":t[0]===vX?"remove":"keep-locked"}catch(t){return e.console.warn(`Could not ask how to handle the worktree (${t instanceof Error?t.message:String(t)}); keeping it.`),"keep-locked"}}function YIe(e,t){return e===void 0||e.length===0||e.startsWith("/")||e.startsWith("-")?!1:!t.commands.some(n=>n.name()===e||n.aliases().includes(e))}function EX(e,t){let n=e,r=n.unknownOption.bind(n);n.unknownOption=function(i){let s=n.args[0];if(YIe(s,t)){n.error(`error: unknown command '${s}'`,{code:"commander.unknownCommand"});return}r(i)}}yw();var ok=null;function AX(e,t){ok={updateInfo:e,pendingMessage:t}}function QIe(e){if(e==="summary"||e==="live"||e==="digest"||e==="off")return e;throw new Error(`Invalid --thinking-ui value: ${e}. Expected summary|live|digest|off`)}function ZIe(e,t){switch(e){case"empty-message":case"slash-command":return;case"slug-generator-error":return t?`slug generation failed: ${t}`:"slug generation failed";case"invalid-slug-output":return t?`model returned invalid slug: ${JSON.stringify(t)}`:"model returned invalid slug";case"create-failed":return t?`named worktree create failed: ${t}`:"named worktree create failed";default:return"unknown reason"}}function ePe(e,t){if(e.worktreeAutoname===!1)return!1;let n=k.AFK_WORKTREE_AUTONAME;if(n!==void 0){let r=n.toLowerCase();return!(r==="0"||r==="false"||r==="off"||r==="no")}return typeof t.interactive?.worktreeAutoname=="boolean"?t.interactive.worktreeAutoname:!0}function tPe(e,t){if(e.thinkingUi!==void 0)return e.thinkingUi;let n=k.AFK_THINKING_UI;if(n!==void 0){let o=n.trim().toLowerCase();if(o==="summary"||o==="live"||o==="digest"||o==="off")return o}let r=t.interactive?.thinkingUi;return r!==void 0?r:"live"}function nPe(){return"/help \xB7 /model \xB7 @ for files \xB7 Shift+Tab mode \xB7 Esc to interrupt \xB7 /exit to quit"}function CX(e){let t=e.command("interactive",{isDefault:!0}).description("Start interactive chat session").argument("[input...]",'Optional first message \u2014 or a /slash-command \u2014 auto-submitted as the opening turn. E.g. `afk "what does this project do"` or `afk /review`. A bare `afk` starts an empty REPL.').option("-m, --model <model>","Model to use. Short aliases: opus|opus_1m|sonnet|sonnet_1m|haiku. Any other value (e.g. `auto` for cursor-api-proxy, or a full `claude-*` ID) passes through to the SDK/proxy untouched.",at()).option("--max-turns <number>","Maximum conversation turns","100").option("--thinking <mode>","Thinking mode: 'adaptive' | 'disabled' | 'max' | 'enabled:<N>'","enabled:max").option("--thinking-ui <mode>","Thinking display mode: summary|live|digest|off. Default live. Also: AFK_THINKING_UI env, or interactive.thinkingUi in afk.config.json.",QIe).option("--theme <mode>","TUI color palette: dark|light|umber|auto. Default dark. umber matches the Umber terminal (dark-only). Also: AFK_THEME env, or theme in afk.config.json. Toggle live with /theme.",Bf).option("--effort <level>","Effort level: low|medium|high|xhigh|max").option("--max-output-tokens <n|max>","Per-response output cap ('max' = model ceiling). Env: AFK_MAX_OUTPUT_TOKENS").option("--resume <id>","Resume a persisted SDK session by id").option("--continue","Continue the most recent persisted session in cwd").option("--debug","Show SDK init metadata on startup; enables /debug command",!1).option("-w, --worktree [branch]","Create a git worktree for an isolated session. Optional value sets the branch name; otherwise auto-named. On clean interactive exit, choose whether to keep or delete it; dirty worktrees are always preserved.").option("--worktree-on-exit <ask|keep|remove>","Clean-worktree quit policy. Default: ask on TTY, remove otherwise. Also: AFK_WORKTREE_ON_EXIT, or interactive.worktreeOnExit in afk.config.json.").option("--no-worktree-autoname","Disable mid-session rename of auto-named worktrees from the first user message via haiku. Default on. Also: AFK_WORKTREE_AUTONAME=0, or interactive.worktreeAutoname:false in afk.config.json.").option("--worktree-base <ref>","Base git ref for the worktree created by --worktree. Default: the remote's default branch (origin/main), fetched fresh. Pass HEAD to base on your local checkout instead. Also: AFK_WORKTREE_BASE, or interactive.worktreeBase in afk.config.json.").option("--no-shell-passthrough","Disable the ! shell-passthrough feature. When set, inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Also: AFK_SHELL_PASSTHROUGH set to 0, false, off, or no.").option("--provider <name>","Provider to use: anthropic|anthropic-direct|openai|openai-compatible. Default: auto-selected by model").option("--dump-prompt [path]",'Dump resolved SDK prompt+options+provenance to file (default: ~/.afk/logs/prompt-dump-<ISO>.json) or "stderr"').option("--dangerously-skip-permissions","Force bypass mode (already the default for new installs): skip path-approval prompts; read/write ANY path with no confirmation. Toggle live with Shift+Tab (permission-mode cycle); disable persistently with `afk config set permissionMode default`. Does not affect ask_question.").option("--mcp-config <path>","Path to an additional MCP config file (highest priority \u2014 merges over ~/.afk/config/mcp.json, project-local .mcp.json, and plugin-contributed configs). File format identical to mcp.json.").option("--plain","Force the session to fully behave like a non-TTY surface for rendering: append-only plain-stdout output instead of the live-overlay renderer (no persistent or per-turn compositor), AND the input surface downgrades to the simple line reader \u2014 even when stdout/stdin ARE a TTY. Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM reserved rows misbehave. Also: AFK_PLAIN_OUTPUT=1. Non-TTY sessions (pipes, CI) already use this path by default.").action(async(n,r)=>{if(r.debug&&(process.env.AFK_DEBUG="1"),r.plain&&(process.env.AFK_PLAIN_OUTPUT="1"),r.dumpPrompt!==void 0){let X=r.dumpPrompt===!0?Ea.join(xX.homedir(),".afk","logs",`prompt-dump-${new Date().toISOString().replace(/[:.]/g,"-")}.json`):String(r.dumpPrompt);process.env.AFK_DUMP_PROMPT=X,r.provider!==void 0&&r.provider!=="anthropic"&&r.provider!=="anthropic-direct"&&console.error(`[--dump-prompt] WARNING: active provider (${r.provider}) does not support prompt dumping. No file will be written.`)}let o=RX({text:"Initializing interactive session...",...Pm}).start();if(r.resume||r.continue)try{let X=Rc({resume:r.resume,continue:r.continue});if(X&&!X.stored){o.fail("Session not found"),process.stderr.write(`Error: session not found: ${JSON.stringify(r.resume)}
1891
1891
  Run \`afk i\` then \`/resume\` to list saved sessions.
1892
1892
  `),process.exitCode=1;return}}catch(X){o.fail("Session not found");let le=X instanceof Error?X.message:String(X);process.stderr.write(`Error: ${le}
1893
1893
  Run \`afk i\` then \`/resume\` to list saved sessions.
@@ -1906,7 +1906,7 @@ Run \`afk i\` then \`/resume\` to list saved sessions.
1906
1906
  ${Pn}.`))}catch(s){Ra(s.message)}}),n.command("unset <key>").description("Remove an afk.env var").option("--json","Output JSON").action((r,o)=>{try{let i=Fh(r,{allowSecret:!0,allowProtected:!0});o.json?console.log(JSON.stringify({ok:!0,...i})):console.log(i.removed?m.success(`\u2713 removed ${i.key} \u2192 ${i.persistedTo}`):m.meta(`(${i.key} was not set)`))}catch(i){Ra(i.message)}})}j();U();import NPe from"path";import BPe from"os";import{createServer as kPe}from"node:http";import{writeFileSync as TPe,unlinkSync as EPe,mkdirSync as RPe,readFileSync as xPe}from"node:fs";import{dirname as APe,join as CPe}from"node:path";j();Tl();eh();import{mkdirSync as mPe,appendFileSync as fPe}from"node:fs";import{dirname as gPe}from"node:path";import{execFile as hPe}from"node:child_process";import{promisify as yPe}from"node:util";import{randomUUID as bPe}from"node:crypto";import*as YX from"node-cron";var ik=class{_count=0;increment(){this._count++}decrement(){this._count>0&&this._count--}isIdle(){return this._count===0}count(){return this._count}};K();Ko();import{mkdirSync as md,readdirSync as zm,readFileSync as aM,renameSync as iM,statSync as FX,unlinkSync as Vm,writeFileSync as sPe}from"node:fs";import{randomBytes as sM}from"node:crypto";import{join as qr}from"node:path";function LX(e,t={},n=Mt()){md(n,{recursive:!0});let o=zm(n).filter(f=>f.endsWith(".json")).length+1,i=`q-${Date.now()}-${sM(3).toString("hex")}`,s=new Date().toISOString(),a={id:i,command:e,enqueuedAt:s,sequence:o,...t.notifyOn!==void 0?{notifyOn:t.notifyOn}:{}},c=`${String(o).padStart(4,"0")}-${i}.json`,d=qr(n,c),u=sM(4).toString("hex"),p=qr(n,`.tmp-${u}.json`);try{sPe(p,JSON.stringify(a),"utf-8"),iM(p,d)}catch(f){try{Vm(p)}catch{}throw f}return a}var OX="poison",$X=new Map,aPe=10;function NX(e=Mt()){md(e,{recursive:!0});let t=zm(e).filter(n=>n.endsWith(".json")&&!n.startsWith(".tmp-")).sort();for(let n of t){let r=qr(e,n),o;try{o=aM(r,"utf-8")}catch(s){DX(e,n,s);continue}let i;try{i=JSON.parse(o)}catch(s){DX(e,n,s);continue}return Vm(r),i}return null}function DX(e,t,n){let r=Ne(t),o=n instanceof SyntaxError?"SyntaxError: invalid JSON":Ne(n instanceof Error?n.message:String(n)),i=qr(e,OX),s=qr(e,t);try{md(i,{recursive:!0});let a=qr(i,t);try{iM(s,a)}catch{a=qr(i,`${Date.now()}-${sM(3).toString("hex")}-${t}`),iM(s,a)}console.error(`[daemon] pull-queue: quarantined malformed entry ${r} \u2192 ${OX}/ (${o})`)}catch(a){let l=Ne(a instanceof Error?a.message:String(a));console.error(`[daemon] pull-queue: failed to quarantine malformed entry ${r}; removing to unblock queue (${l})`);try{Vm(s)}catch(c){let d=`${e}/${t}`,u=($X.get(d)??0)+1;if($X.set(d,u),u===1||u%aPe===0){let p=Ne(c instanceof Error?c.message:String(c));console.error(`[daemon] pull-queue: could not remove unquarantinable entry ${r}; will retry next tick (${p}) [seen ${u}x]`)}}}}function lM(e=Mt()){try{md(e,{recursive:!0})}catch{return[]}let t=zm(e).filter(r=>r.endsWith(".json")&&!r.startsWith(".tmp-")).sort(),n=[];for(let r of t){let o=qr(e,r);try{n.push(JSON.parse(aM(o,"utf-8")))}catch(i){let s=Ne(r),a=i instanceof SyntaxError?"SyntaxError: invalid JSON":Ne(i instanceof Error?i.message:String(i));console.error(`[daemon] pull-queue: skipping unreadable entry ${s} in listPending (${a})`)}}return n}function BX(e=Mt(),t){try{md(e,{recursive:!0})}catch{return!1}let n=zm(e).filter(r=>r.endsWith(".json")&&!r.startsWith(".tmp-")).sort();for(let r of n){let o=qr(e,r);try{if(FX(o).isDirectory())continue}catch{continue}let i;try{i=JSON.parse(aM(o,"utf-8"))}catch{continue}if(i.id===t)return Vm(o),!0}return!1}function UX(e=Mt()){try{md(e,{recursive:!0})}catch{return 0}let t=zm(e).filter(r=>r.endsWith(".json")&&!r.startsWith(".tmp-")).sort(),n=0;for(let r of t){let o=qr(e,r);try{if(FX(o).isDirectory())continue}catch{continue}try{Vm(o),n+=1}catch(i){let s=Ne(r),a=Ne(i instanceof Error?i.message:String(i));console.error(`[daemon] pull-queue: failed to remove entry ${s} in clearPending (${a})`)}}return n}K();tS();Wp();Hp();Dt();io();pe();K();Ko();function jX(e){if(!e.taskId)throw new Error("ScheduledTask.taskId is required");if(!e.command)throw new Error(`task ${e.taskId}: command is required`);if((e.trigger==="cron"||e.trigger==="both")&&!e.cronExpression)throw new Error(`task ${e.taskId}: cronExpression required for trigger=${e.trigger}`);if(e.trigger==="pull"&&e.cronExpression!==void 0)throw new Error(`task ${e.taskId}: cronExpression must not be set when trigger='pull' \u2014 pull tasks are dequeued from the queue directory, not scheduled via cron`)}import{existsSync as lPe,readFileSync as cPe}from"node:fs";var HX=360*60*1e3;function dPe(e,t){if(!lPe(t))return null;let n;try{n=cPe(t,"utf-8")}catch{return null}let r=n.split(`
1907
1907
  `);for(let o=r.length-1;o>=0;o-=1){let i=r[o];if(i)try{let s=JSON.parse(i);if(s.taskId!==e||typeof s.triggeredAt!="string")continue;let a=Date.parse(s.triggeredAt);if(Number.isNaN(a))continue;return a}catch{continue}}return null}function WX(e){let t=dPe(e.taskId,e.telemetryPath);if(t!==null&&e.cooldownMs>0){let n=e.nowMs-t;if(n<e.cooldownMs)return{fire:!1,skipReason:"cooldown",lastFiredAtMs:t,cooldownRemainingMs:e.cooldownMs-n}}return{fire:!0,...t!==null?{lastFiredAtMs:t}:{}}}import{basename as uPe}from"node:path";var KX=500;function GX(e){let t=e.map(r=>`${uPe(r.repoRoot)}: ${r.reason}`).join("; "),n=`${String(e.length)} root(s) failed sweep \u2014 ${t}`;return n.length<=KX?n:`${n.slice(0,KX-1)}\u2026`}var pPe=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);function qX(e){return e.filter(t=>pPe.has(t.verdict)).length}function zX(e){let{removed:t,warnings:n,wouldRemove:r,liveRoots:o,previewRoots:i,contestedRoots:s,failedRoots:a,totalRoots:l}=e,c=o+i,d=o===0&&i>0,u=d?"\u{1F50D}":i>0?"\u2702\uFE0F\u{1F50D}":"\u2702\uFE0F",p=d?"worktree-prune (dry-run)":"worktree-prune",f=[`removed ${String(t)}, warned ${String(n)}`];return i>0&&f.push(`would remove ${String(r)} on ${String(i)} preview root(s)`),s>0&&f.push(`${String(s)} contested`),a>0&&f.push(`${String(a)} failed`),`${u} ${p}: ${f.join("; ")} across ${String(c)}/${String(l)} root(s)`}me();var SPe=12e4,wPe=yPe(hPe),VX=(e,t,n)=>wPe(e,t,{timeout:SPe,...n});async function vPe(e,t,n){if(n!==void 0&&n.length>0)return n;try{let o=(await e("git",["rev-parse","--show-toplevel"],{cwd:t})).stdout.trim();return o.length>0?o:null}catch{return null}}function JX(e){return`${e.replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"task"}-${bPe()}`}var sk=class{registry=new Map;options;defaultCooldownMs;now;idleDetector=new ik;pullPollTimer;isDequeuing=!1;queueDir;constructor(t={}){this.options=t,this.defaultCooldownMs=t.cooldownMs??HX,this.now=t.now??Date.now,this.queueDir=t.queueDir??Mt(),this.ensureTelemetrySink()}register(t){if(jX(t),this.registry.has(t.taskId))throw new Error(`task ${t.taskId} is already registered`);let n;(t.trigger==="cron"||t.trigger==="both")&&(n=YX.schedule(t.cronExpression,()=>{this.runOnce(t,"cron").catch(()=>{})},{name:t.taskId})),this.registry.set(t.taskId,{task:t,cronTask:n})}unregister(t){let n=this.registry.get(t);n&&(n.cronTask&&(Promise.resolve(n.cronTask.stop()).catch(()=>{}),Promise.resolve(n.cronTask.destroy()).catch(()=>{})),this.registry.delete(t))}list(){return Array.from(this.registry.values()).map(t=>t.task)}async tick(t){let n=this.registry.get(t);if(!n)throw new Error(`task ${t} is not registered`);return this.runOnce(n.task,"cron")}async fireOnStart(){let t=Array.from(this.registry.values()).map(r=>r.task).filter(r=>r.trigger==="sessionstart"||r.trigger==="both"),n=[];for(let r of t){let o=r.debounceMs??this.defaultCooldownMs,i=WX({taskId:r.taskId,cooldownMs:o,nowMs:this.now(),telemetryPath:this.telemetryPath()});i.fire?n.push(await this.runOnce(r,"sessionstart")):n.push(this.recordSkip(r,i))}return n}async stop(){this.pullPollTimer!==void 0&&(clearInterval(this.pullPollTimer),this.pullPollTimer=void 0);for(let t of Array.from(this.registry.keys()))this.unregister(t)}startPullLoop(){if(this.pullPollTimer!==void 0)return;let t=this.options.pullPollIntervalMs;!t||t<=0||(this.pullPollTimer=setInterval(()=>{this.pullTick()},t).unref())}async pullTick(){if(this.idleDetector.isIdle()&&!this.isDequeuing){this.isDequeuing=!0;try{let t=NX(this.queueDir);if(t===null)return;let n={taskId:t.id,command:t.command,trigger:"pull",...t.notifyOn!==void 0?{notifyOn:t.notifyOn}:{}};await this.runOnce(n,"pull")}catch(t){let n=Ne(t instanceof Error?t.message:String(t));console.error(`[daemon] pull tick failed: ${n}`)}finally{this.isDequeuing=!1}}}async runOnce(t,n){if(t.command==="__BUILTIN_WORKTREE_PRUNE__")return this.runBuiltinWorktreePrune(t,n);let r=new Date(this.now()),o=this.now(),i={taskId:t.taskId,command:Ne(t.command),trigger:n,...t.cronExpression!==void 0?{cronExpression:t.cronExpression}:{},triggeredAt:r.toISOString()},s=null,a=null,l=null,c=null;this.idleDetector.increment();try{let d=await this.spawnSession(t.taskId);s=d.session,a=d.memoryStore,l=d.mcpManager??null,c=d.dispose;let u=await s.sendMessage(t.command),p=Ne(u.content),f=!1;try{let h=this.options.doneUnverifiedProbe;if(h!==void 0){let b=Array.isArray(u.metadata?.successfulToolNames)?u.metadata.successfulToolNames:[];f=h({responseText:p,successfulToolNames:b})}}catch{f=!1}let g={...i,durationMs:this.now()-o,status:"success",responseExcerpt:p.slice(0,280)};return this.writeTelemetry(g,t,{responseText:p,...f?{doneUnverified:!0}:{}}),g}catch(d){let u={...i,durationMs:this.now()-o,status:"error",errorMessage:Ne(d instanceof Error?d.message:String(d))};return this.writeTelemetry(u,t),u}finally{if(this.idleDetector.decrement(),s)try{await s.close()}catch{}if(c?.(),l)try{await l.disconnectAll()}catch{}a?.close()}}recordSkip(t,n){let r=new Date(this.now()),o={taskId:t.taskId,command:t.command,trigger:"sessionstart",...t.cronExpression!==void 0?{cronExpression:t.cronExpression}:{},triggeredAt:r.toISOString(),durationMs:0,status:"skipped",...n.skipReason!==void 0?{skipReason:n.skipReason}:{}};return this.writeTelemetry(o,t),o}async runBuiltinWorktreePrune(t,n){let r=new Date(this.now()),o=this.now(),i={taskId:t.taskId,command:t.command,trigger:n,...t.cronExpression!==void 0?{cronExpression:t.cronExpression}:{},triggeredAt:r.toISOString()};try{let s=await vPe(VX,process.cwd(),k.AFK_WORKTREE_SWEEP_ROOT),a=await OF(s);if(a.length===0){let v={...i,durationMs:this.now()-o,status:"skipped",responseExcerpt:"worktree-prune skipped: no roots to sweep \u2014 daemon cwd is not inside a git repository and no managed worktree roots are registered (set AFK_WORKTREE_SWEEP_ROOT to target a repo)"};return this.writeTelemetry(v,t),v}let l=parseInt(k.AFK_WORKTREE_MAX_AGE_CLEAN??"",10)||14,c=parseInt(k.AFK_WORKTREE_MAX_AGE_DIRTY??"",10)||30,d=[],u=[],p=[];for(let v of a)try{d.push(await In({execFile:VX,repoRoot:v,dryRun:!1,maxAgeDaysClean:l,maxAgeDaysDirty:c,scope:"all",telemetryPath:this.telemetryPath()}))}catch(E){let T=Ne(E instanceof Error?E.message:String(E));u.push(`[ERROR] sweep failed for ${v}: ${T}`),p.push({repoRoot:v,reason:T}),B(`[worktree-prune] sweep failed for ${v}: ${T}`)}let f={dryRun:d.some(v=>v.dryRun),removed:d.flatMap(v=>v.removed),warnings:[...u,...d.flatMap(v=>v.warnings)],candidates:d.flatMap(v=>v.candidates)},g=d.filter(v=>v.contested===!0),h=d.filter(v=>v.dryRun&&v.contested!==!0),b=d.filter(v=>!v.dryRun&&v.contested!==!0),S=zX({removed:f.removed.length,warnings:f.warnings.length,wouldRemove:qX(h.flatMap(v=>v.candidates)),liveRoots:b.length,previewRoots:h.length,contestedRoots:g.length,failedRoots:p.length,totalRoots:a.length}),w=d.length===0&&a.length>0?{...i,durationMs:this.now()-o,status:"error",errorMessage:GX(p),responseExcerpt:S}:{...i,durationMs:this.now()-o,status:"success",responseExcerpt:S};return this.writeTelemetry(w,t),w}catch(s){let a={...i,durationMs:this.now()-o,status:"error",errorMessage:Ne(s instanceof Error?s.message:String(s))};return this.writeTelemetry(a,t),a}}async spawnSession(t){let n=JX(t),r=this.options.sessionConfig?.cwd??process.cwd(),o=Fr({sessionLabel:JX(t)}),{registry:i,memoryStore:s}=wi(void 0,"daemon",void 0,void 0,pc({cwd:r}),{cwd:r,sessionId:n,...o?.writer!==void 0?{traceWriter:o.writer}:{}}),a,l=Jn(un()).mcpConfigs.filter(g=>g.format==="json").map(g=>g.source),c=ea({cwd:r,...l.length>0?{importedMcpConfigs:l}:{}}),d=Object.values(c.mcpServers).filter(g=>!g.disabled).length;try{if(d>0){let g=Date.now();re(o?.writer,{phase:"mcp_connect_start",metadata:{serverCount:d}});try{a=await Ro.fromConfig(c.mcpServers,{warnings:c.warnings,...o?.writer!==void 0?{traceWriter:o.writer}:{}})}finally{re(o?.writer,{phase:"mcp_connect_done",durationMs:Date.now()-g,metadata:{serverCount:d}})}}else if(c.warnings.length>0)for(let g of c.warnings)console.warn(`[mcp] ${g}`)}catch(g){throw s.close(),g}let u=k.AFK_MAX_TOOL_USE_ITERATIONS,p=u!==void 0&&Number.isFinite(Number(u))&&Number(u)>0?Math.floor(Number(u)):void 0,f={model:"sonnet",permissionMode:"bypassPermissions",hookRegistry:i,isNonInteractive:!0,surface:"daemon",...o?{traceWriter:o.writer}:{},...a!==void 0?{mcpManager:a}:{},...p!==void 0?{maxToolUseIterations:p}:{},...this.options.sessionConfig};try{let g=this.options.sessionConfig?.traceWriter===void 0?o?.writer:void 0,h=this.options.sessionFactory?this.options.sessionFactory(f,g):new Ct(vo(co(f)),g),b=NS(h,{surface:"daemon",model:f.model,cwd:r});return{session:h,memoryStore:s,dispose:b.dispose,...a!==void 0?{mcpManager:a}:{}}}catch(g){throw a&&await a.disconnectAll().catch(()=>{}),s.close(),g}}telemetryPath(){return this.options.telemetryPath??pr()}ensureTelemetrySink(){try{mPe(gPe(this.telemetryPath()),{recursive:!0})}catch{}}writeTelemetry(t,n,r){try{fPe(this.telemetryPath(),`${JSON.stringify(t)}
1908
1908
  `,"utf-8"),this.fireOnTaskComplete(t,n,r)}catch(o){let i=o instanceof Error?o.message:String(o);console.error(`[daemon] telemetry write failed: ${i}`)}}fireOnTaskComplete(t,n,r){let o=this.options.onTaskComplete;if(!o||n!==void 0&&(n.notifyOn==="never"||n.notifyOn==="failure"&&t.status!=="error"))return;let i=n?.notifyChat!==void 0?{...r??{},notifyChat:r?.notifyChat??n.notifyChat}:r;try{let s=o(t,i);s instanceof Promise&&s.catch(a=>{let l=a instanceof Error?a.message:String(a);console.error(`[daemon] onTaskComplete callback failed: ${l}`)})}catch(s){let a=s instanceof Error?s.message:String(s);console.error(`[daemon] onTaskComplete callback failed: ${a}`)}}};K();var _Pe=7777,IPe="127.0.0.1";async function XX(e={}){let t=new sk({...e.sessionConfig!==void 0?{sessionConfig:e.sessionConfig}:{},...e.telemetryPath!==void 0?{telemetryPath:e.telemetryPath}:{},...e.sessionFactory!==void 0?{sessionFactory:e.sessionFactory}:{},...e.cooldownMs!==void 0?{cooldownMs:e.cooldownMs}:{},...e.now!==void 0?{now:e.now}:{},...e.onTaskComplete!==void 0?{onTaskComplete:e.onTaskComplete}:{},...e.doneUnverifiedProbe!==void 0?{doneUnverifiedProbe:e.doneUnverifiedProbe}:{},...e.pullPollIntervalMs!==void 0?{pullPollIntervalMs:e.pullPollIntervalMs}:{},...e.queueDir!==void 0?{queueDir:e.queueDir}:{}});e.pullPollIntervalMs!==void 0&&e.pullPollIntervalMs>0&&t.startPullLoop();for(let a of e.tasks??[])t.register(a);let n=e.writePortFile!==!1,r=CPe(If("default"),"port"),o=kPe((a,l)=>MPe(a,l,t)),{port:i,address:s}=await $Pe(o,e.port??_Pe,e.host??IPe);if(n)try{RPe(APe(r),{recursive:!0}),TPe(r,String(i),"utf-8")}catch{}return{port:i,host:s,scheduler:t,registerTask(a){t.register(a)},unregisterTask(a){t.unregister(a)},tickOnce(a){return t.tick(a)},fireOnStart(){return t.fireOnStart()},async stop(){if(await t.stop(),n)try{xPe(r,"utf-8").trim()===String(i)&&EPe(r)}catch{}await DPe(o)}}}function PPe(e){return new Promise((t,n)=>{let r=[];e.on("data",o=>r.push(o)),e.on("end",()=>t(Buffer.concat(r).toString("utf-8"))),e.on("error",n)})}function MPe(e,t,n){OPe(e,t,n).catch(r=>{let o=r instanceof Error?r.message:String(r);t.headersSent||t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:o}))})}async function OPe(e,t,n){let r=e.url??"/";if(e.method==="GET"&&r==="/health"){let o=JSON.stringify({status:"ok",tasks:n.list().length});t.writeHead(200,{"Content-Type":"application/json"}),t.end(o);return}if(e.method==="GET"&&r==="/tasks"){t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(n.list()));return}if(e.method==="POST"&&r==="/tasks"){let o=await PPe(e),i;try{i=JSON.parse(o)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid JSON body"}));return}if(!i||typeof i!="object"){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"body must be an object"}));return}let s=i,a=s.cron??s.cronExpression;if(typeof s.taskId!="string"||typeof s.command!="string"||typeof a!="string"){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"taskId, command, and cron (or cronExpression) are required strings"}));return}let l=s.notifyChat,c={taskId:s.taskId,command:s.command,trigger:s.trigger??"cron",cronExpression:a,...s.notifyOn!==void 0?{notifyOn:s.notifyOn}:{},...typeof l=="number"||typeof l=="string"?{notifyChat:l}:{}};try{n.register(c)}catch(d){let u=d instanceof Error?d.message:String(d),p=u.includes("already registered")?409:400;t.writeHead(p,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:u}));return}t.writeHead(201,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0}));return}if(e.method==="DELETE"&&r.startsWith("/tasks/")){let o=r.slice(7);if(!o){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"taskId required in URL"}));return}if(!n.list().some(s=>s.taskId===o)){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}n.unregister(o),t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0}));return}t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"not found"}))}function $Pe(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen(t,n,()=>{e.removeListener("error",o);let i=e.address();r(typeof i=="object"&&i?{port:i.port,address:i.address}:{port:t,address:n})})})}function DPe(e){return new Promise((t,n)=>{e.close(r=>{r?n(r):t()})})}K();so();Du();Gg();mv();function QX(e,t){let n=e??t;if(n===void 0||n==="")return;let r=Number(n);if(!Number.isFinite(r)||!Number.isInteger(r)||r<=0)throw new Error(`Invalid timeout-ms: '${n}' \u2014 must be a positive integer (milliseconds).`);return r}function ZX(e,t){let n=e??t;if(n===void 0||n==="")return;let r=Number(n);if(!Number.isFinite(r)||!Number.isInteger(r)||r<0)throw new Error(`Invalid sessionstart-cooldown-ms: '${n}' \u2014 must be a non-negative integer (milliseconds).`);return r}function e9(e,t){if(e!==void 0&&e!==""){if(e==="cron"||e==="sessionstart"||e==="both"||e==="pull")return e;throw new Error(`Invalid trigger: '${e}' \u2014 must be one of cron | sessionstart | both | pull.`)}return t!==void 0&&t!==""?"cron":"sessionstart"}var FPe="",cM="default";function Hi(e){if(e!==void 0&&e.trim()!=="")return e}function t9(e,t,n){return Hi(e)??Hi(t)??Hi(n)??FPe}function n9(e,t,n){return Hi(e)??Hi(t)??Hi(n)??cM}var LPe="127.0.0.1";function r9(e,t){return Hi(e)??Hi(t)??LPe}function o9(e){let t=e.trim().toLowerCase();return t==="127.0.0.1"||t==="localhost"||t==="::1"}At();lt();vh();tc();Dt();er();rr();Ws();cn();Dt();$t();function UPe(e){let t;return(n,r)=>{let o=new AbortController,i=js(o.signal),{rootManager:s,subagentExecutor:a,skillExecutor:l,composeExecutor:c}=kc({surface:"daemon",parentSession:i,apiKey:e.apiKey,model:e.model,managerParentModel:e.model,defaultSubagentModel:mc(e.model),resolveApiKeyForModel:en,...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.openaiBaseUrl!==void 0?{openaiBaseUrl:e.openaiBaseUrl}:{},...e.cwd!==void 0?{cwd:e.cwd,nestedCwd:e.cwd}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter,skillTraceWriter:n.traceWriter}:{}});t??=new xt;let d=n.mcpManager,u=d?.getMcpToolWireNames()??[],p=qs(void 0,{subagentExecutor:a,skillExecutor:l,composeExecutor:c,memoryStore:t,model:String(e.model),...e.openaiBaseUrl!==void 0?{openaiBaseUrl:e.openaiBaseUrl}:{},...d!==void 0?{mcpManager:d}:{}})??new et({permissions:{allowedTools:[...Gt,...gs,...ht,"agent","skill","compose",...u]},subagentExecutor:a,skillExecutor:l,composeExecutor:c,memoryStore:t,surface:"daemon",...d!==void 0?{mcpManager:d}:{}}),f=n.maxToolUseIterations??bc();return new Ct(vo(co({...n,provider:p,isNonInteractive:!0,drainSubagents:g=>s.abortAllAndDrain("session_end","user_signal",void 0,g==="reset"),surface:"daemon",...f!==void 0?{maxToolUseIterations:f}:{}})),r)}}var jPe="\u26A0\uFE0F Unverified: no file write/edit or successful command recorded this turn \u2014 confirm before relying on this.";function HPe(e,t){if(e===void 0)return;let n=ah(e,lh());if(!n.ok){console.error(`[daemon] task ${t}: ignoring notifyChat \u2014 ${n.message} Falling back to default routing.`);return}let r=yl(k.AFK_TELEGRAM_ALLOWED_CHAT_IDS);if(!Kg(n.id,r)){console.error(`[daemon] task ${t}: ignoring notifyChat ${n.id} \u2014 not in AFK_TELEGRAM_ALLOWED_CHAT_IDS. Falling back to default routing.`);return}return n.id}function WPe(e,t={},n=!1){let r=n===!0&&t.doneUnverified===!0,o=e.status==="success"?"\u2705":e.status==="skipped"?"\u23ED\uFE0F":"\u274C",i=(e.durationMs/1e3).toFixed(1),a=[r?`\u26A0\uFE0F Done (unverified) \u2014 daemon task: ${e.taskId} (${e.status})`:`${o} daemon task: ${e.taskId} (${e.status})`,`trigger=${e.trigger} duration=${i}s`];e.skipReason&&a.push(`skipReason=${e.skipReason}`),e.errorMessage&&a.push(`error: ${e.errorMessage.slice(0,400)}`);let l=t.responseText??e.responseExcerpt;return l&&a.push("",l),r&&a.push("",jPe),a.join(`
1909
- `)}function i9(e){e.command("daemon").description("Run agent-afk as a daemon that fires scheduled tasks (e.g. /forge-friction --auto)").option("-p, --port <number>","Control HTTP port","7777").option("--host <address>","Bind address for the control HTTP surface. Overrides AFK_DAEMON_HOST. Defaults to 127.0.0.1 (loopback only). The control surface is UNAUTHENTICATED \u2014 bind a non-loopback address (e.g. 0.0.0.0) only on a trusted or firewalled network.").option("-t, --task <command>","Command to fire on each tick. Required for the cron and both triggers; optional otherwise.").option("-c, --cron <expression>",'Cron expression (e.g. "0 */6 * * *"). Required when --trigger includes cron.').option("-i, --task-id <id>",`Task identifier (default: ${cM})`).option("--once","Fire one tick and exit (for testing)",!1).option("--timeout-ms <ms>","Per-tick session timeout in ms. Overrides AFK_TIMEOUT_MS. Defaults to the session default (120000).").option("--thinking <mode>","Thinking mode: 'adaptive' | 'disabled' | 'enabled:<N>'").option("--effort <level>","Effort level: low|medium|high|xhigh|max").option("--trigger <mode>","Trigger mode: cron | sessionstart | both | pull. Defaults to 'cron' when --cron is set, else 'sessionstart'.").option("--sessionstart-cooldown-ms <ms>","Cooldown between Phase 6 sessionstart fires. Overrides AFK_SESSIONSTART_COOLDOWN_MS. Defaults to 6h.").option("--dump-prompt [path]",'Dump resolved SDK prompt+options+provenance to file (default: ~/.afk/logs/prompt-dump-<ISO>.json) or "stderr"').action(async t=>{let n=parseInt(t.port,10);(Number.isNaN(n)||n<=0)&&V(new Error(`Invalid port: ${t.port}`));let r=Xe(),o=t9(t.task,k.AFK_DAEMON_TASK,r.daemon?.task),i=n9(t.taskId,k.AFK_DAEMON_TASK_ID,r.daemon?.taskId),s=r9(t.host,k.AFK_DAEMON_HOST),a,l,c;try{a=QX(t.timeoutMs,k.AFK_TIMEOUT_MS),l=ZX(t.sessionstartCooldownMs,k.AFK_SESSIONSTART_COOLDOWN_MS),c=e9(t.trigger,t.cron)}catch(C){V(C)}(c==="cron"||c==="both")&&!t.cron&&V(new Error(`--cron is required when --trigger is '${c}'.`)),(c==="cron"||c==="both")&&o.trim()===""&&V(new Error("A daemon task is required for the cron and both triggers. Provide one via --task, the AFK_DAEMON_TASK env var, or daemon.task in afk.config.json."));let d,u;try{d=ki(t.thinking)??fc(),u=Ti(t.effort)??gc()}catch(C){V(C)}let p=r.daemon?.worktreePrune,f=k.AFK_WORKTREE_PRUNE_DISABLE==="1",g=p?.cron??"0 4 * * *",h={taskId:"worktree-prune",command:"__BUILTIN_WORKTREE_PRUNE__",trigger:"cron",cronExpression:g},b=c==="pull"||o.trim()===""?[]:[{taskId:i,command:o,trigger:c,...t.cron!==void 0?{cronExpression:t.cron}:{}}];!f&&p?.enabled!==!1&&b.push(h);let S=Cn();for(let C of S)C.enabled&&b.push(nN(C));if(t.dumpPrompt!==void 0&&t.dumpPrompt!==!1){let C=t.dumpPrompt===!0?NPe.join(BPe.homedir(),".afk","logs",`prompt-dump-${new Date().toISOString().replace(/[:.]/g,"-")}.json`):t.dumpPrompt;process.env.AFK_DUMP_PROMPT=C}let w=0,v=6e4,E=(C,P)=>{let $=Date.now();if($-w<v)return;w=$;let q=P instanceof Error?`${P.name}: ${P.message}`:String(P);xn(`\u{1F6D1} agent-afk daemon ${C}
1909
+ `)}function i9(e){e.command("daemon").description("Run agent-afk as a daemon that fires scheduled tasks (e.g. /forge-friction --auto)").option("-p, --port <number>","Control HTTP port","7777").option("--host <address>","Bind address for the control HTTP surface. Overrides AFK_DAEMON_HOST. Defaults to 127.0.0.1 (loopback only). The control surface is UNAUTHENTICATED \u2014 bind a non-loopback address (e.g. 0.0.0.0) only on a trusted or firewalled network.").option("-t, --task <command>","Command to fire on each tick. Required for the cron and both triggers; optional otherwise.").option("-c, --cron <expression>",'Cron expression (e.g. "0 */6 * * *"). Required when --trigger includes cron.').option("-i, --task-id <id>",`Task identifier (default: ${cM})`).option("--once","Fire one tick and exit (for testing)",!1).option("--timeout-ms <ms>","Per-tick session timeout in ms. Overrides AFK_TIMEOUT_MS. Defaults to the session default (120000).").option("--thinking <mode>","Thinking mode: 'adaptive' | 'disabled' | 'max' | 'enabled:<N>'").option("--effort <level>","Effort level: low|medium|high|xhigh|max").option("--trigger <mode>","Trigger mode: cron | sessionstart | both | pull. Defaults to 'cron' when --cron is set, else 'sessionstart'.").option("--sessionstart-cooldown-ms <ms>","Cooldown between Phase 6 sessionstart fires. Overrides AFK_SESSIONSTART_COOLDOWN_MS. Defaults to 6h.").option("--dump-prompt [path]",'Dump resolved SDK prompt+options+provenance to file (default: ~/.afk/logs/prompt-dump-<ISO>.json) or "stderr"').action(async t=>{let n=parseInt(t.port,10);(Number.isNaN(n)||n<=0)&&V(new Error(`Invalid port: ${t.port}`));let r=Xe(),o=t9(t.task,k.AFK_DAEMON_TASK,r.daemon?.task),i=n9(t.taskId,k.AFK_DAEMON_TASK_ID,r.daemon?.taskId),s=r9(t.host,k.AFK_DAEMON_HOST),a,l,c;try{a=QX(t.timeoutMs,k.AFK_TIMEOUT_MS),l=ZX(t.sessionstartCooldownMs,k.AFK_SESSIONSTART_COOLDOWN_MS),c=e9(t.trigger,t.cron)}catch(C){V(C)}(c==="cron"||c==="both")&&!t.cron&&V(new Error(`--cron is required when --trigger is '${c}'.`)),(c==="cron"||c==="both")&&o.trim()===""&&V(new Error("A daemon task is required for the cron and both triggers. Provide one via --task, the AFK_DAEMON_TASK env var, or daemon.task in afk.config.json."));let d,u;try{d=ki(t.thinking)??fc(),u=Ti(t.effort)??gc()}catch(C){V(C)}let p=r.daemon?.worktreePrune,f=k.AFK_WORKTREE_PRUNE_DISABLE==="1",g=p?.cron??"0 4 * * *",h={taskId:"worktree-prune",command:"__BUILTIN_WORKTREE_PRUNE__",trigger:"cron",cronExpression:g},b=c==="pull"||o.trim()===""?[]:[{taskId:i,command:o,trigger:c,...t.cron!==void 0?{cronExpression:t.cron}:{}}];!f&&p?.enabled!==!1&&b.push(h);let S=Cn();for(let C of S)C.enabled&&b.push(nN(C));if(t.dumpPrompt!==void 0&&t.dumpPrompt!==!1){let C=t.dumpPrompt===!0?NPe.join(BPe.homedir(),".afk","logs",`prompt-dump-${new Date().toISOString().replace(/[:.]/g,"-")}.json`):t.dumpPrompt;process.env.AFK_DUMP_PROMPT=C}let w=0,v=6e4,E=(C,P)=>{let $=Date.now();if($-w<v)return;w=$;let q=P instanceof Error?`${P.name}: ${P.message}`:String(P);xn(`\u{1F6D1} agent-afk daemon ${C}
1910
1910
  ${q.slice(0,500)}`).catch(F=>{console.error("[daemon] crash notification push failed:",F instanceof Error?F.message:String(F))})};process.on("uncaughtException",C=>{E("uncaughtException",C),process.exit(1)}),process.on("unhandledRejection",C=>{E("unhandledRejection",C),process.exit(1)});let T=k.AFK_DAEMON_CWD,A=at(),M=Dn(),_=T!==void 0&&T.length>0?T:void 0;await sc();let x=UPe({model:A,...M!==void 0?{apiKey:M}:{},...r.baseUrl!==void 0?{baseUrl:r.baseUrl}:{},...r.openaiBaseUrl!==void 0?{openaiBaseUrl:r.openaiBaseUrl}:{},..._!==void 0?{cwd:_}:{}});try{let C=await XX({port:n,host:s,...t.once?{writePortFile:!1}:{},sessionConfig:{model:A,...M!==void 0?{apiKey:M}:{},...r.baseUrl!==void 0?{baseUrl:r.baseUrl}:{},...a!==void 0?{timeoutMs:a}:{},...d!==void 0?{thinking:d}:{},...u!==void 0?{effort:u}:{},..._!==void 0?{cwd:_}:{}},sessionFactory:x,...l!==void 0?{cooldownMs:l}:{},...c==="pull"?{pullPollIntervalMs:3e4,queueDir:Mt()}:{},tasks:b,doneUnverifiedProbe:({responseText:$,successfulToolNames:q})=>{let F=Zv($);return F===null||F.kind!=="done"?!1:!q.some(G=>VI.has(G))},onTaskComplete:($,q)=>{let F=HPe(q?.notifyChat,$.taskId);xn(WPe($,q,r.daemon?.verifyDone===!0),{markdown:!0,...F!==void 0?{target:F}:{}}).catch(()=>{})}});if(t.once){console.log(m.info(`\u25B6 Firing task '${i}' once...`));let $=await C.tickOnce(i);console.log(JSON.stringify($,null,2)),await C.stop(),process.exit($.status==="success"?0:1)}if(c==="sessionstart"||c==="both"){let $=await C.fireOnStart();for(let q of $){let F=q.status==="success"?"\u2714":q.status==="skipped"?"\u23ED":"\u2717";console.log(m.info(`${F} sessionstart: ${JSON.stringify(q)}`))}}console.log(m.success(`\u2714 Daemon listening on http://${C.host}:${C.port}`)),o9(C.host)||console.log(m.warning(`\u26A0 Control surface bound to ${C.host} (non-loopback) and is UNAUTHENTICATED \u2014 anyone who can reach this port can schedule commands the daemon will run. Ensure the port is firewalled / on a trusted network.`)),c==="pull"?(console.log(m.success("\u2714 Daemon in pull mode")),console.log(m.dim(` polling queue: ${Mt()} every 30s`))):console.log(m.dim(` task='${i}' command='${o}' trigger='${c}'${t.cron?` cron='${t.cron}'`:""}`)),b.length>1&&console.log(m.meta(` + built-in: worktree-prune (cron: ${g})`)),console.log(m.dim(" Press Ctrl+C to stop."));let P=async()=>{console.log(m.dim(`
1911
1911
  \xB7 Shutting down daemon...`)),await C.stop(),process.exit(0)};process.on("SIGINT",P),process.on("SIGTERM",P)}catch(C){V(C)}})}U();import{execFile as KPe}from"node:child_process";function ak(e){let{bin:t,args:n}=process.platform==="darwin"?{bin:"open",args:[e]}:process.platform==="win32"?{bin:"cmd",args:["/c","start","",e]}:{bin:"xdg-open",args:[e]};try{KPe(t,n,()=>{}).unref()}catch{}}import{createServer as gMe}from"node:http";import{randomBytes as GPe,timingSafeEqual as qPe}from"node:crypto";var zPe=32;function Jm(){return GPe(zPe).toString("hex")}function Ym(e,t){if(typeof t!="string"||t.length===0)return!1;let n=Buffer.from(e,"utf8"),r=Buffer.from(t,"utf8");return n.length!==r.length?!1:qPe(n,r)}function s9(e){return e&&/^Bearer\s+(.+)$/i.exec(e.trim())?.[1]?.trim()||void 0}function a9(e){return c9(e,"token")}function l9(e){return c9(e,"k")}function c9(e,t){let n=e.indexOf("?");return n===-1?void 0:new URLSearchParams(e.slice(n+1)).get(t)??void 0}var dM="afk_web_doc";function d9(e){if(e)for(let t of e.split(";")){let n=t.indexOf("=");if(n===-1||t.slice(0,n).trim()!==dM)continue;let r=t.slice(n+1).trim();try{return decodeURIComponent(r)||void 0}catch{return r||void 0}}}function u9(e,t,n){return e===void 0||e===""?!0:VPe(t,n).includes(e)}function VPe(e,t){return(p9(e)||JPe(e)?["127.0.0.1","localhost","[::1]"]:[e]).map(r=>`http://${r}:${t}`)}function p9(e){return e==="127.0.0.1"||e==="localhost"||e==="::1"||e==="[::1]"}function JPe(e){return e==="0.0.0.0"||e==="::"||e==="[::]"}function m9(e,t){return p9(e)?{ok:!0}:t?{ok:!0}:{ok:!1,reason:`refusing to bind non-loopback host "${e}" without an explicit token. Pass --token <value> or set AFK_WEB_TOKEN. This surface can run tools and edit files.`}}K();import{readFile as YPe}from"node:fs/promises";import{join as XPe,normalize as QPe}from"node:path";var Mo=Object.freeze({"content-security-policy":"default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:","x-content-type-options":"nosniff","x-frame-options":"DENY","referrer-policy":"no-referrer"}),ZPe="__AFK_WEB_TOKEN__";function eMe(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}async function f9(e,t,n,r,o){let i=n==="/"||n==="/index.html",s=Ym(o.token,a9(r)),a=!s&&i&&o.nonces.redeem(l9(r)),l=s||a;if(!(l||Ym(o.docKey,d9(e.headers.cookie)))){t.writeHead(401,{...Mo,"content-type":"text/plain; charset=utf-8"}),t.end("Missing or invalid token. Use the URL printed by `afk web`.");return}let d=i?{"set-cookie":tMe(o.docKey)}:{},u=i?"index.html":n.replace(/^\/+/,""),p=QPe(u);if(p.startsWith("..")||p.startsWith("/")){t.writeHead(403,{...Mo,"content-type":"text/plain; charset=utf-8"}),t.end("Forbidden");return}let f=XPe(P0(),p);try{let g=await YPe(f),h=i?Buffer.from(g.toString("utf8").split(ZPe).join(l?eMe(o.token):"")):g;t.writeHead(200,{...Mo,"content-type":nMe(p),"content-length":h.byteLength,"cache-control":"no-store",...d}),t.end(h)}catch{if(i){t.writeHead(503,{...Mo,...d,"content-type":"text/plain; charset=utf-8"}),t.end("Web UI bundle not built. Run `pnpm build:web-ui` and retry.");return}t.writeHead(404,{...Mo,"content-type":"text/plain; charset=utf-8"}),t.end("Not found")}}function tMe(e){return`${dM}=${encodeURIComponent(e)}; Path=/; HttpOnly; SameSite=Strict`}function nMe(e){return e.endsWith(".html")?"text/html; charset=utf-8":e.endsWith(".js")?"text/javascript; charset=utf-8":e.endsWith(".css")?"text/css; charset=utf-8":e.endsWith(".svg")?"image/svg+xml":"application/octet-stream"}var rMe=6e4,lk=class{constructor(t=Date.now){this.now=t}now;issued=new Map;mint(){let t=Jm();return this.issued.set(t,this.now()+rMe),t}redeem(t){if(this.sweep(),t===void 0||t==="")return!1;let n=this.issued.get(t);return n===void 0?!1:(this.issued.delete(t),n>this.now())}sweep(){let t=this.now();for(let[n,r]of this.issued)r<=t&&this.issued.delete(n)}};Cr();var ck=class{waiters=new Map;listeners=new Set;counter=0;installed=!1;install(){this.installed||(this.installed=!0,ze.install((t,n)=>this.enqueue(t,n)))}uninstall(){if(this.installed){this.installed=!1,ze.uninstall();for(let t of[...this.waiters.keys()])this.settle(t,{action:"decline"})}}list(){return[...this.waiters.values()].map(t=>t.pending)}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}resolve(t,n){return this.waiters.get(t)?(this.settle(t,oMe(n)),!0):!1}enqueue(t,n){this.counter+=1;let r=`el_${this.counter}`,o=n;return o.onActive?.(),new Promise(i=>{let s={id:r,request:t,createdAt:new Date().toISOString(),...o.sessionId!==void 0?{sessionId:o.sessionId}:{}};this.waiters.set(r,{resolve:i,pending:s}),this.emit();let a=()=>{this.settle(r,{action:"cancel"})};n.signal.aborted?a():n.signal.addEventListener("abort",a,{once:!0})})}settle(t,n){let r=this.waiters.get(t);r&&(this.waiters.delete(t),r.resolve(n),this.emit())}emit(){let t=this.list();for(let n of this.listeners)try{n(t)}catch{}}};function oMe(e){if(typeof e!="object"||e===null)return{action:"decline"};let t=e,n=t.action;if(n==="accept"||n==="decline"||n==="cancel"||n==="skip"){let r=t.content;return typeof r=="object"&&r!==null?{action:n,content:r}:{action:n}}return{action:"decline"}}K();K();Is();hs();import*as dk from"node:fs/promises";var g9=80,iMe=20;function sMe(e){let t=e.trim().replace(/\s+/g," ");return t.length>g9?`${t.slice(0,g9)}\u2026`:t}async function aMe(e){let t={};try{let n=0;for await(let r of ei(e))if(n+=1,r.kind==="meta"?(r.cwd!==void 0&&(t.cwd=r.cwd),r.surface!==void 0&&(t.surface=r.surface)):r.kind==="user"&&t.title===void 0&&(t.title=sMe(r.text)),t.title!==void 0&&(t.cwd!==void 0||t.surface!==void 0)||n>=iMe)break}catch{}return t}async function lMe(){let e=new Map,t;try{t=await dk.readdir(tt(),{withFileTypes:!0})}catch{return e}for(let n of t)if(!(!n.isDirectory()||!Yr(n.name)))try{let r=await dk.stat(Ba(n.name));r.isFile()&&e.set(n.name,r.mtime)}catch{}return e}async function cMe(){try{let e=await cE();return new Set(e.map(t=>t.sessionId))}catch{return null}}function dMe(e,t){return e.updatedAt===void 0&&t.updatedAt===void 0?0:e.updatedAt===void 0?1:t.updatedAt===void 0||e.updatedAt>t.updatedAt?-1:e.updatedAt<t.updatedAt?1:0}var uMe=100;async function h9(e,t=uMe){let[n,r]=await Promise.all([lMe(),cMe()]),o=[...e],i=[...n.keys()].filter(l=>!e.has(l)).sort((l,c)=>{let d=n.get(l)?.getTime()??0;return(n.get(c)?.getTime()??0)-d}).slice(0,Math.max(0,t)),s=new Set([...o,...i]),a=await Promise.all([...s].map(async l=>{let c=e.has(l)?"live":"readonly",d=await aMe(l),u=n.get(l),p={id:l,mode:c};return d.cwd!==void 0&&(p.cwd=d.cwd),d.surface!==void 0&&(p.surface=d.surface),d.title!==void 0&&(p.title=d.title),u!==void 0&&(p.updatedAt=u.toISOString()),c==="readonly"&&r!==null&&(p.alive=r.has(l)),p}));return a.sort(dMe),a}function qe(e,t,n){let r=JSON.stringify(n,Ic);e.writeHead(t,{...Mo,"content-type":"application/json; charset=utf-8","content-length":Buffer.byteLength(r),"cache-control":"no-store"}),e.end(r)}function Xm(e,t){return Yr(t)?!0:(qe(e,400,{error:"bad_session_id",message:"session id must be 1-128 chars of [A-Za-z0-9_-]"}),!1)}function mM(e,t,n){return e.owned.has(n)?!0:(qe(t,409,{error:"session_not_owned",message:`session ${n} is attached read-only (it runs in another process). Prompts and approvals can only be sent to sessions started by this server.`}),!1)}async function y9(e,t){let n=await h9(e.owned);qe(t,200,{sessions:n})}var uM=null,pM=null,pMe=async()=>{let[{registerAll:e},{buildSlashUniverse:t}]=await Promise.all([Promise.resolve().then(()=>(LP(),c3)),Promise.resolve().then(()=>(am(),OV))]);return e(),t()},mMe=pMe;async function b9(e){if(uM===null){pM??=mMe().then(t=>(uM=t,t)).finally(()=>{pM=null});try{await pM}catch(t){let n=t instanceof Error?t.message:String(t);console.error(`[web] failed to initialize slash-command universe: ${n}`),qe(e,503,{error:"command_universe_unavailable",message:"Slash-command autocomplete is temporarily unavailable. Retry the request."});return}}qe(e,200,{commands:uM})}async function S9(e,t,n,r){if(!Xm(t,n)||!mM(e,t,n))return;if(e.isBusy(n)){qe(t,409,{error:"session_busy",message:`session ${n} already has a turn in flight. Wait for it to finish, or interrupt it, before sending another prompt.`});return}let o=uk(r,"text");if(o===void 0){qe(t,400,{error:"bad_request",message:"body must be { text: string }"});return}await e.submitPrompt(n,o),qe(t,202,{ok:!0})}function w9(e,t,n,r){Xm(t,n)&&mM(e,t,n)&&k9(e,t,r)}function v9(e,t,n){k9(e,t,n)}function k9(e,t,n){let r=uk(n,"requestId");if(r===void 0){qe(t,400,{error:"bad_request",message:"body must include requestId"});return}let o=T9(n)?n.response:void 0;if(!e.bridge.resolve(r,o)){qe(t,404,{error:"unknown_request",message:`no pending elicitation with id ${r}`});return}qe(t,200,{ok:!0})}function Qm(e,t){let n=e.headers[t];return Array.isArray(n)?n[0]:n}function T9(e){return typeof e=="object"&&e!==null}function uk(e,t){if(!T9(e))return;let n=e[t];return typeof n=="string"?n:void 0}async function E9(e,t,n){if(!e.createSession){qe(t,501,{error:"sessions_not_supported",message:"this server is attach-only and cannot start sessions. Run `afk web` (which wires a session owner) rather than embedding startWebServer without one."});return}let r={},o=uk(n,"cwd"),i=uk(n,"model");o!==void 0&&(r.cwd=o),i!==void 0&&(r.model=i);try{let s=await e.createSession(r);qe(t,201,{session:s})}catch(s){qe(t,500,{error:"session_start_failed",message:s instanceof Error?s.message:String(s)})}}async function R9(e,t,n){if(Xm(t,n)&&mM(e,t,n)){if(!e.interrupt){qe(t,501,{error:"interrupt_not_supported",message:"no interrupt handler wired"});return}try{await e.interrupt(n),qe(t,200,{ok:!0})}catch(r){qe(t,500,{error:"interrupt_failed",message:r instanceof Error?r.message:String(r)})}}}Is();function Zm(e){let t=[];return e.id!==void 0&&t.push(`id: ${e.id}`),t.push(`data: ${JSON.stringify(e.data,Ic)}`),t.join(`
1912
1912
  `)+`