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/telegram.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var CW=Object.defineProperty;var h=(t,e)=>()=>(t&&(e=t(t=0)),e);var uo=(t,e)=>{for(var n in e)CW(t,n,{get:e[n],enumerable:!0})};function Vs(t){return Ys.find(e=>e.name===t)}function Mc(t){return process.env[t]!==void 0}var Gk=h(()=>{"use strict";L()});var Ys,Xk,k,L=h(()=>{"use strict";Gk();Ys=[{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"}],Xk={};for(let t of Ys){let e=t.name;Object.defineProperty(Xk,e,{get(){return process.env[e]},enumerable:!("secret"in t&&t.secret),configurable:!0})}k=Xk});import{basename as PW,dirname as MW,join as rr}from"path";function Qs(t){if(!OW.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function po(){return rr(ee(),"witness")}function st(t){return Qs(t),rr(po(),t)}function ym(t){return rr(st(t),"inbound-attachments")}function bm(t){return rr(st(t),"prompts")}function wm(t){return rr(st(t),"outputs")}function Sm(t){if(!(!t||t===""))return rr(st(t),"bash-captures")}function or(t){return!t||t.startsWith("in-memory:")?null:PW(MW(t))}function Oc(){return rr(ee(),"receipts")}var OW,zk=h(()=>{"use strict";j();OW=/^[a-zA-Z0-9_-]+$/});import{existsSync as Jk,mkdirSync as DW,renameSync as FW,cpSync as LW,rmSync as NW}from"fs";import{join as H,dirname as Qk,isAbsolute as km}from"path";import{homedir as vm}from"os";import{fileURLToPath as $W}from"url";function oe(){let t=k.AFK_HOME;if(t!==void 0&&t!==""){if(!km(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return H(vm(),".afk")}function vt(){let t=k.AFK_FRAMEWORK_DIR;if(t!==void 0&&t!==""){if(!km(t)||t==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${t}`);return t}return H(oe(),"agent-framework")}function Dc(){return H(vt(),"forge-telemetry.jsonl")}function Zk(){return H(vt(),"briefs")}function ev(){return H(vt(),"facets")}function Fc(){return H(oe(),"skills")}function Lt(){return H(oe(),"plugins")}function tv(t=process.cwd()){return H(t,".afk")}function nv(t=process.cwd()){return H(tv(t),"skills")}function rv(t=process.cwd()){return H(tv(t),"plugins")}function ov(t=process.cwd()){return H(t,".afk","plans")}function Lc(){return H(Lt(),".index.json")}function Tm(){return H(rn(),"schedules.json")}function sv(){let t=$W(import.meta.url),e=Qk(t);return H(e,"bundled-plugins")}function rn(){return H(oe(),"config")}function ee(){let t=k.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!km(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return H(oe(),"state")}function ce(){return H(ee(),"sessions")}function Nc(){return H(ee(),"presence")}function $c(){return H(ee(),"memory")}function fo(){return H(ee(),"kv","kv.db")}function Uc(){return H(ee(),"handoffs")}function Bc(){return H(ee(),"session-grants.jsonl")}function Zs(){return H(rn(),"permissions.json")}function iv(){return H(oe(),"farms")}function av(t){return H(iv(),t)}function cv(t="default"){return H(ee(),"daemon",`agent-afk@${t}`)}function lv(){return H(ee(),"worktree-sweep.lock")}function jc(){return H(ee(),"worktree-roots.json")}function sr(){return H(rn(),"afk.env")}function on(){return H(rn(),"afk.config.json")}function _m(){return H(rn(),"settings.json")}function dv(t=process.cwd()){return H(t,".afk","settings.json")}function uv(){return H(oe(),"AFK.md")}function pv(t=process.cwd()){return H(t,"AFK.md")}function fv(){return H(vm(),".afk.env")}function Hc(){return H(vm(),".afk.config.json")}function UW(){return H(oe(),"sessions")}function BW(t,e){if(t!==e&&Jk(t)&&!Jk(e))try{DW(Qk(e),{recursive:!0});try{FW(t,e)}catch(n){if(n.code==="EXDEV")try{LW(t,e,{recursive:!0}),NW(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
2
+ var CW=Object.defineProperty;var h=(t,e)=>()=>(t&&(e=t(t=0)),e);var uo=(t,e)=>{for(var n in e)CW(t,n,{get:e[n],enumerable:!0})};function Vs(t){return Ys.find(e=>e.name===t)}function Mc(t){return process.env[t]!==void 0}var Gk=h(()=>{"use strict";L()});var Ys,Xk,k,L=h(()=>{"use strict";Gk();Ys=[{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"}],Xk={};for(let t of Ys){let e=t.name;Object.defineProperty(Xk,e,{get(){return process.env[e]},enumerable:!("secret"in t&&t.secret),configurable:!0})}k=Xk});import{basename as PW,dirname as MW,join as rr}from"path";function Qs(t){if(!OW.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function po(){return rr(ee(),"witness")}function st(t){return Qs(t),rr(po(),t)}function ym(t){return rr(st(t),"inbound-attachments")}function bm(t){return rr(st(t),"prompts")}function wm(t){return rr(st(t),"outputs")}function Sm(t){if(!(!t||t===""))return rr(st(t),"bash-captures")}function or(t){return!t||t.startsWith("in-memory:")?null:PW(MW(t))}function Oc(){return rr(ee(),"receipts")}var OW,zk=h(()=>{"use strict";j();OW=/^[a-zA-Z0-9_-]+$/});import{existsSync as Jk,mkdirSync as DW,renameSync as FW,cpSync as LW,rmSync as NW}from"fs";import{join as H,dirname as Qk,isAbsolute as km}from"path";import{homedir as vm}from"os";import{fileURLToPath as $W}from"url";function oe(){let t=k.AFK_HOME;if(t!==void 0&&t!==""){if(!km(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return H(vm(),".afk")}function vt(){let t=k.AFK_FRAMEWORK_DIR;if(t!==void 0&&t!==""){if(!km(t)||t==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${t}`);return t}return H(oe(),"agent-framework")}function Dc(){return H(vt(),"forge-telemetry.jsonl")}function Zk(){return H(vt(),"briefs")}function ev(){return H(vt(),"facets")}function Fc(){return H(oe(),"skills")}function Lt(){return H(oe(),"plugins")}function tv(t=process.cwd()){return H(t,".afk")}function nv(t=process.cwd()){return H(tv(t),"skills")}function rv(t=process.cwd()){return H(tv(t),"plugins")}function ov(t=process.cwd()){return H(t,".afk","plans")}function Lc(){return H(Lt(),".index.json")}function Tm(){return H(rn(),"schedules.json")}function sv(){let t=$W(import.meta.url),e=Qk(t);return H(e,"bundled-plugins")}function rn(){return H(oe(),"config")}function ee(){let t=k.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!km(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return H(oe(),"state")}function ce(){return H(ee(),"sessions")}function Nc(){return H(ee(),"presence")}function $c(){return H(ee(),"memory")}function fo(){return H(ee(),"kv","kv.db")}function Uc(){return H(ee(),"handoffs")}function Bc(){return H(ee(),"session-grants.jsonl")}function Zs(){return H(rn(),"permissions.json")}function iv(){return H(oe(),"farms")}function av(t){return H(iv(),t)}function cv(t="default"){return H(ee(),"daemon",`agent-afk@${t}`)}function lv(){return H(ee(),"worktree-sweep.lock")}function jc(){return H(ee(),"worktree-roots.json")}function sr(){return H(rn(),"afk.env")}function on(){return H(rn(),"afk.config.json")}function _m(){return H(rn(),"settings.json")}function dv(t=process.cwd()){return H(t,".afk","settings.json")}function uv(){return H(oe(),"AFK.md")}function pv(t=process.cwd()){return H(t,"AFK.md")}function fv(){return H(vm(),".afk.env")}function Hc(){return H(vm(),".afk.config.json")}function UW(){return H(oe(),"sessions")}function BW(t,e){if(t!==e&&Jk(t)&&!Jk(e))try{DW(Qk(e),{recursive:!0});try{FW(t,e)}catch(n){if(n.code==="EXDEV")try{LW(t,e,{recursive:!0}),NW(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
3
3
  `)}}}catch{}}function mv(){BW(UW(),ce())}function ir(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(t.length>Vk)throw new Error(`Invalid jobId: exceeds ${Vk} chars`);if(!jW.test(t))throw new Error(`Invalid jobId: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function Wc(){return H(ee(),"bg")}function mo(t){return ir(t),H(Wc(),t)}function gv(t){return H(mo(t),"events.jsonl")}function hv(t){return H(mo(t),"meta.json")}function Em(){return H(ee(),"subagent-logs")}function Am(t){return ir(t),H(Em(),t)}function yv(t,e){return ir(e),H(Am(t),`${e}.jsonl`)}function xm(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>Yk)throw new Error(`Invalid browser profile: exceeds ${Yk} chars`);if(!HW.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function WW(){return H(ee(),"browser")}function KW(t){return xm(t),H(WW(),t)}function Rm(t){return H(KW(t),"storageState.json")}function go(t){return typeof t=="string"&&t.length>0&&t.length<=GW&&qW.test(t)}function ei(t){if(!go(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return H(ce(),t)}function ti(t){return H(ei(t),"events.jsonl")}function bv(t){return H(ei(t),"session.key")}function Kc(){return H(ee(),"mcp","server-status.json")}function ho(){return H(ee(),"waves")}function yo(t){return H(ho(),`${t}.json`)}function wv(){return H(ee(),"effect-ledger.jsonl")}var jW,Vk,HW,Yk,qW,GW,j=h(()=>{"use strict";L();zk();jW=/^[A-Za-z0-9_-]+$/,Vk=128;HW=/^[A-Za-z0-9_-]+$/,Yk=128;qW=/^[A-Za-z0-9_-]+$/,GW=128});function XW(){return k.AFK_DEBUG==="1"||k.DEBUG==="1"}function F(...t){XW()&&console.log(...t)}var ie=h(()=>{"use strict";L()});function ar(t,e={}){let{guard:n,onParseError:r}=e,o=[];for(let s of t.split(`
4
4
  `)){let i=s.trim();if(i==="")continue;let a;try{a=JSON.parse(i)}catch{r?.(i);continue}if(n!==void 0){if(!n(a))continue;o.push(a)}else o.push(a)}return o}var qc=h(()=>{"use strict"});import zW from"better-sqlite3";import{existsSync as ni,mkdirSync as Sv,readFileSync as Gc,writeFileSync as kv,readdirSync as JW,appendFileSync as VW,unlinkSync as vv,copyFileSync as YW,renameSync as QW}from"fs";import{join as it,basename as Tv,resolve as Xc,relative as ZW}from"path";function Cv(t){return Math.ceil(t.length/3.5)}function i1(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function Av(t){if(!t||t.length>100||!a1.test(t))throw new Error(`Invalid procedure name "${t}": must be 1-100 chars, alphanumeric/hyphens/underscores only`);return t}function d1(t){if(!t||typeof t!="object")return!1;let e=t;if(typeof e.type!="string"||!c1.has(e.type)||typeof e.timestamp!="string"||!e.data||typeof e.data!="object")return!1;if(e.type==="fact"){let n=e.data;if(typeof n.category!="string"||!l1.has(n.category))return!1}return!0}function xv(t,e){let n=ZW(e,t);if(n.startsWith("..")||n.startsWith("/"))throw new Error("Path traversal detected")}function Rv(t,e){let n=e.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!n)return{name:Tv(t,".md"),content:e,created:"",source_session:null,access_count:0};let r=n[1]??"",o=n[2]??"",s=l=>l.match(/^name:\s*(.+)$/m)?.[1]?.trim()??Tv(t,".md"),i=l=>l.match(/^created:\s*(.+)$/m)?.[1]?.trim()??"",a=l=>l.match(/^source_session:\s*(.+)$/m)?.[1]?.trim()??null,c=l=>{let d=l.match(/^access_count:\s*(\d+)$/m);return d?parseInt(d[1],10):0};return{name:s(r),content:o.trim(),created:i(r),source_session:a(r),access_count:c(r)}}var _v,e1,t1,Ev,zc,n1,Vc,r1,o1,Iv,Im,Jc,s1,Ze,a1,c1,l1,Yc=h(()=>{"use strict";j();ie();qc();_v="HOT.md",e1="HOT.md.bak",t1="memory.db",Ev="memory-wal.jsonl",zc="procedures",n1="HOT.md.tmp",Vc=5250,r1=Math.ceil(Vc/3.5),o1=600,Iv=.8,Im='<!-- HOT TRUNCATED to fit the ~1,500-token cap; move durable detail to the fact archive (memory_update target:"fact"). -->',Jc=4,s1=`
5
5
  CREATE TABLE IF NOT EXISTS sessions (
@@ -119,7 +119,7 @@ ${Im}
119
119
  `).run(i.session_id??null,i.created_at,i.category,i.content,i.source_surface??"cli",i.evidence??null),n++)}else if(s.type==="supersede"){let i=s.data,a,c;if(typeof i.old_content=="string"&&typeof i.old_created_at=="string"){let l;(typeof i.old_session_id<"u"||typeof i.old_category=="string")&&(l=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ? AND COALESCE(session_id,'') = ? AND category = ?").get(i.old_content,i.old_created_at,i.old_session_id??"",i.old_category??"")),l||(l=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ?").get(i.old_content,i.old_created_at)),a=l?.id}else typeof i.old_fact_id=="number"&&(a=i.old_fact_id);if(typeof i.new_content=="string"&&typeof i.new_created_at=="string"){let l;(typeof i.new_session_id<"u"||typeof i.new_category=="string")&&(l=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ? AND COALESCE(session_id,'') = ? AND category = ?").get(i.new_content,i.new_created_at,i.new_session_id??"",i.new_category??"")),l||(l=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ?").get(i.new_content,i.new_created_at)),c=l?.id}else typeof i.new_fact_id=="number"&&(c=i.new_fact_id);typeof a=="number"&&typeof c=="number"&&(this.db.prepare("UPDATE facts SET superseded_by = ? WHERE id = ? AND superseded_by IS NULL").run(c,a),n++)}}catch(i){F("WAL replay: skipping malformed line:",String(i))}}vv(e)}catch(r){F("WAL file unreadable, skipping recovery:",String(r))}return n}close(){this.db.close()}appendWAL(e){let n=it(this.dir,Ev);try{VW(n,JSON.stringify(e)+`
120
120
  `,"utf-8")}catch(r){F("WAL append failed (non-fatal):",String(r))}}};a1=/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;c1=new Set(["fact","session_start","session_end","supersede"]),l1=new Set(["preference","convention","decision","learning"])});import{existsSync as u1,readFileSync as p1}from"fs";import{join as f1}from"path";function Pv(){let t=f1($c(),"HOT.md");if(!u1(t))return null;try{let e=p1(t,"utf-8");return e.trim().length>0?e:null}catch{return null}}function Cm(t){let e=Pv();if(!e)return t;let r=`<cross-session-memory>
121
121
  ${e.replace(/<\/?cross-session-memory\b[^>]*>/gi,"")}
122
- </cross-session-memory>`;return{...t,hotMemory:r}}var Mv=h(()=>{"use strict";j()});function wn(t){switch(t){case"cli":case"repl":return"cli";case"telegram":return"telegram";case"daemon":return"daemon";case"web":return"web";case"subagent":case"unknown":case void 0:return"unknown"}}function Qc(t){return t==null?"main":"subagent"}function Sn(t){return(t??0)>0?"subagent":"main"}var cr=h(()=>{"use strict"});function Pm(t,e="cli"){return n=>{if(n.event!=="SessionEnd")return{};if(n.parentSessionId)return{};try{let r=n.sessionId;r&&(t.startSession({session_id:r,surface:e,actor:Qc(n.parentSessionId)}),t.endSession(r,n.reason??"session ended","completed"))}catch{}return{}}}var Ov=h(()=>{"use strict";cr()});function Fv(t){return m1.has(t)}function Zc(){return k.AFK_MEMORY_EVIDENCE_GATE==="1"}function Mm(t){return Fv(t)}function el(t){if(typeof t!="string")return null;let e=t.trim();return e.length>0?e:null}function Lv(t,e){return Fv(t)?el(e)?"verified":"unverified":"not-applicable"}function Nv(t,e){return e!=="unverified"||t.startsWith(Dv)?t:`${Dv} ${t}`}var m1,Dv,$v=h(()=>{"use strict";L();m1=new Set(["convention"]),Dv="[unverified]"});function h1(t,e){return e?t.map(n=>{if(n.type!=="fact"||!n.category)return{...n,verification:"not-applicable"};let r=Lv(n.category,n.evidence);return{...n,verification:r,content:Nv(n.content,r)}}):t.map(n=>{let r={...n};return delete r.evidence,delete r.verification,r})}function ri(t,e,n){let r=async i=>{try{let a=y1(i),c=t.search(a.query,{category:a.category,since:a.since,limit:a.limit??10});return{content:JSON.stringify(h1(c,Zc()))}}catch(a){return{content:`memory_search error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},o=async i=>{try{let a=b1(i);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 c=t.saveHot(a.content),l={saved:!0,target:"hot",usage:{tokens:c.tokens,maxTokens:c.maxTokens,pct:c.pct}};return c.truncated?(l.truncated=!0,l.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".'):c.pct>=Iv*100&&(l.warning=`Hot memory is at ${c.pct}% of the ~1,500-token cap. Move non-essential lines to the fact archive (target:"fact") before it truncates.`),{content:JSON.stringify(l)}}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 c=a.category,l=el(a.evidence),u={id:t.storeFact({session_id:e,category:c,content:a.content,source_surface:n??"cli",evidence:l}),action:"set",target:"fact"};return Zc()&&Mm(c)&&!l&&(u.warning=Uv),{content:JSON.stringify(u)}}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 c=t.getFact(a.supersedes),l=a.evidence===void 0?void 0:el(a.evidence),u={id:t.supersedeFact(a.supersedes,a.content,a.category??void 0,l),action:"supersede",target:"fact",supersedes:a.supersedes};if(Zc()){let p=a.category??c?.category;p&&Mm(p)&&((l===void 0?c?.evidence??null:l)?l===void 0&&(u.warning=g1):u.warning=Uv)}return{content:JSON.stringify(u)}}if(a.action==="remove"){if(!a.id)return{content:'id (fact ID) is required for action: "remove"',isError:!0};let c=t.removeFact(a.id);return{content:JSON.stringify({removed:c,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}}},s=async i=>{try{let a=w1(i);return t.writeProcedure(a.name,a.content,e),{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",s]])}function y1(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.query!="string")throw new Error("query (string) is required");let n={query:e.query};if(e.category!==void 0){if(typeof e.category!="string")throw new Error("category must be a string");let r=["preference","convention","decision","learning"];if(!r.includes(e.category))throw new Error(`category must be one of: ${r.join(", ")}`);n.category=e.category}if(e.since!==void 0){if(typeof e.since!="string")throw new Error("since must be a string (ISO date)");n.since=e.since}if(e.limit!==void 0){if(typeof e.limit!="number"||e.limit<=0)throw new Error("limit must be a positive number");n.limit=e.limit}return n}function b1(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t,n=["hot","fact"];if(typeof e.target!="string"||!n.includes(e.target))throw new Error(`target must be one of: ${n.join(", ")}`);let r=["set","supersede","remove"];if(typeof e.action!="string"||!r.includes(e.action))throw new Error(`action must be one of: ${r.join(", ")}`);let o={target:e.target,action:e.action};if(e.content!==void 0){if(typeof e.content!="string")throw new Error("content must be a string");o.content=e.content}if(e.category!==void 0){if(typeof e.category!="string")throw new Error("category must be a string");let s=["preference","convention","decision","learning"];if(!s.includes(e.category))throw new Error(`category must be one of: ${s.join(", ")}`);o.category=e.category}if(e.evidence!==void 0){if(typeof e.evidence!="string")throw new Error("evidence must be a string");o.evidence=e.evidence}if(e.supersedes!==void 0){if(typeof e.supersedes!="number"||e.supersedes<=0)throw new Error("supersedes must be a positive fact ID");o.supersedes=e.supersedes}if(e.id!==void 0){if(typeof e.id!="number"||e.id<=0)throw new Error("id must be a positive fact ID");o.id=e.id}return o}function w1(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.name!="string")throw new Error("name (string) is required");if(typeof e.content!="string")throw new Error("content (string) is required");return{name:e.name,content:e.content}}var bo,Bv,jv,kn,tl,Uv,g1,Om=h(()=>{"use strict";Yc();$v();bo={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"]}},Bv={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"]}},jv={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"]}},kn=[bo,Bv,jv],tl=kn.map(t=>t.name),Uv='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.',g1='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 Nt=h(()=>{"use strict";Yc();Mv();Ov();Om()});import{existsSync as T1}from"node:fs";function Um(t){let e=t.indexOf($m);if(e===-1)return;let n=t.slice(e+$m.length),r=n.indexOf("/"),o=r===-1?n:n.slice(0,r);if(o.length!==0)return t.slice(0,e+$m.length)+o}function Gv(t){return t===void 0||T1(t)?"ok":"missing"}var $m,Bm=h(()=>{"use strict";$m="/.afk-worktrees/"});function qe(t){return t.replace(/\bauthorization:\s*bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]").replace(/\bsk-ant-[A-Za-z0-9_-]{20,}/g,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,"[REDACTED]").replace(/\b(?:AKIA|ASIA|AROA|AIDA|AGPA|AIPA|ANPA|ANVA|APKA|ABIA|ACCA)[A-Z0-9]{16}\b/g,"[REDACTED]").replace(/(?<![/.\w])[A-Za-z0-9+/=_-]{32,}(?![/.\w])/g,e=>jm(e)||_1(e)?e:"[REDACTED]")}function jm(t){if(!t.includes("/")||/[+=]/.test(t))return!1;let e=n=>n.length>=32&&!n.includes(".")&&/[A-Za-z]/.test(n)&&/[0-9]/.test(n);return!t.split("/").some(e)}function _1(t){if(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(t))return!0;let e=/^([A-Za-z_][A-Za-z0-9_]*)=(?:[0-9a-f]{40}|[0-9a-f]{64})$/.exec(t);return e!==null&&/^(?:ref|sha|commit|base)$/i.test(e[1]??"")}var vn=h(()=>{"use strict"});import{createHash as E1,randomUUID as A1}from"node:crypto";import{mkdirSync as x1,readFileSync as R1,writeFileSync as I1,renameSync as C1}from"node:fs";import{join as P1,dirname as M1}from"node:path";function L1(t){let e=E1("sha256").update(t,"utf8").digest("hex"),n=qe(t.slice(0,D1)),r=Buffer.byteLength(t,"utf8");return{sha256:e,head:n,byteLen:r}}function N1(){let t=k.AFK_WAVE_MANIFEST_TTL_HOURS;if(t!==void 0&&t!==""){let e=Number.parseFloat(t);if(Number.isFinite(e)&&e>0)return e}return O1}function ol(t){let e=t.cwd!==void 0?Um(t.cwd):void 0;return{id:t.id,status:"pending",promptDigest:L1(t.prompt),cwd:t.cwd,model:t.model,startedAt:void 0,settledAt:void 0,errorMessage:void 0,upstreamIds:t.upstreamIds??[],worktreePath:e}}function sl(t){if(k.AFK_WAVE_MANIFEST_DISABLED!=="1")try{let e=A1().replace(/-/g,""),n=new Date,r=new Date(n.getTime()+N1()*60*60*1e3),o={version:1,waveId:e,parentSessionId:t.parentSessionId,traceLabel:t.traceLabel,createdAt:n.toISOString(),updatedAt:n.toISOString(),expiresAt:r.toISOString(),source:t.source,units:t.units};return il(o),e}catch{return}}function il(t){try{let e=ho();x1(e,{recursive:!0});let n=yo(t.waveId),r=P1(M1(n),`.${t.waveId}.tmp`);I1(r,JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),C1(r,n)}catch{}}function al(t){try{let e=R1(yo(t),"utf8"),n=JSON.parse(e);return typeof n!="object"||n===null||n.version!==1?void 0:n}catch{return}}function lr(t,e,n,r){try{let o=al(t);if(o===void 0)return;let s=new Date().toISOString(),i=o.units.find(a=>a.id===e);if(i===void 0)return;i.status=n,n==="running"&&(i.startedAt=s),(n==="done"||n==="failed"||n==="skipped")&&(i.settledAt=s),r?.errorMessage!==void 0&&(i.errorMessage=r.errorMessage.slice(0,F1)),r?.cwd!==void 0&&(i.cwd=r.cwd,i.worktreePath=Um(r.cwd)),o.updatedAt=s,il(o)}catch{}}var O1,D1,F1,cl=h(()=>{"use strict";L();j();Bm();vn();O1=48,D1=512,F1=500});function te(t){return t.replace(Xv,"").replace($1," ").trim()}function ve(t){return t.replace(Xv,"")}var Xv,$1,at=h(()=>{"use strict";Xv=/\x1B\][^\x07\x1B\x9C]*(?:\x07|\x1B\\|\x9C)|\x1B[P^_X][^\x1B\x9C]*(?:\x1B\\|\x9C)|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[6-_]/g,$1=/[\x00-\x1F\x7F-\x9F]/g});import{readdirSync as zv,unlinkSync as Jv}from"node:fs";function Vv(t){let e={offers:[],deletedExpired:0};try{let n=ho(),r;try{r=zv(n)}catch{return e}let o=Date.now();for(let s of r){if(!s.endsWith(".json"))continue;let i=s.slice(0,-5);if(!/^[A-Za-z0-9]+$/.test(i))continue;let a=al(i);if(a===void 0)continue;let c=new Date(a.expiresAt).getTime();if(!Number.isFinite(c)||c<o){try{Jv(yo(i)),e.deletedExpired+=1}catch{}continue}if(a.offeredAt!==void 0)continue;let l=new Date(a.createdAt).getTime(),d=Number.isFinite(l)?l:0,u=o-d<B1,p=a.parentSessionId===t.sessionId;if(!u&&!p)continue;let f=a.units.filter(b=>U1.has(b.status));if(f.length===0)continue;let m=new Set(a.units.filter(b=>b.status==="done").map(b=>b.id)),g=[],y=[];for(let b of f){if(b.upstreamIds.length>0&&b.upstreamIds.some(_=>!m.has(_))){g.push(b);continue}let T=Gv(b.worktreePath);y.push({unit:b,worktreeStatus:T})}(y.length>0||g.length>0)&&e.offers.push({manifest:a,resumable:y,blocked:g})}}catch{}return e}function Yv(t){let{manifest:e,resumable:n,blocked:r}=t,o=new Date(e.createdAt),s=Date.now()-o.getTime(),i=j1(s),a=[`[wave-resume] Wave ${e.waveId} from ${i} ago has ${n.length+r.length} unsettled unit(s).`,` Source: ${e.source}`];if(n.length>0){a.push(" Units ready to resume:");for(let{unit:c,worktreeStatus:l}of n){let d=ve(c.promptDigest.head.slice(0,80)).replace(/\n/g," "),u=c.cwd!==void 0?` (cwd: ${ve(c.cwd)})`:"",p=l==="missing"?" \u26A0 worktree was swept \u2014 cannot re-dispatch without its working directory":"";a.push(` \xB7 ${c.id}: ${d}...${u}${p}`)}}if(r.length>0){a.push(" Units blocked on failed upstream deps:");for(let c of r)a.push(` \xB7 ${c.id} (depends on: ${c.upstreamIds.join(", ")})`)}return a.push(" To retry, re-dispatch each ready unit's prompt from its listed cwd; this notice does not accept yes/no replies."),a.join(`
122
+ </cross-session-memory>`;return{...t,hotMemory:r}}var Mv=h(()=>{"use strict";j()});function wn(t){switch(t){case"cli":case"repl":return"cli";case"telegram":return"telegram";case"daemon":return"daemon";case"web":return"web";case"subagent":case"unknown":case void 0:return"unknown"}}function Qc(t){return t==null?"main":"subagent"}function Sn(t){return(t??0)>0?"subagent":"main"}var cr=h(()=>{"use strict"});function Pm(t,e="cli"){return n=>{if(n.event!=="SessionEnd")return{};if(n.parentSessionId)return{};try{let r=n.sessionId;r&&(t.startSession({session_id:r,surface:e,actor:Qc(n.parentSessionId)}),t.endSession(r,n.reason??"session ended","completed"))}catch{}return{}}}var Ov=h(()=>{"use strict";cr()});function Fv(t){return m1.has(t)}function Zc(){return k.AFK_MEMORY_EVIDENCE_GATE!=="0"}function Mm(t){return Fv(t)}function el(t){if(typeof t!="string")return null;let e=t.trim();return e.length>0?e:null}function Lv(t,e){return Fv(t)?el(e)?"verified":"unverified":"not-applicable"}function Nv(t,e){return e!=="unverified"||t.startsWith(Dv)?t:`${Dv} ${t}`}var m1,Dv,$v=h(()=>{"use strict";L();m1=new Set(["convention"]),Dv="[unverified]"});function h1(t,e){return e?t.map(n=>{if(n.type!=="fact"||!n.category)return{...n,verification:"not-applicable"};let r=Lv(n.category,n.evidence);return{...n,verification:r,content:Nv(n.content,r)}}):t.map(n=>{let r={...n};return delete r.evidence,delete r.verification,r})}function ri(t,e,n){let r=async i=>{try{let a=y1(i),c=t.search(a.query,{category:a.category,since:a.since,limit:a.limit??10});return{content:JSON.stringify(h1(c,Zc()))}}catch(a){return{content:`memory_search error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},o=async i=>{try{let a=b1(i);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 c=t.saveHot(a.content),l={saved:!0,target:"hot",usage:{tokens:c.tokens,maxTokens:c.maxTokens,pct:c.pct}};return c.truncated?(l.truncated=!0,l.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".'):c.pct>=Iv*100&&(l.warning=`Hot memory is at ${c.pct}% of the ~1,500-token cap. Move non-essential lines to the fact archive (target:"fact") before it truncates.`),{content:JSON.stringify(l)}}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 c=a.category,l=el(a.evidence),u={id:t.storeFact({session_id:e,category:c,content:a.content,source_surface:n??"cli",evidence:l}),action:"set",target:"fact"};return Zc()&&Mm(c)&&!l&&(u.warning=Uv),{content:JSON.stringify(u)}}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 c=t.getFact(a.supersedes),l=a.evidence===void 0?void 0:el(a.evidence),u={id:t.supersedeFact(a.supersedes,a.content,a.category??void 0,l),action:"supersede",target:"fact",supersedes:a.supersedes};if(Zc()){let p=a.category??c?.category;p&&Mm(p)&&((l===void 0?c?.evidence??null:l)?l===void 0&&(u.warning=g1):u.warning=Uv)}return{content:JSON.stringify(u)}}if(a.action==="remove"){if(!a.id)return{content:'id (fact ID) is required for action: "remove"',isError:!0};let c=t.removeFact(a.id);return{content:JSON.stringify({removed:c,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}}},s=async i=>{try{let a=w1(i);return t.writeProcedure(a.name,a.content,e),{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",s]])}function y1(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.query!="string")throw new Error("query (string) is required");let n={query:e.query};if(e.category!==void 0){if(typeof e.category!="string")throw new Error("category must be a string");let r=["preference","convention","decision","learning"];if(!r.includes(e.category))throw new Error(`category must be one of: ${r.join(", ")}`);n.category=e.category}if(e.since!==void 0){if(typeof e.since!="string")throw new Error("since must be a string (ISO date)");n.since=e.since}if(e.limit!==void 0){if(typeof e.limit!="number"||e.limit<=0)throw new Error("limit must be a positive number");n.limit=e.limit}return n}function b1(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t,n=["hot","fact"];if(typeof e.target!="string"||!n.includes(e.target))throw new Error(`target must be one of: ${n.join(", ")}`);let r=["set","supersede","remove"];if(typeof e.action!="string"||!r.includes(e.action))throw new Error(`action must be one of: ${r.join(", ")}`);let o={target:e.target,action:e.action};if(e.content!==void 0){if(typeof e.content!="string")throw new Error("content must be a string");o.content=e.content}if(e.category!==void 0){if(typeof e.category!="string")throw new Error("category must be a string");let s=["preference","convention","decision","learning"];if(!s.includes(e.category))throw new Error(`category must be one of: ${s.join(", ")}`);o.category=e.category}if(e.evidence!==void 0){if(typeof e.evidence!="string")throw new Error("evidence must be a string");o.evidence=e.evidence}if(e.supersedes!==void 0){if(typeof e.supersedes!="number"||e.supersedes<=0)throw new Error("supersedes must be a positive fact ID");o.supersedes=e.supersedes}if(e.id!==void 0){if(typeof e.id!="number"||e.id<=0)throw new Error("id must be a positive fact ID");o.id=e.id}return o}function w1(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.name!="string")throw new Error("name (string) is required");if(typeof e.content!="string")throw new Error("content (string) is required");return{name:e.name,content:e.content}}var bo,Bv,jv,kn,tl,Uv,g1,Om=h(()=>{"use strict";Yc();$v();bo={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"]}},Bv={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"]}},jv={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"]}},kn=[bo,Bv,jv],tl=kn.map(t=>t.name),Uv='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.',g1='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 Nt=h(()=>{"use strict";Yc();Mv();Ov();Om()});import{existsSync as T1}from"node:fs";function Um(t){let e=t.indexOf($m);if(e===-1)return;let n=t.slice(e+$m.length),r=n.indexOf("/"),o=r===-1?n:n.slice(0,r);if(o.length!==0)return t.slice(0,e+$m.length)+o}function Gv(t){return t===void 0||T1(t)?"ok":"missing"}var $m,Bm=h(()=>{"use strict";$m="/.afk-worktrees/"});function qe(t){return t.replace(/\bauthorization:\s*bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]").replace(/\bsk-ant-[A-Za-z0-9_-]{20,}/g,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,"[REDACTED]").replace(/\b(?:AKIA|ASIA|AROA|AIDA|AGPA|AIPA|ANPA|ANVA|APKA|ABIA|ACCA)[A-Z0-9]{16}\b/g,"[REDACTED]").replace(/(?<![/.\w])[A-Za-z0-9+/=_-]{32,}(?![/.\w])/g,e=>jm(e)||_1(e)?e:"[REDACTED]")}function jm(t){if(!t.includes("/")||/[+=]/.test(t))return!1;let e=n=>n.length>=32&&!n.includes(".")&&/[A-Za-z]/.test(n)&&/[0-9]/.test(n);return!t.split("/").some(e)}function _1(t){if(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(t))return!0;let e=/^([A-Za-z_][A-Za-z0-9_]*)=(?:[0-9a-f]{40}|[0-9a-f]{64})$/.exec(t);return e!==null&&/^(?:ref|sha|commit|base)$/i.test(e[1]??"")}var vn=h(()=>{"use strict"});import{createHash as E1,randomUUID as A1}from"node:crypto";import{mkdirSync as x1,readFileSync as R1,writeFileSync as I1,renameSync as C1}from"node:fs";import{join as P1,dirname as M1}from"node:path";function L1(t){let e=E1("sha256").update(t,"utf8").digest("hex"),n=qe(t.slice(0,D1)),r=Buffer.byteLength(t,"utf8");return{sha256:e,head:n,byteLen:r}}function N1(){let t=k.AFK_WAVE_MANIFEST_TTL_HOURS;if(t!==void 0&&t!==""){let e=Number.parseFloat(t);if(Number.isFinite(e)&&e>0)return e}return O1}function ol(t){let e=t.cwd!==void 0?Um(t.cwd):void 0;return{id:t.id,status:"pending",promptDigest:L1(t.prompt),cwd:t.cwd,model:t.model,startedAt:void 0,settledAt:void 0,errorMessage:void 0,upstreamIds:t.upstreamIds??[],worktreePath:e}}function sl(t){if(k.AFK_WAVE_MANIFEST_DISABLED!=="1")try{let e=A1().replace(/-/g,""),n=new Date,r=new Date(n.getTime()+N1()*60*60*1e3),o={version:1,waveId:e,parentSessionId:t.parentSessionId,traceLabel:t.traceLabel,createdAt:n.toISOString(),updatedAt:n.toISOString(),expiresAt:r.toISOString(),source:t.source,units:t.units};return il(o),e}catch{return}}function il(t){try{let e=ho();x1(e,{recursive:!0});let n=yo(t.waveId),r=P1(M1(n),`.${t.waveId}.tmp`);I1(r,JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),C1(r,n)}catch{}}function al(t){try{let e=R1(yo(t),"utf8"),n=JSON.parse(e);return typeof n!="object"||n===null||n.version!==1?void 0:n}catch{return}}function lr(t,e,n,r){try{let o=al(t);if(o===void 0)return;let s=new Date().toISOString(),i=o.units.find(a=>a.id===e);if(i===void 0)return;i.status=n,n==="running"&&(i.startedAt=s),(n==="done"||n==="failed"||n==="skipped")&&(i.settledAt=s),r?.errorMessage!==void 0&&(i.errorMessage=r.errorMessage.slice(0,F1)),r?.cwd!==void 0&&(i.cwd=r.cwd,i.worktreePath=Um(r.cwd)),o.updatedAt=s,il(o)}catch{}}var O1,D1,F1,cl=h(()=>{"use strict";L();j();Bm();vn();O1=48,D1=512,F1=500});function te(t){return t.replace(Xv,"").replace($1," ").trim()}function ve(t){return t.replace(Xv,"")}var Xv,$1,at=h(()=>{"use strict";Xv=/\x1B\][^\x07\x1B\x9C]*(?:\x07|\x1B\\|\x9C)|\x1B[P^_X][^\x1B\x9C]*(?:\x1B\\|\x9C)|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[6-_]/g,$1=/[\x00-\x1F\x7F-\x9F]/g});import{readdirSync as zv,unlinkSync as Jv}from"node:fs";function Vv(t){let e={offers:[],deletedExpired:0};try{let n=ho(),r;try{r=zv(n)}catch{return e}let o=Date.now();for(let s of r){if(!s.endsWith(".json"))continue;let i=s.slice(0,-5);if(!/^[A-Za-z0-9]+$/.test(i))continue;let a=al(i);if(a===void 0)continue;let c=new Date(a.expiresAt).getTime();if(!Number.isFinite(c)||c<o){try{Jv(yo(i)),e.deletedExpired+=1}catch{}continue}if(a.offeredAt!==void 0)continue;let l=new Date(a.createdAt).getTime(),d=Number.isFinite(l)?l:0,u=o-d<B1,p=a.parentSessionId===t.sessionId;if(!u&&!p)continue;let f=a.units.filter(b=>U1.has(b.status));if(f.length===0)continue;let m=new Set(a.units.filter(b=>b.status==="done").map(b=>b.id)),g=[],y=[];for(let b of f){if(b.upstreamIds.length>0&&b.upstreamIds.some(_=>!m.has(_))){g.push(b);continue}let T=Gv(b.worktreePath);y.push({unit:b,worktreeStatus:T})}(y.length>0||g.length>0)&&e.offers.push({manifest:a,resumable:y,blocked:g})}}catch{}return e}function Yv(t){let{manifest:e,resumable:n,blocked:r}=t,o=new Date(e.createdAt),s=Date.now()-o.getTime(),i=j1(s),a=[`[wave-resume] Wave ${e.waveId} from ${i} ago has ${n.length+r.length} unsettled unit(s).`,` Source: ${e.source}`];if(n.length>0){a.push(" Units ready to resume:");for(let{unit:c,worktreeStatus:l}of n){let d=ve(c.promptDigest.head.slice(0,80)).replace(/\n/g," "),u=c.cwd!==void 0?` (cwd: ${ve(c.cwd)})`:"",p=l==="missing"?" \u26A0 worktree was swept \u2014 cannot re-dispatch without its working directory":"";a.push(` \xB7 ${c.id}: ${d}...${u}${p}`)}}if(r.length>0){a.push(" Units blocked on failed upstream deps:");for(let c of r)a.push(` \xB7 ${c.id} (depends on: ${c.upstreamIds.join(", ")})`)}return a.push(" To retry, re-dispatch each ready unit's prompt from its listed cwd; this notice does not accept yes/no replies."),a.join(`
123
123
  `)}function Qv(t){return t||k.AFK_WAVE_RESUME_UNATTENDED==="1"}function Zv(t){try{let e=new Date().toISOString();t.offeredAt=e,t.updatedAt=e,il(t)}catch{}}function j1(t){let e=Math.floor(t/6e4);if(e<60)return`${e}m`;let n=Math.floor(e/60);return n<24?`${n}h`:`${Math.floor(n/24)}d`}function eT(){let t=0;try{let e=ho(),n;try{n=zv(e)}catch{return{deleted:t}}let r=Date.now();for(let o of n){if(!o.endsWith(".json"))continue;let s=o.slice(0,-5);if(!/^[A-Za-z0-9]+$/.test(s))continue;let i=al(s);if(i===void 0)continue;let a=new Date(i.expiresAt).getTime();if(!(Number.isFinite(a)&&a>=r))try{Jv(yo(s)),t+=1}catch{}}}catch{}return{deleted:t}}var U1,B1,Hm=h(()=>{"use strict";cl();Bm();j();L();at();U1=new Set(["pending","running"]),B1=2880*60*1e3});function Ge(t,e=4096){if(t.length<=e)return[t];let n=[],r=t;for(;r.length>0;){if(r.length<=e){n.push(r);break}let o=e,s=r.lastIndexOf(`
124
124
  `,e-1);if(s>e-500&&s>0)o=s+1;else{let i=r.slice(0,e).match(/[.!?]\s+(?=[A-Z])/g);if(i&&i.length>0){let a=i[i.length-1];if(a){let c=r.lastIndexOf(a,e-1);c>e-200&&c>0&&(o=Math.min(c+a.length,e))}}else{let a=r.lastIndexOf(" ",e-1);a>e-100&&a>0&&(o=a+1)}}n.push(r.slice(0,o)),r=r.slice(o)}return n}function _n(t){t=t.replace(/[\x02\x03]/g,"");let e=t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),n=[];e=e.replace(/^ {0,3}```([\w]*)\n([\s\S]*?)```/gm,(o,s,i)=>{let a=n.length;if(i.trim()===""){let c=s?`(empty ${s} block)`:"(empty code block)";n.push(`<i>${c}</i>`)}else n.push(`<pre>${i}</pre>`);return`FENCED${a}`});let r=[];return e=e.replace(/`([^`]+)`/g,(o,s)=>{let i=r.length;return r.push(`<code>${s}</code>`),`CODE${i}`}),e=e.replace(/\*\*([^*]+)\*\*/g,"<b>$1</b>"),e=e.replace(/__([^_]+)__/g,"<b>$1</b>"),e=e.replace(/\*([^*]+)\*/g,"<i>$1</i>"),e=e.replace(/(^|[^\w])_([^_\n]+?)_(?!\w)/gm,"$1<i>$2</i>"),e=e.replace(/~~([^~]+)~~/g,"<s>$1</s>"),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(o,s,i)=>'<a href="'+i.replace(/"/g,"&quot;")+'">'+s+"</a>"),e=e.replace(/^#{1,6}\s+/gm,""),Z1(e)||(e=e.replace(/<\/?[bis]>/g,"")),e=e.replace(/\x02CODE(\d+)\x03/g,(o,s)=>r[Number(s)]??o),e=e.replace(/\x02FENCED(\d+)\x03/g,(o,s)=>n[Number(s)]??o),e}function Z1(t){let e=[],n=/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>/g,r;for(;(r=n.exec(t))!==null;){let o=(r[2]??"").toLowerCase();if(r[1]==="/"){if(e.pop()!==o)return!1}else e.push(o)}return e.length===0}function ge(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function gT(t){if(t.kind==="unavailable")return t.reason==="no-token"?"\u26A0\uFE0F No Claude subscription token found. Run `claude login` on the host machine, then try /usage again.":`\u26A0\uFE0F Usage unavailable (${t.reason}): ${t.detail}`;let n=[["5-hour",t.fiveHour],["7-day",t.sevenDay],["7-day (Sonnet)",t.sevenDaySonnet],["7-day (Opus)",t.sevenDayOpus]].filter(r=>r[1]!==void 0).map(([r,o])=>{let s=Math.round(o.utilization*100),i=o.resetsAt?` (resets ${o.resetsAt.toLocaleString()})`:"";return` ${r}: ${s}%${i}`});return n.length===0?"\u{1F4CA} Usage: no windows reported.":["\u{1F4CA} Claude subscription usage:",...n].join(`
