agent-afk 5.69.0 → 5.70.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/config/types.d.ts +2 -0
- package/dist/cli.mjs +5 -5
- package/dist/config/env.d.ts +1 -0
- package/dist/index.mjs +116 -116
- package/dist/telegram/bot.d.ts +1 -0
- package/dist/telegram/handlers/message.d.ts +4 -1
- package/dist/telegram.mjs +220 -220
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var SG=Object.defineProperty;var x=(e,t)=>()=>(e&&(t=e(e=0)),t);var Tu=(e,t)=>{for(var n in t)SG(e,n,{get:t[n],enumerable:!0})};function ft(){let e=v.AFK_PLAIN_OUTPUT;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"}function Eu(e){return Wl.find(t=>t.name===e)}function Fx(e){return Wl.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function rb(e){return process.env[e]!==void 0}var Wl,v,K=x(()=>{"use strict";Wl=[{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_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-4-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 runs unbounded, 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_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-4-8",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_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_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 1 to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"1",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_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Opt-in to loading + spawning MCP servers declared in <cwd>/.mcp.json. Fail-closed: when unset (or 0), project-local servers are NOT spawned; set to a truthy value (1/true/yes/on) to load them. A project-local .mcp.json spawns arbitrary commands on session start, so it is off by default to prevent code execution when entering an untrusted repo (issue #571). Skipped servers are listed in a startup warning with the opt-in instruction.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BG_AUTO_DELIVER",description:"Auto-deliver background subagent results into the model context on the next user turn (interactive REPL). On by default. Set to 0, false, off, or no (case-insensitive) to disable, restoring the manual /bgsub:join retrieval flow.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_PLAIN_OUTPUT",description:"Force the interactive REPL to fully behave like a non-TTY surface for rendering purposes, even when stdout/stdin ARE a TTY: append-only plain-stdout output instead of the TerminalCompositor live overlay (both the persistent between-turn compositor AND the per-turn StreamRenderer overlay), AND the input surface downgrades to the simple non-TTY line reader instead of the fancy compositor-backed input box. Same code path already used for non-TTY surfaces (pipes, CI). Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM scroll regions misbehave \u2014 trades the live overlay and fancy input UX for reliability. Opt-in \u2014 default TTY behavior (live overlay + fancy input) is unchanged unless this var is set. Truthy values: 1, true (case-insensitive).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_GOBLIN_SPINNER",description:"Goblin-themed working spinner (olive frames + goblin verbs) while the agent runs tools. 1 = on (default), 0 = classic dim spinner.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_TERM_TITLE",description:'Set the terminal/tab title (OSC 2) to reflect afk state \u2014 "afk \u2014 <cwd> \xB7 running" during a turn, "afk \u2014 <cwd>" when idle, cleared on exit. 1 = on (default when stdout is a TTY), 0 = leave the title alone. TTY-only.',type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_NOTIFY",description:"Emit a desktop completion notification (OSC 9) on turn completion, for terminals that map OSC 9 to system notifications (iTerm2, kitty, WezTerm). Opt-in and off by default (intrusive). 1 = on. TTY-only.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_THEME",description:"TUI color palette for the interactive REPL and all CLI rendering: dark | light | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark. Overridden per-launch by --theme and mutable mid-session via /theme. Precedence: --theme flag > this env > config theme > auto-detect > dark. Invalid values are ignored (dark).",type:"string",required:!1,default:"dark",example:"light",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"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 for daemon and subagent surfaces and headed for repl/interactive \u2014 so an operator can watch the agent work in REPL mode.",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. Built-in credential entries (~/.ssh, ~/.aws, ~/.afk/config, \u2026) always apply on top and cannot be removed.",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_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"VISUAL",description:"Standard POSIX env var naming the user's preferred full-screen editor (with optional flags). Consulted FIRST by the /editor slash command (and its key chord) to compose a long prompt externally; takes precedence over EDITOR. No fallback editor is assumed \u2014 if neither VISUAL nor EDITOR is set, /editor prints a hint instead of guessing.",type:"string",required:!1,example:"nvim",category:"process"},{name:"EDITOR",description:"Standard POSIX env var naming the user's preferred editor (with optional flags). Consulted by the /editor slash command AFTER VISUAL, as the standard fallback. No default editor is assumed when both are unset \u2014 /editor prints a hint telling the user to set one.",type:"string",required:!1,example:"vim",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],v={get AFK_COMPACT_KEEP_LAST_TURNS(){return process.env.AFK_COMPACT_KEEP_LAST_TURNS},get AFK_COMPACT_MODEL(){return process.env.AFK_COMPACT_MODEL},get AFK_COMPACT_SHRINK_FRACTION(){return process.env.AFK_COMPACT_SHRINK_FRACTION},get AFK_COMPANION_PRIMER(){return process.env.AFK_COMPANION_PRIMER},get AFK_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_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_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_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_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_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BG_AUTO_DELIVER(){return process.env.AFK_BG_AUTO_DELIVER},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_PLAIN_OUTPUT(){return process.env.AFK_PLAIN_OUTPUT},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},get AFK_GOBLIN_SPINNER(){return process.env.AFK_GOBLIN_SPINNER},get AFK_TERM_TITLE(){return process.env.AFK_TERM_TITLE},get AFK_NOTIFY(){return process.env.AFK_NOTIFY},get AFK_SHOW_DIFFS(){return process.env.AFK_SHOW_DIFFS},get AFK_SKILL_STREAM_VERBOSE(){return process.env.AFK_SKILL_STREAM_VERBOSE},get FORCE_COLOR(){return process.env.FORCE_COLOR},get NO_COLOR(){return process.env.NO_COLOR},get AFK_THEME(){return process.env.AFK_THEME},get COLORFGBG(){return process.env.COLORFGBG},get AFK_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get 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_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 t of Wl){if(!t.secret)continue;let n=Object.getOwnPropertyDescriptor(v,t.name);n&&Object.defineProperty(v,t.name,{...n,enumerable:!1})}})()});import{existsSync as Lx,mkdirSync as vG,renameSync as kG,cpSync as TG,rmSync as EG}from"fs";import{join as ee,dirname as ob,basename as xG,isAbsolute as Ux}from"path";import{homedir as ib}from"os";import{fileURLToPath as RG}from"url";function Ae(){let e=v.AFK_HOME;if(e!==void 0&&e!==""){if(!Ux(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return ee(ib(),".afk")}function At(){return ee(Ae(),"agent-framework")}function Fn(){return ee(At(),"forge-telemetry.jsonl")}function jx(){return ee(At(),"routing-decisions.jsonl")}function Hx(){return ee(At(),"briefs")}function Wx(){return ee(At(),"facets")}function Kl(){return ee(Ae(),"skills")}function Ue(){return ee(Ae(),"plugins")}function Kx(e=process.cwd()){return ee(e,".afk")}function xu(e=process.cwd()){return ee(Kx(e),"skills")}function Ru(e=process.cwd()){return ee(Kx(e),"plugins")}function Cu(e=process.cwd()){return ee(e,".afk","plans")}function fe(){return ee(Ue(),".index.json")}function sb(){return ee(bn(),"schedules.json")}function br(){return ee(Ue(),"cache")}function Gl(e){return ee(br(),e)}function ps(){let e=RG(import.meta.url),t=ob(e);return ee(t,"bundled-plugins")}function bn(){return ee(Ae(),"config")}function we(){let e=v.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!Ux(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return ee(Ae(),"state")}function ms(){return ee(Ae(),"cache")}function qr(){return ee(Ae(),"logs")}function ct(){return ee(we(),"sessions")}function Au(){return ee(we(),"presence")}function ab(){return ee(we(),"todos")}function ql(){return ee(we(),"transcripts")}function _u(){return ee(we(),"memory")}function gt(){return ee(we(),"queue")}function Iu(){return ee(we(),"session-grants.jsonl")}function zl(){return ee(bn(),"permissions.json")}function Gx(){return ee(Ae(),"farms")}function lb(e){return ee(Gx(),e)}function Pu(e){if(!CG.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function Vo(e){return Pu(e),ee(we(),"witness",e)}function qx(e){return!e||e.startsWith("in-memory:")?null:xG(ob(e))}function cb(){return ee(we(),"receipts")}function Mu(e="default"){return ee(we(),"daemon",`agent-afk@${e}`)}function zx(){return ee(we(),"worktree-sweep.lock")}function St(){return ee(bn(),"afk.env")}function Nt(){return ee(bn(),"afk.config.json")}function db(){return ee(bn(),"settings.json")}function Jx(e=process.cwd()){return ee(e,".afk","settings.json")}function Yx(){return ee(ib(),".afk.env")}function Ou(){return ee(ib(),".afk.config.json")}function AG(){return ee(Ae(),"sessions")}function _G(){return ee(Ae(),"todos")}function IG(){return ee(Ae(),"transcripts")}function ub(e,t){if(e!==t&&Lx(e)&&!Lx(t))try{vG(ob(t),{recursive:!0});try{kG(e,t)}catch(n){if(n.code==="EXDEV")try{TG(e,t,{recursive:!0}),EG(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
|
|
2
|
+
var SG=Object.defineProperty;var x=(e,t)=>()=>(e&&(t=e(e=0)),t);var Tu=(e,t)=>{for(var n in t)SG(e,n,{get:t[n],enumerable:!0})};function ft(){let e=v.AFK_PLAIN_OUTPUT;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"}function Eu(e){return Wl.find(t=>t.name===e)}function Fx(e){return Wl.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function rb(e){return process.env[e]!==void 0}var Wl,v,K=x(()=>{"use strict";Wl=[{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_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-4-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 runs unbounded, 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_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-4-8",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_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 1 to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"1",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_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Opt-in to loading + spawning MCP servers declared in <cwd>/.mcp.json. Fail-closed: when unset (or 0), project-local servers are NOT spawned; set to a truthy value (1/true/yes/on) to load them. A project-local .mcp.json spawns arbitrary commands on session start, so it is off by default to prevent code execution when entering an untrusted repo (issue #571). Skipped servers are listed in a startup warning with the opt-in instruction.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BG_AUTO_DELIVER",description:"Auto-deliver background subagent results into the model context on the next user turn (interactive REPL). On by default. Set to 0, false, off, or no (case-insensitive) to disable, restoring the manual /bgsub:join retrieval flow.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_PLAIN_OUTPUT",description:"Force the interactive REPL to fully behave like a non-TTY surface for rendering purposes, even when stdout/stdin ARE a TTY: append-only plain-stdout output instead of the TerminalCompositor live overlay (both the persistent between-turn compositor AND the per-turn StreamRenderer overlay), AND the input surface downgrades to the simple non-TTY line reader instead of the fancy compositor-backed input box. Same code path already used for non-TTY surfaces (pipes, CI). Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM scroll regions misbehave \u2014 trades the live overlay and fancy input UX for reliability. Opt-in \u2014 default TTY behavior (live overlay + fancy input) is unchanged unless this var is set. Truthy values: 1, true (case-insensitive).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_GOBLIN_SPINNER",description:"Goblin-themed working spinner (olive frames + goblin verbs) while the agent runs tools. 1 = on (default), 0 = classic dim spinner.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_TERM_TITLE",description:'Set the terminal/tab title (OSC 2) to reflect afk state \u2014 "afk \u2014 <cwd> \xB7 running" during a turn, "afk \u2014 <cwd>" when idle, cleared on exit. 1 = on (default when stdout is a TTY), 0 = leave the title alone. TTY-only.',type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_NOTIFY",description:"Emit a desktop completion notification (OSC 9) on turn completion, for terminals that map OSC 9 to system notifications (iTerm2, kitty, WezTerm). Opt-in and off by default (intrusive). 1 = on. TTY-only.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_THEME",description:"TUI color palette for the interactive REPL and all CLI rendering: dark | light | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark. Overridden per-launch by --theme and mutable mid-session via /theme. Precedence: --theme flag > this env > config theme > auto-detect > dark. Invalid values are ignored (dark).",type:"string",required:!1,default:"dark",example:"light",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"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 for daemon and subagent surfaces and headed for repl/interactive \u2014 so an operator can watch the agent work in REPL mode.",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. Built-in credential entries (~/.ssh, ~/.aws, ~/.afk/config, \u2026) always apply on top and cannot be removed.",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_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"VISUAL",description:"Standard POSIX env var naming the user's preferred full-screen editor (with optional flags). Consulted FIRST by the /editor slash command (and its key chord) to compose a long prompt externally; takes precedence over EDITOR. No fallback editor is assumed \u2014 if neither VISUAL nor EDITOR is set, /editor prints a hint instead of guessing.",type:"string",required:!1,example:"nvim",category:"process"},{name:"EDITOR",description:"Standard POSIX env var naming the user's preferred editor (with optional flags). Consulted by the /editor slash command AFTER VISUAL, as the standard fallback. No default editor is assumed when both are unset \u2014 /editor prints a hint telling the user to set one.",type:"string",required:!1,example:"vim",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],v={get AFK_COMPACT_KEEP_LAST_TURNS(){return process.env.AFK_COMPACT_KEEP_LAST_TURNS},get AFK_COMPACT_MODEL(){return process.env.AFK_COMPACT_MODEL},get AFK_COMPACT_SHRINK_FRACTION(){return process.env.AFK_COMPACT_SHRINK_FRACTION},get AFK_COMPANION_PRIMER(){return process.env.AFK_COMPANION_PRIMER},get AFK_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_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_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_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_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BG_AUTO_DELIVER(){return process.env.AFK_BG_AUTO_DELIVER},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_PLAIN_OUTPUT(){return process.env.AFK_PLAIN_OUTPUT},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},get AFK_GOBLIN_SPINNER(){return process.env.AFK_GOBLIN_SPINNER},get AFK_TERM_TITLE(){return process.env.AFK_TERM_TITLE},get AFK_NOTIFY(){return process.env.AFK_NOTIFY},get AFK_SHOW_DIFFS(){return process.env.AFK_SHOW_DIFFS},get AFK_SKILL_STREAM_VERBOSE(){return process.env.AFK_SKILL_STREAM_VERBOSE},get FORCE_COLOR(){return process.env.FORCE_COLOR},get NO_COLOR(){return process.env.NO_COLOR},get AFK_THEME(){return process.env.AFK_THEME},get COLORFGBG(){return process.env.COLORFGBG},get AFK_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get 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_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 t of Wl){if(!t.secret)continue;let n=Object.getOwnPropertyDescriptor(v,t.name);n&&Object.defineProperty(v,t.name,{...n,enumerable:!1})}})()});import{existsSync as Lx,mkdirSync as vG,renameSync as kG,cpSync as TG,rmSync as EG}from"fs";import{join as ee,dirname as ob,basename as xG,isAbsolute as Ux}from"path";import{homedir as ib}from"os";import{fileURLToPath as RG}from"url";function Ae(){let e=v.AFK_HOME;if(e!==void 0&&e!==""){if(!Ux(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return ee(ib(),".afk")}function At(){return ee(Ae(),"agent-framework")}function Fn(){return ee(At(),"forge-telemetry.jsonl")}function jx(){return ee(At(),"routing-decisions.jsonl")}function Hx(){return ee(At(),"briefs")}function Wx(){return ee(At(),"facets")}function Kl(){return ee(Ae(),"skills")}function Ue(){return ee(Ae(),"plugins")}function Kx(e=process.cwd()){return ee(e,".afk")}function xu(e=process.cwd()){return ee(Kx(e),"skills")}function Ru(e=process.cwd()){return ee(Kx(e),"plugins")}function Cu(e=process.cwd()){return ee(e,".afk","plans")}function fe(){return ee(Ue(),".index.json")}function sb(){return ee(bn(),"schedules.json")}function br(){return ee(Ue(),"cache")}function Gl(e){return ee(br(),e)}function ps(){let e=RG(import.meta.url),t=ob(e);return ee(t,"bundled-plugins")}function bn(){return ee(Ae(),"config")}function we(){let e=v.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!Ux(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return ee(Ae(),"state")}function ms(){return ee(Ae(),"cache")}function qr(){return ee(Ae(),"logs")}function ct(){return ee(we(),"sessions")}function Au(){return ee(we(),"presence")}function ab(){return ee(we(),"todos")}function ql(){return ee(we(),"transcripts")}function _u(){return ee(we(),"memory")}function gt(){return ee(we(),"queue")}function Iu(){return ee(we(),"session-grants.jsonl")}function zl(){return ee(bn(),"permissions.json")}function Gx(){return ee(Ae(),"farms")}function lb(e){return ee(Gx(),e)}function Pu(e){if(!CG.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function Vo(e){return Pu(e),ee(we(),"witness",e)}function qx(e){return!e||e.startsWith("in-memory:")?null:xG(ob(e))}function cb(){return ee(we(),"receipts")}function Mu(e="default"){return ee(we(),"daemon",`agent-afk@${e}`)}function zx(){return ee(we(),"worktree-sweep.lock")}function St(){return ee(bn(),"afk.env")}function Nt(){return ee(bn(),"afk.config.json")}function db(){return ee(bn(),"settings.json")}function Jx(e=process.cwd()){return ee(e,".afk","settings.json")}function Yx(){return ee(ib(),".afk.env")}function Ou(){return ee(ib(),".afk.config.json")}function AG(){return ee(Ae(),"sessions")}function _G(){return ee(Ae(),"todos")}function IG(){return ee(Ae(),"transcripts")}function ub(e,t){if(e!==t&&Lx(e)&&!Lx(t))try{vG(ob(t),{recursive:!0});try{kG(e,t)}catch(n){if(n.code==="EXDEV")try{TG(e,t,{recursive:!0}),EG(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
|
|
3
3
|
`)}}}catch{}}function Vx(){ub(AG(),ct())}function Xx(){ub(_G(),ab())}function Qx(){ub(IG(),ql())}function pb(){return ee(we(),"repl-history.jsonl")}function MG(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(e.length>Nx)throw new Error(`Invalid jobId: exceeds ${Nx} chars`);if(!PG.test(e))throw new Error(`Invalid jobId: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function Jl(){return ee(we(),"bg")}function Xo(e){return MG(e),ee(Jl(),e)}function $u(e){return ee(Xo(e),"events.jsonl")}function mb(e){return ee(Xo(e),"meta.json")}function Yl(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(e.length>Bx)throw new Error(`Invalid browser profile: exceeds ${Bx} chars`);if(!OG.test(e))throw new Error(`Invalid browser profile: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function fb(){return ee(we(),"browser")}function gb(e){return Yl(e),ee(fb(),e)}function Vl(e){return ee(gb(e),"storageState.json")}function Xl(e){return typeof e=="string"&&e.length>0&&e.length<=DG&&$G.test(e)}function Ql(e){if(!Xl(e))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(e)}`);return ee(ct(),e)}function Du(e){return ee(Ql(e),"events.jsonl")}function hb(e){return ee(Ql(e),"session.key")}function Zl(){return ee(we(),"mcp","server-status.json")}var CG,PG,Nx,OG,Bx,$G,DG,G=x(()=>{"use strict";K();CG=/^[a-zA-Z0-9_-]+$/;PG=/^[A-Za-z0-9_-]+$/,Nx=128;OG=/^[A-Za-z0-9_-]+$/,Bx=128;$G=/^[A-Za-z0-9_-]+$/,DG=128});import{randomBytes as FG}from"node:crypto";import{mkdirSync as LG,renameSync as NG,rmSync as Zx,writeFileSync as BG}from"node:fs";import{dirname as UG,isAbsolute as jG,join as HG}from"node:path";function Fu(){return HG(we(),"last-cwd")}function eR(){try{Zx(Fu(),{force:!0})}catch{}}function tR(e){if(!jG(e))throw new Error(`recordCdIntent: target must be an absolute path, got ${JSON.stringify(e)}`);if(/[\n\r\0]/.test(e))throw new Error(`recordCdIntent: target must not contain newline/CR/NUL, got ${JSON.stringify(e)}`);try{let t=Fu();LG(UG(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${FG(6).toString("hex")}`;try{BG(n,e,{encoding:"utf8",mode:384}),NG(n,t)}catch(r){try{Zx(n,{force:!0})}catch{}throw r}}catch{}}function nR(){let e=v.AFK_SHELL_WRAPPER;return e==="1"||e==="true"}var Lu=x(()=>{"use strict";K();G()});var dt,ht,Uu,ge,Yr,Vr,gs,ju,Le=x(()=>{"use strict";dt=class extends Error{constructor(t){super(t),this.name="AbortError"}},ht=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Uu=class extends ht{constructor(t,n){super(t,n),this.name="IdleWatchdogError"}},ge=class extends Error{constructor(n,r,o,i){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",i?.cause!==void 0&&(this.cause=i.cause)}event;reason;cause},Yr=class extends Error{constructor(t){super(t),this.name="StreamIncompleteError"}},Vr=class extends Error{constructor(n,r,o){super(o??`Budget ceiling reached: $${n.toFixed(4)} cumulative >= $${r.toFixed(4)} limit`);this.runningCostUsd=n;this.maxBudgetUsd=r;this.name="BudgetExceededError"}runningCostUsd;maxBudgetUsd},gs=class extends Error{constructor(t){super(t),this.name="DenialCircuitBreakerError"}},ju=class extends Error{constructor(n,r,o){super(o??`${n} provider does not support AgentConfig.${r}.`);this.provider=n;this.field=r;this.name="UnsupportedProviderConfigError"}provider;field}});function He(){return v.AFK_DEBUG==="1"||v.DEBUG==="1"}function W(...e){He()&&console.log(...e)}var he=x(()=>{"use strict";K()});async function Ts(e,t){if(e)try{await e.write({kind:"tool_call",payload:t})}catch(n){W(`trace.emit tool_call failed: ${Nn(n)}`)}}async function en(e,t){if(e)try{await e.write({kind:"hook_decision",payload:t})}catch(n){W(`trace.emit hook_decision failed: ${Nn(n)}`)}}async function ei(e,t){if(e)try{await e.write({kind:"subagent_lifecycle",payload:t})}catch(n){W(`trace.emit subagent_lifecycle failed: ${Nn(n)}`)}}async function ti(e,t){if(e)try{await e.write({kind:"background_agent",payload:t})}catch(n){W(`trace.emit background_agent failed: ${Nn(n)}`)}}async function MR(e,t){if(e)try{await e.write({kind:"budget",payload:t})}catch(n){W(`trace.emit budget failed: ${Nn(n)}`)}}async function OR(e,t){if(e)try{await e.write({kind:"abort",payload:t})}catch(n){W(`trace.emit abort failed: ${Nn(n)}`)}}async function Yu(e,t){if(e)try{await e.write({kind:"compaction",payload:t})}catch(n){W(`trace.emit compaction failed: ${Nn(n)}`)}}async function $R(e,t){if(e)try{await e.write({kind:"closure",payload:t})}catch(n){W(`trace.emit closure failed: ${Nn(n)}`)}}async function rt(e,t){if(e)try{await e.write({kind:"browser_event",payload:t})}catch(n){W(`trace.emit browser_event failed: ${Nn(n)}`)}}async function ae(e,t){if(e)try{await e.write({kind:"session_phase",payload:t})}catch(n){W(`trace.emit session_phase failed: ${Nn(n)}`)}}function Nn(e){return e instanceof Error?e.message:String(e)}var xe=x(()=>{"use strict";he()});function Vu(e){return e.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function tc(e,t,n,r){let o=t==="oauth"?{authToken:e}:{apiKey:e},i=typeof n=="string"&&n.length>0?{...o,baseURL:n}:o;return r?{...i,fetch:r}:i}function wn(e,t,n,r){return e!=="oauth"?{}:{"anthropic-beta":r?`${DR},${$2}`:DR,"x-app":"cli","User-Agent":D2,"X-Claude-Code-Session-Id":t,"x-client-request-id":n}}function FR(e){return e!=="oauth"?null:[{type:"text",text:F2}]}var DR,$2,D2,F2,Es=x(()=>{"use strict";DR="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",$2="effort-2025-11-24",D2="claude-cli/1.0.0 (external, cli)",F2="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;"});function Qu(e){Ob=e}function Ib(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}function Xu(e,t,n){let r={},o=Ib(e);o&&(r.id=o);let i=Ib(t);i&&(r.baseUrl=i);let s=Ib(n);return s&&(r.apiKey=s),r}function L2(){return{local:Xu(v.AFK_MODEL_LOCAL,v.AFK_MODEL_LOCAL_BASE_URL,v.AFK_MODEL_LOCAL_API_KEY),small:Xu(v.AFK_MODEL_SMALL,v.AFK_MODEL_SMALL_BASE_URL,v.AFK_MODEL_SMALL_API_KEY),medium:Xu(v.AFK_MODEL_MEDIUM,v.AFK_MODEL_MEDIUM_BASE_URL,v.AFK_MODEL_MEDIUM_API_KEY),large:Xu(v.AFK_MODEL_LARGE,v.AFK_MODEL_LARGE_BASE_URL,v.AFK_MODEL_LARGE_API_KEY)}}function Fb(e){let t=L2(),n={};for(let r of nc){let o=ni[r],i=e?.[r],s=t[r],a={id:s.id??i?.id??o.id},l=i?.name;l&&(a.name=l);let c=i?.provider;c&&(a.provider=c);let d=s.baseUrl??i?.baseUrl;d&&(a.baseUrl=d);let u=s.apiKey??i?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function Rs(e){return e||Ob||Fb()}function Cs(e,t=Rs()){let n=e.trim().toLowerCase();if(!(!n||n===BR)){for(let r of nc){let o=t[r].name;if(o&&o.trim().toLowerCase()===n)return r}if(n==="local"||n==="small"||n==="medium"||n==="large")return n}}function ri(e,t=Rs()){if(e===void 0)return{id:""};let n=Cs(e,t);if(n)return t[n];let r=Db[e.trim().toLowerCase()];return r?{id:r}:{id:e}}function to(e,t=Rs()){if(e!==void 0)return ri(e,t).id}function As(e,t=Rs()){if(e===void 0)return;let n=Cs(e,t);if(n&&t[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function UR(e){let t={};if(!e||typeof e!="object")return t;let n=e;for(let r of nc){let o=B2(n[r]);o&&(t[r]=o)}return t}function jR(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();if(t==="anthropic"||t==="anthropic-direct")return"anthropic";if(t==="openai"||t==="openai-compatible")return"openai";if(t==="chatgpt-oauth"||t==="chatgpt")return"chatgpt-oauth"}function xs(e){return typeof e=="string"?e.trim():""}function LR(e){return/[\x00-\x1f\x7f]/.test(e)}function B2(e){if(typeof e=="string"){let t=e.trim();return t?{id:t}:void 0}if(e&&typeof e=="object"){let t=e,n=xs(t.id);if(!n)return;let r={id:n},o=xs(t.name);o&&(r.name=o);let i=jR(t.provider);i&&(r.provider=i);let s=xs(t.baseUrl);s&&(r.baseUrl=s);let a=xs(t.apiKey);return a&&(r.apiKey=a),r}}function HR(e){if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:'model binding must be an object with at least an "id"'};let t=e;if("apiKey"in t||"api_key"in t)return{ok:!1,error:"per-slot API keys are credentials; set AFK_MODEL_<TIER>_API_KEY via `afk config env set` instead of afk.config.json"};if("baseUrl"in t||"base_url"in t)return{ok:!1,error:"per-slot baseUrl is an endpoint-redirect credential vector; set AFK_MODEL_<TIER>_BASE_URL via `afk config env set` instead of afk.config.json"};let n=xs(t.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(LR(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=xs(t.name);if(o){if(LR(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(N2.has(o.trim().toLowerCase()))return{ok:!1,error:`model binding "name" must not shadow a built-in alias ("${o}")`};r.name=o}if(t.provider!==void 0&&t.provider!==""){let i=jR(t.provider);if(!i)return{ok:!1,error:'model binding "provider" must be one of: anthropic, openai (aliases: anthropic-direct, openai-compatible)'};r.provider=i}return{ok:!0,value:r}}var nc,NR,Pb,Mb,$b,ni,BR,Db,rc,Ob,N2,_t=x(()=>{"use strict";K();nc=["local","small","medium","large"],NR="claude-haiku-4-5-20251001",Pb="claude-sonnet-5",Mb="claude-opus-4-8",$b="claude-fable-5",ni={local:{id:""},small:{id:NR},medium:{id:Pb},large:{id:Mb}},BR="auto",Db={opus:Mb,opus_1m:Mb,sonnet:Pb,sonnet_1m:Pb,haiku:NR,fable:$b},rc=[...nc,...Object.keys(Db)];N2=new Set([...nc,BR,...Object.keys(Db)])});function oc(e){return e in Lb}function vt(e){return to(e)}var Lb,Sn=x(()=>{"use strict";_t();Lb={opus:ni.large.id,opus_1m:ni.large.id,sonnet:ni.medium.id,sonnet_1m:ni.medium.id,haiku:ni.small.id,fable:$b}});import U2 from"@anthropic-ai/sdk";import{randomUUID as WR}from"node:crypto";async function _s(e){let{token:t,model:n,system:r,user:o,maxTokens:i=64,signal:s,clientFactory:a}=e;if(!t)throw new Error("oneShotCompletion: token required");let l=Vu(t),c=tc(t,l),d=a?a(c):new U2(c),u=WR(),m=WR(),f=wn(l,u,m),g=vt(n)??n,h={};Object.keys(f).length>0&&(h.headers=f),s&&(h.signal=s);let y=await d.messages.create({model:g,max_tokens:i,system:r,messages:[{role:"user",content:o}]},Object.keys(h).length>0?h:void 0),b=[];for(let S of y.content)S.type==="text"&&b.push(S.text);let w=b.join("").trim();return w.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),w}var Zu=x(()=>{"use strict";Es();Sn()});import{execFileSync as KR}from"child_process";import{existsSync as j2,readFileSync as H2,writeFileSync as W2}from"fs";import{homedir as GR,userInfo as qR}from"os";import{join as zR}from"path";function kt(){let e=JR();if(e===void 0)return;let t=YR(e);if(t!==void 0){if(t.expiresAt!==void 0&&t.expiresAt<=Date.now()){process.stderr.write("agent-afk: Claude Code OAuth token in keychain is expired. Run `claude login` to refresh.\n");return}return t.accessToken}}async function Nb(){let e=JR();if(e===void 0)return;let t=YR(e);if(t===void 0)return;if(t.expiresAt!==void 0&&t.expiresAt>Date.now()+q2)return t.accessToken;if(!t.refreshToken){process.stderr.write("agent-afk: OAuth token expired and no refresh token available. Run `claude login` to refresh.\n");return}let n=await z2(t.refreshToken);if(!n){process.stderr.write("agent-afk: OAuth token refresh failed. Run `claude login` to refresh.\n");return}try{let r={};try{r=JSON.parse(e)}catch{}let o=r.claudeAiOauth??{};r.claudeAiOauth={...o,accessToken:n.accessToken,expiresAt:n.expiresAt,...n.refreshToken!==void 0?{refreshToken:n.refreshToken}:{}},J2(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
4
4
|
`)}return n.accessToken}function JR(){if(process.platform==="darwin")try{return KR("security",["find-generic-password","-s","Claude Code-credentials","-a",qR().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let e=zR(GR(),".claude",".credentials.json");if(!j2(e))return;try{return H2(e,"utf-8")}catch{return}}}function YR(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null)return;let n=t.claudeAiOauth;if(typeof n!="object"||n===null)return;let r=n,o=r.accessToken;if(typeof o!="string"||o.length===0)return;let i={accessToken:o},s=r.refreshToken;typeof s=="string"&&s.length>0&&(i.refreshToken=s);let a=r.expiresAt;return typeof a=="number"&&(i.expiresAt=a),i}async function z2(e){try{let t=await fetch(G2,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:K2})});if(!t.ok)return;let n=await t.json(),r=n.access_token,o=n.expires_in;if(typeof r!="string"||typeof o!="number")return;let i=n.refresh_token;return{accessToken:r,expiresAt:Date.now()+o*1e3,...typeof i=="string"&&i.length>0?{refreshToken:i}:{}}}catch{return}}function no(e){if(!e||e.length<3)return"token:(unknown)";try{let n=e.split(".");if(n.length<2)throw new Error("not a JWT");let r=Buffer.from(n[1],"base64url").toString("utf-8"),o=JSON.parse(r),i=typeof o.email=="string"&&o.email||typeof o.sub=="string"&&o.sub||typeof o.account_id=="string"&&o.account_id||typeof o.preferred_username=="string"&&o.preferred_username;if(i)return i}catch{}return`token:${e.length>=8?e.slice(-8):e}`}function J2(e){if(process.platform==="darwin")KR("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",qR().username,"-w",e],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let t=zR(GR(),".claude",".credentials.json");Y2(t,e)}}function Y2(e,t){W2(e,t,{encoding:"utf-8",mode:384})}var K2,G2,q2,Is=x(()=>{"use strict";K2="9d1c250a-e61b-44d9-88ed-5944d1962f5e",G2="https://platform.claude.com/v1/oauth/token",q2=300*1e3});function yt(e,t){if(e===null||typeof e!="object")return;let n=e.headers;if(n==null)return;if(typeof n.get=="function")return n.get(t)??void 0;if(typeof n=="object"){let o=n,i=o[t]??o[t.toUpperCase()];return typeof i=="string"?i:void 0}}function oi(e){let t=yt(e,"retry-after-ms");if(t!==void 0){let r=Number(t);if(Number.isFinite(r)&&r>=0)return r}let n=yt(e,"retry-after");if(n!==void 0){let r=Number(n);if(Number.isFinite(r)&&r>=0)return Math.round(r*1e3);let o=Date.parse(n);if(!Number.isNaN(o)){let i=o-Date.now();if(i>=0)return i}}}var Bb=x(()=>{"use strict"});function VR(e){if(!Number.isFinite(e)||e<=0)return;let t=e*1e3;if(!(t>X2))return new Date(t)}function Ub(e){if(!("status"in e))return null;let t=e.status;if(t===429){let n=e.message.split("|");if(n.length>=2){let l=VR(parseInt(n[1].trim(),10));if(l!==void 0)return{kind:"oauth-limit",resetsAt:l}}let r=yt(e,"anthropic-ratelimit-unified-representative-claim"),o=yt(e,"anthropic-ratelimit-unified-overage-status"),i=yt(e,"anthropic-ratelimit-unified-status");if(r!==void 0||o!==void 0||i==="rejected"){let l=yt(e,"anthropic-ratelimit-unified-reset");if(l!==void 0){let c=VR(Number(l));if(c!==void 0)return{kind:"oauth-limit",resetsAt:c}}return{kind:"oauth-limit-no-ts"}}if(yt(e,"anthropic-ratelimit-requests-remaining")!==void 0||yt(e,"anthropic-ratelimit-requests-limit")!==void 0||yt(e,"anthropic-ratelimit-requests-reset")!==void 0||yt(e,"anthropic-ratelimit-input-tokens-remaining")!==void 0||yt(e,"anthropic-ratelimit-input-tokens-limit")!==void 0||yt(e,"anthropic-ratelimit-input-tokens-reset")!==void 0||yt(e,"anthropic-ratelimit-output-tokens-remaining")!==void 0||yt(e,"anthropic-ratelimit-output-tokens-limit")!==void 0||yt(e,"anthropic-ratelimit-output-tokens-reset")!==void 0)return{kind:"rate-limit-transient",retryAfterMs:oi(e)};let a=oi(e);return a!==void 0&&a<=V2?{kind:"rate-limit-transient",retryAfterMs:a}:{kind:"oauth-limit-no-ts"}}return t===400&&e.message.includes("invalid_request_error")&&e.message.includes("credit balance")?{kind:"credit-exhausted"}:null}async function XR(e){let{resetsAt:t,signal:n,readToken:r=kt}=e,o=r(),i=t.getTime()+3e4;return new Promise(s=>{let a,l=!1,c=m=>{l||(l=!0,a!==void 0&&clearInterval(a),n.removeEventListener("abort",d),s(m))},d=()=>{c("aborted")},u=()=>n.aborted?(c("aborted"),!0):Date.now()>=i?(c("timer"),!0):r()!==o?(c("hot-swap"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),n.addEventListener("abort",d,{once:!0}))})}async function QR(e){let{signal:t,readToken:n=kt,retryAfterMs:r}=e,o=n(),i=r!==void 0?Date.now()+r:void 0;return new Promise(s=>{let a,l=!1,c=m=>{l||(l=!0,a!==void 0&&clearInterval(a),t.removeEventListener("abort",d),s(m))},d=()=>{c("aborted")},u=()=>t.aborted?(c("aborted"),!0):n()!==o?(c("hot-swap"),!0):i!==void 0&&Date.now()>=i?(c("timer"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),t.addEventListener("abort",d,{once:!0}))})}var V2,X2,jb=x(()=>{"use strict";Is();Bb();V2=300*1e3,X2=864e13});function Hb(e,t=fetch,n){return!e&&!n?t:async(r,o)=>{let i=await t(r,o);if(Q2.has(i.status)){let s=oi({headers:i.headers});if(n)try{n({status:i.status,...s!==void 0?{retryAfterMs:s}:{}})}catch{}if(e){let a={status:i.status,reason:i.status===429?"rate-limit":"overloaded",source:"sdk-fetch"};s!==void 0&&(a.retryAfterMs=s),ae(e,{phase:"rate_limit",...s!==void 0?{durationMs:s}:{},metadata:a})}}return i}}var Q2,ZR=x(()=>{"use strict";xe();jb();Q2=new Set([429,503,529])});var ep,eC=x(()=>{"use strict";ep=class{items=[];waiter=null;attempts=0;push(t){this.attempts+=1;let n={status:t.status,attempt:this.attempts,...t.retryAfterMs!==void 0?{retryAfterMs:t.retryAfterMs}:{}};this.items.push(n);let r=this.waiter;this.waiter=null,r&&r()}takeAll(){return this.items.length===0?[]:this.items.splice(0,this.items.length)}waitForItem(){return this.items.length>0?Promise.resolve():new Promise(t=>{this.waiter=t})}resetAttempts(){this.attempts=0}}});function Bn(e){return e==="bypassPermissions"||e==="autonomous"}var ic=x(()=>{"use strict"});function tp(e){if(typeof e?.baseUrl=="string"&&e.baseUrl.length>0)return!1;let t=v.AFK_DISABLE_PROMPT_CACHE;if(t===void 0||t.length===0)return!0;let n=t.toLowerCase();return!(n==="1"||n==="true"||n==="yes"||n==="on")}function np(){let e=v.AFK_PROMPT_CACHE_TTL;return e==="5m"?"5m":e==="1h"?"1h":Z2}function tC(e,t){if(e.length===0)return e;let n=e[e.length-1],r=rC(n,t);return r===n?e:[...e.slice(0,-1),r]}function nC(e,t){if(e.length===0)return e;let n=e[e.length-1],r=eq(n,t);return r===n?e:[...e.slice(0,-1),r]}function eq(e,t){let n=e.content;if(typeof n=="string")return n.length===0?e:{...e,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:t}}]};if(!Array.isArray(n)||n.length===0)return e;let r=n[n.length-1],o=rC(r,t);return o===r?e:{...e,content:[...n.slice(0,-1),o]}}function rC(e,t){return e.type==="thinking"||e.type==="redacted_thinking"?e:{...e,cache_control:{type:"ephemeral",ttl:t}}}var Z2,Wb=x(()=>{"use strict";K();Z2="1h"});function Kb(e){return e!=="plan"?null:{type:"text",text:rp}}var rp,Gb=x(()=>{"use strict";rp=["## Plan mode is active","","File and memory write tools (`write_file`, `edit_file`, `memory_update`, `procedure_write`) are refused at the hook layer.","`bash` runs for read-only investigation (git status/log/diff, ls, cat, grep, find \u2014 chained or not); state-mutating bash (file writes, rm, installs, commits, pushes) is refused while planning. The user has asked you to plan, not yet to act \u2014 exit plan mode to make changes.","Treat this turn as planning work.","","Traverse the shape that matches the work \u2014 skip steps the terrain already covers, do not skip steps the terrain hides:",""," unknown field \u2192 ground the current terrain \u2192 gather missing codebase context \u2192"," research missing external context \u2192 reveal chaos / constraints / risks \u2192"," name the failure geometry \u2192 form a candidate plan \u2192 apply adversarial pressure \u2192 embody the final plan","","Reach for these skills (invoke via the `skill` tool) when the cost of skipping exceeds the cost of dispatching:"," - `ground-state` \u2014 survey git, infra, memory before non-trivial work"," - `gather` \u2014 parallel context-gathering for a code area"," - `research` \u2014 parallel external + local context for the current task"," - `devils-advocate` \u2014 generate alternatives and rank them before committing"," - `shadow-verify` \u2014 independently re-derive load-bearing claims","","Do not declare readiness silently. When the plan is ready, state: chosen approach, risks named, and alternatives considered.","","Then, IF the task requires implementation (writing code or files), call the `exit_plan_mode` tool to present your plan. The user picks how to proceed (approve and implement, or keep planning). After calling it, END YOUR TURN \u2014 on approval you will receive a separate instruction to save the plan to a file and implement it. Do NOT use `ask_question` to ask whether the plan is OK; that is exactly what `exit_plan_mode` does \u2014 use `ask_question` only to resolve open requirement questions first. For research / read-only tasks that need no code changes, do NOT call `exit_plan_mode` \u2014 just answer.","","Manual fallbacks remain: the user can exit with `/plan off` (same save-and-implement handoff), and Shift+Tab advances the permission-mode ring without saving or implementing. Keep the plan concrete and complete enough to act on directly."].join(`
|
|
5
5
|
`)});var oC=x(()=>{"use strict";Gb()});function qb(e){return e!=="autonomous"?null:{type:"text",text:op}}var op,zb=x(()=>{"use strict";op=["## AFK mode is active","","The operator is away from keyboard. Your channel to them is Telegram via the `send_telegram` tool \u2014 not this transcript, which no one is watching live. At the end of each turn, push your terminal state (Done / Blocked / Asking) to Telegram so the operator can review asynchronously.","","Posture \u2014 bounded autonomy, not unchecked action:"," - Proceed autonomously on reversible work. Do not stop to confirm actions you are already authorized to take and can undo (edits, reads, tests, local commits, non-force pushes, installs)."," - At a one-way door \u2014 anything irreversible, externally visible, credential- or payment-touching, or where multiple readings lead to materially different work \u2014 do NOT guess. Push a concise Asking summary to Telegram naming the decision and your recommended default, then stop and end the turn in the Asking state."," - A mechanical gate refuses high-risk and irreversible operations at the hook layer regardless of this text. Treat a gate refusal as a signal to surface the decision to the operator, not an obstacle to work around.","","Communication discipline:"," - Batch updates. Send a Telegram message at terminal state (and at a genuinely blocking fork), not a play-by-play \u2014 the operator gets a push notification for every message."," - Keep pushes short and scannable: what happened, what changed, what (if anything) you need. Never paste raw tool output, logs, secrets, or full file contents into a push.","","Exit: the operator returns and runs `/afk off` (or Shift+Tab) to restore default permissions and terminal-channel interaction."].join(`
|
|
@@ -70,7 +70,7 @@ end
|
|
|
70
70
|
`,await Zb.writeFile(t,i,"utf8")}function bq(e,t,n){if(!ro(e))return new Error(`git worktree add failed: ${String(e)}`);let r=e.stderr??"",o=e.message??"",i=`${r}
|
|
71
71
|
${o}`;return i.includes("already checked out")||i.includes("is already used by worktree")?new Error(`Branch '${t}' is already checked out in another worktree. Pick a different name.`):i.includes("already exists")?new Error(`Worktree path '${n}' already exists. Remove it or pick a different branch name.`):new Error(o||r||"git worktree add failed")}async function lp(e,t){let n=t?.execFile??gC,r=ap(t?.branchPrefix),o=await hC(n);return await yC(o),kC(o,e,{execFile:n,prefix:r,baseRef:t?.baseRef})}async function bC(e){let t=e?.execFile??gC,n=ap(e?.branchPrefix),r=await hC(t);await yC(r);let o=await wC(r,e?.baseRef,t),i;return{repoRoot:r,handle:()=>i,async create(s){return i===void 0&&(i=await kC(r,s,{execFile:t,prefix:n,preResolvedBase:o})),i}}}async function wC(e,t,n){let r=wq(t);if(r!==void 0)return nw(r,"worktree base ref"),await SC(e,r,n),{ref:r,sha:await vC(e,r,n)}}function nw(e,t){if(e.trim().length===0)throw new Error(`Invalid worktree base ref from ${t}: '' \u2014 base ref cannot be empty.`);if(e.startsWith("-"))throw new Error(`Invalid worktree base ref from ${t}: '${e}' \u2014 must not start with '-' (would be parsed by git as a flag).`);if(e.includes("\0"))throw new Error(`Invalid worktree base ref from ${t}: contains a NUL byte.`);if(/\s/.test(e))throw new Error(`Invalid worktree base ref from ${t}: '${e}' \u2014 must not contain whitespace.`)}function wq(e){let t=e??v.AFK_WORKTREE_BASE;if(!(t===void 0||t.length===0))return t}async function SC(e,t,n){let r=t.indexOf("/");if(r<=0)return;let o=t.slice(0,r),i;try{let{stdout:a}=await n("git",["-C",e,"remote"]);i=a.split(`
|
|
72
72
|
`).map(l=>l.trim()).filter(l=>l.length>0)}catch{return}if(!i.includes(o))return;let s=t.slice(r+1).replace(/[~^@:].*$/,"");if(s.length!==0)try{await n("git",["-C",e,"fetch","--no-tags",o,s])}catch(a){let l=ro(a)?a.message||a.stderr||"":String(a);console.warn(`Worktree base: could not fetch '${o}/${s}' (${l.trim()}). Using the local copy of '${t}', which may be stale.`)}}async function vC(e,t,n){try{let{stdout:r}=await n("git",["-C",e,"rev-parse","--verify",`${t}^{commit}`]),o=r.trim();if(o.length===0)throw new Error("empty rev-parse output");return o}catch(r){let o=ro(r)?r.message||r.stderr||"":String(r);throw new Error(`Cannot resolve worktree base ref '${t}': ${o.trim()} \u2014 check the ref exists (for a remote branch, make sure the remote is reachable so it can be fetched).`)}}async function Sq(e,t){try{let{stdout:n}=await t("git",["-C",e,"symbolic-ref","--short","--quiet","refs/remotes/origin/HEAD"]),r=n.trim();if(r.length>0)return r}catch{}for(let n of["origin/main","origin/master"])try{let{stdout:r}=await t("git",["-C",e,"rev-parse","--verify","--quiet",`${n}^{commit}`]);if(r.trim().length>0)return n}catch{}}async function vq(e,t,n){try{return await vC(e,t,n)}catch{return}}async function kC(e,t,n){let{execFile:r,prefix:o}=n,i=t===!0?hq(o):t;yq(i);let s=i.replaceAll("/","-"),a=ew(e,".afk-worktrees",s),l,c,d=n.preResolvedBase??await wC(e,n.baseRef,r);if(d!==void 0)c=d.sha,l=d.ref;else{let f=await Sq(e,r);if(f!==void 0){await SC(e,f,r);let g=await vq(e,f,r);g!==void 0&&(c=g,l=f)}}let u=["-C",e,"worktree","add","-b",i,a];c!==void 0&&u.push(c);try{await r("git",u)}catch(f){throw bq(f,i,a)}let m={path:a,branch:i,cleanup:async f=>{let g=m.path,h=m.branch;if(f?.force===!0){console.log(`Worktree removed (zero turns \u2014 no work done): ${g}`);try{await r("git",["-C",e,"worktree","remove","--force",g])}catch(b){let w=ro(b)?b.message||b.stderr||"":String(b);console.warn(`Worktree cleanup: 'git worktree remove --force ${g}' failed (${w}). Manual removal may be needed.`);return}try{await r("git",["-C",e,"branch","-d",h])}catch(b){let w=ro(b)?b.message||b.stderr||"":String(b);console.warn(`Could not delete branch '${h}': ${w}`)}return}let y;try{y=await r("git",["-C",g,"status","--porcelain"])}catch(b){let w=ro(b)?b.message||b.stderr||"":String(b);console.warn(`Worktree cleanup: could not check status at ${g} (${w}). Skipping removal \u2014 manual cleanup may be needed.`);return}if(y.stdout.trim().length>0){if(console.log(`Worktree preserved at ${g} (branch: ${h}) \u2014 uncommitted changes.`),tR(g),!nR()){let w=Xb(v.SHELL)==="fish"?"afk shell-init fish | source (add to ~/.config/fish/config.fish)":'eval "$(afk shell-init)" (add to ~/.zshrc or ~/.bashrc)';console.log(` \u2192 cd ${g}
|
|
73
|
-
\u2192 Or install one-time: ${w}`)}return}try{await r("git",["-C",e,"worktree","remove","--force",g])}catch(b){let w=ro(b)?b.message||b.stderr||"":String(b);console.warn(`Worktree cleanup: 'git worktree remove --force ${g}' failed (${w}). Manual removal may be needed.`);return}try{await r("git",["-C",e,"branch","-d",h])}catch(b){let w=ro(b)?b.message||b.stderr||"":String(b);console.warn(`Could not delete branch '${h}': ${w}`)}}};try{let f=c??"",g=l??"";if(c===void 0){try{f=(await r("git",["-C",e,"rev-parse","HEAD"])).stdout.trim()}catch{}try{g=(await r("git",["-C",e,"symbolic-ref","--short","HEAD"])).stdout.trim()}catch{}}let h={owner:"interactive",pid:process.pid,createdAt:new Date().toISOString(),baseSha:f,baseBranch:g};await Zb.writeFile(ew(a,".afk-worktree-meta.json"),JSON.stringify(h,null,2),"utf-8")}catch{}return m}var gC,mq,fq,fC,lc=x(()=>{"use strict";K();Lu();Qb();gC=lq(aq),mq="afk/",fq=/^[A-Za-z0-9_\-./]*$/,fC=64});import{existsSync as Un,readdirSync as EC,readFileSync as cp,realpathSync as kq,statSync as Tq}from"fs";import{homedir as ow}from"os";import{join as It}from"path";function uc(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Ms){let r=e[n];if(r!==void 0){if(r===!0){t[n]={plugins:!0,skills:!0,mcp:!0};continue}if(r!==!1&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=r;t[n]={plugins:o.plugins===!0,skills:o.skills===!0,mcp:o.mcp===!0}}}}return Object.keys(t).length>0?t:void 0}function iw(){return[Nt(),Ou()]}function Bt(e=iw()){for(let t of e)if(Un(t))try{let n=JSON.parse(cp(t,"utf-8")),r=uc(n.importFrom);if(r!==void 0)return r}catch{}}function vn(e,t=ow()){let n={pluginRoots:[],skillRoots:[],mcpConfigs:[]};if(!e)return n;for(let r of Ms){let o=e[r];if(!o)continue;let i=dc[r];if(o.plugins)for(let s of i.pluginRoots(t))Un(s)&&n.pluginRoots.push({dir:s,binary:r});if(o.skills){let s=`imported:${r}`;for(let a of i.skillRoots(t))Un(a)&&n.skillRoots.push({dir:a,origin:s})}if(o.mcp){let s=RC(i.mcpConfigCandidates(t));s&&n.mcpConfigs.push({source:s,format:i.mcpFormat})}}return n}function xC(e,t=ow()){return dc[e].pluginEnabledState(t)}function dp(e=ow()){return Ms.map(t=>xq(t,e))}function xq(e,t){let n=dc[e],r=[];for(let l of n.pluginRoots(t))r.push(...Aq(l));let o=[];for(let l of n.skillRoots(t))o.push(..._q(l));let i=RC(n.mcpConfigCandidates(t)),s=i?Iq(i,n.mcpFormat):[],a=r.length>0||o.length>0||i!==null||n.pluginRoots(t).some(Un)||n.skillRoots(t).some(Un);return{binary:e,label:n.label,present:a,plugins:r,skills:o,mcpServers:s,mcpConfigPath:i,mcpFormat:n.mcpFormat}}function RC(e){for(let t of e)if(Un(t))return t;return null}function Rq(e){let t=It(e,".claude","settings.json");if(!Un(t))return cc;let n;try{n=JSON.parse(cp(t,"utf-8"))}catch{return cc}if(!n||typeof n!="object")return cc;let r=n.enabledPlugins;if(!r||typeof r!="object"||Array.isArray(r))return cc;let o=new Map;for(let[i,s]of Object.entries(r))typeof s=="boolean"&&o.set(i,s);return o}function Cq(e){try{let t=JSON.parse(cp(It(e,".claude-plugin","plugin.json"),"utf-8"));return typeof t.name=="string"&&t.name.length>0?t.name:null}catch{return null}}function Aq(e){if(!Un(e))return[];let t=[];return CC(e,0,t,new Set),t}function CC(e,t,n,r){let o;try{o=kq(e)}catch{o=e}if(t>Eq||r.has(o))return;if(r.add(o),Un(It(e,".claude-plugin","plugin.json"))){let s=Cq(e)??e.split("/").filter(Boolean).pop()??e;n.push({name:s,path:e});return}let i;try{i=EC(e)}catch{return}for(let s of i){if(s.startsWith("."))continue;let a=It(e,s);try{Tq(a).isDirectory()&&CC(a,t+1,n,r)}catch{}}}function _q(e){let t;try{t=EC(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t)!r.isDirectory()||r.name.startsWith("_")||r.name.startsWith(".")||Un(It(e,r.name,"SKILL.md"))&&n.push({name:r.name,path:It(e,r.name)});return n}function Iq(e,t){let n;try{n=cp(e,"utf-8")}catch{return[]}return t==="json"?Pq(n):Mq(n)}function Pq(e){let t;try{t=JSON.parse(e)}catch{return[]}if(t===null||typeof t!="object")return[];let n=t.mcpServers;if(n===null||typeof n!="object"||Array.isArray(n))return[];let r=[];for(let[o,i]of Object.entries(n))r.push({name:o,command:$q(i)});return r}function Mq(e){let t=[],n=e.split(/\r?\n/),r=!1,o=null,i=null,s=null,a=[],l=()=>{if(r&&o){let d;s!==null?d=s:i!==null?d=a.length>0?[i,...a].join(" "):i:d="(no command)",t.push({name:o,command:d})}o=null,i=null,s=null,a=[]},c=/^\[mcp_servers\.([^\]]+)\]\s*$/;for(let d of n){let u=d.trim();if(u===""||u.startsWith("#"))continue;let m=c.exec(u);if(m){l(),r=!0,o=m[1]??null;continue}if(u.startsWith("[")){l(),r=!1;continue}if(!r)continue;let f=u.indexOf("=");if(f===-1)continue;let g=u.slice(0,f).trim(),h=u.slice(f+1).trim();g==="command"?i=rw(TC(h)):g==="url"?s=rw(TC(h)):g==="args"&&(a=Oq(h))}return l(),t}function TC(e){if(e.startsWith('"')||e.startsWith("'"))return e;let t=e.indexOf(" #");return t===-1?e:e.slice(0,t).trimEnd()}function Oq(e){let t=e.trim();if(!t.startsWith("["))return[];let n=t.slice(1,t.lastIndexOf("]"));if(!n.trim())return[];try{return n.split(",").map(r=>rw(r.trim())).filter(r=>r.length>0)}catch{return[]}}function rw(e){let t=e.match(/^"([^"]*)"$/)??e.match(/^'([^']*)'$/);return t&&t[1]!==void 0?t[1]:e.startsWith('"')||e.startsWith("'")?e.slice(1):e.endsWith('"')||e.endsWith("'")?e.slice(0,-1):e}function $q(e){if(e===null||typeof e!="object")return"(invalid)";let t=e;if(typeof t.url=="string")return t.url;if(typeof t.command=="string"){let n=Array.isArray(t.args)?t.args.filter(r=>typeof r=="string"):[];return[t.command,...n].join(" ")}return"(no command)"}var Ms,cc,dc,TSe,Eq,wr=x(()=>{"use strict";G();Ms=["claude-code","codex"],cc=new Map,dc={"claude-code":{label:"Claude Code",pluginRoots:e=>[It(e,".claude","plugins")],skillRoots:e=>[It(e,".claude","skills")],mcpConfigCandidates:e=>[It(e,".claude","mcp.json"),It(e,".claude",".mcp.json"),It(e,".claude","claude-code","mcp.json")],mcpFormat:"json",pluginEnabledState:e=>Rq(e)},codex:{label:"Codex",pluginRoots:e=>[It(e,".codex","plugins")],skillRoots:e=>[It(e,".codex","skills")],mcpConfigCandidates:e=>[It(e,".codex","config.toml")],mcpFormat:"toml",pluginEnabledState:()=>cc}},TSe={"claude-code":dc["claude-code"].label,codex:dc.codex.label},Eq=5});import{readFileSync as Dq,existsSync as Fq}from"fs";import{join as Lq}from"path";function pp(){if(up!==void 0)return up;let e=[Lq(process.cwd(),"afk.config.json"),Nt(),Ou()],t=!1;for(let r of e)if(Fq(r))try{let o=Dq(r,"utf-8"),i=JSON.parse(o),s={},a=UR(i.models);if(typeof i.model=="string"&&i.model.length>0){let c=i.model.toLowerCase();s.model=oc(c)?c:i.model}if(typeof i.maxTokens=="number"&&(s.maxTokens=i.maxTokens),typeof i.temperature=="number"&&(s.temperature=i.temperature),typeof i.systemPrompt=="string"&&i.systemPrompt.length>0&&(s.systemPrompt=i.systemPrompt),typeof i.permissionMode=="string"){let c=i.permissionMode;(c==="default"||c==="plan"||c==="autonomous"||c==="bypassPermissions")&&(s.permissionMode=c)}if(i.autoRouting&&typeof i.autoRouting=="object"){let c={};typeof i.autoRouting.interactive=="boolean"&&(c.interactive=i.autoRouting.interactive),typeof i.autoRouting.chat=="boolean"&&(c.chat=i.autoRouting.chat),typeof i.autoRouting.telegram=="boolean"&&(c.telegram=i.autoRouting.telegram),typeof i.autoRouting.daemon=="boolean"&&(c.daemon=i.autoRouting.daemon),s.autoRouting=c}if(i.daemon&&typeof i.daemon=="object"){let c={};typeof i.daemon.task=="string"&&(c.task=i.daemon.task),typeof i.daemon.taskId=="string"&&(c.taskId=i.daemon.taskId);let d=i.daemon.worktreePrune;d&&typeof d=="object"&&(c.worktreePrune={enabled:typeof d.enabled=="boolean"?d.enabled:!0,cron:typeof d.cron=="string"?d.cron:"0 4 * * *",maxAgeDaysClean:typeof d.maxAgeDaysClean=="number"?d.maxAgeDaysClean:14,maxAgeDaysDirty:typeof d.maxAgeDaysDirty=="number"?d.maxAgeDaysDirty:30,scope:typeof d.scope=="string"?d.scope:"all"}),typeof i.daemon.verifyDone=="boolean"&&(c.verifyDone=i.daemon.verifyDone),s.daemon=c}if(i.telegram&&typeof i.telegram=="object"){let c={},d=i.telegram.notify;if(d&&typeof d=="object"){let u={};if((d.mode==="primary"||d.mode==="broadcast"||d.mode==="custom")&&(u.mode=d.mode),typeof d.primaryChatId=="number"&&Number.isFinite(d.primaryChatId)&&(u.primaryChatId=d.primaryChatId),Array.isArray(d.targets)){let m=d.targets.filter(f=>typeof f=="number"&&Number.isFinite(f));m.length>0&&(u.targets=m)}c.notify=u}typeof i.telegram.verifyDone=="boolean"&&(c.verifyDone=i.telegram.verifyDone),s.telegram=c}if(i.updatePolicy&&["notify","auto","off"].includes(i.updatePolicy)&&(s.updatePolicy=i.updatePolicy),i.theme&&["dark","light","auto"].includes(i.theme)&&(s.theme=i.theme),typeof i.autoResumeOnUsageLimit=="boolean"&&(s.autoResumeOnUsageLimit=i.autoResumeOnUsageLimit),typeof i.enforceDoneEvidence=="boolean"&&(s.enforceDoneEvidence=i.enforceDoneEvidence),typeof i.bgSummaries=="boolean"&&(s.bgSummaries=i.bgSummaries),typeof i.maxSummaryCallsPerSession=="number"&&(s.maxSummaryCallsPerSession=Math.min(500,Math.max(1,i.maxSummaryCallsPerSession))),i.hooks!==null&&typeof i.hooks=="object"&&!Array.isArray(i.hooks)&&(s.hooks=i.hooks),typeof i.enableShellHooks=="boolean"&&(s.enableShellHooks=i.enableShellHooks),typeof i.enablePluginHooks=="boolean"&&(s.enablePluginHooks=i.enablePluginHooks),iw().includes(r)){let c=uc(i.importFrom);c!==void 0&&(s.importFrom=c)}if(i.interactive&&typeof i.interactive=="object"){let c={};typeof i.interactive.worktreeAutoname=="boolean"&&(c.worktreeAutoname=i.interactive.worktreeAutoname),typeof i.interactive.worktreeBranchPrefix=="string"&&(c.worktreeBranchPrefix=tw(i.interactive.worktreeBranchPrefix,`${r}#/interactive/worktreeBranchPrefix`)),typeof i.interactive.worktreeBase=="string"&&i.interactive.worktreeBase.trim().length>0&&(nw(i.interactive.worktreeBase,`${r}#/interactive/worktreeBase`),c.worktreeBase=i.interactive.worktreeBase),typeof i.interactive.suggestGhost=="boolean"&&(c.suggestGhost=i.interactive.suggestGhost),(i.interactive.thinkingUi==="summary"||i.interactive.thinkingUi==="live"||i.interactive.thinkingUi==="digest"||i.interactive.thinkingUi==="off")&&(c.thinkingUi=i.interactive.thinkingUi),Object.keys(c).length>0&&(s.interactive=c)}let l={config:s,sourcePath:r,modelsPartial:a};return t||(up=l),l}catch(o){console.error(`Warning: Failed to parse ${r}:`,o),t=!0}let n={config:{},sourcePath:void 0,modelsPartial:{}};return t||(up=n),n}var up,AC=x(()=>{"use strict";Sn();_t();G();lc();wr()});import{readFileSync as Nq,existsSync as Bq}from"fs";import{join as _C}from"path";function IC(){if(Os!==void 0)return Os.value;let e=[_C(process.cwd(),"AFK.md"),_C(Ae(),"AFK.md")];for(let t of e)if(Bq(t))try{let n=Nq(t,"utf-8").trim();if(n.length>0)return Os={value:{content:n,path:t}},Os.value}catch{}return Os={value:null},Os.value}var Os,PC=x(()=>{"use strict";G()});function mp(){return pp().config.telegram??{}}function $s(){return pp().config.permissionMode??ip}function Et(e){let t=uC(),{config:n,sourcePath:r,modelsPartial:o}=pp(),i={...Ps,...t,...n,...e},s;if(t.systemPrompt!==void 0)s="env:AFK_SYSTEM_PROMPT";else if(n.systemPrompt!==void 0&&r!==void 0)s=`file:${r}`;else if(i.systemPrompt===void 0){let c=IC();c!==null&&(i.systemPrompt=c.content,s=`afk-md:${c.path}`)}let a={model:i.model??Ps.model,maxTokens:i.maxTokens??Ps.maxTokens,temperature:i.temperature??Ps.temperature,updatePolicy:i.updatePolicy??Ps.updatePolicy,...i.apiKey!==void 0?{apiKey:i.apiKey}:{},...i.baseUrl!==void 0?{baseUrl:i.baseUrl}:{},...i.openaiBaseUrl!==void 0?{openaiBaseUrl:i.openaiBaseUrl}:{},...i.systemPrompt!==void 0?{systemPrompt:i.systemPrompt}:{},...s!==void 0?{systemPromptSource:s}:{},permissionMode:i.permissionMode??ip,...i.autoRouting!==void 0?{autoRouting:i.autoRouting}:{},...i.daemon!==void 0?{daemon:i.daemon}:{},...i.telegram!==void 0?{telegram:i.telegram}:{},...i.bgSummaries!==void 0?{bgSummaries:i.bgSummaries}:{},...i.maxSummaryCallsPerSession!==void 0?{maxSummaryCallsPerSession:i.maxSummaryCallsPerSession}:{},...i.interactive!==void 0?{interactive:i.interactive}:{},...i.hooks!==void 0?{hooks:i.hooks}:{},...i.enableShellHooks!==void 0?{enableShellHooks:i.enableShellHooks}:{},...i.enablePluginHooks!==void 0?{enablePluginHooks:i.enablePluginHooks}:{},...i.enforceDoneEvidence!==void 0?{enforceDoneEvidence:i.enforceDoneEvidence}:{},...i.importFrom!==void 0?{importFrom:i.importFrom}:{},...i.theme!==void 0?{theme:i.theme}:{}},l=e?.models??Fb(o);if(Qu(l),a.models=l,typeof a.model=="string"&&a.model.toLowerCase().startsWith("local-")&&(a.baseUrl===void 0||a.baseUrl.length===0))throw new Error(`Model '${a.model}' requires AFK_LOCAL_BASE_URL to be set (e.g. AFK_LOCAL_BASE_URL=http://127.0.0.1:8080). Point it at your local Anthropic-Messages-compatible server.`);return a}var Ut=x(()=>{"use strict";Sn();_t();We();Jb();Vb();AC();PC();Jb();Vb()});function Uq(e,t){return t!==void 0&&Number.isFinite(t)&&t!==0?t:e.find(r=>r>0)??e[0]}function jq(e,t={}){let n=[...e],r=t.mode??"primary";if(r==="broadcast")return n;if(r==="custom"){let i=(t.targets??[]).filter(s=>typeof s=="number"&&Number.isFinite(s)&&s!==0);if(i.length>0)return[...new Set(i)]}let o=Uq(n,t.primaryChatId);return o!==void 0?[o]:[]}function Hq(e){if(!e)return;let t=e.trim();if(!/^-?\d+$/.test(t))return;let n=Number(t);return Number.isFinite(n)&&n!==0?n:void 0}function Wq(e){if(!e)return;let t=e.trim().toLowerCase();return t==="primary"||t==="broadcast"||t==="custom"?t:void 0}function Kq(){let e=mp().notify??{},t=e.mode??Wq(v.AFK_TELEGRAM_NOTIFY_MODE),n=e.primaryChatId??Hq(v.AFK_TELEGRAM_PRIMARY_CHAT_ID);return{...t!==void 0?{mode:t}:{},...n!==void 0?{primaryChatId:n}:{},...e.targets!==void 0?{targets:e.targets}:{}}}function Ds(){let e=sC(v.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return jq(e,Kq())}var fp=x(()=>{"use strict";aC();Ut();K()});function sw(e,t=4096){if(e.length<=t)return[e];let n=[],r=e;for(;r.length>0;){if(r.length<=t){n.push(r);break}let o=t,i=r.lastIndexOf(`
|
|
73
|
+
\u2192 Or install one-time: ${w}`)}return}try{await r("git",["-C",e,"worktree","remove","--force",g])}catch(b){let w=ro(b)?b.message||b.stderr||"":String(b);console.warn(`Worktree cleanup: 'git worktree remove --force ${g}' failed (${w}). Manual removal may be needed.`);return}try{await r("git",["-C",e,"branch","-d",h])}catch(b){let w=ro(b)?b.message||b.stderr||"":String(b);console.warn(`Could not delete branch '${h}': ${w}`)}}};try{let f=c??"",g=l??"";if(c===void 0){try{f=(await r("git",["-C",e,"rev-parse","HEAD"])).stdout.trim()}catch{}try{g=(await r("git",["-C",e,"symbolic-ref","--short","HEAD"])).stdout.trim()}catch{}}let h={owner:"interactive",pid:process.pid,createdAt:new Date().toISOString(),baseSha:f,baseBranch:g};await Zb.writeFile(ew(a,".afk-worktree-meta.json"),JSON.stringify(h,null,2),"utf-8")}catch{}return m}var gC,mq,fq,fC,lc=x(()=>{"use strict";K();Lu();Qb();gC=lq(aq),mq="afk/",fq=/^[A-Za-z0-9_\-./]*$/,fC=64});import{existsSync as Un,readdirSync as EC,readFileSync as cp,realpathSync as kq,statSync as Tq}from"fs";import{homedir as ow}from"os";import{join as It}from"path";function uc(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Ms){let r=e[n];if(r!==void 0){if(r===!0){t[n]={plugins:!0,skills:!0,mcp:!0};continue}if(r!==!1&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=r;t[n]={plugins:o.plugins===!0,skills:o.skills===!0,mcp:o.mcp===!0}}}}return Object.keys(t).length>0?t:void 0}function iw(){return[Nt(),Ou()]}function Bt(e=iw()){for(let t of e)if(Un(t))try{let n=JSON.parse(cp(t,"utf-8")),r=uc(n.importFrom);if(r!==void 0)return r}catch{}}function vn(e,t=ow()){let n={pluginRoots:[],skillRoots:[],mcpConfigs:[]};if(!e)return n;for(let r of Ms){let o=e[r];if(!o)continue;let i=dc[r];if(o.plugins)for(let s of i.pluginRoots(t))Un(s)&&n.pluginRoots.push({dir:s,binary:r});if(o.skills){let s=`imported:${r}`;for(let a of i.skillRoots(t))Un(a)&&n.skillRoots.push({dir:a,origin:s})}if(o.mcp){let s=RC(i.mcpConfigCandidates(t));s&&n.mcpConfigs.push({source:s,format:i.mcpFormat})}}return n}function xC(e,t=ow()){return dc[e].pluginEnabledState(t)}function dp(e=ow()){return Ms.map(t=>xq(t,e))}function xq(e,t){let n=dc[e],r=[];for(let l of n.pluginRoots(t))r.push(...Aq(l));let o=[];for(let l of n.skillRoots(t))o.push(..._q(l));let i=RC(n.mcpConfigCandidates(t)),s=i?Iq(i,n.mcpFormat):[],a=r.length>0||o.length>0||i!==null||n.pluginRoots(t).some(Un)||n.skillRoots(t).some(Un);return{binary:e,label:n.label,present:a,plugins:r,skills:o,mcpServers:s,mcpConfigPath:i,mcpFormat:n.mcpFormat}}function RC(e){for(let t of e)if(Un(t))return t;return null}function Rq(e){let t=It(e,".claude","settings.json");if(!Un(t))return cc;let n;try{n=JSON.parse(cp(t,"utf-8"))}catch{return cc}if(!n||typeof n!="object")return cc;let r=n.enabledPlugins;if(!r||typeof r!="object"||Array.isArray(r))return cc;let o=new Map;for(let[i,s]of Object.entries(r))typeof s=="boolean"&&o.set(i,s);return o}function Cq(e){try{let t=JSON.parse(cp(It(e,".claude-plugin","plugin.json"),"utf-8"));return typeof t.name=="string"&&t.name.length>0?t.name:null}catch{return null}}function Aq(e){if(!Un(e))return[];let t=[];return CC(e,0,t,new Set),t}function CC(e,t,n,r){let o;try{o=kq(e)}catch{o=e}if(t>Eq||r.has(o))return;if(r.add(o),Un(It(e,".claude-plugin","plugin.json"))){let s=Cq(e)??e.split("/").filter(Boolean).pop()??e;n.push({name:s,path:e});return}let i;try{i=EC(e)}catch{return}for(let s of i){if(s.startsWith("."))continue;let a=It(e,s);try{Tq(a).isDirectory()&&CC(a,t+1,n,r)}catch{}}}function _q(e){let t;try{t=EC(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t)!r.isDirectory()||r.name.startsWith("_")||r.name.startsWith(".")||Un(It(e,r.name,"SKILL.md"))&&n.push({name:r.name,path:It(e,r.name)});return n}function Iq(e,t){let n;try{n=cp(e,"utf-8")}catch{return[]}return t==="json"?Pq(n):Mq(n)}function Pq(e){let t;try{t=JSON.parse(e)}catch{return[]}if(t===null||typeof t!="object")return[];let n=t.mcpServers;if(n===null||typeof n!="object"||Array.isArray(n))return[];let r=[];for(let[o,i]of Object.entries(n))r.push({name:o,command:$q(i)});return r}function Mq(e){let t=[],n=e.split(/\r?\n/),r=!1,o=null,i=null,s=null,a=[],l=()=>{if(r&&o){let d;s!==null?d=s:i!==null?d=a.length>0?[i,...a].join(" "):i:d="(no command)",t.push({name:o,command:d})}o=null,i=null,s=null,a=[]},c=/^\[mcp_servers\.([^\]]+)\]\s*$/;for(let d of n){let u=d.trim();if(u===""||u.startsWith("#"))continue;let m=c.exec(u);if(m){l(),r=!0,o=m[1]??null;continue}if(u.startsWith("[")){l(),r=!1;continue}if(!r)continue;let f=u.indexOf("=");if(f===-1)continue;let g=u.slice(0,f).trim(),h=u.slice(f+1).trim();g==="command"?i=rw(TC(h)):g==="url"?s=rw(TC(h)):g==="args"&&(a=Oq(h))}return l(),t}function TC(e){if(e.startsWith('"')||e.startsWith("'"))return e;let t=e.indexOf(" #");return t===-1?e:e.slice(0,t).trimEnd()}function Oq(e){let t=e.trim();if(!t.startsWith("["))return[];let n=t.slice(1,t.lastIndexOf("]"));if(!n.trim())return[];try{return n.split(",").map(r=>rw(r.trim())).filter(r=>r.length>0)}catch{return[]}}function rw(e){let t=e.match(/^"([^"]*)"$/)??e.match(/^'([^']*)'$/);return t&&t[1]!==void 0?t[1]:e.startsWith('"')||e.startsWith("'")?e.slice(1):e.endsWith('"')||e.endsWith("'")?e.slice(0,-1):e}function $q(e){if(e===null||typeof e!="object")return"(invalid)";let t=e;if(typeof t.url=="string")return t.url;if(typeof t.command=="string"){let n=Array.isArray(t.args)?t.args.filter(r=>typeof r=="string"):[];return[t.command,...n].join(" ")}return"(no command)"}var Ms,cc,dc,TSe,Eq,wr=x(()=>{"use strict";G();Ms=["claude-code","codex"],cc=new Map,dc={"claude-code":{label:"Claude Code",pluginRoots:e=>[It(e,".claude","plugins")],skillRoots:e=>[It(e,".claude","skills")],mcpConfigCandidates:e=>[It(e,".claude","mcp.json"),It(e,".claude",".mcp.json"),It(e,".claude","claude-code","mcp.json")],mcpFormat:"json",pluginEnabledState:e=>Rq(e)},codex:{label:"Codex",pluginRoots:e=>[It(e,".codex","plugins")],skillRoots:e=>[It(e,".codex","skills")],mcpConfigCandidates:e=>[It(e,".codex","config.toml")],mcpFormat:"toml",pluginEnabledState:()=>cc}},TSe={"claude-code":dc["claude-code"].label,codex:dc.codex.label},Eq=5});import{readFileSync as Dq,existsSync as Fq}from"fs";import{join as Lq}from"path";function pp(){if(up!==void 0)return up;let e=[Lq(process.cwd(),"afk.config.json"),Nt(),Ou()],t=!1;for(let r of e)if(Fq(r))try{let o=Dq(r,"utf-8"),i=JSON.parse(o),s={},a=UR(i.models);if(typeof i.model=="string"&&i.model.length>0){let c=i.model.toLowerCase();s.model=oc(c)?c:i.model}if(typeof i.maxTokens=="number"&&(s.maxTokens=i.maxTokens),typeof i.temperature=="number"&&(s.temperature=i.temperature),typeof i.systemPrompt=="string"&&i.systemPrompt.length>0&&(s.systemPrompt=i.systemPrompt),typeof i.permissionMode=="string"){let c=i.permissionMode;(c==="default"||c==="plan"||c==="autonomous"||c==="bypassPermissions")&&(s.permissionMode=c)}if(i.autoRouting&&typeof i.autoRouting=="object"){let c={};typeof i.autoRouting.interactive=="boolean"&&(c.interactive=i.autoRouting.interactive),typeof i.autoRouting.chat=="boolean"&&(c.chat=i.autoRouting.chat),typeof i.autoRouting.telegram=="boolean"&&(c.telegram=i.autoRouting.telegram),typeof i.autoRouting.daemon=="boolean"&&(c.daemon=i.autoRouting.daemon),s.autoRouting=c}if(i.daemon&&typeof i.daemon=="object"){let c={};typeof i.daemon.task=="string"&&(c.task=i.daemon.task),typeof i.daemon.taskId=="string"&&(c.taskId=i.daemon.taskId);let d=i.daemon.worktreePrune;d&&typeof d=="object"&&(c.worktreePrune={enabled:typeof d.enabled=="boolean"?d.enabled:!0,cron:typeof d.cron=="string"?d.cron:"0 4 * * *",maxAgeDaysClean:typeof d.maxAgeDaysClean=="number"?d.maxAgeDaysClean:14,maxAgeDaysDirty:typeof d.maxAgeDaysDirty=="number"?d.maxAgeDaysDirty:30,scope:typeof d.scope=="string"?d.scope:"all"}),typeof i.daemon.verifyDone=="boolean"&&(c.verifyDone=i.daemon.verifyDone),s.daemon=c}if(i.telegram&&typeof i.telegram=="object"){let c={},d=i.telegram.notify;if(d&&typeof d=="object"){let u={};if((d.mode==="primary"||d.mode==="broadcast"||d.mode==="custom")&&(u.mode=d.mode),typeof d.primaryChatId=="number"&&Number.isFinite(d.primaryChatId)&&(u.primaryChatId=d.primaryChatId),Array.isArray(d.targets)){let m=d.targets.filter(f=>typeof f=="number"&&Number.isFinite(f));m.length>0&&(u.targets=m)}c.notify=u}if(typeof i.telegram.verifyDone=="boolean"&&(c.verifyDone=i.telegram.verifyDone),Array.isArray(i.telegram.tagOnlyChats)){let u=i.telegram.tagOnlyChats.filter(m=>typeof m=="number"&&Number.isFinite(m));u.length>0&&(c.tagOnlyChats=u)}s.telegram=c}if(i.updatePolicy&&["notify","auto","off"].includes(i.updatePolicy)&&(s.updatePolicy=i.updatePolicy),i.theme&&["dark","light","auto"].includes(i.theme)&&(s.theme=i.theme),typeof i.autoResumeOnUsageLimit=="boolean"&&(s.autoResumeOnUsageLimit=i.autoResumeOnUsageLimit),typeof i.enforceDoneEvidence=="boolean"&&(s.enforceDoneEvidence=i.enforceDoneEvidence),typeof i.bgSummaries=="boolean"&&(s.bgSummaries=i.bgSummaries),typeof i.maxSummaryCallsPerSession=="number"&&(s.maxSummaryCallsPerSession=Math.min(500,Math.max(1,i.maxSummaryCallsPerSession))),i.hooks!==null&&typeof i.hooks=="object"&&!Array.isArray(i.hooks)&&(s.hooks=i.hooks),typeof i.enableShellHooks=="boolean"&&(s.enableShellHooks=i.enableShellHooks),typeof i.enablePluginHooks=="boolean"&&(s.enablePluginHooks=i.enablePluginHooks),iw().includes(r)){let c=uc(i.importFrom);c!==void 0&&(s.importFrom=c)}if(i.interactive&&typeof i.interactive=="object"){let c={};typeof i.interactive.worktreeAutoname=="boolean"&&(c.worktreeAutoname=i.interactive.worktreeAutoname),typeof i.interactive.worktreeBranchPrefix=="string"&&(c.worktreeBranchPrefix=tw(i.interactive.worktreeBranchPrefix,`${r}#/interactive/worktreeBranchPrefix`)),typeof i.interactive.worktreeBase=="string"&&i.interactive.worktreeBase.trim().length>0&&(nw(i.interactive.worktreeBase,`${r}#/interactive/worktreeBase`),c.worktreeBase=i.interactive.worktreeBase),typeof i.interactive.suggestGhost=="boolean"&&(c.suggestGhost=i.interactive.suggestGhost),(i.interactive.thinkingUi==="summary"||i.interactive.thinkingUi==="live"||i.interactive.thinkingUi==="digest"||i.interactive.thinkingUi==="off")&&(c.thinkingUi=i.interactive.thinkingUi),Object.keys(c).length>0&&(s.interactive=c)}let l={config:s,sourcePath:r,modelsPartial:a};return t||(up=l),l}catch(o){console.error(`Warning: Failed to parse ${r}:`,o),t=!0}let n={config:{},sourcePath:void 0,modelsPartial:{}};return t||(up=n),n}var up,AC=x(()=>{"use strict";Sn();_t();G();lc();wr()});import{readFileSync as Nq,existsSync as Bq}from"fs";import{join as _C}from"path";function IC(){if(Os!==void 0)return Os.value;let e=[_C(process.cwd(),"AFK.md"),_C(Ae(),"AFK.md")];for(let t of e)if(Bq(t))try{let n=Nq(t,"utf-8").trim();if(n.length>0)return Os={value:{content:n,path:t}},Os.value}catch{}return Os={value:null},Os.value}var Os,PC=x(()=>{"use strict";G()});function mp(){return pp().config.telegram??{}}function $s(){return pp().config.permissionMode??ip}function Et(e){let t=uC(),{config:n,sourcePath:r,modelsPartial:o}=pp(),i={...Ps,...t,...n,...e},s;if(t.systemPrompt!==void 0)s="env:AFK_SYSTEM_PROMPT";else if(n.systemPrompt!==void 0&&r!==void 0)s=`file:${r}`;else if(i.systemPrompt===void 0){let c=IC();c!==null&&(i.systemPrompt=c.content,s=`afk-md:${c.path}`)}let a={model:i.model??Ps.model,maxTokens:i.maxTokens??Ps.maxTokens,temperature:i.temperature??Ps.temperature,updatePolicy:i.updatePolicy??Ps.updatePolicy,...i.apiKey!==void 0?{apiKey:i.apiKey}:{},...i.baseUrl!==void 0?{baseUrl:i.baseUrl}:{},...i.openaiBaseUrl!==void 0?{openaiBaseUrl:i.openaiBaseUrl}:{},...i.systemPrompt!==void 0?{systemPrompt:i.systemPrompt}:{},...s!==void 0?{systemPromptSource:s}:{},permissionMode:i.permissionMode??ip,...i.autoRouting!==void 0?{autoRouting:i.autoRouting}:{},...i.daemon!==void 0?{daemon:i.daemon}:{},...i.telegram!==void 0?{telegram:i.telegram}:{},...i.bgSummaries!==void 0?{bgSummaries:i.bgSummaries}:{},...i.maxSummaryCallsPerSession!==void 0?{maxSummaryCallsPerSession:i.maxSummaryCallsPerSession}:{},...i.interactive!==void 0?{interactive:i.interactive}:{},...i.hooks!==void 0?{hooks:i.hooks}:{},...i.enableShellHooks!==void 0?{enableShellHooks:i.enableShellHooks}:{},...i.enablePluginHooks!==void 0?{enablePluginHooks:i.enablePluginHooks}:{},...i.enforceDoneEvidence!==void 0?{enforceDoneEvidence:i.enforceDoneEvidence}:{},...i.importFrom!==void 0?{importFrom:i.importFrom}:{},...i.theme!==void 0?{theme:i.theme}:{}},l=e?.models??Fb(o);if(Qu(l),a.models=l,typeof a.model=="string"&&a.model.toLowerCase().startsWith("local-")&&(a.baseUrl===void 0||a.baseUrl.length===0))throw new Error(`Model '${a.model}' requires AFK_LOCAL_BASE_URL to be set (e.g. AFK_LOCAL_BASE_URL=http://127.0.0.1:8080). Point it at your local Anthropic-Messages-compatible server.`);return a}var Ut=x(()=>{"use strict";Sn();_t();We();Jb();Vb();AC();PC();Jb();Vb()});function Uq(e,t){return t!==void 0&&Number.isFinite(t)&&t!==0?t:e.find(r=>r>0)??e[0]}function jq(e,t={}){let n=[...e],r=t.mode??"primary";if(r==="broadcast")return n;if(r==="custom"){let i=(t.targets??[]).filter(s=>typeof s=="number"&&Number.isFinite(s)&&s!==0);if(i.length>0)return[...new Set(i)]}let o=Uq(n,t.primaryChatId);return o!==void 0?[o]:[]}function Hq(e){if(!e)return;let t=e.trim();if(!/^-?\d+$/.test(t))return;let n=Number(t);return Number.isFinite(n)&&n!==0?n:void 0}function Wq(e){if(!e)return;let t=e.trim().toLowerCase();return t==="primary"||t==="broadcast"||t==="custom"?t:void 0}function Kq(){let e=mp().notify??{},t=e.mode??Wq(v.AFK_TELEGRAM_NOTIFY_MODE),n=e.primaryChatId??Hq(v.AFK_TELEGRAM_PRIMARY_CHAT_ID);return{...t!==void 0?{mode:t}:{},...n!==void 0?{primaryChatId:n}:{},...e.targets!==void 0?{targets:e.targets}:{}}}function Ds(){let e=sC(v.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return jq(e,Kq())}var fp=x(()=>{"use strict";aC();Ut();K()});function sw(e,t=4096){if(e.length<=t)return[e];let n=[],r=e;for(;r.length>0;){if(r.length<=t){n.push(r);break}let o=t,i=r.lastIndexOf(`
|
|
74
74
|
`,t);if(i>t-500&&i>0)o=i+1;else{let s=r.slice(0,t).match(/[.!?]\s+(?=[A-Z])/g);if(s&&s.length>0){let a=s[s.length-1];if(a){let l=r.lastIndexOf(a,t);l>t-200&&l>0&&(o=l+2)}}else{let a=r.lastIndexOf(" ",t);a>t-100&&a>0&&(o=a+1)}}n.push(r.slice(0,o).trim()),r=r.slice(o).trim()}return n}function MC(e){e=e.replace(/[\x02\x03]/g,"");let t=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),n=[];t=t.replace(/^ {0,3}```([\w]*)\n([\s\S]*?)```/gm,(o,i,s)=>{let a=n.length;if(s.trim()===""){let l=i?`(empty ${i} block)`:"(empty code block)";n.push(`<i>${l}</i>`)}else n.push(`<pre>${s}</pre>`);return`FENCED${a}`});let r=[];return t=t.replace(/`([^`]+)`/g,(o,i)=>{let s=r.length;return r.push(`<code>${i}</code>`),`CODE${s}`}),t=t.replace(/\*\*([^*]+)\*\*/g,"<b>$1</b>"),t=t.replace(/__([^_]+)__/g,"<b>$1</b>"),t=t.replace(/\*([^*]+)\*/g,"<i>$1</i>"),t=t.replace(/(^|[^\w])_([^_\n]+?)_(?!\w)/gm,"$1<i>$2</i>"),t=t.replace(/~~([^~]+)~~/g,"<s>$1</s>"),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(o,i,s)=>'<a href="'+s.replace(/"/g,""")+'">'+i+"</a>"),t=t.replace(/^#{1,6}\s+/gm,""),Gq(t)||(t=t.replace(/<\/?[bis]>/g,"")),t=t.replace(/\x02CODE(\d+)\x03/g,(o,i)=>r[Number(i)]??o),t=t.replace(/\x02FENCED(\d+)\x03/g,(o,i)=>n[Number(i)]??o),t}function Gq(e){let t=[],n=/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>/g,r;for(;(r=n.exec(e))!==null;){let o=(r[2]??"").toLowerCase();if(r[1]==="/"){if(t.pop()!==o)return!1}else t.push(o)}return t.length===0}var OC=x(()=>{"use strict"});var aw={};Tu(aw,{push:()=>Fs,pushIfConfigured:()=>tn,pushMarkdown:()=>$C});async function Fs(e){if(!e.token)throw new Error("push: token is required");if(e.chatId===""||e.chatId==null||e.chatId===0)throw new Error("push: chatId is required");let t=e.fetchImpl??fetch,r=`${e.apiBase??qq}/bot${e.token}/sendMessage`,o={chat_id:e.chatId,text:e.text.slice(0,4096)};e.parseMode&&(o.parse_mode=e.parseMode),e.replyMarkup&&(o.reply_markup=e.replyMarkup);let i=new AbortController,s=setTimeout(()=>i.abort(),1e4);try{let a=await t(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:i.signal});if(a.ok)return{ok:!0,status:a.status};let l;try{l=(await a.json()).description}catch{l=`HTTP ${a.status}`}return{ok:!1,status:a.status,...l!==void 0?{errorMessage:l}:{}}}catch(a){return{ok:!1,status:0,errorMessage:a instanceof Error?a.message:String(a)}}finally{clearTimeout(s)}}async function $C(e){let t=MC(e.text),n=sw(t),r={ok:!0,status:200};for(let o of n)if(r=await Fs({...e,text:o,parseMode:"HTML"}),!r.ok)return r.status===400&&/can't parse entities/i.test(r.errorMessage??"")?Fs({...e}):r;return r}async function tn(e,t={}){let n=v.TELEGRAM_BOT_TOKEN;if(!n)return null;let r=Ds();if(r.length===0)return null;let o=sw(e),i=[];for(let s of r)for(let a=0;a<o.length;a++){let l={token:n,chatId:s,text:o[a]??"",...t.replyMarkup!==void 0&&a===0?{replyMarkup:t.replyMarkup}:{},...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{}};i.push(t.markdown?await $C(l):await Fs({...l,...t.parseMode!==void 0?{parseMode:t.parseMode}:{}}))}return i}var qq,Sr=x(()=>{"use strict";fp();OC();K();qq="https://api.telegram.org"});function zq(e){return e.length<=DC?e:`${e.slice(0,DC)}\u2026(truncated)`}function Jq(e){try{let n=[`\u{1F514} AFK needs you \u2014 stuck on: ${e.title??e.serverName}`,zq(e.message)];e.url!==void 0&&e.url!==""&&n.push(e.url),tn(n.join(`
|
|
75
75
|
`)).catch(()=>{})}catch{}}var Ls,DC,lw,Ve,vr=x(()=>{"use strict";Sr();Ls={action:"decline"},DC=300;lw=class{handler=null;queue=Promise.resolve();queueDepth=0;install(t){this.handler=t}uninstall(){this.handler=null}hasHandler(){return this.handler!==null}pendingCount(){return this.queueDepth}route(t,n){if(n.signal.aborted)return Promise.resolve(Ls);this.queueDepth+=1;let r,o=new Promise(s=>{r=s}),i=this.handler;return this.queue=this.queue.then(async()=>{try{if(n.signal.aborted){r(Ls);return}if(!i){Jq(t),r(Ls);return}let s,a=new Promise(l=>{s=()=>l(Ls),n.signal.addEventListener("abort",s,{once:!0})});try{try{n.onActive?.()}catch{}let l=await Promise.race([i(t,n).catch(()=>Ls),a]);r(l)}finally{n.signal.removeEventListener("abort",s)}}finally{this.queueDepth-=1,r(Ls)}}).catch(()=>{}),o}},Ve=new lw});function gp(e){return["The user has switched off plan mode. Writes are now permitted. Do two things, in order:","",`1. Save the plan. Write the plan you developed in this conversation to a new markdown file under \`${e}/\` \u2014 pick a short, descriptive kebab-case filename (e.g. \`${e}/refactor-auth-flow.md\`). Capture the full plan: the chosen approach, the concrete step-by-step changes, the risks named, and the alternatives considered. This is the durable record.`,"","2. Implement the plan. Work through the steps you just recorded, verifying as you go \u2014 run the project's lint/test gates where they apply. End in a terminal state: Done with evidence, Blocked with the exact unblock condition, or Asking one precise question."].join(`
|
|
76
76
|
`)}var cw=x(()=>{"use strict"});function Vq(e){switch(e){case"bypassPermissions":return"Approve \u2014 implement now (restore bypass mode: no prompts, read/write any path)";case"acceptEdits":return"Approve \u2014 implement now (restore accept-edits mode: edits auto-approved)";case"dontAsk":case"auto":return"Approve \u2014 implement now (restore your previous mode: no approval prompts)";default:return"Approve \u2014 implement now (restore default mode: writes ask for confirmation, contained to the workspace)"}}function yp(e){return async(t,n,r)=>{let o=e.getPrePlanMode()??"default",i=Vq(o),a={serverName:"agent",origin:"agent",type:"choice",message:"Plan ready. How do you want to proceed? (Your plan is in the conversation above.)",choices:o==="bypassPermissions"?[i,dw]:[i,Yq,dw]},l=await Ve.route(a,{signal:n});if(l.action!=="accept")return{content:"Plan exit not confirmed (the user did not approve). Stay in plan mode \u2014 keep refining the plan; do not implement. Call exit_plan_mode again when ready."};let c=typeof l.content?.value=="string"?l.content.value:"";if(c.startsWith("Keep")||c===dw)return{content:"User chose to keep planning. Stay in plan mode and refine the plan; do not implement. Call exit_plan_mode again when ready."};let d=c.includes("bypass")?"bypassPermissions":o,u=Cu(r?.resolveBase??r?.cwd??process.cwd());return e.requestImplementSeed(gp(u),d),{content:`Plan approved (mode=${d}). The implementation instruction will follow as a new message \u2014 end your turn now.`}}}var jt,Yq,dw,hp,ii=x(()=>{"use strict";vr();cw();G();jt="exit_plan_mode",Yq="Approve \u2014 implement now (bypass mode: no prompts, read/write any path)",dw="Keep planning";hp={name:jt,category:"other",concurrencySafe:!1,description:`Signal that your plan is ready and present it to the user for approval. The user is shown a picker: approve and implement (you pick neither mode \u2014 the user does), or keep planning.
|
|
@@ -869,7 +869,7 @@ Remedy: these paths are outside the fork's granted read roots. Re-dispatch with
|
|
|
869
869
|
Note: this search ran in basic-regex (BRE) mode, where '|' is a literal pipe \u2014 not alternation. If you intended "A or B", retry with extended: true (extended regex / ERE). If you meant the literal character '|', this empty result stands.`),d({content:$});return}if(k===2){let $=js(h.trim());d({content:`grep error: ${$.content}`,isError:!0,...$.truncated?{truncated:!0}:{}});return}let T=qn(g.trimEnd()),_=js(T);d({content:_.content,..._.truncated?{truncated:!0}:{}})}),f.on("error",k=>{let T;if(m===void 0&&Tc(k))try{T=zs(k,process.cwd())}catch{T=`working directory does not exist (process cwd deleted \u2014 deleted worktree?) \u2014 underlying: ${k.message}`}else T=zs(k,m);d({content:`Failed to execute grep: ${T}`,isError:!0})})})}}var YA,VA=x(()=>{"use strict";Kn();zn();lo();Nw();Hs();YA=qw()});import{promises as SV}from"fs";function zw(e){return(t,n,r)=>vV(t,n,r,e)}var vV,XA,QA=x(()=>{"use strict";zn();vV=async(e,t,n,r)=>{if(!e||typeof e!="object")throw new Error("Invalid input: expected an object");let i=e.path;if(typeof i!="string")throw new Error("Invalid input: path must be a string");let s;try{s=ln(i,n,"read",r)}catch(a){return{content:a instanceof Error?a.message:String(a),isError:!0}}try{let a=await SV.readdir(s,{withFileTypes:!0}),l=a.filter(m=>m.isDirectory()).map(m=>`${m.name}/`),c=a.filter(m=>!m.isDirectory()).map(m=>m.name);l.sort(),c.sort();let d=[...l,...c];return d.length===0?{content:"(empty directory)"}:{content:d.join(`
|
|
870
870
|
`)}}catch(a){if(a instanceof Error){let l=a;return l.code==="ENOENT"?{content:`Directory not found: ${s}`,isError:!0}:l.code==="ENOTDIR"?{content:`Not a directory: ${s}`,isError:!0}:l.code==="EACCES"?{content:`Permission denied: ${s}`,isError:!0}:{content:`Error listing directory: ${a.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}};XA=zw()});function kV(e=Fs){return async(t,n)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let o=t.message;if(typeof o!="string")return{content:"Invalid input: message must be a string",isError:!0};if(o.length===0)return{content:"Invalid input: message must be non-empty",isError:!0};if(o.length>ZA)return{content:`Invalid input: message exceeds Telegram's ${ZA}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let i=v.TELEGRAM_BOT_TOKEN;if(!i)return{content:"Telegram is not configured: TELEGRAM_BOT_TOKEN is not set. Run the bot setup wizard or export the env var before using send_telegram.",isError:!0};let s=Ds();if(s.length===0)return{content:"Telegram is not configured: AFK_TELEGRAM_ALLOWED_CHAT_IDS is empty or unset. Add the operator chat ID(s) before using send_telegram.",isError:!0};let a=[];for(let l of s){let c=await e({token:i,chatId:l,text:o});c.ok||a.push(`chat ${l}: ${c.errorMessage??`HTTP ${c.status}`}`)}return a.length===s.length?{content:`Failed to send Telegram message to any chat. ${a.join("; ")}`,isError:!0}:a.length>0?{content:`Sent Telegram message to ${s.length-a.length}/${s.length} chat(s); ${a.length} failed: ${a.join("; ")}`}:{content:s.length===1?`Sent Telegram message to chat ${s[0]}.`:`Sent Telegram message to ${s.length} chats.`}}}var ZA,e_,t_=x(()=>{"use strict";K();Sr();fp();ZA=4096;e_=kV()});async function TV(){let[{JSDOM:e},{Readability:t},{default:n}]=await Promise.all([import("jsdom"),import("@mozilla/readability"),import("turndown")]),r=new n({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});return r.remove(["script","style","noscript","iframe"]),{JSDOM:e,Readability:t,turndown:r}}function EV(){return Jw===null&&(Jw=TV()),Jw}function n_(e){return e.replace(/\n{3,}/g,`
|
|
871
871
|
|
|
872
|
-
`).trim()}function xV(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}async function r_(e,t){let{JSDOM:n,Readability:r,turndown:o}=await EV(),s=new n(e,{url:t}).window.document,a=(s.title??"").trim(),l=(()=>{try{let m=s.cloneNode(!0);return new r(m).parse()}catch{return null}})();if(l&&typeof l.content=="string"&&l.content.trim().length>0){let m=n_(o.turndown(l.content)),f=(l.title??"").trim()||a,g=typeof l.length=="number"&&l.length>0?l.length:(l.textContent??"").replace(/\s+/g," ").trim().length;return{title:f,markdown:m,textLength:g,usedFallback:!1}}let c=s.body,d=c?.innerHTML??"",u=n_(o.turndown(d));return{title:a,markdown:u,textLength:xV(c),usedFallback:!0}}var Jw,o_=x(()=>{"use strict";Jw=null});function CV(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new Error("aborted"));return}let o=()=>{clearTimeout(i),r(t?.reason??new Error("aborted"))},i=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})})}function i_(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function AV(e,t){let n=e.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,t)}async function Jp(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??CV,l=n.signal??void 0,c;for(let d=0;d<=o;d++){if(l?.aborted)throw l.reason??new Error("aborted");try{let u=await e(t,n);if(!RV.has(u.status)||d===o)return u;let m=AV(u,s)??i_(d,i,s);W("[web/retryFetch] retrying",{url:t,attempt:d,status:u.status,waitMs:m}),await u.body?.cancel().catch(()=>{}),await a(m,l)}catch(u){if(l?.aborted||(c=u,d===o))throw u;let m=i_(d,i,s);W("[web/retryFetch] retrying after error",{url:t,attempt:d,waitMs:m}),await a(m,l)}}throw c??new Error("retryFetch: exhausted without a result")}var RV,Yw=x(()=>{"use strict";he();RV=new Set([429,502,503,504])});import{readFileSync as _V}from"node:fs";import{join as IV}from"path";function PV(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function s_(e,t){return PV(t).test(e)}function $V(e,t){if(e!==void 0){let n=e.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(t!==void 0){if(MV.has(t))return!0;if(OV.has(t))return!1}return!1}function a_(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function DV(e){if(e===void 0||e===""||e==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${e}`)}function l_(e){let t=e===void 0||e.trim()===""?"default":e.trim();return Yl(t),t}function FV(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function LV(e){try{return _V(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function NV(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return typeof t.defaultProfile=="string"&&(n.defaultProfile=l_(t.defaultProfile)),n}function c_(e){let t=e?.env??v,n=e?.readFileSync??LV,r=e?.surface??t.AGENT_SURFACE,o=$V(t.AFK_BROWSER_HEADLESS,r),i=a_(t.AFK_BROWSER_ALLOWED_DOMAINS),s=a_(t.AFK_BROWSER_BLOCKED_DOMAINS),a=FV(t.AFK_BROWSER_DOM_SNAPSHOTS),l=DV(t.AFK_BROWSER_BACKEND),c=l_(t.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:i,blockedDomains:s,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=t.AFK_BROWSER_CONFIG,m=u!==void 0&&u.trim()!==""?u.trim():IV(bn(),"browser.json"),f=n(m);if(f===void 0)return d;let g;try{g=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${m}: ${String(y)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${m} must be a JSON object`);let h=NV(d,g);return h.configPath=m,h}function Vw(e,t){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${e}`}}for(let r of t.blockedDomains)if(s_(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>s_(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var MV,OV,Xw=x(()=>{"use strict";K();G();MV=new Set(["daemon","subagent","telegram","afk"]),OV=new Set(["repl","interactive","cli"])});import mi from"node:fs";import Yp from"node:path";import{randomBytes as BV}from"node:crypto";import{chromium as UV}from"playwright";function jV(){try{return"5.69.0"}catch{}try{let e=Yp.resolve(import.meta.dirname,"../../../package.json"),t=mi.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var HV,Vp,d_=x(()=>{"use strict";G();he();HV=jV(),Vp=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(t){this.config=t}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=UV.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i=()=>{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 s=await o.newPage(),a=await s.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await s.content(),c=s.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${HV}`}}loadStorageState(t){let n=Vl(t);try{if(!mi.existsSync(n))return;let r=JSON.parse(mi.readFileSync(n,"utf8"));return W("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){W("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Vl(t);if(!mi.existsSync(r))return;let o=await n.storageState(),i=Yp.join(Yp.dirname(r),`.${Yp.basename(r)}.${process.pid}.${BV(4).toString("hex")}.tmp`);mi.writeFileSync(i,JSON.stringify(o),{mode:384}),mi.chmodSync(i,384),mi.renameSync(i,r),W("[browser/vault] saved session",{profile:t,file:r})}catch(r){W("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as WV}from"crypto";function Qw(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of KV)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function u_(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&GV.test(e.label))}function p_(e){return WV("sha256").update(e,"utf8").digest("hex").slice(0,8)}function m_(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var KV,GV,Rc=x(()=>{"use strict";KV=[{name:"aws-access-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"github-pat",regex:/ghp_[a-zA-Z0-9]{36}/g},{name:"openai-bearer",regex:/sk-[a-zA-Z0-9_-]{20,}/g},{name:"slack-token",regex:/xox[abp]-[a-zA-Z0-9-]{10,}/g},{name:"jwt",regex:/eyJ[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}/g},{name:"form-password",regex:/password=[^&\s]+/gi}];GV=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as qV}from"node:crypto";function zV(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function JV(e,t,n){return`el_${qV("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function YV(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function f_(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function h_(e,t){let n=e.role??"",r=e.name??"";g_.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])h_(i,t)}async function VV(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let i=o.getBoundingClientRect(),s=o;if(i.width===0&&i.height===0){let d=window.getComputedStyle(s);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(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},y_).catch(()=>[])}async function XV(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let i of r){let s=i.tagName.toLowerCase(),a=i.getAttribute("role")??"",l=i.getAttribute("aria-label")??i.getAttribute("placeholder")??(i.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[s]??"");if(s==="input"){let h=i.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in i?i.value:void 0,u=d!==void 0?String(d):void 0,m=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:m};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},y_).catch(()=>[])}function QV(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Xp(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=QV(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=VV(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,m,f,g,h]=await Promise.all([s,a,l,c,d]),y,b=!1;u!==null?(y=[],h_(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await XV(e)).filter(N=>g_.has(N.role??"")));let w=new Map;for(let P of m){let N=f_(P.name),B=w.get(N);(!B||B.bbox.w===0&&P.bbox.w>0)&&w.set(N,P)}let S=y.map(P=>({ax:P,dom:w.get(f_(P.name??""))})),k=r?S:S.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);k.sort((P,N)=>{let B=P.dom?.bbox.y??0,U=N.dom?.bbox.y??0;if(B!==U)return B-U;let j=P.dom?.bbox.x??0,I=N.dom?.bbox.x??0;return j-I}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let _=k.slice(0,n).map((P,N)=>{let B=P.ax.role??"generic",U=P.ax.name??"",j=JV(B,U,N),I=P.dom?.bbox??{x:0,y:0,w:0,h:0},F=P.dom?.type??null,A=null;P.ax.value!==void 0&&P.ax.value!==null&&(A=String(P.ax.value)),P.ax.checked!==void 0&&(A=String(P.ax.checked)),u_({role:B,kind:F})&&(A="[redacted]");let M={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(M.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(M.selected=P.ax.selected),P.ax.expanded!==void 0&&(M.expanded=P.ax.expanded);let O;P.dom?.testId?O=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(O=`#${P.dom.id}`);let H={id:j,role:B,label:zV(U),kind:F,value:A,state:M,bbox:I};return O!==void 0&&(H.selector=O),H}),$="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?$="loading":P==="interactive"?$="navigating":$="idle"}catch{$="navigating"}$!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let R=YV(f),D=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:D,url:g,title:h,textSummary:R,interactive:_,status:{httpStatus:t.httpStatus??null,loadingState:$,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var g_,y_,b_=x(()=>{"use strict";Rc();g_=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);y_="a[href], button, input, select, textarea, [role], [tabindex], label"});async function w_(e,t){try{let n=await e.nth(t).evaluate(s=>{let a=s,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",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}:${t}`,o=0;for(let s=0;s<r.length;s++)o=o*31+r.charCodeAt(s)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Zw(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>w_(e,i)))).filter(o=>o!==null)}async function ZV(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let i=0;i<o;i++){let s;try{s=await r.nth(i).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(s)||(t.add(s),n.push({key:s,locator:r,index:i}))}return n}async function eS(e,t,n){switch(t.kind){case"element_id":return e4(e,t,n);case"selector":return t4(e,t);case"semantic":return n4(e,t)}}async function e4(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),i=await o.count();if(i===0)return{outcome:"not_found",query:t};if(i===1)return{outcome:"resolved",locator:o};let s=await Zw(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function t4(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await Zw(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function n4(e,t){return t.role!==void 0?r4(e,t.text,t.role):o4(e,t.text,t)}async function r4(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let i=await Zw(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function o4(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),i=e.getByLabel(t,{exact:!1}),[s,a,l]=await Promise.all([r.count(),o.count(),i.count()]);if(s+a+l===0)return{outcome:"not_found",query:n};let d=[];s>0&&d.push({loc:r,count:s}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:i,count:l});let u=await ZV(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let m=u.slice(0,5),f=[];for(let h=0;h<m.length;h++){let y=m[h];if(y===void 0)continue;let b=await w_(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,S=0;for(let k=0;k<w.length;k++)S=S*31+w.charCodeAt(k)>>>0;f.push({...b,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var S_=x(()=>{"use strict"});import{randomBytes as i4}from"crypto";import{mkdir as s4,stat as a4,writeFile as l4}from"fs/promises";import{join as tS}from"path";import{gzip as c4}from"zlib";import{promisify as d4}from"util";function u4(e){return tS(Vo(e),"browser")}function p4(e){return tS(u4(e),"screenshots")}function m4(){return new Date().toISOString().replace(/[:.]/g,"-")}function f4(){return i4(3).toString("hex")}async function nS(e,t,n){if(t.length>v_)throw new Error(`writeScreenshotSidecar: buffer exceeds ${v_} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=p4(e);await s4(r,{recursive:!0});let o=`${m4()}-${f4()}-${n}.png`,i=tS(r,o);await l4(i,t);let{size:s}=await a4(i);return{path:i,bytes:s}}var NEe,v_,k_=x(()=>{"use strict";G();Rc();NEe=d4(c4);v_=5*1024*1024});var E_={};Tu(E_,{PlaywrightProvider:()=>rS});function T_(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var rS,x_=x(()=>{"use strict";d_();b_();S_();Xw();Rc();k_();rS=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Vp(t)}async open(t){let n=Vw(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(c){a=c}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let l=await Xp(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await Xp(r,{observationCounter:o.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,s.interactive,s.url,s.title,"browser_observe"),s}async act(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),i=r.url(),s=t.timeoutMs??3e4,a=await eS(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${T_(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":{let h=Qw(t.value??"");await l.fill(t.value??"");break}case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(y){c=y}else c=h}let u=r.url();if(u!==i){let h=Vw(u,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:h.reason}}let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Xp(r,{observationCounter:o.observationCounter,screenshotPath:m,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),i;if(t.target!==void 0){let d=await eS(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${T_(t.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await d.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await nS(n,i,"browser_screenshot"),l=0,c=0;if(t.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:s,bytes:a,width:l,height:c,dataBase64:i.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(t){let n=this.sessions.get(t);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(t,r),r}updateSessionFromObservation(t,n,r,o,i){t.knownElements=new Map(n.map(s=>[s.id,s])),t.currentUrl=r,t.currentTitle=o,t.lastAction=i,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:i}=await nS(n,o,r);return i}catch{return null}}}});var gi={};Tu(gi,{__resetBrowserRegistryForTests:()=>w4,browserProviderActive:()=>y4,closeBrowserProvider:()=>oS,getBrowserProvider:()=>h4,peekBrowserProvider:()=>b4});function R_(){Promise.resolve(oS()).then(()=>{process.exit(130)})}function C_(){Promise.resolve(oS()).then(()=>{process.exit(143)})}function A_(){Jn=null}function g4(){Qp||(process.on("SIGINT",R_),process.on("SIGTERM",C_),process.on("exit",A_),Qp=!0)}function __(){Qp&&(process.removeListener("SIGINT",R_),process.removeListener("SIGTERM",C_),process.removeListener("exit",A_),Qp=!1)}async function h4(e){return Jn!==null?Jn:(fi!==null||(fi=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(x_(),E_)),n=c_(e),r=new t(n);return g4(),Jn=r,fi=null,r})()),fi)}async function oS(){if(Jn===null)return;let e=Jn;Jn=null,fi=null,__(),await e.shutdown()}function y4(){return Jn!==null}function b4(){return Jn}function w4(){Jn=null,fi=null,__()}var Jn,fi,Qp,hi=x(()=>{"use strict";Xw();Jn=null,fi=null,Qp=!1});async function I_(e,t){try{return await r_(e,t)}catch(n){return W("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function x4(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(hi(),gi));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function P_(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??x4,o=null,i=e,s=null,a=null;try{let c=await Jp(n,e,{headers:E4,redirect:"follow",signal:t.signal});s=c.status,i=c.url||e;let d=c.headers.get("content-type")??"";if(c.ok){if(T4.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await c.text();if(k4.test(d)&&!v4.test(d))return{title:"",markdown:u.trim(),finalUrl:i,usedRender:!1};if(o=await I_(u,i),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(c){if(t.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<200)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:i,usedRender:!1};try{let c=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal}),d=await I_(c.html,c.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(t.signal.aborted)throw c;if(o===null){let d=c instanceof Error?c.message:String(c),u=a instanceof Error?a.message:`HTTP ${s??"error"}`,m=new Error(`web_scrape could not retrieve ${e}: fetch failed (${u}) and render failed (${d}).`);throw m.cause=c,m}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:i,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${s??"error"}).`)}var v4,k4,T4,E4,M_=x(()=>{"use strict";o_();Yw();he();v4=/(text\/html|application\/xhtml\+xml)/i,k4=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,T4=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,E4={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function A4(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(R4,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),C4),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=Rr(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let c=i.statusText?` ${i.statusText}`:"";throw new Error(`Exa Search HTTP ${i.status}${c}${l}`)}let s;try{s=await i.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(s.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function O_(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?A4({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function $_(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
872
|
+
`).trim()}function xV(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}async function r_(e,t){let{JSDOM:n,Readability:r,turndown:o}=await EV(),s=new n(e,{url:t}).window.document,a=(s.title??"").trim(),l=(()=>{try{let m=s.cloneNode(!0);return new r(m).parse()}catch{return null}})();if(l&&typeof l.content=="string"&&l.content.trim().length>0){let m=n_(o.turndown(l.content)),f=(l.title??"").trim()||a,g=typeof l.length=="number"&&l.length>0?l.length:(l.textContent??"").replace(/\s+/g," ").trim().length;return{title:f,markdown:m,textLength:g,usedFallback:!1}}let c=s.body,d=c?.innerHTML??"",u=n_(o.turndown(d));return{title:a,markdown:u,textLength:xV(c),usedFallback:!0}}var Jw,o_=x(()=>{"use strict";Jw=null});function CV(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new Error("aborted"));return}let o=()=>{clearTimeout(i),r(t?.reason??new Error("aborted"))},i=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})})}function i_(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function AV(e,t){let n=e.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,t)}async function Jp(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??CV,l=n.signal??void 0,c;for(let d=0;d<=o;d++){if(l?.aborted)throw l.reason??new Error("aborted");try{let u=await e(t,n);if(!RV.has(u.status)||d===o)return u;let m=AV(u,s)??i_(d,i,s);W("[web/retryFetch] retrying",{url:t,attempt:d,status:u.status,waitMs:m}),await u.body?.cancel().catch(()=>{}),await a(m,l)}catch(u){if(l?.aborted||(c=u,d===o))throw u;let m=i_(d,i,s);W("[web/retryFetch] retrying after error",{url:t,attempt:d,waitMs:m}),await a(m,l)}}throw c??new Error("retryFetch: exhausted without a result")}var RV,Yw=x(()=>{"use strict";he();RV=new Set([429,502,503,504])});import{readFileSync as _V}from"node:fs";import{join as IV}from"path";function PV(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function s_(e,t){return PV(t).test(e)}function $V(e,t){if(e!==void 0){let n=e.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(t!==void 0){if(MV.has(t))return!0;if(OV.has(t))return!1}return!1}function a_(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function DV(e){if(e===void 0||e===""||e==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${e}`)}function l_(e){let t=e===void 0||e.trim()===""?"default":e.trim();return Yl(t),t}function FV(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function LV(e){try{return _V(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function NV(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return typeof t.defaultProfile=="string"&&(n.defaultProfile=l_(t.defaultProfile)),n}function c_(e){let t=e?.env??v,n=e?.readFileSync??LV,r=e?.surface??t.AGENT_SURFACE,o=$V(t.AFK_BROWSER_HEADLESS,r),i=a_(t.AFK_BROWSER_ALLOWED_DOMAINS),s=a_(t.AFK_BROWSER_BLOCKED_DOMAINS),a=FV(t.AFK_BROWSER_DOM_SNAPSHOTS),l=DV(t.AFK_BROWSER_BACKEND),c=l_(t.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:i,blockedDomains:s,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=t.AFK_BROWSER_CONFIG,m=u!==void 0&&u.trim()!==""?u.trim():IV(bn(),"browser.json"),f=n(m);if(f===void 0)return d;let g;try{g=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${m}: ${String(y)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${m} must be a JSON object`);let h=NV(d,g);return h.configPath=m,h}function Vw(e,t){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${e}`}}for(let r of t.blockedDomains)if(s_(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>s_(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var MV,OV,Xw=x(()=>{"use strict";K();G();MV=new Set(["daemon","subagent","telegram","afk"]),OV=new Set(["repl","interactive","cli"])});import mi from"node:fs";import Yp from"node:path";import{randomBytes as BV}from"node:crypto";import{chromium as UV}from"playwright";function jV(){try{return"5.70.0"}catch{}try{let e=Yp.resolve(import.meta.dirname,"../../../package.json"),t=mi.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var HV,Vp,d_=x(()=>{"use strict";G();he();HV=jV(),Vp=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(t){this.config=t}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=UV.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i=()=>{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 s=await o.newPage(),a=await s.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await s.content(),c=s.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${HV}`}}loadStorageState(t){let n=Vl(t);try{if(!mi.existsSync(n))return;let r=JSON.parse(mi.readFileSync(n,"utf8"));return W("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){W("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Vl(t);if(!mi.existsSync(r))return;let o=await n.storageState(),i=Yp.join(Yp.dirname(r),`.${Yp.basename(r)}.${process.pid}.${BV(4).toString("hex")}.tmp`);mi.writeFileSync(i,JSON.stringify(o),{mode:384}),mi.chmodSync(i,384),mi.renameSync(i,r),W("[browser/vault] saved session",{profile:t,file:r})}catch(r){W("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as WV}from"crypto";function Qw(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of KV)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function u_(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&GV.test(e.label))}function p_(e){return WV("sha256").update(e,"utf8").digest("hex").slice(0,8)}function m_(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var KV,GV,Rc=x(()=>{"use strict";KV=[{name:"aws-access-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"github-pat",regex:/ghp_[a-zA-Z0-9]{36}/g},{name:"openai-bearer",regex:/sk-[a-zA-Z0-9_-]{20,}/g},{name:"slack-token",regex:/xox[abp]-[a-zA-Z0-9-]{10,}/g},{name:"jwt",regex:/eyJ[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}/g},{name:"form-password",regex:/password=[^&\s]+/gi}];GV=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as qV}from"node:crypto";function zV(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function JV(e,t,n){return`el_${qV("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function YV(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function f_(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function h_(e,t){let n=e.role??"",r=e.name??"";g_.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])h_(i,t)}async function VV(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let i=o.getBoundingClientRect(),s=o;if(i.width===0&&i.height===0){let d=window.getComputedStyle(s);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(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},y_).catch(()=>[])}async function XV(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let i of r){let s=i.tagName.toLowerCase(),a=i.getAttribute("role")??"",l=i.getAttribute("aria-label")??i.getAttribute("placeholder")??(i.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[s]??"");if(s==="input"){let h=i.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in i?i.value:void 0,u=d!==void 0?String(d):void 0,m=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:m};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},y_).catch(()=>[])}function QV(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Xp(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=QV(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=VV(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,m,f,g,h]=await Promise.all([s,a,l,c,d]),y,b=!1;u!==null?(y=[],h_(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await XV(e)).filter(N=>g_.has(N.role??"")));let w=new Map;for(let P of m){let N=f_(P.name),B=w.get(N);(!B||B.bbox.w===0&&P.bbox.w>0)&&w.set(N,P)}let S=y.map(P=>({ax:P,dom:w.get(f_(P.name??""))})),k=r?S:S.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);k.sort((P,N)=>{let B=P.dom?.bbox.y??0,U=N.dom?.bbox.y??0;if(B!==U)return B-U;let j=P.dom?.bbox.x??0,I=N.dom?.bbox.x??0;return j-I}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let _=k.slice(0,n).map((P,N)=>{let B=P.ax.role??"generic",U=P.ax.name??"",j=JV(B,U,N),I=P.dom?.bbox??{x:0,y:0,w:0,h:0},F=P.dom?.type??null,A=null;P.ax.value!==void 0&&P.ax.value!==null&&(A=String(P.ax.value)),P.ax.checked!==void 0&&(A=String(P.ax.checked)),u_({role:B,kind:F})&&(A="[redacted]");let M={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(M.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(M.selected=P.ax.selected),P.ax.expanded!==void 0&&(M.expanded=P.ax.expanded);let O;P.dom?.testId?O=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(O=`#${P.dom.id}`);let H={id:j,role:B,label:zV(U),kind:F,value:A,state:M,bbox:I};return O!==void 0&&(H.selector=O),H}),$="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?$="loading":P==="interactive"?$="navigating":$="idle"}catch{$="navigating"}$!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let R=YV(f),D=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:D,url:g,title:h,textSummary:R,interactive:_,status:{httpStatus:t.httpStatus??null,loadingState:$,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var g_,y_,b_=x(()=>{"use strict";Rc();g_=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);y_="a[href], button, input, select, textarea, [role], [tabindex], label"});async function w_(e,t){try{let n=await e.nth(t).evaluate(s=>{let a=s,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",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}:${t}`,o=0;for(let s=0;s<r.length;s++)o=o*31+r.charCodeAt(s)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Zw(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>w_(e,i)))).filter(o=>o!==null)}async function ZV(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let i=0;i<o;i++){let s;try{s=await r.nth(i).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(s)||(t.add(s),n.push({key:s,locator:r,index:i}))}return n}async function eS(e,t,n){switch(t.kind){case"element_id":return e4(e,t,n);case"selector":return t4(e,t);case"semantic":return n4(e,t)}}async function e4(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),i=await o.count();if(i===0)return{outcome:"not_found",query:t};if(i===1)return{outcome:"resolved",locator:o};let s=await Zw(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function t4(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await Zw(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function n4(e,t){return t.role!==void 0?r4(e,t.text,t.role):o4(e,t.text,t)}async function r4(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let i=await Zw(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function o4(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),i=e.getByLabel(t,{exact:!1}),[s,a,l]=await Promise.all([r.count(),o.count(),i.count()]);if(s+a+l===0)return{outcome:"not_found",query:n};let d=[];s>0&&d.push({loc:r,count:s}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:i,count:l});let u=await ZV(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let m=u.slice(0,5),f=[];for(let h=0;h<m.length;h++){let y=m[h];if(y===void 0)continue;let b=await w_(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,S=0;for(let k=0;k<w.length;k++)S=S*31+w.charCodeAt(k)>>>0;f.push({...b,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var S_=x(()=>{"use strict"});import{randomBytes as i4}from"crypto";import{mkdir as s4,stat as a4,writeFile as l4}from"fs/promises";import{join as tS}from"path";import{gzip as c4}from"zlib";import{promisify as d4}from"util";function u4(e){return tS(Vo(e),"browser")}function p4(e){return tS(u4(e),"screenshots")}function m4(){return new Date().toISOString().replace(/[:.]/g,"-")}function f4(){return i4(3).toString("hex")}async function nS(e,t,n){if(t.length>v_)throw new Error(`writeScreenshotSidecar: buffer exceeds ${v_} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=p4(e);await s4(r,{recursive:!0});let o=`${m4()}-${f4()}-${n}.png`,i=tS(r,o);await l4(i,t);let{size:s}=await a4(i);return{path:i,bytes:s}}var NEe,v_,k_=x(()=>{"use strict";G();Rc();NEe=d4(c4);v_=5*1024*1024});var E_={};Tu(E_,{PlaywrightProvider:()=>rS});function T_(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var rS,x_=x(()=>{"use strict";d_();b_();S_();Xw();Rc();k_();rS=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Vp(t)}async open(t){let n=Vw(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(c){a=c}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let l=await Xp(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await Xp(r,{observationCounter:o.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,s.interactive,s.url,s.title,"browser_observe"),s}async act(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),i=r.url(),s=t.timeoutMs??3e4,a=await eS(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${T_(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":{let h=Qw(t.value??"");await l.fill(t.value??"");break}case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(y){c=y}else c=h}let u=r.url();if(u!==i){let h=Vw(u,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:h.reason}}let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Xp(r,{observationCounter:o.observationCounter,screenshotPath:m,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),i;if(t.target!==void 0){let d=await eS(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${T_(t.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await d.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await nS(n,i,"browser_screenshot"),l=0,c=0;if(t.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:s,bytes:a,width:l,height:c,dataBase64:i.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(t){let n=this.sessions.get(t);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(t,r),r}updateSessionFromObservation(t,n,r,o,i){t.knownElements=new Map(n.map(s=>[s.id,s])),t.currentUrl=r,t.currentTitle=o,t.lastAction=i,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:i}=await nS(n,o,r);return i}catch{return null}}}});var gi={};Tu(gi,{__resetBrowserRegistryForTests:()=>w4,browserProviderActive:()=>y4,closeBrowserProvider:()=>oS,getBrowserProvider:()=>h4,peekBrowserProvider:()=>b4});function R_(){Promise.resolve(oS()).then(()=>{process.exit(130)})}function C_(){Promise.resolve(oS()).then(()=>{process.exit(143)})}function A_(){Jn=null}function g4(){Qp||(process.on("SIGINT",R_),process.on("SIGTERM",C_),process.on("exit",A_),Qp=!0)}function __(){Qp&&(process.removeListener("SIGINT",R_),process.removeListener("SIGTERM",C_),process.removeListener("exit",A_),Qp=!1)}async function h4(e){return Jn!==null?Jn:(fi!==null||(fi=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(x_(),E_)),n=c_(e),r=new t(n);return g4(),Jn=r,fi=null,r})()),fi)}async function oS(){if(Jn===null)return;let e=Jn;Jn=null,fi=null,__(),await e.shutdown()}function y4(){return Jn!==null}function b4(){return Jn}function w4(){Jn=null,fi=null,__()}var Jn,fi,Qp,hi=x(()=>{"use strict";Xw();Jn=null,fi=null,Qp=!1});async function I_(e,t){try{return await r_(e,t)}catch(n){return W("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function x4(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(hi(),gi));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function P_(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??x4,o=null,i=e,s=null,a=null;try{let c=await Jp(n,e,{headers:E4,redirect:"follow",signal:t.signal});s=c.status,i=c.url||e;let d=c.headers.get("content-type")??"";if(c.ok){if(T4.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await c.text();if(k4.test(d)&&!v4.test(d))return{title:"",markdown:u.trim(),finalUrl:i,usedRender:!1};if(o=await I_(u,i),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(c){if(t.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<200)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:i,usedRender:!1};try{let c=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal}),d=await I_(c.html,c.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(t.signal.aborted)throw c;if(o===null){let d=c instanceof Error?c.message:String(c),u=a instanceof Error?a.message:`HTTP ${s??"error"}`,m=new Error(`web_scrape could not retrieve ${e}: fetch failed (${u}) and render failed (${d}).`);throw m.cause=c,m}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:i,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${s??"error"}).`)}var v4,k4,T4,E4,M_=x(()=>{"use strict";o_();Yw();he();v4=/(text\/html|application\/xhtml\+xml)/i,k4=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,T4=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,E4={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function A4(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(R4,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),C4),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=Rr(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let c=i.statusText?` ${i.statusText}`:"";throw new Error(`Exa Search HTTP ${i.status}${c}${l}`)}let s;try{s=await i.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(s.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function O_(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?A4({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function $_(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
873
873
|
|
|
874
874
|
(no results)`;let n=[`# Search results for "${e}"`,""];return t.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
|
|
875
875
|
`).trimEnd()}var R4,C4,D_=x(()=>{"use strict";lo();R4="https://api.exa.ai/search",C4=10});function D4(e){if(!e||typeof e!="object")return{error:"Invalid input: expected an object"};let t=e,n=t.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,i;if(r==="search"){if(typeof t.query!="string"||t.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};i=t.query}else{if(typeof t.url!="string"||t.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let l;try{l=new URL(t.url)}catch{return{error:`Invalid input: "${t.url}" is not a valid absolute URL`}}if(l.protocol!=="http:"&&l.protocol!=="https:")return{error:`Invalid input: protocol "${l.protocol}" not supported (http/https only)`};o=l.toString()}let s=_4;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};s=Math.min(t.timeout_ms,I4)}let a=P4;if(t.max_bytes!==void 0){if(typeof t.max_bytes!="number"||!Number.isFinite(t.max_bytes)||t.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(t.max_bytes,M4)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function iS(e,t){return Buffer.byteLength(e,"utf8")<=t?{content:e,truncated:!1}:{content:Tr(e,t),truncated:!0}}function F4(e){let t=[],n=e;for(let o=0;o<4&&n instanceof Error;o++)t.push(n.message),n=n.cause;let r=t.join(" | ");return $4.some(o=>r.includes(o))}function L4(e={}){let t=e.fetchFn??globalThis.fetch,n=e.env??process.env;return async(r,o)=>{if(typeof t!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let i=D4(r);if("error"in i)return{content:i.error,isError:!0};if(o.aborted){let d=o.reason;return{content:`web_scrape aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let s=new AbortController,a=()=>{s.abort(o.reason)},l,c=()=>{let d=s.signal.reason;return d instanceof Error?d.message:String(d??"aborted")};try{if(o.addEventListener("abort",a,{once:!0}),l=setTimeout(()=>{s.abort(new Error(`web_scrape timeout after ${i.timeoutMs}ms`))},i.timeoutMs),i.mode==="raw"){let u;try{u=await Jp(t,i.url,{method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:s.signal})}catch(g){return s.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape network error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}if(!u.ok)return{content:`web_scrape HTTP ${u.status} ${u.statusText||""}`.trimEnd()+` for ${i.url}`,isError:!0};let m;try{m=await u.text()}catch(g){return{content:`web_scrape read error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}let f=iS(m,i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}if(i.mode==="markdown")try{let u=await P_(i.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:i.timeoutMs,signal:s.signal});if(u.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${i.url}.`,isError:!0};let m=iS(u.markdown,i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}catch(u){if(s.signal.aborted)return{content:`web_scrape aborted: ${c()}`,isError:!0};let m=u instanceof Error?u.message:String(u),f=F4(u)?" (the render fallback needs the optional Playwright browser \u2014 run `pnpm exec playwright install chromium`)":"";return{content:`web_scrape markdown error: ${m}${f}`,isError:!0}}let d=O_({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in d)return{content:d.error,isError:!0};try{let u=await d.search(i.query,{limit:O4,timeoutMs:i.timeoutMs,signal:s.signal}),m=iS($_(i.query,u),i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}catch(u){return s.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape search error (${d.name}): ${u instanceof Error?u.message:String(u)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),o.removeEventListener("abort",a)}}}var _4,I4,P4,M4,O4,$4,F_,L_=x(()=>{"use strict";M_();D_();Yw();Hs();_4=3e4,I4=12e4,P4=1e5,M4=1e6,O4=10,$4=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"];F_=L4()});import{existsSync as B_,mkdirSync as N4,readFileSync as B4,renameSync as U4,unlinkSync as j4,writeFileSync as H4}from"node:fs";import{dirname as N_,join as W4}from"node:path";import{randomBytes as K4}from"node:crypto";function cn(e){let t=e??sb();if(!B_(t))return[];try{let n=B4(t,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);return console.error(`[schedule-store] failed to parse ${t}: ${r}`),[]}}function yi(e,t){let n=t??sb();N4(N_(n),{recursive:!0});let r=W4(N_(n),`.schedules.json.${process.pid}.${K4(4).toString("hex")}.tmp`),o=JSON.stringify(e,null,2);try{H4(r,o,"utf-8"),U4(r,n)}catch(i){try{B_(r)&&j4(r)}catch{}throw i}}function Zp(e,t){let n=cn(t),r=n.map(l=>l.id),o=G4(e.name),i=q4(o,r),s=new Date().toISOString(),a={...e,notifyOn:e.notifyOn??"failure",id:i,createdAt:s,updatedAt:s};return n.push(a),yi(n,t),a}function em(e,t){let n=cn(t),r=n.length,o=n.filter(i=>i.id!==e);return o.length===r?!1:(yi(o,t),!0)}function Cc(e,t){return cn(t).find(n=>n.id===e)}function G4(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function q4(e,t){if(!t.includes(e))return e;let n=2;for(;t.includes(`${e}-${n}`);)n+=1;return`${e}-${n}`}function U_(e){return{taskId:e.id,command:e.command,trigger:e.trigger??"cron",...e.cron!==void 0?{cronExpression:e.cron}:{},...e.notifyOn!==void 0?{notifyOn:e.notifyOn}:{}}}var tm=x(()=>{"use strict";G()});import{existsSync as z4,readFileSync as J4}from"node:fs";import{join as Y4}from"node:path";async function En(e,t,n){let r;try{let o=Y4(Mu("default"),"port");if(!z4(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=J4(o,"utf-8").trim();if(r=parseInt(i,10),Number.isNaN(r))return{synced:!1,detail:"daemon-not-detected (invalid port file)"}}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let o=await fetch(`http://localhost:${r}${t}`,{method:e,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return o.ok?{synced:!0,detail:"synced"}:e==="POST"&&o.status===409?{synced:!0,detail:"already-registered"}:e==="DELETE"&&o.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${o.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}var po,sS=x(()=>{"use strict";G();po="Change saved to schedules.json, but a running daemon (if any) did not pick it up \u2014 it will apply on the next daemon (re)start."});import{existsSync as V4}from"node:fs";import{readFile as X4}from"node:fs/promises";var j_,H_,W_,K_,G_=x(()=>{"use strict";tm();G();sS();j_=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected object",isError:!0};let n=e;if(typeof n.name!="string"||!n.name)return{content:"Invalid input: name required",isError:!0};if(typeof n.command!="string"||!n.command)return{content:"Invalid input: command required",isError:!0};if(typeof n.cron!="string"||!n.cron)return{content:"Invalid input: cron required",isError:!0};let r=n.cron.trim().split(/\s+/);if(r.length!==5&&r.length!==6)return{content:"Invalid input: cron must be a 5 or 6-field expression",isError:!0};let o=Zp({name:n.name,command:n.command,cron:n.cron,trigger:n.trigger??"cron",notifyOn:n.notifyOn,enabled:typeof n.enabled=="boolean"?n.enabled:!0}),i=o.enabled?await En("POST","/tasks",{taskId:o.id,command:o.command,cron:o.cron,trigger:o.trigger,notifyOn:o.notifyOn}):await En("DELETE",`/tasks/${o.id}`);return{content:JSON.stringify({id:o.id,name:o.name,cron:o.cron,enabled:o.enabled,daemonSynced:i.synced,syncDetail:i.detail,...i.synced?{}:{syncNote:po}})}},H_=async(e,t)=>{let n=cn();return{content:JSON.stringify(n.map(r=>({id:r.id,name:r.name,cron:r.cron,trigger:r.trigger,enabled:r.enabled,notifyOn:r.notifyOn})))}},W_=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected object",isError:!0};let n=e;if(typeof n.taskId!="string"||!n.taskId)return{content:"Invalid input: taskId required",isError:!0};let r=n.taskId,o=typeof n.limit=="number"?Math.min(Math.max(1,n.limit),50):10,i=Fn();if(!V4(i))return{content:JSON.stringify([])};let s;try{let c=await X4(i);s=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=s.split(`
|
|
@@ -886,7 +886,7 @@ Note: this search ran in basic-regex (BRE) mode, where '|' is a literal pipe \u2
|
|
|
886
886
|
`),cm(e,o,384)}function iI(e,t){if(!Ac(e))return!1;let n=lm(e,"utf-8"),r=new RegExp(`^${am(t)}=.*$
|
|
887
887
|
?`,"m");if(!r.test(n))return!1;let o=n.replace(r,"");return cm(e,o,384),!0}function sI(e,t){if(!Ac(e))return;let r=lm(e,"utf-8").match(new RegExp(`^${am(t)}=(.*)$`,"m"));return r?r[1]:void 0}function aI(e){let t={};if(!Ac(e))return t;let n=lm(e,"utf-8");for(let r of n.split(`
|
|
888
888
|
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i<=0)continue;let s=o.slice(0,i).trim(),a=o.slice(i+1);t[s]=a}return t}var dm=x(()=>{"use strict"});function Zs(e){let t=Eu(e);return t?L8.has(e)?"non-config":t.secret?"secret":N8.has(e)||e.endsWith("_BASE_URL")?"protected":"settable":"unknown"}function lI(e,t){if(t.includes(`
|
|
889
|
-
`))return{ok:!1,error:`value for ${e.name} must not contain newlines`};switch(e.type){case"number":{let n=Number(t);return Number.isFinite(n)?{ok:!0,value:t.trim()}:{ok:!1,error:`${e.name} expects a number, got ${JSON.stringify(t)}`}}case"boolean":{let n=t.trim().toLowerCase();return["true","false","1","0","yes","no","on","off"].includes(n)?{ok:!0,value:n}:{ok:!1,error:`${e.name} expects a boolean (true/false/1/0/yes/no/on/off), got ${JSON.stringify(t)}`}}case"json":{try{JSON.parse(t)}catch{return{ok:!1,error:`${e.name} expects valid JSON`}}return{ok:!0,value:t}}default:return{ok:!0,value:t}}}function um(e){return cI.get(e)}function SS(e){let t=cI.get(e);return t?t.tier:"unknown"}function pm(e,t){switch(e.type){case"boolean":{if(typeof t=="boolean")return{ok:!0,value:t};if(typeof t=="string"){let n=t.trim().toLowerCase();if(["true","1","yes","on"].includes(n))return{ok:!0,value:!0};if(["false","0","no","off"].includes(n))return{ok:!0,value:!1}}return{ok:!1,error:`${e.path} expects a boolean`}}case"number":{let n=typeof t=="number"?t:typeof t=="string"?Number(t):NaN;return Number.isFinite(n)?e.clamp?e.clamp.integer&&!Number.isInteger(n)?{ok:!1,error:`${e.path} expects an integer`}:{ok:!0,value:Math.min(e.clamp.max,Math.max(e.clamp.min,n))}:{ok:!0,value:n}:{ok:!1,error:`${e.path} expects a number`}}case"enum":return typeof t=="string"&&e.enumValues?.includes(t)?{ok:!0,value:t}:{ok:!1,error:`${e.path} expects one of: ${e.enumValues?.join(", ")}`};case"number-array":{let n;if(Array.isArray(t))n=t;else if(typeof t=="string")n=t.split(",").map(o=>o.trim()).filter(o=>o.length>0).map(o=>Number(o));else return{ok:!1,error:`${e.path} expects an array of numbers`};let r=[];for(let o of n){let i=typeof o=="number"?o:Number(o);if(!Number.isFinite(i))return{ok:!1,error:`${e.path} contains a non-number`};r.push(i)}return{ok:!0,value:r}}case"model-slot":{if(typeof t=="string")return t.trim().length===0?{ok:!1,error:`${e.path} must not be empty`}:{ok:!0,value:t.trim()};let n=HR(t);return n.ok?{ok:!0,value:n.value}:{ok:!1,error:`${e.path}: ${n.error}`}}default:return typeof t!="string"?{ok:!1,error:`${e.path} expects a string`}:t.trim().length===0?{ok:!1,error:`${e.path} must not be empty`}:{ok:!0,value:t}}}function dI(e,t){let n=e;for(let r of t.split(".")){if(n===null||typeof n!="object")return;n=n[r]}return n}function uI(e,t,n){let r=t.split("."),o=e;for(let i=0;i<r.length-1;i++){let s=r[i],a=o[s];(a===null||typeof a!="object"||Array.isArray(a))&&(o[s]={}),o=o[s]}o[r[r.length-1]]=n}function pI(e,t){let n=t.split("."),r=[e],o=e;for(let s=0;s<n.length-1;s++){let a=n[s],l=o[a];if(l===null||typeof l!="object"||Array.isArray(l))return!1;o=l,r.push(o)}let i=n[n.length-1];if(!(i in o))return!1;delete o[i];for(let s=r.length-1;s>=1;s--){let a=r[s];if(Object.keys(a).length===0){let l=n[s-1];delete r[s-1][l]}else break}return!0}var L8,N8,wS,cI,_c=x(()=>{"use strict";K();_t();L8=new Set(["HOME","PATH","SHELL","PAGER","NODE_ENV","CI","VITEST","DEBUG","FORCE_COLOR","NO_COLOR","AGENT_SURFACE","AFK_SESSION_ID","NO_UPDATE_NOTIFIER","SCRIPT","ASCIINEMA_REC"]),N8=new Set(["AFK_MODEL_SMALL_BASE_URL","AFK_MODEL_MEDIUM_BASE_URL","AFK_MODEL_LARGE_BASE_URL","AFK_LOCAL_BASE_URL","AFK_OPENAI_BASE_URL","AFK_SYSTEM_PROMPT","AFK_DAEMON_TASK","AFK_DAEMON_TASK_ID","AFK_DAEMON_CWD","AFK_DAEMON_HOST","AFK_BROWSER_ALLOWED_DOMAINS","AFK_BROWSER_BLOCKED_DOMAINS","AFK_BROWSER_CONFIG","AFK_ALLOW_PROJECT_MCP","AFK_INTERNAL","AFK_WORKTREE_BASE","AFK_WORKTREE_BRANCH_PREFIX","AFK_TELEGRAM_ALLOWED_CHAT_IDS","AFK_TELEGRAM_NOTIFY_MODE","AFK_TELEGRAM_PRIMARY_CHAT_ID","AFK_HOME","AFK_STATE_DIR","AFK_FRAMEWORK_DIR","TELEGRAM_DATA_DIR","AFK_TELEGRAM_CWD"]);wS=[{path:"model",tier:"agent",type:"string",description:"Default model id / alias."},{path:"models.local",tier:"agent",type:"model-slot",description:"Local-tier model id (OpenAI-compatible shim: Ollama, LM Studio, vLLM, MLX). Accepts a bare id string or a { id, provider, name } object (provider: anthropic | openai | chatgpt-oauth \u2014 chatgpt is accepted shorthand; baseUrl/apiKey are human-gated: set them via the AFK_MODEL_<TIER>_BASE_URL / _API_KEY env vars, not here)."},{path:"models.small",tier:"agent",type:"model-slot",description:"Small-tier model id. Accepts a bare id string or a { id, provider, name } object (provider: anthropic | openai | chatgpt-oauth \u2014 chatgpt is accepted shorthand; baseUrl/apiKey are human-gated: set them via the AFK_MODEL_<TIER>_BASE_URL / _API_KEY env vars, not here)."},{path:"models.medium",tier:"agent",type:"model-slot",description:"Medium-tier model id. Accepts a bare id string or a { id, provider, name } object (provider: anthropic | openai | chatgpt-oauth \u2014 chatgpt is accepted shorthand; baseUrl/apiKey are human-gated: set them via the AFK_MODEL_<TIER>_BASE_URL / _API_KEY env vars, not here)."},{path:"models.large",tier:"agent",type:"model-slot",description:"Large-tier model id. Accepts a bare id string or a { id, provider, name } object (provider: anthropic | openai | chatgpt-oauth \u2014 chatgpt is accepted shorthand; baseUrl/apiKey are human-gated: set them via the AFK_MODEL_<TIER>_BASE_URL / _API_KEY env vars, not here)."},{path:"maxTokens",tier:"agent",type:"number",clamp:{min:1,max:1e6,integer:!0},description:"Deprecated and inert: not read by the generation path. Use AFK_MAX_OUTPUT_TOKENS or --max-output-tokens to cap per-response output."},{path:"temperature",tier:"agent",type:"number",clamp:{min:0,max:2},description:"Sampling temperature."},{path:"autoRouting.interactive",tier:"agent",type:"boolean",description:"Auto-route model in the REPL."},{path:"autoRouting.chat",tier:"agent",type:"boolean",description:"Auto-route model for chat."},{path:"autoRouting.telegram",tier:"agent",type:"boolean",description:"Auto-route model for Telegram."},{path:"autoRouting.daemon",tier:"agent",type:"boolean",description:"Auto-route model for the daemon."},{path:"telegram.notify.mode",tier:"human",type:"enum",enumValues:["primary","broadcast","custom"],description:"Telegram notify routing mode (human-tier: notification-redirect vector)."},{path:"telegram.notify.primaryChatId",tier:"human",type:"number",clamp:{min:-1e15,max:1e15,integer:!0},description:"Primary Telegram chat id (human-tier: notification-redirect vector)."},{path:"telegram.notify.targets",tier:"human",type:"number-array",description:"Custom Telegram target chat ids (human-tier: notification-redirect vector)."},{path:"telegram.verifyDone",tier:"human",type:"boolean",description:`Opt-in AFK "Done" verification gate (human-tier: a self-honesty check on the agent's own completion reporting \u2014 the agent must not be able to disable it on its own config, same rationale as enableShellHooks/permissionMode).`},{path:"enforceDoneEvidence",tier:"human",type:"boolean",description:'Opt-in AFK terminal-state enforcement gate: in autonomous mode a turn that self-certifies "Done" with no corroborating evidence (a successful file write/edit or executed command) gets a framework correction injected into the next turn, which must substantiate or downgrade the claim (issue #237). Human-tier: a self-honesty check the agent must not be able to disable on its own config, same rationale as telegram.verifyDone. Sibling of telegram.verifyDone (which only relabels the Telegram push; this one bounces the turn).'},{path:"interactive.worktreeAutoname",tier:"agent",type:"boolean",description:"Auto-name worktrees."},{path:"interactive.suggestGhost",tier:"agent",type:"boolean",description:"Ghost-text suggestions in the REPL."},{path:"interactive.thinkingUi",tier:"agent",type:"enum",enumValues:["summary","live","digest","off"],description:"Default REPL thinking-display mode."},{path:"theme",tier:"agent",type:"enum",enumValues:["dark","light","auto"],description:"TUI color palette (dark | light | auto). Display-only; auto detects a light/dark background from the terminal and falls back to dark."},{path:"updatePolicy",tier:"human",type:"enum",enumValues:["notify","auto","off"],description:"Self-update policy (human-tier: auto self-update is scope-widening)."},{path:"autoResumeOnUsageLimit",tier:"agent",type:"boolean",description:"Auto-resume after a usage-limit pause."},{path:"bgSummaries",tier:"agent",type:"boolean",description:"Background summarisation."},{path:"maxSummaryCallsPerSession",tier:"agent",type:"number",clamp:{min:1,max:500,integer:!0},description:"Cap on summary calls per session."},{path:"systemPrompt",tier:"human",type:"string",description:"Operator system-prompt overlay."},{path:"permissionMode",tier:"human",type:"enum",enumValues:["default","plan","autonomous","bypassPermissions"],description:"Session permission mode for afk chat/interactive (human-tier: privilege-escalation vector). Unset \u2192 bypassPermissions (new-install default); set `default` to re-enable path containment + the approval prompt."},{path:"enableShellHooks",tier:"human",type:"boolean",description:"Enable shell hooks (trust gate)."},{path:"enablePluginHooks",tier:"human",type:"boolean",description:"Enable Claude Code plugin-contributed hooks (trust gate for third-party plugin hooks.json; independent of enableShellHooks)."},{path:"interactive.worktreeBranchPrefix",tier:"human",type:"string",description:"Worktree branch prefix (git-flag sensitive)."},{path:"interactive.worktreeBase",tier:"human",type:"string",description:"Worktree base ref (git-flag sensitive)."},{path:"daemon.task",tier:"human",type:"string",description:"Daemon task prompt."},{path:"daemon.taskId",tier:"human",type:"string",description:"Daemon task id."},{path:"daemon.verifyDone",tier:"human",type:"boolean",description:`Opt-in daemon-surface "Done" verification gate: a cron-tick completion push whose response self-certifies "Done" with no corroborating evidence (a successful file write/edit or executed command) is relabelled "\u26A0\uFE0F Done (unverified)" with a caveat line. The daemon analog of telegram.verifyDone (which is REPL-only); the daemon is single-turn-per-tick, so the only honest enforcement is relabelling the outgoing push rather than bouncing a next turn. Human-tier: a self-honesty check on the agent's own completion reporting \u2014 the agent must not be able to disable it on its own config, same rationale as telegram.verifyDone.`}],cI=new Map(wS.map(e=>[e.path,e]))});import{existsSync as mI,readFileSync as B8,copyFileSync as U8,chmodSync as j8}from"fs";function xS(e){return e===void 0||e.length===0?"<unset>":e.length<=4?"set (****)":`set (****${e.slice(-4)})`}function gm(e){return e?.filePath??St()}function fI(e,t,n){let r=Zs(e);if(r==="unknown")throw new Ic(e);if(r==="non-config")throw new vS(e);if(r==="secret"&&!t)throw new kS(e);if(r==="protected"&&!n)throw new TS(e);return r}function hm(e,t,n){let r=fI(e,n?.allowSecret,n?.allowProtected),o=Eu(e),i=lI(o,t);if(!i.ok)throw new mm(i.error);let s=gm(n);return Rn(s,e,i.value),{key:e,class:r,persistedTo:s,display:r==="secret"?xS(i.value):i.value}}function ym(e,t){let n=fI(e,t?.allowSecret,t?.allowProtected),r=gm(t),o=iI(r,e);return{key:e,class:n,removed:o,persistedTo:r}}function bm(e,t){let n=Zs(e);if(n==="unknown")throw new Ic(e);let r=gm(t),o=sI(r,e),i=rb(e),s=n==="secret"?o!==void 0?xS(o):void 0:o;return{key:e,class:n,persisted:s,activeInProcess:i}}function wm(e){let t=gm(e),n=aI(t),r=[];for(let o of Wl){let i=o.name,s=Zs(i),a=n[i],l=rb(i);if(!e?.all&&a===void 0&&!l)continue;let c=s==="secret"?a!==void 0?xS(a):void 0:a;r.push({key:i,class:s,persisted:c,activeInProcess:l})}return r}function Sm(e){return e?.filePath??Nt()}function vm(e){if(!mI(e))return{};let t;try{t=JSON.parse(B8(e,"utf-8"))}catch{throw new fm(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new fm(e);return t}function gI(e,t){if(mI(e))try{U8(e,`${e}.bak`),j8(`${e}.bak`,384)}catch{}cm(e,JSON.stringify(t,null,2)+`
|
|
889
|
+
`))return{ok:!1,error:`value for ${e.name} must not contain newlines`};switch(e.type){case"number":{let n=Number(t);return Number.isFinite(n)?{ok:!0,value:t.trim()}:{ok:!1,error:`${e.name} expects a number, got ${JSON.stringify(t)}`}}case"boolean":{let n=t.trim().toLowerCase();return["true","false","1","0","yes","no","on","off"].includes(n)?{ok:!0,value:n}:{ok:!1,error:`${e.name} expects a boolean (true/false/1/0/yes/no/on/off), got ${JSON.stringify(t)}`}}case"json":{try{JSON.parse(t)}catch{return{ok:!1,error:`${e.name} expects valid JSON`}}return{ok:!0,value:t}}default:return{ok:!0,value:t}}}function um(e){return cI.get(e)}function SS(e){let t=cI.get(e);return t?t.tier:"unknown"}function pm(e,t){switch(e.type){case"boolean":{if(typeof t=="boolean")return{ok:!0,value:t};if(typeof t=="string"){let n=t.trim().toLowerCase();if(["true","1","yes","on"].includes(n))return{ok:!0,value:!0};if(["false","0","no","off"].includes(n))return{ok:!0,value:!1}}return{ok:!1,error:`${e.path} expects a boolean`}}case"number":{let n=typeof t=="number"?t:typeof t=="string"?Number(t):NaN;return Number.isFinite(n)?e.clamp?e.clamp.integer&&!Number.isInteger(n)?{ok:!1,error:`${e.path} expects an integer`}:{ok:!0,value:Math.min(e.clamp.max,Math.max(e.clamp.min,n))}:{ok:!0,value:n}:{ok:!1,error:`${e.path} expects a number`}}case"enum":return typeof t=="string"&&e.enumValues?.includes(t)?{ok:!0,value:t}:{ok:!1,error:`${e.path} expects one of: ${e.enumValues?.join(", ")}`};case"number-array":{let n;if(Array.isArray(t))n=t;else if(typeof t=="string")n=t.split(",").map(o=>o.trim()).filter(o=>o.length>0).map(o=>Number(o));else return{ok:!1,error:`${e.path} expects an array of numbers`};let r=[];for(let o of n){let i=typeof o=="number"?o:Number(o);if(!Number.isFinite(i))return{ok:!1,error:`${e.path} contains a non-number`};r.push(i)}return{ok:!0,value:r}}case"model-slot":{if(typeof t=="string")return t.trim().length===0?{ok:!1,error:`${e.path} must not be empty`}:{ok:!0,value:t.trim()};let n=HR(t);return n.ok?{ok:!0,value:n.value}:{ok:!1,error:`${e.path}: ${n.error}`}}default:return typeof t!="string"?{ok:!1,error:`${e.path} expects a string`}:t.trim().length===0?{ok:!1,error:`${e.path} must not be empty`}:{ok:!0,value:t}}}function dI(e,t){let n=e;for(let r of t.split(".")){if(n===null||typeof n!="object")return;n=n[r]}return n}function uI(e,t,n){let r=t.split("."),o=e;for(let i=0;i<r.length-1;i++){let s=r[i],a=o[s];(a===null||typeof a!="object"||Array.isArray(a))&&(o[s]={}),o=o[s]}o[r[r.length-1]]=n}function pI(e,t){let n=t.split("."),r=[e],o=e;for(let s=0;s<n.length-1;s++){let a=n[s],l=o[a];if(l===null||typeof l!="object"||Array.isArray(l))return!1;o=l,r.push(o)}let i=n[n.length-1];if(!(i in o))return!1;delete o[i];for(let s=r.length-1;s>=1;s--){let a=r[s];if(Object.keys(a).length===0){let l=n[s-1];delete r[s-1][l]}else break}return!0}var L8,N8,wS,cI,_c=x(()=>{"use strict";K();_t();L8=new Set(["HOME","PATH","SHELL","PAGER","NODE_ENV","CI","VITEST","DEBUG","FORCE_COLOR","NO_COLOR","AGENT_SURFACE","AFK_SESSION_ID","NO_UPDATE_NOTIFIER","SCRIPT","ASCIINEMA_REC"]),N8=new Set(["AFK_MODEL_SMALL_BASE_URL","AFK_MODEL_MEDIUM_BASE_URL","AFK_MODEL_LARGE_BASE_URL","AFK_LOCAL_BASE_URL","AFK_OPENAI_BASE_URL","AFK_SYSTEM_PROMPT","AFK_DAEMON_TASK","AFK_DAEMON_TASK_ID","AFK_DAEMON_CWD","AFK_DAEMON_HOST","AFK_BROWSER_ALLOWED_DOMAINS","AFK_BROWSER_BLOCKED_DOMAINS","AFK_BROWSER_CONFIG","AFK_ALLOW_PROJECT_MCP","AFK_INTERNAL","AFK_WORKTREE_BASE","AFK_WORKTREE_BRANCH_PREFIX","AFK_TELEGRAM_ALLOWED_CHAT_IDS","AFK_TELEGRAM_TAG_ONLY_CHAT_IDS","AFK_TELEGRAM_NOTIFY_MODE","AFK_TELEGRAM_PRIMARY_CHAT_ID","AFK_HOME","AFK_STATE_DIR","AFK_FRAMEWORK_DIR","TELEGRAM_DATA_DIR","AFK_TELEGRAM_CWD"]);wS=[{path:"model",tier:"agent",type:"string",description:"Default model id / alias."},{path:"models.local",tier:"agent",type:"model-slot",description:"Local-tier model id (OpenAI-compatible shim: Ollama, LM Studio, vLLM, MLX). Accepts a bare id string or a { id, provider, name } object (provider: anthropic | openai | chatgpt-oauth \u2014 chatgpt is accepted shorthand; baseUrl/apiKey are human-gated: set them via the AFK_MODEL_<TIER>_BASE_URL / _API_KEY env vars, not here)."},{path:"models.small",tier:"agent",type:"model-slot",description:"Small-tier model id. Accepts a bare id string or a { id, provider, name } object (provider: anthropic | openai | chatgpt-oauth \u2014 chatgpt is accepted shorthand; baseUrl/apiKey are human-gated: set them via the AFK_MODEL_<TIER>_BASE_URL / _API_KEY env vars, not here)."},{path:"models.medium",tier:"agent",type:"model-slot",description:"Medium-tier model id. Accepts a bare id string or a { id, provider, name } object (provider: anthropic | openai | chatgpt-oauth \u2014 chatgpt is accepted shorthand; baseUrl/apiKey are human-gated: set them via the AFK_MODEL_<TIER>_BASE_URL / _API_KEY env vars, not here)."},{path:"models.large",tier:"agent",type:"model-slot",description:"Large-tier model id. Accepts a bare id string or a { id, provider, name } object (provider: anthropic | openai | chatgpt-oauth \u2014 chatgpt is accepted shorthand; baseUrl/apiKey are human-gated: set them via the AFK_MODEL_<TIER>_BASE_URL / _API_KEY env vars, not here)."},{path:"maxTokens",tier:"agent",type:"number",clamp:{min:1,max:1e6,integer:!0},description:"Deprecated and inert: not read by the generation path. Use AFK_MAX_OUTPUT_TOKENS or --max-output-tokens to cap per-response output."},{path:"temperature",tier:"agent",type:"number",clamp:{min:0,max:2},description:"Sampling temperature."},{path:"autoRouting.interactive",tier:"agent",type:"boolean",description:"Auto-route model in the REPL."},{path:"autoRouting.chat",tier:"agent",type:"boolean",description:"Auto-route model for chat."},{path:"autoRouting.telegram",tier:"agent",type:"boolean",description:"Auto-route model for Telegram."},{path:"autoRouting.daemon",tier:"agent",type:"boolean",description:"Auto-route model for the daemon."},{path:"telegram.notify.mode",tier:"human",type:"enum",enumValues:["primary","broadcast","custom"],description:"Telegram notify routing mode (human-tier: notification-redirect vector)."},{path:"telegram.notify.primaryChatId",tier:"human",type:"number",clamp:{min:-1e15,max:1e15,integer:!0},description:"Primary Telegram chat id (human-tier: notification-redirect vector)."},{path:"telegram.notify.targets",tier:"human",type:"number-array",description:"Custom Telegram target chat ids (human-tier: notification-redirect vector)."},{path:"telegram.tagOnlyChats",tier:"human",type:"number-array",description:"Chat ids where the bot answers only when addressed (reply to the bot, @mention, or text_mention resolving to the bot). Human-tier: it governs which chats the bot will respond in \u2014 a message-routing / who-can-drive-the-bot control, same class as the allowlist and telegram.notify.*. Requires Telegram privacy mode OFF for the bot to matter in groups."},{path:"telegram.verifyDone",tier:"human",type:"boolean",description:`Opt-in AFK "Done" verification gate (human-tier: a self-honesty check on the agent's own completion reporting \u2014 the agent must not be able to disable it on its own config, same rationale as enableShellHooks/permissionMode).`},{path:"enforceDoneEvidence",tier:"human",type:"boolean",description:'Opt-in AFK terminal-state enforcement gate: in autonomous mode a turn that self-certifies "Done" with no corroborating evidence (a successful file write/edit or executed command) gets a framework correction injected into the next turn, which must substantiate or downgrade the claim (issue #237). Human-tier: a self-honesty check the agent must not be able to disable on its own config, same rationale as telegram.verifyDone. Sibling of telegram.verifyDone (which only relabels the Telegram push; this one bounces the turn).'},{path:"interactive.worktreeAutoname",tier:"agent",type:"boolean",description:"Auto-name worktrees."},{path:"interactive.suggestGhost",tier:"agent",type:"boolean",description:"Ghost-text suggestions in the REPL."},{path:"interactive.thinkingUi",tier:"agent",type:"enum",enumValues:["summary","live","digest","off"],description:"Default REPL thinking-display mode."},{path:"theme",tier:"agent",type:"enum",enumValues:["dark","light","auto"],description:"TUI color palette (dark | light | auto). Display-only; auto detects a light/dark background from the terminal and falls back to dark."},{path:"updatePolicy",tier:"human",type:"enum",enumValues:["notify","auto","off"],description:"Self-update policy (human-tier: auto self-update is scope-widening)."},{path:"autoResumeOnUsageLimit",tier:"agent",type:"boolean",description:"Auto-resume after a usage-limit pause."},{path:"bgSummaries",tier:"agent",type:"boolean",description:"Background summarisation."},{path:"maxSummaryCallsPerSession",tier:"agent",type:"number",clamp:{min:1,max:500,integer:!0},description:"Cap on summary calls per session."},{path:"systemPrompt",tier:"human",type:"string",description:"Operator system-prompt overlay."},{path:"permissionMode",tier:"human",type:"enum",enumValues:["default","plan","autonomous","bypassPermissions"],description:"Session permission mode for afk chat/interactive (human-tier: privilege-escalation vector). Unset \u2192 bypassPermissions (new-install default); set `default` to re-enable path containment + the approval prompt."},{path:"enableShellHooks",tier:"human",type:"boolean",description:"Enable shell hooks (trust gate)."},{path:"enablePluginHooks",tier:"human",type:"boolean",description:"Enable Claude Code plugin-contributed hooks (trust gate for third-party plugin hooks.json; independent of enableShellHooks)."},{path:"interactive.worktreeBranchPrefix",tier:"human",type:"string",description:"Worktree branch prefix (git-flag sensitive)."},{path:"interactive.worktreeBase",tier:"human",type:"string",description:"Worktree base ref (git-flag sensitive)."},{path:"daemon.task",tier:"human",type:"string",description:"Daemon task prompt."},{path:"daemon.taskId",tier:"human",type:"string",description:"Daemon task id."},{path:"daemon.verifyDone",tier:"human",type:"boolean",description:`Opt-in daemon-surface "Done" verification gate: a cron-tick completion push whose response self-certifies "Done" with no corroborating evidence (a successful file write/edit or executed command) is relabelled "\u26A0\uFE0F Done (unverified)" with a caveat line. The daemon analog of telegram.verifyDone (which is REPL-only); the daemon is single-turn-per-tick, so the only honest enforcement is relabelling the outgoing push rather than bouncing a next turn. Human-tier: a self-honesty check on the agent's own completion reporting \u2014 the agent must not be able to disable it on its own config, same rationale as telegram.verifyDone.`}],cI=new Map(wS.map(e=>[e.path,e]))});import{existsSync as mI,readFileSync as B8,copyFileSync as U8,chmodSync as j8}from"fs";function xS(e){return e===void 0||e.length===0?"<unset>":e.length<=4?"set (****)":`set (****${e.slice(-4)})`}function gm(e){return e?.filePath??St()}function fI(e,t,n){let r=Zs(e);if(r==="unknown")throw new Ic(e);if(r==="non-config")throw new vS(e);if(r==="secret"&&!t)throw new kS(e);if(r==="protected"&&!n)throw new TS(e);return r}function hm(e,t,n){let r=fI(e,n?.allowSecret,n?.allowProtected),o=Eu(e),i=lI(o,t);if(!i.ok)throw new mm(i.error);let s=gm(n);return Rn(s,e,i.value),{key:e,class:r,persistedTo:s,display:r==="secret"?xS(i.value):i.value}}function ym(e,t){let n=fI(e,t?.allowSecret,t?.allowProtected),r=gm(t),o=iI(r,e);return{key:e,class:n,removed:o,persistedTo:r}}function bm(e,t){let n=Zs(e);if(n==="unknown")throw new Ic(e);let r=gm(t),o=sI(r,e),i=rb(e),s=n==="secret"?o!==void 0?xS(o):void 0:o;return{key:e,class:n,persisted:s,activeInProcess:i}}function wm(e){let t=gm(e),n=aI(t),r=[];for(let o of Wl){let i=o.name,s=Zs(i),a=n[i],l=rb(i);if(!e?.all&&a===void 0&&!l)continue;let c=s==="secret"?a!==void 0?xS(a):void 0:a;r.push({key:i,class:s,persisted:c,activeInProcess:l})}return r}function Sm(e){return e?.filePath??Nt()}function vm(e){if(!mI(e))return{};let t;try{t=JSON.parse(B8(e,"utf-8"))}catch{throw new fm(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new fm(e);return t}function gI(e,t){if(mI(e))try{U8(e,`${e}.bak`),j8(`${e}.bak`,384)}catch{}cm(e,JSON.stringify(t,null,2)+`
|
|
890
890
|
`,384)}function hI(e,t){let n=SS(e);if(n==="unknown")throw new Ic(e);if(n==="human"&&!t)throw new ES(e);return n}function mo(e,t,n){let r=hI(e,n?.allowHumanOnly),o=um(e),i=pm(o,t);if(!i.ok)throw new mm(i.error);let s=Sm(n),a=vm(s);return uI(a,e,i.value),gI(s,a),{path:e,class:r,value:i.value,persistedTo:s}}function km(e,t){let n=hI(e,t?.allowHumanOnly),r=Sm(t),o=vm(r),i=pI(o,e);return i&&gI(r,o),{path:e,class:n,removed:i,persistedTo:r}}function ea(e,t){let n=SS(e),r=Sm(t),o=vm(r);return{path:e,class:n,value:dI(o,e)}}function Tm(e){return vm(Sm(e))}var un,Ic,vS,kS,TS,ES,mm,fm,Pc=x(()=>{"use strict";G();K();dm();_c();un="effective on the next session/daemon restart; the current session is unchanged",Ic=class extends Error{constructor(t){super(`unknown config key: ${t}`),this.name="UnknownKeyError"}},vS=class extends Error{constructor(t){super(`${t} is a process/inherited env var and is not afk-configurable`),this.name="NonConfigKeyError"}},kS=class extends Error{constructor(t){super(`${t} holds a credential; the agent cannot set it. A human must run \`afk config env set ${t}\` (the value is entered masked and never enters the model context).`),this.name="SecretWriteRefused"}},TS=class extends Error{constructor(t){super(`${t} controls identity, safety, capability, autonomous runs, request routing, or where AFK's own state lives; the agent cannot set it. A human must run \`afk config env set ${t}\`.`),this.name="ProtectedEnvKeyRefused"}},ES=class extends Error{constructor(t){super(`${t} is human-gated (prompt/hooks/identity); the agent cannot set it. A human must run \`afk config set ${t}\`.`),this.name="HumanOnlyKeyRefused"}},mm=class extends Error{constructor(t){super(t),this.name="ConfigValidationError"}},fm=class extends Error{constructor(t){super(`refusing to write: existing ${t} is not valid JSON (fix or remove it by hand first)`),this.name="MalformedConfigError"}}});function yI(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function bI(e){return e==="env"||e==="config"?e:void 0}function Cr(e){return{content:e,isError:!0}}var wI,SI,vI=x(()=>{"use strict";Pc();wI=async e=>{let t=yI(e);if(!t)return Cr("config_get: expected an object input");let n=bI(t.target);if(!n)return Cr("config_get: `target` must be 'env' or 'config'");let r=typeof t.key=="string"?t.key:void 0,o=t.all===!0;try{if(n==="env"){if(r){let i=bm(r);return{content:JSON.stringify(i,null,2)}}return{content:JSON.stringify(wm({all:o}),null,2)}}if(r){let i=ea(r);return{content:JSON.stringify(i,null,2)}}return{content:JSON.stringify(Tm(),null,2)}}catch(i){return Cr(`config_get: ${i.message}`)}},SI=async e=>{let t=yI(e);if(!t)return Cr("config_set: expected an object input");let n=bI(t.target);if(!n)return Cr("config_set: `target` must be 'env' or 'config'");let r=typeof t.key=="string"?t.key:void 0;if(!r)return Cr("config_set: `key` is required");let o=t.action==="unset"?"unset":"set",i=t.value;try{if(o==="unset"){if(n==="env"){let l=ym(r);return{content:l.removed?`Removed ${l.key} from afk.env (${l.persistedTo}). ${un}.`:`${l.key} was not set in afk.env; nothing to remove.`}}let a=km(r);return{content:a.removed?`Removed ${a.path} from afk.config.json (${a.persistedTo}). ${un}.`:`${a.path} was not set in afk.config.json; nothing to remove.`}}if(i==null)return Cr(`config_set: \`value\` is required to set ${r}`);if(n==="env"){if(typeof i!="string"&&typeof i!="number"&&typeof i!="boolean")return Cr("config_set: env values must be a string, number, or boolean");let a=hm(r,String(i));return{content:`Set ${a.key} = ${a.display} in afk.env (${a.persistedTo}). ${un}.`}}let s=mo(r,i);return{content:`Set ${s.path} = ${JSON.stringify(s.value)} in afk.config.json (${s.persistedTo}). ${un}.`}}catch(s){return Cr(`config_set: ${s.message}`)}}});var kI,TI=x(()=>{"use strict";vr();kI=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let n=e,r=n.question;if(typeof r!="string"||r.trim()==="")return{content:"Invalid input: question must be a non-empty string",isError:!0};let o=new Set(["text","confirm","choice","multi_choice","number"]),i=n.type??"text";if(typeof i!="string"||!o.has(i))return{content:"Invalid input: type must be one of: text, confirm, choice, multi_choice, number",isError:!0};if(i==="choice"||i==="multi_choice"){let f=n.choices;if(!Array.isArray(f)||f.length===0)return{content:`Invalid input: choices array is required and must be non-empty for type "${i}"`,isError:!0};if(f.length>100)return{content:`Invalid input: choices array must not exceed 100 items, got ${f.length}`,isError:!0};for(let g of f)if(typeof g!="string")return{content:"Invalid input: all choices must be strings",isError:!0}}let s=n.min,a=n.max;if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)))return{content:"Invalid input: min must be a finite number",isError:!0};if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)))return{content:"Invalid input: max must be a finite number",isError:!0};if(s!==void 0&&a!==void 0&&s>a)return{content:`Invalid input: min (${s}) must be \u2264 max (${a})`,isError:!0};let l=n.min_length,c=n.max_length;if(l!==void 0&&typeof l!="number")return{content:"Invalid input: min_length must be a number",isError:!0};if(c!==void 0&&typeof c!="number")return{content:"Invalid input: max_length must be a number",isError:!0};if((l!==void 0||c!==void 0)&&i!=="text")return{content:`Invalid input: min_length/max_length are only valid for type "text", got "${i}"`,isError:!0};if(n.allow_custom!==void 0&&i!=="choice"&&i!=="multi_choice")return{content:`Invalid input: allow_custom is only valid for type "choice" or "multi_choice", got "${i}"`,isError:!0};let d={serverName:"agent",message:r.trim(),origin:"agent",type:i,...n.choices!==void 0&&{choices:n.choices},...n.context!==void 0&&typeof n.context=="string"&&{context:n.context},...n.default!==void 0&&{questionDefault:n.default},...l!==void 0&&{minLength:l},...c!==void 0&&{maxLength:c},...s!==void 0&&{min:s},...a!==void 0&&{max:a},...n.allow_skip!==void 0&&{allowSkip:!!n.allow_skip},...n.allow_custom!==void 0&&{allowCustom:!!n.allow_custom}},u=await Ve.route(d,{signal:t}),m=u.action==="decline"||u.action==="cancel";return{content:JSON.stringify(u),...m&&{isError:!0,failureClass:"elicitation-declined"}}}});function Em(e){if(e instanceof Error&&e.name==="TimeoutError")return"timeout";let t=e instanceof Error?e.message:String(e);return/Timeout\s+\d+\s*ms exceeded/i.test(t)?"timeout":void 0}function Yn(e){return H8.some(t=>e.includes(t))}function Vn(e){return e.includes("Executable doesn't exist")?"browser tools require the Playwright chromium binary. Install via: pnpm exec playwright install chromium.":"browser tools require the optional `playwright` peer dependency. Install via: pnpm add playwright (then pnpm exec playwright install chromium). Or pick a different tool."}var H8,ta=x(()=>{"use strict";H8=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"]});function W8(e){if(!e||typeof e!="object")return{error:"browser_open: input must be an object"};let t=e,n=t.url;if(typeof n!="string"||n.length===0)return{error:'browser_open: "url" is required and must be a non-empty string'};let r;try{r=new URL(n)}catch{return{error:`browser_open: "${n}" is not a valid absolute URL`}}if(r.protocol!=="http:"&&r.protocol!=="https:")return{error:`browser_open: protocol "${r.protocol}" is not supported (http/https only)`};let o;if(t.wait_for!==void 0){if(!EI.includes(t.wait_for))return{error:`browser_open: "wait_for" must be one of ${EI.map(a=>`"${a}"`).join(", ")} (got ${JSON.stringify(t.wait_for)})`};o=t.wait_for}let i;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_open: "screenshot" must be a boolean'};i=t.screenshot}let s;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:'browser_open: "timeout_ms" must be a positive finite number'};s=t.timeout_ms}return{url:r.toString(),waitFor:o,screenshot:i,timeoutMs:s}}function K8(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_open aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0,failureClass:"abort"}}let o=W8(t);if("error"in o)return{content:o.error,isError:!0};let i=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let s;try{if(e.getBrowserProvider)s=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(hi(),gi));s=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Yn(c)?{content:Vn(c),isError:!0}:{content:`browser_open failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await s.open({sessionId:i,url:o.url,waitFor:o.waitFor,screenshot:o.screenshot,timeoutMs:o.timeoutMs}),c=Date.now()-a;if("outcome"in l&&l.outcome==="blocked_by_policy")return rt(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:c}),{content:`browser_open blocked: ${l.reason}`,isError:!0,failureClass:"policy-refusal"};let d=l;return rt(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:d.url,status:"ok",durationMs:c,...d.screenshotPath!==null?{screenshotPath:d.screenshotPath}:{}}),{content:JSON.stringify(d,null,2)}}catch(l){let c=Date.now()-a,d=l instanceof Error?l.message:String(l);rt(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:d,recoverable:!1}});let u=Em(l);return{content:`browser_open failed: ${d}`,isError:!0,...u?{failureClass:u}:{}}}}}var EI,xI,RI=x(()=>{"use strict";K();xe();ta();EI=["load","domcontentloaded","networkidle"];xI=K8()});function G8(e){if(e!=null&&typeof e!="object")return{error:"browser_observe: input must be an object or omitted"};if(!e)return{};let t=e,n;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_observe: "screenshot" must be a boolean'};n=t.screenshot}let r;if(t.include_hidden!==void 0){if(typeof t.include_hidden!="boolean")return{error:'browser_observe: "include_hidden" must be a boolean'};r=t.include_hidden}let o;if(t.max_elements!==void 0){if(typeof t.max_elements!="number"||!Number.isFinite(t.max_elements)||t.max_elements<=0||!Number.isInteger(t.max_elements))return{error:'browser_observe: "max_elements" must be a positive integer'};o=t.max_elements}return{screenshot:n,includeHidden:r,maxElements:o}}function q8(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_observe aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=G8(t);if("error"in o)return{content:o.error,isError:!0};let i=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let s;try{if(e.getBrowserProvider)s=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(hi(),gi));s=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Yn(c)?{content:Vn(c),isError:!0}:{content:`browser_observe failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await s.observe({sessionId:i,screenshot:o.screenshot,includeHidden:o.includeHidden,maxElements:o.maxElements}),c=Date.now()-a;return rt(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:l.url,urlAfter:l.url,status:"ok",durationMs:c,...l.screenshotPath!==null?{screenshotPath:l.screenshotPath}:{}}),{content:JSON.stringify(l,null,2)}}catch(l){let c=Date.now()-a,d=l instanceof Error?l.message:String(l);return rt(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:d,recoverable:!1}}),{content:`browser_observe failed: ${d}`,isError:!0}}}}var CI,AI=x(()=>{"use strict";K();xe();ta();CI=q8()});function z8(e){if(!e||typeof e!="object")return{error:"browser_act: input must be an object"};let t=e;if(typeof t.action!="string")return{error:'browser_act: "action" is required and must be a string'};if(!_I.includes(t.action))return{error:`browser_act: "action" must be one of ${_I.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(t.action)})`};let n=t.action,r=t.target;if(!r||typeof r!="object")return{error:'browser_act: "target" is required and must be an object'};let o=r;if(typeof o.kind!="string"||!II.includes(o.kind))return{error:`browser_act: "target.kind" must be one of ${II.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(o.kind)})`};let i,s=o.kind;if(s==="semantic"){if(typeof o.text!="string"||o.text.length===0)return{error:'browser_act: target.kind=semantic requires "target.text" (non-empty string)'};i={kind:"semantic",text:o.text,...typeof o.role=="string"&&o.role.length>0?{role:o.role}:{}}}else if(s==="element_id"){if(typeof o.element_id!="string"||o.element_id.length===0)return{error:'browser_act: target.kind=element_id requires "target.element_id" (non-empty string)'};i={kind:"element_id",elementId:o.element_id}}else{if(typeof o.selector!="string"||o.selector.length===0)return{error:'browser_act: target.kind=selector requires "target.selector" (non-empty string)'};i={kind:"selector",selector:o.selector}}let a;if(t.value!==void 0){if(typeof t.value!="string")return{error:'browser_act: "value" must be a string when provided'};a=t.value}let l;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:'browser_act: "timeout_ms" must be a positive finite number'};l=t.timeout_ms}let c;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_act: "screenshot" must be a boolean'};c=t.screenshot}return{action:n,target:i,value:a,timeoutMs:l,screenshot:c}}function J8(e,t){let n=e.role?`"${e.text}" (role: ${e.role})`:`"${e.text}"`;return[`browser_act: ambiguous target \u2014 ${t.length} elements matched ${n}.`,'Retry with target.kind="element_id" using one of the following:',...t.map(o=>` id=${o.id} role=${o.role} label=${o.label}`)].join(`
|
|
891
891
|
`)}function Y8(e){return e.kind==="semantic"?{kind:"semantic",text:m_(e.text),...e.role!==void 0?{role:e.role}:{}}:e.kind==="element_id"?{kind:"element_id",elementId:e.elementId}:{kind:"selector",selectorHash:p_(e.selector)}}function V8(e={}){return async(t,n,r)=>{if(n.aborted){let c=n.reason;return{content:`browser_act aborted: ${c instanceof Error?c.message:String(c??"aborted")}`,isError:!0,failureClass:"abort"}}let o=z8(t);if("error"in o)return{content:o.error,isError:!0};let i=Y8(o.target),s=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let a;try{if(e.getBrowserProvider)a=await e.getBrowserProvider();else{let{getBrowserProvider:c}=await Promise.resolve().then(()=>(hi(),gi));a=await c()}}catch(c){let d=c instanceof Error?c.message:String(c);return Yn(d)?{content:Vn(d),isError:!0}:{content:`browser_act failed to get provider: ${d}`,isError:!0}}let l=Date.now();try{let c=await a.act({sessionId:s,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),d=Date.now()-l;if("outcome"in c){if(c.outcome==="ambiguous_target")return rt(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:i,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:d}),{content:J8(c.query,c.candidates),isError:!0};if(c.outcome==="blocked_by_policy")return rt(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:i,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:d}),{content:`browser_act blocked: ${c.reason}`,isError:!0,failureClass:"policy-refusal"}}return rt(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:i,urlBefore:c.url,urlAfter:c.url,status:"ok",durationMs:d,...c.screenshotPath!==null?{screenshotPath:c.screenshotPath}:{}}),{content:JSON.stringify(c,null,2)}}catch(c){let d=Date.now()-l,u=c instanceof Error?c.message:String(c);rt(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:i,urlBefore:null,urlAfter:null,status:"error",durationMs:d,error:{reason:u,recoverable:!1}});let m=Em(c);return{content:`browser_act failed: ${u}`,isError:!0,...m?{failureClass:m}:{}}}}}var _I,II,PI,MI=x(()=>{"use strict";Rc();K();xe();ta();_I=["click","fill","press","select","hover","scroll_to","wait_for"],II=["semantic","element_id","selector"];PI=V8()});function X8(e){if(typeof e.kind!="string"||!OI.includes(e.kind))return{error:`browser_screenshot: "target.kind" must be one of ${OI.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e.kind)})`};let t=e.kind;return t==="semantic"?typeof e.text!="string"||e.text.length===0?{error:'browser_screenshot: target.kind=semantic requires "target.text" (non-empty string)'}:{kind:"semantic",text:e.text,...typeof e.role=="string"&&e.role.length>0?{role:e.role}:{}}:t==="element_id"?typeof e.element_id!="string"||e.element_id.length===0?{error:'browser_screenshot: target.kind=element_id requires "target.element_id" (non-empty string)'}:{kind:"element_id",elementId:e.element_id}:typeof e.selector!="string"||e.selector.length===0?{error:'browser_screenshot: target.kind=selector requires "target.selector" (non-empty string)'}:{kind:"selector",selector:e.selector}}function Q8(e){if(e!=null&&typeof e!="object")return{error:"browser_screenshot: input must be an object or omitted"};if(!e)return{};let t=e,n;if(t.target!==void 0){if(!t.target||typeof t.target!="object")return{error:'browser_screenshot: "target" must be an object when provided'};let o=X8(t.target);if("error"in o)return o;n=o}let r;if(t.full_page!==void 0){if(typeof t.full_page!="boolean")return{error:'browser_screenshot: "full_page" must be a boolean'};r=t.full_page}return{target:n,fullPage:r}}function Z8(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_screenshot aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=Q8(t);if("error"in o)return{content:o.error,isError:!0};let i=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let s;try{if(e.getBrowserProvider)s=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(hi(),gi));s=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Yn(c)?{content:Vn(c),isError:!0}:{content:`browser_screenshot failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await s.screenshot({sessionId:i,target:o.target,fullPage:o.fullPage}),c=Date.now()-a,{dataBase64:d,mediaType:u,...m}=l;return rt(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:c,screenshotPath:m.path}),m.width>RS||m.height>RS?{content:JSON.stringify({...m,imageOmitted:`dimensions ${m.width}x${m.height}px exceed the ${RS}px model-vision limit; the PNG was saved to the sidecar path but not attached. Use full_page:false (viewport) or target a specific element for a model-visible image.`},null,2)}:{content:JSON.stringify(m,null,2),image:{mediaType:u,data:d}}}catch(l){let c=Date.now()-a,d=l instanceof Error?l.message:String(l);return rt(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:d,recoverable:!1}}),{content:`browser_screenshot failed: ${d}`,isError:!0}}}}var OI,RS,$I,DI=x(()=>{"use strict";K();xe();ta();OI=["semantic","element_id","selector"],RS=8e3;$I=Z8()});function e5(e={}){return async(t,n,r)=>{if(n.aborted){let a=n.reason;return{content:`browser_close aborted: ${a instanceof Error?a.message:String(a??"aborted")}`,isError:!0}}let o=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(o))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(o)}`,isError:!0};let i;try{if(e.getBrowserProvider)i=await e.getBrowserProvider();else{let{getBrowserProvider:a}=await Promise.resolve().then(()=>(hi(),gi));i=await a()}}catch(a){let l=a instanceof Error?a.message:String(a);return Yn(l)?{content:Vn(l),isError:!0}:{content:`browser_close failed to get provider: ${l}`,isError:!0}}let s=Date.now();try{await i.close({sessionId:o});let a=Date.now()-s;return rt(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:a}),{content:"Browser session closed."}}catch(a){let l=Date.now()-s,c=a instanceof Error?a.message:String(a);return rt(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:l,error:{reason:c,recoverable:!1}}),{content:`browser_close failed: ${c}`,isError:!0}}}}var FI,LI=x(()=>{"use strict";K();xe();ta();FI=e5()});function xm(e,t){let n=e!==void 0?qp(e,t):t!==void 0?qp("default",t):FA,r=t!==void 0?Gw(t):zA,o=t!==void 0?qw(t):YA,i=t!==void 0?jw(t):NA,s=t!==void 0?Ww(t):jA,a=t!==void 0?Kw(t):WA,l=t!==void 0?zw(t):XA,c=dS(),d=rI(t);return new Map([["bash",n],["read_file",i],["write_file",s],["edit_file",a],["glob",r],["grep",o],["list_directory",l],["send_telegram",e_],["web_scrape",F_],["create_schedule",j_],["list_schedules",H_],["get_schedule_history",W_],["cancel_schedule",K_],["worktree",d],["terminal_font_size",c],["config_get",wI],["config_set",SI],["ask_question",kI],["browser_open",xI],["browser_observe",CI],["browser_act",PI],["browser_screenshot",$I],["browser_close",FI]])}var CS=x(()=>{"use strict";LA();BA();HA();KA();JA();VA();QA();t_();L_();G_();pS();oI();vI();TI();RI();AI();MI();DI();LI()});import{existsSync as t5,readFileSync as n5}from"fs";import{join as r5}from"path";function NI(){let e=r5(_u(),"HOT.md");if(!t5(e))return null;try{let t=n5(e,"utf-8");return t.trim().length>0?t:null}catch{return null}}function Ar(e){let t=NI();if(!t)return e;let r=`<cross-session-memory>
|
|
892
892
|
${t.replace(/<\/?cross-session-memory\b[^>]*>/gi,"")}
|
|
@@ -1746,7 +1746,7 @@ ${S}
|
|
|
1746
1746
|
${k}`})}return{fileBlocks:a,warnings:l}}async function c1(e,t,n,r,o="summary",i,s){let a=WN(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0),Va(process.stdout,kd(process.cwd(),!0));let l="",c=0,d=!1,u=!1,m=!1,f=!1,g,h=!1,y=!1,b={abort:null},w=0,S=3e3,k=[],T=new Map,_=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,$=()=>{let B=r.subagentControl;B?.hasPromotableForeground()&&B.promoteActiveForeground().then(U=>{for(let j of U)(i??{fn:console.log}).fn(p.dim(` \u2192 subagent backgrounded as ${j.jobId}: ${j.label}`))}).catch(()=>{})},R=r.getCompositor?r.getCompositor():null,D=()=>new fl({out:gl(i),thinkingMode:o,..._?{activeSkillName:_}:{},onCancel:()=>{t.interrupt().catch(B=>{He()&&console.error(" "+p.error("session.interrupt() failed:"),B)})},...r.subagentControl?{onBackground:$}:{},...s?.history?{history:s.history}:{},...s?.autocompleteState?{autocompleteState:s.autocompleteState}:{},...s?.promptText!==void 0?{promptText:s.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...R?{compositor:R}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),C=D(),P=async()=>{if(!m){m=!0;try{await C.dispose()}catch{}}},N=async()=>{await C.arm();let B=C.getCompositor();if(i&&B){let U=B;i.fn=j=>U.commitAbove(j),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.(B),r.setInterruptNotifier?.(U=>C.setInterrupting(U)),r.rearmStatus?.()};try{R?R.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{h=!0,C.setSoftStopping(!0),t.interrupt().catch(M=>{He()&&console.error(" "+p.error("soft-stop session.interrupt() failed:"),M)});let A=r.subagentControl;A?.hasActiveForeground()&&A.cancelActiveForeground().catch(M=>{He()&&console.error(" "+p.error("soft-stop cancelActiveForeground() failed:"),M)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{y=!0,t.interrupt().catch(A=>{He()&&console.error(" "+p.error("pause-interrupt session.interrupt() failed:"),A)})}),await N(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler($);let{fileBlocks:B,warnings:U}=l1(e.text,{rootDir:process.cwd()});for(let A of U)(i??{fn:console.log}).fn(p.dim(` @-file: ${A}`));let j=B.length>0||e.attachments.length>0?s1(e.text,e.attachments,void 0,B):e.text,I=t.sendMessageStream(j);if(await Bs((A,M)=>{C.process(A,M)},async()=>{for await(let A of I){if(h||y)break;if(A.type==="chunk"&&A.chunk.type==="content"?(l+=A.chunk.content,d=!0):A.type==="message"&&!d&&(l=A.message.content),A.type==="stream_retry"&&(l=l.slice(0,c)),A.type==="chunk"&&A.chunk.type==="tool_use_detail"){let M=A.chunk,O={toolName:M.toolName,toolUseId:M.toolUseId,input:M.toolInput,...M.toolInputRaw!==void 0&&{inputRaw:M.toolInputRaw}};T.set(M.toolUseId,O),k.push(O)}else if(A.type==="chunk"&&A.chunk.type==="tool_result"){let M=A.chunk;c=l.length;let O=T.get(M.toolUseId);if(O&&(O.result=M.content,O.isError=M.isError,T.delete(M.toolUseId)),r.onContextProgress){let H=Date.now();if(H-w>=S){w=H;try{let J=r.onContextProgress();J instanceof Promise&&await J}catch(J){He()&&console.error(" "+p.error("onContextProgress (status refresh) failed:"),J)}}}}if(A.type==="paused"){if(r.setPausedState?.(!0),await P(),R&&A.autoResume===!0){let M=new AbortController;b.abort=M;let O=A.resetsAt?A.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,H=O?`Keep waiting \u2014 auto-resumes at ${O}`:"Keep waiting \u2014 auto-resume in progress",J="Switch model / provider (type /model after)",Q="Stop waiting",Z=[p.warning(" \u23F3 Usage limit reached.")+(O?p.dim(` Auto-resumes at ${O}.`):""),p.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];ar(R,{header:Z,options:[H,J,Q],signal:M.signal,initialIndex:0}).then(ie=>{if(b.abort=null,!ie)return;let q=ie[0];q===void 0||q===H||(y=!0,q===J&&(i??{fn:console.log}).fn(p.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(ve=>{He()&&console.error(" "+p.error("picker pause-interrupt session.interrupt() failed:"),ve)}))}).catch(ie=>{He()&&console.error(" "+p.error("picker promise rejected:"),ie)})}else(i??{fn:console.log}).fn(AR({reason:A.reason,...A.resetsAt!==void 0?{resetsAt:A.resetsAt}:{},...A.accountId!==void 0?{accountId:A.accountId}:{},...A.autoResume!==void 0?{autoResume:A.autoResume}:{}}));continue}if(A.type==="resumed"){r.setPausedState?.(!1),b.abort?.abort(),b.abort=null;let M=A.hotSwapped&&A.accountId?`\u25B6 Resumed on ${A.accountId}`:"\u25B6 Resumed";l="",c=0,d=!1,k.length=0,T.clear(),f=!1,g=void 0,u=!1,C=D(),m=!1,await N(),(i??{fn:console.log}).fn(p.success(M));continue}if(A.type==="error"){await P(),ks(hs(A.error)),u=!0;continue}C.process(A),A.type==="done"&&(f=!0,g=A.metadata)}}),await P(),h){let A=i?i.fn:console.log,M=R?R.getPendingCount():0,O=M>0?` \xB7 ${M} queued`:"";A(p.warning(`\u23F8 Stopped${O} \u2014 work so far kept.`)+p.dim(" Send a message to continue.")),A("")}if(y){let A=i?i.fn:console.log;A(p.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),A("")}if(f&&!h&&!y){Pi(n,a,l,g,k),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),Ya(process.stdout),$F(process.stdout,"afk: turn complete");let A=O=>{i?i.fn(O):console.log(O)},M=sy(l);if(M){A(i1(M)),A("");let O=oL(k);if(r.onTerminalState)try{r.onTerminalState(M,{doneHasCorroboratingEvidence:O})}catch{}if(n.permissionMode==="autonomous"){let H=M.kind==="done"&&mp().verifyDone===!0&&!O;sL(M,void 0,{unverified:H})}}if(Sle(g,n,A),r.onAfterTurn){let O=r.onAfterTurn();O instanceof Promise&&await O.catch(()=>{})}}}catch(B){await P(),u||ks(hs(B))}finally{await P(),Va(process.stdout,kd(process.cwd(),!1)),i&&(i.fn=i.idleFn,i.suppressSubagentCompletion=!1),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setPausedState?.(!1),r.setPauseInterruptHandler?.(null),b.abort?.abort(),b.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}function wle(e,t){let n=Math.round(e*100),r=de(t);if(e>=1){let o=Math.round((e-1)*t);return{tier:"over",text:` context OVER ${Math.round(t/1e3)}k tok by ~${de(o)} tok \u2014 model output may be silently truncated`}}return e>=.95?{tier:"near",text:` context ${n}% used of ${r} \u2014 near limit; output may soon truncate (consider /clear or a fresh session)`}:e>=.8?{tier:"caution",text:` context ${n}% used of ${r} \u2014 approaching limit`}:e>.5?{tier:"normal",text:` context ${n}% used of ${r}`}:{tier:"quiet",text:null}}function Sle(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(Se(e.durationMs)),e.totalCostUsd!==void 0&&r.push(st(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),i=Number(e.usage?.output_tokens??0);o+i>0&&r.push(de(o+i)+" tok"),r.length>0&&n(p.dim(" \u25E6 "+r.join(" \xB7 ")));let s=$k(t),a=Gt(t.model),l=wle(s,a);if(l.text!==null){let c=l.tier==="over"||l.tier==="near"?p.error:l.tier==="caution"?p.warning:p.dim;n(c(l.text))}n("")}var vle=5e3,kle=3,Tle="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function Ele(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(p.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function d1(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,verdictLedger:d,shellPassthrough:u,bgResultNotifier:m}=s,f=null,g=[];e.session.current.waitForInitialization().then(async $=>{He()&&(f=Ug($)),await Yd(e.session.current),He()&&(g=zT())}).catch(()=>{});let h=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,y,b=!1,w=!1,S,k,T,_=0;for(m.onInjectable=()=>{_>=kle||!o.isAwaitingInput()||!o.bufferIsEmpty()||(_++,Ya(process.stdout),h={text:Tle,attachments:[]},o.abortPendingRead())};;){if(f&&(e.replRenderer.writeLine(f),e.replRenderer.writeLine(""),f=null),g.length>0){for(let I of g)e.replRenderer.writeLine(I);e.replRenderer.writeLine(""),g=[]}let $=u.drainNotifications();for(let{job:I,result:F}of $){let A=F.errorReason===void 0?"\u2713":"\u2717",M=F.errorReason==="abort"?"killed":F.errorReason==="timeout"?"timed out":F.errorReason==="signal-killed"?"killed by signal":`exit ${F.exitCode??0}`,O=Math.max(0,Math.round(F.durationMs/100)/10);e.replRenderer.writeLine(p.dim(` ${A} [${I.id}] ${M} \xB7 ${O}s \xB7 `)+I.command)}let R=m.drainNotifications();for(let{job:I}of R){let F=I.status==="completed"?"\u2713":I.status==="failed"?"\u2717":"\u2298",A=I.endedAt!==void 0?Math.max(0,Math.round((I.endedAt-I.startedAt)/100)/10):0,M=I.label.length>60?`${I.label.slice(0,60)}\u2026`:I.label;e.replRenderer.writeLine(p.dim(` ${F} [${I.jobId}] subagent ${I.status} \xB7 ${A}s \xB7 `)+M)}let D=l.renderIfChanged(e.stats.sessionId);if(D.length>0){for(let I of D)e.replRenderer.writeLine(I);e.replRenderer.writeLine("")}let C,P;if(h===void 0){let I=await e.session.current.takePendingPlanExitSeed();I!==void 0&&(e.stats.permissionMode=I.mode,h={text:I.message,attachments:[]})}if(h!==void 0){let I=h;h=void 0;let F=wl(e.stats.permissionMode),A=ji({buffer:I.text,promptText:F,isTTY:!!process.stdout.isTTY,attachmentSummary:ol([...I.attachments])});e.replRenderer.writeLine(A),C=I.text.trim(),P=I.attachments}else{let I=y;y=void 0;let F=await o.readLine({promptFn:()=>wl(e.stats.permissionMode),...I!==void 0?{initialBuffer:I}:{},onSigint:r,onShiftTab:()=>{ny(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});C=F.text.trim(),P=F.attachments}if(!C&&P.length===0)continue;if(C.startsWith("!")){let I=/^(0|false|off|no)$/i.test(v.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!I&&(b||(b=!0,e.replRenderer.writeLine(p.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await u.dispatch(C))){e.statusLine.rearm();continue}}let N=!1;if(C.startsWith("/")){let I=await qF(C,e.slashCtx,P);if(I.handled){if(I.result==="exit"){e.rl.close();return}if((C==="/clear"||C.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(p.dim(` transcript: ${t.path()}`)),d.reset(),S=void 0),I.result!==null&&typeof I.result=="object"&&"kind"in I.result&&I.result.kind==="submit"){h={text:I.result.message,attachments:P??[]},e.statusLine.rearm();continue}if(I.result!==null&&typeof I.result=="object"&&"kind"in I.result&&I.result.kind==="prefill"){y=I.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}N=!0}a.push(C),await Ele(e,C);let B=C;if(N){let I=Ok(C);if(I){let F=I.name.replace(/^\//,"").split(":").pop()??"";if(F&&WT(F)){let A={skillName:F,rawArgs:I.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},M=e.session.current.sessionId,O=Vi(M),H=Date.now();W(`[afk trace] preflight.start commandName=${F}`);let J=!1,Q=await Yi(A,{cwd:e.stats.cwd??process.cwd(),artifactDir:O},Z=>{He()&&e.replRenderer.writeLine(p.warning(`\u26A0 preflight(${F}) failed: `)+(Z instanceof Error?Z.message:String(Z)))});J=Q!==null,W(`[afk trace] preflight.end commandName=${F} durationMs=${Date.now()-H} success=${J}`),B=GT(Q?.manifestBlock,C)}}}let U=u.drainInjections();U.length>0&&(B=U+B);let j=m.drainInjections();if(j.length>0&&(B=j+B),S!==void 0&&(B=S+`
|
|
1747
1747
|
|
|
1748
1748
|
`+B,S=void 0),e.hookRegistry)try{let I={event:"UserPromptSubmit",prompt:B,sessionId:e.stats.sessionId},F=await e.hookRegistry.dispatch(I);F.injectContext&&(B=F.injectContext+B)}catch(I){if(I instanceof ge){e.replRenderer.writeLine(p.warning("\u2298 Turn blocked by hook")+(I.reason?p.dim(`: ${Rr(I.reason)}`):"")),e.statusLine.rearm();continue}if(I instanceof Hn){e.replRenderer.writeLine(p.warning("\u2298 Turn blocked by hook")+p.dim(`: handler timed out after ${I.timeoutMs}ms`)),e.statusLine.rearm();continue}throw I}if(k=void 0,T=void 0,await c1({text:B,attachments:P},e.session.current,e.stats,{setInFlight(I){n.turnInFlight=I},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(I){await t.appendUser(I)},async onTurnComplete(I,F){if(await t.appendTurn(I,F),e.stats.sessionId)try{Mo(e.stats)}catch(A){w||(w=!0,e.replRenderer.writeLine(p.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(A instanceof Error?A.message:String(A))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:(I,F)=>{d?.push(I),k=I.kind,T=F?.doneHasCorroboratingEvidence},setActiveCompositor:I=>{n.activeCompositor=I},setInterruptNotifier:I=>{n.notifyInterrupting=I},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:I=>o.setBackgroundHandler(I),setSoftStopHandler:i,setPausedState:I=>o.setPausedState(I),setPauseInterruptHandler:I=>o.setPauseInterruptHandler(I),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(sr(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:I=>c.repaint(I)}:{}},e.stats.thinkingUi??e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(wl(e.stats.permissionMode))),e.hookRegistry)try{let I=await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId,...k!==void 0?{terminalState:k}:{},...T!==void 0?{doneHasCorroboratingEvidence:T}:{}},void 0,vle);I.injectContext&&I.injectContext.trim().length>0&&(S=I.injectContext)}catch(I){if(I instanceof dt)throw I;I instanceof Hn?(W("[stop hook] handler timed out"),e.completionWriter.fn(p.dim(" [stop hook] timed out"))):I instanceof ge?e.completionWriter.fn(p.dim(` [stop hook] blocked: ${Rr(I.reason??"no reason given")}`)):W("[stop hook] unexpected error: "+String(I))}}}function xle(e,t){if(e!==void 0){let n=e.toLowerCase();return!(n==="0"||n==="false"||n==="off"||n==="no")}return typeof t=="boolean"?t:!0}async function u1(e,t,n,r){let o=await Wj(),i=new ty({rl:e.rl,history:o,statusLine:e.statusLine}),s=xle(v.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await Jj(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar});a=o1(e,n),await d1(e,t,n,r,i,l,a,o)}finally{n.tryAbortShellForeground=null,a?.shellPassthrough.drainOnExit(),a?.bgResultNotifier.dispose(),a?.loopStageBar.stop(),a?.bgStatusBar.stop(),a?.verdictLedger.stop(),a?.contextPane.dispose();let l=c=>console.log(c);e.completionWriter.fn=l,e.completionWriter.idleFn=l,await i.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}lc();Xs();import{execFile as Rle}from"node:child_process";import{dirname as Cle,isAbsolute as Ale,resolve as _le}from"node:path";import{promisify as Ile}from"node:util";var p1=Ile(Rle),Ple=3e3,Mle=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function Ole(){let t=(await p1("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=Ale(t)?t:_le(process.cwd(),t);return Cle(n)}async function m1(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await Ole()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),Ple)});try{let o=dn({execFile:p1,repoRoot:t,dryRun:!1,scope:"interactive",bypassSoftLaunch:!0}),i=await Promise.race([o,r]);if(i==="timeout")return{ran:!1,removedCount:0,skippedReason:"timeout"};let s=i;return s.warnings.some(c=>c.toLowerCase().includes("contested"))?{ran:!1,removedCount:0,skippedReason:"lock-contested"}:{ran:!0,removedCount:s.candidates.filter(c=>Mle.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}Zu();lc();import{promises as $le}from"node:fs";import{dirname as Dle,join as h1}from"node:path";import{randomBytes as Fle}from"node:crypto";var Lle=["Generate a 2-4 word kebab-case slug describing this work request.","Rules:","- ASCII lowercase letters and digits only, separated by single hyphens","- 2 to 4 hyphen-separated words","- Maximum 30 characters total","- No prefix, no quotes, no punctuation other than hyphens","- Output ONLY the slug \u2014 no explanation, no preamble","Examples: fix-cleanup-race, add-telegram-allowlist, refactor-prompt-loader, debug-flaky-test"].join(`
|
|
1749
|
-
`),f1=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,gE=30,Nle=1024,Ble=8e3,Ule="haiku";async function jle(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=Gle(n,Nle),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??Ble),s=t.signal?qle([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await _s({token:t.token,model:t.model??Ule,system:Lle,user:r,maxTokens:32,signal:s})}catch(u){let m=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(i)}let l=Hle(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=Dle(t.worktreePath);return await Wle(l,c)}function Hle(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(f1.test(t)&&t.length<=gE)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(i=>i.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let i=1;i<r.length;i++){let s=`${o}-${r[i]}`;if(s.length>gE)break;o=s}return f1.test(o)?o:null}async function Wle(e,t){if(!await Kle(h1(t,e)))return e;let n=Fle(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,gE-5)}-${n}`}async function Kle(e){try{return await $le.access(e),!0}catch{return!1}}function Gle(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function qle(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function y1(e){let t,n,r=h1(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await jle(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),i=t??"unknown",s=n;if(o!==null){let l=`${ap(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return g1(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){i="create-failed",s=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return g1(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:i,...s!==void 0?{detail:s}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function g1(e,t){e&&e.setCwd(t),zle(t)}function zle(e){try{process.chdir(e)}catch{}}Ut();G();import{spawn as w1}from"child_process";import{existsSync as S1,mkdirSync as Qle,readFileSync as v1,unlinkSync as b1,writeFileSync as k1}from"fs";import{get as Zle}from"https";import{join as T1}from"path";import{readFileSync as Jle}from"fs";import{dirname as Yle,join as Vle}from"path";import{fileURLToPath as Xle}from"url";function pr(){try{return"5.
|
|
1749
|
+
`),f1=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,gE=30,Nle=1024,Ble=8e3,Ule="haiku";async function jle(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=Gle(n,Nle),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??Ble),s=t.signal?qle([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await _s({token:t.token,model:t.model??Ule,system:Lle,user:r,maxTokens:32,signal:s})}catch(u){let m=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(i)}let l=Hle(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=Dle(t.worktreePath);return await Wle(l,c)}function Hle(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(f1.test(t)&&t.length<=gE)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(i=>i.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let i=1;i<r.length;i++){let s=`${o}-${r[i]}`;if(s.length>gE)break;o=s}return f1.test(o)?o:null}async function Wle(e,t){if(!await Kle(h1(t,e)))return e;let n=Fle(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,gE-5)}-${n}`}async function Kle(e){try{return await $le.access(e),!0}catch{return!1}}function Gle(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function qle(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function y1(e){let t,n,r=h1(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await jle(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),i=t??"unknown",s=n;if(o!==null){let l=`${ap(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return g1(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){i="create-failed",s=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return g1(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:i,...s!==void 0?{detail:s}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function g1(e,t){e&&e.setCwd(t),zle(t)}function zle(e){try{process.chdir(e)}catch{}}Ut();G();import{spawn as w1}from"child_process";import{existsSync as S1,mkdirSync as Qle,readFileSync as v1,unlinkSync as b1,writeFileSync as k1}from"fs";import{get as Zle}from"https";import{join as T1}from"path";import{readFileSync as Jle}from"fs";import{dirname as Yle,join as Vle}from"path";import{fileURLToPath as Xle}from"url";function pr(){try{return"5.70.0"}catch{}try{let e=Yle(Xle(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(Jle(Vle(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}K();var ece=64*1024,tce=10800*1e3,nce=800,rce=3600*1e3,oce="update-check.json",ice="pending-update.json";function hE(){return T1(ms(),oce)}function tu(){return T1(ms(),ice)}function yE(){let e=ms();S1(e)||Qle(e,{recursive:!0})}function E1(e,t){let n=a=>a.split(/[-+]/,1)[0]??a,r=a=>a.includes("-"),o=n(e).split(".").map(Number),i=n(t).split(".").map(Number),s=Math.max(o.length,i.length);for(let a=0;a<s;a++){let l=o[a]??0,c=i[a]??0;if(c>l)return!0;if(c<l)return!1}return r(e)&&!r(t)}function x1(){try{let e=v1(hE(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function R1(){try{yE();let e=`
|
|
1750
1750
|
const https = require('https');
|
|
1751
1751
|
const fs = require('fs');
|
|
1752
1752
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|