agent-afk 5.95.0 → 5.95.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  var YS=Object.defineProperty;var we=(t,e)=>()=>(t&&(e=t(t=0)),e);var jd=(t,e)=>{for(var n in e)YS(t,n,{get:e[n],enumerable:!0})};function ho(t){return go.find(e=>e.name===t)}function Ea(t){return process.env[t]!==void 0}var go,b,P=we(()=>{"use strict";go=[{name:"AFK_COMPACT_KEEP_LAST_TURNS",description:"Number of recent turns the compactor keeps verbatim during /compact. Default tuned in compact-handler.ts.",type:"number",required:!1,example:"6",category:"model"},{name:"AFK_COMPACT_MODEL",description:"Override the model used by the /compact summarizer. Falls back to a cheap default (haiku-class).",type:"string",required:!1,example:"claude-haiku-4-5",category:"model"},{name:"AFK_COMPACT_SHRINK_FRACTION",description:"Context-fullness fraction (0\u20131, exclusive) at/above which /compact and auto-compaction relax the keep-window so a short-but-full session (few turns, huge tool exchanges) can still be summarized instead of no-oping on turn count. Default 0.7 (see shared/compaction.ts DEFAULT_COMPACT_SHRINK_THRESHOLD).",type:"number",required:!1,example:"0.8",category:"model"},{name:"AFK_DEFAULT_SUBAGENT_MODEL",description:"Override the default model used when a subagent is dispatched without an explicit model.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_DIAGNOSE_BASELINE",description:"Kill switch for /diagnose reproducer baseline execution. When set to '0', the /diagnose skill skips executing the detected reproducer command for a ground-truth baseline; default enabled (runs). Set to '0' to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_DISABLE_PROMPT_CACHE",description:"Disable Anthropic prompt caching when set to 1/true/yes/on. Unset = caching enabled.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_DISABLE_BASH_INTERPRETER_GUARD",description:"Skip ONLY the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) when set to 1, leaving the rest of path-approval intact. Applies on interactive surfaces (REPL/Telegram), where the denylist is active but your workflow legitimately runs interpreter one-liners. The restricted-root substring check is unaffected. Default: denylist active on interactive surfaces; headless already fails open (opt in with AFK_FORCE_BASH_INTERPRETER_GUARD=1). To disable all of path-approval + bash restriction instead, use AFK_DISABLE_PATH_APPROVAL=1.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_DISABLE_PATH_APPROVAL",description:"Skip the path-approval + bash-restriction hooks entirely when set to 1. Use for headless flows that need wide-open file access (CI scripts, batch jobs). Default: hooks enabled. Note: on headless surfaces (afk chat, daemon) no grant manager is wired, so the interpreter denylist (python -c, node -e, sh -c, ...) fails OPEN by default \u2014 opt headless flows into it with AFK_FORCE_BASH_INTERPRETER_GUARD=1, or set this var to 1 to disable all of path-approval.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_FORCE_BASH_INTERPRETER_GUARD",description:"Apply the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) even on headless surfaces (afk chat, daemon) where no grant manager is wired. By default the denylist fires only on interactive surfaces (REPL/Telegram), failing open on headless so legitimate automation is not hard-blocked with no recourse. Set to 1 to opt headless flows back into the guard. Overridden by AFK_DISABLE_BASH_INTERPRETER_GUARD=1. Default: off (headless fails open).",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_EFFORT",description:"Effort hint guiding adaptive-thinking depth, forwarded as Anthropic output_config.effort (model-gated; ignored where unsupported). Accepts low | medium | high | xhigh | max.",type:"string",required:!1,example:"medium",category:"model"},{name:"AFK_MAX_BUDGET_USD",description:"Cumulative USD budget ceiling for the session. Aborts the turn when the running cost crosses this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_NESTING_DEPTH",description:"Maximum sub-agent/skill nesting depth; 0 disables nested delegation entirely (the agent, skill, AND compose tools all refuse). A top-level session is depth 0, so the default 3 permits three generations of forked descendants (depth 1 \u2192 2 \u2192 3) and refuses the agent and skill tools at depth 3. Resolved once at the root of each session and propagated down through child AgentConfig, so descendants inherit the root value rather than re-reading the environment. Raise with care: depth is a fan-out exponent (a width-N wave at depth D reaches ~N^D concurrent children), so values above 4 invite provider rate-limit (429) cascades. Accepted range 0-6; unset, empty, unparseable, negative, or out-of-range input falls back to the default. An explicit programmatic maxDepth (SubagentExecutorContext / SkillExecutorContext) still wins.",type:"number",required:!1,default:"3",example:"2",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. Falls back to provider default when unset.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Deprecated and inert: not read by the generation path. Use AFK_MAX_OUTPUT_TOKENS (or --max-output-tokens) to cap per-response output tokens; falls back to the model output ceiling when unset.",type:"number",required:!1,default:"4096",example:"8192",category:"model"},{name:"AFK_MAX_TOOL_USE_ITERATIONS",description:"Opt-in ceiling on tool-use rounds per turn for TOP-LEVEL (non-subagent) sessions, on both providers. Mirrors the maxToolUseIterations config key / max_tool_use_iterations tool param. Unset, non-numeric, or <=0 means unlimited (the default \u2014 zero behavior change): a top-level turn ends only when the model stops calling tools, the abort signal fires, the provider errors, or the dollar budget trips. A positive integer N makes top-level turns wind down gracefully after N tool rounds (one tools-stripped final round). An explicit config/CLI value wins over this env default. Does NOT affect subagent forks \u2014 they keep their own non-zero anti-hang default (SUBAGENT_DEFAULT_MAX_TOOL_USE_ITERATIONS) regardless of this var.",type:"number",required:!1,default:"0",example:"150",category:"model"},{name:"AFK_MEMORY_EVIDENCE_GATE",description:'Opt-in (set to 1) evidence gate for durable memory writes. When enabled, a codebase fact (memory_update category "convention") stored without an `evidence` citation is recalled as [unverified], and memory_search results carry a verification verdict. User preferences and agent reflections are never gated. Default off \u2014 memory behaves identically to legacy when unset.',type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_MICROCOMPACT_KEEP_LAST",description:"Number of the most-recent tool_result blocks that tool-result microcompaction keeps intact regardless of size, so the agent does not lose the tool output it is actively reasoning over. Older results are the safe ones to trim. Default 4 (see shared/compaction.ts DEFAULT_MICROCOMPACT_KEEP_LAST). Values <= 0 protect nothing.",type:"number",required:!1,default:"4",example:"3",category:"model"},{name:"AFK_MICROCOMPACT_TOOL_RESULT_BYTES",description:"Byte threshold (tool_result content length) at/above which a tool_result block becomes a microcompaction candidate. When /compact and auto-compaction would otherwise no-op on a short-but-full session, microcompaction clears large/old tool_result CONTENT in place (largest first) \u2014 replacing it with a short placeholder, never removing the block \u2014 to reclaim context deterministically (no LLM call). Blocks below this size are left intact. Default 2048 (see shared/compaction.ts DEFAULT_MICROCOMPACT_TOOL_RESULT_BYTES).",type:"number",required:!1,default:"2048",example:"4096",category:"model"},{name:"AFK_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), fixed-identity aliases (opus, sonnet, haiku, fable), or full model IDs. Migration: AFK_MODEL=sonnet now pins the fixed Sonnet identity rather than following a rebound medium tier.",type:"string",required:!1,default:"medium",example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_TTFB_TIMEOUT_MS",description:"Per-request time-to-first-token timeout (ms) for the anthropic-direct streaming loop. Bounds how long a single model call may stall BEFORE its first streamed CONTENT token (a text/thinking delta or tool_use); the connection-level message_start and keep-alive pings do NOT count. Once a content token streams, the timer is cleared and the rest of the response is governed instead by the progress-aware AFK_MODEL_STALL_TIMEOUT_MS window, so a normal slow call (below the bound) and any actively-streaming extended-thinking response are never aborted. NOTE: a request whose FIRST token takes longer than the bound \u2014 e.g. a very large opus_1m prefill \u2014 is aborted, retried once, then surfaces as an error (raise this value or set 0 for such workloads); this trims the degrading-call tail instead of a silent ~10-min hang on the SDK default. Default 180000 (180s \u2248 2\xD7 the measured p99 ttfb). Set to 0 to disable.",type:"number",required:!1,default:"180000",example:"120000",category:"model"},{name:"AFK_MODEL_STALL_TIMEOUT_MS",description:"Progress-aware POST-first-byte stall window (ms) for the anthropic-direct streaming loop. Bounds how long a stream that has ALREADY produced content may then go completely silent. Every streamed output event resets the window, so this is NOT a total-round cap: a legitimately long, actively-streaming round (large code emission, extended thinking) survives indefinitely, while a stream wedged mid-flight is aborted and surfaces as a real terminal error instead of hanging. Complements AFK_MODEL_TTFB_TIMEOUT_MS, which governs only the window BEFORE the first token; this one takes over after it. Default 1200000 (20min) \u2014 above the 18.5min maximum post-first-byte stream duration observed across 86,076 rounds in 12,381 local traces (p99 122s, p99.9 234s), so no healthy round trips it. Set to 0 to disable (issue #762).",type:"number",required:!1,default:"1200000",example:"600000",category:"model"},{name:"AFK_SUBAGENT_TIMEOUT_MS",description:"Foreground forked-subagent wall-clock budget in ms; 0 disables the cap; explicit per-fork config.timeoutMs and the 60-min background mode still win. Bounds how long a single forked child turn may run before `withTimeout` aborts its controller (cascading through the AbortGraph to descendants) and the parent receives a legible TimeoutError tool_result instead of hanging. Default 2700000 (45 min \u2248 headroom over the longest healthy review/research agent observed in production). Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to opt a whole session back into unbounded child turns. Does NOT affect the background dispatch budget (SUBAGENT_BACKGROUND_TIMEOUT_MS) or a per-fork config.timeoutMs \u2014 both take precedence.",type:"number",required:!1,default:"2700000",example:"3600000",category:"model"},{name:"AFK_SUBAGENT_IDLE_TIMEOUT_MS",description:"Forked-subagent progress-aware idle-watchdog window in ms; 0 disables the watchdog; an explicit per-fork config.idleTimeoutMs still wins. Fires when a forked child produces no observable output event for this window, aborting the same controller the wall-clock timeout targets so partial output is preserved and the run classifies as a failure. This is distinct from AFK_SUBAGENT_TIMEOUT_MS, the blunt wall-clock that bounds total turn time: the idle watchdog is the tighter first-to-fire bound and never fires while the stream is legitimately parked on a provider-communicated backoff (OAuth pause, or a rate-limit event carrying a retry-after), extending the deadline for the pause window instead. Default 480000 (8 min) clears the worst-case transient-429 backoff the watchdog is currently blind to (about 363s) with roughly 2 min of margin, while staying materially tighter than the 45-min wall-clock. Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to disable the idle watchdog for a whole session (the wall-clock still applies). v1 applies to forked sub-agent turns only, not top-level or daemon sessions.",type:"number",required:!1,default:"480000",example:"300000",category:"model"},{name:"AFK_VISION_MODELS",description:'Comma-separated override for image (vision) capability detection on the openai-compatible provider. Each token force-enables a model id by exact or substring match (e.g. "qwen2.5-vl" matches a local VL id); prefix a token with "!" to force-disable. Use to send images to a local vision-language model AFK does not recognise by name, or to blacklist a mis-detected id. Built-in detection already covers gpt-4o/4.1/5.x, o1/o3/o4-mini, Claude, and common VL families.',type:"string",required:!1,example:"qwen2.5-vl,!gpt-4o-mini",category:"model"},{name:"AFK_MODEL_LOCAL",description:'Bind the "local" capability tier (cheapest/fastest, user-configured) to a model id. Overrides afk.config.json models.local. Point at a local Ollama, LM Studio, or any OpenAI-compatible shim.',type:"string",required:!1,example:"llama3.2:3b",category:"model"},{name:"AFK_MODEL_LOCAL_API_KEY",description:'Per-slot API key for the "local" tier. Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LOCAL_BASE_URL",description:'Per-slot endpoint base URL for the "local" tier. Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:11434/v1",category:"model"},{name:"AFK_MODEL_LARGE",description:'Bind the "large" capability tier (most capable) to a model id/alias. Overrides afk.config.json models.large.',type:"string",required:!1,example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-5",category:"model"},{name:"AFK_MODEL_MEDIUM_API_KEY",description:'Per-slot API key for the "medium" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_MEDIUM_BASE_URL",description:'Per-slot endpoint base URL for the "medium" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_SMALL",description:'Bind the "small" capability tier (cheap/fast) to a model id/alias. Overrides afk.config.json models.small.',type:"string",required:!1,example:"gpt-4o-mini",category:"model"},{name:"AFK_MODEL_SMALL_API_KEY",description:'Per-slot API key for the "small" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_SMALL_BASE_URL",description:'Per-slot endpoint base URL for the "small" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_OVERLOAD_PAUSE_MS",description:"Wall-clock ceiling (ms) for the bounded pause after a mid-stream overload (529) exhausts its retry budget. Overrides the per-surface default for ALL surfaces: 0 disables the pause (fail fast). Interactive surfaces (cli/repl/telegram) default to 600000; daemon/cron default to 0 so an always-on runner never silently parks on upstream capacity.",type:"number",required:!1,example:"600000",category:"model"},{name:"AFK_PROMPT_CACHE_TTL",description:"TTL for Anthropic prompt-cache blocks. Accepts 5m or 1h.",type:"string",required:!1,default:"1h",example:"1h",category:"model"},{name:"AFK_SUGGEST_ENABLED",description:"Enable the LLM-backed ghost-text suggestion tier in the interactive REPL. Set to 1/true/yes/on to activate. Off by default.",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_GHOST",description:"Enable REPL ghost-text inline suggestions (Tier-1 history/dropdown + optional Tier-2 LLM). 1 = on (default), 0 = off. Set 0/false/off/no to disable all ghost text. Tier-2 LLM is separately gated by AFK_SUGGEST_ENABLED.",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_MODEL",description:"Override the small model used for REPL ghost-text suggestions. Falls back to AFK_COMPACT_MODEL or haiku-class for anthropic, or the session model for other providers.",type:"string",required:!1,category:"model"},{name:"AFK_TASK_BUDGET",description:"Per-task token budget ceiling. Aborts when cumulative usage would exceed it.",type:"number",required:!1,default:"100000",example:"200000",category:"model"},{name:"AFK_TEMPERATURE",description:"Numeric temperature override for model sampling. Provider default if unset.",type:"number",required:!1,example:"0.7",category:"model"},{name:"AFK_THINKING",description:"Extended-thinking mode. Accepts adaptive | disabled | enabled:<N> | enabled:max. Defaults to the model-appropriate mode when unset (adaptive on current models).",type:"string",required:!1,default:"adaptive",example:"adaptive",category:"model"},{name:"AFK_THINKING_UI",description:"Default thinking-display mode for the interactive REPL: summary | live | digest | off. Display-only \u2014 controls how extended-thinking blocks render, never whether thinking runs (cost/latency unaffected). Overridden per-launch by --thinking-ui and mutable mid-session via /thinking. Precedence: --thinking-ui flag > this env > interactive.thinkingUi config > live. Invalid values are ignored.",type:"string",required:!1,default:"live",example:"digest",category:"misc"},{name:"AFK_TIMEOUT_MS",description:"Per-turn timeout in milliseconds. Provider/SDK default if unset.",type:"number",required:!1,example:"120000",category:"model"},{name:"CLAUDE_MODEL",description:"Legacy alias for AFK_MODEL \u2014 supported for back-compat with pre-AFK_* deployments.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_SYSTEM_PROMPT",description:'Raw operator-overlay prompt. Highest-priority overlay (over afk.config.json and AFK.md). Appended on top of the framework base (prompts/system-prompt.md) under an "# Operator configuration" header \u2014 it augments, never replaces, the base.',type:"string",required:!1,example:"You are a helpful agent.",category:"model"},{name:"AFK_DUMP_PROMPT",description:"Write the resolved system prompt to a file at startup. Accepts a path or 1 for default location.",type:"string",required:!1,example:"/tmp/afk-prompt.txt",category:"debug"},{name:"ANTHROPIC_API_KEY",description:"Anthropic API key. Tier-1 credential \u2014 overrides keychain OAuth and CLAUDE_CODE_OAUTH_TOKEN.",type:"string",required:!1,category:"auth",secret:!0},{name:"CLAUDE_CODE_OAUTH_TOKEN",description:"Claude Code OAuth token. Tier-2 credential \u2014 used when ANTHROPIC_API_KEY is unset; falls back to keychain.",type:"string",required:!1,category:"auth",secret:!0},{name:"OPENAI_API_KEY",description:"OpenAI API key for the openai-compatible provider (gpt-*, o1*, o3*, o4* models).",type:"string",required:!1,category:"auth",secret:!0},{name:"CODEX_API_KEY",description:"Fallback OpenAI API key for the openai-compatible provider, read after OPENAI_API_KEY. Legacy name from the removed @openai/codex-sdk integration \u2014 prefer OPENAI_API_KEY.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_LOCAL_API_KEY",description:"Placeholder API key for local Anthropic-compatible servers (vllm-mlx, etc.). Set when AFK_LOCAL_BASE_URL is configured.",type:"string",required:!1,default:"local",example:"local",category:"auth",secret:!0},{name:"AFK_LOCAL_BASE_URL",description:"Base URL for a self-hosted Anthropic-compatible server. When set, routes traffic away from api.anthropic.com.",type:"string",required:!1,example:"http://127.0.0.1:8080",category:"model"},{name:"AFK_OPENAI_BASE_URL",description:"Base URL override for the OpenAI-compatible provider. Used for local shims (mlx_lm.server, Ollama, vLLM, LM Studio). The OpenAI SDK appends `/chat/completions` itself \u2014 a value ending in `/chat/completions` will be stripped at config-load time with a one-shot warning.",type:"string",required:!1,example:"http://127.0.0.1:8000/v1",category:"model"},{name:"AFK_OPENAI_USE_RESPONSES",description:"Opt the OpenAI-compatible provider into the OpenAI Responses API instead of Chat Completions for API-key sessions. Truthy values: 1, true, yes, on. The ChatGPT-subscription OAuth path uses Responses automatically regardless of this flag.",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_OPENAI_CHATGPT_OAUTH",description:"Opt into using ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. Off by default. READ-ONLY: AFK never refreshes these tokens \u2014 re-run `codex` when the access token expires. Routes requests over the Responses API to the private ChatGPT backend (chatgpt.com/backend-api).",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_PROVIDER",description:"Force provider selection (anthropic | anthropic-direct | openai | openai-compatible | openai-codex). Overrides the model-name heuristic. Same surface as the --provider CLI flag; CLI flag wins when both are set.",type:"string",required:!1,example:"openai-compatible",category:"model"},{name:"EXA_API_KEY",description:"Exa (exa.ai) search API key, enabling web_scrape search mode. Free tier (20k requests/month) available at https://exa.ai. When unset, search mode returns an actionable error; markdown and raw modes are unaffected.",type:"string",required:!1,category:"auth",secret:!0},{name:"TELEGRAM_BOT_TOKEN",description:"Telegram bot token from @BotFather. Required to run the Telegram bot surface.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_BOT_TOKEN",description:"Alternative env var name for the Telegram bot token, accepted by the setup wizard.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_ALLOWED_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs allowed to interact with the bot. Required when the bot is running.",type:"string",required:!1,example:"123456789,987654321",category:"telegram"},{name:"AFK_TELEGRAM_TAG_ONLY_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs where the bot answers only when addressed (a reply to the bot, an @mention of the bot, or a text_mention resolving to the bot). Slash-commands are unaffected; chats not listed behave as usual. The afk.config.json telegram.tagOnlyChats block takes precedence. Requires Telegram privacy mode OFF (BotFather /setprivacy Disable) for non-addressed group messages to reach the bot.",type:"string",required:!1,example:"-100987654321,123456789",category:"telegram"},{name:"AFK_TELEGRAM_PRIMARY_CHAT_ID",description:"Default chat ID for outbound notifications (primary-mode routing). When unset, notifications go to the first private/DM chat in AFK_TELEGRAM_ALLOWED_CHAT_IDS. The afk.config.json telegram.notify block takes precedence.",type:"string",required:!1,example:"123456789",category:"telegram"},{name:"AFK_TELEGRAM_NOTIFY_MODE",description:"Outbound notification fan-out: primary (default \u2014 one chat), broadcast (every allowed chat), or custom (afk.config.json telegram.notify.targets). The afk.config.json telegram.notify.mode takes precedence.",type:"string",required:!1,example:"broadcast",category:"telegram"},{name:"TELEGRAM_DATA_DIR",description:"Override the directory where Telegram bot state is stored. Defaults to ~/.afk/state/telegram/.",type:"string",required:!1,category:"telegram"},{name:"TELEGRAM_VERBOSE",description:"Set to a truthy value ('1'/'true'/'yes'/'on', case-insensitive) to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"true",category:"telegram"},{name:"AFK_TELEGRAM_TRACE",description:"Set to 1 to dump raw bridge traffic between the agent and the Telegram bot \u2014 debugging only.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_TELEGRAM_CWD",description:"Override the working directory used by the Telegram bot when spawning agent sessions.",type:"string",required:!1,category:"telegram"},{name:"AFK_HOME",description:"Override the AFK home directory. Default: ~/.afk/.",type:"string",required:!1,default:"~/.afk",example:"/opt/afk",category:"paths"},{name:"AFK_STATE_DIR",description:"Override the entire AFK state tier (sessions/, todos/, transcripts/, memory/, daemon/, etc.), not just one subdirectory. Must be an absolute path (not /). Default: $AFK_HOME/state/.",type:"string",required:!1,category:"paths"},{name:"AFK_FRAMEWORK_DIR",description:"Override the AFK agent-framework directory used for telemetry and briefs. Default: $AFK_HOME/agent-framework/.",type:"string",required:!1,category:"paths"},{name:"AFK_COMPANION_PRIMER",description:'Opt-in: absolute path to a single companion-primer file. When set, its content is bounded (capped, fenced as <companion-primer>) and appended to the system prompt at session start for top-level sessions (chat/REPL/telegram/daemon), as lower-authority "reflections, not facts" context. Unset (default) = no-op. Only the one named file is ever read \u2014 never a directory or repo walk.',type:"string",required:!1,example:"/Users/me/Projects/afk-companion/PRIMER.md",category:"paths"},{name:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_ON_EXIT",description:"Clean-worktree quit policy for interactive --worktree sessions: ask, keep, or remove.",type:"string",required:!1,example:"ask",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Opt-in to loading + spawning MCP servers declared in <cwd>/.mcp.json. Fail-closed: when unset (or 0), project-local servers are NOT spawned; set to a truthy value (1/true/yes/on) to load them. A project-local .mcp.json spawns arbitrary commands on session start, so it is off by default to prevent code execution when entering an untrusted repo (issue #571). Skipped servers are listed in a startup warning with the opt-in instruction.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BG_AUTO_DELIVER",description:"Auto-deliver background subagent results into the model context on the next user turn (interactive REPL). On by default. Set to 0, false, off, or no (case-insensitive) to disable, restoring the manual /bgsub:join retrieval flow.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_PLAIN_OUTPUT",description:"Force the interactive REPL to fully behave like a non-TTY surface for rendering purposes, even when stdout/stdin ARE a TTY: append-only plain-stdout output instead of the TerminalCompositor live overlay (both the persistent between-turn compositor AND the per-turn StreamRenderer overlay), AND the input surface downgrades to the simple non-TTY line reader instead of the fancy compositor-backed input box. Same code path already used for non-TTY surfaces (pipes, CI). Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM scroll regions misbehave \u2014 trades the live overlay and fancy input UX for reliability. Opt-in \u2014 default TTY behavior (live overlay + fancy input) is unchanged unless this var is set. Truthy values: 1, true (case-insensitive).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_GOBLIN_SPINNER",description:"Goblin-themed working spinner (olive frames + goblin verbs) while the agent runs tools. 1 = on (default), 0 = classic dim spinner.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_GOBLIN_MASCOT",description:"Reacting goblin mini-sprite in the reserved footer band while the agent runs tools (3 rows, animated). 1 = on, unset/0 = off (default). Claims terminal rows, so it is opt-in.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_TERM_TITLE",description:'Set the terminal/tab title (OSC 2) to reflect afk state \u2014 "afk \u2014 <cwd> \xB7 running" during a turn, "afk \u2014 <cwd>" when idle, cleared on exit. 1 = on (default when stdout is a TTY), 0 = leave the title alone. TTY-only.',type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_NOTIFY",description:"Emit a desktop completion notification (OSC 9) on turn completion, for terminals that map OSC 9 to system notifications (iTerm2, kitty, WezTerm). Opt-in and off by default (intrusive). 1 = on. TTY-only.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_THEME",description:"TUI color palette for the interactive REPL and all CLI rendering: dark | light | umber | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark; umber matches the Umber terminal, is dark-only, and is never chosen by auto. Overridden per-launch by --theme and mutable mid-session via /theme. Precedence: --theme flag > this env > config theme > auto-detect > dark. Invalid values are ignored (dark).",type:"string",required:!1,default:"dark",example:"light",category:"misc"},{name:"AFK_TEXT_MEASURE",description:"Maximum line length (columns) for unbordered streamed text in the interactive REPL: assistant prose, thinking blocks, tool-lane text, and subagent text. Display-only \u2014 affects wrapping, never behavior. Bordered elements (cards, error boxes) already cap at 100; this applies the same ceiling to the unbordered surfaces, which previously scaled to the full terminal width. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable capping and restore full-width wrapping. Unparseable or below-minimum values fall back to the default. No-op on terminals at or below the measure, so narrow terminals are unaffected.",type:"string",required:!1,default:"100",example:"full",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_CAPTURE_SUBAGENT_PROMPTS",description:"Opt-in: when set to 1, every prompt a parent session sends to a subagent is written as a redacted markdown file under state/witness/<label>/prompts/. Off by default because nothing prunes the witness tree and prompts may carry secrets the regex redactor cannot catch (connection strings, PEM blocks, PII).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless on every AFK surface \u2014 the CLI entrypoint reports surface `afk`, which is in the headless set \u2014 so watching the agent work in a visible window is opt-in via `AFK_BROWSER_HEADLESS=0`, not implied by running the REPL. Note headed and headless use different chromium downloads (`chromium-*` vs `chromium_headless_shell-*`).",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_ALLOWED_DOMAINS",description:"Comma-separated allowlist of URL host globs. When set, browser_open and any navigation that targets a host outside the list returns status: blocked_by_policy. Unset means no allowlist (permissive). Patterns use simple `*` glob matching against the URL host. Combines with AFK_BROWSER_BLOCKED_DOMAINS \u2014 block wins.",type:"string",required:!1,example:"github.com,*.atlassian.net",category:"browser"},{name:"AFK_BROWSER_BLOCKED_DOMAINS",description:"Comma-separated blocklist of URL host globs. Browser navigation that matches any entry returns status: blocked_by_policy regardless of the allowlist.",type:"string",required:!1,example:"*.ads.example.com",category:"browser"},{name:"AFK_BROWSER_DOM_SNAPSHOTS",description:"Phase 2 opt-in: when set to 1, every browser_act writes a gzipped DOM snapshot sidecar under ~/.afk/state/witness/<sid>/browser/dom-snapshots/. Off by default because snapshots are large; useful for post-mortem analysis of failed actions.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_BACKEND",description:"Select the browser provider backend. Phase 1 supports only `playwright`. Reserved for future `cdp` / `mcp` adapters. Unset defaults to `playwright`.",type:"string",required:!1,example:"playwright",category:"browser"},{name:"AFK_BROWSER_CONFIG",description:"Absolute path to an alternate browser config file. Overrides the default ~/.afk/config/browser.json lookup. Useful for per-project overrides in CI.",type:"string",required:!1,example:"/path/to/browser.json",category:"browser"},{name:"AFK_BROWSER_DEFAULT_PROFILE",description:"Name of the persistent session-vault profile the agent reuses for browser sessions. The context restores its login from (and saves it back to) ~/.afk/state/browser/<profile>/storageState.json, so a human runs `afk browser login --profile <name>` once and the agent reuses that authenticated session across unattended runs. Unset defaults to `default` (a fresh, empty profile \u2014 identical to pre-vault behavior). Allowed charset: [A-Za-z0-9_-], max 128 chars.",type:"string",required:!1,example:"work",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_READ_DENYLIST",description:"Colon-separated list of additional absolute paths the read_file/grep/glob/list_directory tools refuse to read, and that the bash-restriction hook refuses to let a shell command reference on interactive surfaces (REPL, Telegram) \u2014 on headless surfaces (afk chat, daemon) bash fails open regardless of this list. A leading ~/ is expanded (~user/ is not \u2014 spell those absolutely). Built-in credential entries (~/.ssh, ~/.aws, ~/.afk/config, \u2026) always apply on top and cannot be removed. One built-in exception exists: ~/.afk/config/mcp.json (the MCP registry) IS readable \u2014 paths listed here outrank that carve-out, so set this to ~/.afk/config/mcp.json if your registry holds inline secrets rather than ${VAR} placeholders.",type:"string",required:!1,example:"/Users/me/project/.env:/Users/me/secrets",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_WEB_ALLOW_PRIVATE_HOSTS",description:"Opt out of the web_scrape SSRF egress guard. When unset (default) the guard is ACTIVE: the markdown, raw, and headless-render paths refuse loopback (127/8, ::1), link-local (169.254/16 \u2014 including the 169.254.169.254 cloud instance-metadata endpoint), RFC1918 (10/8, 172.16/12, 192.168/16), carrier-grade NAT (100.64/10), IPv6 unique-local (fc00::/7), 0.0.0.0/8, and the IPv4-mapped/compatible IPv6 forms of all of those. Hostnames are resolved and the RESOLVED addresses are classified (DNS-rebinding guard), and the check is re-applied on every redirect hop. Set to 1/true to allow private-host access \u2014 needed only to scrape a local dev server. Enabling it restores a model-reachable SSRF path (issue #575).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"VISUAL",description:"Standard POSIX env var naming the user's preferred full-screen editor (with optional flags). Consulted FIRST by the /editor slash command (and its key chord) to compose a long prompt externally; takes precedence over EDITOR. No fallback editor is assumed \u2014 if neither VISUAL nor EDITOR is set, /editor prints a hint instead of guessing.",type:"string",required:!1,example:"nvim",category:"process"},{name:"EDITOR",description:"Standard POSIX env var naming the user's preferred editor (with optional flags). Consulted by the /editor slash command AFTER VISUAL, as the standard fallback. No default editor is assumed when both are unset \u2014 /editor prints a hint telling the user to set one.",type:"string",required:!1,example:"vim",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],b={get AFK_COMPACT_KEEP_LAST_TURNS(){return process.env.AFK_COMPACT_KEEP_LAST_TURNS},get AFK_COMPACT_MODEL(){return process.env.AFK_COMPACT_MODEL},get AFK_COMPACT_SHRINK_FRACTION(){return process.env.AFK_COMPACT_SHRINK_FRACTION},get AFK_COMPANION_PRIMER(){return process.env.AFK_COMPANION_PRIMER},get AFK_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_NESTING_DEPTH(){return process.env.AFK_MAX_NESTING_DEPTH},get AFK_MAX_OUTPUT_TOKENS(){return process.env.AFK_MAX_OUTPUT_TOKENS},get AFK_MAX_TOKENS(){return process.env.AFK_MAX_TOKENS},get AFK_MAX_TOOL_USE_ITERATIONS(){return process.env.AFK_MAX_TOOL_USE_ITERATIONS},get AFK_MEMORY_EVIDENCE_GATE(){return process.env.AFK_MEMORY_EVIDENCE_GATE},get AFK_MICROCOMPACT_KEEP_LAST(){return process.env.AFK_MICROCOMPACT_KEEP_LAST},get AFK_MICROCOMPACT_TOOL_RESULT_BYTES(){return process.env.AFK_MICROCOMPACT_TOOL_RESULT_BYTES},get AFK_MODEL(){return process.env.AFK_MODEL},get AFK_MODEL_TTFB_TIMEOUT_MS(){return process.env.AFK_MODEL_TTFB_TIMEOUT_MS},get AFK_MODEL_STALL_TIMEOUT_MS(){return process.env.AFK_MODEL_STALL_TIMEOUT_MS},get AFK_MODEL_LARGE(){return process.env.AFK_MODEL_LARGE},get AFK_MODEL_LARGE_API_KEY(){return process.env.AFK_MODEL_LARGE_API_KEY},get AFK_MODEL_LARGE_BASE_URL(){return process.env.AFK_MODEL_LARGE_BASE_URL},get AFK_MODEL_LOCAL(){return process.env.AFK_MODEL_LOCAL},get AFK_MODEL_LOCAL_API_KEY(){return process.env.AFK_MODEL_LOCAL_API_KEY},get AFK_MODEL_LOCAL_BASE_URL(){return process.env.AFK_MODEL_LOCAL_BASE_URL},get AFK_MODEL_MEDIUM(){return process.env.AFK_MODEL_MEDIUM},get AFK_MODEL_MEDIUM_API_KEY(){return process.env.AFK_MODEL_MEDIUM_API_KEY},get AFK_MODEL_MEDIUM_BASE_URL(){return process.env.AFK_MODEL_MEDIUM_BASE_URL},get AFK_MODEL_SMALL(){return process.env.AFK_MODEL_SMALL},get AFK_MODEL_SMALL_API_KEY(){return process.env.AFK_MODEL_SMALL_API_KEY},get AFK_MODEL_SMALL_BASE_URL(){return process.env.AFK_MODEL_SMALL_BASE_URL},get AFK_VISION_MODELS(){return process.env.AFK_VISION_MODELS},get AFK_OVERLOAD_PAUSE_MS(){return process.env.AFK_OVERLOAD_PAUSE_MS},get AFK_PROMPT_CACHE_TTL(){return process.env.AFK_PROMPT_CACHE_TTL},get AFK_SUGGEST_ENABLED(){return process.env.AFK_SUGGEST_ENABLED},get AFK_SUGGEST_GHOST(){return process.env.AFK_SUGGEST_GHOST},get AFK_SUGGEST_MODEL(){return process.env.AFK_SUGGEST_MODEL},get AFK_SUBAGENT_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_TIMEOUT_MS},get AFK_SUBAGENT_IDLE_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_IDLE_TIMEOUT_MS},get AFK_TASK_BUDGET(){return process.env.AFK_TASK_BUDGET},get AFK_TEMPERATURE(){return process.env.AFK_TEMPERATURE},get AFK_THINKING(){return process.env.AFK_THINKING},get AFK_THINKING_UI(){return process.env.AFK_THINKING_UI},get AFK_TIMEOUT_MS(){return process.env.AFK_TIMEOUT_MS},get CLAUDE_MODEL(){return process.env.CLAUDE_MODEL},get AFK_SYSTEM_PROMPT(){return process.env.AFK_SYSTEM_PROMPT},get AFK_DUMP_PROMPT(){return process.env.AFK_DUMP_PROMPT},get ANTHROPIC_API_KEY(){return process.env.ANTHROPIC_API_KEY},get CLAUDE_CODE_OAUTH_TOKEN(){return process.env.CLAUDE_CODE_OAUTH_TOKEN},get OPENAI_API_KEY(){return process.env.OPENAI_API_KEY},get CODEX_API_KEY(){return process.env.CODEX_API_KEY},get AFK_LOCAL_API_KEY(){return process.env.AFK_LOCAL_API_KEY},get AFK_LOCAL_BASE_URL(){return process.env.AFK_LOCAL_BASE_URL},get AFK_OPENAI_BASE_URL(){return process.env.AFK_OPENAI_BASE_URL},get AFK_OPENAI_USE_RESPONSES(){return process.env.AFK_OPENAI_USE_RESPONSES},get AFK_OPENAI_CHATGPT_OAUTH(){return process.env.AFK_OPENAI_CHATGPT_OAUTH},get AFK_PROVIDER(){return process.env.AFK_PROVIDER},get EXA_API_KEY(){return process.env.EXA_API_KEY},get TELEGRAM_BOT_TOKEN(){return process.env.TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_BOT_TOKEN(){return process.env.AFK_TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_ALLOWED_CHAT_IDS(){return process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS},get AFK_TELEGRAM_TAG_ONLY_CHAT_IDS(){return process.env.AFK_TELEGRAM_TAG_ONLY_CHAT_IDS},get AFK_TELEGRAM_PRIMARY_CHAT_ID(){return process.env.AFK_TELEGRAM_PRIMARY_CHAT_ID},get AFK_TELEGRAM_NOTIFY_MODE(){return process.env.AFK_TELEGRAM_NOTIFY_MODE},get TELEGRAM_DATA_DIR(){return process.env.TELEGRAM_DATA_DIR},get TELEGRAM_VERBOSE(){return process.env.TELEGRAM_VERBOSE},get AFK_TELEGRAM_TRACE(){return process.env.AFK_TELEGRAM_TRACE},get AFK_TELEGRAM_CWD(){return process.env.AFK_TELEGRAM_CWD},get AFK_HOME(){return process.env.AFK_HOME},get AFK_STATE_DIR(){return process.env.AFK_STATE_DIR},get AFK_FRAMEWORK_DIR(){return process.env.AFK_FRAMEWORK_DIR},get HOME(){return process.env.HOME},get PATH(){return process.env.PATH},get AFK_DAEMON_CWD(){return process.env.AFK_DAEMON_CWD},get AFK_DAEMON_TASK(){return process.env.AFK_DAEMON_TASK},get AFK_DAEMON_TASK_ID(){return process.env.AFK_DAEMON_TASK_ID},get AFK_DAEMON_HOST(){return process.env.AFK_DAEMON_HOST},get AFK_SESSIONSTART_COOLDOWN_MS(){return process.env.AFK_SESSIONSTART_COOLDOWN_MS},get AFK_WORKTREE_AUTONAME(){return process.env.AFK_WORKTREE_AUTONAME},get AFK_WORKTREE_BRANCH_PREFIX(){return process.env.AFK_WORKTREE_BRANCH_PREFIX},get AFK_WORKTREE_BASE(){return process.env.AFK_WORKTREE_BASE},get AFK_WORKTREE_ON_EXIT(){return process.env.AFK_WORKTREE_ON_EXIT},get AFK_WORKTREE_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BG_AUTO_DELIVER(){return process.env.AFK_BG_AUTO_DELIVER},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_PLAIN_OUTPUT(){return process.env.AFK_PLAIN_OUTPUT},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},get AFK_GOBLIN_SPINNER(){return process.env.AFK_GOBLIN_SPINNER},get AFK_GOBLIN_MASCOT(){return process.env.AFK_GOBLIN_MASCOT},get AFK_TERM_TITLE(){return process.env.AFK_TERM_TITLE},get AFK_NOTIFY(){return process.env.AFK_NOTIFY},get AFK_SHOW_DIFFS(){return process.env.AFK_SHOW_DIFFS},get AFK_SKILL_STREAM_VERBOSE(){return process.env.AFK_SKILL_STREAM_VERBOSE},get FORCE_COLOR(){return process.env.FORCE_COLOR},get NO_COLOR(){return process.env.NO_COLOR},get AFK_THEME(){return process.env.AFK_THEME},get AFK_TEXT_MEASURE(){return process.env.AFK_TEXT_MEASURE},get COLORFGBG(){return process.env.COLORFGBG},get AFK_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get AFK_CAPTURE_SUBAGENT_PROMPTS(){return process.env.AFK_CAPTURE_SUBAGENT_PROMPTS},get DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_BROWSER_DEFAULT_PROFILE(){return process.env.AFK_BROWSER_DEFAULT_PROFILE},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_READ_DENYLIST(){return process.env.AFK_READ_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_WEB_ALLOW_PRIVATE_HOSTS(){return process.env.AFK_WEB_ALLOW_PRIVATE_HOSTS},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get VISUAL(){return process.env.VISUAL},get EDITOR(){return process.env.EDITOR},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let e of go){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(b,e.name);n&&Object.defineProperty(b,e.name,{...n,enumerable:!1})}})()});function XS(){return b.AFK_DEBUG==="1"||b.DEBUG==="1"}function x(...t){XS()&&console.log(...t)}var Z=we(()=>{"use strict";P()});import{existsSync as Hd,mkdirSync as QS,renameSync as ZS,cpSync as ev,rmSync as tv}from"fs";import{join as j,dirname as _a,basename as nv,isAbsolute as Ta}from"path";import{homedir as Kd}from"os";import{fileURLToPath as rv}from"url";function le(){let t=b.AFK_HOME;if(t!==void 0&&t!==""){if(!Ta(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return j(Kd(),".afk")}function Te(){let t=b.AFK_FRAMEWORK_DIR;if(t!==void 0&&t!==""){if(!Ta(t)||t==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${t}`);return t}return j(le(),"agent-framework")}function yo(){return j(Te(),"forge-telemetry.jsonl")}function Gd(){return j(Te(),"briefs")}function qd(){return j(Te(),"facets")}function Bn(){return j(le(),"skills")}function Xt(){return j(le(),"plugins")}function zd(t=process.cwd()){return j(t,".afk")}function Jd(t=process.cwd()){return j(zd(t),"skills")}function Vd(t=process.cwd()){return j(zd(t),"plugins")}function Yd(t=process.cwd()){return j(t,".afk","plans")}function bo(){return j(Xt(),".index.json")}function xa(){return j(jn(),"schedules.json")}function Xd(){let t=rv(import.meta.url),e=_a(t);return j(e,"bundled-plugins")}function jn(){return j(le(),"config")}function fe(){let t=b.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!Ta(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return j(le(),"state")}function Se(){return j(fe(),"sessions")}function wo(){return j(fe(),"presence")}function So(){return j(fe(),"memory")}function vo(){return j(fe(),"session-grants.jsonl")}function Qd(){return j(le(),"farms")}function Zd(t){return j(Qd(),t)}function ko(t){if(!ov.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function Ao(t){return ko(t),j(fe(),"witness",t)}function eu(t){return j(Ao(t),"inbound-attachments")}function tu(t){return j(Ao(t),"prompts")}function Eo(t){return!t||t.startsWith("in-memory:")?null:nv(_a(t))}function nu(t="default"){return j(fe(),"daemon",`agent-afk@${t}`)}function ru(){return j(fe(),"worktree-sweep.lock")}function _o(){return j(fe(),"worktree-roots.json")}function Ra(){return j(jn(),"afk.env")}function Qt(){return j(jn(),"afk.config.json")}function To(){return j(Kd(),".afk.config.json")}function sv(){return j(le(),"sessions")}function iv(t,e){if(t!==e&&Hd(t)&&!Hd(e))try{QS(_a(e),{recursive:!0});try{ZS(t,e)}catch(n){if(n.code==="EXDEV")try{ev(t,e,{recursive:!0}),tv(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
2
2
  `)}}}catch{}}function ou(){iv(sv(),Se())}function Ia(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>Wd)throw new Error(`Invalid browser profile: exceeds ${Wd} chars`);if(!av.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function lv(){return j(fe(),"browser")}function cv(t){return Ia(t),j(lv(),t)}function Ca(t){return j(cv(t),"storageState.json")}function Hn(t){return typeof t=="string"&&t.length>0&&t.length<=uv&&dv.test(t)}function Wn(t){if(!Hn(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return j(Se(),t)}function xo(t){return j(Wn(t),"events.jsonl")}function su(t){return j(Wn(t),"session.key")}var ov,av,Wd,dv,uv,F=we(()=>{"use strict";P();ov=/^[a-zA-Z0-9_-]+$/;av=/^[A-Za-z0-9_-]+$/,Wd=128;dv=/^[A-Za-z0-9_-]+$/,uv=128});import{readFileSync as VT}from"node:fs";import{join as YT}from"path";function XT(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Qf(t,e){return XT(e).test(t)}function ex(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(QT.has(e))return!0;if(ZT.has(e))return!1}return!1}function Zf(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function tx(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function em(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Ia(e),e}function nx(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function rx(t){try{return VT(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function ox(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=em(e.defaultProfile)),n}function tm(t){let e=t?.env??b,n=t?.readFileSync??rx,r=t?.surface??e.AGENT_SURFACE,o=ex(e.AFK_BROWSER_HEADLESS,r),s=Zf(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Zf(e.AFK_BROWSER_BLOCKED_DOMAINS),a=nx(e.AFK_BROWSER_DOM_SNAPSHOTS),l=tx(e.AFK_BROWSER_BACKEND),c=em(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():YT(jn(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(h){throw new Error(`Failed to parse browser config at ${p}: ${String(h)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=ox(d,m);return g.configPath=p,g}function As(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(Qf(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Qf(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var QT,ZT,Es=we(()=>{"use strict";P();F();QT=new Set(["daemon","subagent","telegram","afk"]),ZT=new Set(["repl","interactive","cli"])});import{existsSync as sx,readFileSync as ix}from"node:fs";import{createRequire as ax}from"node:module";import{dirname as lx,join as cx}from"node:path";function om(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<ux&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function be(t){let e=om(t);return rm.some(n=>e.includes(n))}function px(){try{let e=ax(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(ix(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=cx(lx(e),o);return sx(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function kr(){return nm??=px()??dx,nm}function $l(t){return t.includes("install chromium")}function Oe(t,e){let n=om(t),r=e?.latched===!0?` ${fx}`:"";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: ${kr()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${kr()}). Or pick a different tool.${r}`}function Bl(t,e,n=!1){if(!be(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
3
3
 
4
- ${Oe(t,{headless:e,latched:n})}`,{cause:t})}var rm,dx,ux,nm,fx,jl=we(()=>{"use strict";rm=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],dx="pnpm exec playwright install chromium",ux=4;fx="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 jt from"node:fs";import _s from"node:path";import{randomBytes as mx}from"node:crypto";import{chromium as gx}from"playwright";function hx(){try{return"5.95.0"}catch{}try{let t=_s.resolve(import.meta.dirname,"../../../package.json"),e=jt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var yx,Ts,sm=we(()=>{"use strict";jl();F();Z();yx=hx(),Ts=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=gx.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Bl(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){s=l,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let c=await a.content();if(s!==void 0)throw s;let d=a.url(),u=l!==null?l.status():null;return{html:c,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${yx}`}}loadStorageState(e){let n=Ca(e);try{if(!jt.existsSync(n))return;let r=JSON.parse(jt.readFileSync(n,"utf8"));return x("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){x("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Ca(e);if(!jt.existsSync(r))return;let o=await n.storageState(),s=_s.join(_s.dirname(r),`.${_s.basename(r)}.${process.pid}.${mx(4).toString("hex")}.tmp`);jt.writeFileSync(s,JSON.stringify(o),{mode:384}),jt.chmodSync(s,384),jt.renameSync(s,r),x("[browser/vault] saved session",{profile:e,file:r})}catch(r){x("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as bx}from"crypto";function im(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&wx.test(t.label))}function am(t){return bx("sha256").update(t,"utf8").digest("hex").slice(0,8)}function lm(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var wx,xs=we(()=>{"use strict";wx=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Sx}from"node:crypto";function vx(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function kx(t,e,n){return`el_${Sx("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function Ax(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function cm(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function um(t,e){let n=t.role??"",r=t.name??"";dm.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])um(s,e)}async function Ex(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},pm).catch(()=>[])}async function _x(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},pm).catch(()=>[])}function Tx(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Rs(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=Tx(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Ex(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,y=!1;u!==null?(h=[],um(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await _x(t)).filter(W=>dm.has(W.role??"")));let w=new Map;for(let A of p){let W=cm(A.name),te=w.get(W);(!te||te.bbox.w===0&&A.bbox.w>0)&&w.set(W,A)}let v=h.map(A=>({ax:A,dom:w.get(cm(A.name??""))})),S=r?v:v.filter(A=>A.dom?A.dom.bbox.w>0||A.dom.bbox.h>0:!0);S.sort((A,W)=>{let te=A.dom?.bbox.y??0,O=W.dom?.bbox.y??0;if(te!==O)return te-O;let $=A.dom?.bbox.x??0,M=W.dom?.bbox.x??0;return $-M}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=S.slice(0,n).map((A,W)=>{let te=A.ax.role??"generic",O=A.ax.name??"",$=kx(te,O,W),M=A.dom?.bbox??{x:0,y:0,w:0,h:0},C=A.dom?.type??null,K=null;A.ax.value!==void 0&&A.ax.value!==null&&(K=String(A.ax.value)),A.ax.checked!==void 0&&(K=String(A.ax.checked)),im({role:te,kind:C})&&(K="[redacted]");let L={disabled:A.ax.disabled??!1};A.ax.checked!==void 0&&(L.checked=A.ax.checked===!0||A.ax.checked==="mixed"),A.ax.selected!==void 0&&(L.selected=A.ax.selected),A.ax.expanded!==void 0&&(L.expanded=A.ax.expanded);let z;A.dom?.testId?z=`[data-testid="${A.dom.testId}"]`:A.dom?.id&&(z=`#${A.dom.id}`);let X={id:$,role:te,label:vx(O),kind:C,value:K,state:L,bbox:M};return z!==void 0&&(X.selector=z),X}),R="idle";try{let A=await t.evaluate(()=>document.readyState);A==="loading"?R="loading":A==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let U=Ax(f),_=`obs_${e.observationCounter.toString(36)}`,I=new Date().toISOString();return{observationId:_,url:m,title:g,textSummary:U,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:I}}var dm,pm,fm=we(()=>{"use strict";xs();dm=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);pm="a[href], button, input, select, textarea, [role], [tabindex], label"});async function mm(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Hl(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>mm(t,s)))).filter(o=>o!==null)}async function xx(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Wl(t,e,n){switch(e.kind){case"element_id":return Rx(t,e,n);case"selector":return Ix(t,e);case"semantic":return Cx(t,e)}}async function Rx(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Hl(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Ix(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 Hl(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function Cx(t,e){return e.role!==void 0?Px(t,e.text,e.role):Mx(t,e.text,e)}async function Px(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 Hl(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Mx(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:s,count:l});let u=await xx(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let h=p[g];if(h===void 0)continue;let y=await mm(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,v=0;for(let S=0;S<w.length;S++)v=v*31+w.charCodeAt(S)>>>0;f.push({...y,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var gm=we(()=>{"use strict"});async function Kl(t,e,n,r){let o=t.url();if(o===n)return null;let s=As(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 hm=we(()=>{"use strict";Es()});import{randomBytes as Ox}from"crypto";import{mkdir as Dx,stat as Fx,writeFile as Lx}from"fs/promises";import{join as Gl}from"path";import{gzip as Nx}from"zlib";import{promisify as Ux}from"util";function $x(t){return Gl(Ao(t),"browser")}function Bx(t){return Gl($x(t),"screenshots")}function jx(){return new Date().toISOString().replace(/[:.]/g,"-")}function Hx(){return Ox(3).toString("hex")}async function ql(t,e,n){if(e.length>ym)throw new Error(`writeScreenshotSidecar: buffer exceeds ${ym} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=Bx(t);await Dx(r,{recursive:!0});let o=`${jx()}-${Hx()}-${n}.png`,s=Gl(r,o);await Lx(s,e);let{size:i}=await Fx(s);return{path:s,bytes:i}}var aW,ym,bm=we(()=>{"use strict";F();xs();aW=Ux(Nx);ym=5*1024*1024});var Sm={};jd(Sm,{PlaywrightProvider:()=>zl});function wm(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 zl,vm=we(()=>{"use strict";sm();fm();gm();Es();hm();bm();zl=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Ts(e)}async open(e){let n=As(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await Kl(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 Rs(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 Rs(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 Wl(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${wm(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){c=h}else c=g}let u=await Kl(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Rs(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Wl(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${wm(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 ql(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await ql(n,o,r);return s}catch{return null}}}});var Wt={};jd(Wt,{__resetBrowserRegistryForTests:()=>zx,browserProviderActive:()=>Gx,closeBrowserProvider:()=>Jl,getBrowserProvider:()=>Kx,peekBrowserProvider:()=>qx});function km(){Promise.resolve(Jl()).then(()=>{process.exit(130)})}function Am(){Promise.resolve(Jl()).then(()=>{process.exit(143)})}function Em(){Ge=null}function Wx(){Is||(process.on("SIGINT",km),process.on("SIGTERM",Am),process.on("exit",Em),Is=!0)}function _m(){Is&&(process.removeListener("SIGINT",km),process.removeListener("SIGTERM",Am),process.removeListener("exit",Em),Is=!1)}async function Kx(t){return Ge!==null?Ge:(Ht!==null||(Ht=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(vm(),Sm)),n=tm(t),r=new e(n);return Wx(),Ge=r,Ht=null,r})()),Ht)}async function Jl(){if(Ge===null)return;let t=Ge;Ge=null,Ht=null,_m(),await t.shutdown()}function Gx(){return Ge!==null}function qx(){return Ge}function zx(){Ge=null,Ht=null,_m()}var Ge,Ht,Is,Kt=we(()=>{"use strict";Es();Ge=null,Ht=null,Is=!1});Z();P();F();Z();import{randomBytes as kv}from"node:crypto";import{mkdir as Av,writeFile as Ev}from"node:fs/promises";import{join as _v}from"node:path";P();import{mkdirSync as pv,appendFileSync as fv,existsSync as mv}from"fs";import{resolve as gv}from"path";import{dirname as hv}from"path";var yv=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
4
+ ${Oe(t,{headless:e,latched:n})}`,{cause:t})}var rm,dx,ux,nm,fx,jl=we(()=>{"use strict";rm=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],dx="pnpm exec playwright install chromium",ux=4;fx="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 jt from"node:fs";import _s from"node:path";import{randomBytes as mx}from"node:crypto";import{chromium as gx}from"playwright";function hx(){try{return"5.95.2"}catch{}try{let t=_s.resolve(import.meta.dirname,"../../../package.json"),e=jt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var yx,Ts,sm=we(()=>{"use strict";jl();F();Z();yx=hx(),Ts=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=gx.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Bl(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){s=l,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let c=await a.content();if(s!==void 0)throw s;let d=a.url(),u=l!==null?l.status():null;return{html:c,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${yx}`}}loadStorageState(e){let n=Ca(e);try{if(!jt.existsSync(n))return;let r=JSON.parse(jt.readFileSync(n,"utf8"));return x("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){x("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Ca(e);if(!jt.existsSync(r))return;let o=await n.storageState(),s=_s.join(_s.dirname(r),`.${_s.basename(r)}.${process.pid}.${mx(4).toString("hex")}.tmp`);jt.writeFileSync(s,JSON.stringify(o),{mode:384}),jt.chmodSync(s,384),jt.renameSync(s,r),x("[browser/vault] saved session",{profile:e,file:r})}catch(r){x("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as bx}from"crypto";function im(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&wx.test(t.label))}function am(t){return bx("sha256").update(t,"utf8").digest("hex").slice(0,8)}function lm(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var wx,xs=we(()=>{"use strict";wx=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Sx}from"node:crypto";function vx(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function kx(t,e,n){return`el_${Sx("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function Ax(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function cm(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function um(t,e){let n=t.role??"",r=t.name??"";dm.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])um(s,e)}async function Ex(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},pm).catch(()=>[])}async function _x(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},pm).catch(()=>[])}function Tx(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Rs(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=Tx(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Ex(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,y=!1;u!==null?(h=[],um(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await _x(t)).filter(W=>dm.has(W.role??"")));let w=new Map;for(let A of p){let W=cm(A.name),te=w.get(W);(!te||te.bbox.w===0&&A.bbox.w>0)&&w.set(W,A)}let v=h.map(A=>({ax:A,dom:w.get(cm(A.name??""))})),S=r?v:v.filter(A=>A.dom?A.dom.bbox.w>0||A.dom.bbox.h>0:!0);S.sort((A,W)=>{let te=A.dom?.bbox.y??0,O=W.dom?.bbox.y??0;if(te!==O)return te-O;let $=A.dom?.bbox.x??0,M=W.dom?.bbox.x??0;return $-M}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=S.slice(0,n).map((A,W)=>{let te=A.ax.role??"generic",O=A.ax.name??"",$=kx(te,O,W),M=A.dom?.bbox??{x:0,y:0,w:0,h:0},C=A.dom?.type??null,K=null;A.ax.value!==void 0&&A.ax.value!==null&&(K=String(A.ax.value)),A.ax.checked!==void 0&&(K=String(A.ax.checked)),im({role:te,kind:C})&&(K="[redacted]");let L={disabled:A.ax.disabled??!1};A.ax.checked!==void 0&&(L.checked=A.ax.checked===!0||A.ax.checked==="mixed"),A.ax.selected!==void 0&&(L.selected=A.ax.selected),A.ax.expanded!==void 0&&(L.expanded=A.ax.expanded);let z;A.dom?.testId?z=`[data-testid="${A.dom.testId}"]`:A.dom?.id&&(z=`#${A.dom.id}`);let X={id:$,role:te,label:vx(O),kind:C,value:K,state:L,bbox:M};return z!==void 0&&(X.selector=z),X}),R="idle";try{let A=await t.evaluate(()=>document.readyState);A==="loading"?R="loading":A==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let U=Ax(f),_=`obs_${e.observationCounter.toString(36)}`,I=new Date().toISOString();return{observationId:_,url:m,title:g,textSummary:U,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:I}}var dm,pm,fm=we(()=>{"use strict";xs();dm=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);pm="a[href], button, input, select, textarea, [role], [tabindex], label"});async function mm(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Hl(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>mm(t,s)))).filter(o=>o!==null)}async function xx(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Wl(t,e,n){switch(e.kind){case"element_id":return Rx(t,e,n);case"selector":return Ix(t,e);case"semantic":return Cx(t,e)}}async function Rx(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Hl(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Ix(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 Hl(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function Cx(t,e){return e.role!==void 0?Px(t,e.text,e.role):Mx(t,e.text,e)}async function Px(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 Hl(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Mx(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:s,count:l});let u=await xx(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let h=p[g];if(h===void 0)continue;let y=await mm(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,v=0;for(let S=0;S<w.length;S++)v=v*31+w.charCodeAt(S)>>>0;f.push({...y,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var gm=we(()=>{"use strict"});async function Kl(t,e,n,r){let o=t.url();if(o===n)return null;let s=As(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 hm=we(()=>{"use strict";Es()});import{randomBytes as Ox}from"crypto";import{mkdir as Dx,stat as Fx,writeFile as Lx}from"fs/promises";import{join as Gl}from"path";import{gzip as Nx}from"zlib";import{promisify as Ux}from"util";function $x(t){return Gl(Ao(t),"browser")}function Bx(t){return Gl($x(t),"screenshots")}function jx(){return new Date().toISOString().replace(/[:.]/g,"-")}function Hx(){return Ox(3).toString("hex")}async function ql(t,e,n){if(e.length>ym)throw new Error(`writeScreenshotSidecar: buffer exceeds ${ym} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=Bx(t);await Dx(r,{recursive:!0});let o=`${jx()}-${Hx()}-${n}.png`,s=Gl(r,o);await Lx(s,e);let{size:i}=await Fx(s);return{path:s,bytes:i}}var aW,ym,bm=we(()=>{"use strict";F();xs();aW=Ux(Nx);ym=5*1024*1024});var Sm={};jd(Sm,{PlaywrightProvider:()=>zl});function wm(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 zl,vm=we(()=>{"use strict";sm();fm();gm();Es();hm();bm();zl=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Ts(e)}async open(e){let n=As(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await Kl(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 Rs(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 Rs(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 Wl(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${wm(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){c=h}else c=g}let u=await Kl(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Rs(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Wl(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${wm(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 ql(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await ql(n,o,r);return s}catch{return null}}}});var Wt={};jd(Wt,{__resetBrowserRegistryForTests:()=>zx,browserProviderActive:()=>Gx,closeBrowserProvider:()=>Jl,getBrowserProvider:()=>Kx,peekBrowserProvider:()=>qx});function km(){Promise.resolve(Jl()).then(()=>{process.exit(130)})}function Am(){Promise.resolve(Jl()).then(()=>{process.exit(143)})}function Em(){Ge=null}function Wx(){Is||(process.on("SIGINT",km),process.on("SIGTERM",Am),process.on("exit",Em),Is=!0)}function _m(){Is&&(process.removeListener("SIGINT",km),process.removeListener("SIGTERM",Am),process.removeListener("exit",Em),Is=!1)}async function Kx(t){return Ge!==null?Ge:(Ht!==null||(Ht=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(vm(),Sm)),n=tm(t),r=new e(n);return Wx(),Ge=r,Ht=null,r})()),Ht)}async function Jl(){if(Ge===null)return;let t=Ge;Ge=null,Ht=null,_m(),await t.shutdown()}function Gx(){return Ge!==null}function qx(){return Ge}function zx(){Ge=null,Ht=null,_m()}var Ge,Ht,Is,Kt=we(()=>{"use strict";Es();Ge=null,Ht=null,Is=!1});Z();P();F();Z();import{randomBytes as kv}from"node:crypto";import{mkdir as Av,writeFile as Ev}from"node:fs/promises";import{join as _v}from"node:path";P();import{mkdirSync as pv,appendFileSync as fv,existsSync as mv}from"fs";import{resolve as gv}from"path";import{dirname as hv}from"path";var yv=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
5
5
  `,bv=/key|token|secret|password|credential|auth/i,wv=[[/sk-ant-[A-Za-z0-9_\-]{8,200}/g,t=>`<REDACTED sk-ant length=${t[0].length}>`],[/sk-(?!ant-)[A-Za-z0-9_\-]{20,200}/g,t=>`<REDACTED sk- length=${t[0].length}>`],[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,t=>`<REDACTED Bearer length=${t[0].length}>`],[/AKIA[A-Z0-9]{16}/g,t=>`<REDACTED AKIA length=${t[0].length}>`],[/xox[baprs]-[A-Za-z0-9\-]{10,200}/g,t=>`<REDACTED xox token length=${t[0].length}>`],[/\d{8,12}:[A-Za-z0-9_\-]{35}/g,t=>`<REDACTED Telegram token length=${t[0].length}>`],[/([A-Za-z_]{3,}(?:[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]|[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll])[A-Za-z_]*)=([^\s]{16,})/g,t=>`${t[1]}=<REDACTED length=${t[2].length}>`],[/([A-Z_]{3,}(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=([^\s]{16,})/g,t=>`${t[1]}=<REDACTED length=${t[2].length}>`]];function Ma(t){let e=t;for(let[n,r]of wv)e=e.replace(n,(...o)=>{let s=o.slice(0,o.length-2);return r(s)});return e}function Pa(t){return typeof t=="string"?Ma(t):Array.isArray(t)?t.map(Pa):t}function Sv(t){if(t===null||typeof t!="object")return t;let e=t,n={...e},r=e.env;if(r&&typeof r=="object"){let o={};for(let[s,i]of Object.entries(r))bv.test(s)&&typeof i=="string"?o[s]=`<REDACTED length=${i.length}>`:o[s]=i;n.env=o}return"system"in e&&(n.system=Pa(e.system)),"systemPrompt"in e&&(n.systemPrompt=Pa(e.systemPrompt)),n}function vv(t){if(t==null)return{kind:"undefined",note:"SDK uses minimal prompt; claude_code preset NOT loaded"};if(typeof t=="string")return{kind:"custom-string",note:"SDK uses this string as full system prompt; claude_code preset NOT loaded"};if(Array.isArray(t))return{kind:"custom-string-array",note:"SDK uses array as full system prompt with cache boundaries; claude_code preset NOT loaded"};if(typeof t=="object"){let e=t;if(e.type==="preset"&&e.preset==="claude_code"){let n={kind:"preset-claude-code",note:"claude_code preset loaded"};return typeof e.append=="string"&&(n.append={length:e.append.length}),e.excludeDynamicSections===!0&&(n.excludeDynamicSections=!0),n}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}function iu(t){let e=b.AFK_DUMP_PROMPT;if(!e||e===""||e==="0"||e.toLowerCase()==="false")return;process.stderr.write(`[--dump-prompt] WARNING: dump may contain secrets from system prompt or messages. Inspect before sharing.
6
6
  `);let n=t.options,r=typeof n=="object"&&n!==null?n.systemPrompt:void 0,o=vv(r),s={timestamp:new Date().toISOString(),prompt:t.prompt,options:Sv(t.options),provenance:t.provenance,resolution:o};if(e==="1"||e.toLowerCase()==="true"||e.toLowerCase()==="stderr"){let l=JSON.stringify(s,null,2)+`
7
7
  `;process.stderr.write(l);return}let i=gv(e),a=hv(i);try{pv(a,{recursive:!0});let c=(!mv(i)?yv:"")+JSON.stringify(s)+`
@@ -703,7 +703,7 @@ Subagents return their final assistant message verbatim \u2014 instruct them exp
703
703
 
704
704
  Foreground vs. background: by default (mode="foreground") this tool waits for the subagent to finish and returns its final message. Pass mode="background" to fire-and-forget \u2014 the tool returns a jobId immediately so you can keep working in the same turn. When a background job finishes, its result is delivered automatically into your context with the next user message, wrapped in a <background-subagent-result> block; you do not need to poll or join. The \`/bgsub:join <jobId>\` slash command remains available for manual replay. Use background mode for long investigations the user does not need to wait on; use foreground for anything whose result you need to reason about in the same turn.
705
705
 
706
- Do not use this tool for: trivial one-file edits, conversational answers, direct tool calls the user explicitly requested, or tasks where dispatch overhead exceeds the work.`,input_schema:{type:"object",properties:{prompt:{type:"string",description:"The task for the agent to perform."},attachments:{type:"array",items:{type:"string"},description:"Optional inbound image ids shown as [image img_xxxxxx \xB7 \u2026] or absolute image paths. Bytes are resolved by the runtime \u2014 NEVER paste base64 into the tool call."},model:{type:"string",description:"Model for the agent. Defaults to parent session model. Override per-call to right-size cost vs. capability \u2014 `haiku` (cheapest/fastest), `sonnet` (general-use), `opus` (most capable). Append `_1m` (e.g. `sonnet_1m`) for 1M-context variants. Full model IDs are also accepted."},max_turns:{type:"number",description:"Maximum conversation turns. Default 0 = unlimited (no ceiling) \u2014 omit to let the subagent run to natural completion. Set a positive integer to cap turns. A named agent (agent_type) may also set its own default via `maxTurns` frontmatter; an explicit value here overrides it."},max_tool_use_iterations:{type:"number",description:"Maximum tool-use rounds within the subagent's single turn \u2014 the anti-hang ceiling on a tool-call loop. Default 0 = unlimited. Set a positive integer to bound a runaway loop. When the cap is hit the subagent gets one final tools-stripped round to summarize what it gathered (no silent mid-loop stop). A named agent may set its own default via `maxToolUseIterations` frontmatter (explicit value here wins). Honored uniformly by both the anthropic-direct and openai-compatible providers."},id_prefix:{type:"string",description:"Label prefix for log correlation."},mode:{type:"string",enum:["foreground","background"],description:'Execution mode. "foreground" (default) waits for the subagent to finish and returns its output. "background" returns a jobId immediately and leaves the subagent running detached \u2014 its result is auto-delivered into this context with the next user message when it settles (/bgsub:join remains available for manual replay). Background jobs are cancelled when the parent session ends.'},cwd:{type:"string",description:"Optional absolute path for the subagent to run in. When omitted, the child inherits the parent's working directory (e.g. an `afk -w` worktree). When provided, the child's file/shell tools (bash, grep, glob, read_file, write_file, edit_file) anchor at this path instead. Use to dispatch a subagent into a pre-existing git worktree you created with the `worktree` tool (action \"create\" \u2014 preferred over raw `git worktree add`, which produces unmanaged ghost worktrees the background sweep may reap) so the subagent can work in isolation from the parent. Must be absolute (no relative paths) and must not contain `..` segments. Existence is not checked at dispatch time \u2014 a non-existent path surfaces as an error on the child's first cwd-relative tool call. Does not auto-propagate to further nested subagents \u2014 each `agent` call must specify `cwd` explicitly to operate in a worktree."},writeRoots:{type:"array",items:{type:"string"},description:'Optional extra write roots to pre-grant to the forked child. By default a fork can only write inside its cwd/worktree; out-of-root writes are auto-denied. Each entry must be an absolute path with no `..` segments. Composed WITH (never replaces) the child cwd. Mutually exclusive with isolation:"worktree".'},readRoots:{type:"array",items:{type:"string"},description:'Optional extra read roots to pre-grant to the forked child. Use when the task data lives OUTSIDE the repo \u2014 e.g. `~/Downloads`, a scratch data dir. Each entry must be an absolute path with no `..` segments (and not a filesystem root or your home dir). Composed WITH (never replaces) the fork\'s inherited read scope, so the child keeps its repo/worktree/state reach AND gains the named dirs. Writes stay confined. Grandchildren must be re-granted (not inherited). Unlike writeRoots, NOT mutually exclusive with isolation:"worktree" \u2014 widening reads inside an isolated worktree is legitimate.'},isolation:{type:"string",enum:["none","worktree"],description:'Filesystem isolation for the subagent. "none" (default) runs the child in the parent\'s working tree. "worktree" creates a fresh afk-managed git worktree + branch under .afk-worktrees/ and runs the child there, so several parallel write-capable subagents (e.g. speculative fixes, refactor lanes) never corrupt each other\'s edits or test runs. The worktree is torn down when the child finishes; a dirty or commits-ahead tree is preserved and locked instead of removed, so work in progress is never destroyed (recover it via the `worktree` tool). Mutually exclusive with `cwd` (the runtime owns the child\'s cwd when isolating). Ignored for read-only agents such as research-agent \u2014 they have nothing to isolate. Not supported together with mode:"background" in this release.'}},required:["prompt"]}},gt={name:"skill",category:"skill",concurrencySafe:!0,description:"Invoke a registered skill by name. Skills are specialized capabilities that dispatch subagents with domain-specific prompts. Check the system prompt for the list of available skills and their descriptions.",input_schema:{type:"object",properties:{name:{type:"string",description:'Skill name (e.g., "mint", "diagnose", "shadow-verify").'},arguments:{type:"string",description:"Arguments to pass to the skill."}},required:["name"]}},ht={name:"compose",category:"dag",concurrencySafe:!0,description:`Execute multiple subagent tasks as a DAG (directed acyclic graph). Nodes with no dependencies run in parallel; nodes with edges wait for their upstream dependencies to complete. Use when you need to orchestrate independent or dependent subagent work in a single call \u2014 e.g., diagnose in parallel with a fix, or research \u2192 implement \u2192 verify as a pipeline.
706
+ Do not use this tool for: trivial one-file edits, conversational answers, direct tool calls the user explicitly requested, or tasks where dispatch overhead exceeds the work.`,input_schema:{type:"object",properties:{prompt:{type:"string",description:"The task for the agent to perform."},attachments:{type:"array",items:{type:"string"},description:"Optional inbound image ids shown as [image img_xxxxxx \xB7 \u2026] or absolute image paths. Bytes are resolved by the runtime \u2014 NEVER paste base64 into the tool call."},model:{type:"string",description:"Model for the agent. Defaults to parent session model. Override per-call to right-size cost vs. capability \u2014 `haiku` (cheapest/fastest), `sonnet` (general-use), `opus` (most capable). Append `_1m` (e.g. `sonnet_1m`) for 1M-context variants. Full model IDs are also accepted."},max_turns:{type:"number",description:"Maximum conversation turns. Default 0 = unlimited (no ceiling) \u2014 omit to let the subagent run to natural completion. Set a positive integer to cap turns. A named agent (agent_type) may also set its own default via `maxTurns` frontmatter; an explicit value here overrides it."},max_tool_use_iterations:{type:"number",description:"Maximum tool-use rounds within the subagent's single turn \u2014 the anti-hang ceiling on a tool-call loop. Default 0 = unlimited. Set a positive integer to bound a runaway loop. When the cap is hit the subagent gets one final tools-stripped round to summarize what it gathered (no silent mid-loop stop). A named agent may set its own default via `maxToolUseIterations` frontmatter (explicit value here wins). Honored uniformly by both the anthropic-direct and openai-compatible providers."},id_prefix:{type:"string",description:"Label prefix for log correlation."},mode:{type:"string",enum:["foreground","background"],description:'Execution mode. "foreground" (default) waits for the subagent to finish and returns its output. "background" returns a jobId immediately and leaves the subagent running detached \u2014 its result is auto-delivered into this context with the next user message when it settles (/bgsub:join remains available for manual replay). Background jobs are cancelled when the parent session ends.'},cwd:{type:"string",description:"Optional absolute path for the subagent to run in. When omitted, the child inherits the parent's working directory (e.g. an `afk -w` worktree). When provided, the child's file/shell tools (bash, grep, glob, read_file, write_file, edit_file) anchor at this path instead. Use to dispatch a subagent into a pre-existing git worktree you created with the `worktree` tool (action \"create\" \u2014 preferred over raw `git worktree add`, which produces unmanaged ghost worktrees the background sweep may reap) so the subagent can work in isolation from the parent. Must be absolute (no relative paths) and must not contain `..` segments. Existence is not checked at dispatch time \u2014 a non-existent path surfaces as an error on the child's first cwd-relative tool call. Does not auto-propagate to further nested subagents \u2014 each `agent` call must specify `cwd` explicitly to operate in a worktree. To NOT set a cwd, omit the field entirely; a blank value is treated as omitted, never as a path. A filesystem root, your home directory, or an ancestor of it is refused; when the child only needs to READ files outside its tree, keep cwd and add readRoots instead of relocating cwd."},writeRoots:{type:"array",items:{type:"string"},description:'Optional extra write roots to pre-grant to the forked child. By default a fork can only write inside its cwd/worktree; out-of-root writes are auto-denied. Each entry must be an absolute path with no `..` segments. Composed WITH (never replaces) the child cwd. Mutually exclusive with isolation:"worktree".'},readRoots:{type:"array",items:{type:"string"},description:'Optional extra read roots to pre-grant to the forked child. Use when the task data lives OUTSIDE the repo \u2014 e.g. `~/Downloads`, a scratch data dir. Each entry must be an absolute path with no `..` segments (and not a filesystem root or your home dir). An entry may be a DIRECTORY or a single FILE \u2014 a file grants exactly that file, which is how to read home-root dotfiles (`~/.zshrc`, `~/.gitconfig`) given the home dir itself is refused; list the files rather than guessing at a directory that encloses them. Composed WITH (never replaces) the fork\'s inherited read scope, so the child keeps its repo/worktree/state reach AND gains the named dirs. Writes stay confined. Grandchildren must be re-granted (not inherited). Unlike writeRoots, NOT mutually exclusive with isolation:"worktree" \u2014 widening reads inside an isolated worktree is legitimate.'},isolation:{type:"string",enum:["none","worktree"],description:'Filesystem isolation for the subagent. "none" (default) runs the child in the parent\'s working tree. "worktree" creates a fresh afk-managed git worktree + branch under .afk-worktrees/ and runs the child there, so several parallel write-capable subagents (e.g. speculative fixes, refactor lanes) never corrupt each other\'s edits or test runs. The worktree is torn down when the child finishes; a dirty or commits-ahead tree is preserved and locked instead of removed, so work in progress is never destroyed (recover it via the `worktree` tool). Mutually exclusive with `cwd` (the runtime owns the child\'s cwd when isolating) \u2014 to isolate, omit `cwd` rather than blanking it. Ignored for read-only agents such as research-agent \u2014 they have nothing to isolate. Not supported together with mode:"background" in this release.'}},required:["prompt"]}},gt={name:"skill",category:"skill",concurrencySafe:!0,description:"Invoke a registered skill by name. Skills are specialized capabilities that dispatch subagents with domain-specific prompts. Check the system prompt for the list of available skills and their descriptions.",input_schema:{type:"object",properties:{name:{type:"string",description:'Skill name (e.g., "mint", "diagnose", "shadow-verify").'},arguments:{type:"string",description:"Arguments to pass to the skill."}},required:["name"]}},ht={name:"compose",category:"dag",concurrencySafe:!0,description:`Execute multiple subagent tasks as a DAG (directed acyclic graph). Nodes with no dependencies run in parallel; nodes with edges wait for their upstream dependencies to complete. Use when you need to orchestrate independent or dependent subagent work in a single call \u2014 e.g., diagnose in parallel with a fix, or research \u2192 implement \u2192 verify as a pipeline.
707
707
 
708
708
  Each node is a subagent task with its own prompt and optional model. Edges declare "from must finish before to starts." Omit edges entirely for pure parallel fan-out.
709
709
 
@@ -958,9 +958,9 @@ Work autonomously from the task prompt you were dispatched with: investigate, ac
958
958
 
959
959
  Watch for non-convergence: if repeated attempts at the same sub-goal \u2014 the same fix, the same search, the same command \u2014 stop making progress after a few tries, STOP and do not keep retrying. Activity is not progress. Return your best PARTIAL result with a clear note on what you could not resolve and why.
960
960
 
961
- ${jc}`;F();import{homedir as Gh}from"node:os";F();var xz=[...new Set([Gh(),fn(Gh())])];var Nz=new Set(Hh);function jr(t){let e=vP(t);return e!==void 0?e:kP(t)}function vP(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=e.exec(t))!==null;)n=r[1];if(n)return qh(n.trim())}function kP(t){for(let e=t.length-1;e>=0;e--){if(t[e]!=="}")continue;let n=AP(t,e);if(n===-1)continue;let r=t.slice(n,e+1),o=qh(r);if(o!==void 0)return o}}function AP(t,e){let n=0,r=!1,o=!1;for(let s=e;s>=0;s--){let i=t[s];if(o){o=!1;continue}if(r){if(i==="\\"){o=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="}")n++;else if(i==="{"&&(n--,n===0))return s}return-1}function qh(t){try{return JSON.parse(t)}catch{return}}import{z as kt}from"zod";var EP=kt.enum(["supports","opposes","uncertain","blocks"]),_P=kt.object({issue:kt.string().min(1),stance:EP,confidence:kt.number().min(0).max(1),evidence:kt.array(kt.string()),claim:kt.string().min(1)}),TP=kt.object({signal:_P}).passthrough();function xP(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n;for(;(n=e.exec(t))!==null;){let r=n[1];if(r===void 0)continue;let o=zh(r.trim());if(Jh(o))return o}for(let r=0;r<t.length;r++){if(t[r]!=="{"||RP(t,r))continue;let o=IP(t,r);if(o===-1)continue;let s=t.slice(r,o+1),i=zh(s);if(Jh(i))return i;r=o}}function RP(t,e){for(let n=e-1;n>=0;n--){let r=t[n];if(!(r===" "||r===" "||r===`
962
- `||r==="\r"))return r==="["||r===","}return!1}function Vh(t){let e=xP(t);if(e===void 0)return{ok:!1,reason:"absent"};let n=TP.safeParse(e);return n.success?{ok:!0,signal:n.data.signal}:{ok:!1,reason:"malformed"}}function zh(t){try{return JSON.parse(t)}catch{return}}function Jh(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&"signal"in t}function IP(t,e){let n=0,r=!1,o=!1;for(let s=e;s<t.length;s++){let i=t[s];if(o){o=!1;continue}if(r){if(i==="\\"){o=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="{")n++;else if(i==="}"&&(n--,n===0))return s}return-1}P();var rt="overload_exhausted",Xh="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.",CP=600*1e3,PP=7200*1e3,Yh=60*1e3,MP=120*1e3,OP=.25;function wi(t,e=Math.random){return t+Math.floor(e()*t*OP)}function Qh(t=Math.random){let e=MP-Yh;return Yh+Math.floor(t()*e)}function Zh(t){return t.type==="turn.completed"&&t.usage.stopReason===rt}var DP=new Set(["cli","repl","telegram"]);function ey(t){let e=b.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),PP)}return t!==void 0&&DP.has(t)?CP:0}var Hr="stream_incomplete";function Fe(t){return t===vt||t===Hr||t===rt}function Si(){return{toolCalls:[],toolResults:[],thinkingPresent:!1,turnCount:0}}function ty(t,e,n,r,o,s){let i=Vh(n.content),a=i.ok?i.signal:void 0;if(!r)return{id:t,status:e,message:n,trace:o,...a!==void 0&&{signal:a},...s!==void 0&&{stopReason:s}};let l=jr(n.content),c=r.safeParse(l);return c.success?{id:t,status:e,message:n,output:c.data,trace:o,...a!==void 0&&{signal:a},...s!==void 0&&{stopReason:s}}:{id:t,status:"failed",message:n,error:new Error(`structured output did not match schema: ${c.error.message}`,{cause:c.error}),schemaError:c.error,trace:o,...a!==void 0&&{signal:a},...s!==void 0&&{stopReason:s}}}function Wc(t,e,n,r,o){let s=n instanceof Error?n:new Error(String(n));return{id:t,status:e,error:s,trace:r,...o!==void 0&&{stopReason:o}}}function ue(t){return`${t.status}${t.error?`: ${t.error.message}`:""}`}Z();F();F();var bJ=300*1e3;Z();Z();Z();function Kc(t,e){for(let n of e??[])t.push({type:"image",source:{type:"base64",media_type:n.mediaType,data:n.bytes.toString("base64")}})}var $J=5*1024*1024;F();import{createHash as BP}from"node:crypto";import{mkdir as jP,readFile as HP,writeFile as WP}from"node:fs/promises";import{join as KP}from"node:path";var GP=6,qP=new Map;function zP(t){return BP("sha256").update(t).digest("hex")}function JP(t,e,n){let r=Math.max(1,Math.round(n/1024));return`[image ${t} \xB7 ${e} \xB7 ${r} KB]`}async function oy(t,e,n,r=sy){for(let o of n){let s=await r.put(e,o.bytes,o.mediaType);t.push({type:"text",text:JP(s.id,s.mediaType,s.sizeBytes)}),Kc(t,[o])}}var Gc=class{constructor(e=qP,n=zP){this.entries=e;this.hashBytes=n}entries;hashBytes;get(e,n){return this.entries.get(e)?.get(n)}listIds(e){return[...this.entries.get(e)?.keys()??[]].sort()}clear(e){this.entries.delete(e)}async put(e,n,r){let o=this.hashBytes(n),s=this.entries.get(e)??new Map;this.entries.set(e,s);let i=GP,a=0;for(;;){let l=`img_${o.slice(0,i)}`,c=a===0?l:`${l}_${a}`,d=s.get(c);if(d===void 0){let u=eu(e);await jP(u,{recursive:!0});let p=KP(u,`${c}${VP(r)}`);await WP(p,n);let f={path:p,mediaType:r,sizeBytes:n.byteLength};return s.set(c,f),{id:c,...f}}if(d.mediaType===r&&(await HP(d.path)).equals(n))return{id:c,...d};i<o.length?i=Math.min(o.length,i+2):a+=1}}};function VP(t){switch(t){case"image/jpeg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp"}}var sy=new Gc;var wP=[...et,...Ie,"memory_search","agent","skill"],YP=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...Ie,"memory_search","agent","skill"];function ly(t,e){let n={allowedTools:[...$c]};return J(typeof e=="string"?e:void 0)==="openai-compatible"?new qe({permissions:n}):new At({permissions:n})}Z();var qc=0,ki=5e3;async function Kr(t,e,n={}){if(!Number.isFinite(e)||e<=0)return t;let r,o=new Promise((s,i)=>{let a=0,l=c=>{r=setTimeout(()=>{a+=c;let d=0;if(n.extender)try{d=n.extender.onDeadline()}catch{d=0}if(Number.isFinite(d)&&d>0){l(d);return}let u=n.label?` (${n.label})`:"",p="";if(n.extender?.describe)try{let m=n.extender.describe();m!==void 0&&m!==""&&(p=` ${m}`)}catch{}let f=new Re(`Operation timed out after ${a}ms${u}${p}`,a);n.controller&&!n.controller.signal.aborted&&n.controller.abort(f),i(f)},c)};l(e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}function Gr(t,e=Date.now()){if(t.type==="paused")return t.resetsAt===void 0?void 0:t.resetsAt.getTime()-e+3e4;if(t.type==="rate_limit"){let n=t.retryAfterMs;return typeof n!="number"||!Number.isFinite(n)||n<=0?void 0:n+3e4}}function cy(t){if(t.type==="paused"){let e=t.resetsAt!==void 0?t.resetsAt.toISOString():"unknown";return`paused (${t.reason}, resetsAt=${e})`}if(t.type==="rate_limit"){let e=t.retryAfterMs;return`rate_limit (retryAfterMs=${typeof e=="number"?e:"unknown"})`}}var Ai=class{constructor(e,n,r,o){this.controller=e;this.idleTimeoutMs=n;this.label=r;this.onFire=o;this.isEnabled()&&this.arm(this.idleTimeoutMs,"none")}controller;idleTimeoutMs;label;onFire;timer;disposed=!1;fired=!1;inFlightTools=new Set;isEnabled(){return Number.isFinite(this.idleTimeoutMs)&&this.idleTimeoutMs>0}onEvent(e){if(!(!this.isEnabled()||this.disposed||this.fired)){if(e.type==="chunk"){if(e.chunk.type==="tool_use_detail"){this.inFlightTools.add(e.chunk.toolUseId),this.clearTimer();return}if(e.chunk.type==="tool_result"){this.inFlightTools.delete(e.chunk.toolUseId),this.inFlightTools.size===0&&this.arm(this.idleTimeoutMs,e.chunk.type);return}}if(!(this.inFlightTools.size>0)){if(e.type==="paused"){this.arm(this.pausedWindowMs(e),e.type);return}if(e.type==="rate_limit"){let n=Gr(e);if(n!==void 0&&n>0){this.arm(n,e.type);return}}this.arm(this.idleTimeoutMs,e.type)}}}pausedWindowMs(e){let n=Gr(e);return n===void 0?this.idleTimeoutMs:Math.max(this.idleTimeoutMs,n)}arm(e,n){this.timer!==void 0&&clearTimeout(this.timer);let r=e>0?e:this.idleTimeoutMs,o=Date.now(),s=setTimeout(()=>{this.fire(Date.now()-o,n)},r);s.unref(),this.timer=s}clearTimer(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0)}fire(e,n){if(!(this.fired||this.disposed)){this.fired=!0,this.timer=void 0;try{this.onFire?.({idleTimeoutMs:this.idleTimeoutMs,elapsedSinceLastProgressMs:e,lastEventType:n})}catch{}this.controller.signal.aborted||this.controller.abort(new Io(`subagent ${this.label} idle-watchdog fired: no observable progress for ${this.idleTimeoutMs}ms (last event: ${n}). The child stream produced no output for the idle window \u2014 typically a stalled model call under provider throttling with no detectable backoff bracket. Aborting so partial output (if any) is returned; the parent should retry or fall back.`,this.idleTimeoutMs))}}dispose(){this.disposed||(this.disposed=!0,this.inFlightTools.clear(),this.clearTimer())}};var zc=120*6e4,QP=1e3,Ei=class{constructor(e,n=zc,r){this.baseTimeoutMs=e;this.maxExtensionMs=n;this.onGrant=r}baseTimeoutMs;maxExtensionMs;pauseStartedAtMs;pauseWindowCapMs=0;closedCreditMs=0;lastPauseDescription;grantedMs=0;grantCount=0;onGrant;onEvent(e){if(e.type==="resumed"){this.closePause();return}if(e.type!=="paused"&&e.type!=="rate_limit")return;this.closeExpiredPause();let n=Gr(e);if(n===void 0||n<=0)return;let r=Date.now();if(this.pauseStartedAtMs===void 0)this.pauseStartedAtMs=r,this.pauseWindowCapMs=n;else{let o=r-this.pauseStartedAtMs;this.pauseWindowCapMs=Math.max(this.pauseWindowCapMs,o+n)}this.lastPauseDescription=cy(e)}openPauseCreditMs(){if(this.pauseStartedAtMs===void 0)return 0;let e=Date.now()-this.pauseStartedAtMs;return Math.max(0,Math.min(e,this.pauseWindowCapMs))}closePause(){this.pauseStartedAtMs!==void 0&&(this.closedCreditMs+=this.openPauseCreditMs(),this.pauseStartedAtMs=void 0,this.pauseWindowCapMs=0)}closeExpiredPause(){this.pauseStartedAtMs!==void 0&&Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs&&this.closePause()}onDeadline(){let e=this.maxExtensionMs-this.grantedMs;if(!(e>0))return 0;this.closeExpiredPause();let r=this.closedCreditMs+this.openPauseCreditMs()-this.grantedMs;if(r<=0)return 0;let o=Math.min(Math.max(r,QP),e);if(this.grantedMs+=o,this.grantCount+=1,this.onGrant)try{this.onGrant({grantMs:o,totalGrantedMs:this.grantedMs,remainingCapMs:this.maxExtensionMs-this.grantedMs,grantCount:this.grantCount,pauseDescription:this.lastPauseDescription})}catch{}return o}describe(){if(this.lastPauseDescription===void 0)return;let e=[`base budget ${this.baseTimeoutMs}ms`,`pause extension granted ${this.grantedMs}ms across ${this.grantCount} extension${this.grantCount===1?"":"s"} (cap ${this.maxExtensionMs}ms${this.grantedMs>=this.maxExtensionMs?", EXHAUSTED":""})`,`last provider pause: ${this.lastPauseDescription}`];if(this.pauseStartedAtMs!==void 0){let r=Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs?"expired":"still open";e.push(`last pause ${r}, opened ${new Date(this.pauseStartedAtMs).toISOString()} (reported window ${this.pauseWindowCapMs}ms)`)}return`[pause-aware ceiling: ${e.join("; ")}]`}get totalGrantedMs(){return this.grantedMs}};var _i=class{constructor(e,n,r,o,s,i,a,l,c,d,u,p,f,m,g,h=0){this.id=e;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=d;this.agentType=u;this.traceWriter=m;this.onSubagentSucceeded=g;this.idleTimeoutMs=h;this.progressSink=p,this.parentId=f}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;idleTimeoutMs;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;lastStopInjectContext;progressSink;parentId;currentTrace=Si();lastStreamedContent="";pauseCeiling;lastStopReason;get status(){return this.currentStatus}async run(e,n){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.lastStopReason=void 0,this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let r=Date.now(),o=Number.isFinite(this.timeoutMs)&&this.timeoutMs>0?new Ei(this.timeoutMs,zc,i=>{B(this.traceWriter,{phase:"pause_extension_granted",metadata:{subagentId:this.id,grantMs:i.grantMs,totalGrantedMs:i.totalGrantedMs,remainingCapMs:i.remainingCapMs,grantCount:i.grantCount,...i.pauseDescription!==void 0&&{pauseDescription:i.pauseDescription}}})}):void 0;this.pauseCeiling=o;let s=Kr(this.streamToFinalMessage(e,n),this.timeoutMs,{controller:this.controller,label:this.id,...o!==void 0&&{extender:o}});this.inFlight=s;try{let i=await s;this.lastMessage=i.content,this.lastDurationMs=Date.now()-r,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",await It(this.traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:this.lastDurationMs,turnCount:this.currentTrace.turnCount,outputBytes:Buffer.byteLength(this.lastMessage,"utf8"),...this.lastStopReason!==void 0&&{stopReason:this.lastStopReason}});let a=typeof i.metadata?.totalCostUsd=="number"?i.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this.currentTrace.usage,a),this.onTerminal(),i}catch(i){this.lastDurationMs=Date.now()-r;let a=this.controller.signal.aborted&&this.controller.signal.reason instanceof Re&&!this.abortGraph.isCascading(this.id)?this.controller.signal.reason:void 0,l=a??i;if(this.currentStatus!=="cancelled")if(this.controller.signal.aborted&&a===void 0){let c=this.controller.signal.reason instanceof Re;await It(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade",...c?{timeout:!0}:{}}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"}else await It(this.traceWriter,{transition:"failed",subagentId:this.id,errorClass:l instanceof Error?l.constructor.name:"Unknown",errorMessage:l instanceof Error?l.message:String(l),partialOutputBytes:Buffer.byteLength(this.lastStreamedContent,"utf8"),...a!==void 0?{failureClass:"timeout"}:{}}),this.currentStatus="failed",this.latestTerminalStatus="failed";throw this.onTerminal(),l}finally{this.inFlight=null}}async streamToFinalMessage(e,n){let r,o;this.lastStreamedContent="",this.currentTrace=Si();let s=n??this.progressSink??ut(),i={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}},a=new Ai(this.controller,this.idleTimeoutMs,this.id,l=>{B(this.traceWriter,{phase:"idle_watchdog_fired",metadata:{idleTimeoutMs:l.idleTimeoutMs,elapsedSinceLastProgressMs:l.elapsedSinceLastProgressMs,lastEventType:l.lastEventType}})});try{for await(let l of this.session.sendMessageStream(e)){if(s&&s(l,i),a.onEvent(l),this.pauseCeiling?.onEvent(l),l.type==="chunk"){let c=l.chunk;c.type==="content"?this.lastStreamedContent+=c.content:c.type==="tool_use_detail"?this.currentTrace.toolCalls.push({id:c.toolUseId,name:c.toolName,inputBytes:Buffer.byteLength(c.toolInput,"utf8")}):c.type==="tool_result"?this.currentTrace.toolResults.push({toolUseId:c.toolUseId,isError:c.isError,truncated:c.truncated,sizeBytes:c.sizeBytes}):c.type==="thinking"&&(this.currentTrace.thinkingPresent=!0)}if(l.type==="message")r=l.message,this.currentTrace.turnCount++;else if(l.type==="error"){o=l.error;break}else if(l.type==="done"){if(typeof l.metadata?.stopReason=="string"&&(this.lastStopReason=l.metadata.stopReason),typeof l.metadata?.usage=="object"&&l.metadata.usage!==null){let c=l.metadata.usage;this.currentTrace.usage={inputTokens:typeof c.input_tokens=="number"?c.input_tokens:void 0,outputTokens:typeof c.output_tokens=="number"?c.output_tokens:void 0,cacheReadTokens:typeof c.cache_read_input_tokens=="number"?c.cache_read_input_tokens:void 0,cacheCreationTokens:typeof c.cache_creation_input_tokens=="number"?c.cache_creation_input_tokens:void 0}}break}}}finally{a.dispose()}if(o)throw o;if(r)return r;if(this.lastStreamedContent.length>0)return this.lastStopReason??=Hr,{role:"assistant",content:this.lastStreamedContent,timestamp:new Date};if(this.lastStopReason==="tool_use_loop_capped")return{role:"assistant",content:`[subagent ${this.id} reached its tool-use iteration cap before producing a final message; returning a capped partial result]`,timestamp:new Date};throw this.controller.signal.aborted||this.currentStatus==="cancelled"?new Error(`Subagent ${this.id} produced no terminal message`):(this.lastStopReason=Hr,new je(`subagent ${this.id} produced no output \u2014 its model stream ended without a terminal message (stream_incomplete), and no partial text was streamed. This is typically a first-token timeout while the provider was overloaded (the connection was aborted mid retry-backoff). No findings were produced; the parent should retry or fall back.`))}async runToResult(e,n){try{let r=await this.run(e,n);return ty(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace,this.lastStopReason)}catch(r){let o=Wc(this.id,this.currentStatus,r,this.currentTrace,this.lastStopReason);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(e,n,r){let o;if(r){let s=this.progressSink??ut();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{x("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",It(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"});try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async teardown(e){if(this.stopDispatched)return;let n=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(n,e)}}getLastStopInjectContext(){return this.lastStopInjectContext}async dispatchStopAndRelease(e,n){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let r=await Cp(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:e,lastMessage:this.lastMessage,agentType:this.agentType,durationMs:this.lastDurationMs,trace:this.currentTrace},this.traceWriter?{traceWriter:this.traceWriter}:{});if(r.injectContext){if(this.parentAbortSignal?.aborted)x(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else if(n?.deferInjectContextToCaller)this.lastStopInjectContext=r.injectContext;else if(this.parentInputStreamRef)try{let o=this.parentInputStreamRef;o.queueFrameworkContext?o.queueFrameworkContext(r.injectContext):o.pushUserMessage(r.injectContext)}catch(o){x(`Failed to inject context from SubagentStop handler: ${String(o)}`)}}this.onTerminal()}};function dy(t){return Qs(He(t))}function uy(t,e){return t===void 0||!dy(t)||J(t)!=="openai-compatible"?{model:t}:e===void 0||dy(e)||J(e)!=="openai-compatible"?{model:t}:{model:e,coercedFrom:t}}P();var py=async(t,e)=>({action:"decline"}),fy=50,Jc=45*6e4;function my(){let t=b.AFK_SUBAGENT_TIMEOUT_MS;if(t===void 0||t.trim()==="")return Jc;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?Jc:e}var Vc=8*6e4;function gy(){let t=b.AFK_SUBAGENT_IDLE_TIMEOUT_MS;if(t===void 0||t.trim()==="")return Vc;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?Vc:e}var ay=60*6e4;var q=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentProvider;parentModel;parentCwd;parentReadRoots;worktreeMainRootCache=new Map;parentTraceWriter;parentSurface;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(e={}){if(this.parentCanUseTool=e.canUseTool,this.hookRegistry=e.hookRegistry,this.progressSink=e.progressSink,this.parentApiKey=e.apiKey,this.parentBaseUrl=e.baseUrl,this.parentProvider=e.parentModel!==void 0?J(e.parentModel):void 0,this.parentModel=e.parentModel,this.parentCwd=e.cwd,this.parentReadRoots=e.parentReadRoots,this.parentTraceWriter=e.traceWriter,this.parentSurface=e.surface,this.onSubagentSucceededCb=e.onSubagentSucceeded,this.abortGraph=new cr(e.traceWriter),this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),e.parentAbortSignal){let n=e.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(e=>({id:e.id,status:e.status}))}get(e){return this.active.get(e)}onChildAborted(e){return this.abortGraph.onChildAborted(this.rootId,e)}setOnSubagentSucceeded(e){this.onSubagentSucceededCb=e}setCwd(e){this.parentCwd=e,this.worktreeMainRootCache.delete(e)}getReadScopeInputs(){return{parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd}}async resolveMainRootForCwd(e){if(this.worktreeMainRootCache.has(e))return this.worktreeMainRootCache.get(e);let n=await Up(e);return this.worktreeMainRootCache.set(e,n),n}abortAll(e,n="user_signal"){this.abortGraph.abort(this.rootId,e,n)}async forkSubagent(e){if(e.phaseRole!==void 0&&e.phaseRole!=="read-write"&&e.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${e.phaseRole}" is mutually exclusive with config.provider. Remove one \u2014 either let the manager construct the phase-restricted provider, or use config.provider with phaseRole: "read-write" (default).`);let n=`${e.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=e.parent.sessionId,o=e.config.hookRegistry??this.hookRegistry??e.parent.hookRegistry,s=e.config.traceWriter??this.parentTraceWriter;o&&await Ip(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal,...s?{traceWriter:s}:{}});let i=new AbortController;this.abortGraph.register(n,i),this.abortGraph.linkChild(this.rootId,n);let a=e.config.cwd??this.parentCwd,l;if(e.config.readRoots===void 0){let v=this.parentReadRoots===void 0&&this.parentCwd===void 0,S;!v&&a!==void 0&&(S=await this.resolveMainRootForCwd(a),S===void 0&&this.parentCwd!==void 0&&this.parentCwd!==a&&(S=await this.resolveMainRootForCwd(this.parentCwd))),l=es({parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd,childCwd:a,worktreeMainRoot:S,...v?{}:{afkStateRoot:fe()},...v?{}:{afkFrameworkRoot:Te()}})}if(e.config.readRoots===void 0&&e.config.extraReadRoots!==void 0&&e.config.extraReadRoots.length>0&&(l!==void 0||a!==void 0)){let S=l??(a!==void 0?[a]:[]);l=[...new Set([...S,...e.config.extraReadRoots.map(T=>ZP.resolve(T))])]}let c;if(e.config.writeRoots!==void 0&&e.config.writeRoots.length>0){let v=a!==void 0?[a]:[];c=[...new Set([...v,...e.config.writeRoots])]}let d=uy(e.config.model,this.parentModel),u=d.model??e.config.model;d.coercedFrom!==void 0&&process.stderr.write(`[afk] subagent: child model "${d.coercedFrom}" cannot run on this session's OpenAI/ChatGPT backend \u2014 running it as "${u??""}" instead (set AFK_DEFAULT_SUBAGENT_MODEL to choose a different one).
963
- `);let p={...e.config,isSubagentFork:!0,model:u,resume:r,forkSession:r?!0:e.config.forkSession,subagentId:n,subagentToolOutputCapBytes:1e5,abortSignal:i.signal,apiKey:Wh({childModel:u,configApiKey:e.config.apiKey,parentApiKey:this.parentApiKey,parentProvider:this.parentProvider}),baseUrl:e.config.baseUrl??(J(u)==="openai-compatible"?void 0:this.parentBaseUrl),isNonInteractive:e.config.isNonInteractive??!0,maxToolUseIterations:e.config.maxToolUseIterations??fy,autoResumeOnUsageLimit:e.config.autoResumeOnUsageLimit??!1,...e.config.parentSessionId===void 0&&e.parent.sessionId!==void 0?{parentSessionId:e.parent.sessionId}:{},...e.config.phaseRole===void 0&&e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},...e.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},...l!==void 0?{readRoots:l}:{},...c!==void 0?{writeRoots:c}:{},...e.config.traceWriter===void 0&&this.parentTraceWriter!==void 0?{traceWriter:this.parentTraceWriter}:{},...e.config.surface===void 0&&this.parentSurface!==void 0?{surface:this.parentSurface}:{},hookRegistry:o,permissionBubbler:e.config.permissionBubbler??(this.parentCanUseTool!==void 0&&e.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...e.denyElicitations===!1?{}:{onElicitation:py},...e.phaseRole==="read-only"?{provider:ly("read-only",u)}:{}},f=()=>{};p.cwd!==void 0&&(hl(p.cwd),f=Np(p.cwd));let m,g,h,y;try{m=new ot(p);let v=e.parent.getInputStreamRef?.(),S=e.parent.abortSignal,T=this.progressSink??ut();h=e.agentType?.trim()||void 0,y=e.resolvedAgentType?.trim()||void 0;let k=e.parentId?.trim()||void 0;g=new _i(n,m,i,this.abortGraph,e.outputSchema,e.config.timeoutMs??my(),o,()=>{f(),this.active.delete(n),this.abortGraph.dispose(n)},v,S,h??e.idPrefix,T,k??e.parent.sessionId,s,this.onSubagentSucceededCb,e.config.idleTimeoutMs??gy()),this.active.set(n,g)}catch(v){throw f(),this.abortGraph.dispose(n),v}let w=typeof u=="string"?u:JSON.stringify(u);return It(s,{transition:"started",subagentId:n,parentId:e.parent.sessionId??this.rootId,model:w,...p.tools?.allowedTools?{allowedTools:[...p.tools.allowedTools]}:{},...e.promptHead&&e.promptHead.trim()!==""?{promptHead:e.promptHead.slice(0,80)}:{},...h?{agentType:h}:{},...y?{resolvedAgentType:y}:{}}),await ye({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,model:w,parent_session_id:e.parent.sessionId,resolved_agent_type:y}),g}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}};async function yy(t,e={}){let{failFast:n=!0,teardown:r=!0,maxConcurrency:o=8}=e;if(t.length===0)return[];let s=new Array(t.length),i=new Set(t.map((l,c)=>c)),a=!1;return await pr(t.map((l,c)=>c),o,async l=>{let c=t[l];n&&a&&await c.handle.cancel().catch(()=>{});let d=await c.handle.runToResult(c.prompt);if(s[l]=d,i.delete(l),n&&d.status!=="succeeded"){a=!0;for(let u of i){let p=t[u];p&&p.handle.status==="running"&&p.handle.cancel().catch(()=>{})}}}),r&&await Promise.allSettled(t.map(l=>l.handle.teardown())),s}var eM=new Set([...et,...Ie,"memory_search","agent","skill"]);function by(t){let e=new Set;for(let n of t){let r=yi(n,eM);r!==void 0&&e.add(r)}return e}F();F();import{existsSync as Et,readdirSync as dM,readFileSync as uM}from"fs";import{join as st}from"path";F();import{existsSync as Yc,readFileSync as ky,readdirSync as rM,realpathSync as oM,statSync as sM}from"fs";import{join as _n,resolve as Sy}from"path";import{existsSync as tM,mkdirSync as E4,readFileSync as nM,renameSync as _4,writeFileSync as T4,unlinkSync as x4}from"fs";F();function wy(t=bo()){if(!tM(t))return Ti();try{let e=nM(t,"utf8"),n=JSON.parse(e);if(!n||typeof n!="object")return Ti();let r=n,o=r.plugins&&typeof r.plugins=="object"?r.plugins:{};if(r.version===1)return{version:2,plugins:o,marketplaces:{}};if(r.version===2){let s=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:s}}return Ti()}catch{return Ti()}}function Ti(){return{version:2,plugins:{},marketplaces:{}}}var iM=5,vy="cache",qr;function Vt(t=Xt(),e={}){let n=e.trustAll===!0,r=e.sourceEnabled,o=n?`${t}\0trustAll`:t;if(n&&r&&r.size>0){let c=[...r.entries()].map(([d,u])=>`${d}=${u?1:0}`).sort().join(",");o=`${o}\0${c}`}qr||(qr=new Map);let s=qr.get(o);if(s)return[...s];if(!Yc(t))return qr.set(o,[]),[];let i=t===Xt()?bo():_n(t,".index.json"),a=wy(i),l=[];return Ay(t,t,0,l,new Set,a.plugins,n,r),qr.set(o,l),[...l]}function Ay(t,e,n,r,o,s,i,a){if(n>iM)return;let l;try{l=oM(e)}catch{l=e}if(o.has(l))return;if(o.add(l),Yc(_n(e,".claude-plugin","plugin.json"))){let d=Xc(t,e);if(d===null){xi(r,e);return}if(i){if(a&&a.get(lM(d))===!1)return;xi(r,e);return}if(d.layout==="cache"){let p=s[d.key];if(!p||p.enabled===!1)return;xi(r,e);return}let u=s[d.key];if(u&&u.enabled===!1)return;xi(r,e);return}let c;try{c=rM(e)}catch{return}for(let d of c){if(d.startsWith("."))continue;let u=_n(e,d),p;try{p=sM(u)}catch{continue}p.isDirectory()&&Ay(t,u,n+1,r,o,s,i,a)}}function aM(t){try{let e=ky(_n(t,".claude-plugin","plugin.json"),"utf8"),n=JSON.parse(e);if(n!==null&&typeof n=="object"&&"main"in n){let r=n.main;if(typeof r=="string"&&r.trim()!=="")return r}}catch{}}function xi(t,e){let n=aM(e);t.push(n!==void 0?{type:"local",path:e,main:n}:{type:"local",path:e})}function lM(t){if(t.layout!=="cache")return t.key;let e=t.key.indexOf(":");if(e<=0)return t.key;let n=t.key.slice(0,e);return`${t.key.slice(e+1)}@${n}`}function Xc(t,e){if(!e.startsWith(t))return null;let n=e.slice(t.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(s=>s.length>0);if(r.length===0)return null;if(r[0]===vy&&r.length>=3){let s=r[1];if(s){let i=_n(t,vy,s),l=cM(i,e)??r[2];if(l)return{layout:"cache",key:`${s}:${l}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function cM(t,e){let n=_n(t,".claude-plugin","marketplace.json");if(!Yc(n))return null;let r;try{r=JSON.parse(ky(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=Sy(e);for(let i of o){if(!i||typeof i!="object")continue;let a=i;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&Sy(t,a.source)===s)return a.name}return null}var Ey=["command","agent"];function _y(t=le()){let e=[],n=st(t,"skills");if(Et(n))for(let r of Ri(n)){let o=st(n,r,"SKILL.md");Et(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of Ey){let o=st(t,`${r}s`);if(Et(o))for(let s of Ri(o))s.endsWith(".md")&&e.push({path:st(o,s),type:r,source:"user"})}return e}function Ty(t=Xt()){if(!Et(t))return[];let e=[],n=Vt(t);for(let r of n){let s=Xc(t,r.path)?.key,i=st(r.path,"skills");if(Et(i))for(let a of Ri(i)){let l=st(i,a,"SKILL.md");if(!Et(l))continue;let c={path:l,type:"skill",source:"plugin"};s&&(c.plugin_key=s),e.push(c)}for(let a of Ey){let l=st(r.path,`${a}s`);if(Et(l))for(let c of Ri(l)){if(!c.endsWith(".md"))continue;let d={path:st(l,c),type:a,source:"plugin"};s&&(d.plugin_key=s),e.push(d)}}}return e}function xy(t=st(le(),"settings.json")){if(!Et(t))return[];try{let e=uM(t,"utf8"),r=JSON.parse(e).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a=0;a<i.length;a++)o.push({event:s,index:a,raw:i[a]});return o}catch{return[]}}function Ri(t){try{return dM(t).filter(e=>!e.startsWith("."))}catch{return[]}}var Py=ee.object({path:ee.string(),type:ee.enum(["skill","command","agent","hook"]),source:ee.enum(["user","plugin"]),plugin_key:ee.string().optional(),verdict:ee.enum(["correct","misfit","outlier"]),recommended_type:ee.string(),rationale:ee.string(),confidence:ee.enum(["high","med","low"])}),Cy=ee.record(ee.string(),ee.record(ee.string(),ee.number())),X4=ee.object({inventory:ee.object({user:Cy,plugin:Cy}),misfits:ee.array(Py),briefs_written:ee.number(),total_artifacts:ee.number()}),pM=ee.object({writeBriefs:ee.boolean().optional(),scope:ee.enum(["user","plugin","all"]).optional()}),fM=["skill","command","agent"],My=["skill","command","agent","hook"];function mM(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function gM(t){let e=()=>{let s={};for(let i of My)s[i]={correct:0,misfit:0,outlier:0};return s},n={user:e(),plugin:e()};for(let s of t)n[s.source][s.type][s.verdict]+=1;let r={high:0,med:1,low:2},o=t.filter(s=>s.verdict==="misfit").slice().sort((s,i)=>r[s.confidence]-r[i.confidence]);return{inventory:n,misfits:o}}function hM(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function yM(t){let e=t.filter(o=>o.source==="user"),n=t.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),e.length===0)r.push("(none discovered)");else for(let o of e)r.push(`- ${o.path}`);if(r.push(""),r.push('### Plugin-scope artifacts (set `"source": "plugin"`, copy `plugin_key` from each entry)'),n.length===0)r.push("(none discovered)");else for(let o of n){let s=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${s})`)}return r.join(`
961
+ ${jc}`;F();import{homedir as Gh}from"node:os";F();var xz=[...new Set([Gh(),fn(Gh())])];var Wz=new Set(Hh);function jr(t){let e=vP(t);return e!==void 0?e:kP(t)}function vP(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=e.exec(t))!==null;)n=r[1];if(n)return qh(n.trim())}function kP(t){for(let e=t.length-1;e>=0;e--){if(t[e]!=="}")continue;let n=AP(t,e);if(n===-1)continue;let r=t.slice(n,e+1),o=qh(r);if(o!==void 0)return o}}function AP(t,e){let n=0,r=!1,o=!1;for(let s=e;s>=0;s--){let i=t[s];if(o){o=!1;continue}if(r){if(i==="\\"){o=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="}")n++;else if(i==="{"&&(n--,n===0))return s}return-1}function qh(t){try{return JSON.parse(t)}catch{return}}import{z as kt}from"zod";var EP=kt.enum(["supports","opposes","uncertain","blocks"]),_P=kt.object({issue:kt.string().min(1),stance:EP,confidence:kt.number().min(0).max(1),evidence:kt.array(kt.string()),claim:kt.string().min(1)}),TP=kt.object({signal:_P}).passthrough();function xP(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n;for(;(n=e.exec(t))!==null;){let r=n[1];if(r===void 0)continue;let o=zh(r.trim());if(Jh(o))return o}for(let r=0;r<t.length;r++){if(t[r]!=="{"||RP(t,r))continue;let o=IP(t,r);if(o===-1)continue;let s=t.slice(r,o+1),i=zh(s);if(Jh(i))return i;r=o}}function RP(t,e){for(let n=e-1;n>=0;n--){let r=t[n];if(!(r===" "||r===" "||r===`
962
+ `||r==="\r"))return r==="["||r===","}return!1}function Vh(t){let e=xP(t);if(e===void 0)return{ok:!1,reason:"absent"};let n=TP.safeParse(e);return n.success?{ok:!0,signal:n.data.signal}:{ok:!1,reason:"malformed"}}function zh(t){try{return JSON.parse(t)}catch{return}}function Jh(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&"signal"in t}function IP(t,e){let n=0,r=!1,o=!1;for(let s=e;s<t.length;s++){let i=t[s];if(o){o=!1;continue}if(r){if(i==="\\"){o=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="{")n++;else if(i==="}"&&(n--,n===0))return s}return-1}P();var rt="overload_exhausted",Xh="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.",CP=600*1e3,PP=7200*1e3,Yh=60*1e3,MP=120*1e3,OP=.25;function wi(t,e=Math.random){return t+Math.floor(e()*t*OP)}function Qh(t=Math.random){let e=MP-Yh;return Yh+Math.floor(t()*e)}function Zh(t){return t.type==="turn.completed"&&t.usage.stopReason===rt}var DP=new Set(["cli","repl","telegram"]);function ey(t){let e=b.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),PP)}return t!==void 0&&DP.has(t)?CP:0}var Hr="stream_incomplete";function Fe(t){return t===vt||t===Hr||t===rt}function Si(){return{toolCalls:[],toolResults:[],thinkingPresent:!1,turnCount:0}}function ty(t,e,n,r,o,s){let i=Vh(n.content),a=i.ok?i.signal:void 0;if(!r)return{id:t,status:e,message:n,trace:o,...a!==void 0&&{signal:a},...s!==void 0&&{stopReason:s}};let l=jr(n.content),c=r.safeParse(l);return c.success?{id:t,status:e,message:n,output:c.data,trace:o,...a!==void 0&&{signal:a},...s!==void 0&&{stopReason:s}}:{id:t,status:"failed",message:n,error:new Error(`structured output did not match schema: ${c.error.message}`,{cause:c.error}),schemaError:c.error,trace:o,...a!==void 0&&{signal:a},...s!==void 0&&{stopReason:s}}}function Wc(t,e,n,r,o){let s=n instanceof Error?n:new Error(String(n));return{id:t,status:e,error:s,trace:r,...o!==void 0&&{stopReason:o}}}function ue(t){return`${t.status}${t.error?`: ${t.error.message}`:""}`}Z();F();F();var EJ=300*1e3;Z();Z();Z();function Kc(t,e){for(let n of e??[])t.push({type:"image",source:{type:"base64",media_type:n.mediaType,data:n.bytes.toString("base64")}})}var GJ=5*1024*1024;F();import{createHash as BP}from"node:crypto";import{mkdir as jP,readFile as HP,writeFile as WP}from"node:fs/promises";import{join as KP}from"node:path";var GP=6,qP=new Map;function zP(t){return BP("sha256").update(t).digest("hex")}function JP(t,e,n){let r=Math.max(1,Math.round(n/1024));return`[image ${t} \xB7 ${e} \xB7 ${r} KB]`}async function oy(t,e,n,r=sy){for(let o of n){let s=await r.put(e,o.bytes,o.mediaType);t.push({type:"text",text:JP(s.id,s.mediaType,s.sizeBytes)}),Kc(t,[o])}}var Gc=class{constructor(e=qP,n=zP){this.entries=e;this.hashBytes=n}entries;hashBytes;get(e,n){return this.entries.get(e)?.get(n)}listIds(e){return[...this.entries.get(e)?.keys()??[]].sort()}clear(e){this.entries.delete(e)}async put(e,n,r){let o=this.hashBytes(n),s=this.entries.get(e)??new Map;this.entries.set(e,s);let i=GP,a=0;for(;;){let l=`img_${o.slice(0,i)}`,c=a===0?l:`${l}_${a}`,d=s.get(c);if(d===void 0){let u=eu(e);await jP(u,{recursive:!0});let p=KP(u,`${c}${VP(r)}`);await WP(p,n);let f={path:p,mediaType:r,sizeBytes:n.byteLength};return s.set(c,f),{id:c,...f}}if(d.mediaType===r&&(await HP(d.path)).equals(n))return{id:c,...d};i<o.length?i=Math.min(o.length,i+2):a+=1}}};function VP(t){switch(t){case"image/jpeg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp"}}var sy=new Gc;var wP=[...et,...Ie,"memory_search","agent","skill"],YP=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...Ie,"memory_search","agent","skill"];function ly(t,e){let n={allowedTools:[...$c]};return J(typeof e=="string"?e:void 0)==="openai-compatible"?new qe({permissions:n}):new At({permissions:n})}Z();var qc=0,ki=5e3;async function Kr(t,e,n={}){if(!Number.isFinite(e)||e<=0)return t;let r,o=new Promise((s,i)=>{let a=0,l=c=>{r=setTimeout(()=>{a+=c;let d=0;if(n.extender)try{d=n.extender.onDeadline()}catch{d=0}if(Number.isFinite(d)&&d>0){l(d);return}let u=n.label?` (${n.label})`:"",p="";if(n.extender?.describe)try{let m=n.extender.describe();m!==void 0&&m!==""&&(p=` ${m}`)}catch{}let f=new Re(`Operation timed out after ${a}ms${u}${p}`,a);n.controller&&!n.controller.signal.aborted&&n.controller.abort(f),i(f)},c)};l(e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}function Gr(t,e=Date.now()){if(t.type==="paused")return t.resetsAt===void 0?void 0:t.resetsAt.getTime()-e+3e4;if(t.type==="rate_limit"){let n=t.retryAfterMs;return typeof n!="number"||!Number.isFinite(n)||n<=0?void 0:n+3e4}}function cy(t){if(t.type==="paused"){let e=t.resetsAt!==void 0?t.resetsAt.toISOString():"unknown";return`paused (${t.reason}, resetsAt=${e})`}if(t.type==="rate_limit"){let e=t.retryAfterMs;return`rate_limit (retryAfterMs=${typeof e=="number"?e:"unknown"})`}}var Ai=class{constructor(e,n,r,o){this.controller=e;this.idleTimeoutMs=n;this.label=r;this.onFire=o;this.isEnabled()&&this.arm(this.idleTimeoutMs,"none")}controller;idleTimeoutMs;label;onFire;timer;disposed=!1;fired=!1;inFlightTools=new Set;isEnabled(){return Number.isFinite(this.idleTimeoutMs)&&this.idleTimeoutMs>0}onEvent(e){if(!(!this.isEnabled()||this.disposed||this.fired)){if(e.type==="chunk"){if(e.chunk.type==="tool_use_detail"){this.inFlightTools.add(e.chunk.toolUseId),this.clearTimer();return}if(e.chunk.type==="tool_result"){this.inFlightTools.delete(e.chunk.toolUseId),this.inFlightTools.size===0&&this.arm(this.idleTimeoutMs,e.chunk.type);return}}if(!(this.inFlightTools.size>0)){if(e.type==="paused"){this.arm(this.pausedWindowMs(e),e.type);return}if(e.type==="rate_limit"){let n=Gr(e);if(n!==void 0&&n>0){this.arm(n,e.type);return}}this.arm(this.idleTimeoutMs,e.type)}}}pausedWindowMs(e){let n=Gr(e);return n===void 0?this.idleTimeoutMs:Math.max(this.idleTimeoutMs,n)}arm(e,n){this.timer!==void 0&&clearTimeout(this.timer);let r=e>0?e:this.idleTimeoutMs,o=Date.now(),s=setTimeout(()=>{this.fire(Date.now()-o,n)},r);s.unref(),this.timer=s}clearTimer(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0)}fire(e,n){if(!(this.fired||this.disposed)){this.fired=!0,this.timer=void 0;try{this.onFire?.({idleTimeoutMs:this.idleTimeoutMs,elapsedSinceLastProgressMs:e,lastEventType:n})}catch{}this.controller.signal.aborted||this.controller.abort(new Io(`subagent ${this.label} idle-watchdog fired: no observable progress for ${this.idleTimeoutMs}ms (last event: ${n}). The child stream produced no output for the idle window \u2014 typically a stalled model call under provider throttling with no detectable backoff bracket. Aborting so partial output (if any) is returned; the parent should retry or fall back.`,this.idleTimeoutMs))}}dispose(){this.disposed||(this.disposed=!0,this.inFlightTools.clear(),this.clearTimer())}};var zc=120*6e4,QP=1e3,Ei=class{constructor(e,n=zc,r){this.baseTimeoutMs=e;this.maxExtensionMs=n;this.onGrant=r}baseTimeoutMs;maxExtensionMs;pauseStartedAtMs;pauseWindowCapMs=0;closedCreditMs=0;lastPauseDescription;grantedMs=0;grantCount=0;onGrant;onEvent(e){if(e.type==="resumed"){this.closePause();return}if(e.type!=="paused"&&e.type!=="rate_limit")return;this.closeExpiredPause();let n=Gr(e);if(n===void 0||n<=0)return;let r=Date.now();if(this.pauseStartedAtMs===void 0)this.pauseStartedAtMs=r,this.pauseWindowCapMs=n;else{let o=r-this.pauseStartedAtMs;this.pauseWindowCapMs=Math.max(this.pauseWindowCapMs,o+n)}this.lastPauseDescription=cy(e)}openPauseCreditMs(){if(this.pauseStartedAtMs===void 0)return 0;let e=Date.now()-this.pauseStartedAtMs;return Math.max(0,Math.min(e,this.pauseWindowCapMs))}closePause(){this.pauseStartedAtMs!==void 0&&(this.closedCreditMs+=this.openPauseCreditMs(),this.pauseStartedAtMs=void 0,this.pauseWindowCapMs=0)}closeExpiredPause(){this.pauseStartedAtMs!==void 0&&Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs&&this.closePause()}onDeadline(){let e=this.maxExtensionMs-this.grantedMs;if(!(e>0))return 0;this.closeExpiredPause();let r=this.closedCreditMs+this.openPauseCreditMs()-this.grantedMs;if(r<=0)return 0;let o=Math.min(Math.max(r,QP),e);if(this.grantedMs+=o,this.grantCount+=1,this.onGrant)try{this.onGrant({grantMs:o,totalGrantedMs:this.grantedMs,remainingCapMs:this.maxExtensionMs-this.grantedMs,grantCount:this.grantCount,pauseDescription:this.lastPauseDescription})}catch{}return o}describe(){if(this.lastPauseDescription===void 0)return;let e=[`base budget ${this.baseTimeoutMs}ms`,`pause extension granted ${this.grantedMs}ms across ${this.grantCount} extension${this.grantCount===1?"":"s"} (cap ${this.maxExtensionMs}ms${this.grantedMs>=this.maxExtensionMs?", EXHAUSTED":""})`,`last provider pause: ${this.lastPauseDescription}`];if(this.pauseStartedAtMs!==void 0){let r=Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs?"expired":"still open";e.push(`last pause ${r}, opened ${new Date(this.pauseStartedAtMs).toISOString()} (reported window ${this.pauseWindowCapMs}ms)`)}return`[pause-aware ceiling: ${e.join("; ")}]`}get totalGrantedMs(){return this.grantedMs}};var _i=class{constructor(e,n,r,o,s,i,a,l,c,d,u,p,f,m,g,h=0){this.id=e;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=d;this.agentType=u;this.traceWriter=m;this.onSubagentSucceeded=g;this.idleTimeoutMs=h;this.progressSink=p,this.parentId=f}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;idleTimeoutMs;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;lastStopInjectContext;progressSink;parentId;currentTrace=Si();lastStreamedContent="";pauseCeiling;lastStopReason;get status(){return this.currentStatus}async run(e,n){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.lastStopReason=void 0,this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let r=Date.now(),o=Number.isFinite(this.timeoutMs)&&this.timeoutMs>0?new Ei(this.timeoutMs,zc,i=>{B(this.traceWriter,{phase:"pause_extension_granted",metadata:{subagentId:this.id,grantMs:i.grantMs,totalGrantedMs:i.totalGrantedMs,remainingCapMs:i.remainingCapMs,grantCount:i.grantCount,...i.pauseDescription!==void 0&&{pauseDescription:i.pauseDescription}}})}):void 0;this.pauseCeiling=o;let s=Kr(this.streamToFinalMessage(e,n),this.timeoutMs,{controller:this.controller,label:this.id,...o!==void 0&&{extender:o}});this.inFlight=s;try{let i=await s;this.lastMessage=i.content,this.lastDurationMs=Date.now()-r,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",await It(this.traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:this.lastDurationMs,turnCount:this.currentTrace.turnCount,outputBytes:Buffer.byteLength(this.lastMessage,"utf8"),...this.lastStopReason!==void 0&&{stopReason:this.lastStopReason}});let a=typeof i.metadata?.totalCostUsd=="number"?i.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this.currentTrace.usage,a),this.onTerminal(),i}catch(i){this.lastDurationMs=Date.now()-r;let a=this.controller.signal.aborted&&this.controller.signal.reason instanceof Re&&!this.abortGraph.isCascading(this.id)?this.controller.signal.reason:void 0,l=a??i;if(this.currentStatus!=="cancelled")if(this.controller.signal.aborted&&a===void 0){let c=this.controller.signal.reason instanceof Re;await It(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade",...c?{timeout:!0}:{}}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"}else await It(this.traceWriter,{transition:"failed",subagentId:this.id,errorClass:l instanceof Error?l.constructor.name:"Unknown",errorMessage:l instanceof Error?l.message:String(l),partialOutputBytes:Buffer.byteLength(this.lastStreamedContent,"utf8"),...a!==void 0?{failureClass:"timeout"}:{}}),this.currentStatus="failed",this.latestTerminalStatus="failed";throw this.onTerminal(),l}finally{this.inFlight=null}}async streamToFinalMessage(e,n){let r,o;this.lastStreamedContent="",this.currentTrace=Si();let s=n??this.progressSink??ut(),i={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}},a=new Ai(this.controller,this.idleTimeoutMs,this.id,l=>{B(this.traceWriter,{phase:"idle_watchdog_fired",metadata:{idleTimeoutMs:l.idleTimeoutMs,elapsedSinceLastProgressMs:l.elapsedSinceLastProgressMs,lastEventType:l.lastEventType}})});try{for await(let l of this.session.sendMessageStream(e)){if(s&&s(l,i),a.onEvent(l),this.pauseCeiling?.onEvent(l),l.type==="chunk"){let c=l.chunk;c.type==="content"?this.lastStreamedContent+=c.content:c.type==="tool_use_detail"?this.currentTrace.toolCalls.push({id:c.toolUseId,name:c.toolName,inputBytes:Buffer.byteLength(c.toolInput,"utf8")}):c.type==="tool_result"?this.currentTrace.toolResults.push({toolUseId:c.toolUseId,isError:c.isError,truncated:c.truncated,sizeBytes:c.sizeBytes}):c.type==="thinking"&&(this.currentTrace.thinkingPresent=!0)}if(l.type==="message")r=l.message,this.currentTrace.turnCount++;else if(l.type==="error"){o=l.error;break}else if(l.type==="done"){if(typeof l.metadata?.stopReason=="string"&&(this.lastStopReason=l.metadata.stopReason),typeof l.metadata?.usage=="object"&&l.metadata.usage!==null){let c=l.metadata.usage;this.currentTrace.usage={inputTokens:typeof c.input_tokens=="number"?c.input_tokens:void 0,outputTokens:typeof c.output_tokens=="number"?c.output_tokens:void 0,cacheReadTokens:typeof c.cache_read_input_tokens=="number"?c.cache_read_input_tokens:void 0,cacheCreationTokens:typeof c.cache_creation_input_tokens=="number"?c.cache_creation_input_tokens:void 0}}break}}}finally{a.dispose()}if(o)throw o;if(r)return r;if(this.lastStreamedContent.length>0)return this.lastStopReason??=Hr,{role:"assistant",content:this.lastStreamedContent,timestamp:new Date};if(this.lastStopReason==="tool_use_loop_capped")return{role:"assistant",content:`[subagent ${this.id} reached its tool-use iteration cap before producing a final message; returning a capped partial result]`,timestamp:new Date};throw this.controller.signal.aborted||this.currentStatus==="cancelled"?new Error(`Subagent ${this.id} produced no terminal message`):(this.lastStopReason=Hr,new je(`subagent ${this.id} produced no output \u2014 its model stream ended without a terminal message (stream_incomplete), and no partial text was streamed. This is typically a first-token timeout while the provider was overloaded (the connection was aborted mid retry-backoff). No findings were produced; the parent should retry or fall back.`))}async runToResult(e,n){try{let r=await this.run(e,n);return ty(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace,this.lastStopReason)}catch(r){let o=Wc(this.id,this.currentStatus,r,this.currentTrace,this.lastStopReason);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(e,n,r){let o;if(r){let s=this.progressSink??ut();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{x("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",It(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"});try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async teardown(e){if(this.stopDispatched)return;let n=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(n,e)}}getLastStopInjectContext(){return this.lastStopInjectContext}async dispatchStopAndRelease(e,n){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let r=await Cp(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:e,lastMessage:this.lastMessage,agentType:this.agentType,durationMs:this.lastDurationMs,trace:this.currentTrace},this.traceWriter?{traceWriter:this.traceWriter}:{});if(r.injectContext){if(this.parentAbortSignal?.aborted)x(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else if(n?.deferInjectContextToCaller)this.lastStopInjectContext=r.injectContext;else if(this.parentInputStreamRef)try{let o=this.parentInputStreamRef;o.queueFrameworkContext?o.queueFrameworkContext(r.injectContext):o.pushUserMessage(r.injectContext)}catch(o){x(`Failed to inject context from SubagentStop handler: ${String(o)}`)}}this.onTerminal()}};function dy(t){return Qs(He(t))}function uy(t,e){return t===void 0||!dy(t)||J(t)!=="openai-compatible"?{model:t}:e===void 0||dy(e)||J(e)!=="openai-compatible"?{model:t}:{model:e,coercedFrom:t}}P();var py=async(t,e)=>({action:"decline"}),fy=50,Jc=45*6e4;function my(){let t=b.AFK_SUBAGENT_TIMEOUT_MS;if(t===void 0||t.trim()==="")return Jc;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?Jc:e}var Vc=8*6e4;function gy(){let t=b.AFK_SUBAGENT_IDLE_TIMEOUT_MS;if(t===void 0||t.trim()==="")return Vc;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?Vc:e}var ay=60*6e4;var q=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentProvider;parentModel;parentCwd;parentReadRoots;worktreeMainRootCache=new Map;parentTraceWriter;parentSurface;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(e={}){if(this.parentCanUseTool=e.canUseTool,this.hookRegistry=e.hookRegistry,this.progressSink=e.progressSink,this.parentApiKey=e.apiKey,this.parentBaseUrl=e.baseUrl,this.parentProvider=e.parentModel!==void 0?J(e.parentModel):void 0,this.parentModel=e.parentModel,this.parentCwd=e.cwd,this.parentReadRoots=e.parentReadRoots,this.parentTraceWriter=e.traceWriter,this.parentSurface=e.surface,this.onSubagentSucceededCb=e.onSubagentSucceeded,this.abortGraph=new cr(e.traceWriter),this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),e.parentAbortSignal){let n=e.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(e=>({id:e.id,status:e.status}))}get(e){return this.active.get(e)}onChildAborted(e){return this.abortGraph.onChildAborted(this.rootId,e)}setOnSubagentSucceeded(e){this.onSubagentSucceededCb=e}setCwd(e){this.parentCwd=e,this.worktreeMainRootCache.delete(e)}getReadScopeInputs(){return{parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd}}async resolveMainRootForCwd(e){if(this.worktreeMainRootCache.has(e))return this.worktreeMainRootCache.get(e);let n=await Up(e);return this.worktreeMainRootCache.set(e,n),n}abortAll(e,n="user_signal"){this.abortGraph.abort(this.rootId,e,n)}async forkSubagent(e){if(e.phaseRole!==void 0&&e.phaseRole!=="read-write"&&e.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${e.phaseRole}" is mutually exclusive with config.provider. Remove one \u2014 either let the manager construct the phase-restricted provider, or use config.provider with phaseRole: "read-write" (default).`);let n=`${e.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=e.parent.sessionId,o=e.config.hookRegistry??this.hookRegistry??e.parent.hookRegistry,s=e.config.traceWriter??this.parentTraceWriter;o&&await Ip(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal,...s?{traceWriter:s}:{}});let i=new AbortController;this.abortGraph.register(n,i),this.abortGraph.linkChild(this.rootId,n);let a=e.config.cwd??this.parentCwd,l;if(e.config.readRoots===void 0){let v=this.parentReadRoots===void 0&&this.parentCwd===void 0,S;!v&&a!==void 0&&(S=await this.resolveMainRootForCwd(a),S===void 0&&this.parentCwd!==void 0&&this.parentCwd!==a&&(S=await this.resolveMainRootForCwd(this.parentCwd))),l=es({parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd,childCwd:a,worktreeMainRoot:S,...v?{}:{afkStateRoot:fe()},...v?{}:{afkFrameworkRoot:Te()}})}if(e.config.readRoots===void 0&&e.config.extraReadRoots!==void 0&&e.config.extraReadRoots.length>0&&(l!==void 0||a!==void 0)){let S=l??(a!==void 0?[a]:[]);l=[...new Set([...S,...e.config.extraReadRoots.map(T=>ZP.resolve(T))])]}let c;if(e.config.writeRoots!==void 0&&e.config.writeRoots.length>0){let v=a!==void 0?[a]:[];c=[...new Set([...v,...e.config.writeRoots])]}let d=uy(e.config.model,this.parentModel),u=d.model??e.config.model;d.coercedFrom!==void 0&&process.stderr.write(`[afk] subagent: child model "${d.coercedFrom}" cannot run on this session's OpenAI/ChatGPT backend \u2014 running it as "${u??""}" instead (set AFK_DEFAULT_SUBAGENT_MODEL to choose a different one).
963
+ `);let p={...e.config,isSubagentFork:!0,model:u,resume:r,forkSession:r?!0:e.config.forkSession,subagentId:n,subagentToolOutputCapBytes:1e5,abortSignal:i.signal,apiKey:Wh({childModel:u,configApiKey:e.config.apiKey,parentApiKey:this.parentApiKey,parentProvider:this.parentProvider}),baseUrl:e.config.baseUrl??(J(u)==="openai-compatible"?void 0:this.parentBaseUrl),isNonInteractive:e.config.isNonInteractive??!0,maxToolUseIterations:e.config.maxToolUseIterations??fy,autoResumeOnUsageLimit:e.config.autoResumeOnUsageLimit??!1,...e.config.parentSessionId===void 0&&e.parent.sessionId!==void 0?{parentSessionId:e.parent.sessionId}:{},...e.config.phaseRole===void 0&&e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},...e.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},...l!==void 0?{readRoots:l}:{},...c!==void 0?{writeRoots:c}:{},...e.config.traceWriter===void 0&&this.parentTraceWriter!==void 0?{traceWriter:this.parentTraceWriter}:{},...e.config.surface===void 0&&this.parentSurface!==void 0?{surface:this.parentSurface}:{},hookRegistry:o,permissionBubbler:e.config.permissionBubbler??(this.parentCanUseTool!==void 0&&e.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...e.denyElicitations===!1?{}:{onElicitation:py},...e.phaseRole==="read-only"?{provider:ly("read-only",u)}:{}},f=()=>{};p.cwd!==void 0&&(hl(p.cwd),f=Np(p.cwd));let m,g,h,y;try{m=new ot(p);let v=e.parent.getInputStreamRef?.(),S=e.parent.abortSignal,T=this.progressSink??ut();h=e.agentType?.trim()||void 0,y=e.resolvedAgentType?.trim()||void 0;let k=e.parentId?.trim()||void 0;g=new _i(n,m,i,this.abortGraph,e.outputSchema,e.config.timeoutMs??my(),o,()=>{f(),this.active.delete(n),this.abortGraph.dispose(n)},v,S,h??e.idPrefix,T,k??e.parent.sessionId,s,this.onSubagentSucceededCb,e.config.idleTimeoutMs??gy()),this.active.set(n,g)}catch(v){throw f(),this.abortGraph.dispose(n),v}let w=typeof u=="string"?u:JSON.stringify(u);return It(s,{transition:"started",subagentId:n,parentId:e.parent.sessionId??this.rootId,model:w,...p.tools?.allowedTools?{allowedTools:[...p.tools.allowedTools]}:{},...e.promptHead&&e.promptHead.trim()!==""?{promptHead:e.promptHead.slice(0,80)}:{},...h?{agentType:h}:{},...y?{resolvedAgentType:y}:{}}),await ye({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,model:w,parent_session_id:e.parent.sessionId,resolved_agent_type:y}),g}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}};async function yy(t,e={}){let{failFast:n=!0,teardown:r=!0,maxConcurrency:o=8}=e;if(t.length===0)return[];let s=new Array(t.length),i=new Set(t.map((l,c)=>c)),a=!1;return await pr(t.map((l,c)=>c),o,async l=>{let c=t[l];n&&a&&await c.handle.cancel().catch(()=>{});let d=await c.handle.runToResult(c.prompt);if(s[l]=d,i.delete(l),n&&d.status!=="succeeded"){a=!0;for(let u of i){let p=t[u];p&&p.handle.status==="running"&&p.handle.cancel().catch(()=>{})}}}),r&&await Promise.allSettled(t.map(l=>l.handle.teardown())),s}var eM=new Set([...et,...Ie,"memory_search","agent","skill"]);function by(t){let e=new Set;for(let n of t){let r=yi(n,eM);r!==void 0&&e.add(r)}return e}F();F();import{existsSync as Et,readdirSync as dM,readFileSync as uM}from"fs";import{join as st}from"path";F();import{existsSync as Yc,readFileSync as ky,readdirSync as rM,realpathSync as oM,statSync as sM}from"fs";import{join as _n,resolve as Sy}from"path";import{existsSync as tM,mkdirSync as C4,readFileSync as nM,renameSync as P4,writeFileSync as M4,unlinkSync as O4}from"fs";F();function wy(t=bo()){if(!tM(t))return Ti();try{let e=nM(t,"utf8"),n=JSON.parse(e);if(!n||typeof n!="object")return Ti();let r=n,o=r.plugins&&typeof r.plugins=="object"?r.plugins:{};if(r.version===1)return{version:2,plugins:o,marketplaces:{}};if(r.version===2){let s=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:s}}return Ti()}catch{return Ti()}}function Ti(){return{version:2,plugins:{},marketplaces:{}}}var iM=5,vy="cache",qr;function Vt(t=Xt(),e={}){let n=e.trustAll===!0,r=e.sourceEnabled,o=n?`${t}\0trustAll`:t;if(n&&r&&r.size>0){let c=[...r.entries()].map(([d,u])=>`${d}=${u?1:0}`).sort().join(",");o=`${o}\0${c}`}qr||(qr=new Map);let s=qr.get(o);if(s)return[...s];if(!Yc(t))return qr.set(o,[]),[];let i=t===Xt()?bo():_n(t,".index.json"),a=wy(i),l=[];return Ay(t,t,0,l,new Set,a.plugins,n,r),qr.set(o,l),[...l]}function Ay(t,e,n,r,o,s,i,a){if(n>iM)return;let l;try{l=oM(e)}catch{l=e}if(o.has(l))return;if(o.add(l),Yc(_n(e,".claude-plugin","plugin.json"))){let d=Xc(t,e);if(d===null){xi(r,e);return}if(i){if(a&&a.get(lM(d))===!1)return;xi(r,e);return}if(d.layout==="cache"){let p=s[d.key];if(!p||p.enabled===!1)return;xi(r,e);return}let u=s[d.key];if(u&&u.enabled===!1)return;xi(r,e);return}let c;try{c=rM(e)}catch{return}for(let d of c){if(d.startsWith("."))continue;let u=_n(e,d),p;try{p=sM(u)}catch{continue}p.isDirectory()&&Ay(t,u,n+1,r,o,s,i,a)}}function aM(t){try{let e=ky(_n(t,".claude-plugin","plugin.json"),"utf8"),n=JSON.parse(e);if(n!==null&&typeof n=="object"&&"main"in n){let r=n.main;if(typeof r=="string"&&r.trim()!=="")return r}}catch{}}function xi(t,e){let n=aM(e);t.push(n!==void 0?{type:"local",path:e,main:n}:{type:"local",path:e})}function lM(t){if(t.layout!=="cache")return t.key;let e=t.key.indexOf(":");if(e<=0)return t.key;let n=t.key.slice(0,e);return`${t.key.slice(e+1)}@${n}`}function Xc(t,e){if(!e.startsWith(t))return null;let n=e.slice(t.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(s=>s.length>0);if(r.length===0)return null;if(r[0]===vy&&r.length>=3){let s=r[1];if(s){let i=_n(t,vy,s),l=cM(i,e)??r[2];if(l)return{layout:"cache",key:`${s}:${l}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function cM(t,e){let n=_n(t,".claude-plugin","marketplace.json");if(!Yc(n))return null;let r;try{r=JSON.parse(ky(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=Sy(e);for(let i of o){if(!i||typeof i!="object")continue;let a=i;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&Sy(t,a.source)===s)return a.name}return null}var Ey=["command","agent"];function _y(t=le()){let e=[],n=st(t,"skills");if(Et(n))for(let r of Ri(n)){let o=st(n,r,"SKILL.md");Et(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of Ey){let o=st(t,`${r}s`);if(Et(o))for(let s of Ri(o))s.endsWith(".md")&&e.push({path:st(o,s),type:r,source:"user"})}return e}function Ty(t=Xt()){if(!Et(t))return[];let e=[],n=Vt(t);for(let r of n){let s=Xc(t,r.path)?.key,i=st(r.path,"skills");if(Et(i))for(let a of Ri(i)){let l=st(i,a,"SKILL.md");if(!Et(l))continue;let c={path:l,type:"skill",source:"plugin"};s&&(c.plugin_key=s),e.push(c)}for(let a of Ey){let l=st(r.path,`${a}s`);if(Et(l))for(let c of Ri(l)){if(!c.endsWith(".md"))continue;let d={path:st(l,c),type:a,source:"plugin"};s&&(d.plugin_key=s),e.push(d)}}}return e}function xy(t=st(le(),"settings.json")){if(!Et(t))return[];try{let e=uM(t,"utf8"),r=JSON.parse(e).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a=0;a<i.length;a++)o.push({event:s,index:a,raw:i[a]});return o}catch{return[]}}function Ri(t){try{return dM(t).filter(e=>!e.startsWith("."))}catch{return[]}}var Py=ee.object({path:ee.string(),type:ee.enum(["skill","command","agent","hook"]),source:ee.enum(["user","plugin"]),plugin_key:ee.string().optional(),verdict:ee.enum(["correct","misfit","outlier"]),recommended_type:ee.string(),rationale:ee.string(),confidence:ee.enum(["high","med","low"])}),Cy=ee.record(ee.string(),ee.record(ee.string(),ee.number())),rX=ee.object({inventory:ee.object({user:Cy,plugin:Cy}),misfits:ee.array(Py),briefs_written:ee.number(),total_artifacts:ee.number()}),pM=ee.object({writeBriefs:ee.boolean().optional(),scope:ee.enum(["user","plugin","all"]).optional()}),fM=["skill","command","agent"],My=["skill","command","agent","hook"];function mM(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function gM(t){let e=()=>{let s={};for(let i of My)s[i]={correct:0,misfit:0,outlier:0};return s},n={user:e(),plugin:e()};for(let s of t)n[s.source][s.type][s.verdict]+=1;let r={high:0,med:1,low:2},o=t.filter(s=>s.verdict==="misfit").slice().sort((s,i)=>r[s.confidence]-r[i.confidence]);return{inventory:n,misfits:o}}function hM(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function yM(t){let e=t.filter(o=>o.source==="user"),n=t.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),e.length===0)r.push("(none discovered)");else for(let o of e)r.push(`- ${o.path}`);if(r.push(""),r.push('### Plugin-scope artifacts (set `"source": "plugin"`, copy `plugin_key` from each entry)'),n.length===0)r.push("(none discovered)");else for(let o of n){let s=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${s})`)}return r.join(`
964
964
  `)}function bM(t,e){let n=["","## Discovered hooks (audit only these)",""];if(n.push(`Settings file (use this absolute path verbatim in each verdict's \`path\` field): \`${t}\``),n.push(""),e.length===0)return n.push("(no hooks discovered)"),n.join(`
965
965
  `);for(let r of e){let o=`${r.event}-${r.index}`;n.push(`### Hook \`${o}\``),n.push(""),n.push("```json"),n.push(JSON.stringify(r.raw,null,2)),n.push("```"),n.push("")}return n.join(`
966
966
  `)}function wM(t,e){if(!e)return{kind:"failure",message:`${t}: no result`};if(e.schemaError)return{kind:"failure",message:`${t}: schema mismatch \u2014 ${e.schemaError.message}`};if(e.status!=="succeeded"){let n=e.error?` \u2014 ${e.error.message}`:"";return{kind:"failure",message:`${t}: ${e.status}${n}`}}return e.output?{kind:"success",output:e.output}:{kind:"failure",message:`${t}: no output`}}async function SM(t,e,n){let r=n?.apiKey,o=n?.defaultSubagentModel??n?.defaultModel??"sonnet",s=n?.callId,i=typeof t=="object"&&t!==null?t:{},a=pM.parse(i),l=a.writeBriefs??!0,c=a.scope??"all",d=mM(c);if(!e?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let u=e.sessionId,p=re("audit-fit"),f={skill:p["01-skill-inspector.md"],command:p["02-command-inspector.md"],agent:p["03-agent-inspector.md"],hook:p["04-hook-inspector.md"]};for(let O of My)if(!f[O])throw new Error(`audit-fit skill missing inspector prompt for ${O}`);let m=d.runUserDiscovery?_y():[],g=d.runPluginDiscovery?Ty():[],h={skill:[],command:[],agent:[]};for(let O of[...m,...g])h[O.type].push(O);let y=new q({apiKey:r,...n?.defaultModel!==void 0?{parentModel:n.defaultModel}:{},...n?.traceWriter!==void 0?{traceWriter:n.traceWriter}:{}}),w=by(bi.allowedTools),v=()=>async O=>w.has(O)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${O} not allowed for audit-fit inspectors. Allowed tools: ${[...w].join(", ")}`},S=[];for(let O of fM){let $=h[O];if($.length===0)continue;let M=f[O];M&&S.push({type:O,prompt:`${M}
@@ -1100,13 +1100,13 @@ ${r}
1100
1100
 
1101
1101
  ${o}`};if(s&&typeof s=="object"&&"type"in s&&s.type==="preset"){let i=s.append??"";return{...t,systemPrompt:{...s,append:`${i}
1102
1102
 
1103
- ${o}`}}}return{...t,systemPrompt:o}}function na(t){let e=t.toLowerCase().replace(/[`*_~]/g," ").replace(/[^\w\s-]/g," ").replace(/[\s_]+/g," ").trim();return e?e.split(" ").filter(Boolean).slice(0,6).join("-").slice(0,48).replace(/-+$/g,""):""}function Bw(t){return{totalTurns:0,totalCostUsd:0,totalTokens:0,totalDurationMs:0,sessionStartTime:Date.now(),turnCosts:[],turnTokens:[],turns:[],model:t,permissionMode:"default",thinkingUi:"live"}}function jw(t,e,n,r,o){let s=r?.totalCostUsd??0,i=r?.durationMs??0,a=Number(r?.usage?.input_tokens??0),l=Number(r?.usage?.output_tokens??0),c=a,d=l,u=Number(r?.usage?.cache_read_input_tokens??0)+Number(r?.usage?.cache_creation_input_tokens??0),p=r?.usage?.iterations;if(Array.isArray(p)&&p.length>0){let y=p[p.length-1];if(y&&typeof y=="object"){let w=y;c=Number(w.input_tokens??0),d=Number(w.output_tokens??0),u=Number(w.cache_read_input_tokens??0)+Number(w.cache_creation_input_tokens??0)}}t.totalTurns+=1,t.totalCostUsd+=s,t.totalDurationMs+=i,t.totalTokens+=a+l,t.turnCosts.push(s);let f=Number(r?.usage?.context_window_tokens??NaN),m=Array.isArray(p)&&p.length>0,g=Number.isFinite(f)?f:m?c+d+u:void 0;if(t.turnTokens.push({input:c,output:d,cache:u,...g!==void 0?{footprint:g}:{}}),r?.sessionId&&!t.sessionId&&(t.sessionId=String(r.sessionId)),!t.name){let y=na(e);y&&(t.name=y)}let h={user:e,assistant:n,timestamp:Date.now(),costUsd:s,durationMs:i,inputTokens:a,outputTokens:l,...o&&o.length>0?{toolEvents:o}:{}};return t.turns.push(h),h}import{readFileSync as Z0,writeFileSync as eD,existsSync as ra,mkdirSync as tD,readdirSync as nD,statSync as rD,realpathSync as Hw}from"fs";import{join as Kw,basename as Gw,resolve as Ww,sep as oD}from"path";F();import{randomUUID as Q0}from"node:crypto";var Zr=class extends Error{constructor(e){super(e),this.name="SessionRegistryError"}},vd=class{byId=new Map;byBinding=new Map;bySdk=new Map;now;constructor(e){this.now=e?.now??Date.now}create(e){let n=this.now(),r=e.id??Q0();if(this.byId.has(r))throw new Zr(`session handle already exists: ${r}`);let o={surface:e.surface,key:e.key,boundAt:n,lastActiveAt:n},s={id:r,surface:e.surface,model:e.model,createdAt:e.createdAt??n,lastActiveAt:n,status:"active",bindings:[o]};return e.name!==void 0&&(s.name=e.name),e.cwd!==void 0&&(s.cwd=e.cwd),e.sdkSessionId!==void 0&&(s.sdkSessionId=e.sdkSessionId),this.byId.set(r,s),this.pointBinding(this.bindingKey(o.surface,o.key),r),s.sdkSessionId!==void 0&&this.bySdk.set(s.sdkSessionId,r),this.clone(s)}load(e){if(this.byId.has(e.id))throw new Zr(`session handle already exists: ${e.id}`);let n=this.clone(e);if(this.byId.set(n.id,n),n.status==="active")for(let r of n.bindings)this.pointBinding(this.bindingKey(r.surface,r.key),n.id);n.sdkSessionId!==void 0&&this.bySdk.set(n.sdkSessionId,n.id)}get(e){let n=this.byId.get(e);return n?this.clone(n):void 0}getBySdkSessionId(e){let n=this.bySdk.get(e);if(n===void 0)return;let r=this.byId.get(n);return r?this.clone(r):void 0}resolve(e,n){let r=this.byBinding.get(this.bindingKey(e,n));if(r===void 0)return;let o=this.byId.get(r);if(!(!o||o.status!=="active"))return this.clone(o)}bind(e,n){let r=this.require(e),o=this.now(),s=this.bindingKey(n.surface,n.key),i=r.bindings.find(a=>this.bindingKey(a.surface,a.key)===s);i?i.lastActiveAt=o:r.bindings.push({surface:n.surface,key:n.key,boundAt:o,lastActiveAt:o}),this.pointBinding(s,e),r.lastActiveAt=o}unbind(e,n){let r=this.bindingKey(e,n),o=this.byBinding.get(r);if(this.byBinding.delete(r),o===void 0)return;let s=this.byId.get(o);s&&(s.bindings=s.bindings.filter(i=>this.bindingKey(i.surface,i.key)!==r))}attachSdkSessionId(e,n){let r=this.require(e);r.sdkSessionId!==void 0&&r.sdkSessionId!==n&&this.bySdk.get(r.sdkSessionId)===e&&this.bySdk.delete(r.sdkSessionId),r.sdkSessionId=n,this.bySdk.set(n,e),r.lastActiveAt=this.now()}rename(e,n){let r=this.require(e);r.name=n,r.lastActiveAt=this.now()}touch(e){let n=this.require(e);n.lastActiveAt=this.now()}archive(e){let n=this.require(e);n.status="archived",n.lastActiveAt=this.now();for(let r of n.bindings){let o=this.bindingKey(r.surface,r.key);this.byBinding.get(o)===e&&this.byBinding.delete(o)}}list(e){let n=[];for(let r of this.byId.values())e?.surface!==void 0&&r.surface!==e.surface||e?.status!==void 0&&r.status!==e.status||n.push(this.clone(r));return n.sort((r,o)=>o.lastActiveAt-r.lastActiveAt),n}bindingKey(e,n){return`${e}\0${n}`}require(e){let n=this.byId.get(e);if(!n)throw new Zr(`unknown session handle: ${e}`);return n}pointBinding(e,n){let r=this.byBinding.get(e);if(r!==void 0&&r!==n){let o=this.byId.get(r);o&&(o.bindings=o.bindings.filter(s=>this.bindingKey(s.surface,s.key)!==e))}this.byBinding.set(e,n)}clone(e){return{...e,bindings:e.bindings.map(n=>({...n}))}}};var v7=new vd;function eo(){return ou(),Se()}function sD(t){return Kw(eo(),`${t}.json`)}function kd(t,{write:e=!1}={}){let n=t.includes("/")?t:sD(t),r,o;if(!e&&ra(n)?(r=Hw(n),o=Hw(eo())):(r=Ww(n),o=Ww(eo())),!r.startsWith(o+oD)&&r!==o)throw new Error(`Session path escapes sessions directory: ${t}`);return r}function Ad(t,e){let n=eo();ra(n)||tD(n,{recursive:!0});let r=e??t.sessionId??`session-${Date.now()}`,o={sessionId:t.sessionId,...t.name?{name:t.name}:{},...t.source?{source:t.source}:{},...t.actor?{actor:t.actor}:{},...t.telegramChatId!==void 0?{telegramChatId:t.telegramChatId}:{},...t.cwd?{cwd:t.cwd}:{},model:t.model,startedAt:t.sessionStartTime,savedAt:Date.now(),totalTurns:t.totalTurns,totalCostUsd:t.totalCostUsd,totalTokens:t.totalTokens,totalDurationMs:t.totalDurationMs,turns:t.turns},s=kd(r,{write:!0});return eD(s,JSON.stringify(o,null,2)),s}function at(t){let e;try{e=kd(t)}catch(n){console.warn(`loadSession: rejected unsafe session id ${JSON.stringify(t)}: ${n.message}`);return}if(ra(e))try{let n=Z0(e,"utf-8");return JSON.parse(n)}catch(n){console.warn(`loadSession: failed to read/parse ${e}: ${n.message}`);return}}function Ed(t){let e;try{e=kd(t)}catch{return}let n=at(e);if(n)return{path:e,id:Gw(e,".json"),data:n};let r=On();for(let s of r){if(s.id!==t&&s.sessionId!==t&&s.name!==t)continue;let i=at(s.path);if(i)return{path:s.path,id:s.id,data:i}}if(t.length>=3){let s=r.filter(i=>i.name!==void 0&&i.name.startsWith(t));if(s.length===1){let i=s[0];if(i){let a=at(i.path);if(a)return{path:i.path,id:i.id,data:a}}}}}function On(){let t=eo();if(!ra(t))return[];let e=[];for(let n of nD(t)){if(!n.endsWith(".json"))continue;let r=Kw(t,n);try{if(!rD(r).isFile())continue;let s=at(r);if(!s||typeof s.savedAt!="number"||typeof s.model!="string")continue;e.push({path:r,id:Gw(n,".json"),sessionId:s.sessionId,name:s.name,source:s.source,actor:s.actor,telegramChatId:s.telegramChatId,model:s.model,startedAt:s.startedAt,savedAt:s.savedAt,totalTurns:s.totalTurns,totalCostUsd:s.totalCostUsd,cwd:s.cwd})}catch{}}return e.sort((n,r)=>r.savedAt-n.savedAt),e}function qw(t){return t?{resume:t.resumeId,sessionId:t.resumeId,...t.stored?{resumeHistory:t.stored.turns.map(e=>({user:e.user,assistant:e.assistant}))}:{}}:{}}import{promises as to}from"fs";import{join as zw}from"path";var Dn=class{sessions=new Map;pendingSessions=new Map;sessionData=new Map;sessionStats=new Map;autosaveFailureLogged=new Set;pendingResume=new Map;options;constructor(e){this.options={dataDir:e.dataDir||"./data/telegram-sessions",defaultModel:e.defaultModel||"medium",apiKey:e.apiKey,settingSources:e.settingSources,thinking:e.thinking,effort:e.effort,botCwd:e.botCwd,createSession:e.createSession}}getSessionIfExists(e){return this.sessions.get(e)}async getSession(e){let n=this.sessions.get(e);if(n)return this._touchActivity(e),n;let r=this.pendingSessions.get(e);if(r)try{return await r}finally{this._touchActivity(e)}let o=this.sessionData.get(e)??{chatId:e,model:this.options.defaultModel,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()},s=(async()=>{let i={model:o.model,apiKey:this.options.apiKey};this.options.settingSources?.length&&(i.settingSources=this.options.settingSources),this.options.thinking!==void 0&&(i.thinking=this.options.thinking),this.options.effort!==void 0&&(i.effort=this.options.effort);let a=o.cwd??this.options.botCwd;a!==void 0&&a.length>0&&(i.cwd=a);let l=this.pendingResume.get(e);if(l!==void 0){let d=at(l);Object.assign(i,qw({id:l,resumeId:d?.sessionId??l,stored:d}))}let c=await this.options.createSession(Sd(mc(i)));return this.sessions.set(e,c),this.sessionData.set(e,o),l!==void 0&&this.pendingResume.delete(e),c})();this.pendingSessions.set(e,s);try{let i=await s;return this._touchActivity(e),i}finally{this.pendingSessions.delete(e)}}_touchActivity(e){let n=this.sessionData.get(e);n&&(n.lastActivity=new Date().toISOString())}recordTelegramTurn(e,n,r,o){let s=this._getOrCreateStats(e),i=this.sessions.get(e);!s.sessionId&&i?.sessionId&&(s.sessionId=i.sessionId),jw(s,n,r,o),!s.sessionId&&i?.sessionId&&(s.sessionId=i.sessionId);let a=this.sessionData.get(e);if(a&&s.sessionId&&(a.sessionId=s.sessionId),s.sessionId)try{Ad(s)}catch(l){this.autosaveFailureLogged.has(e)||(this.autosaveFailureLogged.add(e),console.error(`[session-manager] autosave failed for chat ${e} \u2014 conversation may not be resumable:`,l))}}_hydrateStatsFromStore(e){if(this.sessionStats.has(e))return;let n=this.sessionData.get(e)?.sessionId;if(!n)return;let r=at(n);if(!r||r.source!=="telegram"||r.telegramChatId!==e)return;let o={sessionId:r.sessionId,name:r.name,model:r.model,source:r.source,telegramChatId:r.telegramChatId,sessionStartTime:r.startedAt,totalTurns:r.totalTurns,totalCostUsd:r.totalCostUsd,totalTokens:r.totalTokens,totalDurationMs:r.totalDurationMs,turns:r.turns,turnCosts:[],turnTokens:[],permissionMode:"default"},s=this.sessionData.get(e)?.cwd;s!==void 0&&(o.cwd=s),this.sessionStats.set(e,o)}getSessionName(e){return this._hydrateStatsFromStore(e),this.sessionStats.get(e)?.name}setSessionName(e,n){let r=this._getOrCreateStats(e);r.name=n;let o=this.sessions.get(e);if(!r.sessionId&&o?.sessionId&&(r.sessionId=o.sessionId),r.totalTurns>0&&r.sessionId){let s=this.sessionData.get(e);return s&&(s.sessionId=r.sessionId),Ad(r),{persisted:!0}}return{persisted:!1}}_getOrCreateStats(e){this._hydrateStatsFromStore(e);let n=this.sessionStats.get(e);if(!n){n=Bw(this.getModel(e)),n.source="telegram",n.telegramChatId=e;let r=this.getCwd(e);r&&(n.cwd=r),this.sessionStats.set(e,n)}return n}_resetStats(e){this.sessionStats.delete(e),this.autosaveFailureLogged.delete(e),this.pendingResume.delete(e);let n=this.sessionData.get(e);n&&delete n.sessionId}async resetSession(e){let n=this.sessions.get(e);n&&(await n.close(),this.sessions.delete(e)),this._resetStats(e);let r=this.sessionData.get(e);r&&(r.lastActivity=new Date().toISOString())}async switchModel(e,n){let r=this.sessions.get(e);r&&(await r.close(),this.sessions.delete(e)),this._resetStats(e);let o=this.sessionData.get(e);o?(o.model=n,o.lastActivity=new Date().toISOString()):(o={chatId:e,model:n,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()},this.sessionData.set(e,o))}getModel(e){return this.sessionData.get(e)?.model||this.options.defaultModel}async setCwd(e,n){let r=this.sessions.get(e);r&&(await r.close(),this.sessions.delete(e)),this._resetStats(e);let o=this.sessionData.get(e);o?(o.cwd=n,o.lastActivity=new Date().toISOString()):(o={chatId:e,model:this.options.defaultModel,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString(),cwd:n},this.sessionData.set(e,o))}getCwd(e){return this.sessionData.get(e)?.cwd??this.options.botCwd}listChatSessions(e){let n=this.sessionData.get(e)?.sessionId;return On().filter(r=>r.source==="telegram"&&r.telegramChatId===e&&r.sessionId!==void 0).map(r=>{let o={sessionId:r.sessionId,model:r.model,turns:r.totalTurns,lastActive:r.savedAt,active:r.sessionId===n};return r.name!==void 0&&(o.name=r.name),o}).sort((r,o)=>o.lastActive-r.lastActive)}async switchToSession(e,n){let r=this.pendingSessions.get(e);if(r!==void 0&&await r.catch(()=>{}),this.sessions.has(e)&&this.sessionData.get(e)?.sessionId===n)return{ok:!1,reason:"already-active"};let o=at(n);if(!o||o.source!=="telegram"||o.telegramChatId!==e)return{ok:!1,reason:"not-found"};let s=this.sessions.get(e);s&&(await s.close().catch(a=>console.error("Error closing session on switch:",a)),this.sessions.delete(e)),this.sessionStats.delete(e),this.autosaveFailureLogged.delete(e);let i=this.sessionData.get(e);return i?(i.model=o.model,i.lastActivity=new Date().toISOString()):(i={chatId:e,model:o.model,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()},this.sessionData.set(e,i)),i.sessionId=n,o.cwd!==void 0?i.cwd=o.cwd:delete i.cwd,this.pendingResume.set(e,n),o.name!==void 0?{ok:!0,name:o.name}:{ok:!0}}async newSession(e){this.pendingResume.delete(e),await this.resetSession(e)}async loadSessions(){try{await to.mkdir(this.options.dataDir,{recursive:!0});let e=await to.readdir(this.options.dataDir);for(let n of e)if(n.endsWith(".json")){let r=zw(this.options.dataDir,n),o=await to.readFile(r,"utf-8"),s=JSON.parse(o);this.sessionData.set(s.chatId,s)}}catch(e){e.code!=="ENOENT"&&console.error("Failed to load sessions:",e)}}async saveSessions(){try{await to.mkdir(this.options.dataDir,{recursive:!0});for(let[e,n]of this.sessionData.entries()){let r=zw(this.options.dataDir,`${e}.json`);await to.writeFile(r,JSON.stringify(n,null,2))}}catch(e){console.error("Failed to save sessions:",e)}}async closeAll(){await this.saveSessions();let e=Array.from(this.sessions.values()).map(n=>n.close().catch(r=>console.error("Error closing session:",r)));await Promise.all(e),this.sessions.clear()}getSessionCount(){return this.sessions.size}getChatCount(){return this.sessionData.size}getBusySessionCount(){let e=0;for(let n of this.sessions.values())n.state!=="idle"&&n.state!=="closed"&&e++;return e}};async function _d(t){await t.reply(cl())}async function Td(t,e){let n=t.chat?.id,r,o=n?e.getSessionIfExists(n):void 0;if(o)try{await Promise.race([o.waitForInitialization(),new Promise((i,a)=>setTimeout(()=>a(new Error("timeout")),2e3))]);let s=o.getSessionMetadata();s.slashCommands?.length&&(r=s.slashCommands)}catch{}await t.reply(dp(r))}import{Markup as Xw}from"telegraf";import{promises as lD}from"fs";import{homedir as Qw}from"os";import{isAbsolute as cD,resolve as xd}from"path";async function no(t,e){t.sendChatAction("typing").catch(()=>{});let n=setInterval(()=>{t.sendChatAction("typing").catch(()=>{})},4e3);try{return await e()}finally{clearInterval(n)}}function iD(t,e){try{if(!t||t.trim().toLowerCase()==="auto")return{available:!0,needs:"unknown"};let n=Pt(t,e);if(n.id==="")return{available:!1,needs:"local",hint:"not configured (set AFK_MODEL_LOCAL / models.local)"};if(n.provider==="chatgpt-oauth"){let o=wt(void 0,{},!0).apiKey!=null;return{available:o,needs:"chatgpt-oauth",hint:o?void 0:"needs ChatGPT sign-in (~/.codex/auth.json)"}}if(n.apiKey)return{available:!0,needs:"unknown"};let r=J(t,e?{slots:e}:void 0);if(r==="anthropic-direct"){let o=!!Ho();return{available:o,needs:"anthropic",hint:o?void 0:"needs Claude sign-in / ANTHROPIC_API_KEY"}}if(r==="openai-compatible"){if(n.baseUrl)return{available:!0,needs:"local"};let o=!!Za()||wt(void 0,{},!1).apiKey!=null;return{available:o,needs:"openai",hint:o?void 0:"needs OPENAI_API_KEY"}}return{available:!0,needs:"unknown"}}catch{return{available:!0,needs:"unknown"}}}function Jw(t,e){return iD(t,e).available}var aD=/^[A-Za-z0-9_@%+=:,./-]+$/;function Vw(t){return aD.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Yw(t,e){let n=["afk","interactive"];return typeof e=="string"&&e.length>0&&n.push("--model",Vw(e)),n.push("--resume",Vw(t)),n.join(" ")}async function Rd(t,e,n,r){let o=t.chat?.id;if(!o){await t.reply(N("Could not identify chat"));return}try{await e.resetSession(o),n.delete(o),await t.reply(sr())}catch(s){r("Clear error:",s),await t.reply(N(s))}}async function Zw(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}try{let o=await e.getSession(r),s=o.hookRegistry,i=await no(t,async()=>(s&&await s.dispatch({event:"PreCompact",sessionId:o.sessionId,trigger:"manual"}),o.compact()));i.compacted?await t.reply(ir({before:i.messagesBefore,after:i.messagesAfter,...i.tokensSavedEstimate!==void 0?{tokensSavedEstimate:i.tokensSavedEstimate}:{}})):await t.reply(ar(i.reason??"unknown"))}catch(o){o instanceof G?await t.reply(`Compaction skipped: ${ke(o.reason??"blocked by hook")}`):(n("Compact error:",o),await t.reply(N(o)))}}async function Id(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1);if(s.length===0){let m=e.getModel(r),g=tn.map(h=>[Xw.button.callback(Jw(h)?h:`${h} \u2014 needs sign-in`,`afk:m:${h}`)]);await t.reply(`Current model: <b>${ke(m.toUpperCase())}</b>
1103
+ ${o}`}}}return{...t,systemPrompt:o}}function na(t){let e=t.toLowerCase().replace(/[`*_~]/g," ").replace(/[^\w\s-]/g," ").replace(/[\s_]+/g," ").trim();return e?e.split(" ").filter(Boolean).slice(0,6).join("-").slice(0,48).replace(/-+$/g,""):""}function Bw(t){return{totalTurns:0,totalCostUsd:0,totalTokens:0,totalDurationMs:0,sessionStartTime:Date.now(),turnCosts:[],turnTokens:[],turns:[],model:t,permissionMode:"default",thinkingUi:"live"}}function jw(t,e,n,r,o){let s=r?.totalCostUsd??0,i=r?.durationMs??0,a=Number(r?.usage?.input_tokens??0),l=Number(r?.usage?.output_tokens??0),c=a,d=l,u=Number(r?.usage?.cache_read_input_tokens??0)+Number(r?.usage?.cache_creation_input_tokens??0),p=r?.usage?.iterations;if(Array.isArray(p)&&p.length>0){let y=p[p.length-1];if(y&&typeof y=="object"){let w=y;c=Number(w.input_tokens??0),d=Number(w.output_tokens??0),u=Number(w.cache_read_input_tokens??0)+Number(w.cache_creation_input_tokens??0)}}t.totalTurns+=1,t.totalCostUsd+=s,t.totalDurationMs+=i,t.totalTokens+=a+l,t.turnCosts.push(s);let f=Number(r?.usage?.context_window_tokens??NaN),m=Array.isArray(p)&&p.length>0,g=Number.isFinite(f)?f:m?c+d+u:void 0;if(t.turnTokens.push({input:c,output:d,cache:u,...g!==void 0?{footprint:g}:{}}),r?.sessionId&&!t.sessionId&&(t.sessionId=String(r.sessionId)),!t.name){let y=na(e);y&&(t.name=y)}let h={user:e,assistant:n,timestamp:Date.now(),costUsd:s,durationMs:i,inputTokens:a,outputTokens:l,...o&&o.length>0?{toolEvents:o}:{}};return t.turns.push(h),h}import{readFileSync as Z0,writeFileSync as eD,existsSync as ra,mkdirSync as tD,readdirSync as nD,statSync as rD,realpathSync as Hw}from"fs";import{join as Kw,basename as Gw,resolve as Ww,sep as oD}from"path";F();import{randomUUID as Q0}from"node:crypto";var Zr=class extends Error{constructor(e){super(e),this.name="SessionRegistryError"}},vd=class{byId=new Map;byBinding=new Map;bySdk=new Map;now;constructor(e){this.now=e?.now??Date.now}create(e){let n=this.now(),r=e.id??Q0();if(this.byId.has(r))throw new Zr(`session handle already exists: ${r}`);let o={surface:e.surface,key:e.key,boundAt:n,lastActiveAt:n},s={id:r,surface:e.surface,model:e.model,createdAt:e.createdAt??n,lastActiveAt:n,status:"active",bindings:[o]};return e.name!==void 0&&(s.name=e.name),e.cwd!==void 0&&(s.cwd=e.cwd),e.sdkSessionId!==void 0&&(s.sdkSessionId=e.sdkSessionId),this.byId.set(r,s),this.pointBinding(this.bindingKey(o.surface,o.key),r),s.sdkSessionId!==void 0&&this.bySdk.set(s.sdkSessionId,r),this.clone(s)}load(e){if(this.byId.has(e.id))throw new Zr(`session handle already exists: ${e.id}`);let n=this.clone(e);if(this.byId.set(n.id,n),n.status==="active")for(let r of n.bindings)this.pointBinding(this.bindingKey(r.surface,r.key),n.id);n.sdkSessionId!==void 0&&this.bySdk.set(n.sdkSessionId,n.id)}get(e){let n=this.byId.get(e);return n?this.clone(n):void 0}getBySdkSessionId(e){let n=this.bySdk.get(e);if(n===void 0)return;let r=this.byId.get(n);return r?this.clone(r):void 0}resolve(e,n){let r=this.byBinding.get(this.bindingKey(e,n));if(r===void 0)return;let o=this.byId.get(r);if(!(!o||o.status!=="active"))return this.clone(o)}bind(e,n){let r=this.require(e),o=this.now(),s=this.bindingKey(n.surface,n.key),i=r.bindings.find(a=>this.bindingKey(a.surface,a.key)===s);i?i.lastActiveAt=o:r.bindings.push({surface:n.surface,key:n.key,boundAt:o,lastActiveAt:o}),this.pointBinding(s,e),r.lastActiveAt=o}unbind(e,n){let r=this.bindingKey(e,n),o=this.byBinding.get(r);if(this.byBinding.delete(r),o===void 0)return;let s=this.byId.get(o);s&&(s.bindings=s.bindings.filter(i=>this.bindingKey(i.surface,i.key)!==r))}attachSdkSessionId(e,n){let r=this.require(e);r.sdkSessionId!==void 0&&r.sdkSessionId!==n&&this.bySdk.get(r.sdkSessionId)===e&&this.bySdk.delete(r.sdkSessionId),r.sdkSessionId=n,this.bySdk.set(n,e),r.lastActiveAt=this.now()}rename(e,n){let r=this.require(e);r.name=n,r.lastActiveAt=this.now()}touch(e){let n=this.require(e);n.lastActiveAt=this.now()}archive(e){let n=this.require(e);n.status="archived",n.lastActiveAt=this.now();for(let r of n.bindings){let o=this.bindingKey(r.surface,r.key);this.byBinding.get(o)===e&&this.byBinding.delete(o)}}list(e){let n=[];for(let r of this.byId.values())e?.surface!==void 0&&r.surface!==e.surface||e?.status!==void 0&&r.status!==e.status||n.push(this.clone(r));return n.sort((r,o)=>o.lastActiveAt-r.lastActiveAt),n}bindingKey(e,n){return`${e}\0${n}`}require(e){let n=this.byId.get(e);if(!n)throw new Zr(`unknown session handle: ${e}`);return n}pointBinding(e,n){let r=this.byBinding.get(e);if(r!==void 0&&r!==n){let o=this.byId.get(r);o&&(o.bindings=o.bindings.filter(s=>this.bindingKey(s.surface,s.key)!==e))}this.byBinding.set(e,n)}clone(e){return{...e,bindings:e.bindings.map(n=>({...n}))}}};var x7=new vd;function eo(){return ou(),Se()}function sD(t){return Kw(eo(),`${t}.json`)}function kd(t,{write:e=!1}={}){let n=t.includes("/")?t:sD(t),r,o;if(!e&&ra(n)?(r=Hw(n),o=Hw(eo())):(r=Ww(n),o=Ww(eo())),!r.startsWith(o+oD)&&r!==o)throw new Error(`Session path escapes sessions directory: ${t}`);return r}function Ad(t,e){let n=eo();ra(n)||tD(n,{recursive:!0});let r=e??t.sessionId??`session-${Date.now()}`,o={sessionId:t.sessionId,...t.name?{name:t.name}:{},...t.source?{source:t.source}:{},...t.actor?{actor:t.actor}:{},...t.telegramChatId!==void 0?{telegramChatId:t.telegramChatId}:{},...t.cwd?{cwd:t.cwd}:{},model:t.model,startedAt:t.sessionStartTime,savedAt:Date.now(),totalTurns:t.totalTurns,totalCostUsd:t.totalCostUsd,totalTokens:t.totalTokens,totalDurationMs:t.totalDurationMs,turns:t.turns},s=kd(r,{write:!0});return eD(s,JSON.stringify(o,null,2)),s}function at(t){let e;try{e=kd(t)}catch(n){console.warn(`loadSession: rejected unsafe session id ${JSON.stringify(t)}: ${n.message}`);return}if(ra(e))try{let n=Z0(e,"utf-8");return JSON.parse(n)}catch(n){console.warn(`loadSession: failed to read/parse ${e}: ${n.message}`);return}}function Ed(t){let e;try{e=kd(t)}catch{return}let n=at(e);if(n)return{path:e,id:Gw(e,".json"),data:n};let r=On();for(let s of r){if(s.id!==t&&s.sessionId!==t&&s.name!==t)continue;let i=at(s.path);if(i)return{path:s.path,id:s.id,data:i}}if(t.length>=3){let s=r.filter(i=>i.name!==void 0&&i.name.startsWith(t));if(s.length===1){let i=s[0];if(i){let a=at(i.path);if(a)return{path:i.path,id:i.id,data:a}}}}}function On(){let t=eo();if(!ra(t))return[];let e=[];for(let n of nD(t)){if(!n.endsWith(".json"))continue;let r=Kw(t,n);try{if(!rD(r).isFile())continue;let s=at(r);if(!s||typeof s.savedAt!="number"||typeof s.model!="string")continue;e.push({path:r,id:Gw(n,".json"),sessionId:s.sessionId,name:s.name,source:s.source,actor:s.actor,telegramChatId:s.telegramChatId,model:s.model,startedAt:s.startedAt,savedAt:s.savedAt,totalTurns:s.totalTurns,totalCostUsd:s.totalCostUsd,cwd:s.cwd})}catch{}}return e.sort((n,r)=>r.savedAt-n.savedAt),e}function qw(t){return t?{resume:t.resumeId,sessionId:t.resumeId,...t.stored?{resumeHistory:t.stored.turns.map(e=>({user:e.user,assistant:e.assistant}))}:{}}:{}}import{promises as to}from"fs";import{join as zw}from"path";var Dn=class{sessions=new Map;pendingSessions=new Map;sessionData=new Map;sessionStats=new Map;autosaveFailureLogged=new Set;pendingResume=new Map;options;constructor(e){this.options={dataDir:e.dataDir||"./data/telegram-sessions",defaultModel:e.defaultModel||"medium",apiKey:e.apiKey,settingSources:e.settingSources,thinking:e.thinking,effort:e.effort,botCwd:e.botCwd,createSession:e.createSession}}getSessionIfExists(e){return this.sessions.get(e)}async getSession(e){let n=this.sessions.get(e);if(n)return this._touchActivity(e),n;let r=this.pendingSessions.get(e);if(r)try{return await r}finally{this._touchActivity(e)}let o=this.sessionData.get(e)??{chatId:e,model:this.options.defaultModel,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()},s=(async()=>{let i={model:o.model,apiKey:this.options.apiKey};this.options.settingSources?.length&&(i.settingSources=this.options.settingSources),this.options.thinking!==void 0&&(i.thinking=this.options.thinking),this.options.effort!==void 0&&(i.effort=this.options.effort);let a=o.cwd??this.options.botCwd;a!==void 0&&a.length>0&&(i.cwd=a);let l=this.pendingResume.get(e);if(l!==void 0){let d=at(l);Object.assign(i,qw({id:l,resumeId:d?.sessionId??l,stored:d}))}let c=await this.options.createSession(Sd(mc(i)));return this.sessions.set(e,c),this.sessionData.set(e,o),l!==void 0&&this.pendingResume.delete(e),c})();this.pendingSessions.set(e,s);try{let i=await s;return this._touchActivity(e),i}finally{this.pendingSessions.delete(e)}}_touchActivity(e){let n=this.sessionData.get(e);n&&(n.lastActivity=new Date().toISOString())}recordTelegramTurn(e,n,r,o){let s=this._getOrCreateStats(e),i=this.sessions.get(e);!s.sessionId&&i?.sessionId&&(s.sessionId=i.sessionId),jw(s,n,r,o),!s.sessionId&&i?.sessionId&&(s.sessionId=i.sessionId);let a=this.sessionData.get(e);if(a&&s.sessionId&&(a.sessionId=s.sessionId),s.sessionId)try{Ad(s)}catch(l){this.autosaveFailureLogged.has(e)||(this.autosaveFailureLogged.add(e),console.error(`[session-manager] autosave failed for chat ${e} \u2014 conversation may not be resumable:`,l))}}_hydrateStatsFromStore(e){if(this.sessionStats.has(e))return;let n=this.sessionData.get(e)?.sessionId;if(!n)return;let r=at(n);if(!r||r.source!=="telegram"||r.telegramChatId!==e)return;let o={sessionId:r.sessionId,name:r.name,model:r.model,source:r.source,telegramChatId:r.telegramChatId,sessionStartTime:r.startedAt,totalTurns:r.totalTurns,totalCostUsd:r.totalCostUsd,totalTokens:r.totalTokens,totalDurationMs:r.totalDurationMs,turns:r.turns,turnCosts:[],turnTokens:[],permissionMode:"default"},s=this.sessionData.get(e)?.cwd;s!==void 0&&(o.cwd=s),this.sessionStats.set(e,o)}getSessionName(e){return this._hydrateStatsFromStore(e),this.sessionStats.get(e)?.name}setSessionName(e,n){let r=this._getOrCreateStats(e);r.name=n;let o=this.sessions.get(e);if(!r.sessionId&&o?.sessionId&&(r.sessionId=o.sessionId),r.totalTurns>0&&r.sessionId){let s=this.sessionData.get(e);return s&&(s.sessionId=r.sessionId),Ad(r),{persisted:!0}}return{persisted:!1}}_getOrCreateStats(e){this._hydrateStatsFromStore(e);let n=this.sessionStats.get(e);if(!n){n=Bw(this.getModel(e)),n.source="telegram",n.telegramChatId=e;let r=this.getCwd(e);r&&(n.cwd=r),this.sessionStats.set(e,n)}return n}_resetStats(e){this.sessionStats.delete(e),this.autosaveFailureLogged.delete(e),this.pendingResume.delete(e);let n=this.sessionData.get(e);n&&delete n.sessionId}async resetSession(e){let n=this.sessions.get(e);n&&(await n.close(),this.sessions.delete(e)),this._resetStats(e);let r=this.sessionData.get(e);r&&(r.lastActivity=new Date().toISOString())}async switchModel(e,n){let r=this.sessions.get(e);r&&(await r.close(),this.sessions.delete(e)),this._resetStats(e);let o=this.sessionData.get(e);o?(o.model=n,o.lastActivity=new Date().toISOString()):(o={chatId:e,model:n,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()},this.sessionData.set(e,o))}getModel(e){return this.sessionData.get(e)?.model||this.options.defaultModel}async setCwd(e,n){let r=this.sessions.get(e);r&&(await r.close(),this.sessions.delete(e)),this._resetStats(e);let o=this.sessionData.get(e);o?(o.cwd=n,o.lastActivity=new Date().toISOString()):(o={chatId:e,model:this.options.defaultModel,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString(),cwd:n},this.sessionData.set(e,o))}getCwd(e){return this.sessionData.get(e)?.cwd??this.options.botCwd}listChatSessions(e){let n=this.sessionData.get(e)?.sessionId;return On().filter(r=>r.source==="telegram"&&r.telegramChatId===e&&r.sessionId!==void 0).map(r=>{let o={sessionId:r.sessionId,model:r.model,turns:r.totalTurns,lastActive:r.savedAt,active:r.sessionId===n};return r.name!==void 0&&(o.name=r.name),o}).sort((r,o)=>o.lastActive-r.lastActive)}async switchToSession(e,n){let r=this.pendingSessions.get(e);if(r!==void 0&&await r.catch(()=>{}),this.sessions.has(e)&&this.sessionData.get(e)?.sessionId===n)return{ok:!1,reason:"already-active"};let o=at(n);if(!o||o.source!=="telegram"||o.telegramChatId!==e)return{ok:!1,reason:"not-found"};let s=this.sessions.get(e);s&&(await s.close().catch(a=>console.error("Error closing session on switch:",a)),this.sessions.delete(e)),this.sessionStats.delete(e),this.autosaveFailureLogged.delete(e);let i=this.sessionData.get(e);return i?(i.model=o.model,i.lastActivity=new Date().toISOString()):(i={chatId:e,model:o.model,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()},this.sessionData.set(e,i)),i.sessionId=n,o.cwd!==void 0?i.cwd=o.cwd:delete i.cwd,this.pendingResume.set(e,n),o.name!==void 0?{ok:!0,name:o.name}:{ok:!0}}async newSession(e){this.pendingResume.delete(e),await this.resetSession(e)}async loadSessions(){try{await to.mkdir(this.options.dataDir,{recursive:!0});let e=await to.readdir(this.options.dataDir);for(let n of e)if(n.endsWith(".json")){let r=zw(this.options.dataDir,n),o=await to.readFile(r,"utf-8"),s=JSON.parse(o);this.sessionData.set(s.chatId,s)}}catch(e){e.code!=="ENOENT"&&console.error("Failed to load sessions:",e)}}async saveSessions(){try{await to.mkdir(this.options.dataDir,{recursive:!0});for(let[e,n]of this.sessionData.entries()){let r=zw(this.options.dataDir,`${e}.json`);await to.writeFile(r,JSON.stringify(n,null,2))}}catch(e){console.error("Failed to save sessions:",e)}}async closeAll(){await this.saveSessions();let e=Array.from(this.sessions.values()).map(n=>n.close().catch(r=>console.error("Error closing session:",r)));await Promise.all(e),this.sessions.clear()}getSessionCount(){return this.sessions.size}getChatCount(){return this.sessionData.size}getBusySessionCount(){let e=0;for(let n of this.sessions.values())n.state!=="idle"&&n.state!=="closed"&&e++;return e}};async function _d(t){await t.reply(cl())}async function Td(t,e){let n=t.chat?.id,r,o=n?e.getSessionIfExists(n):void 0;if(o)try{await Promise.race([o.waitForInitialization(),new Promise((i,a)=>setTimeout(()=>a(new Error("timeout")),2e3))]);let s=o.getSessionMetadata();s.slashCommands?.length&&(r=s.slashCommands)}catch{}await t.reply(dp(r))}import{Markup as Xw}from"telegraf";import{promises as lD}from"fs";import{homedir as Qw}from"os";import{isAbsolute as cD,resolve as xd}from"path";async function no(t,e){t.sendChatAction("typing").catch(()=>{});let n=setInterval(()=>{t.sendChatAction("typing").catch(()=>{})},4e3);try{return await e()}finally{clearInterval(n)}}function iD(t,e){try{if(!t||t.trim().toLowerCase()==="auto")return{available:!0,needs:"unknown"};let n=Pt(t,e);if(n.id==="")return{available:!1,needs:"local",hint:"not configured (set AFK_MODEL_LOCAL / models.local)"};if(n.provider==="chatgpt-oauth"){let o=wt(void 0,{},!0).apiKey!=null;return{available:o,needs:"chatgpt-oauth",hint:o?void 0:"needs ChatGPT sign-in (~/.codex/auth.json)"}}if(n.apiKey)return{available:!0,needs:"unknown"};let r=J(t,e?{slots:e}:void 0);if(r==="anthropic-direct"){let o=!!Ho();return{available:o,needs:"anthropic",hint:o?void 0:"needs Claude sign-in / ANTHROPIC_API_KEY"}}if(r==="openai-compatible"){if(n.baseUrl)return{available:!0,needs:"local"};let o=!!Za()||wt(void 0,{},!1).apiKey!=null;return{available:o,needs:"openai",hint:o?void 0:"needs OPENAI_API_KEY"}}return{available:!0,needs:"unknown"}}catch{return{available:!0,needs:"unknown"}}}function Jw(t,e){return iD(t,e).available}var aD=/^[A-Za-z0-9_@%+=:,./-]+$/;function Vw(t){return aD.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Yw(t,e){let n=["afk","interactive"];return typeof e=="string"&&e.length>0&&n.push("--model",Vw(e)),n.push("--resume",Vw(t)),n.join(" ")}async function Rd(t,e,n,r){let o=t.chat?.id;if(!o){await t.reply(N("Could not identify chat"));return}try{await e.resetSession(o),n.delete(o),await t.reply(sr())}catch(s){r("Clear error:",s),await t.reply(N(s))}}async function Zw(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}try{let o=await e.getSession(r),s=o.hookRegistry,i=await no(t,async()=>(s&&await s.dispatch({event:"PreCompact",sessionId:o.sessionId,trigger:"manual"}),o.compact()));i.compacted?await t.reply(ir({before:i.messagesBefore,after:i.messagesAfter,...i.tokensSavedEstimate!==void 0?{tokensSavedEstimate:i.tokensSavedEstimate}:{}})):await t.reply(ar(i.reason??"unknown"))}catch(o){o instanceof G?await t.reply(`Compaction skipped: ${ke(o.reason??"blocked by hook")}`):(n("Compact error:",o),await t.reply(N(o)))}}async function Id(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1);if(s.length===0){let m=e.getModel(r),g=tn.map(h=>[Xw.button.callback(Jw(h)?h:`${h} \u2014 needs sign-in`,`afk:m:${h}`)]);await t.reply(`Current model: <b>${ke(m.toUpperCase())}</b>
1104
1104
 
1105
1105
  Switch to:`,{parse_mode:"HTML",reply_markup:Xw.inlineKeyboard(g).reply_markup});return}let i=s[0];if(!i){await t.reply(N("Please specify a model: local, small, medium, large, opus, sonnet, haiku, or an org/model id"));return}let a=i.toLowerCase(),l=tn.includes(a),c=rn(a)!==void 0,d=J(a)==="openai-compatible",u=Pt(a).id.trim().toLowerCase(),p=u.startsWith("claude-")||u.startsWith("claude_");if(!l&&!c&&!d&&!p){await t.reply(N(`Invalid model: ${i}
1106
- Aliases: ${tn.join(", ")}, or a full model id`));return}let f=wu(a);if(f){await t.reply(N(f));return}try{await e.switchModel(r,a),await t.reply(or(a))}catch(m){n("Model switch error:",m),await t.reply(N(m))}}function dD(t,e){let n=t.trim();return n==="~"?Qw():n.startsWith("~/")?xd(Qw(),n.slice(2)):cD(n)?xd(n):xd(e,n)}async function eS(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1).filter(c=>c.length>0);if(s.length===0){let c=e.getCwd(r);await t.reply(up(c));return}let i=s[0];if(!i){await t.reply(N("Please specify a directory path"));return}let a=e.getCwd(r)??process.cwd(),l=dD(i,a);try{if(!(await lD.stat(l)).isDirectory()){await t.reply(N(`Not a directory: ${l}`));return}}catch(c){let d=c.code;d==="ENOENT"?await t.reply(ll("ENOENT",l)):d==="EACCES"?await t.reply(ll("EACCES",l)):(n("cwd stat error:",c),await t.reply(N(c)));return}try{await e.setCwd(r,l),await t.reply(pp(l))}catch(c){n("Cwd switch error:",c),await t.reply(N(c))}}async function tS(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1).join(" ").trim();if(!s){await t.reply(fp(e.getSessionName(r)));return}let i=na(s);if(!i){await t.reply(mp());return}try{let{persisted:a}=e.setSessionName(r,i),l=a?Yw(i,e.getModel(r)):void 0;await t.reply(gp(i,l))}catch(a){n("Name set error:",a),await t.reply(`\u{1F3F7}\uFE0F Named "${i}" but couldn't save it \u2014 it'll retry on your next message.`)}}import{Markup as nS}from"telegraf";var oa="afk:sw:",uD=64;function pD(t){let e=t.callbackQuery;return typeof e=="object"&&e!==null&&"data"in e?e.data:""}function rS(t,e){let n=t.getSessionIfExists(e);return n!==void 0&&n.state!=="idle"}async function oS(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let o=e.listChatSessions(r);if(o.length===0){await t.reply(bp());return}let s=o.filter(i=>(oa+i.sessionId).length<=uD).map(i=>[nS.button.callback(`${i.active?"\u2705 ":""}${i.name??"(unnamed)"} \xB7 ${i.turns} turns`,`${oa}${i.sessionId}`)]);await t.reply(yp(o),{parse_mode:"HTML",reply_markup:nS.inlineKeyboard(s).reply_markup})}async function sS(t,e,n,r){let o=t.chat?.id;if(!o){await t.reply(N("Could not identify chat"));return}if(rS(e,o)){await t.reply(dl());return}try{await e.newSession(o),n.delete(o),await t.reply(Sp())}catch(s){r("New session error:",s),await t.reply(N(s))}}async function iS(t,e,n){let r=t.chat?.id,o=pD(t),s=o.startsWith(oa)?o.slice(oa.length):"";if(!(!r||!s)){if(rS(e,r)){await t.reply(dl());return}try{let i=await e.switchToSession(r,s);if(!i.ok){await t.reply(i.reason==="already-active"?kp():vp());return}let a=wp(i.name!==void 0?{name:i.name}:{});await t.editMessageText(a,{parse_mode:"HTML"}).catch(()=>t.reply(a,{parse_mode:"HTML"}))}catch(i){n("Switch callback error:",i),await t.reply(N(i))}}}var fD="\u25D0 AFK mode ON \u2014 I'll work autonomously on reversible tasks and report here. High-risk / irreversible ops are REFUSED (not one-tap approvable) and surfaced as an Asking summary for you to handle deliberately. Send /afk off to stop.",mD="\u25CB AFK mode OFF \u2014 default permissions restored.";async function aS(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let s=(t.message.text??"").split(/\s+/).slice(1).join(" ").trim().toLowerCase();try{let i=await e.getSession(r),a=i.getSessionMetadata().permissionMode==="autonomous",l=s==="on"?!0:s==="off"?!1:!a;if(l===a){await t.reply(l?"\u25D0 AFK mode is already ON.":"\u25CB AFK mode is already OFF.");return}await i.setPermissionMode(l?"autonomous":"default"),await t.reply(l?fD:mD)}catch(i){n("AFK toggle error:",i),await t.reply(N("Could not toggle AFK mode"))}}P();var gD="https://api.anthropic.com/api/oauth/usage",hD="oauth-2025-04-20",yD=1e4;async function lS(t){let e=t?.fetchImpl??fetch,n=t?.timeoutMs??yD,r=t?.token??(b.CLAUDE_CODE_OAUTH_TOKEN||ve());if(!r)return{kind:"unavailable",reason:"no-token",detail:"No Claude Code OAuth token found. Set CLAUDE_CODE_OAUTH_TOKEN or run `claude login` and try again."};let o;try{o=await e(gD,{headers:{Authorization:`Bearer ${r}`,"anthropic-beta":hD},signal:AbortSignal.timeout(n)})}catch(u){return bD(u)?{kind:"unavailable",reason:"timeout",detail:"Request to the usage endpoint timed out."}:{kind:"unavailable",reason:"network-error",detail:"Network error while contacting the usage endpoint."}}if(!o.ok)return{kind:"unavailable",reason:"http-error",detail:`Usage endpoint returned HTTP ${o.status}.`};let s;try{s=await o.json()}catch{return{kind:"unavailable",reason:"malformed-response",detail:"Usage endpoint returned a response that was not valid JSON."}}if(typeof s!="object"||s===null)return{kind:"unavailable",reason:"malformed-response",detail:"Usage endpoint returned an unexpected response shape."};let i=s,a=sa(i.five_hour),l=sa(i.seven_day),c=sa(i.seven_day_sonnet),d=sa(i.seven_day_opus);return!a&&!l&&!c&&!d?{kind:"unavailable",reason:"malformed-response",detail:"Usage endpoint response contained none of the known usage windows."}:{kind:"ok",...a!==void 0?{fiveHour:a}:{},...l!==void 0?{sevenDay:l}:{},...c!==void 0?{sevenDaySonnet:c}:{},...d!==void 0?{sevenDayOpus:d}:{}}}function bD(t){return t instanceof Error&&(t.name==="TimeoutError"||t.name==="AbortError")}var wD=0,SD=4102444800;function vD(t){if(typeof t=="string"){let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}if(typeof t=="number")return!Number.isFinite(t)||t<wD||t>SD?void 0:new Date(t*1e3)}function sa(t){if(typeof t!="object"||t===null)return;let e=t,n=e.utilization;if(typeof n!="number"||!Number.isFinite(n))return;let r=n>1?n/100:n,o=Math.min(1,Math.max(0,r)),s=vD(e.resets_at);return{utilization:o,...s!==void 0?{resetsAt:s}:{}}}async function cS(t,e){try{let n=await lS();await t.reply(cp(n))}catch(n){e("Usage command error:",n),await t.reply(N("Could not fetch usage"))}}import{execFile as $D,spawn as BD}from"node:child_process";import{promisify as jD}from"node:util";F();import{execFile as kD}from"node:child_process";import{randomBytes as AD}from"node:crypto";import{promises as ia}from"node:fs";import{join as aa}from"node:path";import{promisify as ED}from"node:util";var xee=ED(kD);var Tt=class extends Error{cause;code;constructor(e,n,r){super(e),this.name="WorktreeError",this.cause=n,this.code=r}};function _D(t,e=40){return t.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,e).replace(/-+$/g,"")||"task"}function TD(){return AD(4).toString("hex").slice(0,4)}function xD(t){let e=n=>String(n).padStart(2,"0");return`${t.getUTCFullYear()}${e(t.getUTCMonth()+1)}${e(t.getUTCDate())}T${e(t.getUTCHours())}${e(t.getUTCMinutes())}${e(t.getUTCSeconds())}`}function dS(t,e={}){let n=(e.now??(()=>new Date))(),r=(e.randomSuffix??TD)();return`${xD(n)}-${_D(t,32)}-${r}`}function RD(t){let e=t;return e.respawnedAt===void 0&&(e.respawnedAt=void 0),e.respawnedAs===void 0&&(e.respawnedAs=void 0),e.prUrl===void 0&&(e.prUrl=void 0),e.prCreatedAt===void 0&&(e.prCreatedAt=void 0),e}async function Fn(t){let e=aa(Zd(t),"farm.json");try{let n=await ia.readFile(e,"utf8"),r=JSON.parse(n);if(r.schemaVersion!==1&&r.schemaVersion!==2&&r.schemaVersion!==3)throw new Tt(`unsupported farm manifest schema: ${r.schemaVersion} (expected 1, 2, or 3)`,void 0,"unsupported-schema");return RD(r)}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Tt?n:new Tt(`failed to load farm manifest ${e}`,n,"invalid")}}async function uS(t,e){let n=await Fn(t);if(!n)throw new Tt(`farm not found: ${t}`);return n.human_decision=e,n.decidedAt=new Date().toISOString(),n.schemaVersion=3,await ia.writeFile(aa(n.farmDir,"farm.json"),JSON.stringify(n,null,2)+`
1106
+ Aliases: ${tn.join(", ")}, or a full model id`));return}let f=wu(a);if(f){await t.reply(N(f));return}try{await e.switchModel(r,a),await t.reply(or(a))}catch(m){n("Model switch error:",m),await t.reply(N(m))}}function dD(t,e){let n=t.trim();return n==="~"?Qw():n.startsWith("~/")?xd(Qw(),n.slice(2)):cD(n)?xd(n):xd(e,n)}async function eS(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1).filter(c=>c.length>0);if(s.length===0){let c=e.getCwd(r);await t.reply(up(c));return}let i=s[0];if(!i){await t.reply(N("Please specify a directory path"));return}let a=e.getCwd(r)??process.cwd(),l=dD(i,a);try{if(!(await lD.stat(l)).isDirectory()){await t.reply(N(`Not a directory: ${l}`));return}}catch(c){let d=c.code;d==="ENOENT"?await t.reply(ll("ENOENT",l)):d==="EACCES"?await t.reply(ll("EACCES",l)):(n("cwd stat error:",c),await t.reply(N(c)));return}try{await e.setCwd(r,l),await t.reply(pp(l))}catch(c){n("Cwd switch error:",c),await t.reply(N(c))}}async function tS(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1).join(" ").trim();if(!s){await t.reply(fp(e.getSessionName(r)));return}let i=na(s);if(!i){await t.reply(mp());return}try{let{persisted:a}=e.setSessionName(r,i),l=a?Yw(i,e.getModel(r)):void 0;await t.reply(gp(i,l))}catch(a){n("Name set error:",a),await t.reply(`\u{1F3F7}\uFE0F Named "${i}" but couldn't save it \u2014 it'll retry on your next message.`)}}import{Markup as nS}from"telegraf";var oa="afk:sw:",uD=64;function pD(t){let e=t.callbackQuery;return typeof e=="object"&&e!==null&&"data"in e?e.data:""}function rS(t,e){let n=t.getSessionIfExists(e);return n!==void 0&&n.state!=="idle"}async function oS(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let o=e.listChatSessions(r);if(o.length===0){await t.reply(bp());return}let s=o.filter(i=>(oa+i.sessionId).length<=uD).map(i=>[nS.button.callback(`${i.active?"\u2705 ":""}${i.name??"(unnamed)"} \xB7 ${i.turns} turns`,`${oa}${i.sessionId}`)]);await t.reply(yp(o),{parse_mode:"HTML",reply_markup:nS.inlineKeyboard(s).reply_markup})}async function sS(t,e,n,r){let o=t.chat?.id;if(!o){await t.reply(N("Could not identify chat"));return}if(rS(e,o)){await t.reply(dl());return}try{await e.newSession(o),n.delete(o),await t.reply(Sp())}catch(s){r("New session error:",s),await t.reply(N(s))}}async function iS(t,e,n){let r=t.chat?.id,o=pD(t),s=o.startsWith(oa)?o.slice(oa.length):"";if(!(!r||!s)){if(rS(e,r)){await t.reply(dl());return}try{let i=await e.switchToSession(r,s);if(!i.ok){await t.reply(i.reason==="already-active"?kp():vp());return}let a=wp(i.name!==void 0?{name:i.name}:{});await t.editMessageText(a,{parse_mode:"HTML"}).catch(()=>t.reply(a,{parse_mode:"HTML"}))}catch(i){n("Switch callback error:",i),await t.reply(N(i))}}}var fD="\u25D0 AFK mode ON \u2014 I'll work autonomously on reversible tasks and report here. High-risk / irreversible ops are REFUSED (not one-tap approvable) and surfaced as an Asking summary for you to handle deliberately. Send /afk off to stop.",mD="\u25CB AFK mode OFF \u2014 default permissions restored.";async function aS(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let s=(t.message.text??"").split(/\s+/).slice(1).join(" ").trim().toLowerCase();try{let i=await e.getSession(r),a=i.getSessionMetadata().permissionMode==="autonomous",l=s==="on"?!0:s==="off"?!1:!a;if(l===a){await t.reply(l?"\u25D0 AFK mode is already ON.":"\u25CB AFK mode is already OFF.");return}await i.setPermissionMode(l?"autonomous":"default"),await t.reply(l?fD:mD)}catch(i){n("AFK toggle error:",i),await t.reply(N("Could not toggle AFK mode"))}}P();var gD="https://api.anthropic.com/api/oauth/usage",hD="oauth-2025-04-20",yD=1e4;async function lS(t){let e=t?.fetchImpl??fetch,n=t?.timeoutMs??yD,r=t?.token??(b.CLAUDE_CODE_OAUTH_TOKEN||ve());if(!r)return{kind:"unavailable",reason:"no-token",detail:"No Claude Code OAuth token found. Set CLAUDE_CODE_OAUTH_TOKEN or run `claude login` and try again."};let o;try{o=await e(gD,{headers:{Authorization:`Bearer ${r}`,"anthropic-beta":hD},signal:AbortSignal.timeout(n)})}catch(u){return bD(u)?{kind:"unavailable",reason:"timeout",detail:"Request to the usage endpoint timed out."}:{kind:"unavailable",reason:"network-error",detail:"Network error while contacting the usage endpoint."}}if(!o.ok)return{kind:"unavailable",reason:"http-error",detail:`Usage endpoint returned HTTP ${o.status}.`};let s;try{s=await o.json()}catch{return{kind:"unavailable",reason:"malformed-response",detail:"Usage endpoint returned a response that was not valid JSON."}}if(typeof s!="object"||s===null)return{kind:"unavailable",reason:"malformed-response",detail:"Usage endpoint returned an unexpected response shape."};let i=s,a=sa(i.five_hour),l=sa(i.seven_day),c=sa(i.seven_day_sonnet),d=sa(i.seven_day_opus);return!a&&!l&&!c&&!d?{kind:"unavailable",reason:"malformed-response",detail:"Usage endpoint response contained none of the known usage windows."}:{kind:"ok",...a!==void 0?{fiveHour:a}:{},...l!==void 0?{sevenDay:l}:{},...c!==void 0?{sevenDaySonnet:c}:{},...d!==void 0?{sevenDayOpus:d}:{}}}function bD(t){return t instanceof Error&&(t.name==="TimeoutError"||t.name==="AbortError")}var wD=0,SD=4102444800;function vD(t){if(typeof t=="string"){let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}if(typeof t=="number")return!Number.isFinite(t)||t<wD||t>SD?void 0:new Date(t*1e3)}function sa(t){if(typeof t!="object"||t===null)return;let e=t,n=e.utilization;if(typeof n!="number"||!Number.isFinite(n))return;let r=n>1?n/100:n,o=Math.min(1,Math.max(0,r)),s=vD(e.resets_at);return{utilization:o,...s!==void 0?{resetsAt:s}:{}}}async function cS(t,e){try{let n=await lS();await t.reply(cp(n))}catch(n){e("Usage command error:",n),await t.reply(N("Could not fetch usage"))}}import{execFile as $D,spawn as BD}from"node:child_process";import{promisify as jD}from"node:util";F();import{execFile as kD}from"node:child_process";import{randomBytes as AD}from"node:crypto";import{promises as ia}from"node:fs";import{join as aa}from"node:path";import{promisify as ED}from"node:util";var Oee=ED(kD);var Tt=class extends Error{cause;code;constructor(e,n,r){super(e),this.name="WorktreeError",this.cause=n,this.code=r}};function _D(t,e=40){return t.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,e).replace(/-+$/g,"")||"task"}function TD(){return AD(4).toString("hex").slice(0,4)}function xD(t){let e=n=>String(n).padStart(2,"0");return`${t.getUTCFullYear()}${e(t.getUTCMonth()+1)}${e(t.getUTCDate())}T${e(t.getUTCHours())}${e(t.getUTCMinutes())}${e(t.getUTCSeconds())}`}function dS(t,e={}){let n=(e.now??(()=>new Date))(),r=(e.randomSuffix??TD)();return`${xD(n)}-${_D(t,32)}-${r}`}function RD(t){let e=t;return e.respawnedAt===void 0&&(e.respawnedAt=void 0),e.respawnedAs===void 0&&(e.respawnedAs=void 0),e.prUrl===void 0&&(e.prUrl=void 0),e.prCreatedAt===void 0&&(e.prCreatedAt=void 0),e}async function Fn(t){let e=aa(Zd(t),"farm.json");try{let n=await ia.readFile(e,"utf8"),r=JSON.parse(n);if(r.schemaVersion!==1&&r.schemaVersion!==2&&r.schemaVersion!==3)throw new Tt(`unsupported farm manifest schema: ${r.schemaVersion} (expected 1, 2, or 3)`,void 0,"unsupported-schema");return RD(r)}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Tt?n:new Tt(`failed to load farm manifest ${e}`,n,"invalid")}}async function uS(t,e){let n=await Fn(t);if(!n)throw new Tt(`farm not found: ${t}`);return n.human_decision=e,n.decidedAt=new Date().toISOString(),n.schemaVersion=3,await ia.writeFile(aa(n.farmDir,"farm.json"),JSON.stringify(n,null,2)+`
1107
1107
  `,"utf8"),n}async function pS(t,e){let n=await Fn(t);if(!n)throw new Tt(`farm not found: ${t}`);return n.respawnedAt=new Date().toISOString(),n.respawnedAs=e,n.schemaVersion=3,await ia.writeFile(aa(n.farmDir,"farm.json"),JSON.stringify(n,null,2)+`
1108
1108
  `,"utf8"),n}async function fS(t,e){let n=await Fn(t);if(!n)throw new Tt(`farm not found: ${t}`);return n.prUrl=e,n.prCreatedAt=new Date().toISOString(),n.schemaVersion=3,await ia.writeFile(aa(n.farmDir,"farm.json"),JSON.stringify(n,null,2)+`
1109
- `,"utf8"),n}import{execFile as ID,spawn as Cee}from"node:child_process";import{promisify as CD}from"node:util";var PD=CD(ID),MD=2e4,oo=class extends Error{kind;exitCode;stderr;constructor(e,n,r,o){super(e),this.name="GhError",this.kind=n,this.exitCode=r,this.stderr=o}},la=null,ro=null;function OD(t,e,n){return n===!0?"timeout":e==="ENOENT"?"not-found":/already exists/i.test(t)?"already-exists":/authentication|please log in|HTTP 40[13]|bad credentials|token|scope/i.test(t)?"unauthed":/ETIMEDOUT|ECONNRESET|ECONNREFUSED/i.test(t+(e??""))?"network":"unknown"}function mS(t,e){return PD(t,e,{timeout:MD,killSignal:"SIGTERM"}).then(n=>({stdout:n.stdout,stderr:n.stderr}))}async function gS(t={}){let e=(t._now??(()=>Date.now()))(),n=t.ttlMs??6e4,r=t.execFn??mS,o=t.log??(()=>{});return la&&la.expiresAt>e?(o("[gh] checkGhReady cache hit"),la.result):(o("[gh] checkGhReady cache miss \u2014 probing"),ro||(ro=(async()=>{try{await r("gh",["--version"])}catch(a){let l=a;return l.killed?{ok:!1,hint:"`gh` timed out \u2014 check connectivity"}:l.code==="ENOENT"?{ok:!1,hint:"`gh` CLI not found \u2014 install with: brew install gh"}:{ok:!1,hint:"`gh --version` failed unexpectedly \u2014 check gh installation"}}try{await r("gh",["auth","status"])}catch(a){let l=a;return l.killed||/ETIMEDOUT|ECONNRESET|ENOTFOUND/i.test(String(l.code??""))?{ok:!1,hint:"check network \u2014 cannot reach GitHub"}:{ok:!1,hint:"`gh` is not authenticated \u2014 run: gh auth login"}}let i={ok:!0};return n>0&&(la={result:i,expiresAt:e+n}),i})().finally(()=>{ro=null}),ro))}async function hS(t,e){let n=e??mS,r=["pr","create","--base",t.base,"--head",t.head,"--title",t.title,"--body",t.body];try{let{stdout:o}=await n("gh",r);return o.trim()}catch(o){let s=o,i=s.stderr??"",a=s.code,l=s.exitCode??1,c=OD(i,a,s.killed);throw new oo(`gh pr create failed (${c}): ${i.trim()}`,c,l,i)}}function yS(t,e){let n;try{n=e?._store??new tt}catch(r){return{skipped:!0,reason:r instanceof Error?r.message:String(r)}}try{let r={type:"farm-decision",taskSlug:t.taskSlug,decision:t.decision,decidedAt:t.decidedAt,via:t.via};return{factId:n.storeFact({category:"decision",content:JSON.stringify(r),source_surface:"afk"})}}catch(r){return{skipped:!0,reason:r instanceof Error?r.message:String(r)}}}import{promises as DD}from"node:fs";import{join as FD}from"node:path";function SS(t){let e=t.filter(r=>r.score!==null),n=t.filter(r=>r.score===null).map(r=>r.index).sort((r,o)=>r-o);return e.sort((r,o)=>{let s=r.score,i=o.score,a=bS(s),l=bS(i);if(a!==l)return l-a;let c=wS(s.lint_ok),d=wS(i.lint_ok);return c!==d?d-c:s.loc_delta!==i.loc_delta?s.loc_delta-i.loc_delta:r.index-o.index}),[...e.map(r=>r.index),...n]}function bS(t){let e=t.pass+t.fail;return e===0?0:t.pass/e}function wS(t){return t===!0?2:t===!1?1:0}async function ca(t,e={}){if(t.branches.length===0)throw new Error(`resolveWinnerBranch: farm ${t.taskSlug} has no branches`);let n=e.loadScore??LD,r=await Promise.all(t.branches.map(async i=>({index:i.index,score:await n(t.farmDir,i.index)}))),o=SS(r),s=new Map(t.branches.map(i=>[i.index,i]));for(let i of o){let a=r.find(l=>l.index===i)?.score;if(a&&a.pass>0&&a.fail===0){let l=s.get(i);if(l)return{branch:l,source:"winner"}}}for(let i of o)if(r.find(l=>l.index===i)?.score){let l=s.get(i);if(l)return{branch:l,source:"top-scored"}}return{branch:t.branches[0],source:"fallback-first-branch"}}async function LD(t,e){let n=FD(t,"scores",`branch-${e}.json`);try{let r=await DD.readFile(n,"utf8");return JSON.parse(r)}catch(r){return r.code==="ENOENT",null}}var da="afk:f:";var ND=new Set(["p","d","r","x"]),UD=/^[a-z0-9T][a-z0-9T-]{0,62}$/;function vS(t){if(!t||!t.startsWith(da)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(da.length),n=e.indexOf(":");if(n<1)return null;let r=e.slice(0,n),o=e.slice(n+1);return!ND.has(r)||!UD.test(o)?null:{action:r,taskSlug:o}}var HD=jD($D),Cd=new Map;async function AS(t,e={}){let n=e.log??(()=>{}),r=WD(t),o=vS(r);if(!o){await ce(t,"Unknown action",n);return}if(t.chat?.id===void 0){await ce(t,"No chat context",n);return}let s=e.loadFarm??Fn,i;try{i=await s(o.taskSlug)}catch(a){n("[farm-callback] loadFarm failed:",a),await ce(t,"Farm load failed",n);return}if(!i){await ce(t,"Farm not found (already GC\u2019d?)",n);return}try{await KD(o.action,t,i,e,n)}catch(a){n("[farm-callback] dispatch error:",a),await ce(t,"Internal error",n)}}function WD(t){return t.callbackQuery?.data}async function ce(t,e,n){try{await t.answerCbQuery(e)}catch(r){n("[farm-callback] answerCbQuery failed:",r)}}async function KD(t,e,n,r,o){switch(t){case"x":return JD(e,n,r,o);case"d":return VD(e,n,r,o);case"p":return kS(`p:${n.taskSlug}`,e,n,r,o,GD);case"r":return kS(`r:${n.taskSlug}`,e,n,r,o,zD)}}async function kS(t,e,n,r,o,s){let i=Cd.get(t);if(i){o(`[farm-callback] ${t} \u2014 second tap, awaiting in-flight lock`);try{await i}catch{}let l=r.loadFarm??Fn,c;try{c=await l(n.taskSlug)}catch{await ce(e,"Farm load failed",o);return}if(!c){await ce(e,"Farm not found",o);return}return s(e,c,r,o)}let a=s(e,n,r,o);return Cd.set(t,a),a.finally(()=>{Cd.delete(t)}),a}async function GD(t,e,n,r){if(e.prUrl){await ce(t,`PR already open: ${e.prUrl}`,r);return}await ce(t,"Opening PR\u2026",r);let o=n.checkGhReady??gS,s;try{s=await o()}catch(g){r("[farm-callback] checkGhReady threw:",g);try{await t.reply("gh readiness check failed \u2014 see daemon logs")}catch{}return}if(!s.ok){try{await t.reply(s.hint)}catch{}return}let i=n.resolveWinnerBranch??ca,a;try{a=await i(e)}catch(g){r("[farm-callback] resolveWinnerBranch failed:",g);try{await t.reply("Winner lookup failed")}catch{}return}let l=a.branch.branch,c=e.baseBranch??"main",d=`Auto PR: ${e.taskName}`,u=`Auto-generated by afk farm ${e.taskSlug} | winner: ${l} | created: ${new Date().toISOString()}`,p=n.createPr??hS,f;try{f=await p({base:c,head:l,title:d,body:u})}catch(g){if(g instanceof oo){let h={"not-found":"gh CLI not found \u2014 install with: brew install gh","already-exists":"PR already exists for this branch",unauthed:"gh is not authenticated \u2014 run: gh auth login",network:"Network error \u2014 check gh connectivity",timeout:"gh timed out \u2014 check connectivity",unknown:"gh pr create failed \u2014 see daemon logs"};try{await t.reply(h[g.kind])}catch{}return}r("[farm-callback] createPr failed:",g);try{await t.reply("gh pr create failed \u2014 see daemon logs")}catch{}return}let m=n.recordPrCreated??fS;try{await m(e.taskSlug,f)}catch(g){r("[farm-callback] recordPrCreated failed:",g)}try{await t.reply(`PR opened \u2713
1109
+ `,"utf8"),n}import{execFile as ID,spawn as Lee}from"node:child_process";import{promisify as CD}from"node:util";var PD=CD(ID),MD=2e4,oo=class extends Error{kind;exitCode;stderr;constructor(e,n,r,o){super(e),this.name="GhError",this.kind=n,this.exitCode=r,this.stderr=o}},la=null,ro=null;function OD(t,e,n){return n===!0?"timeout":e==="ENOENT"?"not-found":/already exists/i.test(t)?"already-exists":/authentication|please log in|HTTP 40[13]|bad credentials|token|scope/i.test(t)?"unauthed":/ETIMEDOUT|ECONNRESET|ECONNREFUSED/i.test(t+(e??""))?"network":"unknown"}function mS(t,e){return PD(t,e,{timeout:MD,killSignal:"SIGTERM"}).then(n=>({stdout:n.stdout,stderr:n.stderr}))}async function gS(t={}){let e=(t._now??(()=>Date.now()))(),n=t.ttlMs??6e4,r=t.execFn??mS,o=t.log??(()=>{});return la&&la.expiresAt>e?(o("[gh] checkGhReady cache hit"),la.result):(o("[gh] checkGhReady cache miss \u2014 probing"),ro||(ro=(async()=>{try{await r("gh",["--version"])}catch(a){let l=a;return l.killed?{ok:!1,hint:"`gh` timed out \u2014 check connectivity"}:l.code==="ENOENT"?{ok:!1,hint:"`gh` CLI not found \u2014 install with: brew install gh"}:{ok:!1,hint:"`gh --version` failed unexpectedly \u2014 check gh installation"}}try{await r("gh",["auth","status"])}catch(a){let l=a;return l.killed||/ETIMEDOUT|ECONNRESET|ENOTFOUND/i.test(String(l.code??""))?{ok:!1,hint:"check network \u2014 cannot reach GitHub"}:{ok:!1,hint:"`gh` is not authenticated \u2014 run: gh auth login"}}let i={ok:!0};return n>0&&(la={result:i,expiresAt:e+n}),i})().finally(()=>{ro=null}),ro))}async function hS(t,e){let n=e??mS,r=["pr","create","--base",t.base,"--head",t.head,"--title",t.title,"--body",t.body];try{let{stdout:o}=await n("gh",r);return o.trim()}catch(o){let s=o,i=s.stderr??"",a=s.code,l=s.exitCode??1,c=OD(i,a,s.killed);throw new oo(`gh pr create failed (${c}): ${i.trim()}`,c,l,i)}}function yS(t,e){let n;try{n=e?._store??new tt}catch(r){return{skipped:!0,reason:r instanceof Error?r.message:String(r)}}try{let r={type:"farm-decision",taskSlug:t.taskSlug,decision:t.decision,decidedAt:t.decidedAt,via:t.via};return{factId:n.storeFact({category:"decision",content:JSON.stringify(r),source_surface:"afk"})}}catch(r){return{skipped:!0,reason:r instanceof Error?r.message:String(r)}}}import{promises as DD}from"node:fs";import{join as FD}from"node:path";function SS(t){let e=t.filter(r=>r.score!==null),n=t.filter(r=>r.score===null).map(r=>r.index).sort((r,o)=>r-o);return e.sort((r,o)=>{let s=r.score,i=o.score,a=bS(s),l=bS(i);if(a!==l)return l-a;let c=wS(s.lint_ok),d=wS(i.lint_ok);return c!==d?d-c:s.loc_delta!==i.loc_delta?s.loc_delta-i.loc_delta:r.index-o.index}),[...e.map(r=>r.index),...n]}function bS(t){let e=t.pass+t.fail;return e===0?0:t.pass/e}function wS(t){return t===!0?2:t===!1?1:0}async function ca(t,e={}){if(t.branches.length===0)throw new Error(`resolveWinnerBranch: farm ${t.taskSlug} has no branches`);let n=e.loadScore??LD,r=await Promise.all(t.branches.map(async i=>({index:i.index,score:await n(t.farmDir,i.index)}))),o=SS(r),s=new Map(t.branches.map(i=>[i.index,i]));for(let i of o){let a=r.find(l=>l.index===i)?.score;if(a&&a.pass>0&&a.fail===0){let l=s.get(i);if(l)return{branch:l,source:"winner"}}}for(let i of o)if(r.find(l=>l.index===i)?.score){let l=s.get(i);if(l)return{branch:l,source:"top-scored"}}return{branch:t.branches[0],source:"fallback-first-branch"}}async function LD(t,e){let n=FD(t,"scores",`branch-${e}.json`);try{let r=await DD.readFile(n,"utf8");return JSON.parse(r)}catch(r){return r.code==="ENOENT",null}}var da="afk:f:";var ND=new Set(["p","d","r","x"]),UD=/^[a-z0-9T][a-z0-9T-]{0,62}$/;function vS(t){if(!t||!t.startsWith(da)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(da.length),n=e.indexOf(":");if(n<1)return null;let r=e.slice(0,n),o=e.slice(n+1);return!ND.has(r)||!UD.test(o)?null:{action:r,taskSlug:o}}var HD=jD($D),Cd=new Map;async function AS(t,e={}){let n=e.log??(()=>{}),r=WD(t),o=vS(r);if(!o){await ce(t,"Unknown action",n);return}if(t.chat?.id===void 0){await ce(t,"No chat context",n);return}let s=e.loadFarm??Fn,i;try{i=await s(o.taskSlug)}catch(a){n("[farm-callback] loadFarm failed:",a),await ce(t,"Farm load failed",n);return}if(!i){await ce(t,"Farm not found (already GC\u2019d?)",n);return}try{await KD(o.action,t,i,e,n)}catch(a){n("[farm-callback] dispatch error:",a),await ce(t,"Internal error",n)}}function WD(t){return t.callbackQuery?.data}async function ce(t,e,n){try{await t.answerCbQuery(e)}catch(r){n("[farm-callback] answerCbQuery failed:",r)}}async function KD(t,e,n,r,o){switch(t){case"x":return JD(e,n,r,o);case"d":return VD(e,n,r,o);case"p":return kS(`p:${n.taskSlug}`,e,n,r,o,GD);case"r":return kS(`r:${n.taskSlug}`,e,n,r,o,zD)}}async function kS(t,e,n,r,o,s){let i=Cd.get(t);if(i){o(`[farm-callback] ${t} \u2014 second tap, awaiting in-flight lock`);try{await i}catch{}let l=r.loadFarm??Fn,c;try{c=await l(n.taskSlug)}catch{await ce(e,"Farm load failed",o);return}if(!c){await ce(e,"Farm not found",o);return}return s(e,c,r,o)}let a=s(e,n,r,o);return Cd.set(t,a),a.finally(()=>{Cd.delete(t)}),a}async function GD(t,e,n,r){if(e.prUrl){await ce(t,`PR already open: ${e.prUrl}`,r);return}await ce(t,"Opening PR\u2026",r);let o=n.checkGhReady??gS,s;try{s=await o()}catch(g){r("[farm-callback] checkGhReady threw:",g);try{await t.reply("gh readiness check failed \u2014 see daemon logs")}catch{}return}if(!s.ok){try{await t.reply(s.hint)}catch{}return}let i=n.resolveWinnerBranch??ca,a;try{a=await i(e)}catch(g){r("[farm-callback] resolveWinnerBranch failed:",g);try{await t.reply("Winner lookup failed")}catch{}return}let l=a.branch.branch,c=e.baseBranch??"main",d=`Auto PR: ${e.taskName}`,u=`Auto-generated by afk farm ${e.taskSlug} | winner: ${l} | created: ${new Date().toISOString()}`,p=n.createPr??hS,f;try{f=await p({base:c,head:l,title:d,body:u})}catch(g){if(g instanceof oo){let h={"not-found":"gh CLI not found \u2014 install with: brew install gh","already-exists":"PR already exists for this branch",unauthed:"gh is not authenticated \u2014 run: gh auth login",network:"Network error \u2014 check gh connectivity",timeout:"gh timed out \u2014 check connectivity",unknown:"gh pr create failed \u2014 see daemon logs"};try{await t.reply(h[g.kind])}catch{}return}r("[farm-callback] createPr failed:",g);try{await t.reply("gh pr create failed \u2014 see daemon logs")}catch{}return}let m=n.recordPrCreated??fS;try{await m(e.taskSlug,f)}catch(g){r("[farm-callback] recordPrCreated failed:",g)}try{await t.reply(`PR opened \u2713
1110
1110
  \u{1F517} ${f}`)}catch(g){r("[farm-callback] reply failed:",g)}}function qD(t,e=()=>{}){e("[farm] spawning child afk process",{args:t});let n=BD("afk",t,{detached:!0,stdio:"ignore"});n.on("error",r=>{e("[farm] child spawn error",{args:t,err:r.message})}),n.on("exit",(r,o)=>{r!==0&&e("[farm] child exited with non-zero code",{args:t,code:r,signal:o})}),n.unref()}async function zD(t,e,n,r){if(e.respawnedAs){await ce(t,`Already respawned as ${e.respawnedAs}`,r);return}if(e.branches.length===0){await ce(t,"No branches remain \u2014 cannot respawn",r);return}await ce(t,"Respawning\u2026",r);let o=n.resolveWinnerBranch??ca,s;try{s=await o(e)}catch(u){r("[farm-callback] resolveWinnerBranch failed:",u);try{await t.reply("Winner lookup failed")}catch{}return}let i=s.branch,a=dS(e.taskName,{now:n._now,randomSuffix:n._randomSuffix}),l=e.branches.length;r("[farm] spawning child",{childSlug:a,baseRef:i.branch,branches:l});let c=n.spawnFarm??(u=>qD(u,r));try{c(["farm",e.taskName,"--branches",String(l),"--base-ref",i.branch,"--task-slug",a])}catch(u){r("[farm-callback] spawnFarm failed:",u);try{await t.reply("Respawn failed")}catch{}return}let d=n.recordRespawn??pS;try{await d(e.taskSlug,a)}catch(u){r("[farm-callback] recordRespawn failed:",u)}try{await t.reply(`Respawning as \`${a}\` from ${i.branch} \u2713
1111
1111
  \u{1F504} Farm \`${e.taskSlug}\` respawned.
1112
1112
  Child slug: \`${a}\`
@@ -1117,7 +1117,7 @@ Commits:
1117
1117
  ${c.stdout.trim()||"(none)"}
1118
1118
 
1119
1119
  Stat:
1120
- ${d.stdout.trim()||"(no changes)"}`;await t.reply(u.slice(0,4e3))}catch(c){r("[farm-callback] diff failed:",c);try{await t.reply("Diff failed \u2014 see daemon logs.")}catch{}}}async function YD(t,e){let n=await HD("git",e,{cwd:t,maxBuffer:4194304});return{stdout:n.stdout,stderr:n.stderr}}import{TelegramError as XD}from"telegraf";function Ln(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("rate limit")||e.toLowerCase().includes("too many requests")}function Nn(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("network")||e.toLowerCase().includes("connect")||e.toLowerCase().includes("timeout")}function ua(t){return t instanceof XD}import{TelegramError as $n}from"telegraf";var Un=class extends Error{constructor(e){super(e),this.name="StreamTimeoutError"}};P();import nte from"string-width";var QD=/\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P^_X][^\x1B]*\x1B\\|[@-OQ-WYZ\\\-])/g,rte=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;function ES(t){return t.replace(QD,"")}var ZD=/[\x00-\x1F\x7F-\x9F]/g;function pa(t){return ES(t).replace(ZD," ").replace(/ {2,}/g," ").trim()}var eF=300,tF=9e4,_S=18e4,nF=66e4,rF=15e3,RS=4,oF=5e3,IS=6;var sF=2,iF=3e4,aF=1e3,lF=t=>new Promise(e=>setTimeout(e,t)),TS="\u26A0\uFE0F Telegram dropped part of this reply (rate limit) \u2014 ask me to resend it.";function cF(t){if(!(t instanceof $n)||t.code!==429)return null;let e=t.parameters?.retry_after,n=Number(/retry after (\d+)/i.exec(t.description??"")?.[1]),r=typeof e=="number"&&e>0?e:Number.isFinite(n)&&n>0?n:0;return Math.min(r>0?r*1e3:aF,iF)}async function Pd(t,e,n,r={}){let o=r.maxRetries??sF,s=r.sleep??lF;for(let i=0;;i++)try{await t(e,n);return}catch(a){let l=cF(a);if(l===null||i>=o)throw a;await s(l)}}var dF=[[["browser","web","fetch","scrape"],"Researching"],[["test","vitest","jest"],"Running tests"],[["bash","shell","exec","command"],"Running a command"]],uF=[[["search","grep","glob","find"],"Searching"],[["read","open","view","inspect"],"Reading files"],[["edit","write","patch","replace"],"Editing files"]];function Md(t){let e=pa(t),n=new Set(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean));for(let[o,s]of[...dF,...uF])if(o.some(i=>n.has(i)))return s;let r=e.replace(/[_-]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim();return r?`Using ${r}`:"Working"}function pF(t,e){let n=pa(t??"").replace(/\s+/g," ").trim(),r=/^(working|processing|in progress|running)(?:\s*\([^)]*\))?$/i.test(n);return e&&(!n||r)?Md(e):n||(e?Md(e):"Working")}function fF(t){if(/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(t))return"Sub-agent";let e=pa(t).replace(/[_-]+/g," ").replace(/\s+/g," ").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):"Sub-agent"}function mF(t,e){if(t<=0)return"";let n=e.slice(-RS),r=`\u{1F916} Sub-agents \xB7 ${t} ${t===1?"step":"steps"}`;return n.length>0?`
1120
+ ${d.stdout.trim()||"(no changes)"}`;await t.reply(u.slice(0,4e3))}catch(c){r("[farm-callback] diff failed:",c);try{await t.reply("Diff failed \u2014 see daemon logs.")}catch{}}}async function YD(t,e){let n=await HD("git",e,{cwd:t,maxBuffer:4194304});return{stdout:n.stdout,stderr:n.stderr}}import{TelegramError as XD}from"telegraf";function Ln(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("rate limit")||e.toLowerCase().includes("too many requests")}function Nn(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("network")||e.toLowerCase().includes("connect")||e.toLowerCase().includes("timeout")}function ua(t){return t instanceof XD}import{TelegramError as $n}from"telegraf";var Un=class extends Error{constructor(e){super(e),this.name="StreamTimeoutError"}};P();import lte from"string-width";var QD=/\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P^_X][^\x1B]*\x1B\\|[@-OQ-WYZ\\\-])/g,cte=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;function ES(t){return t.replace(QD,"")}var ZD=/[\x00-\x1F\x7F-\x9F]/g;function pa(t){return ES(t).replace(ZD," ").replace(/ {2,}/g," ").trim()}var eF=300,tF=9e4,_S=18e4,nF=66e4,rF=15e3,RS=4,oF=5e3,IS=6;var sF=2,iF=3e4,aF=1e3,lF=t=>new Promise(e=>setTimeout(e,t)),TS="\u26A0\uFE0F Telegram dropped part of this reply (rate limit) \u2014 ask me to resend it.";function cF(t){if(!(t instanceof $n)||t.code!==429)return null;let e=t.parameters?.retry_after,n=Number(/retry after (\d+)/i.exec(t.description??"")?.[1]),r=typeof e=="number"&&e>0?e:Number.isFinite(n)&&n>0?n:0;return Math.min(r>0?r*1e3:aF,iF)}async function Pd(t,e,n,r={}){let o=r.maxRetries??sF,s=r.sleep??lF;for(let i=0;;i++)try{await t(e,n);return}catch(a){let l=cF(a);if(l===null||i>=o)throw a;await s(l)}}var dF=[[["browser","web","fetch","scrape"],"Researching"],[["test","vitest","jest"],"Running tests"],[["bash","shell","exec","command"],"Running a command"]],uF=[[["search","grep","glob","find"],"Searching"],[["read","open","view","inspect"],"Reading files"],[["edit","write","patch","replace"],"Editing files"]];function Md(t){let e=pa(t),n=new Set(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean));for(let[o,s]of[...dF,...uF])if(o.some(i=>n.has(i)))return s;let r=e.replace(/[_-]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim();return r?`Using ${r}`:"Working"}function pF(t,e){let n=pa(t??"").replace(/\s+/g," ").trim(),r=/^(working|processing|in progress|running)(?:\s*\([^)]*\))?$/i.test(n);return e&&(!n||r)?Md(e):n||(e?Md(e):"Working")}function fF(t){if(/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(t))return"Sub-agent";let e=pa(t).replace(/[_-]+/g," ").replace(/\s+/g," ").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):"Sub-agent"}function mF(t,e){if(t<=0)return"";let n=e.slice(-RS),r=`\u{1F916} Sub-agents \xB7 ${t} ${t===1?"step":"steps"}`;return n.length>0?`
1121
1121
  ${r}
1122
1122
  ${n.join(`
1123
1123
  `)}`:`
@@ -1172,7 +1172,7 @@ Enter a number${T}`}w&&(d.allowSkip?S+=`
1172
1172
 
1173
1173
  <i>Type :cancel to cancel.</i>`),e.telegram.sendMessage(n,S,{parse_mode:"HTML"}).catch(()=>{h||(h=!0,u.signal.removeEventListener("abort",y),console.warn("[elicitation-handler] sendMessage failed; declining elicitation for chatId",n),i(),g({action:"decline"}))})})}}F();var US="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function $S(t=Date.now()){let e=t,n=new Array(10).fill("0");for(let o=9;o>=0;o--)n[o]=US[e%32],e=Math.floor(e/32);let r=new Array(16).fill("0");for(let o=0;o<16;o++)r[o]=US[Math.floor(Math.random()*32)];return n.join("")+r.join("")}var uo="afk:pa:",xF=64,co=new Map;function ba(t,e,n=()=>{}){let r=t;if(!r._elicitationRegistered){let o=new RegExp(`^${OF(uo)}`);t.action(o,async s=>RF(s,n)),r._elicitationRegistered=!0}return async(o,s)=>s.signal.aborted?{action:"decline"}:new Promise(i=>{let a=$S(),l=IF(o);co.set(a,{resolve:i,enumValues:l});let c=CF(o),d=PF(a,l),u=Array.from(e).map(async p=>{try{await t.telegram.sendMessage(p,c,{reply_markup:d})}catch(f){n("[elicitation] sendMessage failed:",f)}});Promise.all(u),s.signal.addEventListener("abort",()=>{let p=co.get(a);p&&(co.delete(a),p.resolve({action:"decline"}))},{once:!0})})}async function RF(t,e){let n=t.callbackQuery?.data;if(typeof n!="string"||!n.startsWith(uo)){await t.answerCbQuery("Unknown callback").catch(()=>{});return}let r=n.slice(uo.length),o=r.indexOf(":");if(o<=0||o===r.length-1){await t.answerCbQuery("Malformed callback").catch(()=>{});return}let s=r.slice(0,o),i=r.slice(o+1),a=co.get(s);if(!a){await t.answerCbQuery("This prompt is no longer active.").catch(()=>{});return}if(!a.enumValues.includes(i)){e("[elicitation] callback choice not in enum:",i,a.enumValues),await t.answerCbQuery("Unknown choice").catch(()=>{});return}co.delete(s),a.resolve({action:"accept",content:{choice:i}}),await t.answerCbQuery(`Recorded: ${i}`).catch(l=>{e("[elicitation] answerCbQuery failed:",l)})}function IF(t){if(t.mode!=="form")return["accept","decline"];let e=t.requestedSchema;if(typeof e!="object"||e===null)return["accept","decline"];let n=e.properties;if(typeof n!="object"||n===null)return["accept","decline"];let r=Object.keys(n)[0];if(r===void 0)return["accept","decline"];let o=n[r];if(typeof o!="object"||o===null)return["accept","decline"];let s=o.enum;return Array.isArray(s)?s.map(String):["accept","decline"]}function CF(t){let e=[];t.title&&e.push(t.title),e.push(t.message);let n=e.join(`
1174
1174
 
1175
- `);return n.length>4e3?n.slice(0,3997)+"...":n}function PF(t,e){let n=uo.length+t.length+1,r=xF-n,o=e.map(s=>{let i=s.length<=r?s:s.slice(0,r);return{text:MF(i),callback_data:`${uo}${t}:${i}`}});return o.length===4?{inline_keyboard:[[o[0],o[1]],[o[2],o[3]]]}:{inline_keyboard:o.map(s=>[s])}}function MF(t){switch(t){case"once":return"\u2705 Once";case"session":return"\u{1F501} Session";case"persist":return"\u{1F4BE} Always";case"deny":return"\u274C Deny";case"accept":return"\u2705 Accept";case"decline":return"\u274C Decline";default:return t.charAt(0).toUpperCase()+t.slice(1)}}function OF(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wa(t,e){return(n,r)=>n.type!==void 0?t(n,r):e(n,r)}import*as Sa from"node:fs";F();import{createHmac as DF,randomBytes as FF,timingSafeEqual as Hte}from"node:crypto";var BS="\0";function LF(t){return JSON.stringify(Nd(t))}function Nd(t){if(Array.isArray(t))return t.map(Nd);if(t!==null&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e).sort())n[r]=Nd(e[r]);return n}return t}function va(t){let e;try{e=su(t)}catch{return null}try{let n=Sa.readFileSync(e,"utf8").trim();return n.length>0?n:null}catch{return null}}function jS(t,e){return DF("sha256",t).update(e).digest("hex")}function NF(t,e,n){return["elicitation_response",t,e,LF(n)].join(BS)}function HS(t,e,n,r){return jS(t,NF(e,n,r))}function UF(t,e){return["abort_request",t,e].join(BS)}function WS(t,e,n){return jS(t,UF(e,n))}function KS(){return FF(8).toString("hex")}var $F=1500,GS=700,Ud=160,BF=15*6e4,jF=4;function po(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e)}\u2026`:n}function HF(t){switch(t.kind){case"meta":return`\u{1F4E1} Watching session ${t.sessionId}
1175
+ `);return n.length>4e3?n.slice(0,3997)+"...":n}function PF(t,e){let n=uo.length+t.length+1,r=xF-n,o=e.map(s=>{let i=s.length<=r?s:s.slice(0,r);return{text:MF(i),callback_data:`${uo}${t}:${i}`}});return o.length===4?{inline_keyboard:[[o[0],o[1]],[o[2],o[3]]]}:{inline_keyboard:o.map(s=>[s])}}function MF(t){switch(t){case"once":return"\u2705 Once";case"session":return"\u{1F501} Session";case"persist":return"\u{1F4BE} Always";case"deny":return"\u274C Deny";case"accept":return"\u2705 Accept";case"decline":return"\u274C Decline";default:return t.charAt(0).toUpperCase()+t.slice(1)}}function OF(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wa(t,e){return(n,r)=>n.type!==void 0?t(n,r):e(n,r)}import*as Sa from"node:fs";F();import{createHmac as DF,randomBytes as FF,timingSafeEqual as Jte}from"node:crypto";var BS="\0";function LF(t){return JSON.stringify(Nd(t))}function Nd(t){if(Array.isArray(t))return t.map(Nd);if(t!==null&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e).sort())n[r]=Nd(e[r]);return n}return t}function va(t){let e;try{e=su(t)}catch{return null}try{let n=Sa.readFileSync(e,"utf8").trim();return n.length>0?n:null}catch{return null}}function jS(t,e){return DF("sha256",t).update(e).digest("hex")}function NF(t,e,n){return["elicitation_response",t,e,LF(n)].join(BS)}function HS(t,e,n,r){return jS(t,NF(e,n,r))}function UF(t,e){return["abort_request",t,e].join(BS)}function WS(t,e,n){return jS(t,UF(e,n))}function KS(){return FF(8).toString("hex")}var $F=1500,GS=700,Ud=160,BF=15*6e4,jF=4;function po(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e)}\u2026`:n}function HF(t){switch(t.kind){case"meta":return`\u{1F4E1} Watching session ${t.sessionId}
1176
1176
  model: ${t.model}${t.cwd?`
1177
1177
  cwd: ${t.cwd}`:""}`;case"user":return`\u{1F464} ${po(t.text,GS)}`;case"assistant":return`\u{1F916} ${po(t.text,GS)}`;case"tool":return`\u{1F527} ${t.toolName}(${po(t.input,Ud)})`;case"tool_error":return`\u26A0\uFE0F tool failed: ${po(t.content,Ud)}`;case"done":{let e=[];return typeof t.durationMs=="number"&&e.push(`${(t.durationMs/1e3).toFixed(1)}s`),typeof t.costUsd=="number"&&e.push(`$${t.costUsd.toFixed(4)}`),`\u2705 turn done${e.length?` (${e.join(", ")})`:""}`}case"error":return`\u274C error: ${po(t.message,Ud)}`;case"paused":return`\u23F8\uFE0F paused on usage limit${t.resetsAt?` (resets ${t.resetsAt})`:""}`;case"resumed":return"\u25B6\uFE0F resumed";case"closed":return`\u{1F3C1} session closed${t.reason?` (${t.reason})`:""} \u2014 watch ended`;default:return null}}async function qS(t){let e=Ed(t);return e?.data.sessionId&&await Xi(e.data.sessionId)?e.data.sessionId:await Xi(t)?t:null}async function zS(){let t=[],n=(await Qn()).filter(s=>s.surface!=="telegram");if(n.length>0){t.push("\u{1F7E2} Live sessions:");for(let s of n)t.push(` ${s.sessionId} (${s.surface}, ${s.cwd})`)}let r=On().filter(s=>s.source!=="telegram").slice(0,8),o=[];for(let s of r)s.sessionId&&await Xi(s.sessionId)&&o.push(` ${s.name??s.id} (${s.model})`);return o.length>0&&(t.length>0&&t.push(""),t.push("\u{1F4BE} Recent sessions with activity logs:",...o)),t.length===0?"No watchable sessions found. Start one with `afk i` on your machine, then /watch <session-id-or-name>.":(t.push("","Watch one with /watch <session-id-or-name>."),t.join(`
1178
1178
  `))}var ka=class{watches=new Map;log;bot;messageHandler;elicitHeartbeatMs;constructor(e=()=>{},n,r,o=BF){this.log=e,this.bot=n,this.messageHandler=r,this.elicitHeartbeatMs=o}watching(e){return this.watches.get(e)?.sessionId}getWatched(e){return this.watches.get(e)?.sessionId}start(e,n,r){this.stop(e);let o=new AbortController,s=this._run(e,n,r,o.signal).catch(i=>{this.log("watch loop error:",i)});this.watches.set(e,{sessionId:n,abort:o,finished:s})}stop(e){let n=this.watches.get(e);if(n)return this.watches.delete(e),n.abort.abort(),n.sessionId}async stopAll(){let e=[...this.watches.values()];this.watches.clear();for(let n of e)n.abort.abort();await Promise.allSettled(e.map(n=>n.finished))}async _run(e,n,r,o){let s=[],i=null,a=Promise.resolve(),l=this.bot!==void 0&&this.messageHandler!==void 0?wa(ya(this.messageHandler,this.bot,e,{ledgerOriginated:!0}),ba(this.bot,new Set([e]),(...d)=>this.log("[elicitation]",...d))):void 0,c=()=>{if(i=null,s.length===0)return;let d=s.join(`