agent-afk 5.89.0 → 5.89.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +4 -4
- package/dist/index.mjs +3 -3
- package/dist/telegram.mjs +3 -3
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var WS=Object.defineProperty;var we=(t,e)=>()=>(t&&(e=t(t=0)),e);var Bd=(t,e)=>{for(var n in e)WS(t,n,{get:e[n],enumerable:!0})};function ho(t){return go.find(e=>e.name===t)}function Ea(t){return process.env[t]!==void 0}var go,b,P=we(()=>{"use strict";go=[{name:"AFK_COMPACT_KEEP_LAST_TURNS",description:"Number of recent turns the compactor keeps verbatim during /compact. Default tuned in compact-handler.ts.",type:"number",required:!1,example:"6",category:"model"},{name:"AFK_COMPACT_MODEL",description:"Override the model used by the /compact summarizer. Falls back to a cheap default (haiku-class).",type:"string",required:!1,example:"claude-haiku-4-5",category:"model"},{name:"AFK_COMPACT_SHRINK_FRACTION",description:"Context-fullness fraction (0\u20131, exclusive) at/above which /compact and auto-compaction relax the keep-window so a short-but-full session (few turns, huge tool exchanges) can still be summarized instead of no-oping on turn count. Default 0.7 (see shared/compaction.ts DEFAULT_COMPACT_SHRINK_THRESHOLD).",type:"number",required:!1,example:"0.8",category:"model"},{name:"AFK_DEFAULT_SUBAGENT_MODEL",description:"Override the default model used when a subagent is dispatched without an explicit model.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_DIAGNOSE_BASELINE",description:"Kill switch for /diagnose reproducer baseline execution. When set to '0', the /diagnose skill skips executing the detected reproducer command for a ground-truth baseline; default enabled (runs). Set to '0' to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_DISABLE_PROMPT_CACHE",description:"Disable Anthropic prompt caching when set to 1/true/yes/on. Unset = caching enabled.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_DISABLE_BASH_INTERPRETER_GUARD",description:"Skip ONLY the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) when set to 1, leaving the rest of path-approval intact. Applies on interactive surfaces (REPL/Telegram), where the denylist is active but your workflow legitimately runs interpreter one-liners. The restricted-root substring check is unaffected. Default: denylist active on interactive surfaces; headless already fails open (opt in with AFK_FORCE_BASH_INTERPRETER_GUARD=1). To disable all of path-approval + bash restriction instead, use AFK_DISABLE_PATH_APPROVAL=1.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_DISABLE_PATH_APPROVAL",description:"Skip the path-approval + bash-restriction hooks entirely when set to 1. Use for headless flows that need wide-open file access (CI scripts, batch jobs). Default: hooks enabled. Note: on headless surfaces (afk chat, daemon) no grant manager is wired, so the interpreter denylist (python -c, node -e, sh -c, ...) fails OPEN by default \u2014 opt headless flows into it with AFK_FORCE_BASH_INTERPRETER_GUARD=1, or set this var to 1 to disable all of path-approval.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_FORCE_BASH_INTERPRETER_GUARD",description:"Apply the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) even on headless surfaces (afk chat, daemon) where no grant manager is wired. By default the denylist fires only on interactive surfaces (REPL/Telegram), failing open on headless so legitimate automation is not hard-blocked with no recourse. Set to 1 to opt headless flows back into the guard. Overridden by AFK_DISABLE_BASH_INTERPRETER_GUARD=1. Default: off (headless fails open).",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_EFFORT",description:"Effort hint guiding adaptive-thinking depth, forwarded as Anthropic output_config.effort (model-gated; ignored where unsupported). Accepts low | medium | high | xhigh | max.",type:"string",required:!1,example:"medium",category:"model"},{name:"AFK_MAX_BUDGET_USD",description:"Cumulative USD budget ceiling for the session. Aborts the turn when the running cost crosses this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_NESTING_DEPTH",description:"Maximum sub-agent/skill nesting depth; 0 disables nested delegation entirely (the agent, skill, AND compose tools all refuse). A top-level session is depth 0, so the default 3 permits three generations of forked descendants (depth 1 \u2192 2 \u2192 3) and refuses the agent and skill tools at depth 3. Resolved once at the root of each session and propagated down through child AgentConfig, so descendants inherit the root value rather than re-reading the environment. Raise with care: depth is a fan-out exponent (a width-N wave at depth D reaches ~N^D concurrent children), so values above 4 invite provider rate-limit (429) cascades. Accepted range 0-6; unset, empty, unparseable, negative, or out-of-range input falls back to the default. An explicit programmatic maxDepth (SubagentExecutorContext / SkillExecutorContext) still wins.",type:"number",required:!1,default:"3",example:"2",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. Falls back to provider default when unset.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Deprecated and inert: not read by the generation path. Use AFK_MAX_OUTPUT_TOKENS (or --max-output-tokens) to cap per-response output tokens; falls back to the model output ceiling when unset.",type:"number",required:!1,default:"4096",example:"8192",category:"model"},{name:"AFK_MAX_TOOL_USE_ITERATIONS",description:"Opt-in ceiling on tool-use rounds per turn for TOP-LEVEL (non-subagent) sessions, on both providers. Mirrors the maxToolUseIterations config key / max_tool_use_iterations tool param. Unset, non-numeric, or <=0 means unlimited (the default \u2014 zero behavior change): a top-level turn ends only when the model stops calling tools, the abort signal fires, the provider errors, or the dollar budget trips. A positive integer N makes top-level turns wind down gracefully after N tool rounds (one tools-stripped final round). An explicit config/CLI value wins over this env default. Does NOT affect subagent forks \u2014 they keep their own non-zero anti-hang default (SUBAGENT_DEFAULT_MAX_TOOL_USE_ITERATIONS) regardless of this var.",type:"number",required:!1,default:"0",example:"150",category:"model"},{name:"AFK_MEMORY_EVIDENCE_GATE",description:'Opt-in (set to 1) evidence gate for durable memory writes. When enabled, a codebase fact (memory_update category "convention") stored without an `evidence` citation is recalled as [unverified], and memory_search results carry a verification verdict. User preferences and agent reflections are never gated. Default off \u2014 memory behaves identically to legacy when unset.',type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_MICROCOMPACT_KEEP_LAST",description:"Number of the most-recent tool_result blocks that tool-result microcompaction keeps intact regardless of size, so the agent does not lose the tool output it is actively reasoning over. Older results are the safe ones to trim. Default 4 (see shared/compaction.ts DEFAULT_MICROCOMPACT_KEEP_LAST). Values <= 0 protect nothing.",type:"number",required:!1,default:"4",example:"3",category:"model"},{name:"AFK_MICROCOMPACT_TOOL_RESULT_BYTES",description:"Byte threshold (tool_result content length) at/above which a tool_result block becomes a microcompaction candidate. When /compact and auto-compaction would otherwise no-op on a short-but-full session, microcompaction clears large/old tool_result CONTENT in place (largest first) \u2014 replacing it with a short placeholder, never removing the block \u2014 to reclaim context deterministically (no LLM call). Blocks below this size are left intact. Default 2048 (see shared/compaction.ts DEFAULT_MICROCOMPACT_TOOL_RESULT_BYTES).",type:"number",required:!1,default:"2048",example:"4096",category:"model"},{name:"AFK_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), fixed-identity aliases (opus, sonnet, haiku, fable), or full model IDs. Migration: AFK_MODEL=sonnet now pins the fixed Sonnet identity rather than following a rebound medium tier.",type:"string",required:!1,default:"medium",example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_TTFB_TIMEOUT_MS",description:"Per-request time-to-first-token timeout (ms) for the anthropic-direct streaming loop. Bounds how long a single model call may stall BEFORE its first streamed CONTENT token (a text/thinking delta or tool_use); the connection-level message_start and keep-alive pings do NOT count. Once a content token streams, the timer is cleared and the rest of the response is governed instead by the progress-aware AFK_MODEL_STALL_TIMEOUT_MS window, so a normal slow call (below the bound) and any actively-streaming extended-thinking response are never aborted. NOTE: a request whose FIRST token takes longer than the bound \u2014 e.g. a very large opus_1m prefill \u2014 is aborted, retried once, then surfaces as an error (raise this value or set 0 for such workloads); this trims the degrading-call tail instead of a silent ~10-min hang on the SDK default. Default 180000 (180s \u2248 2\xD7 the measured p99 ttfb). Set to 0 to disable.",type:"number",required:!1,default:"180000",example:"120000",category:"model"},{name:"AFK_MODEL_STALL_TIMEOUT_MS",description:"Progress-aware POST-first-byte stall window (ms) for the anthropic-direct streaming loop. Bounds how long a stream that has ALREADY produced content may then go completely silent. Every streamed output event resets the window, so this is NOT a total-round cap: a legitimately long, actively-streaming round (large code emission, extended thinking) survives indefinitely, while a stream wedged mid-flight is aborted and surfaces as a real terminal error instead of hanging. Complements AFK_MODEL_TTFB_TIMEOUT_MS, which governs only the window BEFORE the first token; this one takes over after it. Default 1200000 (20min) \u2014 above the 18.5min maximum post-first-byte stream duration observed across 86,076 rounds in 12,381 local traces (p99 122s, p99.9 234s), so no healthy round trips it. Set to 0 to disable (issue #762).",type:"number",required:!1,default:"1200000",example:"600000",category:"model"},{name:"AFK_SUBAGENT_TIMEOUT_MS",description:"Foreground forked-subagent wall-clock budget in ms; 0 disables the cap; explicit per-fork config.timeoutMs and the 60-min background mode still win. Bounds how long a single forked child turn may run before `withTimeout` aborts its controller (cascading through the AbortGraph to descendants) and the parent receives a legible TimeoutError tool_result instead of hanging. Default 2700000 (45 min \u2248 headroom over the longest healthy review/research agent observed in production). Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to opt a whole session back into unbounded child turns. Does NOT affect the background dispatch budget (SUBAGENT_BACKGROUND_TIMEOUT_MS) or a per-fork config.timeoutMs \u2014 both take precedence.",type:"number",required:!1,default:"2700000",example:"3600000",category:"model"},{name:"AFK_SUBAGENT_IDLE_TIMEOUT_MS",description:"Forked-subagent progress-aware idle-watchdog window in ms; 0 disables the watchdog; an explicit per-fork config.idleTimeoutMs still wins. Fires when a forked child produces no observable output event for this window, aborting the same controller the wall-clock timeout targets so partial output is preserved and the run classifies as a failure. This is distinct from AFK_SUBAGENT_TIMEOUT_MS, the blunt wall-clock that bounds total turn time: the idle watchdog is the tighter first-to-fire bound and never fires while the stream is legitimately parked on a provider-communicated backoff (OAuth pause, or a rate-limit event carrying a retry-after), extending the deadline for the pause window instead. Default 480000 (8 min) clears the worst-case transient-429 backoff the watchdog is currently blind to (about 363s) with roughly 2 min of margin, while staying materially tighter than the 45-min wall-clock. Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to disable the idle watchdog for a whole session (the wall-clock still applies). v1 applies to forked sub-agent turns only, not top-level or daemon sessions.",type:"number",required:!1,default:"480000",example:"300000",category:"model"},{name:"AFK_VISION_MODELS",description:'Comma-separated override for image (vision) capability detection on the openai-compatible provider. Each token force-enables a model id by exact or substring match (e.g. "qwen2.5-vl" matches a local VL id); prefix a token with "!" to force-disable. Use to send images to a local vision-language model AFK does not recognise by name, or to blacklist a mis-detected id. Built-in detection already covers gpt-4o/4.1/5.x, o1/o3/o4-mini, Claude, and common VL families.',type:"string",required:!1,example:"qwen2.5-vl,!gpt-4o-mini",category:"model"},{name:"AFK_MODEL_LOCAL",description:'Bind the "local" capability tier (cheapest/fastest, user-configured) to a model id. Overrides afk.config.json models.local. Point at a local Ollama, LM Studio, or any OpenAI-compatible shim.',type:"string",required:!1,example:"llama3.2:3b",category:"model"},{name:"AFK_MODEL_LOCAL_API_KEY",description:'Per-slot API key for the "local" tier. Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LOCAL_BASE_URL",description:'Per-slot endpoint base URL for the "local" tier. Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:11434/v1",category:"model"},{name:"AFK_MODEL_LARGE",description:'Bind the "large" capability tier (most capable) to a model id/alias. Overrides afk.config.json models.large.',type:"string",required:!1,example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-5",category:"model"},{name:"AFK_MODEL_MEDIUM_API_KEY",description:'Per-slot API key for the "medium" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_MEDIUM_BASE_URL",description:'Per-slot endpoint base URL for the "medium" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_SMALL",description:'Bind the "small" capability tier (cheap/fast) to a model id/alias. Overrides afk.config.json models.small.',type:"string",required:!1,example:"gpt-4o-mini",category:"model"},{name:"AFK_MODEL_SMALL_API_KEY",description:'Per-slot API key for the "small" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_SMALL_BASE_URL",description:'Per-slot endpoint base URL for the "small" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_OVERLOAD_PAUSE_MS",description:"Wall-clock ceiling (ms) for the bounded pause after a mid-stream overload (529) exhausts its retry budget. Overrides the per-surface default for ALL surfaces: 0 disables the pause (fail fast). Interactive surfaces (cli/repl/telegram) default to 600000; daemon/cron default to 0 so an always-on runner never silently parks on upstream capacity.",type:"number",required:!1,example:"600000",category:"model"},{name:"AFK_PROMPT_CACHE_TTL",description:"TTL for Anthropic prompt-cache blocks. Accepts 5m or 1h.",type:"string",required:!1,default:"1h",example:"1h",category:"model"},{name:"AFK_SUGGEST_ENABLED",description:"Enable the LLM-backed ghost-text suggestion tier in the interactive REPL. Set to 1/true/yes/on to activate. Off by default.",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_GHOST",description:"Enable REPL ghost-text inline suggestions (Tier-1 history/dropdown + optional Tier-2 LLM). 1 = on (default), 0 = off. Set 0/false/off/no to disable all ghost text. Tier-2 LLM is separately gated by AFK_SUGGEST_ENABLED.",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_MODEL",description:"Override the small model used for REPL ghost-text suggestions. Falls back to AFK_COMPACT_MODEL or haiku-class for anthropic, or the session model for other providers.",type:"string",required:!1,category:"model"},{name:"AFK_TASK_BUDGET",description:"Per-task token budget ceiling. Aborts when cumulative usage would exceed it.",type:"number",required:!1,default:"100000",example:"200000",category:"model"},{name:"AFK_TEMPERATURE",description:"Numeric temperature override for model sampling. Provider default if unset.",type:"number",required:!1,example:"0.7",category:"model"},{name:"AFK_THINKING",description:"Extended-thinking mode. Accepts adaptive | disabled | enabled:<N> | enabled:max. Defaults to the model-appropriate mode when unset (adaptive on current models).",type:"string",required:!1,default:"adaptive",example:"adaptive",category:"model"},{name:"AFK_THINKING_UI",description:"Default thinking-display mode for the interactive REPL: summary | live | digest | off. Display-only \u2014 controls how extended-thinking blocks render, never whether thinking runs (cost/latency unaffected). Overridden per-launch by --thinking-ui and mutable mid-session via /thinking. Precedence: --thinking-ui flag > this env > interactive.thinkingUi config > live. Invalid values are ignored.",type:"string",required:!1,default:"live",example:"digest",category:"misc"},{name:"AFK_TIMEOUT_MS",description:"Per-turn timeout in milliseconds. Provider/SDK default if unset.",type:"number",required:!1,example:"120000",category:"model"},{name:"CLAUDE_MODEL",description:"Legacy alias for AFK_MODEL \u2014 supported for back-compat with pre-AFK_* deployments.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_SYSTEM_PROMPT",description:'Raw operator-overlay prompt. Highest-priority overlay (over afk.config.json and AFK.md). Appended on top of the framework base (prompts/system-prompt.md) under an "# Operator configuration" header \u2014 it augments, never replaces, the base.',type:"string",required:!1,example:"You are a helpful agent.",category:"model"},{name:"AFK_DUMP_PROMPT",description:"Write the resolved system prompt to a file at startup. Accepts a path or 1 for default location.",type:"string",required:!1,example:"/tmp/afk-prompt.txt",category:"debug"},{name:"ANTHROPIC_API_KEY",description:"Anthropic API key. Tier-1 credential \u2014 overrides keychain OAuth and CLAUDE_CODE_OAUTH_TOKEN.",type:"string",required:!1,category:"auth",secret:!0},{name:"CLAUDE_CODE_OAUTH_TOKEN",description:"Claude Code OAuth token. Tier-2 credential \u2014 used when ANTHROPIC_API_KEY is unset; falls back to keychain.",type:"string",required:!1,category:"auth",secret:!0},{name:"OPENAI_API_KEY",description:"OpenAI API key for the openai-compatible provider (gpt-*, o1*, o3*, o4* models).",type:"string",required:!1,category:"auth",secret:!0},{name:"CODEX_API_KEY",description:"Fallback OpenAI API key for the openai-compatible provider, read after OPENAI_API_KEY. Legacy name from the removed @openai/codex-sdk integration \u2014 prefer OPENAI_API_KEY.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_LOCAL_API_KEY",description:"Placeholder API key for local Anthropic-compatible servers (vllm-mlx, etc.). Set when AFK_LOCAL_BASE_URL is configured.",type:"string",required:!1,default:"local",example:"local",category:"auth",secret:!0},{name:"AFK_LOCAL_BASE_URL",description:"Base URL for a self-hosted Anthropic-compatible server. When set, routes traffic away from api.anthropic.com.",type:"string",required:!1,example:"http://127.0.0.1:8080",category:"model"},{name:"AFK_OPENAI_BASE_URL",description:"Base URL override for the OpenAI-compatible provider. Used for local shims (mlx_lm.server, Ollama, vLLM, LM Studio). The OpenAI SDK appends `/chat/completions` itself \u2014 a value ending in `/chat/completions` will be stripped at config-load time with a one-shot warning.",type:"string",required:!1,example:"http://127.0.0.1:8000/v1",category:"model"},{name:"AFK_OPENAI_USE_RESPONSES",description:"Opt the OpenAI-compatible provider into the OpenAI Responses API instead of Chat Completions for API-key sessions. Truthy values: 1, true, yes, on. The ChatGPT-subscription OAuth path uses Responses automatically regardless of this flag.",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_OPENAI_CHATGPT_OAUTH",description:"Opt into using ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. Off by default. READ-ONLY: AFK never refreshes these tokens \u2014 re-run `codex` when the access token expires. Routes requests over the Responses API to the private ChatGPT backend (chatgpt.com/backend-api).",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_PROVIDER",description:"Force provider selection (anthropic | anthropic-direct | openai | openai-compatible | openai-codex). Overrides the model-name heuristic. Same surface as the --provider CLI flag; CLI flag wins when both are set.",type:"string",required:!1,example:"openai-compatible",category:"model"},{name:"EXA_API_KEY",description:"Exa (exa.ai) search API key, enabling web_scrape search mode. Free tier (20k requests/month) available at https://exa.ai. When unset, search mode returns an actionable error; markdown and raw modes are unaffected.",type:"string",required:!1,category:"auth",secret:!0},{name:"TELEGRAM_BOT_TOKEN",description:"Telegram bot token from @BotFather. Required to run the Telegram bot surface.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_BOT_TOKEN",description:"Alternative env var name for the Telegram bot token, accepted by the setup wizard.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_ALLOWED_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs allowed to interact with the bot. Required when the bot is running.",type:"string",required:!1,example:"123456789,987654321",category:"telegram"},{name:"AFK_TELEGRAM_TAG_ONLY_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs where the bot answers only when addressed (a reply to the bot, an @mention of the bot, or a text_mention resolving to the bot). Slash-commands are unaffected; chats not listed behave as usual. The afk.config.json telegram.tagOnlyChats block takes precedence. Requires Telegram privacy mode OFF (BotFather /setprivacy Disable) for non-addressed group messages to reach the bot.",type:"string",required:!1,example:"-100987654321,123456789",category:"telegram"},{name:"AFK_TELEGRAM_PRIMARY_CHAT_ID",description:"Default chat ID for outbound notifications (primary-mode routing). When unset, notifications go to the first private/DM chat in AFK_TELEGRAM_ALLOWED_CHAT_IDS. The afk.config.json telegram.notify block takes precedence.",type:"string",required:!1,example:"123456789",category:"telegram"},{name:"AFK_TELEGRAM_NOTIFY_MODE",description:"Outbound notification fan-out: primary (default \u2014 one chat), broadcast (every allowed chat), or custom (afk.config.json telegram.notify.targets). The afk.config.json telegram.notify.mode takes precedence.",type:"string",required:!1,example:"broadcast",category:"telegram"},{name:"TELEGRAM_DATA_DIR",description:"Override the directory where Telegram bot state is stored. Defaults to ~/.afk/state/telegram/.",type:"string",required:!1,category:"telegram"},{name:"TELEGRAM_VERBOSE",description:"Set to a truthy value ('1'/'true'/'yes'/'on', case-insensitive) to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"true",category:"telegram"},{name:"AFK_TELEGRAM_TRACE",description:"Set to 1 to dump raw bridge traffic between the agent and the Telegram bot \u2014 debugging only.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_TELEGRAM_CWD",description:"Override the working directory used by the Telegram bot when spawning agent sessions.",type:"string",required:!1,category:"telegram"},{name:"AFK_HOME",description:"Override the AFK home directory. Default: ~/.afk/.",type:"string",required:!1,default:"~/.afk",example:"/opt/afk",category:"paths"},{name:"AFK_STATE_DIR",description:"Override the entire AFK state tier (sessions/, todos/, transcripts/, memory/, daemon/, etc.), not just one subdirectory. Must be an absolute path (not /). Default: $AFK_HOME/state/.",type:"string",required:!1,category:"paths"},{name:"AFK_FRAMEWORK_DIR",description:"Override the AFK agent-framework directory used for telemetry and briefs. Default: $AFK_HOME/agent-framework/.",type:"string",required:!1,category:"paths"},{name:"AFK_COMPANION_PRIMER",description:'Opt-in: absolute path to a single companion-primer file. When set, its content is bounded (capped, fenced as <companion-primer>) and appended to the system prompt at session start for top-level sessions (chat/REPL/telegram/daemon), as lower-authority "reflections, not facts" context. Unset (default) = no-op. Only the one named file is ever read \u2014 never a directory or repo walk.',type:"string",required:!1,example:"/Users/me/Projects/afk-companion/PRIMER.md",category:"paths"},{name:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_ON_EXIT",description:"Clean-worktree quit policy for interactive --worktree sessions: ask, keep, or remove.",type:"string",required:!1,example:"ask",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Opt-in to loading + spawning MCP servers declared in <cwd>/.mcp.json. Fail-closed: when unset (or 0), project-local servers are NOT spawned; set to a truthy value (1/true/yes/on) to load them. A project-local .mcp.json spawns arbitrary commands on session start, so it is off by default to prevent code execution when entering an untrusted repo (issue #571). Skipped servers are listed in a startup warning with the opt-in instruction.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BG_AUTO_DELIVER",description:"Auto-deliver background subagent results into the model context on the next user turn (interactive REPL). On by default. Set to 0, false, off, or no (case-insensitive) to disable, restoring the manual /bgsub:join retrieval flow.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_PLAIN_OUTPUT",description:"Force the interactive REPL to fully behave like a non-TTY surface for rendering purposes, even when stdout/stdin ARE a TTY: append-only plain-stdout output instead of the TerminalCompositor live overlay (both the persistent between-turn compositor AND the per-turn StreamRenderer overlay), AND the input surface downgrades to the simple non-TTY line reader instead of the fancy compositor-backed input box. Same code path already used for non-TTY surfaces (pipes, CI). Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM scroll regions misbehave \u2014 trades the live overlay and fancy input UX for reliability. Opt-in \u2014 default TTY behavior (live overlay + fancy input) is unchanged unless this var is set. Truthy values: 1, true (case-insensitive).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_GOBLIN_SPINNER",description:"Goblin-themed working spinner (olive frames + goblin verbs) while the agent runs tools. 1 = on (default), 0 = classic dim spinner.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_TERM_TITLE",description:'Set the terminal/tab title (OSC 2) to reflect afk state \u2014 "afk \u2014 <cwd> \xB7 running" during a turn, "afk \u2014 <cwd>" when idle, cleared on exit. 1 = on (default when stdout is a TTY), 0 = leave the title alone. TTY-only.',type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_NOTIFY",description:"Emit a desktop completion notification (OSC 9) on turn completion, for terminals that map OSC 9 to system notifications (iTerm2, kitty, WezTerm). Opt-in and off by default (intrusive). 1 = on. TTY-only.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_THEME",description:"TUI color palette for the interactive REPL and all CLI rendering: dark | light | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark. Overridden per-launch by --theme and mutable mid-session via /theme. Precedence: --theme flag > this env > config theme > auto-detect > dark. Invalid values are ignored (dark).",type:"string",required:!1,default:"dark",example:"light",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_CAPTURE_SUBAGENT_PROMPTS",description:"Opt-in: when set to 1, every prompt a parent session sends to a subagent is written as a redacted markdown file under state/witness/<label>/prompts/. Off by default because nothing prunes the witness tree and prompts may carry secrets the regex redactor cannot catch (connection strings, PEM blocks, PII).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless on every AFK surface \u2014 the CLI entrypoint reports surface `afk`, which is in the headless set \u2014 so watching the agent work in a visible window is opt-in via `AFK_BROWSER_HEADLESS=0`, not implied by running the REPL. Note headed and headless use different chromium downloads (`chromium-*` vs `chromium_headless_shell-*`).",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_ALLOWED_DOMAINS",description:"Comma-separated allowlist of URL host globs. When set, browser_open and any navigation that targets a host outside the list returns status: blocked_by_policy. Unset means no allowlist (permissive). Patterns use simple `*` glob matching against the URL host. Combines with AFK_BROWSER_BLOCKED_DOMAINS \u2014 block wins.",type:"string",required:!1,example:"github.com,*.atlassian.net",category:"browser"},{name:"AFK_BROWSER_BLOCKED_DOMAINS",description:"Comma-separated blocklist of URL host globs. Browser navigation that matches any entry returns status: blocked_by_policy regardless of the allowlist.",type:"string",required:!1,example:"*.ads.example.com",category:"browser"},{name:"AFK_BROWSER_DOM_SNAPSHOTS",description:"Phase 2 opt-in: when set to 1, every browser_act writes a gzipped DOM snapshot sidecar under ~/.afk/state/witness/<sid>/browser/dom-snapshots/. Off by default because snapshots are large; useful for post-mortem analysis of failed actions.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_BACKEND",description:"Select the browser provider backend. Phase 1 supports only `playwright`. Reserved for future `cdp` / `mcp` adapters. Unset defaults to `playwright`.",type:"string",required:!1,example:"playwright",category:"browser"},{name:"AFK_BROWSER_CONFIG",description:"Absolute path to an alternate browser config file. Overrides the default ~/.afk/config/browser.json lookup. Useful for per-project overrides in CI.",type:"string",required:!1,example:"/path/to/browser.json",category:"browser"},{name:"AFK_BROWSER_DEFAULT_PROFILE",description:"Name of the persistent session-vault profile the agent reuses for browser sessions. The context restores its login from (and saves it back to) ~/.afk/state/browser/<profile>/storageState.json, so a human runs `afk browser login --profile <name>` once and the agent reuses that authenticated session across unattended runs. Unset defaults to `default` (a fresh, empty profile \u2014 identical to pre-vault behavior). Allowed charset: [A-Za-z0-9_-], max 128 chars.",type:"string",required:!1,example:"work",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_READ_DENYLIST",description:"Colon-separated list of additional absolute paths the read_file/grep/glob/list_directory tools refuse to read, and that the bash-restriction hook refuses to let a shell command reference on interactive surfaces (REPL, Telegram) \u2014 on headless surfaces (afk chat, daemon) bash fails open regardless of this list. A leading ~/ is expanded (~user/ is not \u2014 spell those absolutely). Built-in credential entries (~/.ssh, ~/.aws, ~/.afk/config, \u2026) always apply on top and cannot be removed. One built-in exception exists: ~/.afk/config/mcp.json (the MCP registry) IS readable \u2014 paths listed here outrank that carve-out, so set this to ~/.afk/config/mcp.json if your registry holds inline secrets rather than ${VAR} placeholders.",type:"string",required:!1,example:"/Users/me/project/.env:/Users/me/secrets",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_WEB_ALLOW_PRIVATE_HOSTS",description:"Opt out of the web_scrape SSRF egress guard. When unset (default) the guard is ACTIVE: the markdown, raw, and headless-render paths refuse loopback (127/8, ::1), link-local (169.254/16 \u2014 including the 169.254.169.254 cloud instance-metadata endpoint), RFC1918 (10/8, 172.16/12, 192.168/16), carrier-grade NAT (100.64/10), IPv6 unique-local (fc00::/7), 0.0.0.0/8, and the IPv4-mapped/compatible IPv6 forms of all of those. Hostnames are resolved and the RESOLVED addresses are classified (DNS-rebinding guard), and the check is re-applied on every redirect hop. Set to 1/true to allow private-host access \u2014 needed only to scrape a local dev server. Enabling it restores a model-reachable SSRF path (issue #575).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"VISUAL",description:"Standard POSIX env var naming the user's preferred full-screen editor (with optional flags). Consulted FIRST by the /editor slash command (and its key chord) to compose a long prompt externally; takes precedence over EDITOR. No fallback editor is assumed \u2014 if neither VISUAL nor EDITOR is set, /editor prints a hint instead of guessing.",type:"string",required:!1,example:"nvim",category:"process"},{name:"EDITOR",description:"Standard POSIX env var naming the user's preferred editor (with optional flags). Consulted by the /editor slash command AFTER VISUAL, as the standard fallback. No default editor is assumed when both are unset \u2014 /editor prints a hint telling the user to set one.",type:"string",required:!1,example:"vim",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],b={get AFK_COMPACT_KEEP_LAST_TURNS(){return process.env.AFK_COMPACT_KEEP_LAST_TURNS},get AFK_COMPACT_MODEL(){return process.env.AFK_COMPACT_MODEL},get AFK_COMPACT_SHRINK_FRACTION(){return process.env.AFK_COMPACT_SHRINK_FRACTION},get AFK_COMPANION_PRIMER(){return process.env.AFK_COMPANION_PRIMER},get AFK_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_NESTING_DEPTH(){return process.env.AFK_MAX_NESTING_DEPTH},get AFK_MAX_OUTPUT_TOKENS(){return process.env.AFK_MAX_OUTPUT_TOKENS},get AFK_MAX_TOKENS(){return process.env.AFK_MAX_TOKENS},get AFK_MAX_TOOL_USE_ITERATIONS(){return process.env.AFK_MAX_TOOL_USE_ITERATIONS},get AFK_MEMORY_EVIDENCE_GATE(){return process.env.AFK_MEMORY_EVIDENCE_GATE},get AFK_MICROCOMPACT_KEEP_LAST(){return process.env.AFK_MICROCOMPACT_KEEP_LAST},get AFK_MICROCOMPACT_TOOL_RESULT_BYTES(){return process.env.AFK_MICROCOMPACT_TOOL_RESULT_BYTES},get AFK_MODEL(){return process.env.AFK_MODEL},get AFK_MODEL_TTFB_TIMEOUT_MS(){return process.env.AFK_MODEL_TTFB_TIMEOUT_MS},get AFK_MODEL_STALL_TIMEOUT_MS(){return process.env.AFK_MODEL_STALL_TIMEOUT_MS},get AFK_MODEL_LARGE(){return process.env.AFK_MODEL_LARGE},get AFK_MODEL_LARGE_API_KEY(){return process.env.AFK_MODEL_LARGE_API_KEY},get AFK_MODEL_LARGE_BASE_URL(){return process.env.AFK_MODEL_LARGE_BASE_URL},get AFK_MODEL_LOCAL(){return process.env.AFK_MODEL_LOCAL},get AFK_MODEL_LOCAL_API_KEY(){return process.env.AFK_MODEL_LOCAL_API_KEY},get AFK_MODEL_LOCAL_BASE_URL(){return process.env.AFK_MODEL_LOCAL_BASE_URL},get AFK_MODEL_MEDIUM(){return process.env.AFK_MODEL_MEDIUM},get AFK_MODEL_MEDIUM_API_KEY(){return process.env.AFK_MODEL_MEDIUM_API_KEY},get AFK_MODEL_MEDIUM_BASE_URL(){return process.env.AFK_MODEL_MEDIUM_BASE_URL},get AFK_MODEL_SMALL(){return process.env.AFK_MODEL_SMALL},get AFK_MODEL_SMALL_API_KEY(){return process.env.AFK_MODEL_SMALL_API_KEY},get AFK_MODEL_SMALL_BASE_URL(){return process.env.AFK_MODEL_SMALL_BASE_URL},get AFK_VISION_MODELS(){return process.env.AFK_VISION_MODELS},get AFK_OVERLOAD_PAUSE_MS(){return process.env.AFK_OVERLOAD_PAUSE_MS},get AFK_PROMPT_CACHE_TTL(){return process.env.AFK_PROMPT_CACHE_TTL},get AFK_SUGGEST_ENABLED(){return process.env.AFK_SUGGEST_ENABLED},get AFK_SUGGEST_GHOST(){return process.env.AFK_SUGGEST_GHOST},get AFK_SUGGEST_MODEL(){return process.env.AFK_SUGGEST_MODEL},get AFK_SUBAGENT_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_TIMEOUT_MS},get AFK_SUBAGENT_IDLE_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_IDLE_TIMEOUT_MS},get AFK_TASK_BUDGET(){return process.env.AFK_TASK_BUDGET},get AFK_TEMPERATURE(){return process.env.AFK_TEMPERATURE},get AFK_THINKING(){return process.env.AFK_THINKING},get AFK_THINKING_UI(){return process.env.AFK_THINKING_UI},get AFK_TIMEOUT_MS(){return process.env.AFK_TIMEOUT_MS},get CLAUDE_MODEL(){return process.env.CLAUDE_MODEL},get AFK_SYSTEM_PROMPT(){return process.env.AFK_SYSTEM_PROMPT},get AFK_DUMP_PROMPT(){return process.env.AFK_DUMP_PROMPT},get ANTHROPIC_API_KEY(){return process.env.ANTHROPIC_API_KEY},get CLAUDE_CODE_OAUTH_TOKEN(){return process.env.CLAUDE_CODE_OAUTH_TOKEN},get OPENAI_API_KEY(){return process.env.OPENAI_API_KEY},get CODEX_API_KEY(){return process.env.CODEX_API_KEY},get AFK_LOCAL_API_KEY(){return process.env.AFK_LOCAL_API_KEY},get AFK_LOCAL_BASE_URL(){return process.env.AFK_LOCAL_BASE_URL},get AFK_OPENAI_BASE_URL(){return process.env.AFK_OPENAI_BASE_URL},get AFK_OPENAI_USE_RESPONSES(){return process.env.AFK_OPENAI_USE_RESPONSES},get AFK_OPENAI_CHATGPT_OAUTH(){return process.env.AFK_OPENAI_CHATGPT_OAUTH},get AFK_PROVIDER(){return process.env.AFK_PROVIDER},get EXA_API_KEY(){return process.env.EXA_API_KEY},get TELEGRAM_BOT_TOKEN(){return process.env.TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_BOT_TOKEN(){return process.env.AFK_TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_ALLOWED_CHAT_IDS(){return process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS},get AFK_TELEGRAM_TAG_ONLY_CHAT_IDS(){return process.env.AFK_TELEGRAM_TAG_ONLY_CHAT_IDS},get AFK_TELEGRAM_PRIMARY_CHAT_ID(){return process.env.AFK_TELEGRAM_PRIMARY_CHAT_ID},get AFK_TELEGRAM_NOTIFY_MODE(){return process.env.AFK_TELEGRAM_NOTIFY_MODE},get TELEGRAM_DATA_DIR(){return process.env.TELEGRAM_DATA_DIR},get TELEGRAM_VERBOSE(){return process.env.TELEGRAM_VERBOSE},get AFK_TELEGRAM_TRACE(){return process.env.AFK_TELEGRAM_TRACE},get AFK_TELEGRAM_CWD(){return process.env.AFK_TELEGRAM_CWD},get AFK_HOME(){return process.env.AFK_HOME},get AFK_STATE_DIR(){return process.env.AFK_STATE_DIR},get AFK_FRAMEWORK_DIR(){return process.env.AFK_FRAMEWORK_DIR},get HOME(){return process.env.HOME},get PATH(){return process.env.PATH},get AFK_DAEMON_CWD(){return process.env.AFK_DAEMON_CWD},get AFK_DAEMON_TASK(){return process.env.AFK_DAEMON_TASK},get AFK_DAEMON_TASK_ID(){return process.env.AFK_DAEMON_TASK_ID},get AFK_DAEMON_HOST(){return process.env.AFK_DAEMON_HOST},get AFK_SESSIONSTART_COOLDOWN_MS(){return process.env.AFK_SESSIONSTART_COOLDOWN_MS},get AFK_WORKTREE_AUTONAME(){return process.env.AFK_WORKTREE_AUTONAME},get AFK_WORKTREE_BRANCH_PREFIX(){return process.env.AFK_WORKTREE_BRANCH_PREFIX},get AFK_WORKTREE_BASE(){return process.env.AFK_WORKTREE_BASE},get AFK_WORKTREE_ON_EXIT(){return process.env.AFK_WORKTREE_ON_EXIT},get AFK_WORKTREE_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BG_AUTO_DELIVER(){return process.env.AFK_BG_AUTO_DELIVER},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_PLAIN_OUTPUT(){return process.env.AFK_PLAIN_OUTPUT},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},get AFK_GOBLIN_SPINNER(){return process.env.AFK_GOBLIN_SPINNER},get AFK_TERM_TITLE(){return process.env.AFK_TERM_TITLE},get AFK_NOTIFY(){return process.env.AFK_NOTIFY},get AFK_SHOW_DIFFS(){return process.env.AFK_SHOW_DIFFS},get AFK_SKILL_STREAM_VERBOSE(){return process.env.AFK_SKILL_STREAM_VERBOSE},get FORCE_COLOR(){return process.env.FORCE_COLOR},get NO_COLOR(){return process.env.NO_COLOR},get AFK_THEME(){return process.env.AFK_THEME},get COLORFGBG(){return process.env.COLORFGBG},get AFK_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get AFK_CAPTURE_SUBAGENT_PROMPTS(){return process.env.AFK_CAPTURE_SUBAGENT_PROMPTS},get DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_BROWSER_DEFAULT_PROFILE(){return process.env.AFK_BROWSER_DEFAULT_PROFILE},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_READ_DENYLIST(){return process.env.AFK_READ_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_WEB_ALLOW_PRIVATE_HOSTS(){return process.env.AFK_WEB_ALLOW_PRIVATE_HOSTS},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get VISUAL(){return process.env.VISUAL},get EDITOR(){return process.env.EDITOR},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let e of go){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(b,e.name);n&&Object.defineProperty(b,e.name,{...n,enumerable:!1})}})()});function KS(){return b.AFK_DEBUG==="1"||b.DEBUG==="1"}function T(...t){KS()&&console.log(...t)}var Z=we(()=>{"use strict";P()});import{existsSync as Hd,mkdirSync as GS,renameSync as qS,cpSync as zS,rmSync as JS}from"fs";import{join as j,dirname as Aa,basename as VS,isAbsolute as _a}from"path";import{homedir as Wd}from"os";import{fileURLToPath as YS}from"url";function oe(){let t=b.AFK_HOME;if(t!==void 0&&t!==""){if(!_a(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return j(Wd(),".afk")}function Te(){let t=b.AFK_FRAMEWORK_DIR;if(t!==void 0&&t!==""){if(!_a(t)||t==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${t}`);return t}return j(oe(),"agent-framework")}function yo(){return j(Te(),"forge-telemetry.jsonl")}function Kd(){return j(Te(),"briefs")}function Gd(){return j(Te(),"facets")}function Un(){return j(oe(),"skills")}function Xt(){return j(oe(),"plugins")}function qd(t=process.cwd()){return j(t,".afk")}function zd(t=process.cwd()){return j(qd(t),"skills")}function Jd(t=process.cwd()){return j(qd(t),"plugins")}function Vd(t=process.cwd()){return j(t,".afk","plans")}function bo(){return j(Xt(),".index.json")}function Ta(){return j($n(),"schedules.json")}function Yd(){let t=YS(import.meta.url),e=Aa(t);return j(e,"bundled-plugins")}function $n(){return j(oe(),"config")}function fe(){let t=b.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!_a(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return j(oe(),"state")}function Se(){return j(fe(),"sessions")}function wo(){return j(fe(),"presence")}function So(){return j(fe(),"memory")}function vo(){return j(fe(),"session-grants.jsonl")}function Xd(){return j(oe(),"farms")}function Qd(t){return j(Xd(),t)}function ko(t){if(!XS.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function xa(t){return ko(t),j(fe(),"witness",t)}function Zd(t){return j(xa(t),"prompts")}function Eo(t){return!t||t.startsWith("in-memory:")?null:VS(Aa(t))}function eu(t="default"){return j(fe(),"daemon",`agent-afk@${t}`)}function tu(){return j(fe(),"worktree-sweep.lock")}function Ao(){return j(fe(),"worktree-roots.json")}function Ra(){return j($n(),"afk.env")}function Qt(){return j($n(),"afk.config.json")}function _o(){return j(Wd(),".afk.config.json")}function QS(){return j(oe(),"sessions")}function ZS(t,e){if(t!==e&&Hd(t)&&!Hd(e))try{GS(Aa(e),{recursive:!0});try{qS(t,e)}catch(n){if(n.code==="EXDEV")try{zS(t,e,{recursive:!0}),JS(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
|
|
2
2
|
`)}}}catch{}}function nu(){ZS(QS(),Se())}function Ca(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>jd)throw new Error(`Invalid browser profile: exceeds ${jd} chars`);if(!ev.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function tv(){return j(fe(),"browser")}function nv(t){return Ca(t),j(tv(),t)}function Ia(t){return j(nv(t),"storageState.json")}function Bn(t){return typeof t=="string"&&t.length>0&&t.length<=ov&&rv.test(t)}function Hn(t){if(!Bn(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return j(Se(),t)}function To(t){return j(Hn(t),"events.jsonl")}function ru(t){return j(Hn(t),"session.key")}var XS,ev,jd,rv,ov,L=we(()=>{"use strict";P();XS=/^[a-zA-Z0-9_-]+$/;ev=/^[A-Za-z0-9_-]+$/,jd=128;rv=/^[A-Za-z0-9_-]+$/,ov=128});import{readFileSync as jT}from"node:fs";import{join as WT}from"path";function KT(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Vf(t,e){return KT(e).test(t)}function zT(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(GT.has(e))return!0;if(qT.has(e))return!1}return!1}function Yf(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function JT(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function Xf(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Ca(e),e}function VT(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function YT(t){try{return jT(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function XT(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=Xf(e.defaultProfile)),n}function Qf(t){let e=t?.env??b,n=t?.readFileSync??YT,r=t?.surface??e.AGENT_SURFACE,o=zT(e.AFK_BROWSER_HEADLESS,r),s=Yf(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Yf(e.AFK_BROWSER_BLOCKED_DOMAINS),a=VT(e.AFK_BROWSER_DOM_SNAPSHOTS),l=JT(e.AFK_BROWSER_BACKEND),c=Xf(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():WT($n(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(h){throw new Error(`Failed to parse browser config at ${p}: ${String(h)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=XT(d,m);return g.configPath=p,g}function vs(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(Vf(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Vf(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var GT,qT,ks=we(()=>{"use strict";P();L();GT=new Set(["daemon","subagent","telegram","afk"]),qT=new Set(["repl","interactive","cli"])});import{existsSync as QT,readFileSync as ZT}from"node:fs";import{createRequire as ex}from"node:module";import{dirname as tx,join as nx}from"node:path";function tm(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<ox&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function be(t){let e=tm(t);return em.some(n=>e.includes(n))}function sx(){try{let e=ex(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(ZT(e,"utf8"));if(typeof n!="object"||n===null)return;let r=n.bin,o=typeof r=="string"?r:typeof r=="object"&&r!==null?r.playwright:void 0;if(typeof o!="string"||o.length===0)return;let s=nx(tx(e),o);return QT(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function vr(){return Zf??=sx()??rx,Zf}function Bl(t){return t.includes("install chromium")}function Oe(t,e){let n=tm(t),r=e?.latched===!0?` ${ix}`:"";if(n.includes("Executable doesn't exist")){let o="";return e?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":e?.headless===!1&&(o=" This launch was headed, which needs the full `chromium-*` build \u2014 the headless shell alone does not satisfy it."),`browser tools require the Playwright chromium binary. Install via: ${vr()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${vr()}). Or pick a different tool.${r}`}function Hl(t,e,n=!1){if(!be(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
3
3
|
|
|
4
|
-
${Oe(t,{headless:e,latched:n})}`,{cause:t})}var em,rx,ox,Zf,ix,jl=we(()=>{"use strict";em=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],rx="pnpm exec playwright install chromium",ox=4;ix="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Ht from"node:fs";import Es from"node:path";import{randomBytes as ax}from"node:crypto";import{chromium as lx}from"playwright";function cx(){try{return"5.89.0"}catch{}try{let t=Es.resolve(import.meta.dirname,"../../../package.json"),e=Ht.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var dx,As,nm=we(()=>{"use strict";jl();L();Z();dx=cx(),As=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=lx.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Hl(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){s=l,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let c=await a.content();if(s!==void 0)throw s;let d=a.url(),u=l!==null?l.status():null;return{html:c,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${dx}`}}loadStorageState(e){let n=Ia(e);try{if(!Ht.existsSync(n))return;let r=JSON.parse(Ht.readFileSync(n,"utf8"));return T("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){T("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Ia(e);if(!Ht.existsSync(r))return;let o=await n.storageState(),s=Es.join(Es.dirname(r),`.${Es.basename(r)}.${process.pid}.${ax(4).toString("hex")}.tmp`);Ht.writeFileSync(s,JSON.stringify(o),{mode:384}),Ht.chmodSync(s,384),Ht.renameSync(s,r),T("[browser/vault] saved session",{profile:e,file:r})}catch(r){T("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as ux}from"crypto";function rm(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&px.test(t.label))}function om(t){return ux("sha256").update(t,"utf8").digest("hex").slice(0,8)}function sm(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var px,_s=we(()=>{"use strict";px=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as fx}from"node:crypto";function mx(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function gx(t,e,n){return`el_${fx("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function hx(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function im(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function lm(t,e){let n=t.role??"",r=t.name??"";am.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])lm(s,e)}async function yx(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},cm).catch(()=>[])}async function bx(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},cm).catch(()=>[])}function wx(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Ts(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=wx(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=yx(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,y=!1;u!==null?(h=[],lm(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await bx(t)).filter(W=>am.has(W.role??"")));let w=new Map;for(let _ of p){let W=im(_.name),te=w.get(W);(!te||te.bbox.w===0&&_.bbox.w>0)&&w.set(W,_)}let k=h.map(_=>({ax:_,dom:w.get(im(_.name??""))})),S=r?k:k.filter(_=>_.dom?_.dom.bbox.w>0||_.dom.bbox.h>0:!0);S.sort((_,W)=>{let te=_.dom?.bbox.y??0,D=W.dom?.bbox.y??0;if(te!==D)return te-D;let B=_.dom?.bbox.x??0,M=W.dom?.bbox.x??0;return B-M}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=S.slice(0,n).map((_,W)=>{let te=_.ax.role??"generic",D=_.ax.name??"",B=gx(te,D,W),M=_.dom?.bbox??{x:0,y:0,w:0,h:0},I=_.dom?.type??null,K=null;_.ax.value!==void 0&&_.ax.value!==null&&(K=String(_.ax.value)),_.ax.checked!==void 0&&(K=String(_.ax.checked)),rm({role:te,kind:I})&&(K="[redacted]");let N={disabled:_.ax.disabled??!1};_.ax.checked!==void 0&&(N.checked=_.ax.checked===!0||_.ax.checked==="mixed"),_.ax.selected!==void 0&&(N.selected=_.ax.selected),_.ax.expanded!==void 0&&(N.expanded=_.ax.expanded);let z;_.dom?.testId?z=`[data-testid="${_.dom.testId}"]`:_.dom?.id&&(z=`#${_.dom.id}`);let X={id:B,role:te,label:mx(D),kind:I,value:K,state:N,bbox:M};return z!==void 0&&(X.selector=z),X}),R="idle";try{let _=await t.evaluate(()=>document.readyState);_==="loading"?R="loading":_==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let O=hx(f),v=`obs_${e.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:v,url:m,title:g,textSummary:O,interactive:E,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:C}}var am,cm,dm=we(()=>{"use strict";_s();am=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);cm="a[href], button, input, select, textarea, [role], [tabindex], label"});async function um(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Wl(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>um(t,s)))).filter(o=>o!==null)}async function Sx(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Kl(t,e,n){switch(e.kind){case"element_id":return vx(t,e,n);case"selector":return kx(t,e);case"semantic":return Ex(t,e)}}async function vx(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Wl(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function kx(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Wl(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function Ex(t,e){return e.role!==void 0?Ax(t,e.text,e.role):_x(t,e.text,e)}async function Ax(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Wl(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function _x(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:s,count:l});let u=await Sx(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let h=p[g];if(h===void 0)continue;let y=await um(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,k=0;for(let S=0;S<w.length;S++)k=k*31+w.charCodeAt(S)>>>0;f.push({...y,id:`el_${k.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var pm=we(()=>{"use strict"});async function Gl(t,e,n,r){let o=t.url();if(o===n)return null;let s=vs(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var fm=we(()=>{"use strict";ks()});import{randomBytes as Tx}from"crypto";import{mkdir as xx,stat as Rx,writeFile as Cx}from"fs/promises";import{join as ql}from"path";import{gzip as Ix}from"zlib";import{promisify as Px}from"util";function Mx(t){return ql(xa(t),"browser")}function Ox(t){return ql(Mx(t),"screenshots")}function Dx(){return new Date().toISOString().replace(/[:.]/g,"-")}function Fx(){return Tx(3).toString("hex")}async function zl(t,e,n){if(e.length>mm)throw new Error(`writeScreenshotSidecar: buffer exceeds ${mm} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=Ox(t);await xx(r,{recursive:!0});let o=`${Dx()}-${Fx()}-${n}.png`,s=ql(r,o);await Cx(s,e);let{size:i}=await Rx(s);return{path:s,bytes:i}}var jj,mm,gm=we(()=>{"use strict";L();_s();jj=Px(Ix);mm=5*1024*1024});var ym={};Bd(ym,{PlaywrightProvider:()=>Jl});function hm(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var Jl,bm=we(()=>{"use strict";nm();dm();pm();ks();fm();gm();Jl=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new As(e)}async open(e){let n=vs(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await Gl(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await Ts(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Ts(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await Kl(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${hm(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){c=h}else c=g}let u=await Gl(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Ts(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Kl(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${hm(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await zl(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await zl(n,o,r);return s}catch{return null}}}});var Wt={};Bd(Wt,{__resetBrowserRegistryForTests:()=>Bx,browserProviderActive:()=>Ux,closeBrowserProvider:()=>Vl,getBrowserProvider:()=>Nx,peekBrowserProvider:()=>$x});function wm(){Promise.resolve(Vl()).then(()=>{process.exit(130)})}function Sm(){Promise.resolve(Vl()).then(()=>{process.exit(143)})}function vm(){Ke=null}function Lx(){xs||(process.on("SIGINT",wm),process.on("SIGTERM",Sm),process.on("exit",vm),xs=!0)}function km(){xs&&(process.removeListener("SIGINT",wm),process.removeListener("SIGTERM",Sm),process.removeListener("exit",vm),xs=!1)}async function Nx(t){return Ke!==null?Ke:(jt!==null||(jt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(bm(),ym)),n=Qf(t),r=new e(n);return Lx(),Ke=r,jt=null,r})()),jt)}async function Vl(){if(Ke===null)return;let t=Ke;Ke=null,jt=null,km(),await t.shutdown()}function Ux(){return Ke!==null}function $x(){return Ke}function Bx(){Ke=null,jt=null,km()}var Ke,jt,xs,Kt=we(()=>{"use strict";ks();Ke=null,jt=null,xs=!1});Z();P();L();Z();import{randomBytes as gv}from"node:crypto";import{mkdir as hv,writeFile as yv}from"node:fs/promises";import{join as bv}from"node:path";P();import{mkdirSync as sv,appendFileSync as iv,existsSync as av}from"fs";import{resolve as lv}from"path";import{dirname as cv}from"path";var dv=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
|
|
4
|
+
${Oe(t,{headless:e,latched:n})}`,{cause:t})}var em,rx,ox,Zf,ix,jl=we(()=>{"use strict";em=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],rx="pnpm exec playwright install chromium",ox=4;ix="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Ht from"node:fs";import Es from"node:path";import{randomBytes as ax}from"node:crypto";import{chromium as lx}from"playwright";function cx(){try{return"5.89.1"}catch{}try{let t=Es.resolve(import.meta.dirname,"../../../package.json"),e=Ht.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var dx,As,nm=we(()=>{"use strict";jl();L();Z();dx=cx(),As=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=lx.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Hl(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){s=l,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let c=await a.content();if(s!==void 0)throw s;let d=a.url(),u=l!==null?l.status():null;return{html:c,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${dx}`}}loadStorageState(e){let n=Ia(e);try{if(!Ht.existsSync(n))return;let r=JSON.parse(Ht.readFileSync(n,"utf8"));return T("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){T("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Ia(e);if(!Ht.existsSync(r))return;let o=await n.storageState(),s=Es.join(Es.dirname(r),`.${Es.basename(r)}.${process.pid}.${ax(4).toString("hex")}.tmp`);Ht.writeFileSync(s,JSON.stringify(o),{mode:384}),Ht.chmodSync(s,384),Ht.renameSync(s,r),T("[browser/vault] saved session",{profile:e,file:r})}catch(r){T("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as ux}from"crypto";function rm(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&px.test(t.label))}function om(t){return ux("sha256").update(t,"utf8").digest("hex").slice(0,8)}function sm(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var px,_s=we(()=>{"use strict";px=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as fx}from"node:crypto";function mx(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function gx(t,e,n){return`el_${fx("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function hx(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function im(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function lm(t,e){let n=t.role??"",r=t.name??"";am.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])lm(s,e)}async function yx(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},cm).catch(()=>[])}async function bx(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},cm).catch(()=>[])}function wx(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Ts(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=wx(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=yx(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,y=!1;u!==null?(h=[],lm(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await bx(t)).filter(W=>am.has(W.role??"")));let w=new Map;for(let _ of p){let W=im(_.name),te=w.get(W);(!te||te.bbox.w===0&&_.bbox.w>0)&&w.set(W,_)}let k=h.map(_=>({ax:_,dom:w.get(im(_.name??""))})),S=r?k:k.filter(_=>_.dom?_.dom.bbox.w>0||_.dom.bbox.h>0:!0);S.sort((_,W)=>{let te=_.dom?.bbox.y??0,D=W.dom?.bbox.y??0;if(te!==D)return te-D;let B=_.dom?.bbox.x??0,M=W.dom?.bbox.x??0;return B-M}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=S.slice(0,n).map((_,W)=>{let te=_.ax.role??"generic",D=_.ax.name??"",B=gx(te,D,W),M=_.dom?.bbox??{x:0,y:0,w:0,h:0},I=_.dom?.type??null,K=null;_.ax.value!==void 0&&_.ax.value!==null&&(K=String(_.ax.value)),_.ax.checked!==void 0&&(K=String(_.ax.checked)),rm({role:te,kind:I})&&(K="[redacted]");let N={disabled:_.ax.disabled??!1};_.ax.checked!==void 0&&(N.checked=_.ax.checked===!0||_.ax.checked==="mixed"),_.ax.selected!==void 0&&(N.selected=_.ax.selected),_.ax.expanded!==void 0&&(N.expanded=_.ax.expanded);let z;_.dom?.testId?z=`[data-testid="${_.dom.testId}"]`:_.dom?.id&&(z=`#${_.dom.id}`);let X={id:B,role:te,label:mx(D),kind:I,value:K,state:N,bbox:M};return z!==void 0&&(X.selector=z),X}),R="idle";try{let _=await t.evaluate(()=>document.readyState);_==="loading"?R="loading":_==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let O=hx(f),v=`obs_${e.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:v,url:m,title:g,textSummary:O,interactive:E,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:C}}var am,cm,dm=we(()=>{"use strict";_s();am=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);cm="a[href], button, input, select, textarea, [role], [tabindex], label"});async function um(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Wl(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>um(t,s)))).filter(o=>o!==null)}async function Sx(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Kl(t,e,n){switch(e.kind){case"element_id":return vx(t,e,n);case"selector":return kx(t,e);case"semantic":return Ex(t,e)}}async function vx(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Wl(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function kx(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Wl(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function Ex(t,e){return e.role!==void 0?Ax(t,e.text,e.role):_x(t,e.text,e)}async function Ax(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Wl(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function _x(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:s,count:l});let u=await Sx(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let h=p[g];if(h===void 0)continue;let y=await um(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,k=0;for(let S=0;S<w.length;S++)k=k*31+w.charCodeAt(S)>>>0;f.push({...y,id:`el_${k.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var pm=we(()=>{"use strict"});async function Gl(t,e,n,r){let o=t.url();if(o===n)return null;let s=vs(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var fm=we(()=>{"use strict";ks()});import{randomBytes as Tx}from"crypto";import{mkdir as xx,stat as Rx,writeFile as Cx}from"fs/promises";import{join as ql}from"path";import{gzip as Ix}from"zlib";import{promisify as Px}from"util";function Mx(t){return ql(xa(t),"browser")}function Ox(t){return ql(Mx(t),"screenshots")}function Dx(){return new Date().toISOString().replace(/[:.]/g,"-")}function Fx(){return Tx(3).toString("hex")}async function zl(t,e,n){if(e.length>mm)throw new Error(`writeScreenshotSidecar: buffer exceeds ${mm} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=Ox(t);await xx(r,{recursive:!0});let o=`${Dx()}-${Fx()}-${n}.png`,s=ql(r,o);await Cx(s,e);let{size:i}=await Rx(s);return{path:s,bytes:i}}var jj,mm,gm=we(()=>{"use strict";L();_s();jj=Px(Ix);mm=5*1024*1024});var ym={};Bd(ym,{PlaywrightProvider:()=>Jl});function hm(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var Jl,bm=we(()=>{"use strict";nm();dm();pm();ks();fm();gm();Jl=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new As(e)}async open(e){let n=vs(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await Gl(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await Ts(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Ts(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await Kl(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${hm(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){c=h}else c=g}let u=await Gl(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Ts(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Kl(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${hm(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await zl(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await zl(n,o,r);return s}catch{return null}}}});var Wt={};Bd(Wt,{__resetBrowserRegistryForTests:()=>Bx,browserProviderActive:()=>Ux,closeBrowserProvider:()=>Vl,getBrowserProvider:()=>Nx,peekBrowserProvider:()=>$x});function wm(){Promise.resolve(Vl()).then(()=>{process.exit(130)})}function Sm(){Promise.resolve(Vl()).then(()=>{process.exit(143)})}function vm(){Ke=null}function Lx(){xs||(process.on("SIGINT",wm),process.on("SIGTERM",Sm),process.on("exit",vm),xs=!0)}function km(){xs&&(process.removeListener("SIGINT",wm),process.removeListener("SIGTERM",Sm),process.removeListener("exit",vm),xs=!1)}async function Nx(t){return Ke!==null?Ke:(jt!==null||(jt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(bm(),ym)),n=Qf(t),r=new e(n);return Lx(),Ke=r,jt=null,r})()),jt)}async function Vl(){if(Ke===null)return;let t=Ke;Ke=null,jt=null,km(),await t.shutdown()}function Ux(){return Ke!==null}function $x(){return Ke}function Bx(){Ke=null,jt=null,km()}var Ke,jt,xs,Kt=we(()=>{"use strict";ks();Ke=null,jt=null,xs=!1});Z();P();L();Z();import{randomBytes as gv}from"node:crypto";import{mkdir as hv,writeFile as yv}from"node:fs/promises";import{join as bv}from"node:path";P();import{mkdirSync as sv,appendFileSync as iv,existsSync as av}from"fs";import{resolve as lv}from"path";import{dirname as cv}from"path";var dv=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
|
|
5
5
|
`,uv=/key|token|secret|password|credential|auth/i,pv=[[/sk-ant-[A-Za-z0-9_\-]{8,200}/g,t=>`<REDACTED sk-ant length=${t[0].length}>`],[/sk-(?!ant-)[A-Za-z0-9_\-]{20,200}/g,t=>`<REDACTED sk- length=${t[0].length}>`],[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,t=>`<REDACTED Bearer length=${t[0].length}>`],[/AKIA[A-Z0-9]{16}/g,t=>`<REDACTED AKIA length=${t[0].length}>`],[/xox[baprs]-[A-Za-z0-9\-]{10,200}/g,t=>`<REDACTED xox token length=${t[0].length}>`],[/\d{8,12}:[A-Za-z0-9_\-]{35}/g,t=>`<REDACTED Telegram token length=${t[0].length}>`],[/([A-Za-z_]{3,}(?:[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]|[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll])[A-Za-z_]*)=([^\s]{16,})/g,t=>`${t[1]}=<REDACTED length=${t[2].length}>`],[/([A-Z_]{3,}(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=([^\s]{16,})/g,t=>`${t[1]}=<REDACTED length=${t[2].length}>`]];function Ma(t){let e=t;for(let[n,r]of pv)e=e.replace(n,(...o)=>{let s=o.slice(0,o.length-2);return r(s)});return e}function Pa(t){return typeof t=="string"?Ma(t):Array.isArray(t)?t.map(Pa):t}function fv(t){if(t===null||typeof t!="object")return t;let e=t,n={...e},r=e.env;if(r&&typeof r=="object"){let o={};for(let[s,i]of Object.entries(r))uv.test(s)&&typeof i=="string"?o[s]=`<REDACTED length=${i.length}>`:o[s]=i;n.env=o}return"system"in e&&(n.system=Pa(e.system)),"systemPrompt"in e&&(n.systemPrompt=Pa(e.systemPrompt)),n}function mv(t){if(t==null)return{kind:"undefined",note:"SDK uses minimal prompt; claude_code preset NOT loaded"};if(typeof t=="string")return{kind:"custom-string",note:"SDK uses this string as full system prompt; claude_code preset NOT loaded"};if(Array.isArray(t))return{kind:"custom-string-array",note:"SDK uses array as full system prompt with cache boundaries; claude_code preset NOT loaded"};if(typeof t=="object"){let e=t;if(e.type==="preset"&&e.preset==="claude_code"){let n={kind:"preset-claude-code",note:"claude_code preset loaded"};return typeof e.append=="string"&&(n.append={length:e.append.length}),e.excludeDynamicSections===!0&&(n.excludeDynamicSections=!0),n}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}function ou(t){let e=b.AFK_DUMP_PROMPT;if(!e||e===""||e==="0"||e.toLowerCase()==="false")return;process.stderr.write(`[--dump-prompt] WARNING: dump may contain secrets from system prompt or messages. Inspect before sharing.
|
|
6
6
|
`);let n=t.options,r=typeof n=="object"&&n!==null?n.systemPrompt:void 0,o=mv(r),s={timestamp:new Date().toISOString(),prompt:t.prompt,options:fv(t.options),provenance:t.provenance,resolution:o};if(e==="1"||e.toLowerCase()==="true"||e.toLowerCase()==="stderr"){let l=JSON.stringify(s,null,2)+`
|
|
7
7
|
`;process.stderr.write(l);return}let i=lv(e),a=cv(i);try{sv(a,{recursive:!0});let c=(!av(i)?dv:"")+JSON.stringify(s)+`
|
|
@@ -693,7 +693,7 @@ Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${t}${r}
|
|
|
693
693
|
|
|
694
694
|
`;return i.toString("utf8")+c+a.toString("utf8")}function Ft(t){return Buffer.byteLength(t,"utf8")<=1e5?{content:t,truncated:!1}:{content:Xe(t,1e5),truncated:!0}}var os=`
|
|
695
695
|
[output truncated \u2014 command exceeded the 8000000-byte output cap and was terminated]`;L();import wl from"path";import{dirname as ZE}from"path";import{appendFileSync as eA,mkdirSync as tA}from"fs";var mt=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=wl.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=wl.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=wl.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 l=this.hooks.getWriteRoots();if(l){let c=l.indexOf(s);c!==-1&&l.splice(c,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=vo();tA(ZE(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});eA(n,r+`
|
|
696
|
-
`)}catch{}}};var nA={name:"bash",category:"shell",concurrencySafe:!1,description:"Execute a shell command and return its stdout and stderr. Use for running programs, installing packages, git operations, and any task that requires a shell. Commands run in the user's default shell. Long-running commands should use timeout_ms. Output is capped to a ~100KB head+tail view (the start and end are kept, the middle elided with a notice), so the command still runs to completion and you keep the real exit code and the tail (test/build summaries, final errors). For the full body of a verbose command, filter it (`| tail -n`, `--quiet`, narrower flags) or redirect to a file and read slices. Commands emitting extreme output (>8MB) are terminated. For reading or writing files \u2014 especially anything sensitive \u2014 prefer the typed file tools (read_file, write_file, edit_file): they support per-call user approval, and interpreter one-liners (python -c, node -e, sh -c, ...) that reference credential paths (SSH keys, cloud credentials, /etc/shadow) are blocked by the path-approval policy on interactive surfaces.",input_schema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute."},timeout_ms:{type:"number",description:"Optional timeout in milliseconds (default 120000, max 600000). The command is killed if it exceeds this duration."}},required:["command"]}},rA={name:"read_file",category:"read",concurrencySafe:!0,description:"Read a file from the filesystem. Returns the file content with line numbers. Use offset and limit to read specific sections of large files. When the read returns a partial view, the response ends with a `... (showing lines X-Y of Z [\u2014 pass offset=N to continue])` annotation indicating the full file size and how to continue. Binary files are detected and rejected. Missing files return an error.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to read."},offset:{type:"number",description:"Line number to start reading from (1-based). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to read. Defaults to 2000."}},required:["file_path"]}},oA={name:"write_file",category:"write",concurrencySafe:!1,description:"Write content to a file, creating it if it does not exist or overwriting if it does. Parent directories are created automatically. Prefer edit_file for modifying existing files \u2014 use write_file only for new files or complete rewrites.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to write."},content:{type:"string",description:"The full content to write to the file."}},required:["file_path","content"]}},sA={name:"edit_file",category:"write",concurrencySafe:!1,description:"Perform an exact string replacement in a file. Finds old_string and replaces it with new_string. The edit fails if old_string is not found or matches multiple locations (unless replace_all is true). Always use read_file first to verify the exact content before editing.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to edit."},old_string:{type:"string",description:"The exact string to find and replace. Must match file content exactly."},new_string:{type:"string",description:"The replacement string."},replace_all:{type:"boolean",description:"If true, replace all occurrences. If false (default), fail when multiple matches exist."}},required:["file_path","old_string","new_string"]}},iA={name:"glob",category:"read",concurrencySafe:!0,description:'Find files matching a glob pattern. Returns matching file paths, capped at 500 results. Use for discovering files before reading them. Patterns follow standard glob syntax (e.g., "src/**/*.ts", "*.json"). Skips node_modules/.git/.hg/.svn by default; name such a directory literally in the pattern (e.g. "node_modules/**/*.js") to search it.',input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "src/**/*.ts").'},path:{type:"string",description:"Base directory to search from. Defaults to the current working directory."}},required:["pattern"]}},aA={name:"grep",category:"read",concurrencySafe:!0,description:"Search file contents for lines matching a pattern. Returns matches in file:line:content format. Runs on ripgrep: `|` `+` `?` `(` `)` `{` `}` are regex metacharacters by default (e.g. `foo|bar` alternates, matching either branch) \u2014 escape with a backslash for the literal character. Honors .gitignore (so build/dependency dirs like node_modules are skipped) but DOES search hidden files/dirs like .github and .env; the .git directory and binary files are skipped. Output is capped to a ~100KB head+tail view; if a search is truncated, narrow it (a more specific pattern, an `include` glob, or a subdirectory `path`) rather than re-running the same broad query. Use for finding symbols, strings, or patterns across the codebase.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Search pattern (ripgrep regex syntax). `|` `+` `?` `(` `)` `{` `}` are metacharacters \u2014 e.g. `foo|bar` matches either "foo" or "bar". Escape with a backslash (e.g. `\\|`) to match the literal character.'},path:{type:"string",description:"Directory or file to search. Defaults to current working directory."},include:{type:"string",description:'File glob to restrict search (e.g., "*.ts"). Passed as -g to ripgrep.'}},required:["pattern"]}},lA={name:"list_directory",category:"read",concurrencySafe:!0,description:"List the contents of a directory. Returns file and subdirectory names with type annotations (directories end with /). Use for exploring project structure.",input_schema:{type:"object",properties:{path:{type:"string",description:"Absolute path to the directory to list."}},required:["path"]}},cA={name:"send_telegram",category:"web",concurrencySafe:!1,riskClass:"caution",description:'Send a Telegram message to the operator. Use to surface terminal-state notifications, blocking questions, or important status updates when the user is away from keyboard (AFK). The message is delivered through the same Telegram bot the operator uses to drive this session. By default the message goes to your primary chat (the first private chat in `AFK_TELEGRAM_ALLOWED_CHAT_IDS`, or `AFK_TELEGRAM_PRIMARY_CHAT_ID` if set); set `telegram.notify` in afk.config.json to broadcast to all allowed chats or target a custom set.\n\nPlain text only \u2014 Telegram\'s 4096-character limit per message is enforced. Returns an error if Telegram is not configured (missing `TELEGRAM_BOT_TOKEN` or empty allowlist) so the tool is safe to attempt unconditionally.\n\nUse sparingly: this is a real push notification to a human. Reserve for terminal states (Done/Blocked/Asking) and material progress, not running commentary. When running inside the Telegram bot, prefer replying normally \u2014 your response already reaches the operator through the bot. Use this tool only from CLI or daemon sessions.\n\nOptionally set `chat` to route to a SPECIFIC chat instead of the default primary target: pass a numeric chat id (e.g. -1001234567890 for a group) or a chat alias name defined in afk.config.json `telegram.chatAliases` (e.g. "ops"). An explicitly-targeted chat must be in the inbound allowlist (AFK_TELEGRAM_ALLOWED_CHAT_IDS) \u2014 a non-allowlisted target is rejected (fail-closed). Omit `chat` for the default behavior (unchanged).',input_schema:{type:"object",properties:{message:{type:"string",description:"Plain-text message body to send to the operator. Max 4096 characters (Telegram API limit). Must be non-empty."},chat:{type:["number","string"],description:"Optional. Target a specific chat instead of the default primary target. A number (or numeric string) is a raw Telegram chat id; a non-numeric string is looked up as a name in afk.config.json `telegram.chatAliases`. The resolved chat must be allowlisted (AFK_TELEGRAM_ALLOWED_CHAT_IDS) or the send is rejected. Omit to send to the configured default (primary DM chat / notify targets)."}},required:["message"]}},dA={name:"web_scrape",category:"web",concurrencySafe:!0,description:'Scrape a web page or run a web search and return text content suitable for reasoning over. Three modes:\n\n- `markdown` (default): fetches the URL and extracts the main content as clean markdown (Readability + Turndown). Handles JS-rendered pages: if the plain fetch yields thin content, it escalates to a headless-browser render and re-extracts. Use this for articles, docs, blog posts, and most "I want to read this page" cases. No API key required (the render fallback needs the Playwright chromium binary; if it is absent the error names the exact install command for this installation).\n- `raw`: GETs the URL directly and returns the response body as decoded text, with no markdown transformation. Use for JSON APIs, robots.txt, RSS, or plain-text endpoints. Not byte-preserving \u2014 binary payloads are decoded as text, so do not rely on this for exact bytes. No API key required.\n- `search`: runs a web search and returns ranked markdown results. Use when you need to FIND a URL, not read one. Provide `query` instead of `url`. Requires `EXA_API_KEY` (free tier at https://exa.ai); the handler returns a clear error if it is unset.\n\nOutputs are capped at `max_bytes` UTF-8 bytes (default 100KB, ceiling 1MB); content over the cap is reduced to head+tail with a `\u2026 [N bytes truncated: \u2026] \u2026` marker so both ends survive. The request is aborted after `timeout_ms` (default 30000, ceiling 120000).',input_schema:{type:"object",properties:{mode:{type:"string",enum:["markdown","raw","search"],description:'Fetch mode. Defaults to "markdown".'},url:{type:"string",description:"Absolute http(s) URL. Required for markdown and raw modes. Ignored in search mode."},query:{type:"string",description:"Search query string. Required for search mode. Ignored otherwise."},timeout_ms:{type:"number",description:"Request timeout in milliseconds (default 30000, clamped to 120000)."},max_bytes:{type:"number",description:"Maximum UTF-8 bytes returned. Content beyond this is reduced to head+tail with a truncation marker (both ends preserved). Default 100000, clamped to 1000000."}},required:[]}},Qe={name:"agent",category:"subagent",concurrencySafe:!0,description:`Dispatch an independent subagent with its own context window and tool access. Use for tasks that protect the main session's context: codebase exploration, multi-file inspection, repo search, verification, debugging, failing-test investigation, PR review, parallel hypothesis testing, independent re-derivation of a claim, audit work, stale-path detection, feature-wiring checks, and any research-shaped investigation.
|
|
696
|
+
`)}catch{}}};var nA={name:"bash",category:"shell",concurrencySafe:!1,description:"Execute a shell command and return its stdout and stderr. Use for running programs, installing packages, git operations, and any task that requires a shell. Commands run through /bin/sh (Node spawn with shell:true) \u2014 NOT bash and NOT your $SHELL; /bin/sh is bash-in-POSIX-mode on macOS but dash on Debian/Ubuntu. Only process substitution <(...) reliably fails closed (exit 2, nothing runs). Other bashisms are nonportable and are NOT dependable refusals: [[ ]] runs on macOS but is a not-found command on dash while the rest of the line still executes; {a,b} expands on macOS but passes through literally on dash (silently wrong argument); arrays run on macOS but are a syntax error on dash. So never assume a bashism-containing command was side-effect-free \u2014 prefer a temp file or a POSIX equivalent. Long-running commands should use timeout_ms. Output is capped to a ~100KB head+tail view (the start and end are kept, the middle elided with a notice), so the command still runs to completion and you keep the real exit code and the tail (test/build summaries, final errors). For the full body of a verbose command, filter it (`| tail -n`, `--quiet`, narrower flags) or redirect to a file and read slices. Commands emitting extreme output (>8MB) are terminated. For reading or writing files \u2014 especially anything sensitive \u2014 prefer the typed file tools (read_file, write_file, edit_file): they support per-call user approval, and interpreter one-liners (python -c, node -e, sh -c, ...) that reference credential paths (SSH keys, cloud credentials, /etc/shadow) are blocked by the path-approval policy on interactive surfaces.",input_schema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute."},timeout_ms:{type:"number",description:"Optional timeout in milliseconds (default 120000, max 600000). The command is killed if it exceeds this duration."}},required:["command"]}},rA={name:"read_file",category:"read",concurrencySafe:!0,description:"Read a file from the filesystem. Returns the file content with line numbers. Use offset and limit to read specific sections of large files. When the read returns a partial view, the response ends with a `... (showing lines X-Y of Z [\u2014 pass offset=N to continue])` annotation indicating the full file size and how to continue. Binary files are detected and rejected. Missing files return an error.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to read."},offset:{type:"number",description:"Line number to start reading from (1-based). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to read. Defaults to 2000."}},required:["file_path"]}},oA={name:"write_file",category:"write",concurrencySafe:!1,description:"Write content to a file, creating it if it does not exist or overwriting if it does. Parent directories are created automatically. Prefer edit_file for modifying existing files \u2014 use write_file only for new files or complete rewrites.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to write."},content:{type:"string",description:"The full content to write to the file."}},required:["file_path","content"]}},sA={name:"edit_file",category:"write",concurrencySafe:!1,description:"Perform an exact string replacement in a file. Finds old_string and replaces it with new_string. The edit fails if old_string is not found or matches multiple locations (unless replace_all is true). Always use read_file first to verify the exact content before editing.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to edit."},old_string:{type:"string",description:"The exact string to find and replace. Must match file content exactly."},new_string:{type:"string",description:"The replacement string."},replace_all:{type:"boolean",description:"If true, replace all occurrences. If false (default), fail when multiple matches exist."}},required:["file_path","old_string","new_string"]}},iA={name:"glob",category:"read",concurrencySafe:!0,description:'Find files matching a glob pattern. Returns matching file paths, capped at 500 results. Use for discovering files before reading them. Patterns follow standard glob syntax (e.g., "src/**/*.ts", "*.json"). Skips node_modules/.git/.hg/.svn by default; name such a directory literally in the pattern (e.g. "node_modules/**/*.js") to search it.',input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "src/**/*.ts").'},path:{type:"string",description:"Base directory to search from. Defaults to the current working directory."}},required:["pattern"]}},aA={name:"grep",category:"read",concurrencySafe:!0,description:"Search file contents for lines matching a pattern. Returns matches in file:line:content format. Runs on ripgrep: `|` `+` `?` `(` `)` `{` `}` are regex metacharacters by default (e.g. `foo|bar` alternates, matching either branch) \u2014 escape with a backslash for the literal character. Honors .gitignore (so build/dependency dirs like node_modules are skipped) but DOES search hidden files/dirs like .github and .env; the .git directory and binary files are skipped. Output is capped to a ~100KB head+tail view; if a search is truncated, narrow it (a more specific pattern, an `include` glob, or a subdirectory `path`) rather than re-running the same broad query. Use for finding symbols, strings, or patterns across the codebase.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Search pattern (ripgrep regex syntax). `|` `+` `?` `(` `)` `{` `}` are metacharacters \u2014 e.g. `foo|bar` matches either "foo" or "bar". Escape with a backslash (e.g. `\\|`) to match the literal character.'},path:{type:"string",description:"Directory or file to search. Defaults to current working directory."},include:{type:"string",description:'File glob to restrict search (e.g., "*.ts"). Passed as -g to ripgrep.'}},required:["pattern"]}},lA={name:"list_directory",category:"read",concurrencySafe:!0,description:"List the contents of a directory. Returns file and subdirectory names with type annotations (directories end with /). Use for exploring project structure.",input_schema:{type:"object",properties:{path:{type:"string",description:"Absolute path to the directory to list."}},required:["path"]}},cA={name:"send_telegram",category:"web",concurrencySafe:!1,riskClass:"caution",description:'Send a Telegram message to the operator. Use to surface terminal-state notifications, blocking questions, or important status updates when the user is away from keyboard (AFK). The message is delivered through the same Telegram bot the operator uses to drive this session. By default the message goes to your primary chat (the first private chat in `AFK_TELEGRAM_ALLOWED_CHAT_IDS`, or `AFK_TELEGRAM_PRIMARY_CHAT_ID` if set); set `telegram.notify` in afk.config.json to broadcast to all allowed chats or target a custom set.\n\nPlain text only \u2014 Telegram\'s 4096-character limit per message is enforced. Returns an error if Telegram is not configured (missing `TELEGRAM_BOT_TOKEN` or empty allowlist) so the tool is safe to attempt unconditionally.\n\nUse sparingly: this is a real push notification to a human. Reserve for terminal states (Done/Blocked/Asking) and material progress, not running commentary. When running inside the Telegram bot, prefer replying normally \u2014 your response already reaches the operator through the bot. Use this tool only from CLI or daemon sessions.\n\nOptionally set `chat` to route to a SPECIFIC chat instead of the default primary target: pass a numeric chat id (e.g. -1001234567890 for a group) or a chat alias name defined in afk.config.json `telegram.chatAliases` (e.g. "ops"). An explicitly-targeted chat must be in the inbound allowlist (AFK_TELEGRAM_ALLOWED_CHAT_IDS) \u2014 a non-allowlisted target is rejected (fail-closed). Omit `chat` for the default behavior (unchanged).',input_schema:{type:"object",properties:{message:{type:"string",description:"Plain-text message body to send to the operator. Max 4096 characters (Telegram API limit). Must be non-empty."},chat:{type:["number","string"],description:"Optional. Target a specific chat instead of the default primary target. A number (or numeric string) is a raw Telegram chat id; a non-numeric string is looked up as a name in afk.config.json `telegram.chatAliases`. The resolved chat must be allowlisted (AFK_TELEGRAM_ALLOWED_CHAT_IDS) or the send is rejected. Omit to send to the configured default (primary DM chat / notify targets)."}},required:["message"]}},dA={name:"web_scrape",category:"web",concurrencySafe:!0,description:'Scrape a web page or run a web search and return text content suitable for reasoning over. Three modes:\n\n- `markdown` (default): fetches the URL and extracts the main content as clean markdown (Readability + Turndown). Handles JS-rendered pages: if the plain fetch yields thin content, it escalates to a headless-browser render and re-extracts. Use this for articles, docs, blog posts, and most "I want to read this page" cases. No API key required (the render fallback needs the Playwright chromium binary; if it is absent the error names the exact install command for this installation).\n- `raw`: GETs the URL directly and returns the response body as decoded text, with no markdown transformation. Use for JSON APIs, robots.txt, RSS, or plain-text endpoints. Not byte-preserving \u2014 binary payloads are decoded as text, so do not rely on this for exact bytes. No API key required.\n- `search`: runs a web search and returns ranked markdown results. Use when you need to FIND a URL, not read one. Provide `query` instead of `url`. Requires `EXA_API_KEY` (free tier at https://exa.ai); the handler returns a clear error if it is unset.\n\nOutputs are capped at `max_bytes` UTF-8 bytes (default 100KB, ceiling 1MB); content over the cap is reduced to head+tail with a `\u2026 [N bytes truncated: \u2026] \u2026` marker so both ends survive. The request is aborted after `timeout_ms` (default 30000, ceiling 120000).',input_schema:{type:"object",properties:{mode:{type:"string",enum:["markdown","raw","search"],description:'Fetch mode. Defaults to "markdown".'},url:{type:"string",description:"Absolute http(s) URL. Required for markdown and raw modes. Ignored in search mode."},query:{type:"string",description:"Search query string. Required for search mode. Ignored otherwise."},timeout_ms:{type:"number",description:"Request timeout in milliseconds (default 30000, clamped to 120000)."},max_bytes:{type:"number",description:"Maximum UTF-8 bytes returned. Content beyond this is reduced to head+tail with a truncation marker (both ends preserved). Default 100000, clamped to 1000000."}},required:[]}},Qe={name:"agent",category:"subagent",concurrencySafe:!0,description:`Dispatch an independent subagent with its own context window and tool access. Use for tasks that protect the main session's context: codebase exploration, multi-file inspection, repo search, verification, debugging, failing-test investigation, PR review, parallel hypothesis testing, independent re-derivation of a claim, audit work, stale-path detection, feature-wiring checks, and any research-shaped investigation.
|
|
697
697
|
|
|
698
698
|
Parallelize: dispatch multiple \`agent\` calls in a single tool-use turn to run independent investigations concurrently.
|
|
699
699
|
|
|
@@ -835,7 +835,7 @@ ${n}
|
|
|
835
835
|
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 ZA}from"node:crypto";var e_=5,El=20;function pf(){return{recent:[],firedFingerprints:new Set}}function fs(t){let e;try{e=t_(t.input)}catch{e=String(t.input)}return ZA("sha256").update(t.name).update("\0").update(e).digest("hex")}function t_(t){return JSON.stringify(kl(t))??"null"}function kl(t){if(Array.isArray(t))return t.map(kl);if(t!==null&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e).sort())n[r]=kl(e[r]);return n}return t}function n_(t,e){let n=0;for(let r of t)r===e&&(n+=1);return n}function ff(t,e){t.recent.push(e),t.recent.length>El&&t.recent.shift();let n=n_(t.recent,e);return n>=e_&&!t.firedFingerprints.has(e)?(t.firedFingerprints.add(e),{fired:!0,count:n}):{fired:!1,count:n}}var Al=3,r_=new Set(["timeout_ms","timeoutMs","timeout"]),mf=240;function o_(t){if(t===null||typeof t!="object"||Array.isArray(t))return t;let e={};for(let[n,r]of Object.entries(t))r_.has(n)||(e[n]=r);return e}function mr(t){return fs({...t,input:o_(t.input)})}function s_(t){let e=t.content.split(`
|
|
836
836
|
`).find(n=>n.trim()!=="")?.trim()??"";return e.length<=mf?e:`${e.slice(0,mf)}\u2026`}var ms=class{streaks=new Map;check(e){let n=this.streaks.get(mr(e));return n===void 0||n.count<Al?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}
|
|
837
837
|
|
|
838
|
-
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=mr(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:s_(n)})}streakFor(e){return this.streaks.get(mr(e))?.count??0}};var a_=8,_l=new Set,l_=8,Me=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 ms;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??ps,this.maxConcurrentSafeCalls=typeof e.maxConcurrentSafeCalls=="number"&&Number.isFinite(e.maxConcurrentSafeCalls)&&e.maxConcurrentSafeCalls>=1?Math.floor(e.maxConcurrentSafeCalls):l_,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 mt({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))}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=Bp(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, ls, cat, find, grep).`;return await this.emitPreToolUseBlock(e.name,s),{content:s,isError:!0,failureClass:"permission-denied"}}async emitPreToolUseBlock(e,n){await lt(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:e,reason:n,...this.subagentId!==void 0?{subagentId:this.subagentId}:{}})}checkRepeatCircuitBreaker(e){if(_l.has(e.name))return null;let n=af(e);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<a_?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(_l.has(e.name))return null;let n=this.repeatFailureGuard.check(e);return n===null?null:(T(`[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=pf());let n=fs(e),r=ff(this.suspectedLoopWindow,n);r.fired&&U(this.traceWriter,{phase:"suspected_loop",metadata:{tool:e.name,count:r.count,windowSize:El}})}recordForkReadDenial(e,n,r){if(this.parentSessionId===void 0||!lf.has(e.name)||!cf(n))return r;let o=this.denialBreaker??{count:0,deniedPaths:[]};o.count+=1;let s=df(e);return o.deniedPaths.includes(s)||o.deniedPaths.push(s),this.denialBreaker=o,o.count<5?r:{content:uf(o.deniedPaths,o.count),isError:!0,failureClass:cn}}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 execute(e){if(e.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:"abort"};if(this.hookRegistry){let l={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 ml(this.hookRegistry,l,{signal:e.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(c){if(c instanceof G)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=dr(e.name,this.permissions);if(!n.allowed){let l=n.reason??`Tool "${e.name}" is not permitted`;return await this.emitPreToolUseBlock(e.name,l),{content:l,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);if(i)return i;this.observeSuspectedLoop(e);let a=await this.executeCore(e);return this.repeatFailureGuard.note(e,a),a.isError!==!0&&this.resetDenialBreaker(),a}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:"abort"},r.add(i);continue}if(this.hookRegistry){let f={event:"PreToolUse",toolName:a.name,input:a.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 ml(this.hookRegistry,f,{signal:a.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(m){if(m instanceof G){n[i]=this.recordForkReadDenial(a,m.reason,{content:`Tool "${a.name}" blocked by PreToolUse hook: ${m.message}`,isError:!0,failureClass:"hook-block"}),r.add(i);continue}throw m}}let l=dr(a.name,this.permissions);if(!l.allowed){let f=l.reason??`Tool "${a.name}" is not permitted`;await this.emitPreToolUseBlock(a.name,f),n[i]={content:f,isError:!0,failureClass:"permission-denied"},r.add(i);continue}let c=await this.runCanUseTool(a);if(c){n[i]=c,r.add(i);continue}let d=await this.checkReadOnlyBash(a);if(d){n[i]=d,r.add(i);continue}let u=this.checkRepeatCircuitBreaker(a);if(u){n[i]=u,r.add(i);continue}let p=this.checkRepeatFailureGuard(a);if(p){n[i]=p,r.add(i);continue}this.observeSuspectedLoop(a)}let o=e.map((i,a)=>({call:i,originalIndex:a})).filter((i,a)=>!r.has(a));if(o.length===0)return n;let s=sf(o.map(i=>i.call),this.classifier);for(let i of s){if(i.isConcurrencySafe){let l=[...i.indices];for(;l.length>0;){let c=new Map,d=[],u=[];for(let f of l){let{call:m,originalIndex:g}=o[f],h=this.checkRepeatFailureGuard(m);if(h){n[g]=h;continue}if(_l.has(m.name)){d.push(f);continue}let y=mr(m),w=Al-this.repeatFailureGuard.streakFor(m),k=c.get(y)??0;k<w?(c.set(y,k+1),d.push(f)):u.push(f)}l=u;let p=await ur(d,this.maxConcurrentSafeCalls,async f=>{let{call:m,originalIndex:g}=o[f];return m.signal.aborted?{result:{content:"Tool call aborted",isError:!0,failureClass:"abort"},originalIndex:g}:{result:await this.executeCore(m),originalIndex:g}});for(let f of p)if(f.status==="fulfilled")n[f.value.originalIndex]=f.value.result;else{let m=f.reason instanceof Error?f.reason.message:String(f.reason),g=d[p.indexOf(f)];n[o[g].originalIndex]={content:`Tool execution error: ${m}`,isError:!0}}for(let f of d){let{call:m,originalIndex:g}=o[f],h=n[g];h!==void 0&&h.failureClass!=="abort"&&this.repeatFailureGuard.note(m,h)}}}else for(let l of i.indices){let{call:c,originalIndex:d}=o[l];if(c.signal.aborted){n[d]={content:"Tool call aborted",isError:!0,failureClass:"abort"};continue}let u=this.checkRepeatFailureGuard(c);if(u){n[d]=u;continue}let p=await this.executeCore(c);n[d]=p,this.repeatFailureGuard.note(c,p)}let a=i.indices.length;i.indices.forEach((l,c)=>{let d=n[o[l].originalIndex];d&&(d.batchIndex=c+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=Xe(e.content,n),e.truncated=!0,T(`[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,l="";try{i=await this.subagentExecutor.execute(e)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),i={content:`Agent tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(e.name,l,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,l="";try{i=await this.skillExecutor.execute(e)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),i={content:`Skill tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(e.name,l,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)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};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}:{}};Cp(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}:{}};Ip(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(i=>{T(`firePostToolUseFailure outer catch (tool=${e}): ${String(i)}`)})}};import{spawn as Y_}from"child_process";import X_ from"os";var c_=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,d_=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,u_=/={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,}/,p_=/(\d+)\s+passing/,f_=/(\d+)\s+failing/,m_=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,g_=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,h_=/(\d+) examples?, (\d+) failures?/,y_=/OK \((\d+) tests?/,b_=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/;function w_(t){let e=t.match(c_);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 S_(t){let e=t.match(d_);if(!e)return null;let n=parseInt(e[1]??"0",10);return{runner:"jest",passed:parseInt(e[2]??"0",10),failed:n}}function v_(t){let e=t.match(u_);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 k_(t){let e=t.match(p_);if(!e)return null;let n=parseInt(e[1]??"0",10),r=t.match(f_),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function E_(t){let e=[...t.matchAll(m_)];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 A_(t){let e=t.match(g_);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 __(t){let e=t.match(h_);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 T_(t){let e=t.match(y_);if(e)return{runner:"phpunit",passed:parseInt(e[1]??"0",10),failed:0};let n=t.match(b_);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 Tl(t){return w_(t)??S_(t)??v_(t)??k_(t)??E_(t)??A_(t)??__(t)??T_(t)??null}var gf=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,x_=/[\x00-\x1F\x7F-\x9F]/g;function gs(t){return t.replace(gf,"").replace(x_," ").trim()}function Lt(t){return t.replace(gf,"")}import{statSync as R_}from"node:fs";function gr(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 C_(t){if(t===void 0)return!1;try{return R_(t),!1}catch{return!0}}function dn(t,e){let n=t instanceof Error?t.message:typeof t?.message=="string"?String(t.message):String(t);return gr(t)&&C_(e)?`working directory does not exist: ${e} (deleted worktree?) \u2014 underlying: ${n}`:n}import $t from"path";import{realpathSync as J_}from"fs";P();import{basename as $_,dirname as B_,join as ys,relative as H_,resolve as pn,sep as hr}from"path";import{homedir as ie}from"os";P();L();import{realpathSync as Sf}from"fs";import{dirname as F_,resolve as Ut,join as Cl}from"path";import{homedir as bt}from"os";var hf=!1;function Nt(t){if(hf)return;hf=!0;let e=t instanceof Error?t.message:String(t);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 Rl}from"node:fs";import{homedir as I_}from"node:os";import{basename as P_,dirname as bf,join as M_}from"node:path";var yf,xl=new Map;function wf(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function O_(t){let e=P_(t),n=e===e.toLowerCase()?e.toUpperCase():e.toLowerCase();if(n===e)return;let r;try{r=Rl(t)}catch{return}let o=xl.get(r.dev);if(o!==void 0)return o;try{let s=Rl(M_(bf(t),n)),i=r.dev===s.dev&&r.ino===s.ino;return xl.set(r.dev,i),i}catch(s){let i=wf(s);return i==="ENOENT"||i==="ENOTDIR"?(xl.set(r.dev,!1),!1):void 0}}function D_(t=I_()){if(yf!==void 0)return yf;let e=t;for(;;)try{return Rl(e),O_(e)??!0}catch(n){let r=wf(n);if(r!=="ENOENT"&&r!=="ENOTDIR")return!0;let o=bf(e);if(o===e)return!0;e=o}}function un(t,e,n=e){if(t===e||t.startsWith(e+"/"))return!0;if(!D_(n))return!1;let r=t.toLowerCase(),o=e.toLowerCase();return r===o||r.startsWith(o+"/")}var L_=[`${bt()}/.ssh`,`${bt()}/.aws`,`${bt()}/.gnupg`,`${bt()}/.config/gcloud`,"/etc","/System","/private/etc","/usr/local/etc",`${bt()}/.afk/config`,`${bt()}/.afk/state`,`${bt()}/.npmrc`,`${bt()}/.docker/config.json`];function N_(){let t=[];try{let e=oe();t.push(Ae(Ut(Cl(e,"config")))),t.push(Ae(Ut(Cl(e,"state"))))}catch(e){Nt(e)}try{t.push(Ae(Ut(fe())))}catch(e){Nt(e)}return t}function U_(){let t=b.AFK_WRITE_DENYLIST,e=t?t.split(":").map(r=>Ae(Ut(r))).filter(Boolean):[];return[...[...new Set([...L_.map(r=>Ae(Ut(r))),...N_()])],...e]}function Ae(t){let e=Ut(t);try{return Sf(e)}catch{}let n=[],r=e;for(let o=0;o<64;o++){let s=F_(r);if(s===r)break;n.unshift(r.slice(s.length+1)),r=s;try{let i=Sf(r);return Cl(i,...n)}catch{}}return e}function hs(t,e="write_file"){let n=Ae(Ut(t));for(let r of U_())if(un(n,r))throw new Error(`${e}: refusing to write to protected path: ${n} (matches denylist entry: ${r})`)}L();var j_=[`${ie()}/.ssh`,`${ie()}/.aws`,`${ie()}/.gnupg`,`${ie()}/.config/gcloud`,`${ie()}/.afk/config`,`${ie()}/.npmrc`,`${ie()}/.docker/config.json`,`${ie()}/.git-credentials`,`${ie()}/.netrc`,`${ie()}/.config/gh/hosts.yml`,`${ie()}/.kube/config`,"/etc/shadow","/etc/sudoers","/private/etc/master.passwd",`${ie()}/.password-store`,`${ie()}/Library/Application Support/Google/Chrome`,`${ie()}/Library/Application Support/Chromium`,`${ie()}/Library/Application Support/BraveSoftware`,`${ie()}/Library/Application Support/Microsoft Edge`,`${ie()}/Library/Application Support/Arc`,`${ie()}/Library/Application Support/Firefox`],kf=[".afk/config/mcp.json",".ssh/config",".ssh/known_hosts"],W_=kf.map(t=>`${ie()}/${t}`);function Ef(t){let e=pn(t);return ys(Ae(B_(e)),$_(e))}var yr;function K_(t){return t?t.split(":").map(e=>e.trim()).filter(Boolean).map(e=>e==="~"||e.startsWith("~/")?ys(ie(),e.slice(1)):e).map(e=>pn(e)):[]}function G_(){try{return[Ae(pn(ys(oe(),"config")))]}catch(t){return Nt(t),[]}}var vf=".afk/";function q_(){try{let t=oe();return kf.filter(e=>e.startsWith(vf)).map(e=>Ef(ys(t,e.slice(vf.length))))}catch(t){return Nt(t),[]}}function Af(){let t=`${b.AFK_READ_DENYLIST??""}\0${b.AFK_HOME??""}`;if(yr&&yr.key===t)return yr;let e=K_(b.AFK_READ_DENYLIST).map(r=>Ae(r)).filter(Boolean),n=[...new Set([...j_.map(r=>Ae(pn(r))),...G_()])];return yr={key:t,builtins:n,extras:e,allow:[...new Set([...W_.map(Ef),...q_()])]},yr}function z_(){let{builtins:t,extras:e}=Af();return[...t,...e]}function _f(t){let e=Ae(pn(t));return z_().filter(n=>n!==e&&un(n,e,n)).map(n=>(n.startsWith(e+hr)?H_(e,n):n.split(hr).slice(e.split(hr).length).join(hr)).split(hr).join("/"))}function br(t){let e=Ae(pn(t)),{builtins:n,extras:r,allow:o}=Af();for(let s of r)if(un(e,s))return{denied:!0,matched:s};if(o.includes(e))return{denied:!1};for(let s of n)if(un(e,s))return{denied:!0,matched:s};return{denied:!1}}function fn(t){try{return J_.native(t)}catch{let e=$t.dirname(t),n=$t.basename(t);return e===t?t:$t.join(fn(e),n)}}var Tf=new Map;function V_(t){let e=Tf.get(t);if(e!==void 0)return e;let n=fn(t);return Tf.set(t,n),n}function xf(t,e,n,r){let o=e?.resolveBase??e?.cwd??r,s=$t.isAbsolute(t)?t:$t.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=fn(s),a=n==="read"?e?.readRoots??[o]:e?.writeRoots??[o];for(let l of a){let c=V_(l),d=$t.relative(c,i);if(!d.startsWith("..")&&!$t.isAbsolute(d))return{restricted:!1,resolved:s,roots:a}}return{restricted:!0,resolved:s,roots:a}}function _e(t,e,n="read",r){let{restricted:o,resolved:s,roots:i}=xf(t,e,n,r);if(n==="read"){let a=br(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(c=>`\`${c}\``).join(", "),l=n==="read"?"read roots":"write roots";throw new Error(`Path \`${t}\` is outside the allowed ${l} [${a}].`)}return s}function Rf(t,e,n="read",r){return xf(t,e,n,r)}function Cf(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 Q_(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 bs(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 l=a.resolveBase??a.cwd??e,c=X_.homedir(),d=[];for(let u of Cf(i)){let p=u==="~"?c:u.startsWith("~/")?c+u.slice(1):u,f=Rf(p,a,"write",l);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.`),ye({event:"tool.bash_path_escape",tool:"bash",restricted_count:d.length,mode:"write"}))}return async(i,a,l)=>{let{command:c,timeout_ms:d}=Q_(i);if(a.aborted)return{content:"Command aborted",isError:!0};if(o(),l!==void 0)try{s(c,l)}catch{}return new Promise(u=>{let p=!1;function f(E){p||(p=!0,clearTimeout(g),a.removeEventListener("abort",x),u(E))}let m=Y_(c,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...(l?.resolveBase??l?.cwd??e)!==void 0?{cwd:l?.resolveBase??l?.cwd??e}:{},...l?.env!==void 0?{env:{...process.env,...l.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),h="",y="",w=0,k=!1;function S(E){if(k||p||w<8e6)return;k=!0,console.warn(`[bash] overflow kill: stream=${E} totalBytes=${w} command="${c}"`),ye({event:"tool.overflow_kill",tool:"bash",total_bytes:w,stream:E}),m.kill("SIGKILL");let R=Lt((h+y).trimEnd()),O=Tl(R)??void 0,v=Xe(R,1e5)+os;f({content:v,truncated:!0,...O!==void 0?{testResult:O}:{}})}m.stdout.on("data",E=>{let R=8e6-w,O=E.length<=R?E:E.subarray(0,Math.max(0,R));w+=O.length,h+=O.toString("utf8"),S("stdout")}),m.stderr.on("data",E=>{let R=8e6-w,O=E.length<=R?E:E.subarray(0,Math.max(0,R));w+=O.length,y+=O.toString("utf8"),S("stderr")});let x=()=>{m.pid!==void 0&&process.kill(-m.pid,"SIGKILL"),f({content:"Command aborted",isError:!0})};a.addEventListener("abort",x),a.aborted&&x(),m.on("close",E=>{if(a.aborted){f({content:"Command aborted",isError:!0});return}if(E!==null&&E!==0){let C=Ft(y.trimEnd()||h.trimEnd());f({content:`Command exited with code ${E}${C.content?`
|
|
838
|
+
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=mr(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:s_(n)})}streakFor(e){return this.streaks.get(mr(e))?.count??0}};var a_=8,_l=new Set,l_=8,Me=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 ms;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??ps,this.maxConcurrentSafeCalls=typeof e.maxConcurrentSafeCalls=="number"&&Number.isFinite(e.maxConcurrentSafeCalls)&&e.maxConcurrentSafeCalls>=1?Math.floor(e.maxConcurrentSafeCalls):l_,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 mt({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))}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=Bp(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 lt(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:e,reason:n,...this.subagentId!==void 0?{subagentId:this.subagentId}:{}})}checkRepeatCircuitBreaker(e){if(_l.has(e.name))return null;let n=af(e);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<a_?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(_l.has(e.name))return null;let n=this.repeatFailureGuard.check(e);return n===null?null:(T(`[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=pf());let n=fs(e),r=ff(this.suspectedLoopWindow,n);r.fired&&U(this.traceWriter,{phase:"suspected_loop",metadata:{tool:e.name,count:r.count,windowSize:El}})}recordForkReadDenial(e,n,r){if(this.parentSessionId===void 0||!lf.has(e.name)||!cf(n))return r;let o=this.denialBreaker??{count:0,deniedPaths:[]};o.count+=1;let s=df(e);return o.deniedPaths.includes(s)||o.deniedPaths.push(s),this.denialBreaker=o,o.count<5?r:{content:uf(o.deniedPaths,o.count),isError:!0,failureClass:cn}}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 execute(e){if(e.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:"abort"};if(this.hookRegistry){let l={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 ml(this.hookRegistry,l,{signal:e.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(c){if(c instanceof G)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=dr(e.name,this.permissions);if(!n.allowed){let l=n.reason??`Tool "${e.name}" is not permitted`;return await this.emitPreToolUseBlock(e.name,l),{content:l,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);if(i)return i;this.observeSuspectedLoop(e);let a=await this.executeCore(e);return this.repeatFailureGuard.note(e,a),a.isError!==!0&&this.resetDenialBreaker(),a}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:"abort"},r.add(i);continue}if(this.hookRegistry){let f={event:"PreToolUse",toolName:a.name,input:a.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 ml(this.hookRegistry,f,{signal:a.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(m){if(m instanceof G){n[i]=this.recordForkReadDenial(a,m.reason,{content:`Tool "${a.name}" blocked by PreToolUse hook: ${m.message}`,isError:!0,failureClass:"hook-block"}),r.add(i);continue}throw m}}let l=dr(a.name,this.permissions);if(!l.allowed){let f=l.reason??`Tool "${a.name}" is not permitted`;await this.emitPreToolUseBlock(a.name,f),n[i]={content:f,isError:!0,failureClass:"permission-denied"},r.add(i);continue}let c=await this.runCanUseTool(a);if(c){n[i]=c,r.add(i);continue}let d=await this.checkReadOnlyBash(a);if(d){n[i]=d,r.add(i);continue}let u=this.checkRepeatCircuitBreaker(a);if(u){n[i]=u,r.add(i);continue}let p=this.checkRepeatFailureGuard(a);if(p){n[i]=p,r.add(i);continue}this.observeSuspectedLoop(a)}let o=e.map((i,a)=>({call:i,originalIndex:a})).filter((i,a)=>!r.has(a));if(o.length===0)return n;let s=sf(o.map(i=>i.call),this.classifier);for(let i of s){if(i.isConcurrencySafe){let l=[...i.indices];for(;l.length>0;){let c=new Map,d=[],u=[];for(let f of l){let{call:m,originalIndex:g}=o[f],h=this.checkRepeatFailureGuard(m);if(h){n[g]=h;continue}if(_l.has(m.name)){d.push(f);continue}let y=mr(m),w=Al-this.repeatFailureGuard.streakFor(m),k=c.get(y)??0;k<w?(c.set(y,k+1),d.push(f)):u.push(f)}l=u;let p=await ur(d,this.maxConcurrentSafeCalls,async f=>{let{call:m,originalIndex:g}=o[f];return m.signal.aborted?{result:{content:"Tool call aborted",isError:!0,failureClass:"abort"},originalIndex:g}:{result:await this.executeCore(m),originalIndex:g}});for(let f of p)if(f.status==="fulfilled")n[f.value.originalIndex]=f.value.result;else{let m=f.reason instanceof Error?f.reason.message:String(f.reason),g=d[p.indexOf(f)];n[o[g].originalIndex]={content:`Tool execution error: ${m}`,isError:!0}}for(let f of d){let{call:m,originalIndex:g}=o[f],h=n[g];h!==void 0&&h.failureClass!=="abort"&&this.repeatFailureGuard.note(m,h)}}}else for(let l of i.indices){let{call:c,originalIndex:d}=o[l];if(c.signal.aborted){n[d]={content:"Tool call aborted",isError:!0,failureClass:"abort"};continue}let u=this.checkRepeatFailureGuard(c);if(u){n[d]=u;continue}let p=await this.executeCore(c);n[d]=p,this.repeatFailureGuard.note(c,p)}let a=i.indices.length;i.indices.forEach((l,c)=>{let d=n[o[l].originalIndex];d&&(d.batchIndex=c+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=Xe(e.content,n),e.truncated=!0,T(`[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,l="";try{i=await this.subagentExecutor.execute(e)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),i={content:`Agent tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(e.name,l,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,l="";try{i=await this.skillExecutor.execute(e)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),i={content:`Skill tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(e.name,l,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)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};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}:{}};Cp(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}:{}};Ip(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(i=>{T(`firePostToolUseFailure outer catch (tool=${e}): ${String(i)}`)})}};import{spawn as Y_}from"child_process";import X_ from"os";var c_=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,d_=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,u_=/={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,}/,p_=/(\d+)\s+passing/,f_=/(\d+)\s+failing/,m_=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,g_=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,h_=/(\d+) examples?, (\d+) failures?/,y_=/OK \((\d+) tests?/,b_=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/;function w_(t){let e=t.match(c_);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 S_(t){let e=t.match(d_);if(!e)return null;let n=parseInt(e[1]??"0",10);return{runner:"jest",passed:parseInt(e[2]??"0",10),failed:n}}function v_(t){let e=t.match(u_);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 k_(t){let e=t.match(p_);if(!e)return null;let n=parseInt(e[1]??"0",10),r=t.match(f_),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function E_(t){let e=[...t.matchAll(m_)];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 A_(t){let e=t.match(g_);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 __(t){let e=t.match(h_);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 T_(t){let e=t.match(y_);if(e)return{runner:"phpunit",passed:parseInt(e[1]??"0",10),failed:0};let n=t.match(b_);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 Tl(t){return w_(t)??S_(t)??v_(t)??k_(t)??E_(t)??A_(t)??__(t)??T_(t)??null}var gf=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,x_=/[\x00-\x1F\x7F-\x9F]/g;function gs(t){return t.replace(gf,"").replace(x_," ").trim()}function Lt(t){return t.replace(gf,"")}import{statSync as R_}from"node:fs";function gr(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 C_(t){if(t===void 0)return!1;try{return R_(t),!1}catch{return!0}}function dn(t,e){let n=t instanceof Error?t.message:typeof t?.message=="string"?String(t.message):String(t);return gr(t)&&C_(e)?`working directory does not exist: ${e} (deleted worktree?) \u2014 underlying: ${n}`:n}import $t from"path";import{realpathSync as J_}from"fs";P();import{basename as $_,dirname as B_,join as ys,relative as H_,resolve as pn,sep as hr}from"path";import{homedir as ie}from"os";P();L();import{realpathSync as Sf}from"fs";import{dirname as F_,resolve as Ut,join as Cl}from"path";import{homedir as bt}from"os";var hf=!1;function Nt(t){if(hf)return;hf=!0;let e=t instanceof Error?t.message:String(t);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 Rl}from"node:fs";import{homedir as I_}from"node:os";import{basename as P_,dirname as bf,join as M_}from"node:path";var yf,xl=new Map;function wf(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function O_(t){let e=P_(t),n=e===e.toLowerCase()?e.toUpperCase():e.toLowerCase();if(n===e)return;let r;try{r=Rl(t)}catch{return}let o=xl.get(r.dev);if(o!==void 0)return o;try{let s=Rl(M_(bf(t),n)),i=r.dev===s.dev&&r.ino===s.ino;return xl.set(r.dev,i),i}catch(s){let i=wf(s);return i==="ENOENT"||i==="ENOTDIR"?(xl.set(r.dev,!1),!1):void 0}}function D_(t=I_()){if(yf!==void 0)return yf;let e=t;for(;;)try{return Rl(e),O_(e)??!0}catch(n){let r=wf(n);if(r!=="ENOENT"&&r!=="ENOTDIR")return!0;let o=bf(e);if(o===e)return!0;e=o}}function un(t,e,n=e){if(t===e||t.startsWith(e+"/"))return!0;if(!D_(n))return!1;let r=t.toLowerCase(),o=e.toLowerCase();return r===o||r.startsWith(o+"/")}var L_=[`${bt()}/.ssh`,`${bt()}/.aws`,`${bt()}/.gnupg`,`${bt()}/.config/gcloud`,"/etc","/System","/private/etc","/usr/local/etc",`${bt()}/.afk/config`,`${bt()}/.afk/state`,`${bt()}/.npmrc`,`${bt()}/.docker/config.json`];function N_(){let t=[];try{let e=oe();t.push(Ae(Ut(Cl(e,"config")))),t.push(Ae(Ut(Cl(e,"state"))))}catch(e){Nt(e)}try{t.push(Ae(Ut(fe())))}catch(e){Nt(e)}return t}function U_(){let t=b.AFK_WRITE_DENYLIST,e=t?t.split(":").map(r=>Ae(Ut(r))).filter(Boolean):[];return[...[...new Set([...L_.map(r=>Ae(Ut(r))),...N_()])],...e]}function Ae(t){let e=Ut(t);try{return Sf(e)}catch{}let n=[],r=e;for(let o=0;o<64;o++){let s=F_(r);if(s===r)break;n.unshift(r.slice(s.length+1)),r=s;try{let i=Sf(r);return Cl(i,...n)}catch{}}return e}function hs(t,e="write_file"){let n=Ae(Ut(t));for(let r of U_())if(un(n,r))throw new Error(`${e}: refusing to write to protected path: ${n} (matches denylist entry: ${r})`)}L();var j_=[`${ie()}/.ssh`,`${ie()}/.aws`,`${ie()}/.gnupg`,`${ie()}/.config/gcloud`,`${ie()}/.afk/config`,`${ie()}/.npmrc`,`${ie()}/.docker/config.json`,`${ie()}/.git-credentials`,`${ie()}/.netrc`,`${ie()}/.config/gh/hosts.yml`,`${ie()}/.kube/config`,"/etc/shadow","/etc/sudoers","/private/etc/master.passwd",`${ie()}/.password-store`,`${ie()}/Library/Application Support/Google/Chrome`,`${ie()}/Library/Application Support/Chromium`,`${ie()}/Library/Application Support/BraveSoftware`,`${ie()}/Library/Application Support/Microsoft Edge`,`${ie()}/Library/Application Support/Arc`,`${ie()}/Library/Application Support/Firefox`],kf=[".afk/config/mcp.json",".ssh/config",".ssh/known_hosts"],W_=kf.map(t=>`${ie()}/${t}`);function Ef(t){let e=pn(t);return ys(Ae(B_(e)),$_(e))}var yr;function K_(t){return t?t.split(":").map(e=>e.trim()).filter(Boolean).map(e=>e==="~"||e.startsWith("~/")?ys(ie(),e.slice(1)):e).map(e=>pn(e)):[]}function G_(){try{return[Ae(pn(ys(oe(),"config")))]}catch(t){return Nt(t),[]}}var vf=".afk/";function q_(){try{let t=oe();return kf.filter(e=>e.startsWith(vf)).map(e=>Ef(ys(t,e.slice(vf.length))))}catch(t){return Nt(t),[]}}function Af(){let t=`${b.AFK_READ_DENYLIST??""}\0${b.AFK_HOME??""}`;if(yr&&yr.key===t)return yr;let e=K_(b.AFK_READ_DENYLIST).map(r=>Ae(r)).filter(Boolean),n=[...new Set([...j_.map(r=>Ae(pn(r))),...G_()])];return yr={key:t,builtins:n,extras:e,allow:[...new Set([...W_.map(Ef),...q_()])]},yr}function z_(){let{builtins:t,extras:e}=Af();return[...t,...e]}function _f(t){let e=Ae(pn(t));return z_().filter(n=>n!==e&&un(n,e,n)).map(n=>(n.startsWith(e+hr)?H_(e,n):n.split(hr).slice(e.split(hr).length).join(hr)).split(hr).join("/"))}function br(t){let e=Ae(pn(t)),{builtins:n,extras:r,allow:o}=Af();for(let s of r)if(un(e,s))return{denied:!0,matched:s};if(o.includes(e))return{denied:!1};for(let s of n)if(un(e,s))return{denied:!0,matched:s};return{denied:!1}}function fn(t){try{return J_.native(t)}catch{let e=$t.dirname(t),n=$t.basename(t);return e===t?t:$t.join(fn(e),n)}}var Tf=new Map;function V_(t){let e=Tf.get(t);if(e!==void 0)return e;let n=fn(t);return Tf.set(t,n),n}function xf(t,e,n,r){let o=e?.resolveBase??e?.cwd??r,s=$t.isAbsolute(t)?t:$t.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=fn(s),a=n==="read"?e?.readRoots??[o]:e?.writeRoots??[o];for(let l of a){let c=V_(l),d=$t.relative(c,i);if(!d.startsWith("..")&&!$t.isAbsolute(d))return{restricted:!1,resolved:s,roots:a}}return{restricted:!0,resolved:s,roots:a}}function _e(t,e,n="read",r){let{restricted:o,resolved:s,roots:i}=xf(t,e,n,r);if(n==="read"){let a=br(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(c=>`\`${c}\``).join(", "),l=n==="read"?"read roots":"write roots";throw new Error(`Path \`${t}\` is outside the allowed ${l} [${a}].`)}return s}function Rf(t,e,n="read",r){return xf(t,e,n,r)}function Cf(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 Q_(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 bs(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 l=a.resolveBase??a.cwd??e,c=X_.homedir(),d=[];for(let u of Cf(i)){let p=u==="~"?c:u.startsWith("~/")?c+u.slice(1):u,f=Rf(p,a,"write",l);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.`),ye({event:"tool.bash_path_escape",tool:"bash",restricted_count:d.length,mode:"write"}))}return async(i,a,l)=>{let{command:c,timeout_ms:d}=Q_(i);if(a.aborted)return{content:"Command aborted",isError:!0};if(o(),l!==void 0)try{s(c,l)}catch{}return new Promise(u=>{let p=!1;function f(E){p||(p=!0,clearTimeout(g),a.removeEventListener("abort",x),u(E))}let m=Y_(c,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...(l?.resolveBase??l?.cwd??e)!==void 0?{cwd:l?.resolveBase??l?.cwd??e}:{},...l?.env!==void 0?{env:{...process.env,...l.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),h="",y="",w=0,k=!1;function S(E){if(k||p||w<8e6)return;k=!0,console.warn(`[bash] overflow kill: stream=${E} totalBytes=${w} command="${c}"`),ye({event:"tool.overflow_kill",tool:"bash",total_bytes:w,stream:E}),m.kill("SIGKILL");let R=Lt((h+y).trimEnd()),O=Tl(R)??void 0,v=Xe(R,1e5)+os;f({content:v,truncated:!0,...O!==void 0?{testResult:O}:{}})}m.stdout.on("data",E=>{let R=8e6-w,O=E.length<=R?E:E.subarray(0,Math.max(0,R));w+=O.length,h+=O.toString("utf8"),S("stdout")}),m.stderr.on("data",E=>{let R=8e6-w,O=E.length<=R?E:E.subarray(0,Math.max(0,R));w+=O.length,y+=O.toString("utf8"),S("stderr")});let x=()=>{m.pid!==void 0&&process.kill(-m.pid,"SIGKILL"),f({content:"Command aborted",isError:!0})};a.addEventListener("abort",x),a.aborted&&x(),m.on("close",E=>{if(a.aborted){f({content:"Command aborted",isError:!0});return}if(E!==null&&E!==0){let C=Ft(y.trimEnd()||h.trimEnd());f({content:`Command exited with code ${E}${C.content?`
|
|
839
839
|
`+C.content:""}`,isError:!0,...C.truncated?{truncated:!0}:{}});return}if(k)return;let R=Lt((h+y).trimEnd()),O=Tl(R)??void 0,v=Ft(R);f({content:v.content,...v.truncated?{truncated:!0}:{},...O!==void 0?{testResult:O}:{}})}),m.on("error",E=>{let R=l?.resolveBase??l?.cwd??e,O;if(R===void 0&&gr(E))try{let v=process.cwd();O=dn(E,v)}catch{O=`working directory does not exist (process cwd deleted \u2014 deleted worktree?) \u2014 underlying: ${E.message}`}else O=dn(E,R);f({content:`Failed to execute: ${O}`,isError:!0})})})}}var If=bs("default");import{promises as Z_}from"fs";var eT=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 l;try{l=_e(s,n,"read",r)}catch(c){return{content:c instanceof Error?c.message:String(c),isError:!0}}try{let c=await Z_.readFile(l),d=Math.min(8192,c.length);for(let k=0;k<d;k++)if(c[k]===0)return{content:`File appears to be binary: ${l}`,isError:!0};let u=c.toString("utf-8");if(u.length===0)return{content:""};let p=u.split(`
|
|
840
840
|
`),f=Math.max(0,i-1),m=Math.min(p.length,f+a),g=p.slice(f,m),h=p.length;if(g.length===0)return{content:`... (offset ${i} is past end of file \u2014 file has ${h} lines)`};let y=String(h).length,w=g.map((k,S)=>{let x=f+S+1;return`${String(x).padStart(y," ")} ${k}`}).join(`
|
|
841
841
|
`);if(g.length<h){let k=f+1,S=f+g.length,x=S<h?` \u2014 pass offset=${S+1} to continue`:"";return{content:`${w}
|