agent-afk 5.22.0 → 5.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  var mg=Object.defineProperty;var ge=(t,e)=>()=>(t&&(e=t(t=0)),e);var qa=(t,e)=>{for(var n in e)mg(t,n,{get:e[n],enumerable:!0})};function ar(t){return ir.find(e=>e.name===t)}function hs(t){return process.env[t]!==void 0}var ir,S,U=ge(()=>{"use strict";ir=[{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_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:"Cap on total tokens per turn (input + output). Default 4096.",type:"number",required:!1,default:"4096",example:"8192",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_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), legacy aliases (opus, sonnet, haiku), the fixed-id fable alias (Claude Fable 5), or full model IDs.",type:"string",required:!1,default:"sonnet",example:"claude-opus-4-5",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_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:"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:"Controls auto-loading of MCP configuration from <cwd>/.mcp.json. Auto-loaded by default \u2014 set to 0 to disable (mitigates config-injection risk in shared/CI environments).",type:"boolean",required:!1,example:"0",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_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_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_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_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:"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"}],S={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_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_MEMORY_EVIDENCE_GATE(){return process.env.AFK_MEMORY_EVIDENCE_GATE},get AFK_MODEL(){return process.env.AFK_MODEL},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_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_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_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},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_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_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 AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let e of ir){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(S,e.name);n&&Object.defineProperty(S,e.name,{...n,enumerable:!1})}})()});function gg(){return S.AFK_DEBUG==="1"||S.DEBUG==="1"}function F(...t){gg()&&console.log(...t)}var oe=ge(()=>{"use strict";U()});import{existsSync as kc,mkdirSync as Fg,renameSync as Lg,cpSync as Ng,rmSync as $g}from"fs";import{join as K,dirname as Ec,isAbsolute as Ac}from"path";import{homedir as xc}from"os";import{fileURLToPath as Ug}from"url";function ce(){let t=S.AFK_HOME;if(t!==void 0&&t!==""){if(!Ac(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return K(xc(),".afk")}function Ae(){return K(ce(),"agent-framework")}function hr(){return K(Ae(),"forge-telemetry.jsonl")}function Tc(){return K(Ae(),"briefs")}function Rc(){return K(Ae(),"facets")}function rn(){return K(ce(),"skills")}function Tt(){return K(ce(),"plugins")}function Pc(t=process.cwd()){return K(t,".afk")}function Ic(t=process.cwd()){return K(Pc(t),"skills")}function Cc(t=process.cwd()){return K(Pc(t),"plugins")}function Mc(t=process.cwd()){return K(t,".afk","plans")}function yr(){return K(Tt(),".index.json")}function Is(){return K(on(),"schedules.json")}function Oc(){let t=Ug(import.meta.url),e=Ec(t);return K(e,"bundled-plugins")}function on(){return K(ce(),"config")}function Ue(){let t=S.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!Ac(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return K(ce(),"state")}function le(){return K(Ue(),"sessions")}function br(){return K(Ue(),"presence")}function wr(){return K(Ue(),"memory")}function Rt(){return K(Ue(),"session-grants.jsonl")}function Dc(){return K(ce(),"farms")}function Fc(t){return K(Dc(),t)}function Sr(t){if(!Bg.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function Lc(t){return Sr(t),K(Ue(),"witness",t)}function Nc(t="default"){return K(Ue(),"daemon",`agent-afk@${t}`)}function $c(){return K(Ue(),"worktree-sweep.lock")}function Cs(){return K(on(),"afk.env")}function Pt(){return K(on(),"afk.config.json")}function vr(){return K(xc(),".afk.config.json")}function jg(){return K(ce(),"sessions")}function Hg(t,e){if(t!==e&&kc(t)&&!kc(e))try{Fg(Ec(e),{recursive:!0});try{Lg(t,e)}catch(n){if(n.code==="EXDEV")try{Ng(t,e,{recursive:!0}),$g(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
2
- `)}}}catch{}}function Uc(){Hg(jg(),le())}function Ms(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>_c)throw new Error(`Invalid browser profile: exceeds ${_c} chars`);if(!Kg.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function Wg(){return K(Ue(),"browser")}function Gg(t){return Ms(t),K(Wg(),t)}function Os(t){return K(Gg(t),"storageState.json")}function sn(t){return typeof t=="string"&&t.length>0&&t.length<=zg&&qg.test(t)}function an(t){if(!sn(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return K(le(),t)}function kr(t){return K(an(t),"events.jsonl")}function Bc(t){return K(an(t),"session.key")}var Bg,Kg,_c,qg,zg,j=ge(()=>{"use strict";U();Bg=/^[a-zA-Z0-9_-]+$/;Kg=/^[A-Za-z0-9_-]+$/,_c=128;qg=/^[A-Za-z0-9_-]+$/,zg=128});import{readFileSync as Ow}from"node:fs";import{join as Dw}from"path";function Fw(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function sd(t,e){return Fw(e).test(t)}function $w(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(Lw.has(e))return!0;if(Nw.has(e))return!1}return!1}function id(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function Uw(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function ad(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Ms(e),e}function Bw(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function jw(t){try{return Ow(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function Hw(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=ad(e.defaultProfile)),n}function cd(t){let e=t?.env??S,n=t?.readFileSync??jw,r=t?.surface??e.AGENT_SURFACE,o=$w(e.AFK_BROWSER_HEADLESS,r),s=id(e.AFK_BROWSER_ALLOWED_DOMAINS),i=id(e.AFK_BROWSER_BLOCKED_DOMAINS),a=Bw(e.AFK_BROWSER_DOM_SNAPSHOTS),c=Uw(e.AFK_BROWSER_BACKEND),l=ad(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():Dw(on(),"browser.json"),f=n(p);if(f===void 0)return d;let g;try{g=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${p}: ${String(y)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${p} must be a JSON object`);let m=Hw(d,g);return m.configPath=p,m}function ii(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(sd(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>sd(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Lw,Nw,ai=ge(()=>{"use strict";U();j();Lw=new Set(["daemon","subagent","telegram","afk"]),Nw=new Set(["repl","interactive","cli"])});import mt from"node:fs";import Xr from"node:path";import{randomBytes as Kw}from"node:crypto";import{chromium as Ww}from"playwright";function Gw(){try{return"5.22.0"}catch{}try{let t=Xr.resolve(import.meta.dirname,"../../../package.json"),e=mt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var qw,Qr,ld=ge(()=>{"use strict";j();oe();qw=Gw(),Qr=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(e){this.config=e}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=Ww.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,e)).catch(e=>{throw this.launchPromise=void 0,e}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),c=await i.content(),l=i.url(),d=a!==null?a.status():null;return{html:c,finalUrl:l,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${qw}`}}loadStorageState(e){let n=Os(e);try{if(!mt.existsSync(n))return;let r=JSON.parse(mt.readFileSync(n,"utf8"));return F("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){F("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Os(e);if(!mt.existsSync(r))return;let o=await n.storageState(),s=Xr.join(Xr.dirname(r),`.${Xr.basename(r)}.${process.pid}.${Kw(4).toString("hex")}.tmp`);mt.writeFileSync(s,JSON.stringify(o),{mode:384}),mt.chmodSync(s,384),mt.renameSync(s,r),F("[browser/vault] saved session",{profile:e,file:r})}catch(r){F("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as zw}from"crypto";function ci(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of Jw)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function dd(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&Vw.test(t.label))}function ud(t){return zw("sha256").update(t,"utf8").digest("hex").slice(0,8)}function pd(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var Jw,Vw,Tn=ge(()=>{"use strict";Jw=[{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}];Vw=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Yw}from"node:crypto";function Xw(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Qw(t,e,n){return`el_${Yw("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function Zw(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function fd(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function gd(t,e){let n=t.role??"",r=t.name??"";md.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])gd(s,e)}async function eS(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},hd).catch(()=>[])}async function tS(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let m=s.type;m==="checkbox"?l="checkbox":m==="radio"?l="radio":m==="button"||m==="submit"||m==="reset"?l="button":m==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,g={role:l,name:c,disabled:p};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},hd).catch(()=>[])}function nS(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Zr(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=nS(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=eS(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,g,m]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],gd(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await tS(t)).filter(L=>md.has(L.role??"")));let k=new Map;for(let _ of p){let L=fd(_.name),B=k.get(L);(!B||B.bbox.w===0&&_.bbox.w>0)&&k.set(L,_)}let C=y.map(_=>({ax:_,dom:k.get(fd(_.name??""))})),h=r?C:C.filter(_=>_.dom?_.dom.bbox.w>0||_.dom.bbox.h>0:!0);h.sort((_,L)=>{let B=_.dom?.bbox.y??0,O=L.dom?.bbox.y??0;if(B!==O)return B-O;let E=_.dom?.bbox.x??0,M=L.dom?.bbox.x??0;return E-M}),h.length>200&&o.push("page has 200+ interactive elements; consider scoping");let x=h.slice(0,n).map((_,L)=>{let B=_.ax.role??"generic",O=_.ax.name??"",E=Qw(B,O,L),M=_.dom?.bbox??{x:0,y:0,w:0,h:0},T=_.dom?.type??null,H=null;_.ax.value!==void 0&&_.ax.value!==null&&(H=String(_.ax.value)),_.ax.checked!==void 0&&(H=String(_.ax.checked)),dd({role:B,kind:T})&&(H="[redacted]");let R={disabled:_.ax.disabled??!1};_.ax.checked!==void 0&&(R.checked=_.ax.checked===!0||_.ax.checked==="mixed"),_.ax.selected!==void 0&&(R.selected=_.ax.selected),_.ax.expanded!==void 0&&(R.expanded=_.ax.expanded);let I;_.dom?.testId?I=`[data-testid="${_.dom.testId}"]`:_.dom?.id&&(I=`#${_.dom.id}`);let z={id:E,role:B,label:Xw(O),kind:T,value:H,state:R,bbox:M};return I!==void 0&&(z.selector=I),z}),w="idle";try{let _=await t.evaluate(()=>document.readyState);_==="loading"?w="loading":_==="interactive"?w="navigating":w="idle"}catch{w="navigating"}w!=="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 D=Zw(f),P=`obs_${e.observationCounter.toString(36)}`,N=new Date().toISOString();return{observationId:P,url:g,title:m,textSummary:D,interactive:x,status:{httpStatus:e.httpStatus??null,loadingState:w,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:N}}var md,hd,yd=ge(()=>{"use strict";Tn();md=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);hd="a[href], button, input, select, textarea, [role], [tabindex], label"});async function bd(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function li(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>bd(t,s)))).filter(o=>o!==null)}async function rS(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function di(t,e,n){switch(e.kind){case"element_id":return oS(t,e,n);case"selector":return sS(t,e);case"semantic":return iS(t,e)}}async function oS(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await li(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function sS(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await li(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function iS(t,e){return e.role!==void 0?aS(t,e.text,e.role):cS(t,e.text,e)}async function aS(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await li(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function cS(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await rS(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let m=u[0];return m===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:m.locator.nth(m.index)}}let p=u.slice(0,5),f=[];for(let m=0;m<p.length;m++){let y=p[m];if(y===void 0)continue;let b=await bd(y.locator,y.index);if(b!==null){let k=`${b.role}:${b.label}:${m}`,C=0;for(let h=0;h<k.length;h++)C=C*31+k.charCodeAt(h)>>>0;f.push({...b,id:`el_${C.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var wd=ge(()=>{"use strict"});import{randomBytes as lS}from"crypto";import{mkdir as dS,stat as uS,writeFile as pS}from"fs/promises";import{join as ui}from"path";import{gzip as fS}from"zlib";import{promisify as mS}from"util";function gS(t){return ui(Lc(t),"browser")}function hS(t){return ui(gS(t),"screenshots")}function yS(){return new Date().toISOString().replace(/[:.]/g,"-")}function bS(){return lS(3).toString("hex")}async function pi(t,e,n){if(e.length>Sd)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Sd} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=hS(t);await dS(r,{recursive:!0});let o=`${yS()}-${bS()}-${n}.png`,s=ui(r,o);await pS(s,e);let{size:i}=await uS(s);return{path:s,bytes:i}}var WM,Sd,vd=ge(()=>{"use strict";j();Tn();WM=mS(fS);Sd=5*1024*1024});var _d={};qa(_d,{PlaywrightProvider:()=>fi});function kd(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var fi,Ed=ge(()=>{"use strict";ld();yd();wd();ai();Tn();vd();fi=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Qr(e)}async open(e){let n=ii(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(l){a=l}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let c=await Zr(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,c.interactive,c.url,c.title,"browser_open"),a!==null)throw a;return c}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Zr(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await di(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${kd(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":{let m=ci(e.value??"");await c.fill(e.value??"");break}case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(m){if(m instanceof Error&&/navigation|net::ERR/i.test(m.message))try{await d()}catch(y){l=y}else l=m}let u=r.url();if(u!==s){let m=ii(u,this.config);if(!m.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:m.reason}}let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Zr(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await di(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${kd(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await pi(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await pi(n,o,r);return s}catch{return null}}}});var ht={};qa(ht,{__resetBrowserRegistryForTests:()=>_S,browserProviderActive:()=>vS,closeBrowserProvider:()=>mi,getBrowserProvider:()=>SS,peekBrowserProvider:()=>kS});function Ad(){Promise.resolve(mi()).then(()=>{process.exit(130)})}function xd(){Promise.resolve(mi()).then(()=>{process.exit(143)})}function Td(){Ce=null}function wS(){eo||(process.on("SIGINT",Ad),process.on("SIGTERM",xd),process.on("exit",Td),eo=!0)}function Rd(){eo&&(process.removeListener("SIGINT",Ad),process.removeListener("SIGTERM",xd),process.removeListener("exit",Td),eo=!1)}async function SS(t){return Ce!==null?Ce:(gt!==null||(gt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Ed(),_d)),n=cd(t),r=new e(n);return wS(),Ce=r,gt=null,r})()),gt)}async function mi(){if(Ce===null)return;let t=Ce;Ce=null,gt=null,Rd(),await t.shutdown()}function vS(){return Ce!==null}function kS(){return Ce}function _S(){Ce=null,gt=null,Rd()}var Ce,gt,eo,yt=ge(()=>{"use strict";ai();Ce=null,gt=null,eo=!1});oe();var pe=class extends Error{constructor(e){super(e),this.name="AbortError"}},Je=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},V=class extends Error{constructor(n,r,o,s){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",s?.cause!==void 0&&(this.cause=s.cause)}event;reason;cause},kt=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};oe();async function _t(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){F(`trace.emit tool_call failed: ${$e(n)}`)}}async function Ne(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){F(`trace.emit hook_decision failed: ${$e(n)}`)}}async function ct(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){F(`trace.emit subagent_lifecycle failed: ${$e(n)}`)}}async function za(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){F(`trace.emit budget failed: ${$e(n)}`)}}async function Ja(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){F(`trace.emit abort failed: ${$e(n)}`)}}async function Va(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){F(`trace.emit compaction failed: ${$e(n)}`)}}async function Ya(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){F(`trace.emit closure failed: ${$e(n)}`)}}async function ne(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){F(`trace.emit browser_event failed: ${$e(n)}`)}}async function ie(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){F(`trace.emit session_phase failed: ${$e(n)}`)}}function $e(t){return t instanceof Error?t.message:String(t)}import Ta from"path";import{appendFileSync as tx,mkdirSync as nx}from"fs";import{dirname as rx}from"path";import Xf from"@anthropic-ai/sdk";var Xa="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",hg="effort-2025-11-24",yg="claude-cli/1.0.0 (external, cli)",bg="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function cr(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function tn(t,e,n,r){let o=e==="oauth"?{authToken:t}:{apiKey:t},s=typeof n=="string"&&n.length>0?{...o,baseURL:n}:o;return r?{...s,fetch:r}:s}function _e(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${Xa},${hg}`:Xa,"x-app":"cli","User-Agent":yg,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Qa(t){return t!=="oauth"?null:[{type:"text",text:bg}]}import kg from"@anthropic-ai/sdk";U();var dr=["local","small","medium","large"],lt={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-5"},large:{id:"claude-opus-4-8"}},ec={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},tc="auto",ws="claude-fable-5",nc={fable:ws},bs;function Ss(t){bs=t}function ys(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function lr(t,e,n){let r={},o=ys(t);o&&(r.id=o);let s=ys(e);s&&(r.baseUrl=s);let i=ys(n);return i&&(r.apiKey=i),r}function wg(){return{local:lr(S.AFK_MODEL_LOCAL,S.AFK_MODEL_LOCAL_BASE_URL,S.AFK_MODEL_LOCAL_API_KEY),small:lr(S.AFK_MODEL_SMALL,S.AFK_MODEL_SMALL_BASE_URL,S.AFK_MODEL_SMALL_API_KEY),medium:lr(S.AFK_MODEL_MEDIUM,S.AFK_MODEL_MEDIUM_BASE_URL,S.AFK_MODEL_MEDIUM_API_KEY),large:lr(S.AFK_MODEL_LARGE,S.AFK_MODEL_LARGE_BASE_URL,S.AFK_MODEL_LARGE_API_KEY)}}function rc(t){let e=wg(),n={};for(let r of dr){let o=lt[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},c=s?.name;c&&(a.name=c);let l=s?.provider;l&&(a.provider=l);let d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function At(t){return t||bs||rc()}function xt(t,e=At()){let n=t.trim().toLowerCase();if(!n||n===tc)return;for(let o of dr){let s=e[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:ec[n]}function vs(t,e=At()){if(t===void 0)return{id:""};let n=xt(t,e);if(n)return e[n];let r=nc[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function Ve(t,e=At()){if(t!==void 0)return vs(t,e).id}function oc(t,e=At()){if(t===void 0)return;let n=xt(t,e);if(n&&e[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 sc(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of dr){let o=vg(n[r]);o&&(e[r]=o)}return e}function ic(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="anthropic"||e==="anthropic-direct")return"anthropic";if(e==="openai"||e==="openai-compatible")return"openai"}function Et(t){return typeof t=="string"?t.trim():""}function Za(t){return/[\x00-\x1f\x7f]/.test(t)}var Sg=new Set([...dr,...Object.keys(ec),tc,...Object.keys(nc)]);function vg(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=Et(e.id);if(!n)return;let r={id:n},o=Et(e.name);o&&(r.name=o);let s=ic(e.provider);s&&(r.provider=s);let i=Et(e.baseUrl);i&&(r.baseUrl=i);let a=Et(e.apiKey);return a&&(r.apiKey=a),r}}function ac(t){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:'model binding must be an object with at least an "id"'};let e=t;if("apiKey"in e||"api_key"in e)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 e||"base_url"in e)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=Et(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(Za(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=Et(e.name);if(o){if(Za(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(Sg.has(o.trim().toLowerCase()))return{ok:!1,error:`model binding "name" must not shadow a built-in alias ("${o}")`};r.name=o}if(e.provider!==void 0&&e.provider!==""){let s=ic(e.provider);if(!s)return{ok:!1,error:'model binding "provider" must be one of: anthropic, openai (aliases: anthropic-direct, openai-compatible)'};r.provider=s}return{ok:!0,value:r}}var ks={opus:lt.large.id,opus_1m:lt.large.id,sonnet:lt.medium.id,sonnet_1m:lt.medium.id,haiku:lt.small.id,fable:ws};function cc(t){return t in ks}function ae(t){return Ve(t)}import{randomUUID as lc}from"node:crypto";async function dc(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let c=cr(e),l=tn(e,c),d=a?a(l):new kg(l),u=lc(),p=lc(),f=_e(c,u,p),g=ae(n)??n,m={};Object.keys(f).length>0&&(m.headers=f),i&&(m.signal=i);let y=await d.messages.create({model:g,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(m).length>0?m:void 0),b=[];for(let C of y.content)C.type==="text"&&b.push(C.text);let k=b.join("").trim();return k.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),k}import{execFileSync as uc}from"child_process";import{existsSync as _g,readFileSync as Eg,writeFileSync as Ag}from"fs";import{homedir as pc,userInfo as fc}from"os";import{join as mc}from"path";var xg="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Tg="https://platform.claude.com/v1/oauth/token",Rg=300*1e3;function he(){let t=gc();if(t===void 0)return;let e=hc(t);if(e!==void 0){if(e.expiresAt!==void 0&&e.expiresAt<=Date.now()){process.stderr.write("agent-afk: Claude Code OAuth token in keychain is expired. Run `claude login` to refresh.\n");return}return e.accessToken}}async function _s(){let t=gc();if(t===void 0)return;let e=hc(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+Rg)return e.accessToken;if(!e.refreshToken){process.stderr.write("agent-afk: OAuth token expired and no refresh token available. Run `claude login` to refresh.\n");return}let n=await Pg(e.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(t)}catch{}let o=r.claudeAiOauth??{};r.claudeAiOauth={...o,accessToken:n.accessToken,expiresAt:n.expiresAt,...n.refreshToken!==void 0?{refreshToken:n.refreshToken}:{}},Ig(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
2
+ `)}}}catch{}}function Uc(){Hg(jg(),le())}function Ms(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>_c)throw new Error(`Invalid browser profile: exceeds ${_c} chars`);if(!Kg.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function Wg(){return K(Ue(),"browser")}function Gg(t){return Ms(t),K(Wg(),t)}function Os(t){return K(Gg(t),"storageState.json")}function sn(t){return typeof t=="string"&&t.length>0&&t.length<=zg&&qg.test(t)}function an(t){if(!sn(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return K(le(),t)}function kr(t){return K(an(t),"events.jsonl")}function Bc(t){return K(an(t),"session.key")}var Bg,Kg,_c,qg,zg,j=ge(()=>{"use strict";U();Bg=/^[a-zA-Z0-9_-]+$/;Kg=/^[A-Za-z0-9_-]+$/,_c=128;qg=/^[A-Za-z0-9_-]+$/,zg=128});import{readFileSync as Ow}from"node:fs";import{join as Dw}from"path";function Fw(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function sd(t,e){return Fw(e).test(t)}function $w(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(Lw.has(e))return!0;if(Nw.has(e))return!1}return!1}function id(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function Uw(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function ad(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Ms(e),e}function Bw(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function jw(t){try{return Ow(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function Hw(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=ad(e.defaultProfile)),n}function cd(t){let e=t?.env??S,n=t?.readFileSync??jw,r=t?.surface??e.AGENT_SURFACE,o=$w(e.AFK_BROWSER_HEADLESS,r),s=id(e.AFK_BROWSER_ALLOWED_DOMAINS),i=id(e.AFK_BROWSER_BLOCKED_DOMAINS),a=Bw(e.AFK_BROWSER_DOM_SNAPSHOTS),c=Uw(e.AFK_BROWSER_BACKEND),l=ad(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():Dw(on(),"browser.json"),f=n(p);if(f===void 0)return d;let g;try{g=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${p}: ${String(y)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${p} must be a JSON object`);let m=Hw(d,g);return m.configPath=p,m}function ii(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(sd(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>sd(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Lw,Nw,ai=ge(()=>{"use strict";U();j();Lw=new Set(["daemon","subagent","telegram","afk"]),Nw=new Set(["repl","interactive","cli"])});import mt from"node:fs";import Xr from"node:path";import{randomBytes as Kw}from"node:crypto";import{chromium as Ww}from"playwright";function Gw(){try{return"5.23.1"}catch{}try{let t=Xr.resolve(import.meta.dirname,"../../../package.json"),e=mt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var qw,Qr,ld=ge(()=>{"use strict";j();oe();qw=Gw(),Qr=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(e){this.config=e}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=Ww.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,e)).catch(e=>{throw this.launchPromise=void 0,e}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),c=await i.content(),l=i.url(),d=a!==null?a.status():null;return{html:c,finalUrl:l,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${qw}`}}loadStorageState(e){let n=Os(e);try{if(!mt.existsSync(n))return;let r=JSON.parse(mt.readFileSync(n,"utf8"));return F("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){F("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Os(e);if(!mt.existsSync(r))return;let o=await n.storageState(),s=Xr.join(Xr.dirname(r),`.${Xr.basename(r)}.${process.pid}.${Kw(4).toString("hex")}.tmp`);mt.writeFileSync(s,JSON.stringify(o),{mode:384}),mt.chmodSync(s,384),mt.renameSync(s,r),F("[browser/vault] saved session",{profile:e,file:r})}catch(r){F("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as zw}from"crypto";function ci(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of Jw)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function dd(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&Vw.test(t.label))}function ud(t){return zw("sha256").update(t,"utf8").digest("hex").slice(0,8)}function pd(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var Jw,Vw,Tn=ge(()=>{"use strict";Jw=[{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}];Vw=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Yw}from"node:crypto";function Xw(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Qw(t,e,n){return`el_${Yw("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function Zw(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function fd(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function gd(t,e){let n=t.role??"",r=t.name??"";md.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])gd(s,e)}async function eS(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},hd).catch(()=>[])}async function tS(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let m=s.type;m==="checkbox"?l="checkbox":m==="radio"?l="radio":m==="button"||m==="submit"||m==="reset"?l="button":m==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,g={role:l,name:c,disabled:p};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},hd).catch(()=>[])}function nS(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Zr(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=nS(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=eS(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,g,m]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],gd(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await tS(t)).filter(L=>md.has(L.role??"")));let k=new Map;for(let _ of p){let L=fd(_.name),B=k.get(L);(!B||B.bbox.w===0&&_.bbox.w>0)&&k.set(L,_)}let C=y.map(_=>({ax:_,dom:k.get(fd(_.name??""))})),h=r?C:C.filter(_=>_.dom?_.dom.bbox.w>0||_.dom.bbox.h>0:!0);h.sort((_,L)=>{let B=_.dom?.bbox.y??0,O=L.dom?.bbox.y??0;if(B!==O)return B-O;let E=_.dom?.bbox.x??0,M=L.dom?.bbox.x??0;return E-M}),h.length>200&&o.push("page has 200+ interactive elements; consider scoping");let x=h.slice(0,n).map((_,L)=>{let B=_.ax.role??"generic",O=_.ax.name??"",E=Qw(B,O,L),M=_.dom?.bbox??{x:0,y:0,w:0,h:0},T=_.dom?.type??null,H=null;_.ax.value!==void 0&&_.ax.value!==null&&(H=String(_.ax.value)),_.ax.checked!==void 0&&(H=String(_.ax.checked)),dd({role:B,kind:T})&&(H="[redacted]");let R={disabled:_.ax.disabled??!1};_.ax.checked!==void 0&&(R.checked=_.ax.checked===!0||_.ax.checked==="mixed"),_.ax.selected!==void 0&&(R.selected=_.ax.selected),_.ax.expanded!==void 0&&(R.expanded=_.ax.expanded);let I;_.dom?.testId?I=`[data-testid="${_.dom.testId}"]`:_.dom?.id&&(I=`#${_.dom.id}`);let z={id:E,role:B,label:Xw(O),kind:T,value:H,state:R,bbox:M};return I!==void 0&&(z.selector=I),z}),w="idle";try{let _=await t.evaluate(()=>document.readyState);_==="loading"?w="loading":_==="interactive"?w="navigating":w="idle"}catch{w="navigating"}w!=="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 D=Zw(f),P=`obs_${e.observationCounter.toString(36)}`,N=new Date().toISOString();return{observationId:P,url:g,title:m,textSummary:D,interactive:x,status:{httpStatus:e.httpStatus??null,loadingState:w,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:N}}var md,hd,yd=ge(()=>{"use strict";Tn();md=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);hd="a[href], button, input, select, textarea, [role], [tabindex], label"});async function bd(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function li(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>bd(t,s)))).filter(o=>o!==null)}async function rS(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function di(t,e,n){switch(e.kind){case"element_id":return oS(t,e,n);case"selector":return sS(t,e);case"semantic":return iS(t,e)}}async function oS(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await li(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function sS(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await li(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function iS(t,e){return e.role!==void 0?aS(t,e.text,e.role):cS(t,e.text,e)}async function aS(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await li(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function cS(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await rS(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let m=u[0];return m===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:m.locator.nth(m.index)}}let p=u.slice(0,5),f=[];for(let m=0;m<p.length;m++){let y=p[m];if(y===void 0)continue;let b=await bd(y.locator,y.index);if(b!==null){let k=`${b.role}:${b.label}:${m}`,C=0;for(let h=0;h<k.length;h++)C=C*31+k.charCodeAt(h)>>>0;f.push({...b,id:`el_${C.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var wd=ge(()=>{"use strict"});import{randomBytes as lS}from"crypto";import{mkdir as dS,stat as uS,writeFile as pS}from"fs/promises";import{join as ui}from"path";import{gzip as fS}from"zlib";import{promisify as mS}from"util";function gS(t){return ui(Lc(t),"browser")}function hS(t){return ui(gS(t),"screenshots")}function yS(){return new Date().toISOString().replace(/[:.]/g,"-")}function bS(){return lS(3).toString("hex")}async function pi(t,e,n){if(e.length>Sd)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Sd} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=hS(t);await dS(r,{recursive:!0});let o=`${yS()}-${bS()}-${n}.png`,s=ui(r,o);await pS(s,e);let{size:i}=await uS(s);return{path:s,bytes:i}}var WM,Sd,vd=ge(()=>{"use strict";j();Tn();WM=mS(fS);Sd=5*1024*1024});var _d={};qa(_d,{PlaywrightProvider:()=>fi});function kd(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var fi,Ed=ge(()=>{"use strict";ld();yd();wd();ai();Tn();vd();fi=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Qr(e)}async open(e){let n=ii(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(l){a=l}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let c=await Zr(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,c.interactive,c.url,c.title,"browser_open"),a!==null)throw a;return c}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Zr(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await di(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${kd(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":{let m=ci(e.value??"");await c.fill(e.value??"");break}case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(m){if(m instanceof Error&&/navigation|net::ERR/i.test(m.message))try{await d()}catch(y){l=y}else l=m}let u=r.url();if(u!==s){let m=ii(u,this.config);if(!m.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:m.reason}}let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Zr(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await di(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${kd(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await pi(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await pi(n,o,r);return s}catch{return null}}}});var ht={};qa(ht,{__resetBrowserRegistryForTests:()=>_S,browserProviderActive:()=>vS,closeBrowserProvider:()=>mi,getBrowserProvider:()=>SS,peekBrowserProvider:()=>kS});function Ad(){Promise.resolve(mi()).then(()=>{process.exit(130)})}function xd(){Promise.resolve(mi()).then(()=>{process.exit(143)})}function Td(){Ce=null}function wS(){eo||(process.on("SIGINT",Ad),process.on("SIGTERM",xd),process.on("exit",Td),eo=!0)}function Rd(){eo&&(process.removeListener("SIGINT",Ad),process.removeListener("SIGTERM",xd),process.removeListener("exit",Td),eo=!1)}async function SS(t){return Ce!==null?Ce:(gt!==null||(gt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Ed(),_d)),n=cd(t),r=new e(n);return wS(),Ce=r,gt=null,r})()),gt)}async function mi(){if(Ce===null)return;let t=Ce;Ce=null,gt=null,Rd(),await t.shutdown()}function vS(){return Ce!==null}function kS(){return Ce}function _S(){Ce=null,gt=null,Rd()}var Ce,gt,eo,yt=ge(()=>{"use strict";ai();Ce=null,gt=null,eo=!1});oe();var pe=class extends Error{constructor(e){super(e),this.name="AbortError"}},Je=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},V=class extends Error{constructor(n,r,o,s){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",s?.cause!==void 0&&(this.cause=s.cause)}event;reason;cause},kt=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};oe();async function _t(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){F(`trace.emit tool_call failed: ${$e(n)}`)}}async function Ne(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){F(`trace.emit hook_decision failed: ${$e(n)}`)}}async function ct(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){F(`trace.emit subagent_lifecycle failed: ${$e(n)}`)}}async function za(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){F(`trace.emit budget failed: ${$e(n)}`)}}async function Ja(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){F(`trace.emit abort failed: ${$e(n)}`)}}async function Va(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){F(`trace.emit compaction failed: ${$e(n)}`)}}async function Ya(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){F(`trace.emit closure failed: ${$e(n)}`)}}async function ne(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){F(`trace.emit browser_event failed: ${$e(n)}`)}}async function ie(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){F(`trace.emit session_phase failed: ${$e(n)}`)}}function $e(t){return t instanceof Error?t.message:String(t)}import Ta from"path";import{appendFileSync as tx,mkdirSync as nx}from"fs";import{dirname as rx}from"path";import Xf from"@anthropic-ai/sdk";var Xa="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",hg="effort-2025-11-24",yg="claude-cli/1.0.0 (external, cli)",bg="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function cr(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function tn(t,e,n,r){let o=e==="oauth"?{authToken:t}:{apiKey:t},s=typeof n=="string"&&n.length>0?{...o,baseURL:n}:o;return r?{...s,fetch:r}:s}function _e(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${Xa},${hg}`:Xa,"x-app":"cli","User-Agent":yg,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Qa(t){return t!=="oauth"?null:[{type:"text",text:bg}]}import kg from"@anthropic-ai/sdk";U();var dr=["local","small","medium","large"],lt={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-5"},large:{id:"claude-opus-4-8"}},ec={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},tc="auto",ws="claude-fable-5",nc={fable:ws},bs;function Ss(t){bs=t}function ys(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function lr(t,e,n){let r={},o=ys(t);o&&(r.id=o);let s=ys(e);s&&(r.baseUrl=s);let i=ys(n);return i&&(r.apiKey=i),r}function wg(){return{local:lr(S.AFK_MODEL_LOCAL,S.AFK_MODEL_LOCAL_BASE_URL,S.AFK_MODEL_LOCAL_API_KEY),small:lr(S.AFK_MODEL_SMALL,S.AFK_MODEL_SMALL_BASE_URL,S.AFK_MODEL_SMALL_API_KEY),medium:lr(S.AFK_MODEL_MEDIUM,S.AFK_MODEL_MEDIUM_BASE_URL,S.AFK_MODEL_MEDIUM_API_KEY),large:lr(S.AFK_MODEL_LARGE,S.AFK_MODEL_LARGE_BASE_URL,S.AFK_MODEL_LARGE_API_KEY)}}function rc(t){let e=wg(),n={};for(let r of dr){let o=lt[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},c=s?.name;c&&(a.name=c);let l=s?.provider;l&&(a.provider=l);let d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function At(t){return t||bs||rc()}function xt(t,e=At()){let n=t.trim().toLowerCase();if(!n||n===tc)return;for(let o of dr){let s=e[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:ec[n]}function vs(t,e=At()){if(t===void 0)return{id:""};let n=xt(t,e);if(n)return e[n];let r=nc[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function Ve(t,e=At()){if(t!==void 0)return vs(t,e).id}function oc(t,e=At()){if(t===void 0)return;let n=xt(t,e);if(n&&e[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 sc(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of dr){let o=vg(n[r]);o&&(e[r]=o)}return e}function ic(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="anthropic"||e==="anthropic-direct")return"anthropic";if(e==="openai"||e==="openai-compatible")return"openai"}function Et(t){return typeof t=="string"?t.trim():""}function Za(t){return/[\x00-\x1f\x7f]/.test(t)}var Sg=new Set([...dr,...Object.keys(ec),tc,...Object.keys(nc)]);function vg(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=Et(e.id);if(!n)return;let r={id:n},o=Et(e.name);o&&(r.name=o);let s=ic(e.provider);s&&(r.provider=s);let i=Et(e.baseUrl);i&&(r.baseUrl=i);let a=Et(e.apiKey);return a&&(r.apiKey=a),r}}function ac(t){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:'model binding must be an object with at least an "id"'};let e=t;if("apiKey"in e||"api_key"in e)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 e||"base_url"in e)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=Et(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(Za(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=Et(e.name);if(o){if(Za(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(Sg.has(o.trim().toLowerCase()))return{ok:!1,error:`model binding "name" must not shadow a built-in alias ("${o}")`};r.name=o}if(e.provider!==void 0&&e.provider!==""){let s=ic(e.provider);if(!s)return{ok:!1,error:'model binding "provider" must be one of: anthropic, openai (aliases: anthropic-direct, openai-compatible)'};r.provider=s}return{ok:!0,value:r}}var ks={opus:lt.large.id,opus_1m:lt.large.id,sonnet:lt.medium.id,sonnet_1m:lt.medium.id,haiku:lt.small.id,fable:ws};function cc(t){return t in ks}function ae(t){return Ve(t)}import{randomUUID as lc}from"node:crypto";async function dc(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let c=cr(e),l=tn(e,c),d=a?a(l):new kg(l),u=lc(),p=lc(),f=_e(c,u,p),g=ae(n)??n,m={};Object.keys(f).length>0&&(m.headers=f),i&&(m.signal=i);let y=await d.messages.create({model:g,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(m).length>0?m:void 0),b=[];for(let C of y.content)C.type==="text"&&b.push(C.text);let k=b.join("").trim();return k.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),k}import{execFileSync as uc}from"child_process";import{existsSync as _g,readFileSync as Eg,writeFileSync as Ag}from"fs";import{homedir as pc,userInfo as fc}from"os";import{join as mc}from"path";var xg="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Tg="https://platform.claude.com/v1/oauth/token",Rg=300*1e3;function he(){let t=gc();if(t===void 0)return;let e=hc(t);if(e!==void 0){if(e.expiresAt!==void 0&&e.expiresAt<=Date.now()){process.stderr.write("agent-afk: Claude Code OAuth token in keychain is expired. Run `claude login` to refresh.\n");return}return e.accessToken}}async function _s(){let t=gc();if(t===void 0)return;let e=hc(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+Rg)return e.accessToken;if(!e.refreshToken){process.stderr.write("agent-afk: OAuth token expired and no refresh token available. Run `claude login` to refresh.\n");return}let n=await Pg(e.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(t)}catch{}let o=r.claudeAiOauth??{};r.claudeAiOauth={...o,accessToken:n.accessToken,expiresAt:n.expiresAt,...n.refreshToken!==void 0?{refreshToken:n.refreshToken}:{}},Ig(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
3
3
  `)}return n.accessToken}function gc(){if(process.platform==="darwin")try{return uc("security",["find-generic-password","-s","Claude Code-credentials","-a",fc().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=mc(pc(),".claude",".credentials.json");if(!_g(t))return;try{return Eg(t,"utf-8")}catch{return}}}function hc(t){let e;try{e=JSON.parse(t)}catch{return}if(typeof e!="object"||e===null)return;let n=e.claudeAiOauth;if(typeof n!="object"||n===null)return;let r=n,o=r.accessToken;if(typeof o!="string"||o.length===0)return;let s={accessToken:o},i=r.refreshToken;typeof i=="string"&&i.length>0&&(s.refreshToken=i);let a=r.expiresAt;return typeof a=="number"&&(s.expiresAt=a),s}async function Pg(t){try{let e=await fetch(Tg,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:xg})});if(!e.ok)return;let n=await e.json(),r=n.access_token,o=n.expires_in;if(typeof r!="string"||typeof o!="number")return;let s=n.refresh_token;return{accessToken:r,expiresAt:Date.now()+o*1e3,...typeof s=="string"&&s.length>0?{refreshToken:s}:{}}}catch{return}}function nn(t){if(!t||t.length<3)return"token:(unknown)";try{let n=t.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),s=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(s)return s}catch{}return`token:${t.length>=8?t.slice(-8):t}`}function Ig(t){if(process.platform==="darwin")uc("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",fc().username,"-w",t],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let e=mc(pc(),".claude",".credentials.json");Cg(e,t)}}function Cg(t,e){Ag(t,e,{encoding:"utf-8",mode:384})}function Es(t){if(t===null||typeof t!="object")return;let e=t.headers;if(e==null)return;let n=s=>{if(typeof e.get=="function")return e.get(s)??void 0;if(typeof e=="object"){let a=e,c=a[s]??a[s.toUpperCase()];return typeof c=="string"?c:void 0}},r=n("retry-after-ms");if(r!==void 0){let s=Number(r);if(Number.isFinite(s)&&s>=0)return s}let o=n("retry-after");if(o!==void 0){let s=Number(o);if(Number.isFinite(s)&&s>=0)return Math.round(s*1e3);let i=Date.parse(o);if(!Number.isNaN(i)){let a=i-Date.now();if(a>=0)return a}}}function ur(t){if(!("status"in t))return null;let e=t.status;if(e===429){let n=t.message.split("|");if(n.length>=2){let o=parseInt(n[1].trim(),10);if(!isNaN(o)&&o>0)return{kind:"oauth-limit",resetsAt:new Date(o*1e3)}}let r=Es(t);return r!==void 0?{kind:"rate-limit-transient",retryAfterMs:r}:{kind:"oauth-limit-no-ts"}}return e===400&&t.message.includes("invalid_request_error")&&t.message.includes("credit balance")?{kind:"credit-exhausted"}:null}async function yc(t){let{resetsAt:e,signal:n,readToken:r=he}=t,o=r(),s=e.getTime()+3e4;return new Promise(i=>{let a,c=!1,l=p=>{c||(c=!0,a!==void 0&&clearInterval(a),n.removeEventListener("abort",d),i(p))},d=()=>{l("aborted")},u=()=>n.aborted?(l("aborted"),!0):Date.now()>=s?(l("timer"),!0):r()!==o?(l("hot-swap"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),n.addEventListener("abort",d,{once:!0}))})}async function bc(t){let{signal:e,readToken:n=he,retryAfterMs:r}=t,o=n(),s=r!==void 0?Date.now()+r:void 0;return new Promise(i=>{let a,c=!1,l=p=>{c||(c=!0,a!==void 0&&clearInterval(a),e.removeEventListener("abort",d),i(p))},d=()=>{l("aborted")},u=()=>e.aborted?(l("aborted"),!0):n()!==o?(l("hot-swap"),!0):s!==void 0&&Date.now()>=s?(l("timer"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),e.addEventListener("abort",d,{once:!0}))})}var Mg=new Set([429,503,529]);function As(t,e=fetch){return t?async(n,r)=>{let o=await e(n,r);if(Mg.has(o.status)){let s=Es({headers:o.headers}),i={status:o.status,reason:o.status===429?"rate-limit":"overloaded",source:"sdk-fetch"};s!==void 0&&(i.retryAfterMs=s),ie(t,{phase:"rate_limit",...s!==void 0?{durationMs:s}:{},metadata:i})}return o}:e}import{randomUUID as Jf}from"node:crypto";function Ee(t){return t==="bypassPermissions"||t==="autonomous"}U();var Og="1h";function pr(t){if(typeof t?.baseUrl=="string"&&t.baseUrl.length>0)return!1;let e=S.AFK_DISABLE_PROMPT_CACHE;if(e===void 0||e.length===0)return!0;let n=e.toLowerCase();return!(n==="1"||n==="true"||n==="yes"||n==="on")}function fr(){let t=S.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":t==="1h"?"1h":Og}function wc(t,e){if(t.length===0)return t;let n=t[t.length-1],r=vc(n,e);return r===n?t:[...t.slice(0,-1),r]}function Sc(t,e){if(t.length===0)return t;let n=t[t.length-1],r=Dg(n,e);return r===n?t:[...t.slice(0,-1),r]}function Dg(t,e){let n=t.content;if(typeof n=="string")return n.length===0?t:{...t,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:e}}]};if(!Array.isArray(n)||n.length===0)return t;let r=n[n.length-1],o=vc(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function vc(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}var mr=["## 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(`
4
4
  `);function xs(t){return t!=="plan"?null:{type:"text",text:mr}}var gr=["## 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(`
5
5
  `);function Ts(t){return t!=="autonomous"?null:{type:"text",text:gr}}function Rs(t,e=()=>{}){let n=new Set;if(!t)return n;for(let r of t.split(",")){let o=r.trim();if(o){if(!/^-?\d+$/.test(o)){e("[allowlist] Ignoring non-numeric chat ID:",o);continue}n.add(Number(o))}}return n}function Ps(t,e=()=>{}){return async(n,r)=>{let o=n.chat?.id;if(o===void 0||!t.has(o)){e("[allowlist] Rejecting update from chat:",o??"<unknown>");return}await r()}}import{readFileSync as th,existsSync as nh}from"fs";import{join as zc}from"path";import{config as hP}from"dotenv";j();U();function jc(){return S.ANTHROPIC_API_KEY||S.CLAUDE_CODE_OAUTH_TOKEN||he()}function Hc(){return S.OPENAI_API_KEY||S.CODEX_API_KEY||void 0}function It(t){let e=Z(t);return e==="openai-compatible"||e==="openai-codex"?Hc():jc()}U();import{execFile as Jg}from"node:child_process";import{promisify as Vg}from"node:util";U();j();U();var eP=Vg(Jg);var Yg=/^[A-Za-z0-9_\-./]*$/,Kc=64;function Wc(t,e){if(t.length>Kc)throw new Error(`Invalid branch prefix from ${e}: length ${t.length} exceeds ${Kc}.`);if(!Yg.test(t))throw new Error(`Invalid branch prefix from ${e}: '${t}' \u2014 only [A-Za-z0-9_-./] are allowed.`);if(t.startsWith("-"))throw new Error(`Invalid branch prefix from ${e}: '${t}' \u2014 must not start with '-' (would be parsed by git as a flag).`);return t}function Gc(t,e){if(t.trim().length===0)throw new Error(`Invalid worktree base ref from ${e}: '' \u2014 base ref cannot be empty.`);if(t.startsWith("-"))throw new Error(`Invalid worktree base ref from ${e}: '${t}' \u2014 must not start with '-' (would be parsed by git as a flag).`);if(t.includes("\0"))throw new Error(`Invalid worktree base ref from ${e}: contains a NUL byte.`);if(/\s/.test(t))throw new Error(`Invalid worktree base ref from ${e}: '${t}' \u2014 must not contain whitespace.`)}U();j();import{existsSync as _r,readdirSync as rP,readFileSync as Xg,realpathSync as oP,statSync as sP}from"fs";import{homedir as Qg}from"os";import{join as Ye}from"path";var qc=["claude-code","codex"],Ds={"claude-code":{label:"Claude Code",pluginRoots:t=>[Ye(t,".claude","plugins")],skillRoots:t=>[Ye(t,".claude","skills")],mcpConfigCandidates:t=>[Ye(t,".claude","mcp.json"),Ye(t,".claude",".mcp.json"),Ye(t,".claude","claude-code","mcp.json")],mcpFormat:"json"},codex:{label:"Codex",pluginRoots:t=>[Ye(t,".codex","plugins")],skillRoots:t=>[Ye(t,".codex","skills")],mcpConfigCandidates:t=>[Ye(t,".codex","config.toml")],mcpFormat:"toml"}},lP={"claude-code":Ds["claude-code"].label,codex:Ds.codex.label};function Fs(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e={};for(let n of qc){let r=t[n];if(r!==void 0){if(r===!0){e[n]={plugins:!0,skills:!0,mcp:!0};continue}if(r!==!1&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=r;e[n]={plugins:o.plugins===!0,skills:o.skills===!0,mcp:o.mcp===!0}}}}return Object.keys(e).length>0?e:void 0}function Zg(){return[Pt(),vr()]}function Ls(t=Zg()){for(let e of t)if(_r(e))try{let n=JSON.parse(Xg(e,"utf-8")),r=Fs(n.importFrom);if(r!==void 0)return r}catch{}}function Ns(t,e=Qg()){let n={pluginRoots:[],skillRoots:[],mcpConfigs:[]};if(!t)return n;for(let r of qc){let o=t[r];if(!o)continue;let s=Ds[r];if(o.plugins)for(let i of s.pluginRoots(e))_r(i)&&n.pluginRoots.push(i);if(o.skills){let i=`imported:${r}`;for(let a of s.skillRoots(e))_r(a)&&n.skillRoots.push({dir:a,origin:i})}if(o.mcp){let i=eh(s.mcpConfigCandidates(e));i&&n.mcpConfigs.push({source:i,format:s.mcpFormat})}}return n}function eh(t){for(let e of t)if(_r(e))return e;return null}var Ct;function rh(){if(Ct!==void 0)return Ct;let t=[zc(process.cwd(),"afk.config.json"),Pt(),vr()];for(let e of t)if(nh(e))try{let n=th(e,"utf-8"),r=JSON.parse(n),o={},s=sc(r.models);if(typeof r.model=="string"&&r.model.length>0){let i=r.model.toLowerCase();o.model=cc(i)?i:r.model}if(typeof r.maxTokens=="number"&&(o.maxTokens=r.maxTokens),typeof r.temperature=="number"&&(o.temperature=r.temperature),r.systemPrompt&&(o.systemPrompt=r.systemPrompt),typeof r.permissionMode=="string"){let i=r.permissionMode;(i==="default"||i==="plan"||i==="autonomous"||i==="bypassPermissions")&&(o.permissionMode=i)}if(r.autoRouting&&typeof r.autoRouting=="object"){let i={};typeof r.autoRouting.interactive=="boolean"&&(i.interactive=r.autoRouting.interactive),typeof r.autoRouting.chat=="boolean"&&(i.chat=r.autoRouting.chat),typeof r.autoRouting.telegram=="boolean"&&(i.telegram=r.autoRouting.telegram),typeof r.autoRouting.daemon=="boolean"&&(i.daemon=r.autoRouting.daemon),o.autoRouting=i}if(r.daemon&&typeof r.daemon=="object"){let i={};typeof r.daemon.task=="string"&&(i.task=r.daemon.task),typeof r.daemon.taskId=="string"&&(i.taskId=r.daemon.taskId);let a=r.daemon.worktreePrune;a&&typeof a=="object"&&(i.worktreePrune={enabled:typeof a.enabled=="boolean"?a.enabled:!0,cron:typeof a.cron=="string"?a.cron:"0 4 * * *",maxAgeDaysClean:typeof a.maxAgeDaysClean=="number"?a.maxAgeDaysClean:14,maxAgeDaysDirty:typeof a.maxAgeDaysDirty=="number"?a.maxAgeDaysDirty:30,scope:typeof a.scope=="string"?a.scope:"all"}),o.daemon=i}if(r.telegram&&typeof r.telegram=="object"){let i={},a=r.telegram.notify;if(a&&typeof a=="object"){let c={};if((a.mode==="primary"||a.mode==="broadcast"||a.mode==="custom")&&(c.mode=a.mode),typeof a.primaryChatId=="number"&&Number.isFinite(a.primaryChatId)&&(c.primaryChatId=a.primaryChatId),Array.isArray(a.targets)){let l=a.targets.filter(d=>typeof d=="number"&&Number.isFinite(d));l.length>0&&(c.targets=l)}i.notify=c}typeof r.telegram.verifyDone=="boolean"&&(i.verifyDone=r.telegram.verifyDone),o.telegram=i}if(r.updatePolicy&&["notify","auto","off"].includes(r.updatePolicy)&&(o.updatePolicy=r.updatePolicy),typeof r.autoResumeOnUsageLimit=="boolean"&&(o.autoResumeOnUsageLimit=r.autoResumeOnUsageLimit),typeof r.bgSummaries=="boolean"&&(o.bgSummaries=r.bgSummaries),typeof r.maxSummaryCallsPerSession=="number"&&(o.maxSummaryCallsPerSession=Math.min(500,Math.max(1,r.maxSummaryCallsPerSession))),r.hooks!==null&&typeof r.hooks=="object"&&!Array.isArray(r.hooks)&&(o.hooks=r.hooks),typeof r.enableShellHooks=="boolean"&&(o.enableShellHooks=r.enableShellHooks),e!==zc(process.cwd(),"afk.config.json")){let i=Fs(r.importFrom);i!==void 0&&(o.importFrom=i)}if(r.interactive&&typeof r.interactive=="object"){let i={};typeof r.interactive.worktreeAutoname=="boolean"&&(i.worktreeAutoname=r.interactive.worktreeAutoname),typeof r.interactive.worktreeBranchPrefix=="string"&&(i.worktreeBranchPrefix=Wc(r.interactive.worktreeBranchPrefix,`${e}#/interactive/worktreeBranchPrefix`)),typeof r.interactive.worktreeBase=="string"&&r.interactive.worktreeBase.trim().length>0&&(Gc(r.interactive.worktreeBase,`${e}#/interactive/worktreeBase`),i.worktreeBase=r.interactive.worktreeBase),typeof r.interactive.suggestGhost=="boolean"&&(i.suggestGhost=r.interactive.suggestGhost),Object.keys(i).length>0&&(o.interactive=i)}return Ct={config:o,sourcePath:e,modelsPartial:s},Ct}catch(n){console.error(`Warning: Failed to parse ${e}:`,n)}return Ct={config:{},sourcePath:void 0,modelsPartial:{}},Ct}function Jc(){return rh().config.telegram??{}}U();function oh(t,e){return e!==void 0&&Number.isFinite(e)&&e!==0?e:t.find(r=>r>0)??t[0]}function sh(t,e={}){let n=[...t],r=e.mode??"primary";if(r==="broadcast")return n;if(r==="custom"){let s=(e.targets??[]).filter(i=>typeof i=="number"&&Number.isFinite(i)&&i!==0);if(s.length>0)return[...new Set(s)]}let o=oh(n,e.primaryChatId);return o!==void 0?[o]:[]}function ih(t){if(!t)return;let e=t.trim();if(!/^-?\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)&&n!==0?n:void 0}function ah(t){if(!t)return;let e=t.trim().toLowerCase();return e==="primary"||e==="broadcast"||e==="custom"?e:void 0}function ch(){let t=Jc().notify??{},e=t.mode??ah(S.AFK_TELEGRAM_NOTIFY_MODE),n=t.primaryChatId??ih(S.AFK_TELEGRAM_PRIMARY_CHAT_ID);return{...e!==void 0?{mode:e}:{},...n!==void 0?{primaryChatId:n}:{},...t.targets!==void 0?{targets:t.targets}:{}}}function Er(){let t=Rs(S.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return sh(t,ch())}function de(t,e=4096){if(t.length<=e)return[t];let n=[],r=t;for(;r.length>0;){if(r.length<=e){n.push(r);break}let o=e,s=r.lastIndexOf(`
@@ -886,7 +886,7 @@ Be terse and operational. The user is doing one-time setup; they want it done, n
886
886
  `}};function Q(t){let e=ol[t];if(!e){let n=Object.keys(ol).sort(),r=n.length>0?"Available: "+n.join(", "):"";throw new Error("Unknown skill: "+t+". "+r)}return e}function Hs(t,e){return e?!0:(t.audience??"public")==="public"}var Ot=new Map;function re(t){Ot.set(t.name,t)}function ye(t){let e=Ot.get(t);if(e)return e;let n=Array.from(Ot.keys()).sort(),r=n.length>0?`
887
887
  Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${t}${r}`)}function Pr(){return Array.from(Ot.keys()).sort()}function sl(t){let e=0;for(let[n,r]of Ot)r.origin===t&&(Ot.delete(n),e++);return e}var fn=class{nodes=new Map;traceWriter;constructor(e){this.traceWriter=e}register(e,n){this.nodes.has(e)||this.nodes.set(e,{controller:n,children:new Set,listeners:new Set,cascading:!1})}has(e){return this.nodes.has(e)}getController(e){return this.nodes.get(e)?.controller}childrenOf(e){let n=this.nodes.get(e);return n?Array.from(n.children):[]}linkChild(e,n){let r=this.nodes.get(e),o=this.nodes.get(n);if(!r)throw new Error(`AbortGraph: parent ${e} not registered`);if(!o)throw new Error(`AbortGraph: child ${n} not registered`);if(o.parentId=e,r.children.add(n),r.controller.signal.aborted){o.controller.signal.aborted||(o.cascading=!0,o.controller.abort(r.controller.signal.reason));return}r.controller.signal.addEventListener("abort",()=>{let s=this.nodes.get(n);!s||s.parentId!==e||s.controller.signal.aborted||(s.cascading=!0,s.controller.abort(r.controller.signal.reason))},{once:!0}),o.controller.signal.addEventListener("abort",()=>{let s=this.nodes.get(n);if(!s||s.parentId!==e||s.cascading)return;let i=this.nodes.get(e);if(!i)return;let a={parentId:e,childId:n,reason:s.controller.signal.reason};for(let c of i.listeners)try{c(a)}catch{}},{once:!0})}onChildAborted(e,n){let r=this.nodes.get(e);if(!r)throw new Error(`AbortGraph: ${e} not registered`);return r.listeners.add(n),()=>{r.listeners.delete(n)}}abort(e,n,r="user_signal"){let o=this.nodes.get(e);if(!o||o.controller.signal.aborted)return;let s=[],i=[...o.children],a=new Set;for(;i.length;){let c=i.shift();if(a.has(c))continue;a.add(c);let l=this.nodes.get(c);if(l){l.cascading=!0,s.push(c);for(let d of l.children)i.push(d)}}Ja(this.traceWriter,{origin:r,cascadedTo:s,...n!==void 0?{reason:yh(n)}:{}}),o.controller.abort(n);for(let c of s){let l=this.nodes.get(c);l&&!l.controller.signal.aborted&&l.controller.abort(n)}}dispose(e){let n=this.nodes.get(e);if(n){n.parentId&&this.nodes.get(n.parentId)?.children.delete(e);for(let r of n.children){let o=this.nodes.get(r);o&&(o.parentId=void 0)}this.nodes.delete(e)}}};function yh(t){if(typeof t=="string")return t;if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}var mn=0,Ir=5e3;async function gn(t,e,n={}){if(!Number.isFinite(e)||e<=0)return t;let r,o=new Promise((s,i)=>{r=setTimeout(()=>{let a=n.label?` (${n.label})`:"",c=new Je(`Operation timed out after ${e}ms${a}`,e);n.controller&&!n.controller.signal.aborted&&n.controller.abort(c),i(c)},e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}oe();var Cr=3e4;var hn=class extends Error{constructor(n,r){super(`hook handler timed out after ${r}ms during ${n}`);this.hookEvent=n;this.timeoutMs=r;this.name="HookHandlerTimeoutError"}hookEvent;timeoutMs;code="HOOK_HANDLER_TIMEOUT"};async function Re(t,e,n,r){if(!t)return;if(r.kind==="blocked"){await Ne(t,{hookEvent:e,decision:"block",...r.err.reason!==void 0?{reason:r.err.reason}:{},...e==="PreToolUse"&&n.toolName!==void 0?{blockedTool:n.toolName}:{}});return}let o=r.decision;await Ne(t,{hookEvent:e,decision:o.decision,...o.reason!==void 0?{reason:o.reason}:{},...o.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(o.injectContext,"utf8")}:{}})}async function il(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Re(n.traceWriter,"SubagentStart",{},{kind:"decision",decision:r})}catch(r){throw r instanceof V&&await Re(n.traceWriter,"SubagentStart",{},{kind:"blocked",err:r}),r}}function bh(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new hn(n,e)))},e);i.unref(),t.then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}async function al(t,e,n={}){if(!t)return{};try{let r=await bh(t.dispatch(e,n.signal,Cr),Cr,"SubagentStop");return await Re(n.traceWriter,"SubagentStop",{},{kind:"decision",decision:r}),r}catch(r){return r instanceof hn?(console.warn(`[afk] SubagentStop hook timed out after ${Cr}ms (subagentId=${e.subagentId}): ${r.message}`),n.onError?.(r),{}):(r instanceof V&&await Re(n.traceWriter,"SubagentStop",{},{kind:"blocked",err:r}),r instanceof V||r instanceof pe?(F(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):(F(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{}))}}async function Ks(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Re(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){throw r instanceof V&&await Re(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r}}async function cl(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Re(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof V&&await Re(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof V||r instanceof pe){F(`PostToolUse hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}F(`PostToolUse hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}async function ll(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Re(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof V&&await Re(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof V||r instanceof pe){F(`PostToolUseFailure hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}F(`PostToolUseFailure hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}U();j();import{mkdir as wh,writeFile as Sh}from"fs/promises";import{dirname as vh,join as kh}from"path";function _h(){return kh(Ae(),"routing-decisions.jsonl")}function Eh(t){let e={surface:"afk"};for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}async function be(t){if(!(S.VITEST||S.NODE_ENV==="test"))try{let e=_h();await wh(vh(e),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,...Eh(t)})+`
888
888
  `;await Sh(e,r,{flag:"a"})}catch{}}import{AsyncLocalStorage as Ah}from"node:async_hooks";var dl=new Ah;function ul(t,e){return dl.run(t,e)}function Xe(){return dl.getStore()}import{promises as pl}from"node:fs";import{join as xh,resolve as Th,sep as Gs}from"node:path";var Rh=".afk-worktree-meta.json",Ws=`${Gs}.afk-worktrees${Gs}`;function Ph(t){let e=Th(t),n=e.indexOf(Ws);if(n===-1)return;let o=e.slice(n+Ws.length).split(Gs)[0];if(o)return e.slice(0,n+Ws.length)+o}async function fl(t){let e=Ph(t);if(e===void 0)return;let n=xh(e,Rh);try{let r={};try{r=JSON.parse(await pl.readFile(n,"utf-8"))}catch{r={owner:"agent"}}r.pid=process.pid,r.createdAt=new Date().toISOString(),await pl.writeFile(n,JSON.stringify(r,null,2),"utf-8")}catch{}}import{execFile as Ih}from"node:child_process";import{promisify as Ch}from"node:util";import yn from"node:path";var Mh=Ch(Ih),Oh=(t,e)=>Mh(t,e);async function ml(t,e=Oh){if(!(t===void 0||t===""))try{let{stdout:n}=await e("git",["-C",t,"rev-parse","--git-common-dir","--show-toplevel"]),r=n.split(`
889
- `).map(l=>l.trim()),o=r[0],s=r[1];if(!o||!s)return;let i=yn.isAbsolute(o)?o:yn.resolve(t,o),a=yn.resolve(yn.dirname(i)),c=yn.resolve(s);return a===c?void 0:a}catch{return}}j();import Ji from"path";import{appendFileSync as qk,mkdirSync as zk}from"fs";import{dirname as Jk}from"path";function Mr(t,e){return t??e}function bn(t,e){return e?.allowedTools?e.allowedTools.includes(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" is not in the configured allowlist`}:{allowed:!0}}function Or(t,e){return gl(t,e)}function Dr(t,e){return gl(t,e)}function gl(t,e){if(!t?.allowedTools||e.length===0)return t;let n=new Set(t.allowedTools),r=!1;for(let o of e)n.has(o)||(n.add(o),r=!0);return r?{...t,allowedTools:[...n]}:t}oe();import Qs from"path";import{appendFileSync as vb,mkdirSync as kb}from"fs";import{dirname as _b}from"path";import{createHash as Eb}from"node:crypto";async function wn(t,e,n){let r=new Array(t.length),o=Math.min(Math.max(1,Math.floor(e)),t.length),s=0,i=[];for(let a=0;a<o;a++)i.push((async()=>{for(;s<t.length;){let c=s++;try{r[c]={status:"fulfilled",value:await n(t[c])}}catch(l){r[c]={status:"rejected",reason:l}}}})());return await Promise.all(i),r}var Dh=/\bgit\b[^|;&]*\s(commit|push|pull|merge|rebase|reset|checkout|switch|restore|cherry-pick|revert|am|apply|clean|add|rm|mv|init)\b/i,Fh=/\bgit\b[^|;&]*\s+tag\s+-/i,Lh=/\bgit\b[^|;&]*\s+branch\s+-[dDmM]\b/i,Nh=/\bgit\b[^|;&]*\s+remote\s+(add|remove|rm|set-url|rename)\b/i,$h=/\bgit\b[^|;&]*\s+worktree\s+(remove|prune|move|lock|unlock)\b/i,Uh=/\bgit\b[^|;&]*\s+stash\b(?!\s+(list|show)\b)/i,Bh=/\bstash@\{[^}]*\}/gi,jh=/\bgit\s+config\b[^|;&]*\s(--add|--unset|--unset-all|--replace-all|--rename-section|--remove-section|--edit|-e)\b/i,Hh=/\bgit\s+config\s+(?:--(?:global|system|local|worktree)\s+|(?:--file|-f)\s+\S+\s+)*[\w][\w.-]*\s+\S/i,Kh=/\bgh\s+\w[\w-]*\s+(create|merge|close|edit|delete|comment|review|reopen|sync|fork|clone|ready)\b/i,Wh=/\bgh\s+api\b.*(-X|--method)\s+(POST|PUT|PATCH|DELETE)\b/i,Gh=/\bgh\s+api\b.*(\s-f\b|\s-F\b|--field\b)/i,qh=/\bgh\s+(secret|variable|workflow|release|run|cache|ssh-key|gpg-key)\s+(set|run|rerun|cancel|upload|delete|enable|disable)\b/i,zh=/\|\s*(sh|bash|zsh|dash)\b/i,Jh=/\b(rm|rmdir|unlink|mv|cp|mkdir|touch|dd|truncate|tee|sponge|ln|chmod|chown|chgrp|shred|rsync)\b/i,Vh=/\bfind\b[^|;&]*\s-delete\b/i,Yh=/\bfind\b[^|;&]*\s-exec\s+['"]?\s*(rm|rmdir|unlink|mv|cp|dd|truncate|shred|tee|chmod|chown|chgrp|install|patch)\b/i,Fr=String.raw`(?:^|[\n;|&(]|\$\()\s*`,Xh=new RegExp(Fr+String.raw`patch\b`,"i"),Qh=new RegExp(Fr+String.raw`install\b`,"i"),Zh=new RegExp(Fr+String.raw`(?:source\b|\.\s+\S)`,"i"),ey=/\btar\s+-?[a-zA-Z]*[cxruA][a-zA-Z]*\b/i,ty=new RegExp(Fr+String.raw`unzip\b`,"i"),ny=/\bcpio\b[^|;&]*\s-[a-zA-Z]*i\b/i,ry=/\bsed\b[^|;&]*\s-[a-zA-Z]*i\b/i,oy=/\bperl\b[^|;&]*\s-[a-zA-Z]*i\b/i,sy=/\b(?:python3?|nodejs|node|bun|ruby|perl|php)\b[^|;&]*?\s-(?:c|e)\b\s*("(?:[^"\\]|\\.)*"|'[^']*'|`[^`]*`)/i,iy=/open\s*\([^)]*,\s*['"][wax]|writeFileSync|writeFile\b|appendFileSync|appendFile\b|createWriteStream|File\.(?:write|delete)\b|IO\.write\b|FileUtils\.|\bBun\.write\b|os\.remove\b|shutil\.\w|\.write_text\b|\.write_bytes\b/i,ay=/\b(npm|pnpm|yarn|pip|pip3|brew|cargo|go|apt|apt-get|gem|poetry|bundle|composer)\s+(install|add|remove|uninstall|i|ci|up|update|upgrade|dlx|get|require)\b/i,cy=/\b(curl|wget)\b[^|;&]*\s(-o\b|-O\b|--output\b)/i,ly=/\bcurl\b[^|;&]*\s-X\s+(POST|PUT|PATCH|DELETE)\b/i,dy=/\bcurl\b[^|;&]*\s(-d\b|--data\b|-F\b|--form\b)/i,uy=/(\d*&?>>?\s*\/dev\/null|\d*>&\d+|&>\s*\/dev\/null|&>>\s*\/dev\/null)/gi,py=/\$\(\(.*?\)\)/g,fy=/(?<![=<>-])>>?(?!&)/,my=[{re:Dh,reason:"git repository mutation"},{re:Fh,reason:"git tag create/delete"},{re:Lh,reason:"git branch delete/rename"},{re:Nh,reason:"git remote mutation"},{re:Uh,reason:"git stash mutation (only `stash list`/`stash show` allowed)"},{re:jh,reason:"git config write flag (only reads allowed)"},{re:Hh,reason:"git config set (`<key> <value>`; only reads allowed)"},{re:Kh,reason:"gh write operation"},{re:Wh,reason:"gh api write method (POST/PUT/PATCH/DELETE)"},{re:Gh,reason:"gh api field payload (-f/-F/--field)"},{re:qh,reason:"gh extended write operation (secret/variable/workflow/run/cache)"},{re:$h,reason:"git worktree mutation (remove/prune/move)"},{re:ry,reason:"sed in-place edit (-i)"},{re:oy,reason:"perl in-place edit (-i)"},{re:ay,reason:"package install/modify"},{re:cy,reason:"curl/wget output-to-file"},{re:ly,reason:"curl write method (POST/PUT/PATCH/DELETE)"},{re:dy,reason:"curl data/form payload"},{re:Yh,reason:"find -exec with mutating verb"}],gy=[{re:zh,reason:"pipe-to-shell (RCE via piped interpreter)"},{re:Jh,reason:"filesystem mutation"},{re:Vh,reason:"find -delete (file removal)"},{re:Xh,reason:"patch (applies a diff to files)"},{re:Qh,reason:"install (writes files)"},{re:Zh,reason:"source/dot-source executes a script"},{re:ey,reason:"tar create/extract/append/update (writes files/archive)"},{re:ty,reason:"unzip (writes files)"},{re:ny,reason:"cpio extract (-i mode writes files)"}];function hy(t){return t.replace(/'[^']*'/g," ").replace(/"(?:[^"\\]|\\.)*"/g,e=>/\$\(|`/.test(e)?e:" ")}function Lr(t){if(typeof t!="string"||t.trim().length===0)return{mutating:!1};let e=t.replace(Bh," ");for(let s of my)if(s.re.test(e))return{mutating:!0,reason:s.reason};let n=t.match(sy)?.[1];if(n&&iy.test(n))return{mutating:!0,reason:"interpreter one-liner file write (`-c`/`-e`)"};let r=hy(t);for(let s of gy)if(s.re.test(r))return{mutating:!0,reason:s.reason};let o=r.replace(py," ").replace(uy," ").replace(/&(>>?)/g,"$1");return fy.test(o)?{mutating:!0,reason:"output redirection to a file (`>`/`>>`)"}:{mutating:!1}}j();var yy={name:"bash",category:"shell",concurrencySafe:!1,description:"Execute a shell command and return its stdout and stderr. Use for running programs, installing packages, git operations, and any task that requires a shell. Commands run in the user's default shell. Long-running commands should use timeout_ms. Output is capped at ~100KB; excess is truncated with a notice.",input_schema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute."},timeout_ms:{type:"number",description:"Optional timeout in milliseconds (default 120000, max 600000). The command is killed if it exceeds this duration."}},required:["command"]}},by={name:"read_file",category:"read",concurrencySafe:!0,description:"Read a file from the filesystem. Returns the file content with line numbers. Use offset and limit to read specific sections of large files. When the read returns a partial view, the response ends with a `... (showing lines X-Y of Z [\u2014 pass offset=N to continue])` annotation indicating the full file size and how to continue. Binary files are detected and rejected. Missing files return an error.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to read."},offset:{type:"number",description:"Line number to start reading from (1-based). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to read. Defaults to 2000."}},required:["file_path"]}},wy={name:"write_file",category:"write",concurrencySafe:!1,description:"Write content to a file, creating it if it does not exist or overwriting if it does. Parent directories are created automatically. Prefer edit_file for modifying existing files \u2014 use write_file only for new files or complete rewrites.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to write."},content:{type:"string",description:"The full content to write to the file."}},required:["file_path","content"]}},Sy={name:"edit_file",category:"write",concurrencySafe:!1,description:"Perform an exact string replacement in a file. Finds old_string and replaces it with new_string. The edit fails if old_string is not found or matches multiple locations (unless replace_all is true). Always use read_file first to verify the exact content before editing.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to edit."},old_string:{type:"string",description:"The exact string to find and replace. Must match file content exactly."},new_string:{type:"string",description:"The replacement string."},replace_all:{type:"boolean",description:"If true, replace all occurrences. If false (default), fail when multiple matches exist."}},required:["file_path","old_string","new_string"]}},vy={name:"glob",category:"read",concurrencySafe:!0,description:'Find files matching a glob pattern. Returns matching file paths, capped at 500 results. Use for discovering files before reading them. Patterns follow standard glob syntax (e.g., "src/**/*.ts", "*.json").',input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "src/**/*.ts").'},path:{type:"string",description:"Base directory to search from. Defaults to the current working directory."}},required:["pattern"]}},ky={name:"grep",category:"read",concurrencySafe:!0,description:"Search file contents for lines matching a pattern. Returns matches in file:line:content format. Runs `grep -rn` in basic-regex (BRE) mode by default, where `|` is a LITERAL pipe \u2014 not alternation; set extended: true for extended-regex (ERE) alternation. A no-match result on a pattern containing `|` is often a false negative \u2014 re-read the returned hint. Output is capped to prevent overflow. Use for finding symbols, strings, or patterns across the codebase.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Search pattern. Basic regex (BRE) by default: `|` `+` `?` `(` `)` `{` `}` are LITERAL characters. Set extended: true for extended regex (ERE) where `|` means alternation."},path:{type:"string",description:"Directory or file to search. Defaults to current working directory."},include:{type:"string",description:'File glob to restrict search (e.g., "*.ts"). Passed as --include to grep.'},extended:{type:"boolean",description:"Use extended regex (ERE, `grep -E`) so `|` is alternation and `+ ? ( ) { }` are metacharacters. Default false (BRE \u2014 those characters match literally)."}},required:["pattern"]}},_y={name:"list_directory",category:"read",concurrencySafe:!0,description:"List the contents of a directory. Returns file and subdirectory names with type annotations (directories end with /). Use for exploring project structure.",input_schema:{type:"object",properties:{path:{type:"string",description:"Absolute path to the directory to list."}},required:["path"]}},Ey={name:"send_telegram",category:"web",concurrencySafe:!1,riskClass:"caution",description:"Send a Telegram message to the operator. Use to surface terminal-state notifications, blocking questions, or important status updates when the user is away from keyboard (AFK). The message is delivered through the same Telegram bot the operator uses to drive this session. By default the message goes to your primary chat (the first private chat in `AFK_TELEGRAM_ALLOWED_CHAT_IDS`, or `AFK_TELEGRAM_PRIMARY_CHAT_ID` if set); set `telegram.notify` in afk.config.json to broadcast to all allowed chats or target a custom set.\n\nPlain text only \u2014 Telegram's 4096-character limit per message is enforced. Returns an error if Telegram is not configured (missing `TELEGRAM_BOT_TOKEN` or empty allowlist) so the tool is safe to attempt unconditionally.\n\nUse sparingly: this is a real push notification to a human. Reserve for terminal states (Done/Blocked/Asking) and material progress, not running commentary. When running inside the Telegram bot, prefer replying normally \u2014 your response already reaches the operator through the bot. Use this tool only from CLI or daemon sessions.",input_schema:{type:"object",properties:{message:{type:"string",description:"Plain-text message body to send to the operator. Max 4096 characters (Telegram API limit). Must be non-empty."}},required:["message"]}},Ay={name:"web_scrape",category:"web",concurrencySafe:!0,description:'Scrape a web page or run a web search and return text content suitable for reasoning over. Three modes:\n\n- `markdown` (default): fetches the URL and extracts the main content as clean markdown (Readability + Turndown). Handles JS-rendered pages: if the plain fetch yields thin content, it escalates to a headless-browser render and re-extracts. Use this for articles, docs, blog posts, and most "I want to read this page" cases. No API key required (the render fallback needs the Playwright chromium binary \u2014 `pnpm exec playwright install chromium`).\n- `raw`: GETs the URL directly with no transformation. Use for JSON APIs, robots.txt, RSS, plain-text endpoints, or when you need the literal bytes. No API key required.\n- `search`: runs a web search and returns ranked markdown results. Use when you need to FIND a URL, not read one. Provide `query` instead of `url`. Requires `EXA_API_KEY` (free tier at https://exa.ai); the handler returns a clear error if it is unset.\n\nOutputs are capped at `max_bytes` UTF-8 bytes (default 1MB, ceiling 10MB) and the request is aborted after `timeout_ms` (default 30000, ceiling 120000).',input_schema:{type:"object",properties:{mode:{type:"string",enum:["markdown","raw","search"],description:'Fetch mode. Defaults to "markdown".'},url:{type:"string",description:"Absolute http(s) URL. Required for markdown and raw modes. Ignored in search mode."},query:{type:"string",description:"Search query string. Required for search mode. Ignored otherwise."},timeout_ms:{type:"number",description:"Request timeout in milliseconds (default 30000, clamped to 120000)."},max_bytes:{type:"number",description:"Maximum UTF-8 bytes returned. Content beyond this is truncated with a marker. Default 1000000, clamped to 10000000."}},required:[]}},Be={name:"agent",category:"subagent",concurrencySafe:!0,description:`Dispatch an independent subagent with its own context window and tool access. Use for tasks that protect the main session's context: codebase exploration, multi-file inspection, repo search, verification, debugging, failing-test investigation, PR review, parallel hypothesis testing, independent re-derivation of a claim, audit work, stale-path detection, feature-wiring checks, and any research-shaped investigation.
889
+ `).map(l=>l.trim()),o=r[0],s=r[1];if(!o||!s)return;let i=yn.isAbsolute(o)?o:yn.resolve(t,o),a=yn.resolve(yn.dirname(i)),c=yn.resolve(s);return a===c?void 0:a}catch{return}}j();import Ji from"path";import{appendFileSync as qk,mkdirSync as zk}from"fs";import{dirname as Jk}from"path";function Mr(t,e){return t??e}function bn(t,e){return e?.allowedTools?e.allowedTools.includes(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" is not in the configured allowlist`}:{allowed:!0}}function Or(t,e){return gl(t,e)}function Dr(t,e){return gl(t,e)}function gl(t,e){if(!t?.allowedTools||e.length===0)return t;let n=new Set(t.allowedTools),r=!1;for(let o of e)n.has(o)||(n.add(o),r=!0);return r?{...t,allowedTools:[...n]}:t}oe();import Qs from"path";import{appendFileSync as vb,mkdirSync as kb}from"fs";import{dirname as _b}from"path";import{createHash as Eb}from"node:crypto";async function wn(t,e,n){let r=new Array(t.length),o=Math.min(Math.max(1,Math.floor(e)),t.length),s=0,i=[];for(let a=0;a<o;a++)i.push((async()=>{for(;s<t.length;){let c=s++;try{r[c]={status:"fulfilled",value:await n(t[c])}}catch(l){r[c]={status:"rejected",reason:l}}}})());return await Promise.all(i),r}var Dh=/\bgit\b[^|;&]*\s(commit|push|pull|merge|rebase|reset|checkout|switch|restore|cherry-pick|revert|am|apply|clean|add|rm|mv|init)\b/i,Fh=/\bgit\b[^|;&]*\s+tag\s+-/i,Lh=/\bgit\b[^|;&]*\s+branch\s+-[dDmM]\b/i,Nh=/\bgit\b[^|;&]*\s+remote\s+(add|remove|rm|set-url|rename)\b/i,$h=/\bgit\b[^|;&]*\s+worktree\s+(remove|prune|move|lock|unlock)\b/i,Uh=/\bgit\b[^|;&]*\s+stash\b(?!\s+(list|show)\b)/i,Bh=/\bstash@\{[^}]*\}/gi,jh=/\bgit\s+config\b[^|;&]*\s(--add|--unset|--unset-all|--replace-all|--rename-section|--remove-section|--edit|-e)\b/i,Hh=/\bgit\s+config\s+(?:--(?:global|system|local|worktree)\s+|(?:--file|-f)\s+\S+\s+)*[\w][\w.-]*\s+\S/i,Kh=/\bgh\s+\w[\w-]*\s+(create|merge|close|edit|delete|comment|review|reopen|sync|fork|clone|ready)\b/i,Wh=/\bgh\s+api\b.*(-X|--method)\s+(POST|PUT|PATCH|DELETE)\b/i,Gh=/\bgh\s+api\b.*(\s-f\b|\s-F\b|--field\b)/i,qh=/\bgh\s+(secret|variable|workflow|release|run|cache|ssh-key|gpg-key)\s+(set|run|rerun|cancel|upload|delete|enable|disable)\b/i,zh=/\|\s*(sh|bash|zsh|dash)\b/i,Jh=/\b(rm|rmdir|unlink|mv|cp|mkdir|touch|dd|truncate|tee|sponge|ln|chmod|chown|chgrp|shred|rsync)\b/i,Vh=/\bfind\b[^|;&]*\s-delete\b/i,Yh=/\bfind\b[^|;&]*\s-exec\s+['"]?\s*(rm|rmdir|unlink|mv|cp|dd|truncate|shred|tee|chmod|chown|chgrp|install|patch)\b/i,Fr=String.raw`(?:^|[\n;|&(]|\$\()\s*`,Xh=new RegExp(Fr+String.raw`patch\b`,"i"),Qh=new RegExp(Fr+String.raw`install\b`,"i"),Zh=new RegExp(Fr+String.raw`(?:source\b|\.\s+\S)`,"i"),ey=/\btar\s+-?[a-zA-Z]*[cxruA][a-zA-Z]*\b/i,ty=new RegExp(Fr+String.raw`unzip\b`,"i"),ny=/\bcpio\b[^|;&]*\s-[a-zA-Z]*i\b/i,ry=/\bsed\b[^|;&]*\s-[a-zA-Z]*i\b/i,oy=/\bperl\b[^|;&]*\s-[a-zA-Z]*i\b/i,sy=/\b(?:python3?|nodejs|node|bun|ruby|perl|php)\b[^|;&]*?\s-(?:c|e)\b\s*("(?:[^"\\]|\\.)*"|'[^']*'|`[^`]*`)/i,iy=/open\s*\([^)]*,\s*['"][wax]|writeFileSync|writeFile\b|appendFileSync|appendFile\b|createWriteStream|File\.(?:write|delete)\b|IO\.write\b|FileUtils\.|\bBun\.write\b|os\.remove\b|shutil\.\w|\.write_text\b|\.write_bytes\b/i,ay=/\b(npm|pnpm|yarn|pip|pip3|brew|cargo|go|apt|apt-get|gem|poetry|bundle|composer)\s+(install|add|remove|uninstall|i|ci|up|update|upgrade|dlx|get|require)\b/i,cy=/\b(curl|wget)\b[^|;&]*\s(-o\b|-O\b|--output\b)/i,ly=/\bcurl\b[^|;&]*\s-X\s+(POST|PUT|PATCH|DELETE)\b/i,dy=/\bcurl\b[^|;&]*\s(-d\b|--data\b|-F\b|--form\b)/i,uy=/(\d*&?>>?\s*\/dev\/null|\d*>&\d+|&>\s*\/dev\/null|&>>\s*\/dev\/null)/gi,py=/\$\(\(.*?\)\)/g,fy=/(?<![=<>-])>>?(?!&)/,my=[{re:Dh,reason:"git repository mutation"},{re:Fh,reason:"git tag create/delete"},{re:Lh,reason:"git branch delete/rename"},{re:Nh,reason:"git remote mutation"},{re:Uh,reason:"git stash mutation (only `stash list`/`stash show` allowed)"},{re:jh,reason:"git config write flag (only reads allowed)"},{re:Hh,reason:"git config set (`<key> <value>`; only reads allowed)"},{re:Kh,reason:"gh write operation"},{re:Wh,reason:"gh api write method (POST/PUT/PATCH/DELETE)"},{re:Gh,reason:"gh api field payload (-f/-F/--field)"},{re:qh,reason:"gh extended write operation (secret/variable/workflow/run/cache)"},{re:$h,reason:"git worktree mutation (remove/prune/move)"},{re:ry,reason:"sed in-place edit (-i)"},{re:oy,reason:"perl in-place edit (-i)"},{re:ay,reason:"package install/modify"},{re:cy,reason:"curl/wget output-to-file"},{re:ly,reason:"curl write method (POST/PUT/PATCH/DELETE)"},{re:dy,reason:"curl data/form payload"},{re:Yh,reason:"find -exec with mutating verb"}],gy=[{re:zh,reason:"pipe-to-shell (RCE via piped interpreter)"},{re:Jh,reason:"filesystem mutation"},{re:Vh,reason:"find -delete (file removal)"},{re:Xh,reason:"patch (applies a diff to files)"},{re:Qh,reason:"install (writes files)"},{re:Zh,reason:"source/dot-source executes a script"},{re:ey,reason:"tar create/extract/append/update (writes files/archive)"},{re:ty,reason:"unzip (writes files)"},{re:ny,reason:"cpio extract (-i mode writes files)"}];function hy(t){return t.replace(/'[^']*'/g," ").replace(/"(?:[^"\\]|\\.)*"/g,e=>/\$\(|`/.test(e)?e:" ")}function Lr(t){if(typeof t!="string"||t.trim().length===0)return{mutating:!1};let e=t.replace(Bh," ");for(let s of my)if(s.re.test(e))return{mutating:!0,reason:s.reason};let n=t.match(sy)?.[1];if(n&&iy.test(n))return{mutating:!0,reason:"interpreter one-liner file write (`-c`/`-e`)"};let r=hy(t);for(let s of gy)if(s.re.test(r))return{mutating:!0,reason:s.reason};let o=r.replace(py," ").replace(uy," ").replace(/&(>>?)/g,"$1");return fy.test(o)?{mutating:!0,reason:"output redirection to a file (`>`/`>>`)"}:{mutating:!1}}j();var yy={name:"bash",category:"shell",concurrencySafe:!1,description:"Execute a shell command and return its stdout and stderr. Use for running programs, installing packages, git operations, and any task that requires a shell. Commands run in the user's default shell. Long-running commands should use timeout_ms. Output is capped at ~100KB; excess is truncated with a notice. For reading or writing files \u2014 especially anything sensitive \u2014 prefer the typed file tools (read_file, write_file, edit_file): they support per-call user approval, and interpreter one-liners (python -c, node -e, sh -c, ...) that reference credential paths (SSH keys, cloud credentials, /etc/shadow) are blocked by the path-approval policy on interactive surfaces.",input_schema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute."},timeout_ms:{type:"number",description:"Optional timeout in milliseconds (default 120000, max 600000). The command is killed if it exceeds this duration."}},required:["command"]}},by={name:"read_file",category:"read",concurrencySafe:!0,description:"Read a file from the filesystem. Returns the file content with line numbers. Use offset and limit to read specific sections of large files. When the read returns a partial view, the response ends with a `... (showing lines X-Y of Z [\u2014 pass offset=N to continue])` annotation indicating the full file size and how to continue. Binary files are detected and rejected. Missing files return an error.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to read."},offset:{type:"number",description:"Line number to start reading from (1-based). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to read. Defaults to 2000."}},required:["file_path"]}},wy={name:"write_file",category:"write",concurrencySafe:!1,description:"Write content to a file, creating it if it does not exist or overwriting if it does. Parent directories are created automatically. Prefer edit_file for modifying existing files \u2014 use write_file only for new files or complete rewrites.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to write."},content:{type:"string",description:"The full content to write to the file."}},required:["file_path","content"]}},Sy={name:"edit_file",category:"write",concurrencySafe:!1,description:"Perform an exact string replacement in a file. Finds old_string and replaces it with new_string. The edit fails if old_string is not found or matches multiple locations (unless replace_all is true). Always use read_file first to verify the exact content before editing.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to edit."},old_string:{type:"string",description:"The exact string to find and replace. Must match file content exactly."},new_string:{type:"string",description:"The replacement string."},replace_all:{type:"boolean",description:"If true, replace all occurrences. If false (default), fail when multiple matches exist."}},required:["file_path","old_string","new_string"]}},vy={name:"glob",category:"read",concurrencySafe:!0,description:'Find files matching a glob pattern. Returns matching file paths, capped at 500 results. Use for discovering files before reading them. Patterns follow standard glob syntax (e.g., "src/**/*.ts", "*.json").',input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "src/**/*.ts").'},path:{type:"string",description:"Base directory to search from. Defaults to the current working directory."}},required:["pattern"]}},ky={name:"grep",category:"read",concurrencySafe:!0,description:"Search file contents for lines matching a pattern. Returns matches in file:line:content format. Runs `grep -rn` in basic-regex (BRE) mode by default, where `|` is a LITERAL pipe \u2014 not alternation; set extended: true for extended-regex (ERE) alternation. A no-match result on a pattern containing `|` is often a false negative \u2014 re-read the returned hint. Output is capped to prevent overflow. Use for finding symbols, strings, or patterns across the codebase.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Search pattern. Basic regex (BRE) by default: `|` `+` `?` `(` `)` `{` `}` are LITERAL characters. Set extended: true for extended regex (ERE) where `|` means alternation."},path:{type:"string",description:"Directory or file to search. Defaults to current working directory."},include:{type:"string",description:'File glob to restrict search (e.g., "*.ts"). Passed as --include to grep.'},extended:{type:"boolean",description:"Use extended regex (ERE, `grep -E`) so `|` is alternation and `+ ? ( ) { }` are metacharacters. Default false (BRE \u2014 those characters match literally)."}},required:["pattern"]}},_y={name:"list_directory",category:"read",concurrencySafe:!0,description:"List the contents of a directory. Returns file and subdirectory names with type annotations (directories end with /). Use for exploring project structure.",input_schema:{type:"object",properties:{path:{type:"string",description:"Absolute path to the directory to list."}},required:["path"]}},Ey={name:"send_telegram",category:"web",concurrencySafe:!1,riskClass:"caution",description:"Send a Telegram message to the operator. Use to surface terminal-state notifications, blocking questions, or important status updates when the user is away from keyboard (AFK). The message is delivered through the same Telegram bot the operator uses to drive this session. By default the message goes to your primary chat (the first private chat in `AFK_TELEGRAM_ALLOWED_CHAT_IDS`, or `AFK_TELEGRAM_PRIMARY_CHAT_ID` if set); set `telegram.notify` in afk.config.json to broadcast to all allowed chats or target a custom set.\n\nPlain text only \u2014 Telegram's 4096-character limit per message is enforced. Returns an error if Telegram is not configured (missing `TELEGRAM_BOT_TOKEN` or empty allowlist) so the tool is safe to attempt unconditionally.\n\nUse sparingly: this is a real push notification to a human. Reserve for terminal states (Done/Blocked/Asking) and material progress, not running commentary. When running inside the Telegram bot, prefer replying normally \u2014 your response already reaches the operator through the bot. Use this tool only from CLI or daemon sessions.",input_schema:{type:"object",properties:{message:{type:"string",description:"Plain-text message body to send to the operator. Max 4096 characters (Telegram API limit). Must be non-empty."}},required:["message"]}},Ay={name:"web_scrape",category:"web",concurrencySafe:!0,description:'Scrape a web page or run a web search and return text content suitable for reasoning over. Three modes:\n\n- `markdown` (default): fetches the URL and extracts the main content as clean markdown (Readability + Turndown). Handles JS-rendered pages: if the plain fetch yields thin content, it escalates to a headless-browser render and re-extracts. Use this for articles, docs, blog posts, and most "I want to read this page" cases. No API key required (the render fallback needs the Playwright chromium binary \u2014 `pnpm exec playwright install chromium`).\n- `raw`: GETs the URL directly with no transformation. Use for JSON APIs, robots.txt, RSS, plain-text endpoints, or when you need the literal bytes. No API key required.\n- `search`: runs a web search and returns ranked markdown results. Use when you need to FIND a URL, not read one. Provide `query` instead of `url`. Requires `EXA_API_KEY` (free tier at https://exa.ai); the handler returns a clear error if it is unset.\n\nOutputs are capped at `max_bytes` UTF-8 bytes (default 1MB, ceiling 10MB) and the request is aborted after `timeout_ms` (default 30000, ceiling 120000).',input_schema:{type:"object",properties:{mode:{type:"string",enum:["markdown","raw","search"],description:'Fetch mode. Defaults to "markdown".'},url:{type:"string",description:"Absolute http(s) URL. Required for markdown and raw modes. Ignored in search mode."},query:{type:"string",description:"Search query string. Required for search mode. Ignored otherwise."},timeout_ms:{type:"number",description:"Request timeout in milliseconds (default 30000, clamped to 120000)."},max_bytes:{type:"number",description:"Maximum UTF-8 bytes returned. Content beyond this is truncated with a marker. Default 1000000, clamped to 10000000."}},required:[]}},Be={name:"agent",category:"subagent",concurrencySafe:!0,description:`Dispatch an independent subagent with its own context window and tool access. Use for tasks that protect the main session's context: codebase exploration, multi-file inspection, repo search, verification, debugging, failing-test investigation, PR review, parallel hypothesis testing, independent re-derivation of a claim, audit work, stale-path detection, feature-wiring checks, and any research-shaped investigation.
890
890
 
891
891
  Parallelize: dispatch multiple \`agent\` calls in a single tool-use turn to run independent investigations concurrently.
892
892