125
125
  `)}function zm(t,e){return t==="ENOENT"?`\u274C Directory not found: ${e}`:t==="EACCES"?`\u274C Permission denied: ${e}`:`\u274C Unexpected error (${t}): ${e}`}function ai(t){return`\u23F3 Queued (#${t} in line)`}function X(t){return`\u274C Error: ${t instanceof Error?t.message:t}`}function fl(){return"\u26A0\uFE0F An internal error occurred. Please try again."}function hT(t){let e=["\u{1F4CB} Commands:",""," /start \u2014 Show welcome"," /help \u2014 Show this list"," /clear \u2014 Clear conversation history"," /compact \u2014 Summarize older messages"," /model \u2014 Switch Claude model"," /cd \u2014 Change working directory"," /name \u2014 Show or set the session name"," /usage \u2014 Show Claude subscription usage"," /sessions \u2014 List and switch between sessions"," /new \u2014 Start a new session (keeps the current one)"," /watch \u2014 Live-tail a CLI session from this chat"," /unwatch \u2014 Stop watching a session","","Also works from the CLI."];return t&&t.length>0&&e.push("","\u{1F4CB} Session commands (from SDK, when using settingSources):","",...t.map(n=>` /${n.replace(/^\//,"")}`)),e.push("","Just send a message to chat with Claude."),e.join(`
@@ -319,7 +319,7 @@ ${o}`,paths:[e,n]}:o!==null?s={content:o,paths:[n]}:r!==null?s={content:r,paths:
319
319
 
320
320
  ${e}`}var eJ,Mh=h(()=>{"use strict";eJ=new Set(["script","style","noscript","template","svg"])});function rJ(t,e){return new Promise((n,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(e?.reason??new Error("aborted"))},s=setTimeout(()=>{e?.removeEventListener("abort",o),n()},t);e?.addEventListener("abort",o,{once:!0})})}function bx(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function oJ(t,e){let n=t.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,e)}async function wx(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??rJ,c=n.signal??void 0,l;for(let d=0;d<=o;d++){if(c?.aborted)throw c.reason??new Error("aborted");try{let u=await t(e,n);if(!nJ.has(u.status)||d===o)return u;let p=oJ(u,i)??bx(d,s,i);F("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,c)}catch(u){if(c?.aborted||(l=u,d===o))throw u;let p=bx(d,s,i);F("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,c)}}throw l??new Error("retryFetch: exhausted without a result")}var nJ,Sx=h(()=>{"use strict";ie();nJ=new Set([429,502,503,504])});import{BlockList as sJ,isIP as Dh}from"node:net";import{lookup as iJ}from"node:dns/promises";import{Agent as aJ}from"undici";function vx(){let t=k.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return t==="1"||t==="true"}function uJ(t){return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Oh(t){let e=Dh(t);return e===0?!1:dJ.check(t,e===4?"ipv4":"ipv6")}async function Tx(t){return iJ(t,{all:!0,verbatim:!0})}async function Or(t,e={}){if(e.allowPrivateHosts??vx())return{allowed:!0};let n;try{n=new URL(t)}catch{return{allowed:!1,reason:`"${t}" 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=uJ(n.hostname),o=(a,c)=>`refusing to fetch ${c} \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(Dh(r)!==0)return Oh(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let s=e.lookupFn??Tx,i;try{i=await s(r)}catch{return{allowed:!0}}for(let a of i)if(Oh(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function Ji(t,e={}){let n=await Or(t,e);if(!n.allowed)throw new Ce(n.reason)}async function Dn(t,e,n={},r={}){let o={...r.lookupFn!==void 0?{lookupFn:r.lookupFn}:{},...r.allowPrivateHosts!==void 0?{allowPrivateHosts:r.allowPrivateHosts}:{}},s=e;for(let i=0;i<=kx;i++){await Ji(s,o);let a={...n,redirect:"manual",...t===globalThis.fetch&&!(r.allowPrivateHosts??vx())?{dispatcher:pJ}:{}},c=await wx(t,s,a,r.retry??{});if(!fJ.has(c.status))return c;let l=c.headers.get("location");if(l===null||l.trim()==="")return c;let d;try{d=new URL(l,c.url||s).toString()}catch{return c}await c.body?.cancel().catch(()=>{}),s=d}throw new Ce(`too many redirects (>${kx}) starting from ${e}`)}var cJ,lJ,dJ,Ce,pJ,kx,fJ,Dr=h(()=>{"use strict";L();Sx();cJ=[["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]],lJ=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],dJ=(()=>{let t=new sJ;for(let[e,n]of cJ)t.addSubnet(e,n,"ipv4");for(let[e,n]of lJ)t.addSubnet(e,n,"ipv6");return t})(),Ce=class extends Error{constructor(e){super(e),this.name="EgressBlockedError"}};pJ=new aJ({connect:{lookup(t,e,n){Tx(t).then(r=>{let o=r.find(i=>Oh(i.address));if(o!==void 0){n(new Ce(`refusing to connect to ${t} (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 s=r[0];if(s===void 0){n(new Error(`DNS lookup returned no addresses for ${t}`),"",0);return}n(null,s.address,Dh(s.address))},r=>n(r,"",0))}}});kx=20,fJ=new Set([301,302,303,307,308])});var Lh={};uo(Lh,{enforceDomainPolicy:()=>It,loadBrowserConfig:()=>Fh});import{readFileSync as mJ}from"node:fs";import{join as gJ}from"path";function hJ(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function _x(t,e){return hJ(e).test(t)}function wJ(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(yJ.has(e))return!0;if(bJ.has(e))return!1}return!1}function Ex(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function SJ(t){if(t===void 0||t==="")return"auto";if(t==="playwright"||t==="agent-browser"||t==="auto")return t;throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${t}`)}function Ax(t){let e=t===void 0||t.trim()===""?"default":t.trim();return xm(e),e}function kJ(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function vJ(t){try{return mJ(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function TJ(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright"||e.backend==="agent-browser"||e.backend==="auto")n.backend=e.backend;else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=Ax(e.defaultProfile)),n}function Fh(t){let e=t?.env??k,n=t?.readFileSync??vJ,r=t?.surface??e.AGENT_SURFACE,o=wJ(e.AFK_BROWSER_HEADLESS,r),s=Ex(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Ex(e.AFK_BROWSER_BLOCKED_DOMAINS),a=kJ(e.AFK_BROWSER_DOM_SNAPSHOTS),c=SJ(e.AFK_BROWSER_BACKEND),l=Ax(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():gJ(rn(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${p}: ${String(y)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=TJ(d,m);return g.configPath=p,g}function It(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(_x(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>_x(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var yJ,bJ,Fn=h(()=>{"use strict";L();j();yJ=new Set(["daemon","subagent","telegram","afk"]),bJ=new Set(["repl","interactive","cli"])});import{readFileSync as _J}from"node:fs";import{join as EJ}from"node:path";import{homedir as AJ}from"node:os";function RJ(t){let e=t??xJ,n;try{n=_J(e,"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 s;try{s=new URL(o.url)}catch{return null}let{hostname:i,protocol:a}=s;if(!(i==="127.0.0.1"||i==="localhost"||i==="::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 IJ(t){try{return process.kill(t,0),!0}catch{return!1}}async function CJ(t,e,n=2e3){try{let r=new AbortController,o=setTimeout(()=>r.abort(),n),s=await fetch(`${t}/health`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Host:"127.0.0.1:8833"},signal:r.signal});return clearTimeout(o),s.ok}catch{return!1}}async function Nh(t){let e=RJ(t);return e===null?{available:!1,connection:null,reason:"connection file missing or invalid"}:IJ(e.pid)?await CJ(e.url,e.token)?{available:!0,connection:e,reason:null}:{available:!1,connection:e,reason:`health probe failed at ${e.url}`}:{available:!1,connection:e,reason:`stale connection file: PID ${e.pid} not alive`}}var xJ,xx=h(()=>{"use strict";xJ=EJ(AJ(),".config","agent-browser","connection.json")});async function Rx(t){let{config:e,surface:n}=t;if(e.backend==="playwright")return{backend:"playwright",reason:"explicit config: backend=playwright",probeMs:0,availability:null};if(e.backend==="agent-browser"){let i=Date.now(),a=await Nh(),c=Date.now()-i;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:c,availability:a}}if(n&&PJ.has(n))return{backend:"playwright",reason:`auto: surface "${n}" excluded from Agent Browser`,probeMs:0,availability:null};if(e.headless)return{backend:"playwright",reason:"auto: headless mode requires Playwright",probeMs:0,availability:null};let r=Date.now(),o=await Nh(),s=Date.now()-r;return o.available?{backend:"agent-browser",reason:"auto: Agent Browser available and preferred",probeMs:s,availability:o}:{backend:"playwright",reason:`auto: Agent Browser unavailable (${o.reason})`,probeMs:s,availability:o}}var PJ,Ix=h(()=>{"use strict";xx();PJ=new Set(["daemon","subagent"])});import{createHash as MJ}from"crypto";function Cx(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&OJ.test(t.label))}function Px(t){return MJ("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Mx(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var OJ,_d=h(()=>{"use strict";OJ=/password|secret|token|api[_-]?key|otp|2fa/i});import{randomBytes as DJ}from"crypto";import{mkdir as FJ,stat as LJ,writeFile as NJ}from"fs/promises";import{join as $h}from"path";import{gzip as $J}from"zlib";import{promisify as UJ}from"util";function BJ(t){return $h(st(t),"browser")}function jJ(t){return $h(BJ(t),"screenshots")}function HJ(){return new Date().toISOString().replace(/[:.]/g,"-")}function WJ(){return DJ(3).toString("hex")}async function Ko(t,e,n){if(e.length>Ox)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Ox} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=jJ(t);await FJ(r,{recursive:!0});let o=`${HJ()}-${WJ()}-${n}.png`,s=$h(r,o);await NJ(s,e);let{size:i}=await LJ(s);return{path:s,bytes:i}}var aye,Ox,Uh=h(()=>{"use strict";j();_d();aye=UJ($J);Ox=5*1024*1024});var Ed,Dx=h(()=>{"use strict";Ed=class{baseUrl;token;constructor(e){this.baseUrl=e.url,this.token=e.token}async call(e,n,r=3e4){let o={version:1,method:e,params:n},s=new AbortController,i=setTimeout(()=>s.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:s.signal});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Agent Browser ${e} failed (HTTP ${a.status}): ${c}`)}return await a.json()}finally{clearTimeout(i)}}async listTabs(){return(await this.call("tabs.list",null)).tabs}async openTab(e){return{tabId:(await this.call("tabs.open",{url:e},6e4)).tab_id}}async closeTab(e){await this.call("tabs.close",{tab_id:e})}async read(e,n){return this.call("page.read",{tab_id:e,mode:n?.mode??"main",...n?.query?{query:n.query}:{},...n?.budget?{budget:n.budget}:{}})}async inspect(e,n){return this.call("page.inspect",{tab_id:e,mode:n?.mode??"interactive",...n?.query?{query:n.query}:{},...n?.limit?{limit:n.limit}:{}})}async click(e,n){await this.call("page.click",{tab_id:e,element_id:n})}async fill(e,n,r){await this.call("page.fill",{tab_id:e,element_id:n,value:r})}async press(e,n,r){await this.call("page.press",{tab_id:e,key:n,...r?{element_id:r}:{}})}async select(e,n,r){await this.call("page.select",{tab_id:e,element_id:n,value:r})}async waitFor(e,n,r){await this.call("page.wait",{tab_id:e,condition:n,...r?.value?{value:r.value}:{},...r?.timeout?{timeout:r.timeout}:{}},(r?.timeout??3e4)+5e3)}async evalScript(e,n){return this.call("page.eval",{tab_id:e,script:n})}async screenshot(e){return this.call("page.screenshot",{tab_id:e})}}});function Bh(t){return{id:t.id,role:t.role,label:t.label,kind:t.kind,value:t.value,state:{disabled:t.disabled,...t.checked!==void 0?{checked:t.checked}:{},...t.selected!==void 0?{selected:t.selected}:{},...t.expanded!==void 0?{expanded:t.expanded}:{}},bbox:t.bbox,...t.selector?{selector:t.selector}:{}}}function Fx(t,e){switch(e.kind){case"element_id":if(t.has(e.elementId))return e.elementId;throw new Error(`Element ${e.elementId} not found in current observation. Call browser_observe to refresh.`);case"selector":return null;case"semantic":return null}}async function jh(t,e,n,r,o,s){switch(n){case"click":await t.click(e,r);break;case"fill":if(o===void 0)throw new Error("fill requires a value");await t.fill(e,r,o);break;case"press":if(o===void 0)throw new Error("press requires a value (key combo)");await t.press(e,o,r);break;case"select":if(o===void 0)throw new Error("select requires a value");await t.select(e,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 i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');await t.evalScript(e,`document.querySelector('[data-element-id="${i}"]')?.scrollIntoView({behavior:'smooth',block:'center'})`);break}case"wait_for":await t.waitFor(e,"element",{value:r,timeout:s??1e4});break;default:throw new Error(`Unknown action: ${n}`)}}async function Lx(t,e){if(e.target.kind!=="semantic")throw new Error("resolveSemanticAndAct called with non-semantic target");let{elements:n}=await t.client.inspect(t.tabId,{mode:"interactive",query:e.target.text,limit:10}),r=n;if(e.target.role){let c=e.target.role.toLowerCase();r=n.filter(l=>l.role.toLowerCase()===c)}if(r.length===0)throw new Error(`No element found matching semantic target: text="${e.target.text}"`+(e.target.role?`, role="${e.target.role}"`:""));if(r.length>1)return{outcome:"ambiguous_target",query:{text:e.target.text,...e.target.role?{role:e.target.role}:{}},candidates:r.slice(0,5).map(Bh)};let s=r[0].id;await jh(t.client,t.tabId,e.action,s,e.value,e.timeoutMs);let i=await t.client.read(t.tabId,{mode:"main"}),a=It(i.url,t.config);return a.allowed?{elementId:s}:{outcome:"blocked_by_policy",url:i.url,reason:`action navigated to blocked domain: ${a.reason}`}}var Nx=h(()=>{"use strict";Fn()});var $x={};uo($x,{AgentBrowserProvider:()=>Hh});var Hh,Ux=h(()=>{"use strict";Fn();Uh();Dx();Nx();Hh=class{name="agent-browser";config;client;sessions=new Map;constructor(e,n){this.config=e,this.client=new Ed(n)}async open(e){let n=It(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let r=this.sessions.get(e.sessionId);if(r)await this.client.evalScript(r.tabId,`window.location.href = ${JSON.stringify(e.url)}`),await this.client.waitFor(r.tabId,"load",{timeout:e.timeoutMs??3e4});else{let{tabId:i}=await this.client.openTab(e.url);await this.client.waitFor(i,"load",{timeout:e.timeoutMs??3e4}),r={tabId:i,observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null},this.sessions.set(e.sessionId,r)}let o=await this.client.read(r.tabId,{mode:"main"}),s=It(o.url,this.config);return s.allowed?this.buildObservation(r,e.sessionId,e.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: ${s.reason}`})}async observe(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);return this.buildObservation(n,e.sessionId,e.screenshot,e.maxElements,"browser_observe")}async act(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);let r=Fx(n.knownElements,e.target);if(r===null){if(e.target.kind==="semantic"){let i=await Lx({client:this.client,config:this.config,tabId:n.tabId},e);return"outcome"in i?i:(n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString(),this.buildObservation(n,e.sessionId,e.screenshot,void 0,"browser_act"))}throw e.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(e.target)}`)}await jh(this.client,n.tabId,e.action,r,e.value,e.timeoutMs),n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString();let o=await this.client.read(n.tabId,{mode:"main"}),s=It(o.url,this.config);return s.allowed?this.buildObservation(n,e.sessionId,e.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: ${s.reason}`})}async render(e){throw new Error("AgentBrowserProvider does not support render(). Use PlaywrightProvider for one-shot content fetches.")}async screenshot(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);if(e.target!==void 0||e.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"),s=o.length>=24?o.readUInt32BE(16):0,i=o.length>=24?o.readUInt32BE(20):0;return{path:(await Ko(e.sessionId,o,"browser_screenshot")).path,bytes:o.length,width:s,height:i,dataBase64:r.data,mediaType:"image/png"}}async extract(e){throw new Error("AgentBrowserProvider does not support extract() yet.")}async close(e){let n=this.sessions.get(e.sessionId);if(n){try{await this.client.closeTab(n.tabId)}catch{}this.sessions.delete(e.sessionId)}}describe(e){let n=this.sessions.get(e);return n?{active:!0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:1}:null}async shutdown(){let e=Array.from(this.sessions.entries()).map(async([,n])=>{try{await this.client.closeTab(n.tabId)}catch{}});await Promise.all(e),this.sessions.clear()}async buildObservation(e,n,r,o,s="browser_open"){let[i,a]=await Promise.all([this.client.read(e.tabId,{mode:"main",budget:4e3}),this.client.inspect(e.tabId,{mode:"interactive",limit:o??80})]),c=a.elements.map(Bh),l=o??80,d=c.slice(0,l);e.observationCounter+=1,e.knownElements=new Map(d.map(g=>[g.id,g])),e.currentUrl=i.url,e.currentTitle=i.title;let u=[];c.length>l&&u.push(`page has ${c.length} interactive elements; showing first ${l}`);let p=null;if(r)try{let g=await this.client.screenshot(e.tabId),y=Buffer.from(g.data,"base64");p=(await Ko(n,y,s)).path}catch{u.push("screenshot capture failed")}let f=`obs_${e.observationCounter.toString(36)}`,m={httpStatus:null,loadingState:"idle",hasDialog:!1,consoleErrors:0};return{observationId:f,url:i.url,title:i.title,textSummary:i.content.slice(0,4e3),interactive:d,status:m,warnings:u,screenshotPath:p,capturedAt:new Date().toISOString()}}}});import{existsSync as KJ,readFileSync as qJ}from"node:fs";import{createRequire as GJ}from"node:module";import{dirname as XJ,join as zJ}from"node:path";function Hx(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<VJ&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function ze(t){let e=Hx(t);return jx.some(n=>e.includes(n))}function YJ(){try{let e=GJ(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(qJ(e,"utf8"));if(typeof n!="object"||n===null)return;let r=n.bin,o=typeof r=="string"?r:typeof r=="object"&&r!==null?r.playwright:void 0;if(typeof o!="string"||o.length===0)return;let s=zJ(XJ(e),o);return KJ(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function Vi(){return Bx??=YJ()??JJ,Bx}function Wh(t){return t.includes("install chromium")}function gt(t,e){let n=Hx(t),r=e?.latched===!0?` ${QJ}`:"";if(n.includes("Executable doesn't exist")){let o="";return e?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":e?.headless===!1&&(o=" This launch was headed, which needs the full `chromium-*` build \u2014 the headless shell alone does not satisfy it."),`browser tools require the Playwright chromium binary. Install via: ${Vi()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${Vi()}). Or pick a different tool.${r}`}function Ad(t,e,n=!1){if(!ze(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
321
321
 
322
- ${gt(t,{headless:e,latched:n})}`,{cause:t})}var jx,JJ,VJ,Bx,QJ,Kh=h(()=>{"use strict";jx=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],JJ="pnpm exec playwright install chromium",VJ=4;QJ="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 Fr from"node:fs";import xd from"node:path";import{randomBytes as ZJ}from"node:crypto";function eV(){try{return"5.196.0"}catch{}try{let t=xd.resolve(import.meta.dirname,"../../../package.json"),e=Fr.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var tV,Rd,Wx=h(()=>{"use strict";Kh();j();ie();tV=eV(),Rd=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=(async()=>{let e;try{({chromium:e}=await import("playwright"))}catch(n){let r=Ad(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await e.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=Ad(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(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${tV}`}}loadStorageState(e){let n=Rm(e);try{if(!Fr.existsSync(n))return;let r=JSON.parse(Fr.readFileSync(n,"utf8"));return F("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){F("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Rm(e);if(!Fr.existsSync(r))return;let o=await n.storageState(),s=xd.join(xd.dirname(r),`.${xd.basename(r)}.${process.pid}.${ZJ(4).toString("hex")}.tmp`);Fr.writeFileSync(s,JSON.stringify(o),{mode:384}),Fr.chmodSync(s,384),Fr.renameSync(s,r),F("[browser/vault] saved session",{profile:e,file:r})}catch(r){F("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as nV}from"node:crypto";function rV(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function oV(t,e,n){return`el_${nV("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function sV(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Kx(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Gx(t,e){let n=t.role??"",r=t.name??"";qx.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Gx(s,e)}async function iV(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},Xx).catch(()=>[])}async function aV(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},Xx).catch(()=>[])}function cV(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Id(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=cV(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=iV(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],Gx(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await aV(t)).filter(P=>qx.has(P.role??"")));let S=new Map;for(let R of p){let P=Kx(R.name),W=S.get(P);(!W||W.bbox.w===0&&R.bbox.w>0)&&S.set(P,R)}let T=y.map(R=>({ax:R,dom:S.get(Kx(R.name??""))})),_=r?T:T.filter(R=>R.dom?R.dom.bbox.w>0||R.dom.bbox.h>0:!0);_.sort((R,P)=>{let W=R.dom?.bbox.y??0,M=P.dom?.bbox.y??0;if(W!==M)return W-M;let $=R.dom?.bbox.x??0,D=P.dom?.bbox.x??0;return $-D}),_.length>200&&o.push("page has 200+ interactive elements; consider scoping");let x=_.slice(0,n).map((R,P)=>{let W=R.ax.role??"generic",M=R.ax.name??"",$=oV(W,M,P),D=R.dom?.bbox??{x:0,y:0,w:0,h:0},N=R.dom?.type??null,B=null;R.ax.value!==void 0&&R.ax.value!==null&&(B=String(R.ax.value)),R.ax.checked!==void 0&&(B=String(R.ax.checked)),Cx({role:W,kind:N})&&(B="[redacted]");let K={disabled:R.ax.disabled??!1};R.ax.checked!==void 0&&(K.checked=R.ax.checked===!0||R.ax.checked==="mixed"),R.ax.selected!==void 0&&(K.selected=R.ax.selected),R.ax.expanded!==void 0&&(K.expanded=R.ax.expanded);let Y;R.dom?.testId?Y=`[data-testid="${R.dom.testId}"]`:R.dom?.id&&(Y=`#${R.dom.id}`);let Ft={id:$,role:W,label:rV(M),kind:N,value:B,state:K,bbox:D};return Y!==void 0&&(Ft.selector=Y),Ft}),I="idle";try{let R=await t.evaluate(()=>document.readyState);R==="loading"?I="loading":R==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let C=sV(f),v=`obs_${e.observationCounter.toString(36)}`,E=new Date().toISOString();return{observationId:v,url:m,title:g,textSummary:C,interactive:x,status:{httpStatus:e.httpStatus??null,loadingState:I,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:E}}var qx,Xx,zx=h(()=>{"use strict";_d();qx=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Xx="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Jx(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function qh(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Jx(t,s)))).filter(o=>o!==null)}async function lV(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Gh(t,e,n){switch(e.kind){case"element_id":return dV(t,e,n);case"selector":return uV(t,e);case"semantic":return pV(t,e)}}async function dV(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await qh(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function uV(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await qh(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function pV(t,e){return e.role!==void 0?fV(t,e.text,e.role):mV(t,e.text,e)}async function fV(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await qh(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function mV(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await lV(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let y=p[g];if(y===void 0)continue;let b=await Jx(y.locator,y.index);if(b!==null){let S=`${b.role}:${b.label}:${g}`,T=0;for(let _=0;_<S.length;_++)T=T*31+S.charCodeAt(_)>>>0;f.push({...b,id:`el_${T.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Vx=h(()=>{"use strict"});async function Xh(t,e,n,r){let o=t.url();if(o===n)return null;let s=It(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var Yx=h(()=>{"use strict";Fn()});var Jh={};uo(Jh,{PlaywrightProvider:()=>zh});function Qx(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var zh,Vh=h(()=>{"use strict";Wx();zx();Vx();Fn();Yx();Uh();zh=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Rd(e)}async open(e){let n=It(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await Xh(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await Id(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Id(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await Gh(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Qx(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(y){l=y}else l=g}let u=await Xh(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Id(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Gh(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Qx(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await Ko(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Ko(n,o,r);return s}catch{return null}}}});var Nr={};uo(Nr,{__resetBrowserRegistryForTests:()=>SV,browserProviderActive:()=>yV,closeBrowserProvider:()=>Qh,getBrowserProvider:()=>hV,getLastRoutingDecision:()=>wV,peekBrowserProvider:()=>bV});function Zx(){Promise.resolve(Qh()).then(()=>{process.exit(130)})}function eR(){Promise.resolve(Qh()).then(()=>{process.exit(143)})}function tR(){Xt=null}function gV(){Cd||(process.on("SIGINT",Zx),process.on("SIGTERM",eR),process.on("exit",tR),Cd=!0)}function nR(){Cd&&(process.removeListener("SIGINT",Zx),process.removeListener("SIGTERM",eR),process.removeListener("exit",tR),Cd=!1)}async function hV(t){return Xt!==null?Xt:(Lr!==null||(Lr=(async()=>{let e=Fh(t),n=t?.surface??(t?.env??{}).AGENT_SURFACE??k.AGENT_SURFACE,r=await Rx({config:e,surface:n});Yh=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:s}=await Promise.resolve().then(()=>(Ux(),$x)),i=r.availability.connection;o=new s(e,i)}else{let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(Vh(),Jh));o=new s(e)}return gV(),Xt=o,Lr=null,o})()),Lr)}async function Qh(){if(Xt===null)return;let t=Xt;Xt=null,Lr=null,nR(),await t.shutdown()}function yV(){return Xt!==null}function bV(){return Xt}function wV(){return Yh}function SV(){Xt=null,Lr=null,Yh=null,nR()}var Xt,Lr,Cd,Yh,$r=h(()=>{"use strict";Fn();Ix();L();Xt=null,Lr=null,Cd=!1,Yh=null});async function rR(t,e){try{return await gx(t,e)}catch(n){return F("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function AV(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>($r(),Nr)),r=await n();try{return await r.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}catch(o){if(r.name==="agent-browser"){let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(Vh(),Jh)),{loadBrowserConfig:i}=await Promise.resolve().then(()=>(Fn(),Lh)),a=i(),c=new s(a);try{return await c.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}finally{await c.shutdown()}}throw o}}async function oR(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??AV,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,c=null,l=null;try{let u=await Dn(n,t,{headers:EV,signal:e.signal},o);c=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(_V.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await u.text();if(TV.test(p)&&!vV.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await rR(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof Ce||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;l=u}if(!(s===null||s.textLength<200)&&s!==null){let u=Ph({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await Ji(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>Ji(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await Ji(u.finalUrl,o);let p=await rR(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=Ph({html:u.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:u.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(u){if(e.signal.aborted||u instanceof Ce)throw u;if(s===null){let p=u instanceof Error?u.message:String(u),f=l instanceof Error?l.message:`HTTP ${c??"error"}`,m=new Error(`web_scrape could not retrieve ${t}: fetch failed (${f}) and render failed (${p}).`);throw m.cause=u,m}}if(s!==null)return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${c??"error"}).`)}var vV,TV,_V,EV,sR=h(()=>{"use strict";hx();Mh();Dr();ie();vV=/(text\/html|application\/xhtml\+xml)/i,TV=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,_V=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,EV={"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 IV(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(xV,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),RV),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=te(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function iR(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?IV({apiKey:t.exaApiKey,fetchFn:t.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 aR(t,e){if(e.length===0)return`# Search results for "${t}"
322
+ ${gt(t,{headless:e,latched:n})}`,{cause:t})}var jx,JJ,VJ,Bx,QJ,Kh=h(()=>{"use strict";jx=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],JJ="pnpm exec playwright install chromium",VJ=4;QJ="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 Fr from"node:fs";import xd from"node:path";import{randomBytes as ZJ}from"node:crypto";function eV(){try{return"5.197.0"}catch{}try{let t=xd.resolve(import.meta.dirname,"../../../package.json"),e=Fr.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var tV,Rd,Wx=h(()=>{"use strict";Kh();j();ie();tV=eV(),Rd=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=(async()=>{let e;try{({chromium:e}=await import("playwright"))}catch(n){let r=Ad(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await e.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=Ad(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(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${tV}`}}loadStorageState(e){let n=Rm(e);try{if(!Fr.existsSync(n))return;let r=JSON.parse(Fr.readFileSync(n,"utf8"));return F("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){F("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Rm(e);if(!Fr.existsSync(r))return;let o=await n.storageState(),s=xd.join(xd.dirname(r),`.${xd.basename(r)}.${process.pid}.${ZJ(4).toString("hex")}.tmp`);Fr.writeFileSync(s,JSON.stringify(o),{mode:384}),Fr.chmodSync(s,384),Fr.renameSync(s,r),F("[browser/vault] saved session",{profile:e,file:r})}catch(r){F("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as nV}from"node:crypto";function rV(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function oV(t,e,n){return`el_${nV("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function sV(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Kx(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Gx(t,e){let n=t.role??"",r=t.name??"";qx.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Gx(s,e)}async function iV(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},Xx).catch(()=>[])}async function aV(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},Xx).catch(()=>[])}function cV(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Id(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=cV(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=iV(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],Gx(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await aV(t)).filter(P=>qx.has(P.role??"")));let S=new Map;for(let R of p){let P=Kx(R.name),W=S.get(P);(!W||W.bbox.w===0&&R.bbox.w>0)&&S.set(P,R)}let T=y.map(R=>({ax:R,dom:S.get(Kx(R.name??""))})),_=r?T:T.filter(R=>R.dom?R.dom.bbox.w>0||R.dom.bbox.h>0:!0);_.sort((R,P)=>{let W=R.dom?.bbox.y??0,M=P.dom?.bbox.y??0;if(W!==M)return W-M;let $=R.dom?.bbox.x??0,D=P.dom?.bbox.x??0;return $-D}),_.length>200&&o.push("page has 200+ interactive elements; consider scoping");let x=_.slice(0,n).map((R,P)=>{let W=R.ax.role??"generic",M=R.ax.name??"",$=oV(W,M,P),D=R.dom?.bbox??{x:0,y:0,w:0,h:0},N=R.dom?.type??null,B=null;R.ax.value!==void 0&&R.ax.value!==null&&(B=String(R.ax.value)),R.ax.checked!==void 0&&(B=String(R.ax.checked)),Cx({role:W,kind:N})&&(B="[redacted]");let K={disabled:R.ax.disabled??!1};R.ax.checked!==void 0&&(K.checked=R.ax.checked===!0||R.ax.checked==="mixed"),R.ax.selected!==void 0&&(K.selected=R.ax.selected),R.ax.expanded!==void 0&&(K.expanded=R.ax.expanded);let Y;R.dom?.testId?Y=`[data-testid="${R.dom.testId}"]`:R.dom?.id&&(Y=`#${R.dom.id}`);let Ft={id:$,role:W,label:rV(M),kind:N,value:B,state:K,bbox:D};return Y!==void 0&&(Ft.selector=Y),Ft}),I="idle";try{let R=await t.evaluate(()=>document.readyState);R==="loading"?I="loading":R==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let C=sV(f),v=`obs_${e.observationCounter.toString(36)}`,E=new Date().toISOString();return{observationId:v,url:m,title:g,textSummary:C,interactive:x,status:{httpStatus:e.httpStatus??null,loadingState:I,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:E}}var qx,Xx,zx=h(()=>{"use strict";_d();qx=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Xx="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Jx(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function qh(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Jx(t,s)))).filter(o=>o!==null)}async function lV(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Gh(t,e,n){switch(e.kind){case"element_id":return dV(t,e,n);case"selector":return uV(t,e);case"semantic":return pV(t,e)}}async function dV(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await qh(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function uV(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await qh(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function pV(t,e){return e.role!==void 0?fV(t,e.text,e.role):mV(t,e.text,e)}async function fV(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await qh(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function mV(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await lV(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let y=p[g];if(y===void 0)continue;let b=await Jx(y.locator,y.index);if(b!==null){let S=`${b.role}:${b.label}:${g}`,T=0;for(let _=0;_<S.length;_++)T=T*31+S.charCodeAt(_)>>>0;f.push({...b,id:`el_${T.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Vx=h(()=>{"use strict"});async function Xh(t,e,n,r){let o=t.url();if(o===n)return null;let s=It(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var Yx=h(()=>{"use strict";Fn()});var Jh={};uo(Jh,{PlaywrightProvider:()=>zh});function Qx(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var zh,Vh=h(()=>{"use strict";Wx();zx();Vx();Fn();Yx();Uh();zh=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Rd(e)}async open(e){let n=It(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await Xh(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await Id(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Id(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await Gh(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Qx(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(y){l=y}else l=g}let u=await Xh(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Id(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Gh(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Qx(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await Ko(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Ko(n,o,r);return s}catch{return null}}}});var Nr={};uo(Nr,{__resetBrowserRegistryForTests:()=>SV,browserProviderActive:()=>yV,closeBrowserProvider:()=>Qh,getBrowserProvider:()=>hV,getLastRoutingDecision:()=>wV,peekBrowserProvider:()=>bV});function Zx(){Promise.resolve(Qh()).then(()=>{process.exit(130)})}function eR(){Promise.resolve(Qh()).then(()=>{process.exit(143)})}function tR(){Xt=null}function gV(){Cd||(process.on("SIGINT",Zx),process.on("SIGTERM",eR),process.on("exit",tR),Cd=!0)}function nR(){Cd&&(process.removeListener("SIGINT",Zx),process.removeListener("SIGTERM",eR),process.removeListener("exit",tR),Cd=!1)}async function hV(t){return Xt!==null?Xt:(Lr!==null||(Lr=(async()=>{let e=Fh(t),n=t?.surface??(t?.env??{}).AGENT_SURFACE??k.AGENT_SURFACE,r=await Rx({config:e,surface:n});Yh=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:s}=await Promise.resolve().then(()=>(Ux(),$x)),i=r.availability.connection;o=new s(e,i)}else{let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(Vh(),Jh));o=new s(e)}return gV(),Xt=o,Lr=null,o})()),Lr)}async function Qh(){if(Xt===null)return;let t=Xt;Xt=null,Lr=null,nR(),await t.shutdown()}function yV(){return Xt!==null}function bV(){return Xt}function wV(){return Yh}function SV(){Xt=null,Lr=null,Yh=null,nR()}var Xt,Lr,Cd,Yh,$r=h(()=>{"use strict";Fn();Ix();L();Xt=null,Lr=null,Cd=!1,Yh=null});async function rR(t,e){try{return await gx(t,e)}catch(n){return F("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function AV(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>($r(),Nr)),r=await n();try{return await r.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}catch(o){if(r.name==="agent-browser"){let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(Vh(),Jh)),{loadBrowserConfig:i}=await Promise.resolve().then(()=>(Fn(),Lh)),a=i(),c=new s(a);try{return await c.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}finally{await c.shutdown()}}throw o}}async function oR(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??AV,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,c=null,l=null;try{let u=await Dn(n,t,{headers:EV,signal:e.signal},o);c=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(_V.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await u.text();if(TV.test(p)&&!vV.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await rR(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof Ce||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;l=u}if(!(s===null||s.textLength<200)&&s!==null){let u=Ph({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await Ji(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>Ji(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await Ji(u.finalUrl,o);let p=await rR(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=Ph({html:u.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:u.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(u){if(e.signal.aborted||u instanceof Ce)throw u;if(s===null){let p=u instanceof Error?u.message:String(u),f=l instanceof Error?l.message:`HTTP ${c??"error"}`,m=new Error(`web_scrape could not retrieve ${t}: fetch failed (${f}) and render failed (${p}).`);throw m.cause=u,m}}if(s!==null)return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${c??"error"}).`)}var vV,TV,_V,EV,sR=h(()=>{"use strict";hx();Mh();Dr();ie();vV=/(text\/html|application\/xhtml\+xml)/i,TV=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,_V=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,EV={"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 IV(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(xV,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),RV),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=te(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function iR(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?IV({apiKey:t.exaApiKey,fetchFn:t.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 aR(t,e){if(e.length===0)return`# Search results for "${t}"
323
323
 
324
324
  (no results)`;let n=[`# Search results for "${t}"`,""];return e.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(`
325
325
  `).trimEnd()}var xV,RV,cR=h(()=>{"use strict";at();xV="https://api.exa.ai/search",RV=10});function Pd(t){if(t instanceof Error&&t.name==="TimeoutError")return"timeout";let e=t instanceof Error?t.message:String(t);return/Timeout\s+\d+\s*ms exceeded/i.test(e)?"timeout":void 0}var Ur=h(()=>{"use strict";Kh()});function FV(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t,n=e.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,s;if(r==="search"){if(typeof e.query!="string"||e.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=e.query}else{if(typeof e.url!="string"||e.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let c;try{c=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(c.protocol!=="http:"&&c.protocol!=="https:")return{error:`Invalid input: protocol "${c.protocol}" not supported (http/https only)`};o=c.toString()}let i=CV;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(e.timeout_ms,PV)}let a=MV;if(e.max_bytes!==void 0){if(typeof e.max_bytes!="number"||!Number.isFinite(e.max_bytes)||e.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(e.max_bytes,OV)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Zh(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:Et(t,e),truncated:!0}}function LV(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env,r=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{};return async(o,s)=>{if(typeof e!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let i=FV(o);if("error"in i)return{content:i.error,isError:!0};if(s.aborted){let u=s.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let a=new AbortController,c=()=>{a.abort(s.reason)},l,d=()=>{let u=a.signal.reason;return u instanceof Error?u.message:String(u??"aborted")};try{if(s.addEventListener("abort",c,{once:!0}),l=setTimeout(()=>{a.abort(new Error(`web_scrape timeout after ${i.timeoutMs}ms`))},i.timeoutMs),i.url!==void 0){let p=await Or(i.url,r);if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(!p.allowed)return{content:`web_scrape blocked: ${p.reason}`,isError:!0}}if(i.mode==="raw"){let p;try{let g={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};p=await Dn(e,i.url,g,r)}catch(g){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:g instanceof Ce?{content:`web_scrape blocked: ${g.message}`,isError:!0}:{content:`web_scrape network error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}if(!p.ok)return{content:`web_scrape HTTP ${p.status} ${p.statusText||""}`.trimEnd()+` for ${i.url}`,isError:!0};let f;try{f=await p.text()}catch(g){return{content:`web_scrape read error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}let m=Zh(f,i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}if(i.mode==="markdown")try{let p=await oR(i.url,{fetchFn:e,renderFn:t.renderFn,timeoutMs:i.timeoutMs,signal:a.signal,...t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{}});if(p.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${i.url}.`,isError:!0};let f=Zh(yx(p.markdown,p.advisory),i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(p instanceof Ce)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),m=ze(p)&&!Wh(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${Vi()}\`)`:"";return{content:`web_scrape markdown error: ${f}${m}`,isError:!0}}let u=iR({exaApiKey:n.EXA_API_KEY,fetchFn:e});if("error"in u)return{content:u.error,isError:!0};try{let p=await u.search(i.query,{limit:DV,timeoutMs:i.timeoutMs,signal:a.signal}),f=Zh(aR(i.query,p),i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:{content:`web_scrape search error (${u.name}): ${p instanceof Error?p.message:String(p)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),s.removeEventListener("abort",c)}}}var CV,PV,MV,OV,DV,lR,dR=h(()=>{"use strict";sR();cR();Dr();Ht();Mh();Ur();CV=3e4,PV=12e4,MV=1e5,OV=1e6,DV=10;lR=LV()});function UV(t){return NV.has(t)?"low":t==="DELETE"?"high":"medium"}function BV(t){return $V.has(t)}function WV(t){let e={};return t.forEach((n,r)=>{let o=r.toLowerCase();HV.has(o)||jV.some(s=>o.startsWith(s))||(e[r]=n)}),e}function KV(t,e){if(t==null)return{serialized:void 0,inferredContentType:void 0};let n=Object.keys(e).some(o=>o.toLowerCase()==="content-type");return typeof t=="string"?{serialized:t,inferredContentType:n?void 0:"text/plain"}:{serialized:JSON.stringify(t),inferredContentType:n?void 0:"application/json"}}function qV(t,e,n){let r=Buffer.byteLength(t,"utf8"),o=t,s=!1;if(r>n&&(o=Et(t,n),s=!0),!s&&/application\/json/i.test(e))try{return{body:JSON.parse(o),truncated:!1}}catch{}return{body:o,truncated:s}}async function fR(t){let{url:e,method:n,signal:r,domainCheck:o,recordEffect:s}=t,i=Math.min(t.maxResponseBytes??ey,ty),a={...t.headers},c=t.fetchFn??globalThis.fetch,l=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},d=UV(n);if(o!==void 0){let v=o(e);if(!v.allowed)throw Object.assign(new Error(`web_request blocked by domain policy: ${v.reason}`),{name:"DomainPolicyError"})}let u=await Or(e,l);if(!u.allowed)throw new Ce(u.reason);let{serialized:p,inferredContentType:f}=KV(t.body,a);f!==void 0&&(a["content-type"]=f);let m={method:n,headers:Object.keys(a).length>0?a:void 0,body:p,signal:r},y=BV(n)?{retries:2,baseDelayMs:300,maxDelayMs:5e3}:{retries:0},b=Date.now(),S;try{S=await Dn(c,e,m,{...l,retry:y})}catch(v){throw v instanceof Ce,v}let T=Date.now()-b,_=S.headers.get("content-type")??"",A;try{let v=S.body?.getReader();if(!v)A="";else{let E=[],R=0,P=i*2;for(;;){let{done:W,value:M}=await v.read();if(W||!M)break;if(E.push(M),R+=M.byteLength,R>=P){await v.cancel();break}}A=new TextDecoder().decode(Buffer.concat(E,R))}}catch{A=""}let{body:x,truncated:I}=qV(A,_,i),C=WV(S.headers);return s!==void 0&&Promise.resolve(s({url:e,method:n,status:S.status,risk:d,timing_ms:T})).catch(()=>{}),{status:S.status,headers:C,body:x,truncated:I,timing_ms:T,risk:d}}function mR(t){if(typeof t!="string"||t.trim().length===0)return{error:"method must be a non-empty string (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS)"};let e=t.trim().toUpperCase(),n=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];return n.includes(e)?e:{error:`method "${t}" is not supported \u2014 must be one of: ${n.join(", ")}`}}var uR,pR,ey,ty,NV,$V,jV,HV,gR=h(()=>{"use strict";Dr();Ht();uR=3e4,pR=12e4,ey=1e5,ty=1e6,NV=new Set(["GET","HEAD","OPTIONS"]),$V=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]);jV=["set-cookie","x-"],HV=new Set(["server","via","age","vary","authorization","www-authenticate"])});function GV(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t;if(typeof e.url!="string"||e.url.length===0)return{error:'Invalid input: "url" must be a non-empty string'};let n;try{n=new URL(e.url)}catch{return{error:`Invalid input: "${e.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=mR(e.method);if(typeof o=="object"&&"error"in o)return{error:`Invalid input: ${o.error}`};let s=o,i;if(e.body!==void 0&&e.body!==null){if(typeof e.body!="string"&&typeof e.body!="object")return{error:'Invalid input: "body" must be a string, object, or array'};i=e.body}let a={};if(e.headers!==void 0){if(typeof e.headers!="object"||e.headers===null||Array.isArray(e.headers))return{error:'Invalid input: "headers" must be a string-keyed object'};let u=e.headers;for(let[p,f]of Object.entries(u)){if(typeof f!="string")return{error:`Invalid input: header value for "${p}" must be a string`};a[p]=f}}let c=uR;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'Invalid input: "timeout_ms" must be a positive finite number'};c=Math.min(e.timeout_ms,pR)}let l=ey;if(e.max_response_bytes!==void 0){if(typeof e.max_response_bytes!="number"||!Number.isFinite(e.max_response_bytes)||e.max_response_bytes<=0)return{error:'Invalid input: "max_response_bytes" must be a positive finite number'};l=Math.min(e.max_response_bytes,ty)}let d;if(e.credential!==void 0){if(typeof e.credential!="string"||e.credential.length===0)return{error:'Invalid input: "credential" must be a non-empty string (an env var name)'};d=e.credential}return{url:r,method:s,body:i,headers:a,timeoutMs:c,maxResponseBytes:l,credential:d}}function XV(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env;async function r(){if(t.domainCheck!==void 0)return t.domainCheck;try{let{loadBrowserConfig:o,enforceDomainPolicy:s}=await Promise.resolve().then(()=>(Fn(),Lh)),i=o();return a=>s(a,i)}catch{return}}return async(o,s)=>{if(typeof e!="function")return{content:"web_request unavailable: global fetch() is not present (agent-afk requires Node 20+).",isError:!0};let i=GV(o);if("error"in i)return{content:i.error,isError:!0};if(s.aborted){let p=s.reason;return{content:`web_request aborted: ${p instanceof Error?p.message:String(p??"aborted")}`,isError:!0}}let a={...i.headers};if(i.credential!==void 0){let p=n[i.credential];if(p===void 0||p.trim().length===0)return{content:`web_request credential error: environment variable "${i.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(m=>m.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 c=new AbortController,l=()=>c.abort(s.reason),d,u=()=>{let p=c.signal.reason;return p instanceof Error?p.message:String(p??"aborted")};try{s.addEventListener("abort",l,{once:!0}),d=setTimeout(()=>{c.abort(new Error(`web_request timeout after ${i.timeoutMs}ms`))},i.timeoutMs);let p=await r(),f={url:i.url,method:i.method,body:i.body,headers:a,maxResponseBytes:i.maxResponseBytes,signal:c.signal,fetchFn:e,lookupFn:t.lookupFn,domainCheck:p,recordEffect:t.recordEffect},m;try{m=await fR(f)}catch(S){if(c.signal.aborted)return{content:`web_request aborted: ${u()}`,isError:!0};if(S instanceof Ce)return{content:`web_request blocked: ${S.message}`,isError:!0};let T=S instanceof Error&&S.name==="DomainPolicyError"?"blocked":"network error",_=S instanceof Error?S.message:String(S);return{content:`web_request ${T}: ${_}`,isError:!0}}if(c.signal.aborted)return{content:`web_request aborted: ${u()}`,isError:!0};let g=m.body;if(typeof g=="string")g=qe(g);else if(typeof g=="object"&&g!==null){let S=qe(JSON.stringify(g));try{g=JSON.parse(S)}catch{g=S}}let y={status:m.status,headers:m.headers,body:g,timing_ms:m.timing_ms,...m.truncated?{truncated:!0}:{}};return{content:JSON.stringify(y,null,2),...m.truncated?{truncated:!0}:{}}}finally{d!==void 0&&clearTimeout(d),s.removeEventListener("abort",l)}}}var hR,yR=h(()=>{"use strict";gR();Dr();vn();hR=XV()});import{existsSync as wR,mkdirSync as zV,readFileSync as JV,renameSync as VV,unlinkSync as YV,writeFileSync as QV}from"node:fs";import{dirname as bR,join as ZV}from"node:path";import{randomBytes as e4}from"node:crypto";function Br(t){let e=t??Tm();if(!wR(e))return[];try{let n=JV(e,"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 ${e}: ${r}`),[]}}function Yi(t,e){let n=e??Tm();zV(bR(n),{recursive:!0});let r=ZV(bR(n),`.schedules.json.${process.pid}.${e4(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{QV(r,o,"utf-8"),VV(r,n)}catch(s){try{wR(r)&&YV(r)}catch{}throw s}}function SR(t,e){let n=Br(e),r=n.map(c=>c.id),o=t4(t.name),s=n4(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),Yi(n,e),a}function kR(t,e){let n=Br(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(Yi(o,e),!0)}function vR(t,e){return Br(e).find(n=>n.id===t)}function t4(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function n4(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}function TR(t){return{taskId:t.id,command:t.command,trigger:t.trigger??"cron",...t.cron!==void 0?{cronExpression:t.cron}:{},...t.notifyOn!==void 0?{notifyOn:t.notifyOn}:{},...t.notifyChat!==void 0?{notifyChat:t.notifyChat}:{}}}var _R=h(()=>{"use strict";j()});import{existsSync as r4,readFileSync as o4}from"node:fs";import{join as s4}from"node:path";async function qo(t,e,n){let r,o;try{let s=s4(cv("default"),"port");if(!r4(s))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=o4(s,"utf-8").trim(),a=i4(i);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 s=r.includes(":")?`[${r}]`:r,i=await fetch(`http://${s}:${o}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return i.ok?{synced:!0,detail:"synced"}:t==="POST"&&i.status===409?{synced:!0,detail:"already-registered"}:t==="DELETE"&&i.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${i.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}function i4(t){let e=parseInt(t,10);if(String(e)===t&&!Number.isNaN(e))return e<1||e>65535?null:{host:"localhost",port:e};let n=t.lastIndexOf(":");if(n<1)return null;let r=t.slice(0,n),o=t.slice(n+1);if(!/^\d+$/.test(o))return null;let s=parseInt(o,10);return Number.isNaN(s)||s<1||s>65535||/^:+$/.test(r)?null:{host:r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r,port:s}}var ny,ER=h(()=>{"use strict";j();ny="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 a4}from"node:fs";import{readFile as c4}from"node:fs/promises";var AR,xR,RR,IR,CR=h(()=>{"use strict";_R();j();ER();AR=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;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 s=SR({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}),i=s.enabled?await qo("POST","/tasks",{taskId:s.id,command:s.command,cron:s.cron,trigger:s.trigger,notifyOn:s.notifyOn,...s.notifyChat!==void 0?{notifyChat:s.notifyChat}:{}}):await qo("DELETE",`/tasks/${s.id}`);return{content:JSON.stringify({id:s.id,name:s.name,cron:s.cron,enabled:s.enabled,daemonSynced:i.synced,syncDetail:i.detail,...i.synced?{}:{syncNote:ny}})}},xR=async(t,e)=>{let n=Br();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})))}},RR=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;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,s=Dc();if(!a4(s))return{content:JSON.stringify([])};let i;try{let l=await c4(s);i=(l.length>1048576?l.subarray(l.length-1048576):l).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=i.split(`
@@ -1081,7 +1081,7 @@ Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${t}${r}
1081
1081
  `;process.stderr.write(l)}}var E6,A6,x6,ma=h(()=>{"use strict";L();vn();E6=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
1082
1082
  `,A6=/key|token|secret|password|credential|auth/i;x6=[[/sk-ant-[A-Za-z0-9_\-]{8,200}/g,t=>`<REDACTED sk-ant length=${t[0].length}>`],[/sk-(?!ant-)[A-Za-z0-9_\-]{20,200}/g,t=>`<REDACTED sk- length=${t[0].length}>`],[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,t=>`<REDACTED Bearer length=${t[0].length}>`],[/AKIA[A-Z0-9]{16}/g,t=>`<REDACTED AKIA length=${t[0].length}>`],[/xox[baprs]-[A-Za-z0-9\-]{10,200}/g,t=>`<REDACTED xox token length=${t[0].length}>`],[/\d{8,12}:[A-Za-z0-9_\-]{35}/g,t=>`<REDACTED Telegram token length=${t[0].length}>`],[/([A-Za-z_]{3,}(?:[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]|[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll])[A-Za-z_]*)=([^\s]{16,})/g,dM],[/([A-Z_]{3,}(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=([^\s]{16,})/g,dM]]});import{randomBytes as C6}from"node:crypto";import{mkdir as P6,writeFile as M6}from"node:fs/promises";import{join as O6}from"node:path";function F6(t){return k.AFK_CAPTURE_SUBAGENT_PROMPTS!=="1"||!t.isSubagentFork||!t.sessionId||!t.subagentId?!1:t.prompt.length>0}function lb(t,e){let n=Buffer.byteLength(t,"utf8");return n<=e?{text:t,originalBytes:n,truncated:!1}:{text:Buffer.from(t,"utf8").subarray(0,e).toString("utf8").replace(/\uFFFD+$/,""),originalBytes:n,truncated:!0}}function L6(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,60)}function wu(t){return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function N6(t,e){let n=["---",`subagentId: ${wu(t.subagentId??"unknown")}`,`sessionLabel: ${wu(t.sessionId??"unknown")}`,`turn: ${t.turn}`,`capturedAt: ${wu(new Date().toISOString())}`,`promptBytes: ${e.originalBytes}`,`bodyBytes: ${Buffer.byteLength(e.text,"utf8")}`,`truncated: ${e.truncated}`,"redaction: best-effort"];return t.model!==void 0&&n.push(`model: ${wu(t.model)}`),n.push("---",D6,""),n.push(e.text),e.truncated&&n.push("",`<!-- TRUNCATED at ${pM} bytes of ${e.originalBytes} -->`),`${n.join(`
1083
1083
  `)}
1084
- `}async function fM(t){try{if(!F6(t))return;let e=lb(t.prompt,pM),n=e.truncated?e.text.replace(/\S+$/,""):e.text,r=Xr(n),o=N6(t,{...e,text:r}),s=bm(t.sessionId);await P6(s,{recursive:!0,mode:448});let i=new Date().toISOString().replace(/[:.]/g,"-"),a=C6(3).toString("hex"),c=O6(s,`${i}-${L6(t.subagentId)}-t${t.turn}-${a}.md`);await M6(c,o,{encoding:"utf8",mode:384,flag:"wx"})}catch(e){he("subagent-prompt-capture",t.sessionId??"unknown","captureSubagentPrompt",e)}}var pM,D6,db=h(()=>{"use strict";L();j();Fl();ma();pM=8*1024,D6="<!-- Best-effort secret redaction only. Connection strings, PEM blocks, and PII are NOT caught. -->"});import{appendFile as $6,mkdir as U6}from"node:fs/promises";import{join as B6}from"node:path";function H6(t){return!(k.AFK_CAPTURE_SUBAGENT_OUTPUT!=="1"||!t.isSubagentFork||!t.sessionId||!t.subagentId)}function W6(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,60)}function Su(t){return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function hM(t){let e=lb(t,mM),n=e.truncated?e.text.replace(/\S+$/,""):e.text,r=Xr(n);return e.truncated?`${r}
1084
+ `}async function fM(t){try{if(!F6(t))return;let e=lb(t.prompt,pM),n=e.truncated?e.text.replace(/\S+$/,""):e.text,r=Xr(n),o=N6(t,{...e,text:r}),s=bm(t.sessionId);await P6(s,{recursive:!0,mode:448});let i=new Date().toISOString().replace(/[:.]/g,"-"),a=C6(3).toString("hex"),c=O6(s,`${i}-${L6(t.subagentId)}-t${t.turn}-${a}.md`);await M6(c,o,{encoding:"utf8",mode:384,flag:"wx"})}catch(e){he("subagent-prompt-capture",t.sessionId??"unknown","captureSubagentPrompt",e)}}var pM,D6,db=h(()=>{"use strict";L();j();Fl();ma();pM=8*1024,D6="<!-- Best-effort secret redaction only. Connection strings, PEM blocks, and PII are NOT caught. -->"});import{appendFile as $6,mkdir as U6}from"node:fs/promises";import{join as B6}from"node:path";function H6(t){return!(k.AFK_CAPTURE_SUBAGENT_OUTPUT==="0"||!t.isSubagentFork||!t.sessionId||!t.subagentId)}function W6(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,60)}function Su(t){return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function hM(t){let e=lb(t,mM),n=e.truncated?e.text.replace(/\S+$/,""):e.text,r=Xr(n);return e.truncated?`${r}
1085
1085
  <!-- TRUNCATED at ${mM} bytes of ${e.originalBytes} -->`:r}function K6(t){let e=["---",`subagentId: ${Su(t.subagentId??"unknown")}`,`sessionLabel: ${Su(t.sessionId??"unknown")}`,`startedAt: ${Su(new Date().toISOString())}`,"redaction: best-effort","capture: incremental (flushed at each tool-call boundary)"];return t.model!==void 0&&e.push(`model: ${Su(t.model)}`),e.push("---",j6,""),`${e.join(`
1086
1086
  `)}
1087
1087
  `}function ku(t,e){let n=new Date().toISOString();if(t==="say")return`
@@ -1171,7 +1171,7 @@ On your first turn, decide whether to call memory_search based on the request:
1171
1171
  - If hot memory (shown in <cross-session-memory> tags above) already covers the relevant context, skip the search.
1172
1172
  - Search at most once per session for general context. Search again only if new information surfaces a specific topic worth querying.
1173
1173
 
1174
- Use FTS5 syntax: "exact phrase", term1 AND term2, prefix*.`});function wa(t,e){let n=(u,p)=>{if(!(u==null&&p==null))return(u??0)+(p??0)},r=(u,p)=>p!==void 0?p:u,o={stopReason:e.stopReason??t.stopReason??null,...e.raw!==void 0?{raw:e.raw}:t.raw!==void 0?{raw:t.raw}:{}},s=n(t.inputTokens,e.inputTokens);s!==void 0&&(o.inputTokens=s);let i=n(t.outputTokens,e.outputTokens);i!==void 0&&(o.outputTokens=i);let a=r(t.cachedInputTokens,e.cachedInputTokens);a!==void 0&&(o.cachedInputTokens=a);let c=r(t.cacheCreationTokens,e.cacheCreationTokens);c!==void 0&&(o.cacheCreationTokens=c);let l=n(t.totalTokens,e.totalTokens);l!==void 0&&(o.totalTokens=l);let d=n(t.totalCostUsd,e.totalCostUsd);return d!==void 0&&(o.totalCostUsd=d),o}var xb=h(()=>{"use strict"});function Uu(){try{let t=Sa();return Promise.resolve(t.map(e=>{let n={name:e.name,description:e.description};return e.argumentHint&&(n.argumentHint=e.argumentHint),e.whenToUse&&(n.whenToUse=e.whenToUse),e.source&&(n.source=e.source),n}))}catch{return Promise.resolve([])}}var Rb=h(()=>{"use strict";Gn()});var ts,Ib=h(()=>{"use strict";J();ts=class{constructor(e,n,r){this.signal=e;this.traceWriter=n;this.provider=r;q(n,{phase:"loop_start"}),this.interruptedAt=e.aborted?Date.now():null,n&&!e.aborted&&e.addEventListener("abort",this.onInterrupt,{once:!0})}signal;traceWriter;provider;interruptedAt;onInterrupt=()=>{this.interruptedAt===null&&(this.interruptedAt=Date.now())};finish(e){this.signal.removeEventListener("abort",this.onInterrupt),this.interruptedAt!==null&&this.signal.reason==="interrupted"&&q(this.traceWriter,{phase:"interrupt_halt",durationMs:Date.now()-this.interruptedAt,metadata:{provider:this.provider}}),q(this.traceWriter,{phase:"loop_end",durationMs:e})}}});import{readFileSync as iQ}from"node:fs";import{homedir as aQ}from"node:os";import{join as O0}from"node:path";function cQ(t){try{return iQ(t,"utf-8")}catch{return null}}function Xn(t,e={},n=!1){let r=e.readEnv??(d=>process.env[d]),o=(e.homedir??aQ)(),s=e.readFile??cQ;if(n){let d=O0(o,".codex","auth.json"),u=s(d);if(u!==null){let p=D0(u);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:ns(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(t&&t.length>0)return{apiKey:t,source:"config",last4:ns(t)};let i=r("OPENAI_API_KEY");if(i&&i.length>0)return{apiKey:i,source:"env",last4:ns(i),envVar:"OPENAI_API_KEY"};let a=r("CODEX_API_KEY");if(a&&a.length>0)return{apiKey:a,source:"env",last4:ns(a),envVar:"CODEX_API_KEY"};let c=O0(o,".codex","auth.json"),l=s(c);if(l!==null){let d=D0(l);if(d.kind==="apikey")return{apiKey:d.apiKey,source:"codex-cli",last4:ns(d.apiKey)};if(d.kind==="chatgpt"){if(lQ(r)&&d.accessToken){if(d.expiresAt!==void 0&&d.expiresAt<=Math.floor(Date.now()/1e3))return{apiKey:null,source:"chatgpt-oauth-expired",expiresAt:d.expiresAt};let u={apiKey:d.accessToken,source:"chatgpt-oauth",last4:ns(d.accessToken)};return d.accountId!==void 0&&(u.accountId=d.accountId),d.expiresAt!==void 0&&(u.expiresAt=d.expiresAt),u}return{apiKey:null,source:"no-usable-auth-codex-oauth"}}}return{apiKey:null,source:"no-usable-auth"}}function D0(t){let e;try{e=JSON.parse(t)}catch{return{kind:"invalid"}}if(typeof e!="object"||e===null)return{kind:"invalid"};let n=e,r=n.OPENAI_API_KEY;if(typeof r=="string"&&r.length>0)return{kind:"apikey",apiKey:r};let o=n.tokens,s=typeof o=="object"&&o!==null?o:null,i=s&&typeof s.access_token=="string"?s.access_token:void 0;if(n.auth_mode==="chatgpt"||i){let a={kind:"chatgpt"};if(i&&(a.accessToken=i),s){let c=dQ(s);c!==void 0&&(a.accountId=c);let l=uQ(s);l!==void 0&&(a.expiresAt=l)}return a}return{kind:"no-key"}}function ns(t){return t.length<=4?t:t.slice(-4)}function lQ(t){let e=t("AFK_OPENAI_CHATGPT_OAUTH");if(!e)return!1;let n=e.trim().toLowerCase();return n==="1"||n==="true"||n==="yes"||n==="on"}function F0(t){let e=t.split(".");if(e.length<2||!e[1])return null;try{let n=Buffer.from(e[1],"base64url").toString("utf-8"),r=JSON.parse(n);return typeof r=="object"&&r!==null?r:null}catch{return null}}function dQ(t){let e=t.account_id;if(typeof e=="string"&&e.length>0)return e;for(let n of["access_token","id_token"]){let r=t[n];if(typeof r!="string")continue;let o=F0(r);if(!o)continue;let s=o["https://api.openai.com/auth"];if(typeof s=="object"&&s!==null){let a=s.chatgpt_account_id;if(typeof a=="string"&&a.length>0)return a}let i=o.chatgpt_account_id;if(typeof i=="string"&&i.length>0)return i}}function uQ(t){let e=t.access_token;if(typeof e!="string")return;let n=F0(e)?.exp;return typeof n=="number"?n:void 0}function pQ(t){if(typeof t!="number")return"";let e=t-Math.floor(Date.now()/1e3);if(e<=0)return", EXPIRED \u2014 re-run `codex` to refresh";let n=Math.floor(e/3600),r=Math.floor(e%3600/60);return`, expires in ${n>0?`${n}h `:""}${r}m`}function Cb(t){switch(t.source){case"config":return`using explicit AFK config API key (\u2026${t.last4??"????"})`;case"env":return`using ${t.envVar??"OPENAI_API_KEY"} env var (\u2026${t.last4??"????"})`;case"codex-cli":return`using Codex CLI API key from ~/.codex/auth.json (\u2026${t.last4??"????"})`;case"chatgpt-oauth":{let e=t.accountId?`\u2026${t.accountId.slice(-4)}`:"unknown",n=pQ(t.expiresAt);return`using ChatGPT subscription OAuth from ~/.codex/auth.json (account ${e}${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 ka=h(()=>{"use strict"});function Bu(t,e,n){let r=t.lastIndexOf(L0);if(r===-1)return t;let o=t.indexOf(`
1174
+ Use FTS5 syntax: "exact phrase", term1 AND term2, prefix*.`});function wa(t,e){let n=(u,p)=>{if(!(u==null&&p==null))return(u??0)+(p??0)},r=(u,p)=>p!==void 0?p:u,o={stopReason:e.stopReason??t.stopReason??null,...e.raw!==void 0?{raw:e.raw}:t.raw!==void 0?{raw:t.raw}:{}},s=n(t.inputTokens,e.inputTokens);s!==void 0&&(o.inputTokens=s);let i=n(t.outputTokens,e.outputTokens);i!==void 0&&(o.outputTokens=i);let a=r(t.cachedInputTokens,e.cachedInputTokens);a!==void 0&&(o.cachedInputTokens=a);let c=r(t.cacheCreationTokens,e.cacheCreationTokens);c!==void 0&&(o.cacheCreationTokens=c);let l=n(t.totalTokens,e.totalTokens);l!==void 0&&(o.totalTokens=l);let d=n(t.totalCostUsd,e.totalCostUsd);return d!==void 0&&(o.totalCostUsd=d),o}var xb=h(()=>{"use strict"});function Uu(){try{let t=Sa();return Promise.resolve(t.map(e=>{let n={name:e.name,description:e.description};return e.argumentHint&&(n.argumentHint=e.argumentHint),e.whenToUse&&(n.whenToUse=e.whenToUse),e.source&&(n.source=e.source),n}))}catch{return Promise.resolve([])}}var Rb=h(()=>{"use strict";Gn()});var ts,Ib=h(()=>{"use strict";J();ts=class{constructor(e,n,r){this.signal=e;this.traceWriter=n;this.provider=r;q(n,{phase:"loop_start"}),this.interruptedAt=e.aborted?Date.now():null,n&&!e.aborted&&e.addEventListener("abort",this.onInterrupt,{once:!0})}signal;traceWriter;provider;interruptedAt;onInterrupt=()=>{this.interruptedAt===null&&(this.interruptedAt=Date.now())};finish(e){this.signal.removeEventListener("abort",this.onInterrupt),this.interruptedAt!==null&&this.signal.reason==="interrupted"&&q(this.traceWriter,{phase:"interrupt_halt",durationMs:Date.now()-this.interruptedAt,metadata:{provider:this.provider}}),q(this.traceWriter,{phase:"loop_end",durationMs:e})}}});import{readFileSync as iQ}from"node:fs";import{homedir as aQ}from"node:os";import{join as O0}from"node:path";function cQ(t){try{return iQ(t,"utf-8")}catch{return null}}function Xn(t,e={},n=!1){let r=e.readEnv??(d=>process.env[d]),o=(e.homedir??aQ)(),s=e.readFile??cQ;if(n){let d=O0(o,".codex","auth.json"),u=s(d);if(u!==null){let p=D0(u);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:ns(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(t&&t.length>0)return{apiKey:t,source:"config",last4:ns(t)};let i=r("OPENAI_API_KEY");if(i&&i.length>0)return{apiKey:i,source:"env",last4:ns(i),envVar:"OPENAI_API_KEY"};let a=r("CODEX_API_KEY");if(a&&a.length>0)return{apiKey:a,source:"env",last4:ns(a),envVar:"CODEX_API_KEY"};let c=O0(o,".codex","auth.json"),l=s(c);if(l!==null){let d=D0(l);if(d.kind==="apikey")return{apiKey:d.apiKey,source:"codex-cli",last4:ns(d.apiKey)};if(d.kind==="chatgpt"){if(lQ(r)&&d.accessToken){if(d.expiresAt!==void 0&&d.expiresAt<=Math.floor(Date.now()/1e3))return{apiKey:null,source:"chatgpt-oauth-expired",expiresAt:d.expiresAt};let u={apiKey:d.accessToken,source:"chatgpt-oauth",last4:ns(d.accessToken)};return d.accountId!==void 0&&(u.accountId=d.accountId),d.expiresAt!==void 0&&(u.expiresAt=d.expiresAt),u}return{apiKey:null,source:"no-usable-auth-codex-oauth"}}}return{apiKey:null,source:"no-usable-auth"}}function D0(t){let e;try{e=JSON.parse(t)}catch{return{kind:"invalid"}}if(typeof e!="object"||e===null)return{kind:"invalid"};let n=e,r=n.OPENAI_API_KEY;if(typeof r=="string"&&r.length>0)return{kind:"apikey",apiKey:r};let o=n.tokens,s=typeof o=="object"&&o!==null?o:null,i=s&&typeof s.access_token=="string"?s.access_token:void 0;if(n.auth_mode==="chatgpt"||i){let a={kind:"chatgpt"};if(i&&(a.accessToken=i),s){let c=dQ(s);c!==void 0&&(a.accountId=c);let l=uQ(s);l!==void 0&&(a.expiresAt=l)}return a}return{kind:"no-key"}}function ns(t){return t.length<=4?t:t.slice(-4)}function lQ(t){let e=t("AFK_OPENAI_CHATGPT_OAUTH");if(!e)return!0;let n=e.trim().toLowerCase();return!(n==="0"||n==="false"||n==="no"||n==="off")}function F0(t){let e=t.split(".");if(e.length<2||!e[1])return null;try{let n=Buffer.from(e[1],"base64url").toString("utf-8"),r=JSON.parse(n);return typeof r=="object"&&r!==null?r:null}catch{return null}}function dQ(t){let e=t.account_id;if(typeof e=="string"&&e.length>0)return e;for(let n of["access_token","id_token"]){let r=t[n];if(typeof r!="string")continue;let o=F0(r);if(!o)continue;let s=o["https://api.openai.com/auth"];if(typeof s=="object"&&s!==null){let a=s.chatgpt_account_id;if(typeof a=="string"&&a.length>0)return a}let i=o.chatgpt_account_id;if(typeof i=="string"&&i.length>0)return i}}function uQ(t){let e=t.access_token;if(typeof e!="string")return;let n=F0(e)?.exp;return typeof n=="number"?n:void 0}function pQ(t){if(typeof t!="number")return"";let e=t-Math.floor(Date.now()/1e3);if(e<=0)return", EXPIRED \u2014 re-run `codex` to refresh";let n=Math.floor(e/3600),r=Math.floor(e%3600/60);return`, expires in ${n>0?`${n}h `:""}${r}m`}function Cb(t){switch(t.source){case"config":return`using explicit AFK config API key (\u2026${t.last4??"????"})`;case"env":return`using ${t.envVar??"OPENAI_API_KEY"} env var (\u2026${t.last4??"????"})`;case"codex-cli":return`using Codex CLI API key from ~/.codex/auth.json (\u2026${t.last4??"????"})`;case"chatgpt-oauth":{let e=t.accountId?`\u2026${t.accountId.slice(-4)}`:"unknown",n=pQ(t.expiresAt);return`using ChatGPT subscription OAuth from ~/.codex/auth.json (account ${e}${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 ka=h(()=>{"use strict"});function Bu(t,e,n){let r=t.lastIndexOf(L0);if(r===-1)return t;let o=t.indexOf(`
1175
1175
  `,r+L0.length);if(o===-1)return t;let s=o+1;if(!t.startsWith(Pb,s))return t;let i=t.indexOf(`
1176
1176
  `,s),a=i===-1?t.length:i,c=t.slice(s+Pb.length,a),l=Xl(e??new Date,n);return c===l?t:t.slice(0,s+Pb.length)+l+t.slice(a)}var L0,Pb,Mb=h(()=>{"use strict";Ue();L0=`# Environment
1177
1177
  - Working directory: `,Pb="- Date: "});function fQ(t,e){let n=e===1?"An image was":`${e} images were`,r=e===1?"an image":"images",o=e===1?"it":"them",s=t&&t.trim().length>0?`the current model ("${t.trim()}")`:"the current model";return`[${n} attached to this message, but ${s} 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 mQ(t){let e=t.source;return e.type==="base64"?`data:${e.media_type};base64,${e.data}`:e.type==="url"?e.url:null}function N0(t,e){if(typeof t=="string")return t;let n=[],r=0;for(let i of t)if(typeof i=="object"&&i&&"type"in i){if(i.type==="text")n.push(i.text);else if(i.type==="image")r+=1;else if(i.type==="document"){let a=i,c=a.title??"document",l=a.source;if(l&&l.type==="text")n.push(`[Document: ${c}]
@@ -1196,7 +1196,7 @@ ${o}`:o}function hQ(t){let e=t.systemPrompt;if(e!==void 0){if(typeof e=="string"
1196
1196
 
1197
1197
  `));let s=$Q(e);return s.length>0&&(o.tools=s),o}function NQ(t){if(t===null)return"";if(typeof t=="string")return t;let e=[];for(let n of t)n.type==="text"?e.push({type:"input_text",text:n.text}):e.push({type:"input_image",image_url:n.image_url.url,detail:"auto"});return e}function $Q(t){return!t||t.length===0?[]:t.map(e=>{let n={type:"function",name:e.function.name,parameters:e.function.parameters};return e.function.description!==void 0&&(n.description=e.function.description),n})}var dO=h(()=>{"use strict"});function Ia(t,e){let n=Eo(t);if(typeof e=="number"&&Number.isFinite(e)&&e>0){let r=Math.floor(e),o=ag(t);if(o!==void 0&&r>o){let s=`max:${t}:${r}`;return uO.has(s)||(uO.add(s),console.warn(`[afk] maxOutputTokens ${r} exceeds the ${t} output ceiling (${o}); clamping to ${o}.`)),o}return r}return n}function pO(t,e){let n=Ia(t,e);return fi(t)?{max_completion_tokens:n}:{max_tokens:n}}function Gb(t){return t??"default"}function fO(t){switch(t){case"low":return"low";case"medium":return"medium";case"high":case"xhigh":case"max":return"high"}}function Ju(t,e){if(t!==void 0&&fi(e))return fO(t)}var uO,Ca=h(()=>{"use strict";Bt();mr();uO=new Set});function Vu(t){let e=lO(t.messages,t.activeTools),n={model:t.model,input:e.input,stream:!0};t.isChatGptBackend||(n.max_output_tokens=Ia(t.model,t.maxOutputTokens));let r=e.instructions??(t.isChatGptBackend?Q0:void 0);r!==void 0&&(n.instructions=r),t.isChatGptBackend&&(n.store=!1),e.tools&&e.tools.length>0&&(n.tools=e.tools);let o=Ju(t.effort,t.model);return o!==void 0&&(n.reasoning={effort:o}),t.temperature!==void 0&&(n.temperature=t.temperature),n}function mO(t){let e={model:t.model,messages:t.messages,stream:!0,stream_options:{include_usage:!0}};Object.assign(e,pO(t.model,t.maxOutputTokens)),t.activeTools&&t.activeTools.length>0&&(e.tools=t.activeTools);let n=Ju(t.effort,t.model);return n!==void 0&&(e.reasoning_effort=n),t.temperature!==void 0&&(e.temperature=t.temperature),e}var Xb=h(()=>{"use strict";dO();Gu();Ca()});async function*cs(t,e){if(e.aborted)throw gO(e);let n=t[Symbol.asyncIterator](),r=!1,o=Symbol("aborted"),s,i=new Promise(a=>{s=()=>a(o),e.addEventListener("abort",s,{once:!0})});try{for(;;){let a=n.next(),c=await Promise.race([a,i]);if(c===o)throw Promise.resolve(a).catch(()=>{}),r=!0,gO(e);if(c.done)return;yield c.value}}finally{e.removeEventListener("abort",s);let a=Promise.resolve(n.return?.()).catch(()=>{});r||await a}}function gO(t){let e=t.reason;if(e instanceof Error)return e;let n=new Error(typeof e=="string"&&e.length>0?e:"The operation was aborted");return n.name="AbortError",n}var Yu=h(()=>{"use strict"});import UQ from"openai";async function Qu(t){let{apiKey:e,baseURL:n,defaultHeaders:r,model:o,system:s,user:i,maxTokens:a=64,signal:c,clientFactory:l}=t,d;if(t.client!==void 0)d=t.client;else{let m=Xn(e,{},t.forceChatgptOAuth??!1);if(m.apiKey===null)throw new Error("oneShotChatCompletion: no usable OpenAI auth (set OPENAI_API_KEY or pass apiKey)");let g={apiKey:m.apiKey};n!==void 0&&(g.baseURL=n),r!==void 0&&(g.defaultHeaders=r);let y=l??BQ;d=y?y(g):new UQ(g)}let u=fi(o)?{max_completion_tokens:a}:{max_tokens:a},f=(await d.chat.completions.create({model:o,...u,stream:!1,messages:[{role:"system",content:s},{role:"user",content:i}]},c?{signal:c}:void 0)).choices?.[0]?.message?.content;return typeof f=="string"?f.trim():""}async function hO(t){let{client:e,model:n,system:r,user:o,isChatGptBackend:s,maxTokens:i=1024,signal:a}=t,l=Vu({model:n,messages:[{role:"system",content:r},{role:"user",content:o}],activeTools:void 0,maxOutputTokens:i,effort:void 0,temperature:void 0,isChatGptBackend:s}),d=await e.responses.create(l,a?{signal:a}:void 0),u=a?cs(d,a):d,p=Wu(),f=!1;for await(let m of u){m.type==="response.completed"&&(f=!0);let g=Ku(m,p,"compact-oneshot");for(;!g.next().done;);}if(!f)throw new Pa(p.finishReason);return p.assistantText.trim()}var Pa,BQ,Zu=h(()=>{"use strict";ka();mr();Xb();Ta();Nb();Yu();Pa=class extends Error{constructor(n){super(`responses summarize did not complete (terminal status: ${n??"none"})`);this.finishReason=n;this.name="ResponsesSummaryIncompleteError"}finishReason},BQ=null});function zb(t){return jQ*Math.pow(2,t)}function Jb(t){let e=jn(t);if(e!==void 0)return Math.min(e,HQ)}function zn(t){if(t===null||typeof t!="object")return;let e=t;return typeof e.status=="number"?e.status:void 0}function ep(t){let e=zn(t);return e===void 0?!1:yO.has(e)}function tp(t){let e=zn(t);return e===void 0?!1:yO.has(e)}var yO,bO,wO,jQ,HQ,ls=h(()=>{"use strict";Qy();yO=new Set([429,500,502,503,529]),bO=3,wO=3,jQ=2e3;HQ=12e4});function Vb(t){return t!=="plan"?null:{type:"text",text:np}}var np,Yb=h(()=>{"use strict";np=["## 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(`
1198
1198
  `)});function Qb(t){return t!=="autonomous"?null:{type:"text",text:rp}}var rp,Zb=h(()=>{"use strict";rp=["## 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(`
1199
- `)});function Jn(t,e){if(!e||typeof e!="object")return"";let n=e;if(t==="skill"||t==="Skill"){let i=n.name;return typeof i=="string"&&i.length>0?`(${i.length>60?i.slice(0,59)+"\u2026":i})`:""}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 i=qe(o.replace(/\\\r?\n/g," ").replace(/\s+/g," ").trim());return" "+(i.length>SO?i.slice(0,SO-1)+"\u2026":i)}let s=n.query??n.pattern??n.url??n.description;return typeof s=="string"?" "+s:""}var SO,Ma=h(()=>{"use strict";vn();SO=160});function op(t){if(!t||typeof t!="object")return;let e=t,n={};for(let r of WQ){let o=e[r];o!==void 0&&(n[r]=typeof o=="string"&&o.length>kO?o.slice(0,kO):o)}return Object.keys(n).length>0?JSON.stringify(n):void 0}function sp(t){if(!t||typeof t!="object")return;let e=t;if(Object.keys(e).length===0)return;let n={};for(let[r,o]of Object.entries(e))if(typeof o=="string"){let s=o.length>vO?o.slice(0,vO):o;n[r]=qe(s)}else o!=null&&typeof o!="object"&&(n[r]=o);return Object.keys(n).length>0?JSON.stringify(n):void 0}var WQ,kO,vO,ew=h(()=>{"use strict";vn();WQ=["file_path","name","id_prefix"],kO=4096,vO=8192});import{createHash as KQ}from"crypto";function ip(t){let{toolUseId:e,name:n,input:r,subagentId:o}=t,s=r??{},i=JSON.stringify(s),a=JSON.stringify(qQ(n,s));return{phase:"started",toolUseId:e,name:n,inputBytes:Buffer.byteLength(i,"utf8"),argsFingerprint:KQ("sha256").update(a).digest("hex"),...o!==void 0?{subagentId:o}:{}}}function qQ(t,e){if(typeof e!="object"||e===null)return e;let n=e;switch(t){case"browser_act":return n.action==="fill"&&"value"in n?{...n,value:"[REDACTED]"}:e;case"config_set":return n.target==="env"&&"value"in n?{...n,value:"[REDACTED]"}:e;default:return e}}function ap(t){let{toolUseId:e,name:n,result:r,truncated:o,durationMs:s,subagentId:i}=t;return{phase:"completed",toolUseId:e,name:n,resultBytes:Buffer.byteLength(r.content,"utf8"),isError:r.isError===!0,truncated:o,durationMs:s,...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}:{},...i!==void 0?{subagentId:i}:{},...r.testResult!==void 0?{testResult:r.testResult}:{}}}var cp=h(()=>{"use strict"});async function*lp(t){let e=[],n=!1,r=null,o=()=>{let l=r;r=null,l?.()},a=t(l=>{n||(e.push(l),o())}).finally(()=>{n=!0,o()}).then(l=>({ok:!0,value:l}),l=>({ok:!1,error:l}));for(;;){for(;e.length>0;)yield e.shift();if(n)break;await new Promise(l=>{r=l})}let c=await a;if(!c.ok)throw c.error;return c.value}var tw=h(()=>{"use strict"});import{randomUUID as GQ}from"node:crypto";async function*TO({state:t,signal:e,vision:n,toolDispatcher:r,traceWriter:o,priorTurns:s,sessionId:i,subagentId:a}){if(!r)return void 0;let c=va(t);for(let m of c)m.id.length===0&&(m.id=GQ());let{calls:l,parseErrors:d}=z0(c,e),u=new Map;for(let m of l){let g=Date.now();u.set(m.id,g),br(o,ip({toolUseId:m.id,name:m.name,input:m.input,subagentId:a})),yield{type:"tool.use.start",toolUseId:m.id,toolName:m.name,toolInput:Jn(m.name,m.input),toolInputRaw:op(m.input),toolInputCapture:k.AFK_CAPTURE_SUBAGENT_OUTPUT==="1"?sp(m.input):void 0,sessionId:i}}let p=[];if(e.aborted){let m=Ne(e);for(let g of l){let y={content:"Tool call aborted",isError:!0,failureClass:m};p.push({call:g,result:y}),yield{type:"tool.output",toolUseId:g.id,toolName:g.name,content:y.content,isError:!0,failureClass:m,sessionId:i}}}else{let m;try{if(r.executeBatch)m=yield*lp(g=>r.executeBatch(l,y=>{g({type:"tool.activity",activeCount:y.length,activeToolUseIds:[...y],sessionId:i})}));else{m=[];for(let g of l){if(e.aborted){m.push({content:"Tool call aborted",isError:!0,failureClass:Ne(e)});continue}try{m.push(await r.execute(g))}catch(y){let b=y instanceof Error?y.message:String(y);m.push({content:`Tool execution threw: ${b}`,isError:!0})}}}}catch(g){let y=g instanceof Error?g.message:String(g);m=l.map(()=>({content:`Tool batch execution failed: ${y}`,isError:!0}))}for(let g=0;g<l.length;g++){let y=l[g],b=m[g],S=d.get(y.id);S!==void 0&&(b={content:`${S}
1199
+ `)});function Jn(t,e){if(!e||typeof e!="object")return"";let n=e;if(t==="skill"||t==="Skill"){let i=n.name;return typeof i=="string"&&i.length>0?`(${i.length>60?i.slice(0,59)+"\u2026":i})`:""}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 i=qe(o.replace(/\\\r?\n/g," ").replace(/\s+/g," ").trim());return" "+(i.length>SO?i.slice(0,SO-1)+"\u2026":i)}let s=n.query??n.pattern??n.url??n.description;return typeof s=="string"?" "+s:""}var SO,Ma=h(()=>{"use strict";vn();SO=160});function op(t){if(!t||typeof t!="object")return;let e=t,n={};for(let r of WQ){let o=e[r];o!==void 0&&(n[r]=typeof o=="string"&&o.length>kO?o.slice(0,kO):o)}return Object.keys(n).length>0?JSON.stringify(n):void 0}function sp(t){if(!t||typeof t!="object")return;let e=t;if(Object.keys(e).length===0)return;let n={};for(let[r,o]of Object.entries(e))if(typeof o=="string"){let s=o.length>vO?o.slice(0,vO):o;n[r]=qe(s)}else o!=null&&typeof o!="object"&&(n[r]=o);return Object.keys(n).length>0?JSON.stringify(n):void 0}var WQ,kO,vO,ew=h(()=>{"use strict";vn();WQ=["file_path","name","id_prefix"],kO=4096,vO=8192});import{createHash as KQ}from"crypto";function ip(t){let{toolUseId:e,name:n,input:r,subagentId:o}=t,s=r??{},i=JSON.stringify(s),a=JSON.stringify(qQ(n,s));return{phase:"started",toolUseId:e,name:n,inputBytes:Buffer.byteLength(i,"utf8"),argsFingerprint:KQ("sha256").update(a).digest("hex"),...o!==void 0?{subagentId:o}:{}}}function qQ(t,e){if(typeof e!="object"||e===null)return e;let n=e;switch(t){case"browser_act":return n.action==="fill"&&"value"in n?{...n,value:"[REDACTED]"}:e;case"config_set":return n.target==="env"&&"value"in n?{...n,value:"[REDACTED]"}:e;default:return e}}function ap(t){let{toolUseId:e,name:n,result:r,truncated:o,durationMs:s,subagentId:i}=t;return{phase:"completed",toolUseId:e,name:n,resultBytes:Buffer.byteLength(r.content,"utf8"),isError:r.isError===!0,truncated:o,durationMs:s,...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}:{},...i!==void 0?{subagentId:i}:{},...r.testResult!==void 0?{testResult:r.testResult}:{}}}var cp=h(()=>{"use strict"});async function*lp(t){let e=[],n=!1,r=null,o=()=>{let l=r;r=null,l?.()},a=t(l=>{n||(e.push(l),o())}).finally(()=>{n=!0,o()}).then(l=>({ok:!0,value:l}),l=>({ok:!1,error:l}));for(;;){for(;e.length>0;)yield e.shift();if(n)break;await new Promise(l=>{r=l})}let c=await a;if(!c.ok)throw c.error;return c.value}var tw=h(()=>{"use strict"});import{randomUUID as GQ}from"node:crypto";async function*TO({state:t,signal:e,vision:n,toolDispatcher:r,traceWriter:o,priorTurns:s,sessionId:i,subagentId:a}){if(!r)return void 0;let c=va(t);for(let m of c)m.id.length===0&&(m.id=GQ());let{calls:l,parseErrors:d}=z0(c,e),u=new Map;for(let m of l){let g=Date.now();u.set(m.id,g),br(o,ip({toolUseId:m.id,name:m.name,input:m.input,subagentId:a})),yield{type:"tool.use.start",toolUseId:m.id,toolName:m.name,toolInput:Jn(m.name,m.input),toolInputRaw:op(m.input),toolInputCapture:k.AFK_CAPTURE_SUBAGENT_OUTPUT!=="0"?sp(m.input):void 0,sessionId:i}}let p=[];if(e.aborted){let m=Ne(e);for(let g of l){let y={content:"Tool call aborted",isError:!0,failureClass:m};p.push({call:g,result:y}),yield{type:"tool.output",toolUseId:g.id,toolName:g.name,content:y.content,isError:!0,failureClass:m,sessionId:i}}}else{let m;try{if(r.executeBatch)m=yield*lp(g=>r.executeBatch(l,y=>{g({type:"tool.activity",activeCount:y.length,activeToolUseIds:[...y],sessionId:i})}));else{m=[];for(let g of l){if(e.aborted){m.push({content:"Tool call aborted",isError:!0,failureClass:Ne(e)});continue}try{m.push(await r.execute(g))}catch(y){let b=y instanceof Error?y.message:String(y);m.push({content:`Tool execution threw: ${b}`,isError:!0})}}}}catch(g){let y=g instanceof Error?g.message:String(g);m=l.map(()=>({content:`Tool batch execution failed: ${y}`,isError:!0}))}for(let g=0;g<l.length;g++){let y=l[g],b=m[g],S=d.get(y.id);S!==void 0&&(b={content:`${S}
1200
1200
  --
1201
1201
  ${b.content}`,isError:!0,...b.truncated===!0?{truncated:!0}:{}}),p.push({call:y,result:b});let T=u.get(y.id),_=typeof T=="number"?Date.now()-T:0,A=b.truncated===!0||b.content.includes("[output truncated");br(o,ap({toolUseId:y.id,name:y.name,result:b,truncated:A,durationMs:_,subagentId:a})),yield{type:"tool.output",toolUseId:y.id,toolName:y.name,content:b.content,...b.isError===!0?{isError:!0}:{},...b.truncated===!0?{truncated:!0}:{},...b.capturePath!==void 0?{capturePath:b.capturePath}:{},...b.incomplete===!0?{incomplete:!0}:{},...b.incompleteReason?{incompleteReason:b.incompleteReason}:{},...typeof b.batchIndex=="number"&&typeof b.batchSize=="number"?{batchIndex:b.batchIndex,batchSize:b.batchSize}:{},...b.failureClass?{failureClass:b.failureClass}:{},durationMs:b.durationMs!==void 0?b.durationMs:_,...b.exitCode!==void 0?{exitCode:b.exitCode}:{},sessionId:i},b.render?.diff&&(yield{type:"tool.diff",toolUseId:y.id,diff:b.render.diff,sessionId:i})}}s.push(J0(t.assistantText,c,t.reasoningText));for(let m of V0(p))s.push(m);for(let{result:m}of p)m.harnessUserMessage?.kind==="queued_user_message"&&s.push({role:"user",content:m.harnessUserMessage.text});let f=Y0(p,{vision:n});return f&&s.push(f),p.find(m=>m.result.failureClass===Co)?.result}var _O=h(()=>{"use strict";In();J();ew();L();Ci();Ma();cp();tw();Ta();Fb()});function up(t){return t!==void 0&&t>0?Math.floor(t):0}function pp(t,e){return e>0&&t>=e}function fp(t,e){return e>0?`round ${t}/${e}`:`round ${t}`}var Mt,dp,ds=h(()=>{"use strict";Mt="tool_use_loop_capped",dp="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 EO(t,e,n,r){try{return yi(Ee(t??{}),Ia(e,n),Tt(e),r),null}catch(o){return o instanceof Error?o:new Error(String(o))}}var AO=h(()=>{"use strict";Ao();Bt();Ca()});function xO(t){let e=t.get("retry-after");if(e==null)return;let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.round(n*1e3);let r=Date.parse(e);if(!Number.isNaN(r)){let o=r-Date.now();if(o>=0)return o}}function RO(t=fetch,e,n,r){return!e&&!n&&!r?t:async(o,s)=>{if(r){let a=mu(s),c=s?.signal instanceof AbortSignal?s.signal:void 0;await r.acquirePermit(a,c)}let i=await t(o,s);if(n)try{n(i.headers)}catch{}if(r&&i.status===429)try{let a=xO(i.headers);r.freeze(a??5e3)}catch{}if(e&&XQ.has(i.status))try{let a=xO(i.headers);e({status:i.status,...a!==void 0?{retryAfterMs:a}:{}})}catch{}return i}}var XQ,IO=h(()=>{"use strict";ua();XQ=new Set([429,503,529])});import zQ from"openai";function VQ(t){let e={apiKey:t.apiKey};return t.baseURL!==void 0&&(e.baseURL=t.baseURL),t.defaultHeaders!==void 0&&(e.defaultHeaders=t.defaultHeaders),t.fetch!==void 0&&(e.fetch=t.fetch),new zQ(e)}function CO(){return JQ??VQ}function ZQ(t){if(!t)return!1;let e;try{e=new URL(t).hostname}catch{return!1}return YQ.has(e)||e.startsWith("127.")?!0:QQ.some(n=>e===n.slice(1)||e.endsWith(n))}function PO(t){if(ZQ(t))return;let e=n=>{let r=XP(n);r!==void 0&&Vo.update(r)};return RO(globalThis.fetch,void 0,e,Vo)}var JQ,YQ,QQ,nw=h(()=>{"use strict";ua();tb();IO();JQ=null;YQ=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","chatgpt.com"]),QQ=[".chatgpt.com"]});async function*rw(t,e){let n=0;for(;;){let r=Wu(),o=Date.now(),s,i=null;for(let d=0;;d++)try{s=await e.createStream(t.controller.signal);break}catch(u){if(t.controller.signal.aborted)return null;if(ep(u)&&d<bO){let p=Jb(u),f=p??zb(d);if(q(t.traceWriter,{phase:"rate_limit",durationMs:f,resolvedModel:t.currentModel,metadata:{source:"connection",reason:p!==void 0?"retry-after":"backoff",attempt:d}}),await We(f,t.controller.signal),t.controller.signal.aborted)return null;continue}i=u;break}if(i!==null)return yield{type:"error",error:e.clarifyError(i)},null;let a=null,c=!1;try{for await(let d of cs(s,t.controller.signal)){if(t.isClosed())return null;for(let u of e.translate(d,r))c||(c=!0,q(t.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-o,resolvedModel:t.currentModel})),yield u}}catch(d){if(t.controller.signal.aborted)return null;if(tp(d)&&n<wO){n++,yield{type:"stream.retry",sessionId:t.initSessionId};let u=Jb(d),p=u??zb(n-1);if(q(t.traceWriter,{phase:"rate_limit",durationMs:p,resolvedModel:t.currentModel,metadata:{source:"stream",reason:u!==void 0?"retry-after":"backoff",attempt:n}}),await We(p,t.controller.signal),t.controller.signal.aborted)return null;continue}a=d}if(a!==null)return yield{type:"error",error:e.clarifyError(a)},null;if(t.controller.signal.aborted)return null;let l=G0(r)&&r.toolCallsByIndex.size>0;return r.finishReason===null&&r.assistantText.length===0&&!l?(yield{type:"error",error:new ct("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:l}}}var MO=h(()=>{"use strict";J();Yu();Un();Ta();se();ls()});function OO(t){if(t instanceof Pa||ep(t)||tp(t))return!1;let e=zn(t);return e!==void 0&&e9.has(e)}var e9,DO=h(()=>{"use strict";ls();Zu();e9=new Set([400,404,405,415,422,501])});import{randomUUID as n9}from"node:crypto";function FO(t,e,n={}){let r=Xn(t.apiKey,n.authDeps,t.forceChatgptOAuth??!1),o=n.sessionIdOverride??t.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=typeof t.model=="string"?t.model:"gpt-4o-mini",i=_e(s)??s,a={auth:r,model:i,synthesizedSessionId:o,promptStream:e,config:t};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),t.traceWriter!==void 0&&(a.traceWriter=t.traceWriter),new mp(a)}var ow,mp,sw=h(()=>{"use strict";J();xo();xb();Bt();lt();Rb();ga();Ib();ie();ka();B0();mr();Ta();Fb();Nb();Gu();L();Hu();Ao();Ub();se();Ra();cO();Zu();ls();Yb();Zb();qr();Ma();_O();ds();Hn();Ca();AO();nw();MO();Xb();ls();nw();Ca();DO();ow="openai-compatible",mp=class{client;opts;initSessionId;toolDispatcher;onPermissionMode;onCwdChange;openAITools;wireMode;useOpenAIPricing;traceWriter;priorTurns=[];currentModel;currentPermissionMode;responsesCompactionUnavailable=!1;abort=new os;closed=!1;lastUsage=null;autoCompactThreshold;constructor(e){if(this.opts=e,this.initSessionId=e.synthesizedSessionId,this.currentModel=e.model,this.currentPermissionMode=Gb(e.config.permissionMode),this.toolDispatcher=e.toolDispatcher,this.onPermissionMode=e.onPermissionMode,this.onCwdChange=e.onCwdChange,this.traceWriter=e.traceWriter,this.autoCompactThreshold=bi(e.config.autoCompact,e.model),this.toolDispatcher){let s=this.toolDispatcher;Array.isArray(s.toolDefs)&&s.toolDefs.length>0&&(this.openAITools=X0(s.toolDefs))}let n=(e.useResponsesApi??!1)||Z0(k.AFK_OPENAI_USE_RESPONSES),r=eO(e.auth,n);this.wireMode=r.mode,this.useOpenAIPricing=r.baseURL===void 0&&e.baseURL===void 0||Ob(e.model)&&e.config.forceXaiOAuth!==!0;let o=e.config.resumeHistory?.at(-1);if(o?.inputTokens!==void 0&&o.inputTokens>0&&(this.lastUsage={inputTokens:o.inputTokens,stopReason:null,resultSubtype:"success",isError:!1}),e.auth.apiKey===null)this.client=null;else{let s=CO(),i={apiKey:e.auth.apiKey},a=r.baseURL??e.baseURL;a!==void 0&&(i.baseURL=a),r.headers!==void 0?i.defaultHeaders=r.headers:e.defaultHeaders!==void 0&&(i.defaultHeaders=e.defaultHeaders);let c=PO(a);c!==void 0&&(i.fetch=c),this.client=s(i)}}activeOpenAITools(){if(!this.openAITools)return;if(this.currentPermissionMode==="plan")return this.openAITools;let e=this.openAITools.filter(n=>n.function.name!==yt);return e.length>0?e: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:ow}},this.opts.auth.apiKey===null){yield{type:"error",error:new Error(Cb(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===$b)break;let o=r;if(o.done)break;if(yield*this.runTurn(o.value.content),this.autoCompactThreshold!==void 0&&!this.closed){let s=this.lastUsage,i=sn(this.currentModel);if(s!==null&&i>0){let a=Ee(s);if(gi(a,i,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(c){if(!(c instanceof Z))throw c}}}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}async*runTurn(e){let n=this.abort.begin();if(n.signal.aborted)return;let r=Date.now(),o=n9(),s=new ts(n.signal,this.traceWriter,"openai-compatible");try{yield*this._runTurnInner(e,n,r,o)}finally{s.finish(Date.now()-r)}}async*_runTurnInner(e,n,r,o){let s=kl(this.currentModel),i=EO(this.lastUsage,this.currentModel,this.opts.config.maxOutputTokens,this.opts.config.model??this.currentModel);if(i){this.abort.clear(n),yield{type:"error",error:i};return}this.priorTurns.push({role:"user",content:$0(e,{vision:s,model:this.currentModel})});let a={stopReason:null,resultSubtype:"success",isError:!1},c="",l="",d=up(this.opts.config.maxToolUseIterations),u=this.opts.config.softDeadlineMs??0,p=null,f=0,m=0,g=[];for(;;){if(n.signal.aborted){this.abort.clear(n),yield*this.finishTurn(a,r);return}let b=yield*this.runIteration(n,s,p);if(b===null){this.abort.clear(n),(n.signal.aborted||this.closed)&&(yield*this.finishTurn(a,r));return}let S=q0(b.state,this.useOpenAIPricing?this.currentModel:void 0);if(a=wa(a,S),a.contextWindowTokens=(S.inputTokens??0)+(S.outputTokens??0),this.lastUsage=a,b.text.length>0&&(c=b.text),l=b.state.reasoningText,!b.needsToolDispatch){Vt(b.state.finishReason)&&(g=va(b.state).map(x=>x.name));break}if(p!==null)break;let T=yield*this.dispatchAndAppend(b.state,n.signal,s);if(T){this.abort.clear(n),yield{type:"error",error:new So(T.content)};return}f+=1;{let x=va(b.state);m+=x.length;let I=x.at(-1),C=I?.name,v;try{v=I?JSON.parse(I.argumentsRaw||"{}"):void 0}catch{v=void 0}let E=I?`${I.name}${Jn(I.name,v)}`:"unknown";yield{type:"progress",progress:{taskId:o,description:"Working",summary:`${fp(f,d)}: ${E}`,lastToolName:C,totalTokens:a.totalTokens??0,toolUses:m,durationMs:Date.now()-r},sessionId:this.initSessionId}}if(n.signal.aborted){this.abort.clear(n),yield*this.finishTurn(a,r);return}let _=pp(f,d),A=Iu(r,u);if(_||A){p=_?Mt:Ct;continue}}if(this.abort.clear(n),c.length>0){let b={role:"assistant",content:c};l.length>0&&(b.reasoning_content=l),this.priorTurns.push(b)}let y=Vt(a.stopReason)?Cu(g,a.stopReason,{canIncreaseOutputLimit:!(this.opts.auth.source==="chatgpt-oauth"&&a.stopReason==="max_output_tokens")}):null;c.length>0?yield{type:"assistant.message",text:y?`${c}
1202
1202
 
@@ -1403,7 +1403,7 @@ ${e}`:s,a=new V({parentAbortSignal:n?.abortSignal,...r?.traceWriter!==void 0?{tr
1403
1403
  `)}return c(o,[],0),i.sort((l,d)=>l.name<d.name?-1:l.name>d.name?1:0),Xa.set(n,i),i}var cee,ef,Xa,dee,SN=h(()=>{"use strict";gs();uw();L();at();ms();cee=10,ef=1e3,Xa=new Map;Tp(()=>Xa.clear());dee=/[\u0000-\u001F\u007F-\u009F]/});import{existsSync as uee,readFileSync as pee}from"fs";import{join as fee}from"path";function kN(t){let e=fee(t,".claude-plugin","plugin.json");if(!uee(e))return{name:null,version:null};try{let n=JSON.parse(pee(e,"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 vN=h(()=>{"use strict"});import{readFileSync as mee}from"node:fs";import{join as gee}from"node:path";function gp(t,e){let n=Sa(t,e),r=e?.excludeName,s=(r!==void 0&&r.length>0?n.filter(a=>a.name!==r&&!a.name.endsWith(`:${r}`)):n).filter(a=>a.source!=="command");if(s.length===0)return"";let i=[];for(let a of s){let c=a.argumentHint?`${a.argumentHint}`:"",l=c?`- \`${a.name} ${c}\`: ${a.description}`:`- ${a.name}: ${a.description}`;i.push(l),a.whenToUse&&i.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.","",...i].join(`
1404
1404
  `)}function TN(t,e){return[...cD(t,e),...wN(t,e)]}function Sa(t,e){let n=[],r=new Set,o=k.AFK_INTERNAL==="1",s=Xi(Gi());qa(Fc(),"user"),cM("project"),qa(nv(e?.cwd),"project");for(let{dir:c,origin:l}of s.skillRoots)qa(c,l);for(let c of ab()){let l=fn(c);ib(l,o)&&(n.push({name:c,description:l.description,source:l.origin==="user"?"user":l.origin==="project"?"project":l.origin?.startsWith("imported:")?"imported":"builtin",argumentHint:l.argumentHint,whenToUse:l.whenToUse}),r.add(c),c.includes(":")&&r.add(c.split(":").pop()))}let i=t??tf(e),a=Ap();for(let c of i){if(c.type!=="local")continue;let l=TN(c.path,a);for(let d of l)!d.name||r.has(d.name)||ib({audience:d.audience},o)&&(n.push({name:d.name,description:d.description??`Skill from plugin at ${c.path}`,source:d.origin==="command"?"command":"plugin",argumentHint:d.argumentHint,whenToUse:d.whenToUse}),r.add(d.name))}return n}function ja(t,e){let n=new Map,r=t??tf(e),o=Ap();for(let s of r){if(s.type!=="local")continue;let i=TN(s.path,o);for(let a of i)a.name&&a.body&&a.body.length>0&&!n.has(a.name)&&n.set(a.name,{body:a.body,pluginPath:s.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 _N(t,e=()=>{}){let n=t??tf(),r=[],o=new Set;for(let s of n){if(s.type!=="local")continue;let i=kN(s.path).name;if(i!==null)for(let a of Ip(gee(s.path,"agents"))){let c=te(a),l;try{l=mee(a,"utf8")}catch(p){let f=te(p instanceof Error?p.message:String(p));e(`[afk] agents: cannot read ${c}: ${f}`);continue}let d=Zr(l,p=>e(`[afk] agents: ${c}: ${p}`));if(d===void 0)continue;let u=`${i}:${d.name}`;o.has(u)||(o.add(u),r.push({name:u,definition:d.definition,source:`plugin:${i}`,filePath:a,...d.bashReadOnly===!0?{bashReadOnly:!0}:{},...d.ignoredKeys!==void 0?{ignoredKeys:d.ignoredKeys}:{}}))}}return r}function tf(t){return[...mn(rv(t?.cwd)),...mn(),...mn(sv()),...Xi(Gi()).pluginRoots.flatMap(({dir:e,binary:n})=>mn(e,{trustAll:!0,sourceEnabled:QA(n)}))]}async function EN(){await yN(tf(),{pluginApi:{registerSkill:Je,listSkills:ab,getSkill:fn,loadSkillPrompts:ue,env:k,SubagentManager:V,describeFailure:Oe,discoverPluginSkillBodies:ja,getAgentFrameworkDir:vt,getSkillsDir:Fc,getSessionsDir:ce,getOrDeriveFacet:Kr,listSessionIds:ca,deriveSessionFacet:aa,loadStoredSession:ou}})}var Gn=h(()=>{"use strict";gN();Jt();bt();cS();ms();bN();gs();SN();vN();La();_w();at();we();Re();Ky();j();L();Sd()});function Is(t,e,n){let r=Ei({cwd:e,...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=[t.toolBase];return t.userSystem&&o.push(t.userSystem),o.push(t.memoryPrompt),t.workspacePrompt.length>0&&o.push(t.workspacePrompt),t.hotMemory.length>0&&o.push(t.hotMemory),o.push(r),t.manifest.length>0&&o.push(t.manifest),o.join(`
1405
1405
 
1406
- `)}var nf=h(()=>{"use strict";Ue()});function AN(t){let{config:e,cwd:n}=t,r=t.hasSkillExecutor?gp(void 0,{cwd:n,...typeof e.skillDispatchName=="string"&&e.skillDispatchName.length>0?{excludeName:e.skillDispatchName}:{}}):"",o=Lu(e.isSkillDispatch),s=Nu(t.readOnlyMemory),i=$u(t.workspaceEnabled),a={surface:t.surface,sessionId:e.sessionId,depth:e.depth,maxDepth:e.maxDepth,workspace:t.runtimeStateSource.getWorkspace()},c={toolBase:o,memoryPrompt:s,workspacePrompt:i,hotMemory:e.hotMemory??"",manifest:r,userSystem:t.userSystem};return{stableSystemPrefix:c,toolSystemAppend:Is(c,n,a)}}var xN=h(()=>{"use strict";Gn();Ab();nf()});import hee from"@anthropic-ai/sdk";function RN(t){if(t===void 0)return null;if(typeof t=="string")return t.length>0?t:null;if(typeof t=="object"&&t!==null&&"append"in t){let e=t.append;return e&&e.length>0?e:null}return null}function IN(t,e,n,r){let o=e.config,{localMode:s,token:i}=MP(o);if(!i||i.length===0)throw new Error(`${n} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let a=ko(i),{client:c,throttleQueue:l,systemPrefix:d,tokenRefresher:u}=zP({config:o,token:i,authMode:a,localMode:s,factory:t.providerFactory??du(),createClient:v=>new hee(v)}),p=RN(o.systemPrompt),f=typeof o.model=="string"&&o.model.length>0?_e(o.model)??o.model:r,m=El(o,f),g=o.permissionMode??"default";t.setCurrentPermissionMode(g),t.ensureSharedRoots(o.cwd),o.cwd&&t.setCurrentCwd(o.cwd);let y=t.getSharedReadRoots(),b=t.getSharedWriteRoots();o.readRoots&&y&&y.length<=1&&(y.length=0,y.push(...o.readRoots)),o.writeRoots&&b&&b.length<=1&&(b.length=0,b.push(...o.writeRoots));let{queryDispatcher:S,runtimeStateSource:T,toolDefs:_,resolvedSessionId:A}=oM({config:o,model:f,permissionMode:g,surface:t.surface,providerName:n,externalTools:t.externalTools,sharedReadRoots:y,sharedWriteRoots:b,getCwd:()=>t.getCurrentCwd()||o.cwd||process.cwd(),getMcpTools:()=>t.mcpManager?.getMcpTools()??[],getSubagents:()=>t.subagentExecutor?t.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]},getMintedSessionId:()=>t.getMintedSessionId(),setMintedSessionId:v=>{t.setMintedSessionId(v)},getPresenceSessionId:()=>t.getPresenceSessionId(),setPresenceSessionId:v=>{t.setPresenceSessionId(v)},buildDispatcher:(v,E)=>t.buildDispatcher(v,E)}),x=o.cwd||process.cwd(),{stableSystemPrefix:I,toolSystemAppend:C}=AN({config:o,cwd:x,surface:t.surface,readOnlyMemory:t.readOnlyMemory,workspaceEnabled:t.workspaceStore!==void 0,hasSkillExecutor:!!t.skillExecutor,runtimeStateSource:T,userSystem:p});return uM({prompt:e.prompt,options:{model:f,maxTokens:m,system:C},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:c,authMode:a,localMode:s,model:f,maxTokens:m,cwd:x,systemPrefix:d,throttleQueue:l,tokenRefresher:u,queryDispatcher:S,runtimeStateSource:T,toolDefs:_,resolvedSessionId:A,stableSystemPrefix:I,toolSystemAppend:C}}var lS=h(()=>{"use strict";xn();lt();Rl();OP();uu();JP();sM();xN();ma()});function CN(t){let e=t.initialUsageInputTokens!==void 0&&t.initialUsageInputTokens>0?{inputTokens:t.initialUsageInputTokens,stopReason:null,resultSubtype:"success",isError:!1}:null;return{messages:t.initialMessages?[...t.initialMessages]:[],currentModel:t.model,requestedModel:t.requestedModel??t.model,currentPermissionMode:t.permissionMode,userSystem:t.userSystem,toolDispatcher:t.toolDispatcher,lastUsage:e,closed:!1,autoCompactThreshold:t.autoCompactThreshold}}var PN=h(()=>{"use strict"});function za(t){if(typeof t?.baseUrl=="string"&&t.baseUrl.length>0)return!1;let e=k.AFK_DISABLE_PROMPT_CACHE;if(e===void 0||e.length===0)return!0;let n=e.toLowerCase();return!(n==="1"||n==="true"||n==="yes"||n==="on")}function oo(){let t=k.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":t==="1h"?"1h":yee}function rf(t){return za(t)&&oo()==="1h"}function MN(t,e){if(t.length===0)return t;let n=t[t.length-1],r=DN(n,e);return r===n?t:[...t.slice(0,-1),r]}function ON(t,e){if(t.length===0)return t;let n=t[t.length-1],r=bee(n,e);return r===n?t:[...t.slice(0,-1),r]}function bee(t,e){let n=t.content;if(typeof n=="string")return n.length===0?t:{...t,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:e}}]};if(!Array.isArray(n)||n.length===0)return t;let r=n[n.length-1],o=DN(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function DN(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}var yee,Cs=h(()=>{"use strict";L();yee="1h"});var dS=h(()=>{"use strict";Bo()});function _ee(t){let e=n=>n===void 0?void 0:n*uS;return{inputPerMTok:t.inputPerMTok*uS,outputPerMTok:t.outputPerMTok*uS,...e(t.cacheWrite5mPerMTok)!==void 0?{cacheWrite5mPerMTok:e(t.cacheWrite5mPerMTok)}:{},...e(t.cacheWrite1hPerMTok)!==void 0?{cacheWrite1hPerMTok:e(t.cacheWrite1hPerMTok)}:{},...e(t.cacheReadPerMTok)!==void 0?{cacheReadPerMTok:e(t.cacheReadPerMTok)}:{}}}function Eee(t){return t.responseSpeed??t.requestSpeed??"standard"}function Aee(t){return rs(t,FN,vee)}function pS(t,e,n,r,o,s,i={}){let a=Aee(t);if(!a)return;let c=Eee(i)==="fast"&&Tee.test(t)?_ee(a):a,l=1e6,d=Ke(e),u=Ke(n),p=Ke(r),f=Ke(o),m=d/l*c.inputPerMTok,g=u/l*c.outputPerMTok,y=c.cacheWrite5mPerMTok??c.inputPerMTok*wee,b=c.cacheWrite1hPerMTok??c.inputPerMTok*See,S=c.cacheReadPerMTok??c.inputPerMTok*kee,T=s??{ephemeral5m:f,ephemeral1h:0},_=Ke(T.ephemeral5m),A=Ke(T.ephemeral1h),x=Math.max(0,f-(_+A)),I=_/l*y+A/l*b+x/l*b,C=p/l*S;return m+g+I+C}var wee,See,kee,FN,vee,uS,Tee,fS=h(()=>{"use strict";ju();wee=1.25,See=2,kee=.1,FN=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}]]),vee=/-\d{8}$/,uS=2,Tee=/^claude-opus-(?:5|4-8)(?:-|$)/});function xee(t){let e=t.speed;return e==="fast"||e==="standard"?e:void 0}function Ree(t){let e=o=>Number.isFinite(o)&&o>=0?o:0,n=t.cache_creation;if(n)return{ephemeral5m:e(n.ephemeral_5m_input_tokens??0),ephemeral1h:e(n.ephemeral_1h_input_tokens??0)};let r=e(t.cache_creation_input_tokens??0);return oo()==="1h"?{ephemeral5m:0,ephemeral1h:r}:{ephemeral5m:r,ephemeral1h:0}}function mS(t,e,n,r){if(!t)return{stopReason:e??null};let o=xee(t),s={inputTokens:t.input_tokens,outputTokens:t.output_tokens,stopReason:e??null,raw:{...t,...o?{speed:o}:{}}};if(t.cache_read_input_tokens!=null&&(s.cachedInputTokens=t.cache_read_input_tokens),t.cache_creation_input_tokens!=null&&(s.cacheCreationTokens=t.cache_creation_input_tokens),s.totalTokens=(t.input_tokens??0)+(t.output_tokens??0),n){let i=pS(n,t.input_tokens??0,t.output_tokens??0,t.cache_read_input_tokens??0,t.cache_creation_input_tokens??0,Ree(t),{...r?{requestSpeed:r}:{},...o?{responseSpeed:o}:{}});i!==void 0&&(s.totalCostUsd=i)}return s}var LN=h(()=>{"use strict";Cs();fS()});var gS=h(()=>{"use strict";fS();LN();xb()});function Ja(t){return t>2147483647?2147483647:t}var hS=h(()=>{"use strict"});function of(){let t=k.AFK_MODEL_TTFB_TIMEOUT_MS;if(t===void 0||t.trim()==="")return NN;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?NN:Ja(e)}function $N(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?void 0:(t<Pee?t:Mee)+Cee}function UN(t,e){if(e<=0)return{signal:t,timedOut:()=>!1,firstByteSeen:()=>{},extend:()=>{},dispose:()=>{}};let n=new AbortController,r=AbortSignal.any([t,n.signal]),o=!1,s=!1,i=Date.now()+e,a,c=u=>{a=setTimeout(()=>{o=!0,n.abort(new Error(Iee))},Ja(u)),a.unref()};c(e);let l=()=>{s||(s=!0,clearTimeout(a))};return{signal:r,timedOut:()=>o,firstByteSeen:l,extend:u=>{s||o||typeof u!="number"||!Number.isFinite(u)||u<=0||(i+=u,clearTimeout(a),c(Math.max(1,i-Date.now())))},dispose:l}}var NN,Iee,Cee,Pee,Mee,sf=h(()=>{"use strict";L();hS();NN=18e4;Iee="model_ttfb_timeout",Cee=3e4,Pee=6e4,Mee=8e3});function jN(){let t=k.AFK_MODEL_STALL_TIMEOUT_MS;if(t===void 0||t.trim()==="")return BN;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?BN:Ja(e)}function WN(t){return t instanceof Error&&t.message===HN}function yS(t){return new Error(`Model stream stalled: no output for ${Math.round(t/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 KN(t,e,n){if(e<=0)return{signal:t,timedOut:()=>!1,progress:()=>{},dispose:()=>{}};let r=new AbortController,o=AbortSignal.any([t,r.signal]),s,i=!1,a=!1,c=u=>{if(!(a||i)){i=!0,s=void 0;try{n?.({stallTimeoutMs:e,elapsedSinceLastProgressMs:Date.now()-u})}catch{}r.signal.aborted||r.abort(new Error(HN))}};return{signal:o,timedOut:()=>i,progress:()=>{if(a||i)return;s!==void 0&&clearTimeout(s);let u=Date.now(),p=setTimeout(()=>c(u),e);p.unref(),s=p},dispose:()=>{a||(a=!0,s!==void 0&&clearTimeout(s),s=void 0)}}}var BN,HN,af=h(()=>{"use strict";L();hS();BN=12e5;HN="model_stream_stall_timeout"});function cf(t,e=Math.random){return t+Math.floor(e()*t*Lee)}function GN(t=Math.random){let e=Fee-qN;return qN+Math.floor(t()*e)}function XN(t){return t.type==="turn.completed"&&t.usage.stopReason===ot}function zN(t){let e=k.AFK_OVERLOAD_PAUSE_MS;if(e!==void 0&&e.trim()!==""){let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.min(Math.floor(n),Dee)}return t!==void 0&&Nee.has(t)?Oee:0}var bS,Oee,Dee,qN,Fee,Lee,Nee,Va=h(()=>{"use strict";L();Zo();Zo();bS="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.",Oee=600*1e3,Dee=7200*1e3,qN=60*1e3,Fee=120*1e3,Lee=.25;Nee=new Set(["cli","repl","telegram","web"])});function df(t){if(!Number.isFinite(t)||t<=0)return 0;let e=Math.floor(t*2/3);return Math.max(1,e)}function JN(t){if(!("status"in t))return!1;let e=t.status;return e===529||e===503}function Ya(t){if(t===null||typeof t!="object")return!1;let e=t;if(e.status===529||e.status===503)return!0;let n=e.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 lf,Ps=h(()=>{"use strict";lf=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*Uee(t,e,n){q(t.traceWriter,{phase:"ttfb_timeout",durationMs:Date.now()-e,metadata:{reason:"ttfb-timeout",source:"first-byte",resolvedModel:t.model,attempt:n}}),yield{type:"stream.retry",sessionId:t.ctx.sessionId}}async function*SS(t,{input:e,turn:n,retry:r,requestStartedAt:o}){return t==="ttfb"?(r.ttfbRetries+=1,yield*Uee(e,o,r.ttfbRetries),"continue"):t==="overload"?(r.overloadRetries+=1,q(e.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:r.overloadRetries}}),yield{type:"stream.retry",sessionId:e.ctx.sessionId},yield*VN(cf(5e3*Math.pow(2,r.overloadRetries-1)),e,n),e.signal.aborted?"terminated":"continue"):(r.streamIncompleteRetries+=1,q(e.traceWriter,{phase:"rate_limit",metadata:{reason:"stream-incomplete",source:"mid-stream",attempt:r.streamIncompleteRetries}}),yield{type:"stream.retry",sessionId:e.ctx.sessionId},yield*VN(1e3*Math.pow(2,r.streamIncompleteRetries-1),e,n),e.signal.aborted?"terminated":"continue")}async function*VN(t,e,n){await We(t,e.signal),e.signal.aborted&&(yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId})}var YN=h(()=>{"use strict";J();Un();Va();Ps()});function ZN(t){let e=t.fastModeController?.snapshotTurn({resolvedModelId:t.model,providerFamily:"anthropic-direct",hasCustomEndpoint:t.baseUrl!==void 0,executionPath:"top-level"}),n=e?.effective===!0,r=An(t.authMode,t.sessionId,t.requestId,t.effort!==void 0,rf(t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{}),n);return{decision:e,runInput:{client:t.client,messages:t.messages,system:t.system,tools:t.tools,toolDispatcher:t.toolDispatcher,model:t.model,maxTokens:t.maxTokens,headers:r,signal:t.signal,ctx:{sessionId:t.sessionId},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...n?{fastMode:!0}:{},...t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{},...t.maxToolUseIterations!==void 0?{maxToolUseIterations:t.maxToolUseIterations}:{},...t.softDeadlineMs!==void 0?{softDeadlineMs:t.softDeadlineMs}:{},...t.traceWriter?{traceWriter:t.traceWriter}:{},...t.subagentId!==void 0?{subagentId:t.subagentId}:{},...t.throttleQueue?{throttleQueue:t.throttleQueue}:{},...t.onUsageProgress?{onUsageProgress:t.onUsageProgress}:{},...t.beforeNextRound?{beforeNextRound:t.beforeNextRound}:{}}}}function uf(t,e){let n=t instanceof Error?t:new Error(String(t));if(!e||n.message.startsWith(QN))return n;let r=new Error(`${QN} ${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 s=Object.getOwnPropertyDescriptor(n,o);s!==void 0&&Object.defineProperty(r,o,s)}return r}var QN,kS=h(()=>{"use strict";xn();Cs();QN="[Fast mode requested; no standard-mode fallback will be attempted]"});async function*e$(t,e,n){let r=e.throttleQueue;if(!r)return await t;r.resetAttempts();let o=Symbol("create-done"),s=!1,i=t.then(a=>(s=!0,a),a=>{throw s=!0,a});for(;;){for(let c of r.takeAll())n?.(c.retryAfterMs),yield{type:"rate_limit",sessionId:e.ctx.sessionId,status:c.status,attempt:c.attempt,...c.retryAfterMs!==void 0?{retryAfterMs:c.retryAfterMs}:{}};if(s)return await i;await Promise.race([i.then(()=>o,()=>o),r.waitForItem().then(()=>{})])}}var t$=h(()=>{"use strict"});function n$(t,e){try{let n=[];for(let r=0;r<t.length;r++){let o=t[r];if(o.role!=="assistant"||typeof o.content=="string")continue;let s=o.content;for(let i=0;i<s.length;i++){let a=s[i];if(a.type==="thinking"){let c=a;(!c.thinking||!c.signature)&&n.push({msgIdx:r,blockIdx:i,thinking:c.thinking?`(${c.thinking.length} chars)`:"(empty)",sigLen:c.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",e.message),console.error(`[afk] messages.length=${t.length}, invalid thinking blocks:`,n.length>0?JSON.stringify(n):"none found (cause may be elsewhere)")}catch{}}var r$=h(()=>{"use strict"});function Bee(t){let{name:e,description:n,input_schema:r}=t;return{name:e,...n!==void 0?{description:n}:{},input_schema:r}}async function jee(t,e,n,r,o){for(let s=0;;s++){if(s>0){let i=cf(5e3*Math.pow(2,s-1));if(await We(i,o),o.aborted)throw new Error("aborted")}try{return await Promise.resolve(t.messages.create(e,{headers:n,signal:r}))}catch(i){if(r.aborted)throw i;let a=i instanceof Error?i:new Error(String(i));if(JN(a)){if(s<3)continue;throw new pf}throw a}}}function Hee(t){return{model:t.model,max_tokens:t.maxTokens,messages:t.messages,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0?{tools:t.tools.map(Bee)}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{output_config:{effort:t.effort}}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.fastMode===!0?{speed:"fast"}:{}}}async function*o$({input:t,turn:e,retry:n,ttfbTimeoutMs:r,stallTimeoutMs:o}){let s=za({baseUrl:t.baseUrl})?ON(t.messages,oo()):t.messages,i=Hee({...t,messages:s,tools:e.windDownReason!==null?null:t.tools}),a=Date.now(),c=UN(t.signal,r),l=KN(c.signal,o,d=>{q(t.traceWriter,{phase:"idle_watchdog_fired",durationMs:d.elapsedSinceLastProgressMs,resolvedModel:t.model,metadata:{source:"model-stream",stallTimeoutMs:d.stallTimeoutMs,elapsedSinceLastProgressMs:d.elapsedSinceLastProgressMs}})});try{return{kind:"opened",events:yield*e$(jee(t.client,i,t.headers,l.signal,t.signal),t,u=>{let p=$N(u);p!==void 0&&c.extend(p)}),ttfb:c,stall:l,requestStartedAt:a}}catch(d){if(c.timedOut()&&!t.signal.aborted&&n.canRetryTtfb())return c.dispose(),l.dispose(),{kind:"retry-ttfb",requestStartedAt:a};if(c.dispose(),l.dispose(),t.signal.aborted)return yield{type:"turn.completed",usage:e.terminalUsage(),sessionId:t.ctx.sessionId},{kind:"terminated"};if(d instanceof pf)return{kind:"overload-exhausted"};let u=uf(d,t.fastMode===!0);return u.message.includes("thinking")&&n$(t.messages,u),yield{type:"error",error:u},{kind:"terminated"}}}var pf,s$=h(()=>{"use strict";kS();Cs();J();Un();sf();af();Va();Ps();t$();r$();pf=class extends Error{constructor(){super("Connection-phase overload budget exhausted"),this.name="ConnectionOverloadExhaustedError"}}});function i$(t,e){return t||e!==null}function a$(){return new ct("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 c$=h(()=>{"use strict";se()});function Wee(t){let e=t.trim();if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function Kee(t,e,n){let r=[],o=[];for(let a of t)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:Wee(a.partialJson)}));let s=a=>a.type==="tool_use",i=r.filter(s);return{stopReason:e,assistantBlocks:r,toolUseBlocks:i,usage:n,text:o.join("")}}async function*l$(t,e,n){let r=[],o=null,s=null,i=!1,a=!!k.AFK_TELEGRAM_TRACE;try{a&&console.log("[translate] starting SDK event iteration");for await(let c of t){switch(a&&console.log("[translate] SDK evt:",c.type),c.type){case"message_start":{let l=c.message?.usage;l&&(s={...l});break}case"content_block_start":{let l=c.content_block;l.type==="text"?r[c.index]={kind:"text",text:""}:l.type==="thinking"?r[c.index]={kind:"thinking",thinking:"",signature:""}:l.type==="redacted_thinking"?r[c.index]={kind:"redacted_thinking",data:l.data}:l.type==="tool_use"&&(r[c.index]={kind:"tool_use",id:l.id,name:l.name,partialJson:""},yield{kind:"event",event:{type:"tool.use.start",toolUseId:l.id,toolName:l.name,toolInput:" \u2026",pending:!0,sessionId:e.sessionId}});break}case"content_block_delta":{let l=r[c.index],d=c.delta;d.type==="text_delta"?(l&&l.kind==="text"&&(l.text+=d.text),yield{kind:"event",event:{type:"delta.text",text:d.text,sessionId:e.sessionId}}):d.type==="input_json_delta"?(l&&l.kind==="tool_use"&&(l.partialJson+=d.partial_json),n?.()):d.type==="thinking_delta"?(l&&l.kind==="thinking"&&(l.thinking+=d.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:d.thinking,sessionId:e.sessionId}}):(d.type==="signature_delta"&&l&&l.kind==="thinking"&&(l.signature=d.signature),n?.());break}case"content_block_stop":{let l=r[c.index];l&&l.kind==="tool_use"&&(yield{kind:"event",event:{type:"tool.use",summary:l.name,toolUseIds:[l.id],sessionId:e.sessionId}});break}case"message_delta":{c.delta&&c.delta.stop_reason!==void 0&&(o=c.delta.stop_reason);let l=c.usage;l&&(s!==null?(s.output_tokens=l.output_tokens,l.cache_creation_input_tokens!=null&&(s.cache_creation_input_tokens=l.cache_creation_input_tokens),l.cache_read_input_tokens!=null&&(s.cache_read_input_tokens=l.cache_read_input_tokens),l.input_tokens!=null&&(s.input_tokens=l.input_tokens)):s={cache_creation:null,cache_creation_input_tokens:l.cache_creation_input_tokens??null,cache_read_input_tokens:l.cache_read_input_tokens??null,inference_geo:null,input_tokens:l.input_tokens??0,output_tokens:l.output_tokens,server_tool_use:null,service_tier:null});break}case"message_stop":{i=!0;break}default:break}if(i)break}a&&console.log("[translate] SDK iteration ended naturally, stopped=",i)}catch(c){a&&console.log("[translate] SDK iteration threw:",c.message),yield{kind:"event",event:{type:"error",error:c instanceof Error?c:new Error(String(c))}};return}if(!i$(i,o)){yield{kind:"event",event:{type:"error",error:a$()}};return}a&&console.log("[translate] yielding turn-result"),yield{kind:"turn-result",result:Kee(r,o,s)}}var d$=h(()=>{"use strict";L();c$()});async function*u$({events:t,input:e,turn:n,retry:r,ttfb:o,stall:s,stallTimeoutMs:i,requestStartedAt:a}){let c=null,l=!1,d=!1,u=!1,p=!1,f=!1,m=!1;try{k.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let g of l$(cs(t,e.signal),e.ctx,()=>s.progress()))if(!m&&(g.kind==="turn-result"||g.event.type!=="error")&&(m=!0,o.firstByteSeen(),q(e.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-a,resolvedModel:e.model})),s.progress(),k.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",g.kind,g.kind==="event"?g.event.type:""),g.kind==="event"){if(g.event.type==="error"){if(o.timedOut()&&!e.signal.aborted&&r.canRetryTtfb()&&!m){d=!0;break}if(s.timedOut()&&!e.signal.aborted){yield{type:"error",error:yS(i)},l=!0;break}if(Ya(g.event.error)&&r.canRetryOverload()&&!e.signal.aborted){u=!0;break}if(Ya(g.event.error)&&!e.signal.aborted){f=!0;break}if(e.signal.aborted)break;if(g.event.error instanceof ct&&r.canRetryStreamIncomplete()&&!e.signal.aborted){p=!0;break}yield g.event,l=!0;break}yield g.event}else{c=g.result;break}k.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",c?"set":"null")}catch(g){if(o.timedOut()&&!e.signal.aborted&&r.canRetryTtfb()&&!m)o.dispose(),s.dispose(),d=!0;else{if(o.dispose(),s.dispose(),e.signal.aborted)return yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId},{kind:"terminated"};let y=g instanceof Error?g:new Error(String(g));if((s.timedOut()||WN(y))&&!e.signal.aborted)return yield{type:"error",error:yS(i)},{kind:"terminated"};if(Ya(y)&&r.canRetryOverload()&&!e.signal.aborted)u=!0;else if(Ya(y)&&!e.signal.aborted)f=!0;else return yield{type:"error",error:y},{kind:"terminated"}}}return o.dispose(),s.dispose(),d?{kind:"retry",reason:"ttfb"}:u?{kind:"retry",reason:"overload"}:p?{kind:"retry",reason:"stream-incomplete"}:f?{kind:"overload-exhausted"}:l?{kind:"translator-errored"}:{kind:"streamed",turnResult:c}}var p$=h(()=>{"use strict";d$();se();Yu();J();L();af();Ps()});async function*f$(t,e,n){let r=[],o=new Map;for(let i of t.toolUseBlocks)r.push({id:i.id,name:i.name,input:i.input,signal:e.signal}),o.set(i.id,Date.now()),br(e.traceWriter,ip({toolUseId:i.id,name:i.name,input:i.input,subagentId:e.subagentId})),yield{type:"tool.use.start",toolUseId:i.id,toolName:i.name,toolInput:Jn(i.name,i.input),toolInputRaw:op(i.input),toolInputCapture:k.AFK_CAPTURE_SUBAGENT_OUTPUT==="1"?sp(i.input):void 0,sessionId:e.ctx.sessionId};if(e.signal.aborted){let i=r.map(a=>({type:"tool_result",tool_use_id:a.id,content:"Tool call aborted",is_error:!0}));return e.messages.push({role:"user",content:i}),yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId},{kind:"aborted"}}let s;if(e.toolDispatcher.executeBatch)s=yield*lp(async i=>{try{return await e.toolDispatcher.executeBatch(r,a=>{i({type:"tool.activity",activeCount:a.length,activeToolUseIds:[...a],sessionId:e.ctx.sessionId})})}catch(a){return r.map(()=>({content:`Tool batch execution failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}))}});else{s=[];for(let i of r){if(e.signal.aborted){s.push({content:"Tool call aborted",isError:!0,failureClass:Ne(e.signal)});continue}try{s.push(await e.toolDispatcher.execute(i))}catch(a){let c=a instanceof Error?a.message:String(a);s.push({content:`Tool execution threw: ${c}`,isError:!0})}}}return{kind:"dispatched",calls:r,results:s,startTimes:o}}var m$=h(()=>{"use strict";In();J();ew();L();Ma();cp();tw()});async function*g$(t,e,n,r){let o=[];for(let c=0;c<t.length;c++){let l=t[c],d=e[c],u=n.get(l.id),p=typeof u=="number"?Date.now()-u:0,f=d.truncated===!0||d.content.includes("[output truncated");br(r.traceWriter,ap({toolUseId:l.id,name:l.name,result:d,truncated:f,durationMs:p,subagentId:r.subagentId})),yield{type:"tool.output",toolUseId:l.id,toolName:l.name,content:d.content,...d.isError===!0?{isError:!0}:{},...f?{truncated:!0}:{},...d.capturePath!==void 0?{capturePath:d.capturePath}:{},...d.incomplete===!0?{incomplete:!0}:{},...d.incompleteReason?{incompleteReason:d.incompleteReason}:{},...typeof d.batchIndex=="number"&&typeof d.batchSize=="number"?{batchIndex:d.batchIndex,batchSize:d.batchSize}:{},...d.failureClass?{failureClass:d.failureClass}:{},durationMs:d.durationMs!==void 0?d.durationMs:p,...d.exitCode!==void 0?{exitCode:d.exitCode}:{},sessionId:r.ctx.sessionId},d.render?.diff&&(yield{type:"tool.diff",toolUseId:l.id,diff:d.render.diff,sessionId:r.ctx.sessionId});let{content:m,isError:g,image:y}=d,b=y!==void 0?[{type:"image",source:{type:"base64",media_type:y.mediaType,data:y.data}},...m.length>0?[{type:"text",text:m}]:[]]:m;o.push({type:"tool_result",tool_use_id:l.id,content:b,...g===!0?{is_error:!0}:{}})}let s=e.flatMap(c=>c.harnessUserMessage?.kind==="queued_user_message"?[{type:"text",text:c.harnessUserMessage.text}]:[]),i={role:"user",content:[...o,...s]};r.messages.push(i);let a=e.find(c=>c.failureClass===Co);return a?(yield{type:"error",error:new So(a.content)},"denial-tripped"):"committed"}var h$=h(()=>{"use strict";J();cp();Ci();se()});async function*y$(t,e,n,r,o){let s=e.messages.length;e.messages.push({role:"assistant",content:t.assistantBlocks});try{n.toolCallCount+=t.toolUseBlocks.length;let d=yield*f$(t,e,n);if(d.kind==="aborted"||(yield*g$(d.calls,d.results,d.startTimes,e))==="denial-tripped")return"terminated"}catch(d){throw e.messages.splice(s),d}n.iterations+=1;let i=t.toolUseBlocks[t.toolUseBlocks.length-1],a=i?`${i.name}${Jn(i.name,i.input)}`:"unknown";if(yield{type:"progress",progress:{taskId:n.taskId,description:"Working",summary:`${fp(n.iterations,r)}: ${a}`,lastToolName:i?.name,totalTokens:n.usage.totalTokens??0,toolUses:n.toolCallCount,durationMs:Date.now()-n.startedAt},sessionId:e.ctx.sessionId},n.windDownReason!==null)return yield{type:"turn.completed",usage:n.withDuration({...n.usage,stopReason:n.windDownReason}),sessionId:e.ctx.sessionId},"terminated";let c=pp(n.iterations,r),l=Iu(n.startedAt,o);if(c||l){let d=c?dp:xu,u=e.messages[e.messages.length-1];u!==void 0&&u.role==="user"&&Array.isArray(u.content)&&u.content.push({type:"text",text:d}),n.windDownReason=c?Mt:Ct}return"continue"}var b$=h(()=>{"use strict";Ma();Hn();ds();m$();h$()});function*w$(t,e,n){if(t.stopReason==="refusal"){t.text.length>0&&(yield{type:"assistant.message",text:t.text,sessionId:e.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:e.ctx.sessionId},yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId};return}let r=Vt(t.stopReason)?Cu(t.toolUseBlocks.map(s=>s.name),t.stopReason):null;t.text.length>0?(yield{type:"assistant.message",text:r?`${t.text}
1406
+ `)}var nf=h(()=>{"use strict";Ue()});function AN(t){let{config:e,cwd:n}=t,r=t.hasSkillExecutor?gp(void 0,{cwd:n,...typeof e.skillDispatchName=="string"&&e.skillDispatchName.length>0?{excludeName:e.skillDispatchName}:{}}):"",o=Lu(e.isSkillDispatch),s=Nu(t.readOnlyMemory),i=$u(t.workspaceEnabled),a={surface:t.surface,sessionId:e.sessionId,depth:e.depth,maxDepth:e.maxDepth,workspace:t.runtimeStateSource.getWorkspace()},c={toolBase:o,memoryPrompt:s,workspacePrompt:i,hotMemory:e.hotMemory??"",manifest:r,userSystem:t.userSystem};return{stableSystemPrefix:c,toolSystemAppend:Is(c,n,a)}}var xN=h(()=>{"use strict";Gn();Ab();nf()});import hee from"@anthropic-ai/sdk";function RN(t){if(t===void 0)return null;if(typeof t=="string")return t.length>0?t:null;if(typeof t=="object"&&t!==null&&"append"in t){let e=t.append;return e&&e.length>0?e:null}return null}function IN(t,e,n,r){let o=e.config,{localMode:s,token:i}=MP(o);if(!i||i.length===0)throw new Error(`${n} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let a=ko(i),{client:c,throttleQueue:l,systemPrefix:d,tokenRefresher:u}=zP({config:o,token:i,authMode:a,localMode:s,factory:t.providerFactory??du(),createClient:v=>new hee(v)}),p=RN(o.systemPrompt),f=typeof o.model=="string"&&o.model.length>0?_e(o.model)??o.model:r,m=El(o,f),g=o.permissionMode??"default";t.setCurrentPermissionMode(g),t.ensureSharedRoots(o.cwd),o.cwd&&t.setCurrentCwd(o.cwd);let y=t.getSharedReadRoots(),b=t.getSharedWriteRoots();o.readRoots&&y&&y.length<=1&&(y.length=0,y.push(...o.readRoots)),o.writeRoots&&b&&b.length<=1&&(b.length=0,b.push(...o.writeRoots));let{queryDispatcher:S,runtimeStateSource:T,toolDefs:_,resolvedSessionId:A}=oM({config:o,model:f,permissionMode:g,surface:t.surface,providerName:n,externalTools:t.externalTools,sharedReadRoots:y,sharedWriteRoots:b,getCwd:()=>t.getCurrentCwd()||o.cwd||process.cwd(),getMcpTools:()=>t.mcpManager?.getMcpTools()??[],getSubagents:()=>t.subagentExecutor?t.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]},getMintedSessionId:()=>t.getMintedSessionId(),setMintedSessionId:v=>{t.setMintedSessionId(v)},getPresenceSessionId:()=>t.getPresenceSessionId(),setPresenceSessionId:v=>{t.setPresenceSessionId(v)},buildDispatcher:(v,E)=>t.buildDispatcher(v,E)}),x=o.cwd||process.cwd(),{stableSystemPrefix:I,toolSystemAppend:C}=AN({config:o,cwd:x,surface:t.surface,readOnlyMemory:t.readOnlyMemory,workspaceEnabled:t.workspaceStore!==void 0,hasSkillExecutor:!!t.skillExecutor,runtimeStateSource:T,userSystem:p});return uM({prompt:e.prompt,options:{model:f,maxTokens:m,system:C},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:c,authMode:a,localMode:s,model:f,maxTokens:m,cwd:x,systemPrefix:d,throttleQueue:l,tokenRefresher:u,queryDispatcher:S,runtimeStateSource:T,toolDefs:_,resolvedSessionId:A,stableSystemPrefix:I,toolSystemAppend:C}}var lS=h(()=>{"use strict";xn();lt();Rl();OP();uu();JP();sM();xN();ma()});function CN(t){let e=t.initialUsageInputTokens!==void 0&&t.initialUsageInputTokens>0?{inputTokens:t.initialUsageInputTokens,stopReason:null,resultSubtype:"success",isError:!1}:null;return{messages:t.initialMessages?[...t.initialMessages]:[],currentModel:t.model,requestedModel:t.requestedModel??t.model,currentPermissionMode:t.permissionMode,userSystem:t.userSystem,toolDispatcher:t.toolDispatcher,lastUsage:e,closed:!1,autoCompactThreshold:t.autoCompactThreshold}}var PN=h(()=>{"use strict"});function za(t){if(typeof t?.baseUrl=="string"&&t.baseUrl.length>0)return!1;let e=k.AFK_DISABLE_PROMPT_CACHE;if(e===void 0||e.length===0)return!0;let n=e.toLowerCase();return!(n==="1"||n==="true"||n==="yes"||n==="on")}function oo(){let t=k.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":t==="1h"?"1h":yee}function rf(t){return za(t)&&oo()==="1h"}function MN(t,e){if(t.length===0)return t;let n=t[t.length-1],r=DN(n,e);return r===n?t:[...t.slice(0,-1),r]}function ON(t,e){if(t.length===0)return t;let n=t[t.length-1],r=bee(n,e);return r===n?t:[...t.slice(0,-1),r]}function bee(t,e){let n=t.content;if(typeof n=="string")return n.length===0?t:{...t,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:e}}]};if(!Array.isArray(n)||n.length===0)return t;let r=n[n.length-1],o=DN(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function DN(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}var yee,Cs=h(()=>{"use strict";L();yee="1h"});var dS=h(()=>{"use strict";Bo()});function _ee(t){let e=n=>n===void 0?void 0:n*uS;return{inputPerMTok:t.inputPerMTok*uS,outputPerMTok:t.outputPerMTok*uS,...e(t.cacheWrite5mPerMTok)!==void 0?{cacheWrite5mPerMTok:e(t.cacheWrite5mPerMTok)}:{},...e(t.cacheWrite1hPerMTok)!==void 0?{cacheWrite1hPerMTok:e(t.cacheWrite1hPerMTok)}:{},...e(t.cacheReadPerMTok)!==void 0?{cacheReadPerMTok:e(t.cacheReadPerMTok)}:{}}}function Eee(t){return t.responseSpeed??t.requestSpeed??"standard"}function Aee(t){return rs(t,FN,vee)}function pS(t,e,n,r,o,s,i={}){let a=Aee(t);if(!a)return;let c=Eee(i)==="fast"&&Tee.test(t)?_ee(a):a,l=1e6,d=Ke(e),u=Ke(n),p=Ke(r),f=Ke(o),m=d/l*c.inputPerMTok,g=u/l*c.outputPerMTok,y=c.cacheWrite5mPerMTok??c.inputPerMTok*wee,b=c.cacheWrite1hPerMTok??c.inputPerMTok*See,S=c.cacheReadPerMTok??c.inputPerMTok*kee,T=s??{ephemeral5m:f,ephemeral1h:0},_=Ke(T.ephemeral5m),A=Ke(T.ephemeral1h),x=Math.max(0,f-(_+A)),I=_/l*y+A/l*b+x/l*b,C=p/l*S;return m+g+I+C}var wee,See,kee,FN,vee,uS,Tee,fS=h(()=>{"use strict";ju();wee=1.25,See=2,kee=.1,FN=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}]]),vee=/-\d{8}$/,uS=2,Tee=/^claude-opus-(?:5|4-8)(?:-|$)/});function xee(t){let e=t.speed;return e==="fast"||e==="standard"?e:void 0}function Ree(t){let e=o=>Number.isFinite(o)&&o>=0?o:0,n=t.cache_creation;if(n)return{ephemeral5m:e(n.ephemeral_5m_input_tokens??0),ephemeral1h:e(n.ephemeral_1h_input_tokens??0)};let r=e(t.cache_creation_input_tokens??0);return oo()==="1h"?{ephemeral5m:0,ephemeral1h:r}:{ephemeral5m:r,ephemeral1h:0}}function mS(t,e,n,r){if(!t)return{stopReason:e??null};let o=xee(t),s={inputTokens:t.input_tokens,outputTokens:t.output_tokens,stopReason:e??null,raw:{...t,...o?{speed:o}:{}}};if(t.cache_read_input_tokens!=null&&(s.cachedInputTokens=t.cache_read_input_tokens),t.cache_creation_input_tokens!=null&&(s.cacheCreationTokens=t.cache_creation_input_tokens),s.totalTokens=(t.input_tokens??0)+(t.output_tokens??0),n){let i=pS(n,t.input_tokens??0,t.output_tokens??0,t.cache_read_input_tokens??0,t.cache_creation_input_tokens??0,Ree(t),{...r?{requestSpeed:r}:{},...o?{responseSpeed:o}:{}});i!==void 0&&(s.totalCostUsd=i)}return s}var LN=h(()=>{"use strict";Cs();fS()});var gS=h(()=>{"use strict";fS();LN();xb()});function Ja(t){return t>2147483647?2147483647:t}var hS=h(()=>{"use strict"});function of(){let t=k.AFK_MODEL_TTFB_TIMEOUT_MS;if(t===void 0||t.trim()==="")return NN;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?NN:Ja(e)}function $N(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?void 0:(t<Pee?t:Mee)+Cee}function UN(t,e){if(e<=0)return{signal:t,timedOut:()=>!1,firstByteSeen:()=>{},extend:()=>{},dispose:()=>{}};let n=new AbortController,r=AbortSignal.any([t,n.signal]),o=!1,s=!1,i=Date.now()+e,a,c=u=>{a=setTimeout(()=>{o=!0,n.abort(new Error(Iee))},Ja(u)),a.unref()};c(e);let l=()=>{s||(s=!0,clearTimeout(a))};return{signal:r,timedOut:()=>o,firstByteSeen:l,extend:u=>{s||o||typeof u!="number"||!Number.isFinite(u)||u<=0||(i+=u,clearTimeout(a),c(Math.max(1,i-Date.now())))},dispose:l}}var NN,Iee,Cee,Pee,Mee,sf=h(()=>{"use strict";L();hS();NN=18e4;Iee="model_ttfb_timeout",Cee=3e4,Pee=6e4,Mee=8e3});function jN(){let t=k.AFK_MODEL_STALL_TIMEOUT_MS;if(t===void 0||t.trim()==="")return BN;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?BN:Ja(e)}function WN(t){return t instanceof Error&&t.message===HN}function yS(t){return new Error(`Model stream stalled: no output for ${Math.round(t/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 KN(t,e,n){if(e<=0)return{signal:t,timedOut:()=>!1,progress:()=>{},dispose:()=>{}};let r=new AbortController,o=AbortSignal.any([t,r.signal]),s,i=!1,a=!1,c=u=>{if(!(a||i)){i=!0,s=void 0;try{n?.({stallTimeoutMs:e,elapsedSinceLastProgressMs:Date.now()-u})}catch{}r.signal.aborted||r.abort(new Error(HN))}};return{signal:o,timedOut:()=>i,progress:()=>{if(a||i)return;s!==void 0&&clearTimeout(s);let u=Date.now(),p=setTimeout(()=>c(u),e);p.unref(),s=p},dispose:()=>{a||(a=!0,s!==void 0&&clearTimeout(s),s=void 0)}}}var BN,HN,af=h(()=>{"use strict";L();hS();BN=12e5;HN="model_stream_stall_timeout"});function cf(t,e=Math.random){return t+Math.floor(e()*t*Lee)}function GN(t=Math.random){let e=Fee-qN;return qN+Math.floor(t()*e)}function XN(t){return t.type==="turn.completed"&&t.usage.stopReason===ot}function zN(t){let e=k.AFK_OVERLOAD_PAUSE_MS;if(e!==void 0&&e.trim()!==""){let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.min(Math.floor(n),Dee)}return t!==void 0&&Nee.has(t)?Oee:0}var bS,Oee,Dee,qN,Fee,Lee,Nee,Va=h(()=>{"use strict";L();Zo();Zo();bS="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.",Oee=600*1e3,Dee=7200*1e3,qN=60*1e3,Fee=120*1e3,Lee=.25;Nee=new Set(["cli","repl","telegram","web"])});function df(t){if(!Number.isFinite(t)||t<=0)return 0;let e=Math.floor(t*2/3);return Math.max(1,e)}function JN(t){if(!("status"in t))return!1;let e=t.status;return e===529||e===503}function Ya(t){if(t===null||typeof t!="object")return!1;let e=t;if(e.status===529||e.status===503)return!0;let n=e.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 lf,Ps=h(()=>{"use strict";lf=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*Uee(t,e,n){q(t.traceWriter,{phase:"ttfb_timeout",durationMs:Date.now()-e,metadata:{reason:"ttfb-timeout",source:"first-byte",resolvedModel:t.model,attempt:n}}),yield{type:"stream.retry",sessionId:t.ctx.sessionId}}async function*SS(t,{input:e,turn:n,retry:r,requestStartedAt:o}){return t==="ttfb"?(r.ttfbRetries+=1,yield*Uee(e,o,r.ttfbRetries),"continue"):t==="overload"?(r.overloadRetries+=1,q(e.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:r.overloadRetries}}),yield{type:"stream.retry",sessionId:e.ctx.sessionId},yield*VN(cf(5e3*Math.pow(2,r.overloadRetries-1)),e,n),e.signal.aborted?"terminated":"continue"):(r.streamIncompleteRetries+=1,q(e.traceWriter,{phase:"rate_limit",metadata:{reason:"stream-incomplete",source:"mid-stream",attempt:r.streamIncompleteRetries}}),yield{type:"stream.retry",sessionId:e.ctx.sessionId},yield*VN(1e3*Math.pow(2,r.streamIncompleteRetries-1),e,n),e.signal.aborted?"terminated":"continue")}async function*VN(t,e,n){await We(t,e.signal),e.signal.aborted&&(yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId})}var YN=h(()=>{"use strict";J();Un();Va();Ps()});function ZN(t){let e=t.fastModeController?.snapshotTurn({resolvedModelId:t.model,providerFamily:"anthropic-direct",hasCustomEndpoint:t.baseUrl!==void 0,executionPath:"top-level"}),n=e?.effective===!0,r=An(t.authMode,t.sessionId,t.requestId,t.effort!==void 0,rf(t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{}),n);return{decision:e,runInput:{client:t.client,messages:t.messages,system:t.system,tools:t.tools,toolDispatcher:t.toolDispatcher,model:t.model,maxTokens:t.maxTokens,headers:r,signal:t.signal,ctx:{sessionId:t.sessionId},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...n?{fastMode:!0}:{},...t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{},...t.maxToolUseIterations!==void 0?{maxToolUseIterations:t.maxToolUseIterations}:{},...t.softDeadlineMs!==void 0?{softDeadlineMs:t.softDeadlineMs}:{},...t.traceWriter?{traceWriter:t.traceWriter}:{},...t.subagentId!==void 0?{subagentId:t.subagentId}:{},...t.throttleQueue?{throttleQueue:t.throttleQueue}:{},...t.onUsageProgress?{onUsageProgress:t.onUsageProgress}:{},...t.beforeNextRound?{beforeNextRound:t.beforeNextRound}:{}}}}function uf(t,e){let n=t instanceof Error?t:new Error(String(t));if(!e||n.message.startsWith(QN))return n;let r=new Error(`${QN} ${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 s=Object.getOwnPropertyDescriptor(n,o);s!==void 0&&Object.defineProperty(r,o,s)}return r}var QN,kS=h(()=>{"use strict";xn();Cs();QN="[Fast mode requested; no standard-mode fallback will be attempted]"});async function*e$(t,e,n){let r=e.throttleQueue;if(!r)return await t;r.resetAttempts();let o=Symbol("create-done"),s=!1,i=t.then(a=>(s=!0,a),a=>{throw s=!0,a});for(;;){for(let c of r.takeAll())n?.(c.retryAfterMs),yield{type:"rate_limit",sessionId:e.ctx.sessionId,status:c.status,attempt:c.attempt,...c.retryAfterMs!==void 0?{retryAfterMs:c.retryAfterMs}:{}};if(s)return await i;await Promise.race([i.then(()=>o,()=>o),r.waitForItem().then(()=>{})])}}var t$=h(()=>{"use strict"});function n$(t,e){try{let n=[];for(let r=0;r<t.length;r++){let o=t[r];if(o.role!=="assistant"||typeof o.content=="string")continue;let s=o.content;for(let i=0;i<s.length;i++){let a=s[i];if(a.type==="thinking"){let c=a;(!c.thinking||!c.signature)&&n.push({msgIdx:r,blockIdx:i,thinking:c.thinking?`(${c.thinking.length} chars)`:"(empty)",sigLen:c.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",e.message),console.error(`[afk] messages.length=${t.length}, invalid thinking blocks:`,n.length>0?JSON.stringify(n):"none found (cause may be elsewhere)")}catch{}}var r$=h(()=>{"use strict"});function Bee(t){let{name:e,description:n,input_schema:r}=t;return{name:e,...n!==void 0?{description:n}:{},input_schema:r}}async function jee(t,e,n,r,o){for(let s=0;;s++){if(s>0){let i=cf(5e3*Math.pow(2,s-1));if(await We(i,o),o.aborted)throw new Error("aborted")}try{return await Promise.resolve(t.messages.create(e,{headers:n,signal:r}))}catch(i){if(r.aborted)throw i;let a=i instanceof Error?i:new Error(String(i));if(JN(a)){if(s<3)continue;throw new pf}throw a}}}function Hee(t){return{model:t.model,max_tokens:t.maxTokens,messages:t.messages,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0?{tools:t.tools.map(Bee)}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{output_config:{effort:t.effort}}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.fastMode===!0?{speed:"fast"}:{}}}async function*o$({input:t,turn:e,retry:n,ttfbTimeoutMs:r,stallTimeoutMs:o}){let s=za({baseUrl:t.baseUrl})?ON(t.messages,oo()):t.messages,i=Hee({...t,messages:s,tools:e.windDownReason!==null?null:t.tools}),a=Date.now(),c=UN(t.signal,r),l=KN(c.signal,o,d=>{q(t.traceWriter,{phase:"idle_watchdog_fired",durationMs:d.elapsedSinceLastProgressMs,resolvedModel:t.model,metadata:{source:"model-stream",stallTimeoutMs:d.stallTimeoutMs,elapsedSinceLastProgressMs:d.elapsedSinceLastProgressMs}})});try{return{kind:"opened",events:yield*e$(jee(t.client,i,t.headers,l.signal,t.signal),t,u=>{let p=$N(u);p!==void 0&&c.extend(p)}),ttfb:c,stall:l,requestStartedAt:a}}catch(d){if(c.timedOut()&&!t.signal.aborted&&n.canRetryTtfb())return c.dispose(),l.dispose(),{kind:"retry-ttfb",requestStartedAt:a};if(c.dispose(),l.dispose(),t.signal.aborted)return yield{type:"turn.completed",usage:e.terminalUsage(),sessionId:t.ctx.sessionId},{kind:"terminated"};if(d instanceof pf)return{kind:"overload-exhausted"};let u=uf(d,t.fastMode===!0);return u.message.includes("thinking")&&n$(t.messages,u),yield{type:"error",error:u},{kind:"terminated"}}}var pf,s$=h(()=>{"use strict";kS();Cs();J();Un();sf();af();Va();Ps();t$();r$();pf=class extends Error{constructor(){super("Connection-phase overload budget exhausted"),this.name="ConnectionOverloadExhaustedError"}}});function i$(t,e){return t||e!==null}function a$(){return new ct("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 c$=h(()=>{"use strict";se()});function Wee(t){let e=t.trim();if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function Kee(t,e,n){let r=[],o=[];for(let a of t)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:Wee(a.partialJson)}));let s=a=>a.type==="tool_use",i=r.filter(s);return{stopReason:e,assistantBlocks:r,toolUseBlocks:i,usage:n,text:o.join("")}}async function*l$(t,e,n){let r=[],o=null,s=null,i=!1,a=!!k.AFK_TELEGRAM_TRACE;try{a&&console.log("[translate] starting SDK event iteration");for await(let c of t){switch(a&&console.log("[translate] SDK evt:",c.type),c.type){case"message_start":{let l=c.message?.usage;l&&(s={...l});break}case"content_block_start":{let l=c.content_block;l.type==="text"?r[c.index]={kind:"text",text:""}:l.type==="thinking"?r[c.index]={kind:"thinking",thinking:"",signature:""}:l.type==="redacted_thinking"?r[c.index]={kind:"redacted_thinking",data:l.data}:l.type==="tool_use"&&(r[c.index]={kind:"tool_use",id:l.id,name:l.name,partialJson:""},yield{kind:"event",event:{type:"tool.use.start",toolUseId:l.id,toolName:l.name,toolInput:" \u2026",pending:!0,sessionId:e.sessionId}});break}case"content_block_delta":{let l=r[c.index],d=c.delta;d.type==="text_delta"?(l&&l.kind==="text"&&(l.text+=d.text),yield{kind:"event",event:{type:"delta.text",text:d.text,sessionId:e.sessionId}}):d.type==="input_json_delta"?(l&&l.kind==="tool_use"&&(l.partialJson+=d.partial_json),n?.()):d.type==="thinking_delta"?(l&&l.kind==="thinking"&&(l.thinking+=d.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:d.thinking,sessionId:e.sessionId}}):(d.type==="signature_delta"&&l&&l.kind==="thinking"&&(l.signature=d.signature),n?.());break}case"content_block_stop":{let l=r[c.index];l&&l.kind==="tool_use"&&(yield{kind:"event",event:{type:"tool.use",summary:l.name,toolUseIds:[l.id],sessionId:e.sessionId}});break}case"message_delta":{c.delta&&c.delta.stop_reason!==void 0&&(o=c.delta.stop_reason);let l=c.usage;l&&(s!==null?(s.output_tokens=l.output_tokens,l.cache_creation_input_tokens!=null&&(s.cache_creation_input_tokens=l.cache_creation_input_tokens),l.cache_read_input_tokens!=null&&(s.cache_read_input_tokens=l.cache_read_input_tokens),l.input_tokens!=null&&(s.input_tokens=l.input_tokens)):s={cache_creation:null,cache_creation_input_tokens:l.cache_creation_input_tokens??null,cache_read_input_tokens:l.cache_read_input_tokens??null,inference_geo:null,input_tokens:l.input_tokens??0,output_tokens:l.output_tokens,server_tool_use:null,service_tier:null});break}case"message_stop":{i=!0;break}default:break}if(i)break}a&&console.log("[translate] SDK iteration ended naturally, stopped=",i)}catch(c){a&&console.log("[translate] SDK iteration threw:",c.message),yield{kind:"event",event:{type:"error",error:c instanceof Error?c:new Error(String(c))}};return}if(!i$(i,o)){yield{kind:"event",event:{type:"error",error:a$()}};return}a&&console.log("[translate] yielding turn-result"),yield{kind:"turn-result",result:Kee(r,o,s)}}var d$=h(()=>{"use strict";L();c$()});async function*u$({events:t,input:e,turn:n,retry:r,ttfb:o,stall:s,stallTimeoutMs:i,requestStartedAt:a}){let c=null,l=!1,d=!1,u=!1,p=!1,f=!1,m=!1;try{k.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let g of l$(cs(t,e.signal),e.ctx,()=>s.progress()))if(!m&&(g.kind==="turn-result"||g.event.type!=="error")&&(m=!0,o.firstByteSeen(),q(e.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-a,resolvedModel:e.model})),s.progress(),k.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",g.kind,g.kind==="event"?g.event.type:""),g.kind==="event"){if(g.event.type==="error"){if(o.timedOut()&&!e.signal.aborted&&r.canRetryTtfb()&&!m){d=!0;break}if(s.timedOut()&&!e.signal.aborted){yield{type:"error",error:yS(i)},l=!0;break}if(Ya(g.event.error)&&r.canRetryOverload()&&!e.signal.aborted){u=!0;break}if(Ya(g.event.error)&&!e.signal.aborted){f=!0;break}if(e.signal.aborted)break;if(g.event.error instanceof ct&&r.canRetryStreamIncomplete()&&!e.signal.aborted){p=!0;break}yield g.event,l=!0;break}yield g.event}else{c=g.result;break}k.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",c?"set":"null")}catch(g){if(o.timedOut()&&!e.signal.aborted&&r.canRetryTtfb()&&!m)o.dispose(),s.dispose(),d=!0;else{if(o.dispose(),s.dispose(),e.signal.aborted)return yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId},{kind:"terminated"};let y=g instanceof Error?g:new Error(String(g));if((s.timedOut()||WN(y))&&!e.signal.aborted)return yield{type:"error",error:yS(i)},{kind:"terminated"};if(Ya(y)&&r.canRetryOverload()&&!e.signal.aborted)u=!0;else if(Ya(y)&&!e.signal.aborted)f=!0;else return yield{type:"error",error:y},{kind:"terminated"}}}return o.dispose(),s.dispose(),d?{kind:"retry",reason:"ttfb"}:u?{kind:"retry",reason:"overload"}:p?{kind:"retry",reason:"stream-incomplete"}:f?{kind:"overload-exhausted"}:l?{kind:"translator-errored"}:{kind:"streamed",turnResult:c}}var p$=h(()=>{"use strict";d$();se();Yu();J();L();af();Ps()});async function*f$(t,e,n){let r=[],o=new Map;for(let i of t.toolUseBlocks)r.push({id:i.id,name:i.name,input:i.input,signal:e.signal}),o.set(i.id,Date.now()),br(e.traceWriter,ip({toolUseId:i.id,name:i.name,input:i.input,subagentId:e.subagentId})),yield{type:"tool.use.start",toolUseId:i.id,toolName:i.name,toolInput:Jn(i.name,i.input),toolInputRaw:op(i.input),toolInputCapture:k.AFK_CAPTURE_SUBAGENT_OUTPUT!=="0"?sp(i.input):void 0,sessionId:e.ctx.sessionId};if(e.signal.aborted){let i=r.map(a=>({type:"tool_result",tool_use_id:a.id,content:"Tool call aborted",is_error:!0}));return e.messages.push({role:"user",content:i}),yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId},{kind:"aborted"}}let s;if(e.toolDispatcher.executeBatch)s=yield*lp(async i=>{try{return await e.toolDispatcher.executeBatch(r,a=>{i({type:"tool.activity",activeCount:a.length,activeToolUseIds:[...a],sessionId:e.ctx.sessionId})})}catch(a){return r.map(()=>({content:`Tool batch execution failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}))}});else{s=[];for(let i of r){if(e.signal.aborted){s.push({content:"Tool call aborted",isError:!0,failureClass:Ne(e.signal)});continue}try{s.push(await e.toolDispatcher.execute(i))}catch(a){let c=a instanceof Error?a.message:String(a);s.push({content:`Tool execution threw: ${c}`,isError:!0})}}}return{kind:"dispatched",calls:r,results:s,startTimes:o}}var m$=h(()=>{"use strict";In();J();ew();L();Ma();cp();tw()});async function*g$(t,e,n,r){let o=[];for(let c=0;c<t.length;c++){let l=t[c],d=e[c],u=n.get(l.id),p=typeof u=="number"?Date.now()-u:0,f=d.truncated===!0||d.content.includes("[output truncated");br(r.traceWriter,ap({toolUseId:l.id,name:l.name,result:d,truncated:f,durationMs:p,subagentId:r.subagentId})),yield{type:"tool.output",toolUseId:l.id,toolName:l.name,content:d.content,...d.isError===!0?{isError:!0}:{},...f?{truncated:!0}:{},...d.capturePath!==void 0?{capturePath:d.capturePath}:{},...d.incomplete===!0?{incomplete:!0}:{},...d.incompleteReason?{incompleteReason:d.incompleteReason}:{},...typeof d.batchIndex=="number"&&typeof d.batchSize=="number"?{batchIndex:d.batchIndex,batchSize:d.batchSize}:{},...d.failureClass?{failureClass:d.failureClass}:{},durationMs:d.durationMs!==void 0?d.durationMs:p,...d.exitCode!==void 0?{exitCode:d.exitCode}:{},sessionId:r.ctx.sessionId},d.render?.diff&&(yield{type:"tool.diff",toolUseId:l.id,diff:d.render.diff,sessionId:r.ctx.sessionId});let{content:m,isError:g,image:y}=d,b=y!==void 0?[{type:"image",source:{type:"base64",media_type:y.mediaType,data:y.data}},...m.length>0?[{type:"text",text:m}]:[]]:m;o.push({type:"tool_result",tool_use_id:l.id,content:b,...g===!0?{is_error:!0}:{}})}let s=e.flatMap(c=>c.harnessUserMessage?.kind==="queued_user_message"?[{type:"text",text:c.harnessUserMessage.text}]:[]),i={role:"user",content:[...o,...s]};r.messages.push(i);let a=e.find(c=>c.failureClass===Co);return a?(yield{type:"error",error:new So(a.content)},"denial-tripped"):"committed"}var h$=h(()=>{"use strict";J();cp();Ci();se()});async function*y$(t,e,n,r,o){let s=e.messages.length;e.messages.push({role:"assistant",content:t.assistantBlocks});try{n.toolCallCount+=t.toolUseBlocks.length;let d=yield*f$(t,e,n);if(d.kind==="aborted"||(yield*g$(d.calls,d.results,d.startTimes,e))==="denial-tripped")return"terminated"}catch(d){throw e.messages.splice(s),d}n.iterations+=1;let i=t.toolUseBlocks[t.toolUseBlocks.length-1],a=i?`${i.name}${Jn(i.name,i.input)}`:"unknown";if(yield{type:"progress",progress:{taskId:n.taskId,description:"Working",summary:`${fp(n.iterations,r)}: ${a}`,lastToolName:i?.name,totalTokens:n.usage.totalTokens??0,toolUses:n.toolCallCount,durationMs:Date.now()-n.startedAt},sessionId:e.ctx.sessionId},n.windDownReason!==null)return yield{type:"turn.completed",usage:n.withDuration({...n.usage,stopReason:n.windDownReason}),sessionId:e.ctx.sessionId},"terminated";let c=pp(n.iterations,r),l=Iu(n.startedAt,o);if(c||l){let d=c?dp:xu,u=e.messages[e.messages.length-1];u!==void 0&&u.role==="user"&&Array.isArray(u.content)&&u.content.push({type:"text",text:d}),n.windDownReason=c?Mt:Ct}return"continue"}var b$=h(()=>{"use strict";Ma();Hn();ds();m$();h$()});function*w$(t,e,n){if(t.stopReason==="refusal"){t.text.length>0&&(yield{type:"assistant.message",text:t.text,sessionId:e.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:e.ctx.sessionId},yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId};return}let r=Vt(t.stopReason)?Cu(t.toolUseBlocks.map(s=>s.name),t.stopReason):null;t.text.length>0?(yield{type:"assistant.message",text:r?`${t.text}
1407
1407
 
1408
1408
  ${r}`:t.text,sessionId:e.ctx.sessionId},t.text.length<=qee&&(yield{type:"suggestion",suggestion:t.text,sessionId:e.ctx.sessionId})):r!==null&&(yield{type:"notice",text:r,kind:"truncation",sessionId:e.ctx.sessionId});let o=t.assistantBlocks.filter(s=>s.type!=="tool_use");o.length>0&&e.messages.push({role:"assistant",content:o}),yield{type:"turn.completed",usage:n.withDuration(n.windDownReason!==null?{...n.usage,stopReason:n.windDownReason}:n.usage),sessionId:e.ctx.sessionId}}var qee,S$=h(()=>{"use strict";ga();qee=200});import{randomUUID as Gee}from"node:crypto";var mf,k$=h(()=>{"use strict";gS();mf=class{usage={stopReason:null};iterations=0;toolCallCount=0;windDownReason=null;taskId=Gee();startedAt=Date.now();elapsedMs(){return Date.now()-this.startedAt}withDuration(e){return{...e,durationMs:this.elapsedMs()}}terminalUsage(){return this.withDuration(this.usage)}addRoundUsage(e){this.usage=wa(this.usage,e),this.usage.contextWindowTokens=(e.inputTokens??0)+(e.outputTokens??0)+(e.cachedInputTokens??0)+(e.cacheCreationTokens??0)}}});function v$(t,e){if(!e)return;let n=t.messages.at(-1);!n||n.role!=="user"||(Array.isArray(n.content)?n.content.push({type:"text",text:e}):n.content=[{type:"text",text:n.content},{type:"text",text:e}],Nl(t.traceWriter,{jobId:t.subagentId??"",subagentId:t.subagentId??"",byteLength:Buffer.byteLength(e,"utf8")}))}var T$=h(()=>{"use strict";J()});async function*vS(t){let e=up(t.maxToolUseIterations),n=t.softDeadlineMs??0,r=new mf,o=new lf,s=l=>({input:t,turn:r,retry:o,requestStartedAt:l}),i=df(of()),a=jN(),c=new ts(t.signal,t.traceWriter,"anthropic-direct");try{for(;;){if(t.signal.aborted){yield{type:"turn.completed",usage:r.terminalUsage(),sessionId:t.ctx.sessionId};return}let l=yield*o$({input:t,turn:r,retry:o,ttfbTimeoutMs:i,stallTimeoutMs:a});if(l.kind==="terminated")return;if(l.kind==="retry-ttfb"){if((yield*SS("ttfb",s(l.requestStartedAt)))==="terminated")return;continue}if(l.kind==="overload-exhausted"){q(t.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"connection-phase",attempt:3,exhausted:!0}}),yield{type:"assistant.message",text:bS,sessionId:t.ctx.sessionId},yield{type:"turn.completed",usage:r.withDuration({...r.usage,stopReason:ot}),sessionId:t.ctx.sessionId};return}let{events:d,ttfb:u,stall:p,requestStartedAt:f}=l,m=yield*u$({events:d,input:t,turn:r,retry:o,ttfb:u,stall:p,stallTimeoutMs:a,requestStartedAt:f});if(m.kind==="terminated")return;if(m.kind==="retry"){if((yield*SS(m.reason,s(f)))==="terminated")return;continue}if(o.reset(),m.kind==="overload-exhausted"){q(t.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:3,exhausted:!0}}),yield{type:"assistant.message",text:bS,sessionId:t.ctx.sessionId},yield{type:"turn.completed",usage:r.withDuration({...r.usage,stopReason:ot}),sessionId:t.ctx.sessionId};return}if(m.kind==="translator-errored"){t.signal.aborted&&(yield{type:"turn.completed",usage:r.terminalUsage(),sessionId:t.ctx.sessionId});return}let g=m.turnResult;if(g===null){yield{type:"turn.completed",usage:r.terminalUsage(),sessionId:t.ctx.sessionId};return}if(r.addRoundUsage(mS(g.usage,g.stopReason,t.model,t.fastMode?"fast":void 0)),t.onUsageProgress?.(r.usage),g.stopReason!=="tool_use"){yield*w$(g,t,r);return}if((yield*y$(g,t,r,e,n))==="terminated")return;v$(t,t.beforeNextRound?.())}}finally{c.finish(r.elapsedMs())}}var _$=h(()=>{"use strict";gS();J();sf();af();ds();Va();Ps();YN();s$();p$();b$();S$();k$();Ib();T$()});function Xee(t,e){return t.authMode==="oauth"&&t.tokenRefresher!==void 0&&"status"in e&&e.status===401}async function*E$(t,e,n){let r=null;for await(let s of vS(e)){if(n())return;if(s.type==="error"&&Xee(t,s.error)){r=s;break}yield s}if(!r)return;if(!await t.forceClientRefresh()){yield r;return}e.client=t.getClient(),e.headers=t.rotateHeaders(e),yield*vS(e)}var A$=h(()=>{"use strict";_$()});var gf=h(()=>{"use strict"});async function*x$(t,e,n,r,o){let s=Uo(Xe()??"");if(yield{type:"paused",reason:"usage-limit",accountId:s,autoResume:t.autoResumeOnUsageLimit},q(e.traceWriter,{phase:"usage_limit_pause",metadata:{reason:"usage-limit",source:"retry-layer",hasResetTimestamp:!1,autoResume:t.autoResumeOnUsageLimit}}),!t.autoResumeOnUsageLimit){t.markCredentialSnapshotStale(),yield o;return}let i=Date.now(),a=!1;for(;;){let c;if(t.getUsageLimitWait())c="aborted";else{let p=LP({signal:e.signal,retryAfterMs:6e4});t.setUsageLimitWait(p);try{c=await p}finally{t.setUsageLimitWait(null)}}if(c==="aborted")return;let d=s;if(c==="hot-swap"){let p=await t.forceClientRefresh();p&&(e.client=t.getClient(),d=p.accountId)}e.headers=t.rotateHeaders(e);let u=null;for await(let p of r(t,e,n)){if(!a&&p.type==="error"){let f=la(p.error);if(f&&(f.kind==="oauth-limit"||f.kind==="oauth-limit-no-ts")){u=p;break}}a||(yield{type:"resumed",hotSwapped:c==="hot-swap",accountId:d},q(e.traceWriter,{phase:"usage_limit_resume",durationMs:Date.now()-i,metadata:{source:"retry-layer",hotSwapped:c==="hot-swap"}}),a=!0),yield p}if(!u)return;if(Date.now()-i>72e5){yield u;return}}}async function*R$(t,e,n,r,o,s){if(s.getTime()-Date.now()>72e5){t.markCredentialSnapshotStale(),yield o;return}let i=Uo(Xe()??""),a=Date.now();if(yield{type:"paused",reason:"usage-limit",resetsAt:s,accountId:i,autoResume:t.autoResumeOnUsageLimit},q(e.traceWriter,{phase:"usage_limit_pause",metadata:{reason:"usage-limit",source:"retry-layer",hasResetTimestamp:!0,autoResume:t.autoResumeOnUsageLimit,resetsAt:s.toISOString()}}),!t.autoResumeOnUsageLimit){t.markCredentialSnapshotStale(),yield o;return}let c,l=t.getUsageLimitWait();if(l)c=await l;else{let u=FP({resetsAt:s,signal:e.signal});t.setUsageLimitWait(u);try{c=await u}finally{t.setUsageLimitWait(null)}}if(c==="aborted")return;let d=i;if(c==="hot-swap"){let u=await t.forceClientRefresh();u&&(e.client=t.getClient(),d=u.accountId)}e.headers=t.rotateHeaders(e),yield{type:"resumed",hotSwapped:c==="hot-swap",accountId:d},q(e.traceWriter,{phase:"usage_limit_resume",durationMs:Date.now()-a,metadata:{source:"retry-layer",hotSwapped:c==="hot-swap"}}),yield*r(t,e,n)}var I$=h(()=>{"use strict";da();dS();J();gf()});async function*M$(t,e,n,r){let o=null,s=null,i=!1,a=0;for(;;){let c,l=!1;for await(let p of r(t,e,n)){if(p.type==="error"){let f=la(p.error);if(f&&f.kind==="oauth-limit"){s=f.resetsAt,o=p;break}if(f&&f.kind==="oauth-limit-no-ts"){i=!0,o=p;break}if(f&&f.kind==="rate-limit-transient"&&a<3){l=!0,c=f.retryAfterMs;break}}yield p}if(!l)break;if(a+=1,n()||e.signal.aborted)return;let u=Math.min(c??5e3,12e4)+Math.floor(Math.random()*1e3);if(q(e.traceWriter,{phase:"rate_limit",metadata:{reason:"retry-after",source:"retry-layer",attempt:a,waitMs:u}}),await We(u,e.signal),n()||e.signal.aborted)return;e.headers=t.rotateHeaders(e)}if(o){if(i){yield*x$(t,e,n,r,o);return}s&&(yield*R$(t,e,n,r,o,s))}}var O$=h(()=>{"use strict";da();Un();J();gf();I$()});async function*D$(t,e,n,r){let o=zN(t.surface),s=null,i=!1;for(;;){let a=null;for await(let l of r(t,e,n)){if(XN(l)){a=l;break}yield l}if(!a){i&&s!==null&&q(e.traceWriter,{phase:"overload_resume",durationMs:Date.now()-s,metadata:{source:"retry-layer",outcome:"recovered"}});return}if(n()||e.signal.aborted||o===0){yield a;return}s??=Date.now();let c=o-(Date.now()-s);if(c<=0){i&&q(e.traceWriter,{phase:"overload_resume",durationMs:Date.now()-s,metadata:{source:"retry-layer",outcome:"ceiling-reached"}}),yield a;return}if(i||(q(e.traceWriter,{phase:"overload_pause",metadata:{reason:"overloaded",source:"retry-layer",hasResetTimestamp:!1,ceilingMs:o,surface:t.surface??"unknown"}}),i=!0),await We(Math.min(GN(),c),e.signal),n()){yield a;return}if(e.signal.aborted)return;e.headers=t.rotateHeaders(e),yield{type:"stream.retry",sessionId:e.ctx.sessionId}}}var F$=h(()=>{"use strict";Va();Un();J()});import{randomUUID as Yee}from"node:crypto";var hf,L$=h(()=>{"use strict";xn();Cs();dS();A$();O$();F$();gf();hf=class{_client;_authMode;initSessionId;baseUrl;tokenRefresher;autoResumeOnUsageLimit;surface;refreshPromise=null;usageLimitWaitPromise=null;credentialSnapshotStale=!1;constructor(e){this._client=e.client,this._authMode=e.authMode,this.initSessionId=e.initSessionId,this.baseUrl=e.baseUrl,this.tokenRefresher=e.tokenRefresher,this.autoResumeOnUsageLimit=e.autoResumeOnUsageLimit,e.surface!==void 0&&(this.surface=e.surface)}get client(){return this._client}get authMode(){return this._authMode}rotateHeaders(e){return An(this._authMode,this.initSessionId,Yee(),e.effort!==void 0,rf({...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{}}),e.fastMode===!0)}tierContext(){let e=this;return{get authMode(){return e._authMode},get surface(){return e.surface},get autoResumeOnUsageLimit(){return e.autoResumeOnUsageLimit},get tokenRefresher(){return e.tokenRefresher},getClient:()=>e._client,rotateHeaders:n=>e.rotateHeaders(n),forceClientRefresh:()=>e.forceClientRefresh(),getUsageLimitWait:()=>e.usageLimitWaitPromise,setUsageLimitWait:n=>{e.usageLimitWaitPromise=n},markCredentialSnapshotStale:()=>{e.credentialSnapshotStale=!0}}}async forceClientRefresh(){if(!this.tokenRefresher)return null;let e=Xe(),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=Xe();return{accountId:Uo(r??""),swapped:e!==r}}async*turnWithRetries(e,n){this.credentialSnapshotStale&&(await this.forceClientRefresh()&&(e.client=this._client,e.headers=this.rotateHeaders(e)),this.credentialSnapshotStale=!1);let r=this.tierContext();yield*D$(r,e,n,(o,s,i)=>M$(o,s,i,E$))}}});function N$(){return Qee.map(t=>({...t}))}var Qee,$$=h(()=>{"use strict";Qee=[{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 yf(t){if(t.length===0)return;let e=t[t.length-1];if(!e||e.role!=="assistant"||typeof e.content=="string")return;let n=e.content,r=[];for(let s of n)s.type==="tool_use"&&typeof s.id=="string"&&r.push(s.id);if(r.length===0)return;let o={role:"user",content:r.map(s=>({type:"tool_result",tool_use_id:s,content:"Tool call interrupted before completing \u2014 no result recorded.",is_error:!0}))};t.push(o)}var _S=h(()=>{"use strict"});var bf=h(()=>{"use strict";Ao()});async function*U$(t){if(t.state.autoCompactThreshold===void 0||t.state.closed)return;let e=t.state.lastUsage,n=sn(t.state.requestedModel);if(e===null||n<=0)return;let r=Ee(e);if(gi(r,n,t.state.autoCompactThreshold))try{t.hookRegistry&&await t.hookRegistry.dispatch({event:"PreCompact",sessionId:t.initSessionId,trigger:"auto"}),(await t.compact()).compacted&&(t.state.lastUsage=null)}catch(o){if(!(o instanceof Z))throw o}}var B$=h(()=>{"use strict";Bt();bf();se()});import{randomUUID as Zee}from"node:crypto";async function*j$(t){yield{type:"session.init",info:{sessionId:t.initSessionId,model:t.state.currentModel,permissionMode:t.state.currentPermissionMode,cwd:process.cwd(),tools:[],slashCommands:[],skills:[],plugins:[],mcpServers:t.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:t.retry.authMode,version:"anthropic-direct-v1"}};let n=t.promptStream[Symbol.asyncIterator]();try{for(;!t.state.closed;){let r=await Promise.race([n.next(),t.abort.closedPromise]);if(r==="__closed__")break;let o=r;if(o.done)break;let s=o.value,i=t.abort.begin();if(i.signal.aborted){t.abort.clear(i);return}yf(t.state.messages);{let u;try{yi(Ee(t.state.lastUsage??{}),t.maxTokens,Tt(t.state.requestedModel??t.state.currentModel),t.state.requestedModel??t.state.currentModel)}catch(p){u=p instanceof Error?p:new Error(String(p))}if(u!==void 0){t.abort.clear(i),yield{type:"error",error:u};continue}}t.state.messages.push({role:"user",content:s.content});let a=t.composeSystem(),{decision:c,runInput:l}=ZN({client:t.retry.client,messages:t.state.messages,system:a,tools:t.state.currentPermissionMode==="plan"?t.tools:t.tools?.filter(u=>u.name!==yt)??null,toolDispatcher:t.state.toolDispatcher,model:t.state.currentModel,maxTokens:t.maxTokens,signal:i.signal,authMode:t.retry.authMode,sessionId:t.initSessionId,requestId:Zee(),...t.fastModeController?{fastModeController:t.fastModeController}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{},...t.maxToolUseIterations!==void 0?{maxToolUseIterations:t.maxToolUseIterations}:{},...t.softDeadlineMs!==void 0?{softDeadlineMs:t.softDeadlineMs}:{},...t.traceWriter?{traceWriter:t.traceWriter}:{},...t.subagentId!==void 0?{subagentId:t.subagentId}:{},...t.throttleQueue?{throttleQueue:t.throttleQueue}:{},...t.beforeNextRound?{beforeNextRound:t.beforeNextRound}:{},onUsageProgress:u=>{t.state.lastUsage=u}}),d=!1;try{for await(let u of t.retry.turnWithRetries(l,()=>t.state.closed)){if(u.type==="turn.completed"){if(t.state.lastUsage=u.usage,t.abort.clear(i),d=!0,yield u,t.state.closed)return;continue}if(t.state.closed)return;u.type==="error"&&(d=!0),yield u}}catch(u){if(t.state.closed)return;if(i.signal.aborted){t.abort.clear(i),d||(yield t.makeInterruptedTurnEvent());continue}yield{type:"error",error:uf(u,c?.effective===!0)};return}finally{t.abort.clear(i)}if(t.state.closed)return;if(i.signal.aborted){d||(yield t.makeInterruptedTurnEvent());continue}yield*U$(t)}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}var H$=h(()=>{"use strict";qr();Bt();_S();bf();kS();B$()});function W$(t){let e=t.lastUsage,n=Tt(t.requestedModel),r;if(e&&n>0){let i=Ee(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=mi(e);return{tools:[],agents:[],isAutoCompactEnabled:t.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}function K$(t){return t?t.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}function q$(t){return{subscriptionType:t==="oauth"?"claude-subscription":"api-key"}}var G$=h(()=>{"use strict";Bt();bf()});var X$=h(()=>{"use strict";Zb()});var z$=h(()=>{"use strict";Yb()});function J$(t){let{state:e,systemPrefix:n,baseUrl:r}=t;e.userSystem&&(e.userSystem=Bu(e.userSystem));let o=[];n&&n.length>0&&o.push(...n),e.userSystem&&e.userSystem.length>0&&o.push({type:"text",text:e.userSystem});let s=Vb(e.currentPermissionMode);s!==null&&o.push(s);let i=Qb(e.currentPermissionMode);return i!==null&&o.push(i),o.length===0?null:za({baseUrl:r})?MN(o,oo()):o}var V$=h(()=>{"use strict";Cs();X$();z$();Mb()});function Y$(t,e){e===void 0||e.length===0||(t.requestedModel=e,t.currentModel=_e(e)??e)}function Q$(t){let{state:e,mode:n,onPermissionMode:r}=t;e.currentPermissionMode=n,e.toolDispatcher.setAllowAll?.(_t(n)),r?.(n)}function Z$(t){let{state:e,cwd:n,cwdDependentsFactory:r}=t;if(e.toolDispatcher.setResolveBase?.(n),!r)return;let{userSystem:o,dispatcher:s}=r(n);e.userSystem=o,e.toolDispatcher=s}function eU(t){let{state:e,basePrompt:n,systemPromptRebuildFactory:r}=t;return r?(e.userSystem=r(n),!0):!1}var tU=h(()=>{"use strict";xo();lt()});function nU(t){return{type:"turn.completed",usage:{stopReason:"interrupted",resultSubtype:"interrupted",isError:!1},sessionId:t}}var rU=h(()=>{"use strict"});function ete(t){if(t.role!=="user")return!1;let e=t.content;if(typeof e=="string")return!0;if(!Array.isArray(e))return!1;for(let n of e)if(n.type==="tool_result")return!1;return!0}function tte(t){let n=[(t.role==="user"?"User":"Assistant")+":"];if(typeof t.content=="string")n.push(t.content);else if(Array.isArray(t.content))for(let r of t.content){let o=r.type;if(o==="text"&&"text"in r)n.push(r.text);else if(o==="tool_use"){let s=r.name??"unknown",i=cU(r.input);n.push(`[tool call: ${s} ${i}]`)}else if(o==="tool_result"){let s=r.content;n.push(`[tool result: ${lU(s)}]`)}else o==="image"?n.push("[image]"):o==="document"&&n.push("[document]")}return n.join(`
1409
1409
  `)}function nte(t){let e=0;if(typeof t.content=="string")e+=t.content.length;else if(Array.isArray(t.content))for(let n of t.content){let r=n.type;r==="text"&&"text"in n?e+=n.text.length:r==="tool_use"?e+=cU(n.input).length:r==="tool_result"&&(e+=lU(n.content).length)}return e}function rte(t){if(typeof t=="string")return Yr(t);if(Array.isArray(t)){let e=0;for(let n of t)n.type==="text"&&"text"in n&&(e+=Yr(n.text));return e}return 0}function ote(t){if(typeof t=="string")return is(t);if(Array.isArray(t)){for(let e of t)if(e.type==="text"&&"text"in e)return is(e.text)}return!1}function ES(t,e){return zu(t,ste,e??{})}function oU(t,e,n,r){return jb(t,e,wf,n,r)}function sU(t,e,n){let r=Hb(t,wf);return{model:e,max_tokens:n,system:_a,messages:[{role:"user",content:xa(r)}],stream:!0}}function iU(t,e,n){return Wb(t,e,n,wf)}function aU(t,e,n){return Kb(t,e,n,wf)}function cU(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function lU(t){if(typeof t=="string")return t.length>320?t.slice(0,317)+"...":t;if(Array.isArray(t)){let e=[];for(let r of t)r.type==="text"&&"text"in r&&e.push(r.text);let n=e.join(" ");return n.length>320?n.slice(0,317)+"...":n}return""}var wf,ste,dU=h(()=>{"use strict";Ra();wf={isFreshUserTurn:ete,renderMessage:tte,buildPreamble(t){return[{role:"user",content:Ea+`