agent-afk 5.196.0 → 5.197.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/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Pme=Object.defineProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var Mn=(e,t)=>{for(var n in t)Pme(e,n,{get:t[n],enumerable:!0})};function ea(e){return dc.find(t=>t.name===e)}function _A(e){return dc.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function uc(e){return process.env[e]!==void 0}function Ty(e){let t=process.env[e];return t===void 0||t===""?void 0:t}var bB=b(()=>{"use strict";F()});function je(){let e=k.AFK_PLAIN_OUTPUT;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"}var dc,wB,k,F=b(()=>{"use strict";bB();dc=[{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:"AFK_WORKSPACE_DISABLED",description:"Disable the shared agent workspace (WorkspaceStore + workspace_publish/workspace_query tools + preamble injection). When set to 1, subagents do not get workspace tools and no workspace preamble is injected at fork time \u2014 each agent works in full isolation as before v5.133. Used as the control arm of the file-read deduplication A/B experiment. Default: workspace enabled (unset or 0).",type:"boolean",required:!1,default:"0",example:"1",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_XAI_GROK_CLIENT_VERSION",description:"Override the semver sent as x-grok-client-version to the xAI OAuth CLI chat proxy. Use only if the proxy raises its required Grok CLI version before agent-afk is updated; invalid values fall back to the official Grok Build version file or built-in compatible default.",type:"string",required:!1,example:"1.0.6",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:"APPDATA",description:"Windows %APPDATA% (Roaming). Used for VS Code/Cursor settings discovery and credential denylist paths.",type:"string",required:!1,category:"process"},{name:"LOCALAPPDATA",description:"Windows %LOCALAPPDATA%. Used for browser credential denylist paths (Chrome, Firefox, Edge, etc.).",type:"string",required:!1,category:"process"},{name:"USERPROFILE",description:"Windows %USERPROFILE%. Used for credential denylist paths (.ssh, .aws, .gnupg) on win32.",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_BASH_PREVIEW_HEAD_LINES",description:"Number of leading non-empty lines shown in the bash output head block of the TUI outcome preview. 0 (default) disables the head block entirely. Accepted range 0\u2013200; non-integer, negative, or out-of-range input falls back to the default. When head + tail >= total non-empty lines, all lines are shown without a hidden-line notice. Keep preview preferences separate from model-context caps (AFK_BASH_PREVIEW_TAIL_LINES).",type:"number",required:!1,default:"0",example:"3",category:"misc"},{name:"AFK_BASH_PREVIEW_TAIL_LINES",description:"Number of trailing non-empty lines shown in the bash output tail block of the TUI outcome preview. Default 7 (compact tail-first preview). Accepted range 0\u2013200; non-integer, negative, or out-of-range input falls back to the default. When head + tail >= total non-empty lines, all lines are shown without a hidden-line notice. Keep preview preferences separate from model-context caps (AFK_BASH_PREVIEW_HEAD_LINES).",type:"number",required:!1,default:"7",example:"10",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_TURN_SEPARATOR",description:"Render a dim horizontal rule between conversation turns in the REPL. 0 = off, unset/1 = on (default). TTY-only: piped/one-shot output (afk chat) never emits the rule.",type:"boolean",required:!1,example:"0",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:"AFK_PROSE_MEASURE",description:"Maximum line length (columns) for prose-only blocks (paragraphs, list items, blockquotes) in the interactive REPL. Code fences use the wider AFK_TEXT_MEASURE (default 100). When AFK_TEXT_MEASURE is explicitly set, it overrides this value for backward compatibility. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable. Unparseable or below-minimum values fall back to the default.",type:"string",required:!1,default:"80",example:"72",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"COLORTERM",description:"OS-level terminal color-depth hint. Accepted values: truecolor or 24bit (24-bit color), 256color (256-color). Set by the outer terminal emulator, not by AFK. Read by chalk's supports-color to set its initial color level; also read by configureColor() to recommend FORCE_COLOR=3 for tmux truecolor users on Node \u2264 24.",type:"string",required:!1,example:"truecolor",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_RETENTION_DISABLE",description:"Disable the witness-tree retention sweep entirely, so no session directory is ever evicted.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_MAX_AGE_DAYS",description:"Evict a witness session directory once its newest content is older than this many days. Default 30.",type:"number",required:!1,default:"30",category:"debug"},{name:"AFK_WITNESS_MAX_BYTES",description:"Aggregate byte cap for the witness tree; oldest session directories are evicted first once exceeded. Default 2147483648 (2 GiB).",type:"number",required:!1,default:"2147483648",category:"debug"},{name:"AFK_SESSION_RETENTION_DISABLE",description:"Disable the session sidecar retention sweep entirely, so no state/sessions/*.json file is ever evicted.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_MAX_AGE_DAYS",description:"Evict a session sidecar file once it is older than this many days (based on savedAt). Default 30.",type:"number",required:!1,default:"30",category:"debug"},{name:"AFK_SESSION_MAX_COUNT",description:"Count-based safety valve: evict oldest session sidecars first once the total exceeds this number. Default 1000.",type:"number",required:!1,default:"1000",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:"AFK_SUBAGENT_RESULT_CAP_BYTES",description:"Foreground subagent result size cap in bytes. When a subagent's final message exceeds this threshold, the full output is spilled to a sidecar file (state/sessions/<id>/subagent-handoffs/<subagentId>.txt) and the parent receives a head+tail slice with a read_file pointer. Prevents large subagent outputs from bloating parent context. Set to 0 to disable the cap entirely. Default 32768 (32KB). Note: sidecar files contain unredacted subagent output (same caveats as AFK_CAPTURE_SUBAGENT_OUTPUT). No automatic GC covers subagent-handoffs/ today; retention is tied to session-directory cleanup.",type:"number",required:!1,default:"32768",example:"16384",category:"model"},{name:"AFK_SUBAGENT_LOG",description:"Opt-in per-subagent conversation log. Writes OutputEvent JSONL to state/subagent-logs/<sessionLabel>/<subagentId>.jsonl for both foreground and background subagents. Powers /tasks:view replay. OFF by default (raw tool arguments are written without redaction \u2014 consistent with AFK_CAPTURE_SUBAGENT_PROMPTS / AFK_CAPTURE_SUBAGENT_OUTPUT). Set to 1 to enable.",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:"Browser provider backend: auto (default, prefer Agent Browser, fall back to Playwright), agent-browser (require Agent Browser), or playwright (headless only).",type:"string",required:!1,default:"auto",example:"agent-browser",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"},{name:"AFK_LEASE_TTL_MS",description:"Lease TTL in milliseconds for durable task execution (issue #1411). A leased task whose lease expires before it completes is recovered and re-enqueued (or dead-lettered if maxAttempts is exhausted). Default: 600000 (10 minutes).",type:"number",required:!1,example:"600000",category:"misc"}],wB={};for(let e of dc){let t=e.name;Object.defineProperty(wB,t,{get(){return process.env[t]},enumerable:!("secret"in e&&e.secret),configurable:!0})}k=wB});import{basename as Ime,dirname as Mme,join as ta}from"path";function pc(e){if(!Ome.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function On(){return ta(ue(),"witness")}function Gt(e){return pc(e),ta(On(),e)}function xy(e){return ta(Gt(e),"inbound-attachments")}function Ey(e){return ta(Gt(e),"prompts")}function Ry(e){return ta(Gt(e),"outputs")}function Ay(e){if(!(!e||e===""))return ta(Gt(e),"bash-captures")}function xi(e){return!e||e.startsWith("in-memory:")?null:Ime(Mme(e))}function Gp(){return ta(ue(),"receipts")}var Ome,SB=b(()=>{"use strict";B();Ome=/^[a-zA-Z0-9_-]+$/});var EB={};Mn(EB,{assertSafeBrowserProfile:()=>bc,assertSafeJobId:()=>Kr,ensureSessionsMigrated:()=>HA,ensureTodosMigrated:()=>WA,ensureTranscriptsMigrated:()=>KA,getAfkCacheDir:()=>ra,getAfkConfigDir:()=>qn,getAfkHome:()=>be,getAfkStateDir:()=>ue,getAgentFrameworkDir:()=>kt,getBashCapturesDir:()=>Ay,getBgJobDir:()=>Ei,getBgJobLog:()=>im,getBgJobMeta:()=>Oy,getBgJobsRoot:()=>yc,getBriefsDir:()=>$A,getBrowserProfileStateDir:()=>Fy,getBrowserStateRoot:()=>Ly,getBrowserStorageStatePath:()=>wc,getBundledPluginsDir:()=>na,getDaemonStateDir:()=>Zp,getEffectLedgerPath:()=>GA,getEnvConfigPath:()=>qt,getFacetCacheDir:()=>qp,getFarmDir:()=>Py,getFarmsDir:()=>FA,getFirstRunMarkerPath:()=>My,getHandoffsDir:()=>oa,getInboundAttachmentsDir:()=>xy,getJsonConfigPath:()=>mn,getLegacyEnvConfigPath:()=>UA,getLegacyJsonConfigPath:()=>rm,getLogsDir:()=>Bo,getMarketplaceCacheDir:()=>Wr,getMarketplaceDir:()=>fc,getMemoryDir:()=>Xp,getOauthPendingPath:()=>vc,getPermissionsStorePath:()=>hc,getPluginsDir:()=>Qe,getPluginsIndexPath:()=>Te,getPresenceDir:()=>Yp,getProjectAfkDir:()=>DA,getProjectAfkMdPath:()=>nm,getProjectPlansDir:()=>Vp,getProjectPluginsDir:()=>Jp,getProjectSettingsPath:()=>BA,getProjectSkillsDir:()=>zp,getPromptsDir:()=>Ey,getQueueDir:()=>Ze,getReceiptsDir:()=>Gp,getReplHistoryPath:()=>om,getRoutingDecisionsPath:()=>OA,getSchedulesPath:()=>Cy,getSdkHomeDir:()=>Nme,getSdkSchemaViolationsPath:()=>Bme,getSessionGrantsPath:()=>Qp,getSessionKeyPath:()=>Ny,getSessionLedgerDir:()=>Sc,getSessionLedgerPath:()=>ia,getSessionsDir:()=>Le,getSettingsPath:()=>Iy,getSkillsDir:()=>mc,getStateDatabasePath:()=>$n,getSubagentLogPath:()=>Dy,getSubagentLogSessionDir:()=>sm,getSubagentLogsRoot:()=>$y,getSubagentOutputsDir:()=>Ry,getTelemetryPath:()=>br,getTodosDir:()=>_y,getTraceDir:()=>Gt,getTranscriptsDir:()=>gc,getUserAfkMdPath:()=>tm,getWaveManifestPath:()=>aa,getWavesDir:()=>sa,getWebUiAssetsDir:()=>LA,getWitnessRoot:()=>On,getWorktreeRootsRegistryPath:()=>em,getWorktreeSweepLockPath:()=>NA,isSafeLedgerSessionId:()=>Gr,sessionLabelFromTracePath:()=>xi,validateSessionId:()=>pc});import{existsSync as vB,mkdirSync as $me,renameSync as Dme,cpSync as Lme,rmSync as Fme}from"fs";import{join as ne,dirname as PA,isAbsolute as IA}from"path";import{homedir as MA}from"os";import{fileURLToPath as xB}from"url";function be(){let e=k.AFK_HOME;if(e!==void 0&&e!==""){if(!IA(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return ne(MA(),".afk")}function Nme(){return be()}function kt(){let e=k.AFK_FRAMEWORK_DIR;if(e!==void 0&&e!==""){if(!IA(e)||e==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${e}`);return e}return ne(be(),"agent-framework")}function br(){return ne(kt(),"forge-telemetry.jsonl")}function OA(){return ne(kt(),"routing-decisions.jsonl")}function Bme(){return ne(kt(),"sdk-schema-violations.jsonl")}function $A(){return ne(kt(),"briefs")}function qp(){return ne(kt(),"facets")}function mc(){return ne(be(),"skills")}function Qe(){return ne(be(),"plugins")}function DA(e=process.cwd()){return ne(e,".afk")}function zp(e=process.cwd()){return ne(DA(e),"skills")}function Jp(e=process.cwd()){return ne(DA(e),"plugins")}function Vp(e=process.cwd()){return ne(e,".afk","plans")}function Te(){return ne(Qe(),".index.json")}function Cy(){return ne(qn(),"schedules.json")}function Wr(){return ne(Qe(),"cache")}function fc(e){return ne(Wr(),e)}function na(){let e=xB(import.meta.url),t=PA(e);return ne(t,"bundled-plugins")}function LA(){let e=xB(import.meta.url),t=PA(e);return ne(t,"web-ui-assets")}function qn(){return ne(be(),"config")}function ue(){let e=k.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!IA(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return ne(be(),"state")}function ra(){return ne(be(),"cache")}function Bo(){return ne(be(),"logs")}function Le(){return ne(ue(),"sessions")}function Yp(){return ne(ue(),"presence")}function _y(){return ne(ue(),"todos")}function gc(){return ne(ue(),"transcripts")}function Xp(){return ne(ue(),"memory")}function $n(){return ne(ue(),"kv","kv.db")}function Ze(){return ne(ue(),"queue")}function oa(){return ne(ue(),"handoffs")}function Qp(){return ne(ue(),"session-grants.jsonl")}function hc(){return ne(qn(),"permissions.json")}function FA(){return ne(be(),"farms")}function Py(e){return ne(FA(),e)}function Zp(e="default"){return ne(ue(),"daemon",`agent-afk@${e}`)}function NA(){return ne(ue(),"worktree-sweep.lock")}function em(){return ne(ue(),"worktree-roots.json")}function qt(){return ne(qn(),"afk.env")}function mn(){return ne(qn(),"afk.config.json")}function Iy(){return ne(qn(),"settings.json")}function BA(e=process.cwd()){return ne(e,".afk","settings.json")}function tm(){return ne(be(),"AFK.md")}function nm(e=process.cwd()){return ne(e,"AFK.md")}function UA(){return ne(MA(),".afk.env")}function rm(){return ne(MA(),".afk.config.json")}function Ume(){return ne(be(),"sessions")}function jme(){return ne(be(),"todos")}function Hme(){return ne(be(),"transcripts")}function jA(e,t){if(e!==t&&vB(e)&&!vB(t))try{$me(PA(t),{recursive:!0});try{Dme(e,t)}catch(n){if(n.code==="EXDEV")try{Lme(e,t,{recursive:!0}),Fme(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
2
+ var Pme=Object.defineProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var Mn=(e,t)=>{for(var n in t)Pme(e,n,{get:t[n],enumerable:!0})};function ea(e){return dc.find(t=>t.name===e)}function _A(e){return dc.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function uc(e){return process.env[e]!==void 0}function Ty(e){let t=process.env[e];return t===void 0||t===""?void 0:t}var bB=b(()=>{"use strict";F()});function je(){let e=k.AFK_PLAIN_OUTPUT;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"}var dc,wB,k,F=b(()=>{"use strict";bB();dc=[{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:'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. On by default. Set to 0 to disable.',type:"boolean",required:!1,default:"1",example:"0",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. On by default. Set to 0/false/no/off to disable.",type:"boolean",required:!1,default:"1",example:"0",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. On by default. Set to 0/false/no/off to disable. Requires AFK_SUGGEST_ENABLED (it reuses the same suggestion model and provider).",type:"boolean",required:!1,default:"1",example:"0",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:"AFK_WORKSPACE_DISABLED",description:"Disable the shared agent workspace (WorkspaceStore + workspace_publish/workspace_query tools + preamble injection). When set to 1, subagents do not get workspace tools and no workspace preamble is injected at fork time \u2014 each agent works in full isolation as before v5.133. Used as the control arm of the file-read deduplication A/B experiment. Default: workspace enabled (unset or 0).",type:"boolean",required:!1,default:"0",example:"1",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_XAI_GROK_CLIENT_VERSION",description:"Override the semver sent as x-grok-client-version to the xAI OAuth CLI chat proxy. Use only if the proxy raises its required Grok CLI version before agent-afk is updated; invalid values fall back to the official Grok Build version file or built-in compatible default.",type:"string",required:!1,example:"1.0.6",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:"Use ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. On by default. Set to 0/false/no/off to disable. 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,default:"1",example:"0",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:"APPDATA",description:"Windows %APPDATA% (Roaming). Used for VS Code/Cursor settings discovery and credential denylist paths.",type:"string",required:!1,category:"process"},{name:"LOCALAPPDATA",description:"Windows %LOCALAPPDATA%. Used for browser credential denylist paths (Chrome, Firefox, Edge, etc.).",type:"string",required:!1,category:"process"},{name:"USERPROFILE",description:"Windows %USERPROFILE%. Used for credential denylist paths (.ssh, .aws, .gnupg) on win32.",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_BASH_PREVIEW_HEAD_LINES",description:"Number of leading non-empty lines shown in the bash output head block of the TUI outcome preview. 0 (default) disables the head block entirely. Accepted range 0\u2013200; non-integer, negative, or out-of-range input falls back to the default. When head + tail >= total non-empty lines, all lines are shown without a hidden-line notice. Keep preview preferences separate from model-context caps (AFK_BASH_PREVIEW_TAIL_LINES).",type:"number",required:!1,default:"0",example:"3",category:"misc"},{name:"AFK_BASH_PREVIEW_TAIL_LINES",description:"Number of trailing non-empty lines shown in the bash output tail block of the TUI outcome preview. Default 7 (compact tail-first preview). Accepted range 0\u2013200; non-integer, negative, or out-of-range input falls back to the default. When head + tail >= total non-empty lines, all lines are shown without a hidden-line notice. Keep preview preferences separate from model-context caps (AFK_BASH_PREVIEW_HEAD_LINES).",type:"number",required:!1,default:"7",example:"10",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_TURN_SEPARATOR",description:"Render a dim horizontal rule between conversation turns in the REPL. 0 = off, unset/1 = on (default). TTY-only: piped/one-shot output (afk chat) never emits the rule.",type:"boolean",required:!1,example:"0",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:"AFK_PROSE_MEASURE",description:"Maximum line length (columns) for prose-only blocks (paragraphs, list items, blockquotes) in the interactive REPL. Code fences use the wider AFK_TEXT_MEASURE (default 100). When AFK_TEXT_MEASURE is explicitly set, it overrides this value for backward compatibility. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable. Unparseable or below-minimum values fall back to the default.",type:"string",required:!1,default:"80",example:"72",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"COLORTERM",description:"OS-level terminal color-depth hint. Accepted values: truecolor or 24bit (24-bit color), 256color (256-color). Set by the outer terminal emulator, not by AFK. Read by chalk's supports-color to set its initial color level; also read by configureColor() to recommend FORCE_COLOR=3 for tmux truecolor users on Node \u2264 24.",type:"string",required:!1,example:"truecolor",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_RETENTION_DISABLE",description:"Disable the witness-tree retention sweep entirely, so no session directory is ever evicted.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_MAX_AGE_DAYS",description:"Evict a witness session directory once its newest content is older than this many days. Default 30.",type:"number",required:!1,default:"30",category:"debug"},{name:"AFK_WITNESS_MAX_BYTES",description:"Aggregate byte cap for the witness tree; oldest session directories are evicted first once exceeded. Default 2147483648 (2 GiB).",type:"number",required:!1,default:"2147483648",category:"debug"},{name:"AFK_SESSION_RETENTION_DISABLE",description:"Disable the session sidecar retention sweep entirely, so no state/sessions/*.json file is ever evicted.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_MAX_AGE_DAYS",description:"Evict a session sidecar file once it is older than this many days (based on savedAt). Default 30.",type:"number",required:!1,default:"30",category:"debug"},{name:"AFK_SESSION_MAX_COUNT",description:"Count-based safety valve: evict oldest session sidecars first once the total exceeds this number. Default 1000.",type:"number",required:!1,default:"1000",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:"Capture subagent conversational OUTPUT (assistant text plus each tool call with its arguments) as 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. On by default. Set to 0 to disable. Note: best-effort regex redaction only \u2014 connection strings, PEM blocks, and PII are not caught.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_SUBAGENT_RESULT_CAP_BYTES",description:"Foreground subagent result size cap in bytes. When a subagent's final message exceeds this threshold, the full output is spilled to a sidecar file (state/sessions/<id>/subagent-handoffs/<subagentId>.txt) and the parent receives a head+tail slice with a read_file pointer. Prevents large subagent outputs from bloating parent context. Set to 0 to disable the cap entirely. Default 32768 (32KB). Note: sidecar files contain unredacted subagent output (same caveats as AFK_CAPTURE_SUBAGENT_OUTPUT). No automatic GC covers subagent-handoffs/ today; retention is tied to session-directory cleanup.",type:"number",required:!1,default:"32768",example:"16384",category:"model"},{name:"AFK_SUBAGENT_LOG",description:"Opt-in per-subagent conversation log. Writes OutputEvent JSONL to state/subagent-logs/<sessionLabel>/<subagentId>.jsonl for both foreground and background subagents. Powers /tasks:view replay. OFF by default (raw tool arguments are written without redaction \u2014 consistent with AFK_CAPTURE_SUBAGENT_PROMPTS / AFK_CAPTURE_SUBAGENT_OUTPUT). Set to 1 to enable.",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:"Browser provider backend: auto (default, prefer Agent Browser, fall back to Playwright), agent-browser (require Agent Browser), or playwright (headless only).",type:"string",required:!1,default:"auto",example:"agent-browser",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"},{name:"AFK_LEASE_TTL_MS",description:"Lease TTL in milliseconds for durable task execution (issue #1411). A leased task whose lease expires before it completes is recovered and re-enqueued (or dead-lettered if maxAttempts is exhausted). Default: 600000 (10 minutes).",type:"number",required:!1,example:"600000",category:"misc"}],wB={};for(let e of dc){let t=e.name;Object.defineProperty(wB,t,{get(){return process.env[t]},enumerable:!("secret"in e&&e.secret),configurable:!0})}k=wB});import{basename as Ime,dirname as Mme,join as ta}from"path";function pc(e){if(!Ome.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function On(){return ta(ue(),"witness")}function Gt(e){return pc(e),ta(On(),e)}function xy(e){return ta(Gt(e),"inbound-attachments")}function Ey(e){return ta(Gt(e),"prompts")}function Ry(e){return ta(Gt(e),"outputs")}function Ay(e){if(!(!e||e===""))return ta(Gt(e),"bash-captures")}function xi(e){return!e||e.startsWith("in-memory:")?null:Ime(Mme(e))}function Gp(){return ta(ue(),"receipts")}var Ome,SB=b(()=>{"use strict";B();Ome=/^[a-zA-Z0-9_-]+$/});var EB={};Mn(EB,{assertSafeBrowserProfile:()=>bc,assertSafeJobId:()=>Kr,ensureSessionsMigrated:()=>HA,ensureTodosMigrated:()=>WA,ensureTranscriptsMigrated:()=>KA,getAfkCacheDir:()=>ra,getAfkConfigDir:()=>qn,getAfkHome:()=>be,getAfkStateDir:()=>ue,getAgentFrameworkDir:()=>kt,getBashCapturesDir:()=>Ay,getBgJobDir:()=>Ei,getBgJobLog:()=>im,getBgJobMeta:()=>Oy,getBgJobsRoot:()=>yc,getBriefsDir:()=>$A,getBrowserProfileStateDir:()=>Fy,getBrowserStateRoot:()=>Ly,getBrowserStorageStatePath:()=>wc,getBundledPluginsDir:()=>na,getDaemonStateDir:()=>Zp,getEffectLedgerPath:()=>GA,getEnvConfigPath:()=>qt,getFacetCacheDir:()=>qp,getFarmDir:()=>Py,getFarmsDir:()=>FA,getFirstRunMarkerPath:()=>My,getHandoffsDir:()=>oa,getInboundAttachmentsDir:()=>xy,getJsonConfigPath:()=>mn,getLegacyEnvConfigPath:()=>UA,getLegacyJsonConfigPath:()=>rm,getLogsDir:()=>Bo,getMarketplaceCacheDir:()=>Wr,getMarketplaceDir:()=>fc,getMemoryDir:()=>Xp,getOauthPendingPath:()=>vc,getPermissionsStorePath:()=>hc,getPluginsDir:()=>Qe,getPluginsIndexPath:()=>Te,getPresenceDir:()=>Yp,getProjectAfkDir:()=>DA,getProjectAfkMdPath:()=>nm,getProjectPlansDir:()=>Vp,getProjectPluginsDir:()=>Jp,getProjectSettingsPath:()=>BA,getProjectSkillsDir:()=>zp,getPromptsDir:()=>Ey,getQueueDir:()=>Ze,getReceiptsDir:()=>Gp,getReplHistoryPath:()=>om,getRoutingDecisionsPath:()=>OA,getSchedulesPath:()=>Cy,getSdkHomeDir:()=>Nme,getSdkSchemaViolationsPath:()=>Bme,getSessionGrantsPath:()=>Qp,getSessionKeyPath:()=>Ny,getSessionLedgerDir:()=>Sc,getSessionLedgerPath:()=>ia,getSessionsDir:()=>Le,getSettingsPath:()=>Iy,getSkillsDir:()=>mc,getStateDatabasePath:()=>$n,getSubagentLogPath:()=>Dy,getSubagentLogSessionDir:()=>sm,getSubagentLogsRoot:()=>$y,getSubagentOutputsDir:()=>Ry,getTelemetryPath:()=>br,getTodosDir:()=>_y,getTraceDir:()=>Gt,getTranscriptsDir:()=>gc,getUserAfkMdPath:()=>tm,getWaveManifestPath:()=>aa,getWavesDir:()=>sa,getWebUiAssetsDir:()=>LA,getWitnessRoot:()=>On,getWorktreeRootsRegistryPath:()=>em,getWorktreeSweepLockPath:()=>NA,isSafeLedgerSessionId:()=>Gr,sessionLabelFromTracePath:()=>xi,validateSessionId:()=>pc});import{existsSync as vB,mkdirSync as $me,renameSync as Dme,cpSync as Lme,rmSync as Fme}from"fs";import{join as ne,dirname as PA,isAbsolute as IA}from"path";import{homedir as MA}from"os";import{fileURLToPath as xB}from"url";function be(){let e=k.AFK_HOME;if(e!==void 0&&e!==""){if(!IA(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return ne(MA(),".afk")}function Nme(){return be()}function kt(){let e=k.AFK_FRAMEWORK_DIR;if(e!==void 0&&e!==""){if(!IA(e)||e==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${e}`);return e}return ne(be(),"agent-framework")}function br(){return ne(kt(),"forge-telemetry.jsonl")}function OA(){return ne(kt(),"routing-decisions.jsonl")}function Bme(){return ne(kt(),"sdk-schema-violations.jsonl")}function $A(){return ne(kt(),"briefs")}function qp(){return ne(kt(),"facets")}function mc(){return ne(be(),"skills")}function Qe(){return ne(be(),"plugins")}function DA(e=process.cwd()){return ne(e,".afk")}function zp(e=process.cwd()){return ne(DA(e),"skills")}function Jp(e=process.cwd()){return ne(DA(e),"plugins")}function Vp(e=process.cwd()){return ne(e,".afk","plans")}function Te(){return ne(Qe(),".index.json")}function Cy(){return ne(qn(),"schedules.json")}function Wr(){return ne(Qe(),"cache")}function fc(e){return ne(Wr(),e)}function na(){let e=xB(import.meta.url),t=PA(e);return ne(t,"bundled-plugins")}function LA(){let e=xB(import.meta.url),t=PA(e);return ne(t,"web-ui-assets")}function qn(){return ne(be(),"config")}function ue(){let e=k.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!IA(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return ne(be(),"state")}function ra(){return ne(be(),"cache")}function Bo(){return ne(be(),"logs")}function Le(){return ne(ue(),"sessions")}function Yp(){return ne(ue(),"presence")}function _y(){return ne(ue(),"todos")}function gc(){return ne(ue(),"transcripts")}function Xp(){return ne(ue(),"memory")}function $n(){return ne(ue(),"kv","kv.db")}function Ze(){return ne(ue(),"queue")}function oa(){return ne(ue(),"handoffs")}function Qp(){return ne(ue(),"session-grants.jsonl")}function hc(){return ne(qn(),"permissions.json")}function FA(){return ne(be(),"farms")}function Py(e){return ne(FA(),e)}function Zp(e="default"){return ne(ue(),"daemon",`agent-afk@${e}`)}function NA(){return ne(ue(),"worktree-sweep.lock")}function em(){return ne(ue(),"worktree-roots.json")}function qt(){return ne(qn(),"afk.env")}function mn(){return ne(qn(),"afk.config.json")}function Iy(){return ne(qn(),"settings.json")}function BA(e=process.cwd()){return ne(e,".afk","settings.json")}function tm(){return ne(be(),"AFK.md")}function nm(e=process.cwd()){return ne(e,"AFK.md")}function UA(){return ne(MA(),".afk.env")}function rm(){return ne(MA(),".afk.config.json")}function Ume(){return ne(be(),"sessions")}function jme(){return ne(be(),"todos")}function Hme(){return ne(be(),"transcripts")}function jA(e,t){if(e!==t&&vB(e)&&!vB(t))try{$me(PA(t),{recursive:!0});try{Dme(e,t)}catch(n){if(n.code==="EXDEV")try{Lme(e,t,{recursive:!0}),Fme(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
3
3
  `)}}}catch{}}function HA(){jA(Ume(),Le())}function WA(){jA(jme(),_y())}function KA(){jA(Hme(),gc())}function om(){return ne(ue(),"repl-history.jsonl")}function My(){return ne(ue(),".first-run-shown")}function Kr(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(e.length>kB)throw new Error(`Invalid jobId: exceeds ${kB} chars`);if(!Wme.test(e))throw new Error(`Invalid jobId: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function yc(){return ne(ue(),"bg")}function Ei(e){return Kr(e),ne(yc(),e)}function im(e){return ne(Ei(e),"events.jsonl")}function Oy(e){return ne(Ei(e),"meta.json")}function $y(){return ne(ue(),"subagent-logs")}function sm(e){return Kr(e),ne($y(),e)}function Dy(e,t){return Kr(t),ne(sm(e),`${t}.jsonl`)}function bc(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(e.length>TB)throw new Error(`Invalid browser profile: exceeds ${TB} chars`);if(!Kme.test(e))throw new Error(`Invalid browser profile: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function Ly(){return ne(ue(),"browser")}function Fy(e){return bc(e),ne(Ly(),e)}function wc(e){return ne(Fy(e),"storageState.json")}function Gr(e){return typeof e=="string"&&e.length>0&&e.length<=qme&&Gme.test(e)}function Sc(e){if(!Gr(e))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(e)}`);return ne(Le(),e)}function ia(e){return ne(Sc(e),"events.jsonl")}function Ny(e){return ne(Sc(e),"session.key")}function vc(){return ne(ue(),"mcp","server-status.json")}function sa(){return ne(ue(),"waves")}function aa(e){return ne(sa(),`${e}.json`)}function GA(){return ne(ue(),"effect-ledger.jsonl")}var Wme,kB,Kme,TB,Gme,qme,B=b(()=>{"use strict";F();SB();Wme=/^[A-Za-z0-9_-]+$/,kB=128;Kme=/^[A-Za-z0-9_-]+$/,TB=128;Gme=/^[A-Za-z0-9_-]+$/,qme=128});import{randomBytes as zme}from"node:crypto";import{mkdirSync as Jme,renameSync as Vme,rmSync as RB,writeFileSync as Yme}from"node:fs";import{dirname as Xme,isAbsolute as Qme,join as Zme}from"node:path";function By(){return Zme(ue(),"last-cwd")}function AB(){try{RB(By(),{force:!0})}catch{}}function CB(e){if(!Qme(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=By();Jme(Xme(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${zme(6).toString("hex")}`;try{Yme(n,e,{encoding:"utf8",mode:384}),Vme(n,t)}catch(r){try{RB(n,{force:!0})}catch{}throw r}}catch{}}function _B(){let e=k.AFK_SHELL_WRAPPER;return e==="1"||e==="true"}var Uy=b(()=>{"use strict";F();B()});import Q from"chalk";var IB,efe,tfe,MB,OB,$B,m,L=b(()=>{"use strict";IB={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("#B5888F"),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("#5B8FA8"),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},efe={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("#8A5D64"),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("#2D5B7A"),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")},tfe={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("#C4929A"),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("#78ACB8"),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")},MB=IB,OB=efe,$B=tfe,m={...IB}});function DB(){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 LB=b(()=>{"use strict";L()});import nfe from"chalk";import{createEmphasize as rfe,common as ofe}from"emphasize";function NB(){qr.clear()}function lfe(e){let t=qr.get(e);if(t!==void 0)return qr.delete(e),qr.set(e,t),t}function cfe(e,t){if(qr.has(e)&&qr.delete(e),qr.set(e,t),qr.size>afe){let n=qr.keys().next().value;n!==void 0&&qr.delete(n)}}function BB(e,t){if(nfe.level===0||e.length>ife)return e;let n=e.length<sfe,r=n?`${t} ${e}`:"";if(n){let i=lfe(r);if(i!==void 0)return i}let o;try{if(!t||!FB.registered(t))o=e;else{let i=FB.highlight(t,e,DB());o=typeof i?.value=="string"?i.value:e}}catch{o=e}return n&&cfe(r,o),o}var FB,ife,sfe,afe,qr,zA=b(()=>{"use strict";LB();FB=rfe(ofe),ife=2048,sfe=512,afe=32,qr=new Map});function HB(){return jB}function zr(e){Object.assign(m,UB[e]),NB(),jB=e}function Ri(e){if(e==null)return;let t=e.trim().toLowerCase();return t==="auto"||jy.includes(t)?t:void 0}function ufe(){let e=k.COLORFGBG;if(!e)return"dark";let t=e.split(";"),n=t[t.length-1]?.trim();if(!n)return"dark";let r=Number.parseInt(n,10);return Number.isInteger(r)&&(r===7||r>=9)?"light":"dark"}function Jr(e){return e==="auto"?ufe():e!==void 0?e:"dark"}function Hy(e){let t=Ri(e);if(t!==void 0)return t;throw new Error(`Invalid --theme value: ${e}. Expected ${[...jy,"auto"].join("|")}`)}function Wy(e,t){if(e!==void 0)return e;let n=Ri(k.AFK_THEME);return n!==void 0?n:t}var UB,jy,jB,kc=b(()=>{"use strict";L();zA();F();UB={dark:MB,light:OB,umber:$B},jy=Object.keys(UB),jB="dark"});var Dt,Tt,Ky,Re,zn,Vr,Tc,Gy,He=b(()=>{"use strict";Dt=class extends Error{constructor(t){super(t),this.name="AbortError"}},Tt=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Ky=class extends Tt{constructor(t,n){super(t,n),this.name="IdleWatchdogError"}},Re=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},zn=class extends Error{toolResultsGathered;constructor(t){super(t),this.name="StreamIncompleteError"}},Vr=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},Tc=class extends Error{constructor(t){super(t),this.name="DenialCircuitBreakerError"}},Gy=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 dfe from"string-width";function Me(e){return e.replace(JA,"")}function z(e){return dfe(e)}function la(e){return e.length===0?[]:GB?Array.from(GB.segment(e),t=>t.segment):Array.from(e)}function pfe(e){let t=[],n=0,r;for(JA.lastIndex=0;(r=JA.exec(e))!==null;){if(r.index>n)for(let o of la(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 la(e.slice(n)))t.push({type:"text",value:o});return t}function it(e,t){let n=z(e);return n>t?ee(e,t,""):e+" ".repeat(t-n)}function mfe(e,t){let n=Math.max(0,t-z(e));return" ".repeat(n)+e}function qy(e,t,n="left"){let r=Math.max(0,t-z(e));if(r===0)return e;if(n==="right")return mfe(e,t);if(n==="center"){let o=Math.floor(r/2);return" ".repeat(o)+e+" ".repeat(r-o)}return it(e,t)}function ee(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 pfe(e)){if(c.type==="ansi"){s+=c.value,a=!0;let d=ffe.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?gfe:"")+(a?"\x1B[0m":"")}function qB(e,t,n="\u2026"){if(t<=0)return"";if(z(e)<=t)return e;let r=z(n);if(r>t)return"";let o=Math.max(0,t-r),i=la(e),s=0,a=i.length;for(let l=i.length-1;l>=0;l--){let c=z(i[l]);if(s+c>o)break;s+=c,a=l}return n+i.slice(a).join("")}function zB(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.trunc(e))):0}function am(e,t){let n=zB(t,e.length);if(n===0||e.length===0)return 0;let r=0;for(let o of la(e)){let i=r+o.length;if(i>=n)return r;r=i}return r}function ca(e,t){let n=zB(t,e.length);if(n>=e.length||e.length===0)return e.length;let r=0;for(let o of la(e)){let i=r+o.length;if(r>=n||n>r&&n<i)return i;r=i}return e.length}var JA,GB,ffe,gfe,de=b(()=>{"use strict";JA=/\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P^_X][^\x1B]*\x1B\\|[@-OQ-WYZ\\\-])/g,GB=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;ffe=/^\x1b\]8;[^;\x07\x1b]*;(.*?)(?:\x07|\x1b\\)$/s,gfe="\x1B]8;;\x1B\\"});function re(){let e=process.stdout.columns;return typeof e=="number"&&e>0?e:80}function hfe(){for(let e of zy)try{e()}catch{}}function yfe(){for(let e of Jy)try{e()}catch{}}function bfe(){ua!==null&&clearTimeout(ua),ua=setTimeout(()=>{ua=null,hfe()},150)}function VA(){yfe(),bfe()}function wfe(e){return zy.add(e),Ec||(process.stdout.on("resize",VA),Ec=!0),()=>{zy.delete(e),JB()}}function Sfe(e){return Jy.add(e),Ec||(process.stdout.on("resize",VA),Ec=!0),()=>{Jy.delete(e),JB()}}function JB(){zy.size===0&&Jy.size===0&&(Ec&&(process.stdout.off("resize",VA),Ec=!1),ua!==null&&(clearTimeout(ua),ua=null))}var zy,Jy,Ec,ua,qe,we=b(()=>{"use strict";zy=new Set,Jy=new Set,Ec=!1,ua=null;qe={subscribe:wfe,subscribeImmediate:Sfe}});import VB 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(`
@@ -60,7 +60,7 @@ var Pme=Object.defineProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var Mn=(e,t)=>{
60
60
  `;process.stderr.write(c)}}var gge,hge,yge,Uo=b(()=>{"use strict";F();Sr();gge=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
61
61
  `,hge=/key|token|secret|password|credential|auth/i;yge=[[/sk-ant-[A-Za-z0-9_\-]{8,200}/g,e=>`<REDACTED sk-ant length=${e[0].length}>`],[/sk-(?!ant-)[A-Za-z0-9_\-]{20,200}/g,e=>`<REDACTED sk- length=${e[0].length}>`],[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,e=>`<REDACTED Bearer length=${e[0].length}>`],[/AKIA[A-Z0-9]{16}/g,e=>`<REDACTED AKIA length=${e[0].length}>`],[/xox[baprs]-[A-Za-z0-9\-]{10,200}/g,e=>`<REDACTED xox token length=${e[0].length}>`],[/\d{8,12}:[A-Za-z0-9_\-]{35}/g,e=>`<REDACTED Telegram token length=${e[0].length}>`],[/([A-Za-z_]{3,}(?:[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]|[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll])[A-Za-z_]*)=([^\s]{16,})/g,WU],[/([A-Z_]{3,}(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=([^\s]{16,})/g,WU]]});import{randomBytes as Sge}from"node:crypto";import{mkdir as vge,writeFile as kge}from"node:fs/promises";import{join as Tge}from"node:path";function Ege(e){return k.AFK_CAPTURE_SUBAGENT_PROMPTS!=="1"||!e.isSubagentFork||!e.sessionId||!e.subagentId?!1:e.prompt.length>0}function gC(e,t){let n=Buffer.byteLength(e,"utf8");return n<=t?{text:e,originalBytes:n,truncated:!1}:{text:Buffer.from(e,"utf8").subarray(0,t).toString("utf8").replace(/\uFFFD+$/,""),originalBytes:n,truncated:!0}}function Rge(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,60)}function nb(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Age(e,t){let n=["---",`subagentId: ${nb(e.subagentId??"unknown")}`,`sessionLabel: ${nb(e.sessionId??"unknown")}`,`turn: ${e.turn}`,`capturedAt: ${nb(new Date().toISOString())}`,`promptBytes: ${t.originalBytes}`,`bodyBytes: ${Buffer.byteLength(t.text,"utf8")}`,`truncated: ${t.truncated}`,"redaction: best-effort"];return e.model!==void 0&&n.push(`model: ${nb(e.model)}`),n.push("---",xge,""),n.push(t.text),t.truncated&&n.push("",`<!-- TRUNCATED at ${GU} bytes of ${t.originalBytes} -->`),`${n.join(`
62
62
  `)}
63
- `}async function qU(e){try{if(!Ege(e))return;let t=gC(e.prompt,GU),n=t.truncated?t.text.replace(/\S+$/,""):t.text,r=Ke(n),o=Age(e,{...t,text:r}),i=Ey(e.sessionId);await vge(i,{recursive:!0,mode:448});let s=new Date().toISOString().replace(/[:.]/g,"-"),a=Sge(3).toString("hex"),l=Tge(i,`${s}-${Rge(e.subagentId)}-t${e.turn}-${a}.md`);await kge(l,o,{encoding:"utf8",mode:384,flag:"wx"})}catch(t){xt("subagent-prompt-capture",e.sessionId??"unknown","captureSubagentPrompt",t)}}var GU,xge,hC=b(()=>{"use strict";F();B();tb();Uo();GU=8*1024,xge="<!-- Best-effort secret redaction only. Connection strings, PEM blocks, and PII are NOT caught. -->"});import{appendFile as Cge,mkdir as _ge}from"node:fs/promises";import{join as Pge}from"node:path";function Mge(e){return!(k.AFK_CAPTURE_SUBAGENT_OUTPUT!=="1"||!e.isSubagentFork||!e.sessionId||!e.subagentId)}function Oge(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,60)}function rb(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function VU(e){let t=gC(e,zU),n=t.truncated?t.text.replace(/\S+$/,""):t.text,r=Ke(n);return t.truncated?`${r}
63
+ `}async function qU(e){try{if(!Ege(e))return;let t=gC(e.prompt,GU),n=t.truncated?t.text.replace(/\S+$/,""):t.text,r=Ke(n),o=Age(e,{...t,text:r}),i=Ey(e.sessionId);await vge(i,{recursive:!0,mode:448});let s=new Date().toISOString().replace(/[:.]/g,"-"),a=Sge(3).toString("hex"),l=Tge(i,`${s}-${Rge(e.subagentId)}-t${e.turn}-${a}.md`);await kge(l,o,{encoding:"utf8",mode:384,flag:"wx"})}catch(t){xt("subagent-prompt-capture",e.sessionId??"unknown","captureSubagentPrompt",t)}}var GU,xge,hC=b(()=>{"use strict";F();B();tb();Uo();GU=8*1024,xge="<!-- Best-effort secret redaction only. Connection strings, PEM blocks, and PII are NOT caught. -->"});import{appendFile as Cge,mkdir as _ge}from"node:fs/promises";import{join as Pge}from"node:path";function Mge(e){return!(k.AFK_CAPTURE_SUBAGENT_OUTPUT==="0"||!e.isSubagentFork||!e.sessionId||!e.subagentId)}function Oge(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,60)}function rb(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function VU(e){let t=gC(e,zU),n=t.truncated?t.text.replace(/\S+$/,""):t.text,r=Ke(n);return t.truncated?`${r}
64
64
  <!-- TRUNCATED at ${zU} bytes of ${t.originalBytes} -->`:r}function $ge(e){let t=["---",`subagentId: ${rb(e.subagentId??"unknown")}`,`sessionLabel: ${rb(e.sessionId??"unknown")}`,`startedAt: ${rb(new Date().toISOString())}`,"redaction: best-effort","capture: incremental (flushed at each tool-call boundary)"];return e.model!==void 0&&t.push(`model: ${rb(e.model)}`),t.push("---",Ige,""),`${t.join(`
65
65
  `)}
66
66
  `}function ob(e,t){let n=new Date().toISOString();if(e==="say")return`
@@ -296,7 +296,7 @@ ${KC}
296
296
  INSERT INTO facts (session_id, created_at, category, content, source_surface, evidence)
297
297
  VALUES (?, ?, ?, ?, ?, ?)
298
298
  `).run(s.session_id??null,s.created_at,s.category,s.content,s.source_surface??"cli",s.evidence??null),n++)}else if(i.type==="supersede"){let s=i.data,a,l;if(typeof s.old_content=="string"&&typeof s.old_created_at=="string"){let c;(typeof s.old_session_id<"u"||typeof s.old_category=="string")&&(c=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ? AND COALESCE(session_id,'') = ? AND category = ?").get(s.old_content,s.old_created_at,s.old_session_id??"",s.old_category??"")),c||(c=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ?").get(s.old_content,s.old_created_at)),a=c?.id}else typeof s.old_fact_id=="number"&&(a=s.old_fact_id);if(typeof s.new_content=="string"&&typeof s.new_created_at=="string"){let c;(typeof s.new_session_id<"u"||typeof s.new_category=="string")&&(c=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ? AND COALESCE(session_id,'') = ? AND category = ?").get(s.new_content,s.new_created_at,s.new_session_id??"",s.new_category??"")),c||(c=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ?").get(s.new_content,s.new_created_at)),l=c?.id}else typeof s.new_fact_id=="number"&&(l=s.new_fact_id);typeof a=="number"&&typeof l=="number"&&(this.db.prepare("UPDATE facts SET superseded_by = ? WHERE id = ? AND superseded_by IS NULL").run(l,a),n++)}}catch(s){N("WAL replay: skipping malformed line:",String(s))}}h1(t)}catch(r){N("WAL file unreadable, skipping recovery:",String(r))}return n}close(){this.db.close()}appendWAL(t){let n=Xn(this.dir,w1);try{Qye(n,JSON.stringify(t)+`
299
- `,"utf-8")}catch(r){N("WAL append failed (non-fatal):",String(r))}}};cbe=/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;ube=new Set(["fact","session_start","session_end","supersede"]),dbe=new Set(["preference","convention","decision","learning"])});function E1(e){return mbe.has(e)}function Fb(){return k.AFK_MEMORY_EVIDENCE_GATE==="1"}function GC(e){return E1(e)}function Nb(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function R1(e,t){return E1(e)?Nb(t)?"verified":"unverified":"not-applicable"}function A1(e,t){return t!=="unverified"||e.startsWith(x1)?e:`${x1} ${e}`}var mbe,x1,C1=b(()=>{"use strict";F();mbe=new Set(["convention"]),x1="[unverified]"});function gbe(e,t){return t?e.map(n=>{if(n.type!=="fact"||!n.category)return{...n,verification:"not-applicable"};let r=R1(n.category,n.evidence);return{...n,verification:r,content:A1(n.content,r)}}):e.map(n=>{let r={...n};return delete r.evidence,delete r.verification,r})}function Im(e,t,n){let r=async s=>{try{let a=hbe(s),l=e.search(a.query,{category:a.category,since:a.since,limit:a.limit??10});return{content:JSON.stringify(gbe(l,Fb()))}}catch(a){return{content:`memory_search error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},o=async s=>{try{let a=ybe(s);if(a.target==="hot"){if(a.action!=="set")return{content:'Hot memory only supports action: "set". Use supersede/remove only for facts.',isError:!0};if(!a.content)return{content:'content is required for action: "set"',isError:!0};let l=e.saveHot(a.content),c={saved:!0,target:"hot",usage:{tokens:l.tokens,maxTokens:l.maxTokens,pct:l.pct}};return l.truncated?(c.truncated=!0,c.note='Hot memory exceeded the ~1,500-token cap and was truncated from the end (lowest-priority lines dropped; a sentinel marks the cut). Keep hot memory to a few durable essentials \u2014 move detail to the fact archive with target:"fact".'):l.pct>=T1*100&&(c.warning=`Hot memory is at ${l.pct}% of the ~1,500-token cap. Move non-essential lines to the fact archive (target:"fact") before it truncates.`),{content:JSON.stringify(c)}}if(a.action==="set"){if(!a.category)return{content:"category is required for fact storage",isError:!0};if(!a.content)return{content:'content is required for action: "set"',isError:!0};let l=a.category,c=Nb(a.evidence),d={id:e.storeFact({session_id:t,category:l,content:a.content,source_surface:n??"cli",evidence:c}),action:"set",target:"fact"};return Fb()&&GC(l)&&!c&&(d.warning=_1),{content:JSON.stringify(d)}}if(a.action==="supersede"){if(!a.supersedes)return{content:'supersedes (fact ID) is required for action: "supersede"',isError:!0};if(!a.content)return{content:'content is required for action: "supersede"',isError:!0};let l=e.getFact(a.supersedes),c=a.evidence===void 0?void 0:Nb(a.evidence),d={id:e.supersedeFact(a.supersedes,a.content,a.category??void 0,c),action:"supersede",target:"fact",supersedes:a.supersedes};if(Fb()){let p=a.category??l?.category;p&&GC(p)&&((c===void 0?l?.evidence??null:c)?c===void 0&&(d.warning=fbe):d.warning=_1)}return{content:JSON.stringify(d)}}if(a.action==="remove"){if(!a.id)return{content:'id (fact ID) is required for action: "remove"',isError:!0};let l=e.removeFact(a.id);return{content:JSON.stringify({removed:l,action:"remove",target:"fact"})}}return{content:`Unknown action: ${a.action}`,isError:!0}}catch(a){return{content:`memory_update error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},i=async s=>{try{let a=bbe(s);return e.writeProcedure(a.name,a.content,t),{content:JSON.stringify({name:a.name,written:!0})}}catch(a){return{content:`procedure_write error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}};return new Map([["memory_search",r],["memory_update",o],["procedure_write",i]])}function hbe(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e;if(typeof t.query!="string")throw new Error("query (string) is required");let n={query:t.query};if(t.category!==void 0){if(typeof t.category!="string")throw new Error("category must be a string");let r=["preference","convention","decision","learning"];if(!r.includes(t.category))throw new Error(`category must be one of: ${r.join(", ")}`);n.category=t.category}if(t.since!==void 0){if(typeof t.since!="string")throw new Error("since must be a string (ISO date)");n.since=t.since}if(t.limit!==void 0){if(typeof t.limit!="number"||t.limit<=0)throw new Error("limit must be a positive number");n.limit=t.limit}return n}function ybe(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e,n=["hot","fact"];if(typeof t.target!="string"||!n.includes(t.target))throw new Error(`target must be one of: ${n.join(", ")}`);let r=["set","supersede","remove"];if(typeof t.action!="string"||!r.includes(t.action))throw new Error(`action must be one of: ${r.join(", ")}`);let o={target:t.target,action:t.action};if(t.content!==void 0){if(typeof t.content!="string")throw new Error("content must be a string");o.content=t.content}if(t.category!==void 0){if(typeof t.category!="string")throw new Error("category must be a string");let i=["preference","convention","decision","learning"];if(!i.includes(t.category))throw new Error(`category must be one of: ${i.join(", ")}`);o.category=t.category}if(t.evidence!==void 0){if(typeof t.evidence!="string")throw new Error("evidence must be a string");o.evidence=t.evidence}if(t.supersedes!==void 0){if(typeof t.supersedes!="number"||t.supersedes<=0)throw new Error("supersedes must be a positive fact ID");o.supersedes=t.supersedes}if(t.id!==void 0){if(typeof t.id!="number"||t.id<=0)throw new Error("id must be a positive fact ID");o.id=t.id}return o}function bbe(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e;if(typeof t.name!="string")throw new Error("name (string) is required");if(typeof t.content!="string")throw new Error("content (string) is required");return{name:t.name,content:t.content}}var Wc,P1,I1,Bi,Aa,_1,fbe,qC=b(()=>{"use strict";Lb();C1();Wc={name:"memory_search",category:"read",concurrencySafe:!0,description:'Search cross-session memory for facts and procedures. Returns results ranked by relevance. Use this to recall information from prior sessions. Supports FTS5 match syntax: AND, OR, NOT, "exact phrase", prefix*',input_schema:{type:"object",properties:{query:{type:"string",description:'Search query (supports FTS5 match syntax: AND, OR, NOT, "exact phrase", prefix*)'},category:{type:"string",enum:["preference","convention","decision","learning"],description:"Optional: filter by fact category"},since:{type:"string",description:"Optional: ISO date \u2014 only return facts created after this date"},limit:{type:"number",description:"Max results (default 10)"}},required:["query"]}},P1={name:"memory_update",category:"write",concurrencySafe:!1,description:'Store a fact in cross-session memory or update hot memory. Hot memory (target: "hot") persists in the system prompt across all future sessions. Facts (target: "fact") are stored in the searchable archive.',input_schema:{type:"object",properties:{target:{type:"string",enum:["hot","fact"],description:'"hot" writes to HOT.md (system prompt), "fact" writes to the searchable archive'},action:{type:"string",enum:["set","supersede","remove"],description:"Operation: set (create/overwrite), supersede (replace while keeping history), remove (delete)"},content:{type:"string",description:"The content to store (for set/supersede)"},category:{type:"string",enum:["preference","convention","decision","learning"],description:"Required for fact target"},evidence:{type:"string",description:'Optional provenance citation backing a codebase fact \u2014 a file:line, commit SHA, or trace-event id. When the evidence gate is enabled, a "convention" fact stored without it is recalled as [unverified]; preferences and reflections never need it.'},supersedes:{type:"number",description:"Fact ID being superseded (for supersede action)"},id:{type:"number",description:"Fact ID to remove (for remove action)"}},required:["target","action"]}},I1={name:"procedure_write",category:"write",concurrencySafe:!1,description:"Write a reusable procedure to memory. Procedures are markdown files describing how to perform recurring tasks. They persist across sessions and are searchable via memory_search.",input_schema:{type:"object",properties:{name:{type:"string",description:"Procedure name (kebab-case, becomes the filename)"},content:{type:"string",description:"Procedure content (markdown)"}},required:["name","content"]}},Bi=[Wc,P1,I1],Aa=Bi.map(e=>e.name),_1='Stored without evidence \u2014 this codebase fact (category "convention") will be recalled as [unverified]. Supply `evidence` (a file:line, commit SHA, or trace-event id) so future sessions can trust it as ground truth rather than an unverified agent claim.',fbe='Superseded without fresh evidence \u2014 the prior citation is carried forward and this codebase fact (category "convention") is still recalled as verified against the OLD evidence, which may not back the changed content. Re-supply `evidence` if the claim changed (or pass an empty string to clear it and recall as [unverified]).'});var M1,wbe,Sbe,vbe,O1,Kc,Bb,Ub=b(()=>{"use strict";M1={name:"state_get",category:"read",concurrencySafe:!0,description:"Retrieve a document from the durable cross-session state store. Returns null if the document does not exist or has expired. Documents are namespaced (namespace + key) JSON values with a version counter.",input_schema:{type:"object",properties:{namespace:{type:"string",description:'Document namespace. Pattern: [A-Za-z0-9_.-]+, max 128 chars. Use a consistent namespace per concern (e.g. "todos", "project-state").'},key:{type:"string",description:"Document key. Same pattern/limit as namespace."}},required:["namespace","key"]}},wbe={name:"state_put",category:"write",concurrencySafe:!1,description:"Write or update a document in the durable cross-session state store. Creates on first insert (version starts at 1) and increments version on updates. Use state_cas instead when concurrent writes are a concern.",input_schema:{type:"object",properties:{namespace:{type:"string",description:"Document namespace. Pattern: [A-Za-z0-9_.-]+, max 128 chars."},key:{type:"string",description:"Document key. Same pattern/limit as namespace."},value:{description:"JSON-serializable value to store. Any JSON type is accepted (object, array, string, number, boolean, null)."},ttl_ms:{type:"number",description:"Optional time-to-live in milliseconds. Document is automatically deleted after this many ms from the write time."},metadata:{description:"Optional metadata object (JSON-serializable). Not returned by state_get \u2014 for audit/tagging only."}},required:["namespace","key","value"]}},Sbe={name:"state_cas",category:"write",concurrencySafe:!1,description:"Compare-and-swap write to the durable cross-session state store. Updates the document only when its current version matches expected_version. Returns {matched: false} if the version does not match or the document does not exist. Use this for safe concurrent updates by multiple sessions.",input_schema:{type:"object",properties:{namespace:{type:"string",description:"Document namespace. Pattern: [A-Za-z0-9_.-]+, max 128 chars."},key:{type:"string",description:"Document key. Same pattern/limit as namespace."},expected_version:{type:"number",description:"Version the document must currently have for the update to succeed."},value:{description:"New JSON-serializable value to store if the CAS matches."},ttl_ms:{type:"number",description:"Optional TTL in milliseconds from the write time."},metadata:{description:"Optional metadata object (JSON-serializable)."}},required:["namespace","key","expected_version","value"]}},vbe={name:"state_delete",category:"write",concurrencySafe:!1,description:"Delete a document from the durable cross-session state store. Returns {deleted: true} if the document existed and was removed, {deleted: false} if it did not exist.",input_schema:{type:"object",properties:{namespace:{type:"string",description:"Document namespace. Pattern: [A-Za-z0-9_.-]+, max 128 chars."},key:{type:"string",description:"Document key. Same pattern/limit as namespace."}},required:["namespace","key"]}},O1={name:"state_query",category:"read",concurrencySafe:!0,description:"List documents in a namespace from the durable cross-session state store. Returns documents sorted by key. Supports key prefix filtering and pagination. Expired documents are excluded. Default limit is 20, maximum is 100.",input_schema:{type:"object",properties:{namespace:{type:"string",description:"Document namespace. Pattern: [A-Za-z0-9_.-]+, max 128 chars."},key_prefix:{type:"string",description:"Optional key prefix filter. Only documents whose key starts with this string are returned."},limit:{type:"number",description:"Maximum number of results to return (default 20, max 100)."}},required:["namespace"]}},Kc=[M1,wbe,Sbe,vbe,O1],Bb=[M1,O1]});function zC(e,t="all"){switch(t){case"self":return{self:e.getSelf()};case"tools":return{tools:e.getTools()};case"subagents":return{subagents:e.getSubagents()};case"workspace":return{workspace:e.getWorkspace()};default:return{self:e.getSelf(),tools:e.getTools(),subagents:e.getSubagents(),workspace:e.getWorkspace()}}}function JC(e){return e==="self"||e==="tools"||e==="subagents"||e==="workspace"||e==="all"?e:"all"}function Mm(e){let n=[`- Working directory: ${e.cwd.replace(/[\r\n]/g," ")}`];n.push(`- Date: ${jb(e.now??new Date,e.timeZone)}`);let r=typeof e.sessionId=="string"&&e.sessionId.length>0?e.sessionId.slice(0,8):null,o=e.surface&&e.surface!=="unknown"?e.surface:null,i=typeof e.depth=="number"?typeof e.maxDepth=="number"?`depth ${e.depth}/${e.maxDepth}`:`depth ${e.depth}`:null,s=[o,i].filter(a=>typeof a=="string");if(r!==null||s.length>0){let a=["- Session:"];r!==null&&a.push(r),s.length>0&&a.push(`(${s.join(", ")})`),n.push(a.join(" "))}if(e.workspace!==void 0&&e.workspace!==null){let a=e.workspace;if(a.branch!==null||a.headSha!==null){let l=a.branch??"(detached)",c=a.headSha!==null?` @ ${a.headSha}`:"",u;a.dirty===null?u="":a.dirty?u=` (${a.dirtyCount!==null?a.dirtyCount:"?"} dirty)`:u=" (clean)",n.push(`- Workspace: ${l}${c}${u}`)}}return`# Environment
299
+ `,"utf-8")}catch(r){N("WAL append failed (non-fatal):",String(r))}}};cbe=/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;ube=new Set(["fact","session_start","session_end","supersede"]),dbe=new Set(["preference","convention","decision","learning"])});function E1(e){return mbe.has(e)}function Fb(){return k.AFK_MEMORY_EVIDENCE_GATE!=="0"}function GC(e){return E1(e)}function Nb(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function R1(e,t){return E1(e)?Nb(t)?"verified":"unverified":"not-applicable"}function A1(e,t){return t!=="unverified"||e.startsWith(x1)?e:`${x1} ${e}`}var mbe,x1,C1=b(()=>{"use strict";F();mbe=new Set(["convention"]),x1="[unverified]"});function gbe(e,t){return t?e.map(n=>{if(n.type!=="fact"||!n.category)return{...n,verification:"not-applicable"};let r=R1(n.category,n.evidence);return{...n,verification:r,content:A1(n.content,r)}}):e.map(n=>{let r={...n};return delete r.evidence,delete r.verification,r})}function Im(e,t,n){let r=async s=>{try{let a=hbe(s),l=e.search(a.query,{category:a.category,since:a.since,limit:a.limit??10});return{content:JSON.stringify(gbe(l,Fb()))}}catch(a){return{content:`memory_search error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},o=async s=>{try{let a=ybe(s);if(a.target==="hot"){if(a.action!=="set")return{content:'Hot memory only supports action: "set". Use supersede/remove only for facts.',isError:!0};if(!a.content)return{content:'content is required for action: "set"',isError:!0};let l=e.saveHot(a.content),c={saved:!0,target:"hot",usage:{tokens:l.tokens,maxTokens:l.maxTokens,pct:l.pct}};return l.truncated?(c.truncated=!0,c.note='Hot memory exceeded the ~1,500-token cap and was truncated from the end (lowest-priority lines dropped; a sentinel marks the cut). Keep hot memory to a few durable essentials \u2014 move detail to the fact archive with target:"fact".'):l.pct>=T1*100&&(c.warning=`Hot memory is at ${l.pct}% of the ~1,500-token cap. Move non-essential lines to the fact archive (target:"fact") before it truncates.`),{content:JSON.stringify(c)}}if(a.action==="set"){if(!a.category)return{content:"category is required for fact storage",isError:!0};if(!a.content)return{content:'content is required for action: "set"',isError:!0};let l=a.category,c=Nb(a.evidence),d={id:e.storeFact({session_id:t,category:l,content:a.content,source_surface:n??"cli",evidence:c}),action:"set",target:"fact"};return Fb()&&GC(l)&&!c&&(d.warning=_1),{content:JSON.stringify(d)}}if(a.action==="supersede"){if(!a.supersedes)return{content:'supersedes (fact ID) is required for action: "supersede"',isError:!0};if(!a.content)return{content:'content is required for action: "supersede"',isError:!0};let l=e.getFact(a.supersedes),c=a.evidence===void 0?void 0:Nb(a.evidence),d={id:e.supersedeFact(a.supersedes,a.content,a.category??void 0,c),action:"supersede",target:"fact",supersedes:a.supersedes};if(Fb()){let p=a.category??l?.category;p&&GC(p)&&((c===void 0?l?.evidence??null:c)?c===void 0&&(d.warning=fbe):d.warning=_1)}return{content:JSON.stringify(d)}}if(a.action==="remove"){if(!a.id)return{content:'id (fact ID) is required for action: "remove"',isError:!0};let l=e.removeFact(a.id);return{content:JSON.stringify({removed:l,action:"remove",target:"fact"})}}return{content:`Unknown action: ${a.action}`,isError:!0}}catch(a){return{content:`memory_update error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},i=async s=>{try{let a=bbe(s);return e.writeProcedure(a.name,a.content,t),{content:JSON.stringify({name:a.name,written:!0})}}catch(a){return{content:`procedure_write error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}};return new Map([["memory_search",r],["memory_update",o],["procedure_write",i]])}function hbe(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e;if(typeof t.query!="string")throw new Error("query (string) is required");let n={query:t.query};if(t.category!==void 0){if(typeof t.category!="string")throw new Error("category must be a string");let r=["preference","convention","decision","learning"];if(!r.includes(t.category))throw new Error(`category must be one of: ${r.join(", ")}`);n.category=t.category}if(t.since!==void 0){if(typeof t.since!="string")throw new Error("since must be a string (ISO date)");n.since=t.since}if(t.limit!==void 0){if(typeof t.limit!="number"||t.limit<=0)throw new Error("limit must be a positive number");n.limit=t.limit}return n}function ybe(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e,n=["hot","fact"];if(typeof t.target!="string"||!n.includes(t.target))throw new Error(`target must be one of: ${n.join(", ")}`);let r=["set","supersede","remove"];if(typeof t.action!="string"||!r.includes(t.action))throw new Error(`action must be one of: ${r.join(", ")}`);let o={target:t.target,action:t.action};if(t.content!==void 0){if(typeof t.content!="string")throw new Error("content must be a string");o.content=t.content}if(t.category!==void 0){if(typeof t.category!="string")throw new Error("category must be a string");let i=["preference","convention","decision","learning"];if(!i.includes(t.category))throw new Error(`category must be one of: ${i.join(", ")}`);o.category=t.category}if(t.evidence!==void 0){if(typeof t.evidence!="string")throw new Error("evidence must be a string");o.evidence=t.evidence}if(t.supersedes!==void 0){if(typeof t.supersedes!="number"||t.supersedes<=0)throw new Error("supersedes must be a positive fact ID");o.supersedes=t.supersedes}if(t.id!==void 0){if(typeof t.id!="number"||t.id<=0)throw new Error("id must be a positive fact ID");o.id=t.id}return o}function bbe(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e;if(typeof t.name!="string")throw new Error("name (string) is required");if(typeof t.content!="string")throw new Error("content (string) is required");return{name:t.name,content:t.content}}var Wc,P1,I1,Bi,Aa,_1,fbe,qC=b(()=>{"use strict";Lb();C1();Wc={name:"memory_search",category:"read",concurrencySafe:!0,description:'Search cross-session memory for facts and procedures. Returns results ranked by relevance. Use this to recall information from prior sessions. Supports FTS5 match syntax: AND, OR, NOT, "exact phrase", prefix*',input_schema:{type:"object",properties:{query:{type:"string",description:'Search query (supports FTS5 match syntax: AND, OR, NOT, "exact phrase", prefix*)'},category:{type:"string",enum:["preference","convention","decision","learning"],description:"Optional: filter by fact category"},since:{type:"string",description:"Optional: ISO date \u2014 only return facts created after this date"},limit:{type:"number",description:"Max results (default 10)"}},required:["query"]}},P1={name:"memory_update",category:"write",concurrencySafe:!1,description:'Store a fact in cross-session memory or update hot memory. Hot memory (target: "hot") persists in the system prompt across all future sessions. Facts (target: "fact") are stored in the searchable archive.',input_schema:{type:"object",properties:{target:{type:"string",enum:["hot","fact"],description:'"hot" writes to HOT.md (system prompt), "fact" writes to the searchable archive'},action:{type:"string",enum:["set","supersede","remove"],description:"Operation: set (create/overwrite), supersede (replace while keeping history), remove (delete)"},content:{type:"string",description:"The content to store (for set/supersede)"},category:{type:"string",enum:["preference","convention","decision","learning"],description:"Required for fact target"},evidence:{type:"string",description:'Optional provenance citation backing a codebase fact \u2014 a file:line, commit SHA, or trace-event id. When the evidence gate is enabled, a "convention" fact stored without it is recalled as [unverified]; preferences and reflections never need it.'},supersedes:{type:"number",description:"Fact ID being superseded (for supersede action)"},id:{type:"number",description:"Fact ID to remove (for remove action)"}},required:["target","action"]}},I1={name:"procedure_write",category:"write",concurrencySafe:!1,description:"Write a reusable procedure to memory. Procedures are markdown files describing how to perform recurring tasks. They persist across sessions and are searchable via memory_search.",input_schema:{type:"object",properties:{name:{type:"string",description:"Procedure name (kebab-case, becomes the filename)"},content:{type:"string",description:"Procedure content (markdown)"}},required:["name","content"]}},Bi=[Wc,P1,I1],Aa=Bi.map(e=>e.name),_1='Stored without evidence \u2014 this codebase fact (category "convention") will be recalled as [unverified]. Supply `evidence` (a file:line, commit SHA, or trace-event id) so future sessions can trust it as ground truth rather than an unverified agent claim.',fbe='Superseded without fresh evidence \u2014 the prior citation is carried forward and this codebase fact (category "convention") is still recalled as verified against the OLD evidence, which may not back the changed content. Re-supply `evidence` if the claim changed (or pass an empty string to clear it and recall as [unverified]).'});var M1,wbe,Sbe,vbe,O1,Kc,Bb,Ub=b(()=>{"use strict";M1={name:"state_get",category:"read",concurrencySafe:!0,description:"Retrieve a document from the durable cross-session state store. Returns null if the document does not exist or has expired. Documents are namespaced (namespace + key) JSON values with a version counter.",input_schema:{type:"object",properties:{namespace:{type:"string",description:'Document namespace. Pattern: [A-Za-z0-9_.-]+, max 128 chars. Use a consistent namespace per concern (e.g. "todos", "project-state").'},key:{type:"string",description:"Document key. Same pattern/limit as namespace."}},required:["namespace","key"]}},wbe={name:"state_put",category:"write",concurrencySafe:!1,description:"Write or update a document in the durable cross-session state store. Creates on first insert (version starts at 1) and increments version on updates. Use state_cas instead when concurrent writes are a concern.",input_schema:{type:"object",properties:{namespace:{type:"string",description:"Document namespace. Pattern: [A-Za-z0-9_.-]+, max 128 chars."},key:{type:"string",description:"Document key. Same pattern/limit as namespace."},value:{description:"JSON-serializable value to store. Any JSON type is accepted (object, array, string, number, boolean, null)."},ttl_ms:{type:"number",description:"Optional time-to-live in milliseconds. Document is automatically deleted after this many ms from the write time."},metadata:{description:"Optional metadata object (JSON-serializable). Not returned by state_get \u2014 for audit/tagging only."}},required:["namespace","key","value"]}},Sbe={name:"state_cas",category:"write",concurrencySafe:!1,description:"Compare-and-swap write to the durable cross-session state store. Updates the document only when its current version matches expected_version. Returns {matched: false} if the version does not match or the document does not exist. Use this for safe concurrent updates by multiple sessions.",input_schema:{type:"object",properties:{namespace:{type:"string",description:"Document namespace. Pattern: [A-Za-z0-9_.-]+, max 128 chars."},key:{type:"string",description:"Document key. Same pattern/limit as namespace."},expected_version:{type:"number",description:"Version the document must currently have for the update to succeed."},value:{description:"New JSON-serializable value to store if the CAS matches."},ttl_ms:{type:"number",description:"Optional TTL in milliseconds from the write time."},metadata:{description:"Optional metadata object (JSON-serializable)."}},required:["namespace","key","expected_version","value"]}},vbe={name:"state_delete",category:"write",concurrencySafe:!1,description:"Delete a document from the durable cross-session state store. Returns {deleted: true} if the document existed and was removed, {deleted: false} if it did not exist.",input_schema:{type:"object",properties:{namespace:{type:"string",description:"Document namespace. Pattern: [A-Za-z0-9_.-]+, max 128 chars."},key:{type:"string",description:"Document key. Same pattern/limit as namespace."}},required:["namespace","key"]}},O1={name:"state_query",category:"read",concurrencySafe:!0,description:"List documents in a namespace from the durable cross-session state store. Returns documents sorted by key. Supports key prefix filtering and pagination. Expired documents are excluded. Default limit is 20, maximum is 100.",input_schema:{type:"object",properties:{namespace:{type:"string",description:"Document namespace. Pattern: [A-Za-z0-9_.-]+, max 128 chars."},key_prefix:{type:"string",description:"Optional key prefix filter. Only documents whose key starts with this string are returned."},limit:{type:"number",description:"Maximum number of results to return (default 20, max 100)."}},required:["namespace"]}},Kc=[M1,wbe,Sbe,vbe,O1],Bb=[M1,O1]});function zC(e,t="all"){switch(t){case"self":return{self:e.getSelf()};case"tools":return{tools:e.getTools()};case"subagents":return{subagents:e.getSubagents()};case"workspace":return{workspace:e.getWorkspace()};default:return{self:e.getSelf(),tools:e.getTools(),subagents:e.getSubagents(),workspace:e.getWorkspace()}}}function JC(e){return e==="self"||e==="tools"||e==="subagents"||e==="workspace"||e==="all"?e:"all"}function Mm(e){let n=[`- Working directory: ${e.cwd.replace(/[\r\n]/g," ")}`];n.push(`- Date: ${jb(e.now??new Date,e.timeZone)}`);let r=typeof e.sessionId=="string"&&e.sessionId.length>0?e.sessionId.slice(0,8):null,o=e.surface&&e.surface!=="unknown"?e.surface:null,i=typeof e.depth=="number"?typeof e.maxDepth=="number"?`depth ${e.depth}/${e.maxDepth}`:`depth ${e.depth}`:null,s=[o,i].filter(a=>typeof a=="string");if(r!==null||s.length>0){let a=["- Session:"];r!==null&&a.push(r),s.length>0&&a.push(`(${s.join(", ")})`),n.push(a.join(" "))}if(e.workspace!==void 0&&e.workspace!==null){let a=e.workspace;if(a.branch!==null||a.headSha!==null){let l=a.branch??"(detached)",c=a.headSha!==null?` @ ${a.headSha}`:"",u;a.dirty===null?u="":a.dirty?u=` (${a.dirtyCount!==null?a.dirtyCount:"?"} dirty)`:u=" (clean)",n.push(`- Workspace: ${l}${c}${u}`)}}return`# Environment
300
300
  ${n.join(`
301
301
  `)}`}function jb(e,t){try{let n=t??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",r=new Intl.DateTimeFormat("en-CA",{timeZone:n,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),o=s=>r.find(a=>a.type===s)?.value??"";return`${new Intl.DateTimeFormat("en-US",{timeZone:n,weekday:"long"}).format(e)}, ${o("year")}-${o("month")}-${o("day")} (${n})`}catch{return e.toISOString().slice(0,10)}}var VC=b(()=>{"use strict"});import{spawnSync as kbe}from"child_process";function Hb(e,t,n=!1){try{let r=kbe("git",t,{cwd:e,encoding:"utf8",maxBuffer:4096,shell:!1});if(r.status!==0||r.signal!==null||r.error!==void 0)return null;let o=typeof r.stdout=="string"?r.stdout.trim():null;return o===null?null:o.length>0||n?o:null}catch{return null}}function YC(e){let t=Hb(e,["rev-parse","--short","HEAD"]);if(t===null)return{...Tbe};let n=Hb(e,["symbolic-ref","--short","HEAD"]),r=Hb(e,["status","--porcelain"],!0),o=!1,i=0;if(r!==null){let a=r.split(`
302
302
  `).filter(l=>l.trim().length>0);o=a.length>0,i=a.length}else o=null,i=null;let s=Hb(e,["remote","get-url","origin"]);return{branch:n,headSha:t,dirty:o,dirtyCount:i,remoteUrl:s}}var Tbe,XC=b(()=>{"use strict";Tbe={branch:null,headSha:null,dirty:null,dirtyCount:null,remoteUrl:null}});function Om(e){return{getSelf(){return{sessionId:e.sessionId??null,surface:Ebe(e.surface),parentSessionId:e.parentSessionId??null,depth:e.depth??null,maxDepth:e.maxDepth??null,phaseRole:e.phaseRole??null,cwd:e.getCwd(),model:{provider:e.providerName,name:e.modelName},permissionMode:xbe(e.permissionMode)}},getTools(){return{enabled:e.getEnabledToolNames(),mcpServers:Rbe(e.getMcpTools())}},getSubagents(){return e.getSubagents()},getWorkspace(){return YC(e.getCwd())}}}function xbe(e){switch(e){case"bypassPermissions":case"acceptEdits":case"dontAsk":case"auto":return"elevated";default:return"default"}}function Ebe(e){switch(e){case"cli":case"repl":case"daemon":case"telegram":case"subagent":case"web":return e;default:return"unknown"}}function Rbe(e){let t=new Map;for(let n of e){if(!n.name.startsWith("mcp__"))continue;let r=n.name.split("__");if(r.length<3)continue;let o=r[1];typeof o!="string"||o.length===0||t.set(o,(t.get(o)??0)+1)}return[...t.entries()].map(([n,r])=>({name:n,toolCount:r})).sort((n,r)=>n.name.localeCompare(r.name))}var $1=b(()=>{"use strict";XC()});function Gc(e){return async(t,n)=>{let r=t&&typeof t=="object"?JC(t.view):"all",o=zC(e,r);return{content:JSON.stringify(o)}}}function $m(e,t){let n=Gc(t),r=e,o=Array.isArray(r.toolDefs)?r.toolDefs:null,i={async execute(s){return s.name==="get_runtime_state"?n(s.input,s.signal):e.execute(s)}};if(o!==null){let s=o.some(a=>a.name==="get_runtime_state");i.toolDefs=s?o:[...o,xr]}return i}var xr,Ct,Wb=b(()=>{"use strict";VC();xr={name:"get_runtime_state",category:"other",concurrencySafe:!0,description:"Inspect what the runtime knows about this session: identity (sessionId, surface, depth, parent), tool affordances (currently-enabled tool names and MCP server summary), delegation state (active subagent handles, background jobs), and git workspace state (branch, HEAD SHA, dirty count, remote URL). Returns a compact JSON snapshot.\n\nUse when uncertain about: your current nesting depth, whether a tool you want is actually available right now, what MCP servers are wired, whether earlier subagents you dispatched are still running, or what git branch / commit the session started on.\n\nViews:\n- `self` \u2014 identity + model + permissions + cwd only\n- `tools` \u2014 enabled tool names + MCP server summary only\n- `subagents` \u2014 active subagent handles + background jobs only\n- `workspace` \u2014 git state (branch, headSha, dirty, dirtyCount, remoteUrl)\n- `all` \u2014 union of the four above (default)\n\nThis is a read-only, in-memory inspection. It does not probe the file system or network. Fields the runtime does not know (e.g. depth for a top-level session) come back as `null` rather than synthesised defaults.",input_schema:{type:"object",properties:{view:{type:"string",enum:["self","tools","subagents","workspace","all"],description:'Which slice of state to return. Defaults to "all". Use a narrower view when only one slice is needed to keep the response compact.'}},required:[]}},Ct=[xr.name]});function D1(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function QC(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?"unknown":D1(e)?"alive":"dead"}var ZC=b(()=>{"use strict"});import{mkdir as Itt,writeFile as e_,unlink as Mtt,readdir as Abe,readFile as Gb}from"fs/promises";import{unlinkSync as Cbe,existsSync as _be,mkdirSync as Pbe,writeFileSync as Ibe}from"fs";import{join as L1}from"path";function Dm(e){return L1(Yp(),`${e}.json`)}function t_(e,t){let r=(Kb.get(e)??Promise.resolve()).then(t,t);return Kb.set(e,r),r.catch(()=>{}).then(()=>{Kb.get(e)===r&&Kb.delete(e)}),r}function Mbe(e){let t={schemaVersion:F1,heartbeatAt:new Date().toISOString(),...e};return JSON.stringify(t,null,2)}function n_(e){try{Pbe(Yp(),{recursive:!0,mode:448}),Ibe(Dm(e.sessionId),Mbe(e),{encoding:"utf8",mode:384})}catch{}}async function r_(e,t){return t_(e,async()=>{try{let n=Dm(e),r=await Gb(n,"utf8"),o=JSON.parse(r);o.afk=t,await e_(n,JSON.stringify(o,null,2),{encoding:"utf8",mode:384})}catch{}})}async function o_(e,t){return t_(e,async()=>{try{let n=Dm(e),r=await Gb(n,"utf8"),o=JSON.parse(r);t?o.blockedSince=new Date().toISOString():delete o.blockedSince,await e_(n,JSON.stringify(o,null,2),{encoding:"utf8",mode:384})}catch{}})}async function N1(e,t){return t_(e,async()=>{try{let n=Dm(e),r=await Gb(n,"utf8"),o=JSON.parse(r);o.cwd=t,await e_(n,JSON.stringify(o,null,2),{encoding:"utf8",mode:384})}catch{}})}function Lm(e){try{let t=Dm(e);_be(t)&&Cbe(t)}catch{}}function Obe(e,t){if(typeof e!="string")return null;let n=Date.parse(e);return Number.isNaN(n)?null:t-n}async function qb(){let e=Yp(),t;try{t=await Abe(e)}catch{return[]}let n=Date.now(),r=[];for(let o of t){if(!o.endsWith(".json"))continue;let i=L1(e,o);try{let s=await Gb(i,"utf8"),a=JSON.parse(s);if(a!==null&&typeof a=="object"&&"sessionId"in a&&typeof a.sessionId=="string"){let l=a,c=a;r.push({...l,path:i,liveness:QC(c.pid),heartbeatAgeMs:Obe(c.heartbeatAt,n)})}}catch{}}return r}async function i_(e={}){let t=await qb(),{maxHeartbeatAgeMs:n}=e;return t.filter(r=>!(r.liveness==="dead"||n!==void 0&&r.heartbeatAgeMs!==null&&r.heartbeatAgeMs>n))}var F1,Kb,Ca=b(()=>{"use strict";B();ZC();F1=1;Kb=new Map});var zt=b(()=>{"use strict";VC();$1();Wb();XC();Ca();ZC()});function s_(e){return $be.has(e)}function B1(e,t){return e.reduce((n,r,o)=>{let i=t(r.name,r.input),s=n[n.length-1];return s&&i&&s.isConcurrencySafe?s.indices.push(o):n.push({isConcurrencySafe:i,indices:[o]}),n},[])}var $be,a_=b(()=>{"use strict";Ln();qC();Ub();zt();$be=new Set([...ro,Dn,xa,Ea,...Bi,...Kc,xr].filter(e=>e.concurrencySafe===!0).map(e=>e.name))});import{createHash as Dbe}from"node:crypto";function U1(e){let t;try{t=JSON.stringify(e.input)??"null"}catch{t=String(e.input)}return Dbe("sha256").update(e.name).update("\0").update(t).digest("hex")}var j1=b(()=>{"use strict"});function W1(e){return e!==void 0&&e.includes(l_)}function K1(e){let t=e.input??{},n=e.name==="read_file"?t.file_path:t.path;return typeof n=="string"&&n.length>0?n:`<${e.name} with no explicit path>`}function G1(e,t){let n=e.length>0?e.map(r=>` - ${r}`).join(`
@@ -430,7 +430,7 @@ ${o}`,paths:[t,n]}:o!==null?i={content:o,paths:[n]}:r!==null?i={content:r,paths:
430
430
 
431
431
  ${t}`}var Cke,tP=b(()=>{"use strict";Cke=new Set(["script","style","noscript","template","svg"])});function Ike(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 fK(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function Mke(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 gK(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??Ike,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(!Pke.has(d.status)||u===o)return d;let p=Mke(d,s)??fK(u,i,s);N("[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=fK(u,i,s);N("[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 Pke,hK=b(()=>{"use strict";me();Pke=new Set([429,502,503,504])});import{BlockList as Oke,isIP as rP}from"node:net";import{lookup as $ke}from"node:dns/promises";import{Agent as Dke}from"undici";function bK(){let e=k.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return e==="1"||e==="true"}function Bke(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function nP(e){let t=rP(e);return t===0?!1:Nke.check(e,t===4?"ipv4":"ipv6")}async function wK(e){return $ke(e,{all:!0,verbatim:!0})}async function $a(e,t={}){if(t.allowPrivateHosts??bK())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=Bke(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(rP(r)!==0)return nP(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let i=t.lookupFn??wK,s;try{s=await i(r)}catch{return{allowed:!0}}for(let a of s)if(nP(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function uf(e,t={}){let n=await $a(e,t);if(!n.allowed)throw new Jt(n.reason)}async function Gi(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<=yK;s++){await uf(i,o);let a={...n,redirect:"manual",...e===globalThis.fetch&&!(r.allowPrivateHosts??bK())?{dispatcher:Uke}:{}},l=await gK(e,i,a,r.retry??{});if(!jke.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 Jt(`too many redirects (>${yK}) starting from ${t}`)}var Lke,Fke,Nke,Jt,Uke,yK,jke,Da=b(()=>{"use strict";F();hK();Lke=[["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]],Fke=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],Nke=(()=>{let e=new Oke;for(let[t,n]of Lke)e.addSubnet(t,n,"ipv4");for(let[t,n]of Fke)e.addSubnet(t,n,"ipv6");return e})(),Jt=class extends Error{constructor(t){super(t),this.name="EgressBlockedError"}};Uke=new Dke({connect:{lookup(e,t,n){wK(e).then(r=>{let o=r.find(s=>nP(s.address));if(o!==void 0){n(new Jt(`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,rP(i.address))},r=>n(r,"",0))}}});yK=20,jke=new Set([301,302,303,307,308])});var iP={};Mn(iP,{enforceDomainPolicy:()=>Ar,loadBrowserConfig:()=>oP});import{readFileSync as Hke}from"node:fs";import{join as Wke}from"path";function Kke(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function SK(e,t){return Kke(t).test(e)}function zke(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(Gke.has(t))return!0;if(qke.has(t))return!1}return!1}function vK(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function Jke(e){if(e===void 0||e==="")return"auto";if(e==="playwright"||e==="agent-browser"||e==="auto")return e;throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${e}`)}function kK(e){let t=e===void 0||e.trim()===""?"default":e.trim();return bc(t),t}function Vke(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function Yke(e){try{return Hke(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function Xke(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"||t.backend==="agent-browser"||t.backend==="auto")n.backend=t.backend;else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${String(t.backend)}`);return typeof t.defaultProfile=="string"&&(n.defaultProfile=kK(t.defaultProfile)),n}function oP(e){let t=e?.env??k,n=e?.readFileSync??Yke,r=e?.surface??t.AGENT_SURFACE,o=zke(t.AFK_BROWSER_HEADLESS,r),i=vK(t.AFK_BROWSER_ALLOWED_DOMAINS),s=vK(t.AFK_BROWSER_BLOCKED_DOMAINS),a=Vke(t.AFK_BROWSER_DOM_SNAPSHOTS),l=Jke(t.AFK_BROWSER_BACKEND),c=kK(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():Wke(qn(),"browser.json"),f=n(p);if(f===void 0)return u;let g;try{g=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${p}: ${String(y)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${p} must be a JSON object`);let h=Xke(u,g);return h.configPath=p,h}function Ar(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(SK(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>SK(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Gke,qke,qi=b(()=>{"use strict";F();B();Gke=new Set(["daemon","subagent","telegram","afk"]),qke=new Set(["repl","interactive","cli"])});import{readFileSync as Qke}from"node:fs";import{join as Zke}from"node:path";import{homedir as eTe}from"node:os";function nTe(e){let t=e??tTe,n;try{n=Qke(t,"utf8")}catch{return null}let r;try{r=JSON.parse(n)}catch{return null}if(typeof r!="object"||r===null||Array.isArray(r))return null;let o=r;if(typeof o.url!="string"||typeof o.token!="string"||typeof o.pid!="number")return null;let i;try{i=new URL(o.url)}catch{return null}let{hostname:s,protocol:a}=i;if(!(s==="127.0.0.1"||s==="localhost"||s==="::1")||a!=="http:")throw new Error(`Agent Browser connection file contains an untrusted URL: ${o.url}. Only http://127.0.0.1 or http://localhost is permitted.`);return{url:o.url,token:o.token,pid:o.pid,version:typeof o.version=="string"?o.version:"unknown"}}function rTe(e){try{return process.kill(e,0),!0}catch{return!1}}async function oTe(e,t,n=2e3){try{let r=new AbortController,o=setTimeout(()=>r.abort(),n),i=await fetch(`${e}/health`,{method:"GET",headers:{Authorization:`Bearer ${t}`,Host:"127.0.0.1:8833"},signal:r.signal});return clearTimeout(o),i.ok}catch{return!1}}async function sP(e){let t=nTe(e);return t===null?{available:!1,connection:null,reason:"connection file missing or invalid"}:rTe(t.pid)?await oTe(t.url,t.token)?{available:!0,connection:t,reason:null}:{available:!1,connection:t,reason:`health probe failed at ${t.url}`}:{available:!1,connection:t,reason:`stale connection file: PID ${t.pid} not alive`}}var tTe,TK=b(()=>{"use strict";tTe=Zke(eTe(),".config","agent-browser","connection.json")});async function xK(e){let{config:t,surface:n}=e;if(t.backend==="playwright")return{backend:"playwright",reason:"explicit config: backend=playwright",probeMs:0,availability:null};if(t.backend==="agent-browser"){let s=Date.now(),a=await sP(),l=Date.now()-s;if(!a.available)throw new Error(`AFK_BROWSER_BACKEND=agent-browser but Agent Browser is not available: ${a.reason}`);return{backend:"agent-browser",reason:"explicit config: backend=agent-browser",probeMs:l,availability:a}}if(n&&iTe.has(n))return{backend:"playwright",reason:`auto: surface "${n}" excluded from Agent Browser`,probeMs:0,availability:null};if(t.headless)return{backend:"playwright",reason:"auto: headless mode requires Playwright",probeMs:0,availability:null};let r=Date.now(),o=await sP(),i=Date.now()-r;return o.available?{backend:"agent-browser",reason:"auto: Agent Browser available and preferred",probeMs:i,availability:o}:{backend:"playwright",reason:`auto: Agent Browser unavailable (${o.reason})`,probeMs:i,availability:o}}var iTe,EK=b(()=>{"use strict";TK();iTe=new Set(["daemon","subagent"])});import{createHash as sTe}from"crypto";function RK(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&aTe.test(e.label))}function AK(e){return sTe("sha256").update(e,"utf8").digest("hex").slice(0,8)}function CK(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var aTe,Ew=b(()=>{"use strict";aTe=/password|secret|token|api[_-]?key|otp|2fa/i});import{randomBytes as lTe}from"crypto";import{mkdir as cTe,stat as uTe,writeFile as dTe}from"fs/promises";import{join as aP}from"path";import{gzip as pTe}from"zlib";import{promisify as mTe}from"util";function fTe(e){return aP(Gt(e),"browser")}function gTe(e){return aP(fTe(e),"screenshots")}function hTe(){return new Date().toISOString().replace(/[:.]/g,"-")}function yTe(){return lTe(3).toString("hex")}async function uu(e,t,n){if(t.length>_K)throw new Error(`writeScreenshotSidecar: buffer exceeds ${_K} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=gTe(e);await cTe(r,{recursive:!0});let o=`${hTe()}-${yTe()}-${n}.png`,i=aP(r,o);await dTe(i,t);let{size:s}=await uTe(i);return{path:i,bytes:s}}var lat,_K,lP=b(()=>{"use strict";B();Ew();lat=mTe(pTe);_K=5*1024*1024});var Rw,PK=b(()=>{"use strict";Rw=class{baseUrl;token;constructor(t){this.baseUrl=t.url,this.token=t.token}async call(t,n,r=3e4){let o={version:1,method:t,params:n},i=new AbortController,s=setTimeout(()=>i.abort(),r);try{let a=await fetch(`${this.baseUrl}/agent`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,Host:new URL(this.baseUrl).host},body:JSON.stringify(o),signal:i.signal});if(!a.ok){let l=await a.text().catch(()=>"");throw new Error(`Agent Browser ${t} failed (HTTP ${a.status}): ${l}`)}return await a.json()}finally{clearTimeout(s)}}async listTabs(){return(await this.call("tabs.list",null)).tabs}async openTab(t){return{tabId:(await this.call("tabs.open",{url:t},6e4)).tab_id}}async closeTab(t){await this.call("tabs.close",{tab_id:t})}async read(t,n){return this.call("page.read",{tab_id:t,mode:n?.mode??"main",...n?.query?{query:n.query}:{},...n?.budget?{budget:n.budget}:{}})}async inspect(t,n){return this.call("page.inspect",{tab_id:t,mode:n?.mode??"interactive",...n?.query?{query:n.query}:{},...n?.limit?{limit:n.limit}:{}})}async click(t,n){await this.call("page.click",{tab_id:t,element_id:n})}async fill(t,n,r){await this.call("page.fill",{tab_id:t,element_id:n,value:r})}async press(t,n,r){await this.call("page.press",{tab_id:t,key:n,...r?{element_id:r}:{}})}async select(t,n,r){await this.call("page.select",{tab_id:t,element_id:n,value:r})}async waitFor(t,n,r){await this.call("page.wait",{tab_id:t,condition:n,...r?.value?{value:r.value}:{},...r?.timeout?{timeout:r.timeout}:{}},(r?.timeout??3e4)+5e3)}async evalScript(t,n){return this.call("page.eval",{tab_id:t,script:n})}async screenshot(t){return this.call("page.screenshot",{tab_id:t})}}});function cP(e){return{id:e.id,role:e.role,label:e.label,kind:e.kind,value:e.value,state:{disabled:e.disabled,...e.checked!==void 0?{checked:e.checked}:{},...e.selected!==void 0?{selected:e.selected}:{},...e.expanded!==void 0?{expanded:e.expanded}:{}},bbox:e.bbox,...e.selector?{selector:e.selector}:{}}}function IK(e,t){switch(t.kind){case"element_id":if(e.has(t.elementId))return t.elementId;throw new Error(`Element ${t.elementId} not found in current observation. Call browser_observe to refresh.`);case"selector":return null;case"semantic":return null}}async function uP(e,t,n,r,o,i){switch(n){case"click":await e.click(t,r);break;case"fill":if(o===void 0)throw new Error("fill requires a value");await e.fill(t,r,o);break;case"press":if(o===void 0)throw new Error("press requires a value (key combo)");await e.press(t,o,r);break;case"select":if(o===void 0)throw new Error("select requires a value");await e.select(t,r,o);break;case"hover":throw new Error("hover is not supported by Agent Browser; use element_id from a prior observation to target clicks instead");case"scroll_to":{let s=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');await e.evalScript(t,`document.querySelector('[data-element-id="${s}"]')?.scrollIntoView({behavior:'smooth',block:'center'})`);break}case"wait_for":await e.waitFor(t,"element",{value:r,timeout:i??1e4});break;default:throw new Error(`Unknown action: ${n}`)}}async function MK(e,t){if(t.target.kind!=="semantic")throw new Error("resolveSemanticAndAct called with non-semantic target");let{elements:n}=await e.client.inspect(e.tabId,{mode:"interactive",query:t.target.text,limit:10}),r=n;if(t.target.role){let l=t.target.role.toLowerCase();r=n.filter(c=>c.role.toLowerCase()===l)}if(r.length===0)throw new Error(`No element found matching semantic target: text="${t.target.text}"`+(t.target.role?`, role="${t.target.role}"`:""));if(r.length>1)return{outcome:"ambiguous_target",query:{text:t.target.text,...t.target.role?{role:t.target.role}:{}},candidates:r.slice(0,5).map(cP)};let i=r[0].id;await uP(e.client,e.tabId,t.action,i,t.value,t.timeoutMs);let s=await e.client.read(e.tabId,{mode:"main"}),a=Ar(s.url,e.config);return a.allowed?{elementId:i}:{outcome:"blocked_by_policy",url:s.url,reason:`action navigated to blocked domain: ${a.reason}`}}var OK=b(()=>{"use strict";qi()});var $K={};Mn($K,{AgentBrowserProvider:()=>dP});var dP,DK=b(()=>{"use strict";qi();lP();PK();OK();dP=class{name="agent-browser";config;client;sessions=new Map;constructor(t,n){this.config=t,this.client=new Rw(n)}async open(t){let n=Ar(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let r=this.sessions.get(t.sessionId);if(r)await this.client.evalScript(r.tabId,`window.location.href = ${JSON.stringify(t.url)}`),await this.client.waitFor(r.tabId,"load",{timeout:t.timeoutMs??3e4});else{let{tabId:s}=await this.client.openTab(t.url);await this.client.waitFor(s,"load",{timeout:t.timeoutMs??3e4}),r={tabId:s,observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null},this.sessions.set(t.sessionId,r)}let o=await this.client.read(r.tabId,{mode:"main"}),i=Ar(o.url,this.config);return i.allowed?this.buildObservation(r,t.sessionId,t.screenshot,void 0,"browser_open"):(await this.client.evalScript(r.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`redirected to blocked domain: ${i.reason}`})}async observe(t){let n=this.sessions.get(t.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${t.sessionId}. Call browser_open first.`);return this.buildObservation(n,t.sessionId,t.screenshot,t.maxElements,"browser_observe")}async act(t){let n=this.sessions.get(t.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${t.sessionId}. Call browser_open first.`);let r=IK(n.knownElements,t.target);if(r===null){if(t.target.kind==="semantic"){let s=await MK({client:this.client,config:this.config,tabId:n.tabId},t);return"outcome"in s?s:(n.lastAction=`browser_act:${t.action}`,n.lastActionAt=new Date().toISOString(),this.buildObservation(n,t.sessionId,t.screenshot,void 0,"browser_act"))}throw t.target.kind==="selector"?new Error("selector targets are not supported by Agent Browser; use element_id or semantic targets"):new Error(`Cannot resolve target: ${JSON.stringify(t.target)}`)}await uP(this.client,n.tabId,t.action,r,t.value,t.timeoutMs),n.lastAction=`browser_act:${t.action}`,n.lastActionAt=new Date().toISOString();let o=await this.client.read(n.tabId,{mode:"main"}),i=Ar(o.url,this.config);return i.allowed?this.buildObservation(n,t.sessionId,t.screenshot,void 0,"browser_act"):(await this.client.evalScript(n.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`action navigated to blocked domain: ${i.reason}`})}async render(t){throw new Error("AgentBrowserProvider does not support render(). Use PlaywrightProvider for one-shot content fetches.")}async screenshot(t){let n=this.sessions.get(t.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${t.sessionId}. Call browser_open first.`);if(t.target!==void 0||t.fullPage)throw new Error("Agent Browser does not support element or full-page screenshots; omit target and fullPage.");let r=await this.client.screenshot(n.tabId),o=Buffer.from(r.data,"base64"),i=o.length>=24?o.readUInt32BE(16):0,s=o.length>=24?o.readUInt32BE(20):0;return{path:(await uu(t.sessionId,o,"browser_screenshot")).path,bytes:o.length,width:i,height:s,dataBase64:r.data,mediaType:"image/png"}}async extract(t){throw new Error("AgentBrowserProvider does not support extract() yet.")}async close(t){let n=this.sessions.get(t.sessionId);if(n){try{await this.client.closeTab(n.tabId)}catch{}this.sessions.delete(t.sessionId)}}describe(t){let n=this.sessions.get(t);return n?{active:!0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:1}:null}async shutdown(){let t=Array.from(this.sessions.entries()).map(async([,n])=>{try{await this.client.closeTab(n.tabId)}catch{}});await Promise.all(t),this.sessions.clear()}async buildObservation(t,n,r,o,i="browser_open"){let[s,a]=await Promise.all([this.client.read(t.tabId,{mode:"main",budget:4e3}),this.client.inspect(t.tabId,{mode:"interactive",limit:o??80})]),l=a.elements.map(cP),c=o??80,u=l.slice(0,c);t.observationCounter+=1,t.knownElements=new Map(u.map(h=>[h.id,h])),t.currentUrl=s.url,t.currentTitle=s.title;let d=[];l.length>c&&d.push(`page has ${l.length} interactive elements; showing first ${c}`);let p=null;if(r)try{let h=await this.client.screenshot(t.tabId),y=Buffer.from(h.data,"base64");p=(await uu(n,y,i)).path}catch{d.push("screenshot capture failed")}let f=`obs_${t.observationCounter.toString(36)}`,g={httpStatus:null,loadingState:"idle",hasDialog:!1,consoleErrors:0};return{observationId:f,url:s.url,title:s.title,textSummary:s.content.slice(0,4e3),interactive:u,status:g,warnings:d,screenshotPath:p,capturedAt:new Date().toISOString()}}}});import{existsSync as bTe,readFileSync as wTe}from"node:fs";import{createRequire as STe}from"node:module";import{dirname as vTe,join as kTe}from"node:path";function NK(e){if(typeof e=="string")return e;let t=[],n=e;for(let r=0;r<xTe&&n instanceof Error;r++)t.push(n.message),n=n.cause;return t.length>0?t.join(" | "):String(e)}function bn(e){let t=NK(e);return FK.some(n=>t.includes(n))}function ETe(){try{let t=STe(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(wTe(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=kTe(vTe(t),o);return bTe(i)?`node ${/\s/.test(i)?`"${i}"`:i} install chromium`:void 0}catch{return}}function df(){return LK??=ETe()??TTe,LK}function pP(e){return e.includes("install chromium")}function tr(e,t){let n=NK(e),r=t?.latched===!0?` ${RTe}`:"";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: ${df()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${df()}). Or pick a different tool.${r}`}function du(e,t,n=!1){if(!bn(e))return e;let r=e instanceof Error?e.message:String(e);return new Error(`${r}
432
432
 
433
- ${tr(e,{headless:t,latched:n})}`,{cause:e})}var FK,TTe,xTe,LK,RTe,Aw=b(()=>{"use strict";FK=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],TTe="pnpm exec playwright install chromium",xTe=4;RTe="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 La from"node:fs";import Cw from"node:path";import{randomBytes as ATe}from"node:crypto";function CTe(){try{return"5.196.0"}catch{}try{let e=Cw.resolve(import.meta.dirname,"../../../package.json"),t=La.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var _Te,_w,BK=b(()=>{"use strict";Aw();B();me();_Te=CTe(),_w=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=(async()=>{let t;try{({chromium:t}=await import("playwright"))}catch(n){let r=du(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await t.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=du(n,this.config.headless,!0);throw this.latchLaunchFailure(r),r}finally{this.launchPromise=void 0}})(),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/${_Te}`}}loadStorageState(t){let n=wc(t);try{if(!La.existsSync(n))return;let r=JSON.parse(La.readFileSync(n,"utf8"));return N("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){N("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=wc(t);if(!La.existsSync(r))return;let o=await n.storageState(),i=Cw.join(Cw.dirname(r),`.${Cw.basename(r)}.${process.pid}.${ATe(4).toString("hex")}.tmp`);La.writeFileSync(i,JSON.stringify(o),{mode:384}),La.chmodSync(i,384),La.renameSync(i,r),N("[browser/vault] saved session",{profile:t,file:r})}catch(r){N("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as PTe}from"node:crypto";function ITe(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function MTe(e,t,n){return`el_${PTe("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function OTe(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function UK(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function HK(e,t){let n=e.role??"",r=e.name??"";jK.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])HK(i,t)}async function $Te(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},WK).catch(()=>[])}async function DTe(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},WK).catch(()=>[])}function LTe(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Pw(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=LTe(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=$Te(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]),y,w=!1;d!==null?(y=[],HK(d,y)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,y=(await DTe(e)).filter(O=>jK.has(O.role??"")));let S=new Map;for(let I of p){let O=UK(I.name),H=S.get(O);(!H||H.bbox.w===0&&I.bbox.w>0)&&S.set(O,I)}let v=y.map(I=>({ax:I,dom:S.get(UK(I.name??""))})),x=r?v:v.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);x.sort((I,O)=>{let H=I.dom?.bbox.y??0,M=O.dom?.bbox.y??0;if(H!==M)return H-M;let U=I.dom?.bbox.x??0,q=O.dom?.bbox.x??0;return U-q}),x.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=x.slice(0,n).map((I,O)=>{let H=I.ax.role??"generic",M=I.ax.name??"",U=MTe(H,M,O),q=I.dom?.bbox??{x:0,y:0,w:0,h:0},j=I.dom?.type??null,W=null;I.ax.value!==void 0&&I.ax.value!==null&&(W=String(I.ax.value)),I.ax.checked!==void 0&&(W=String(I.ax.checked)),RK({role:H,kind:j})&&(W="[redacted]");let X={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(X.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(X.selected=I.ax.selected),I.ax.expanded!==void 0&&(X.expanded=I.ax.expanded);let D;I.dom?.testId?D=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(D=`#${I.dom.id}`);let G={id:U,role:H,label:ITe(M),kind:j,value:W,state:X,bbox:q};return D!==void 0&&(G.selector=D),G}),_="idle";try{let I=await e.evaluate(()=>document.readyState);I==="loading"?_="loading":I==="interactive"?_="navigating":_="idle"}catch{_="navigating"}_!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let P=OTe(f),R=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:R,url:g,title:h,textSummary:P,interactive:E,status:{httpStatus:t.httpStatus??null,loadingState:_,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var jK,WK,KK=b(()=>{"use strict";Ew();jK=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);WK="a[href], button, input, select, textarea, [role], [tabindex], label"});async function GK(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 mP(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>GK(e,i)))).filter(o=>o!==null)}async function FTe(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 fP(e,t,n){switch(t.kind){case"element_id":return NTe(e,t,n);case"selector":return BTe(e,t);case"semantic":return UTe(e,t)}}async function NTe(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 mP(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function BTe(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 mP(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function UTe(e,t){return t.role!==void 0?jTe(e,t.text,t.role):HTe(e,t.text,t)}async function jTe(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 mP(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function HTe(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 FTe(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 y=p[h];if(y===void 0)continue;let w=await GK(y.locator,y.index);if(w!==null){let S=`${w.role}:${w.label}:${h}`,v=0;for(let x=0;x<S.length;x++)v=v*31+S.charCodeAt(x)>>>0;f.push({...w,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var qK=b(()=>{"use strict"});async function gP(e,t,n,r){let o=e.url();if(o===n)return null;let i=Ar(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 zK=b(()=>{"use strict";qi()});var yP={};Mn(yP,{PlaywrightProvider:()=>hP});function JK(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 hP,bP=b(()=>{"use strict";BK();KK();qK();qi();zK();lP();hP=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new _w(t)}async open(t){let n=Ar(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 gP(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 Pw(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 Pw(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 fP(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${JK(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(y){c=y}else c=h}let d=await gP(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 Pw(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 fP(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${JK(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 uu(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 uu(n,o,r);return i}catch{return null}}}});var Na={};Mn(Na,{__resetBrowserRegistryForTests:()=>JTe,browserProviderActive:()=>GTe,closeBrowserProvider:()=>SP,getBrowserProvider:()=>KTe,getLastRoutingDecision:()=>zTe,peekBrowserProvider:()=>qTe});function VK(){Promise.resolve(SP()).then(()=>{process.exit(130)})}function YK(){Promise.resolve(SP()).then(()=>{process.exit(143)})}function XK(){po=null}function WTe(){Iw||(process.on("SIGINT",VK),process.on("SIGTERM",YK),process.on("exit",XK),Iw=!0)}function QK(){Iw&&(process.removeListener("SIGINT",VK),process.removeListener("SIGTERM",YK),process.removeListener("exit",XK),Iw=!1)}async function KTe(e){return po!==null?po:(Fa!==null||(Fa=(async()=>{let t=oP(e),n=e?.surface??(e?.env??{}).AGENT_SURFACE??k.AGENT_SURFACE,r=await xK({config:t,surface:n});wP=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:i}=await Promise.resolve().then(()=>(DK(),$K)),s=r.availability.connection;o=new i(t,s)}else{let{PlaywrightProvider:i}=await Promise.resolve().then(()=>(bP(),yP));o=new i(t)}return WTe(),po=o,Fa=null,o})()),Fa)}async function SP(){if(po===null)return;let e=po;po=null,Fa=null,QK(),await e.shutdown()}function GTe(){return po!==null}function qTe(){return po}function zTe(){return wP}function JTe(){po=null,Fa=null,wP=null,QK()}var po,Fa,Iw,wP,Ba=b(()=>{"use strict";qi();EK();F();po=null,Fa=null,Iw=!1,wP=null});async function ZK(e,t){try{return await dK(e,t)}catch(n){return N("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function exe(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Ba(),Na)),r=await n();try{return await r.render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}catch(o){if(r.name==="agent-browser"){let{PlaywrightProvider:i}=await Promise.resolve().then(()=>(bP(),yP)),{loadBrowserConfig:s}=await Promise.resolve().then(()=>(qi(),iP)),a=s(),l=new i(a);try{return await l.render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}finally{await l.shutdown()}}throw o}}async function eG(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??exe,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let d=await Gi(n,e,{headers:ZTe,signal:t.signal},o);l=d.status,a=d.url||e;let p=d.headers.get("content-type")??"";if(d.ok){if(QTe.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(XTe.test(p)&&!YTe.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await ZK(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof Jt||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=eP({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...d!==void 0?{advisory:d}:{}}}try{await uf(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>uf(f,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await uf(d.finalUrl,o);let p=await ZK(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||p.textLength>=i.textLength){let f=eP({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 Jt)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 YTe,XTe,QTe,ZTe,tG=b(()=>{"use strict";pK();tP();Da();me();YTe=/(text\/html|application\/xhtml\+xml)/i,XTe=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,QTe=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,ZTe={"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 rxe(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(txe,{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),nxe),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let u=await i.text(),d=ae(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 nG(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?rxe({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 rG(e,t){if(t.length===0)return`# Search results for "${e}"
433
+ ${tr(e,{headless:t,latched:n})}`,{cause:e})}var FK,TTe,xTe,LK,RTe,Aw=b(()=>{"use strict";FK=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],TTe="pnpm exec playwright install chromium",xTe=4;RTe="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 La from"node:fs";import Cw from"node:path";import{randomBytes as ATe}from"node:crypto";function CTe(){try{return"5.197.0"}catch{}try{let e=Cw.resolve(import.meta.dirname,"../../../package.json"),t=La.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var _Te,_w,BK=b(()=>{"use strict";Aw();B();me();_Te=CTe(),_w=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=(async()=>{let t;try{({chromium:t}=await import("playwright"))}catch(n){let r=du(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await t.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=du(n,this.config.headless,!0);throw this.latchLaunchFailure(r),r}finally{this.launchPromise=void 0}})(),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/${_Te}`}}loadStorageState(t){let n=wc(t);try{if(!La.existsSync(n))return;let r=JSON.parse(La.readFileSync(n,"utf8"));return N("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){N("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=wc(t);if(!La.existsSync(r))return;let o=await n.storageState(),i=Cw.join(Cw.dirname(r),`.${Cw.basename(r)}.${process.pid}.${ATe(4).toString("hex")}.tmp`);La.writeFileSync(i,JSON.stringify(o),{mode:384}),La.chmodSync(i,384),La.renameSync(i,r),N("[browser/vault] saved session",{profile:t,file:r})}catch(r){N("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as PTe}from"node:crypto";function ITe(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function MTe(e,t,n){return`el_${PTe("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function OTe(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function UK(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function HK(e,t){let n=e.role??"",r=e.name??"";jK.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])HK(i,t)}async function $Te(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},WK).catch(()=>[])}async function DTe(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},WK).catch(()=>[])}function LTe(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Pw(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=LTe(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=$Te(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]),y,w=!1;d!==null?(y=[],HK(d,y)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,y=(await DTe(e)).filter(O=>jK.has(O.role??"")));let S=new Map;for(let I of p){let O=UK(I.name),H=S.get(O);(!H||H.bbox.w===0&&I.bbox.w>0)&&S.set(O,I)}let v=y.map(I=>({ax:I,dom:S.get(UK(I.name??""))})),x=r?v:v.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);x.sort((I,O)=>{let H=I.dom?.bbox.y??0,M=O.dom?.bbox.y??0;if(H!==M)return H-M;let U=I.dom?.bbox.x??0,q=O.dom?.bbox.x??0;return U-q}),x.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=x.slice(0,n).map((I,O)=>{let H=I.ax.role??"generic",M=I.ax.name??"",U=MTe(H,M,O),q=I.dom?.bbox??{x:0,y:0,w:0,h:0},j=I.dom?.type??null,W=null;I.ax.value!==void 0&&I.ax.value!==null&&(W=String(I.ax.value)),I.ax.checked!==void 0&&(W=String(I.ax.checked)),RK({role:H,kind:j})&&(W="[redacted]");let X={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(X.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(X.selected=I.ax.selected),I.ax.expanded!==void 0&&(X.expanded=I.ax.expanded);let D;I.dom?.testId?D=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(D=`#${I.dom.id}`);let G={id:U,role:H,label:ITe(M),kind:j,value:W,state:X,bbox:q};return D!==void 0&&(G.selector=D),G}),_="idle";try{let I=await e.evaluate(()=>document.readyState);I==="loading"?_="loading":I==="interactive"?_="navigating":_="idle"}catch{_="navigating"}_!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let P=OTe(f),R=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:R,url:g,title:h,textSummary:P,interactive:E,status:{httpStatus:t.httpStatus??null,loadingState:_,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var jK,WK,KK=b(()=>{"use strict";Ew();jK=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);WK="a[href], button, input, select, textarea, [role], [tabindex], label"});async function GK(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 mP(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>GK(e,i)))).filter(o=>o!==null)}async function FTe(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 fP(e,t,n){switch(t.kind){case"element_id":return NTe(e,t,n);case"selector":return BTe(e,t);case"semantic":return UTe(e,t)}}async function NTe(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 mP(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function BTe(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 mP(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function UTe(e,t){return t.role!==void 0?jTe(e,t.text,t.role):HTe(e,t.text,t)}async function jTe(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 mP(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function HTe(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 FTe(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 y=p[h];if(y===void 0)continue;let w=await GK(y.locator,y.index);if(w!==null){let S=`${w.role}:${w.label}:${h}`,v=0;for(let x=0;x<S.length;x++)v=v*31+S.charCodeAt(x)>>>0;f.push({...w,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var qK=b(()=>{"use strict"});async function gP(e,t,n,r){let o=e.url();if(o===n)return null;let i=Ar(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 zK=b(()=>{"use strict";qi()});var yP={};Mn(yP,{PlaywrightProvider:()=>hP});function JK(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 hP,bP=b(()=>{"use strict";BK();KK();qK();qi();zK();lP();hP=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new _w(t)}async open(t){let n=Ar(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 gP(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 Pw(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 Pw(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 fP(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${JK(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(y){c=y}else c=h}let d=await gP(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 Pw(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 fP(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${JK(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 uu(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 uu(n,o,r);return i}catch{return null}}}});var Na={};Mn(Na,{__resetBrowserRegistryForTests:()=>JTe,browserProviderActive:()=>GTe,closeBrowserProvider:()=>SP,getBrowserProvider:()=>KTe,getLastRoutingDecision:()=>zTe,peekBrowserProvider:()=>qTe});function VK(){Promise.resolve(SP()).then(()=>{process.exit(130)})}function YK(){Promise.resolve(SP()).then(()=>{process.exit(143)})}function XK(){po=null}function WTe(){Iw||(process.on("SIGINT",VK),process.on("SIGTERM",YK),process.on("exit",XK),Iw=!0)}function QK(){Iw&&(process.removeListener("SIGINT",VK),process.removeListener("SIGTERM",YK),process.removeListener("exit",XK),Iw=!1)}async function KTe(e){return po!==null?po:(Fa!==null||(Fa=(async()=>{let t=oP(e),n=e?.surface??(e?.env??{}).AGENT_SURFACE??k.AGENT_SURFACE,r=await xK({config:t,surface:n});wP=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:i}=await Promise.resolve().then(()=>(DK(),$K)),s=r.availability.connection;o=new i(t,s)}else{let{PlaywrightProvider:i}=await Promise.resolve().then(()=>(bP(),yP));o=new i(t)}return WTe(),po=o,Fa=null,o})()),Fa)}async function SP(){if(po===null)return;let e=po;po=null,Fa=null,QK(),await e.shutdown()}function GTe(){return po!==null}function qTe(){return po}function zTe(){return wP}function JTe(){po=null,Fa=null,wP=null,QK()}var po,Fa,Iw,wP,Ba=b(()=>{"use strict";qi();EK();F();po=null,Fa=null,Iw=!1,wP=null});async function ZK(e,t){try{return await dK(e,t)}catch(n){return N("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function exe(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Ba(),Na)),r=await n();try{return await r.render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}catch(o){if(r.name==="agent-browser"){let{PlaywrightProvider:i}=await Promise.resolve().then(()=>(bP(),yP)),{loadBrowserConfig:s}=await Promise.resolve().then(()=>(qi(),iP)),a=s(),l=new i(a);try{return await l.render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}finally{await l.shutdown()}}throw o}}async function eG(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??exe,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let d=await Gi(n,e,{headers:ZTe,signal:t.signal},o);l=d.status,a=d.url||e;let p=d.headers.get("content-type")??"";if(d.ok){if(QTe.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(XTe.test(p)&&!YTe.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await ZK(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof Jt||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=eP({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...d!==void 0?{advisory:d}:{}}}try{await uf(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>uf(f,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await uf(d.finalUrl,o);let p=await ZK(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||p.textLength>=i.textLength){let f=eP({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 Jt)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 YTe,XTe,QTe,ZTe,tG=b(()=>{"use strict";pK();tP();Da();me();YTe=/(text\/html|application\/xhtml\+xml)/i,XTe=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,QTe=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,ZTe={"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 rxe(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(txe,{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),nxe),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let u=await i.text(),d=ae(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 nG(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?rxe({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 rG(e,t){if(t.length===0)return`# Search results for "${e}"
434
434
 
435
435
  (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(`
436
436
  `).trimEnd()}var txe,nxe,oG=b(()=>{"use strict";We();txe="https://api.exa.ai/search",nxe=10});function Mw(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 Ua=b(()=>{"use strict";Aw()});function cxe(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=oxe;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,ixe)}let a=sxe;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,axe)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function vP(e,t){return Buffer.byteLength(e,"utf8")<=t?{content:e,truncated:!1}:{content:Tr(e,t),truncated:!0}}function uxe(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=cxe(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 $a(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 Gi(t,s.url,h,r)}catch(h){return a.signal.aborted?{content:`web_scrape aborted: ${u()}`,isError:!0}:h instanceof Jt?{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=vP(f,s.maxBytes);return{content:g.content,...g.truncated?{truncated:!0}:{}}}if(s.mode==="markdown")try{let p=await eG(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=vP(mK(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 Jt)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),g=bn(p)&&!pP(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${df()}\`)`:"";return{content:`web_scrape markdown error: ${f}${g}`,isError:!0}}let d=nG({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:lxe,timeoutMs:s.timeoutMs,signal:a.signal}),f=vP(rG(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 oxe,ixe,sxe,axe,lxe,iG,sG=b(()=>{"use strict";tG();oG();Da();no();tP();Ua();oxe=3e4,ixe=12e4,sxe=1e5,axe=1e6,lxe=10;iG=uxe()});function mxe(e){return dxe.has(e)?"low":e==="DELETE"?"high":"medium"}function fxe(e){return pxe.has(e)}function yxe(e){let t={};return e.forEach((n,r)=>{let o=r.toLowerCase();hxe.has(o)||gxe.some(i=>o.startsWith(i))||(t[r]=n)}),t}function bxe(e,t){if(e==null)return{serialized:void 0,inferredContentType:void 0};let n=Object.keys(t).some(o=>o.toLowerCase()==="content-type");return typeof e=="string"?{serialized:e,inferredContentType:n?void 0:"text/plain"}:{serialized:JSON.stringify(e),inferredContentType:n?void 0:"application/json"}}function wxe(e,t,n){let r=Buffer.byteLength(e,"utf8"),o=e,i=!1;if(r>n&&(o=Tr(e,n),i=!0),!i&&/application\/json/i.test(t))try{return{body:JSON.parse(o),truncated:!1}}catch{}return{body:o,truncated:i}}async function cG(e){let{url:t,method:n,signal:r,domainCheck:o,recordEffect:i}=e,s=Math.min(e.maxResponseBytes??kP,TP),a={...e.headers},l=e.fetchFn??globalThis.fetch,c=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},u=mxe(n);if(o!==void 0){let R=o(t);if(!R.allowed)throw Object.assign(new Error(`web_request blocked by domain policy: ${R.reason}`),{name:"DomainPolicyError"})}let d=await $a(t,c);if(!d.allowed)throw new Jt(d.reason);let{serialized:p,inferredContentType:f}=bxe(e.body,a);f!==void 0&&(a["content-type"]=f);let g={method:n,headers:Object.keys(a).length>0?a:void 0,body:p,signal:r},y=fxe(n)?{retries:2,baseDelayMs:300,maxDelayMs:5e3}:{retries:0},w=Date.now(),S;try{S=await Gi(l,t,g,{...c,retry:y})}catch(R){throw R instanceof Jt,R}let v=Date.now()-w,x=S.headers.get("content-type")??"",T;try{let R=S.body?.getReader();if(!R)T="";else{let C=[],I=0,O=s*2;for(;;){let{done:H,value:M}=await R.read();if(H||!M)break;if(C.push(M),I+=M.byteLength,I>=O){await R.cancel();break}}T=new TextDecoder().decode(Buffer.concat(C,I))}}catch{T=""}let{body:E,truncated:_}=wxe(T,x,s),P=yxe(S.headers);return i!==void 0&&Promise.resolve(i({url:t,method:n,status:S.status,risk:u,timing_ms:v})).catch(()=>{}),{status:S.status,headers:P,body:E,truncated:_,timing_ms:v,risk:u}}function uG(e){if(typeof e!="string"||e.trim().length===0)return{error:"method must be a non-empty string (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS)"};let t=e.trim().toUpperCase(),n=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];return n.includes(t)?t:{error:`method "${e}" is not supported \u2014 must be one of: ${n.join(", ")}`}}var aG,lG,kP,TP,dxe,pxe,gxe,hxe,dG=b(()=>{"use strict";Da();no();aG=3e4,lG=12e4,kP=1e5,TP=1e6,dxe=new Set(["GET","HEAD","OPTIONS"]),pxe=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]);gxe=["set-cookie","x-"],hxe=new Set(["server","via","age","vary","authorization","www-authenticate"])});function Sxe(e){if(!e||typeof e!="object")return{error:"Invalid input: expected an object"};let t=e;if(typeof t.url!="string"||t.url.length===0)return{error:'Invalid input: "url" must be a non-empty string'};let n;try{n=new URL(t.url)}catch{return{error:`Invalid input: "${t.url}" is not a valid absolute URL`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{error:`Invalid input: protocol "${n.protocol}" not supported (http/https only)`};n.username="",n.password="";let r=n.toString(),o=uG(t.method);if(typeof o=="object"&&"error"in o)return{error:`Invalid input: ${o.error}`};let i=o,s;if(t.body!==void 0&&t.body!==null){if(typeof t.body!="string"&&typeof t.body!="object")return{error:'Invalid input: "body" must be a string, object, or array'};s=t.body}let a={};if(t.headers!==void 0){if(typeof t.headers!="object"||t.headers===null||Array.isArray(t.headers))return{error:'Invalid input: "headers" must be a string-keyed object'};let d=t.headers;for(let[p,f]of Object.entries(d)){if(typeof f!="string")return{error:`Invalid input: header value for "${p}" must be a string`};a[p]=f}}let l=aG;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'};l=Math.min(t.timeout_ms,lG)}let c=kP;if(t.max_response_bytes!==void 0){if(typeof t.max_response_bytes!="number"||!Number.isFinite(t.max_response_bytes)||t.max_response_bytes<=0)return{error:'Invalid input: "max_response_bytes" must be a positive finite number'};c=Math.min(t.max_response_bytes,TP)}let u;if(t.credential!==void 0){if(typeof t.credential!="string"||t.credential.length===0)return{error:'Invalid input: "credential" must be a non-empty string (an env var name)'};u=t.credential}return{url:r,method:i,body:s,headers:a,timeoutMs:l,maxResponseBytes:c,credential:u}}function vxe(e={}){let t=e.fetchFn??globalThis.fetch,n=e.env??process.env;async function r(){if(e.domainCheck!==void 0)return e.domainCheck;try{let{loadBrowserConfig:o,enforceDomainPolicy:i}=await Promise.resolve().then(()=>(qi(),iP)),s=o();return a=>i(a,s)}catch{return}}return async(o,i)=>{if(typeof t!="function")return{content:"web_request unavailable: global fetch() is not present (agent-afk requires Node 20+).",isError:!0};let s=Sxe(o);if("error"in s)return{content:s.error,isError:!0};if(i.aborted){let p=i.reason;return{content:`web_request aborted: ${p instanceof Error?p.message:String(p??"aborted")}`,isError:!0}}let a={...s.headers};if(s.credential!==void 0){let p=n[s.credential];if(p===void 0||p.trim().length===0)return{content:`web_request credential error: environment variable "${s.credential}" is not set. Set it in afk.env or export it in the shell before starting AFK.`,isError:!0};if(Object.keys(a).some(g=>g.toLowerCase()==="authorization"))return{content:'web_request credential error: both "credential" and an explicit Authorization header were provided. Use one or the other.',isError:!0};a.Authorization=`Bearer ${p}`}let l=new AbortController,c=()=>l.abort(i.reason),u,d=()=>{let p=l.signal.reason;return p instanceof Error?p.message:String(p??"aborted")};try{i.addEventListener("abort",c,{once:!0}),u=setTimeout(()=>{l.abort(new Error(`web_request timeout after ${s.timeoutMs}ms`))},s.timeoutMs);let p=await r(),f={url:s.url,method:s.method,body:s.body,headers:a,maxResponseBytes:s.maxResponseBytes,signal:l.signal,fetchFn:t,lookupFn:e.lookupFn,domainCheck:p,recordEffect:e.recordEffect},g;try{g=await cG(f)}catch(S){if(l.signal.aborted)return{content:`web_request aborted: ${d()}`,isError:!0};if(S instanceof Jt)return{content:`web_request blocked: ${S.message}`,isError:!0};let v=S instanceof Error&&S.name==="DomainPolicyError"?"blocked":"network error",x=S instanceof Error?S.message:String(S);return{content:`web_request ${v}: ${x}`,isError:!0}}if(l.signal.aborted)return{content:`web_request aborted: ${d()}`,isError:!0};let h=g.body;if(typeof h=="string")h=ut(h);else if(typeof h=="object"&&h!==null){let S=ut(JSON.stringify(h));try{h=JSON.parse(S)}catch{h=S}}let y={status:g.status,headers:g.headers,body:h,timing_ms:g.timing_ms,...g.truncated?{truncated:!0}:{}};return{content:JSON.stringify(y,null,2),...g.truncated?{truncated:!0}:{}}}finally{u!==void 0&&clearTimeout(u),i.removeEventListener("abort",c)}}}var pG,mG=b(()=>{"use strict";dG();Da();Sr();pG=vxe()});import{existsSync as gG,mkdirSync as kxe,readFileSync as Txe,renameSync as xxe,unlinkSync as Exe,writeFileSync as Rxe}from"node:fs";import{dirname as fG,join as Axe}from"node:path";import{randomBytes as Cxe}from"node:crypto";function Nn(e){let t=e??Cy();if(!gG(t))return[];try{let n=Txe(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 zi(e,t){let n=t??Cy();kxe(fG(n),{recursive:!0});let r=Axe(fG(n),`.schedules.json.${process.pid}.${Cxe(4).toString("hex")}.tmp`),o=JSON.stringify(e,null,2);try{Rxe(r,o,"utf-8"),xxe(r,n)}catch(i){try{gG(r)&&Exe(r)}catch{}throw i}}function Ow(e,t){let n=Nn(t),r=n.map(l=>l.id),o=_xe(e.name),i=Pxe(o,r),s=new Date().toISOString(),a={...e,notifyOn:e.notifyOn??"failure",id:i,createdAt:s,updatedAt:s};return n.push(a),zi(n,t),a}function $w(e,t){let n=Nn(t),r=n.length,o=n.filter(i=>i.id!==e);return o.length===r?!1:(zi(o,t),!0)}function pf(e,t){return Nn(t).find(n=>n.id===e)}function _xe(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function Pxe(e,t){if(!t.includes(e))return e;let n=2;for(;t.includes(`${e}-${n}`);)n+=1;return`${e}-${n}`}function Dw(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 Lw=b(()=>{"use strict";B()});import{existsSync as Ixe,readFileSync as Mxe}from"node:fs";import{join as Oxe}from"node:path";async function nr(e,t,n){let r,o;try{let i=Oxe(Zp("default"),"port");if(!Ixe(i))return{synced:!1,detail:"daemon-not-detected (no port file)"};let s=Mxe(i,"utf-8").trim(),a=$xe(s);if(!a)return{synced:!1,detail:"daemon-not-detected (invalid port file)"};({host:r,port:o}=a)}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let i=r.includes(":")?`[${r}]`:r,s=await fetch(`http://${i}:${o}${t}`,{method:e,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return s.ok?{synced:!0,detail:"synced"}:e==="POST"&&s.status===409?{synced:!0,detail:"already-registered"}:e==="DELETE"&&s.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${s.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}function $xe(e){let t=parseInt(e,10);if(String(t)===e&&!Number.isNaN(t))return t<1||t>65535?null:{host:"localhost",port:t};let n=e.lastIndexOf(":");if(n<1)return null;let r=e.slice(0,n),o=e.slice(n+1);if(!/^\d+$/.test(o))return null;let i=parseInt(o,10);return Number.isNaN(i)||i<1||i>65535||/^:+$/.test(r)?null:{host:r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r,port:i}}var Ji,xP=b(()=>{"use strict";B();Ji="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 Dxe}from"node:fs";import{readFile as Lxe}from"node:fs/promises";var hG,yG,bG,wG,SG=b(()=>{"use strict";Lw();B();xP();hG=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=Ow({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 nr("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 nr("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:Ji}})}},yG=async(e,t)=>{let n=Nn();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})))}},bG=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=br();if(!Dxe(i))return{content:JSON.stringify([])};let s;try{let c=await Lxe(i);s=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=s.split(`
@@ -1244,7 +1244,7 @@ On your first turn, decide whether to call memory_search based on the request:
1244
1244
  - If hot memory (shown in <cross-session-memory> tags above) already covers the relevant context, skip the search.
1245
1245
  - Search at most once per session for general context. Search again only if new information surfaces a specific topic worth querying.
1246
1246
 
1247
- Use FTS5 syntax: "exact phrase", term1 AND term2, prefix*.`});function $f(e,t){let n=(d,p)=>{if(!(d==null&&p==null))return(d??0)+(p??0)},r=(d,p)=>p!==void 0?p:d,o={stopReason:t.stopReason??e.stopReason??null,...t.raw!==void 0?{raw:t.raw}:e.raw!==void 0?{raw:e.raw}:{}},i=n(e.inputTokens,t.inputTokens);i!==void 0&&(o.inputTokens=i);let s=n(e.outputTokens,t.outputTokens);s!==void 0&&(o.outputTokens=s);let a=r(e.cachedInputTokens,t.cachedInputTokens);a!==void 0&&(o.cachedInputTokens=a);let l=r(e.cacheCreationTokens,t.cacheCreationTokens);l!==void 0&&(o.cacheCreationTokens=l);let c=n(e.totalTokens,t.totalTokens);c!==void 0&&(o.totalTokens=c);let u=n(e.totalCostUsd,t.totalCostUsd);return u!==void 0&&(o.totalCostUsd=u),o}var NI=b(()=>{"use strict"});function HS(){try{let e=Xa();return Promise.resolve(e.map(t=>{let n={name:t.name,description:t.description};return t.argumentHint&&(n.argumentHint=t.argumentHint),t.whenToUse&&(n.whenToUse=t.whenToUse),t.source&&(n.source=t.source),n}))}catch{return Promise.resolve([])}}var BI=b(()=>{"use strict";Ir()});function yo(e){return e!=null&&h_e.includes(e)}function y_e(e){switch(e){case"max_tokens":return'stop_reason "max_tokens"';case"length":return'finish_reason "length"';case"max_output_tokens":return'incomplete_details.reason "max_output_tokens"';default:return"the provider output-token cap"}}function WS(e,t,n={}){let r=`\u26A0 This turn was cut off at the output-token limit (${y_e(t)}) before the model finished \u2014 anything above is partial, not a complete answer.`;if(e.length>0){let o=[...new Set(e)].join(", "),i=n.canIncreaseOutputLimit===!1?"Continue in a follow-up turn or retry so the model can finish the action.":"Raise --max-output-tokens / AFK_MAX_OUTPUT_TOKENS, then retry.";return`${r} A tool call was truncated mid-request and was NOT dispatched (${o}); that action did not run. ${i}`}return n.canIncreaseOutputLimit===!1?`${r} Continue in a follow-up turn or retry the request.`:`${r} Raise --max-output-tokens / AFK_MAX_OUTPUT_TOKENS to allow a longer reply.`}var h_e,Df=b(()=>{"use strict";h_e=["max_tokens","length","max_output_tokens"]});var Ru,UI=b(()=>{"use strict";fe();Ru=class{constructor(t,n,r){this.signal=t;this.traceWriter=n;this.provider=r;oe(n,{phase:"loop_start"}),this.interruptedAt=t.aborted?Date.now():null,n&&!t.aborted&&t.addEventListener("abort",this.onInterrupt,{once:!0})}signal;traceWriter;provider;interruptedAt;onInterrupt=()=>{this.interruptedAt===null&&(this.interruptedAt=Date.now())};finish(t){this.signal.removeEventListener("abort",this.onInterrupt),this.interruptedAt!==null&&this.signal.reason==="interrupted"&&oe(this.traceWriter,{phase:"interrupt_halt",durationMs:Date.now()-this.interruptedAt,metadata:{provider:this.provider}}),oe(this.traceWriter,{phase:"loop_end",durationMs:t})}}});import{readFileSync as b_e}from"node:fs";import{homedir as w_e}from"node:os";import{join as Dz}from"node:path";function S_e(e){try{return b_e(e,"utf-8")}catch{return null}}function bo(e,t={},n=!1){let r=t.readEnv??(u=>process.env[u]),o=(t.homedir??w_e)(),i=t.readFile??S_e;if(n){let u=Dz(o,".codex","auth.json"),d=i(u);if(d!==null){let p=Lz(d);if(p.kind==="chatgpt"&&p.accessToken){if(p.expiresAt!==void 0&&p.expiresAt<=Math.floor(Date.now()/1e3))return{apiKey:null,source:"chatgpt-oauth-expired",expiresAt:p.expiresAt};let f={apiKey:p.accessToken,source:"chatgpt-oauth",last4:Au(p.accessToken)};return p.accountId!==void 0&&(f.accountId=p.accountId),p.expiresAt!==void 0&&(f.expiresAt=p.expiresAt),f}}return{apiKey:null,source:"no-usable-auth-forced-chatgpt-oauth"}}if(e&&e.length>0)return{apiKey:e,source:"config",last4:Au(e)};let s=r("OPENAI_API_KEY");if(s&&s.length>0)return{apiKey:s,source:"env",last4:Au(s),envVar:"OPENAI_API_KEY"};let a=r("CODEX_API_KEY");if(a&&a.length>0)return{apiKey:a,source:"env",last4:Au(a),envVar:"CODEX_API_KEY"};let l=Dz(o,".codex","auth.json"),c=i(l);if(c!==null){let u=Lz(c);if(u.kind==="apikey")return{apiKey:u.apiKey,source:"codex-cli",last4:Au(u.apiKey)};if(u.kind==="chatgpt"){if(v_e(r)&&u.accessToken){if(u.expiresAt!==void 0&&u.expiresAt<=Math.floor(Date.now()/1e3))return{apiKey:null,source:"chatgpt-oauth-expired",expiresAt:u.expiresAt};let d={apiKey:u.accessToken,source:"chatgpt-oauth",last4:Au(u.accessToken)};return u.accountId!==void 0&&(d.accountId=u.accountId),u.expiresAt!==void 0&&(d.expiresAt=u.expiresAt),d}return{apiKey:null,source:"no-usable-auth-codex-oauth"}}}return{apiKey:null,source:"no-usable-auth"}}function Lz(e){let t;try{t=JSON.parse(e)}catch{return{kind:"invalid"}}if(typeof t!="object"||t===null)return{kind:"invalid"};let n=t,r=n.OPENAI_API_KEY;if(typeof r=="string"&&r.length>0)return{kind:"apikey",apiKey:r};let o=n.tokens,i=typeof o=="object"&&o!==null?o:null,s=i&&typeof i.access_token=="string"?i.access_token:void 0;if(n.auth_mode==="chatgpt"||s){let a={kind:"chatgpt"};if(s&&(a.accessToken=s),i){let l=k_e(i);l!==void 0&&(a.accountId=l);let c=T_e(i);c!==void 0&&(a.expiresAt=c)}return a}return{kind:"no-key"}}function Au(e){return e.length<=4?e:e.slice(-4)}function v_e(e){let t=e("AFK_OPENAI_CHATGPT_OAUTH");if(!t)return!1;let n=t.trim().toLowerCase();return n==="1"||n==="true"||n==="yes"||n==="on"}function Fz(e){let t=e.split(".");if(t.length<2||!t[1])return null;try{let n=Buffer.from(t[1],"base64url").toString("utf-8"),r=JSON.parse(n);return typeof r=="object"&&r!==null?r:null}catch{return null}}function k_e(e){let t=e.account_id;if(typeof t=="string"&&t.length>0)return t;for(let n of["access_token","id_token"]){let r=e[n];if(typeof r!="string")continue;let o=Fz(r);if(!o)continue;let i=o["https://api.openai.com/auth"];if(typeof i=="object"&&i!==null){let a=i.chatgpt_account_id;if(typeof a=="string"&&a.length>0)return a}let s=o.chatgpt_account_id;if(typeof s=="string"&&s.length>0)return s}}function T_e(e){let t=e.access_token;if(typeof t!="string")return;let n=Fz(t)?.exp;return typeof n=="number"?n:void 0}function x_e(e){if(typeof e!="number")return"";let t=e-Math.floor(Date.now()/1e3);if(t<=0)return", EXPIRED \u2014 re-run `codex` to refresh";let n=Math.floor(t/3600),r=Math.floor(t%3600/60);return`, expires in ${n>0?`${n}h `:""}${r}m`}function Lf(e){switch(e.source){case"config":return`using explicit AFK config API key (\u2026${e.last4??"????"})`;case"env":return`using ${e.envVar??"OPENAI_API_KEY"} env var (\u2026${e.last4??"????"})`;case"codex-cli":return`using Codex CLI API key from ~/.codex/auth.json (\u2026${e.last4??"????"})`;case"chatgpt-oauth":{let t=e.accountId?`\u2026${e.accountId.slice(-4)}`:"unknown",n=x_e(e.expiresAt);return`using ChatGPT subscription OAuth from ~/.codex/auth.json (account ${t}${n})`}case"chatgpt-oauth-expired":return"ChatGPT subscription token from ~/.codex/auth.json is EXPIRED \u2014 re-run `codex` to refresh. (read-only; AFK does not refresh the token itself.)";case"no-usable-auth-codex-oauth":return"Found ChatGPT/OAuth credentials in ~/.codex/auth.json but the OpenAI provider is in API-key mode. To use your ChatGPT subscription, set AFK_OPENAI_CHATGPT_OAUTH=1 (read-only; AFK will not refresh the token \u2014 re-run `codex` when it expires). Otherwise run `codex login --api-key` or set OPENAI_API_KEY.";case"no-usable-auth-forced-chatgpt-oauth":return"This model's slot is configured provider: 'chatgpt-oauth' but no ChatGPT-subscription token was found in ~/.codex/auth.json. Sign in with `codex` using ChatGPT (not API-key mode), or change the slot to provider: 'openai' with a key. (read-only; AFK will not refresh the token \u2014 re-run `codex` when it expires).";default:return"No OpenAI auth found. Set OPENAI_API_KEY, pass an explicit apiKey in AFK config, or run `codex login --api-key`."}}var Cu=b(()=>{"use strict"});function KS(e,t,n){let r=e.lastIndexOf(Nz);if(r===-1)return e;let o=e.indexOf(`
1247
+ Use FTS5 syntax: "exact phrase", term1 AND term2, prefix*.`});function $f(e,t){let n=(d,p)=>{if(!(d==null&&p==null))return(d??0)+(p??0)},r=(d,p)=>p!==void 0?p:d,o={stopReason:t.stopReason??e.stopReason??null,...t.raw!==void 0?{raw:t.raw}:e.raw!==void 0?{raw:e.raw}:{}},i=n(e.inputTokens,t.inputTokens);i!==void 0&&(o.inputTokens=i);let s=n(e.outputTokens,t.outputTokens);s!==void 0&&(o.outputTokens=s);let a=r(e.cachedInputTokens,t.cachedInputTokens);a!==void 0&&(o.cachedInputTokens=a);let l=r(e.cacheCreationTokens,t.cacheCreationTokens);l!==void 0&&(o.cacheCreationTokens=l);let c=n(e.totalTokens,t.totalTokens);c!==void 0&&(o.totalTokens=c);let u=n(e.totalCostUsd,t.totalCostUsd);return u!==void 0&&(o.totalCostUsd=u),o}var NI=b(()=>{"use strict"});function HS(){try{let e=Xa();return Promise.resolve(e.map(t=>{let n={name:t.name,description:t.description};return t.argumentHint&&(n.argumentHint=t.argumentHint),t.whenToUse&&(n.whenToUse=t.whenToUse),t.source&&(n.source=t.source),n}))}catch{return Promise.resolve([])}}var BI=b(()=>{"use strict";Ir()});function yo(e){return e!=null&&h_e.includes(e)}function y_e(e){switch(e){case"max_tokens":return'stop_reason "max_tokens"';case"length":return'finish_reason "length"';case"max_output_tokens":return'incomplete_details.reason "max_output_tokens"';default:return"the provider output-token cap"}}function WS(e,t,n={}){let r=`\u26A0 This turn was cut off at the output-token limit (${y_e(t)}) before the model finished \u2014 anything above is partial, not a complete answer.`;if(e.length>0){let o=[...new Set(e)].join(", "),i=n.canIncreaseOutputLimit===!1?"Continue in a follow-up turn or retry so the model can finish the action.":"Raise --max-output-tokens / AFK_MAX_OUTPUT_TOKENS, then retry.";return`${r} A tool call was truncated mid-request and was NOT dispatched (${o}); that action did not run. ${i}`}return n.canIncreaseOutputLimit===!1?`${r} Continue in a follow-up turn or retry the request.`:`${r} Raise --max-output-tokens / AFK_MAX_OUTPUT_TOKENS to allow a longer reply.`}var h_e,Df=b(()=>{"use strict";h_e=["max_tokens","length","max_output_tokens"]});var Ru,UI=b(()=>{"use strict";fe();Ru=class{constructor(t,n,r){this.signal=t;this.traceWriter=n;this.provider=r;oe(n,{phase:"loop_start"}),this.interruptedAt=t.aborted?Date.now():null,n&&!t.aborted&&t.addEventListener("abort",this.onInterrupt,{once:!0})}signal;traceWriter;provider;interruptedAt;onInterrupt=()=>{this.interruptedAt===null&&(this.interruptedAt=Date.now())};finish(t){this.signal.removeEventListener("abort",this.onInterrupt),this.interruptedAt!==null&&this.signal.reason==="interrupted"&&oe(this.traceWriter,{phase:"interrupt_halt",durationMs:Date.now()-this.interruptedAt,metadata:{provider:this.provider}}),oe(this.traceWriter,{phase:"loop_end",durationMs:t})}}});import{readFileSync as b_e}from"node:fs";import{homedir as w_e}from"node:os";import{join as Dz}from"node:path";function S_e(e){try{return b_e(e,"utf-8")}catch{return null}}function bo(e,t={},n=!1){let r=t.readEnv??(u=>process.env[u]),o=(t.homedir??w_e)(),i=t.readFile??S_e;if(n){let u=Dz(o,".codex","auth.json"),d=i(u);if(d!==null){let p=Lz(d);if(p.kind==="chatgpt"&&p.accessToken){if(p.expiresAt!==void 0&&p.expiresAt<=Math.floor(Date.now()/1e3))return{apiKey:null,source:"chatgpt-oauth-expired",expiresAt:p.expiresAt};let f={apiKey:p.accessToken,source:"chatgpt-oauth",last4:Au(p.accessToken)};return p.accountId!==void 0&&(f.accountId=p.accountId),p.expiresAt!==void 0&&(f.expiresAt=p.expiresAt),f}}return{apiKey:null,source:"no-usable-auth-forced-chatgpt-oauth"}}if(e&&e.length>0)return{apiKey:e,source:"config",last4:Au(e)};let s=r("OPENAI_API_KEY");if(s&&s.length>0)return{apiKey:s,source:"env",last4:Au(s),envVar:"OPENAI_API_KEY"};let a=r("CODEX_API_KEY");if(a&&a.length>0)return{apiKey:a,source:"env",last4:Au(a),envVar:"CODEX_API_KEY"};let l=Dz(o,".codex","auth.json"),c=i(l);if(c!==null){let u=Lz(c);if(u.kind==="apikey")return{apiKey:u.apiKey,source:"codex-cli",last4:Au(u.apiKey)};if(u.kind==="chatgpt"){if(v_e(r)&&u.accessToken){if(u.expiresAt!==void 0&&u.expiresAt<=Math.floor(Date.now()/1e3))return{apiKey:null,source:"chatgpt-oauth-expired",expiresAt:u.expiresAt};let d={apiKey:u.accessToken,source:"chatgpt-oauth",last4:Au(u.accessToken)};return u.accountId!==void 0&&(d.accountId=u.accountId),u.expiresAt!==void 0&&(d.expiresAt=u.expiresAt),d}return{apiKey:null,source:"no-usable-auth-codex-oauth"}}}return{apiKey:null,source:"no-usable-auth"}}function Lz(e){let t;try{t=JSON.parse(e)}catch{return{kind:"invalid"}}if(typeof t!="object"||t===null)return{kind:"invalid"};let n=t,r=n.OPENAI_API_KEY;if(typeof r=="string"&&r.length>0)return{kind:"apikey",apiKey:r};let o=n.tokens,i=typeof o=="object"&&o!==null?o:null,s=i&&typeof i.access_token=="string"?i.access_token:void 0;if(n.auth_mode==="chatgpt"||s){let a={kind:"chatgpt"};if(s&&(a.accessToken=s),i){let l=k_e(i);l!==void 0&&(a.accountId=l);let c=T_e(i);c!==void 0&&(a.expiresAt=c)}return a}return{kind:"no-key"}}function Au(e){return e.length<=4?e:e.slice(-4)}function v_e(e){let t=e("AFK_OPENAI_CHATGPT_OAUTH");if(!t)return!0;let n=t.trim().toLowerCase();return!(n==="0"||n==="false"||n==="no"||n==="off")}function Fz(e){let t=e.split(".");if(t.length<2||!t[1])return null;try{let n=Buffer.from(t[1],"base64url").toString("utf-8"),r=JSON.parse(n);return typeof r=="object"&&r!==null?r:null}catch{return null}}function k_e(e){let t=e.account_id;if(typeof t=="string"&&t.length>0)return t;for(let n of["access_token","id_token"]){let r=e[n];if(typeof r!="string")continue;let o=Fz(r);if(!o)continue;let i=o["https://api.openai.com/auth"];if(typeof i=="object"&&i!==null){let a=i.chatgpt_account_id;if(typeof a=="string"&&a.length>0)return a}let s=o.chatgpt_account_id;if(typeof s=="string"&&s.length>0)return s}}function T_e(e){let t=e.access_token;if(typeof t!="string")return;let n=Fz(t)?.exp;return typeof n=="number"?n:void 0}function x_e(e){if(typeof e!="number")return"";let t=e-Math.floor(Date.now()/1e3);if(t<=0)return", EXPIRED \u2014 re-run `codex` to refresh";let n=Math.floor(t/3600),r=Math.floor(t%3600/60);return`, expires in ${n>0?`${n}h `:""}${r}m`}function Lf(e){switch(e.source){case"config":return`using explicit AFK config API key (\u2026${e.last4??"????"})`;case"env":return`using ${e.envVar??"OPENAI_API_KEY"} env var (\u2026${e.last4??"????"})`;case"codex-cli":return`using Codex CLI API key from ~/.codex/auth.json (\u2026${e.last4??"????"})`;case"chatgpt-oauth":{let t=e.accountId?`\u2026${e.accountId.slice(-4)}`:"unknown",n=x_e(e.expiresAt);return`using ChatGPT subscription OAuth from ~/.codex/auth.json (account ${t}${n})`}case"chatgpt-oauth-expired":return"ChatGPT subscription token from ~/.codex/auth.json is EXPIRED \u2014 re-run `codex` to refresh. (read-only; AFK does not refresh the token itself.)";case"no-usable-auth-codex-oauth":return"Found ChatGPT/OAuth credentials in ~/.codex/auth.json but the OpenAI provider is in API-key mode. To use your ChatGPT subscription, set AFK_OPENAI_CHATGPT_OAUTH=1 (read-only; AFK will not refresh the token \u2014 re-run `codex` when it expires). Otherwise run `codex login --api-key` or set OPENAI_API_KEY.";case"no-usable-auth-forced-chatgpt-oauth":return"This model's slot is configured provider: 'chatgpt-oauth' but no ChatGPT-subscription token was found in ~/.codex/auth.json. Sign in with `codex` using ChatGPT (not API-key mode), or change the slot to provider: 'openai' with a key. (read-only; AFK will not refresh the token \u2014 re-run `codex` when it expires).";default:return"No OpenAI auth found. Set OPENAI_API_KEY, pass an explicit apiKey in AFK config, or run `codex login --api-key`."}}var Cu=b(()=>{"use strict"});function KS(e,t,n){let r=e.lastIndexOf(Nz);if(r===-1)return e;let o=e.indexOf(`
1248
1248
  `,r+Nz.length);if(o===-1)return e;let i=o+1;if(!e.startsWith(jI,i))return e;let s=e.indexOf(`
1249
1249
  `,i),a=s===-1?e.length:s,l=e.slice(i+jI.length,a),c=jb(t??new Date,n);return l===c?e:e.slice(0,i+jI.length)+c+e.slice(a)}var Nz,jI,HI=b(()=>{"use strict";zt();Nz=`# Environment
1250
1250
  - Working directory: `,jI="- Date: "});function E_e(e,t){let n=t===1?"An image was":`${t} images were`,r=t===1?"an image":"images",o=t===1?"it":"them",i=e&&e.trim().length>0?`the current model ("${e.trim()}")`:"the current model";return`[${n} attached to this message, but ${i} cannot view images. Acknowledge to the user that you received ${r} but are unable to see ${o}, and suggest switching to a vision-capable model (e.g. gpt-4o or a Claude model).]`}function R_e(e){let t=e.source;return t.type==="base64"?`data:${t.media_type};base64,${t.data}`:t.type==="url"?t.url:null}function Bz(e,t){if(typeof e=="string")return e;let n=[],r=0;for(let s of e)if(typeof s=="object"&&s&&"type"in s){if(s.type==="text")n.push(s.text);else if(s.type==="image")r+=1;else if(s.type==="document"){let a=s,l=a.title??"document",c=a.source;if(c&&c.type==="text")n.push(`[Document: ${l}]
@@ -1269,7 +1269,7 @@ ${o}`:o}function C_e(e){let t=e.systemPrompt;if(t!==void 0){if(typeof t=="string
1269
1269
 
1270
1270
  `));let i=Y_e(t);return i.length>0&&(o.tools=i),o}function V_e(e){if(e===null)return"";if(typeof e=="string")return e;let t=[];for(let n of e)n.type==="text"?t.push({type:"input_text",text:n.text}):t.push({type:"input_image",image_url:n.image_url.url,detail:"auto"});return t}function Y_e(e){return!e||e.length===0?[]:e.map(t=>{let n={type:"function",name:t.function.name,parameters:t.function.parameters};return t.function.description!==void 0&&(n.description=t.function.description),n})}var pJ=b(()=>{"use strict"});function Kf(e,t){let n=Sa(e);if(typeof t=="number"&&Number.isFinite(t)&&t>0){let r=Math.floor(t),o=xC(e);if(o!==void 0&&r>o){let i=`max:${e}:${r}`;return mJ.has(i)||(mJ.add(i),console.warn(`[afk] maxOutputTokens ${r} exceeds the ${e} output ceiling (${o}); clamping to ${o}.`)),o}return r}return n}function fJ(e,t){let n=Kf(e,t);return bm(e)?{max_completion_tokens:n}:{max_tokens:n}}function nM(e){return e??"default"}function gJ(e){switch(e){case"low":return"low";case"medium":return"medium";case"high":case"xhigh":case"max":return"high"}}function ZS(e,t){if(e!==void 0&&bm(t))return gJ(e)}var mJ,Gf=b(()=>{"use strict";vr();wa();mJ=new Set});function ev(e){let t=dJ(e.messages,e.activeTools),n={model:e.model,input:t.input,stream:!0};e.isChatGptBackend||(n.max_output_tokens=Kf(e.model,e.maxOutputTokens));let r=t.instructions??(e.isChatGptBackend?eJ:void 0);r!==void 0&&(n.instructions=r),e.isChatGptBackend&&(n.store=!1),t.tools&&t.tools.length>0&&(n.tools=t.tools);let o=ZS(e.effort,e.model);return o!==void 0&&(n.reasoning={effort:o}),e.temperature!==void 0&&(n.temperature=e.temperature),n}function hJ(e){let t={model:e.model,messages:e.messages,stream:!0,stream_options:{include_usage:!0}};Object.assign(t,fJ(e.model,e.maxOutputTokens)),e.activeTools&&e.activeTools.length>0&&(t.tools=e.activeTools);let n=ZS(e.effort,e.model);return n!==void 0&&(t.reasoning_effort=n),e.temperature!==void 0&&(t.temperature=e.temperature),t}var rM=b(()=>{"use strict";pJ();YS();Gf()});async function*$u(e,t){if(t.aborted)throw yJ(t);let n=e[Symbol.asyncIterator](),r=!1,o=Symbol("aborted"),i,s=new Promise(a=>{i=()=>a(o),t.addEventListener("abort",i,{once:!0})});try{for(;;){let a=n.next(),l=await Promise.race([a,s]);if(l===o)throw Promise.resolve(a).catch(()=>{}),r=!0,yJ(t);if(l.done)return;yield l.value}}finally{t.removeEventListener("abort",i);let a=Promise.resolve(n.return?.()).catch(()=>{});r||await a}}function yJ(e){let t=e.reason;if(t instanceof Error)return t;let n=new Error(typeof t=="string"&&t.length>0?t:"The operation was aborted");return n.name="AbortError",n}var tv=b(()=>{"use strict"});import X_e from"openai";async function nv(e){let{apiKey:t,baseURL:n,defaultHeaders:r,model:o,system:i,user:s,maxTokens:a=64,signal:l,clientFactory:c}=e,u;if(e.client!==void 0)u=e.client;else{let g=bo(t,{},e.forceChatgptOAuth??!1);if(g.apiKey===null)throw new Error("oneShotChatCompletion: no usable OpenAI auth (set OPENAI_API_KEY or pass apiKey)");let h={apiKey:g.apiKey};n!==void 0&&(h.baseURL=n),r!==void 0&&(h.defaultHeaders=r);let y=c??Q_e;u=y?y(h):new X_e(h)}let d=bm(o)?{max_completion_tokens:a}:{max_tokens:a},f=(await u.chat.completions.create({model:o,...d,stream:!1,messages:[{role:"system",content:i},{role:"user",content:s}]},l?{signal:l}:void 0)).choices?.[0]?.message?.content;return typeof f=="string"?f.trim():""}async function bJ(e){let{client:t,model:n,system:r,user:o,isChatGptBackend:i,maxTokens:s=1024,signal:a}=e,c=ev({model:n,messages:[{role:"system",content:r},{role:"user",content:o}],activeTools:void 0,maxOutputTokens:s,effort:void 0,temperature:void 0,isChatGptBackend:i}),u=await t.responses.create(c,a?{signal:a}:void 0),d=a?$u(u,a):u,p=zS(),f=!1;for await(let g of d){g.type==="response.completed"&&(f=!0);let h=JS(g,p,"compact-oneshot");for(;!h.next().done;);}if(!f)throw new qf(p.finishReason);return p.assistantText.trim()}var qf,Q_e,rv=b(()=>{"use strict";Cu();wa();rM();Nf();zI();tv();qf=class extends Error{constructor(n){super(`responses summarize did not complete (terminal status: ${n??"none"})`);this.finishReason=n;this.name="ResponsesSummaryIncompleteError"}finishReason},Q_e=null});function oM(e){return Z_e*Math.pow(2,e)}function iM(e){let t=rs(e);if(t!==void 0)return Math.min(t,ePe)}function as(e){if(e===null||typeof e!="object")return;let t=e;return typeof t.status=="number"?t.status:void 0}function ov(e){let t=as(e);return t===void 0?!1:wJ.has(t)}function iv(e){let t=as(e);return t===void 0?!1:wJ.has(t)}var wJ,SJ,vJ,Z_e,ePe,Du=b(()=>{"use strict";TI();wJ=new Set([429,500,502,503,529]),SJ=3,vJ=3,Z_e=2e3;ePe=12e4});function sM(e){return e!=="plan"?null:{type:"text",text:sv}}var sv,aM=b(()=>{"use strict";sv=["## Plan mode is active","","File and memory write tools (`write_file`, `edit_file`, `memory_update`, `procedure_write`) are refused at the hook layer.","`bash` runs for read-only investigation (git status/log/diff, ls, cat, grep, find \u2014 chained or not); state-mutating bash (file writes, rm, installs, commits, pushes) is refused while planning. The user has asked you to plan, not yet to act \u2014 exit plan mode to make changes.","Treat this turn as planning work.","","Traverse the shape that matches the work \u2014 skip steps the terrain already covers, do not skip steps the terrain hides:",""," unknown field \u2192 ground the current terrain \u2192 gather missing codebase context \u2192"," research missing external context \u2192 reveal chaos / constraints / risks \u2192"," name the failure geometry \u2192 form a candidate plan \u2192 apply adversarial pressure \u2192 embody the final plan","","Reach for these skills (invoke via the `skill` tool) when the cost of skipping exceeds the cost of dispatching:"," - `ground-state` \u2014 survey git, infra, memory before non-trivial work"," - `gather` \u2014 parallel context-gathering for a code area"," - `research` \u2014 parallel external + local context for the current task"," - `devils-advocate` \u2014 generate alternatives and rank them before committing"," - `shadow-verify` \u2014 independently re-derive load-bearing claims","","Do not declare readiness silently. When the plan is ready, state: chosen approach, risks named, and alternatives considered.","","Then, IF the task requires implementation (writing code or files), call the `exit_plan_mode` tool to present your plan. The user picks how to proceed (approve and implement, or keep planning). After calling it, END YOUR TURN \u2014 on approval you will receive a separate instruction to save the plan to a file and implement it. Do NOT use `ask_question` to ask whether the plan is OK; that is exactly what `exit_plan_mode` does \u2014 use `ask_question` only to resolve open requirement questions first. For research / read-only tasks that need no code changes, do NOT call `exit_plan_mode` \u2014 just answer.","","Manual fallbacks remain: the user can exit with `/plan off` (same save-and-implement handoff), and Shift+Tab advances the permission-mode ring without saving or implementing. Keep the plan concrete and complete enough to act on directly."].join(`
1271
1271
  `)});function lM(e){return e!=="autonomous"?null:{type:"text",text:av}}var av,cM=b(()=>{"use strict";av=["## AFK mode is active","","The operator is away from keyboard. Your channel to them is Telegram via the `send_telegram` tool \u2014 not this transcript, which no one is watching live. At the end of each turn, push your terminal state (Done / Blocked / Asking) to Telegram so the operator can review asynchronously.","","Posture \u2014 bounded autonomy, not unchecked action:"," - Proceed autonomously on reversible work. Do not stop to confirm actions you are already authorized to take and can undo (edits, reads, tests, local commits, non-force pushes, installs)."," - At a one-way door \u2014 anything irreversible, externally visible, credential- or payment-touching, or where multiple readings lead to materially different work \u2014 do NOT guess. Push a concise Asking summary to Telegram naming the decision and your recommended default, then stop and end the turn in the Asking state."," - A mechanical gate refuses high-risk and irreversible operations at the hook layer regardless of this text. Treat a gate refusal as a signal to surface the decision to the operator, not an obstacle to work around.","","Communication discipline:"," - Batch updates. Send a Telegram message at terminal state (and at a genuinely blocking fork), not a play-by-play \u2014 the operator gets a push notification for every message."," - Keep pushes short and scannable: what happened, what changed, what (if anything) you need. Never paste raw tool output, logs, secrets, or full file contents into a push.","","Exit: the operator returns and runs `/afk off` (or Shift+Tab) to restore default permissions and terminal-channel interaction."].join(`
1272
- `)});function ls(e,t){if(!t||typeof t!="object")return"";let n=t;if(e==="skill"||e==="Skill"){let s=n.name;return typeof s=="string"&&s.length>0?`(${s.length>60?s.slice(0,59)+"\u2026":s})`:""}let r=n.file_path??n.path??n.filePath;if(typeof r=="string")return" "+r;let o=n.command??n.cmd;if(typeof o=="string"){let s=ut(o.replace(/\\\r?\n/g," ").replace(/\s+/g," ").trim());return" "+(s.length>kJ?s.slice(0,kJ-1)+"\u2026":s)}let i=n.query??n.pattern??n.url??n.description;return typeof i=="string"?" "+i:""}var kJ,zf=b(()=>{"use strict";Sr();kJ=160});function lv(e){if(!e||typeof e!="object")return;let t=e,n={};for(let r of tPe){let o=t[r];o!==void 0&&(n[r]=typeof o=="string"&&o.length>TJ?o.slice(0,TJ):o)}return Object.keys(n).length>0?JSON.stringify(n):void 0}function cv(e){if(!e||typeof e!="object")return;let t=e;if(Object.keys(t).length===0)return;let n={};for(let[r,o]of Object.entries(t))if(typeof o=="string"){let i=o.length>xJ?o.slice(0,xJ):o;n[r]=ut(i)}else o!=null&&typeof o!="object"&&(n[r]=o);return Object.keys(n).length>0?JSON.stringify(n):void 0}var tPe,TJ,xJ,uM=b(()=>{"use strict";Sr();tPe=["file_path","name","id_prefix"],TJ=4096,xJ=8192});import{createHash as nPe}from"crypto";function uv(e){let{toolUseId:t,name:n,input:r,subagentId:o}=e,i=r??{},s=JSON.stringify(i),a=JSON.stringify(rPe(n,i));return{phase:"started",toolUseId:t,name:n,inputBytes:Buffer.byteLength(s,"utf8"),argsFingerprint:nPe("sha256").update(a).digest("hex"),...o!==void 0?{subagentId:o}:{}}}function rPe(e,t){if(typeof t!="object"||t===null)return t;let n=t;switch(e){case"browser_act":return n.action==="fill"&&"value"in n?{...n,value:"[REDACTED]"}:t;case"config_set":return n.target==="env"&&"value"in n?{...n,value:"[REDACTED]"}:t;default:return t}}function dv(e){let{toolUseId:t,name:n,result:r,truncated:o,durationMs:i,subagentId:s}=e;return{phase:"completed",toolUseId:t,name:n,resultBytes:Buffer.byteLength(r.content,"utf8"),isError:r.isError===!0,truncated:o,durationMs:i,...r.incomplete===!0?{incomplete:!0}:{},...r.incompleteReason?{incompleteReason:r.incompleteReason}:{},...r.circuitBreaker===!0?{circuitBreaker:!0}:{},...r.failureClass?{failureClass:r.failureClass}:{},...typeof r.batchIndex=="number"&&typeof r.batchSize=="number"?{batchIndex:r.batchIndex,batchSize:r.batchSize}:{},...s!==void 0?{subagentId:s}:{},...r.testResult!==void 0?{testResult:r.testResult}:{}}}var pv=b(()=>{"use strict"});async function*mv(e){let t=[],n=!1,r=null,o=()=>{let c=r;r=null,c?.()},a=e(c=>{n||(t.push(c),o())}).finally(()=>{n=!0,o()}).then(c=>({ok:!0,value:c}),c=>({ok:!1,error:c}));for(;;){for(;t.length>0;)yield t.shift();if(n)break;await new Promise(c=>{r=c})}let l=await a;if(!l.ok)throw l.error;return l.value}var dM=b(()=>{"use strict"});import{randomUUID as oPe}from"node:crypto";async function*EJ({state:e,signal:t,vision:n,toolDispatcher:r,traceWriter:o,priorTurns:i,sessionId:s,subagentId:a}){if(!r)return void 0;let l=Ff(e);for(let g of l)g.id.length===0&&(g.id=oPe());let{calls:c,parseErrors:u}=Yz(l,t),d=new Map;for(let g of c){let h=Date.now();d.set(g.id,h),pa(o,uv({toolUseId:g.id,name:g.name,input:g.input,subagentId:a})),yield{type:"tool.use.start",toolUseId:g.id,toolName:g.name,toolInput:ls(g.name,g.input),toolInputRaw:lv(g.input),toolInputCapture:k.AFK_CAPTURE_SUBAGENT_OUTPUT==="1"?cv(g.input):void 0,sessionId:s}}let p=[];if(t.aborted){let g=rn(t);for(let h of c){let y={content:"Tool call aborted",isError:!0,failureClass:g};p.push({call:h,result:y}),yield{type:"tool.output",toolUseId:h.id,toolName:h.name,content:y.content,isError:!0,failureClass:g,sessionId:s}}}else{let g;try{if(r.executeBatch)g=yield*mv(h=>r.executeBatch(c,y=>{h({type:"tool.activity",activeCount:y.length,activeToolUseIds:[...y],sessionId:s})}));else{g=[];for(let h of c){if(t.aborted){g.push({content:"Tool call aborted",isError:!0,failureClass:rn(t)});continue}try{g.push(await r.execute(h))}catch(y){let w=y instanceof Error?y.message:String(y);g.push({content:`Tool execution threw: ${w}`,isError:!0})}}}}catch(h){let y=h instanceof Error?h.message:String(h);g=c.map(()=>({content:`Tool batch execution failed: ${y}`,isError:!0}))}for(let h=0;h<c.length;h++){let y=c[h],w=g[h],S=u.get(y.id);S!==void 0&&(w={content:`${S}
1272
+ `)});function ls(e,t){if(!t||typeof t!="object")return"";let n=t;if(e==="skill"||e==="Skill"){let s=n.name;return typeof s=="string"&&s.length>0?`(${s.length>60?s.slice(0,59)+"\u2026":s})`:""}let r=n.file_path??n.path??n.filePath;if(typeof r=="string")return" "+r;let o=n.command??n.cmd;if(typeof o=="string"){let s=ut(o.replace(/\\\r?\n/g," ").replace(/\s+/g," ").trim());return" "+(s.length>kJ?s.slice(0,kJ-1)+"\u2026":s)}let i=n.query??n.pattern??n.url??n.description;return typeof i=="string"?" "+i:""}var kJ,zf=b(()=>{"use strict";Sr();kJ=160});function lv(e){if(!e||typeof e!="object")return;let t=e,n={};for(let r of tPe){let o=t[r];o!==void 0&&(n[r]=typeof o=="string"&&o.length>TJ?o.slice(0,TJ):o)}return Object.keys(n).length>0?JSON.stringify(n):void 0}function cv(e){if(!e||typeof e!="object")return;let t=e;if(Object.keys(t).length===0)return;let n={};for(let[r,o]of Object.entries(t))if(typeof o=="string"){let i=o.length>xJ?o.slice(0,xJ):o;n[r]=ut(i)}else o!=null&&typeof o!="object"&&(n[r]=o);return Object.keys(n).length>0?JSON.stringify(n):void 0}var tPe,TJ,xJ,uM=b(()=>{"use strict";Sr();tPe=["file_path","name","id_prefix"],TJ=4096,xJ=8192});import{createHash as nPe}from"crypto";function uv(e){let{toolUseId:t,name:n,input:r,subagentId:o}=e,i=r??{},s=JSON.stringify(i),a=JSON.stringify(rPe(n,i));return{phase:"started",toolUseId:t,name:n,inputBytes:Buffer.byteLength(s,"utf8"),argsFingerprint:nPe("sha256").update(a).digest("hex"),...o!==void 0?{subagentId:o}:{}}}function rPe(e,t){if(typeof t!="object"||t===null)return t;let n=t;switch(e){case"browser_act":return n.action==="fill"&&"value"in n?{...n,value:"[REDACTED]"}:t;case"config_set":return n.target==="env"&&"value"in n?{...n,value:"[REDACTED]"}:t;default:return t}}function dv(e){let{toolUseId:t,name:n,result:r,truncated:o,durationMs:i,subagentId:s}=e;return{phase:"completed",toolUseId:t,name:n,resultBytes:Buffer.byteLength(r.content,"utf8"),isError:r.isError===!0,truncated:o,durationMs:i,...r.incomplete===!0?{incomplete:!0}:{},...r.incompleteReason?{incompleteReason:r.incompleteReason}:{},...r.circuitBreaker===!0?{circuitBreaker:!0}:{},...r.failureClass?{failureClass:r.failureClass}:{},...typeof r.batchIndex=="number"&&typeof r.batchSize=="number"?{batchIndex:r.batchIndex,batchSize:r.batchSize}:{},...s!==void 0?{subagentId:s}:{},...r.testResult!==void 0?{testResult:r.testResult}:{}}}var pv=b(()=>{"use strict"});async function*mv(e){let t=[],n=!1,r=null,o=()=>{let c=r;r=null,c?.()},a=e(c=>{n||(t.push(c),o())}).finally(()=>{n=!0,o()}).then(c=>({ok:!0,value:c}),c=>({ok:!1,error:c}));for(;;){for(;t.length>0;)yield t.shift();if(n)break;await new Promise(c=>{r=c})}let l=await a;if(!l.ok)throw l.error;return l.value}var dM=b(()=>{"use strict"});import{randomUUID as oPe}from"node:crypto";async function*EJ({state:e,signal:t,vision:n,toolDispatcher:r,traceWriter:o,priorTurns:i,sessionId:s,subagentId:a}){if(!r)return void 0;let l=Ff(e);for(let g of l)g.id.length===0&&(g.id=oPe());let{calls:c,parseErrors:u}=Yz(l,t),d=new Map;for(let g of c){let h=Date.now();d.set(g.id,h),pa(o,uv({toolUseId:g.id,name:g.name,input:g.input,subagentId:a})),yield{type:"tool.use.start",toolUseId:g.id,toolName:g.name,toolInput:ls(g.name,g.input),toolInputRaw:lv(g.input),toolInputCapture:k.AFK_CAPTURE_SUBAGENT_OUTPUT!=="0"?cv(g.input):void 0,sessionId:s}}let p=[];if(t.aborted){let g=rn(t);for(let h of c){let y={content:"Tool call aborted",isError:!0,failureClass:g};p.push({call:h,result:y}),yield{type:"tool.output",toolUseId:h.id,toolName:h.name,content:y.content,isError:!0,failureClass:g,sessionId:s}}}else{let g;try{if(r.executeBatch)g=yield*mv(h=>r.executeBatch(c,y=>{h({type:"tool.activity",activeCount:y.length,activeToolUseIds:[...y],sessionId:s})}));else{g=[];for(let h of c){if(t.aborted){g.push({content:"Tool call aborted",isError:!0,failureClass:rn(t)});continue}try{g.push(await r.execute(h))}catch(y){let w=y instanceof Error?y.message:String(y);g.push({content:`Tool execution threw: ${w}`,isError:!0})}}}}catch(h){let y=h instanceof Error?h.message:String(h);g=c.map(()=>({content:`Tool batch execution failed: ${y}`,isError:!0}))}for(let h=0;h<c.length;h++){let y=c[h],w=g[h],S=u.get(y.id);S!==void 0&&(w={content:`${S}
1273
1273
  --
1274
1274
  ${w.content}`,isError:!0,...w.truncated===!0?{truncated:!0}:{}}),p.push({call:y,result:w});let v=d.get(y.id),x=typeof v=="number"?Date.now()-v:0,T=w.truncated===!0||w.content.includes("[output truncated");pa(o,dv({toolUseId:y.id,name:y.name,result:w,truncated:T,durationMs:x,subagentId:a})),yield{type:"tool.output",toolUseId:y.id,toolName:y.name,content:w.content,...w.isError===!0?{isError:!0}:{},...w.truncated===!0?{truncated:!0}:{},...w.capturePath!==void 0?{capturePath:w.capturePath}:{},...w.incomplete===!0?{incomplete:!0}:{},...w.incompleteReason?{incompleteReason:w.incompleteReason}:{},...typeof w.batchIndex=="number"&&typeof w.batchSize=="number"?{batchIndex:w.batchIndex,batchSize:w.batchSize}:{},...w.failureClass?{failureClass:w.failureClass}:{},durationMs:w.durationMs!==void 0?w.durationMs:x,...w.exitCode!==void 0?{exitCode:w.exitCode}:{},sessionId:s},w.render?.diff&&(yield{type:"tool.diff",toolUseId:y.id,diff:w.render.diff,sessionId:s})}}i.push(Xz(e.assistantText,l,e.reasoningText));for(let g of Qz(p))i.push(g);for(let{result:g}of p)g.harnessUserMessage?.kind==="queued_user_message"&&i.push({role:"user",content:g.harnessUserMessage.text});let f=Zz(p,{vision:n});return f&&i.push(f),p.find(g=>g.result.failureClass===qc)?.result}var RJ=b(()=>{"use strict";Ni();fe();uM();F();Fm();zf();pv();dM();Nf();GI()});function gv(e){return e!==void 0&&e>0?Math.floor(e):0}function hv(e,t){return t>0&&e>=t}function yv(e,t){return t>0?`round ${e}/${t}`:`round ${e}`}var Mr,fv,Lu=b(()=>{"use strict";Mr="tool_use_loop_capped",fv="You have reached your tool-use budget for this turn. Do not request any more tools \u2014 give your final answer now using only the information already gathered."});function wv(e){if(e===void 0||!Number.isFinite(e)||e<=0||e<=12e4)return 0;let t=e*.15,n=Math.min(3e5,Math.max(3e4,t));return Math.max(0,Math.floor(e-n))}function Sv(e,t,n=Date.now()){return t>0&&n-e>=t}var Or,bv,cs=b(()=>{"use strict";Or="soft_deadline_wind_down",bv="Your time budget for this turn is nearly spent. Do not request any more tools \u2014 give your final answer now using only the information already gathered. If your work is incomplete, say briefly what you established, what remains unresolved, and what you would check next."});function AJ(e,t,n,r){try{return km(Ft(e??{}),Kf(t,n),st(t),r),null}catch(o){return o instanceof Error?o:new Error(String(o))}}var CJ=b(()=>{"use strict";Bc();vr();Gf()});function _J(e){let t=e.get("retry-after");if(t==null)return;let n=Number(t);if(Number.isFinite(n)&&n>=0)return Math.round(n*1e3);let r=Date.parse(t);if(!Number.isNaN(r)){let o=r-Date.now();if(o>=0)return o}}function PJ(e=fetch,t,n,r){return!t&&!n&&!r?e:async(o,i)=>{if(r){let a=MS(i),l=i?.signal instanceof AbortSignal?i.signal:void 0;await r.acquirePermit(a,l)}let s=await e(o,i);if(n)try{n(s.headers)}catch{}if(r&&s.status===429)try{let a=_J(s.headers);r.freeze(a??5e3)}catch{}if(t&&iPe.has(s.status))try{let a=_J(s.headers);t({status:s.status,...a!==void 0?{retryAfterMs:a}:{}})}catch{}return s}}var iPe,IJ=b(()=>{"use strict";Af();iPe=new Set([429,503,529])});import sPe from"openai";function lPe(e){let t={apiKey:e.apiKey};return e.baseURL!==void 0&&(t.baseURL=e.baseURL),e.defaultHeaders!==void 0&&(t.defaultHeaders=e.defaultHeaders),e.fetch!==void 0&&(t.fetch=e.fetch),new sPe(t)}function MJ(){return aPe??lPe}function dPe(e){if(!e)return!1;let t;try{t=new URL(e).hostname}catch{return!1}return cPe.has(t)||t.startsWith("127.")?!0:uPe.some(n=>t===n.slice(1)||t.endsWith(n))}function OJ(e){if(dPe(e))return;let t=n=>{let r=cz(n);r!==void 0&&vu.update(r)};return PJ(globalThis.fetch,void 0,t,vu)}var aPe,cPe,uPe,pM=b(()=>{"use strict";Af();CI();IJ();aPe=null;cPe=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","chatgpt.com"]),uPe=[".chatgpt.com"]});async function*mM(e,t){let n=0;for(;;){let r=zS(),o=Date.now(),i,s=null;for(let u=0;;u++)try{i=await t.createStream(e.controller.signal);break}catch(d){if(e.controller.signal.aborted)return null;if(ov(d)&&u<SJ){let p=iM(d),f=p??oM(u);if(oe(e.traceWriter,{phase:"rate_limit",durationMs:f,resolvedModel:e.currentModel,metadata:{source:"connection",reason:p!==void 0?"retry-after":"backoff",attempt:u}}),await an(f,e.controller.signal),e.controller.signal.aborted)return null;continue}s=d;break}if(s!==null)return yield{type:"error",error:t.clarifyError(s)},null;let a=null,l=!1;try{for await(let u of $u(i,e.controller.signal)){if(e.isClosed())return null;for(let d of t.translate(u,r))l||(l=!0,oe(e.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-o,resolvedModel:e.currentModel})),yield d}}catch(u){if(e.controller.signal.aborted)return null;if(iv(u)&&n<vJ){n++,yield{type:"stream.retry",sessionId:e.initSessionId};let d=iM(u),p=d??oM(n-1);if(oe(e.traceWriter,{phase:"rate_limit",durationMs:p,resolvedModel:e.currentModel,metadata:{source:"stream",reason:d!==void 0?"retry-after":"backoff",attempt:n}}),await an(p,e.controller.signal),e.controller.signal.aborted)return null;continue}a=u}if(a!==null)return yield{type:"error",error:t.clarifyError(a)},null;if(e.controller.signal.aborted)return null;let c=Jz(r)&&r.toolCallsByIndex.size>0;return r.finishReason===null&&r.assistantText.length===0&&!c?(yield{type:"error",error:new zn("the model stream ended without a finish_reason and without a dispatchable response (no visible answer text and no complete tool call): the response was empty or cut off before any usable content arrived. The turn is incomplete.")},null):{state:r,events:[],text:r.assistantText,needsToolDispatch:c}}}var $J=b(()=>{"use strict";fe();tv();Zi();Nf();He();Du()});function DJ(e){if(e instanceof qf||ov(e)||iv(e))return!1;let t=as(e);return t!==void 0&&pPe.has(t)}var pPe,LJ=b(()=>{"use strict";Du();rv();pPe=new Set([400,404,405,415,422,501])});import{randomUUID as fPe}from"node:crypto";function FJ(e,t,n={}){let r=bo(e.apiKey,n.authDeps,e.forceChatgptOAuth??!1),o=n.sessionIdOverride??e.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,i=typeof e.model=="string"?e.model:"gpt-4o-mini",s=Lt(i)??i,a={auth:r,model:s,synthesizedSessionId:o,promptStream:t,config:e};return n.baseURL!==void 0&&(a.baseURL=n.baseURL),n.defaultHeaders!==void 0&&(a.defaultHeaders=n.defaultHeaders),n.toolDispatcher!==void 0&&(a.toolDispatcher=n.toolDispatcher),n.onPermissionMode!==void 0&&(a.onPermissionMode=n.onPermissionMode),n.onCwdChange!==void 0&&(a.onCwdChange=n.onCwdChange),n.mcpManager!==void 0&&(a.mcpManager=n.mcpManager),n.useResponsesApi!==void 0&&(a.useResponsesApi=n.useResponsesApi),e.traceWriter!==void 0&&(a.traceWriter=e.traceWriter),new vv(a)}var fM,vv,gM=b(()=>{"use strict";fe();Uc();NI();vr();Yn();BI();Df();UI();me();Cu();Hz();wa();Nf();GI();zI();YS();F();qS();Bc();VI();He();Wf();uJ();rv();Du();aM();cM();qa();zf();RJ();Lu();cs();Gf();CJ();pM();$J();rM();Du();pM();Gf();LJ();fM="openai-compatible",vv=class{client;opts;initSessionId;toolDispatcher;onPermissionMode;onCwdChange;openAITools;wireMode;useOpenAIPricing;traceWriter;priorTurns=[];currentModel;currentPermissionMode;responsesCompactionUnavailable=!1;abort=new Pu;closed=!1;lastUsage=null;autoCompactThreshold;constructor(t){if(this.opts=t,this.initSessionId=t.synthesizedSessionId,this.currentModel=t.model,this.currentPermissionMode=nM(t.config.permissionMode),this.toolDispatcher=t.toolDispatcher,this.onPermissionMode=t.onPermissionMode,this.onCwdChange=t.onCwdChange,this.traceWriter=t.traceWriter,this.autoCompactThreshold=Tm(t.config.autoCompact,t.model),this.toolDispatcher){let i=this.toolDispatcher;Array.isArray(i.toolDefs)&&i.toolDefs.length>0&&(this.openAITools=Vz(i.toolDefs))}let n=(t.useResponsesApi??!1)||tJ(k.AFK_OPENAI_USE_RESPONSES),r=nJ(t.auth,n);this.wireMode=r.mode,this.useOpenAIPricing=r.baseURL===void 0&&t.baseURL===void 0||WI(t.model)&&t.config.forceXaiOAuth!==!0;let o=t.config.resumeHistory?.at(-1);if(o?.inputTokens!==void 0&&o.inputTokens>0&&(this.lastUsage={inputTokens:o.inputTokens,stopReason:null,resultSubtype:"success",isError:!1}),t.auth.apiKey===null)this.client=null;else{let i=MJ(),s={apiKey:t.auth.apiKey},a=r.baseURL??t.baseURL;a!==void 0&&(s.baseURL=a),r.headers!==void 0?s.defaultHeaders=r.headers:t.defaultHeaders!==void 0&&(s.defaultHeaders=t.defaultHeaders);let l=OJ(a);l!==void 0&&(s.fetch=l),this.client=i(s)}}activeOpenAITools(){if(!this.openAITools)return;if(this.currentPermissionMode==="plan")return this.openAITools;let t=this.openAITools.filter(n=>n.function.name!==Un);return t.length>0?t:void 0}async*[Symbol.asyncIterator](){if(yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.currentModel,permissionMode:this.currentPermissionMode,cwd:process.cwd(),tools:this.openAITools?this.openAITools.map(r=>r.function.name):[],slashCommands:[],skills:[],plugins:[],mcpServers:this.opts.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:this.opts.auth.source,version:fM}},this.opts.auth.apiKey===null){yield{type:"error",error:new Error(Lf(this.opts.auth))};return}let n=this.opts.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let r=await Promise.race([n.next(),this.abort.closedPromise]);if(r===JI)break;let o=r;if(o.done)break;if(yield*this.runTurn(o.value.content),this.autoCompactThreshold!==void 0&&!this.closed){let i=this.lastUsage,s=jo(this.currentModel);if(i!==null&&s>0){let a=Ft(i);if(Sm(a,s,this.autoCompactThreshold))try{await this.opts.config.hookRegistry?.dispatch({event:"PreCompact",sessionId:this.initSessionId,trigger:"auto"}),(await this.compactHistory("token_threshold")).compacted&&(this.lastUsage=null)}catch(l){if(!(l instanceof Re))throw l}}}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}async*runTurn(t){let n=this.abort.begin();if(n.signal.aborted)return;let r=Date.now(),o=fPe(),i=new Ru(n.signal,this.traceWriter,"openai-compatible");try{yield*this._runTurnInner(t,n,r,o)}finally{i.finish(Date.now()-r)}}async*_runTurnInner(t,n,r,o){let i=pb(this.currentModel),s=AJ(this.lastUsage,this.currentModel,this.opts.config.maxOutputTokens,this.opts.config.model??this.currentModel);if(s){this.abort.clear(n),yield{type:"error",error:s};return}this.priorTurns.push({role:"user",content:Uz(t,{vision:i,model:this.currentModel})});let a={stopReason:null,resultSubtype:"success",isError:!1},l="",c="",u=gv(this.opts.config.maxToolUseIterations),d=this.opts.config.softDeadlineMs??0,p=null,f=0,g=0,h=[];for(;;){if(n.signal.aborted){this.abort.clear(n),yield*this.finishTurn(a,r);return}let w=yield*this.runIteration(n,i,p);if(w===null){this.abort.clear(n),(n.signal.aborted||this.closed)&&(yield*this.finishTurn(a,r));return}let S=zz(w.state,this.useOpenAIPricing?this.currentModel:void 0);if(a=$f(a,S),a.contextWindowTokens=(S.inputTokens??0)+(S.outputTokens??0),this.lastUsage=a,w.text.length>0&&(l=w.text),c=w.state.reasoningText,!w.needsToolDispatch){yo(w.state.finishReason)&&(h=Ff(w.state).map(E=>E.name));break}if(p!==null)break;let v=yield*this.dispatchAndAppend(w.state,n.signal,i);if(v){this.abort.clear(n),yield{type:"error",error:new Tc(v.content)};return}f+=1;{let E=Ff(w.state);g+=E.length;let _=E.at(-1),P=_?.name,R;try{R=_?JSON.parse(_.argumentsRaw||"{}"):void 0}catch{R=void 0}let C=_?`${_.name}${ls(_.name,R)}`:"unknown";yield{type:"progress",progress:{taskId:o,description:"Working",summary:`${yv(f,u)}: ${C}`,lastToolName:P,totalTokens:a.totalTokens??0,toolUses:g,durationMs:Date.now()-r},sessionId:this.initSessionId}}if(n.signal.aborted){this.abort.clear(n),yield*this.finishTurn(a,r);return}let x=hv(f,u),T=Sv(r,d);if(x||T){p=x?Mr:Or;continue}}if(this.abort.clear(n),l.length>0){let w={role:"assistant",content:l};c.length>0&&(w.reasoning_content=c),this.priorTurns.push(w)}let y=yo(a.stopReason)?WS(h,a.stopReason,{canIncreaseOutputLimit:!(this.opts.auth.source==="chatgpt-oauth"&&a.stopReason==="max_output_tokens")}):null;l.length>0?yield{type:"assistant.message",text:y?`${l}
1275
1275
 
@@ -1479,7 +1479,7 @@ ${t}`:i,a=new ke({parentAbortSignal:n?.abortSignal,...r?.traceWriter!==void 0?{t
1479
1479
  `)}return l(o,[],0),s.sort((c,u)=>c.name<u.name?-1:c.name>u.name?1:0),lg.set(n,s),s}var F0e,gk,lg,B0e,CX=b(()=>{"use strict";ju();xM();F();We();Lr();F0e=10,gk=1e3,lg=new Map;Pv(()=>lg.clear());B0e=/[\u0000-\u001F\u007F-\u009F]/});import{existsSync as U0e,readFileSync as j0e}from"fs";import{join as H0e}from"path";function si(e){let t=H0e(e,".claude-plugin","plugin.json");if(!U0e(t))return{name:null,version:null};try{let n=JSON.parse(j0e(t,"utf8"));return{name:typeof n.name=="string"&&n.name.trim()?n.name.trim():null,version:typeof n.version=="string"&&n.version.trim()?n.version.trim():null}}catch{return{name:null,version:null}}}var cg=b(()=>{"use strict"});import{readFileSync as W0e}from"node:fs";import{join as K0e}from"node:path";function kv(e,t){let n=Xa(e,t),r=t?.excludeName,i=(r!==void 0&&r.length>0?n.filter(a=>a.name!==r&&!a.name.endsWith(`:${r}`)):n).filter(a=>a.source!=="command");if(i.length===0)return"";let s=[];for(let a of i){let l=a.argumentHint?`${a.argumentHint}`:"",c=l?`- \`${a.name} ${l}\`: ${a.description}`:`- ${a.name}: ${a.description}`;s.push(c),a.whenToUse&&s.push(` When to use: ${a.whenToUse}`)}return["Available skills (invoke via the `skill` tool):","","Each skill either forks an isolated subagent (delegation \u2014 preserves the main session's context) or loads its instructions directly into your current context for you to execute directly. The mode is fixed per-skill, not per-call. To run a skill N times in parallel with isolation, dispatch N subagents (via `agent` or `compose`) that each call `skill` once. Prefer a skill over inline investigation when the task shape matches.","",...s].join(`
1480
1480
  `)}function _X(e,t){return[...hV(e,t),...AX(e,t)]}function Xa(e,t){let n=[],r=new Set,o=k.AFK_INTERNAL==="1",i=Rr(Fn());ii(mc(),"user"),Tz("project"),ii(zp(t?.cwd),"project");for(let{dir:l,origin:c}of i.skillRoots)ii(l,c);for(let l of ho()){let c=Ve(l);lr(c,o)&&(n.push({name:l,description:c.description,source:c.origin==="user"?"user":c.origin==="project"?"project":c.origin?.startsWith("imported:")?"imported":"builtin",argumentHint:c.argumentHint,whenToUse:c.whenToUse}),r.add(l),l.includes(":")&&r.add(l.split(":").pop()))}let s=e??hk(t),a=Ov();for(let l of s){if(l.type!=="local")continue;let c=_X(l.path,a);for(let u of c)!u.name||r.has(u.name)||lr({audience:u.audience},o)&&(n.push({name:u.name,description:u.description??`Skill from plugin at ${l.path}`,source:u.origin==="command"?"command":"plugin",argumentHint:u.argumentHint,whenToUse:u.whenToUse}),r.add(u.name))}return n}function ng(e,t){let n=new Map,r=e??hk(t),o=Ov();for(let i of r){if(i.type!=="local")continue;let s=_X(i.path,o);for(let a of s)a.name&&a.body&&a.body.length>0&&!n.has(a.name)&&n.set(a.name,{body:a.body,pluginPath:i.path,...a.allowedTools!==void 0?{allowedTools:a.allowedTools}:{},...a.context!==void 0?{context:a.context}:{},...a.readOnly===!0?{readOnly:!0}:{},...a.model!==void 0?{model:a.model}:{}})}return n}function PX(e,t=()=>{}){let n=e??hk(),r=[],o=new Set;for(let i of n){if(i.type!=="local")continue;let s=si(i.path).name;if(s!==null)for(let a of Lv(K0e(i.path,"agents"))){let l=ae(a),c;try{c=W0e(a,"utf8")}catch(p){let f=ae(p instanceof Error?p.message:String(p));t(`[afk] agents: cannot read ${l}: ${f}`);continue}let u=el(c,p=>t(`[afk] agents: ${l}: ${p}`));if(u===void 0)continue;let d=`${s}:${u.name}`;o.has(d)||(o.add(d),r.push({name:d,definition:u.definition,source:`plugin:${s}`,filePath:a,...u.bashReadOnly===!0?{bashReadOnly:!0}:{},...u.ignoredKeys!==void 0?{ignoredKeys:u.ignoredKeys}:{}}))}}return r}function hk(e){return[...Dr(Jp(e?.cwd)),...Dr(),...Dr(na()),...Rr(Fn()).pluginRoots.flatMap(({dir:t,binary:n})=>Dr(t,{trustAll:!0,sourceEnabled:zW(n)}))]}async function rd(){await EX(hk(),{pluginApi:{registerSkill:Sn,listSkills:ho,getSkill:Ve,loadSkillPrompts:ot,env:k,SubagentManager:ke,describeFailure:Zt,discoverPluginSkillBodies:ng,getAgentFrameworkDir:kt,getSkillsDir:mc,getSessionsDir:Le,getOrDeriveFacet:Yo,listSessionIds:Ga,deriveSessionFacet:Rf,loadStoredSession:yS}})}var Ir=b(()=>{"use strict";P0();Yt();ar();_0();Lr();RX();ju();CX();cg();Zf();NM();We();wt();St();bS();B();F();zo()});function od(e,t,n){let r=Mm({cwd:t,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:n.surface,...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:n.workspace}),o=[e.toolBase];return e.userSystem&&o.push(e.userSystem),o.push(e.memoryPrompt),e.workspacePrompt.length>0&&o.push(e.workspacePrompt),e.hotMemory.length>0&&o.push(e.hotMemory),o.push(r),e.manifest.length>0&&o.push(e.manifest),o.join(`
1481
1481
 
1482
- `)}var yk=b(()=>{"use strict";zt()});function IX(e){let{config:t,cwd:n}=e,r=e.hasSkillExecutor?kv(void 0,{cwd:n,...typeof t.skillDispatchName=="string"&&t.skillDispatchName.length>0?{excludeName:t.skillDispatchName}:{}}):"",o=BS(t.isSkillDispatch),i=US(e.readOnlyMemory),s=jS(e.workspaceEnabled),a={surface:e.surface,sessionId:t.sessionId,depth:t.depth,maxDepth:t.maxDepth,workspace:e.runtimeStateSource.getWorkspace()},l={toolBase:o,memoryPrompt:i,workspacePrompt:s,hotMemory:t.hotMemory??"",manifest:r,userSystem:e.userSystem};return{stableSystemPrefix:l,toolSystemAppend:od(l,n,a)}}var MX=b(()=>{"use strict";Ir();FI();yk()});import G0e from"@anthropic-ai/sdk";function OX(e){if(e===void 0)return null;if(typeof e=="string")return e.length>0?e:null;if(typeof e=="object"&&e!==null&&"append"in e){let t=e.append;return t&&t.length>0?t:null}return null}function $X(e,t,n,r){let o=t.config,{localMode:i,token:s}=Vq(o);if(!s||s.length===0)throw new Error(`${n} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let a=lb(s),{client:l,throttleQueue:c,systemPrefix:u,tokenRefresher:d}=uz({config:o,token:s,authMode:a,localMode:i,factory:e.providerFactory??AS(),createClient:R=>new G0e(R)}),p=OX(o.systemPrompt),f=typeof o.model=="string"&&o.model.length>0?Lt(o.model)??o.model:r,g=yb(o,f),h=o.permissionMode??"default";e.setCurrentPermissionMode(h),e.ensureSharedRoots(o.cwd),o.cwd&&e.setCurrentCwd(o.cwd);let y=e.getSharedReadRoots(),w=e.getSharedWriteRoots();o.readRoots&&y&&y.length<=1&&(y.length=0,y.push(...o.readRoots)),o.writeRoots&&w&&w.length<=1&&(w.length=0,w.push(...o.writeRoots));let{queryDispatcher:S,runtimeStateSource:v,toolDefs:x,resolvedSessionId:T}=Sz({config:o,model:f,permissionMode:h,surface:e.surface,providerName:n,externalTools:e.externalTools,sharedReadRoots:y,sharedWriteRoots:w,getCwd:()=>e.getCurrentCwd()||o.cwd||process.cwd(),getMcpTools:()=>e.mcpManager?.getMcpTools()??[],getSubagents:()=>e.subagentExecutor?e.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]},getMintedSessionId:()=>e.getMintedSessionId(),setMintedSessionId:R=>{e.setMintedSessionId(R)},getPresenceSessionId:()=>e.getPresenceSessionId(),setPresenceSessionId:R=>{e.setPresenceSessionId(R)},buildDispatcher:(R,C)=>e.buildDispatcher(R,C)}),E=o.cwd||process.cwd(),{stableSystemPrefix:_,toolSystemAppend:P}=IX({config:o,cwd:E,surface:e.surface,readOnlyMemory:e.readOnlyMemory,workspaceEnabled:e.workspaceStore!==void 0,hasSkillExecutor:!!e.skillExecutor,runtimeStateSource:v,userSystem:p});return KU({prompt:t.prompt,options:{model:f,maxTokens:g,system:P},provenance:{systemPrompt:{source:o.systemPromptSource??"none",shape:typeof o.systemPrompt=="string"?"string":Array.isArray(o.systemPrompt)?"string[]":o.systemPrompt!=null?"preset":"undefined",...typeof o.systemPrompt=="string"?{length:o.systemPrompt.length}:{}},...o.apiKey?{apiKey:{source:"config"}}:{}}}),{client:l,authMode:a,localMode:i,model:f,maxTokens:g,cwd:E,systemPrefix:u,throttleQueue:c,tokenRefresher:d,queryDispatcher:S,runtimeStateSource:v,toolDefs:x,resolvedSessionId:T,stableSystemPrefix:_,toolSystemAppend:P}}var I0=b(()=>{"use strict";ga();Yn();Sb();Yq();CS();dz();vz();MX();Uo()});function DX(e){let t=e.initialUsageInputTokens!==void 0&&e.initialUsageInputTokens>0?{inputTokens:e.initialUsageInputTokens,stopReason:null,resultSubtype:"success",isError:!1}:null;return{messages:e.initialMessages?[...e.initialMessages]:[],currentModel:e.model,requestedModel:e.requestedModel??e.model,currentPermissionMode:e.permissionMode,userSystem:e.userSystem,toolDispatcher:e.toolDispatcher,lastUsage:t,closed:!1,autoCompactThreshold:e.autoCompactThreshold}}var LX=b(()=>{"use strict"});function ug(e){if(typeof e?.baseUrl=="string"&&e.baseUrl.length>0)return!1;let t=k.AFK_DISABLE_PROMPT_CACHE;if(t===void 0||t.length===0)return!0;let n=t.toLowerCase();return!(n==="1"||n==="true"||n==="yes"||n==="on")}function cl(){let e=k.AFK_PROMPT_CACHE_TTL;return e==="5m"?"5m":e==="1h"?"1h":q0e}function bk(e){return ug(e)&&cl()==="1h"}function FX(e,t){if(e.length===0)return e;let n=e[e.length-1],r=BX(n,t);return r===n?e:[...e.slice(0,-1),r]}function NX(e,t){if(e.length===0)return e;let n=e[e.length-1],r=z0e(n,t);return r===n?e:[...e.slice(0,-1),r]}function z0e(e,t){let n=e.content;if(typeof n=="string")return n.length===0?e:{...e,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:t}}]};if(!Array.isArray(n)||n.length===0)return e;let r=n[n.length-1],o=BX(r,t);return o===r?e:{...e,content:[...n.slice(0,-1),o]}}function BX(e,t){return e.type==="thinking"||e.type==="redacted_thinking"?e:{...e,cache_control:{type:"ephemeral",ttl:t}}}var q0e,id=b(()=>{"use strict";F();q0e="1h"});var M0=b(()=>{"use strict";Wi()});function Z0e(e){let t=n=>n===void 0?void 0:n*O0;return{inputPerMTok:e.inputPerMTok*O0,outputPerMTok:e.outputPerMTok*O0,...t(e.cacheWrite5mPerMTok)!==void 0?{cacheWrite5mPerMTok:t(e.cacheWrite5mPerMTok)}:{},...t(e.cacheWrite1hPerMTok)!==void 0?{cacheWrite1hPerMTok:t(e.cacheWrite1hPerMTok)}:{},...t(e.cacheReadPerMTok)!==void 0?{cacheReadPerMTok:t(e.cacheReadPerMTok)}:{}}}function eOe(e){return e.responseSpeed??e.requestSpeed??"standard"}function tOe(e){return _u(e,UX,X0e)}function $0(e,t,n,r,o,i,s={}){let a=tOe(e);if(!a)return;let l=eOe(s)==="fast"&&Q0e.test(e)?Z0e(a):a,c=1e6,u=cn(t),d=cn(n),p=cn(r),f=cn(o),g=u/c*l.inputPerMTok,h=d/c*l.outputPerMTok,y=l.cacheWrite5mPerMTok??l.inputPerMTok*J0e,w=l.cacheWrite1hPerMTok??l.inputPerMTok*V0e,S=l.cacheReadPerMTok??l.inputPerMTok*Y0e,v=i??{ephemeral5m:f,ephemeral1h:0},x=cn(v.ephemeral5m),T=cn(v.ephemeral1h),E=Math.max(0,f-(x+T)),_=x/c*y+T/c*w+E/c*w,P=p/c*S;return g+h+_+P}var J0e,V0e,Y0e,UX,X0e,O0,Q0e,D0=b(()=>{"use strict";GS();J0e=1.25,V0e=2,Y0e=.1,UX=new Map([["claude-sonnet-5",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-opus-5",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-8",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-7",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-6",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-sonnet-4-6",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-sonnet-4-5-20250929",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-opus-4-5-20250929",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-haiku-4-5-20250929",{inputPerMTok:1,outputPerMTok:5,cacheWrite5mPerMTok:1.25,cacheWrite1hPerMTok:2,cacheReadPerMTok:.1}],["claude-haiku-4-5-20251001",{inputPerMTok:1,outputPerMTok:5,cacheWrite5mPerMTok:1.25,cacheWrite1hPerMTok:2,cacheReadPerMTok:.1}],["claude-3-7-sonnet-20250219",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20241022",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20240620",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-haiku-20241022",{inputPerMTok:.8,outputPerMTok:4,cacheWrite5mPerMTok:1,cacheWrite1hPerMTok:1.6,cacheReadPerMTok:.08}],["claude-3-opus-20240229",{inputPerMTok:15,outputPerMTok:75,cacheWrite5mPerMTok:18.75,cacheWrite1hPerMTok:30,cacheReadPerMTok:1.5}],["claude-3-sonnet-20240229",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-haiku-20240307",{inputPerMTok:.25,outputPerMTok:1.25,cacheWrite5mPerMTok:.3,cacheWrite1hPerMTok:.5,cacheReadPerMTok:.03}]]),X0e=/-\d{8}$/,O0=2,Q0e=/^claude-opus-(?:5|4-8)(?:-|$)/});function nOe(e){let t=e.speed;return t==="fast"||t==="standard"?t:void 0}function rOe(e){let t=o=>Number.isFinite(o)&&o>=0?o:0,n=e.cache_creation;if(n)return{ephemeral5m:t(n.ephemeral_5m_input_tokens??0),ephemeral1h:t(n.ephemeral_1h_input_tokens??0)};let r=t(e.cache_creation_input_tokens??0);return cl()==="1h"?{ephemeral5m:0,ephemeral1h:r}:{ephemeral5m:r,ephemeral1h:0}}function L0(e,t,n,r){if(!e)return{stopReason:t??null};let o=nOe(e),i={inputTokens:e.input_tokens,outputTokens:e.output_tokens,stopReason:t??null,raw:{...e,...o?{speed:o}:{}}};if(e.cache_read_input_tokens!=null&&(i.cachedInputTokens=e.cache_read_input_tokens),e.cache_creation_input_tokens!=null&&(i.cacheCreationTokens=e.cache_creation_input_tokens),i.totalTokens=(e.input_tokens??0)+(e.output_tokens??0),n){let s=$0(n,e.input_tokens??0,e.output_tokens??0,e.cache_read_input_tokens??0,e.cache_creation_input_tokens??0,rOe(e),{...r?{requestSpeed:r}:{},...o?{responseSpeed:o}:{}});s!==void 0&&(i.totalCostUsd=s)}return i}var jX=b(()=>{"use strict";id();D0()});var F0=b(()=>{"use strict";D0();jX();NI()});function dg(e){return e>2147483647?2147483647:e}var N0=b(()=>{"use strict"});function WX(){let e=k.AFK_MODEL_TTFB_TIMEOUT_MS;if(e===void 0||e.trim()==="")return HX;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<0?HX:dg(t)}function KX(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?void 0:(e<sOe?e:aOe)+iOe}function GX(e,t){if(t<=0)return{signal:e,timedOut:()=>!1,firstByteSeen:()=>{},extend:()=>{},dispose:()=>{}};let n=new AbortController,r=AbortSignal.any([e,n.signal]),o=!1,i=!1,s=Date.now()+t,a,l=d=>{a=setTimeout(()=>{o=!0,n.abort(new Error(oOe))},dg(d)),a.unref()};l(t);let c=()=>{i||(i=!0,clearTimeout(a))};return{signal:r,timedOut:()=>o,firstByteSeen:c,extend:d=>{i||o||typeof d!="number"||!Number.isFinite(d)||d<=0||(s+=d,clearTimeout(a),l(Math.max(1,s-Date.now())))},dispose:c}}var HX,oOe,iOe,sOe,aOe,B0=b(()=>{"use strict";F();N0();HX=18e4;oOe="model_ttfb_timeout",iOe=3e4,sOe=6e4,aOe=8e3});function zX(){let e=k.AFK_MODEL_STALL_TIMEOUT_MS;if(e===void 0||e.trim()==="")return qX;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<0?qX:dg(t)}function VX(e){return e instanceof Error&&e.message===JX}function U0(e){return new Error(`Model stream stalled: no output for ${Math.round(e/1e3)}s after the response had already started streaming. The round was aborted rather than left hanging (issue #762: two sessions hung 38 and 63 minutes with no terminal event). A round that keeps producing output is never cut off, no matter how long it runs. Raise AFK_MODEL_STALL_TIMEOUT_MS, or set it to 0 to disable this bound.`)}function YX(e,t,n){if(t<=0)return{signal:e,timedOut:()=>!1,progress:()=>{},dispose:()=>{}};let r=new AbortController,o=AbortSignal.any([e,r.signal]),i,s=!1,a=!1,l=d=>{if(!(a||s)){s=!0,i=void 0;try{n?.({stallTimeoutMs:t,elapsedSinceLastProgressMs:Date.now()-d})}catch{}r.signal.aborted||r.abort(new Error(JX))}};return{signal:o,timedOut:()=>s,progress:()=>{if(a||s)return;i!==void 0&&clearTimeout(i);let d=Date.now(),p=setTimeout(()=>l(d),t);p.unref(),i=p},dispose:()=>{a||(a=!0,i!==void 0&&clearTimeout(i),i=void 0)}}}var qX,JX,wk=b(()=>{"use strict";F();N0();qX=12e5;JX="model_stream_stall_timeout"});function Sk(e,t=Math.random){return e+Math.floor(t()*e*dOe)}function QX(e=Math.random){let t=uOe-XX;return XX+Math.floor(e()*t)}function ZX(e){return e.type==="turn.completed"&&e.usage.stopReason===Hn}function e8(e){let t=k.AFK_OVERLOAD_PAUSE_MS;if(t!==void 0&&t.trim()!==""){let n=Number(t);if(Number.isFinite(n)&&n>=0)return Math.min(Math.floor(n),cOe)}return e!==void 0&&pOe.has(e)?lOe:0}var j0,lOe,cOe,XX,uOe,dOe,pOe,pg=b(()=>{"use strict";F();Gu();Gu();j0="Anthropic is overloaded (HTTP 529) and did not recover within this turn's retry budget. This is an upstream capacity event, not an afk error. The turn was committed, so the conversation so far is preserved \u2014 resume with `afk --resume <sessionId>` to continue from saved state once capacity frees up.",lOe=600*1e3,cOe=7200*1e3,XX=60*1e3,uOe=120*1e3,dOe=.25;pOe=new Set(["cli","repl","telegram","web"])});function t8(e){if(!Number.isFinite(e)||e<=0)return 0;let t=Math.floor(e*2/3);return Math.max(1,t)}function n8(e){if(!("status"in e))return!1;let t=e.status;return t===529||t===503}function mg(e){if(e===null||typeof e!="object")return!1;let t=e;if(t.status===529||t.status===503)return!0;let n=t.error;if(n===null||typeof n!="object")return!1;let r=n;return((r.error!==null&&typeof r.error=="object"?r.error.type:void 0)??r.type)==="overloaded_error"}var vk,fg=b(()=>{"use strict";vk=class{overloadRetries=0;streamIncompleteRetries=0;ttfbRetries=0;canRetryOverload(){return this.overloadRetries<3}canRetryStreamIncomplete(){return this.streamIncompleteRetries<2}canRetryTtfb(){return this.ttfbRetries<2}reset(){this.overloadRetries=0,this.streamIncompleteRetries=0,this.ttfbRetries=0}}});async function*fOe(e,t,n){oe(e.traceWriter,{phase:"ttfb_timeout",durationMs:Date.now()-t,metadata:{reason:"ttfb-timeout",source:"first-byte",resolvedModel:e.model,attempt:n}}),yield{type:"stream.retry",sessionId:e.ctx.sessionId}}async function*W0(e,{input:t,turn:n,retry:r,requestStartedAt:o}){return e==="ttfb"?(r.ttfbRetries+=1,yield*fOe(t,o,r.ttfbRetries),"continue"):e==="overload"?(r.overloadRetries+=1,oe(t.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:r.overloadRetries}}),yield{type:"stream.retry",sessionId:t.ctx.sessionId},yield*r8(Sk(5e3*Math.pow(2,r.overloadRetries-1)),t,n),t.signal.aborted?"terminated":"continue"):(r.streamIncompleteRetries+=1,oe(t.traceWriter,{phase:"rate_limit",metadata:{reason:"stream-incomplete",source:"mid-stream",attempt:r.streamIncompleteRetries}}),yield{type:"stream.retry",sessionId:t.ctx.sessionId},yield*r8(1e3*Math.pow(2,r.streamIncompleteRetries-1),t,n),t.signal.aborted?"terminated":"continue")}async function*r8(e,t,n){await an(e,t.signal),t.signal.aborted&&(yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:t.ctx.sessionId})}var o8=b(()=>{"use strict";fe();Zi();pg();fg()});function s8(e){let t=e.fastModeController?.snapshotTurn({resolvedModelId:e.model,providerFamily:"anthropic-direct",hasCustomEndpoint:e.baseUrl!==void 0,executionPath:"top-level"}),n=t?.effective===!0,r=Oi(e.authMode,e.sessionId,e.requestId,e.effort!==void 0,bk(e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}),n);return{decision:t,runInput:{client:e.client,messages:e.messages,system:e.system,tools:e.tools,toolDispatcher:e.toolDispatcher,model:e.model,maxTokens:e.maxTokens,headers:r,signal:e.signal,ctx:{sessionId:e.sessionId},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...n?{fastMode:!0}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.maxToolUseIterations!==void 0?{maxToolUseIterations:e.maxToolUseIterations}:{},...e.softDeadlineMs!==void 0?{softDeadlineMs:e.softDeadlineMs}:{},...e.traceWriter?{traceWriter:e.traceWriter}:{},...e.subagentId!==void 0?{subagentId:e.subagentId}:{},...e.throttleQueue?{throttleQueue:e.throttleQueue}:{},...e.onUsageProgress?{onUsageProgress:e.onUsageProgress}:{},...e.beforeNextRound?{beforeNextRound:e.beforeNextRound}:{}}}}function kk(e,t){let n=e instanceof Error?e:new Error(String(e));if(!t||n.message.startsWith(i8))return n;let r=new Error(`${i8} ${n.message}`,{cause:n});r.name=n.name,n.stack!==void 0&&(r.stack=n.stack);for(let o of Object.getOwnPropertyNames(n)){if(o==="message"||o==="stack")continue;let i=Object.getOwnPropertyDescriptor(n,o);i!==void 0&&Object.defineProperty(r,o,i)}return r}var i8,K0=b(()=>{"use strict";ga();id();i8="[Fast mode requested; no standard-mode fallback will be attempted]"});async function*a8(e,t,n){let r=t.throttleQueue;if(!r)return await e;r.resetAttempts();let o=Symbol("create-done"),i=!1,s=e.then(a=>(i=!0,a),a=>{throw i=!0,a});for(;;){for(let l of r.takeAll())n?.(l.retryAfterMs),yield{type:"rate_limit",sessionId:t.ctx.sessionId,status:l.status,attempt:l.attempt,...l.retryAfterMs!==void 0?{retryAfterMs:l.retryAfterMs}:{}};if(i)return await s;await Promise.race([s.then(()=>o,()=>o),r.waitForItem().then(()=>{})])}}var l8=b(()=>{"use strict"});function c8(e,t){try{let n=[];for(let r=0;r<e.length;r++){let o=e[r];if(o.role!=="assistant"||typeof o.content=="string")continue;let i=o.content;for(let s=0;s<i.length;s++){let a=i[s];if(a.type==="thinking"){let l=a;(!l.thinking||!l.signature)&&n.push({msgIdx:r,blockIdx:s,thinking:l.thinking?`(${l.thinking.length} chars)`:"(empty)",sigLen:l.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",t.message),console.error(`[afk] messages.length=${e.length}, invalid thinking blocks:`,n.length>0?JSON.stringify(n):"none found (cause may be elsewhere)")}catch{}}var u8=b(()=>{"use strict"});function gOe(e){let{name:t,description:n,input_schema:r}=e;return{name:t,...n!==void 0?{description:n}:{},input_schema:r}}async function hOe(e,t,n,r,o){for(let i=0;;i++){if(i>0){let s=Sk(5e3*Math.pow(2,i-1));if(await an(s,o),o.aborted)throw new Error("aborted")}try{return await Promise.resolve(e.messages.create(t,{headers:n,signal:r}))}catch(s){if(r.aborted)throw s;let a=s instanceof Error?s:new Error(String(s));if(n8(a)){if(i<3)continue;throw new Tk}throw a}}}function yOe(e){return{model:e.model,max_tokens:e.maxTokens,messages:e.messages,stream:!0,...e.system!==null?{system:e.system}:{},...e.tools!==null&&e.tools.length>0?{tools:e.tools.map(gOe)}:{},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{output_config:{effort:e.effort}}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.fastMode===!0?{speed:"fast"}:{}}}async function*d8({input:e,turn:t,retry:n,ttfbTimeoutMs:r,stallTimeoutMs:o}){let i=ug({baseUrl:e.baseUrl})?NX(e.messages,cl()):e.messages,s=yOe({...e,messages:i,tools:t.windDownReason!==null?null:e.tools}),a=Date.now(),l=GX(e.signal,r),c=YX(l.signal,o,u=>{oe(e.traceWriter,{phase:"idle_watchdog_fired",durationMs:u.elapsedSinceLastProgressMs,resolvedModel:e.model,metadata:{source:"model-stream",stallTimeoutMs:u.stallTimeoutMs,elapsedSinceLastProgressMs:u.elapsedSinceLastProgressMs}})});try{return{kind:"opened",events:yield*a8(hOe(e.client,s,e.headers,c.signal,e.signal),e,d=>{let p=KX(d);p!==void 0&&l.extend(p)}),ttfb:l,stall:c,requestStartedAt:a}}catch(u){if(l.timedOut()&&!e.signal.aborted&&n.canRetryTtfb())return l.dispose(),c.dispose(),{kind:"retry-ttfb",requestStartedAt:a};if(l.dispose(),c.dispose(),e.signal.aborted)return yield{type:"turn.completed",usage:t.terminalUsage(),sessionId:e.ctx.sessionId},{kind:"terminated"};if(u instanceof Tk)return{kind:"overload-exhausted"};let d=kk(u,e.fastMode===!0);return d.message.includes("thinking")&&c8(e.messages,d),yield{type:"error",error:d},{kind:"terminated"}}}var Tk,p8=b(()=>{"use strict";K0();id();fe();Zi();B0();wk();pg();fg();l8();u8();Tk=class extends Error{constructor(){super("Connection-phase overload budget exhausted"),this.name="ConnectionOverloadExhaustedError"}}});function m8(e,t){return e||t!==null}function f8(){return new zn("the model stream ended without a terminal message (no message_stop and no stop_reason): the turn is incomplete. The cause is not knowable at this layer \u2014 a client-side abort carrying an AbortError reason (including the SDK request timeout) and an upstream peer close are indistinguishable here. Check the trace for a preceding ttfb_timeout, idle_watchdog_fired, or rate_limit phase before suspecting the network.")}var g8=b(()=>{"use strict";He()});function bOe(e){let t=e.trim();if(t.length===0)return{};try{return JSON.parse(t)}catch{return{}}}function wOe(e,t,n){let r=[],o=[];for(let a of e)a&&(a.kind==="text"?(r.push({type:"text",text:a.text}),o.push(a.text)):a.kind==="thinking"?a.thinking&&a.signature&&r.push({type:"thinking",thinking:a.thinking,signature:a.signature}):a.kind==="redacted_thinking"?r.push({type:"redacted_thinking",data:a.data}):r.push({type:"tool_use",id:a.id,name:a.name,input:bOe(a.partialJson)}));let i=a=>a.type==="tool_use",s=r.filter(i);return{stopReason:t,assistantBlocks:r,toolUseBlocks:s,usage:n,text:o.join("")}}async function*h8(e,t,n){let r=[],o=null,i=null,s=!1,a=!!k.AFK_TELEGRAM_TRACE;try{a&&console.log("[translate] starting SDK event iteration");for await(let l of e){switch(a&&console.log("[translate] SDK evt:",l.type),l.type){case"message_start":{let c=l.message?.usage;c&&(i={...c});break}case"content_block_start":{let c=l.content_block;c.type==="text"?r[l.index]={kind:"text",text:""}:c.type==="thinking"?r[l.index]={kind:"thinking",thinking:"",signature:""}:c.type==="redacted_thinking"?r[l.index]={kind:"redacted_thinking",data:c.data}:c.type==="tool_use"&&(r[l.index]={kind:"tool_use",id:c.id,name:c.name,partialJson:""},yield{kind:"event",event:{type:"tool.use.start",toolUseId:c.id,toolName:c.name,toolInput:" \u2026",pending:!0,sessionId:t.sessionId}});break}case"content_block_delta":{let c=r[l.index],u=l.delta;u.type==="text_delta"?(c&&c.kind==="text"&&(c.text+=u.text),yield{kind:"event",event:{type:"delta.text",text:u.text,sessionId:t.sessionId}}):u.type==="input_json_delta"?(c&&c.kind==="tool_use"&&(c.partialJson+=u.partial_json),n?.()):u.type==="thinking_delta"?(c&&c.kind==="thinking"&&(c.thinking+=u.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:u.thinking,sessionId:t.sessionId}}):(u.type==="signature_delta"&&c&&c.kind==="thinking"&&(c.signature=u.signature),n?.());break}case"content_block_stop":{let c=r[l.index];c&&c.kind==="tool_use"&&(yield{kind:"event",event:{type:"tool.use",summary:c.name,toolUseIds:[c.id],sessionId:t.sessionId}});break}case"message_delta":{l.delta&&l.delta.stop_reason!==void 0&&(o=l.delta.stop_reason);let c=l.usage;c&&(i!==null?(i.output_tokens=c.output_tokens,c.cache_creation_input_tokens!=null&&(i.cache_creation_input_tokens=c.cache_creation_input_tokens),c.cache_read_input_tokens!=null&&(i.cache_read_input_tokens=c.cache_read_input_tokens),c.input_tokens!=null&&(i.input_tokens=c.input_tokens)):i={cache_creation:null,cache_creation_input_tokens:c.cache_creation_input_tokens??null,cache_read_input_tokens:c.cache_read_input_tokens??null,inference_geo:null,input_tokens:c.input_tokens??0,output_tokens:c.output_tokens,server_tool_use:null,service_tier:null});break}case"message_stop":{s=!0;break}default:break}if(s)break}a&&console.log("[translate] SDK iteration ended naturally, stopped=",s)}catch(l){a&&console.log("[translate] SDK iteration threw:",l.message),yield{kind:"event",event:{type:"error",error:l instanceof Error?l:new Error(String(l))}};return}if(!m8(s,o)){yield{kind:"event",event:{type:"error",error:f8()}};return}a&&console.log("[translate] yielding turn-result"),yield{kind:"turn-result",result:wOe(r,o,i)}}var y8=b(()=>{"use strict";F();g8()});async function*b8({events:e,input:t,turn:n,retry:r,ttfb:o,stall:i,stallTimeoutMs:s,requestStartedAt:a}){let l=null,c=!1,u=!1,d=!1,p=!1,f=!1,g=!1;try{k.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let h of h8($u(e,t.signal),t.ctx,()=>i.progress()))if(!g&&(h.kind==="turn-result"||h.event.type!=="error")&&(g=!0,o.firstByteSeen(),oe(t.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-a,resolvedModel:t.model})),i.progress(),k.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",h.kind,h.kind==="event"?h.event.type:""),h.kind==="event"){if(h.event.type==="error"){if(o.timedOut()&&!t.signal.aborted&&r.canRetryTtfb()&&!g){u=!0;break}if(i.timedOut()&&!t.signal.aborted){yield{type:"error",error:U0(s)},c=!0;break}if(mg(h.event.error)&&r.canRetryOverload()&&!t.signal.aborted){d=!0;break}if(mg(h.event.error)&&!t.signal.aborted){f=!0;break}if(t.signal.aborted)break;if(h.event.error instanceof zn&&r.canRetryStreamIncomplete()&&!t.signal.aborted){p=!0;break}yield h.event,c=!0;break}yield h.event}else{l=h.result;break}k.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",l?"set":"null")}catch(h){if(o.timedOut()&&!t.signal.aborted&&r.canRetryTtfb()&&!g)o.dispose(),i.dispose(),u=!0;else{if(o.dispose(),i.dispose(),t.signal.aborted)return yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:t.ctx.sessionId},{kind:"terminated"};let y=h instanceof Error?h:new Error(String(h));if((i.timedOut()||VX(y))&&!t.signal.aborted)return yield{type:"error",error:U0(s)},{kind:"terminated"};if(mg(y)&&r.canRetryOverload()&&!t.signal.aborted)d=!0;else if(mg(y)&&!t.signal.aborted)f=!0;else return yield{type:"error",error:y},{kind:"terminated"}}}return o.dispose(),i.dispose(),u?{kind:"retry",reason:"ttfb"}:d?{kind:"retry",reason:"overload"}:p?{kind:"retry",reason:"stream-incomplete"}:f?{kind:"overload-exhausted"}:c?{kind:"translator-errored"}:{kind:"streamed",turnResult:l}}var w8=b(()=>{"use strict";y8();He();tv();fe();F();wk();fg()});async function*S8(e,t,n){let r=[],o=new Map;for(let s of e.toolUseBlocks)r.push({id:s.id,name:s.name,input:s.input,signal:t.signal}),o.set(s.id,Date.now()),pa(t.traceWriter,uv({toolUseId:s.id,name:s.name,input:s.input,subagentId:t.subagentId})),yield{type:"tool.use.start",toolUseId:s.id,toolName:s.name,toolInput:ls(s.name,s.input),toolInputRaw:lv(s.input),toolInputCapture:k.AFK_CAPTURE_SUBAGENT_OUTPUT==="1"?cv(s.input):void 0,sessionId:t.ctx.sessionId};if(t.signal.aborted){let s=r.map(a=>({type:"tool_result",tool_use_id:a.id,content:"Tool call aborted",is_error:!0}));return t.messages.push({role:"user",content:s}),yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:t.ctx.sessionId},{kind:"aborted"}}let i;if(t.toolDispatcher.executeBatch)i=yield*mv(async s=>{try{return await t.toolDispatcher.executeBatch(r,a=>{s({type:"tool.activity",activeCount:a.length,activeToolUseIds:[...a],sessionId:t.ctx.sessionId})})}catch(a){return r.map(()=>({content:`Tool batch execution failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}))}});else{i=[];for(let s of r){if(t.signal.aborted){i.push({content:"Tool call aborted",isError:!0,failureClass:rn(t.signal)});continue}try{i.push(await t.toolDispatcher.execute(s))}catch(a){let l=a instanceof Error?a.message:String(a);i.push({content:`Tool execution threw: ${l}`,isError:!0})}}}return{kind:"dispatched",calls:r,results:i,startTimes:o}}var v8=b(()=>{"use strict";Ni();fe();uM();F();zf();pv();dM()});async function*k8(e,t,n,r){let o=[];for(let l=0;l<e.length;l++){let c=e[l],u=t[l],d=n.get(c.id),p=typeof d=="number"?Date.now()-d:0,f=u.truncated===!0||u.content.includes("[output truncated");pa(r.traceWriter,dv({toolUseId:c.id,name:c.name,result:u,truncated:f,durationMs:p,subagentId:r.subagentId})),yield{type:"tool.output",toolUseId:c.id,toolName:c.name,content:u.content,...u.isError===!0?{isError:!0}:{},...f?{truncated:!0}:{},...u.capturePath!==void 0?{capturePath:u.capturePath}:{},...u.incomplete===!0?{incomplete:!0}:{},...u.incompleteReason?{incompleteReason:u.incompleteReason}:{},...typeof u.batchIndex=="number"&&typeof u.batchSize=="number"?{batchIndex:u.batchIndex,batchSize:u.batchSize}:{},...u.failureClass?{failureClass:u.failureClass}:{},durationMs:u.durationMs!==void 0?u.durationMs:p,...u.exitCode!==void 0?{exitCode:u.exitCode}:{},sessionId:r.ctx.sessionId},u.render?.diff&&(yield{type:"tool.diff",toolUseId:c.id,diff:u.render.diff,sessionId:r.ctx.sessionId});let{content:g,isError:h,image:y}=u,w=y!==void 0?[{type:"image",source:{type:"base64",media_type:y.mediaType,data:y.data}},...g.length>0?[{type:"text",text:g}]:[]]:g;o.push({type:"tool_result",tool_use_id:c.id,content:w,...h===!0?{is_error:!0}:{}})}let i=t.flatMap(l=>l.harnessUserMessage?.kind==="queued_user_message"?[{type:"text",text:l.harnessUserMessage.text}]:[]),s={role:"user",content:[...o,...i]};r.messages.push(s);let a=t.find(l=>l.failureClass===qc);return a?(yield{type:"error",error:new Tc(a.content)},"denial-tripped"):"committed"}var T8=b(()=>{"use strict";fe();pv();Fm();He()});async function*x8(e,t,n,r,o){let i=t.messages.length;t.messages.push({role:"assistant",content:e.assistantBlocks});try{n.toolCallCount+=e.toolUseBlocks.length;let u=yield*S8(e,t,n);if(u.kind==="aborted"||(yield*k8(u.calls,u.results,u.startTimes,t))==="denial-tripped")return"terminated"}catch(u){throw t.messages.splice(i),u}n.iterations+=1;let s=e.toolUseBlocks[e.toolUseBlocks.length-1],a=s?`${s.name}${ls(s.name,s.input)}`:"unknown";if(yield{type:"progress",progress:{taskId:n.taskId,description:"Working",summary:`${yv(n.iterations,r)}: ${a}`,lastToolName:s?.name,totalTokens:n.usage.totalTokens??0,toolUses:n.toolCallCount,durationMs:Date.now()-n.startedAt},sessionId:t.ctx.sessionId},n.windDownReason!==null)return yield{type:"turn.completed",usage:n.withDuration({...n.usage,stopReason:n.windDownReason}),sessionId:t.ctx.sessionId},"terminated";let l=hv(n.iterations,r),c=Sv(n.startedAt,o);if(l||c){let u=l?fv:bv,d=t.messages[t.messages.length-1];d!==void 0&&d.role==="user"&&Array.isArray(d.content)&&d.content.push({type:"text",text:u}),n.windDownReason=l?Mr:Or}return"continue"}var E8=b(()=>{"use strict";zf();cs();Lu();v8();T8()});function*R8(e,t,n){if(e.stopReason==="refusal"){e.text.length>0&&(yield{type:"assistant.message",text:e.text,sessionId:t.ctx.sessionId}),yield{type:"notice",text:`The model stopped with a content-safety refusal (stop_reason: "refusal") and returned no output. This is Anthropic's safety system declining the request \u2014 not an afk error. Because the flagged context stays in the conversation, follow-up messages will likely be refused the same way; rephrase the request or start a fresh session to continue.`,kind:"refusal",sessionId:t.ctx.sessionId},yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:t.ctx.sessionId};return}let r=yo(e.stopReason)?WS(e.toolUseBlocks.map(i=>i.name),e.stopReason):null;e.text.length>0?(yield{type:"assistant.message",text:r?`${e.text}
1482
+ `)}var yk=b(()=>{"use strict";zt()});function IX(e){let{config:t,cwd:n}=e,r=e.hasSkillExecutor?kv(void 0,{cwd:n,...typeof t.skillDispatchName=="string"&&t.skillDispatchName.length>0?{excludeName:t.skillDispatchName}:{}}):"",o=BS(t.isSkillDispatch),i=US(e.readOnlyMemory),s=jS(e.workspaceEnabled),a={surface:e.surface,sessionId:t.sessionId,depth:t.depth,maxDepth:t.maxDepth,workspace:e.runtimeStateSource.getWorkspace()},l={toolBase:o,memoryPrompt:i,workspacePrompt:s,hotMemory:t.hotMemory??"",manifest:r,userSystem:e.userSystem};return{stableSystemPrefix:l,toolSystemAppend:od(l,n,a)}}var MX=b(()=>{"use strict";Ir();FI();yk()});import G0e from"@anthropic-ai/sdk";function OX(e){if(e===void 0)return null;if(typeof e=="string")return e.length>0?e:null;if(typeof e=="object"&&e!==null&&"append"in e){let t=e.append;return t&&t.length>0?t:null}return null}function $X(e,t,n,r){let o=t.config,{localMode:i,token:s}=Vq(o);if(!s||s.length===0)throw new Error(`${n} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let a=lb(s),{client:l,throttleQueue:c,systemPrefix:u,tokenRefresher:d}=uz({config:o,token:s,authMode:a,localMode:i,factory:e.providerFactory??AS(),createClient:R=>new G0e(R)}),p=OX(o.systemPrompt),f=typeof o.model=="string"&&o.model.length>0?Lt(o.model)??o.model:r,g=yb(o,f),h=o.permissionMode??"default";e.setCurrentPermissionMode(h),e.ensureSharedRoots(o.cwd),o.cwd&&e.setCurrentCwd(o.cwd);let y=e.getSharedReadRoots(),w=e.getSharedWriteRoots();o.readRoots&&y&&y.length<=1&&(y.length=0,y.push(...o.readRoots)),o.writeRoots&&w&&w.length<=1&&(w.length=0,w.push(...o.writeRoots));let{queryDispatcher:S,runtimeStateSource:v,toolDefs:x,resolvedSessionId:T}=Sz({config:o,model:f,permissionMode:h,surface:e.surface,providerName:n,externalTools:e.externalTools,sharedReadRoots:y,sharedWriteRoots:w,getCwd:()=>e.getCurrentCwd()||o.cwd||process.cwd(),getMcpTools:()=>e.mcpManager?.getMcpTools()??[],getSubagents:()=>e.subagentExecutor?e.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]},getMintedSessionId:()=>e.getMintedSessionId(),setMintedSessionId:R=>{e.setMintedSessionId(R)},getPresenceSessionId:()=>e.getPresenceSessionId(),setPresenceSessionId:R=>{e.setPresenceSessionId(R)},buildDispatcher:(R,C)=>e.buildDispatcher(R,C)}),E=o.cwd||process.cwd(),{stableSystemPrefix:_,toolSystemAppend:P}=IX({config:o,cwd:E,surface:e.surface,readOnlyMemory:e.readOnlyMemory,workspaceEnabled:e.workspaceStore!==void 0,hasSkillExecutor:!!e.skillExecutor,runtimeStateSource:v,userSystem:p});return KU({prompt:t.prompt,options:{model:f,maxTokens:g,system:P},provenance:{systemPrompt:{source:o.systemPromptSource??"none",shape:typeof o.systemPrompt=="string"?"string":Array.isArray(o.systemPrompt)?"string[]":o.systemPrompt!=null?"preset":"undefined",...typeof o.systemPrompt=="string"?{length:o.systemPrompt.length}:{}},...o.apiKey?{apiKey:{source:"config"}}:{}}}),{client:l,authMode:a,localMode:i,model:f,maxTokens:g,cwd:E,systemPrefix:u,throttleQueue:c,tokenRefresher:d,queryDispatcher:S,runtimeStateSource:v,toolDefs:x,resolvedSessionId:T,stableSystemPrefix:_,toolSystemAppend:P}}var I0=b(()=>{"use strict";ga();Yn();Sb();Yq();CS();dz();vz();MX();Uo()});function DX(e){let t=e.initialUsageInputTokens!==void 0&&e.initialUsageInputTokens>0?{inputTokens:e.initialUsageInputTokens,stopReason:null,resultSubtype:"success",isError:!1}:null;return{messages:e.initialMessages?[...e.initialMessages]:[],currentModel:e.model,requestedModel:e.requestedModel??e.model,currentPermissionMode:e.permissionMode,userSystem:e.userSystem,toolDispatcher:e.toolDispatcher,lastUsage:t,closed:!1,autoCompactThreshold:e.autoCompactThreshold}}var LX=b(()=>{"use strict"});function ug(e){if(typeof e?.baseUrl=="string"&&e.baseUrl.length>0)return!1;let t=k.AFK_DISABLE_PROMPT_CACHE;if(t===void 0||t.length===0)return!0;let n=t.toLowerCase();return!(n==="1"||n==="true"||n==="yes"||n==="on")}function cl(){let e=k.AFK_PROMPT_CACHE_TTL;return e==="5m"?"5m":e==="1h"?"1h":q0e}function bk(e){return ug(e)&&cl()==="1h"}function FX(e,t){if(e.length===0)return e;let n=e[e.length-1],r=BX(n,t);return r===n?e:[...e.slice(0,-1),r]}function NX(e,t){if(e.length===0)return e;let n=e[e.length-1],r=z0e(n,t);return r===n?e:[...e.slice(0,-1),r]}function z0e(e,t){let n=e.content;if(typeof n=="string")return n.length===0?e:{...e,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:t}}]};if(!Array.isArray(n)||n.length===0)return e;let r=n[n.length-1],o=BX(r,t);return o===r?e:{...e,content:[...n.slice(0,-1),o]}}function BX(e,t){return e.type==="thinking"||e.type==="redacted_thinking"?e:{...e,cache_control:{type:"ephemeral",ttl:t}}}var q0e,id=b(()=>{"use strict";F();q0e="1h"});var M0=b(()=>{"use strict";Wi()});function Z0e(e){let t=n=>n===void 0?void 0:n*O0;return{inputPerMTok:e.inputPerMTok*O0,outputPerMTok:e.outputPerMTok*O0,...t(e.cacheWrite5mPerMTok)!==void 0?{cacheWrite5mPerMTok:t(e.cacheWrite5mPerMTok)}:{},...t(e.cacheWrite1hPerMTok)!==void 0?{cacheWrite1hPerMTok:t(e.cacheWrite1hPerMTok)}:{},...t(e.cacheReadPerMTok)!==void 0?{cacheReadPerMTok:t(e.cacheReadPerMTok)}:{}}}function eOe(e){return e.responseSpeed??e.requestSpeed??"standard"}function tOe(e){return _u(e,UX,X0e)}function $0(e,t,n,r,o,i,s={}){let a=tOe(e);if(!a)return;let l=eOe(s)==="fast"&&Q0e.test(e)?Z0e(a):a,c=1e6,u=cn(t),d=cn(n),p=cn(r),f=cn(o),g=u/c*l.inputPerMTok,h=d/c*l.outputPerMTok,y=l.cacheWrite5mPerMTok??l.inputPerMTok*J0e,w=l.cacheWrite1hPerMTok??l.inputPerMTok*V0e,S=l.cacheReadPerMTok??l.inputPerMTok*Y0e,v=i??{ephemeral5m:f,ephemeral1h:0},x=cn(v.ephemeral5m),T=cn(v.ephemeral1h),E=Math.max(0,f-(x+T)),_=x/c*y+T/c*w+E/c*w,P=p/c*S;return g+h+_+P}var J0e,V0e,Y0e,UX,X0e,O0,Q0e,D0=b(()=>{"use strict";GS();J0e=1.25,V0e=2,Y0e=.1,UX=new Map([["claude-sonnet-5",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-opus-5",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-8",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-7",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-6",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-sonnet-4-6",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-sonnet-4-5-20250929",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-opus-4-5-20250929",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-haiku-4-5-20250929",{inputPerMTok:1,outputPerMTok:5,cacheWrite5mPerMTok:1.25,cacheWrite1hPerMTok:2,cacheReadPerMTok:.1}],["claude-haiku-4-5-20251001",{inputPerMTok:1,outputPerMTok:5,cacheWrite5mPerMTok:1.25,cacheWrite1hPerMTok:2,cacheReadPerMTok:.1}],["claude-3-7-sonnet-20250219",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20241022",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20240620",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-haiku-20241022",{inputPerMTok:.8,outputPerMTok:4,cacheWrite5mPerMTok:1,cacheWrite1hPerMTok:1.6,cacheReadPerMTok:.08}],["claude-3-opus-20240229",{inputPerMTok:15,outputPerMTok:75,cacheWrite5mPerMTok:18.75,cacheWrite1hPerMTok:30,cacheReadPerMTok:1.5}],["claude-3-sonnet-20240229",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-haiku-20240307",{inputPerMTok:.25,outputPerMTok:1.25,cacheWrite5mPerMTok:.3,cacheWrite1hPerMTok:.5,cacheReadPerMTok:.03}]]),X0e=/-\d{8}$/,O0=2,Q0e=/^claude-opus-(?:5|4-8)(?:-|$)/});function nOe(e){let t=e.speed;return t==="fast"||t==="standard"?t:void 0}function rOe(e){let t=o=>Number.isFinite(o)&&o>=0?o:0,n=e.cache_creation;if(n)return{ephemeral5m:t(n.ephemeral_5m_input_tokens??0),ephemeral1h:t(n.ephemeral_1h_input_tokens??0)};let r=t(e.cache_creation_input_tokens??0);return cl()==="1h"?{ephemeral5m:0,ephemeral1h:r}:{ephemeral5m:r,ephemeral1h:0}}function L0(e,t,n,r){if(!e)return{stopReason:t??null};let o=nOe(e),i={inputTokens:e.input_tokens,outputTokens:e.output_tokens,stopReason:t??null,raw:{...e,...o?{speed:o}:{}}};if(e.cache_read_input_tokens!=null&&(i.cachedInputTokens=e.cache_read_input_tokens),e.cache_creation_input_tokens!=null&&(i.cacheCreationTokens=e.cache_creation_input_tokens),i.totalTokens=(e.input_tokens??0)+(e.output_tokens??0),n){let s=$0(n,e.input_tokens??0,e.output_tokens??0,e.cache_read_input_tokens??0,e.cache_creation_input_tokens??0,rOe(e),{...r?{requestSpeed:r}:{},...o?{responseSpeed:o}:{}});s!==void 0&&(i.totalCostUsd=s)}return i}var jX=b(()=>{"use strict";id();D0()});var F0=b(()=>{"use strict";D0();jX();NI()});function dg(e){return e>2147483647?2147483647:e}var N0=b(()=>{"use strict"});function WX(){let e=k.AFK_MODEL_TTFB_TIMEOUT_MS;if(e===void 0||e.trim()==="")return HX;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<0?HX:dg(t)}function KX(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?void 0:(e<sOe?e:aOe)+iOe}function GX(e,t){if(t<=0)return{signal:e,timedOut:()=>!1,firstByteSeen:()=>{},extend:()=>{},dispose:()=>{}};let n=new AbortController,r=AbortSignal.any([e,n.signal]),o=!1,i=!1,s=Date.now()+t,a,l=d=>{a=setTimeout(()=>{o=!0,n.abort(new Error(oOe))},dg(d)),a.unref()};l(t);let c=()=>{i||(i=!0,clearTimeout(a))};return{signal:r,timedOut:()=>o,firstByteSeen:c,extend:d=>{i||o||typeof d!="number"||!Number.isFinite(d)||d<=0||(s+=d,clearTimeout(a),l(Math.max(1,s-Date.now())))},dispose:c}}var HX,oOe,iOe,sOe,aOe,B0=b(()=>{"use strict";F();N0();HX=18e4;oOe="model_ttfb_timeout",iOe=3e4,sOe=6e4,aOe=8e3});function zX(){let e=k.AFK_MODEL_STALL_TIMEOUT_MS;if(e===void 0||e.trim()==="")return qX;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<0?qX:dg(t)}function VX(e){return e instanceof Error&&e.message===JX}function U0(e){return new Error(`Model stream stalled: no output for ${Math.round(e/1e3)}s after the response had already started streaming. The round was aborted rather than left hanging (issue #762: two sessions hung 38 and 63 minutes with no terminal event). A round that keeps producing output is never cut off, no matter how long it runs. Raise AFK_MODEL_STALL_TIMEOUT_MS, or set it to 0 to disable this bound.`)}function YX(e,t,n){if(t<=0)return{signal:e,timedOut:()=>!1,progress:()=>{},dispose:()=>{}};let r=new AbortController,o=AbortSignal.any([e,r.signal]),i,s=!1,a=!1,l=d=>{if(!(a||s)){s=!0,i=void 0;try{n?.({stallTimeoutMs:t,elapsedSinceLastProgressMs:Date.now()-d})}catch{}r.signal.aborted||r.abort(new Error(JX))}};return{signal:o,timedOut:()=>s,progress:()=>{if(a||s)return;i!==void 0&&clearTimeout(i);let d=Date.now(),p=setTimeout(()=>l(d),t);p.unref(),i=p},dispose:()=>{a||(a=!0,i!==void 0&&clearTimeout(i),i=void 0)}}}var qX,JX,wk=b(()=>{"use strict";F();N0();qX=12e5;JX="model_stream_stall_timeout"});function Sk(e,t=Math.random){return e+Math.floor(t()*e*dOe)}function QX(e=Math.random){let t=uOe-XX;return XX+Math.floor(e()*t)}function ZX(e){return e.type==="turn.completed"&&e.usage.stopReason===Hn}function e8(e){let t=k.AFK_OVERLOAD_PAUSE_MS;if(t!==void 0&&t.trim()!==""){let n=Number(t);if(Number.isFinite(n)&&n>=0)return Math.min(Math.floor(n),cOe)}return e!==void 0&&pOe.has(e)?lOe:0}var j0,lOe,cOe,XX,uOe,dOe,pOe,pg=b(()=>{"use strict";F();Gu();Gu();j0="Anthropic is overloaded (HTTP 529) and did not recover within this turn's retry budget. This is an upstream capacity event, not an afk error. The turn was committed, so the conversation so far is preserved \u2014 resume with `afk --resume <sessionId>` to continue from saved state once capacity frees up.",lOe=600*1e3,cOe=7200*1e3,XX=60*1e3,uOe=120*1e3,dOe=.25;pOe=new Set(["cli","repl","telegram","web"])});function t8(e){if(!Number.isFinite(e)||e<=0)return 0;let t=Math.floor(e*2/3);return Math.max(1,t)}function n8(e){if(!("status"in e))return!1;let t=e.status;return t===529||t===503}function mg(e){if(e===null||typeof e!="object")return!1;let t=e;if(t.status===529||t.status===503)return!0;let n=t.error;if(n===null||typeof n!="object")return!1;let r=n;return((r.error!==null&&typeof r.error=="object"?r.error.type:void 0)??r.type)==="overloaded_error"}var vk,fg=b(()=>{"use strict";vk=class{overloadRetries=0;streamIncompleteRetries=0;ttfbRetries=0;canRetryOverload(){return this.overloadRetries<3}canRetryStreamIncomplete(){return this.streamIncompleteRetries<2}canRetryTtfb(){return this.ttfbRetries<2}reset(){this.overloadRetries=0,this.streamIncompleteRetries=0,this.ttfbRetries=0}}});async function*fOe(e,t,n){oe(e.traceWriter,{phase:"ttfb_timeout",durationMs:Date.now()-t,metadata:{reason:"ttfb-timeout",source:"first-byte",resolvedModel:e.model,attempt:n}}),yield{type:"stream.retry",sessionId:e.ctx.sessionId}}async function*W0(e,{input:t,turn:n,retry:r,requestStartedAt:o}){return e==="ttfb"?(r.ttfbRetries+=1,yield*fOe(t,o,r.ttfbRetries),"continue"):e==="overload"?(r.overloadRetries+=1,oe(t.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:r.overloadRetries}}),yield{type:"stream.retry",sessionId:t.ctx.sessionId},yield*r8(Sk(5e3*Math.pow(2,r.overloadRetries-1)),t,n),t.signal.aborted?"terminated":"continue"):(r.streamIncompleteRetries+=1,oe(t.traceWriter,{phase:"rate_limit",metadata:{reason:"stream-incomplete",source:"mid-stream",attempt:r.streamIncompleteRetries}}),yield{type:"stream.retry",sessionId:t.ctx.sessionId},yield*r8(1e3*Math.pow(2,r.streamIncompleteRetries-1),t,n),t.signal.aborted?"terminated":"continue")}async function*r8(e,t,n){await an(e,t.signal),t.signal.aborted&&(yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:t.ctx.sessionId})}var o8=b(()=>{"use strict";fe();Zi();pg();fg()});function s8(e){let t=e.fastModeController?.snapshotTurn({resolvedModelId:e.model,providerFamily:"anthropic-direct",hasCustomEndpoint:e.baseUrl!==void 0,executionPath:"top-level"}),n=t?.effective===!0,r=Oi(e.authMode,e.sessionId,e.requestId,e.effort!==void 0,bk(e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}),n);return{decision:t,runInput:{client:e.client,messages:e.messages,system:e.system,tools:e.tools,toolDispatcher:e.toolDispatcher,model:e.model,maxTokens:e.maxTokens,headers:r,signal:e.signal,ctx:{sessionId:e.sessionId},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...n?{fastMode:!0}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.maxToolUseIterations!==void 0?{maxToolUseIterations:e.maxToolUseIterations}:{},...e.softDeadlineMs!==void 0?{softDeadlineMs:e.softDeadlineMs}:{},...e.traceWriter?{traceWriter:e.traceWriter}:{},...e.subagentId!==void 0?{subagentId:e.subagentId}:{},...e.throttleQueue?{throttleQueue:e.throttleQueue}:{},...e.onUsageProgress?{onUsageProgress:e.onUsageProgress}:{},...e.beforeNextRound?{beforeNextRound:e.beforeNextRound}:{}}}}function kk(e,t){let n=e instanceof Error?e:new Error(String(e));if(!t||n.message.startsWith(i8))return n;let r=new Error(`${i8} ${n.message}`,{cause:n});r.name=n.name,n.stack!==void 0&&(r.stack=n.stack);for(let o of Object.getOwnPropertyNames(n)){if(o==="message"||o==="stack")continue;let i=Object.getOwnPropertyDescriptor(n,o);i!==void 0&&Object.defineProperty(r,o,i)}return r}var i8,K0=b(()=>{"use strict";ga();id();i8="[Fast mode requested; no standard-mode fallback will be attempted]"});async function*a8(e,t,n){let r=t.throttleQueue;if(!r)return await e;r.resetAttempts();let o=Symbol("create-done"),i=!1,s=e.then(a=>(i=!0,a),a=>{throw i=!0,a});for(;;){for(let l of r.takeAll())n?.(l.retryAfterMs),yield{type:"rate_limit",sessionId:t.ctx.sessionId,status:l.status,attempt:l.attempt,...l.retryAfterMs!==void 0?{retryAfterMs:l.retryAfterMs}:{}};if(i)return await s;await Promise.race([s.then(()=>o,()=>o),r.waitForItem().then(()=>{})])}}var l8=b(()=>{"use strict"});function c8(e,t){try{let n=[];for(let r=0;r<e.length;r++){let o=e[r];if(o.role!=="assistant"||typeof o.content=="string")continue;let i=o.content;for(let s=0;s<i.length;s++){let a=i[s];if(a.type==="thinking"){let l=a;(!l.thinking||!l.signature)&&n.push({msgIdx:r,blockIdx:s,thinking:l.thinking?`(${l.thinking.length} chars)`:"(empty)",sigLen:l.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",t.message),console.error(`[afk] messages.length=${e.length}, invalid thinking blocks:`,n.length>0?JSON.stringify(n):"none found (cause may be elsewhere)")}catch{}}var u8=b(()=>{"use strict"});function gOe(e){let{name:t,description:n,input_schema:r}=e;return{name:t,...n!==void 0?{description:n}:{},input_schema:r}}async function hOe(e,t,n,r,o){for(let i=0;;i++){if(i>0){let s=Sk(5e3*Math.pow(2,i-1));if(await an(s,o),o.aborted)throw new Error("aborted")}try{return await Promise.resolve(e.messages.create(t,{headers:n,signal:r}))}catch(s){if(r.aborted)throw s;let a=s instanceof Error?s:new Error(String(s));if(n8(a)){if(i<3)continue;throw new Tk}throw a}}}function yOe(e){return{model:e.model,max_tokens:e.maxTokens,messages:e.messages,stream:!0,...e.system!==null?{system:e.system}:{},...e.tools!==null&&e.tools.length>0?{tools:e.tools.map(gOe)}:{},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{output_config:{effort:e.effort}}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.fastMode===!0?{speed:"fast"}:{}}}async function*d8({input:e,turn:t,retry:n,ttfbTimeoutMs:r,stallTimeoutMs:o}){let i=ug({baseUrl:e.baseUrl})?NX(e.messages,cl()):e.messages,s=yOe({...e,messages:i,tools:t.windDownReason!==null?null:e.tools}),a=Date.now(),l=GX(e.signal,r),c=YX(l.signal,o,u=>{oe(e.traceWriter,{phase:"idle_watchdog_fired",durationMs:u.elapsedSinceLastProgressMs,resolvedModel:e.model,metadata:{source:"model-stream",stallTimeoutMs:u.stallTimeoutMs,elapsedSinceLastProgressMs:u.elapsedSinceLastProgressMs}})});try{return{kind:"opened",events:yield*a8(hOe(e.client,s,e.headers,c.signal,e.signal),e,d=>{let p=KX(d);p!==void 0&&l.extend(p)}),ttfb:l,stall:c,requestStartedAt:a}}catch(u){if(l.timedOut()&&!e.signal.aborted&&n.canRetryTtfb())return l.dispose(),c.dispose(),{kind:"retry-ttfb",requestStartedAt:a};if(l.dispose(),c.dispose(),e.signal.aborted)return yield{type:"turn.completed",usage:t.terminalUsage(),sessionId:e.ctx.sessionId},{kind:"terminated"};if(u instanceof Tk)return{kind:"overload-exhausted"};let d=kk(u,e.fastMode===!0);return d.message.includes("thinking")&&c8(e.messages,d),yield{type:"error",error:d},{kind:"terminated"}}}var Tk,p8=b(()=>{"use strict";K0();id();fe();Zi();B0();wk();pg();fg();l8();u8();Tk=class extends Error{constructor(){super("Connection-phase overload budget exhausted"),this.name="ConnectionOverloadExhaustedError"}}});function m8(e,t){return e||t!==null}function f8(){return new zn("the model stream ended without a terminal message (no message_stop and no stop_reason): the turn is incomplete. The cause is not knowable at this layer \u2014 a client-side abort carrying an AbortError reason (including the SDK request timeout) and an upstream peer close are indistinguishable here. Check the trace for a preceding ttfb_timeout, idle_watchdog_fired, or rate_limit phase before suspecting the network.")}var g8=b(()=>{"use strict";He()});function bOe(e){let t=e.trim();if(t.length===0)return{};try{return JSON.parse(t)}catch{return{}}}function wOe(e,t,n){let r=[],o=[];for(let a of e)a&&(a.kind==="text"?(r.push({type:"text",text:a.text}),o.push(a.text)):a.kind==="thinking"?a.thinking&&a.signature&&r.push({type:"thinking",thinking:a.thinking,signature:a.signature}):a.kind==="redacted_thinking"?r.push({type:"redacted_thinking",data:a.data}):r.push({type:"tool_use",id:a.id,name:a.name,input:bOe(a.partialJson)}));let i=a=>a.type==="tool_use",s=r.filter(i);return{stopReason:t,assistantBlocks:r,toolUseBlocks:s,usage:n,text:o.join("")}}async function*h8(e,t,n){let r=[],o=null,i=null,s=!1,a=!!k.AFK_TELEGRAM_TRACE;try{a&&console.log("[translate] starting SDK event iteration");for await(let l of e){switch(a&&console.log("[translate] SDK evt:",l.type),l.type){case"message_start":{let c=l.message?.usage;c&&(i={...c});break}case"content_block_start":{let c=l.content_block;c.type==="text"?r[l.index]={kind:"text",text:""}:c.type==="thinking"?r[l.index]={kind:"thinking",thinking:"",signature:""}:c.type==="redacted_thinking"?r[l.index]={kind:"redacted_thinking",data:c.data}:c.type==="tool_use"&&(r[l.index]={kind:"tool_use",id:c.id,name:c.name,partialJson:""},yield{kind:"event",event:{type:"tool.use.start",toolUseId:c.id,toolName:c.name,toolInput:" \u2026",pending:!0,sessionId:t.sessionId}});break}case"content_block_delta":{let c=r[l.index],u=l.delta;u.type==="text_delta"?(c&&c.kind==="text"&&(c.text+=u.text),yield{kind:"event",event:{type:"delta.text",text:u.text,sessionId:t.sessionId}}):u.type==="input_json_delta"?(c&&c.kind==="tool_use"&&(c.partialJson+=u.partial_json),n?.()):u.type==="thinking_delta"?(c&&c.kind==="thinking"&&(c.thinking+=u.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:u.thinking,sessionId:t.sessionId}}):(u.type==="signature_delta"&&c&&c.kind==="thinking"&&(c.signature=u.signature),n?.());break}case"content_block_stop":{let c=r[l.index];c&&c.kind==="tool_use"&&(yield{kind:"event",event:{type:"tool.use",summary:c.name,toolUseIds:[c.id],sessionId:t.sessionId}});break}case"message_delta":{l.delta&&l.delta.stop_reason!==void 0&&(o=l.delta.stop_reason);let c=l.usage;c&&(i!==null?(i.output_tokens=c.output_tokens,c.cache_creation_input_tokens!=null&&(i.cache_creation_input_tokens=c.cache_creation_input_tokens),c.cache_read_input_tokens!=null&&(i.cache_read_input_tokens=c.cache_read_input_tokens),c.input_tokens!=null&&(i.input_tokens=c.input_tokens)):i={cache_creation:null,cache_creation_input_tokens:c.cache_creation_input_tokens??null,cache_read_input_tokens:c.cache_read_input_tokens??null,inference_geo:null,input_tokens:c.input_tokens??0,output_tokens:c.output_tokens,server_tool_use:null,service_tier:null});break}case"message_stop":{s=!0;break}default:break}if(s)break}a&&console.log("[translate] SDK iteration ended naturally, stopped=",s)}catch(l){a&&console.log("[translate] SDK iteration threw:",l.message),yield{kind:"event",event:{type:"error",error:l instanceof Error?l:new Error(String(l))}};return}if(!m8(s,o)){yield{kind:"event",event:{type:"error",error:f8()}};return}a&&console.log("[translate] yielding turn-result"),yield{kind:"turn-result",result:wOe(r,o,i)}}var y8=b(()=>{"use strict";F();g8()});async function*b8({events:e,input:t,turn:n,retry:r,ttfb:o,stall:i,stallTimeoutMs:s,requestStartedAt:a}){let l=null,c=!1,u=!1,d=!1,p=!1,f=!1,g=!1;try{k.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let h of h8($u(e,t.signal),t.ctx,()=>i.progress()))if(!g&&(h.kind==="turn-result"||h.event.type!=="error")&&(g=!0,o.firstByteSeen(),oe(t.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-a,resolvedModel:t.model})),i.progress(),k.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",h.kind,h.kind==="event"?h.event.type:""),h.kind==="event"){if(h.event.type==="error"){if(o.timedOut()&&!t.signal.aborted&&r.canRetryTtfb()&&!g){u=!0;break}if(i.timedOut()&&!t.signal.aborted){yield{type:"error",error:U0(s)},c=!0;break}if(mg(h.event.error)&&r.canRetryOverload()&&!t.signal.aborted){d=!0;break}if(mg(h.event.error)&&!t.signal.aborted){f=!0;break}if(t.signal.aborted)break;if(h.event.error instanceof zn&&r.canRetryStreamIncomplete()&&!t.signal.aborted){p=!0;break}yield h.event,c=!0;break}yield h.event}else{l=h.result;break}k.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",l?"set":"null")}catch(h){if(o.timedOut()&&!t.signal.aborted&&r.canRetryTtfb()&&!g)o.dispose(),i.dispose(),u=!0;else{if(o.dispose(),i.dispose(),t.signal.aborted)return yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:t.ctx.sessionId},{kind:"terminated"};let y=h instanceof Error?h:new Error(String(h));if((i.timedOut()||VX(y))&&!t.signal.aborted)return yield{type:"error",error:U0(s)},{kind:"terminated"};if(mg(y)&&r.canRetryOverload()&&!t.signal.aborted)d=!0;else if(mg(y)&&!t.signal.aborted)f=!0;else return yield{type:"error",error:y},{kind:"terminated"}}}return o.dispose(),i.dispose(),u?{kind:"retry",reason:"ttfb"}:d?{kind:"retry",reason:"overload"}:p?{kind:"retry",reason:"stream-incomplete"}:f?{kind:"overload-exhausted"}:c?{kind:"translator-errored"}:{kind:"streamed",turnResult:l}}var w8=b(()=>{"use strict";y8();He();tv();fe();F();wk();fg()});async function*S8(e,t,n){let r=[],o=new Map;for(let s of e.toolUseBlocks)r.push({id:s.id,name:s.name,input:s.input,signal:t.signal}),o.set(s.id,Date.now()),pa(t.traceWriter,uv({toolUseId:s.id,name:s.name,input:s.input,subagentId:t.subagentId})),yield{type:"tool.use.start",toolUseId:s.id,toolName:s.name,toolInput:ls(s.name,s.input),toolInputRaw:lv(s.input),toolInputCapture:k.AFK_CAPTURE_SUBAGENT_OUTPUT!=="0"?cv(s.input):void 0,sessionId:t.ctx.sessionId};if(t.signal.aborted){let s=r.map(a=>({type:"tool_result",tool_use_id:a.id,content:"Tool call aborted",is_error:!0}));return t.messages.push({role:"user",content:s}),yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:t.ctx.sessionId},{kind:"aborted"}}let i;if(t.toolDispatcher.executeBatch)i=yield*mv(async s=>{try{return await t.toolDispatcher.executeBatch(r,a=>{s({type:"tool.activity",activeCount:a.length,activeToolUseIds:[...a],sessionId:t.ctx.sessionId})})}catch(a){return r.map(()=>({content:`Tool batch execution failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}))}});else{i=[];for(let s of r){if(t.signal.aborted){i.push({content:"Tool call aborted",isError:!0,failureClass:rn(t.signal)});continue}try{i.push(await t.toolDispatcher.execute(s))}catch(a){let l=a instanceof Error?a.message:String(a);i.push({content:`Tool execution threw: ${l}`,isError:!0})}}}return{kind:"dispatched",calls:r,results:i,startTimes:o}}var v8=b(()=>{"use strict";Ni();fe();uM();F();zf();pv();dM()});async function*k8(e,t,n,r){let o=[];for(let l=0;l<e.length;l++){let c=e[l],u=t[l],d=n.get(c.id),p=typeof d=="number"?Date.now()-d:0,f=u.truncated===!0||u.content.includes("[output truncated");pa(r.traceWriter,dv({toolUseId:c.id,name:c.name,result:u,truncated:f,durationMs:p,subagentId:r.subagentId})),yield{type:"tool.output",toolUseId:c.id,toolName:c.name,content:u.content,...u.isError===!0?{isError:!0}:{},...f?{truncated:!0}:{},...u.capturePath!==void 0?{capturePath:u.capturePath}:{},...u.incomplete===!0?{incomplete:!0}:{},...u.incompleteReason?{incompleteReason:u.incompleteReason}:{},...typeof u.batchIndex=="number"&&typeof u.batchSize=="number"?{batchIndex:u.batchIndex,batchSize:u.batchSize}:{},...u.failureClass?{failureClass:u.failureClass}:{},durationMs:u.durationMs!==void 0?u.durationMs:p,...u.exitCode!==void 0?{exitCode:u.exitCode}:{},sessionId:r.ctx.sessionId},u.render?.diff&&(yield{type:"tool.diff",toolUseId:c.id,diff:u.render.diff,sessionId:r.ctx.sessionId});let{content:g,isError:h,image:y}=u,w=y!==void 0?[{type:"image",source:{type:"base64",media_type:y.mediaType,data:y.data}},...g.length>0?[{type:"text",text:g}]:[]]:g;o.push({type:"tool_result",tool_use_id:c.id,content:w,...h===!0?{is_error:!0}:{}})}let i=t.flatMap(l=>l.harnessUserMessage?.kind==="queued_user_message"?[{type:"text",text:l.harnessUserMessage.text}]:[]),s={role:"user",content:[...o,...i]};r.messages.push(s);let a=t.find(l=>l.failureClass===qc);return a?(yield{type:"error",error:new Tc(a.content)},"denial-tripped"):"committed"}var T8=b(()=>{"use strict";fe();pv();Fm();He()});async function*x8(e,t,n,r,o){let i=t.messages.length;t.messages.push({role:"assistant",content:e.assistantBlocks});try{n.toolCallCount+=e.toolUseBlocks.length;let u=yield*S8(e,t,n);if(u.kind==="aborted"||(yield*k8(u.calls,u.results,u.startTimes,t))==="denial-tripped")return"terminated"}catch(u){throw t.messages.splice(i),u}n.iterations+=1;let s=e.toolUseBlocks[e.toolUseBlocks.length-1],a=s?`${s.name}${ls(s.name,s.input)}`:"unknown";if(yield{type:"progress",progress:{taskId:n.taskId,description:"Working",summary:`${yv(n.iterations,r)}: ${a}`,lastToolName:s?.name,totalTokens:n.usage.totalTokens??0,toolUses:n.toolCallCount,durationMs:Date.now()-n.startedAt},sessionId:t.ctx.sessionId},n.windDownReason!==null)return yield{type:"turn.completed",usage:n.withDuration({...n.usage,stopReason:n.windDownReason}),sessionId:t.ctx.sessionId},"terminated";let l=hv(n.iterations,r),c=Sv(n.startedAt,o);if(l||c){let u=l?fv:bv,d=t.messages[t.messages.length-1];d!==void 0&&d.role==="user"&&Array.isArray(d.content)&&d.content.push({type:"text",text:u}),n.windDownReason=l?Mr:Or}return"continue"}var E8=b(()=>{"use strict";zf();cs();Lu();v8();T8()});function*R8(e,t,n){if(e.stopReason==="refusal"){e.text.length>0&&(yield{type:"assistant.message",text:e.text,sessionId:t.ctx.sessionId}),yield{type:"notice",text:`The model stopped with a content-safety refusal (stop_reason: "refusal") and returned no output. This is Anthropic's safety system declining the request \u2014 not an afk error. Because the flagged context stays in the conversation, follow-up messages will likely be refused the same way; rephrase the request or start a fresh session to continue.`,kind:"refusal",sessionId:t.ctx.sessionId},yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:t.ctx.sessionId};return}let r=yo(e.stopReason)?WS(e.toolUseBlocks.map(i=>i.name),e.stopReason):null;e.text.length>0?(yield{type:"assistant.message",text:r?`${e.text}
1483
1483
 
1484
1484
  ${r}`:e.text,sessionId:t.ctx.sessionId},e.text.length<=SOe&&(yield{type:"suggestion",suggestion:e.text,sessionId:t.ctx.sessionId})):r!==null&&(yield{type:"notice",text:r,kind:"truncation",sessionId:t.ctx.sessionId});let o=e.assistantBlocks.filter(i=>i.type!=="tool_use");o.length>0&&t.messages.push({role:"assistant",content:o}),yield{type:"turn.completed",usage:n.withDuration(n.windDownReason!==null?{...n.usage,stopReason:n.windDownReason}:n.usage),sessionId:t.ctx.sessionId}}var SOe,A8=b(()=>{"use strict";Df();SOe=200});import{randomUUID as vOe}from"node:crypto";var Ek,C8=b(()=>{"use strict";F0();Ek=class{usage={stopReason:null};iterations=0;toolCallCount=0;windDownReason=null;taskId=vOe();startedAt=Date.now();elapsedMs(){return Date.now()-this.startedAt}withDuration(t){return{...t,durationMs:this.elapsedMs()}}terminalUsage(){return this.withDuration(this.usage)}addRoundUsage(t){this.usage=$f(this.usage,t),this.usage.contextWindowTokens=(t.inputTokens??0)+(t.outputTokens??0)+(t.cachedInputTokens??0)+(t.cacheCreationTokens??0)}}});function _8(e,t){if(!t)return;let n=e.messages.at(-1);!n||n.role!=="user"||(Array.isArray(n.content)?n.content.push({type:"text",text:t}):n.content=[{type:"text",text:n.content},{type:"text",text:t}],ab(e.traceWriter,{jobId:e.subagentId??"",subagentId:e.subagentId??"",byteLength:Buffer.byteLength(t,"utf8")}))}var P8=b(()=>{"use strict";fe()});async function*G0(e){let t=gv(e.maxToolUseIterations),n=e.softDeadlineMs??0,r=new Ek,o=new vk,i=c=>({input:e,turn:r,retry:o,requestStartedAt:c}),s=t8(WX()),a=zX(),l=new Ru(e.signal,e.traceWriter,"anthropic-direct");try{for(;;){if(e.signal.aborted){yield{type:"turn.completed",usage:r.terminalUsage(),sessionId:e.ctx.sessionId};return}let c=yield*d8({input:e,turn:r,retry:o,ttfbTimeoutMs:s,stallTimeoutMs:a});if(c.kind==="terminated")return;if(c.kind==="retry-ttfb"){if((yield*W0("ttfb",i(c.requestStartedAt)))==="terminated")return;continue}if(c.kind==="overload-exhausted"){oe(e.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"connection-phase",attempt:3,exhausted:!0}}),yield{type:"assistant.message",text:j0,sessionId:e.ctx.sessionId},yield{type:"turn.completed",usage:r.withDuration({...r.usage,stopReason:Hn}),sessionId:e.ctx.sessionId};return}let{events:u,ttfb:d,stall:p,requestStartedAt:f}=c,g=yield*b8({events:u,input:e,turn:r,retry:o,ttfb:d,stall:p,stallTimeoutMs:a,requestStartedAt:f});if(g.kind==="terminated")return;if(g.kind==="retry"){if((yield*W0(g.reason,i(f)))==="terminated")return;continue}if(o.reset(),g.kind==="overload-exhausted"){oe(e.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:3,exhausted:!0}}),yield{type:"assistant.message",text:j0,sessionId:e.ctx.sessionId},yield{type:"turn.completed",usage:r.withDuration({...r.usage,stopReason:Hn}),sessionId:e.ctx.sessionId};return}if(g.kind==="translator-errored"){e.signal.aborted&&(yield{type:"turn.completed",usage:r.terminalUsage(),sessionId:e.ctx.sessionId});return}let h=g.turnResult;if(h===null){yield{type:"turn.completed",usage:r.terminalUsage(),sessionId:e.ctx.sessionId};return}if(r.addRoundUsage(L0(h.usage,h.stopReason,e.model,e.fastMode?"fast":void 0)),e.onUsageProgress?.(r.usage),h.stopReason!=="tool_use"){yield*R8(h,e,r);return}if((yield*x8(h,e,r,t,n))==="terminated")return;_8(e,e.beforeNextRound?.())}}finally{l.finish(r.elapsedMs())}}var I8=b(()=>{"use strict";F0();fe();B0();wk();Lu();pg();fg();o8();p8();w8();E8();A8();C8();UI();P8()});function kOe(e,t){return e.authMode==="oauth"&&e.tokenRefresher!==void 0&&"status"in t&&t.status===401}async function*M8(e,t,n){let r=null;for await(let i of G0(t)){if(n())return;if(i.type==="error"&&kOe(e,i.error)){r=i;break}yield i}if(!r)return;if(!await e.forceClientRefresh()){yield r;return}t.client=e.getClient(),t.headers=e.rotateHeaders(t),yield*G0(t)}var O8=b(()=>{"use strict";I8()});var Rk=b(()=>{"use strict"});async function*$8(e,t,n,r,o){let i=ao(yt()??"");if(yield{type:"paused",reason:"usage-limit",accountId:i,autoResume:e.autoResumeOnUsageLimit},oe(t.traceWriter,{phase:"usage_limit_pause",metadata:{reason:"usage-limit",source:"retry-layer",hasResetTimestamp:!1,autoResume:e.autoResumeOnUsageLimit}}),!e.autoResumeOnUsageLimit){e.markCredentialSnapshotStale(),yield o;return}let s=Date.now(),a=!1;for(;;){let l;if(e.getUsageLimitWait())l="aborted";else{let p=Zq({signal:t.signal,retryAfterMs:6e4});e.setUsageLimitWait(p);try{l=await p}finally{e.setUsageLimitWait(null)}}if(l==="aborted")return;let u=i;if(l==="hot-swap"){let p=await e.forceClientRefresh();p&&(t.client=e.getClient(),u=p.accountId)}t.headers=e.rotateHeaders(t);let d=null;for await(let p of r(e,t,n)){if(!a&&p.type==="error"){let f=_S(p.error);if(f&&(f.kind==="oauth-limit"||f.kind==="oauth-limit-no-ts")){d=p;break}}a||(yield{type:"resumed",hotSwapped:l==="hot-swap",accountId:u},oe(t.traceWriter,{phase:"usage_limit_resume",durationMs:Date.now()-s,metadata:{source:"retry-layer",hotSwapped:l==="hot-swap"}}),a=!0),yield p}if(!d)return;if(Date.now()-s>72e5){yield d;return}}}async function*D8(e,t,n,r,o,i){if(i.getTime()-Date.now()>72e5){e.markCredentialSnapshotStale(),yield o;return}let s=ao(yt()??""),a=Date.now();if(yield{type:"paused",reason:"usage-limit",resetsAt:i,accountId:s,autoResume:e.autoResumeOnUsageLimit},oe(t.traceWriter,{phase:"usage_limit_pause",metadata:{reason:"usage-limit",source:"retry-layer",hasResetTimestamp:!0,autoResume:e.autoResumeOnUsageLimit,resetsAt:i.toISOString()}}),!e.autoResumeOnUsageLimit){e.markCredentialSnapshotStale(),yield o;return}let l,c=e.getUsageLimitWait();if(c)l=await c;else{let d=Qq({resetsAt:i,signal:t.signal});e.setUsageLimitWait(d);try{l=await d}finally{e.setUsageLimitWait(null)}}if(l==="aborted")return;let u=s;if(l==="hot-swap"){let d=await e.forceClientRefresh();d&&(t.client=e.getClient(),u=d.accountId)}t.headers=e.rotateHeaders(t),yield{type:"resumed",hotSwapped:l==="hot-swap",accountId:u},oe(t.traceWriter,{phase:"usage_limit_resume",durationMs:Date.now()-a,metadata:{source:"retry-layer",hotSwapped:l==="hot-swap"}}),yield*r(e,t,n)}var L8=b(()=>{"use strict";PS();M0();fe();Rk()});async function*B8(e,t,n,r){let o=null,i=null,s=!1,a=0;for(;;){let l,c=!1;for await(let p of r(e,t,n)){if(p.type==="error"){let f=_S(p.error);if(f&&f.kind==="oauth-limit"){i=f.resetsAt,o=p;break}if(f&&f.kind==="oauth-limit-no-ts"){s=!0,o=p;break}if(f&&f.kind==="rate-limit-transient"&&a<3){c=!0,l=f.retryAfterMs;break}}yield p}if(!c)break;if(a+=1,n()||t.signal.aborted)return;let d=Math.min(l??5e3,12e4)+Math.floor(Math.random()*1e3);if(oe(t.traceWriter,{phase:"rate_limit",metadata:{reason:"retry-after",source:"retry-layer",attempt:a,waitMs:d}}),await an(d,t.signal),n()||t.signal.aborted)return;t.headers=e.rotateHeaders(t)}if(o){if(s){yield*$8(e,t,n,r,o);return}i&&(yield*D8(e,t,n,r,o,i))}}var U8=b(()=>{"use strict";PS();Zi();fe();Rk();L8()});async function*j8(e,t,n,r){let o=e8(e.surface),i=null,s=!1;for(;;){let a=null;for await(let c of r(e,t,n)){if(ZX(c)){a=c;break}yield c}if(!a){s&&i!==null&&oe(t.traceWriter,{phase:"overload_resume",durationMs:Date.now()-i,metadata:{source:"retry-layer",outcome:"recovered"}});return}if(n()||t.signal.aborted||o===0){yield a;return}i??=Date.now();let l=o-(Date.now()-i);if(l<=0){s&&oe(t.traceWriter,{phase:"overload_resume",durationMs:Date.now()-i,metadata:{source:"retry-layer",outcome:"ceiling-reached"}}),yield a;return}if(s||(oe(t.traceWriter,{phase:"overload_pause",metadata:{reason:"overloaded",source:"retry-layer",hasResetTimestamp:!1,ceilingMs:o,surface:e.surface??"unknown"}}),s=!0),await an(Math.min(QX(),l),t.signal),n()){yield a;return}if(t.signal.aborted)return;t.headers=e.rotateHeaders(t),yield{type:"stream.retry",sessionId:t.ctx.sessionId}}}var H8=b(()=>{"use strict";pg();Zi();fe()});import{randomUUID as ROe}from"node:crypto";var Ak,W8=b(()=>{"use strict";ga();id();M0();O8();U8();H8();Rk();Ak=class{_client;_authMode;initSessionId;baseUrl;tokenRefresher;autoResumeOnUsageLimit;surface;refreshPromise=null;usageLimitWaitPromise=null;credentialSnapshotStale=!1;constructor(t){this._client=t.client,this._authMode=t.authMode,this.initSessionId=t.initSessionId,this.baseUrl=t.baseUrl,this.tokenRefresher=t.tokenRefresher,this.autoResumeOnUsageLimit=t.autoResumeOnUsageLimit,t.surface!==void 0&&(this.surface=t.surface)}get client(){return this._client}get authMode(){return this._authMode}rotateHeaders(t){return Oi(this._authMode,this.initSessionId,ROe(),t.effort!==void 0,bk({...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{}}),t.fastMode===!0)}tierContext(){let t=this;return{get authMode(){return t._authMode},get surface(){return t.surface},get autoResumeOnUsageLimit(){return t.autoResumeOnUsageLimit},get tokenRefresher(){return t.tokenRefresher},getClient:()=>t._client,rotateHeaders:n=>t.rotateHeaders(n),forceClientRefresh:()=>t.forceClientRefresh(),getUsageLimitWait:()=>t.usageLimitWaitPromise,setUsageLimitWait:n=>{t.usageLimitWaitPromise=n},markCredentialSnapshotStale:()=>{t.credentialSnapshotStale=!0}}}async forceClientRefresh(){if(!this.tokenRefresher)return null;let t=yt(),n=null;try{if(this.refreshPromise)n=await this.refreshPromise;else{this.refreshPromise=this.tokenRefresher();try{n=await this.refreshPromise??null}finally{this.refreshPromise=null}}}catch{return this.refreshPromise=null,null}if(!n)return null;this._client=n;let r=yt();return{accountId:ao(r??""),swapped:t!==r}}async*turnWithRetries(t,n){this.credentialSnapshotStale&&(await this.forceClientRefresh()&&(t.client=this._client,t.headers=this.rotateHeaders(t)),this.credentialSnapshotStale=!1);let r=this.tierContext();yield*j8(r,t,n,(o,i,s)=>B8(o,i,s,M8))}}});function K8(){return AOe.map(e=>({...e}))}var AOe,G8=b(()=>{"use strict";AOe=[{value:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",description:"Balanced Claude \u2014 recommended default (1M context, 128k output)"},{value:"claude-sonnet-5",displayName:"Claude Sonnet 5",description:"Newer balanced Claude \u2014 adaptive thinking, new tokenizer"},{value:"claude-opus-5",displayName:"Claude Opus 5",description:"Highest-capability Claude for agentic coding"},{value:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",description:"Fastest, cheapest Claude"}]});function Ck(e){if(e.length===0)return;let t=e[e.length-1];if(!t||t.role!=="assistant"||typeof t.content=="string")return;let n=t.content,r=[];for(let i of n)i.type==="tool_use"&&typeof i.id=="string"&&r.push(i.id);if(r.length===0)return;let o={role:"user",content:r.map(i=>({type:"tool_result",tool_use_id:i,content:"Tool call interrupted before completing \u2014 no result recorded.",is_error:!0}))};e.push(o)}var z0=b(()=>{"use strict"});var _k=b(()=>{"use strict";Bc()});async function*q8(e){if(e.state.autoCompactThreshold===void 0||e.state.closed)return;let t=e.state.lastUsage,n=jo(e.state.requestedModel);if(t===null||n<=0)return;let r=Ft(t);if(Sm(r,n,e.state.autoCompactThreshold))try{e.hookRegistry&&await e.hookRegistry.dispatch({event:"PreCompact",sessionId:e.initSessionId,trigger:"auto"}),(await e.compact()).compacted&&(e.state.lastUsage=null)}catch(o){if(!(o instanceof Re))throw o}}var z8=b(()=>{"use strict";vr();_k();He()});import{randomUUID as COe}from"node:crypto";async function*J8(e){yield{type:"session.init",info:{sessionId:e.initSessionId,model:e.state.currentModel,permissionMode:e.state.currentPermissionMode,cwd:process.cwd(),tools:[],slashCommands:[],skills:[],plugins:[],mcpServers:e.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:e.retry.authMode,version:"anthropic-direct-v1"}};let n=e.promptStream[Symbol.asyncIterator]();try{for(;!e.state.closed;){let r=await Promise.race([n.next(),e.abort.closedPromise]);if(r==="__closed__")break;let o=r;if(o.done)break;let i=o.value,s=e.abort.begin();if(s.signal.aborted){e.abort.clear(s);return}Ck(e.state.messages);{let d;try{km(Ft(e.state.lastUsage??{}),e.maxTokens,st(e.state.requestedModel??e.state.currentModel),e.state.requestedModel??e.state.currentModel)}catch(p){d=p instanceof Error?p:new Error(String(p))}if(d!==void 0){e.abort.clear(s),yield{type:"error",error:d};continue}}e.state.messages.push({role:"user",content:i.content});let a=e.composeSystem(),{decision:l,runInput:c}=s8({client:e.retry.client,messages:e.state.messages,system:a,tools:e.state.currentPermissionMode==="plan"?e.tools:e.tools?.filter(d=>d.name!==Un)??null,toolDispatcher:e.state.toolDispatcher,model:e.state.currentModel,maxTokens:e.maxTokens,signal:s.signal,authMode:e.retry.authMode,sessionId:e.initSessionId,requestId:COe(),...e.fastModeController?{fastModeController:e.fastModeController}:{},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.maxToolUseIterations!==void 0?{maxToolUseIterations:e.maxToolUseIterations}:{},...e.softDeadlineMs!==void 0?{softDeadlineMs:e.softDeadlineMs}:{},...e.traceWriter?{traceWriter:e.traceWriter}:{},...e.subagentId!==void 0?{subagentId:e.subagentId}:{},...e.throttleQueue?{throttleQueue:e.throttleQueue}:{},...e.beforeNextRound?{beforeNextRound:e.beforeNextRound}:{},onUsageProgress:d=>{e.state.lastUsage=d}}),u=!1;try{for await(let d of e.retry.turnWithRetries(c,()=>e.state.closed)){if(d.type==="turn.completed"){if(e.state.lastUsage=d.usage,e.abort.clear(s),u=!0,yield d,e.state.closed)return;continue}if(e.state.closed)return;d.type==="error"&&(u=!0),yield d}}catch(d){if(e.state.closed)return;if(s.signal.aborted){e.abort.clear(s),u||(yield e.makeInterruptedTurnEvent());continue}yield{type:"error",error:kk(d,l?.effective===!0)};return}finally{e.abort.clear(s)}if(e.state.closed)return;if(s.signal.aborted){u||(yield e.makeInterruptedTurnEvent());continue}yield*q8(e)}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}var V8=b(()=>{"use strict";qa();vr();z0();_k();K0();z8()});function Y8(e){let t=e.lastUsage,n=st(e.requestedModel),r;if(t&&n>0){let s=Ft(t);r=Math.min(100,Math.max(0,s/n*100))}let{totalTokens:o,apiUsage:i}=wm(t);return{tools:[],agents:[],isAutoCompactEnabled:e.autoCompactThreshold!==void 0,apiUsage:i,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}function X8(e){return e?e.getServerStates().map(t=>({name:t.serverName,status:t.status})):[]}function Q8(e){return{subscriptionType:e==="oauth"?"claude-subscription":"api-key"}}var Z8=b(()=>{"use strict";vr();_k()});var e6=b(()=>{"use strict";cM()});var t6=b(()=>{"use strict";aM()});function n6(e){let{state:t,systemPrefix:n,baseUrl:r}=e;t.userSystem&&(t.userSystem=KS(t.userSystem));let o=[];n&&n.length>0&&o.push(...n),t.userSystem&&t.userSystem.length>0&&o.push({type:"text",text:t.userSystem});let i=sM(t.currentPermissionMode);i!==null&&o.push(i);let s=lM(t.currentPermissionMode);return s!==null&&o.push(s),o.length===0?null:ug({baseUrl:r})?FX(o,cl()):o}var r6=b(()=>{"use strict";id();e6();t6();HI()});function o6(e,t){t===void 0||t.length===0||(e.requestedModel=t,e.currentModel=Lt(t)??t)}function i6(e){let{state:t,mode:n,onPermissionMode:r}=e;t.currentPermissionMode=n,t.toolDispatcher.setAllowAll?.(kr(n)),r?.(n)}function s6(e){let{state:t,cwd:n,cwdDependentsFactory:r}=e;if(t.toolDispatcher.setResolveBase?.(n),!r)return;let{userSystem:o,dispatcher:i}=r(n);t.userSystem=o,t.toolDispatcher=i}function a6(e){let{state:t,basePrompt:n,systemPromptRebuildFactory:r}=e;return r?(t.userSystem=r(n),!0):!1}var l6=b(()=>{"use strict";Uc();Yn()});function c6(e){return{type:"turn.completed",usage:{stopReason:"interrupted",resultSubtype:"interrupted",isError:!1},sessionId:e}}var u6=b(()=>{"use strict"});function _Oe(e){if(e.role!=="user")return!1;let t=e.content;if(typeof t=="string")return!0;if(!Array.isArray(t))return!1;for(let n of t)if(n.type==="tool_result")return!1;return!0}function POe(e){let n=[(e.role==="user"?"User":"Assistant")+":"];if(typeof e.content=="string")n.push(e.content);else if(Array.isArray(e.content))for(let r of e.content){let o=r.type;if(o==="text"&&"text"in r)n.push(r.text);else if(o==="tool_use"){let i=r.name??"unknown",s=g6(r.input);n.push(`[tool call: ${i} ${s}]`)}else if(o==="tool_result"){let i=r.content;n.push(`[tool result: ${h6(i)}]`)}else o==="image"?n.push("[image]"):o==="document"&&n.push("[document]")}return n.join(`
1485
1485
  `)}function IOe(e){let t=0;if(typeof e.content=="string")t+=e.content.length;else if(Array.isArray(e.content))for(let n of e.content){let r=n.type;r==="text"&&"text"in n?t+=n.text.length:r==="tool_use"?t+=g6(n.input).length:r==="tool_result"&&(t+=h6(n.content).length)}return t}function MOe(e){if(typeof e=="string")return Qa(e);if(Array.isArray(e)){let t=0;for(let n of e)n.type==="text"&&"text"in n&&(t+=Qa(n.text));return t}return 0}function OOe(e){if(typeof e=="string")return Mu(e);if(Array.isArray(e)){for(let t of e)if(t.type==="text"&&"text"in t)return Mu(t.text)}return!1}function J0(e,t){return QS(e,$Oe,t??{})}function d6(e,t,n,r){return XI(e,t,Pk,n,r)}function p6(e,t,n){let r=QI(e,Pk);return{model:t,max_tokens:n,system:Bf,messages:[{role:"user",content:Hf(r)}],stream:!0}}function m6(e,t,n){return ZI(e,t,n,Pk)}function f6(e,t,n){return eM(e,t,n,Pk)}function g6(e){try{let t=JSON.stringify(e);return t.length>240?t.slice(0,237)+"...":t}catch{return"{}"}}function h6(e){if(typeof e=="string")return e.length>320?e.slice(0,317)+"...":e;if(Array.isArray(e)){let t=[];for(let r of e)r.type==="text"&&"text"in r&&t.push(r.text);let n=t.join(" ");return n.length>320?n.slice(0,317)+"...":n}return""}var Pk,$Oe,y6=b(()=>{"use strict";Wf();Pk={isFreshUserTurn:_Oe,renderMessage:POe,buildPreamble(e){return[{role:"user",content:Uf+`
@@ -2124,7 +2124,7 @@ _ended: ${new Date().toISOString()}_
2124
2124
  `),w(),p(T),h.prevBufferRows=0},x=()=>{w(),d({text:"",attachments:[...h.attachments]}),h.prevBufferRows=0};c=(T,E)=>{eae(T,E,h,{opts:e,stdout:n,repaintCtx:y,callbacks:{onSubmit:S,onAbort:v,onEof:x},pasteWindowMs:g},Bh,jse,Hse)},Bh(h,y),u=qe.subscribe(()=>{h.prevBufferRows=0,h.prevStatusRows=0,h.rowsBelow=0,Bh(h,y)}),t.on("keypress",c)})}finally{e.statusLine?.setExtraRows(s),o.restore(),i?.release()}}F();Xg();El();async function nae(e){return!process.stdout.isTTY||!process.stdin.isTTY||je()?Nse(e):tae(e)}dD();lh();mi();Ht();El();Ol();op();F();var pR=class{history;autocompleteState;rl;statusLine;compositor=null;armedStdout=null;backgroundHandler=null;softStopHandler=null;taskViewHandler=null;pauseInterruptHandler=null;pendingReadReject=null;pendingReadResolve=null;slashRegistryView=Bd();constructor(t){this.rl=t.rl,this.history=t.history,this.statusLine=t.statusLine,this.autocompleteState=uR()}async armCompositor(t){if(this.compositor)return;let n=t.stdout??process.stdout,r=t.stdin??process.stdin;if(!n.isTTY||!r.isTTY||je())return;let o=new Xd({stdout:n,stdin:r,promptText:t.promptFn,onCancel:t.onCancel,onSoftStop:()=>{this.softStopHandler?.()},onBackground:()=>{this.backgroundHandler?.()},onPauseInterrupt:()=>{this.pauseInterruptHandler?.()},onTaskView:()=>this.taskViewHandler?.()??!1,...t.onShiftTab?{onShiftTab:t.onShiftTab}:{},...t.onOpenEditor?{onOpenEditor:t.onOpenEditor}:{},history:this.history,autocompleteState:this.autocompleteState,formatInputBuffer:i=>gi(i,this.slashRegistryView),caretBlink:Q9()&&!KT(),captureMode:WT(),goblinSpinner:GT(),...t.scrollRegion?{scrollRegion:t.scrollRegion}:{},...t.anchorRow!==void 0?{anchorRow:t.anchorRow}:{},...t.suggest?{suggest:t.suggest}:{}});await o.arm(),o.setInputMode("idle"),o.setOnRewindRequest(()=>{this.requestRewind()}),this.compositor=o,this.armedStdout=n}async dispose(){if(this.compositor){if(this.pendingReadReject){this.compositor.setOnSubmit(null),this.compositor.setOnIdleEscape(null);let t=this.pendingReadReject;this.pendingReadReject=null,this.pendingReadResolve=null,t(new Error("InputSurface disposed while readLine was in progress"))}try{this.compositor.disarm()}catch{}this.compositor=null,this.armedStdout=null,this.backgroundHandler=null,this.softStopHandler=null,this.taskViewHandler=null,this.pauseInterruptHandler=null}}getCompositor(){return this.compositor}setBackgroundHandler(t){this.backgroundHandler=t}setSoftStopHandler(t){this.softStopHandler=t}setTaskViewHandler(t){this.taskViewHandler=t}setPauseInterruptHandler(t){this.pauseInterruptHandler=t}setPausedState(t){this.compositor&&(this.compositor.paused=t)}suspendForElicitation(){this.compositor?.suspendInput()}resumeAfterElicitation(){this.compositor?.resumeInput()}async readLine(t){if(this.compositor&&this.compositor.isArmed()){let n=this.compositor;return new Promise((r,o)=>{this.pendingReadReject=o,this.pendingReadResolve=r,n.setOnIdleEscape(t.onEscape??null),t.primePromptSuggestion===!0&&n.primePromptGhost();let i=s=>{n.setOnSubmit(null),this.pendingReadReject=null,this.pendingReadResolve=null,n.setOnIdleEscape(null);let a=this.armedStdout??process.stdout,l=s.displayText??s.text,c=xl({buffer:gi(l,this.slashRegistryView),promptText:t.promptFn(),isTTY:!!a.isTTY,attachmentSummary:zd([...s.attachments])});En(n,c.split(`
2125
2125
  `)),r({text:s.text,attachments:[...s.attachments]})};n.setOnSubmit(i),t.initialBuffer!==void 0&&t.initialBuffer.length>0&&n.prefillInput(t.initialBuffer),n.setInputMode("idle"),n.repaint()})}return nae({rl:this.rl,promptFn:t.promptFn,...t.initialBuffer!==void 0?{initialBuffer:t.initialBuffer}:{},...t.onSigint?{onSigint:t.onSigint}:{},...t.onShiftTab?{onShiftTab:t.onShiftTab}:{},...t.compositor?{compositor:t.compositor}:{},history:this.history,autocompleteState:this.autocompleteState,...this.statusLine?{statusLine:this.statusLine}:{}})}isAwaitingInput(){return this.pendingReadResolve!==null}bufferIsEmpty(){let t=this.compositor?.getBuffer();return t?t.text.length===0&&!t.queued:!0}abortPendingRead(t){if(!this.pendingReadResolve)return;this.compositor?.setOnSubmit(null);let n=this.pendingReadResolve;this.pendingReadReject=null,this.pendingReadResolve=null,this.compositor?.setOnIdleEscape(null),t?.clearBuffer&&this.compositor?.prefillInput(""),n({text:"",attachments:[]})}requestRewind(){if(!this.pendingReadResolve)return!1;this.compositor?.setOnSubmit(null);let t=this.pendingReadResolve;return this.pendingReadReject=null,this.pendingReadResolve=null,this.compositor?.setOnIdleEscape(null),t({text:"/rewind",attachments:[]}),!0}toRunTurnRefs(t){return{history:this.history,autocompleteState:this.autocompleteState,promptText:t}}};F();dx();sr();Ns();nF();me();$L();L();var _F=["default","plan","bypassPermissions"];function z2e(e,t){switch(t){case"plan":e.out.success(m.warning("\u25CF plan mode ON")+m.dim(" \u2014 writes refused; read-only bash runs, mutating bash blocked."));return;case"bypassPermissions":e.out.line(m.bypass("\u26A1 bypass ON")+m.dim(" \u2014 path-approval prompts + containment OFF; read/write any path. (Does not affect ask_question.)"));return;case"default":e.out.success(m.success("\u25CB default")+m.dim(" \u2014 path containment + approval prompts restored."));return}}async function mR(e){let t=e.stats.permissionMode;if(t==="autonomous"){await _h(e,!1);return}let n=_F.indexOf(t),r=_F[(n+1)%_F.length]??"default";try{await e.session.current.setPermissionMode(r),e.stats.permissionMode=r,e.ui.repaintStatusLine(),z2e(e,r)}catch(o){e.out.error(`Could not switch permission mode: ${o instanceof Error?o.message:String(o)}`)}}zL();L();Cf();Io();L();function bp(e){let t=m.brand("afk"),n=e==="plan"?m.warning(" \u25CF"):e==="autonomous"?m.info(" \u25D0"):e==="bypassPermissions"?m.bypass(" \u26A1 bp"):"";return t+n+m.brand(" \u203A ")}function rae(e){let t,n=e.history;if(n&&typeof n.push=="function"){let r=n.push.bind(n);n.push=o=>{let i=n.getEntries?.()?.[0];r(o);let s=n.getEntries?.()?.[0];s!==i&&(t=s)}}return{getLastSubmitted:()=>t}}F();function oae(e){if(!e.enabled)return{};let{engine:t,surface:n,stats:r,historyTracker:o}=e;return{suggest:{engine:t,getContext:()=>({model:r.model,apiKey:e.apiKey,baseUrl:e.baseUrl,cwd:r.cwd??process.cwd(),getHistory:()=>{let i=n.history;return i.getEntries?[...i.getEntries()]:[]},get lastSubmitted(){return o.getLastSubmitted()},getDropdownTopCandidate:i=>{let a=n.autocompleteState.candidates[0];return a&&a.value.startsWith(i)&&a.value.length>i.length?a.value:null},getTranscriptTail:()=>{let i=r.turns;return i.length===0?"":i.slice(-2).reverse().map(s=>`user: ${s.user}
2126
2126
  assistant: ${s.assistant}`).join(`
2127
- `)},getUserArc:()=>r.turns.map(i=>i.user),getLastAssistantResponse:()=>r.turns[r.turns.length-1]?.assistant??"",getRecentCommands:()=>{let i=n.history;return i.getEntries?[...i.getEntries()]:[]},llmEnabled:()=>/^(1|true|yes|on)$/i.test(k.AFK_SUGGEST_ENABLED??""),promptSuggestEnabled:()=>/^(1|true|yes|on)$/i.test(k.AFK_SUGGEST_PROMPT??"")})}}}Ml();async function iae(e,t,n,r,o,i,s){let a=yZ({onError:g=>N("[afk suggest] Tier-2 completion failed:",g)}),l=rae(t);await t.armCompositor({promptFn:()=>bp(e.stats.permissionMode),onCancel:o,onShiftTab:()=>{mR(e.slashCtx).catch(()=>{}),e.statusLine.rearm()},onOpenEditor:()=>{let g=t.getCompositor();DE({compositor:g,notify:(h,y)=>{let w=h==="error"?m.error(y):h==="warn"?m.warning(y):m.dim(y);g?.commitAbove(w)},suspendFooter:()=>e.slashCtx.suspendFooter?.(),resumeFooter:()=>e.slashCtx.resumeFooter?.()}).catch(()=>{})},scrollRegion:e.statusLine,...e.preArmAnchorRow!==void 0?{anchorRow:e.preArmAnchorRow}:{},...oae({enabled:i,engine:a,surface:t,stats:e.stats,apiKey:e.suggestApiKey,baseUrl:e.suggestBaseUrl,historyTracker:l})});let c=t.getCompositor();c&&(e.hasPendingUserMessage=()=>c.peekQueuedText()!==void 0,e.session.current?.setPlanExitQueueCheck(e.hasPendingUserMessage));let u=Rh({readLine:g=>t.readLine({promptFn:()=>g}).then(h=>h.text),writer:{line:(g="")=>{let h=t.getCompositor();h?h.commitAbove(g):process.stdout.write(xn(g,process.stdout)+`
2127
+ `)},getUserArc:()=>r.turns.map(i=>i.user),getLastAssistantResponse:()=>r.turns[r.turns.length-1]?.assistant??"",getRecentCommands:()=>{let i=n.history;return i.getEntries?[...i.getEntries()]:[]},llmEnabled:()=>!/^(0|false|no|off)$/i.test(k.AFK_SUGGEST_ENABLED??""),promptSuggestEnabled:()=>!/^(0|false|no|off)$/i.test(k.AFK_SUGGEST_PROMPT??"")})}}}Ml();async function iae(e,t,n,r,o,i,s){let a=yZ({onError:g=>N("[afk suggest] Tier-2 completion failed:",g)}),l=rae(t);await t.armCompositor({promptFn:()=>bp(e.stats.permissionMode),onCancel:o,onShiftTab:()=>{mR(e.slashCtx).catch(()=>{}),e.statusLine.rearm()},onOpenEditor:()=>{let g=t.getCompositor();DE({compositor:g,notify:(h,y)=>{let w=h==="error"?m.error(y):h==="warn"?m.warning(y):m.dim(y);g?.commitAbove(w)},suspendFooter:()=>e.slashCtx.suspendFooter?.(),resumeFooter:()=>e.slashCtx.resumeFooter?.()}).catch(()=>{})},scrollRegion:e.statusLine,...e.preArmAnchorRow!==void 0?{anchorRow:e.preArmAnchorRow}:{},...oae({enabled:i,engine:a,surface:t,stats:e.stats,apiKey:e.suggestApiKey,baseUrl:e.suggestBaseUrl,historyTracker:l})});let c=t.getCompositor();c&&(e.hasPendingUserMessage=()=>c.peekQueuedText()!==void 0,e.session.current?.setPlanExitQueueCheck(e.hasPendingUserMessage));let u=Rh({readLine:g=>t.readLine({promptFn:()=>g}).then(h=>h.text),writer:{line:(g="")=>{let h=t.getCompositor();h?h.commitAbove(g):process.stdout.write(xn(g,process.stdout)+`
2128
2128
  `)}},pendingCount:()=>Be.pendingCount(),...c?{pickFromList:g=>Rn(c,g),readTextOverlay:g=>UE(c,g)}:{}});Be.install(u),e.replRenderer.setCompositor(t.getCompositor()),e.slashCtx.getCompositor=()=>t.getCompositor();let d=t.getCompositor();if(d){let g=h=>d.commitAbove(h);e.completionWriter.fn=g,e.completionWriter.idleFn=g}let p=g=>{t.setSoftStopHandler(g),n.requestSoftStop=g};e.slashCtx.setSoftStopHandler=p,e.slashCtx.onStageChange=(g,h)=>{s.getLoopStageBar()?.repaint(g),s.getMascotBar()?.onStage(g,h)};let f=(()=>{let g=parseInt(e.options.maxTurns,10);return g>0?g:void 0})();return e.slashCtx.onContextProgress=async()=>{await e.contextSampler.refresh(),await e.gitStatusSampler.refresh(),e.statusLine.repaint(mr(e.stats,e.contextSampler,e.gitStatusSampler,f))},e.slashCtx.transcript=r,e.slashCtx.stdinElicitationHandler=u,e.slashCtx.swapElicitationHandler=g=>Be.install(g??u),e.inputSurfaceRef&&(e.inputSurfaceRef.current=t),e.gitStatusSampler.setOnUpdate(()=>{e.statusLine.repaint(mr(e.stats,e.contextSampler,e.gitStatusSampler,f))}),e.gitStatusSampler.refresh(),sz(()=>{e.statusLine.repaint(mr(e.stats,e.contextSampler,e.gitStatusSampler,f))}),{installSoftStop:p}}DL();we();function sae(e={}){let t=e.load??CE,n=e.onResize??(s=>qe.subscribe(s)),r="",o,i=n(()=>{r=""});return{renderIfChanged(s){let a=s??"unbound",l=t(a),c=Vre(l);return a===o&&c===r?[]:(o=a,r=c,c===""?[]:_E(l))},invalidate(){r=""},dispose(){try{i()}catch{}}}}L();de();we();F();var PF={done:{glyph:"\u2713",color:e=>m.success(e),label:"done"},blocked:{glyph:"\u2298",color:e=>m.error(e),label:"blocked"},asking:{glyph:"?",color:e=>m.warning(e),label:"asking"},interrupted:{glyph:"\u23F8",color:e=>m.meta(e),label:"interrupted"}};function aae(e={}){let t=Math.max(2,e.capacity??8),n=[],r=null,o=()=>0,i=!1,s=0,a,l=null;function c(){let g=r?.rows;return typeof g=="number"&&g>0?g:24}function u(g){let h=o();return Math.max(1,g-1-h)}function d(){if(!i||!r?.isTTY)return;let g=f(),h=c(),y=g!==null&&h>1?1:0;if(y!==s&&(s>0&&p(),s=y,a?.(s)),y===0)return;let w=u(h);r.write("\x1B[s"),r.write(`\x1B[${w};1H`),r.write("\x1B[2K"),r.write(g),r.write("\x1B[u")}function p(){if(!r?.isTTY)return;let g=c(),h=u(g);r.write("\x1B[s"),r.write(`\x1B[${h};1H`),r.write("\x1B[2K"),r.write("\x1B[u")}function f(){if(n.length===0)return null;let g=m.dim(" ledger "),h=m.dim(" \xB7 "),y=n.map(T=>{let E=PF[T];return E.color(`${E.glyph} ${E.label}`)}),w=m.dim(` (${n.length} turn${n.length===1?"":"s"})`),S=g+y.join(h)+w,v=Math.max(20,re()-2);if(z(S)<=v)return S;let x=g+n.map(T=>PF[T].color(PF[T].glyph)).join(m.dim(" "))+w;return ee(x,v)}return{push(g){n.push(g.kind),n.length>t&&(n=n.slice(n.length-t)),d()},reset(){n=[],i&&s>0&&(p(),s=0,a?.(0))},entries(){return n},render(){return f()},setRowCountChangeHandler(g){a=g},start(g){i||je()||(i=!0,r=g.stream??process.stdout,o=g.getAdjacentRows??(()=>0),s=0,l=qe.subscribe(()=>d()),d())},stop(){i&&(i=!1,l!==null&&(l(),l=null),s>0&&(p(),s=0,a?.(0)),r=null)},repaint(){d()}}}de();L();tt();we();F();var lae=["\u25D0","\u25D1","\u25D2","\u25D3"],fR=class{stream;registry;throttleMs;started=!1;lastRepaint=0;spinnerIndex=0;spinnerInterval=null;resizeUnsub=null;resizeImmediateUnsub=null;registryStartedHandler=null;registrySettledHandler=null;rowCount=0;lastPaintStartRow=0;preResizeStartRow=null;preResizeRowCount=null;onRowCountChange;getAdjacentRows;constructor(t,n={}){this.registry=t,this.stream=n.stream??process.stdout,this.throttleMs=n.throttleMs??200,this.getAdjacentRows=n.getAdjacentRows??(()=>0)}setRowCountChangeHandler(t){this.onRowCountChange=t}start(){this.started||je()||(this.started=!0,this.registry&&(this.registryStartedHandler=t=>{this.scheduleRepaint()},this.registrySettledHandler=t=>{this.scheduleRepaint()},this.registry.on("started",this.registryStartedHandler),this.registry.on("settled",this.registrySettledHandler)),this.resizeUnsub=qe.subscribe(()=>this.repaint()),this.resizeImmediateUnsub=qe.subscribeImmediate(()=>this.resetGeometry()),this.spinnerInterval=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%lae.length,this.rowCount>0&&this.repaint()},Math.max(this.throttleMs,50)))}stop(){this.started&&(this.started=!1,this.registry&&(this.registryStartedHandler&&(this.registry.off("started",this.registryStartedHandler),this.registryStartedHandler=null),this.registrySettledHandler&&(this.registry.off("settled",this.registrySettledHandler),this.registrySettledHandler=null)),this.resizeUnsub&&(this.resizeUnsub(),this.resizeUnsub=null),this.resizeImmediateUnsub&&(this.resizeImmediateUnsub(),this.resizeImmediateUnsub=null),this.spinnerInterval&&(clearInterval(this.spinnerInterval),this.spinnerInterval=null),this.rowCount>0&&(this.clearRows(),this.rowCount=0,this.onRowCountChange?.(0)))}resetGeometry(){this.rowCount>0&&(this.preResizeStartRow=this.lastPaintStartRow,this.preResizeRowCount=this.rowCount),this.rowCount=0,this.lastRepaint=0}scheduleRepaint(){Date.now()-this.lastRepaint<this.throttleMs||this.repaint()}redraw(){this.repaint()}repaint(){if(!this.started||!this.stream.isTTY)return;this.lastRepaint=Date.now();let t=(this.registry?.list()??[]).filter(s=>s.status==="running").map(s=>({kind:"subagent",job:s})),n=this.stream.rows??24,r=this.getAdjacentRows(),o=Math.max(0,Math.min(t.length,n-1-r));if(this.clearPreResizeRows(),o!==this.rowCount&&(this.rowCount>0&&this.clearRows(),this.rowCount=o,this.onRowCountChange?.(o)),o===0)return;let i=Math.max(1,n-o-r);this.lastPaintStartRow=i,this.stream.write("\x1B[s");for(let s=0;s<o;s++){let a=t[s],l=i+s;this.stream.write(`\x1B[${l};1H`),this.stream.write("\x1B[2K"),this.stream.write(this.formatItemLine(a))}this.stream.write("\x1B[u")}clearRows(){if(!this.stream.isTTY)return;let t=this.stream.rows??24,n=this.getAdjacentRows(),r=Math.min(this.rowCount,t-1-n),o=Math.max(1,t-r-n);this.stream.write("\x1B[s");for(let i=0;i<r;i++)this.stream.write(`\x1B[${o+i};1H`),this.stream.write("\x1B[2K");this.stream.write("\x1B[u")}clearPreResizeRows(){let t=this.preResizeStartRow,n=this.preResizeRowCount;if(this.preResizeStartRow=null,this.preResizeRowCount=null,t===null||n===null||!this.stream.isTTY)return;let r=this.stream.rows??24,o=[];for(let i=0;i<n;i++){let s=t+i;s<=r&&o.push(s)}if(o.length!==0){this.stream.write("\x1B[s");for(let i of o)this.stream.write(`\x1B[${i};1H`),this.stream.write("\x1B[2K");this.stream.write("\x1B[u")}}formatItemLine(t){return this.formatJobLine(t.job)}formatJobLine(t){let n=Math.max(4,(this.stream.columns??80)-2),r=m.brand(lae[this.spinnerIndex]),o=m.dim(t.jobId),i=m.bold(t.label||t.jobId),s=[r,o,i],a=Date.now()-t.startedAt;return s.push(m.dim(he(a))),ee(" "+s.join(" "),n)}};$x();we();F();Qy();Qy();var cae=13,uae=3,J2e=[".....BBB.....","...BBBBBBB...","..KYYYYYYYK..","DDKMMMMMMMKDD"];function Ql(e,t){return[...J2e,e,t]}var IF=".DKMYMMMYMKD.",V2e=".DKM.MMM.MKD.",Y2e=".DKMLMMMLMKD.",X2e="DDKMRMMMRMKDD",Q2e="DDKM.MMM.MKDD",MF="..KMMKKKMMK..",OF="..KMKKKKKMK..",Z2e="..KKKKKKKKK..",dae={idle:[Ql(IF,MF)],working:[Ql(IF,MF),Ql(V2e,OF),Ql(Y2e,MF),Ql(IF,OF)],alert:[Ql(X2e,Z2e),Ql(Q2e,OF)]};function pae(e){return dae[e].length}function mae(e="idle",t=0){if(Cc())return[];let n=dae[e],r=(t%n.length+n.length)%n.length;return ZA(n[r]??n[0])}mi();var fae=uae,eqe=8,gae=" ",tqe=1500,nqe=220,gR=class{stream;getAdjacentRows;frameMs;started=!1;state="idle";frame=0;rowCount=0;lastStartRow=0;lastRowCount=0;timer=null;stageState="idle";alertTimer=null;resizeUnsub=null;onRowCountChange;constructor(t){this.stream=t.stream??process.stdout,this.getAdjacentRows=t.getAdjacentRows,this.frameMs=t.frameMs??nqe}setRowCountChangeHandler(t){this.onRowCountChange=t}stop(){this.started&&(this.started=!1,this.resizeUnsub&&(this.resizeUnsub(),this.resizeUnsub=null),this.stopTimer(),this.clearAlertTimer(),this.clearBand(),this.rowCount=0,this.state="idle",this.stageState="idle",this.onRowCountChange?.(0))}start(){this.started||Z9()&&(je()||Cc()||this.stream.isTTY&&(this.started=!0,this.resizeUnsub=qe.subscribe(()=>this.repaint())))}setState(t){!this.started||t===this.state||(this.state=t,this.frame=0,t==="idle"?this.stopTimer():this.startTimer(),this.repaint())}onStage(t,n){if(this.started){if(this.stageState=t==="acting"?"working":"idle",n?.toolErrored){this.flashAlert();return}this.alertTimer||this.setState(this.stageState)}}redraw(){this.repaint()}getRowCount(){return this.rowCount}clearBand(){if(!this.stream.isTTY||this.lastRowCount<=0)return;let t=this.stream.rows??24;this.stream.write("\x1B[s");for(let n=0;n<this.lastRowCount;n++){let r=this.lastStartRow+n;r<1||r>t||(this.stream.write(`\x1B[${r};1H`),this.stream.write("\x1B[2K"))}this.stream.write("\x1B[u"),this.lastRowCount=0,this.lastStartRow=0}repaint(){if(!this.started||!this.stream.isTTY)return;let t=this.state==="idle"?[]:mae(this.state,this.frame),n=t.length>0?this.visibleRows():0,r=this.stream.rows??24,o=this.getAdjacentRows(),i=Math.max(1,r-n-o);if(this.lastRowCount>0&&(n!==this.lastRowCount||i!==this.lastStartRow)&&this.clearBand(),n!==this.rowCount&&(this.rowCount=n,this.onRowCountChange?.(n)),n!==0){this.stream.write("\x1B[s");for(let s=0;s<n;s++){let a=i+s;a<1||a>r||(this.stream.write(`\x1B[${a};1H`),this.stream.write("\x1B[2K"),this.stream.write(gae+(t[s]??"")))}this.stream.write("\x1B[u"),this.lastStartRow=i,this.lastRowCount=n}}visibleRows(){let t=this.stream.rows??24;return(this.stream.columns??80)<cae+gae.length+1?0:t-1-this.getAdjacentRows()-1-eqe>=fae?fae:0}clearAlertTimer(){this.alertTimer&&(clearTimeout(this.alertTimer),this.alertTimer=null)}flashAlert(){this.clearAlertTimer(),this.setState("alert"),this.alertTimer=setTimeout(()=>{this.alertTimer=null,this.setState(this.stageState)},tqe),this.alertTimer.unref?.()}stopTimer(){this.timer&&(clearInterval(this.timer),this.timer=null)}startTimer(){this.timer||pae(this.state)<=1||(this.timer=setInterval(()=>{this.frame+=1,this.repaint()},this.frameMs),this.timer.unref?.())}};L();de();function rqe(e){let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60);if(n<60)return`${n}m${t%60}s`;let r=Math.floor(n/60);return r<24?`${r}h${n%60}m`:`${Math.floor(r/24)}d${r%24}h`}function hae(e,t){let{totalTurns:n,elapsedMs:r,toolCalls:o,activeSubs:i,totalSubs:s,contextRatio:a}=e,l=m.dim(" \xB7 "),c=m.brand(`T${n}`),u=m.dim(rqe(r)),d=m.chrome(`${o} calls`),p=s>0?m.info(`${i}/${s} subs`):m.dim("0 subs"),f=Math.round(Math.max(0,Math.min(1,a))*100),g=a>.8?m.error:a>.5?m.warning:m.chrome,h=m.dim("ctx ")+g(`${f}%`),y=[c,u,d,p,h].join(l);return ee(" "+y,t)}we();F();vh();var hR=class{stream;registry;getExtraRows;started=!1;snapshot=null;onRowCountChange;resizeUnsub=null;tickInterval=null;totalSubsEver=0;constructor(t){this.stream=t.stream??process.stdout,this.registry=t.backgroundRegistry,this.getExtraRows=t.getExtraRows}setRowCountChangeHandler(t){this.onRowCountChange=t}start(){this.started||je()||(this.started=!0,this.onRowCountChange?.(1),this.resizeUnsub=qe.subscribe(()=>this.repaint()),this.tickInterval=setInterval(()=>this.repaint(),1e3),this.repaint())}stop(){this.started&&(this.started=!1,this.resizeUnsub&&(this.resizeUnsub(),this.resizeUnsub=null),this.tickInterval!==null&&(clearInterval(this.tickInterval),this.tickInterval=null),this.clearRow(),this.onRowCountChange?.(0))}update(t,n){let r=this.registry?this.registry.list():[],o=r.filter(l=>l.status==="running").length;this.totalSubsEver=Math.max(this.totalSubsEver,r.length);let i=this.totalSubsEver,s=t.turns.reduce((l,c)=>l+(c.toolEvents?.length??0),0),a;if(n!==void 0)a=n;else{let l=t.turnTokens[t.turnTokens.length-1];a=l!==void 0?(l.footprint??l.input+l.output+l.cache)/st(t.model):0}this.snapshot={totalTurns:t.totalTurns,sessionStartTime:t.sessionStartTime,toolCalls:s,activeSubs:o,totalSubs:i,contextRatio:Math.max(0,Math.min(1,a))},this.started&&this.repaint()}redraw(){this.repaint()}repaint(){if(!this.started||!this.stream.isTTY)return;let t=this.stream.rows??24,n=this.getExtraRows(),r=Math.max(1,t-n+1),o=Math.max(4,(this.stream.columns??80)-2),i=this.snapshot,s=i?{totalTurns:i.totalTurns,elapsedMs:Date.now()-i.sessionStartTime,toolCalls:i.toolCalls,activeSubs:i.activeSubs,totalSubs:i.totalSubs,contextRatio:i.contextRatio}:{totalTurns:0,elapsedMs:0,toolCalls:0,activeSubs:0,totalSubs:0,contextRatio:0};this.stream.write("\x1B[s"),this.stream.write(`\x1B[${r};1H`),this.stream.write("\x1B[2K"),this.stream.write(hae(s,o)),this.stream.write("\x1B[u")}clearRow(){if(!this.stream.isTTY)return;let t=this.stream.rows??24,n=this.getExtraRows(),r=Math.max(1,t-n+1);this.stream.write("\x1B[s"),this.stream.write(`\x1B[${r};1H`),this.stream.write("\x1B[2K"),this.stream.write("\x1B[u")}};import{EventEmitter as cqe}from"node:events";qm();import{spawn as oqe}from"node:child_process";var iqe=/\x1b(?:\[[0-9;]*[a-zA-Z]|[\]P^_X][^\x07\x1b]*(?:\x07|\x1b\\)|[@-OQ-WYZ\\])/g;function sqe(){let e="";return{strip(t){let r=(e+t).replace(iqe,""),o=r.match(/\x1b(?:[\]P^_X][^\x07\x1b]*|\[[0-9;]*)?$/);return o?(e=o[0],r.slice(0,r.length-e.length)):(e="",r)},flush(){return e="",""}}}function yae(e,t){if(e.length<=t)return e;let n=t;for(;n>0&&(e[n]&192)===128;)n--;return e.subarray(0,n)}var aqe=12e4,lqe=1e5;function bae(e){let t=Date.now(),n=e.timeoutMs??aqe,r=e.maxBytes??lqe,o=sqe(),i;try{i=oqe(e.command,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...e.cwd!==void 0?{cwd:e.cwd}:{},...e.env!==void 0?{env:{...process.env,...e.env}}:{}})}catch(T){let E=T instanceof Error?T.message:String(T);return{pid:void 0,kill:()=>{},promise:Promise.resolve({exitCode:null,durationMs:Date.now()-t,displayCaptured:"",modelCaptured:"",truncated:!1,errorReason:"spawn-failed",errorMessage:`Failed to spawn shell: ${E}`})}}i.unref();let s,a=!1,l=new Promise(T=>{s=E=>{a||(a=!0,T(E))}}),c="",u="",d=0,p=0,f=!1,g=!1,h=!1;function y(T){let E=r-d;if(E>0){let _=T.length<=E?T:yae(T,E);d+=_.length,c+=_.toString("utf8"),T.length>E&&(f=!0)}else T.length>0&&(f=!0);if(p<r){let _=o.strip(T.toString("utf8")),P=Buffer.byteLength(_,"utf8"),R=r-p;if(P<=R)u+=_,p+=P;else{let C=Buffer.from(_,"utf8");u+=yae(C,R).toString("utf8"),p=r,f=!0}}}function w(){i.pid!==void 0&&i.pid!==0&&!i.killed&&Zn(i.pid)}let S=setTimeout(()=>{w(),e.abort.removeEventListener("abort",v),s({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:f,errorReason:"timeout",errorMessage:`Command timed out after ${n}ms`})},n),v=()=>{w(),clearTimeout(S),s({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:f,errorReason:"abort",errorMessage:h?"Command killed":"Command aborted"})};e.abort.addEventListener("abort",v);function x(){g||a||d<r&&p<r||(g=!0,w(),clearTimeout(S),e.abort.removeEventListener("abort",v),s({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:!0,errorReason:"overflow",errorMessage:`Output exceeded ${r} bytes`}))}return i.stdout?.on("data",T=>{y(T);try{e.onChunk?.(T,"stdout")}catch{}x()}),i.stderr?.on("data",T=>{y(T);try{e.onChunk?.(T,"stderr")}catch{}x()}),i.on("error",T=>{clearTimeout(S),e.abort.removeEventListener("abort",v),s({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:f,errorReason:"spawn-failed",errorMessage:`Shell process error: ${T.message}`})}),i.on("close",(T,E)=>{if(clearTimeout(S),e.abort.removeEventListener("abort",v),!(g||a)){if(o.flush(),h){s({exitCode:T,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:f,errorReason:"abort",errorMessage:"Command killed"});return}if(T!==null&&T!==0){s({exitCode:T,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:f,errorReason:"nonzero-exit",errorMessage:`Command exited with code ${T}`});return}if(T===null){s({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:f,errorReason:"signal-killed",errorMessage:E?`Command killed by signal ${E}`:"Command killed by signal"});return}s({exitCode:T,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:f})}}),{pid:i.pid,promise:l,kill:(T="SIGKILL")=>{i.pid===void 0||i.pid===0||i.killed||(h=!0,Zn(i.pid,T))}}}var wae=200,Uh=class extends cqe{jobs=new Map;handles=new Map;aborts=new Map;counter=0;start(t){let n=`sh-${++this.counter}`,r=new AbortController,o=bae({command:t.command,...t.cwd!==void 0?{cwd:t.cwd}:{},abort:r.signal,...t.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{},...t.maxBytes!==void 0?{maxBytes:t.maxBytes}:{},...t.env!==void 0?{env:t.env}:{},...t.onChunk!==void 0?{onChunk:t.onChunk}:{}}),i={id:n,command:t.command,pid:o.pid,startedAt:Date.now(),mode:t.mode,status:"running"};return this.jobs.set(n,i),this.handles.set(n,o),this.aborts.set(n,r),o.promise.then(s=>{i.result=s,i.status=uqe(s),this.aborts.delete(n),this.handles.delete(n);try{this.emit("complete",i)}catch(a){console.warn(`[shell-jobs] listener for 'complete' threw on ${n}: ${a instanceof Error?a.message:String(a)}`)}this.pruneHistory()}),{job:i,handle:o}}get(t){return this.jobs.get(t)}list(){return[...this.jobs.values()].sort((t,n)=>t.startedAt-n.startedAt)}running(){return this.list().filter(t=>t.status==="running")}kill(t){let n=this.jobs.get(t);if(!n||n.status!=="running")return!1;let r=this.aborts.get(t);if(r)return r.abort(),!0;let o=this.handles.get(t);return o?(o.kill(),!0):!1}killAll(){let t=this.running();for(let n of t)this.kill(n.id);return t}runningCount(){let t=0;for(let n of this.jobs.values())n.status==="running"&&t++;return t}pruneHistory(){if(!(this.jobs.size<=wae))for(let[t,n]of this.jobs){if(this.jobs.size<=wae)break;n.status!=="running"&&this.jobs.delete(t)}}};function uqe(e){return e.errorReason===void 0?"completed":e.errorReason==="abort"?"killed":"failed"}L();tt();function dqe(e){if(!e.startsWith("!"))return null;if(e.startsWith("!&")){let n=e.slice(2).trim();return n.length===0?null:{mode:"background",command:n}}let t=e.slice(1).trim();return t.length===0?null:{mode:"foreground",command:t}}function pqe(e,t){let n=he(t.durationMs);return t.errorReason==="abort"?m.dim(` [${e.id} \xB7 killed \xB7 ${n}]`):t.errorReason==="timeout"?m.dim(` [${e.id} \xB7 timed out \xB7 ${n}]`):t.errorReason==="overflow"?m.dim(` [${e.id} \xB7 output overflow \xB7 ${n}]`):t.errorReason==="spawn-failed"?m.warning(` [${e.id} \xB7 spawn failed \xB7 ${n}]`):t.errorReason==="nonzero-exit"?m.warning(` [${e.id} \xB7 exit ${t.exitCode} \xB7 ${n}]`):t.errorReason==="signal-killed"?m.warning(` [${e.id} \xB7 killed by signal \xB7 ${n}]`):m.dim(` [${e.id} \xB7 exit ${t.exitCode??0} \xB7 ${n}]`)}function Sae(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function mqe(e,t,n){let r=[],o=[`mode="${t}"`];return n.exitCode!==null&&o.push(`exit="${n.exitCode}"`),n.errorReason!==void 0&&o.push(`reason="${n.errorReason}"`),o.push(`duration="${he(n.durationMs)}"`),n.truncated&&o.push('truncated="true"'),r.push(`<bash-passthrough ${o.join(" ")}>`),r.push(`<command>${Sae(e)}</command>`),r.push("<output>"),r.push(Sae(n.modelCaptured)),r.push("</output>"),r.push("</bash-passthrough>"),r.join(`
2129
2129
  `)}var yR=class e{constructor(t){this.opts=t;this.registry.on("complete",n=>{if(n.mode!=="background")return;let r=n.result;r&&(this.queueInjection({command:n.command,mode:"background",result:r}),this.pendingNotifications.push({job:n,result:r}),this.pendingNotifications.length>e.MAX_PENDING_NOTIFICATIONS&&this.pendingNotifications.shift())})}opts;registry=new Uh;pendingInjections=[];pendingNotifications=[];activeFgJobId=null;static MAX_PENDING_INJECTIONS=25;static MAX_PENDING_NOTIFICATIONS=50;async dispatch(t){let n=dqe(t);return n===null?t==="!"||t==="!&"||t.startsWith("! ")||t.startsWith("!& ")?(this.opts.writeLine(m.dim(" usage: !<cmd> (foreground) !&<cmd> (background)")),!0):!1:(n.mode==="foreground"?await this.runForeground(n.command):this.startBackground(n.command),!0)}drainInjections(){if(this.pendingInjections.length===0)return"";let t=this.pendingInjections.map(n=>mqe(n.command,n.mode,n.result));return this.pendingInjections=[],t.join(`
2130
2130
  `)+`
@@ -2171,7 +2171,7 @@ ${x}
2171
2171
  ${T}`})}return{fileBlocks:l,warnings:c}}function Oae(e){let t=e.replace(/\s+/g," ").trim();return t.length<=60?t:`${t.slice(0,59)}\u2026`}async function $ae(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}}F();L();F();tt();L();fl();function Dae(){return{toolStartTimes:new Map,subagentStartTimes:new Map,subagentLabels:new Map}}function Lae(e,t){je()&&(t.pending||e.toolStartTimes.has(t.toolUseId)||e.toolStartTimes.set(t.toolUseId,Date.now()))}function Fae(e,t,n,r){if(!je())return;let o=e.toolStartTimes.get(t.toolUseId),i=o!==void 0?Date.now()-o:void 0;e.toolStartTimes.delete(t.toolUseId);let s=$e(n??"tool"),a=t.isError?m.error("err"):m.success("ok"),l=i!==void 0?` \xB7 ${he(i)}`:"";r.fn(m.dim(` \u25E6 ${s}${l} \xB7 `)+a)}function Nae(e,t,n,r){if(!je())return;let{subagentId:o,agentType:i}=n,s=$e(i??o);if(e.subagentStartTimes.has(o)||(e.subagentStartTimes.set(o,Date.now()),e.subagentLabels.set(o,s),r.fn(m.dim(` \u25E6 worker ${s} started`))),t.type==="done"||t.type==="error"){let l=e.subagentStartTimes.get(o),c=l!==void 0?Date.now()-l:void 0;e.subagentStartTimes.delete(o),e.subagentLabels.delete(o);let u=c!==void 0?` \xB7 ${he(c)}`:"",d=t.type==="error"?m.error("failed"):m.success("done");r.fn(m.dim(` \u25E6 worker ${s}${u} \xB7 `)+d)}}var SR=class{state;writer;ttfb;constructor(t,n){this.state=Dae(),this.writer=t,this.ttfb=n}onToolStart(t){Lae(this.state,t)}onToolResult(t,n){Fae(this.state,t,n,this.writer)}onSubagentEvent(t,n){Nae(this.state,t,n,this.writer)}onFirstContent(t){this.ttfb.waitingLineEmitted&&(this.ttfb.waitingLineEmitted=!1,t.write("\r\x1B[2K"))}};function Bae(e){return{startedAt:e,received:!1,waitingLineEmitted:!1}}function Uae(e){return e.received?{}:{turnStartedAt:e.startedAt}}function jae(e,t,n){let r=t.type==="chunk"&&t.chunk.type==="content"&&!n;return r&&(e.received=!0),r}function Hae(e,t=process.stdout,n){if(!je()||!t.isTTY)return;(e?.fn??console.log)(m.dim(" \u25E6 waiting for response\u2026")),n&&(n.waitingLineEmitted=!0,e&&(n.plainHooks=new SR(e,n)))}me();L();var Xqe=3e3;async function Wae(e,t){if(!e)return t;let n=Date.now();if(n-t<Xqe)return t;try{let r=e();r instanceof Promise&&await r}catch(r){ze()&&console.error(" "+m.error("onContextProgress (status refresh) failed:"),r)}return n}L();me();gt();Ns();var Qqe="Keep waiting \u2014 auto-resume in progress",Kae="Switch model / provider (type /model after)",Zqe="Stop waiting";async function Gae(e){let{event:t,session:n,borrowedCompositor:r,pickerRef:o,completionWriter:i,disposeRendererOnce:s,setPausedState:a,onPauseInterrupt:l}=e;if(a?.(!0),await s(),r&&t.autoResume===!0){let c=new AbortController;o.abort=c;let u=t.resetsAt?t.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,d=u?`Keep waiting \u2014 auto-resumes at ${u}`:Qqe,p=[m.warning(" \u23F3 Usage limit reached.")+(u?m.dim(` Auto-resumes at ${u}.`):""),m.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];Rn(r,{header:p,options:[d,Kae,Zqe],signal:c.signal,initialIndex:0}).then(f=>{if(o.abort=null,!f)return;let g=f[0];g===void 0||g===d||(l(),g===Kae&&(i??{fn:console.log}).fn(m.dim(" Hint: type /model <name> to switch, then send your message again.")),n.interrupt().catch(h=>{ze()&&console.error(" "+m.error("picker pause-interrupt session.interrupt() failed:"),h)}))}).catch(f=>{ze()&&console.error(" "+m.error("picker promise rejected:"),f)})}else(i??{fn:console.log}).fn(lU({reason:t.reason,...t.resetsAt!==void 0?{resetsAt:t.resetsAt}:{},...t.accountId!==void 0?{accountId:t.accountId}:{},...t.autoResume!==void 0?{autoResume:t.autoResume}:{}}))}xx();async function qae(e,t,n,r,o="summary",i,s){let a=JZ(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0);let l=Date.now(),c=Bae(l);Hae(i,process.stdout,c),Fd(process.stdout,Wg(process.cwd(),!0));let u="",d=0,p=!1,f=!1,g=!1,h=!1,y=!1,w,S=!1,v=!1,x={abort:null},T=0,E=[],_=new Map,P=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,R=()=>{let U=r.subagentControl;U?.hasPromotableForeground()&&$ae(U,C,r.onQueuedUserMessage).then(({jobs:q,flushedText:j,flushedPreview:W})=>{let X=(i??{fn:console.log}).fn;for(let D of q)X(m.dim(` \u2192 subagent backgrounded as ${D.jobId}: ${D.label}`));q.some(D=>D.sharesWorktree)&&X(m.warning("\u26A0 Background child is writing to your worktree \u2014 edits may conflict until it finishes")),j!==void 0&&X(m.dim(` \u2192 queued message sent to this turn: ${Oae(W??j)}`))}).catch(()=>{})},C=r.getCompositor?r.getCompositor():null,I=()=>new ap({out:cp(i),thinkingMode:o,...P?{activeSkillName:P}:{},onCancel:()=>{t.interrupt().catch(U=>{ze()&&console.error(" "+m.error("session.interrupt() failed:"),U)})},...r.subagentControl?{onBackground:R}:{},...s?.history?{history:s.history}:{},...s?.autocompleteState?{autocompleteState:s.autocompleteState}:{},...s?.promptText!==void 0?{promptText:s.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...C?{compositor:C}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{},...Uae(c),...r.addPreviewDiffRef?{addPreviewDiffRef:r.addPreviewDiffRef}:{}}),O=I(),H=async()=>{if(!h){h=!0;try{await O.dispose()}catch{}}},M=async()=>{await O.arm();let U=O.getCompositor();if(i&&U){let q=U;i.fn=j=>q.commitAbove(j),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.(U),r.setInterruptNotifier?.(q=>O.setInterrupting(q)),r.rearmStatus?.()};try{C?C.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{S=!0,O.setSoftStopping(!0),t.interrupt().catch(Z=>{ze()&&console.error(" "+m.error("soft-stop session.interrupt() failed:"),Z)});let K=r.subagentControl;K?.hasActiveForeground()&&K.cancelActiveForeground().catch(Z=>{ze()&&console.error(" "+m.error("soft-stop cancelActiveForeground() failed:"),Z)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{v=!0,t.interrupt().catch(K=>{ze()&&console.error(" "+m.error("pause-interrupt session.interrupt() failed:"),K)})}),await M(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(R),r.setTaskViewHandler?.(Aae(r));let{fileBlocks:U,warnings:q}=Mae(e.text,{rootDir:process.cwd()});for(let K of q)(i??{fn:console.log}).fn(m.dim(` @-file: ${K}`));if(e.attachments.length>0&&(await t.waitForInitialization(),t.sessionId===void 0))throw new Error("CLI session initialized without a session id");let j=U.length>0||e.attachments.length>0?await Iae(e.text,e.attachments,void 0,U,t.sessionId):e.text,W=t.sendMessageStream(j);await xu((K,Z)=>{O.process(K,Z),Z&&c.plainHooks?.onSubagentEvent(K,Z)},async()=>{for await(let K of W){if(S||v)break;let Z=jae(c,K,f);if(K.type==="chunk"&&K.chunk.type==="content"?(u=p?Eae(u,K.chunk.content):u+K.chunk.content,p=!1,f=!0):K.type==="message"&&!f&&(u=K.message.content),K.type==="stream_retry"&&(u=u.slice(0,d),p=u.length>0),K.type==="chunk"&&K.chunk.type==="tool_use_detail"){let le=K.chunk,te={toolName:le.toolName,toolUseId:le.toolUseId,input:le.toolInput,...le.toolInputRaw!==void 0&&{inputRaw:le.toolInputRaw}};_.set(le.toolUseId,te),E.push(te),c.plainHooks?.onToolStart(le)}else if(K.type==="chunk"&&K.chunk.type==="tool_result"){let le=K.chunk;d=u.length,p=!0;let te=_.get(le.toolUseId);te&&(te.result=le.content,te.isError=le.isError,_.delete(le.toolUseId)),c.plainHooks?.onToolResult(le,te?.toolName),T=await Wae(r.onContextProgress,T)}if(K.type==="paused"){await Gae({event:K,session:t,borrowedCompositor:C,pickerRef:x,completionWriter:i,disposeRendererOnce:H,setPausedState:r.setPausedState,onPauseInterrupt:()=>{v=!0}});continue}if(K.type==="resumed"){r.setPausedState?.(!1),x.abort?.abort(),x.abort=null;let le=K.hotSwapped&&K.accountId?`\u25B6 Resumed on ${K.accountId}`:"\u25B6 Resumed";u="",d=0,p=!1,f=!1,E.length=0,_.clear(),y=!1,w=void 0,g=!1,O=I(),h=!1,await M(),(i??{fn:console.log}).fn(m.success(le));continue}if(K.type==="error"){await H(),Oc(xc(K.error)),g=!0;continue}O.process(K),Z&&(c.plainHooks?.onFirstContent(process.stdout),O.notifyFirstContent()),K.type==="done"&&(y=!0,w=K.metadata)}});let D=!1;if(y&&!S&&!v){let K=Tae(O.getPendingBuffer());K>=0?O.stripPendingTerminalState(K):jh(u)!==null&&(D=!0)}await H();let G=i?i.fn:console.log;if(S){let K=C?C.getPendingCount():0,Z=K>0?` \xB7 ${K} queued`:"";G(m.warning(`\u23F8 Stopped${Z} \u2014 work so far kept.`)+m.dim(" Send a message to continue.")),G("")}if(v&&(G(m.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),G("")),y&&!S&&!v){wl(n,a,u,w,E),await r.onTurnComplete?.(a,u).catch(()=>{}),Ld(process.stdout),n7(process.stdout,"afk: turn complete");let K=le=>{i?i.fn(le):console.log(le)},Z=jh(u);if(Z&&!D){K(Rae(Z,{durationMs:w?.durationMs,totalCostUsd:w?.totalCostUsd,toolCount:E.length})),K("");let le=IL(E),te=Tre(E);if(r.onTerminalState)try{r.onTerminalState(Z,{doneHasCorroboratingEvidence:te,doneEvidenceClassification:le})}catch{}if(n.permissionMode==="autonomous"){let _e=Z.kind==="done"&&af().verifyDone===!0&&!te;Ere(Z,void 0,{unverified:_e})}}if(DF(w,n,K),LF(K,process.stdout),r.onAfterTurn){let le=r.onAfterTurn();le instanceof Promise&&await le.catch(()=>{})}}}catch(U){await H(),g||Oc(xc(U))}finally{await H(),Fd(process.stdout,Wg(process.cwd(),!1)),i&&(i.fn=i.idleFn,i.suppressSubagentCompletion=!1),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setTaskViewHandler?.(null),r.setSoftStopHandler?.(null),r.setPausedState?.(!1),r.setPauseInterruptHandler?.(null),x.abort?.abort(),x.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}Cs();um();var eze=5e3,tze=3,nze="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function rze(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 zae(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,mascotBar:u,healthRail:d,verdictLedger:p,shellPassthrough:f,bgResultNotifier:g}=s,h=null,y=[];e.session.current.waitForInitialization().then(async I=>{ze()&&(h=xE(I)),await Sh(e.session.current),ze()&&(y=ZD())}).catch(()=>{});let w=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,S,v=!1,x=!1,T;e.clearPendingStopInjection=()=>{T=void 0};let E,_,P,R=(()=>{let I=parseInt(e.options.maxTurns,10);return I>0?I:void 0})(),C=0;for(g.onInjectable=()=>{C>=tze||!o.isAwaitingInput()||!o.bufferIsEmpty()||(C++,Ld(process.stdout),w={text:nze,attachments:[]},o.abortPendingRead())};;){if(C=0,h&&(e.replRenderer.writeLine(h),e.replRenderer.writeLine(""),h=null),y.length>0){for(let D of y)e.replRenderer.writeLine(D);e.replRenderer.writeLine(""),y=[]}let I=f.drainNotifications();for(let{job:D,result:G}of I){let K=G.errorReason===void 0?"\u2713":"\u2717",Z=G.errorReason==="abort"?"killed":G.errorReason==="timeout"?"timed out":G.errorReason==="signal-killed"?"killed by signal":`exit ${G.exitCode??0}`,le=Math.max(0,Math.round(G.durationMs/100)/10);e.replRenderer.writeLine(m.dim(` ${K} [${D.id}] ${Z} \xB7 ${le}s \xB7 `)+D.command)}let O=g.drainNotifications();for(let{job:D}of O){let G=D.status==="completed"?"\u2713":D.status==="failed"?"\u2717":"\u2298",K=D.endedAt!==void 0?Math.max(0,Math.round((D.endedAt-D.startedAt)/100)/10):0,Z=ee(D.label,60);e.replRenderer.writeLine(m.dim(` ${G} [${D.jobId}] subagent ${D.status} \xB7 ${K}s \xB7 `)+Z)}let H=l.renderIfChanged(e.stats.sessionId);if(H.length>0){for(let D of H)e.replRenderer.writeLine(D);e.replRenderer.writeLine("")}let M,U;if(w===void 0){let D=await e.session.current.takePendingPlanExitSeed();D!==void 0&&(e.stats.permissionMode=D.mode,w={text:D.message,attachments:[]})}if(w!==void 0){let D=w;w=void 0;let G=bp(e.stats.permissionMode),K=xl({buffer:D.text,promptText:G,isTTY:!!process.stdout.isTTY,attachmentSummary:zd([...D.attachments])});e.replRenderer.writeLine(K),M=D.text.trim(),U=D.attachments}else{let D=S;S=void 0;let G=await o.readLine({promptFn:()=>bp(e.stats.permissionMode),...D!==void 0?{initialBuffer:D}:{},primePromptSuggestion:!0,onSigint:r,onShiftTab:()=>{mR(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});M=G.text.trim(),U=G.attachments}if(!M&&U.length===0)continue;if(M.startsWith("!")){let D=/^(0|false|off|no)$/i.test(k.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!D&&(v||(v=!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 f.dispatch(M))){e.statusLine.rearm();continue}}let q=!1;if(M.startsWith("/")){let D=await i7(M,e.slashCtx,U);if(D.handled){if(D.result==="exit"){await e.resolveWorktreeDisposition?.(!0),e.rl.close();return}if((M==="/clear"||M.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(m.dim(` transcript: ${t.path()}`)),p.reset(),T=void 0),D.result!==null&&typeof D.result=="object"&&"kind"in D.result&&D.result.kind==="submit"){w={text:D.result.message,attachments:U??[]},e.statusLine.rearm();continue}if(D.result!==null&&typeof D.result=="object"&&"kind"in D.result&&D.result.kind==="prefill"){S=D.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}q=!0}a.push(M),await rze(e,M);let j=M;if(q){let D=k$(M);if(D){let G=D.name.replace(/^\//,"").split(":").pop()??"";if(G&&JD(G)){let K={skillName:G,rawArgs:D.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},Z=e.session.current.sessionId,le=Wl(Z),te=Date.now();N(`[afk trace] preflight.start commandName=${G}`);let _e=!1,De=await Hl(K,{cwd:e.stats.cwd??process.cwd(),artifactDir:le},Pn=>{ze()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${G}) failed: `)+(Pn instanceof Error?Pn.message:String(Pn)))});_e=De!==null,N(`[afk trace] preflight.end commandName=${G} durationMs=${Date.now()-te} success=${_e}`),j=XD(De?.manifestBlock,M)}}}let W=f.drainInjections();W.length>0&&(j=W+j);let X=g.drainInjections();if(X.length>0&&(j=X+j),T!==void 0&&(j=T+`
2172
2172
 
2173
2173
  `+j,T=void 0),e.hookRegistry)try{let D={event:"UserPromptSubmit",prompt:j,sessionId:e.stats.sessionId},G=await e.hookRegistry.dispatch(D);G.injectContext&&(j=G.injectContext+j)}catch(D){if(D instanceof Re){e.replRenderer.writeLine(m.warning("\u2298 Turn blocked by hook")+(D.reason?m.dim(`: ${ae(D.reason)}`):"")),e.statusLine.rearm();continue}if(D instanceof eo){e.replRenderer.writeLine(m.warning("\u2298 Turn blocked by hook")+m.dim(`: handler timed out after ${D.timeoutMs}ms`)),e.statusLine.rearm();continue}throw D}if(E=_=P=void 0,gU(),wU(),await qae({text:j,attachments:U},e.session.current,e.stats,{setInFlight(D){n.turnInFlight=D},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(D){await t.appendUser(D)},async onQueuedUserMessage(D){await t.appendQueuedUser(D)},async onTurnComplete(D,G){if(await t.appendTurn(D,G),e.stats.sessionId)try{As(e.stats)}catch(K){x||(x=!0,e.replRenderer.writeLine(m.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(K instanceof Error?K.message:String(K))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.repaint(mr(e.stats,e.contextSampler,e.gitStatusSampler,R)),e.statusLine.rearm(),c?.repaint("observing"),d?.update(e.stats)},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:(D,G)=>{p?.push(D),E=D.kind,_=G?.doneHasCorroboratingEvidence,P=G?.doneEvidenceClassification},setActiveCompositor:D=>{n.activeCompositor=D,D===null&&n.interruptPickerAbort&&(n.interruptPickerAbort.abort(),n.interruptPickerAbort=null)},setInterruptNotifier:D=>{n.notifyInterrupting=D},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:D=>o.setBackgroundHandler(D),setTaskViewHandler:D=>o.setTaskViewHandler(D),setSoftStopHandler:i,setPausedState:D=>o.setPausedState(D),setPauseInterruptHandler:D=>o.setPauseInterruptHandler(D),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(mr(e.stats,e.contextSampler,e.gitStatusSampler,R)),d?.update(e.stats,e.contextSampler.getRatio())},...c?{onStageChange:(D,G)=>{c.repaint(D),u?.onStage(D,G)}}:{},...e.addPreviewDiffRef?{addPreviewDiffRef:e.addPreviewDiffRef}:{}},e.stats.thinkingUi??e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(bp(e.stats.permissionMode))),e.hookRegistry)try{let D=await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId,...E!==void 0?{terminalState:E}:{},..._!==void 0?{doneHasCorroboratingEvidence:_}:{},...P!==void 0?{doneEvidenceClassification:P}:{}},void 0,eze);D.injectContext&&D.injectContext.trim().length>0&&(T=D.injectContext)}catch(D){if(D instanceof Dt)throw D;D instanceof eo?(N("[stop hook] handler timed out"),e.completionWriter.fn(m.dim(" [stop hook] timed out"))):D instanceof Re?e.completionWriter.fn(m.dim(` [stop hook] blocked: ${ae(D.reason??"no reason given")}`)):N("[stop hook] unexpected error: "+String(D))}}}function oze(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 Jae(e,t,n,r){let o=await Fse(),i=new pR({rl:e.rl,history:o,statusLine:e.statusLine}),s=oze(k.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await iae(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar,getMascotBar:()=>a?.mascotBar});a=kae(e,n);let c=a;e.slashCtx.suspendFooter=()=>{c.bgStatusBar.stop(),c.mascotBar.stop(),c.healthRail.stop(),e.statusLine.stop()},e.slashCtx.resumeFooter=()=>{e.statusLine.start(),c.healthRail.start(),c.mascotBar.start(),c.bgStatusBar.start(),c.bgStatusBar.redraw()},await zae(e,t,n,r,i,l,a,o),await e.resolveWorktreeDisposition?.(!0)}finally{n.tryAbortShellForeground=null,a?.shellPassthrough.drainOnExit(),a?.bgResultNotifier.dispose(),a?.healthRail.stop(),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)}}Qm();pu();import{execFile as ize}from"node:child_process";import{dirname as sze,isAbsolute as aze,resolve as lze}from"node:path";import{promisify as cze}from"node:util";var Vae=cze(ize),uze=3e3,dze=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function pze(){let t=(await Vae("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=aze(t)?t:lze(process.cwd(),t);return sze(n)}async function Yae(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await pze()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),uze)});try{let o=or({execFile:Vae,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=>dze.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}db();Qm();import{promises as mze}from"node:fs";import{dirname as fze,join as Zae}from"node:path";import{randomBytes as gze}from"node:crypto";var hze=["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(`
2174
- `),Xae=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,NF=30,yze=1024,bze=8e3,wze="haiku";async function Sze(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=xze(n,yze),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??bze),s=t.signal?Eze([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await Fc({token:t.token,model:t.model??wze,system:hze,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=vze(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=fze(t.worktreePath);return await kze(l,c)}function vze(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(Xae.test(t)&&t.length<=NF)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>NF)break;o=s}return Xae.test(o)?o:null}async function kze(e,t){if(!await Tze(Zae(t,e)))return e;let n=gze(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,NF-5)}-${n}`}async function Tze(e){try{return await mze.access(e),!0}catch{return!1}}function xze(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 Eze(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 ele(e){let t,n,r=Zae(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await Sze(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=`${yw(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return Qae(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 Qae(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 Qae(e,t){e&&e.setCwd(t),Rze(t)}function Rze(e){try{process.chdir(e)}catch{}}vt();Pt();kc();Io();B();import{spawn as nle}from"child_process";import{existsSync as rle,mkdirSync as Ize,readFileSync as ole,unlinkSync as tle,writeFileSync as ile}from"fs";import{get as Mze}from"https";import{join as sle}from"path";import{readFileSync as Aze}from"fs";import{dirname as Cze,join as _ze}from"path";import{fileURLToPath as Pze}from"url";function $o(){try{return"5.196.0"}catch{}try{let e=Cze(Pze(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(Aze(_ze(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}L();F();var Oze=64*1024,$ze=10800*1e3,Dze=800,Lze=3600*1e3,Fze="update-check.json",Nze="pending-update.json";function BF(){return sle(ra(),Fze)}function Hh(){return sle(ra(),Nze)}function UF(){let e=ra();rle(e)||Ize(e,{recursive:!0})}function ale(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 lle(){try{let e=ole(BF(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function cle(){try{UF();let e=`
2174
+ `),Xae=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,NF=30,yze=1024,bze=8e3,wze="haiku";async function Sze(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=xze(n,yze),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??bze),s=t.signal?Eze([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await Fc({token:t.token,model:t.model??wze,system:hze,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=vze(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=fze(t.worktreePath);return await kze(l,c)}function vze(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(Xae.test(t)&&t.length<=NF)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>NF)break;o=s}return Xae.test(o)?o:null}async function kze(e,t){if(!await Tze(Zae(t,e)))return e;let n=gze(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,NF-5)}-${n}`}async function Tze(e){try{return await mze.access(e),!0}catch{return!1}}function xze(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 Eze(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 ele(e){let t,n,r=Zae(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await Sze(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=`${yw(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return Qae(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 Qae(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 Qae(e,t){e&&e.setCwd(t),Rze(t)}function Rze(e){try{process.chdir(e)}catch{}}vt();Pt();kc();Io();B();import{spawn as nle}from"child_process";import{existsSync as rle,mkdirSync as Ize,readFileSync as ole,unlinkSync as tle,writeFileSync as ile}from"fs";import{get as Mze}from"https";import{join as sle}from"path";import{readFileSync as Aze}from"fs";import{dirname as Cze,join as _ze}from"path";import{fileURLToPath as Pze}from"url";function $o(){try{return"5.197.0"}catch{}try{let e=Cze(Pze(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(Aze(_ze(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}L();F();var Oze=64*1024,$ze=10800*1e3,Dze=800,Lze=3600*1e3,Fze="update-check.json",Nze="pending-update.json";function BF(){return sle(ra(),Fze)}function Hh(){return sle(ra(),Nze)}function UF(){let e=ra();rle(e)||Ize(e,{recursive:!0})}function ale(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 lle(){try{let e=ole(BF(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function cle(){try{UF();let e=`
2175
2175
  const https = require('https');
2176
2176
  const fs = require('fs');
2177
2177
  const url = 'https://registry.npmjs.org/agent-afk/latest';