agent-afk 5.120.0 → 5.121.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/subagent-hooks.d.ts +1 -1
- package/dist/cli.mjs +8 -6
- package/dist/index.mjs +6 -4
- package/dist/telegram.mjs +135 -133
- package/dist/utils/errors.d.ts +2 -0
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
var Jte=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var no=(e,t)=>{for(var n in t)Jte(e,n,{get:t[n],enumerable:!0})};function ds(e){return Za.find(t=>t.name===e)}function aE(e){return Za.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function Qa(e){return process.env[e]!==void 0}function rg(e){let t=process.env[e];return t===void 0||t===""?void 0:t}var KO=y(()=>{"use strict";B()});function pt(){let e=v.AFK_PLAIN_OUTPUT;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"}var Za,v,B=y(()=>{"use strict";KO();Za=[{name:"AFK_COMPACT_KEEP_LAST_TURNS",description:"Number of recent turns the compactor keeps verbatim during /compact. Default tuned in compact-handler.ts.",type:"number",required:!1,example:"6",category:"model"},{name:"AFK_COMPACT_MODEL",description:"Override the model used by the /compact summarizer. Falls back to a cheap default (haiku-class).",type:"string",required:!1,example:"claude-haiku-4-5",category:"model"},{name:"AFK_COMPACT_SHRINK_FRACTION",description:"Context-fullness fraction (0\u20131, exclusive) at/above which /compact and auto-compaction relax the keep-window so a short-but-full session (few turns, huge tool exchanges) can still be summarized instead of no-oping on turn count. Default 0.7 (see shared/compaction.ts DEFAULT_COMPACT_SHRINK_THRESHOLD).",type:"number",required:!1,example:"0.8",category:"model"},{name:"AFK_DEFAULT_SUBAGENT_MODEL",description:"Override the default model used when a subagent is dispatched without an explicit model.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_DIAGNOSE_BASELINE",description:"Kill switch for /diagnose reproducer baseline execution. When set to '0', the /diagnose skill skips executing the detected reproducer command for a ground-truth baseline; default enabled (runs). Set to '0' to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_DISABLE_PROMPT_CACHE",description:"Disable Anthropic prompt caching when set to 1/true/yes/on. Unset = caching enabled.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_DISABLE_BASH_INTERPRETER_GUARD",description:"Skip ONLY the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) when set to 1, leaving the rest of path-approval intact. Applies on interactive surfaces (REPL/Telegram), where the denylist is active but your workflow legitimately runs interpreter one-liners. The restricted-root substring check is unaffected. Default: denylist active on interactive surfaces; headless already fails open (opt in with AFK_FORCE_BASH_INTERPRETER_GUARD=1). To disable all of path-approval + bash restriction instead, use AFK_DISABLE_PATH_APPROVAL=1.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_DISABLE_PATH_APPROVAL",description:"Skip the path-approval + bash-restriction hooks entirely when set to 1. Use for headless flows that need wide-open file access (CI scripts, batch jobs). Default: hooks enabled. Note: on headless surfaces (afk chat, daemon) no grant manager is wired, so the interpreter denylist (python -c, node -e, sh -c, ...) fails OPEN by default \u2014 opt headless flows into it with AFK_FORCE_BASH_INTERPRETER_GUARD=1, or set this var to 1 to disable all of path-approval.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_FORCE_BASH_INTERPRETER_GUARD",description:"Apply the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) even on headless surfaces (afk chat, daemon) where no grant manager is wired. By default the denylist fires only on interactive surfaces (REPL/Telegram), failing open on headless so legitimate automation is not hard-blocked with no recourse. Set to 1 to opt headless flows back into the guard. Overridden by AFK_DISABLE_BASH_INTERPRETER_GUARD=1. Default: off (headless fails open).",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_EFFORT",description:"Effort hint guiding adaptive-thinking depth, forwarded as Anthropic output_config.effort (model-gated; ignored where unsupported). Accepts low | medium | high | xhigh | max.",type:"string",required:!1,example:"medium",category:"model"},{name:"AFK_MAX_BUDGET_USD",description:"Cumulative USD budget ceiling for the session. Aborts the turn when the running cost crosses this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS",description:"Maximum concurrency-safe tool calls run simultaneously within one dispatcher batch. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"4",category:"model"},{name:"AFK_MAX_CONCURRENT_SUBAGENT_CALLS",description:"Maximum subagent calls run simultaneously from one compose/DAG layer or skill wave. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"2",category:"model"},{name:"AFK_MAX_CONCURRENT_BACKGROUND_JOBS",description:"Maximum background subagent jobs running simultaneously in one registry. Default 10; accepted range 1-64; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"10",example:"5",category:"model"},{name:"AFK_MAX_NESTING_DEPTH",description:"Maximum sub-agent/skill nesting depth; 0 disables nested delegation entirely (the agent, skill, AND compose tools all refuse). A top-level session is depth 0, so the default 3 permits three generations of forked descendants (depth 1 \u2192 2 \u2192 3) and refuses the agent and skill tools at depth 3. Resolved once at the root of each session and propagated down through child AgentConfig, so descendants inherit the root value rather than re-reading the environment. Raise with care: depth is a fan-out exponent (a width-N wave at depth D reaches ~N^D concurrent children), so values above 4 invite provider rate-limit (429) cascades. Accepted range 0-6; unset, empty, unparseable, negative, or out-of-range input falls back to the default. An explicit programmatic maxDepth (SubagentExecutorContext / SkillExecutorContext) still wins.",type:"number",required:!1,default:"3",example:"2",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. When unset, falls back to the model output ceiling (AFK's own per-model limit, 64k\u2013128k \u2014 NOT a small provider default), so every request advertises the full ceiling by default. An over-ceiling value is clamped down with a warning.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Deprecated and inert: not read by the generation path. Use AFK_MAX_OUTPUT_TOKENS (or --max-output-tokens) to cap per-response output tokens; falls back to the model output ceiling when unset.",type:"number",required:!1,default:"4096",example:"8192",category:"model"},{name:"AFK_MAX_TOOL_USE_ITERATIONS",description:"Opt-in ceiling on tool-use rounds per turn for TOP-LEVEL (non-subagent) sessions, on both providers. Mirrors the maxToolUseIterations config key / max_tool_use_iterations tool param. Unset, non-numeric, or <=0 means unlimited (the default \u2014 zero behavior change): a top-level turn ends only when the model stops calling tools, the abort signal fires, the provider errors, or the dollar budget trips. A positive integer N makes top-level turns wind down gracefully after N tool rounds (one tools-stripped final round). An explicit config/CLI value wins over this env default. Does NOT affect subagent forks \u2014 they keep their own non-zero anti-hang default (SUBAGENT_DEFAULT_MAX_TOOL_USE_ITERATIONS) regardless of this var.",type:"number",required:!1,default:"0",example:"150",category:"model"},{name:"AFK_MEMORY_EVIDENCE_GATE",description:'Opt-in (set to 1) evidence gate for durable memory writes. When enabled, a codebase fact (memory_update category "convention") stored without an `evidence` citation is recalled as [unverified], and memory_search results carry a verification verdict. User preferences and agent reflections are never gated. Default off \u2014 memory behaves identically to legacy when unset.',type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_MICROCOMPACT_KEEP_LAST",description:"Number of the most-recent tool_result blocks that tool-result microcompaction keeps intact regardless of size, so the agent does not lose the tool output it is actively reasoning over. Older results are the safe ones to trim. Default 4 (see shared/compaction.ts DEFAULT_MICROCOMPACT_KEEP_LAST). Values <= 0 protect nothing.",type:"number",required:!1,default:"4",example:"3",category:"model"},{name:"AFK_MICROCOMPACT_TOOL_RESULT_BYTES",description:"Byte threshold (tool_result content length) at/above which a tool_result block becomes a microcompaction candidate. When /compact and auto-compaction would otherwise no-op on a short-but-full session, microcompaction clears large/old tool_result CONTENT in place (largest first) \u2014 replacing it with a short placeholder, never removing the block \u2014 to reclaim context deterministically (no LLM call). Blocks below this size are left intact. Default 2048 (see shared/compaction.ts DEFAULT_MICROCOMPACT_TOOL_RESULT_BYTES).",type:"number",required:!1,default:"2048",example:"4096",category:"model"},{name:"AFK_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), fixed-identity aliases (opus, sonnet, haiku, fable), or full model IDs. Migration: AFK_MODEL=sonnet now pins the fixed Sonnet identity rather than following a rebound medium tier.",type:"string",required:!1,default:"medium",example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_TTFB_TIMEOUT_MS",description:"Per-ROUND time-to-first-token budget (ms) for the anthropic-direct streaming loop. Bounds how long a round may stall BEFORE its first streamed CONTENT token (a text/thinking delta or tool_use); the connection-level message_start and keep-alive pings do NOT count. Once a content token streams, the timer is cleared and the rest of the response is governed instead by the progress-aware AFK_MODEL_STALL_TIMEOUT_MS window, so a normal slow call (below the bound) and any actively-streaming extended-thinking response are never aborted. The budget is divided into 3 shorter first-byte ATTEMPTS (each ~2/3 of this value, so the worst-case wall time per round is unchanged from the previous 2-attempt regime while a transient stall gets 3 chances instead of 2). NOTE: a request whose FIRST token takes longer than the per-attempt bound \u2014 e.g. a very large opus_1m prefill \u2014 is aborted and re-driven, then surfaces as an error once the budget is spent (raise this value or set 0 for such workloads); this trims the degrading-call tail instead of a silent ~10-min hang on the SDK default. Default 180000 (180s \u2248 2\xD7 the measured p99 ttfb), i.e. 3 \xD7 120s. Set to 0 to disable.",type:"number",required:!1,default:"180000",example:"120000",category:"model"},{name:"AFK_MODEL_STALL_TIMEOUT_MS",description:"Progress-aware POST-first-byte stall window (ms) for the anthropic-direct streaming loop. Bounds how long a stream that has ALREADY produced content may then go completely silent. Every streamed output event resets the window, so this is NOT a total-round cap: a legitimately long, actively-streaming round (large code emission, extended thinking) survives indefinitely, while a stream wedged mid-flight is aborted and surfaces as a real terminal error instead of hanging. Complements AFK_MODEL_TTFB_TIMEOUT_MS, which governs only the window BEFORE the first token; this one takes over after it. Default 1200000 (20min) \u2014 above the 18.5min maximum post-first-byte stream duration observed across 86,076 rounds in 12,381 local traces (p99 122s, p99.9 234s), so no healthy round trips it. Set to 0 to disable (issue #762).",type:"number",required:!1,default:"1200000",example:"600000",category:"model"},{name:"AFK_SUBAGENT_TIMEOUT_MS",description:"Foreground forked-subagent wall-clock budget in ms; 0 disables the cap; explicit per-fork config.timeoutMs and the 60-min background mode still win. Bounds how long a single forked child turn may run before `withTimeout` aborts its controller (cascading through the AbortGraph to descendants) and the parent receives a legible TimeoutError tool_result instead of hanging. Default 2700000 (45 min \u2248 headroom over the longest healthy review/research agent observed in production). Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to opt a whole session back into unbounded child turns. Does NOT affect the background dispatch budget (SUBAGENT_BACKGROUND_TIMEOUT_MS) or a per-fork config.timeoutMs \u2014 both take precedence.",type:"number",required:!1,default:"2700000",example:"3600000",category:"model"},{name:"AFK_SUBAGENT_IDLE_TIMEOUT_MS",description:"Forked-subagent progress-aware idle-watchdog window in ms; 0 disables the watchdog; an explicit per-fork config.idleTimeoutMs still wins. Fires when a forked child produces no observable output event for this window, aborting the same controller the wall-clock timeout targets so partial output is preserved and the run classifies as a failure. This is distinct from AFK_SUBAGENT_TIMEOUT_MS, the blunt wall-clock that bounds total turn time: the idle watchdog is the tighter first-to-fire bound and never fires while the stream is legitimately parked on a provider-communicated backoff (OAuth pause, or a rate-limit event carrying a retry-after), extending the deadline for the pause window instead. Default 480000 (8 min) clears the worst-case transient-429 backoff the watchdog is currently blind to (about 363s) with roughly 2 min of margin, while staying materially tighter than the 45-min wall-clock. Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to disable the idle watchdog for a whole session (the wall-clock still applies). v1 applies to forked sub-agent turns only, not top-level or daemon sessions.",type:"number",required:!1,default:"480000",example:"300000",category:"model"},{name:"AFK_VISION_MODELS",description:'Comma-separated override for image (vision) capability detection on the openai-compatible provider. Each token force-enables a model id by exact or substring match (e.g. "qwen2.5-vl" matches a local VL id); prefix a token with "!" to force-disable. Use to send images to a local vision-language model AFK does not recognise by name, or to blacklist a mis-detected id. Built-in detection already covers gpt-4o/4.1/5.x, o1/o3/o4-mini, Claude, and common VL families.',type:"string",required:!1,example:"qwen2.5-vl,!gpt-4o-mini",category:"model"},{name:"AFK_MODEL_LOCAL",description:'Bind the "local" capability tier (cheapest/fastest, user-configured) to a model id. Overrides afk.config.json models.local. Point at a local Ollama, LM Studio, or any OpenAI-compatible shim.',type:"string",required:!1,example:"llama3.2:3b",category:"model"},{name:"AFK_MODEL_LOCAL_API_KEY",description:'Per-slot API key for the "local" tier. Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LOCAL_BASE_URL",description:'Per-slot endpoint base URL for the "local" tier. Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:11434/v1",category:"model"},{name:"AFK_MODEL_LARGE",description:'Bind the "large" capability tier (most capable) to a model id/alias. Overrides afk.config.json models.large.',type:"string",required:!1,example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-5",category:"model"},{name:"AFK_MODEL_MEDIUM_API_KEY",description:'Per-slot API key for the "medium" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_MEDIUM_BASE_URL",description:'Per-slot endpoint base URL for the "medium" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_SMALL",description:'Bind the "small" capability tier (cheap/fast) to a model id/alias. Overrides afk.config.json models.small.',type:"string",required:!1,example:"gpt-4o-mini",category:"model"},{name:"AFK_MODEL_SMALL_API_KEY",description:'Per-slot API key for the "small" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_SMALL_BASE_URL",description:'Per-slot endpoint base URL for the "small" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_OVERLOAD_PAUSE_MS",description:"Wall-clock ceiling (ms) for the bounded pause after a mid-stream overload (529) exhausts its retry budget. Overrides the per-surface default for ALL surfaces: 0 disables the pause (fail fast). Interactive surfaces (cli/repl/telegram) default to 600000; daemon/cron default to 0 so an always-on runner never silently parks on upstream capacity.",type:"number",required:!1,example:"600000",category:"model"},{name:"AFK_PROMPT_CACHE_TTL",description:"TTL for Anthropic prompt-cache blocks. Accepts 5m or 1h.",type:"string",required:!1,default:"1h",example:"1h",category:"model"},{name:"AFK_SUGGEST_ENABLED",description:"Enable the LLM-backed ghost-text suggestion tier in the interactive REPL. Set to 1/true/yes/on to activate. Off by default.",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_PROMPT",description:"Enable LLM-generated empty-prompt suggestions \u2014 a proposed next action shown as ghost text when the prompt is blank, accepted with Tab or Right-arrow. Fires only after a turn has completed in the session: the startup prompt (and the prompt right after /clear) is left clean because there is no session context to ground a proposal in. Set to 1/true/yes/on to activate. Off by default. Requires AFK_SUGGEST_ENABLED (it reuses the same suggestion model and provider).",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_GHOST",description:"Enable REPL ghost-text inline suggestions (Tier-1 history/dropdown + optional Tier-2 LLM). 1 = on (default), 0 = off. Set 0/false/off/no to disable all ghost text. Tier-2 LLM is separately gated by AFK_SUGGEST_ENABLED.",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_MODEL",description:"Override the small model used for REPL ghost-text suggestions. Falls back to AFK_COMPACT_MODEL or haiku-class for anthropic, or the session model for other providers.",type:"string",required:!1,category:"model"},{name:"AFK_TASK_BUDGET",description:"Per-task token budget ceiling. Aborts when cumulative usage would exceed it.",type:"number",required:!1,default:"100000",example:"200000",category:"model"},{name:"AFK_TEMPERATURE",description:"Numeric temperature override for model sampling. Provider default if unset.",type:"number",required:!1,example:"0.7",category:"model"},{name:"AFK_THINKING",description:"Extended-thinking mode. Accepts adaptive | disabled | max | enabled:<N> | enabled:max. Defaults to the model-appropriate mode when unset (adaptive on current models).",type:"string",required:!1,default:"adaptive",example:"adaptive",category:"model"},{name:"AFK_THINKING_UI",description:"Default thinking-display mode for the interactive REPL: summary | live | digest | off. Display-only \u2014 controls how extended-thinking blocks render, never whether thinking runs (cost/latency unaffected). Overridden per-launch by --thinking-ui and mutable mid-session via /thinking. Precedence: --thinking-ui flag > this env > interactive.thinkingUi config > live. Invalid values are ignored.",type:"string",required:!1,default:"live",example:"digest",category:"misc"},{name:"AFK_TIMEOUT_MS",description:"Per-turn timeout in milliseconds. Provider/SDK default if unset.",type:"number",required:!1,example:"120000",category:"model"},{name:"CLAUDE_MODEL",description:"Legacy alias for AFK_MODEL \u2014 supported for back-compat with pre-AFK_* deployments.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_SYSTEM_PROMPT",description:'Raw operator-overlay prompt. Highest-priority overlay (over afk.config.json and AFK.md). Appended on top of the framework base (prompts/system-prompt.md) under an "# Operator configuration" header \u2014 it augments, never replaces, the base.',type:"string",required:!1,example:"You are a helpful agent.",category:"model"},{name:"AFK_DUMP_PROMPT",description:"Write the resolved system prompt to a file at startup. Accepts a path or 1 for default location.",type:"string",required:!1,example:"/tmp/afk-prompt.txt",category:"debug"},{name:"ANTHROPIC_API_KEY",description:"Anthropic API key. Tier-1 credential \u2014 overrides keychain OAuth and CLAUDE_CODE_OAUTH_TOKEN.",type:"string",required:!1,category:"auth",secret:!0},{name:"CLAUDE_CODE_OAUTH_TOKEN",description:"Claude Code OAuth token. Tier-2 credential \u2014 used when ANTHROPIC_API_KEY is unset; falls back to keychain.",type:"string",required:!1,category:"auth",secret:!0},{name:"OPENAI_API_KEY",description:"OpenAI API key for the openai-compatible provider (gpt-*, o1*, o3*, o4* models).",type:"string",required:!1,category:"auth",secret:!0},{name:"CODEX_API_KEY",description:"Fallback OpenAI API key for the openai-compatible provider, read after OPENAI_API_KEY. Legacy name from the removed @openai/codex-sdk integration \u2014 prefer OPENAI_API_KEY.",type:"string",required:!1,category:"auth",secret:!0},{name:"XAI_API_KEY",description:"xAI API key for the xai provider (Grok models) in API-key mode. Metered; distinct from SuperGrok / SuperGrok Heavy / X Premium+ OAuth.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_XAI_BASE_URL",description:"Base URL for xAI API-key mode. Default https://api.x.ai/v1. The OpenAI SDK appends /chat/completions.",type:"string",required:!1,example:"https://api.x.ai/v1",category:"model"},{name:"AFK_XAI_OAUTH_BASE_URL",description:"Base URL for xAI SuperGrok / SuperGrok Heavy / X Premium+ OAuth inference. Default https://cli-chat-proxy.grok.com/v1 (subscription path). Some accounts work on https://api.x.ai/v1 with OAuth \u2014 override if needed. Distinct from AFK_XAI_BASE_URL (API-key mode).",type:"string",required:!1,example:"https://cli-chat-proxy.grok.com/v1",category:"model"},{name:"AFK_LOCAL_API_KEY",description:"Placeholder API key for local Anthropic-compatible servers (vllm-mlx, etc.). Set when AFK_LOCAL_BASE_URL is configured.",type:"string",required:!1,default:"local",example:"local",category:"auth",secret:!0},{name:"AFK_LOCAL_BASE_URL",description:"Base URL for a self-hosted Anthropic-compatible server. When set, routes traffic away from api.anthropic.com.",type:"string",required:!1,example:"http://127.0.0.1:8080",category:"model"},{name:"AFK_OPENAI_BASE_URL",description:"Base URL override for the OpenAI-compatible provider. Used for local shims (mlx_lm.server, Ollama, vLLM, LM Studio). The OpenAI SDK appends `/chat/completions` itself \u2014 a value ending in `/chat/completions` will be stripped at config-load time with a one-shot warning.",type:"string",required:!1,example:"http://127.0.0.1:8000/v1",category:"model"},{name:"AFK_OPENAI_USE_RESPONSES",description:"Opt the OpenAI-compatible provider into the OpenAI Responses API instead of Chat Completions for API-key sessions. Truthy values: 1, true, yes, on. The ChatGPT-subscription OAuth path uses Responses automatically regardless of this flag.",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_OPENAI_CHATGPT_OAUTH",description:"Opt into using ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. Off by default. READ-ONLY: AFK never refreshes these tokens \u2014 re-run `codex` when the access token expires. Routes requests over the Responses API to the private ChatGPT backend (chatgpt.com/backend-api).",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_PROVIDER",description:"Force provider selection (anthropic | anthropic-direct | openai | openai-compatible | openai-codex | xai | xai-oauth). Overrides the model-name heuristic. Same surface as the --provider CLI flag; CLI flag wins when both are set.",type:"string",required:!1,example:"openai-compatible",category:"model"},{name:"EXA_API_KEY",description:"Exa (exa.ai) search API key, enabling web_scrape search mode. Free tier (20k requests/month) available at https://exa.ai. When unset, search mode returns an actionable error; markdown and raw modes are unaffected.",type:"string",required:!1,category:"auth",secret:!0},{name:"TELEGRAM_BOT_TOKEN",description:"Telegram bot token from @BotFather. Required to run the Telegram bot surface.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_BOT_TOKEN",description:"Alternative env var name for the Telegram bot token, accepted by the setup wizard.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_ALLOWED_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs allowed to interact with the bot. Required when the bot is running.",type:"string",required:!1,example:"123456789,987654321",category:"telegram"},{name:"AFK_TELEGRAM_TAG_ONLY_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs where the bot answers only when addressed (a reply to the bot, an @mention of the bot, or a text_mention resolving to the bot). Slash-commands are unaffected; chats not listed behave as usual. The afk.config.json telegram.tagOnlyChats block takes precedence. Requires Telegram privacy mode OFF (BotFather /setprivacy Disable) for non-addressed group messages to reach the bot.",type:"string",required:!1,example:"-100987654321,123456789",category:"telegram"},{name:"AFK_TELEGRAM_PRIMARY_CHAT_ID",description:"Default chat ID for outbound notifications (primary-mode routing). When unset, notifications go to the first private/DM chat in AFK_TELEGRAM_ALLOWED_CHAT_IDS. The afk.config.json telegram.notify block takes precedence.",type:"string",required:!1,example:"123456789",category:"telegram"},{name:"AFK_TELEGRAM_NOTIFY_MODE",description:"Outbound notification fan-out: primary (default \u2014 one chat), broadcast (every allowed chat), or custom (afk.config.json telegram.notify.targets). The afk.config.json telegram.notify.mode takes precedence.",type:"string",required:!1,example:"broadcast",category:"telegram"},{name:"TELEGRAM_DATA_DIR",description:"Override the directory where Telegram bot state is stored. Defaults to ~/.afk/state/telegram/.",type:"string",required:!1,category:"telegram"},{name:"TELEGRAM_VERBOSE",description:"Set to a truthy value ('1'/'true'/'yes'/'on', case-insensitive) to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"true",category:"telegram"},{name:"TMUX",description:"OS-level tmux session identifier. Set automatically by tmux to the socket path and session info (e.g. /tmp/tmux-501/default,12345,0) inside any tmux pane. Not set by AFK. Read by configureColor() to detect a tmux environment; for truecolor support on Node \u2264 24, set FORCE_COLOR=3 in your shell or ~/.afk/config/afk.env.",type:"string",required:!1,example:"/tmp/tmux-501/default,12345,0",category:"process"},{name:"AFK_TELEGRAM_TRACE",description:"Set to 1 to dump raw bridge traffic between the agent and the Telegram bot \u2014 debugging only.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_TELEGRAM_CWD",description:"Override the working directory used by the Telegram bot when spawning agent sessions.",type:"string",required:!1,category:"telegram"},{name:"AFK_HOME",description:"Override the AFK home directory. Default: ~/.afk/.",type:"string",required:!1,default:"~/.afk",example:"/opt/afk",category:"paths"},{name:"AFK_STATE_DIR",description:"Override the entire AFK state tier (sessions/, todos/, transcripts/, memory/, daemon/, etc.), not just one subdirectory. Must be an absolute path (not /). Default: $AFK_HOME/state/.",type:"string",required:!1,category:"paths"},{name:"AFK_FRAMEWORK_DIR",description:"Override the AFK agent-framework directory used for telemetry and briefs. Default: $AFK_HOME/agent-framework/.",type:"string",required:!1,category:"paths"},{name:"AFK_COMPANION_PRIMER",description:'Opt-in: absolute path to a single companion-primer file. When set, its content is bounded (capped, fenced as <companion-primer>) and appended to the system prompt at session start for top-level sessions (chat/REPL/telegram/daemon), as lower-authority "reflections, not facts" context. Unset (default) = no-op. Only the one named file is ever read \u2014 never a directory or repo walk.',type:"string",required:!1,example:"/Users/me/Projects/afk-companion/PRIMER.md",category:"paths"},{name:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WEB_PORT",description:"Port for the `afk web` browser surface. Defaults to 4141; falls back to an ephemeral port when taken. Overridden by --port.",type:"number",required:!1,example:"4141",category:"daemon"},{name:"AFK_WEB_HOST",description:"Bind address for the `afk web` browser surface. Defaults to 127.0.0.1. Unlike the daemon control surface, a non-loopback bind is REFUSED unless AFK_WEB_TOKEN (or --token) is also set, because this surface can submit prompts and approve tool use. Overridden by --host.",type:"string",required:!1,example:"127.0.0.1",category:"daemon"},{name:"AFK_WEB_TOKEN",description:"Bearer token for the `afk web` surface. When unset, a random per-run token is minted and printed in the startup URL. Setting this explicitly is also what permits a non-loopback bind.",type:"string",required:!1,category:"daemon",secret:!0},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_ON_EXIT",description:"Clean-worktree quit policy for interactive --worktree sessions: ask, keep, or remove.",type:"string",required:!1,example:"ask",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Opt-in to loading + spawning MCP servers declared in <cwd>/.mcp.json. Fail-closed: when unset (or 0), project-local servers are NOT spawned; set to a truthy value (1/true/yes/on) to load them. A project-local .mcp.json spawns arbitrary commands on session start, so it is off by default to prevent code execution when entering an untrusted repo (issue #571). Skipped servers are listed in a startup warning with the opt-in instruction.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BG_AUTO_DELIVER",description:"Auto-deliver background subagent results into the model context on the next user turn (interactive REPL). On by default. Set to 0, false, off, or no (case-insensitive) to disable, restoring the manual /bgsub:join retrieval flow.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_PLAIN_OUTPUT",description:"Force the interactive REPL to fully behave like a non-TTY surface for rendering purposes, even when stdout/stdin ARE a TTY: append-only plain-stdout output instead of the TerminalCompositor live overlay (both the persistent between-turn compositor AND the per-turn StreamRenderer overlay), AND the input surface downgrades to the simple non-TTY line reader instead of the fancy compositor-backed input box. Same code path already used for non-TTY surfaces (pipes, CI). Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM scroll regions misbehave \u2014 trades the live overlay and fancy input UX for reliability. Opt-in \u2014 default TTY behavior (live overlay + fancy input) is unchanged unless this var is set. Truthy values: 1, true (case-insensitive).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_GOBLIN_SPINNER",description:"Goblin-themed working spinner (olive frames + goblin verbs) while the agent runs tools. 1 = on (default), 0 = classic dim spinner.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_GOBLIN_MASCOT",description:"Reacting goblin mini-sprite in the reserved footer band while the agent runs tools (3 rows, animated). 1 = on, unset/0 = off (default). Claims terminal rows, so it is opt-in.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_TERM_TITLE",description:'Set the terminal/tab title (OSC 2) to reflect afk state \u2014 "afk \u2014 <cwd> \xB7 running" during a turn, "afk \u2014 <cwd>" when idle, cleared on exit. 1 = on (default when stdout is a TTY), 0 = leave the title alone. TTY-only.',type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_NOTIFY",description:"Emit a desktop completion notification (OSC 9) on turn completion, for terminals that map OSC 9 to system notifications (iTerm2, kitty, WezTerm). Opt-in and off by default (intrusive). 1 = on. TTY-only.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_THEME",description:"TUI color palette for the interactive REPL and all CLI rendering: dark | light | umber | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark; umber matches the Umber terminal, is dark-only, and is never chosen by auto. Overridden per-launch by --theme and mutable mid-session via /theme. Precedence: --theme flag > this env > config theme > auto-detect > dark. Invalid values are ignored (dark).",type:"string",required:!1,default:"dark",example:"light",category:"misc"},{name:"AFK_TEXT_MEASURE",description:"Maximum line length (columns) for unbordered streamed text in the interactive REPL: assistant prose, thinking blocks, tool-lane text, and subagent text. Display-only \u2014 affects wrapping, never behavior. Bordered elements (cards, error boxes) already cap at 100; this applies the same ceiling to the unbordered surfaces, which previously scaled to the full terminal width. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable capping and restore full-width wrapping. Unparseable or below-minimum values fall back to the default. No-op on terminals at or below the measure, so narrow terminals are unaffected.",type:"string",required:!1,default:"100",example:"full",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"COLORTERM",description:"OS-level terminal color-depth hint. Accepted values: truecolor or 24bit (24-bit color), 256color (256-color). Set by the outer terminal emulator, not by AFK. Read by chalk's supports-color to set its initial color level; also read by configureColor() to recommend FORCE_COLOR=3 for tmux truecolor users on Node \u2264 24.",type:"string",required:!1,example:"truecolor",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_RETENTION_DISABLE",description:"Disable the witness-tree retention sweep entirely, so no session directory is ever evicted.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_MAX_AGE_DAYS",description:"Evict a witness session directory once its newest content is older than this many days. Default 30.",type:"number",required:!1,default:"30",category:"debug"},{name:"AFK_WITNESS_MAX_BYTES",description:"Aggregate byte cap for the witness tree; oldest session directories are evicted first once exceeded. Default 2147483648 (2 GiB).",type:"number",required:!1,default:"2147483648",category:"debug"},{name:"AFK_WAVE_MANIFEST_DISABLED",description:"Disable the wave manifest system entirely. When set to 1, no manifest is written for parallel subagent waves, and no resumption offer is made at session start.",type:"boolean",required:!1,default:"0",example:"1",category:"misc"},{name:"AFK_WAVE_MANIFEST_TTL_HOURS",description:"Time-to-live for wave manifests in hours. Manifests older than this are deleted on reconciliation and by the witness sweep. Default 48 (two days).",type:"number",required:!1,default:"48",example:"24",category:"misc"},{name:"AFK_WAVE_RESUME_UNATTENDED",description:"When set to 1, surface wave resumption offers even on non-interactive surfaces (daemon, one-shot chat). By default, offers are only made on interactive surfaces (REPL, Telegram).",type:"boolean",required:!1,default:"0",example:"1",category:"misc"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_CAPTURE_SUBAGENT_PROMPTS",description:"Opt-in: when set to 1, every prompt a parent session sends to a subagent is written as a redacted markdown file under state/witness/<label>/prompts/. Off by default because nothing prunes the witness tree and prompts may carry secrets the regex redactor cannot catch (connection strings, PEM blocks, PII).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_CAPTURE_SUBAGENT_OUTPUT",description:"Opt-in: when set to 1, a subagent's conversational OUTPUT (assistant text plus each tool call with its arguments) is appended incrementally to a redacted markdown transcript under state/witness/<label>/outputs/. Flushed at every tool-call boundary, so a child killed by a timeout still leaves a usable partial record \u2014 the case where final-message capture yields nothing. Off by default for the same reasons as AFK_CAPTURE_SUBAGENT_PROMPTS (unpruned witness tree, best-effort regex redaction).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless on every AFK surface \u2014 the CLI entrypoint reports surface `afk`, which is in the headless set \u2014 so watching the agent work in a visible window is opt-in via `AFK_BROWSER_HEADLESS=0`, not implied by running the REPL. Note headed and headless use different chromium downloads (`chromium-*` vs `chromium_headless_shell-*`).",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_ALLOWED_DOMAINS",description:"Comma-separated allowlist of URL host globs. When set, browser_open and any navigation that targets a host outside the list returns status: blocked_by_policy. Unset means no allowlist (permissive). Patterns use simple `*` glob matching against the URL host. Combines with AFK_BROWSER_BLOCKED_DOMAINS \u2014 block wins.",type:"string",required:!1,example:"github.com,*.atlassian.net",category:"browser"},{name:"AFK_BROWSER_BLOCKED_DOMAINS",description:"Comma-separated blocklist of URL host globs. Browser navigation that matches any entry returns status: blocked_by_policy regardless of the allowlist.",type:"string",required:!1,example:"*.ads.example.com",category:"browser"},{name:"AFK_BROWSER_DOM_SNAPSHOTS",description:"Phase 2 opt-in: when set to 1, every browser_act writes a gzipped DOM snapshot sidecar under ~/.afk/state/witness/<sid>/browser/dom-snapshots/. Off by default because snapshots are large; useful for post-mortem analysis of failed actions.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_BACKEND",description:"Select the browser provider backend. Phase 1 supports only `playwright`. Reserved for future `cdp` / `mcp` adapters. Unset defaults to `playwright`.",type:"string",required:!1,example:"playwright",category:"browser"},{name:"AFK_BROWSER_CONFIG",description:"Absolute path to an alternate browser config file. Overrides the default ~/.afk/config/browser.json lookup. Useful for per-project overrides in CI.",type:"string",required:!1,example:"/path/to/browser.json",category:"browser"},{name:"AFK_BROWSER_DEFAULT_PROFILE",description:"Name of the persistent session-vault profile the agent reuses for browser sessions. The context restores its login from (and saves it back to) ~/.afk/state/browser/<profile>/storageState.json, so a human runs `afk browser login --profile <name>` once and the agent reuses that authenticated session across unattended runs. Unset defaults to `default` (a fresh, empty profile \u2014 identical to pre-vault behavior). Allowed charset: [A-Za-z0-9_-], max 128 chars.",type:"string",required:!1,example:"work",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_READ_DENYLIST",description:"Colon-separated list of additional absolute paths the read_file/grep/glob/list_directory tools refuse to read, and that the bash-restriction hook refuses to let a shell command reference on interactive surfaces (REPL, Telegram) \u2014 on headless surfaces (afk chat, daemon) bash fails open regardless of this list. A leading ~/ is expanded (~user/ is not \u2014 spell those absolutely). Built-in credential entries (~/.ssh, ~/.aws, ~/.afk/config, \u2026) always apply on top and cannot be removed. One built-in exception exists: ~/.afk/config/mcp.json (the MCP registry) IS readable \u2014 paths listed here outrank that carve-out, so set this to ~/.afk/config/mcp.json if your registry holds inline secrets rather than ${VAR} placeholders.",type:"string",required:!1,example:"/Users/me/project/.env:/Users/me/secrets",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_RATE_LIMIT_ADMISSION_DISABLED",description:"Bypass the process-wide rate-limit admission gate (issue #941). Set to 1 to skip pre-request capacity checks. Default 0 (gate active). OAuth subscription accounts already pass through automatically when no per-minute headers are returned.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_RATE_LIMIT_STAGGER_MAX_MS",description:"Jitter ceiling (ms) for the rate-limit admission bucket: each waiter at a window boundary wakes at reset + random(0..ceiling) to avoid re-storming the API. Default 500. Set to 0 in tests for deterministic timing.",type:"number",required:!1,default:"500",example:"0",category:"model"},{name:"AFK_WEB_ALLOW_PRIVATE_HOSTS",description:"Opt out of the web_scrape SSRF egress guard. When unset (default) the guard is ACTIVE: the markdown, raw, and headless-render paths refuse loopback (127/8, ::1), link-local (169.254/16 \u2014 including the 169.254.169.254 cloud instance-metadata endpoint), RFC1918 (10/8, 172.16/12, 192.168/16), carrier-grade NAT (100.64/10), IPv6 unique-local (fc00::/7), 0.0.0.0/8, and the IPv4-mapped/compatible IPv6 forms of all of those. Hostnames are resolved and the RESOLVED addresses are classified (DNS-rebinding guard), and the check is re-applied on every redirect hop. Set to 1/true to allow private-host access \u2014 needed only to scrape a local dev server. Enabling it restores a model-reachable SSRF path (issue #575).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"VISUAL",description:"Standard POSIX env var naming the user's preferred full-screen editor (with optional flags). Consulted FIRST by the /editor slash command (and its key chord) to compose a long prompt externally; takes precedence over EDITOR. No fallback editor is assumed \u2014 if neither VISUAL nor EDITOR is set, /editor prints a hint instead of guessing.",type:"string",required:!1,example:"nvim",category:"process"},{name:"EDITOR",description:"Standard POSIX env var naming the user's preferred editor (with optional flags). Consulted by the /editor slash command AFTER VISUAL, as the standard fallback. No default editor is assumed when both are unset \u2014 /editor prints a hint telling the user to set one.",type:"string",required:!1,example:"vim",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],v={get AFK_COMPACT_KEEP_LAST_TURNS(){return process.env.AFK_COMPACT_KEEP_LAST_TURNS},get AFK_COMPACT_MODEL(){return process.env.AFK_COMPACT_MODEL},get AFK_COMPACT_SHRINK_FRACTION(){return process.env.AFK_COMPACT_SHRINK_FRACTION},get AFK_COMPANION_PRIMER(){return process.env.AFK_COMPANION_PRIMER},get AFK_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_CONCURRENT_BACKGROUND_JOBS(){return process.env.AFK_MAX_CONCURRENT_BACKGROUND_JOBS},get AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS(){return process.env.AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS},get AFK_MAX_CONCURRENT_SUBAGENT_CALLS(){return process.env.AFK_MAX_CONCURRENT_SUBAGENT_CALLS},get AFK_MAX_NESTING_DEPTH(){return process.env.AFK_MAX_NESTING_DEPTH},get AFK_MAX_OUTPUT_TOKENS(){return process.env.AFK_MAX_OUTPUT_TOKENS},get AFK_MAX_TOKENS(){return process.env.AFK_MAX_TOKENS},get AFK_MAX_TOOL_USE_ITERATIONS(){return process.env.AFK_MAX_TOOL_USE_ITERATIONS},get AFK_MEMORY_EVIDENCE_GATE(){return process.env.AFK_MEMORY_EVIDENCE_GATE},get AFK_MICROCOMPACT_KEEP_LAST(){return process.env.AFK_MICROCOMPACT_KEEP_LAST},get AFK_MICROCOMPACT_TOOL_RESULT_BYTES(){return process.env.AFK_MICROCOMPACT_TOOL_RESULT_BYTES},get AFK_MODEL(){return process.env.AFK_MODEL},get AFK_MODEL_TTFB_TIMEOUT_MS(){return process.env.AFK_MODEL_TTFB_TIMEOUT_MS},get AFK_MODEL_STALL_TIMEOUT_MS(){return process.env.AFK_MODEL_STALL_TIMEOUT_MS},get AFK_MODEL_LARGE(){return process.env.AFK_MODEL_LARGE},get AFK_MODEL_LARGE_API_KEY(){return process.env.AFK_MODEL_LARGE_API_KEY},get AFK_MODEL_LARGE_BASE_URL(){return process.env.AFK_MODEL_LARGE_BASE_URL},get AFK_MODEL_LOCAL(){return process.env.AFK_MODEL_LOCAL},get AFK_MODEL_LOCAL_API_KEY(){return process.env.AFK_MODEL_LOCAL_API_KEY},get AFK_MODEL_LOCAL_BASE_URL(){return process.env.AFK_MODEL_LOCAL_BASE_URL},get AFK_MODEL_MEDIUM(){return process.env.AFK_MODEL_MEDIUM},get AFK_MODEL_MEDIUM_API_KEY(){return process.env.AFK_MODEL_MEDIUM_API_KEY},get AFK_MODEL_MEDIUM_BASE_URL(){return process.env.AFK_MODEL_MEDIUM_BASE_URL},get AFK_MODEL_SMALL(){return process.env.AFK_MODEL_SMALL},get AFK_MODEL_SMALL_API_KEY(){return process.env.AFK_MODEL_SMALL_API_KEY},get AFK_MODEL_SMALL_BASE_URL(){return process.env.AFK_MODEL_SMALL_BASE_URL},get AFK_VISION_MODELS(){return process.env.AFK_VISION_MODELS},get AFK_OVERLOAD_PAUSE_MS(){return process.env.AFK_OVERLOAD_PAUSE_MS},get AFK_PROMPT_CACHE_TTL(){return process.env.AFK_PROMPT_CACHE_TTL},get AFK_SUGGEST_ENABLED(){return process.env.AFK_SUGGEST_ENABLED},get AFK_SUGGEST_PROMPT(){return process.env.AFK_SUGGEST_PROMPT},get AFK_SUGGEST_GHOST(){return process.env.AFK_SUGGEST_GHOST},get AFK_SUGGEST_MODEL(){return process.env.AFK_SUGGEST_MODEL},get AFK_SUBAGENT_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_TIMEOUT_MS},get AFK_SUBAGENT_IDLE_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_IDLE_TIMEOUT_MS},get AFK_TASK_BUDGET(){return process.env.AFK_TASK_BUDGET},get AFK_TEMPERATURE(){return process.env.AFK_TEMPERATURE},get AFK_THINKING(){return process.env.AFK_THINKING},get AFK_THINKING_UI(){return process.env.AFK_THINKING_UI},get AFK_TIMEOUT_MS(){return process.env.AFK_TIMEOUT_MS},get CLAUDE_MODEL(){return process.env.CLAUDE_MODEL},get AFK_SYSTEM_PROMPT(){return process.env.AFK_SYSTEM_PROMPT},get AFK_DUMP_PROMPT(){return process.env.AFK_DUMP_PROMPT},get ANTHROPIC_API_KEY(){return process.env.ANTHROPIC_API_KEY},get CLAUDE_CODE_OAUTH_TOKEN(){return process.env.CLAUDE_CODE_OAUTH_TOKEN},get OPENAI_API_KEY(){return process.env.OPENAI_API_KEY},get CODEX_API_KEY(){return process.env.CODEX_API_KEY},get XAI_API_KEY(){return process.env.XAI_API_KEY},get AFK_XAI_BASE_URL(){return process.env.AFK_XAI_BASE_URL},get AFK_XAI_OAUTH_BASE_URL(){return process.env.AFK_XAI_OAUTH_BASE_URL},get AFK_LOCAL_API_KEY(){return process.env.AFK_LOCAL_API_KEY},get AFK_LOCAL_BASE_URL(){return process.env.AFK_LOCAL_BASE_URL},get AFK_OPENAI_BASE_URL(){return process.env.AFK_OPENAI_BASE_URL},get AFK_OPENAI_USE_RESPONSES(){return process.env.AFK_OPENAI_USE_RESPONSES},get AFK_OPENAI_CHATGPT_OAUTH(){return process.env.AFK_OPENAI_CHATGPT_OAUTH},get AFK_PROVIDER(){return process.env.AFK_PROVIDER},get EXA_API_KEY(){return process.env.EXA_API_KEY},get TELEGRAM_BOT_TOKEN(){return process.env.TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_BOT_TOKEN(){return process.env.AFK_TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_ALLOWED_CHAT_IDS(){return process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS},get AFK_TELEGRAM_TAG_ONLY_CHAT_IDS(){return process.env.AFK_TELEGRAM_TAG_ONLY_CHAT_IDS},get AFK_TELEGRAM_PRIMARY_CHAT_ID(){return process.env.AFK_TELEGRAM_PRIMARY_CHAT_ID},get AFK_TELEGRAM_NOTIFY_MODE(){return process.env.AFK_TELEGRAM_NOTIFY_MODE},get TELEGRAM_DATA_DIR(){return process.env.TELEGRAM_DATA_DIR},get TELEGRAM_VERBOSE(){return process.env.TELEGRAM_VERBOSE},get TMUX(){return process.env.TMUX},get AFK_TELEGRAM_TRACE(){return process.env.AFK_TELEGRAM_TRACE},get AFK_TELEGRAM_CWD(){return process.env.AFK_TELEGRAM_CWD},get AFK_HOME(){return process.env.AFK_HOME},get AFK_STATE_DIR(){return process.env.AFK_STATE_DIR},get AFK_FRAMEWORK_DIR(){return process.env.AFK_FRAMEWORK_DIR},get HOME(){return process.env.HOME},get PATH(){return process.env.PATH},get AFK_DAEMON_CWD(){return process.env.AFK_DAEMON_CWD},get AFK_DAEMON_TASK(){return process.env.AFK_DAEMON_TASK},get AFK_DAEMON_TASK_ID(){return process.env.AFK_DAEMON_TASK_ID},get AFK_DAEMON_HOST(){return process.env.AFK_DAEMON_HOST},get AFK_SESSIONSTART_COOLDOWN_MS(){return process.env.AFK_SESSIONSTART_COOLDOWN_MS},get AFK_WEB_PORT(){return process.env.AFK_WEB_PORT},get AFK_WEB_HOST(){return process.env.AFK_WEB_HOST},get AFK_WEB_TOKEN(){return process.env.AFK_WEB_TOKEN},get AFK_WORKTREE_AUTONAME(){return process.env.AFK_WORKTREE_AUTONAME},get AFK_WORKTREE_BRANCH_PREFIX(){return process.env.AFK_WORKTREE_BRANCH_PREFIX},get AFK_WORKTREE_BASE(){return process.env.AFK_WORKTREE_BASE},get AFK_WORKTREE_ON_EXIT(){return process.env.AFK_WORKTREE_ON_EXIT},get AFK_WORKTREE_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BG_AUTO_DELIVER(){return process.env.AFK_BG_AUTO_DELIVER},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_PLAIN_OUTPUT(){return process.env.AFK_PLAIN_OUTPUT},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},get AFK_GOBLIN_SPINNER(){return process.env.AFK_GOBLIN_SPINNER},get AFK_GOBLIN_MASCOT(){return process.env.AFK_GOBLIN_MASCOT},get AFK_TERM_TITLE(){return process.env.AFK_TERM_TITLE},get AFK_NOTIFY(){return process.env.AFK_NOTIFY},get AFK_SHOW_DIFFS(){return process.env.AFK_SHOW_DIFFS},get AFK_SKILL_STREAM_VERBOSE(){return process.env.AFK_SKILL_STREAM_VERBOSE},get FORCE_COLOR(){return process.env.FORCE_COLOR},get NO_COLOR(){return process.env.NO_COLOR},get AFK_THEME(){return process.env.AFK_THEME},get AFK_TEXT_MEASURE(){return process.env.AFK_TEXT_MEASURE},get COLORFGBG(){return process.env.COLORFGBG},get COLORTERM(){return process.env.COLORTERM},get AFK_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_WITNESS_RETENTION_DISABLE(){return process.env.AFK_WITNESS_RETENTION_DISABLE},get AFK_WITNESS_MAX_AGE_DAYS(){return process.env.AFK_WITNESS_MAX_AGE_DAYS},get AFK_WITNESS_MAX_BYTES(){return process.env.AFK_WITNESS_MAX_BYTES},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get AFK_CAPTURE_SUBAGENT_PROMPTS(){return process.env.AFK_CAPTURE_SUBAGENT_PROMPTS},get AFK_CAPTURE_SUBAGENT_OUTPUT(){return process.env.AFK_CAPTURE_SUBAGENT_OUTPUT},get DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_BROWSER_DEFAULT_PROFILE(){return process.env.AFK_BROWSER_DEFAULT_PROFILE},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_READ_DENYLIST(){return process.env.AFK_READ_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_RATE_LIMIT_ADMISSION_DISABLED(){return process.env.AFK_RATE_LIMIT_ADMISSION_DISABLED},get AFK_RATE_LIMIT_STAGGER_MAX_MS(){return process.env.AFK_RATE_LIMIT_STAGGER_MAX_MS},get AFK_WEB_ALLOW_PRIVATE_HOSTS(){return process.env.AFK_WEB_ALLOW_PRIVATE_HOSTS},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get VISUAL(){return process.env.VISUAL},get EDITOR(){return process.env.EDITOR},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS},get AFK_WAVE_MANIFEST_DISABLED(){return process.env.AFK_WAVE_MANIFEST_DISABLED},get AFK_WAVE_MANIFEST_TTL_HOURS(){return process.env.AFK_WAVE_MANIFEST_TTL_HOURS},get AFK_WAVE_RESUME_UNATTENDED(){return process.env.AFK_WAVE_RESUME_UNATTENDED}};(function(){for(let t of Za){if(!t.secret)continue;let n=Object.getOwnPropertyDescriptor(v,t.name);n&&Object.defineProperty(v,t.name,{...n,enumerable:!1})}})()});import{existsSync as GO,mkdirSync as Xte,renameSync as Qte,cpSync as Zte,rmSync as ene}from"fs";import{join as te,dirname as og,basename as tne,isAbsolute as lE}from"path";import{homedir as cE}from"os";import{fileURLToPath as VO}from"url";function ke(){let e=v.AFK_HOME;if(e!==void 0&&e!==""){if(!lE(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return te(cE(),".afk")}function Dt(){let e=v.AFK_FRAMEWORK_DIR;if(e!==void 0&&e!==""){if(!lE(e)||e==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${e}`);return e}return te(ke(),"agent-framework")}function yr(){return te(Dt(),"forge-telemetry.jsonl")}function YO(){return te(Dt(),"routing-decisions.jsonl")}function JO(){return te(Dt(),"briefs")}function XO(){return te(Dt(),"facets")}function cd(){return te(ke(),"skills")}function Je(){return te(ke(),"plugins")}function QO(e=process.cwd()){return te(e,".afk")}function ig(e=process.cwd()){return te(QO(e),"skills")}function sg(e=process.cwd()){return te(QO(e),"plugins")}function ag(e=process.cwd()){return te(e,".afk","plans")}function Te(){return te(Je(),".index.json")}function uE(){return te(zn(),"schedules.json")}function ro(){return te(Je(),"cache")}function ud(e){return te(ro(),e)}function el(){let e=VO(import.meta.url),t=og(e);return te(t,"bundled-plugins")}function ZO(){let e=VO(import.meta.url),t=og(e);return te(t,"web-ui-assets")}function zn(){return te(ke(),"config")}function ge(){let e=v.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!lE(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return te(ke(),"state")}function tl(){return te(ke(),"cache")}function Go(){return te(ke(),"logs")}function ot(){return te(ge(),"sessions")}function lg(){return te(ge(),"presence")}function dE(){return te(ge(),"todos")}function dd(){return te(ge(),"transcripts")}function cg(){return te(ge(),"memory")}function $t(){return te(ge(),"queue")}function ug(){return te(ge(),"session-grants.jsonl")}function pd(){return te(zn(),"permissions.json")}function eD(){return te(ke(),"farms")}function pE(e){return te(eD(),e)}function dg(e){if(!nne.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function Vn(){return te(ge(),"witness")}function un(e){return dg(e),te(Vn(),e)}function tD(e){return te(un(e),"inbound-attachments")}function nD(e){return te(un(e),"prompts")}function rD(e){return te(un(e),"outputs")}function nl(e){return!e||e.startsWith("in-memory:")?null:tne(og(e))}function mE(){return te(ge(),"receipts")}function pg(e="default"){return te(ge(),"daemon",`agent-afk@${e}`)}function oD(){return te(ge(),"worktree-sweep.lock")}function mg(){return te(ge(),"worktree-roots.json")}function Kt(){return te(zn(),"afk.env")}function dn(){return te(zn(),"afk.config.json")}function fE(){return te(zn(),"settings.json")}function iD(e=process.cwd()){return te(e,".afk","settings.json")}function fg(){return te(ke(),"AFK.md")}function gg(e=process.cwd()){return te(e,"AFK.md")}function sD(){return te(cE(),".afk.env")}function hg(){return te(cE(),".afk.config.json")}function rne(){return te(ke(),"sessions")}function one(){return te(ke(),"todos")}function ine(){return te(ke(),"transcripts")}function gE(e,t){if(e!==t&&GO(e)&&!GO(t))try{Xte(og(t),{recursive:!0});try{Qte(e,t)}catch(n){if(n.code==="EXDEV")try{Zte(e,t,{recursive:!0}),ene(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
|
|
3
|
-
`)}}}catch{}}function aD(){gE(rne(),ot())}function lD(){gE(one(),dE())}function cD(){gE(ine(),dd())}function hE(){return te(ge(),"repl-history.jsonl")}function ane(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(e.length>qO)throw new Error(`Invalid jobId: exceeds ${qO} chars`);if(!sne.test(e))throw new Error(`Invalid jobId: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function md(){return te(ge(),"bg")}function ps(e){return ane(e),te(md(),e)}function yg(e){return te(ps(e),"events.jsonl")}function yE(e){return te(ps(e),"meta.json")}function fd(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(e.length>zO)throw new Error(`Invalid browser profile: exceeds ${zO} chars`);if(!lne.test(e))throw new Error(`Invalid browser profile: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function bE(){return te(ge(),"browser")}function SE(e){return fd(e),te(bE(),e)}function gd(e){return te(SE(e),"storageState.json")}function oo(e){return typeof e=="string"&&e.length>0&&e.length<=une&&cne.test(e)}function hd(e){if(!oo(e))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(e)}`);return te(ot(),e)}function rl(e){return te(hd(e),"events.jsonl")}function wE(e){return te(hd(e),"session.key")}function yd(){return te(ge(),"mcp","server-status.json")}function bd(){return te(ge(),"waves")}function Sd(e){return te(bd(),`${e}.json`)}var nne,sne,qO,lne,zO,cne,une,K=y(()=>{"use strict";B();nne=/^[a-zA-Z0-9_-]+$/;sne=/^[A-Za-z0-9_-]+$/,qO=128;lne=/^[A-Za-z0-9_-]+$/,zO=128;cne=/^[A-Za-z0-9_-]+$/,une=128});import{randomBytes as dne}from"node:crypto";import{mkdirSync as pne,renameSync as mne,rmSync as uD,writeFileSync as fne}from"node:fs";import{dirname as gne,isAbsolute as hne,join as yne}from"node:path";function bg(){return yne(ge(),"last-cwd")}function dD(){try{uD(bg(),{force:!0})}catch{}}function pD(e){if(!hne(e))throw new Error(`recordCdIntent: target must be an absolute path, got ${JSON.stringify(e)}`);if(/[\n\r\0]/.test(e))throw new Error(`recordCdIntent: target must not contain newline/CR/NUL, got ${JSON.stringify(e)}`);try{let t=bg();pne(gne(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${dne(6).toString("hex")}`;try{fne(n,e,{encoding:"utf8",mode:384}),mne(n,t)}catch(r){try{uD(n,{force:!0})}catch{}throw r}}catch{}}function mD(){let e=v.AFK_SHELL_WRAPPER;return e==="1"||e==="true"}var Sg=y(()=>{"use strict";B();K()});import Q from"chalk";var gD,bne,Sne,hD,yD,bD,m,j=y(()=>{"use strict";gD={brand:Q.hex("#E67E4C"),mint:Q.hex("#5FE3A1"),goblin:Q.hex("#9CB04A"),user:Q.cyan,caret:Q.hex("#7AA2F7"),tool:Q.hex("#DCDCAA"),chrome:Q.hex("#B0B8C2"),syntaxString:Q.italic.hex("#8AB07A"),toolArg:Q.dim.white,thinking:Q.italic.hex("#9B8FB5"),success:Q.green,error:Q.red,warning:Q.yellow,plan:Q.hex("#9F7CE0"),bypass:Q.bold.hex("#FF6AC1"),meta:Q.blackBright,info:Q.hex("#5BA8FF"),fileRef:Q.hex("#56B5A8"),heading:Q.bold.white,label:Q.dim,dim:Q.dim,bold:Q.bold,italic:Q.italic,diffAdd:Q.green,diffRemove:Q.red,diffHunk:Q.blackBright},bne={brand:Q.hex("#C0562A"),mint:Q.hex("#1B9E63"),goblin:Q.hex("#6B7D2A"),user:Q.hex("#0E7490"),caret:Q.hex("#3B5BDB"),tool:Q.hex("#7A6E00"),chrome:Q.hex("#5A6470"),syntaxString:Q.italic.hex("#3F7A3F"),toolArg:Q.hex("#6B7280"),thinking:Q.italic.hex("#6D5B8E"),success:Q.hex("#2E7D32"),error:Q.hex("#C62828"),warning:Q.hex("#B8860B"),plan:Q.hex("#7048C0"),bypass:Q.bold.hex("#D6297F"),meta:Q.hex("#6B7280"),info:Q.hex("#1D6FD6"),fileRef:Q.hex("#0F766E"),heading:Q.bold.hex("#1F2937"),label:Q.dim,dim:Q.dim,bold:Q.bold,italic:Q.italic,diffAdd:Q.hex("#2E7D32"),diffRemove:Q.hex("#C62828"),diffHunk:Q.hex("#6B7280")},Sne={brand:Q.hex("#FF9B5A"),mint:Q.hex("#B4FCC3"),goblin:Q.hex("#A5AC55"),user:Q.hex("#42CBC8"),caret:Q.hex("#9DBEFC"),tool:Q.hex("#F7D179"),chrome:Q.hex("#D3CDC5"),syntaxString:Q.italic.hex("#96C182"),toolArg:Q.dim.hex("#D3CDC5"),thinking:Q.italic.hex("#B49EC4"),success:Q.hex("#8AE49E"),error:Q.hex("#EF7F74"),warning:Q.hex("#D7AA32"),plan:Q.hex("#AE93DE"),bypass:Q.bold.hex("#FFACE9"),meta:Q.hex("#AAA19B"),info:Q.hex("#739EF0"),fileRef:Q.hex("#80E5E2"),heading:Q.bold.hex("#F9F6F2"),label:Q.dim,dim:Q.dim,bold:Q.bold,italic:Q.italic,diffAdd:Q.hex("#8AE49E"),diffRemove:Q.hex("#EF7F74"),diffHunk:Q.hex("#AAA19B")},hD=gD,yD=bne,bD=Sne,m={...gD}});function SD(){return{keyword:m.brand,built_in:m.brand,literal:m.brand,tag:m.brand,string:m.syntaxString,regexp:m.syntaxString,attr:m.syntaxString,comment:m.meta,meta:m.meta,quote:m.meta,number:m.warning,function:m.tool,title:m.tool,class:m.tool,"selector-tag":m.tool}}var wD=y(()=>{"use strict";j()});import wne from"chalk";import{createEmphasize as vne,common as kne}from"emphasize";function kD(){br.clear()}function Rne(e){let t=br.get(e);if(t!==void 0)return br.delete(e),br.set(e,t),t}function Ane(e,t){if(br.has(e)&&br.delete(e),br.set(e,t),br.size>xne){let n=br.keys().next().value;n!==void 0&&br.delete(n)}}function TD(e,t){if(wne.level===0||e.length>Tne)return e;let n=e.length<Ene,r=n?`${t} ${e}`:"";if(n){let i=Rne(r);if(i!==void 0)return i}let o;try{if(!t||!vD.registered(t))o=e;else{let i=vD.highlight(t,e,SD());o=typeof i?.value=="string"?i.value:e}}catch{o=e}return n&&Ane(r,o),o}var vD,Tne,Ene,xne,br,kE=y(()=>{"use strict";wD();vD=vne(kne),Tne=2048,Ene=512,xne=32,br=new Map});function RD(){return xD}function Sr(e){Object.assign(m,ED[e]),kD(),xD=e}function qo(e){if(e==null)return;let t=e.trim().toLowerCase();return t==="auto"||wg.includes(t)?t:void 0}function Cne(){let e=v.COLORFGBG;if(!e)return"dark";let t=e.split(";"),n=t[t.length-1]?.trim();if(!n)return"dark";let r=Number.parseInt(n,10);return Number.isInteger(r)&&(r===7||r>=9)?"light":"dark"}function wr(e){return e==="auto"?Cne():e!==void 0?e:"dark"}function vg(e){let t=qo(e);if(t!==void 0)return t;throw new Error(`Invalid --theme value: ${e}. Expected ${[...wg,"auto"].join("|")}`)}function kg(e,t){if(e!==void 0)return e;let n=qo(v.AFK_THEME);return n!==void 0?n:t}var ED,wg,xD,ol=y(()=>{"use strict";j();kE();B();ED={dark:hD,light:yD,umber:bD},wg=Object.keys(ED),xD="dark"});var xt,mt,Tg,Ae,vr,kr,il,Eg,He=y(()=>{"use strict";xt=class extends Error{constructor(t){super(t),this.name="AbortError"}},mt=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Tg=class extends mt{constructor(t,n){super(t,n),this.name="IdleWatchdogError"}},Ae=class extends Error{constructor(n,r,o,i){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",i?.cause!==void 0&&(this.cause=i.cause)}event;reason;cause},vr=class extends Error{constructor(t){super(t),this.name="StreamIncompleteError"}},kr=class extends Error{constructor(n,r,o){super(o??`Budget ceiling reached: $${n.toFixed(4)} cumulative >= $${r.toFixed(4)} limit`);this.runningCostUsd=n;this.maxBudgetUsd=r;this.name="BudgetExceededError"}runningCostUsd;maxBudgetUsd},il=class extends Error{constructor(t){super(t),this.name="DenialCircuitBreakerError"}},Eg=class extends Error{constructor(n,r,o){super(o??`${n} provider does not support AgentConfig.${r}.`);this.provider=n;this.field=r;this.name="UnsupportedProviderConfigError"}provider;field}});import _ne from"string-width";function Be(e){return e.replace(TE,"")}function Z(e){return _ne(e)}function al(e){return e.length===0?[]:_D?Array.from(_D.segment(e),t=>t.segment):Array.from(e)}function Ine(e){let t=[],n=0,r;for(TE.lastIndex=0;(r=TE.exec(e))!==null;){if(r.index>n)for(let o of al(e.slice(n,r.index)))t.push({type:"text",value:o});t.push({type:"ansi",value:r[0]}),n=r.index+r[0].length}if(n<e.length)for(let o of al(e.slice(n)))t.push({type:"text",value:o});return t}function ft(e,t){let n=Math.max(0,t-Z(e));return e+" ".repeat(n)}function Pne(e,t){let n=Math.max(0,t-Z(e));return" ".repeat(n)+e}function EE(e,t,n="left"){let r=Math.max(0,t-Z(e));if(r===0)return e;if(n==="right")return Pne(e,t);if(n==="center"){let o=Math.floor(r/2);return" ".repeat(o)+e+" ".repeat(r-o)}return ft(e,t)}function se(e,t,n="\u2026"){if(t<=0)return"";if(Z(e)<=t)return e;let r=Z(n),o=Math.max(0,t-r),i=0,s="",a=!1,l=!1;for(let c of Ine(e)){if(c.type==="ansi"){s+=c.value,a=!0;let d=Mne.exec(c.value);d&&(l=(d[1]??"").length>0);continue}let u=i+Z(c.value);if(u>o)break;s+=c.value,i=u}return s+n+(l?One:"")+(a?"\x1B[0m":"")}function ID(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.trunc(e))):0}function xE(e,t){let n=ID(t,e.length);if(n===0||e.length===0)return 0;let r=0;for(let o of al(e)){let i=r+o.length;if(i>=n)return r;r=i}return r}function ms(e,t){let n=ID(t,e.length);if(n>=e.length||e.length===0)return e.length;let r=0;for(let o of al(e)){let i=r+o.length;if(r>=n||n>r&&n<i)return i;r=i}return e.length}var TE,_D,Mne,One,he=y(()=>{"use strict";TE=/\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P^_X][^\x1B]*\x1B\\|[@-OQ-WYZ\\\-])/g,_D=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;Mne=/^\x1b\]8;[^;\x07\x1b]*;(.*?)(?:\x07|\x1b\\)$/s,One="\x1B]8;;\x1B\\"});function oe(){let e=process.stdout.columns;return typeof e=="number"&&e>0?e:80}function Dne(){for(let e of xg)try{e()}catch{}}function $ne(){for(let e of Rg)try{e()}catch{}}function Fne(){fs!==null&&clearTimeout(fs),fs=setTimeout(()=>{fs=null,Dne()},150)}function RE(){$ne(),Fne()}function Lne(e){return xg.add(e),ll||(process.stdout.on("resize",RE),ll=!0),()=>{xg.delete(e),PD()}}function Nne(e){return Rg.add(e),ll||(process.stdout.on("resize",RE),ll=!0),()=>{Rg.delete(e),PD()}}function PD(){xg.size===0&&Rg.size===0&&(ll&&(process.stdout.off("resize",RE),ll=!1),fs!==null&&(clearTimeout(fs),fs=null))}var xg,Rg,ll,fs,Ke,Ce=y(()=>{"use strict";xg=new Set,Rg=new Set,ll=!1,fs=null;Ke={subscribe:Lne,subscribeImmediate:Nne}});import MD from"wrap-ansi";function pe(e,t,n={}){if(!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY)return e;let r=Math.floor(t);return e.replaceAll(`\r
|
|
3
|
+
`)}}}catch{}}function aD(){gE(rne(),ot())}function lD(){gE(one(),dE())}function cD(){gE(ine(),dd())}function hE(){return te(ge(),"repl-history.jsonl")}function ane(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(e.length>qO)throw new Error(`Invalid jobId: exceeds ${qO} chars`);if(!sne.test(e))throw new Error(`Invalid jobId: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function md(){return te(ge(),"bg")}function ps(e){return ane(e),te(md(),e)}function yg(e){return te(ps(e),"events.jsonl")}function yE(e){return te(ps(e),"meta.json")}function fd(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(e.length>zO)throw new Error(`Invalid browser profile: exceeds ${zO} chars`);if(!lne.test(e))throw new Error(`Invalid browser profile: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function bE(){return te(ge(),"browser")}function SE(e){return fd(e),te(bE(),e)}function gd(e){return te(SE(e),"storageState.json")}function oo(e){return typeof e=="string"&&e.length>0&&e.length<=une&&cne.test(e)}function hd(e){if(!oo(e))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(e)}`);return te(ot(),e)}function rl(e){return te(hd(e),"events.jsonl")}function wE(e){return te(hd(e),"session.key")}function yd(){return te(ge(),"mcp","server-status.json")}function bd(){return te(ge(),"waves")}function Sd(e){return te(bd(),`${e}.json`)}var nne,sne,qO,lne,zO,cne,une,K=y(()=>{"use strict";B();nne=/^[a-zA-Z0-9_-]+$/;sne=/^[A-Za-z0-9_-]+$/,qO=128;lne=/^[A-Za-z0-9_-]+$/,zO=128;cne=/^[A-Za-z0-9_-]+$/,une=128});import{randomBytes as dne}from"node:crypto";import{mkdirSync as pne,renameSync as mne,rmSync as uD,writeFileSync as fne}from"node:fs";import{dirname as gne,isAbsolute as hne,join as yne}from"node:path";function bg(){return yne(ge(),"last-cwd")}function dD(){try{uD(bg(),{force:!0})}catch{}}function pD(e){if(!hne(e))throw new Error(`recordCdIntent: target must be an absolute path, got ${JSON.stringify(e)}`);if(/[\n\r\0]/.test(e))throw new Error(`recordCdIntent: target must not contain newline/CR/NUL, got ${JSON.stringify(e)}`);try{let t=bg();pne(gne(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${dne(6).toString("hex")}`;try{fne(n,e,{encoding:"utf8",mode:384}),mne(n,t)}catch(r){try{uD(n,{force:!0})}catch{}throw r}}catch{}}function mD(){let e=v.AFK_SHELL_WRAPPER;return e==="1"||e==="true"}var Sg=y(()=>{"use strict";B();K()});import Q from"chalk";var gD,bne,Sne,hD,yD,bD,m,j=y(()=>{"use strict";gD={brand:Q.hex("#E67E4C"),mint:Q.hex("#5FE3A1"),goblin:Q.hex("#9CB04A"),user:Q.cyan,caret:Q.hex("#7AA2F7"),tool:Q.hex("#DCDCAA"),chrome:Q.hex("#B0B8C2"),syntaxString:Q.italic.hex("#8AB07A"),toolArg:Q.dim.white,thinking:Q.italic.hex("#9B8FB5"),success:Q.green,error:Q.red,warning:Q.yellow,plan:Q.hex("#9F7CE0"),bypass:Q.bold.hex("#FF6AC1"),meta:Q.blackBright,info:Q.hex("#5BA8FF"),fileRef:Q.hex("#56B5A8"),heading:Q.bold.white,label:Q.dim,dim:Q.dim,bold:Q.bold,italic:Q.italic,diffAdd:Q.green,diffRemove:Q.red,diffHunk:Q.blackBright},bne={brand:Q.hex("#C0562A"),mint:Q.hex("#1B9E63"),goblin:Q.hex("#6B7D2A"),user:Q.hex("#0E7490"),caret:Q.hex("#3B5BDB"),tool:Q.hex("#7A6E00"),chrome:Q.hex("#5A6470"),syntaxString:Q.italic.hex("#3F7A3F"),toolArg:Q.hex("#6B7280"),thinking:Q.italic.hex("#6D5B8E"),success:Q.hex("#2E7D32"),error:Q.hex("#C62828"),warning:Q.hex("#B8860B"),plan:Q.hex("#7048C0"),bypass:Q.bold.hex("#D6297F"),meta:Q.hex("#6B7280"),info:Q.hex("#1D6FD6"),fileRef:Q.hex("#0F766E"),heading:Q.bold.hex("#1F2937"),label:Q.dim,dim:Q.dim,bold:Q.bold,italic:Q.italic,diffAdd:Q.hex("#2E7D32"),diffRemove:Q.hex("#C62828"),diffHunk:Q.hex("#6B7280")},Sne={brand:Q.hex("#FF9B5A"),mint:Q.hex("#B4FCC3"),goblin:Q.hex("#A5AC55"),user:Q.hex("#42CBC8"),caret:Q.hex("#9DBEFC"),tool:Q.hex("#F7D179"),chrome:Q.hex("#D3CDC5"),syntaxString:Q.italic.hex("#96C182"),toolArg:Q.dim.hex("#D3CDC5"),thinking:Q.italic.hex("#B49EC4"),success:Q.hex("#8AE49E"),error:Q.hex("#EF7F74"),warning:Q.hex("#D7AA32"),plan:Q.hex("#AE93DE"),bypass:Q.bold.hex("#FFACE9"),meta:Q.hex("#AAA19B"),info:Q.hex("#739EF0"),fileRef:Q.hex("#80E5E2"),heading:Q.bold.hex("#F9F6F2"),label:Q.dim,dim:Q.dim,bold:Q.bold,italic:Q.italic,diffAdd:Q.hex("#8AE49E"),diffRemove:Q.hex("#EF7F74"),diffHunk:Q.hex("#AAA19B")},hD=gD,yD=bne,bD=Sne,m={...gD}});function SD(){return{keyword:m.brand,built_in:m.brand,literal:m.brand,tag:m.brand,string:m.syntaxString,regexp:m.syntaxString,attr:m.syntaxString,comment:m.meta,meta:m.meta,quote:m.meta,number:m.warning,function:m.tool,title:m.tool,class:m.tool,"selector-tag":m.tool}}var wD=y(()=>{"use strict";j()});import wne from"chalk";import{createEmphasize as vne,common as kne}from"emphasize";function kD(){br.clear()}function Rne(e){let t=br.get(e);if(t!==void 0)return br.delete(e),br.set(e,t),t}function Ane(e,t){if(br.has(e)&&br.delete(e),br.set(e,t),br.size>xne){let n=br.keys().next().value;n!==void 0&&br.delete(n)}}function TD(e,t){if(wne.level===0||e.length>Tne)return e;let n=e.length<Ene,r=n?`${t} ${e}`:"";if(n){let i=Rne(r);if(i!==void 0)return i}let o;try{if(!t||!vD.registered(t))o=e;else{let i=vD.highlight(t,e,SD());o=typeof i?.value=="string"?i.value:e}}catch{o=e}return n&&Ane(r,o),o}var vD,Tne,Ene,xne,br,kE=y(()=>{"use strict";wD();vD=vne(kne),Tne=2048,Ene=512,xne=32,br=new Map});function RD(){return xD}function Sr(e){Object.assign(m,ED[e]),kD(),xD=e}function qo(e){if(e==null)return;let t=e.trim().toLowerCase();return t==="auto"||wg.includes(t)?t:void 0}function Cne(){let e=v.COLORFGBG;if(!e)return"dark";let t=e.split(";"),n=t[t.length-1]?.trim();if(!n)return"dark";let r=Number.parseInt(n,10);return Number.isInteger(r)&&(r===7||r>=9)?"light":"dark"}function wr(e){return e==="auto"?Cne():e!==void 0?e:"dark"}function vg(e){let t=qo(e);if(t!==void 0)return t;throw new Error(`Invalid --theme value: ${e}. Expected ${[...wg,"auto"].join("|")}`)}function kg(e,t){if(e!==void 0)return e;let n=qo(v.AFK_THEME);return n!==void 0?n:t}var ED,wg,xD,ol=y(()=>{"use strict";j();kE();B();ED={dark:hD,light:yD,umber:bD},wg=Object.keys(ED),xD="dark"});var xt,mt,Tg,Ae,vr,kr,il,Eg,He=y(()=>{"use strict";xt=class extends Error{constructor(t){super(t),this.name="AbortError"}},mt=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Tg=class extends mt{constructor(t,n){super(t,n),this.name="IdleWatchdogError"}},Ae=class extends Error{constructor(n,r,o,i){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",i?.cause!==void 0&&(this.cause=i.cause),i?.injectContext!==void 0&&(this.injectContext=i.injectContext)}event;reason;cause;injectContext},vr=class extends Error{constructor(t){super(t),this.name="StreamIncompleteError"}},kr=class extends Error{constructor(n,r,o){super(o??`Budget ceiling reached: $${n.toFixed(4)} cumulative >= $${r.toFixed(4)} limit`);this.runningCostUsd=n;this.maxBudgetUsd=r;this.name="BudgetExceededError"}runningCostUsd;maxBudgetUsd},il=class extends Error{constructor(t){super(t),this.name="DenialCircuitBreakerError"}},Eg=class extends Error{constructor(n,r,o){super(o??`${n} provider does not support AgentConfig.${r}.`);this.provider=n;this.field=r;this.name="UnsupportedProviderConfigError"}provider;field}});import _ne from"string-width";function Be(e){return e.replace(TE,"")}function Z(e){return _ne(e)}function al(e){return e.length===0?[]:_D?Array.from(_D.segment(e),t=>t.segment):Array.from(e)}function Ine(e){let t=[],n=0,r;for(TE.lastIndex=0;(r=TE.exec(e))!==null;){if(r.index>n)for(let o of al(e.slice(n,r.index)))t.push({type:"text",value:o});t.push({type:"ansi",value:r[0]}),n=r.index+r[0].length}if(n<e.length)for(let o of al(e.slice(n)))t.push({type:"text",value:o});return t}function ft(e,t){let n=Math.max(0,t-Z(e));return e+" ".repeat(n)}function Pne(e,t){let n=Math.max(0,t-Z(e));return" ".repeat(n)+e}function EE(e,t,n="left"){let r=Math.max(0,t-Z(e));if(r===0)return e;if(n==="right")return Pne(e,t);if(n==="center"){let o=Math.floor(r/2);return" ".repeat(o)+e+" ".repeat(r-o)}return ft(e,t)}function se(e,t,n="\u2026"){if(t<=0)return"";if(Z(e)<=t)return e;let r=Z(n),o=Math.max(0,t-r),i=0,s="",a=!1,l=!1;for(let c of Ine(e)){if(c.type==="ansi"){s+=c.value,a=!0;let d=Mne.exec(c.value);d&&(l=(d[1]??"").length>0);continue}let u=i+Z(c.value);if(u>o)break;s+=c.value,i=u}return s+n+(l?One:"")+(a?"\x1B[0m":"")}function ID(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.trunc(e))):0}function xE(e,t){let n=ID(t,e.length);if(n===0||e.length===0)return 0;let r=0;for(let o of al(e)){let i=r+o.length;if(i>=n)return r;r=i}return r}function ms(e,t){let n=ID(t,e.length);if(n>=e.length||e.length===0)return e.length;let r=0;for(let o of al(e)){let i=r+o.length;if(r>=n||n>r&&n<i)return i;r=i}return e.length}var TE,_D,Mne,One,he=y(()=>{"use strict";TE=/\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P^_X][^\x1B]*\x1B\\|[@-OQ-WYZ\\\-])/g,_D=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;Mne=/^\x1b\]8;[^;\x07\x1b]*;(.*?)(?:\x07|\x1b\\)$/s,One="\x1B]8;;\x1B\\"});function oe(){let e=process.stdout.columns;return typeof e=="number"&&e>0?e:80}function Dne(){for(let e of xg)try{e()}catch{}}function $ne(){for(let e of Rg)try{e()}catch{}}function Fne(){fs!==null&&clearTimeout(fs),fs=setTimeout(()=>{fs=null,Dne()},150)}function RE(){$ne(),Fne()}function Lne(e){return xg.add(e),ll||(process.stdout.on("resize",RE),ll=!0),()=>{xg.delete(e),PD()}}function Nne(e){return Rg.add(e),ll||(process.stdout.on("resize",RE),ll=!0),()=>{Rg.delete(e),PD()}}function PD(){xg.size===0&&Rg.size===0&&(ll&&(process.stdout.off("resize",RE),ll=!1),fs!==null&&(clearTimeout(fs),fs=null))}var xg,Rg,ll,fs,Ke,Ce=y(()=>{"use strict";xg=new Set,Rg=new Set,ll=!1,fs=null;Ke={subscribe:Lne,subscribeImmediate:Nne}});import MD from"wrap-ansi";function pe(e,t,n={}){if(!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY)return e;let r=Math.floor(t);return e.replaceAll(`\r
|
|
4
4
|
`,`
|
|
5
5
|
`).split(`
|
|
6
6
|
`).map(o=>{let i=Array.from({length:256},(a,l)=>String.fromCodePoint(57344+l)).find(a=>!o.includes(a)),s=i?o.replace(/^((?:\x1B\[[0-9;]*m)*)( +)/,(a,l,c)=>l+i.repeat(c.length)):o;return MD(s,r,{hard:n.breakLongWords??!1,trim:!0,wordWrap:!0}).replaceAll(i??"\uE000"," ")}).join(`
|
|
@@ -70,8 +70,8 @@ ${r}
|
|
|
70
70
|
<!-- CAP REACHED at ${l$} bytes \u2014 capture stopped -->
|
|
71
71
|
`),o+=Buffer.byteLength(d,"utf8");let p=s?d:`${Nre(e)}${d}`;s=!0,l=l.then(async()=>{await Ore(t,{recursive:!0,mode:448}),await Mre(n,p,{encoding:"utf8",mode:384})}).catch(f=>{ht("subagent-output-capture",e.sessionId??"unknown","write",f)})},u=()=>{if(r.length===0)return;let d=r.join("").trim();r=[],d.length>0&&(c(Dg("say",{text:d})),a=!0)};return{observe(d){try{if(d.type==="chunk"){let p=d.chunk;if(p.type==="content"){r.push(p.content);return}if(p.type==="tool_use_detail"){if(p.pending)return;u(),c(Dg("tool",{toolName:p.toolName,toolInput:p.toolInputRaw??p.toolInput}))}return}if(d.type==="message"){if(!a&&r.length===0){let p=d.message.content.trim();p.length>0&&(c(Dg("say",{text:p})),a=!0)}return}(d.type==="done"||d.type==="error")&&(u(),a=!1)}catch(p){ht("subagent-output-capture",e.sessionId??"unknown","observe",p)}},end(d){try{u(),c(Dg("end",{reason:d}))}catch(p){ht("subagent-output-capture",e.sessionId??"unknown","end",p)}}}}var a$,l$,$re,d$=y(()=>{"use strict";B();K();Pg();Xo();BE();a$=4*1024,l$=512*1024,$re="<!-- Best-effort secret redaction only. Connection strings, PEM blocks, and PII are NOT caught. -->"});async function ys(e,t){if(e)try{await e.write({kind:"tool_call",payload:t})}catch(n){ht("trace.emit",e,"tool_call",n)}}async function An(e,t){if(e)try{await e.write({kind:"hook_decision",payload:t})}catch(n){ht("trace.emit",e,"hook_decision",n)}}async function bs(e,t){if(e)try{await e.write({kind:"subagent_lifecycle",payload:t})}catch(n){ht("trace.emit",e,"subagent_lifecycle",n)}}async function Ss(e,t){if(e)try{await e.write({kind:"background_agent",payload:t})}catch(n){ht("trace.emit",e,"background_agent",n)}}async function p$(e,t){if(e)try{await e.write({kind:"budget",payload:t})}catch(n){ht("trace.emit",e,"budget",n)}}async function m$(e,t){if(e)try{await e.write({kind:"abort",payload:t})}catch(n){ht("trace.emit",e,"abort",n)}}async function $g(e,t){if(e)try{await e.write({kind:"compaction",payload:t})}catch(n){ht("trace.emit",e,"compaction",n)}}async function f$(e,t){if(e)try{await e.write({kind:"closure",payload:t})}catch(n){ht("trace.emit",e,"closure",n)}}async function yt(e,t){if(e)try{await e.write({kind:"browser_event",payload:t})}catch(n){ht("trace.emit",e,"browser_event",n)}}async function g$(e,t){if(e)try{await e.write({kind:"queued_user_message",payload:t})}catch(n){ht("trace.emit",e,"queued_user_message",n)}}async function re(e,t){if(e)try{await e.write({kind:"session_phase",payload:t})}catch(n){ht("trace.emit",e,"session_phase",n)}}var ce=y(()=>{"use strict";Pg()});function h$(e){let t=[...e.oauthEntries??[],...e.effort?[e.effortEntry]:[],...e.extendedCacheTtl?[e.extendedCacheEntry]:[],...e.fast?[Bre]:[]].filter(Boolean);return[...new Set(t)].join(",")||void 0}var Bre,y$=y(()=>{"use strict";Bre="fast-mode-2026-02-01"});function Fg(e){return e.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Td(e,t,n,r){let o=t==="oauth"?{authToken:e}:{apiKey:e},i=typeof n=="string"&&n.length>0?{...o,baseURL:n}:o;return r?{...i,fetch:r}:i}function Qo(e,t,n,r,o,i){let s=h$({oauthEntries:e==="oauth"?Ure.split(","):[],effort:e==="oauth"&&r===!0,extendedCacheTtl:o,fast:i,effortEntry:jre,extendedCacheEntry:b$});return e!=="oauth"?s?{"anthropic-beta":s}:{}:{"anthropic-beta":s,"x-app":"cli","User-Agent":Hre,"X-Claude-Code-Session-Id":t,"x-client-request-id":n}}function S$(e){return e!=="oauth"?null:[{type:"text",text:Wre}]}var b$,Ure,jre,Hre,Wre,ws=y(()=>{"use strict";y$();b$="extended-cache-ttl-2025-04-11",Ure=`claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,${b$}`,jre="effort-2025-11-24",Hre="claude-cli/1.0.0 (external, cli)",Wre="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;"});function Ng(e){HE=e}function UE(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}function Lg(e,t,n){let r={},o=UE(e);o&&(r.id=o);let i=UE(t);i&&(r.baseUrl=i);let s=UE(n);return s&&(r.apiKey=s),r}function Kre(){return{local:Lg(v.AFK_MODEL_LOCAL,v.AFK_MODEL_LOCAL_BASE_URL,v.AFK_MODEL_LOCAL_API_KEY),small:Lg(v.AFK_MODEL_SMALL,v.AFK_MODEL_SMALL_BASE_URL,v.AFK_MODEL_SMALL_API_KEY),medium:Lg(v.AFK_MODEL_MEDIUM,v.AFK_MODEL_MEDIUM_BASE_URL,v.AFK_MODEL_MEDIUM_API_KEY),large:Lg(v.AFK_MODEL_LARGE,v.AFK_MODEL_LARGE_BASE_URL,v.AFK_MODEL_LARGE_API_KEY)}}function GE(e){let t=Kre(),n={};for(let r of xd){let o=vs[r],i=e?.[r],s=t[r],a={id:s.id??i?.id??o.id},l=i?.name;l&&(a.name=l);let c=i?.provider;c&&(a.provider=c);let u=s.baseUrl??i?.baseUrl;u&&(a.baseUrl=u);let d=s.apiKey??i?.apiKey;d&&(a.apiKey=d),n[r]=a}return n}function gl(e){return e||HE||GE()}function hl(e,t=gl()){let n=e.trim().toLowerCase();if(!(!n||n===k$)){for(let r of xd){let o=t[r].name;if(o&&o.trim().toLowerCase()===n)return r}if(n==="local"||n==="small"||n==="medium"||n==="large")return n}}function ks(e,t=gl()){if(e===void 0)return{id:""};let n=hl(e,t);if(n)return t[n];let r=KE[e.trim().toLowerCase()];return r?{id:r}:{id:e}}function xr(e,t=gl()){if(e!==void 0)return ks(e,t).id}function yl(e,t=gl()){if(e===void 0)return;let n=hl(e,t);if(n&&t[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function T$(e){let t={};if(!e||typeof e!="object")return t;let n=e;for(let r of xd){let o=qre(n[r]);o&&(t[r]=o)}return t}function E$(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();if(t==="anthropic"||t==="anthropic-direct")return"anthropic";if(t==="openai"||t==="openai-compatible")return"openai";if(t==="chatgpt-oauth"||t==="chatgpt")return"chatgpt-oauth";if(t==="xai")return"xai";if(t==="xai-oauth"||t==="xai_oauth")return"xai-oauth"}function fl(e){return typeof e=="string"?e.trim():""}function w$(e){return/[\x00-\x1f\x7f]/.test(e)}function qre(e){if(typeof e=="string"){let t=e.trim();return t?{id:t}:void 0}if(e&&typeof e=="object"){let t=e,n=fl(t.id);if(!n)return;let r={id:n},o=fl(t.name);o&&(r.name=o);let i=E$(t.provider);i&&(r.provider=i);let s=fl(t.baseUrl);s&&(r.baseUrl=s);let a=fl(t.apiKey);return a&&(r.apiKey=a),r}}function x$(e){if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:'model binding must be an object with at least an "id"'};let t=e;if("apiKey"in t||"api_key"in t)return{ok:!1,error:"per-slot API keys are credentials; set AFK_MODEL_<TIER>_API_KEY via `afk config env set` instead of afk.config.json"};if("baseUrl"in t||"base_url"in t)return{ok:!1,error:"per-slot baseUrl is an endpoint-redirect credential vector; set AFK_MODEL_<TIER>_BASE_URL via `afk config env set` instead of afk.config.json"};let n=fl(t.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(w$(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=fl(t.name);if(o){if(w$(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(Gre.has(o.trim().toLowerCase()))return{ok:!1,error:`model binding "name" must not shadow a built-in alias ("${o}")`};r.name=o}if(t.provider!==void 0&&t.provider!==""){let i=E$(t.provider);if(!i)return{ok:!1,error:'model binding "provider" must be one of: anthropic, openai (aliases: anthropic-direct, openai-compatible)'};r.provider=i}return{ok:!0,value:r}}var xd,v$,Ed,jE,WE,vs,k$,KE,Rd,HE,Gre,Ft=y(()=>{"use strict";B();xd=["local","small","medium","large"],v$="claude-haiku-4-5-20251001",Ed="claude-sonnet-4-6",jE="claude-opus-5",WE="claude-fable-5",vs={local:{id:""},small:{id:v$},medium:{id:Ed},large:{id:jE}},k$="auto",KE={opus:jE,opus_1m:jE,sonnet:Ed,sonnet_1m:Ed,haiku:v$,fable:WE},Rd=[...xd,...Object.keys(KE)];Gre=new Set([...xd,k$,...Object.keys(KE)])});function Ad(e){return e in qE}function At(e){return xr(e)}var qE,Cn=y(()=>{"use strict";Ft();qE={opus:vs.large.id,opus_1m:vs.large.id,sonnet:vs.medium.id,sonnet_1m:vs.medium.id,haiku:vs.small.id,fable:WE}});import zre from"@anthropic-ai/sdk";import{randomUUID as R$}from"node:crypto";async function bl(e){let{token:t,model:n,system:r,user:o,maxTokens:i=64,signal:s,clientFactory:a}=e;if(!t)throw new Error("oneShotCompletion: token required");let l=Fg(t),c=Td(t,l),u=a?a(c):new zre(c),d=R$(),p=R$(),f=Qo(l,d,p),g=At(n)??n,h={};Object.keys(f).length>0&&(h.headers=f),s&&(h.signal=s);let b=await u.messages.create({model:g,max_tokens:i,system:r,messages:[{role:"user",content:o}]},Object.keys(h).length>0?h:void 0),S=[];for(let k of b.content)k.type==="text"&&S.push(k.text);let w=S.join("").trim();return w.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),w}var Bg=y(()=>{"use strict";ws();Cn()});function Jre(){let e=v.AFK_VISION_MODELS,t=[],n=[];if(e)for(let r of e.split(",")){let o=r.trim().toLowerCase();if(o)if(o.startsWith("!")){let i=o.slice(1).trim();i&&n.push(i)}else t.push(o)}return{enable:t,disable:n}}function A$(e,t){return e===t||e.includes(t)}function Ug(e){if(!e)return!1;let t=(xr(e)??e).trim();if(!t)return!1;let n=t.toLowerCase(),{enable:r,disable:o}=Jre();return o.some(i=>A$(n,i))?!1:r.some(i=>A$(n,i))||Vre.has(n)?!0:Yre.some(i=>i.test(t))}function C$(e){let t=e.trim().toLowerCase();return t.includes("/")?t.slice(t.lastIndexOf("/")+1):t}function Ts(e){return e?/^o[0-9]/.test(C$(e)):!1}function Cd(e){if(!e)return!1;if(Ts(e))return!0;let t=C$(e);return Xre.some(n=>n.test(t))}var Vre,Yre,Xre,Es=y(()=>{"use strict";B();Ft();Vre=new Set(["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4-turbo","o1","o3","o4-mini"]),Yre=[/^claude-/i,/^gpt-4o/i,/^gpt-4\.1/i,/^gpt-4-turbo/i,/^gpt-4-vision/i,/^gpt-5/i,/(?:^|[/_-])(?:vl|vlm)(?:[/_.-]|$)/i,/(?:^|[/_-])(?:llava|pixtral|internvl|cogvlm|idefics|moondream|janus)/i,/(?:vision|minicpm-?[vo]|qwen[\d.]*-?vl|llama-?3\.2-\d+b-vision|gemma-3|phi-3\.5-vision|phi-4-multimodal)/i];Xre=[/^gpt-5/]});function zE(e){let t=String(e).trim().toLowerCase(),n=jg[t];if(t.endsWith("_1m")&&n!==void 0)return n;let r=xr(e)??String(e);return jg[r]??jg[r.toLowerCase()]}function xs(e){return zE(e)??Qre}function toe(e){if(!e)return!1;let t=e.trim().toLowerCase();return t?!!(t.includes("/")||t.startsWith("gpt-")||t.startsWith("gpt_")||Ts(t)||t.startsWith("codex-")||t.startsWith("codex_")||t==="codex"||t==="grok"||t.startsWith("grok-")||t.startsWith("grok_")):!1}function it(e){let t=String(e).trim().toLowerCase(),n=Sl[t];if(t.endsWith("_1m")&&n!==void 0)return n;let r=xr(e)??String(e),o=Sl[r]??Sl[r.toLowerCase()];return o!==void 0?o:toe(r)?eoe:Zre}function so(e){let t=it(e);if(String(e).trim().toLowerCase().endsWith("_1m"))return t;let r=xr(e)??String(e),o=_$[r]??_$[r.toLowerCase()];return o!==void 0?Math.min(t,o):t}var jg,Qre,Sl,Zre,eoe,_$,Yn=y(()=>{"use strict";Ft();Es();jg={opus:128e3,opus_1m:128e3,sonnet:128e3,sonnet_1m:128e3,haiku:64e3,fable:128e3,"claude-opus-5":128e3,"claude-opus-4-8":128e3,"claude-opus-4-7":128e3,"claude-opus-4-6":128e3,"claude-sonnet-5":128e3,"claude-sonnet-4-6":128e3,"claude-haiku-4-5-20251001":64e3,"claude-fable-5":128e3,"gpt-5.5":128e3,"gpt-5.6":128e3,"gpt-5.6-sol":128e3,"gpt-5.6-terra":128e3,"gpt-5.6-luna":128e3},Qre=64e3;Sl={opus:1e6,opus_1m:1e6,sonnet:1e6,sonnet_1m:1e6,haiku:2e5,fable:1e6,"claude-fable-5":1e6,"claude-sonnet-5":1e6,"claude-opus-5":1e6,"claude-opus-4-8":1e6,"claude-opus-4-7":1e6,"claude-opus-4-6":1e6,"claude-sonnet-4-6":1e6,"gpt-4o":128e3,"gpt-4o-mini":128e3,"gpt-4.1":1e6,"gpt-4.1-mini":1e6,"gpt-5.5":1e6,"gpt-5.6":1e6,"gpt-5.6-sol":1e6,"gpt-5.6-terra":1e6,"gpt-5.6-luna":1e6,o1:2e5,"o1-mini":128e3,o3:2e5,"o3-mini":2e5,"o4-mini":2e5,"mlx-community/qwen3-30b-a3b-4bit":128e3,"mlx-community/qwen3-32b-4bit":128e3,"mlx-community/qwen2.5-coder-32b-instruct-4bit":131072,"grok-4.6":5e5,"grok-4.5":5e5,"grok-4.3":1e6,"grok-4.20-0309-reasoning":1e6,"grok-4.20-0309-non-reasoning":1e6,"grok-4.20-multi-agent-0309":1e6,"grok-build-0.1":256e3},Zre=2e5,eoe=262144;_$={"claude-sonnet-5":2e5,"claude-opus-5":2e5,"claude-sonnet-4-6":2e5,"claude-opus-4-8":2e5,"claude-opus-4-7":2e5,"claude-opus-4-6":2e5}});function I$(e){return(e.inputTokens??0)+(e.outputTokens??0)}function Ct(e){return e.contextWindowTokens??I$(e)}function _d(e){return e?{totalTokens:Ct(e),apiUsage:{input_tokens:e.inputTokens??0,output_tokens:e.outputTokens??0,cache_read_input_tokens:e.cachedInputTokens??0,cache_creation_input_tokens:e.cacheCreationTokens??0,context_window_tokens:Ct(e)}}:{totalTokens:0,apiUsage:null}}function Id(e,t,n){return t<=0||e<=0||n<=0||n>=1?!1:e/t>=n}function Pd(e,t){return t<=0||e<=0?0:e/t}function P$(e){let t=it(e),n=so(e),r=xs(e);if(t<=0||r<=0||n<t)return Hg;let o=(t-r)/t-noe;return o>0?o:Hg}function Md(e,t,n,r){if(e<=0||n<=0||t<=0)return;let o=e+t;if(!(o<=n))throw new Error(`[afk] Context-window overflow: the conversation already used ~${e.toLocaleString()} tokens (last-turn API count) and the configured output ceiling is ${t.toLocaleString()} tokens \u2014 together they exceed the ${r} context window of ${n.toLocaleString()} tokens by ${(o-n).toLocaleString()} tokens. The provider would reject this request with HTTP 400. To continue: run /compact to summarise the conversation history, or start a new session.`)}function Od(e,t){if(e===void 0||e===!1)return;let n=t!==void 0?P$(t):1;if(e===!0)return Math.min(Hg,n);let r=e.threshold;if(!(typeof r!="number"||!Number.isFinite(r)||r<=0||r>=1))return Math.min(r,n)}var Hg,noe,wl=y(()=>{"use strict";Yn();Hg=.9,noe=.04});function Kg(e,t){let n=xs(t),r=e.maxOutputTokens;if(typeof r=="number"&&Number.isFinite(r)&&r>0){let o=Math.floor(r);if(o>n){let i=`max:${t}:${o}`;return Wg.has(i)||(Wg.add(i),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${t} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function M$(e){if(!e||e.length===0)return;let t=[];for(let n of e)n.user.length>0&&t.push({role:"user",content:n.user}),n.assistant.length>0&&t.push({role:"assistant",content:n.assistant});return t.length>0?t:void 0}function Gg(e,t,n){switch(e.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&ooe(n))return{type:"adaptive",display:"summarized"};if(t<=1024)throw new Error(`[afk] Extended thinking requires max_tokens > 1024 (the API constraint is 1024 <= budget_tokens < max_tokens), but the resolved output cap is ${t}. Raise --max-output-tokens / AFK_MAX_OUTPUT_TOKENS above 1024, or disable thinking with --thinking disabled.`);let r=Math.floor(t*ioe),o=Math.max(1024,t-1-r),i=e.budgetTokens!==void 0&&Number.isFinite(e.budgetTokens)?Math.floor(e.budgetTokens):void 0,s=Math.min(Math.max(i??o,1024),o);if(i!==void 0&&i>o){let a=`think:${n??"default"}:${i}:${t}`;Wg.has(a)||(Wg.add(a),console.warn(`[afk] thinking budgetTokens ${i} leaves too little of max_tokens ${t} for the reply; clamping to ${o}.`))}return{type:"enabled",budget_tokens:s,display:"summarized"}}}}function qg(e,t){if(e!==void 0)return e;let n=t.toLowerCase();if(/(claude-)?(opus|sonnet)-(4-[678]|5)/.test(n))return"max"}var roe,ooe,Wg,ioe,zg=y(()=>{"use strict";Yn();wl();roe=e=>/opus-4-(7|[89])/.test(e),ooe=e=>roe(e)||/(claude-)?(opus|sonnet)-5/.test(e),Wg=new Set,ioe=.25});import VE from"path";import{dirname as soe}from"path";import{appendFileSync as aoe,mkdirSync as loe}from"fs";var Zo,Vg=y(()=>{"use strict";K();Zo=class{hooks;constructor(t){this.hooks=t}addReadRoot(t,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots();if(!o)return;let i=VE.resolve(t);o.includes(i)||(o.push(i),this.appendAuditLog({action:"grant-read",path:i,source:n,sessionId:r}))}addWriteRoot(t,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots(),i=this.hooks.getWriteRoots();if(!o||!i)return;let s=VE.resolve(t);o.includes(s)||o.push(s),i.includes(s)||(i.push(s),this.appendAuditLog({action:"grant-write",path:s,source:n,sessionId:r}))}revokeRoot(t,n="slash",r){let o=this.hooks.getReadRoots();if(!o)return;let i=VE.resolve(t),s=this.hooks.getProtectedRoot();if(s!==void 0&&i===s)return;let a=o.indexOf(i);a!==-1&&o.splice(a,1);let l=this.hooks.getWriteRoots();if(l){let c=l.indexOf(i);c!==-1&&l.splice(c,1)}this.appendAuditLog({action:"revoke",path:i,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(t){try{let n=ug();loe(soe(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:t.sessionId??this.hooks.getDefaultSessionId?.()??null,action:t.action,path:t.path,source:t.source});aoe(n,r+`
|
|
72
72
|
`)}catch{}}}});function Jn(e){return e==="bypassPermissions"||e==="autonomous"}var vl=y(()=>{"use strict"});var Yg,O$=y(()=>{"use strict";Vg();vl();Yg=class{_readRoots;_writeRoots;_initialResolveBase;_currentCwd;_permissionMode="default";manager=new Zo({getReadRoots:()=>this._readRoots,getWriteRoots:()=>this._writeRoots,ensureInitialized:()=>this.ensureInitialized(),getProtectedRoot:()=>this._initialResolveBase,getAllowAll:()=>Jn(this._permissionMode)});get readRoots(){return this._readRoots}get writeRoots(){return this._writeRoots}get currentCwd(){return this._currentCwd}set currentCwd(t){this._currentCwd=t}get permissionMode(){return this._permissionMode}set permissionMode(t){this._permissionMode=t}ensureInitialized(t){if(!this._readRoots){let n=t?[t]:[];this._readRoots=n.slice(),this._writeRoots=n.slice(),t&&!this._initialResolveBase&&(this._initialResolveBase=t),t&&!this._currentCwd&&(this._currentCwd=t)}}}});function moe(e){return v[e]}function N$(e,t=!0){let n=moe(e.key);if(n===void 0)return{...e,rawValue:n,effectiveValue:e.defaultValue,source:"default",valid:!0};let r=n.trim(),o=Number(r);return/^\d+$/.test(r)&&Number.isInteger(o)&&o>0&&o<=e.maxValue?{...e,rawValue:n,effectiveValue:o,source:"environment",valid:!0}:(t&&!D$.has(e.key)&&(D$.add(e.key),process.stderr.write(`[afk] Invalid ${e.key}=${JSON.stringify(n)}; using default ${e.defaultValue}. Expected an integer in [1, ${e.maxValue}].
|
|
73
|
-
`)),{...e,rawValue:n,effectiveValue:e.defaultValue,source:"fallback",valid:!1})}function B$(e=!0){return L$.map(t=>N$(t,e))}function YE(e){let t=L$.find(n=>n.key===e);if(!t)throw new Error(`Unknown concurrency setting: ${e}`);return N$(t).effectiveValue}function U$(){return YE("AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS")}function Dd(){return YE("AFK_MAX_CONCURRENT_SUBAGENT_CALLS")}function j$(){return YE("AFK_MAX_CONCURRENT_BACKGROUND_JOBS")}var $$,F$,coe,uoe,doe,poe,L$,D$,$d=y(()=>{"use strict";B();$$=8,F$=8,coe=10,uoe=32,doe=32,poe=64,L$=[{key:"AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS",defaultValue:$$,maxValue:uoe},{key:"AFK_MAX_CONCURRENT_SUBAGENT_CALLS",defaultValue:F$,maxValue:doe},{key:"AFK_MAX_CONCURRENT_BACKGROUND_JOBS",defaultValue:coe,maxValue:poe}],D$=new Set});function JE(e){if(e instanceof mt)return"timeout";if(e instanceof kr)return"budget";if(typeof e=="string"){if(e==="budget"||e.startsWith("Budget "))return"budget";if(e==="timeout"||e.includes("timed out"))return"timeout";if(e==="closed")return"closed"}return"interrupted"}function Yt(e){let t=JE(e.reason);return t==="timeout"||t==="budget"?t:"abort"}var Rs=y(()=>{"use strict";He()});async function kl(e,t,n){let r=new Array(e.length),o=Math.min(Math.max(1,Math.floor(t)),e.length),i=0,s=[];for(let a=0;a<o;a++)s.push((async()=>{for(;i<e.length;){let l=i++;try{r[l]={status:"fulfilled",value:await n(e[l])}}catch(c){r[l]={status:"rejected",reason:c}}}})());return await Promise.all(s),r}var Jg=y(()=>{"use strict";$d()});function foe(e,t,n){return new Promise((r,o)=>{let i=!1,s=setTimeout(()=>{i||(i=!0,o(new Rr(n,t)))},t);s.unref(),Promise.resolve(e).then(a=>{i||(i=!0,clearTimeout(s),r(a))},a=>{i||(i=!0,clearTimeout(s),o(a))})})}function goe(e){return e.continue===!1||e.decision==="block"}function XE(e,t){if(e?.aborted){let n=e.reason,r=`aborted during ${t}${n?`: ${String(n)}`:""}`;throw new xt(r)}}function H$(){return new QE}var As,Rr,QE,Fd=y(()=>{"use strict";He();As=3e4;Rr=class extends Error{constructor(n,r){super(`hook handler timed out after ${r}ms during ${n}`);this.hookEvent=n;this.timeoutMs=r;this.name="HookHandlerTimeoutError"}hookEvent;timeoutMs;code="HOOK_HANDLER_TIMEOUT"},QE=class{handlers=new Map;register(t,n,r={}){let o=this.handlers.get(t);o||(o=[],this.handlers.set(t,o));let i={handler:n,options:r};return o.push(i),()=>{let s=this.handlers.get(t);if(!s)return;let a=s.indexOf(i);a>=0&&s.splice(a,1)}}count(t){return this.handlers.get(t)?.length??0}async dispatch(t,n,r=As){XE(n,t.event);let o=this.handlers.get(t.event);if(!o||o.length===0)return{};let i=o.slice(),s={};for(let a of i){XE(n,t.event);let l;try{let u=a.handler(t,n);l=!a.options.longRunning&&r>0&&Number.isFinite(r)?await foe(u,r,t.event):await u}catch(u){throw u instanceof Rr?u:new Ae(`hook handler threw during ${t.event}`,t.event,u instanceof Error?u.message:String(u),{cause:u})}if(XE(n,t.event),goe(l))throw new Ae(`hook handler blocked ${t.event}${l.reason?`: ${l.reason}`:""}`,t.event,l.reason);let c=[s.injectContext,l.injectContext].filter(u=>typeof u=="string"&&u.length>0).join(`
|
|
74
|
-
`);s={...s,...l,...c.length>0?{injectContext:c}:{}}}return s}}});async function Ar(e,t,n,r){if(!e)return;if(r.kind==="blocked"){await An(e,{hookEvent:t,decision:"block",...r.err.reason!==void 0?{reason:r.err.reason}:{},...t==="PreToolUse"&&n.toolName!==void 0?{blockedTool:n.toolName}:{}});return}let o=r.decision;await An(e,{hookEvent:t,decision:o.decision,...o.reason!==void 0?{reason:o.reason}:{},...o.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(o.injectContext,"utf8")}:{}})}async function W$(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await Ar(n.traceWriter,"SubagentStart",{},{kind:"decision",decision:r})}catch(r){throw r instanceof Ae&&await Ar(n.traceWriter,"SubagentStart",{},{kind:"blocked",err:r}),r}}function hoe(e,t,n){return new Promise((r,o)=>{let i=!1,s=setTimeout(()=>{i||(i=!0,o(new Rr(n,t)))},t);s.unref(),e.then(a=>{i||(i=!0,clearTimeout(s),r(a))},a=>{i||(i=!0,clearTimeout(s),o(a))})})}async function K$(e,t,n={}){if(!e)return{};try{let r=await hoe(e.dispatch(t,n.signal,As),As,"SubagentStop");return await Ar(n.traceWriter,"SubagentStop",{},{kind:"decision",decision:r}),r}catch(r){return r instanceof Rr?(console.warn(`[afk] SubagentStop hook timed out after ${As}ms (subagentId=${t.subagentId}): ${r.message}`),n.onError?.(r),{}):(r instanceof Ae&&await Ar(n.traceWriter,"SubagentStop",{},{kind:"blocked",err:r}),r instanceof Ae||r instanceof xt?(U(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):(U(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{}))}}async function G$(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await Ar(n.traceWriter,"PreToolUse",{toolName:t.toolName},{kind:"decision",decision:r})}catch(r){throw r instanceof Ae&&await Ar(n.traceWriter,"PreToolUse",{toolName:t.toolName},{kind:"blocked",err:r}),r}}async function q$(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await Ar(n.traceWriter,"PostToolUse",{toolName:t.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof Ae&&await Ar(n.traceWriter,"PostToolUse",{toolName:t.toolName},{kind:"blocked",err:r}),r instanceof Ae||r instanceof xt){U(`PostToolUse hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}U(`PostToolUse hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}async function z$(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await Ar(n.traceWriter,"PostToolUseFailure",{toolName:t.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof Ae&&await Ar(n.traceWriter,"PostToolUseFailure",{toolName:t.toolName},{kind:"blocked",err:r}),r instanceof Ae||r instanceof xt){U(`PostToolUseFailure hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}U(`PostToolUseFailure hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var Xg=y(()=>{"use strict";ue();He();Fd();ce()});function V$(e,t){return t?.allowedTools?t.allowedTools.includes(e)?{allowed:!0}:{allowed:!1,reason:`Tool "${e}" is not in the configured allowlist`}:{allowed:!0}}function Qg(e,t){return Y$(e,t)}function Zg(e,t){return Y$(e,t)}function Y$(e,t){if(!e?.allowedTools||t.length===0)return e;let n=new Set(e.allowedTools),r=!1;for(let o of t)n.has(o)||(n.add(o),r=!0);return r?{...e,allowedTools:[...n]}:e}var eh=y(()=>{"use strict"});function qoe(e){return e.replace(/'[^']*'/g," ").replace(/"(?:[^"\\]|\\.)*"/g,t=>/\$\(|`/.test(t)?t:" ")}function ZE(e){return(e.split("/").pop()??e).replace(/^\\+/,"")}function X$(e){let t=[],n=[],r=[],o="",i=!1,s=()=>{i&&(r.push(o),o="",i=!1)},a=()=>{s(),r.length>0&&(t.push(r),r=[])},l=d=>{let p=d,f=1,g="";for(;p<e.length&&f>0;){let h=e[p];if(h==="(")f++;else if(h===")"&&(f--,f===0)){p++;break}g+=h,p++}return n.push(g),p},c=0,u=e.length;for(;c<u;){let d=e[c];if(d==="'"){for(i=!0,c++;c<u&&e[c]!=="'";)o+=e[c],c++;c++;continue}if(d==='"'){for(i=!0,c++;c<u&&e[c]!=='"';)if(e[c]==="$"&&e[c+1]==="(")c=l(c+2);else if(e[c]==="`"){c++;let p="";for(;c<u&&e[c]!=="`";)p+=e[c],c++;c++,n.push(p)}else o+=e[c],c++;c++;continue}if(d==="`"){s(),c++;let p="";for(;c<u&&e[c]!=="`";)p+=e[c],c++;c++,n.push(p);continue}if(d==="$"&&e[c+1]==="("){s(),c=l(c+2);continue}if(d===";"||d===`
|
|
73
|
+
`)),{...e,rawValue:n,effectiveValue:e.defaultValue,source:"fallback",valid:!1})}function B$(e=!0){return L$.map(t=>N$(t,e))}function YE(e){let t=L$.find(n=>n.key===e);if(!t)throw new Error(`Unknown concurrency setting: ${e}`);return N$(t).effectiveValue}function U$(){return YE("AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS")}function Dd(){return YE("AFK_MAX_CONCURRENT_SUBAGENT_CALLS")}function j$(){return YE("AFK_MAX_CONCURRENT_BACKGROUND_JOBS")}var $$,F$,coe,uoe,doe,poe,L$,D$,$d=y(()=>{"use strict";B();$$=8,F$=8,coe=10,uoe=32,doe=32,poe=64,L$=[{key:"AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS",defaultValue:$$,maxValue:uoe},{key:"AFK_MAX_CONCURRENT_SUBAGENT_CALLS",defaultValue:F$,maxValue:doe},{key:"AFK_MAX_CONCURRENT_BACKGROUND_JOBS",defaultValue:coe,maxValue:poe}],D$=new Set});function JE(e){if(e instanceof mt)return"timeout";if(e instanceof kr)return"budget";if(typeof e=="string"){if(e==="budget"||e.startsWith("Budget "))return"budget";if(e==="timeout"||e.includes("timed out"))return"timeout";if(e==="closed")return"closed"}return"interrupted"}function Yt(e){let t=JE(e.reason);return t==="timeout"||t==="budget"?t:"abort"}var Rs=y(()=>{"use strict";He()});async function kl(e,t,n){let r=new Array(e.length),o=Math.min(Math.max(1,Math.floor(t)),e.length),i=0,s=[];for(let a=0;a<o;a++)s.push((async()=>{for(;i<e.length;){let l=i++;try{r[l]={status:"fulfilled",value:await n(e[l])}}catch(c){r[l]={status:"rejected",reason:c}}}})());return await Promise.all(s),r}var Jg=y(()=>{"use strict";$d()});function foe(e,t,n){return new Promise((r,o)=>{let i=!1,s=setTimeout(()=>{i||(i=!0,o(new Rr(n,t)))},t);s.unref(),Promise.resolve(e).then(a=>{i||(i=!0,clearTimeout(s),r(a))},a=>{i||(i=!0,clearTimeout(s),o(a))})})}function goe(e){return e.continue===!1||e.decision==="block"}function XE(e,t){if(e?.aborted){let n=e.reason,r=`aborted during ${t}${n?`: ${String(n)}`:""}`;throw new xt(r)}}function H$(){return new QE}var As,Rr,QE,Fd=y(()=>{"use strict";He();As=3e4;Rr=class extends Error{constructor(n,r){super(`hook handler timed out after ${r}ms during ${n}`);this.hookEvent=n;this.timeoutMs=r;this.name="HookHandlerTimeoutError"}hookEvent;timeoutMs;code="HOOK_HANDLER_TIMEOUT"},QE=class{handlers=new Map;register(t,n,r={}){let o=this.handlers.get(t);o||(o=[],this.handlers.set(t,o));let i={handler:n,options:r};return o.push(i),()=>{let s=this.handlers.get(t);if(!s)return;let a=s.indexOf(i);a>=0&&s.splice(a,1)}}count(t){return this.handlers.get(t)?.length??0}async dispatch(t,n,r=As){XE(n,t.event);let o=this.handlers.get(t.event);if(!o||o.length===0)return{};let i=o.slice(),s={};for(let a of i){XE(n,t.event);let l;try{let u=a.handler(t,n);l=!a.options.longRunning&&r>0&&Number.isFinite(r)?await foe(u,r,t.event):await u}catch(u){throw u instanceof Rr?u:new Ae(`hook handler threw during ${t.event}`,t.event,u instanceof Error?u.message:String(u),{cause:u})}if(XE(n,t.event),goe(l))throw new Ae(`hook handler blocked ${t.event}${l.reason?`: ${l.reason}`:""}`,t.event,l.reason,l.injectContext!==void 0?{injectContext:l.injectContext}:void 0);let c=[s.injectContext,l.injectContext].filter(u=>typeof u=="string"&&u.length>0).join(`
|
|
74
|
+
`);s={...s,...l,...c.length>0?{injectContext:c}:{}}}return s}}});async function Ar(e,t,n,r){if(!e)return;if(r.kind==="blocked"){await An(e,{hookEvent:t,decision:"block",...r.err.reason!==void 0?{reason:r.err.reason}:{},...t==="PreToolUse"&&n.toolName!==void 0?{blockedTool:n.toolName}:{}});return}let o=r.decision;await An(e,{hookEvent:t,decision:o.decision,...o.reason!==void 0?{reason:o.reason}:{},...o.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(o.injectContext,"utf8")}:{}})}async function W$(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await Ar(n.traceWriter,"SubagentStart",{},{kind:"decision",decision:r})}catch(r){throw r instanceof Ae&&await Ar(n.traceWriter,"SubagentStart",{},{kind:"blocked",err:r}),r}}function hoe(e,t,n){return new Promise((r,o)=>{let i=!1,s=setTimeout(()=>{i||(i=!0,o(new Rr(n,t)))},t);s.unref(),e.then(a=>{i||(i=!0,clearTimeout(s),r(a))},a=>{i||(i=!0,clearTimeout(s),o(a))})})}async function K$(e,t,n={}){if(!e)return{};try{let r=await hoe(e.dispatch(t,n.signal,As),As,"SubagentStop");return await Ar(n.traceWriter,"SubagentStop",{},{kind:"decision",decision:r}),r}catch(r){return r instanceof Rr?(console.warn(`[afk] SubagentStop hook timed out after ${As}ms (subagentId=${t.subagentId}): ${r.message}`),n.onError?.(r),{}):(r instanceof Ae&&await Ar(n.traceWriter,"SubagentStop",{},{kind:"blocked",err:r}),r instanceof Ae||r instanceof xt?(U(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):(U(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{}))}}async function G$(e,t,n={}){if(!e)return{};try{let r=await e.dispatch(t,n.signal);return await Ar(n.traceWriter,"PreToolUse",{toolName:t.toolName},{kind:"decision",decision:r}),r}catch(r){throw r instanceof Ae&&await Ar(n.traceWriter,"PreToolUse",{toolName:t.toolName},{kind:"blocked",err:r}),r}}async function q$(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await Ar(n.traceWriter,"PostToolUse",{toolName:t.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof Ae&&await Ar(n.traceWriter,"PostToolUse",{toolName:t.toolName},{kind:"blocked",err:r}),r instanceof Ae||r instanceof xt){U(`PostToolUse hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}U(`PostToolUse hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}async function z$(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await Ar(n.traceWriter,"PostToolUseFailure",{toolName:t.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof Ae&&await Ar(n.traceWriter,"PostToolUseFailure",{toolName:t.toolName},{kind:"blocked",err:r}),r instanceof Ae||r instanceof xt){U(`PostToolUseFailure hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}U(`PostToolUseFailure hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var Xg=y(()=>{"use strict";ue();He();Fd();ce()});function V$(e,t){return t?.allowedTools?t.allowedTools.includes(e)?{allowed:!0}:{allowed:!1,reason:`Tool "${e}" is not in the configured allowlist`}:{allowed:!0}}function Qg(e,t){return Y$(e,t)}function Zg(e,t){return Y$(e,t)}function Y$(e,t){if(!e?.allowedTools||t.length===0)return e;let n=new Set(e.allowedTools),r=!1;for(let o of t)n.has(o)||(n.add(o),r=!0);return r?{...e,allowedTools:[...n]}:e}var eh=y(()=>{"use strict"});function qoe(e){return e.replace(/'[^']*'/g," ").replace(/"(?:[^"\\]|\\.)*"/g,t=>/\$\(|`/.test(t)?t:" ")}function ZE(e){return(e.split("/").pop()??e).replace(/^\\+/,"")}function X$(e){let t=[],n=[],r=[],o="",i=!1,s=()=>{i&&(r.push(o),o="",i=!1)},a=()=>{s(),r.length>0&&(t.push(r),r=[])},l=d=>{let p=d,f=1,g="";for(;p<e.length&&f>0;){let h=e[p];if(h==="(")f++;else if(h===")"&&(f--,f===0)){p++;break}g+=h,p++}return n.push(g),p},c=0,u=e.length;for(;c<u;){let d=e[c];if(d==="'"){for(i=!0,c++;c<u&&e[c]!=="'";)o+=e[c],c++;c++;continue}if(d==='"'){for(i=!0,c++;c<u&&e[c]!=='"';)if(e[c]==="$"&&e[c+1]==="(")c=l(c+2);else if(e[c]==="`"){c++;let p="";for(;c<u&&e[c]!=="`";)p+=e[c],c++;c++,n.push(p)}else o+=e[c],c++;c++;continue}if(d==="`"){s(),c++;let p="";for(;c<u&&e[c]!=="`";)p+=e[c],c++;c++,n.push(p);continue}if(d==="$"&&e[c+1]==="("){s(),c=l(c+2);continue}if(d===";"||d===`
|
|
75
75
|
`||d==="&"||d==="|"||d==="("||d===")"){a(),c++;continue}if(d===" "||d===" "||d==="\r"){s(),c++;continue}o+=d,i=!0,c++}a();for(let d of n)for(let p of X$(d))t.push(p);return t}function Joe(e,t){let n=[...e],r=0,o=n[r];for((o==="export"||o==="local"||o==="declare")&&r++;r<n.length;){let i=/^([A-Za-z_]\w*)=(.*)$/.exec(n[r]);if(i===null)break;t.set(i[1],i[2]),r++}for(let i=0;r<n.length&&i<12;i++){let s=n[r],a=/^\$\{?([A-Za-z_]\w*)\}?$/.exec(s);if(a!==null){let c=t.get(a[1]);if(c!==void 0){let u=c.split(/\s+/).filter(Boolean);n=[...n.slice(0,r),...u,...n.slice(r+1)];continue}}let l=ZE(s);if(!zoe.has(l))break;if(r++,l==="env")for(;r<n.length;){let c=n[r],u=/^([A-Za-z_]\w*)=(.*)$/.exec(c);if(u!==null){t.set(u[1],u[2]),r++;continue}if(!c.startsWith("-"))break;r++,Voe.has(c)&&r<n.length&&r++}else if(l==="xargs")for(;r<n.length&&n[r].startsWith("-");){let c=n[r];r++,Yoe.has(c)&&r<n.length&&r++}else if(l==="timeout"){for(;r<n.length&&n[r].startsWith("-");){let c=n[r];r++,(c==="-k"||c==="--kill-after"||c==="-s"||c==="--signal")&&r<n.length&&r++}r<n.length&&/^[\d.]+[smhd]?$/.test(n[r])&&r++}else if(l==="nice")for(;r<n.length&&n[r].startsWith("-");){let c=n[r];r++,c==="-n"&&r<n.length&&r++}else for(;r<n.length&&n[r].startsWith("-");){let c=n[r];r++,(c==="-u"||c==="--user")&&r<n.length&&r++}}return r>=n.length?null:{command:n[r],argv:n.slice(r+1)}}function Zoe(e){let t=0;for(;t<e.length;){let n=e[t];if(Xoe.has(n)){t+=2;continue}if(!n.startsWith("-"))break;t++}return{sub:e[t],rest:e.slice(t+1)}}function Q$(e){if(e.includes("--help")||e.includes("-h"))return null;let{sub:t,rest:n}=Zoe(e);if(t===void 0||t==="help"||t==="config")return null;if(Qoe.has(t))return"git repository mutation";let r=n[0]??"";switch(t){case"tag":return r.startsWith("-")?"git tag create/delete":null;case"branch":return/^-[dDmMcC]/.test(r)||/^--(delete|move|copy|force)/.test(r)?"git branch delete/rename":null;case"remote":return["add","remove","rm","set-url","rename"].includes(r)?"git remote mutation":null;case"worktree":return["add","remove","prune","move","lock","unlock"].includes(r)?"git worktree mutation (add/remove/prune/move)":null;case"stash":return r==="list"||r==="show"?null:"git stash mutation (only `stash list`/`stash show` allowed)";default:return null}}function tie(e){if((e.command.split("/").pop()??e.command)!=="curl")return!1;for(let n=0;n<e.argv.length;n++){let r=e.argv[n];if((r==="-X"||r==="--request")&&eie.test(e.argv[n+1]??"")||/^-X(POST|PUT|PATCH|DELETE)$/i.test(r)||/^--request=(POST|PUT|PATCH|DELETE)$/i.test(r))return!0}return!1}function J$(e){for(let t=0;t<e.length-1;t++)if(ZE(e[t])==="git"){let n=Q$(e.slice(t+1));if(n!==null)return n}return null}function nie(e){let t=new Map;for(let n of X$(e)){let r=Joe(n,t);if(r===null){let s=J$(n);if(s!==null)return s;continue}let o=ZE(r.command);if(o==="git"){let s=Q$(r.argv);if(s!==null)return s;continue}if(o==="curl"&&tie(r))return"curl write method (POST/PUT/PATCH/DELETE)";let i=J$(n);if(i!==null)return i}return null}function nh(e){if(typeof e!="string"||e.trim().length===0)return{mutating:!1};for(let i of Koe)if(i.re.test(e))return{mutating:!0,reason:i.reason};let t=e.match($oe)?.[1];if(t&&Foe.test(t))return{mutating:!0,reason:"interpreter one-liner file write (`-c`/`-e`)"};let n=nie(e);if(n!==null)return{mutating:!0,reason:n};let r=qoe(e);for(let i of Goe)if(i.re.test(r))return{mutating:!0,reason:i.reason};let o=r.replace(Hoe," ").replace(joe," ").replace(/&(>>?)/g,"$1");return Woe.test(o)?{mutating:!0,reason:"output redirection to a file (`>`/`>>`)"}:{mutating:!1}}var yoe,boe,Soe,woe,voe,koe,Toe,Eoe,xoe,Roe,th,Aoe,Coe,_oe,Ioe,Poe,Moe,Ooe,Doe,$oe,Foe,Loe,Noe,Boe,Uoe,joe,Hoe,Woe,Koe,Goe,zoe,Voe,Yoe,Xoe,Qoe,eie,ex=y(()=>{"use strict";yoe=/\bgit\s+config\b[^|;&]*\s(--add|--unset|--unset-all|--replace-all|--rename-section|--remove-section|--edit|-e)\b/i,boe=/\bgit\s+config\s+(?:--(?:global|system|local|worktree)\s+|(?:--file|-f)\s+\S+\s+)*[\w][\w.-]*\s+\S/i,Soe=/\bgh\s+\w[\w-]*\s+(create|merge|close|edit|delete|comment|review|reopen|sync|fork|clone|ready)\b/i,woe=/\bgh\s+api\b.*(-X|--method)\s+(POST|PUT|PATCH|DELETE)\b/i,voe=/\bgh\s+api\b.*(\s-f\b|\s-F\b|--field\b)/i,koe=/\bgh\s+(secret|variable|workflow|release|run|cache|ssh-key|gpg-key)\s+(set|run|rerun|cancel|upload|delete|enable|disable)\b/i,Toe=/\|\s*(sh|bash|zsh|dash|ksh|mksh|csh|tcsh|fish|ash|python3?|node|nodejs|perl|ruby|php|bun)\b/i,Eoe=/\b(rm|rmdir|unlink|mv|cp|mkdir|touch|dd|truncate|tee|sponge|ln|chmod|chown|chgrp|shred|rsync)\b/i,xoe=/\bfind\b[^|;&]*\s-delete\b/i,Roe=/\bfind\b[^|;&]*\s-exec\s+['"]?\s*(rm|rmdir|unlink|mv|cp|dd|truncate|shred|tee|chmod|chown|chgrp|install|patch)\b/i,th=String.raw`(?:^|[\n;|&(]|\$\()\s*`,Aoe=new RegExp(th+String.raw`patch\b`,"i"),Coe=new RegExp(th+String.raw`install\b`,"i"),_oe=new RegExp(th+String.raw`(?:source\b|\.\s+\S)`,"i"),Ioe=/\btar\s+-?[a-zA-Z]*[cxruA][a-zA-Z]*\b/i,Poe=new RegExp(th+String.raw`unzip\b`,"i"),Moe=/\bcpio\b[^|;&]*\s-[a-zA-Z]*i\b/i,Ooe=/\bsed\b[^|;&]*\s-[a-zA-Z]*i\b/i,Doe=/\bperl\b[^|;&]*\s-[a-zA-Z]*i\b/i,$oe=/\b(?:python3?|nodejs|node|bun|ruby|perl|php)\b[^|;&]*?\s-(?:c|e)\b\s*("(?:[^"\\]|\\.)*"|'[^']*'|`[^`]*`)/i,Foe=/open\s*\([^)]*,\s*['"][wax]|writeFileSync|writeFile\b|appendFileSync|appendFile\b|createWriteStream|File\.(?:write|delete)\b|IO\.write\b|FileUtils\.|\bBun\.write\b|os\.remove\b|os\.system\b|os\.popen\b|\bsubprocess\.|\bDeno\.(?:write|writeFile|writeTextFile|remove)\b|shutil\.\w|\.write_text\b|\.write_bytes\b/i,Loe=/\b(npm|pnpm|yarn|pip|pip3|brew|cargo|go|apt|apt-get|gem|poetry|bundle|composer)\s+(install|add|remove|uninstall|i|ci|up|update|upgrade|dlx|get|require)\b/i,Noe=/\b(curl|wget)\b[^|;&]*\s(-o\b|-O\b|--output\b)/i,Boe=/\bcurl\b[^|;&]*\s-X\s+(POST|PUT|PATCH|DELETE)\b/i,Uoe=/\bcurl\b[^|;&]*\s(-d\b|--data\b|-F\b|--form\b)/i,joe=/(\d*&?>>?\s*\/dev\/null|\d*>&\d+|&>\s*\/dev\/null|&>>\s*\/dev\/null)/gi,Hoe=/\$\(\(.*?\)\)/g,Woe=/(?<![=<>-])>>?(?!&)/,Koe=[{re:boe,reason:"git config set (`<key> <value>`; only reads allowed)"},{re:Roe,reason:"find -exec with mutating verb"}],Goe=[{re:Toe,reason:"pipe-to-shell (RCE via piped interpreter)"},{re:Eoe,reason:"filesystem mutation"},{re:xoe,reason:"find -delete (file removal)"},{re:Aoe,reason:"patch (applies a diff to files)"},{re:Coe,reason:"install (writes files)"},{re:_oe,reason:"source/dot-source executes a script"},{re:Ioe,reason:"tar create/extract/append/update (writes files/archive)"},{re:Poe,reason:"unzip (writes files)"},{re:Moe,reason:"cpio extract (-i mode writes files)"},{re:yoe,reason:"git config write flag (only reads allowed)"},{re:Soe,reason:"gh write operation"},{re:woe,reason:"gh api write method (POST/PUT/PATCH/DELETE)"},{re:voe,reason:"gh api field payload (-f/-F/--field)"},{re:koe,reason:"gh extended write operation (secret/variable/workflow/run/cache)"},{re:Ooe,reason:"sed in-place edit (-i)"},{re:Doe,reason:"perl in-place edit (-i)"},{re:Loe,reason:"package install/modify"},{re:Noe,reason:"curl/wget output-to-file"},{re:Boe,reason:"curl write method (POST/PUT/PATCH/DELETE)"},{re:Uoe,reason:"curl data/form payload"}];zoe=new Set(["env","xargs","command","sudo","nice","time","timeout","nohup","stdbuf","busybox","eval"]);Voe=new Set(["-u","--unset","-C","--chdir","-S","--split-string"]),Yoe=new Set(["-a","--arg-file","-E","--eof","-I","--replace","-i","-L","--max-lines","-l","-n","--max-args","-P","--max-procs","-s","--max-chars","-d","--delimiter","--process-slot-var"]);Xoe=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),Qoe=new Set(["commit","push","pull","fetch","merge","rebase","reset","checkout","switch","restore","cherry-pick","revert","am","apply","clean","add","rm","mv","init","clone"]);eie=/^(POST|PUT|PATCH|DELETE)$/i});function rie(e,t){if(e.length<=t)return e;let n=t;for(;n>0&&(e[n]&192)===128;)n--;return e.subarray(0,n)}function oie(e,t){if(e.length<=t)return e;let n=e.length-t;for(;n<e.length&&(e[n]&192)===128;)n++;return e.subarray(n)}function ao(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=Math.max(0,t-iie),o=Math.ceil(r/2),i=r-o,s=rie(n,o),a=oie(n,i),c=`
|
|
76
76
|
|
|
77
77
|
\u2026 [${n.length-s.length-a.length} bytes truncated: showing first ${s.length} + last ${a.length} of ${n.length}] \u2026
|
|
@@ -222,7 +222,9 @@ ${n}
|
|
|
222
222
|
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.`}var xl,CF,Sx,Kd=y(()=>{"use strict";xl="denial-breaker",CF=new Set(["read_file","list_directory","glob","grep"]),Sx="Sub-agent path access denied:"});import{createHash as pse}from"node:crypto";function MF(){return{recent:[],firedFingerprints:new Set}}function bh(e){let t;try{t=fse(e.input)}catch{t=String(e.input)}return pse("sha256").update(e.name).update("\0").update(t).digest("hex")}function fse(e){return JSON.stringify(wx(e))??"null"}function wx(e){if(Array.isArray(e))return e.map(wx);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=wx(t[r]);return n}return e}function gse(e,t){let n=0;for(let r of e)r===t&&(n+=1);return n}function OF(e,t){e.recent.push(t),e.recent.length>vx&&e.recent.shift();let n=gse(e.recent,t);return n>=mse&&!e.firedFingerprints.has(t)?(e.firedFingerprints.add(t),{fired:!0,count:n}):{fired:!1,count:n}}var mse,vx,kx=y(()=>{"use strict";mse=5,vx=20});function yse(e){if(e===null||typeof e!="object"||Array.isArray(e))return e;let t={};for(let[n,r]of Object.entries(e))hse.has(n)||(t[n]=r);return t}function Gd(e){return bh({...e,input:yse(e.input)})}function bse(e){let t=e.content.split(`
|
|
223
223
|
`).find(n=>n.trim()!=="")?.trim()??"";return t.length<=DF?t:`${t.slice(0,DF)}\u2026`}var Tx,hse,DF,Sh,$F=y(()=>{"use strict";kx();Tx=3,hse=new Set(["timeout_ms","timeoutMs","timeout"]),DF=240;Sh=class{streaks=new Map;check(t){let n=this.streaks.get(Gd(t));return n===void 0||n.count<Tx?null:{count:n.count,tool:t.name,result:{content:`Repeat-failure guard: "${t.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}
|
|
224
224
|
|
|
225
|
-
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(t,n){let r=Gd(t);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:bse(n)})}streakFor(t){return this.streaks.get(Gd(t))?.count??0}}});var Rl,Ex,Xt,Al=y(()=>{"use strict";$d();ue();He();Rs();Jg();Xg();eh();ex();ei();Vg();ce();bx();AF();Kd();kx();$F();bx();Rl=8,Ex=new Set,Xt=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 Sh;denialBreaker=null;suspectedLoopWindow=null;grantManager;constructor(t){this.handlers=t.handlers,this.schemas=t.schemas,this.hookRegistry=t.hookRegistry,this.permissions=t.permissions,this.canUseTool=t.canUseTool,this.subagentExecutor=t.subagentExecutor,this.skillExecutor=t.skillExecutor,this.composeExecutor=t.composeExecutor,this.classifier=t.concurrencyClassifier??yx,this.maxConcurrentSafeCalls=typeof t.maxConcurrentSafeCalls=="number"&&Number.isFinite(t.maxConcurrentSafeCalls)&&t.maxConcurrentSafeCalls>=1?Math.floor(t.maxConcurrentSafeCalls):U$(),this.resolveBase=t.cwd,this._env=t.env,this.sessionId=t.sessionId,this.parentSessionId=t.parentSessionId,this.subagentId=t.subagentId,this.sessionGrantManager=t.sessionGrantManager,this.traceWriter=t.traceWriter,this.readOnlyBash=t.readOnlyBash===!0,this.maxOutputBytes=typeof t.maxOutputBytes=="number"&&Number.isFinite(t.maxOutputBytes)&&t.maxOutputBytes>0?t.maxOutputBytes:void 0,this._allowAll=t.allowAll===!0;let n=t.cwd?[t.cwd]:[];this._readRoots=t.readRoots??n.slice(),this._writeRoots=t.writeRoots??n.slice(),this.grantManager=new Zo({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(t){return{...this.handlerContext,toolUseId:t.id,...this.traceWriter!==void 0?{traceWriter:this.traceWriter}:{}}}addReadRoot(t,n="slash"){this.grantManager.addReadRoot(t,n)}addWriteRoot(t,n="slash"){this.grantManager.addWriteRoot(t,n)}revokeRoot(t,n="slash"){this.grantManager.revokeRoot(t,n)}getGrants(){return this.grantManager.getGrants()}setAllowAll(t){this._allowAll=t}setResolveBase(t){let n=this.resolveBase;if(n!==t){if(this.resolveBase=t,n!==void 0){let r=this._readRoots.indexOf(n);r!==-1?this._readRoots[r]=t:this._readRoots.includes(t)||this._readRoots.push(t);let o=this._writeRoots.indexOf(n);o!==-1?this._writeRoots[o]=t:this._writeRoots.includes(t)||this._writeRoots.push(t)}else this._readRoots.includes(t)||this._readRoots.push(t),this._writeRoots.includes(t)||this._writeRoots.push(t);this.subagentExecutor?.setCwd(t),this.skillExecutor?.setCwd(t),this.composeExecutor?.setCwd(t)}}get toolDefs(){let t=this.permissions?.allowedTools;if(!t)return this.schemas;let n=new Set(t);return this.schemas.filter(r=>n.has(r.name))}denialReason(t,n){return this.isRegisteredTool(t)?n??`Tool "${t}" is not permitted`:this.unknownToolMessage(t)}isRegisteredTool(t){return this.handlers.has(t)||t==="agent"&&this.subagentExecutor!==void 0||t==="skill"&&this.skillExecutor!==void 0||t==="compose"&&this.composeExecutor!==void 0}unknownToolMessage(t){let n=this.toolDefs.map(o=>o.name).join(", "),r=n.length>0?`Available tools: ${n}. Do NOT retry "${t}" or a variant of it; use one of the tools listed above.`:`Do NOT retry "${t}" or a variant of it.`;return`Unknown tool "${t}" \u2014 it does not exist in this session. ${r}`}async checkReadOnlyBash(t){if(!this.readOnlyBash||t.name!=="bash")return null;let n=t.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=nh(r);if(!o.mutating)return null;let i=`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(t.name,i),{content:i,isError:!0,failureClass:"permission-denied"}}async emitPreToolUseBlock(t,n){await An(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:t,reason:n,...this.subagentId!==void 0?{subagentId:this.subagentId}:{}})}checkRepeatCircuitBreaker(t){if(Ex.has(t.name))return null;let n=RF(t);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<Rl?null:{content:`Loop circuit breaker: "${t.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(t){if(Ex.has(t.name))return null;let n=this.repeatFailureGuard.check(t);return n===null?null:(U(`[repeat-failure-guard #723] refused ${n.tool} after ${n.count} identical failures`),n.result)}observeSuspectedLoop(t){if(this.parentSessionId===void 0)return;this.suspectedLoopWindow===null&&(this.suspectedLoopWindow=MF());let n=bh(t),r=OF(this.suspectedLoopWindow,n);r.fired&&re(this.traceWriter,{phase:"suspected_loop",metadata:{tool:t.name,count:r.count,windowSize:vx}})}recordForkReadDenial(t,n,r){if(this.parentSessionId===void 0||!CF.has(t.name)||!_F(n))return r;let o=this.denialBreaker??{count:0,deniedPaths:[]};o.count+=1;let i=IF(t);return o.deniedPaths.includes(i)||o.deniedPaths.push(i),this.denialBreaker=o,o.count<5?r:{content:PF(o.deniedPaths,o.count),isError:!0,failureClass:xl}}resetDenialBreaker(){this.denialBreaker=null}async runCanUseTool(t){if(!this.canUseTool)return null;let n;try{n=await this.canUseTool(t.name,t.input??{},{signal:t.signal,toolUseID:t.id})}catch(r){let o=`Tool "${t.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`;return await this.emitPreToolUseBlock(t.name,o),{content:o,isError:!0,failureClass:"permission-denied"}}if(n.behavior==="deny"){let r=n.message||`Tool "${t.name}" denied by permission policy`;return await this.emitPreToolUseBlock(t.name,r),{content:r,isError:!0,failureClass:"permission-denied"}}return n.updatedInput!==void 0&&(t.input=n.updatedInput),null}async runPreDispatchGates(t){if(this.hookRegistry){let a={event:"PreToolUse",toolName:t.name,input:t.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 G$(this.hookRegistry,a,{signal:t.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(l){if(l instanceof Ae)return this.recordForkReadDenial(t,l.reason,{content:`Tool "${t.name}" blocked by PreToolUse hook: ${l.message}`,isError:!0,failureClass:"hook-block"});throw l}}let n=V$(t.name,this.permissions);if(!n.allowed){let a=this.denialReason(t.name,n.reason);return await this.emitPreToolUseBlock(t.name,a),{content:a,isError:!0,failureClass:"permission-denied"}}let r=await this.runCanUseTool(t);if(r)return r;let o=await this.checkReadOnlyBash(t);if(o)return o;let i=this.checkRepeatCircuitBreaker(t);if(i)return i;let s=this.checkRepeatFailureGuard(t);return s||(this.observeSuspectedLoop(t),null)}async execute(t){if(t.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:Yt(t.signal)};let n=await this.runPreDispatchGates(t);if(n)return n;let r=await this.executeCore(t);return this.repeatFailureGuard.note(t,r),r.isError!==!0&&this.resetDenialBreaker(),r}async executeBatch(t){if(t.length===0)return[];if(t.length===1)return[await this.execute(t[0])];let n=new Array(t.length),r=new Set;for(let s=0;s<t.length;s++){let a=t[s];if(a.signal.aborted){n[s]={content:"Tool call aborted",isError:!0,failureClass:Yt(a.signal)},r.add(s);continue}let l=await this.runPreDispatchGates(a);if(l){n[s]=l,r.add(s);continue}}let o=t.map((s,a)=>({call:s,originalIndex:a})).filter((s,a)=>!r.has(a));if(o.length===0)return n;let i=xF(o.map(s=>s.call),this.classifier);for(let s of i){if(s.isConcurrencySafe){let l=[...s.indices];for(;l.length>0;){let c=new Map,u=[],d=[];for(let g of l){let{call:h,originalIndex:b}=o[g],S=this.checkRepeatFailureGuard(h);if(S){n[b]=S;continue}if(Ex.has(h.name)){u.push(g);continue}let w=Gd(h),k=Tx-this.repeatFailureGuard.streakFor(h),E=c.get(w)??0;E<k?(c.set(w,E+1),u.push(g)):d.push(g)}l=d;let p=u.map(g=>o[g]?.call).filter(g=>g!==void 0&&g.name==="agent");if(p.length>=2&&this.subagentExecutor)try{this.subagentExecutor.notifyWaveStart(p,this.sessionId??"",null)}catch{}let f=await kl(u,this.maxConcurrentSafeCalls,async g=>{let{call:h,originalIndex:b}=o[g];return h.signal.aborted?{result:{content:"Tool call aborted",isError:!0,failureClass:Yt(h.signal)},originalIndex:b}:{result:await this.executeCore(h),originalIndex:b}});for(let g of f)if(g.status==="fulfilled")n[g.value.originalIndex]=g.value.result;else{let h=g.reason instanceof Error?g.reason.message:String(g.reason),b=u[f.indexOf(g)];n[o[b].originalIndex]={content:`Tool execution error: ${h}`,isError:!0}}for(let g of u){let{call:h,originalIndex:b}=o[g],S=n[b];S!==void 0&&S.failureClass!=="abort"&&this.repeatFailureGuard.note(h,S)}if(p.length>=2&&this.subagentExecutor)try{this.subagentExecutor.notifyWaveEnd()}catch{}}}else for(let l of s.indices){let{call:c,originalIndex:u}=o[l];if(c.signal.aborted){n[u]={content:"Tool call aborted",isError:!0,failureClass:Yt(c.signal)};continue}let d=this.checkRepeatFailureGuard(c);if(d){n[u]=d;continue}let p=await this.executeCore(c);n[u]=p,this.repeatFailureGuard.note(c,p)}let a=s.indices.length;s.indices.forEach((l,c)=>{let u=n[o[l].originalIndex];u&&(u.batchIndex=c+1,u.batchSize=a)})}return n.some(s=>s!==void 0&&s.isError!==!0)&&this.resetDenialBreaker(),n}async executeCore(t){let n=await this.executeCoreInner(t);return this.applyOutputCap(n)}applyOutputCap(t){let n=this.maxOutputBytes;if(n===void 0)return t;let r=Buffer.byteLength(t.content,"utf8");return r<=n||(t.content=ao(t.content,n),t.truncated=!0,U(`[output-cap #661] fork tool result capped: original=${r}B capped=${Buffer.byteLength(t.content,"utf8")}B (cap=${n}B)`)),t}async executeCoreInner(t){if(t.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let s,a=!1,l="";try{s=await this.subagentExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),s={content:`Agent tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,s.content,t.signal,t.input,s),s}if(t.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let s,a=!1,l="";try{s=await this.skillExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),s={content:`Skill tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,s.content,t.signal,t.input,s),s}if(t.name==="compose"){let s=await this.executeCompose(t);return this.firePostToolUse(t.name,s.content,t.signal,t.input,s),s}let n=this.handlers.get(t.name);if(!n){let s=this.unknownToolMessage(t.name);return await this.emitPreToolUseBlock(t.name,s),{content:s,isError:!0,failureClass:"permission-denied"}}let r,o=!1,i="";try{r=await n(t.input,t.signal,this.callHandlerContext(t))}catch(s){o=!0,i=s instanceof Error?s.message:String(s),r={content:`Tool execution error: ${i}`,isError:!0}}return o?this.firePostToolUseFailure(t.name,i,t.signal,t.input):this.firePostToolUse(t.name,r.content,t.signal,t.input,r),r}async executeCompose(t){if(!this.composeExecutor)return{content:"Compose tool is not available in this session configuration",isError:!0};try{return await this.composeExecutor.execute(t)}catch(n){return{content:`Compose tool error: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}firePostToolUse(t,n,r,o,i){if(!this.hookRegistry)return;let s={event:"PostToolUse",toolName:t,output:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{},...i?.incomplete===!0?{incomplete:!0}:{},...i?.incompleteReason?{incompleteReason:i.incompleteReason}:{}};q$(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(()=>{})}firePostToolUseFailure(t,n,r,o){if(!this.hookRegistry)return;let i={event:"PostToolUseFailure",toolName:t,error:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};z$(this.hookRegistry,i,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(s=>{U(`firePostToolUseFailure outer catch (tool=${t}): ${String(s)}`)})}}});import{mkdir as wse,writeFile as vse}from"fs/promises";import{dirname as kse,join as Tse}from"path";function Ese(){return Tse(Dt(),"routing-decisions.jsonl")}function xse(e){let t={surface:"afk"};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}async function Fe(e){if(!(v.VITEST||v.NODE_ENV==="test"))try{let t=Ese();await wse(kse(t),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,...xse(e)})+`
|
|
225
|
+
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(t,n){let r=Gd(t);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:bse(n)})}streakFor(t){return this.streaks.get(Gd(t))?.count??0}}});var Rl,Ex,Xt,Al=y(()=>{"use strict";$d();ue();He();Rs();Jg();Xg();eh();ex();ei();Vg();ce();bx();AF();Kd();kx();$F();bx();Rl=8,Ex=new Set,Xt=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 Sh;denialBreaker=null;suspectedLoopWindow=null;grantManager;constructor(t){this.handlers=t.handlers,this.schemas=t.schemas,this.hookRegistry=t.hookRegistry,this.permissions=t.permissions,this.canUseTool=t.canUseTool,this.subagentExecutor=t.subagentExecutor,this.skillExecutor=t.skillExecutor,this.composeExecutor=t.composeExecutor,this.classifier=t.concurrencyClassifier??yx,this.maxConcurrentSafeCalls=typeof t.maxConcurrentSafeCalls=="number"&&Number.isFinite(t.maxConcurrentSafeCalls)&&t.maxConcurrentSafeCalls>=1?Math.floor(t.maxConcurrentSafeCalls):U$(),this.resolveBase=t.cwd,this._env=t.env,this.sessionId=t.sessionId,this.parentSessionId=t.parentSessionId,this.subagentId=t.subagentId,this.sessionGrantManager=t.sessionGrantManager,this.traceWriter=t.traceWriter,this.readOnlyBash=t.readOnlyBash===!0,this.maxOutputBytes=typeof t.maxOutputBytes=="number"&&Number.isFinite(t.maxOutputBytes)&&t.maxOutputBytes>0?t.maxOutputBytes:void 0,this._allowAll=t.allowAll===!0;let n=t.cwd?[t.cwd]:[];this._readRoots=t.readRoots??n.slice(),this._writeRoots=t.writeRoots??n.slice(),this.grantManager=new Zo({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(t){return{...this.handlerContext,toolUseId:t.id,...this.traceWriter!==void 0?{traceWriter:this.traceWriter}:{}}}addReadRoot(t,n="slash"){this.grantManager.addReadRoot(t,n)}addWriteRoot(t,n="slash"){this.grantManager.addWriteRoot(t,n)}revokeRoot(t,n="slash"){this.grantManager.revokeRoot(t,n)}getGrants(){return this.grantManager.getGrants()}setAllowAll(t){this._allowAll=t}setResolveBase(t){let n=this.resolveBase;if(n!==t){if(this.resolveBase=t,n!==void 0){let r=this._readRoots.indexOf(n);r!==-1?this._readRoots[r]=t:this._readRoots.includes(t)||this._readRoots.push(t);let o=this._writeRoots.indexOf(n);o!==-1?this._writeRoots[o]=t:this._writeRoots.includes(t)||this._writeRoots.push(t)}else this._readRoots.includes(t)||this._readRoots.push(t),this._writeRoots.includes(t)||this._writeRoots.push(t);this.subagentExecutor?.setCwd(t),this.skillExecutor?.setCwd(t),this.composeExecutor?.setCwd(t)}}get toolDefs(){let t=this.permissions?.allowedTools;if(!t)return this.schemas;let n=new Set(t);return this.schemas.filter(r=>n.has(r.name))}denialReason(t,n){return this.isRegisteredTool(t)?n??`Tool "${t}" is not permitted`:this.unknownToolMessage(t)}isRegisteredTool(t){return this.handlers.has(t)||t==="agent"&&this.subagentExecutor!==void 0||t==="skill"&&this.skillExecutor!==void 0||t==="compose"&&this.composeExecutor!==void 0}unknownToolMessage(t){let n=this.toolDefs.map(o=>o.name).join(", "),r=n.length>0?`Available tools: ${n}. Do NOT retry "${t}" or a variant of it; use one of the tools listed above.`:`Do NOT retry "${t}" or a variant of it.`;return`Unknown tool "${t}" \u2014 it does not exist in this session. ${r}`}async checkReadOnlyBash(t){if(!this.readOnlyBash||t.name!=="bash")return null;let n=t.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=nh(r);if(!o.mutating)return null;let i=`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(t.name,i),{content:i,isError:!0,failureClass:"permission-denied"}}async emitPreToolUseBlock(t,n){await An(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:t,reason:n,...this.subagentId!==void 0?{subagentId:this.subagentId}:{}})}checkRepeatCircuitBreaker(t){if(Ex.has(t.name))return null;let n=RF(t);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<Rl?null:{content:`Loop circuit breaker: "${t.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(t){if(Ex.has(t.name))return null;let n=this.repeatFailureGuard.check(t);return n===null?null:(U(`[repeat-failure-guard #723] refused ${n.tool} after ${n.count} identical failures`),n.result)}observeSuspectedLoop(t){if(this.parentSessionId===void 0)return;this.suspectedLoopWindow===null&&(this.suspectedLoopWindow=MF());let n=bh(t),r=OF(this.suspectedLoopWindow,n);r.fired&&re(this.traceWriter,{phase:"suspected_loop",metadata:{tool:t.name,count:r.count,windowSize:vx}})}recordForkReadDenial(t,n,r){if(this.parentSessionId===void 0||!CF.has(t.name)||!_F(n))return r;let o=this.denialBreaker??{count:0,deniedPaths:[]};o.count+=1;let i=IF(t);return o.deniedPaths.includes(i)||o.deniedPaths.push(i),this.denialBreaker=o,o.count<5?r:{content:PF(o.deniedPaths,o.count),isError:!0,failureClass:xl}}resetDenialBreaker(){this.denialBreaker=null}async runCanUseTool(t){if(!this.canUseTool)return null;let n;try{n=await this.canUseTool(t.name,t.input??{},{signal:t.signal,toolUseID:t.id})}catch(r){let o=`Tool "${t.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`;return await this.emitPreToolUseBlock(t.name,o),{content:o,isError:!0,failureClass:"permission-denied"}}if(n.behavior==="deny"){let r=n.message||`Tool "${t.name}" denied by permission policy`;return await this.emitPreToolUseBlock(t.name,r),{content:r,isError:!0,failureClass:"permission-denied"}}return n.updatedInput!==void 0&&(t.input=n.updatedInput),null}async runPreDispatchGates(t){if(this.hookRegistry){let a={event:"PreToolUse",toolName:t.name,input:t.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 G$(this.hookRegistry,a,{signal:t.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(l){if(l instanceof Ae)return this.recordForkReadDenial(t,l.reason,{content:`Tool "${t.name}" blocked by PreToolUse hook${l.reason?`: ${l.reason}`:""}${l.injectContext?`
|
|
226
|
+
|
|
227
|
+
${l.injectContext}`:""}`,isError:!0,failureClass:"hook-block"});throw l}}let n=V$(t.name,this.permissions);if(!n.allowed){let a=this.denialReason(t.name,n.reason);return await this.emitPreToolUseBlock(t.name,a),{content:a,isError:!0,failureClass:"permission-denied"}}let r=await this.runCanUseTool(t);if(r)return r;let o=await this.checkReadOnlyBash(t);if(o)return o;let i=this.checkRepeatCircuitBreaker(t);if(i)return i;let s=this.checkRepeatFailureGuard(t);return s||(this.observeSuspectedLoop(t),null)}async execute(t){if(t.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:Yt(t.signal)};let n=await this.runPreDispatchGates(t);if(n)return n;let r=await this.executeCore(t);return this.repeatFailureGuard.note(t,r),r.isError!==!0&&this.resetDenialBreaker(),r}async executeBatch(t){if(t.length===0)return[];if(t.length===1)return[await this.execute(t[0])];let n=new Array(t.length),r=new Set;for(let s=0;s<t.length;s++){let a=t[s];if(a.signal.aborted){n[s]={content:"Tool call aborted",isError:!0,failureClass:Yt(a.signal)},r.add(s);continue}let l=await this.runPreDispatchGates(a);if(l){n[s]=l,r.add(s);continue}}let o=t.map((s,a)=>({call:s,originalIndex:a})).filter((s,a)=>!r.has(a));if(o.length===0)return n;let i=xF(o.map(s=>s.call),this.classifier);for(let s of i){if(s.isConcurrencySafe){let l=[...s.indices];for(;l.length>0;){let c=new Map,u=[],d=[];for(let g of l){let{call:h,originalIndex:b}=o[g],S=this.checkRepeatFailureGuard(h);if(S){n[b]=S;continue}if(Ex.has(h.name)){u.push(g);continue}let w=Gd(h),k=Tx-this.repeatFailureGuard.streakFor(h),E=c.get(w)??0;E<k?(c.set(w,E+1),u.push(g)):d.push(g)}l=d;let p=u.map(g=>o[g]?.call).filter(g=>g!==void 0&&g.name==="agent");if(p.length>=2&&this.subagentExecutor)try{this.subagentExecutor.notifyWaveStart(p,this.sessionId??"",null)}catch{}let f=await kl(u,this.maxConcurrentSafeCalls,async g=>{let{call:h,originalIndex:b}=o[g];return h.signal.aborted?{result:{content:"Tool call aborted",isError:!0,failureClass:Yt(h.signal)},originalIndex:b}:{result:await this.executeCore(h),originalIndex:b}});for(let g of f)if(g.status==="fulfilled")n[g.value.originalIndex]=g.value.result;else{let h=g.reason instanceof Error?g.reason.message:String(g.reason),b=u[f.indexOf(g)];n[o[b].originalIndex]={content:`Tool execution error: ${h}`,isError:!0}}for(let g of u){let{call:h,originalIndex:b}=o[g],S=n[b];S!==void 0&&S.failureClass!=="abort"&&this.repeatFailureGuard.note(h,S)}if(p.length>=2&&this.subagentExecutor)try{this.subagentExecutor.notifyWaveEnd()}catch{}}}else for(let l of s.indices){let{call:c,originalIndex:u}=o[l];if(c.signal.aborted){n[u]={content:"Tool call aborted",isError:!0,failureClass:Yt(c.signal)};continue}let d=this.checkRepeatFailureGuard(c);if(d){n[u]=d;continue}let p=await this.executeCore(c);n[u]=p,this.repeatFailureGuard.note(c,p)}let a=s.indices.length;s.indices.forEach((l,c)=>{let u=n[o[l].originalIndex];u&&(u.batchIndex=c+1,u.batchSize=a)})}return n.some(s=>s!==void 0&&s.isError!==!0)&&this.resetDenialBreaker(),n}async executeCore(t){let n=await this.executeCoreInner(t);return this.applyOutputCap(n)}applyOutputCap(t){let n=this.maxOutputBytes;if(n===void 0)return t;let r=Buffer.byteLength(t.content,"utf8");return r<=n||(t.content=ao(t.content,n),t.truncated=!0,U(`[output-cap #661] fork tool result capped: original=${r}B capped=${Buffer.byteLength(t.content,"utf8")}B (cap=${n}B)`)),t}async executeCoreInner(t){if(t.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let s,a=!1,l="";try{s=await this.subagentExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),s={content:`Agent tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,s.content,t.signal,t.input,s),s}if(t.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let s,a=!1,l="";try{s=await this.skillExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),s={content:`Skill tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,s.content,t.signal,t.input,s),s}if(t.name==="compose"){let s=await this.executeCompose(t);return this.firePostToolUse(t.name,s.content,t.signal,t.input,s),s}let n=this.handlers.get(t.name);if(!n){let s=this.unknownToolMessage(t.name);return await this.emitPreToolUseBlock(t.name,s),{content:s,isError:!0,failureClass:"permission-denied"}}let r,o=!1,i="";try{r=await n(t.input,t.signal,this.callHandlerContext(t))}catch(s){o=!0,i=s instanceof Error?s.message:String(s),r={content:`Tool execution error: ${i}`,isError:!0}}return o?this.firePostToolUseFailure(t.name,i,t.signal,t.input):this.firePostToolUse(t.name,r.content,t.signal,t.input,r),r}async executeCompose(t){if(!this.composeExecutor)return{content:"Compose tool is not available in this session configuration",isError:!0};try{return await this.composeExecutor.execute(t)}catch(n){return{content:`Compose tool error: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}firePostToolUse(t,n,r,o,i){if(!this.hookRegistry)return;let s={event:"PostToolUse",toolName:t,output:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{},...i?.incomplete===!0?{incomplete:!0}:{},...i?.incompleteReason?{incompleteReason:i.incompleteReason}:{}};q$(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(()=>{})}firePostToolUseFailure(t,n,r,o){if(!this.hookRegistry)return;let i={event:"PostToolUseFailure",toolName:t,error:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};z$(this.hookRegistry,i,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(s=>{U(`firePostToolUseFailure outer catch (tool=${t}): ${String(s)}`)})}}});import{mkdir as wse,writeFile as vse}from"fs/promises";import{dirname as kse,join as Tse}from"path";function Ese(){return Tse(Dt(),"routing-decisions.jsonl")}function xse(e){let t={surface:"afk"};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}async function Fe(e){if(!(v.VITEST||v.NODE_ENV==="test"))try{let t=Ese();await wse(kse(t),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,...xse(e)})+`
|
|
226
228
|
`;await vse(t,r,{flag:"a"})}catch{}}var Qn=y(()=>{"use strict";B();K()});function Fse(e){let t=e.match(Rse);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"vitest",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function Lse(e){let t=e.match(Ase);if(!t)return null;let n=parseInt(t[1]??"0",10);return{runner:"jest",passed:parseInt(t[2]??"0",10),failed:n}}function Nse(e){let t=e.match(Cse);if(!t)return null;if(t[2]!==void 0){let n=parseInt(t[2],10),r=parseInt(t[1]??"0",10);return{runner:"pytest",passed:n,failed:r}}return t[4]!==void 0?{runner:"pytest",passed:parseInt(t[4],10),failed:0}:null}function Bse(e){let t=e.match(_se);if(!t)return null;let n=parseInt(t[1]??"0",10),r=e.match(Ise),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function Use(e){let t=[...e.matchAll(Pse)];if(t.length===0)return null;let n=0,r=0;for(let o of t)o[1]==="ok"?n++:o[1]==="FAIL"&&r++;return{runner:"go-test",passed:n,failed:r}}function jse(e){let t=e.match(Mse);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"cargo",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function Hse(e){let t=e.match(Ose);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10);return{runner:"rspec",passed:n-r,failed:r}}function Wse(e){let t=e.match(Dse);if(t)return{runner:"phpunit",passed:parseInt(t[1]??"0",10),failed:0};let n=e.match($se);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 xx(e){return Fse(e)??Lse(e)??Nse(e)??Bse(e)??Use(e)??jse(e)??Hse(e)??Wse(e)??null}var Rse,Ase,Cse,_se,Ise,Pse,Mse,Ose,Dse,$se,FF=y(()=>{"use strict";Rse=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,Ase=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,Cse=/={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,}/,_se=/(\d+)\s+passing/,Ise=/(\d+)\s+failing/,Pse=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,Mse=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,Ose=/(\d+) examples?, (\d+) failures?/,Dse=/OK \((\d+) tests?/,$se=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/});function Oe(e){return e.replace(LF,"").replace(Kse," ").trim()}function Zn(e){return e.replace(LF,"")}var LF,Kse,In=y(()=>{"use strict";LF=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,Kse=/[\x00-\x1F\x7F-\x9F]/g});import{statSync as Gse}from"node:fs";function qd(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.code==="ENOENT"&&typeof t.syscall=="string"&&t.syscall.startsWith("spawn")}function qse(e){if(e===void 0)return!1;try{return Gse(e),!1}catch{return!0}}function Cl(e,t){let n=e instanceof Error?e.message:typeof e?.message=="string"?String(e.message):String(e);return qd(e)&&qse(t)?`working directory does not exist: ${t} (deleted worktree?) \u2014 underlying: ${n}`:n}var Rx=y(()=>{"use strict"});function _r(e){let t=e instanceof Error?e.message:String(e);NF.has(t)||(NF.add(t),console.warn(`[afk-home] Malformed AFK home/state env var ignored while deriving the credential floor: ${t}. The relocated tree is NOT protected \u2014 the default ~/.afk entries still apply. Fix the env var to restore coverage.`))}var NF,zd=y(()=>{"use strict";NF=new Set});import{statSync as Cx}from"node:fs";import{homedir as zse}from"node:os";import{basename as Vse,dirname as UF,join as Yse}from"node:path";function jF(e){return typeof e=="object"&&e!==null&&"code"in e?String(e.code):void 0}function Jse(e){let t=Vse(e),n=t===t.toLowerCase()?t.toUpperCase():t.toLowerCase();if(n===t)return;let r;try{r=Cx(e)}catch{return}let o=Ax.get(r.dev);if(o!==void 0)return o;try{let i=Cx(Yse(UF(e),n)),s=r.dev===i.dev&&r.ino===i.ino;return Ax.set(r.dev,s),s}catch(i){let s=jF(i);return s==="ENOENT"||s==="ENOTDIR"?(Ax.set(r.dev,!1),!1):void 0}}function HF(e=zse()){if(BF!==void 0)return BF;let t=e;for(;;)try{return Cx(t),Jse(t)??!0}catch(n){let r=jF(n);if(r!=="ENOENT"&&r!=="ENOTDIR")return!0;let o=UF(t);if(o===t)return!0;t=o}}function _l(e,t,n=t){if(e===t||e.startsWith(t+"/"))return!0;if(!HF(n))return!1;let r=e.toLowerCase(),o=t.toLowerCase();return r===o||r.startsWith(o+"/")}function _x(e,t){return e.includes(t)?!0:HF(t)?e.toLowerCase().includes(t.toLowerCase()):!1}var BF,Ax,wh=y(()=>{"use strict";Ax=new Map});import{realpathSync as WF}from"fs";import{dirname as Xse,resolve as Os,join as Ix}from"path";import{homedir as ni}from"os";function Zse(){let e=[];try{let t=ke();e.push(Os(Ix(t,"config"))),e.push(Os(Ix(t,"state")))}catch(t){_r(t)}try{e.push(Os(ge()))}catch(t){_r(t)}return e}function Px(){let e=`${v.AFK_WRITE_DENYLIST??""}\0${v.AFK_HOME??""}\0${v.AFK_STATE_DIR??""}`;if(!vh||vh.key!==e){let t=v.AFK_WRITE_DENYLIST,n=t?t.split(":").map(r=>Os(r)).filter(Boolean):[];vh={key:e,unresolved:[...new Set([...Qse.map(r=>Os(r)),...Zse()]),...n]}}return[...new Set(vh.unresolved.map(t=>st(t)))]}function st(e){let t=Os(e);try{return WF(t)}catch{}let n=[],r=t;for(let o=0;o<64;o++){let i=Xse(r);if(i===r)break;n.unshift(r.slice(i.length+1)),r=i;try{let s=WF(r);return Ix(s,...n)}catch{}}return t}function kh(e,t="write_file"){let n=st(Os(e));for(let r of Px())if(_l(n,r))throw new Error(`${t}: refusing to write to protected path: ${n} (matches denylist entry: ${r})`)}var Qse,vh,Ds=y(()=>{"use strict";B();K();zd();wh();Qse=[`${ni()}/.ssh`,`${ni()}/.aws`,`${ni()}/.gnupg`,`${ni()}/.config/gcloud`,"/etc","/System","/private/etc","/usr/local/etc",`${ni()}/.afk/config`,`${ni()}/.afk/state`,`${ni()}/.npmrc`,`${ni()}/.docker/config.json`]});import{isAbsolute as eae,relative as tae,sep as nae}from"node:path";import{homedir as Mx}from"node:os";function rae(e,t){let n=tae(t,e);return n===""||n!==".."&&!n.startsWith(`..${nae}`)&&!eae(n)}function Ox(e,t){return e.filter(n=>!t.some(r=>rae(n,r)))}function oae(e,t){return e.filter(({source:n})=>n!==t).map(({root:n})=>n)}function KF(e,t){return e.flatMap(({rel:n,resolved:r})=>Ox([r],oae(t,iae[n])))}var iae,GF=y(()=>{"use strict";iae={".afk/config/mcp.json":`${Mx()}/.afk/config`,".ssh/config":`${Mx()}/.ssh`,".ssh/known_hosts":`${Mx()}/.ssh`}});import{existsSync as qF}from"fs";import{isAbsolute as sae,resolve as YF}from"path";import{homedir as zF}from"os";function $s(e){return e==="~"?zF():e.startsWith("~/")?YF(zF(),e.slice(2)):e}function Th(e){if(!e.startsWith("https://"))throw new Error(`Plugin source must use https:// (got: ${e}). git://, http://, ssh://, file://, and git@ are rejected to avoid downgrade attacks and unauthenticated clones.`)}function Il(e){let t=e.trim();if(!t)throw new Error('plugin source is required (examples: "owner/repo", "https://github.com/owner/repo.git", "./my-plugin")');if(uae(t)){let o=VF(t);if(!qF(o))throw new Error(`could not resolve plugin source: "${t}" looks like a local path but does not exist on disk`);return{type:"local",path:o}}if(aae.test(t))return{type:"git",url:t};let n=cae.exec(t);if(n&&n[1]&&n[2])return{type:"marketplace-ref",marketplace:n[1],plugin:n[2]};let r=lae.exec(t);if(r&&r[1]&&r[2]){let o=r[1],i=r[2];return{type:"github",owner:o,repo:i,url:`https://github.com/${o}/${i}.git`}}if(qF(t))return{type:"local",path:VF(t)};throw new Error(`could not resolve plugin source: "${t}". Use a git URL (https://\u2026/repo.git), GitHub shorthand (owner/repo), or a local path to a directory that exists on disk.`)}function uae(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("~")||e.startsWith("/")}function VF(e){let t=$s(e);return sae(t)?t:YF(process.cwd(),t)}var aae,lae,cae,Pl=y(()=>{"use strict";aae=/^(?:https?:\/\/|git:\/\/|ssh:\/\/|git\+ssh:\/\/|file:\/\/|git@[^:]+:)/,lae=/^([a-zA-Z0-9][a-zA-Z0-9_.-]*)\/([a-zA-Z0-9][a-zA-Z0-9._-]*?)(?:\.git)?$/,cae=/^([a-zA-Z0-9][a-zA-Z0-9_.-]*):([a-zA-Z0-9][a-zA-Z0-9_.-]*)$/});import{basename as dae,dirname as pae,join as Dx,relative as mae,resolve as Ml,sep as Vd}from"path";import{homedir as Xe}from"os";function XF(e){let t=Ml(e);return Dx(st(pae(t)),dae(t))}function Fx(e){return e?e.split(":").map(t=>t.trim()).filter(Boolean).map(t=>t==="~"||t.startsWith("~/")?$s(t.replace(/^~\/+/,"~/")):t).map(t=>Ml(t)):[]}function gae(){try{return[st(Ml(Dx(ke(),"config")))]}catch(e){return _r(e),[]}}function hae(){try{let e=ke();return co.filter(t=>t.startsWith(JF)).map(t=>XF(Dx(e,t.slice(JF.length))))}catch(e){return _r(e),[]}}function QF(){let e=`${v.AFK_READ_DENYLIST??""}\0${v.AFK_HOME??""}`;if(Yd&&Yd.key===e)return Yd;let t=Fx(v.AFK_READ_DENYLIST).map(s=>st(s)).filter(Boolean),n=$x.map(s=>({source:s,root:st(Ml(s))})),r=gae(),o=[...new Set([...n.map(({root:s})=>s),...r])],i=n.filter(({source:s,root:a})=>s!==fae||!r.includes(a)).map(({root:s})=>s);return Yd={key:e,builtins:o,extras:t,allow:[...new Set([...KF(co.map(s=>({rel:s,resolved:XF(`${Xe()}/${s}`)})),n),...Ox(hae(),i)])]},Yd}function Lx(){let{builtins:e,extras:t}=QF();return[...e,...t]}function ZF(e){let t=st(Ml(e));return Lx().filter(n=>n!==t&&_l(n,t,n)).map(n=>(n.startsWith(t+Vd)?mae(t,n):n.split(Vd).slice(t.split(Vd).length).join(Vd)).split(Vd).join("/"))}function Qt(e){let t=st(Ml(e)),{builtins:n,extras:r,allow:o}=QF();for(let i of r)if(_l(t,i))return{denied:!0,matched:i};if(o.includes(t))return{denied:!1};for(let i of n)if(_l(t,i))return{denied:!0,matched:i};return{denied:!1}}var $x,co,fae,m2e,Yd,JF,uo=y(()=>{"use strict";B();Ds();K();zd();GF();wh();Pl();$x=[`${Xe()}/.ssh`,`${Xe()}/.aws`,`${Xe()}/.gnupg`,`${Xe()}/.config/gcloud`,`${Xe()}/.afk/config`,`${Xe()}/.npmrc`,`${Xe()}/.docker/config.json`,`${Xe()}/.git-credentials`,`${Xe()}/.netrc`,`${Xe()}/.config/gh/hosts.yml`,`${Xe()}/.kube/config`,"/etc/shadow","/etc/sudoers","/private/etc/master.passwd",`${Xe()}/.password-store`,`${Xe()}/Library/Application Support/Google/Chrome`,`${Xe()}/Library/Application Support/Chromium`,`${Xe()}/Library/Application Support/BraveSoftware`,`${Xe()}/Library/Application Support/Microsoft Edge`,`${Xe()}/Library/Application Support/Arc`,`${Xe()}/Library/Application Support/Firefox`],co=[".afk/config/mcp.json",".ssh/config",".ssh/known_hosts"],fae=`${Xe()}/.afk/config`,m2e=co.map(e=>`${Xe()}/${e}`);JF=".afk/"});import Fs from"path";import{realpathSync as yae}from"fs";function fn(e){try{return yae.native(e)}catch{let t=Fs.dirname(e),n=Fs.basename(e);return t===e?e:Fs.join(fn(t),n)}}function bae(e){let t=eL.get(e);if(t!==void 0)return t;let n=fn(e);return eL.set(e,n),n}function tL(e,t,n,r){let o=t?.resolveBase??t?.cwd??r,i=Fs.isAbsolute(e)?e:Fs.resolve(o??process.cwd(),e);if(t?.allowAll===!0)return{restricted:!1,resolved:i,roots:[]};if(o===void 0)return{restricted:!1,resolved:i,roots:[]};let s=fn(i),a=n==="read"?t?.readRoots??[o]:t?.writeRoots??[o];for(let l of a){let c=bae(l),u=Fs.relative(c,s);if(!u.startsWith("..")&&!Fs.isAbsolute(u))return{restricted:!1,resolved:i,roots:a}}return{restricted:!0,resolved:i,roots:a}}function Zt(e,t,n="read",r){let{restricted:o,resolved:i,roots:s}=tL(e,t,n,r);if(n==="read"){let a=Qt(i);if(a.denied)throw new Error(`Path \`${e}\` is a protected credential/secret path (read-denylist entry: \`${a.matched}\`) and cannot be read.`)}if(o){let a=s.map(c=>`\`${c}\``).join(", "),l=n==="read"?"read roots":"write roots";throw new Error(`Path \`${e}\` is outside the allowed ${l} [${a}].`)}return i}function Jd(e,t,n="read",r){return tL(e,t,n,r)}function nL(e){let t=new Set,n=[];for(let r of e.split(/\s+/)){if(r.length===0)continue;let o=r.replace(/^\d*[<>|&]+/,"").replace(/^['"]/,"").replace(/['";,)]+$/,"");if(o.length===0)continue;let i=o.startsWith("/"),s=o==="~"||o.startsWith("~/");!i&&!s||t.has(o)||(t.add(o),n.push(o))}return n}var eL,Pn=y(()=>{"use strict";uo();eL=new Map});import{spawn as Sae}from"child_process";import wae from"os";function vae(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e;if(typeof t.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(t.timeout_ms<0||t.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=t.timeout_ms}return{command:t.command,timeout_ms:n}}function Eh(e,t){let n=!1,r=!1;function o(){n||e==="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 i(s,a){if(r)return;let l=a.resolveBase??a.cwd??t,c=wae.homedir(),u=[];for(let d of nL(s)){let p=d==="~"?c:d.startsWith("~/")?c+d.slice(1):d,f=Jd(p,a,"write",l);f.restricted&&u.push(f.resolved)}u.length!==0&&(r=!0,console.warn(`[security] bash: command references path(s) outside writeRoots: ${u.join(", ")} \u2014 bash containment is best-effort (tracked C4); use file tools for contained writes.`),Fe({event:"tool.bash_path_escape",tool:"bash",restricted_count:u.length,mode:"write"}))}return async(s,a,l)=>{let{command:c,timeout_ms:u}=vae(s);if(a.aborted)return{content:"Command aborted",isError:!0};if(o(),l!==void 0)try{i(c,l)}catch{}return new Promise(d=>{let p=!1;function f(A){p||(p=!0,clearTimeout(h),a.removeEventListener("abort",T),d(A))}let g=Sae(c,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...(l?.resolveBase??l?.cwd??t)!==void 0?{cwd:l?.resolveBase??l?.cwd??t}:{},...l?.env!==void 0?{env:{...process.env,...l.env}}:{}});g.unref();let h=setTimeout(()=>{g.pid!==void 0&&process.kill(-g.pid,"SIGKILL"),f({content:`Command timed out after ${u}ms`,isError:!0})},u),b="",S="",w=0,k=!1;function E(A){if(k||p||w<8e6)return;k=!0,console.warn(`[bash] overflow kill: stream=${A} totalBytes=${w} command="${c}"`),Fe({event:"tool.overflow_kill",tool:"bash",total_bytes:w,stream:A}),g.kill("SIGKILL");let M=Zn((b+S).trimEnd()),_=xx(M)??void 0,R=ao(M,1e5)+rh;f({content:R,truncated:!0,..._!==void 0?{testResult:_}:{}})}g.stdout.on("data",A=>{let M=8e6-w,_=A.length<=M?A:A.subarray(0,Math.max(0,M));w+=_.length,b+=_.toString("utf8"),E("stdout")}),g.stderr.on("data",A=>{let M=8e6-w,_=A.length<=M?A:A.subarray(0,Math.max(0,M));w+=_.length,S+=_.toString("utf8"),E("stderr")});let T=()=>{g.pid!==void 0&&process.kill(-g.pid,"SIGKILL"),f({content:"Command aborted",isError:!0})};a.addEventListener("abort",T),a.aborted&&T(),g.on("close",A=>{if(a.aborted){f({content:"Command aborted",isError:!0});return}if(A!==null&&A!==0){let C=lo(S.trimEnd()||b.trimEnd());f({content:`Command exited with code ${A}${C.content?`
|
|
227
229
|
`+C.content:""}`,isError:!0,...C.truncated?{truncated:!0}:{}});return}if(k)return;let M=Zn((b+S).trimEnd()),_=xx(M)??void 0,R=lo(M);f({content:R.content,...R.truncated?{truncated:!0}:{},..._!==void 0?{testResult:_}:{}})}),g.on("error",A=>{let M=l?.resolveBase??l?.cwd??t,_;if(M===void 0&&qd(A))try{let R=process.cwd();_=Cl(A,R)}catch{_=`working directory does not exist (process cwd deleted \u2014 deleted worktree?) \u2014 underlying: ${A.message}`}else _=Cl(A,M);f({content:`Failed to execute: ${_}`,isError:!0})})})}}var rL,oL=y(()=>{"use strict";Qn();FF();In();Rx();ei();Pn();rL=Eh("default")});function ri(e,t,n="Path"){if(!(e instanceof Error))return;let r=e.code;if(r==="ENOENT")return{content:`${n} not found: ${t}`,isError:!0};if(r==="EACCES")return{content:`Permission denied: ${t}`,isError:!0};if(r==="ENOTDIR")return{content:`Not a directory: ${t}`,isError:!0}}var Qd=y(()=>{"use strict"});import{promises as kae}from"fs";function Nx(e){return(t,n,r)=>Tae(t,n,r,e)}var Tae,iL,sL=y(()=>{"use strict";Pn();Qd();Tae=async(e,t,n,r)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let o=e,i=o.file_path,s=o.offset??1,a=o.limit??2e3;if(typeof i!="string")return{content:"Invalid input: file_path must be a string",isError:!0};if(typeof s!="number"||s<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=Zt(i,n,"read",r)}catch(c){return{content:c instanceof Error?c.message:String(c),isError:!0}}try{let c=await kae.readFile(l),u=Math.min(8192,c.length);for(let k=0;k<u;k++)if(c[k]===0)return{content:`File appears to be binary: ${l}`,isError:!0};let d=c.toString("utf-8");if(d.length===0)return{content:""};let p=d.split(`
|
|
228
230
|
`),f=Math.max(0,s-1),g=Math.min(p.length,f+a),h=p.slice(f,g),b=p.length;if(h.length===0)return{content:`... (offset ${s} is past end of file \u2014 file has ${b} lines)`};let S=String(b).length,w=h.map((k,E)=>{let T=f+E+1;return`${String(T).padStart(S," ")} ${k}`}).join(`
|
|
@@ -314,7 +316,7 @@ ${o}`,paths:[t,n]}:o!==null?i={content:o,paths:[n]}:r!==null?i={content:r,paths:
|
|
|
314
316
|
|
|
315
317
|
${t}`}var Dce,uR=y(()=>{"use strict";Dce=new Set(["script","style","noscript","template","svg"])});function Lce(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new Error("aborted"));return}let o=()=>{clearTimeout(i),r(t?.reason??new Error("aborted"))},i=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})})}function DN(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function Nce(e,t){let n=e.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,t)}async function $N(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??Lce,l=n.signal??void 0,c;for(let u=0;u<=o;u++){if(l?.aborted)throw l.reason??new Error("aborted");try{let d=await e(t,n);if(!Fce.has(d.status)||u===o)return d;let p=Nce(d,s)??DN(u,i,s);U("[web/retryFetch] retrying",{url:t,attempt:u,status:d.status,waitMs:p}),await d.body?.cancel().catch(()=>{}),await a(p,l)}catch(d){if(l?.aborted||(c=d,u===o))throw d;let p=DN(u,i,s);U("[web/retryFetch] retrying after error",{url:t,attempt:u,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var Fce,FN=y(()=>{"use strict";ue();Fce=new Set([429,502,503,504])});import{BlockList as Bce,isIP as pR}from"node:net";import{lookup as Uce}from"node:dns/promises";import{Agent as jce}from"undici";function NN(){let e=v.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return e==="1"||e==="true"}function Gce(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function dR(e){let t=pR(e);return t===0?!1:Kce.check(e,t===4?"ipv4":"ipv6")}async function BN(e){return Uce(e,{all:!0,verbatim:!0})}async function mR(e,t={}){if(t.allowPrivateHosts??NN())return{allowed:!0};let n;try{n=new URL(e)}catch{return{allowed:!1,reason:`"${e}" is not a valid absolute URL`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{allowed:!1,reason:`protocol "${n.protocol}" not supported (http/https only)`};let r=Gce(n.hostname),o=(a,l)=>`refusing to fetch ${l} \u2014 internal/private address ${a} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`;if(pR(r)!==0)return dR(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let i=t.lookupFn??BN,s;try{s=await i(r)}catch{return{allowed:!0}}for(let a of s)if(dR(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function pp(e,t={}){let n=await mR(e,t);if(!n.allowed)throw new tr(n.reason)}async function Gh(e,t,n={},r={}){let o={...r.lookupFn!==void 0?{lookupFn:r.lookupFn}:{},...r.allowPrivateHosts!==void 0?{allowPrivateHosts:r.allowPrivateHosts}:{}},i=t;for(let s=0;s<=LN;s++){await pp(i,o);let a={...n,redirect:"manual",...e===globalThis.fetch&&!(r.allowPrivateHosts??NN())?{dispatcher:qce}:{}},l=await $N(e,i,a,r.retry??{});if(!zce.has(l.status))return l;let c=l.headers.get("location");if(c===null||c.trim()==="")return l;let u;try{u=new URL(c,l.url||i).toString()}catch{return l}await l.body?.cancel().catch(()=>{}),i=u}throw new tr(`too many redirects (>${LN}) starting from ${t}`)}var Hce,Wce,Kce,tr,qce,LN,zce,fR=y(()=>{"use strict";B();FN();Hce=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.168.0.0",16]],Wce=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],Kce=(()=>{let e=new Bce;for(let[t,n]of Hce)e.addSubnet(t,n,"ipv4");for(let[t,n]of Wce)e.addSubnet(t,n,"ipv6");return e})(),tr=class extends Error{constructor(t){super(t),this.name="EgressBlockedError"}};qce=new jce({connect:{lookup(e,t,n){BN(e).then(r=>{let o=r.find(s=>dR(s.address));if(o!==void 0){n(new tr(`refusing to connect to ${e} (resolved) \u2014 internal/private address ${o.address} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`),"",0);return}let i=r[0];if(i===void 0){n(new Error(`DNS lookup returned no addresses for ${e}`),"",0);return}n(null,i.address,pR(i.address))},r=>n(r,"",0))}}});LN=20,zce=new Set([301,302,303,307,308])});import{readFileSync as Vce}from"node:fs";import{join as Yce}from"path";function Jce(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function UN(e,t){return Jce(t).test(e)}function Zce(e,t){if(e!==void 0){let n=e.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(t!==void 0){if(Xce.has(t))return!0;if(Qce.has(t))return!1}return!1}function jN(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function eue(e){if(e===void 0||e===""||e==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${e}`)}function HN(e){let t=e===void 0||e.trim()===""?"default":e.trim();return fd(t),t}function tue(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function nue(e){try{return Vce(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function rue(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return typeof t.defaultProfile=="string"&&(n.defaultProfile=HN(t.defaultProfile)),n}function WN(e){let t=e?.env??v,n=e?.readFileSync??nue,r=e?.surface??t.AGENT_SURFACE,o=Zce(t.AFK_BROWSER_HEADLESS,r),i=jN(t.AFK_BROWSER_ALLOWED_DOMAINS),s=jN(t.AFK_BROWSER_BLOCKED_DOMAINS),a=tue(t.AFK_BROWSER_DOM_SNAPSHOTS),l=eue(t.AFK_BROWSER_BACKEND),c=HN(t.AFK_BROWSER_DEFAULT_PROFILE),u={headless:o,allowedDomains:i,blockedDomains:s,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},d=t.AFK_BROWSER_CONFIG,p=d!==void 0&&d.trim()!==""?d.trim():Yce(zn(),"browser.json"),f=n(p);if(f===void 0)return u;let g;try{g=JSON.parse(f)}catch(b){throw new Error(`Failed to parse browser config at ${p}: ${String(b)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${p} must be a JSON object`);let h=rue(u,g);return h.configPath=p,h}function qh(e,t){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${e}`}}for(let r of t.blockedDomains)if(UN(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>UN(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Xce,Qce,zh=y(()=>{"use strict";B();K();Xce=new Set(["daemon","subagent","telegram","afk"]),Qce=new Set(["repl","interactive","cli"])});import{existsSync as oue,readFileSync as iue}from"node:fs";import{createRequire as sue}from"node:module";import{dirname as aue,join as lue}from"node:path";function qN(e){if(typeof e=="string")return e;let t=[],n=e;for(let r=0;r<uue&&n instanceof Error;r++)t.push(n.message),n=n.cause;return t.length>0?t.join(" | "):String(e)}function tn(e){let t=qN(e);return GN.some(n=>t.includes(n))}function due(){try{let t=sue(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(iue(t,"utf8"));if(typeof n!="object"||n===null)return;let r=n.bin,o=typeof r=="string"?r:typeof r=="object"&&r!==null?r.playwright:void 0;if(typeof o!="string"||o.length===0)return;let i=lue(aue(t),o);return oue(i)?`node ${/\s/.test(i)?`"${i}"`:i} install chromium`:void 0}catch{return}}function mp(){return KN??=due()??cue,KN}function gR(e){return e.includes("install chromium")}function On(e,t){let n=qN(e),r=t?.latched===!0?` ${pue}`:"";if(n.includes("Executable doesn't exist")){let o="";return t?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":t?.headless===!1&&(o=" This launch was headed, which needs the full `chromium-*` build \u2014 the headless shell alone does not satisfy it."),`browser tools require the Playwright chromium binary. Install via: ${mp()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${mp()}). Or pick a different tool.${r}`}function fp(e,t,n=!1){if(!tn(e))return e;let r=e instanceof Error?e.message:String(e);return new Error(`${r}
|
|
316
318
|
|
|
317
|
-
${On(e,{headless:t,latched:n})}`,{cause:e})}var GN,cue,uue,KN,pue,Vh=y(()=>{"use strict";GN=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],cue="pnpm exec playwright install chromium",uue=4;pue="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 Bs from"node:fs";import Yh from"node:path";import{randomBytes as mue}from"node:crypto";import{chromium as fue}from"playwright";function gue(){try{return"5.120.0"}catch{}try{let e=Yh.resolve(import.meta.dirname,"../../../package.json"),t=Bs.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var hue,Jh,zN=y(()=>{"use strict";Vh();K();ue();hue=gue(),Jh=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(t){this.config=t}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(t){this.launchFailure={error:t}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=fue.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,this.clearLaunchFailure(),t)).catch(t=>{this.launchPromise=void 0;let n=fp(t,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){i=l,await a.abort("blockedbyclient")}});let s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw i??p}if(i!==void 0)throw i;let c=await a.content();if(i!==void 0)throw i;let u=a.url(),d=l!==null?l.status():null;return{html:c,finalUrl:u,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){this.clearLaunchFailure();let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${hue}`}}loadStorageState(t){let n=gd(t);try{if(!Bs.existsSync(n))return;let r=JSON.parse(Bs.readFileSync(n,"utf8"));return U("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){U("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=gd(t);if(!Bs.existsSync(r))return;let o=await n.storageState(),i=Yh.join(Yh.dirname(r),`.${Yh.basename(r)}.${process.pid}.${mue(4).toString("hex")}.tmp`);Bs.writeFileSync(i,JSON.stringify(o),{mode:384}),Bs.chmodSync(i,384),Bs.renameSync(i,r),U("[browser/vault] saved session",{profile:t,file:r})}catch(r){U("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as yue}from"crypto";function VN(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&bue.test(e.label))}function YN(e){return yue("sha256").update(e,"utf8").digest("hex").slice(0,8)}function JN(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var bue,Xh=y(()=>{"use strict";bue=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Sue}from"node:crypto";function wue(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function vue(e,t,n){return`el_${Sue("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function kue(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function XN(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function ZN(e,t){let n=e.role??"",r=e.name??"";QN.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])ZN(i,t)}async function Tue(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let i=o.getBoundingClientRect(),s=o;if(i.width===0&&i.height===0){let u=window.getComputedStyle(s);if(u.display==="none"||u.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},eB).catch(()=>[])}async function Eue(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let i of r){let s=i.tagName.toLowerCase(),a=i.getAttribute("role")??"",l=i.getAttribute("aria-label")??i.getAttribute("placeholder")??(i.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[s]??"");if(s==="input"){let h=i.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let u="value"in i?i.value:void 0,d=u!==void 0?String(u):void 0,p=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},eB).catch(()=>[])}function xue(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Qh(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=xue(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Tue(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,f,g,h]=await Promise.all([s,a,l,c,u]),b,S=!1;d!==null?(b=[],ZN(d,b)):(o.push("observation skipped accessibility tree (returned null)"),S=!0,b=(await Eue(e)).filter(O=>QN.has(O.role??"")));let w=new Map;for(let P of p){let O=XN(P.name),z=w.get(O);(!z||z.bbox.w===0&&P.bbox.w>0)&&w.set(O,P)}let k=b.map(P=>({ax:P,dom:w.get(XN(P.name??""))})),E=r?k:k.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);E.sort((P,O)=>{let z=P.dom?.bbox.y??0,$=O.dom?.bbox.y??0;if(z!==$)return z-$;let G=P.dom?.bbox.x??0,H=O.dom?.bbox.x??0;return G-H}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=E.slice(0,n).map((P,O)=>{let z=P.ax.role??"generic",$=P.ax.name??"",G=vue(z,$,O),H=P.dom?.bbox??{x:0,y:0,w:0,h:0},I=P.dom?.type??null,L=null;P.ax.value!==void 0&&P.ax.value!==null&&(L=String(P.ax.value)),P.ax.checked!==void 0&&(L=String(P.ax.checked)),VN({role:z,kind:I})&&(L="[redacted]");let F={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(F.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(F.selected=P.ax.selected),P.ax.expanded!==void 0&&(F.expanded=P.ax.expanded);let D;P.dom?.testId?D=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(D=`#${P.dom.id}`);let W={id:G,role:z,label:wue($),kind:I,value:L,state:F,bbox:H};return D!==void 0&&(W.selector=D),W}),M="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?M="loading":P==="interactive"?M="navigating":M="idle"}catch{M="navigating"}M!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),S&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let _=kue(f),R=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:R,url:g,title:h,textSummary:_,interactive:A,status:{httpStatus:t.httpStatus??null,loadingState:M,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var QN,eB,tB=y(()=>{"use strict";Xh();QN=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);eB="a[href], button, input, select, textarea, [role], [tabindex], label"});async function nB(e,t){try{let n=await e.nth(t).evaluate(s=>{let a=s,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.height)}}),r=`${n.role}:${n.label}:${t}`,o=0;for(let s=0;s<r.length;s++)o=o*31+r.charCodeAt(s)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function hR(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>nB(e,i)))).filter(o=>o!==null)}async function Rue(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let i=0;i<o;i++){let s;try{s=await r.nth(i).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(s)||(t.add(s),n.push({key:s,locator:r,index:i}))}return n}async function yR(e,t,n){switch(t.kind){case"element_id":return Aue(e,t,n);case"selector":return Cue(e,t);case"semantic":return _ue(e,t)}}async function Aue(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),i=await o.count();if(i===0)return{outcome:"not_found",query:t};if(i===1)return{outcome:"resolved",locator:o};let s=await hR(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function Cue(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await hR(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function _ue(e,t){return t.role!==void 0?Iue(e,t.text,t.role):Pue(e,t.text,t)}async function Iue(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let i=await hR(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function Pue(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),i=e.getByLabel(t,{exact:!1}),[s,a,l]=await Promise.all([r.count(),o.count(),i.count()]);if(s+a+l===0)return{outcome:"not_found",query:n};let u=[];s>0&&u.push({loc:r,count:s}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:i,count:l});let d=await Rue(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=d.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let S=await nB(b.locator,b.index);if(S!==null){let w=`${S.role}:${S.label}:${h}`,k=0;for(let E=0;E<w.length;E++)k=k*31+w.charCodeAt(E)>>>0;f.push({...S,id:`el_${k.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var rB=y(()=>{"use strict"});async function bR(e,t,n,r){let o=e.url();if(o===n)return null;let i=qh(o,t);if(i.allowed)return null;try{await e.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:i.reason}}var oB=y(()=>{"use strict";zh()});import{randomBytes as Mue}from"crypto";import{mkdir as Oue,stat as Due,writeFile as $ue}from"fs/promises";import{join as SR}from"path";import{gzip as Fue}from"zlib";import{promisify as Lue}from"util";function Nue(e){return SR(un(e),"browser")}function Bue(e){return SR(Nue(e),"screenshots")}function Uue(){return new Date().toISOString().replace(/[:.]/g,"-")}function jue(){return Mue(3).toString("hex")}async function wR(e,t,n){if(t.length>iB)throw new Error(`writeScreenshotSidecar: buffer exceeds ${iB} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=Bue(e);await Oue(r,{recursive:!0});let o=`${Uue()}-${jue()}-${n}.png`,i=SR(r,o);await $ue(i,t);let{size:s}=await Due(i);return{path:i,bytes:s}}var nYe,iB,sB=y(()=>{"use strict";K();Xh();nYe=Lue(Fue);iB=5*1024*1024});var lB={};no(lB,{PlaywrightProvider:()=>vR});function aB(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var vR,cB=y(()=>{"use strict";zN();tB();rB();zh();oB();sB();vR=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Jh(t)}async open(t){let n=qh(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(d){a=d}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let d=await bR(o,this.config,t.url,()=>this.close({sessionId:r}));if(d!==null)return d}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let u=await Qh(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,u.interactive,u.url,u.title,"browser_open"),a!==null)throw a;return u}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await Qh(r,{observationCounter:o.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,s.interactive,s.url,s.title,"browser_observe"),s}async act(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),i=r.url(),s=t.timeoutMs??3e4,a=await yR(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${aB(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":await l.fill(t.value??"");break;case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=await bR(r,this.config,i,()=>this.close({sessionId:n}));if(d!==null)return d;let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Qh(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal,requestGuard:t.requestGuard})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),i;if(t.target!==void 0){let u=await yR(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${aB(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await u.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await wR(n,i,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}return{path:s,bytes:a,width:l,height:c,dataBase64:i.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(t){let n=this.sessions.get(t);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(t,r),r}updateSessionFromObservation(t,n,r,o,i){t.knownElements=new Map(n.map(s=>[s.id,s])),t.currentUrl=r,t.currentTitle=o,t.lastAction=i,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:i}=await wR(n,o,r);return i}catch{return null}}}});var js={};no(js,{__resetBrowserRegistryForTests:()=>que,browserProviderActive:()=>Kue,closeBrowserProvider:()=>kR,getBrowserProvider:()=>Wue,peekBrowserProvider:()=>Gue});function uB(){Promise.resolve(kR()).then(()=>{process.exit(130)})}function dB(){Promise.resolve(kR()).then(()=>{process.exit(143)})}function pB(){Mr=null}function Hue(){Zh||(process.on("SIGINT",uB),process.on("SIGTERM",dB),process.on("exit",pB),Zh=!0)}function mB(){Zh&&(process.removeListener("SIGINT",uB),process.removeListener("SIGTERM",dB),process.removeListener("exit",pB),Zh=!1)}async function Wue(e){return Mr!==null?Mr:(Us!==null||(Us=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(cB(),lB)),n=WN(e),r=new t(n);return Hue(),Mr=r,Us=null,r})()),Us)}async function kR(){if(Mr===null)return;let e=Mr;Mr=null,Us=null,mB(),await e.shutdown()}function Kue(){return Mr!==null}function Gue(){return Mr}function que(){Mr=null,Us=null,mB()}var Mr,Us,Zh,Hs=y(()=>{"use strict";zh();Mr=null,Us=null,Zh=!1});async function fB(e,t){try{return await PN(e,t)}catch(n){return U("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function Que(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Hs(),js));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function gB(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??Que,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let d=await Gh(n,e,{headers:Xue,signal:t.signal},o);l=d.status,a=d.url||e;let p=d.headers.get("content-type")??"";if(d.ok){if(Jue.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await d.text();if(Yue.test(p)&&!Vue.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await fB(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof tr||d instanceof Error&&d.message.startsWith("web_scrape markdown mode received binary"))throw d;c=d}if(!(i===null||i.textLength<200)&&i!==null){let d=cR({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...d!==void 0?{advisory:d}:{}}}try{await pp(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>pp(f,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await pp(d.finalUrl,o);let p=await fB(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||p.textLength>=i.textLength){let f=cR({html:d.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:d.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(d){if(t.signal.aborted||d instanceof tr)throw d;if(i===null){let p=d instanceof Error?d.message:String(d),f=c instanceof Error?c.message:`HTTP ${l??"error"}`,g=new Error(`web_scrape could not retrieve ${e}: fetch failed (${f}) and render failed (${p}).`);throw g.cause=d,g}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${l??"error"}).`)}var Vue,Yue,Jue,Xue,hB=y(()=>{"use strict";MN();uR();fR();ue();Vue=/(text\/html|application\/xhtml\+xml)/i,Yue=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,Jue=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,Xue={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function tde(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(Zue,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),ede),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let u=await i.text(),d=Oe(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}catch{}let c=i.statusText?` ${i.statusText}`:"";throw new Error(`Exa Search HTTP ${i.status}${c}${l}`)}let s;try{s=await i.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(s.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function yB(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?tde({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function bB(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
319
|
+
${On(e,{headless:t,latched:n})}`,{cause:e})}var GN,cue,uue,KN,pue,Vh=y(()=>{"use strict";GN=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],cue="pnpm exec playwright install chromium",uue=4;pue="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 Bs from"node:fs";import Yh from"node:path";import{randomBytes as mue}from"node:crypto";import{chromium as fue}from"playwright";function gue(){try{return"5.121.0"}catch{}try{let e=Yh.resolve(import.meta.dirname,"../../../package.json"),t=Bs.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var hue,Jh,zN=y(()=>{"use strict";Vh();K();ue();hue=gue(),Jh=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(t){this.config=t}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(t){this.launchFailure={error:t}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=fue.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,this.clearLaunchFailure(),t)).catch(t=>{this.launchPromise=void 0;let n=fp(t,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){i=l,await a.abort("blockedbyclient")}});let s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw i??p}if(i!==void 0)throw i;let c=await a.content();if(i!==void 0)throw i;let u=a.url(),d=l!==null?l.status():null;return{html:c,finalUrl:u,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){this.clearLaunchFailure();let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${hue}`}}loadStorageState(t){let n=gd(t);try{if(!Bs.existsSync(n))return;let r=JSON.parse(Bs.readFileSync(n,"utf8"));return U("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){U("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=gd(t);if(!Bs.existsSync(r))return;let o=await n.storageState(),i=Yh.join(Yh.dirname(r),`.${Yh.basename(r)}.${process.pid}.${mue(4).toString("hex")}.tmp`);Bs.writeFileSync(i,JSON.stringify(o),{mode:384}),Bs.chmodSync(i,384),Bs.renameSync(i,r),U("[browser/vault] saved session",{profile:t,file:r})}catch(r){U("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as yue}from"crypto";function VN(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&bue.test(e.label))}function YN(e){return yue("sha256").update(e,"utf8").digest("hex").slice(0,8)}function JN(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var bue,Xh=y(()=>{"use strict";bue=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Sue}from"node:crypto";function wue(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function vue(e,t,n){return`el_${Sue("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function kue(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function XN(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function ZN(e,t){let n=e.role??"",r=e.name??"";QN.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])ZN(i,t)}async function Tue(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let i=o.getBoundingClientRect(),s=o;if(i.width===0&&i.height===0){let u=window.getComputedStyle(s);if(u.display==="none"||u.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},eB).catch(()=>[])}async function Eue(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let i of r){let s=i.tagName.toLowerCase(),a=i.getAttribute("role")??"",l=i.getAttribute("aria-label")??i.getAttribute("placeholder")??(i.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[s]??"");if(s==="input"){let h=i.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let u="value"in i?i.value:void 0,d=u!==void 0?String(u):void 0,p=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},eB).catch(()=>[])}function xue(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Qh(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=xue(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Tue(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,f,g,h]=await Promise.all([s,a,l,c,u]),b,S=!1;d!==null?(b=[],ZN(d,b)):(o.push("observation skipped accessibility tree (returned null)"),S=!0,b=(await Eue(e)).filter(O=>QN.has(O.role??"")));let w=new Map;for(let P of p){let O=XN(P.name),z=w.get(O);(!z||z.bbox.w===0&&P.bbox.w>0)&&w.set(O,P)}let k=b.map(P=>({ax:P,dom:w.get(XN(P.name??""))})),E=r?k:k.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);E.sort((P,O)=>{let z=P.dom?.bbox.y??0,$=O.dom?.bbox.y??0;if(z!==$)return z-$;let G=P.dom?.bbox.x??0,H=O.dom?.bbox.x??0;return G-H}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=E.slice(0,n).map((P,O)=>{let z=P.ax.role??"generic",$=P.ax.name??"",G=vue(z,$,O),H=P.dom?.bbox??{x:0,y:0,w:0,h:0},I=P.dom?.type??null,L=null;P.ax.value!==void 0&&P.ax.value!==null&&(L=String(P.ax.value)),P.ax.checked!==void 0&&(L=String(P.ax.checked)),VN({role:z,kind:I})&&(L="[redacted]");let F={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(F.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(F.selected=P.ax.selected),P.ax.expanded!==void 0&&(F.expanded=P.ax.expanded);let D;P.dom?.testId?D=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(D=`#${P.dom.id}`);let W={id:G,role:z,label:wue($),kind:I,value:L,state:F,bbox:H};return D!==void 0&&(W.selector=D),W}),M="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?M="loading":P==="interactive"?M="navigating":M="idle"}catch{M="navigating"}M!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),S&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let _=kue(f),R=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:R,url:g,title:h,textSummary:_,interactive:A,status:{httpStatus:t.httpStatus??null,loadingState:M,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var QN,eB,tB=y(()=>{"use strict";Xh();QN=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);eB="a[href], button, input, select, textarea, [role], [tabindex], label"});async function nB(e,t){try{let n=await e.nth(t).evaluate(s=>{let a=s,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.height)}}),r=`${n.role}:${n.label}:${t}`,o=0;for(let s=0;s<r.length;s++)o=o*31+r.charCodeAt(s)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function hR(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>nB(e,i)))).filter(o=>o!==null)}async function Rue(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let i=0;i<o;i++){let s;try{s=await r.nth(i).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(s)||(t.add(s),n.push({key:s,locator:r,index:i}))}return n}async function yR(e,t,n){switch(t.kind){case"element_id":return Aue(e,t,n);case"selector":return Cue(e,t);case"semantic":return _ue(e,t)}}async function Aue(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),i=await o.count();if(i===0)return{outcome:"not_found",query:t};if(i===1)return{outcome:"resolved",locator:o};let s=await hR(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function Cue(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await hR(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function _ue(e,t){return t.role!==void 0?Iue(e,t.text,t.role):Pue(e,t.text,t)}async function Iue(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let i=await hR(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function Pue(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),i=e.getByLabel(t,{exact:!1}),[s,a,l]=await Promise.all([r.count(),o.count(),i.count()]);if(s+a+l===0)return{outcome:"not_found",query:n};let u=[];s>0&&u.push({loc:r,count:s}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:i,count:l});let d=await Rue(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=d.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let S=await nB(b.locator,b.index);if(S!==null){let w=`${S.role}:${S.label}:${h}`,k=0;for(let E=0;E<w.length;E++)k=k*31+w.charCodeAt(E)>>>0;f.push({...S,id:`el_${k.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var rB=y(()=>{"use strict"});async function bR(e,t,n,r){let o=e.url();if(o===n)return null;let i=qh(o,t);if(i.allowed)return null;try{await e.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:i.reason}}var oB=y(()=>{"use strict";zh()});import{randomBytes as Mue}from"crypto";import{mkdir as Oue,stat as Due,writeFile as $ue}from"fs/promises";import{join as SR}from"path";import{gzip as Fue}from"zlib";import{promisify as Lue}from"util";function Nue(e){return SR(un(e),"browser")}function Bue(e){return SR(Nue(e),"screenshots")}function Uue(){return new Date().toISOString().replace(/[:.]/g,"-")}function jue(){return Mue(3).toString("hex")}async function wR(e,t,n){if(t.length>iB)throw new Error(`writeScreenshotSidecar: buffer exceeds ${iB} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=Bue(e);await Oue(r,{recursive:!0});let o=`${Uue()}-${jue()}-${n}.png`,i=SR(r,o);await $ue(i,t);let{size:s}=await Due(i);return{path:i,bytes:s}}var nYe,iB,sB=y(()=>{"use strict";K();Xh();nYe=Lue(Fue);iB=5*1024*1024});var lB={};no(lB,{PlaywrightProvider:()=>vR});function aB(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var vR,cB=y(()=>{"use strict";zN();tB();rB();zh();oB();sB();vR=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Jh(t)}async open(t){let n=qh(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(d){a=d}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let d=await bR(o,this.config,t.url,()=>this.close({sessionId:r}));if(d!==null)return d}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let u=await Qh(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,u.interactive,u.url,u.title,"browser_open"),a!==null)throw a;return u}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await Qh(r,{observationCounter:o.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,s.interactive,s.url,s.title,"browser_observe"),s}async act(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),i=r.url(),s=t.timeoutMs??3e4,a=await yR(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${aB(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":await l.fill(t.value??"");break;case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=await bR(r,this.config,i,()=>this.close({sessionId:n}));if(d!==null)return d;let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Qh(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal,requestGuard:t.requestGuard})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),i;if(t.target!==void 0){let u=await yR(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${aB(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await u.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await wR(n,i,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}return{path:s,bytes:a,width:l,height:c,dataBase64:i.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(t){let n=this.sessions.get(t);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(t,r),r}updateSessionFromObservation(t,n,r,o,i){t.knownElements=new Map(n.map(s=>[s.id,s])),t.currentUrl=r,t.currentTitle=o,t.lastAction=i,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:i}=await wR(n,o,r);return i}catch{return null}}}});var js={};no(js,{__resetBrowserRegistryForTests:()=>que,browserProviderActive:()=>Kue,closeBrowserProvider:()=>kR,getBrowserProvider:()=>Wue,peekBrowserProvider:()=>Gue});function uB(){Promise.resolve(kR()).then(()=>{process.exit(130)})}function dB(){Promise.resolve(kR()).then(()=>{process.exit(143)})}function pB(){Mr=null}function Hue(){Zh||(process.on("SIGINT",uB),process.on("SIGTERM",dB),process.on("exit",pB),Zh=!0)}function mB(){Zh&&(process.removeListener("SIGINT",uB),process.removeListener("SIGTERM",dB),process.removeListener("exit",pB),Zh=!1)}async function Wue(e){return Mr!==null?Mr:(Us!==null||(Us=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(cB(),lB)),n=WN(e),r=new t(n);return Hue(),Mr=r,Us=null,r})()),Us)}async function kR(){if(Mr===null)return;let e=Mr;Mr=null,Us=null,mB(),await e.shutdown()}function Kue(){return Mr!==null}function Gue(){return Mr}function que(){Mr=null,Us=null,mB()}var Mr,Us,Zh,Hs=y(()=>{"use strict";zh();Mr=null,Us=null,Zh=!1});async function fB(e,t){try{return await PN(e,t)}catch(n){return U("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function Que(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Hs(),js));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function gB(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??Que,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let d=await Gh(n,e,{headers:Xue,signal:t.signal},o);l=d.status,a=d.url||e;let p=d.headers.get("content-type")??"";if(d.ok){if(Jue.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await d.text();if(Yue.test(p)&&!Vue.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await fB(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof tr||d instanceof Error&&d.message.startsWith("web_scrape markdown mode received binary"))throw d;c=d}if(!(i===null||i.textLength<200)&&i!==null){let d=cR({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...d!==void 0?{advisory:d}:{}}}try{await pp(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>pp(f,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await pp(d.finalUrl,o);let p=await fB(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||p.textLength>=i.textLength){let f=cR({html:d.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:d.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(d){if(t.signal.aborted||d instanceof tr)throw d;if(i===null){let p=d instanceof Error?d.message:String(d),f=c instanceof Error?c.message:`HTTP ${l??"error"}`,g=new Error(`web_scrape could not retrieve ${e}: fetch failed (${f}) and render failed (${p}).`);throw g.cause=d,g}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${l??"error"}).`)}var Vue,Yue,Jue,Xue,hB=y(()=>{"use strict";MN();uR();fR();ue();Vue=/(text\/html|application\/xhtml\+xml)/i,Yue=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,Jue=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,Xue={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function tde(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(Zue,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),ede),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let u=await i.text(),d=Oe(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}catch{}let c=i.statusText?` ${i.statusText}`:"";throw new Error(`Exa Search HTTP ${i.status}${c}${l}`)}let s;try{s=await i.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(s.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function yB(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?tde({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function bB(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
318
320
|
|
|
319
321
|
(no results)`;let n=[`# Search results for "${e}"`,""];return t.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
|
|
320
322
|
`).trimEnd()}var Zue,ede,SB=y(()=>{"use strict";In();Zue="https://api.exa.ai/search",ede=10});function ey(e){if(e instanceof Error&&e.name==="TimeoutError")return"timeout";let t=e instanceof Error?e.message:String(e);return/Timeout\s+\d+\s*ms exceeded/i.test(t)?"timeout":void 0}var Ws=y(()=>{"use strict";Vh()});function ade(e){if(!e||typeof e!="object")return{error:"Invalid input: expected an object"};let t=e,n=t.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,i;if(r==="search"){if(typeof t.query!="string"||t.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};i=t.query}else{if(typeof t.url!="string"||t.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let l;try{l=new URL(t.url)}catch{return{error:`Invalid input: "${t.url}" is not a valid absolute URL`}}if(l.protocol!=="http:"&&l.protocol!=="https:")return{error:`Invalid input: protocol "${l.protocol}" not supported (http/https only)`};o=l.toString()}let s=nde;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};s=Math.min(t.timeout_ms,rde)}let a=ode;if(t.max_bytes!==void 0){if(typeof t.max_bytes!="number"||!Number.isFinite(t.max_bytes)||t.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(t.max_bytes,ide)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function TR(e,t){return Buffer.byteLength(e,"utf8")<=t?{content:e,truncated:!1}:{content:ao(e,t),truncated:!0}}function lde(e={}){let t=e.fetchFn??globalThis.fetch,n=e.env??process.env,r=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{};return async(o,i)=>{if(typeof t!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=ade(o);if("error"in s)return{content:s.error,isError:!0};if(i.aborted){let d=i.reason;return{content:`web_scrape aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let a=new AbortController,l=()=>{a.abort(i.reason)},c,u=()=>{let d=a.signal.reason;return d instanceof Error?d.message:String(d??"aborted")};try{if(i.addEventListener("abort",l,{once:!0}),c=setTimeout(()=>{a.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs),s.url!==void 0){let p=await mR(s.url,r);if(a.signal.aborted)return{content:`web_scrape aborted: ${u()}`,isError:!0};if(!p.allowed)return{content:`web_scrape blocked: ${p.reason}`,isError:!0}}if(s.mode==="raw"){let p;try{let h={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};p=await Gh(t,s.url,h,r)}catch(h){return a.signal.aborted?{content:`web_scrape aborted: ${u()}`,isError:!0}:h instanceof tr?{content:`web_scrape blocked: ${h.message}`,isError:!0}:{content:`web_scrape network error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}if(!p.ok)return{content:`web_scrape HTTP ${p.status} ${p.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let f;try{f=await p.text()}catch(h){return{content:`web_scrape read error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}let g=TR(f,s.maxBytes);return{content:g.content,...g.truncated?{truncated:!0}:{}}}if(s.mode==="markdown")try{let p=await gB(s.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:s.timeoutMs,signal:a.signal,...e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{}});if(p.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0};let f=TR(ON(p.markdown,p.advisory),s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){if(a.signal.aborted)return{content:`web_scrape aborted: ${u()}`,isError:!0};if(p instanceof tr)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),g=tn(p)&&!gR(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${mp()}\`)`:"";return{content:`web_scrape markdown error: ${f}${g}`,isError:!0}}let d=yB({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in d)return{content:d.error,isError:!0};try{let p=await d.search(s.query,{limit:sde,timeoutMs:s.timeoutMs,signal:a.signal}),f=TR(bB(s.query,p),s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){return a.signal.aborted?{content:`web_scrape aborted: ${u()}`,isError:!0}:{content:`web_scrape search error (${d.name}): ${p instanceof Error?p.message:String(p)}`,isError:!0}}}finally{c!==void 0&&clearTimeout(c),i.removeEventListener("abort",l)}}}var nde,rde,ode,ide,sde,wB,vB=y(()=>{"use strict";hB();SB();fR();ei();uR();Ws();nde=3e4,rde=12e4,ode=1e5,ide=1e6,sde=10;wB=lde()});import{existsSync as TB,mkdirSync as cde,readFileSync as ude,renameSync as dde,unlinkSync as pde,writeFileSync as mde}from"node:fs";import{dirname as kB,join as fde}from"node:path";import{randomBytes as gde}from"node:crypto";function hn(e){let t=e??uE();if(!TB(t))return[];try{let n=ude(t,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);return console.error(`[schedule-store] failed to parse ${t}: ${r}`),[]}}function si(e,t){let n=t??uE();cde(kB(n),{recursive:!0});let r=fde(kB(n),`.schedules.json.${process.pid}.${gde(4).toString("hex")}.tmp`),o=JSON.stringify(e,null,2);try{mde(r,o,"utf-8"),dde(r,n)}catch(i){try{TB(r)&&pde(r)}catch{}throw i}}function ty(e,t){let n=hn(t),r=n.map(l=>l.id),o=hde(e.name),i=yde(o,r),s=new Date().toISOString(),a={...e,notifyOn:e.notifyOn??"failure",id:i,createdAt:s,updatedAt:s};return n.push(a),si(n,t),a}function ny(e,t){let n=hn(t),r=n.length,o=n.filter(i=>i.id!==e);return o.length===r?!1:(si(o,t),!0)}function gp(e,t){return hn(t).find(n=>n.id===e)}function hde(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function yde(e,t){if(!t.includes(e))return e;let n=2;for(;t.includes(`${e}-${n}`);)n+=1;return`${e}-${n}`}function ry(e){return{taskId:e.id,command:e.command,trigger:e.trigger??"cron",...e.cron!==void 0?{cronExpression:e.cron}:{},...e.notifyOn!==void 0?{notifyOn:e.notifyOn}:{},...e.notifyChat!==void 0?{notifyChat:e.notifyChat}:{}}}var oy=y(()=>{"use strict";K()});import{existsSync as bde,readFileSync as Sde}from"node:fs";import{join as wde}from"node:path";async function Dn(e,t,n){let r;try{let o=wde(pg("default"),"port");if(!bde(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=Sde(o,"utf-8").trim();if(r=parseInt(i,10),Number.isNaN(r))return{synced:!1,detail:"daemon-not-detected (invalid port file)"}}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let o=await fetch(`http://localhost:${r}${t}`,{method:e,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return o.ok?{synced:!0,detail:"synced"}:e==="POST"&&o.status===409?{synced:!0,detail:"already-registered"}:e==="DELETE"&&o.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${o.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}var ai,ER=y(()=>{"use strict";K();ai="Change saved to schedules.json, but a running daemon (if any) did not pick it up \u2014 it will apply on the next daemon (re)start."});import{existsSync as vde}from"node:fs";import{readFile as kde}from"node:fs/promises";var EB,xB,RB,AB,CB=y(()=>{"use strict";oy();K();ER();EB=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected object",isError:!0};let n=e;if(typeof n.name!="string"||!n.name)return{content:"Invalid input: name required",isError:!0};if(typeof n.command!="string"||!n.command)return{content:"Invalid input: command required",isError:!0};if(typeof n.cron!="string"||!n.cron)return{content:"Invalid input: cron required",isError:!0};let r=n.cron.trim().split(/\s+/);if(r.length!==5&&r.length!==6)return{content:"Invalid input: cron must be a 5 or 6-field expression",isError:!0};let o=n.notifyChat;if(o!==void 0&&typeof o!="number"&&typeof o!="string")return{content:"Invalid input: notifyChat must be a number (chat id) or string (chat id or alias name)",isError:!0};let i=ty({name:n.name,command:n.command,cron:n.cron,trigger:n.trigger??"cron",notifyOn:n.notifyOn,...o!==void 0?{notifyChat:o}:{},enabled:typeof n.enabled=="boolean"?n.enabled:!0}),s=i.enabled?await Dn("POST","/tasks",{taskId:i.id,command:i.command,cron:i.cron,trigger:i.trigger,notifyOn:i.notifyOn,...i.notifyChat!==void 0?{notifyChat:i.notifyChat}:{}}):await Dn("DELETE",`/tasks/${i.id}`);return{content:JSON.stringify({id:i.id,name:i.name,cron:i.cron,enabled:i.enabled,daemonSynced:s.synced,syncDetail:s.detail,...s.synced?{}:{syncNote:ai}})}},xB=async(e,t)=>{let n=hn();return{content:JSON.stringify(n.map(r=>({id:r.id,name:r.name,cron:r.cron,trigger:r.trigger,enabled:r.enabled,notifyOn:r.notifyOn})))}},RB=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected object",isError:!0};let n=e;if(typeof n.taskId!="string"||!n.taskId)return{content:"Invalid input: taskId required",isError:!0};let r=n.taskId,o=typeof n.limit=="number"?Math.min(Math.max(1,n.limit),50):10,i=yr();if(!vde(i))return{content:JSON.stringify([])};let s;try{let c=await kde(i);s=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=s.split(`
|
|
@@ -1872,7 +1874,7 @@ ${E}
|
|
|
1872
1874
|
${T}`})}return{fileBlocks:l,warnings:c}}function z9(e){let t=e.replace(/\s+/g," ").trim();return t.length<=60?t:`${t.slice(0,59)}\u2026`}async function V9(e,t,n){let r=t?.peekQueuedText(),o=r!==void 0?{text:r.text,claimed:!1}:void 0;r!==void 0&&t?.reserveQueued?.(r);let i;try{i=await e.promoteActiveForeground(o)}catch(s){throw r!==void 0&&t?.releaseQueued?.(r),s}if(o?.claimed===!0&&t!==null&&r!==void 0){try{await n?.(o.text)}catch{}return t.dropQueued(r),{jobs:i,flushedText:o.text,flushedPreview:r.preview}}return r!==void 0&&t?.releaseQueued?.(r),{jobs:i}}Tv();async function Y9(e,t,n,r,o="summary",i,s){let a=SJ(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0),au(process.stdout,Lm(process.cwd(),!0));let l="",c=0,u=!1,d=!1,p=!1,f=!1,g=!1,h,b=!1,S=!1,w={abort:null},k=0,E=3e3,T=[],A=new Map,M=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,_=()=>{let $=r.subagentControl;$?.hasPromotableForeground()&&V9($,R,r.onQueuedUserMessage).then(({jobs:G,flushedText:H,flushedPreview:I})=>{let L=(i??{fn:console.log}).fn;for(let F of G)L(m.dim(` \u2192 subagent backgrounded as ${F.jobId}: ${F.label}`));H!==void 0&&L(m.dim(` \u2192 queued message sent to this turn: ${z9(I??H)}`))}).catch(()=>{})},R=r.getCompositor?r.getCompositor():null,C=()=>new Pu({out:Mu(i),thinkingMode:o,...M?{activeSkillName:M}:{},onCancel:()=>{t.interrupt().catch($=>{Ge()&&console.error(" "+m.error("session.interrupt() failed:"),$)})},...r.subagentControl?{onBackground:_}:{},...s?.history?{history:s.history}:{},...s?.autocompleteState?{autocompleteState:s.autocompleteState}:{},...s?.promptText!==void 0?{promptText:s.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...R?{compositor:R}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),P=C(),O=async()=>{if(!f){f=!0;try{await P.dispose()}catch{}}},z=async()=>{await P.arm();let $=P.getCompositor();if(i&&$){let G=$;i.fn=H=>G.commitAbove(H),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.($),r.setInterruptNotifier?.(G=>P.setInterrupting(G)),r.rearmStatus?.()};try{R?R.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{b=!0,P.setSoftStopping(!0),t.interrupt().catch(D=>{Ge()&&console.error(" "+m.error("soft-stop session.interrupt() failed:"),D)});let F=r.subagentControl;F?.hasActiveForeground()&&F.cancelActiveForeground().catch(D=>{Ge()&&console.error(" "+m.error("soft-stop cancelActiveForeground() failed:"),D)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{S=!0,t.interrupt().catch(F=>{Ge()&&console.error(" "+m.error("pause-interrupt session.interrupt() failed:"),F)})}),await z(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(_);let{fileBlocks:$,warnings:G}=q9(e.text,{rootDir:process.cwd()});for(let F of G)(i??{fn:console.log}).fn(m.dim(` @-file: ${F}`));if(e.attachments.length>0&&(await t.waitForInitialization(),t.sessionId===void 0))throw new Error("CLI session initialized without a session id");let H=$.length>0||e.attachments.length>0?await G9(e.text,e.attachments,void 0,$,t.sessionId):e.text,I=t.sendMessageStream(H);if(await Jl((F,D)=>{P.process(F,D)},async()=>{for await(let F of I){if(b||S)break;if(F.type==="chunk"&&F.chunk.type==="content"?(l=u?W9(l,F.chunk.content):l+F.chunk.content,u=!1,d=!0):F.type==="message"&&!d&&(l=F.message.content),F.type==="stream_retry"&&(l=l.slice(0,c),u=l.length>0),F.type==="chunk"&&F.chunk.type==="tool_use_detail"){let D=F.chunk,W={toolName:D.toolName,toolUseId:D.toolUseId,input:D.toolInput,...D.toolInputRaw!==void 0&&{inputRaw:D.toolInputRaw}};A.set(D.toolUseId,W),T.push(W)}else if(F.type==="chunk"&&F.chunk.type==="tool_result"){let D=F.chunk;c=l.length,u=!0;let W=A.get(D.toolUseId);if(W&&(W.result=D.content,W.isError=D.isError,A.delete(D.toolUseId)),r.onContextProgress){let ne=Date.now();if(ne-k>=E){k=ne;try{let ee=r.onContextProgress();ee instanceof Promise&&await ee}catch(ee){Ge()&&console.error(" "+m.error("onContextProgress (status refresh) failed:"),ee)}}}}if(F.type==="paused"){if(r.setPausedState?.(!0),await O(),R&&F.autoResume===!0){let D=new AbortController;w.abort=D;let W=F.resetsAt?F.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,ne=W?`Keep waiting \u2014 auto-resumes at ${W}`:"Keep waiting \u2014 auto-resume in progress",ee="Switch model / provider (type /model after)",X="Stop waiting",ae=[m.warning(" \u23F3 Usage limit reached.")+(W?m.dim(` Auto-resumes at ${W}.`):""),m.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];Kn(R,{header:ae,options:[ne,ee,X],signal:D.signal,initialIndex:0}).then(V=>{if(w.abort=null,!V)return;let Pe=V[0];Pe===void 0||Pe===ne||(S=!0,Pe===ee&&(i??{fn:console.log}).fn(m.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(Re=>{Ge()&&console.error(" "+m.error("picker pause-interrupt session.interrupt() failed:"),Re)}))}).catch(V=>{Ge()&&console.error(" "+m.error("picker promise rejected:"),V)})}else(i??{fn:console.log}).fn(zD({reason:F.reason,...F.resetsAt!==void 0?{resetsAt:F.resetsAt}:{},...F.accountId!==void 0?{accountId:F.accountId}:{},...F.autoResume!==void 0?{autoResume:F.autoResume}:{}}));continue}if(F.type==="resumed"){r.setPausedState?.(!1),w.abort?.abort(),w.abort=null;let D=F.hotSwapped&&F.accountId?`\u25B6 Resumed on ${F.accountId}`:"\u25B6 Resumed";l="",c=0,u=!1,d=!1,T.length=0,A.clear(),g=!1,h=void 0,p=!1,P=C(),f=!1,await z(),(i??{fn:console.log}).fn(m.success(D));continue}if(F.type==="error"){await O(),ml(sl(F.error)),p=!0;continue}P.process(F),F.type==="done"&&(g=!0,h=F.metadata)}}),await O(),b){let F=i?i.fn:console.log,D=R?R.getPendingCount():0,W=D>0?` \xB7 ${D} queued`:"";F(m.warning(`\u23F8 Stopped${W} \u2014 work so far kept.`)+m.dim(" Send a message to continue.")),F("")}if(S){let F=i?i.fn:console.log;F(m.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),F("")}if(g&&!b&&!S){fa(n,a,l,h,T),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),su(process.stdout),MY(process.stdout,"afk: turn complete");let F=W=>{i?i.fn(W):console.log(W)},D=sT(l);if(D){F(K9(D)),F("");let W=T6(T);if(r.onTerminalState)try{r.onTerminalState(D,{doneHasCorroboratingEvidence:W})}catch{}if(n.permissionMode==="autonomous"){let ne=D.kind==="done"&&up().verifyDone===!0&&!W;x6(D,void 0,{unverified:ne})}}if(R0e(h,n,F),r.onAfterTurn){let W=r.onAfterTurn();W instanceof Promise&&await W.catch(()=>{})}}}catch($){await O(),p||ml(sl($))}finally{await O(),au(process.stdout,Lm(process.cwd(),!1)),i&&(i.fn=i.idleFn,i.suppressSubagentCompletion=!1),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setPausedState?.(!1),r.setPauseInterruptHandler?.(null),w.abort?.abort(),w.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}function x0e(e,t){let n=Math.round(e*100),r=fe(t);if(e>=1){let o=Math.round((e-1)*t);return{tier:"over",text:` context OVER ${Math.round(t/1e3)}k tok by ~${fe(o)} tok \u2014 model output may be silently truncated`}}return e>=.95?{tier:"near",text:` context ${n}% used of ${r} \u2014 near limit; output may soon truncate (consider /clear or a fresh session)`}:e>=.8?{tier:"caution",text:` context ${n}% used of ${r} \u2014 approaching limit`}:e>.5?{tier:"normal",text:` context ${n}% used of ${r}`}:{tier:"quiet",text:null}}function R0e(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(_e(e.durationMs)),e.totalCostUsd!==void 0&&r.push(kt(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),i=Number(e.usage?.output_tokens??0);o+i>0&&r.push(fe(o+i)+" tok"),r.length>0&&n(m.dim(" \u25E6 "+r.join(" \xB7 ")));let s=QP(t),a=it(t.model),l=x0e(s,a);if(l.text!==null){let u=l.tier==="over"||l.tier==="near"?m.error:l.tier==="caution"?m.warning:m.dim;n(u(l.text))}let c=H9(Qv(qy()),new Date,{autoResume:kN()});if(c.text!==null){let u=c.tier==="over"||c.tier==="near"?m.error:c.tier==="caution"?m.warning:m.dim;n(u(c.text))}n("")}Bi();var A0e=5e3,C0e=3,_0e="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function I0e(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(m.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function J9(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,mascotBar:u,verdictLedger:d,shellPassthrough:p,bgResultNotifier:f}=s,g=null,h=[];e.session.current.waitForInitialization().then(async _=>{Ge()&&(g=yk(_)),await pf(e.session.current),Ge()&&(h=zP())}).catch(()=>{});let b=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,S,w=!1,k=!1,E,T,A,M=0;for(f.onInjectable=()=>{M>=C0e||!o.isAwaitingInput()||!o.bufferIsEmpty()||(M++,su(process.stdout),b={text:_0e,attachments:[]},o.abortPendingRead())};;){if(g&&(e.replRenderer.writeLine(g),e.replRenderer.writeLine(""),g=null),h.length>0){for(let I of h)e.replRenderer.writeLine(I);e.replRenderer.writeLine(""),h=[]}let _=p.drainNotifications();for(let{job:I,result:L}of _){let F=L.errorReason===void 0?"\u2713":"\u2717",D=L.errorReason==="abort"?"killed":L.errorReason==="timeout"?"timed out":L.errorReason==="signal-killed"?"killed by signal":`exit ${L.exitCode??0}`,W=Math.max(0,Math.round(L.durationMs/100)/10);e.replRenderer.writeLine(m.dim(` ${F} [${I.id}] ${D} \xB7 ${W}s \xB7 `)+I.command)}let R=f.drainNotifications();for(let{job:I}of R){let L=I.status==="completed"?"\u2713":I.status==="failed"?"\u2717":"\u2298",F=I.endedAt!==void 0?Math.max(0,Math.round((I.endedAt-I.startedAt)/100)/10):0,D=se(I.label,60);e.replRenderer.writeLine(m.dim(` ${L} [${I.jobId}] subagent ${I.status} \xB7 ${F}s \xB7 `)+D)}let C=l.renderIfChanged(e.stats.sessionId);if(C.length>0){for(let I of C)e.replRenderer.writeLine(I);e.replRenderer.writeLine("")}let P,O;if(b===void 0){let I=await e.session.current.takePendingPlanExitSeed();I!==void 0&&(e.stats.permissionMode=I.mode,b={text:I.message,attachments:[]})}if(b!==void 0){let I=b;b=void 0;let L=Uu(e.stats.permissionMode),F=Sa({buffer:I.text,promptText:L,isTTY:!!process.stdout.isTTY,attachmentSummary:Su([...I.attachments])});e.replRenderer.writeLine(F),P=I.text.trim(),O=I.attachments}else{let I=S;S=void 0;let L=await o.readLine({promptFn:()=>Uu(e.stats.permissionMode),...I!==void 0?{initialBuffer:I}:{},primePromptSuggestion:!0,onSigint:r,onShiftTab:()=>{tT(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});P=L.text.trim(),O=L.attachments}if(!P&&O.length===0)continue;if(P.startsWith("!")){let I=/^(0|false|off|no)$/i.test(v.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!I&&(w||(w=!0,e.replRenderer.writeLine(m.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await p.dispatch(P))){e.statusLine.rearm();continue}}let z=!1;if(P.startsWith("/")){let I=await $Y(P,e.slashCtx,O);if(I.handled){if(I.result==="exit"){await e.resolveWorktreeDisposition?.(!0),e.rl.close();return}if((P==="/clear"||P.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(m.dim(` transcript: ${t.path()}`)),d.reset(),E=void 0),I.result!==null&&typeof I.result=="object"&&"kind"in I.result&&I.result.kind==="submit"){b={text:I.result.message,attachments:O??[]},e.statusLine.rearm();continue}if(I.result!==null&&typeof I.result=="object"&&"kind"in I.result&&I.result.kind==="prefill"){S=I.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}z=!0}a.push(P),await I0e(e,P);let $=P;if(z){let I=_I(P);if(I){let L=I.name.replace(/^\//,"").split(":").pop()??"";if(L&&HP(L)){let F={skillName:L,rawArgs:I.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},D=e.session.current.sessionId,W=Ia(D),ne=Date.now();U(`[afk trace] preflight.start commandName=${L}`);let ee=!1,X=await _a(F,{cwd:e.stats.cwd??process.cwd(),artifactDir:W},ae=>{Ge()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${L}) failed: `)+(ae instanceof Error?ae.message:String(ae)))});ee=X!==null,U(`[afk trace] preflight.end commandName=${L} durationMs=${Date.now()-ne} success=${ee}`),$=GP(X?.manifestBlock,P)}}}let G=p.drainInjections();G.length>0&&($=G+$);let H=f.drainInjections();if(H.length>0&&($=H+$),E!==void 0&&($=E+`
|
|
1873
1875
|
|
|
1874
1876
|
`+$,E=void 0),e.hookRegistry)try{let I={event:"UserPromptSubmit",prompt:$,sessionId:e.stats.sessionId},L=await e.hookRegistry.dispatch(I);L.injectContext&&($=L.injectContext+$)}catch(I){if(I instanceof Ae){e.replRenderer.writeLine(m.warning("\u2298 Turn blocked by hook")+(I.reason?m.dim(`: ${Oe(I.reason)}`):"")),e.statusLine.rearm();continue}if(I instanceof Rr){e.replRenderer.writeLine(m.warning("\u2298 Turn blocked by hook")+m.dim(`: handler timed out after ${I.timeoutMs}ms`)),e.statusLine.rearm();continue}throw I}if(T=void 0,A=void 0,await Y9({text:$,attachments:O},e.session.current,e.stats,{setInFlight(I){n.turnInFlight=I},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(I){await t.appendUser(I)},async onQueuedUserMessage(I){await t.appendQueuedUser(I)},async onTurnComplete(I,L){if(await t.appendTurn(I,L),e.stats.sessionId)try{Ni(e.stats)}catch(F){k||(k=!0,e.replRenderer.writeLine(m.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(F instanceof Error?F.message:String(F))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:(I,L)=>{d?.push(I),T=I.kind,A=L?.doneHasCorroboratingEvidence},setActiveCompositor:I=>{n.activeCompositor=I},setInterruptNotifier:I=>{n.notifyInterrupting=I},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:I=>o.setBackgroundHandler(I),setSoftStopHandler:i,setPausedState:I=>o.setPausedState(I),setPauseInterruptHandler:I=>o.setPauseInterruptHandler(I),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(mr(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:(I,L)=>{c.repaint(I),u?.onStage(I,L)}}:{}},e.stats.thinkingUi??e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(Uu(e.stats.permissionMode))),e.hookRegistry)try{let I=await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId,...T!==void 0?{terminalState:T}:{},...A!==void 0?{doneHasCorroboratingEvidence:A}:{}},void 0,A0e);I.injectContext&&I.injectContext.trim().length>0&&(E=I.injectContext)}catch(I){if(I instanceof xt)throw I;I instanceof Rr?(U("[stop hook] handler timed out"),e.completionWriter.fn(m.dim(" [stop hook] timed out"))):I instanceof Ae?e.completionWriter.fn(m.dim(` [stop hook] blocked: ${Oe(I.reason??"no reason given")}`)):U("[stop hook] unexpected error: "+String(I))}}}function P0e(e,t){if(e!==void 0){let n=e.toLowerCase();return!(n==="0"||n==="false"||n==="off"||n==="no")}return typeof t=="boolean"?t:!0}async function X9(e,t,n,r){let o=await y9(),i=new eT({rl:e.rl,history:o,statusLine:e.statusLine}),s=P0e(v.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await E9(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar,getMascotBar:()=>a?.mascotBar});a=U9(e,n),await J9(e,t,n,r,i,l,a,o),await e.resolveWorktreeDisposition?.(!0)}finally{n.tryAbortShellForeground=null,a?.shellPassthrough.drainOnExit(),a?.bgResultNotifier.dispose(),a?.loopStageBar.stop(),a?.mascotBar.stop(),a?.bgStatusBar.stop(),a?.verdictLedger.stop(),a?.contextPane.dispose();let l=c=>console.log(c);e.completionWriter.fn=l,e.completionWriter.idleFn=l,await i.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}np();Ul();import{execFile as M0e}from"node:child_process";import{dirname as O0e,isAbsolute as D0e,resolve as $0e}from"node:path";import{promisify as F0e}from"node:util";var Q9=F0e(M0e),L0e=3e3,N0e=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function B0e(){let t=(await Q9("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=D0e(t)?t:$0e(process.cwd(),t);return O0e(n)}async function Z9(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await B0e()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),L0e)});try{let o=Fn({execFile:Q9,repoRoot:t,dryRun:!1,scope:"interactive",bypassSoftLaunch:!0}),i=await Promise.race([o,r]);if(i==="timeout")return{ran:!1,removedCount:0,skippedReason:"timeout"};let s=i;return s.warnings.some(c=>c.toLowerCase().includes("contested"))?{ran:!1,removedCount:0,skippedReason:"lock-contested"}:{ran:!0,removedCount:s.candidates.filter(c=>N0e.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}Bg();np();import{promises as U0e}from"node:fs";import{dirname as j0e,join as nQ}from"node:path";import{randomBytes as H0e}from"node:crypto";var W0e=["Generate a 2-4 word kebab-case slug describing this work request.","Rules:","- ASCII lowercase letters and digits only, separated by single hyphens","- 2 to 4 hyphen-separated words","- Maximum 30 characters total","- No prefix, no quotes, no punctuation other than hyphens","- Output ONLY the slug \u2014 no explanation, no preamble","Examples: fix-cleanup-race, add-telegram-allowlist, refactor-prompt-loader, debug-flaky-test"].join(`
|
|
1875
|
-
`),eQ=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,k0=30,K0e=1024,G0e=8e3,q0e="haiku";async function z0e(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=X0e(n,K0e),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??G0e),s=t.signal?Q0e([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await bl({token:t.token,model:t.model??q0e,system:W0e,user:r,maxTokens:32,signal:s})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(i)}let l=V0e(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=j0e(t.worktreePath);return await Y0e(l,c)}function V0e(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(eQ.test(t)&&t.length<=k0)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(i=>i.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let i=1;i<r.length;i++){let s=`${o}-${r[i]}`;if(s.length>k0)break;o=s}return eQ.test(o)?o:null}async function Y0e(e,t){if(!await J0e(nQ(t,e)))return e;let n=H0e(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,k0-5)}-${n}`}async function J0e(e){try{return await U0e.access(e),!0}catch{return!1}}function X0e(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function Q0e(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function rQ(e){let t,n,r=nQ(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await z0e(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),i=t??"unknown",s=n;if(o!==null){let l=`${Lh(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return tQ(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){i="create-failed",s=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return tQ(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:i,...s!==void 0?{detail:s}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function tQ(e,t){e&&e.setCwd(t),Z0e(t)}function Z0e(e){try{process.chdir(e)}catch{}}ut();It();ol();Yr();K();import{spawn as iQ}from"child_process";import{existsSync as sQ,mkdirSync as oOe,readFileSync as aQ,unlinkSync as oQ,writeFileSync as lQ}from"fs";import{get as iOe}from"https";import{join as cQ}from"path";import{readFileSync as eOe}from"fs";import{dirname as tOe,join as nOe}from"path";import{fileURLToPath as rOe}from"url";function Qr(){try{return"5.
|
|
1877
|
+
`),eQ=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,k0=30,K0e=1024,G0e=8e3,q0e="haiku";async function z0e(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=X0e(n,K0e),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??G0e),s=t.signal?Q0e([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await bl({token:t.token,model:t.model??q0e,system:W0e,user:r,maxTokens:32,signal:s})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(i)}let l=V0e(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=j0e(t.worktreePath);return await Y0e(l,c)}function V0e(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(eQ.test(t)&&t.length<=k0)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(i=>i.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let i=1;i<r.length;i++){let s=`${o}-${r[i]}`;if(s.length>k0)break;o=s}return eQ.test(o)?o:null}async function Y0e(e,t){if(!await J0e(nQ(t,e)))return e;let n=H0e(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,k0-5)}-${n}`}async function J0e(e){try{return await U0e.access(e),!0}catch{return!1}}function X0e(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function Q0e(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function rQ(e){let t,n,r=nQ(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await z0e(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),i=t??"unknown",s=n;if(o!==null){let l=`${Lh(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return tQ(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){i="create-failed",s=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return tQ(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:i,...s!==void 0?{detail:s}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function tQ(e,t){e&&e.setCwd(t),Z0e(t)}function Z0e(e){try{process.chdir(e)}catch{}}ut();It();ol();Yr();K();import{spawn as iQ}from"child_process";import{existsSync as sQ,mkdirSync as oOe,readFileSync as aQ,unlinkSync as oQ,writeFileSync as lQ}from"fs";import{get as iOe}from"https";import{join as cQ}from"path";import{readFileSync as eOe}from"fs";import{dirname as tOe,join as nOe}from"path";import{fileURLToPath as rOe}from"url";function Qr(){try{return"5.121.0"}catch{}try{let e=tOe(rOe(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(eOe(nOe(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}j();B();var sOe=64*1024,aOe=10800*1e3,lOe=800,cOe=3600*1e3,uOe="update-check.json",dOe="pending-update.json";function T0(){return cQ(tl(),uOe)}function Cf(){return cQ(tl(),dOe)}function E0(){let e=tl();sQ(e)||oOe(e,{recursive:!0})}function uQ(e,t){let n=a=>a.split(/[-+]/,1)[0]??a,r=a=>a.includes("-"),o=n(e).split(".").map(Number),i=n(t).split(".").map(Number),s=Math.max(o.length,i.length);for(let a=0;a<s;a++){let l=o[a]??0,c=i[a]??0;if(c>l)return!0;if(c<l)return!1}return r(e)&&!r(t)}function dQ(){try{let e=aQ(T0(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function pQ(){try{E0();let e=`
|
|
1876
1878
|
const https = require('https');
|
|
1877
1879
|
const fs = require('fs');
|
|
1878
1880
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|