agent-afk 5.120.0 → 5.121.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  var E_=Object.defineProperty;var ke=(t,e)=>()=>(t&&(e=t(t=0)),e);var wp=(t,e)=>{for(var n in e)E_(t,n,{get:e[n],enumerable:!0})};function br(t){return wr.find(e=>e.name===t)}function ss(t){return process.env[t]!==void 0}var Sp=ke(()=>{"use strict";C()});var wr,h,C=ke(()=>{"use strict";Sp();wr=[{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:"XAI_API_KEY",description:"xAI API key for the xai provider (Grok models) in API-key mode. Metered; distinct from SuperGrok / SuperGrok Heavy / X Premium+ OAuth.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_XAI_BASE_URL",description:"Base URL for xAI API-key mode. Default https://api.x.ai/v1. The OpenAI SDK appends /chat/completions.",type:"string",required:!1,example:"https://api.x.ai/v1",category:"model"},{name:"AFK_XAI_OAUTH_BASE_URL",description:"Base URL for xAI SuperGrok / SuperGrok Heavy / X Premium+ OAuth inference. Default https://cli-chat-proxy.grok.com/v1 (subscription path). Some accounts work on https://api.x.ai/v1 with OAuth \u2014 override if needed. Distinct from AFK_XAI_BASE_URL (API-key mode).",type:"string",required:!1,example:"https://cli-chat-proxy.grok.com/v1",category:"model"},{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 | xai | xai-oauth). 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_WAVE_MANIFEST_DISABLED",description:"Disable the wave manifest system entirely. When set to 1, no manifest is written for parallel subagent waves, and no resumption offer is made at session start.",type:"boolean",required:!1,default:"0",example:"1",category:"misc"},{name:"AFK_WAVE_MANIFEST_TTL_HOURS",description:"Time-to-live for wave manifests in hours. Manifests older than this are deleted on reconciliation and by the witness sweep. Default 48 (two days).",type:"number",required:!1,default:"48",example:"24",category:"misc"},{name:"AFK_WAVE_RESUME_UNATTENDED",description:"When set to 1, surface wave resumption offers even on non-interactive surfaces (daemon, one-shot chat). By default, offers are only made on interactive surfaces (REPL, Telegram).",type:"boolean",required:!1,default:"0",example:"1",category:"misc"},{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_RATE_LIMIT_ADMISSION_DISABLED",description:"Bypass the process-wide rate-limit admission gate (issue #941). Set to 1 to skip pre-request capacity checks. Default 0 (gate active). OAuth subscription accounts already pass through automatically when no per-minute headers are returned.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_RATE_LIMIT_STAGGER_MAX_MS",description:"Jitter ceiling (ms) for the rate-limit admission bucket: each waiter at a window boundary wakes at reset + random(0..ceiling) to avoid re-storming the API. Default 500. Set to 0 in tests for deterministic timing.",type:"number",required:!1,default:"500",example:"0",category:"model"},{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"}],h={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 XAI_API_KEY(){return process.env.XAI_API_KEY},get AFK_XAI_BASE_URL(){return process.env.AFK_XAI_BASE_URL},get AFK_XAI_OAUTH_BASE_URL(){return process.env.AFK_XAI_OAUTH_BASE_URL},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_RATE_LIMIT_ADMISSION_DISABLED(){return process.env.AFK_RATE_LIMIT_ADMISSION_DISABLED},get AFK_RATE_LIMIT_STAGGER_MAX_MS(){return process.env.AFK_RATE_LIMIT_STAGGER_MAX_MS},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},get AFK_WAVE_MANIFEST_DISABLED(){return process.env.AFK_WAVE_MANIFEST_DISABLED},get AFK_WAVE_MANIFEST_TTL_HOURS(){return process.env.AFK_WAVE_MANIFEST_TTL_HOURS},get AFK_WAVE_RESUME_UNATTENDED(){return process.env.AFK_WAVE_RESUME_UNATTENDED}};(function(){for(let e of wr){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(h,e.name);n&&Object.defineProperty(h,e.name,{...n,enumerable:!1})}})()});function R_(){return h.AFK_DEBUG==="1"||h.DEBUG==="1"}function P(...t){R_()&&console.log(...t)}var oe=ke(()=>{"use strict";C()});import{existsSync as vp,mkdirSync as x_,renameSync as I_,cpSync as C_,rmSync as P_}from"fs";import{join as B,dirname as Dc,basename as M_,isAbsolute as Fc}from"path";import{homedir as Ap}from"os";import{fileURLToPath as O_}from"url";function ce(){let t=h.AFK_HOME;if(t!==void 0&&t!==""){if(!Fc(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return B(Ap(),".afk")}function Fe(){let t=h.AFK_FRAMEWORK_DIR;if(t!==void 0&&t!==""){if(!Fc(t)||t==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${t}`);return t}return B(ce(),"agent-framework")}function is(){return B(Fe(),"forge-telemetry.jsonl")}function _p(){return B(Fe(),"briefs")}function Tp(){return B(Fe(),"facets")}function Sr(){return B(ce(),"skills")}function vn(){return B(ce(),"plugins")}function Ep(t=process.cwd()){return B(t,".afk")}function Rp(t=process.cwd()){return B(Ep(t),"skills")}function xp(t=process.cwd()){return B(Ep(t),"plugins")}function Ip(t=process.cwd()){return B(t,".afk","plans")}function as(){return B(vn(),".index.json")}function Lc(){return B(vr(),"schedules.json")}function Cp(){let t=O_(import.meta.url),e=Dc(t);return B(e,"bundled-plugins")}function vr(){return B(ce(),"config")}function pe(){let t=h.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!Fc(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return B(ce(),"state")}function Ie(){return B(pe(),"sessions")}function cs(){return B(pe(),"presence")}function ls(){return B(pe(),"memory")}function ds(){return B(pe(),"session-grants.jsonl")}function Pp(){return B(ce(),"farms")}function Mp(t){return B(Pp(),t)}function us(t){if(!D_.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function kr(){return B(pe(),"witness")}function Rt(t){return us(t),B(kr(),t)}function Op(t){return B(Rt(t),"inbound-attachments")}function Dp(t){return B(Rt(t),"prompts")}function Fp(t){return B(Rt(t),"outputs")}function kn(t){return!t||t.startsWith("in-memory:")?null:M_(Dc(t))}function Lp(t="default"){return B(pe(),"daemon",`agent-afk@${t}`)}function Np(){return B(pe(),"worktree-sweep.lock")}function ps(){return B(pe(),"worktree-roots.json")}function Nc(){return B(vr(),"afk.env")}function An(){return B(vr(),"afk.config.json")}function fs(){return B(Ap(),".afk.config.json")}function F_(){return B(ce(),"sessions")}function L_(t,e){if(t!==e&&vp(t)&&!vp(e))try{x_(Dc(e),{recursive:!0});try{I_(t,e)}catch(n){if(n.code==="EXDEV")try{C_(t,e,{recursive:!0}),P_(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
2
2
  `)}}}catch{}}function Up(){L_(F_(),Ie())}function Uc(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>kp)throw new Error(`Invalid browser profile: exceeds ${kp} chars`);if(!N_.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function U_(){return B(pe(),"browser")}function B_(t){return Uc(t),B(U_(),t)}function Bc(t){return B(B_(t),"storageState.json")}function _n(t){return typeof t=="string"&&t.length>0&&t.length<=H_&&$_.test(t)}function Ar(t){if(!_n(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return B(Ie(),t)}function _r(t){return B(Ar(t),"events.jsonl")}function Bp(t){return B(Ar(t),"session.key")}function ms(){return B(pe(),"waves")}function gs(t){return B(ms(),`${t}.json`)}var D_,N_,kp,$_,H_,D=ke(()=>{"use strict";C();D_=/^[a-zA-Z0-9_-]+$/;N_=/^[A-Za-z0-9_-]+$/,kp=128;$_=/^[A-Za-z0-9_-]+$/,H_=128});import{readFileSync as JC}from"node:fs";import{join as YC}from"path";function QC(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Xg(t,e){return QC(e).test(t)}function tP(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(ZC.has(e))return!0;if(eP.has(e))return!1}return!1}function zg(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function nP(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function Vg(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Uc(e),e}function rP(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function oP(t){try{return JC(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function sP(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=Vg(e.defaultProfile)),n}function Jg(t){let e=t?.env??h,n=t?.readFileSync??oP,r=t?.surface??e.AGENT_SURFACE,o=tP(e.AFK_BROWSER_HEADLESS,r),s=zg(e.AFK_BROWSER_ALLOWED_DOMAINS),i=zg(e.AFK_BROWSER_BLOCKED_DOMAINS),a=rP(e.AFK_BROWSER_DOM_SNAPSHOTS),c=nP(e.AFK_BROWSER_BACKEND),l=Vg(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():YC(vr(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${p}: ${String(y)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=sP(d,m);return g.configPath=p,g}function ui(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(Xg(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Xg(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var ZC,eP,pi=ke(()=>{"use strict";C();D();ZC=new Set(["daemon","subagent","telegram","afk"]),eP=new Set(["repl","interactive","cli"])});import{existsSync as iP,readFileSync as aP}from"node:fs";import{createRequire as cP}from"node:module";import{dirname as lP,join as dP}from"node:path";function Zg(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<pP&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function xe(t){let e=Zg(t);return Qg.some(n=>e.includes(n))}function fP(){try{let e=cP(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(aP(e,"utf8"));if(typeof n!="object"||n===null)return;let r=n.bin,o=typeof r=="string"?r:typeof r=="object"&&r!==null?r.playwright:void 0;if(typeof o!="string"||o.length===0)return;let s=dP(lP(e),o);return iP(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function io(){return Yg??=fP()??uP,Yg}function Xl(t){return t.includes("install chromium")}function He(t,e){let n=Zg(t),r=e?.latched===!0?` ${mP}`:"";if(n.includes("Executable doesn't exist")){let o="";return e?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":e?.headless===!1&&(o=" This launch was headed, which needs the full `chromium-*` build \u2014 the headless shell alone does not satisfy it."),`browser tools require the Playwright chromium binary. Install via: ${io()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${io()}). Or pick a different tool.${r}`}function zl(t,e,n=!1){if(!xe(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
3
3
 
4
- ${He(t,{headless:e,latched:n})}`,{cause:t})}var Qg,uP,pP,Yg,mP,Vl=ke(()=>{"use strict";Qg=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],uP="pnpm exec playwright install chromium",pP=4;mP="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 un from"node:fs";import fi from"node:path";import{randomBytes as gP}from"node:crypto";import{chromium as hP}from"playwright";function yP(){try{return"5.120.0"}catch{}try{let t=fi.resolve(import.meta.dirname,"../../../package.json"),e=un.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var bP,mi,eh=ke(()=>{"use strict";Vl();D();oe();bP=yP(),mi=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=hP.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=zl(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${bP}`}}loadStorageState(e){let n=Bc(e);try{if(!un.existsSync(n))return;let r=JSON.parse(un.readFileSync(n,"utf8"));return P("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){P("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Bc(e);if(!un.existsSync(r))return;let o=await n.storageState(),s=fi.join(fi.dirname(r),`.${fi.basename(r)}.${process.pid}.${gP(4).toString("hex")}.tmp`);un.writeFileSync(s,JSON.stringify(o),{mode:384}),un.chmodSync(s,384),un.renameSync(s,r),P("[browser/vault] saved session",{profile:e,file:r})}catch(r){P("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as wP}from"crypto";function th(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&SP.test(t.label))}function nh(t){return wP("sha256").update(t,"utf8").digest("hex").slice(0,8)}function rh(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var SP,gi=ke(()=>{"use strict";SP=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as vP}from"node:crypto";function kP(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function AP(t,e,n){return`el_${vP("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function _P(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function oh(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function ih(t,e){let n=t.role??"",r=t.name??"";sh.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])ih(s,e)}async function TP(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},ah).catch(()=>[])}async function EP(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},ah).catch(()=>[])}function RP(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function hi(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=RP(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=TP(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],ih(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await EP(t)).filter(W=>sh.has(W.role??"")));let v=new Map;for(let T of p){let W=oh(T.name),Q=v.get(W);(!Q||Q.bbox.w===0&&T.bbox.w>0)&&v.set(W,T)}let _=y.map(T=>({ax:T,dom:v.get(oh(T.name??""))})),w=r?_:_.filter(T=>T.dom?T.dom.bbox.w>0||T.dom.bbox.h>0:!0);w.sort((T,W)=>{let Q=T.dom?.bbox.y??0,O=W.dom?.bbox.y??0;if(Q!==O)return Q-O;let L=T.dom?.bbox.x??0,F=W.dom?.bbox.x??0;return L-F}),w.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=w.slice(0,n).map((T,W)=>{let Q=T.ax.role??"generic",O=T.ax.name??"",L=AP(Q,O,W),F=T.dom?.bbox??{x:0,y:0,w:0,h:0},M=T.dom?.type??null,G=null;T.ax.value!==void 0&&T.ax.value!==null&&(G=String(T.ax.value)),T.ax.checked!==void 0&&(G=String(T.ax.checked)),th({role:Q,kind:M})&&(G="[redacted]");let U={disabled:T.ax.disabled??!1};T.ax.checked!==void 0&&(U.checked=T.ax.checked===!0||T.ax.checked==="mixed"),T.ax.selected!==void 0&&(U.selected=T.ax.selected),T.ax.expanded!==void 0&&(U.expanded=T.ax.expanded);let z;T.dom?.testId?z=`[data-testid="${T.dom.testId}"]`:T.dom?.id&&(z=`#${T.dom.id}`);let Z={id:L,role:Q,label:kP(O),kind:M,value:G,state:U,bbox:F};return z!==void 0&&(Z.selector=z),Z}),R="idle";try{let T=await t.evaluate(()=>document.readyState);T==="loading"?R="loading":T==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=_P(f),S=`obs_${e.observationCounter.toString(36)}`,x=new Date().toISOString();return{observationId:S,url:m,title:g,textSummary:I,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:x}}var sh,ah,ch=ke(()=>{"use strict";gi();sh=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);ah="a[href], button, input, select, textarea, [role], [tabindex], label"});async function lh(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Jl(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>lh(t,s)))).filter(o=>o!==null)}async function xP(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Yl(t,e,n){switch(e.kind){case"element_id":return IP(t,e,n);case"selector":return CP(t,e);case"semantic":return PP(t,e)}}async function IP(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Jl(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function CP(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Jl(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function PP(t,e){return e.role!==void 0?MP(t,e.text,e.role):OP(t,e.text,e)}async function MP(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Jl(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function OP(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await xP(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let y=p[g];if(y===void 0)continue;let b=await lh(y.locator,y.index);if(b!==null){let v=`${b.role}:${b.label}:${g}`,_=0;for(let w=0;w<v.length;w++)_=_*31+v.charCodeAt(w)>>>0;f.push({...b,id:`el_${_.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var dh=ke(()=>{"use strict"});async function Ql(t,e,n,r){let o=t.url();if(o===n)return null;let s=ui(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var uh=ke(()=>{"use strict";pi()});import{randomBytes as DP}from"crypto";import{mkdir as FP,stat as LP,writeFile as NP}from"fs/promises";import{join as Zl}from"path";import{gzip as UP}from"zlib";import{promisify as BP}from"util";function $P(t){return Zl(Rt(t),"browser")}function HP(t){return Zl($P(t),"screenshots")}function jP(){return new Date().toISOString().replace(/[:.]/g,"-")}function WP(){return DP(3).toString("hex")}async function ed(t,e,n){if(e.length>ph)throw new Error(`writeScreenshotSidecar: buffer exceeds ${ph} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=HP(t);await FP(r,{recursive:!0});let o=`${jP()}-${WP()}-${n}.png`,s=Zl(r,o);await NP(s,e);let{size:i}=await LP(s);return{path:s,bytes:i}}var MX,ph,fh=ke(()=>{"use strict";D();gi();MX=BP(UP);ph=5*1024*1024});var gh={};wp(gh,{PlaywrightProvider:()=>td});function mh(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var td,hh=ke(()=>{"use strict";eh();ch();dh();pi();uh();fh();td=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new mi(e)}async open(e){let n=ui(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await Ql(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await hi(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await hi(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await Yl(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${mh(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(y){l=y}else l=g}let u=await Ql(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await hi(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Yl(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${mh(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await ed(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await ed(n,o,r);return s}catch{return null}}}});var fn={};wp(fn,{__resetBrowserRegistryForTests:()=>zP,browserProviderActive:()=>qP,closeBrowserProvider:()=>nd,getBrowserProvider:()=>GP,peekBrowserProvider:()=>XP});function yh(){Promise.resolve(nd()).then(()=>{process.exit(130)})}function bh(){Promise.resolve(nd()).then(()=>{process.exit(143)})}function wh(){rt=null}function KP(){yi||(process.on("SIGINT",yh),process.on("SIGTERM",bh),process.on("exit",wh),yi=!0)}function Sh(){yi&&(process.removeListener("SIGINT",yh),process.removeListener("SIGTERM",bh),process.removeListener("exit",wh),yi=!1)}async function GP(t){return rt!==null?rt:(pn!==null||(pn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(hh(),gh)),n=Jg(t),r=new e(n);return KP(),rt=r,pn=null,r})()),pn)}async function nd(){if(rt===null)return;let t=rt;rt=null,pn=null,Sh(),await t.shutdown()}function qP(){return rt!==null}function XP(){return rt}function zP(){rt=null,pn=null,Sh()}var rt,pn,yi,mn=ke(()=>{"use strict";pi();rt=null,pn=null,yi=!1});oe();C();D();import{randomBytes as nT}from"node:crypto";import{mkdir as rT,writeFile as oT}from"node:fs/promises";import{join as sT}from"node:path";oe();var j_=256,$p=new WeakMap,Tr=new Map;function W_(t){return t instanceof Error?t.message:String(t)}function K_(t,e){if(typeof e=="object"&&e!==null){let r=$p.get(e);return r||(r=new Set,$p.set(e,r)),r.has(t)?!1:(r.add(t),!0)}let n=`${t}\0${String(e)}`;if(Tr.has(n))return!1;if(Tr.set(n,!0),Tr.size>j_){let r=Tr.keys().next().value;r!==void 0&&Tr.delete(r)}return!0}function he(t,e,n,r){try{let o=`[afk] ${t} artifact write failed (${n}): ${W_(r)}`;if(!K_(t,e)){P(o);return}console.error(`${o} \u2014 further failures in this subsystem for this session are logged only under AFK_DEBUG=1.`)}catch{}}C();import{mkdirSync as q_,appendFileSync as X_,existsSync as z_}from"fs";import{resolve as V_}from"path";import{dirname as J_}from"path";function $c(t){return t.replace(/\bauthorization:\s*bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]").replace(/\bsk-ant-[A-Za-z0-9_-]{20,}/g,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,"[REDACTED]").replace(/\b(?:AKIA|ASIA|AROA|AIDA|AGPA|AIPA|ANPA|ANVA|APKA|ABIA|ACCA)[A-Z0-9]{16}\b/g,"[REDACTED]").replace(/(?<![/.\w])[A-Za-z0-9+/=_-]{32,}(?![/.\w])/g,e=>Hc(e)||G_(e)?e:"[REDACTED]")}function Hc(t){if(!t.includes("/")||/[+=]/.test(t))return!1;let e=n=>n.length>=32&&!n.includes(".")&&/[A-Za-z]/.test(n)&&/[0-9]/.test(n);return!t.split("/").some(e)}function G_(t){if(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(t))return!0;let e=/^([A-Za-z_][A-Za-z0-9_]*)=(?:[0-9a-f]{40}|[0-9a-f]{64})$/.exec(t);return e!==null&&/^(?:ref|sha|commit|base)$/i.test(e[1]??"")}var Y_=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
4
+ ${He(t,{headless:e,latched:n})}`,{cause:t})}var Qg,uP,pP,Yg,mP,Vl=ke(()=>{"use strict";Qg=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],uP="pnpm exec playwright install chromium",pP=4;mP="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 un from"node:fs";import fi from"node:path";import{randomBytes as gP}from"node:crypto";import{chromium as hP}from"playwright";function yP(){try{return"5.121.0"}catch{}try{let t=fi.resolve(import.meta.dirname,"../../../package.json"),e=un.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var bP,mi,eh=ke(()=>{"use strict";Vl();D();oe();bP=yP(),mi=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=hP.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=zl(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${bP}`}}loadStorageState(e){let n=Bc(e);try{if(!un.existsSync(n))return;let r=JSON.parse(un.readFileSync(n,"utf8"));return P("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){P("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Bc(e);if(!un.existsSync(r))return;let o=await n.storageState(),s=fi.join(fi.dirname(r),`.${fi.basename(r)}.${process.pid}.${gP(4).toString("hex")}.tmp`);un.writeFileSync(s,JSON.stringify(o),{mode:384}),un.chmodSync(s,384),un.renameSync(s,r),P("[browser/vault] saved session",{profile:e,file:r})}catch(r){P("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as wP}from"crypto";function th(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&SP.test(t.label))}function nh(t){return wP("sha256").update(t,"utf8").digest("hex").slice(0,8)}function rh(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var SP,gi=ke(()=>{"use strict";SP=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as vP}from"node:crypto";function kP(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function AP(t,e,n){return`el_${vP("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function _P(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function oh(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function ih(t,e){let n=t.role??"",r=t.name??"";sh.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])ih(s,e)}async function TP(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},ah).catch(()=>[])}async function EP(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},ah).catch(()=>[])}function RP(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function hi(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=RP(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=TP(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],ih(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await EP(t)).filter(W=>sh.has(W.role??"")));let v=new Map;for(let T of p){let W=oh(T.name),Q=v.get(W);(!Q||Q.bbox.w===0&&T.bbox.w>0)&&v.set(W,T)}let _=y.map(T=>({ax:T,dom:v.get(oh(T.name??""))})),w=r?_:_.filter(T=>T.dom?T.dom.bbox.w>0||T.dom.bbox.h>0:!0);w.sort((T,W)=>{let Q=T.dom?.bbox.y??0,O=W.dom?.bbox.y??0;if(Q!==O)return Q-O;let L=T.dom?.bbox.x??0,F=W.dom?.bbox.x??0;return L-F}),w.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=w.slice(0,n).map((T,W)=>{let Q=T.ax.role??"generic",O=T.ax.name??"",L=AP(Q,O,W),F=T.dom?.bbox??{x:0,y:0,w:0,h:0},M=T.dom?.type??null,G=null;T.ax.value!==void 0&&T.ax.value!==null&&(G=String(T.ax.value)),T.ax.checked!==void 0&&(G=String(T.ax.checked)),th({role:Q,kind:M})&&(G="[redacted]");let U={disabled:T.ax.disabled??!1};T.ax.checked!==void 0&&(U.checked=T.ax.checked===!0||T.ax.checked==="mixed"),T.ax.selected!==void 0&&(U.selected=T.ax.selected),T.ax.expanded!==void 0&&(U.expanded=T.ax.expanded);let z;T.dom?.testId?z=`[data-testid="${T.dom.testId}"]`:T.dom?.id&&(z=`#${T.dom.id}`);let Z={id:L,role:Q,label:kP(O),kind:M,value:G,state:U,bbox:F};return z!==void 0&&(Z.selector=z),Z}),R="idle";try{let T=await t.evaluate(()=>document.readyState);T==="loading"?R="loading":T==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=_P(f),S=`obs_${e.observationCounter.toString(36)}`,x=new Date().toISOString();return{observationId:S,url:m,title:g,textSummary:I,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:x}}var sh,ah,ch=ke(()=>{"use strict";gi();sh=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);ah="a[href], button, input, select, textarea, [role], [tabindex], label"});async function lh(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Jl(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>lh(t,s)))).filter(o=>o!==null)}async function xP(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Yl(t,e,n){switch(e.kind){case"element_id":return IP(t,e,n);case"selector":return CP(t,e);case"semantic":return PP(t,e)}}async function IP(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Jl(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function CP(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Jl(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function PP(t,e){return e.role!==void 0?MP(t,e.text,e.role):OP(t,e.text,e)}async function MP(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Jl(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function OP(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await xP(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let y=p[g];if(y===void 0)continue;let b=await lh(y.locator,y.index);if(b!==null){let v=`${b.role}:${b.label}:${g}`,_=0;for(let w=0;w<v.length;w++)_=_*31+v.charCodeAt(w)>>>0;f.push({...b,id:`el_${_.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var dh=ke(()=>{"use strict"});async function Ql(t,e,n,r){let o=t.url();if(o===n)return null;let s=ui(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var uh=ke(()=>{"use strict";pi()});import{randomBytes as DP}from"crypto";import{mkdir as FP,stat as LP,writeFile as NP}from"fs/promises";import{join as Zl}from"path";import{gzip as UP}from"zlib";import{promisify as BP}from"util";function $P(t){return Zl(Rt(t),"browser")}function HP(t){return Zl($P(t),"screenshots")}function jP(){return new Date().toISOString().replace(/[:.]/g,"-")}function WP(){return DP(3).toString("hex")}async function ed(t,e,n){if(e.length>ph)throw new Error(`writeScreenshotSidecar: buffer exceeds ${ph} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=HP(t);await FP(r,{recursive:!0});let o=`${jP()}-${WP()}-${n}.png`,s=Zl(r,o);await NP(s,e);let{size:i}=await LP(s);return{path:s,bytes:i}}var MX,ph,fh=ke(()=>{"use strict";D();gi();MX=BP(UP);ph=5*1024*1024});var gh={};wp(gh,{PlaywrightProvider:()=>td});function mh(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var td,hh=ke(()=>{"use strict";eh();ch();dh();pi();uh();fh();td=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new mi(e)}async open(e){let n=ui(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await Ql(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await hi(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await hi(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await Yl(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${mh(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(y){l=y}else l=g}let u=await Ql(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await hi(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Yl(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${mh(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await ed(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await ed(n,o,r);return s}catch{return null}}}});var fn={};wp(fn,{__resetBrowserRegistryForTests:()=>zP,browserProviderActive:()=>qP,closeBrowserProvider:()=>nd,getBrowserProvider:()=>GP,peekBrowserProvider:()=>XP});function yh(){Promise.resolve(nd()).then(()=>{process.exit(130)})}function bh(){Promise.resolve(nd()).then(()=>{process.exit(143)})}function wh(){rt=null}function KP(){yi||(process.on("SIGINT",yh),process.on("SIGTERM",bh),process.on("exit",wh),yi=!0)}function Sh(){yi&&(process.removeListener("SIGINT",yh),process.removeListener("SIGTERM",bh),process.removeListener("exit",wh),yi=!1)}async function GP(t){return rt!==null?rt:(pn!==null||(pn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(hh(),gh)),n=Jg(t),r=new e(n);return KP(),rt=r,pn=null,r})()),pn)}async function nd(){if(rt===null)return;let t=rt;rt=null,pn=null,Sh(),await t.shutdown()}function qP(){return rt!==null}function XP(){return rt}function zP(){rt=null,pn=null,Sh()}var rt,pn,yi,mn=ke(()=>{"use strict";pi();rt=null,pn=null,yi=!1});oe();C();D();import{randomBytes as nT}from"node:crypto";import{mkdir as rT,writeFile as oT}from"node:fs/promises";import{join as sT}from"node:path";oe();var j_=256,$p=new WeakMap,Tr=new Map;function W_(t){return t instanceof Error?t.message:String(t)}function K_(t,e){if(typeof e=="object"&&e!==null){let r=$p.get(e);return r||(r=new Set,$p.set(e,r)),r.has(t)?!1:(r.add(t),!0)}let n=`${t}\0${String(e)}`;if(Tr.has(n))return!1;if(Tr.set(n,!0),Tr.size>j_){let r=Tr.keys().next().value;r!==void 0&&Tr.delete(r)}return!0}function he(t,e,n,r){try{let o=`[afk] ${t} artifact write failed (${n}): ${W_(r)}`;if(!K_(t,e)){P(o);return}console.error(`${o} \u2014 further failures in this subsystem for this session are logged only under AFK_DEBUG=1.`)}catch{}}C();import{mkdirSync as q_,appendFileSync as X_,existsSync as z_}from"fs";import{resolve as V_}from"path";import{dirname as J_}from"path";function $c(t){return t.replace(/\bauthorization:\s*bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]").replace(/\bsk-ant-[A-Za-z0-9_-]{20,}/g,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,"[REDACTED]").replace(/\b(?:AKIA|ASIA|AROA|AIDA|AGPA|AIPA|ANPA|ANVA|APKA|ABIA|ACCA)[A-Z0-9]{16}\b/g,"[REDACTED]").replace(/(?<![/.\w])[A-Za-z0-9+/=_-]{32,}(?![/.\w])/g,e=>Hc(e)||G_(e)?e:"[REDACTED]")}function Hc(t){if(!t.includes("/")||/[+=]/.test(t))return!1;let e=n=>n.length>=32&&!n.includes(".")&&/[A-Za-z]/.test(n)&&/[0-9]/.test(n);return!t.split("/").some(e)}function G_(t){if(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(t))return!0;let e=/^([A-Za-z_][A-Za-z0-9_]*)=(?:[0-9a-f]{40}|[0-9a-f]{64})$/.exec(t);return e!==null&&/^(?:ref|sha|commit|base)$/i.test(e[1]??"")}var Y_=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
5
5
  `,Q_=/key|token|secret|password|credential|auth/i;function Hp(t){let e=t[1],n=t[2],r=n[0],o=(r==='"'||r==="'")&&n.at(-1)===r?n.slice(1,-1):n,s=/(?:^|_)(?:PATH|FILE)(?:_|$)/i.test(e),i=o.startsWith("/")||o.startsWith("~/"),c=o.split("/").filter(Boolean).some(l=>/[A-Z0-9.\-]/.test(l));return s&&i&&c&&Hc(o)?`${e}=${n}`:`${e}=<REDACTED length=${n.length}>`}var Z_=[[/sk-ant-[A-Za-z0-9_\-]{8,200}/g,t=>`<REDACTED sk-ant length=${t[0].length}>`],[/sk-(?!ant-)[A-Za-z0-9_\-]{20,200}/g,t=>`<REDACTED sk- length=${t[0].length}>`],[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,t=>`<REDACTED Bearer length=${t[0].length}>`],[/AKIA[A-Z0-9]{16}/g,t=>`<REDACTED AKIA length=${t[0].length}>`],[/xox[baprs]-[A-Za-z0-9\-]{10,200}/g,t=>`<REDACTED xox token length=${t[0].length}>`],[/\d{8,12}:[A-Za-z0-9_\-]{35}/g,t=>`<REDACTED Telegram token length=${t[0].length}>`],[/([A-Za-z_]{3,}(?:[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]|[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll])[A-Za-z_]*)=([^\s]{16,})/g,Hp],[/([A-Z_]{3,}(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=([^\s]{16,})/g,Hp]];function Er(t){let e=t;for(let[n,r]of Z_)e=e.replace(n,(...o)=>{let s=o.slice(0,o.length-2);return r(s)});return e}function jc(t){return typeof t=="string"?Er(t):Array.isArray(t)?t.map(jc):t}function eT(t){if(t===null||typeof t!="object")return t;let e=t,n={...e},r=e.env;if(r&&typeof r=="object"){let o={};for(let[s,i]of Object.entries(r))Q_.test(s)&&typeof i=="string"?o[s]=`<REDACTED length=${i.length}>`:o[s]=i;n.env=o}return"system"in e&&(n.system=jc(e.system)),"systemPrompt"in e&&(n.systemPrompt=jc(e.systemPrompt)),n}function tT(t){if(t==null)return{kind:"undefined",note:"SDK uses minimal prompt; claude_code preset NOT loaded"};if(typeof t=="string")return{kind:"custom-string",note:"SDK uses this string as full system prompt; claude_code preset NOT loaded"};if(Array.isArray(t))return{kind:"custom-string-array",note:"SDK uses array as full system prompt with cache boundaries; claude_code preset NOT loaded"};if(typeof t=="object"){let e=t;if(e.type==="preset"&&e.preset==="claude_code"){let n={kind:"preset-claude-code",note:"claude_code preset loaded"};return typeof e.append=="string"&&(n.append={length:e.append.length}),e.excludeDynamicSections===!0&&(n.excludeDynamicSections=!0),n}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}function jp(t){let e=h.AFK_DUMP_PROMPT;if(!e||e===""||e==="0"||e.toLowerCase()==="false")return;process.stderr.write(`[--dump-prompt] WARNING: dump may contain secrets from system prompt or messages. Inspect before sharing.
6
6
  `);let n=t.options,r=typeof n=="object"&&n!==null?n.systemPrompt:void 0,o=tT(r),s={timestamp:new Date().toISOString(),prompt:t.prompt,options:eT(t.options),provenance:t.provenance,resolution:o};if(e==="1"||e.toLowerCase()==="true"||e.toLowerCase()==="stderr"){let c=JSON.stringify(s,null,2)+`
7
7
  `;process.stderr.write(c);return}let i=V_(e),a=J_(i);try{q_(a,{recursive:!0});let l=(!z_(i)?Y_:"")+JSON.stringify(s)+`
@@ -25,9 +25,9 @@ ${r}
25
25
  ### end \xB7 ${e.reason??"unknown"} \xB7 ${n}
26
26
  `}function zp(t){if(!mT(t))return null;let e=Fp(t.sessionId),n=pT(e,`${gT(t.subagentId)}.md`),r=[],o=0,s=!1,i=!1,a=!1,c=Promise.resolve(),l=u=>{if(s)return;o>=qp&&(s=!0,u=`
27
27
  <!-- CAP REACHED at ${qp} bytes \u2014 capture stopped -->
28
- `),o+=Buffer.byteLength(u,"utf8");let p=i?u:`${hT(t)}${u}`;i=!0,c=c.then(async()=>{await uT(e,{recursive:!0,mode:448}),await dT(n,p,{encoding:"utf8",mode:384})}).catch(f=>{he("subagent-output-capture",t.sessionId??"unknown","write",f)})},d=()=>{if(r.length===0)return;let u=r.join("").trim();r=[],u.length>0&&(l(bs("say",{text:u})),a=!0)};return{observe(u){try{if(u.type==="chunk"){let p=u.chunk;if(p.type==="content"){r.push(p.content);return}if(p.type==="tool_use_detail"){if(p.pending)return;d(),l(bs("tool",{toolName:p.toolName,toolInput:p.toolInputRaw??p.toolInput}))}return}if(u.type==="message"){if(!a&&r.length===0){let p=u.message.content.trim();p.length>0&&(l(bs("say",{text:p})),a=!0)}return}(u.type==="done"||u.type==="error")&&(d(),a=!1)}catch(p){he("subagent-output-capture",t.sessionId??"unknown","observe",p)}},end(u){try{d(),l(bs("end",{reason:u}))}catch(p){he("subagent-output-capture",t.sessionId??"unknown","end",p)}}}}var Le=class extends Error{constructor(e){super(e),this.name="AbortError"}},Ae=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},ws=class extends Ae{constructor(e,n){super(e,n),this.name="IdleWatchdogError"}},q=class extends Error{constructor(n,r,o,s){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",s?.cause!==void 0&&(this.cause=s.cause)}event;reason;cause},Qe=class extends Error{constructor(e){super(e),this.name="StreamIncompleteError"}},Ze=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},Tn=class extends Error{constructor(e){super(e),this.name="DenialCircuitBreakerError"}};async function Zt(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){he("trace.emit",t,"tool_call",n)}}async function xt(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){he("trace.emit",t,"hook_decision",n)}}async function en(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){he("trace.emit",t,"subagent_lifecycle",n)}}async function Vp(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){he("trace.emit",t,"budget",n)}}async function Jp(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){he("trace.emit",t,"abort",n)}}async function Ss(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){he("trace.emit",t,"compaction",n)}}async function Yp(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){he("trace.emit",t,"closure",n)}}async function fe(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){he("trace.emit",t,"browser_event",n)}}async function $(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){he("trace.emit",t,"session_phase",n)}}import TT from"@anthropic-ai/sdk";var yT="fast-mode-2026-02-01";function Qp(t){let e=[...t.oauthEntries??[],...t.effort?[t.effortEntry]:[],...t.extendedCacheTtl?[t.extendedCacheEntry]:[],...t.fast?[yT]:[]].filter(Boolean);return[...new Set(e)].join(",")||void 0}var Zp="extended-cache-ttl-2025-04-11",bT=`claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,${Zp}`,wT="effort-2025-11-24",ST="claude-cli/1.0.0 (external, cli)",vT="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function vs(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Rr(t,e,n,r){let o=e==="oauth"?{authToken:t}:{apiKey:t},s=typeof n=="string"&&n.length>0?{...o,baseURL:n}:o;return r?{...s,fetch:r}:s}function It(t,e,n,r,o,s){let i=Qp({oauthEntries:t==="oauth"?bT.split(","):[],effort:t==="oauth"&&r===!0,extendedCacheTtl:o,fast:s,effortEntry:wT,extendedCacheEntry:Zp});return t!=="oauth"?i?{"anthropic-beta":i}:{}:{"anthropic-beta":i,"x-app":"cli","User-Agent":ST,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function ef(t){return t!=="oauth"?null:[{type:"text",text:vT}]}C();var Ir=["local","small","medium","large"],nf="claude-haiku-4-5-20251001",xr="claude-sonnet-4-6",Gc="claude-opus-5",Xc="claude-fable-5",tn={local:{id:""},small:{id:nf},medium:{id:xr},large:{id:Gc}},rf="auto",zc={opus:Gc,opus_1m:Gc,sonnet:xr,sonnet_1m:xr,haiku:nf,fable:Xc},nn=[...Ir,...Object.keys(zc)],qc;function Vc(t){qc=t}function Kc(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function ks(t,e,n){let r={},o=Kc(t);o&&(r.id=o);let s=Kc(e);s&&(r.baseUrl=s);let i=Kc(n);return i&&(r.apiKey=i),r}function kT(){return{local:ks(h.AFK_MODEL_LOCAL,h.AFK_MODEL_LOCAL_BASE_URL,h.AFK_MODEL_LOCAL_API_KEY),small:ks(h.AFK_MODEL_SMALL,h.AFK_MODEL_SMALL_BASE_URL,h.AFK_MODEL_SMALL_API_KEY),medium:ks(h.AFK_MODEL_MEDIUM,h.AFK_MODEL_MEDIUM_BASE_URL,h.AFK_MODEL_MEDIUM_API_KEY),large:ks(h.AFK_MODEL_LARGE,h.AFK_MODEL_LARGE_BASE_URL,h.AFK_MODEL_LARGE_API_KEY)}}function of(t){let e=kT(),n={};for(let r of Ir){let o=tn[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},c=s?.name;c&&(a.name=c);let l=s?.provider;l&&(a.provider=l);let d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function Rn(t){return t||qc||of()}function xn(t,e=Rn()){let n=t.trim().toLowerCase();if(!(!n||n===rf)){for(let r of Ir){let o=e[r].name;if(o&&o.trim().toLowerCase()===n)return r}if(n==="local"||n==="small"||n==="medium"||n==="large")return n}}function rn(t,e=Rn()){if(t===void 0)return{id:""};let n=xn(t,e);if(n)return e[n];let r=zc[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function et(t,e=Rn()){if(t!==void 0)return rn(t,e).id}function sf(t,e=Rn()){if(t===void 0)return;let n=xn(t,e);if(n&&e[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function af(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of Ir){let o=_T(n[r]);o&&(e[r]=o)}return e}function cf(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="anthropic"||e==="anthropic-direct")return"anthropic";if(e==="openai"||e==="openai-compatible")return"openai";if(e==="chatgpt-oauth"||e==="chatgpt")return"chatgpt-oauth";if(e==="xai")return"xai";if(e==="xai-oauth"||e==="xai_oauth")return"xai-oauth"}function En(t){return typeof t=="string"?t.trim():""}function tf(t){return/[\x00-\x1f\x7f]/.test(t)}var AT=new Set([...Ir,rf,...Object.keys(zc)]);function _T(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=En(e.id);if(!n)return;let r={id:n},o=En(e.name);o&&(r.name=o);let s=cf(e.provider);s&&(r.provider=s);let i=En(e.baseUrl);i&&(r.baseUrl=i);let a=En(e.apiKey);return a&&(r.apiKey=a),r}}function lf(t){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:'model binding must be an object with at least an "id"'};let e=t;if("apiKey"in e||"api_key"in e)return{ok:!1,error:"per-slot API keys are credentials; set AFK_MODEL_<TIER>_API_KEY via `afk config env set` instead of afk.config.json"};if("baseUrl"in e||"base_url"in e)return{ok:!1,error:"per-slot baseUrl is an endpoint-redirect credential vector; set AFK_MODEL_<TIER>_BASE_URL via `afk config env set` instead of afk.config.json"};let n=En(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(tf(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=En(e.name);if(o){if(tf(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(AT.has(o.trim().toLowerCase()))return{ok:!1,error:`model binding "name" must not shadow a built-in alias ("${o}")`};r.name=o}if(e.provider!==void 0&&e.provider!==""){let s=cf(e.provider);if(!s)return{ok:!1,error:'model binding "provider" must be one of: anthropic, openai (aliases: anthropic-direct, openai-compatible)'};r.provider=s}return{ok:!0,value:r}}var Jc={opus:tn.large.id,opus_1m:tn.large.id,sonnet:tn.medium.id,sonnet_1m:tn.medium.id,haiku:tn.small.id,fable:Xc};function As(t){return t in Jc}function we(t){return et(t)}import{randomUUID as df}from"node:crypto";async function uf(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let c=vs(e),l=Rr(e,c),d=a?a(l):new TT(l),u=df(),p=df(),f=It(c,u,p),m=we(n)??n,g={};Object.keys(f).length>0&&(g.headers=f),i&&(g.signal=i);let y=await d.messages.create({model:m,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(g).length>0?g:void 0),b=[];for(let _ of y.content)_.type==="text"&&b.push(_.text);let v=b.join("").trim();return v.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),v}C();var ET=new Set(["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4-turbo","o1","o3","o4-mini"]),RT=[/^claude-/i,/^gpt-4o/i,/^gpt-4\.1/i,/^gpt-4-turbo/i,/^gpt-4-vision/i,/^gpt-5/i,/(?:^|[/_-])(?:vl|vlm)(?:[/_.-]|$)/i,/(?:^|[/_-])(?:llava|pixtral|internvl|cogvlm|idefics|moondream|janus)/i,/(?:vision|minicpm-?[vo]|qwen[\d.]*-?vl|llama-?3\.2-\d+b-vision|gemma-3|phi-3\.5-vision|phi-4-multimodal)/i];function xT(){let t=h.AFK_VISION_MODELS,e=[],n=[];if(t)for(let r of t.split(",")){let o=r.trim().toLowerCase();if(o)if(o.startsWith("!")){let s=o.slice(1).trim();s&&n.push(s)}else e.push(o)}return{enable:e,disable:n}}function pf(t,e){return t===e||t.includes(e)}function Yc(t){if(!t)return!1;let e=(et(t)??t).trim();if(!e)return!1;let n=e.toLowerCase(),{enable:r,disable:o}=xT();return o.some(s=>pf(n,s))?!1:r.some(s=>pf(n,s))||ET.has(n)?!0:RT.some(s=>s.test(e))}function ff(t){let e=t.trim().toLowerCase();return e.includes("/")?e.slice(e.lastIndexOf("/")+1):e}function on(t){return t?/^o[0-9]/.test(ff(t)):!1}var IT=[/^gpt-5/];function Cr(t){if(!t)return!1;if(on(t))return!0;let e=ff(t);return IT.some(n=>n.test(e))}var Qc={opus:128e3,opus_1m:128e3,sonnet:128e3,sonnet_1m:128e3,haiku:64e3,fable:128e3,"claude-opus-5":128e3,"claude-opus-4-8":128e3,"claude-opus-4-7":128e3,"claude-opus-4-6":128e3,"claude-sonnet-5":128e3,"claude-sonnet-4-6":128e3,"claude-haiku-4-5-20251001":64e3,"claude-fable-5":128e3,"gpt-5.5":128e3,"gpt-5.6":128e3,"gpt-5.6-sol":128e3,"gpt-5.6-terra":128e3,"gpt-5.6-luna":128e3},CT=64e3;function el(t){let e=String(t).trim().toLowerCase(),n=Qc[e];if(e.endsWith("_1m")&&n!==void 0)return n;let r=et(t)??String(t);return Qc[r]??Qc[r.toLowerCase()]}function In(t){return el(t)??CT}var Zc={opus:1e6,opus_1m:1e6,sonnet:1e6,sonnet_1m:1e6,haiku:2e5,fable:1e6,"claude-fable-5":1e6,"claude-sonnet-5":1e6,"claude-opus-5":1e6,"claude-opus-4-8":1e6,"claude-opus-4-7":1e6,"claude-opus-4-6":1e6,"claude-sonnet-4-6":1e6,"gpt-4o":128e3,"gpt-4o-mini":128e3,"gpt-4.1":1e6,"gpt-4.1-mini":1e6,"gpt-5.5":1e6,"gpt-5.6":1e6,"gpt-5.6-sol":1e6,"gpt-5.6-terra":1e6,"gpt-5.6-luna":1e6,o1:2e5,"o1-mini":128e3,o3:2e5,"o3-mini":2e5,"o4-mini":2e5,"mlx-community/qwen3-30b-a3b-4bit":128e3,"mlx-community/qwen3-32b-4bit":128e3,"mlx-community/qwen2.5-coder-32b-instruct-4bit":131072,"grok-4.6":5e5,"grok-4.5":5e5,"grok-4.3":1e6,"grok-4.20-0309-reasoning":1e6,"grok-4.20-0309-non-reasoning":1e6,"grok-4.20-multi-agent-0309":1e6,"grok-build-0.1":256e3},PT=2e5,MT=262144;function OT(t){if(!t)return!1;let e=t.trim().toLowerCase();return e?!!(e.includes("/")||e.startsWith("gpt-")||e.startsWith("gpt_")||on(e)||e.startsWith("codex-")||e.startsWith("codex_")||e==="codex"||e==="grok"||e.startsWith("grok-")||e.startsWith("grok_")):!1}function ze(t){let e=String(t).trim().toLowerCase(),n=Zc[e];if(e.endsWith("_1m")&&n!==void 0)return n;let r=et(t)??String(t),o=Zc[r]??Zc[r.toLowerCase()];return o!==void 0?o:OT(r)?MT:PT}var mf={"claude-sonnet-5":2e5,"claude-opus-5":2e5,"claude-sonnet-4-6":2e5,"claude-opus-4-8":2e5,"claude-opus-4-7":2e5,"claude-opus-4-6":2e5};function lt(t){let e=ze(t);if(String(t).trim().toLowerCase().endsWith("_1m"))return e;let r=et(t)??String(t),o=mf[r]??mf[r.toLowerCase()];return o!==void 0?Math.min(e,o):e}function gf(t){return(t.inputTokens??0)+(t.outputTokens??0)}function me(t){return t.contextWindowTokens??gf(t)}function Pr(t){return t?{totalTokens:me(t),apiUsage:{input_tokens:t.inputTokens??0,output_tokens:t.outputTokens??0,cache_read_input_tokens:t.cachedInputTokens??0,cache_creation_input_tokens:t.cacheCreationTokens??0,context_window_tokens:me(t)}}:{totalTokens:0,apiUsage:null}}function Mr(t,e,n){return e<=0||t<=0||n<=0||n>=1?!1:t/e>=n}function Or(t,e){return e<=0||t<=0?0:t/e}var _s=.9,DT=.04;function hf(t){let e=ze(t),n=lt(t),r=In(t);if(e<=0||r<=0||n<e)return _s;let o=(e-r)/e-DT;return o>0?o:_s}function Dr(t,e,n,r){if(t<=0||n<=0||e<=0)return;let o=t+e;if(!(o<=n))throw new Error(`[afk] Context-window overflow: the conversation already used ~${t.toLocaleString()} tokens (last-turn API count) and the configured output ceiling is ${e.toLocaleString()} tokens \u2014 together they exceed the ${r} context window of ${n.toLocaleString()} tokens by ${(o-n).toLocaleString()} tokens. The provider would reject this request with HTTP 400. To continue: run /compact to summarise the conversation history, or start a new session.`)}function Fr(t,e){if(t===void 0||t===!1)return;let n=e!==void 0?hf(e):1;if(t===!0)return Math.min(_s,n);let r=t.threshold;if(!(typeof r!="number"||!Number.isFinite(r)||r<=0||r>=1))return Math.min(r,n)}var FT=t=>/opus-4-(7|[89])/.test(t),LT=t=>FT(t)||/(claude-)?(opus|sonnet)-5/.test(t),Ts=new Set,NT=.25;function Es(t,e){let n=In(e),r=t.maxOutputTokens;if(typeof r=="number"&&Number.isFinite(r)&&r>0){let o=Math.floor(r);if(o>n){let s=`max:${e}:${o}`;return Ts.has(s)||(Ts.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${e} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function yf(t){if(!t||t.length===0)return;let e=[];for(let n of t)n.user.length>0&&e.push({role:"user",content:n.user}),n.assistant.length>0&&e.push({role:"assistant",content:n.assistant});return e.length>0?e:void 0}function Rs(t,e,n){switch(t.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&LT(n))return{type:"adaptive",display:"summarized"};if(e<=1024)throw new Error(`[afk] Extended thinking requires max_tokens > 1024 (the API constraint is 1024 <= budget_tokens < max_tokens), but the resolved output cap is ${e}. Raise --max-output-tokens / AFK_MAX_OUTPUT_TOKENS above 1024, or disable thinking with --thinking disabled.`);let r=Math.floor(e*NT),o=Math.max(1024,e-1-r),s=t.budgetTokens!==void 0&&Number.isFinite(t.budgetTokens)?Math.floor(t.budgetTokens):void 0,i=Math.min(Math.max(s??o,1024),o);if(s!==void 0&&s>o){let a=`think:${n??"default"}:${s}:${e}`;Ts.has(a)||(Ts.add(a),console.warn(`[afk] thinking budgetTokens ${s} leaves too little of max_tokens ${e} for the reply; clamping to ${o}.`))}return{type:"enabled",budget_tokens:i,display:"summarized"}}}}function xs(t,e){if(t!==void 0)return t;let n=e.toLowerCase();if(/(claude-)?(opus|sonnet)-(4-[678]|5)/.test(n))return"max"}D();import tl from"path";import{dirname as UT}from"path";import{appendFileSync as BT,mkdirSync as $T}from"fs";var Ct=class{hooks;constructor(e){this.hooks=e}addReadRoot(e,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots();if(!o)return;let s=tl.resolve(e);o.includes(s)||(o.push(s),this.appendAuditLog({action:"grant-read",path:s,source:n,sessionId:r}))}addWriteRoot(e,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots(),s=this.hooks.getWriteRoots();if(!o||!s)return;let i=tl.resolve(e);o.includes(i)||o.push(i),s.includes(i)||(s.push(i),this.appendAuditLog({action:"grant-write",path:i,source:n,sessionId:r}))}revokeRoot(e,n="slash",r){let o=this.hooks.getReadRoots();if(!o)return;let s=tl.resolve(e),i=this.hooks.getProtectedRoot();if(i!==void 0&&s===i)return;let a=o.indexOf(s);a!==-1&&o.splice(a,1);let c=this.hooks.getWriteRoots();if(c){let l=c.indexOf(s);l!==-1&&c.splice(l,1)}this.appendAuditLog({action:"revoke",path:s,source:n,sessionId:r})}getGrants(){return{resolveBase:this.hooks.getProtectedRoot(),readRoots:this.hooks.getReadRoots()?.slice()??[],writeRoots:this.hooks.getWriteRoots()?.slice()??[],allowAll:this.hooks.getAllowAll()}}appendAuditLog(e){try{let n=ds();$T(UT(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??this.hooks.getDefaultSessionId?.()??null,action:e.action,path:e.path,source:e.source});BT(n,r+`
28
+ `),o+=Buffer.byteLength(u,"utf8");let p=i?u:`${hT(t)}${u}`;i=!0,c=c.then(async()=>{await uT(e,{recursive:!0,mode:448}),await dT(n,p,{encoding:"utf8",mode:384})}).catch(f=>{he("subagent-output-capture",t.sessionId??"unknown","write",f)})},d=()=>{if(r.length===0)return;let u=r.join("").trim();r=[],u.length>0&&(l(bs("say",{text:u})),a=!0)};return{observe(u){try{if(u.type==="chunk"){let p=u.chunk;if(p.type==="content"){r.push(p.content);return}if(p.type==="tool_use_detail"){if(p.pending)return;d(),l(bs("tool",{toolName:p.toolName,toolInput:p.toolInputRaw??p.toolInput}))}return}if(u.type==="message"){if(!a&&r.length===0){let p=u.message.content.trim();p.length>0&&(l(bs("say",{text:p})),a=!0)}return}(u.type==="done"||u.type==="error")&&(d(),a=!1)}catch(p){he("subagent-output-capture",t.sessionId??"unknown","observe",p)}},end(u){try{d(),l(bs("end",{reason:u}))}catch(p){he("subagent-output-capture",t.sessionId??"unknown","end",p)}}}}var Le=class extends Error{constructor(e){super(e),this.name="AbortError"}},Ae=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},ws=class extends Ae{constructor(e,n){super(e,n),this.name="IdleWatchdogError"}},q=class extends Error{constructor(n,r,o,s){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",s?.cause!==void 0&&(this.cause=s.cause),s?.injectContext!==void 0&&(this.injectContext=s.injectContext)}event;reason;cause;injectContext},Qe=class extends Error{constructor(e){super(e),this.name="StreamIncompleteError"}},Ze=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},Tn=class extends Error{constructor(e){super(e),this.name="DenialCircuitBreakerError"}};async function Zt(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){he("trace.emit",t,"tool_call",n)}}async function xt(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){he("trace.emit",t,"hook_decision",n)}}async function en(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){he("trace.emit",t,"subagent_lifecycle",n)}}async function Vp(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){he("trace.emit",t,"budget",n)}}async function Jp(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){he("trace.emit",t,"abort",n)}}async function Ss(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){he("trace.emit",t,"compaction",n)}}async function Yp(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){he("trace.emit",t,"closure",n)}}async function fe(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){he("trace.emit",t,"browser_event",n)}}async function $(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){he("trace.emit",t,"session_phase",n)}}import TT from"@anthropic-ai/sdk";var yT="fast-mode-2026-02-01";function Qp(t){let e=[...t.oauthEntries??[],...t.effort?[t.effortEntry]:[],...t.extendedCacheTtl?[t.extendedCacheEntry]:[],...t.fast?[yT]:[]].filter(Boolean);return[...new Set(e)].join(",")||void 0}var Zp="extended-cache-ttl-2025-04-11",bT=`claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,${Zp}`,wT="effort-2025-11-24",ST="claude-cli/1.0.0 (external, cli)",vT="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function vs(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Rr(t,e,n,r){let o=e==="oauth"?{authToken:t}:{apiKey:t},s=typeof n=="string"&&n.length>0?{...o,baseURL:n}:o;return r?{...s,fetch:r}:s}function It(t,e,n,r,o,s){let i=Qp({oauthEntries:t==="oauth"?bT.split(","):[],effort:t==="oauth"&&r===!0,extendedCacheTtl:o,fast:s,effortEntry:wT,extendedCacheEntry:Zp});return t!=="oauth"?i?{"anthropic-beta":i}:{}:{"anthropic-beta":i,"x-app":"cli","User-Agent":ST,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function ef(t){return t!=="oauth"?null:[{type:"text",text:vT}]}C();var Ir=["local","small","medium","large"],nf="claude-haiku-4-5-20251001",xr="claude-sonnet-4-6",Gc="claude-opus-5",Xc="claude-fable-5",tn={local:{id:""},small:{id:nf},medium:{id:xr},large:{id:Gc}},rf="auto",zc={opus:Gc,opus_1m:Gc,sonnet:xr,sonnet_1m:xr,haiku:nf,fable:Xc},nn=[...Ir,...Object.keys(zc)],qc;function Vc(t){qc=t}function Kc(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function ks(t,e,n){let r={},o=Kc(t);o&&(r.id=o);let s=Kc(e);s&&(r.baseUrl=s);let i=Kc(n);return i&&(r.apiKey=i),r}function kT(){return{local:ks(h.AFK_MODEL_LOCAL,h.AFK_MODEL_LOCAL_BASE_URL,h.AFK_MODEL_LOCAL_API_KEY),small:ks(h.AFK_MODEL_SMALL,h.AFK_MODEL_SMALL_BASE_URL,h.AFK_MODEL_SMALL_API_KEY),medium:ks(h.AFK_MODEL_MEDIUM,h.AFK_MODEL_MEDIUM_BASE_URL,h.AFK_MODEL_MEDIUM_API_KEY),large:ks(h.AFK_MODEL_LARGE,h.AFK_MODEL_LARGE_BASE_URL,h.AFK_MODEL_LARGE_API_KEY)}}function of(t){let e=kT(),n={};for(let r of Ir){let o=tn[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},c=s?.name;c&&(a.name=c);let l=s?.provider;l&&(a.provider=l);let d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function Rn(t){return t||qc||of()}function xn(t,e=Rn()){let n=t.trim().toLowerCase();if(!(!n||n===rf)){for(let r of Ir){let o=e[r].name;if(o&&o.trim().toLowerCase()===n)return r}if(n==="local"||n==="small"||n==="medium"||n==="large")return n}}function rn(t,e=Rn()){if(t===void 0)return{id:""};let n=xn(t,e);if(n)return e[n];let r=zc[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function et(t,e=Rn()){if(t!==void 0)return rn(t,e).id}function sf(t,e=Rn()){if(t===void 0)return;let n=xn(t,e);if(n&&e[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function af(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of Ir){let o=_T(n[r]);o&&(e[r]=o)}return e}function cf(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="anthropic"||e==="anthropic-direct")return"anthropic";if(e==="openai"||e==="openai-compatible")return"openai";if(e==="chatgpt-oauth"||e==="chatgpt")return"chatgpt-oauth";if(e==="xai")return"xai";if(e==="xai-oauth"||e==="xai_oauth")return"xai-oauth"}function En(t){return typeof t=="string"?t.trim():""}function tf(t){return/[\x00-\x1f\x7f]/.test(t)}var AT=new Set([...Ir,rf,...Object.keys(zc)]);function _T(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=En(e.id);if(!n)return;let r={id:n},o=En(e.name);o&&(r.name=o);let s=cf(e.provider);s&&(r.provider=s);let i=En(e.baseUrl);i&&(r.baseUrl=i);let a=En(e.apiKey);return a&&(r.apiKey=a),r}}function lf(t){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:'model binding must be an object with at least an "id"'};let e=t;if("apiKey"in e||"api_key"in e)return{ok:!1,error:"per-slot API keys are credentials; set AFK_MODEL_<TIER>_API_KEY via `afk config env set` instead of afk.config.json"};if("baseUrl"in e||"base_url"in e)return{ok:!1,error:"per-slot baseUrl is an endpoint-redirect credential vector; set AFK_MODEL_<TIER>_BASE_URL via `afk config env set` instead of afk.config.json"};let n=En(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(tf(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=En(e.name);if(o){if(tf(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(AT.has(o.trim().toLowerCase()))return{ok:!1,error:`model binding "name" must not shadow a built-in alias ("${o}")`};r.name=o}if(e.provider!==void 0&&e.provider!==""){let s=cf(e.provider);if(!s)return{ok:!1,error:'model binding "provider" must be one of: anthropic, openai (aliases: anthropic-direct, openai-compatible)'};r.provider=s}return{ok:!0,value:r}}var Jc={opus:tn.large.id,opus_1m:tn.large.id,sonnet:tn.medium.id,sonnet_1m:tn.medium.id,haiku:tn.small.id,fable:Xc};function As(t){return t in Jc}function we(t){return et(t)}import{randomUUID as df}from"node:crypto";async function uf(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let c=vs(e),l=Rr(e,c),d=a?a(l):new TT(l),u=df(),p=df(),f=It(c,u,p),m=we(n)??n,g={};Object.keys(f).length>0&&(g.headers=f),i&&(g.signal=i);let y=await d.messages.create({model:m,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(g).length>0?g:void 0),b=[];for(let _ of y.content)_.type==="text"&&b.push(_.text);let v=b.join("").trim();return v.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),v}C();var ET=new Set(["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4-turbo","o1","o3","o4-mini"]),RT=[/^claude-/i,/^gpt-4o/i,/^gpt-4\.1/i,/^gpt-4-turbo/i,/^gpt-4-vision/i,/^gpt-5/i,/(?:^|[/_-])(?:vl|vlm)(?:[/_.-]|$)/i,/(?:^|[/_-])(?:llava|pixtral|internvl|cogvlm|idefics|moondream|janus)/i,/(?:vision|minicpm-?[vo]|qwen[\d.]*-?vl|llama-?3\.2-\d+b-vision|gemma-3|phi-3\.5-vision|phi-4-multimodal)/i];function xT(){let t=h.AFK_VISION_MODELS,e=[],n=[];if(t)for(let r of t.split(",")){let o=r.trim().toLowerCase();if(o)if(o.startsWith("!")){let s=o.slice(1).trim();s&&n.push(s)}else e.push(o)}return{enable:e,disable:n}}function pf(t,e){return t===e||t.includes(e)}function Yc(t){if(!t)return!1;let e=(et(t)??t).trim();if(!e)return!1;let n=e.toLowerCase(),{enable:r,disable:o}=xT();return o.some(s=>pf(n,s))?!1:r.some(s=>pf(n,s))||ET.has(n)?!0:RT.some(s=>s.test(e))}function ff(t){let e=t.trim().toLowerCase();return e.includes("/")?e.slice(e.lastIndexOf("/")+1):e}function on(t){return t?/^o[0-9]/.test(ff(t)):!1}var IT=[/^gpt-5/];function Cr(t){if(!t)return!1;if(on(t))return!0;let e=ff(t);return IT.some(n=>n.test(e))}var Qc={opus:128e3,opus_1m:128e3,sonnet:128e3,sonnet_1m:128e3,haiku:64e3,fable:128e3,"claude-opus-5":128e3,"claude-opus-4-8":128e3,"claude-opus-4-7":128e3,"claude-opus-4-6":128e3,"claude-sonnet-5":128e3,"claude-sonnet-4-6":128e3,"claude-haiku-4-5-20251001":64e3,"claude-fable-5":128e3,"gpt-5.5":128e3,"gpt-5.6":128e3,"gpt-5.6-sol":128e3,"gpt-5.6-terra":128e3,"gpt-5.6-luna":128e3},CT=64e3;function el(t){let e=String(t).trim().toLowerCase(),n=Qc[e];if(e.endsWith("_1m")&&n!==void 0)return n;let r=et(t)??String(t);return Qc[r]??Qc[r.toLowerCase()]}function In(t){return el(t)??CT}var Zc={opus:1e6,opus_1m:1e6,sonnet:1e6,sonnet_1m:1e6,haiku:2e5,fable:1e6,"claude-fable-5":1e6,"claude-sonnet-5":1e6,"claude-opus-5":1e6,"claude-opus-4-8":1e6,"claude-opus-4-7":1e6,"claude-opus-4-6":1e6,"claude-sonnet-4-6":1e6,"gpt-4o":128e3,"gpt-4o-mini":128e3,"gpt-4.1":1e6,"gpt-4.1-mini":1e6,"gpt-5.5":1e6,"gpt-5.6":1e6,"gpt-5.6-sol":1e6,"gpt-5.6-terra":1e6,"gpt-5.6-luna":1e6,o1:2e5,"o1-mini":128e3,o3:2e5,"o3-mini":2e5,"o4-mini":2e5,"mlx-community/qwen3-30b-a3b-4bit":128e3,"mlx-community/qwen3-32b-4bit":128e3,"mlx-community/qwen2.5-coder-32b-instruct-4bit":131072,"grok-4.6":5e5,"grok-4.5":5e5,"grok-4.3":1e6,"grok-4.20-0309-reasoning":1e6,"grok-4.20-0309-non-reasoning":1e6,"grok-4.20-multi-agent-0309":1e6,"grok-build-0.1":256e3},PT=2e5,MT=262144;function OT(t){if(!t)return!1;let e=t.trim().toLowerCase();return e?!!(e.includes("/")||e.startsWith("gpt-")||e.startsWith("gpt_")||on(e)||e.startsWith("codex-")||e.startsWith("codex_")||e==="codex"||e==="grok"||e.startsWith("grok-")||e.startsWith("grok_")):!1}function ze(t){let e=String(t).trim().toLowerCase(),n=Zc[e];if(e.endsWith("_1m")&&n!==void 0)return n;let r=et(t)??String(t),o=Zc[r]??Zc[r.toLowerCase()];return o!==void 0?o:OT(r)?MT:PT}var mf={"claude-sonnet-5":2e5,"claude-opus-5":2e5,"claude-sonnet-4-6":2e5,"claude-opus-4-8":2e5,"claude-opus-4-7":2e5,"claude-opus-4-6":2e5};function lt(t){let e=ze(t);if(String(t).trim().toLowerCase().endsWith("_1m"))return e;let r=et(t)??String(t),o=mf[r]??mf[r.toLowerCase()];return o!==void 0?Math.min(e,o):e}function gf(t){return(t.inputTokens??0)+(t.outputTokens??0)}function me(t){return t.contextWindowTokens??gf(t)}function Pr(t){return t?{totalTokens:me(t),apiUsage:{input_tokens:t.inputTokens??0,output_tokens:t.outputTokens??0,cache_read_input_tokens:t.cachedInputTokens??0,cache_creation_input_tokens:t.cacheCreationTokens??0,context_window_tokens:me(t)}}:{totalTokens:0,apiUsage:null}}function Mr(t,e,n){return e<=0||t<=0||n<=0||n>=1?!1:t/e>=n}function Or(t,e){return e<=0||t<=0?0:t/e}var _s=.9,DT=.04;function hf(t){let e=ze(t),n=lt(t),r=In(t);if(e<=0||r<=0||n<e)return _s;let o=(e-r)/e-DT;return o>0?o:_s}function Dr(t,e,n,r){if(t<=0||n<=0||e<=0)return;let o=t+e;if(!(o<=n))throw new Error(`[afk] Context-window overflow: the conversation already used ~${t.toLocaleString()} tokens (last-turn API count) and the configured output ceiling is ${e.toLocaleString()} tokens \u2014 together they exceed the ${r} context window of ${n.toLocaleString()} tokens by ${(o-n).toLocaleString()} tokens. The provider would reject this request with HTTP 400. To continue: run /compact to summarise the conversation history, or start a new session.`)}function Fr(t,e){if(t===void 0||t===!1)return;let n=e!==void 0?hf(e):1;if(t===!0)return Math.min(_s,n);let r=t.threshold;if(!(typeof r!="number"||!Number.isFinite(r)||r<=0||r>=1))return Math.min(r,n)}var FT=t=>/opus-4-(7|[89])/.test(t),LT=t=>FT(t)||/(claude-)?(opus|sonnet)-5/.test(t),Ts=new Set,NT=.25;function Es(t,e){let n=In(e),r=t.maxOutputTokens;if(typeof r=="number"&&Number.isFinite(r)&&r>0){let o=Math.floor(r);if(o>n){let s=`max:${e}:${o}`;return Ts.has(s)||(Ts.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${e} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function yf(t){if(!t||t.length===0)return;let e=[];for(let n of t)n.user.length>0&&e.push({role:"user",content:n.user}),n.assistant.length>0&&e.push({role:"assistant",content:n.assistant});return e.length>0?e:void 0}function Rs(t,e,n){switch(t.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&LT(n))return{type:"adaptive",display:"summarized"};if(e<=1024)throw new Error(`[afk] Extended thinking requires max_tokens > 1024 (the API constraint is 1024 <= budget_tokens < max_tokens), but the resolved output cap is ${e}. Raise --max-output-tokens / AFK_MAX_OUTPUT_TOKENS above 1024, or disable thinking with --thinking disabled.`);let r=Math.floor(e*NT),o=Math.max(1024,e-1-r),s=t.budgetTokens!==void 0&&Number.isFinite(t.budgetTokens)?Math.floor(t.budgetTokens):void 0,i=Math.min(Math.max(s??o,1024),o);if(s!==void 0&&s>o){let a=`think:${n??"default"}:${s}:${e}`;Ts.has(a)||(Ts.add(a),console.warn(`[afk] thinking budgetTokens ${s} leaves too little of max_tokens ${e} for the reply; clamping to ${o}.`))}return{type:"enabled",budget_tokens:i,display:"summarized"}}}}function xs(t,e){if(t!==void 0)return t;let n=e.toLowerCase();if(/(claude-)?(opus|sonnet)-(4-[678]|5)/.test(n))return"max"}D();import tl from"path";import{dirname as UT}from"path";import{appendFileSync as BT,mkdirSync as $T}from"fs";var Ct=class{hooks;constructor(e){this.hooks=e}addReadRoot(e,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots();if(!o)return;let s=tl.resolve(e);o.includes(s)||(o.push(s),this.appendAuditLog({action:"grant-read",path:s,source:n,sessionId:r}))}addWriteRoot(e,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots(),s=this.hooks.getWriteRoots();if(!o||!s)return;let i=tl.resolve(e);o.includes(i)||o.push(i),s.includes(i)||(s.push(i),this.appendAuditLog({action:"grant-write",path:i,source:n,sessionId:r}))}revokeRoot(e,n="slash",r){let o=this.hooks.getReadRoots();if(!o)return;let s=tl.resolve(e),i=this.hooks.getProtectedRoot();if(i!==void 0&&s===i)return;let a=o.indexOf(s);a!==-1&&o.splice(a,1);let c=this.hooks.getWriteRoots();if(c){let l=c.indexOf(s);l!==-1&&c.splice(l,1)}this.appendAuditLog({action:"revoke",path:s,source:n,sessionId:r})}getGrants(){return{resolveBase:this.hooks.getProtectedRoot(),readRoots:this.hooks.getReadRoots()?.slice()??[],writeRoots:this.hooks.getWriteRoots()?.slice()??[],allowAll:this.hooks.getAllowAll()}}appendAuditLog(e){try{let n=ds();$T(UT(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??this.hooks.getDefaultSessionId?.()??null,action:e.action,path:e.path,source:e.source});BT(n,r+`
29
29
  `)}catch{}}};function Ve(t){return t==="bypassPermissions"||t==="autonomous"}var Is=class{_readRoots;_writeRoots;_initialResolveBase;_currentCwd;_permissionMode="default";manager=new Ct({getReadRoots:()=>this._readRoots,getWriteRoots:()=>this._writeRoots,ensureInitialized:()=>this.ensureInitialized(),getProtectedRoot:()=>this._initialResolveBase,getAllowAll:()=>Ve(this._permissionMode)});get readRoots(){return this._readRoots}get writeRoots(){return this._writeRoots}get currentCwd(){return this._currentCwd}set currentCwd(e){this._currentCwd=e}get permissionMode(){return this._permissionMode}set permissionMode(e){this._permissionMode=e}ensureInitialized(e){if(!this._readRoots){let n=e?[e]:[];this._readRoots=n.slice(),this._writeRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e),e&&!this._currentCwd&&(this._currentCwd=e)}}};C();var wf=8,Sf=8,HT=10,jT=32,WT=32,KT=64,GT=[{key:"AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS",defaultValue:wf,maxValue:jT},{key:"AFK_MAX_CONCURRENT_SUBAGENT_CALLS",defaultValue:Sf,maxValue:WT},{key:"AFK_MAX_CONCURRENT_BACKGROUND_JOBS",defaultValue:HT,maxValue:KT}],bf=new Set;function qT(t){return h[t]}function XT(t,e=!0){let n=qT(t.key);if(n===void 0)return{...t,rawValue:n,effectiveValue:t.defaultValue,source:"default",valid:!0};let r=n.trim(),o=Number(r);return/^\d+$/.test(r)&&Number.isInteger(o)&&o>0&&o<=t.maxValue?{...t,rawValue:n,effectiveValue:o,source:"environment",valid:!0}:(e&&!bf.has(t.key)&&(bf.add(t.key),process.stderr.write(`[afk] Invalid ${t.key}=${JSON.stringify(n)}; using default ${t.defaultValue}. Expected an integer in [1, ${t.maxValue}].
30
- `)),{...t,rawValue:n,effectiveValue:t.defaultValue,source:"fallback",valid:!1})}function vf(t){let e=GT.find(n=>n.key===t);if(!e)throw new Error(`Unknown concurrency setting: ${t}`);return XT(e).effectiveValue}function kf(){return vf("AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS")}function Cs(){return vf("AFK_MAX_CONCURRENT_SUBAGENT_CALLS")}oe();function nl(t){if(t instanceof Ae)return"timeout";if(t instanceof Ze)return"budget";if(typeof t=="string"){if(t==="budget"||t.startsWith("Budget "))return"budget";if(t==="timeout"||t.includes("timed out"))return"timeout";if(t==="closed")return"closed"}return"interrupted"}function _e(t){let e=nl(t.reason);return e==="timeout"||e==="budget"?e:"abort"}async function Lr(t,e,n){let r=new Array(t.length),o=Math.min(Math.max(1,Math.floor(e)),t.length),s=0,i=[];for(let a=0;a<o;a++)i.push((async()=>{for(;s<t.length;){let c=s++;try{r[c]={status:"fulfilled",value:await n(t[c])}}catch(l){r[c]={status:"rejected",reason:l}}}})());return await Promise.all(i),r}oe();var Ps=3e4;var Nr=class extends Error{constructor(n,r){super(`hook handler timed out after ${r}ms during ${n}`);this.hookEvent=n;this.timeoutMs=r;this.name="HookHandlerTimeoutError"}hookEvent;timeoutMs;code="HOOK_HANDLER_TIMEOUT"};async function tt(t,e,n,r){if(!t)return;if(r.kind==="blocked"){await xt(t,{hookEvent:e,decision:"block",...r.err.reason!==void 0?{reason:r.err.reason}:{},...e==="PreToolUse"&&n.toolName!==void 0?{blockedTool:n.toolName}:{}});return}let o=r.decision;await xt(t,{hookEvent:e,decision:o.decision,...o.reason!==void 0?{reason:o.reason}:{},...o.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(o.injectContext,"utf8")}:{}})}async function Af(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await tt(n.traceWriter,"SubagentStart",{},{kind:"decision",decision:r})}catch(r){throw r instanceof q&&await tt(n.traceWriter,"SubagentStart",{},{kind:"blocked",err:r}),r}}function zT(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new Nr(n,e)))},e);i.unref(),t.then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}async function _f(t,e,n={}){if(!t)return{};try{let r=await zT(t.dispatch(e,n.signal,Ps),Ps,"SubagentStop");return await tt(n.traceWriter,"SubagentStop",{},{kind:"decision",decision:r}),r}catch(r){return r instanceof Nr?(console.warn(`[afk] SubagentStop hook timed out after ${Ps}ms (subagentId=${e.subagentId}): ${r.message}`),n.onError?.(r),{}):(r instanceof q&&await tt(n.traceWriter,"SubagentStop",{},{kind:"blocked",err:r}),r instanceof q||r instanceof Le?(P(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):(P(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{}))}}async function Tf(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await tt(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){throw r instanceof q&&await tt(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r}}async function Ef(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await tt(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof q&&await tt(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof q||r instanceof Le){P(`PostToolUse hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}P(`PostToolUse hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}async function Rf(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await tt(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof q&&await tt(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof q||r instanceof Le){P(`PostToolUseFailure hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}P(`PostToolUseFailure hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}function Ms(t,e){return e?.allowedTools?e.allowedTools.includes(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" is not in the configured allowlist`}:{allowed:!0}}function Os(t,e){return xf(t,e)}function Ds(t,e){return xf(t,e)}function xf(t,e){if(!t?.allowedTools||e.length===0)return t;let n=new Set(t.allowedTools),r=!1;for(let o of e)n.has(o)||(n.add(o),r=!0);return r?{...t,allowedTools:[...n]}:t}var VT=/\bgit\s+config\b[^|;&]*\s(--add|--unset|--unset-all|--replace-all|--rename-section|--remove-section|--edit|-e)\b/i,JT=/\bgit\s+config\s+(?:--(?:global|system|local|worktree)\s+|(?:--file|-f)\s+\S+\s+)*[\w][\w.-]*\s+\S/i,YT=/\bgh\s+\w[\w-]*\s+(create|merge|close|edit|delete|comment|review|reopen|sync|fork|clone|ready)\b/i,QT=/\bgh\s+api\b.*(-X|--method)\s+(POST|PUT|PATCH|DELETE)\b/i,ZT=/\bgh\s+api\b.*(\s-f\b|\s-F\b|--field\b)/i,eE=/\bgh\s+(secret|variable|workflow|release|run|cache|ssh-key|gpg-key)\s+(set|run|rerun|cancel|upload|delete|enable|disable)\b/i,tE=/\|\s*(sh|bash|zsh|dash|ksh|mksh|csh|tcsh|fish|ash|python3?|node|nodejs|perl|ruby|php|bun)\b/i,nE=/\b(rm|rmdir|unlink|mv|cp|mkdir|touch|dd|truncate|tee|sponge|ln|chmod|chown|chgrp|shred|rsync)\b/i,rE=/\bfind\b[^|;&]*\s-delete\b/i,oE=/\bfind\b[^|;&]*\s-exec\s+['"]?\s*(rm|rmdir|unlink|mv|cp|dd|truncate|shred|tee|chmod|chown|chgrp|install|patch)\b/i,Fs=String.raw`(?:^|[\n;|&(]|\$\()\s*`,sE=new RegExp(Fs+String.raw`patch\b`,"i"),iE=new RegExp(Fs+String.raw`install\b`,"i"),aE=new RegExp(Fs+String.raw`(?:source\b|\.\s+\S)`,"i"),cE=/\btar\s+-?[a-zA-Z]*[cxruA][a-zA-Z]*\b/i,lE=new RegExp(Fs+String.raw`unzip\b`,"i"),dE=/\bcpio\b[^|;&]*\s-[a-zA-Z]*i\b/i,uE=/\bsed\b[^|;&]*\s-[a-zA-Z]*i\b/i,pE=/\bperl\b[^|;&]*\s-[a-zA-Z]*i\b/i,fE=/\b(?:python3?|nodejs|node|bun|ruby|perl|php)\b[^|;&]*?\s-(?:c|e)\b\s*("(?:[^"\\]|\\.)*"|'[^']*'|`[^`]*`)/i,mE=/open\s*\([^)]*,\s*['"][wax]|writeFileSync|writeFile\b|appendFileSync|appendFile\b|createWriteStream|File\.(?:write|delete)\b|IO\.write\b|FileUtils\.|\bBun\.write\b|os\.remove\b|os\.system\b|os\.popen\b|\bsubprocess\.|\bDeno\.(?:write|writeFile|writeTextFile|remove)\b|shutil\.\w|\.write_text\b|\.write_bytes\b/i,gE=/\b(npm|pnpm|yarn|pip|pip3|brew|cargo|go|apt|apt-get|gem|poetry|bundle|composer)\s+(install|add|remove|uninstall|i|ci|up|update|upgrade|dlx|get|require)\b/i,hE=/\b(curl|wget)\b[^|;&]*\s(-o\b|-O\b|--output\b)/i,yE=/\bcurl\b[^|;&]*\s-X\s+(POST|PUT|PATCH|DELETE)\b/i,bE=/\bcurl\b[^|;&]*\s(-d\b|--data\b|-F\b|--form\b)/i,wE=/(\d*&?>>?\s*\/dev\/null|\d*>&\d+|&>\s*\/dev\/null|&>>\s*\/dev\/null)/gi,SE=/\$\(\(.*?\)\)/g,vE=/(?<![=<>-])>>?(?!&)/,kE=[{re:JT,reason:"git config set (`<key> <value>`; only reads allowed)"},{re:oE,reason:"find -exec with mutating verb"}],AE=[{re:tE,reason:"pipe-to-shell (RCE via piped interpreter)"},{re:nE,reason:"filesystem mutation"},{re:rE,reason:"find -delete (file removal)"},{re:sE,reason:"patch (applies a diff to files)"},{re:iE,reason:"install (writes files)"},{re:aE,reason:"source/dot-source executes a script"},{re:cE,reason:"tar create/extract/append/update (writes files/archive)"},{re:lE,reason:"unzip (writes files)"},{re:dE,reason:"cpio extract (-i mode writes files)"},{re:VT,reason:"git config write flag (only reads allowed)"},{re:YT,reason:"gh write operation"},{re:QT,reason:"gh api write method (POST/PUT/PATCH/DELETE)"},{re:ZT,reason:"gh api field payload (-f/-F/--field)"},{re:eE,reason:"gh extended write operation (secret/variable/workflow/run/cache)"},{re:uE,reason:"sed in-place edit (-i)"},{re:pE,reason:"perl in-place edit (-i)"},{re:gE,reason:"package install/modify"},{re:hE,reason:"curl/wget output-to-file"},{re:yE,reason:"curl write method (POST/PUT/PATCH/DELETE)"},{re:bE,reason:"curl data/form payload"}];function _E(t){return t.replace(/'[^']*'/g," ").replace(/"(?:[^"\\]|\\.)*"/g,e=>/\$\(|`/.test(e)?e:" ")}var TE=new Set(["env","xargs","command","sudo","nice","time","timeout","nohup","stdbuf","busybox","eval"]);function rl(t){return(t.split("/").pop()??t).replace(/^\\+/,"")}var EE=new Set(["-u","--unset","-C","--chdir","-S","--split-string"]),RE=new Set(["-a","--arg-file","-E","--eof","-I","--replace","-i","-L","--max-lines","-l","-n","--max-args","-P","--max-procs","-s","--max-chars","-d","--delimiter","--process-slot-var"]);function Cf(t){let e=[],n=[],r=[],o="",s=!1,i=()=>{s&&(r.push(o),o="",s=!1)},a=()=>{i(),r.length>0&&(e.push(r),r=[])},c=u=>{let p=u,f=1,m="";for(;p<t.length&&f>0;){let g=t[p];if(g==="(")f++;else if(g===")"&&(f--,f===0)){p++;break}m+=g,p++}return n.push(m),p},l=0,d=t.length;for(;l<d;){let u=t[l];if(u==="'"){for(s=!0,l++;l<d&&t[l]!=="'";)o+=t[l],l++;l++;continue}if(u==='"'){for(s=!0,l++;l<d&&t[l]!=='"';)if(t[l]==="$"&&t[l+1]==="(")l=c(l+2);else if(t[l]==="`"){l++;let p="";for(;l<d&&t[l]!=="`";)p+=t[l],l++;l++,n.push(p)}else o+=t[l],l++;l++;continue}if(u==="`"){i(),l++;let p="";for(;l<d&&t[l]!=="`";)p+=t[l],l++;l++,n.push(p);continue}if(u==="$"&&t[l+1]==="("){i(),l=c(l+2);continue}if(u===";"||u===`
30
+ `)),{...t,rawValue:n,effectiveValue:t.defaultValue,source:"fallback",valid:!1})}function vf(t){let e=GT.find(n=>n.key===t);if(!e)throw new Error(`Unknown concurrency setting: ${t}`);return XT(e).effectiveValue}function kf(){return vf("AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS")}function Cs(){return vf("AFK_MAX_CONCURRENT_SUBAGENT_CALLS")}oe();function nl(t){if(t instanceof Ae)return"timeout";if(t instanceof Ze)return"budget";if(typeof t=="string"){if(t==="budget"||t.startsWith("Budget "))return"budget";if(t==="timeout"||t.includes("timed out"))return"timeout";if(t==="closed")return"closed"}return"interrupted"}function _e(t){let e=nl(t.reason);return e==="timeout"||e==="budget"?e:"abort"}async function Lr(t,e,n){let r=new Array(t.length),o=Math.min(Math.max(1,Math.floor(e)),t.length),s=0,i=[];for(let a=0;a<o;a++)i.push((async()=>{for(;s<t.length;){let c=s++;try{r[c]={status:"fulfilled",value:await n(t[c])}}catch(l){r[c]={status:"rejected",reason:l}}}})());return await Promise.all(i),r}oe();var Ps=3e4;var Nr=class extends Error{constructor(n,r){super(`hook handler timed out after ${r}ms during ${n}`);this.hookEvent=n;this.timeoutMs=r;this.name="HookHandlerTimeoutError"}hookEvent;timeoutMs;code="HOOK_HANDLER_TIMEOUT"};async function tt(t,e,n,r){if(!t)return;if(r.kind==="blocked"){await xt(t,{hookEvent:e,decision:"block",...r.err.reason!==void 0?{reason:r.err.reason}:{},...e==="PreToolUse"&&n.toolName!==void 0?{blockedTool:n.toolName}:{}});return}let o=r.decision;await xt(t,{hookEvent:e,decision:o.decision,...o.reason!==void 0?{reason:o.reason}:{},...o.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(o.injectContext,"utf8")}:{}})}async function Af(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await tt(n.traceWriter,"SubagentStart",{},{kind:"decision",decision:r})}catch(r){throw r instanceof q&&await tt(n.traceWriter,"SubagentStart",{},{kind:"blocked",err:r}),r}}function zT(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new Nr(n,e)))},e);i.unref(),t.then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}async function _f(t,e,n={}){if(!t)return{};try{let r=await zT(t.dispatch(e,n.signal,Ps),Ps,"SubagentStop");return await tt(n.traceWriter,"SubagentStop",{},{kind:"decision",decision:r}),r}catch(r){return r instanceof Nr?(console.warn(`[afk] SubagentStop hook timed out after ${Ps}ms (subagentId=${e.subagentId}): ${r.message}`),n.onError?.(r),{}):(r instanceof q&&await tt(n.traceWriter,"SubagentStop",{},{kind:"blocked",err:r}),r instanceof q||r instanceof Le?(P(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):(P(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{}))}}async function Tf(t,e,n={}){if(!t)return{};try{let r=await t.dispatch(e,n.signal);return await tt(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"decision",decision:r}),r}catch(r){throw r instanceof q&&await tt(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r}}async function Ef(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await tt(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof q&&await tt(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof q||r instanceof Le){P(`PostToolUse hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}P(`PostToolUse hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}async function Rf(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await tt(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof q&&await tt(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof q||r instanceof Le){P(`PostToolUseFailure hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}P(`PostToolUseFailure hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}function Ms(t,e){return e?.allowedTools?e.allowedTools.includes(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" is not in the configured allowlist`}:{allowed:!0}}function Os(t,e){return xf(t,e)}function Ds(t,e){return xf(t,e)}function xf(t,e){if(!t?.allowedTools||e.length===0)return t;let n=new Set(t.allowedTools),r=!1;for(let o of e)n.has(o)||(n.add(o),r=!0);return r?{...t,allowedTools:[...n]}:t}var VT=/\bgit\s+config\b[^|;&]*\s(--add|--unset|--unset-all|--replace-all|--rename-section|--remove-section|--edit|-e)\b/i,JT=/\bgit\s+config\s+(?:--(?:global|system|local|worktree)\s+|(?:--file|-f)\s+\S+\s+)*[\w][\w.-]*\s+\S/i,YT=/\bgh\s+\w[\w-]*\s+(create|merge|close|edit|delete|comment|review|reopen|sync|fork|clone|ready)\b/i,QT=/\bgh\s+api\b.*(-X|--method)\s+(POST|PUT|PATCH|DELETE)\b/i,ZT=/\bgh\s+api\b.*(\s-f\b|\s-F\b|--field\b)/i,eE=/\bgh\s+(secret|variable|workflow|release|run|cache|ssh-key|gpg-key)\s+(set|run|rerun|cancel|upload|delete|enable|disable)\b/i,tE=/\|\s*(sh|bash|zsh|dash|ksh|mksh|csh|tcsh|fish|ash|python3?|node|nodejs|perl|ruby|php|bun)\b/i,nE=/\b(rm|rmdir|unlink|mv|cp|mkdir|touch|dd|truncate|tee|sponge|ln|chmod|chown|chgrp|shred|rsync)\b/i,rE=/\bfind\b[^|;&]*\s-delete\b/i,oE=/\bfind\b[^|;&]*\s-exec\s+['"]?\s*(rm|rmdir|unlink|mv|cp|dd|truncate|shred|tee|chmod|chown|chgrp|install|patch)\b/i,Fs=String.raw`(?:^|[\n;|&(]|\$\()\s*`,sE=new RegExp(Fs+String.raw`patch\b`,"i"),iE=new RegExp(Fs+String.raw`install\b`,"i"),aE=new RegExp(Fs+String.raw`(?:source\b|\.\s+\S)`,"i"),cE=/\btar\s+-?[a-zA-Z]*[cxruA][a-zA-Z]*\b/i,lE=new RegExp(Fs+String.raw`unzip\b`,"i"),dE=/\bcpio\b[^|;&]*\s-[a-zA-Z]*i\b/i,uE=/\bsed\b[^|;&]*\s-[a-zA-Z]*i\b/i,pE=/\bperl\b[^|;&]*\s-[a-zA-Z]*i\b/i,fE=/\b(?:python3?|nodejs|node|bun|ruby|perl|php)\b[^|;&]*?\s-(?:c|e)\b\s*("(?:[^"\\]|\\.)*"|'[^']*'|`[^`]*`)/i,mE=/open\s*\([^)]*,\s*['"][wax]|writeFileSync|writeFile\b|appendFileSync|appendFile\b|createWriteStream|File\.(?:write|delete)\b|IO\.write\b|FileUtils\.|\bBun\.write\b|os\.remove\b|os\.system\b|os\.popen\b|\bsubprocess\.|\bDeno\.(?:write|writeFile|writeTextFile|remove)\b|shutil\.\w|\.write_text\b|\.write_bytes\b/i,gE=/\b(npm|pnpm|yarn|pip|pip3|brew|cargo|go|apt|apt-get|gem|poetry|bundle|composer)\s+(install|add|remove|uninstall|i|ci|up|update|upgrade|dlx|get|require)\b/i,hE=/\b(curl|wget)\b[^|;&]*\s(-o\b|-O\b|--output\b)/i,yE=/\bcurl\b[^|;&]*\s-X\s+(POST|PUT|PATCH|DELETE)\b/i,bE=/\bcurl\b[^|;&]*\s(-d\b|--data\b|-F\b|--form\b)/i,wE=/(\d*&?>>?\s*\/dev\/null|\d*>&\d+|&>\s*\/dev\/null|&>>\s*\/dev\/null)/gi,SE=/\$\(\(.*?\)\)/g,vE=/(?<![=<>-])>>?(?!&)/,kE=[{re:JT,reason:"git config set (`<key> <value>`; only reads allowed)"},{re:oE,reason:"find -exec with mutating verb"}],AE=[{re:tE,reason:"pipe-to-shell (RCE via piped interpreter)"},{re:nE,reason:"filesystem mutation"},{re:rE,reason:"find -delete (file removal)"},{re:sE,reason:"patch (applies a diff to files)"},{re:iE,reason:"install (writes files)"},{re:aE,reason:"source/dot-source executes a script"},{re:cE,reason:"tar create/extract/append/update (writes files/archive)"},{re:lE,reason:"unzip (writes files)"},{re:dE,reason:"cpio extract (-i mode writes files)"},{re:VT,reason:"git config write flag (only reads allowed)"},{re:YT,reason:"gh write operation"},{re:QT,reason:"gh api write method (POST/PUT/PATCH/DELETE)"},{re:ZT,reason:"gh api field payload (-f/-F/--field)"},{re:eE,reason:"gh extended write operation (secret/variable/workflow/run/cache)"},{re:uE,reason:"sed in-place edit (-i)"},{re:pE,reason:"perl in-place edit (-i)"},{re:gE,reason:"package install/modify"},{re:hE,reason:"curl/wget output-to-file"},{re:yE,reason:"curl write method (POST/PUT/PATCH/DELETE)"},{re:bE,reason:"curl data/form payload"}];function _E(t){return t.replace(/'[^']*'/g," ").replace(/"(?:[^"\\]|\\.)*"/g,e=>/\$\(|`/.test(e)?e:" ")}var TE=new Set(["env","xargs","command","sudo","nice","time","timeout","nohup","stdbuf","busybox","eval"]);function rl(t){return(t.split("/").pop()??t).replace(/^\\+/,"")}var EE=new Set(["-u","--unset","-C","--chdir","-S","--split-string"]),RE=new Set(["-a","--arg-file","-E","--eof","-I","--replace","-i","-L","--max-lines","-l","-n","--max-args","-P","--max-procs","-s","--max-chars","-d","--delimiter","--process-slot-var"]);function Cf(t){let e=[],n=[],r=[],o="",s=!1,i=()=>{s&&(r.push(o),o="",s=!1)},a=()=>{i(),r.length>0&&(e.push(r),r=[])},c=u=>{let p=u,f=1,m="";for(;p<t.length&&f>0;){let g=t[p];if(g==="(")f++;else if(g===")"&&(f--,f===0)){p++;break}m+=g,p++}return n.push(m),p},l=0,d=t.length;for(;l<d;){let u=t[l];if(u==="'"){for(s=!0,l++;l<d&&t[l]!=="'";)o+=t[l],l++;l++;continue}if(u==='"'){for(s=!0,l++;l<d&&t[l]!=='"';)if(t[l]==="$"&&t[l+1]==="(")l=c(l+2);else if(t[l]==="`"){l++;let p="";for(;l<d&&t[l]!=="`";)p+=t[l],l++;l++,n.push(p)}else o+=t[l],l++;l++;continue}if(u==="`"){i(),l++;let p="";for(;l<d&&t[l]!=="`";)p+=t[l],l++;l++,n.push(p);continue}if(u==="$"&&t[l+1]==="("){i(),l=c(l+2);continue}if(u===";"||u===`
31
31
  `||u==="&"||u==="|"||u==="("||u===")"){a(),l++;continue}if(u===" "||u===" "||u==="\r"){i(),l++;continue}o+=u,s=!0,l++}a();for(let u of n)for(let p of Cf(u))e.push(p);return e}function xE(t,e){let n=[...t],r=0,o=n[r];for((o==="export"||o==="local"||o==="declare")&&r++;r<n.length;){let s=/^([A-Za-z_]\w*)=(.*)$/.exec(n[r]);if(s===null)break;e.set(s[1],s[2]),r++}for(let s=0;r<n.length&&s<12;s++){let i=n[r],a=/^\$\{?([A-Za-z_]\w*)\}?$/.exec(i);if(a!==null){let l=e.get(a[1]);if(l!==void 0){let d=l.split(/\s+/).filter(Boolean);n=[...n.slice(0,r),...d,...n.slice(r+1)];continue}}let c=rl(i);if(!TE.has(c))break;if(r++,c==="env")for(;r<n.length;){let l=n[r],d=/^([A-Za-z_]\w*)=(.*)$/.exec(l);if(d!==null){e.set(d[1],d[2]),r++;continue}if(!l.startsWith("-"))break;r++,EE.has(l)&&r<n.length&&r++}else if(c==="xargs")for(;r<n.length&&n[r].startsWith("-");){let l=n[r];r++,RE.has(l)&&r<n.length&&r++}else if(c==="timeout"){for(;r<n.length&&n[r].startsWith("-");){let l=n[r];r++,(l==="-k"||l==="--kill-after"||l==="-s"||l==="--signal")&&r<n.length&&r++}r<n.length&&/^[\d.]+[smhd]?$/.test(n[r])&&r++}else if(c==="nice")for(;r<n.length&&n[r].startsWith("-");){let l=n[r];r++,l==="-n"&&r<n.length&&r++}else for(;r<n.length&&n[r].startsWith("-");){let l=n[r];r++,(l==="-u"||l==="--user")&&r<n.length&&r++}}return r>=n.length?null:{command:n[r],argv:n.slice(r+1)}}var IE=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),CE=new Set(["commit","push","pull","fetch","merge","rebase","reset","checkout","switch","restore","cherry-pick","revert","am","apply","clean","add","rm","mv","init","clone"]);function PE(t){let e=0;for(;e<t.length;){let n=t[e];if(IE.has(n)){e+=2;continue}if(!n.startsWith("-"))break;e++}return{sub:t[e],rest:t.slice(e+1)}}function Pf(t){if(t.includes("--help")||t.includes("-h"))return null;let{sub:e,rest:n}=PE(t);if(e===void 0||e==="help"||e==="config")return null;if(CE.has(e))return"git repository mutation";let r=n[0]??"";switch(e){case"tag":return r.startsWith("-")?"git tag create/delete":null;case"branch":return/^-[dDmMcC]/.test(r)||/^--(delete|move|copy|force)/.test(r)?"git branch delete/rename":null;case"remote":return["add","remove","rm","set-url","rename"].includes(r)?"git remote mutation":null;case"worktree":return["add","remove","prune","move","lock","unlock"].includes(r)?"git worktree mutation (add/remove/prune/move)":null;case"stash":return r==="list"||r==="show"?null:"git stash mutation (only `stash list`/`stash show` allowed)";default:return null}}var ME=/^(POST|PUT|PATCH|DELETE)$/i;function OE(t){if((t.command.split("/").pop()??t.command)!=="curl")return!1;for(let n=0;n<t.argv.length;n++){let r=t.argv[n];if((r==="-X"||r==="--request")&&ME.test(t.argv[n+1]??"")||/^-X(POST|PUT|PATCH|DELETE)$/i.test(r)||/^--request=(POST|PUT|PATCH|DELETE)$/i.test(r))return!0}return!1}function If(t){for(let e=0;e<t.length-1;e++)if(rl(t[e])==="git"){let n=Pf(t.slice(e+1));if(n!==null)return n}return null}function DE(t){let e=new Map;for(let n of Cf(t)){let r=xE(n,e);if(r===null){let i=If(n);if(i!==null)return i;continue}let o=rl(r.command);if(o==="git"){let i=Pf(r.argv);if(i!==null)return i;continue}if(o==="curl"&&OE(r))return"curl write method (POST/PUT/PATCH/DELETE)";let s=If(n);if(s!==null)return s}return null}function Mf(t){if(typeof t!="string"||t.trim().length===0)return{mutating:!1};for(let s of kE)if(s.re.test(t))return{mutating:!0,reason:s.reason};let e=t.match(fE)?.[1];if(e&&mE.test(e))return{mutating:!0,reason:"interpreter one-liner file write (`-c`/`-e`)"};let n=DE(t);if(n!==null)return{mutating:!0,reason:n};let r=_E(t);for(let s of AE)if(s.re.test(r))return{mutating:!0,reason:s.reason};let o=r.replace(SE," ").replace(wE," ").replace(/&(>>?)/g,"$1");return vE.test(o)?{mutating:!0,reason:"output redirection to a file (`>`/`>>`)"}:{mutating:!1}}function FE(t,e){if(t.length<=e)return t;let n=e;for(;n>0&&(t[n]&192)===128;)n--;return t.subarray(0,n)}function LE(t,e){if(t.length<=e)return t;let n=t.length-e;for(;n<t.length&&(t[n]&192)===128;)n++;return t.subarray(n)}var NE=160;function dt(t,e){let n=Buffer.from(t,"utf8");if(n.length<=e)return t;let r=Math.max(0,e-NE),o=Math.ceil(r/2),s=r-o,i=FE(n,o),a=LE(n,s),l=`
32
32
 
33
33
  \u2026 [${n.length-i.length-a.length} bytes truncated: showing first ${i.length} + last ${a.length} of ${n.length}] \u2026
@@ -178,7 +178,9 @@ ${n}
178
178
  Remedy: these paths are outside the fork's granted read roots. Re-dispatch with the needed paths inside the child's cwd/worktree, or pass explicit readRoots granting them. If this worker is deliberately confined (e.g. an \`afk farm\` branch worker), this failure is expected \u2014 the paths are outside its assigned scope; widen the scope or narrow the task.`}import{createHash as XR}from"node:crypto";var zR=5,ml=20;function um(){return{recent:[],firedFingerprints:new Set}}function Js(t){let e;try{e=VR(t.input)}catch{e=String(t.input)}return XR("sha256").update(t.name).update("\0").update(e).digest("hex")}function VR(t){return JSON.stringify(fl(t))??"null"}function fl(t){if(Array.isArray(t))return t.map(fl);if(t!==null&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e).sort())n[r]=fl(e[r]);return n}return t}function JR(t,e){let n=0;for(let r of t)r===e&&(n+=1);return n}function pm(t,e){t.recent.push(e),t.recent.length>ml&&t.recent.shift();let n=JR(t.recent,e);return n>=zR&&!t.firedFingerprints.has(e)?(t.firedFingerprints.add(e),{fired:!0,count:n}):{fired:!1,count:n}}var gl=3,YR=new Set(["timeout_ms","timeoutMs","timeout"]),fm=240;function QR(t){if(t===null||typeof t!="object"||Array.isArray(t))return t;let e={};for(let[n,r]of Object.entries(t))YR.has(n)||(e[n]=r);return e}function Gr(t){return Js({...t,input:QR(t.input)})}function ZR(t){let e=t.content.split(`
179
179
  `).find(n=>n.trim()!=="")?.trim()??"";return e.length<=fm?e:`${e.slice(0,fm)}\u2026`}var Ys=class{streaks=new Map;check(e){let n=this.streaks.get(Gr(e));return n===void 0||n.count<gl?null:{count:n.count,tool:e.name,result:{content:`Repeat-failure guard: "${e.name}" has already failed ${n.count} times in a row with the same arguments, so this call was NOT executed again. The last failure was: ${n.lastError}
180
180
 
181
- Retrying it verbatim will fail the same way. Fix the underlying cause, change the arguments, use a different tool, or stop and report the blocker.`,isError:!0,failureClass:"repeat-failure"}}}note(e,n){let r=Gr(e);if(n.isError!==!0){this.streaks.delete(r);return}let o=this.streaks.get(r);this.streaks.set(r,{count:(o?.count??0)+1,lastError:ZR(n)})}streakFor(e){return this.streaks.get(Gr(e))?.count??0}};var tx=8,hl=new Set;var $e=class{handlers;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;skillExecutor;composeExecutor;classifier;maxConcurrentSafeCalls;resolveBase;_readRoots;_writeRoots;_allowAll;_env;sessionId;parentSessionId;subagentId;sessionGrantManager;traceWriter;readOnlyBash;maxOutputBytes;repeatBreaker=null;repeatFailureGuard=new Ys;denialBreaker=null;suspectedLoopWindow=null;grantManager;constructor(e){this.handlers=e.handlers,this.schemas=e.schemas,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.canUseTool=e.canUseTool,this.subagentExecutor=e.subagentExecutor,this.skillExecutor=e.skillExecutor,this.composeExecutor=e.composeExecutor,this.classifier=e.concurrencyClassifier??Vs,this.maxConcurrentSafeCalls=typeof e.maxConcurrentSafeCalls=="number"&&Number.isFinite(e.maxConcurrentSafeCalls)&&e.maxConcurrentSafeCalls>=1?Math.floor(e.maxConcurrentSafeCalls):kf(),this.resolveBase=e.cwd,this._env=e.env,this.sessionId=e.sessionId,this.parentSessionId=e.parentSessionId,this.subagentId=e.subagentId,this.sessionGrantManager=e.sessionGrantManager,this.traceWriter=e.traceWriter,this.readOnlyBash=e.readOnlyBash===!0,this.maxOutputBytes=typeof e.maxOutputBytes=="number"&&Number.isFinite(e.maxOutputBytes)&&e.maxOutputBytes>0?e.maxOutputBytes:void 0,this._allowAll=e.allowAll===!0;let n=e.cwd?[e.cwd]:[];this._readRoots=e.readRoots??n.slice(),this._writeRoots=e.writeRoots??n.slice(),this.grantManager=new Ct({getReadRoots:()=>this._readRoots,getWriteRoots:()=>this._writeRoots,getProtectedRoot:()=>this.resolveBase,getAllowAll:()=>this._allowAll,getDefaultSessionId:()=>this.sessionId})}get handlerContext(){return{cwd:this.resolveBase,resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),...this._allowAll?{allowAll:!0}:{},...this._env!==void 0?{env:this._env}:{},...this.sessionId!==void 0?{sessionId:this.sessionId}:{}}}callHandlerContext(e){return{...this.handlerContext,toolUseId:e.id,...this.traceWriter!==void 0?{traceWriter:this.traceWriter}:{}}}addReadRoot(e,n="slash"){this.grantManager.addReadRoot(e,n)}addWriteRoot(e,n="slash"){this.grantManager.addWriteRoot(e,n)}revokeRoot(e,n="slash"){this.grantManager.revokeRoot(e,n)}getGrants(){return this.grantManager.getGrants()}setAllowAll(e){this._allowAll=e}setResolveBase(e){let n=this.resolveBase;if(n!==e){if(this.resolveBase=e,n!==void 0){let r=this._readRoots.indexOf(n);r!==-1?this._readRoots[r]=e:this._readRoots.includes(e)||this._readRoots.push(e);let o=this._writeRoots.indexOf(n);o!==-1?this._writeRoots[o]=e:this._writeRoots.includes(e)||this._writeRoots.push(e)}else this._readRoots.includes(e)||this._readRoots.push(e),this._writeRoots.includes(e)||this._writeRoots.push(e);this.subagentExecutor?.setCwd(e),this.skillExecutor?.setCwd(e),this.composeExecutor?.setCwd(e)}}get toolDefs(){let e=this.permissions?.allowedTools;if(!e)return this.schemas;let n=new Set(e);return this.schemas.filter(r=>n.has(r.name))}denialReason(e,n){return this.isRegisteredTool(e)?n??`Tool "${e}" is not permitted`:this.unknownToolMessage(e)}isRegisteredTool(e){return this.handlers.has(e)||e==="agent"&&this.subagentExecutor!==void 0||e==="skill"&&this.skillExecutor!==void 0||e==="compose"&&this.composeExecutor!==void 0}unknownToolMessage(e){let n=this.toolDefs.map(o=>o.name).join(", "),r=n.length>0?`Available tools: ${n}. Do NOT retry "${e}" or a variant of it; use one of the tools listed above.`:`Do NOT retry "${e}" or a variant of it.`;return`Unknown tool "${e}" \u2014 it does not exist in this session. ${r}`}async checkReadOnlyBash(e){if(!this.readOnlyBash||e.name!=="bash")return null;let n=e.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=Mf(r);if(!o.mutating)return null;let s=`Bash command blocked: read-only skill may not run mutating commands (${o.reason??"mutation detected"}). Allowed: read-only recon (git status/log/diff/show/ls-remote, ls, cat, find, grep, gh pr view/diff). For a remote ref you have not fetched, \`gh pr diff <n>\`, \`gh pr view <n>\` and \`git ls-remote\` need no local ref \u2014 \`git fetch\` is blocked. Do NOT retry variants of a blocked command: if the task genuinely requires a mutation, stop and report that requirement to your caller instead.`;return await this.emitPreToolUseBlock(e.name,s),{content:s,isError:!0,failureClass:"permission-denied"}}async emitPreToolUseBlock(e,n){await xt(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:e,reason:n,...this.subagentId!==void 0?{subagentId:this.subagentId}:{}})}checkRepeatCircuitBreaker(e){if(hl.has(e.name))return null;let n=im(e);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<tx?null:{content:`Loop circuit breaker: "${e.name}" has been called ${this.repeatBreaker.count} times in a row with byte-identical input. The result will not change. Stop repeating this call \u2014 reuse the previous result, change the input, try a different tool, or end the turn.`,isError:!0,circuitBreaker:!0}}checkRepeatFailureGuard(e){if(hl.has(e.name))return null;let n=this.repeatFailureGuard.check(e);return n===null?null:(P(`[repeat-failure-guard #723] refused ${n.tool} after ${n.count} identical failures`),n.result)}observeSuspectedLoop(e){if(this.parentSessionId===void 0)return;this.suspectedLoopWindow===null&&(this.suspectedLoopWindow=um());let n=Js(e),r=pm(this.suspectedLoopWindow,n);r.fired&&$(this.traceWriter,{phase:"suspected_loop",metadata:{tool:e.name,count:r.count,windowSize:ml}})}recordForkReadDenial(e,n,r){if(this.parentSessionId===void 0||!am.has(e.name)||!cm(n))return r;let o=this.denialBreaker??{count:0,deniedPaths:[]};o.count+=1;let s=lm(e);return o.deniedPaths.includes(s)||o.deniedPaths.push(s),this.denialBreaker=o,o.count<5?r:{content:dm(o.deniedPaths,o.count),isError:!0,failureClass:Mn}}resetDenialBreaker(){this.denialBreaker=null}async runCanUseTool(e){if(!this.canUseTool)return null;let n;try{n=await this.canUseTool(e.name,e.input??{},{signal:e.signal,toolUseID:e.id})}catch(r){let o=`Tool "${e.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`;return await this.emitPreToolUseBlock(e.name,o),{content:o,isError:!0,failureClass:"permission-denied"}}if(n.behavior==="deny"){let r=n.message||`Tool "${e.name}" denied by permission policy`;return await this.emitPreToolUseBlock(e.name,r),{content:r,isError:!0,failureClass:"permission-denied"}}return n.updatedInput!==void 0&&(e.input=n.updatedInput),null}async runPreDispatchGates(e){if(this.hookRegistry){let a={event:"PreToolUse",toolName:e.name,input:e.input,...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.resolveBase!==void 0?{cwd:this.resolveBase}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{}};try{await Tf(this.hookRegistry,a,{signal:e.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(c){if(c instanceof q)return this.recordForkReadDenial(e,c.reason,{content:`Tool "${e.name}" blocked by PreToolUse hook: ${c.message}`,isError:!0,failureClass:"hook-block"});throw c}}let n=Ms(e.name,this.permissions);if(!n.allowed){let a=this.denialReason(e.name,n.reason);return await this.emitPreToolUseBlock(e.name,a),{content:a,isError:!0,failureClass:"permission-denied"}}let r=await this.runCanUseTool(e);if(r)return r;let o=await this.checkReadOnlyBash(e);if(o)return o;let s=this.checkRepeatCircuitBreaker(e);if(s)return s;let i=this.checkRepeatFailureGuard(e);return i||(this.observeSuspectedLoop(e),null)}async execute(e){if(e.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:_e(e.signal)};let n=await this.runPreDispatchGates(e);if(n)return n;let r=await this.executeCore(e);return this.repeatFailureGuard.note(e,r),r.isError!==!0&&this.resetDenialBreaker(),r}async executeBatch(e){if(e.length===0)return[];if(e.length===1)return[await this.execute(e[0])];let n=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){let a=e[i];if(a.signal.aborted){n[i]={content:"Tool call aborted",isError:!0,failureClass:_e(a.signal)},r.add(i);continue}let c=await this.runPreDispatchGates(a);if(c){n[i]=c,r.add(i);continue}}let o=e.map((i,a)=>({call:i,originalIndex:a})).filter((i,a)=>!r.has(a));if(o.length===0)return n;let s=sm(o.map(i=>i.call),this.classifier);for(let i of s){if(i.isConcurrencySafe){let c=[...i.indices];for(;c.length>0;){let l=new Map,d=[],u=[];for(let m of c){let{call:g,originalIndex:y}=o[m],b=this.checkRepeatFailureGuard(g);if(b){n[y]=b;continue}if(hl.has(g.name)){d.push(m);continue}let v=Gr(g),_=gl-this.repeatFailureGuard.streakFor(g),w=l.get(v)??0;w<_?(l.set(v,w+1),d.push(m)):u.push(m)}c=u;let p=d.map(m=>o[m]?.call).filter(m=>m!==void 0&&m.name==="agent");if(p.length>=2&&this.subagentExecutor)try{this.subagentExecutor.notifyWaveStart(p,this.sessionId??"",null)}catch{}let f=await Lr(d,this.maxConcurrentSafeCalls,async m=>{let{call:g,originalIndex:y}=o[m];return g.signal.aborted?{result:{content:"Tool call aborted",isError:!0,failureClass:_e(g.signal)},originalIndex:y}:{result:await this.executeCore(g),originalIndex:y}});for(let m of f)if(m.status==="fulfilled")n[m.value.originalIndex]=m.value.result;else{let g=m.reason instanceof Error?m.reason.message:String(m.reason),y=d[f.indexOf(m)];n[o[y].originalIndex]={content:`Tool execution error: ${g}`,isError:!0}}for(let m of d){let{call:g,originalIndex:y}=o[m],b=n[y];b!==void 0&&b.failureClass!=="abort"&&this.repeatFailureGuard.note(g,b)}if(p.length>=2&&this.subagentExecutor)try{this.subagentExecutor.notifyWaveEnd()}catch{}}}else for(let c of i.indices){let{call:l,originalIndex:d}=o[c];if(l.signal.aborted){n[d]={content:"Tool call aborted",isError:!0,failureClass:_e(l.signal)};continue}let u=this.checkRepeatFailureGuard(l);if(u){n[d]=u;continue}let p=await this.executeCore(l);n[d]=p,this.repeatFailureGuard.note(l,p)}let a=i.indices.length;i.indices.forEach((c,l)=>{let d=n[o[c].originalIndex];d&&(d.batchIndex=l+1,d.batchSize=a)})}return n.some(i=>i!==void 0&&i.isError!==!0)&&this.resetDenialBreaker(),n}async executeCore(e){let n=await this.executeCoreInner(e);return this.applyOutputCap(n)}applyOutputCap(e){let n=this.maxOutputBytes;if(n===void 0)return e;let r=Buffer.byteLength(e.content,"utf8");return r<=n||(e.content=dt(e.content,n),e.truncated=!0,P(`[output-cap #661] fork tool result capped: original=${r}B capped=${Buffer.byteLength(e.content,"utf8")}B (cap=${n}B)`)),e}async executeCoreInner(e){if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let i,a=!1,c="";try{i=await this.subagentExecutor.execute(e)}catch(l){a=!0,c=l instanceof Error?l.message:String(l),i={content:`Agent tool error: ${c}`,isError:!0}}return a?this.firePostToolUseFailure(e.name,c,e.signal,e.input):this.firePostToolUse(e.name,i.content,e.signal,e.input,i),i}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let i,a=!1,c="";try{i=await this.skillExecutor.execute(e)}catch(l){a=!0,c=l instanceof Error?l.message:String(l),i={content:`Skill tool error: ${c}`,isError:!0}}return a?this.firePostToolUseFailure(e.name,c,e.signal,e.input):this.firePostToolUse(e.name,i.content,e.signal,e.input,i),i}if(e.name==="compose"){let i=await this.executeCompose(e);return this.firePostToolUse(e.name,i.content,e.signal,e.input,i),i}let n=this.handlers.get(e.name);if(!n){let i=this.unknownToolMessage(e.name);return await this.emitPreToolUseBlock(e.name,i),{content:i,isError:!0,failureClass:"permission-denied"}}let r,o=!1,s="";try{r=await n(e.input,e.signal,this.callHandlerContext(e))}catch(i){o=!0,s=i instanceof Error?i.message:String(i),r={content:`Tool execution error: ${s}`,isError:!0}}return o?this.firePostToolUseFailure(e.name,s,e.signal,e.input):this.firePostToolUse(e.name,r.content,e.signal,e.input,r),r}async executeCompose(e){if(!this.composeExecutor)return{content:"Compose tool is not available in this session configuration",isError:!0};try{return await this.composeExecutor.execute(e)}catch(n){return{content:`Compose tool error: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}firePostToolUse(e,n,r,o,s){if(!this.hookRegistry)return;let i={event:"PostToolUse",toolName:e,output:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{},...s?.incomplete===!0?{incomplete:!0}:{},...s?.incompleteReason?{incompleteReason:s.incompleteReason}:{}};Ef(this.hookRegistry,i,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(()=>{})}firePostToolUseFailure(e,n,r,o){if(!this.hookRegistry)return;let s={event:"PostToolUseFailure",toolName:e,error:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};Rf(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(i=>{P(`firePostToolUseFailure outer catch (tool=${e}): ${String(i)}`)})}};import{spawn as Zx}from"child_process";import eI from"os";C();D();import{mkdir as nx,writeFile as rx}from"fs/promises";import{dirname as ox,join as sx}from"path";function ix(){return sx(Fe(),"routing-decisions.jsonl")}function ax(t){let e={surface:"afk"};for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}async function Te(t){if(!(h.VITEST||h.NODE_ENV==="test"))try{let e=ix();await nx(ox(e),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,...ax(t)})+`
181
+ Retrying it verbatim will fail the same way. Fix the underlying cause, change the arguments, use a different tool, or stop and report the blocker.`,isError:!0,failureClass:"repeat-failure"}}}note(e,n){let r=Gr(e);if(n.isError!==!0){this.streaks.delete(r);return}let o=this.streaks.get(r);this.streaks.set(r,{count:(o?.count??0)+1,lastError:ZR(n)})}streakFor(e){return this.streaks.get(Gr(e))?.count??0}};var tx=8,hl=new Set;var $e=class{handlers;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;skillExecutor;composeExecutor;classifier;maxConcurrentSafeCalls;resolveBase;_readRoots;_writeRoots;_allowAll;_env;sessionId;parentSessionId;subagentId;sessionGrantManager;traceWriter;readOnlyBash;maxOutputBytes;repeatBreaker=null;repeatFailureGuard=new Ys;denialBreaker=null;suspectedLoopWindow=null;grantManager;constructor(e){this.handlers=e.handlers,this.schemas=e.schemas,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.canUseTool=e.canUseTool,this.subagentExecutor=e.subagentExecutor,this.skillExecutor=e.skillExecutor,this.composeExecutor=e.composeExecutor,this.classifier=e.concurrencyClassifier??Vs,this.maxConcurrentSafeCalls=typeof e.maxConcurrentSafeCalls=="number"&&Number.isFinite(e.maxConcurrentSafeCalls)&&e.maxConcurrentSafeCalls>=1?Math.floor(e.maxConcurrentSafeCalls):kf(),this.resolveBase=e.cwd,this._env=e.env,this.sessionId=e.sessionId,this.parentSessionId=e.parentSessionId,this.subagentId=e.subagentId,this.sessionGrantManager=e.sessionGrantManager,this.traceWriter=e.traceWriter,this.readOnlyBash=e.readOnlyBash===!0,this.maxOutputBytes=typeof e.maxOutputBytes=="number"&&Number.isFinite(e.maxOutputBytes)&&e.maxOutputBytes>0?e.maxOutputBytes:void 0,this._allowAll=e.allowAll===!0;let n=e.cwd?[e.cwd]:[];this._readRoots=e.readRoots??n.slice(),this._writeRoots=e.writeRoots??n.slice(),this.grantManager=new Ct({getReadRoots:()=>this._readRoots,getWriteRoots:()=>this._writeRoots,getProtectedRoot:()=>this.resolveBase,getAllowAll:()=>this._allowAll,getDefaultSessionId:()=>this.sessionId})}get handlerContext(){return{cwd:this.resolveBase,resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),...this._allowAll?{allowAll:!0}:{},...this._env!==void 0?{env:this._env}:{},...this.sessionId!==void 0?{sessionId:this.sessionId}:{}}}callHandlerContext(e){return{...this.handlerContext,toolUseId:e.id,...this.traceWriter!==void 0?{traceWriter:this.traceWriter}:{}}}addReadRoot(e,n="slash"){this.grantManager.addReadRoot(e,n)}addWriteRoot(e,n="slash"){this.grantManager.addWriteRoot(e,n)}revokeRoot(e,n="slash"){this.grantManager.revokeRoot(e,n)}getGrants(){return this.grantManager.getGrants()}setAllowAll(e){this._allowAll=e}setResolveBase(e){let n=this.resolveBase;if(n!==e){if(this.resolveBase=e,n!==void 0){let r=this._readRoots.indexOf(n);r!==-1?this._readRoots[r]=e:this._readRoots.includes(e)||this._readRoots.push(e);let o=this._writeRoots.indexOf(n);o!==-1?this._writeRoots[o]=e:this._writeRoots.includes(e)||this._writeRoots.push(e)}else this._readRoots.includes(e)||this._readRoots.push(e),this._writeRoots.includes(e)||this._writeRoots.push(e);this.subagentExecutor?.setCwd(e),this.skillExecutor?.setCwd(e),this.composeExecutor?.setCwd(e)}}get toolDefs(){let e=this.permissions?.allowedTools;if(!e)return this.schemas;let n=new Set(e);return this.schemas.filter(r=>n.has(r.name))}denialReason(e,n){return this.isRegisteredTool(e)?n??`Tool "${e}" is not permitted`:this.unknownToolMessage(e)}isRegisteredTool(e){return this.handlers.has(e)||e==="agent"&&this.subagentExecutor!==void 0||e==="skill"&&this.skillExecutor!==void 0||e==="compose"&&this.composeExecutor!==void 0}unknownToolMessage(e){let n=this.toolDefs.map(o=>o.name).join(", "),r=n.length>0?`Available tools: ${n}. Do NOT retry "${e}" or a variant of it; use one of the tools listed above.`:`Do NOT retry "${e}" or a variant of it.`;return`Unknown tool "${e}" \u2014 it does not exist in this session. ${r}`}async checkReadOnlyBash(e){if(!this.readOnlyBash||e.name!=="bash")return null;let n=e.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=Mf(r);if(!o.mutating)return null;let s=`Bash command blocked: read-only skill may not run mutating commands (${o.reason??"mutation detected"}). Allowed: read-only recon (git status/log/diff/show/ls-remote, ls, cat, find, grep, gh pr view/diff). For a remote ref you have not fetched, \`gh pr diff <n>\`, \`gh pr view <n>\` and \`git ls-remote\` need no local ref \u2014 \`git fetch\` is blocked. Do NOT retry variants of a blocked command: if the task genuinely requires a mutation, stop and report that requirement to your caller instead.`;return await this.emitPreToolUseBlock(e.name,s),{content:s,isError:!0,failureClass:"permission-denied"}}async emitPreToolUseBlock(e,n){await xt(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:e,reason:n,...this.subagentId!==void 0?{subagentId:this.subagentId}:{}})}checkRepeatCircuitBreaker(e){if(hl.has(e.name))return null;let n=im(e);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<tx?null:{content:`Loop circuit breaker: "${e.name}" has been called ${this.repeatBreaker.count} times in a row with byte-identical input. The result will not change. Stop repeating this call \u2014 reuse the previous result, change the input, try a different tool, or end the turn.`,isError:!0,circuitBreaker:!0}}checkRepeatFailureGuard(e){if(hl.has(e.name))return null;let n=this.repeatFailureGuard.check(e);return n===null?null:(P(`[repeat-failure-guard #723] refused ${n.tool} after ${n.count} identical failures`),n.result)}observeSuspectedLoop(e){if(this.parentSessionId===void 0)return;this.suspectedLoopWindow===null&&(this.suspectedLoopWindow=um());let n=Js(e),r=pm(this.suspectedLoopWindow,n);r.fired&&$(this.traceWriter,{phase:"suspected_loop",metadata:{tool:e.name,count:r.count,windowSize:ml}})}recordForkReadDenial(e,n,r){if(this.parentSessionId===void 0||!am.has(e.name)||!cm(n))return r;let o=this.denialBreaker??{count:0,deniedPaths:[]};o.count+=1;let s=lm(e);return o.deniedPaths.includes(s)||o.deniedPaths.push(s),this.denialBreaker=o,o.count<5?r:{content:dm(o.deniedPaths,o.count),isError:!0,failureClass:Mn}}resetDenialBreaker(){this.denialBreaker=null}async runCanUseTool(e){if(!this.canUseTool)return null;let n;try{n=await this.canUseTool(e.name,e.input??{},{signal:e.signal,toolUseID:e.id})}catch(r){let o=`Tool "${e.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`;return await this.emitPreToolUseBlock(e.name,o),{content:o,isError:!0,failureClass:"permission-denied"}}if(n.behavior==="deny"){let r=n.message||`Tool "${e.name}" denied by permission policy`;return await this.emitPreToolUseBlock(e.name,r),{content:r,isError:!0,failureClass:"permission-denied"}}return n.updatedInput!==void 0&&(e.input=n.updatedInput),null}async runPreDispatchGates(e){if(this.hookRegistry){let a={event:"PreToolUse",toolName:e.name,input:e.input,...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.resolveBase!==void 0?{cwd:this.resolveBase}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{}};try{await Tf(this.hookRegistry,a,{signal:e.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(c){if(c instanceof q)return this.recordForkReadDenial(e,c.reason,{content:`Tool "${e.name}" blocked by PreToolUse hook${c.reason?`: ${c.reason}`:""}${c.injectContext?`
182
+
183
+ ${c.injectContext}`:""}`,isError:!0,failureClass:"hook-block"});throw c}}let n=Ms(e.name,this.permissions);if(!n.allowed){let a=this.denialReason(e.name,n.reason);return await this.emitPreToolUseBlock(e.name,a),{content:a,isError:!0,failureClass:"permission-denied"}}let r=await this.runCanUseTool(e);if(r)return r;let o=await this.checkReadOnlyBash(e);if(o)return o;let s=this.checkRepeatCircuitBreaker(e);if(s)return s;let i=this.checkRepeatFailureGuard(e);return i||(this.observeSuspectedLoop(e),null)}async execute(e){if(e.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:_e(e.signal)};let n=await this.runPreDispatchGates(e);if(n)return n;let r=await this.executeCore(e);return this.repeatFailureGuard.note(e,r),r.isError!==!0&&this.resetDenialBreaker(),r}async executeBatch(e){if(e.length===0)return[];if(e.length===1)return[await this.execute(e[0])];let n=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){let a=e[i];if(a.signal.aborted){n[i]={content:"Tool call aborted",isError:!0,failureClass:_e(a.signal)},r.add(i);continue}let c=await this.runPreDispatchGates(a);if(c){n[i]=c,r.add(i);continue}}let o=e.map((i,a)=>({call:i,originalIndex:a})).filter((i,a)=>!r.has(a));if(o.length===0)return n;let s=sm(o.map(i=>i.call),this.classifier);for(let i of s){if(i.isConcurrencySafe){let c=[...i.indices];for(;c.length>0;){let l=new Map,d=[],u=[];for(let m of c){let{call:g,originalIndex:y}=o[m],b=this.checkRepeatFailureGuard(g);if(b){n[y]=b;continue}if(hl.has(g.name)){d.push(m);continue}let v=Gr(g),_=gl-this.repeatFailureGuard.streakFor(g),w=l.get(v)??0;w<_?(l.set(v,w+1),d.push(m)):u.push(m)}c=u;let p=d.map(m=>o[m]?.call).filter(m=>m!==void 0&&m.name==="agent");if(p.length>=2&&this.subagentExecutor)try{this.subagentExecutor.notifyWaveStart(p,this.sessionId??"",null)}catch{}let f=await Lr(d,this.maxConcurrentSafeCalls,async m=>{let{call:g,originalIndex:y}=o[m];return g.signal.aborted?{result:{content:"Tool call aborted",isError:!0,failureClass:_e(g.signal)},originalIndex:y}:{result:await this.executeCore(g),originalIndex:y}});for(let m of f)if(m.status==="fulfilled")n[m.value.originalIndex]=m.value.result;else{let g=m.reason instanceof Error?m.reason.message:String(m.reason),y=d[f.indexOf(m)];n[o[y].originalIndex]={content:`Tool execution error: ${g}`,isError:!0}}for(let m of d){let{call:g,originalIndex:y}=o[m],b=n[y];b!==void 0&&b.failureClass!=="abort"&&this.repeatFailureGuard.note(g,b)}if(p.length>=2&&this.subagentExecutor)try{this.subagentExecutor.notifyWaveEnd()}catch{}}}else for(let c of i.indices){let{call:l,originalIndex:d}=o[c];if(l.signal.aborted){n[d]={content:"Tool call aborted",isError:!0,failureClass:_e(l.signal)};continue}let u=this.checkRepeatFailureGuard(l);if(u){n[d]=u;continue}let p=await this.executeCore(l);n[d]=p,this.repeatFailureGuard.note(l,p)}let a=i.indices.length;i.indices.forEach((c,l)=>{let d=n[o[c].originalIndex];d&&(d.batchIndex=l+1,d.batchSize=a)})}return n.some(i=>i!==void 0&&i.isError!==!0)&&this.resetDenialBreaker(),n}async executeCore(e){let n=await this.executeCoreInner(e);return this.applyOutputCap(n)}applyOutputCap(e){let n=this.maxOutputBytes;if(n===void 0)return e;let r=Buffer.byteLength(e.content,"utf8");return r<=n||(e.content=dt(e.content,n),e.truncated=!0,P(`[output-cap #661] fork tool result capped: original=${r}B capped=${Buffer.byteLength(e.content,"utf8")}B (cap=${n}B)`)),e}async executeCoreInner(e){if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let i,a=!1,c="";try{i=await this.subagentExecutor.execute(e)}catch(l){a=!0,c=l instanceof Error?l.message:String(l),i={content:`Agent tool error: ${c}`,isError:!0}}return a?this.firePostToolUseFailure(e.name,c,e.signal,e.input):this.firePostToolUse(e.name,i.content,e.signal,e.input,i),i}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let i,a=!1,c="";try{i=await this.skillExecutor.execute(e)}catch(l){a=!0,c=l instanceof Error?l.message:String(l),i={content:`Skill tool error: ${c}`,isError:!0}}return a?this.firePostToolUseFailure(e.name,c,e.signal,e.input):this.firePostToolUse(e.name,i.content,e.signal,e.input,i),i}if(e.name==="compose"){let i=await this.executeCompose(e);return this.firePostToolUse(e.name,i.content,e.signal,e.input,i),i}let n=this.handlers.get(e.name);if(!n){let i=this.unknownToolMessage(e.name);return await this.emitPreToolUseBlock(e.name,i),{content:i,isError:!0,failureClass:"permission-denied"}}let r,o=!1,s="";try{r=await n(e.input,e.signal,this.callHandlerContext(e))}catch(i){o=!0,s=i instanceof Error?i.message:String(i),r={content:`Tool execution error: ${s}`,isError:!0}}return o?this.firePostToolUseFailure(e.name,s,e.signal,e.input):this.firePostToolUse(e.name,r.content,e.signal,e.input,r),r}async executeCompose(e){if(!this.composeExecutor)return{content:"Compose tool is not available in this session configuration",isError:!0};try{return await this.composeExecutor.execute(e)}catch(n){return{content:`Compose tool error: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}firePostToolUse(e,n,r,o,s){if(!this.hookRegistry)return;let i={event:"PostToolUse",toolName:e,output:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{},...s?.incomplete===!0?{incomplete:!0}:{},...s?.incompleteReason?{incompleteReason:s.incompleteReason}:{}};Ef(this.hookRegistry,i,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(()=>{})}firePostToolUseFailure(e,n,r,o){if(!this.hookRegistry)return;let s={event:"PostToolUseFailure",toolName:e,error:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};Rf(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(i=>{P(`firePostToolUseFailure outer catch (tool=${e}): ${String(i)}`)})}};import{spawn as Zx}from"child_process";import eI from"os";C();D();import{mkdir as nx,writeFile as rx}from"fs/promises";import{dirname as ox,join as sx}from"path";function ix(){return sx(Fe(),"routing-decisions.jsonl")}function ax(t){let e={surface:"afk"};for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}async function Te(t){if(!(h.VITEST||h.NODE_ENV==="test"))try{let e=ix();await nx(ox(e),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,...ax(t)})+`
182
184
  `;await rx(e,r,{flag:"a"})}catch{}}var cx=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,lx=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,dx=/={3,}\s*(?:(\d+)\s+failed,\s*)?(\d+)\s+passed(?:,\s*(\d+)\s+warning)?.*in\s+[\d.]+s\s*={3,}|={3,}\s*(\d+)\s+passed.*in\s+[\d.]+s\s*={3,}/,ux=/(\d+)\s+passing/,px=/(\d+)\s+failing/,fx=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,mx=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,gx=/(\d+) examples?, (\d+) failures?/,hx=/OK \((\d+) tests?/,yx=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/;function bx(t){let e=t.match(cx);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10),o=e[3]!==void 0?parseInt(e[3],10):void 0;return{runner:"vitest",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function wx(t){let e=t.match(lx);if(!e)return null;let n=parseInt(e[1]??"0",10);return{runner:"jest",passed:parseInt(e[2]??"0",10),failed:n}}function Sx(t){let e=t.match(dx);if(!e)return null;if(e[2]!==void 0){let n=parseInt(e[2],10),r=parseInt(e[1]??"0",10);return{runner:"pytest",passed:n,failed:r}}return e[4]!==void 0?{runner:"pytest",passed:parseInt(e[4],10),failed:0}:null}function vx(t){let e=t.match(ux);if(!e)return null;let n=parseInt(e[1]??"0",10),r=t.match(px),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function kx(t){let e=[...t.matchAll(fx)];if(e.length===0)return null;let n=0,r=0;for(let o of e)o[1]==="ok"?n++:o[1]==="FAIL"&&r++;return{runner:"go-test",passed:n,failed:r}}function Ax(t){let e=t.match(mx);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10),o=e[3]!==void 0?parseInt(e[3],10):void 0;return{runner:"cargo",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function _x(t){let e=t.match(gx);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10);return{runner:"rspec",passed:n-r,failed:r}}function Tx(t){let e=t.match(hx);if(e)return{runner:"phpunit",passed:parseInt(e[1]??"0",10),failed:0};let n=t.match(yx);if(n){let r=parseInt(n[1]??"0",10),o=parseInt(n[2]??"0",10);return{runner:"phpunit",passed:r-o,failed:o}}return null}function yl(t){return bx(t)??wx(t)??Sx(t)??vx(t)??kx(t)??Ax(t)??_x(t)??Tx(t)??null}var mm=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,Ex=/[\x00-\x1F\x7F-\x9F]/g;function Ee(t){return t.replace(mm,"").replace(Ex," ").trim()}function Ft(t){return t.replace(mm,"")}import{statSync as Rx}from"node:fs";function qr(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.code==="ENOENT"&&typeof e.syscall=="string"&&e.syscall.startsWith("spawn")}function xx(t){if(t===void 0)return!1;try{return Rx(t),!1}catch{return!0}}function On(t,e){let n=t instanceof Error?t.message:typeof t?.message=="string"?String(t.message):String(t);return qr(t)&&xx(e)?`working directory does not exist: ${e} (deleted worktree?) \u2014 underlying: ${n}`:n}import cn from"path";import{realpathSync as Yx}from"fs";C();import{basename as Gx,dirname as qx,join as Al,relative as Xx,resolve as Ln,sep as Xr}from"path";import{homedir as se}from"os";C();D();import{realpathSync as wm}from"fs";import{dirname as Dx,resolve as sn,join as Sl}from"path";import{homedir as Nt}from"os";var gm=new Set;function Lt(t){let e=t instanceof Error?t.message:String(t);gm.has(e)||(gm.add(e),console.warn(`[afk-home] Malformed AFK home/state env var ignored while deriving the credential floor: ${e}. The relocated tree is NOT protected \u2014 the default ~/.afk entries still apply. Fix the env var to restore coverage.`))}import{statSync as wl}from"node:fs";import{homedir as Ix}from"node:os";import{basename as Cx,dirname as ym,join as Px}from"node:path";var hm,bl=new Map;function bm(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function Mx(t){let e=Cx(t),n=e===e.toLowerCase()?e.toUpperCase():e.toLowerCase();if(n===e)return;let r;try{r=wl(t)}catch{return}let o=bl.get(r.dev);if(o!==void 0)return o;try{let s=wl(Px(ym(t),n)),i=r.dev===s.dev&&r.ino===s.ino;return bl.set(r.dev,i),i}catch(s){let i=bm(s);return i==="ENOENT"||i==="ENOTDIR"?(bl.set(r.dev,!1),!1):void 0}}function Ox(t=Ix()){if(hm!==void 0)return hm;let e=t;for(;;)try{return wl(e),Mx(e)??!0}catch(n){let r=bm(n);if(r!=="ENOENT"&&r!=="ENOTDIR")return!0;let o=ym(e);if(o===e)return!0;e=o}}function Dn(t,e,n=e){if(t===e||t.startsWith(e+"/"))return!0;if(!Ox(n))return!1;let r=t.toLowerCase(),o=e.toLowerCase();return r===o||r.startsWith(o+"/")}var Fx=[`${Nt()}/.ssh`,`${Nt()}/.aws`,`${Nt()}/.gnupg`,`${Nt()}/.config/gcloud`,"/etc","/System","/private/etc","/usr/local/etc",`${Nt()}/.afk/config`,`${Nt()}/.afk/state`,`${Nt()}/.npmrc`,`${Nt()}/.docker/config.json`];function Lx(){let t=[];try{let e=ce();t.push(sn(Sl(e,"config"))),t.push(sn(Sl(e,"state")))}catch(e){Lt(e)}try{t.push(sn(pe()))}catch(e){Lt(e)}return t}var Qs;function Nx(){let t=`${h.AFK_WRITE_DENYLIST??""}\0${h.AFK_HOME??""}\0${h.AFK_STATE_DIR??""}`;if(!Qs||Qs.key!==t){let e=h.AFK_WRITE_DENYLIST,n=e?e.split(":").map(r=>sn(r)).filter(Boolean):[];Qs={key:t,unresolved:[...new Set([...Fx.map(r=>sn(r)),...Lx()]),...n]}}return[...new Set(Qs.unresolved.map(e=>mt(e)))]}function mt(t){let e=sn(t);try{return wm(e)}catch{}let n=[],r=e;for(let o=0;o<64;o++){let s=Dx(r);if(s===r)break;n.unshift(r.slice(s.length+1)),r=s;try{let i=wm(r);return Sl(i,...n)}catch{}}return e}function Zs(t,e="write_file"){let n=mt(sn(t));for(let r of Nx())if(Dn(n,r))throw new Error(`${e}: refusing to write to protected path: ${n} (matches denylist entry: ${r})`)}D();import{isAbsolute as Ux,relative as Bx,sep as $x}from"node:path";import{homedir as vl}from"node:os";function Hx(t,e){let n=Bx(e,t);return n===""||n!==".."&&!n.startsWith(`..${$x}`)&&!Ux(n)}function kl(t,e){return t.filter(n=>!e.some(r=>Hx(n,r)))}function jx(t,e){return t.filter(({source:n})=>n!==e).map(({root:n})=>n)}var Wx={".afk/config/mcp.json":`${vl()}/.afk/config`,".ssh/config":`${vl()}/.ssh`,".ssh/known_hosts":`${vl()}/.ssh`};function Sm(t,e){return t.flatMap(({rel:n,resolved:r})=>kl([r],jx(e,Wx[n])))}import{isAbsolute as m1,resolve as Kx}from"path";import{homedir as vm}from"os";function Fn(t){return t==="~"?vm():t.startsWith("~/")?Kx(vm(),t.slice(2)):t}var Am=[`${se()}/.ssh`,`${se()}/.aws`,`${se()}/.gnupg`,`${se()}/.config/gcloud`,`${se()}/.afk/config`,`${se()}/.npmrc`,`${se()}/.docker/config.json`,`${se()}/.git-credentials`,`${se()}/.netrc`,`${se()}/.config/gh/hosts.yml`,`${se()}/.kube/config`,"/etc/shadow","/etc/sudoers","/private/etc/master.passwd",`${se()}/.password-store`,`${se()}/Library/Application Support/Google/Chrome`,`${se()}/Library/Application Support/Chromium`,`${se()}/Library/Application Support/BraveSoftware`,`${se()}/Library/Application Support/Microsoft Edge`,`${se()}/Library/Application Support/Arc`,`${se()}/Library/Application Support/Firefox`],Vr=[".afk/config/mcp.json",".ssh/config",".ssh/known_hosts"],zx=`${se()}/.afk/config`,E1=Vr.map(t=>`${se()}/${t}`);function _m(t){let e=Ln(t);return Al(mt(qx(e)),Gx(e))}var zr;function Tm(t){return t?t.split(":").map(e=>e.trim()).filter(Boolean).map(e=>e==="~"||e.startsWith("~/")?Fn(e.replace(/^~\/+/,"~/")):e).map(e=>Ln(e)):[]}function Vx(){try{return[mt(Ln(Al(ce(),"config")))]}catch(t){return Lt(t),[]}}var km=".afk/";function Jx(){try{let t=ce();return Vr.filter(e=>e.startsWith(km)).map(e=>_m(Al(t,e.slice(km.length))))}catch(t){return Lt(t),[]}}function Em(){let t=`${h.AFK_READ_DENYLIST??""}\0${h.AFK_HOME??""}`;if(zr&&zr.key===t)return zr;let e=Tm(h.AFK_READ_DENYLIST).map(i=>mt(i)).filter(Boolean),n=Am.map(i=>({source:i,root:mt(Ln(i))})),r=Vx(),o=[...new Set([...n.map(({root:i})=>i),...r])],s=n.filter(({source:i,root:a})=>i!==zx||!r.includes(a)).map(({root:i})=>i);return zr={key:t,builtins:o,extras:e,allow:[...new Set([...Sm(Vr.map(i=>({rel:i,resolved:_m(`${se()}/${i}`)})),n),...kl(Jx(),s)])]},zr}function Rm(){let{builtins:t,extras:e}=Em();return[...t,...e]}function xm(t){let e=mt(Ln(t));return Rm().filter(n=>n!==e&&Dn(n,e,n)).map(n=>(n.startsWith(e+Xr)?Xx(e,n):n.split(Xr).slice(e.split(Xr).length).join(Xr)).split(Xr).join("/"))}function an(t){let e=mt(Ln(t)),{builtins:n,extras:r,allow:o}=Em();for(let s of r)if(Dn(e,s))return{denied:!0,matched:s};if(o.includes(e))return{denied:!1};for(let s of n)if(Dn(e,s))return{denied:!0,matched:s};return{denied:!1}}function Nn(t){try{return Yx.native(t)}catch{let e=cn.dirname(t),n=cn.basename(t);return e===t?t:cn.join(Nn(e),n)}}var Im=new Map;function Qx(t){let e=Im.get(t);if(e!==void 0)return e;let n=Nn(t);return Im.set(t,n),n}function Cm(t,e,n,r){let o=e?.resolveBase??e?.cwd??r,s=cn.isAbsolute(t)?t:cn.resolve(o??process.cwd(),t);if(e?.allowAll===!0)return{restricted:!1,resolved:s,roots:[]};if(o===void 0)return{restricted:!1,resolved:s,roots:[]};let i=Nn(s),a=n==="read"?e?.readRoots??[o]:e?.writeRoots??[o];for(let c of a){let l=Qx(c),d=cn.relative(l,i);if(!d.startsWith("..")&&!cn.isAbsolute(d))return{restricted:!1,resolved:s,roots:a}}return{restricted:!0,resolved:s,roots:a}}function Ce(t,e,n="read",r){let{restricted:o,resolved:s,roots:i}=Cm(t,e,n,r);if(n==="read"){let a=an(s);if(a.denied)throw new Error(`Path \`${t}\` is a protected credential/secret path (read-denylist entry: \`${a.matched}\`) and cannot be read.`)}if(o){let a=i.map(l=>`\`${l}\``).join(", "),c=n==="read"?"read roots":"write roots";throw new Error(`Path \`${t}\` is outside the allowed ${c} [${a}].`)}return s}function Pm(t,e,n="read",r){return Cm(t,e,n,r)}function Mm(t){let e=new Set,n=[];for(let r of t.split(/\s+/)){if(r.length===0)continue;let o=r.replace(/^\d*[<>|&]+/,"").replace(/^['"]/,"").replace(/['";,)]+$/,"");if(o.length===0)continue;let s=o.startsWith("/"),i=o==="~"||o.startsWith("~/");!s&&!i||e.has(o)||(e.add(o),n.push(o))}return n}function tI(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(e.timeout_ms<0||e.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=e.timeout_ms}return{command:e.command,timeout_ms:n}}function ei(t,e){let n=!1,r=!1;function o(){n||t==="bypassPermissions"&&(n=!0,console.warn("[security] bash handler: shell=true with bypassPermissions \u2014 all shell metacharacters are interpreted without confirmation. Migrate to execFile to eliminate this risk (tracked: C4)."))}function s(i,a){if(r)return;let c=a.resolveBase??a.cwd??e,l=eI.homedir(),d=[];for(let u of Mm(i)){let p=u==="~"?l:u.startsWith("~/")?l+u.slice(1):u,f=Pm(p,a,"write",c);f.restricted&&d.push(f.resolved)}d.length!==0&&(r=!0,console.warn(`[security] bash: command references path(s) outside writeRoots: ${d.join(", ")} \u2014 bash containment is best-effort (tracked C4); use file tools for contained writes.`),Te({event:"tool.bash_path_escape",tool:"bash",restricted_count:d.length,mode:"write"}))}return async(i,a,c)=>{let{command:l,timeout_ms:d}=tI(i);if(a.aborted)return{content:"Command aborted",isError:!0};if(o(),c!==void 0)try{s(l,c)}catch{}return new Promise(u=>{let p=!1;function f(k){p||(p=!0,clearTimeout(g),a.removeEventListener("abort",A),u(k))}let m=Zx(l,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...(c?.resolveBase??c?.cwd??e)!==void 0?{cwd:c?.resolveBase??c?.cwd??e}:{},...c?.env!==void 0?{env:{...process.env,...c.env}}:{}});m.unref();let g=setTimeout(()=>{m.pid!==void 0&&process.kill(-m.pid,"SIGKILL"),f({content:`Command timed out after ${d}ms`,isError:!0})},d),y="",b="",v=0,_=!1;function w(k){if(_||p||v<8e6)return;_=!0,console.warn(`[bash] overflow kill: stream=${k} totalBytes=${v} command="${l}"`),Te({event:"tool.overflow_kill",tool:"bash",total_bytes:v,stream:k}),m.kill("SIGKILL");let R=Ft((y+b).trimEnd()),I=yl(R)??void 0,S=dt(R,1e5)+Ls;f({content:S,truncated:!0,...I!==void 0?{testResult:I}:{}})}m.stdout.on("data",k=>{let R=8e6-v,I=k.length<=R?k:k.subarray(0,Math.max(0,R));v+=I.length,y+=I.toString("utf8"),w("stdout")}),m.stderr.on("data",k=>{let R=8e6-v,I=k.length<=R?k:k.subarray(0,Math.max(0,R));v+=I.length,b+=I.toString("utf8"),w("stderr")});let A=()=>{m.pid!==void 0&&process.kill(-m.pid,"SIGKILL"),f({content:"Command aborted",isError:!0})};a.addEventListener("abort",A),a.aborted&&A(),m.on("close",k=>{if(a.aborted){f({content:"Command aborted",isError:!0});return}if(k!==null&&k!==0){let x=Pt(b.trimEnd()||y.trimEnd());f({content:`Command exited with code ${k}${x.content?`
183
185
  `+x.content:""}`,isError:!0,...x.truncated?{truncated:!0}:{}});return}if(_)return;let R=Ft((y+b).trimEnd()),I=yl(R)??void 0,S=Pt(R);f({content:S.content,...S.truncated?{truncated:!0}:{},...I!==void 0?{testResult:I}:{}})}),m.on("error",k=>{let R=c?.resolveBase??c?.cwd??e,I;if(R===void 0&&qr(k))try{let S=process.cwd();I=On(k,S)}catch{I=`working directory does not exist (process cwd deleted \u2014 deleted worktree?) \u2014 underlying: ${k.message}`}else I=On(k,R);f({content:`Failed to execute: ${I}`,isError:!0})})})}}var Om=ei("default");import{promises as nI}from"fs";function Ut(t,e,n="Path"){if(!(t instanceof Error))return;let r=t.code;if(r==="ENOENT")return{content:`${n} not found: ${e}`,isError:!0};if(r==="EACCES")return{content:`Permission denied: ${e}`,isError:!0};if(r==="ENOTDIR")return{content:`Not a directory: ${e}`,isError:!0}}var rI=async(t,e,n,r)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let o=t,s=o.file_path,i=o.offset??1,a=o.limit??2e3;if(typeof s!="string")return{content:"Invalid input: file_path must be a string",isError:!0};if(typeof i!="number"||i<1)return{content:"Invalid input: offset must be a positive number",isError:!0};if(typeof a!="number"||a<1)return{content:"Invalid input: limit must be a positive number",isError:!0};let c;try{c=Ce(s,n,"read",r)}catch(l){return{content:l instanceof Error?l.message:String(l),isError:!0}}try{let l=await nI.readFile(c),d=Math.min(8192,l.length);for(let _=0;_<d;_++)if(l[_]===0)return{content:`File appears to be binary: ${c}`,isError:!0};let u=l.toString("utf-8");if(u.length===0)return{content:""};let p=u.split(`
184
186
  `),f=Math.max(0,i-1),m=Math.min(p.length,f+a),g=p.slice(f,m),y=p.length;if(g.length===0)return{content:`... (offset ${i} is past end of file \u2014 file has ${y} lines)`};let b=String(y).length,v=g.map((_,w)=>{let A=f+w+1;return`${String(A).padStart(b," ")} ${_}`}).join(`