agent-afk 4.9.0 → 4.9.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/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var E$=Object.defineProperty;var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var vl=(e,t)=>{for(var n in t)E$(e,n,{get:t[n],enumerable:!0})};function kl(e){return Mi.find(t=>t.name===e)}function Ob(e){return Mi.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function Vp(e){return process.env[e]!==void 0}var Mi,k,G=_(()=>{"use strict";Mi=[{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_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:"Per-turn USD budget ceiling. Aborts the turn when projected spend would exceed 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_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-4-6",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:"Allow loading MCP configuration from <cwd>/.mcp.json. Disabled by default \u2014 opt-in to mitigate config-injection risks.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_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:"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_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"}],k={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_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},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_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_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 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_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 t of Mi){if(!t.secret)continue;let n=Object.getOwnPropertyDescriptor(k,t.name);n&&Object.defineProperty(k,t.name,{...n,enumerable:!1})}})()});import{existsSync as $b,mkdirSync as T$,renameSync as R$,cpSync as C$,rmSync as _$}from"fs";import{join as Z,dirname as Lb,isAbsolute as Fb}from"path";import{homedir as Yp}from"os";import{fileURLToPath as A$}from"url";function Ae(){let e=k.AFK_HOME;if(e!==void 0&&e!==""){if(!Fb(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return Z(Yp(),".afk")}function Ct(){return Z(Ae(),"agent-framework")}function sr(){return Z(Ct(),"forge-telemetry.jsonl")}function qo(){return Z(Ct(),"briefs")}function xl(){return Z(Ae(),"skills")}function He(){return Z(Ae(),"plugins")}function Nb(){return Z(process.cwd(),".afk")}function El(){return Z(Nb(),"skills")}function Oi(){return Z(Nb(),"plugins")}function Bb(e=process.cwd()){return Z(e,".afk","plans")}function ce(){return Z(He(),".index.json")}function Xp(){return Z(tn(),"schedules.json")}function Rn(){return Z(He(),"cache")}function $i(e){return Z(Rn(),e)}function Hr(){let e=A$(import.meta.url),t=Lb(e);return Z(t,"bundled-plugins")}function tn(){return Z(Ae(),"config")}function Te(){let e=k.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!Fb(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return Z(Ae(),"state")}function Tl(){return Z(Ae(),"cache")}function Jo(){return Z(Ae(),"logs")}function Cn(){return Z(Te(),"sessions")}function Rl(){return Z(Te(),"presence")}function Zp(){return Z(Te(),"todos")}function Qp(){return Z(Te(),"transcripts")}function Cl(){return Z(Te(),"memory")}function nn(){return Z(Te(),"queue")}function Vo(){return Z(Te(),"session-grants.jsonl")}function Ub(){return Z(Ae(),"farms")}function em(e){return Z(Ub(),e)}function P$(e){if(!I$.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function Yo(e){return P$(e),Z(Te(),"witness",e)}function _l(e="default"){return Z(Te(),"daemon",`agent-afk@${e}`)}function jb(){return Z(Te(),"worktree-sweep.lock")}function at(){return Z(tn(),"afk.env")}function _t(){return Z(tn(),"afk.config.json")}function Hb(){return Z(tn(),"settings.json")}function Wb(e=process.cwd()){return Z(e,".afk","settings.json")}function Kb(){return Z(Yp(),".afk.env")}function Al(){return Z(Yp(),".afk.config.json")}function M$(){return Z(Ae(),"sessions")}function O$(){return Z(Ae(),"todos")}function $$(){return Z(Ae(),"transcripts")}function tm(e,t){if(e!==t&&$b(e)&&!$b(t))try{T$(Lb(t),{recursive:!0});try{R$(e,t)}catch(n){if(n.code==="EXDEV")try{C$(e,t,{recursive:!0}),_$(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
|
|
2
|
+
var E$=Object.defineProperty;var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var vl=(e,t)=>{for(var n in t)E$(e,n,{get:t[n],enumerable:!0})};function kl(e){return Mi.find(t=>t.name===e)}function Ob(e){return Mi.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function Vp(e){return process.env[e]!==void 0}var Mi,k,G=_(()=>{"use strict";Mi=[{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_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_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-4-6",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:"Allow loading MCP configuration from <cwd>/.mcp.json. Disabled by default \u2014 opt-in to mitigate config-injection risks.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_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:"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_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"}],k={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_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},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_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_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 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_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 t of Mi){if(!t.secret)continue;let n=Object.getOwnPropertyDescriptor(k,t.name);n&&Object.defineProperty(k,t.name,{...n,enumerable:!1})}})()});import{existsSync as $b,mkdirSync as T$,renameSync as R$,cpSync as C$,rmSync as _$}from"fs";import{join as Z,dirname as Lb,isAbsolute as Fb}from"path";import{homedir as Yp}from"os";import{fileURLToPath as A$}from"url";function Ae(){let e=k.AFK_HOME;if(e!==void 0&&e!==""){if(!Fb(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return Z(Yp(),".afk")}function Ct(){return Z(Ae(),"agent-framework")}function sr(){return Z(Ct(),"forge-telemetry.jsonl")}function qo(){return Z(Ct(),"briefs")}function xl(){return Z(Ae(),"skills")}function He(){return Z(Ae(),"plugins")}function Nb(){return Z(process.cwd(),".afk")}function El(){return Z(Nb(),"skills")}function Oi(){return Z(Nb(),"plugins")}function Bb(e=process.cwd()){return Z(e,".afk","plans")}function ce(){return Z(He(),".index.json")}function Xp(){return Z(tn(),"schedules.json")}function Rn(){return Z(He(),"cache")}function $i(e){return Z(Rn(),e)}function Hr(){let e=A$(import.meta.url),t=Lb(e);return Z(t,"bundled-plugins")}function tn(){return Z(Ae(),"config")}function Te(){let e=k.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!Fb(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return Z(Ae(),"state")}function Tl(){return Z(Ae(),"cache")}function Jo(){return Z(Ae(),"logs")}function Cn(){return Z(Te(),"sessions")}function Rl(){return Z(Te(),"presence")}function Zp(){return Z(Te(),"todos")}function Qp(){return Z(Te(),"transcripts")}function Cl(){return Z(Te(),"memory")}function nn(){return Z(Te(),"queue")}function Vo(){return Z(Te(),"session-grants.jsonl")}function Ub(){return Z(Ae(),"farms")}function em(e){return Z(Ub(),e)}function P$(e){if(!I$.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function Yo(e){return P$(e),Z(Te(),"witness",e)}function _l(e="default"){return Z(Te(),"daemon",`agent-afk@${e}`)}function jb(){return Z(Te(),"worktree-sweep.lock")}function at(){return Z(tn(),"afk.env")}function _t(){return Z(tn(),"afk.config.json")}function Hb(){return Z(tn(),"settings.json")}function Wb(e=process.cwd()){return Z(e,".afk","settings.json")}function Kb(){return Z(Yp(),".afk.env")}function Al(){return Z(Yp(),".afk.config.json")}function M$(){return Z(Ae(),"sessions")}function O$(){return Z(Ae(),"todos")}function $$(){return Z(Ae(),"transcripts")}function tm(e,t){if(e!==t&&$b(e)&&!$b(t))try{T$(Lb(t),{recursive:!0});try{R$(e,t)}catch(n){if(n.code==="EXDEV")try{C$(e,t,{recursive:!0}),_$(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
|
|
3
3
|
`)}}}catch{}}function Gb(){tm(M$(),Cn())}function zb(){tm(O$(),Zp())}function qb(){tm($$(),Qp())}function nm(){return Z(Te(),"repl-history.jsonl")}function L$(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(e.length>Db)throw new Error(`Invalid jobId: exceeds ${Db} chars`);if(!D$.test(e))throw new Error(`Invalid jobId: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function Di(){return Z(Te(),"bg")}function Wr(e){return L$(e),Z(Di(),e)}function Il(e){return Z(Wr(e),"events.jsonl")}function rm(e){return Z(Wr(e),"meta.json")}function om(e){return typeof e=="string"&&e.length>0&&e.length<=N$&&F$.test(e)}function sm(e){if(!om(e))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(e)}`);return Z(Cn(),e)}function Jb(e){return Z(sm(e),"events.jsonl")}function Li(){return Z(Te(),"mcp","server-status.json")}var I$,D$,Db,F$,N$,K=_(()=>{"use strict";G();I$=/^[a-zA-Z0-9_-]+$/;D$=/^[A-Za-z0-9_-]+$/,Db=128;F$=/^[A-Za-z0-9_-]+$/,N$=128});import{randomBytes as B$}from"node:crypto";import{mkdirSync as U$,renameSync as j$,rmSync as Vb,writeFileSync as H$}from"node:fs";import{dirname as W$,isAbsolute as K$,join as G$}from"node:path";function Pl(){return G$(Te(),"last-cwd")}function Yb(){try{Vb(Pl(),{force:!0})}catch{}}function Xb(e){if(!K$(e))throw new Error(`recordCdIntent: target must be an absolute path, got ${JSON.stringify(e)}`);if(/[\n\r\0]/.test(e))throw new Error(`recordCdIntent: target must not contain newline/CR/NUL, got ${JSON.stringify(e)}`);try{let t=Pl();U$(W$(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${B$(6).toString("hex")}`;try{H$(n,e,{encoding:"utf8",mode:384}),j$(n,t)}catch(r){try{Vb(n,{force:!0})}catch{}throw r}}catch{}}function Zb(){let e=k.AFK_SHELL_WRAPPER;return e==="1"||e==="true"}var Ml=_(()=>{"use strict";G();K()});var At,It,Ie,ir,Ol,Pt=_(()=>{"use strict";At=class extends Error{constructor(t){super(t),this.name="AbortError"}},It=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Ie=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},ir=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},Ol=class extends Error{constructor(n,r,o){super(o??`${n} provider does not support AgentConfig.${r}.`);this.provider=n;this.field=r;this.name="UnsupportedProviderConfigError"}provider;field}});function Ze(){return k.AFK_DEBUG==="1"||k.DEBUG==="1"}function V(...e){Ze()&&console.log(...e)}var Pe=_(()=>{"use strict";G()});async function bm(e,t){if(e)try{await e.write({kind:"tool_call",payload:t})}catch(n){V(`trace.emit tool_call failed: ${In(n)}`)}}async function ns(e,t){if(e)try{await e.write({kind:"hook_decision",payload:t})}catch(n){V(`trace.emit hook_decision failed: ${In(n)}`)}}async function zr(e,t){if(e)try{await e.write({kind:"subagent_lifecycle",payload:t})}catch(n){V(`trace.emit subagent_lifecycle failed: ${In(n)}`)}}async function rs(e,t){if(e)try{await e.write({kind:"background_agent",payload:t})}catch(n){V(`trace.emit background_agent failed: ${In(n)}`)}}async function kw(e,t){if(e)try{await e.write({kind:"budget",payload:t})}catch(n){V(`trace.emit budget failed: ${In(n)}`)}}async function xw(e,t){if(e)try{await e.write({kind:"abort",payload:t})}catch(n){V(`trace.emit abort failed: ${In(n)}`)}}async function Ew(e,t){if(e)try{await e.write({kind:"compaction",payload:t})}catch(n){V(`trace.emit compaction failed: ${In(n)}`)}}async function Tw(e,t){if(e)try{await e.write({kind:"closure",payload:t})}catch(n){V(`trace.emit closure failed: ${In(n)}`)}}async function lt(e,t){if(e)try{await e.write({kind:"session_phase",payload:t})}catch(n){V(`trace.emit session_phase failed: ${In(n)}`)}}function In(e){return e instanceof Error?e.message:String(e)}var bt=_(()=>{"use strict";Pe()});function Ul(e){return e.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Ui(e,t,n){let r=t==="oauth"?{authToken:e}:{apiKey:e};return typeof n=="string"&&n.length>0?{...r,baseURL:n}:r}function rn(e,t,n,r){return e!=="oauth"?{}:{"anthropic-beta":r?`${Rw},${CD}`:Rw,"x-app":"cli","User-Agent":_D,"X-Claude-Code-Session-Id":t,"x-client-request-id":n}}function Cw(e){return e!=="oauth"?null:[{type:"text",text:AD}]}var Rw,CD,_D,AD,os=_(()=>{"use strict";Rw="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",CD="effort-2025-11-24",_D="claude-cli/1.0.0 (external, cli)",AD="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;"});function Wl(e){Sm=e}function wm(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}function jl(e,t,n){let r={},o=wm(e);o&&(r.id=o);let s=wm(t);s&&(r.baseUrl=s);let i=wm(n);return i&&(r.apiKey=i),r}function OD(){return{local:jl(k.AFK_MODEL_LOCAL,k.AFK_MODEL_LOCAL_BASE_URL,k.AFK_MODEL_LOCAL_API_KEY),small:jl(k.AFK_MODEL_SMALL,k.AFK_MODEL_SMALL_BASE_URL,k.AFK_MODEL_SMALL_API_KEY),medium:jl(k.AFK_MODEL_MEDIUM,k.AFK_MODEL_MEDIUM_BASE_URL,k.AFK_MODEL_MEDIUM_API_KEY),large:jl(k.AFK_MODEL_LARGE,k.AFK_MODEL_LARGE_BASE_URL,k.AFK_MODEL_LARGE_API_KEY)}}function xm(e){let t=OD(),n={};for(let r of vm){let o=qr[r],s=e?.[r],i=t[r],a={id:i.id??s?.id??o.id},l=s?.name;l&&(a.name=l);let c=s?.provider;c&&(a.provider=c);let u=i.baseUrl??s?.baseUrl;u&&(a.baseUrl=u);let d=i.apiKey??s?.apiKey;d&&(a.apiKey=d),n[r]=a}return n}function ss(e){return e||Sm||xm()}function is(e,t=ss()){let n=e.trim().toLowerCase();if(!n||n===PD)return;for(let o of vm){let s=t[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:ID[n]}function Em(e,t=ss()){if(e===void 0)return{id:""};let n=is(e,t);if(n)return t[n];let r=MD[e.trim().toLowerCase()];return r?{id:r}:{id:e}}function Jr(e,t=ss()){if(e!==void 0)return Em(e,t).id}function as(e,t=ss()){if(e===void 0)return;let n=is(e,t);if(n&&t[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function _w(e){let t={};if(!e||typeof e!="object")return t;let n=e;for(let r of vm){let o=DD(n[r]);o&&(t[r]=o)}return t}function $D(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();if(t==="anthropic"||t==="anthropic-direct")return"anthropic";if(t==="openai"||t==="openai-compatible")return"openai"}function Hl(e){return typeof e=="string"?e.trim():""}function DD(e){if(typeof e=="string"){let t=e.trim();return t?{id:t}:void 0}if(e&&typeof e=="object"){let t=e,n=Hl(t.id);if(!n)return;let r={id:n},o=Hl(t.name);o&&(r.name=o);let s=$D(t.provider);s&&(r.provider=s);let i=Hl(t.baseUrl);i&&(r.baseUrl=i);let a=Hl(t.apiKey);return a&&(r.apiKey=a),r}}var vm,qr,ID,PD,km,MD,Sm,Wt=_(()=>{"use strict";G();vm=["local","small","medium","large"],qr={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-4-6"},large:{id:"claude-opus-4-8"}},ID={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},PD="auto",km="claude-fable-5",MD={fable:km}});function Rm(e){return e in Tm}function gt(e){return Jr(e)}var Tm,Pn=_(()=>{"use strict";Wt();Tm={opus:qr.large.id,opus_1m:qr.large.id,sonnet:qr.medium.id,sonnet_1m:qr.medium.id,haiku:qr.small.id,fable:km}});import LD from"@anthropic-ai/sdk";import{randomUUID as Aw}from"node:crypto";async function ls(e){let{token:t,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=e;if(!t)throw new Error("oneShotCompletion: token required");let l=Ul(t),c=Ui(t,l),u=a?a(c):new LD(c),d=Aw(),m=Aw(),f=rn(l,d,m),g=gt(n)??n,h={};Object.keys(f).length>0&&(h.headers=f),i&&(h.signal=i);let b=await u.messages.create({model:g,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(h).length>0?h:void 0),y=[];for(let w of b.content)w.type==="text"&&y.push(w.text);let v=y.join("").trim();return v.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),v}var Kl=_(()=>{"use strict";os();Pn()});import{execFileSync as Iw}from"child_process";import{existsSync as FD,readFileSync as ND,writeFileSync as BD}from"fs";import{homedir as Pw,userInfo as Mw}from"os";import{join as Ow}from"path";function ct(){let e=$w();if(e===void 0)return;let t=Dw(e);if(t!==void 0){if(t.expiresAt!==void 0&&t.expiresAt<=Date.now()){process.stderr.write("agent-afk: Claude Code OAuth token in keychain is expired. Run `claude login` to refresh.\n");return}return t.accessToken}}async function Cm(){let e=$w();if(e===void 0)return;let t=Dw(e);if(t===void 0)return;if(t.expiresAt!==void 0&&t.expiresAt>Date.now()+HD)return t.accessToken;if(!t.refreshToken){process.stderr.write("agent-afk: OAuth token expired and no refresh token available. Run `claude login` to refresh.\n");return}let n=await WD(t.refreshToken);if(!n){process.stderr.write("agent-afk: OAuth token refresh failed. Run `claude login` to refresh.\n");return}try{let r={};try{r=JSON.parse(e)}catch{}let o=r.claudeAiOauth??{};r.claudeAiOauth={...o,accessToken:n.accessToken,expiresAt:n.expiresAt,...n.refreshToken!==void 0?{refreshToken:n.refreshToken}:{}},KD(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
4
4
|
`)}return n.accessToken}function $w(){if(process.platform==="darwin")try{return Iw("security",["find-generic-password","-s","Claude Code-credentials","-a",Mw().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let e=Ow(Pw(),".claude",".credentials.json");if(!FD(e))return;try{return ND(e,"utf-8")}catch{return}}}function Dw(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null)return;let n=t.claudeAiOauth;if(typeof n!="object"||n===null)return;let r=n,o=r.accessToken;if(typeof o!="string"||o.length===0)return;let 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 WD(e){try{let t=await fetch(jD,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:UD})});if(!t.ok)return;let n=await t.json(),r=n.access_token,o=n.expires_in;if(typeof r!="string"||typeof o!="number")return;let s=n.refresh_token;return{accessToken:r,expiresAt:Date.now()+o*1e3,...typeof s=="string"&&s.length>0?{refreshToken:s}:{}}}catch{return}}function cr(e){if(!e||e.length<3)return"token:(unknown)";try{let n=e.split(".");if(n.length<2)throw new Error("not a JWT");let r=Buffer.from(n[1],"base64url").toString("utf-8"),o=JSON.parse(r),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:${e.length>=8?e.slice(-8):e}`}function KD(e){if(process.platform==="darwin")Iw("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",Mw().username,"-w",e],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let t=Ow(Pw(),".claude",".credentials.json");GD(t,e)}}function GD(e,t){BD(e,t,{encoding:"utf-8",mode:384})}var UD,jD,HD,cs=_(()=>{"use strict";UD="9d1c250a-e61b-44d9-88ed-5944d1962f5e",jD="https://platform.claude.com/v1/oauth/token",HD=300*1e3});function Gl(e){if(typeof e?.baseUrl=="string"&&e.baseUrl.length>0)return!1;let t=k.AFK_DISABLE_PROMPT_CACHE;if(t===void 0||t.length===0)return!0;let n=t.toLowerCase();return!(n==="1"||n==="true"||n==="yes"||n==="on")}function zl(){let e=k.AFK_PROMPT_CACHE_TTL;return e==="5m"?"5m":e==="1h"?"1h":zD}function Lw(e,t){if(e.length===0)return e;let n=e[e.length-1],r=Nw(n,t);return r===n?e:[...e.slice(0,-1),r]}function Fw(e,t){if(e.length===0)return e;let n=e[e.length-1],r=qD(n,t);return r===n?e:[...e.slice(0,-1),r]}function qD(e,t){let n=e.content;if(typeof n=="string")return n.length===0?e:{...e,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:t}}]};if(!Array.isArray(n)||n.length===0)return e;let r=n[n.length-1],o=Nw(r,t);return o===r?e:{...e,content:[...n.slice(0,-1),o]}}function Nw(e,t){return e.type==="thinking"||e.type==="redacted_thinking"?e:{...e,cache_control:{type:"ephemeral",ttl:t}}}var zD,_m=_(()=>{"use strict";G();zD="1h"});function Bw(e){return e!=="plan"?null:{type:"text",text:Am}}var Am,Im=_(()=>{"use strict";Am=["## Plan mode is active","","Write-class tools (`write_file`, `edit_file`, write-intent `bash`) are refused at the hook layer.","The user has asked you to plan, not yet to act. 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. The user will then exit plan mode with `/plan off`, which has you save this plan to a file and implement it (Shift+Tab exits without implementing) \u2014 so keep the plan concrete and complete enough to act on directly."].join(`
|
|
5
5
|
`)});function Fe(e){let t=Uw[e];if(!t){let n=Object.keys(Uw).sort(),r=n.length>0?"Available: "+n.join(", "):"";throw new Error("Unknown skill: "+e+". "+r)}return t}var Uw,Kt=_(()=>{"use strict";Uw={"audit-fit":{"01-skill-inspector.md":`# Skill Inspector
|
|
@@ -759,7 +759,7 @@ Return a well-structured specification (700\u20131000 words) that a developer ca
|
|
|
759
759
|
- How to validate success
|
|
760
760
|
|
|
761
761
|
Be direct and clear. Avoid marketing language; favor technical precision.
|
|
762
|
-
`,"verify.md":'# Phase 6: Verify (Ship-Yesterday Gate)\n\nYou are a quality gate. Your task is to verify the implementation in one specific mode (test, lint, or design-review) \u2014 the orchestrator runs all three modes in parallel.\n\n## Input\nYou are given:\n- The implementation plan from Phase 3 (verification commands, success criteria)\n- The build results from Phase 5 (files changed, test status)\n- Your **mode** \u2014 one of: `test`, `lint`, `design-review`\n\n## Your Task\n\nThe orchestrator runs three modes in parallel: `test` and `lint` are **programmatic** checks; `design-review` is a code-quality review. A green status across all three is the bar to ship.\n\n**If mode is `test`:**\n- Run the full test suite specified in the plan.\n- Capture failures and concrete error messages.\n\n**If mode is `lint`:**\n- Run linting and type-checking.\n- Capture each lint/type error with file:line where possible.\n\n**If mode is `design-review`:**\nEvaluate the implementation diff across these dimensions and decide PASS/FAIL based on whether any dimension has a red (blocker):\n\n1. **Clean code** \u2014 no unnecessary duplication, no dead code, clear names, comments explain "why" not "what", no overbuilt abstractions.\n2. **Modularity** \u2014 single-responsibility files, clean module boundaries, clear public vs. private APIs.\n3. **Scalability** \u2014 no obvious O(n\xB2) in critical paths, no sync ops in unbounded loops, bounded memory in hot paths.\n4. **Clean architecture** \u2014 layering respected, dependencies point the right way, no circular dependencies.\n5. **Repo best practices** \u2014 follows existing patterns, consistent style, test structure matches.\n6. **Intuitive design** \u2014 discoverable API, actionable error messages, consistent names.\n7. **Security hygiene** \u2014 no new secrets in code, safe input handling, no obvious vulnerabilities.\n\nA red on any dimension is a FAIL; yellows are nice-to-have and do not block.\n\n## Output\n\nRespond with a single fenced JSON code block and no prose outside it. The JSON must conform to:\n\n```json\n{\n "status": "PASS",\n "status_reason": "short reason \u2014 only when status is FAIL, omit otherwise",\n "issues": ["src/example.ts:42 \u2014 concrete issue description"],\n "summary": "Optional one-paragraph human-readable summary of what was checked.",\n "signal": {\n "issue": "stable-slug-or-question",\n "stance": "supports",\n "confidence": 0.9,\n "evidence": ["src/example.ts:42"],\n "claim": "Implementation passes this verification mode without blockers."\n }\n}\n```\n\nField semantics:\n- `status` \u2014 `"PASS"` if this mode is green; `"FAIL"` if anything red.\n- `status_reason` \u2014 short reason when `FAIL`; omit when `PASS`.\n- `issues` \u2014 concrete blockers with file:line citations where possible. Empty array when `PASS`.\n- `summary` \u2014 optional narrative; the orchestrator may surface it to the user. Keep it concise.\n- `signal` \u2014 OPTIONAL passive-observation field (v0). When the\n implementation cleanly passes or cleanly fails your mode, you MAY emit a\n `signal` object conforming to the shape shown. See `docs/signal-block.md`\n for the full convention. Rules:\n - `issue` \u2014 a stable slug naming what was checked (e.g.\n `"verify-test-mode"`, `"verify-lint-mode"`, `"verify-design-review"`).\n Use the same slug across reruns of the same mode.\n - `stance` \u2014 `supports` when `status: "PASS"`; `opposes` when\n `status: "FAIL"`; `uncertain` when issues are real but ambiguous;\n `blocks` when the verification tool itself failed (e.g. test runner\n crashed).\n - `confidence` \u2014 how sure you are about the verdict, not how sure you\n are that the code is good overall.\n - `evidence` \u2014 at least one `file:line` citation matching an entry in\n `issues[]`, or pointing to a test/lint output. Empty array permitted\n when `status: "PASS"` and there is nothing to cite.\n - `claim` \u2014 one sentence summarizing your mode-specific verdict.\n - OMIT the entire `signal` field when verification was inconclusive\n (e.g., you could not run the tests). Do not fabricate a stance.\n'},"service-setup":{"system.md":"You are installing an AFK background process (telegram bot or daemon) as a macOS LaunchAgent so it auto-starts on login and relaunches on crash. The user-facing surface is the `afk service` command group; you orchestrate its lifecycle and refuse to install in states that would produce a `KeepAlive` crash loop.\n\n## Hard rules\n\n1. **macOS only.** Before doing anything, run `uname` and confirm output is `Darwin`. On anything else, tell the user `afk service` is macOS-only (uses `launchctl` and `~/Library/LaunchAgents/`) and stop. Do not attempt a workaround.\n2. **Use only the sanctioned subcommands.** Never invoke `launchctl` directly, never write to `~/Library/LaunchAgents/` yourself, never read `~/.afk/config/afk.env`. The sanctioned surface:\n - `afk service install <telegram|daemon> [--no-watch] [--dry-run]`\n - `afk service uninstall <name>`\n - `afk service status [name]`\n - `afk service restart <name>`\n - `afk service list`\n - `afk telegram check-token` \u2014 JSON `{set, valid, username?, botId?, reason?}` (only used during pre-flight for the telegram service)\n3. **Never install the telegram service if the token isn't valid.** `KeepAlive=true` + invalid token = infinite crash loop with the log file growing unbounded. If `check-token` doesn't return `valid: true`, route the user to `/telegram-setup` and stop.\n4. **`afk service status` and `afk service list` emit human-formatted text, not JSON.** Parse by looking for substrings: `Not installed`, `Running (PID <n>)`, `Installed but not running`. Do not invent fields.\n\n## The flow\n\n### Step 1 \u2014 Identify the target service\n\nIf the user named a service in the invocation args (`telegram` or `daemon`), use that. Otherwise ask:\n\n> Which AFK service do you want to install as always-on?\n>\n> - `telegram` \u2014 the bot that lets you drive AFK from your phone\n> - `daemon` \u2014 the cron-based headless runner for scheduled tasks\n>\n> (Reply `telegram` or `daemon`.)\n\nWait for their answer. Anything outside the two values: re-ask once, then bail with a clear message if still ambiguous.\n\n### Step 2 \u2014 Platform check\n\nRun `uname`. If the trimmed stdout is not `Darwin`, tell the user:\n\n> `afk service` only works on macOS \u2014 it uses `launchctl` and `~/Library/LaunchAgents/`. On Linux you'd want a systemd user unit (not yet shipped). Detected platform: `<output>`.\n\nThen stop.\n\n### Step 3 \u2014 Check current install state\n\nRun `afk service status <name>`. Three branches based on the human-formatted output:\n\n- Contains `Not installed` \u2192 not installed yet. Continue to Step 4.\n- Contains `Running (PID <n>)` \u2192 already installed and running. Tell the user:\n\n > \u2713 `<name>` is already installed and running (PID <n>). Manage it with:\n > - `afk service status <name>` \u2014 running state + log path\n > - `afk service restart <name>` \u2014 bounce the process\n > - `afk service uninstall <name>` \u2014 stop + remove plist\n > - Log file is shown in the status output above.\n\n Then stop. Do not reinstall.\n\n- Contains `Installed but not running` \u2192 installed but the process exited. Ask:\n\n > `<name>` is installed but not running (last exit may indicate why \u2014 see status output above). Want to restart it (`afk service restart <name>`) or uninstall and reinstall fresh?\n\n Honor the user's choice. If they pick restart, run `afk service restart <name>` and skip to Step 6. If reinstall, run `afk service uninstall <name>` and continue to Step 4.\n\n### Step 4 \u2014 Pre-flight prerequisites\n\nPer service:\n\n**For `telegram`:** run `afk telegram check-token` and parse the JSON.\n\n- `{set: true, valid: true, username: \"FooBot\"}` \u2192 proceed.\n- `{set: false}` or `{valid: false}` \u2192 tell the user:\n\n > Before I install the telegram bot as a LaunchAgent, the bot token needs to be set and valid \u2014 otherwise `KeepAlive` will crash-loop the service. Run `/telegram-setup` first to configure the token, then come back and run `/service-setup telegram`.\n\n Then stop. Do not attempt the install.\n\n**For `daemon`:** no automated pre-flight is run here (the daemon reads schedules from `~/.afk/config/schedules.json` at boot and gracefully handles an empty list). Just warn the user once:\n\n> Note: the daemon reads schedules from `~/.afk/config/schedules.json`. If you haven't created any with `afk schedule add` yet, the service will run idle until you do \u2014 that's fine.\n\nThen continue.\n\n### Step 5 \u2014 Install\n\nRun `afk service install <name>`. Read the human-formatted output:\n\n- `\u2713 Installed com.afk.<name>` \u2192 success. Note the WatchPaths line from the output (telegram only). Continue to Step 6.\n- `\u26A0 ... already installed` \u2192 race with Step 3 (or the user installed manually between steps). Re-run status; do not force-reinstall.\n- `\u2717 Install failed: <reason>` \u2192 surface the exact reason verbatim. Common causes worth naming when you see them:\n - \"Telegram entrypoint resolved to a `.ts` file\" \u2192 user is running from source without building. Tell them to run `pnpm build` first; launchd needs the compiled `.mjs` entrypoint.\n - \"Already bootstrapped\" \u2192 orphan plist from a prior install. Run `afk service uninstall <name>` and retry once.\n\n Then stop. Don't loop indefinitely.\n\n### Step 6 \u2014 Verify\n\nRun `afk service status <name>` again. If the output shows `Running (PID <n>)`:\n\n> \u2713 `<name>` is now running as a LaunchAgent (PID <n>). It will auto-start on login and relaunch if it crashes.\n\nIf it still shows `Installed but not running` after install:\n\n> Plist is installed but the process didn't start. Check the log:\n> ```\n> tail -50 ~/.afk/logs/service-<name>.log\n> ```\n> If you can share the tail, I can help diagnose. Otherwise try `afk service restart <name>` once.\n\nDon't loop \u2014 let the user inspect and come back.\n\n### Step 7 \u2014 Hand off the cheatsheet\n\nEnd with the management commands the user will need later:\n\n> Management:\n> - `afk service status <name>` \u2014 check running state, PID, last exit\n> - `afk service restart <name>` \u2014 bounce after config changes\n> - `afk service uninstall <name>` \u2014 stop and remove the plist\n> - Logs: `~/.afk/logs/service-<name>.log`\n>\n> Note: `afk telegram status` reports \"stopped\" when launchd is the supervisor \u2014 that's expected. Use `afk service status telegram` to introspect the LaunchAgent-managed instance.\n\nThen stop.\n\n## Tone\n\nTerse and operational. One line per step confirmation. Use `\u2713` / `\u2717` markers. Code-fence any command the user should run. Don't narrate the launchd internals unless asked \u2014 the user wants the service running, not a tutorial.\n\n## Surface awareness\n\nIf the user is reaching you over Telegram (mentioned phone, or session metadata indicates so), note once at Step 1:\n\n> Heads up \u2014 `afk service` installs a per-user LaunchAgent on the machine where AFK is installed. You'll need to be on that machine (SSH or local terminal) for the commands I'm about to run. I can still walk through them, but the install happens there.\n"},"telegram-setup":{"system.md":`You are walking the user through first-time Telegram bot setup for AFK (Agent AFK). Your job: get them from "no bot" to a working push-notification channel with the token never leaving their local machine.
|
|
762
|
+
`,"verify.md":'# Phase 6: Verify (Ship-Yesterday Gate)\n\nYou are a quality gate. Your task is to verify the implementation in one specific mode (test, lint, or design-review) \u2014 the orchestrator runs all three modes in parallel.\n\n## Input\nYou are given:\n- The implementation plan from Phase 3 (verification commands, success criteria)\n- The build results from Phase 5 (files changed, test status)\n- Your **mode** \u2014 one of: `test`, `lint`, `design-review`\n\n## Your Task\n\nThe orchestrator runs three modes in parallel: `test` and `lint` are **programmatic** checks; `design-review` is a code-quality review. A green status across all three is the bar to ship.\n\n**If mode is `test`:**\n- Run the full test suite specified in the plan.\n- Capture failures and concrete error messages.\n\n**If mode is `lint`:**\n- Run linting and type-checking.\n- Capture each lint/type error with file:line where possible.\n\n**If mode is `design-review`:**\nEvaluate the implementation diff on two axes \u2014 **spec compliance** (did it build what the plan specified?) and **code quality** (is the build any good?). A red on *either* axis is a FAIL.\n\n**Spec compliance \u2014 check this FIRST, against the Phase 3 plan\'s success criteria (in your input):**\n- **Completeness** \u2014 every success criterion / acceptance condition in the plan has a corresponding change in the diff. A criterion with no implementing change is a blocker.\n- **No scope creep** \u2014 nothing substantive was built beyond what the plan asked for. Unrequested features or behavior changes are a blocker (cite `file:line`).\n- If the plan carries **no explicit success criteria** to check against, do NOT silently treat the global constraints \u2014 or the diff\'s own apparent goals \u2014 as "the spec" and pass. Emit a blocker: `spec-compliance not assessable \u2014 plan lacks explicit success criteria`. A reviewer who invents the spec rubber-stamps everything.\n\n**Code quality \u2014 evaluate the implementation diff across these dimensions:**\n\n1. **Clean code** \u2014 no unnecessary duplication, no dead code, clear names, comments explain "why" not "what", no overbuilt abstractions.\n2. **Modularity** \u2014 single-responsibility files, clean module boundaries, clear public vs. private APIs.\n3. **Scalability** \u2014 no obvious O(n\xB2) in critical paths, no sync ops in unbounded loops, bounded memory in hot paths.\n4. **Clean architecture** \u2014 layering respected, dependencies point the right way, no circular dependencies.\n5. **Repo best practices** \u2014 follows existing patterns, consistent style, test structure matches.\n6. **Intuitive design** \u2014 discoverable API, actionable error messages, consistent names.\n7. **Security hygiene** \u2014 no new secrets in code, safe input handling, no obvious vulnerabilities.\n\nA red on the spec-compliance axis or any code-quality dimension is a FAIL; yellows are nice-to-have and do not block.\n\n## Output\n\nRespond with a single fenced JSON code block and no prose outside it. The JSON must conform to:\n\n```json\n{\n "status": "PASS",\n "status_reason": "short reason \u2014 only when status is FAIL, omit otherwise",\n "issues": ["src/example.ts:42 \u2014 concrete issue description"],\n "summary": "Optional one-paragraph human-readable summary of what was checked.",\n "signal": {\n "issue": "stable-slug-or-question",\n "stance": "supports",\n "confidence": 0.9,\n "evidence": ["src/example.ts:42"],\n "claim": "Implementation passes this verification mode without blockers."\n }\n}\n```\n\nField semantics:\n- `status` \u2014 `"PASS"` if this mode is green; `"FAIL"` if anything red.\n- `status_reason` \u2014 short reason when `FAIL`; omit when `PASS`.\n- `issues` \u2014 concrete blockers with file:line citations where possible. Empty array when `PASS`.\n- `summary` \u2014 optional narrative; the orchestrator may surface it to the user. Keep it concise.\n- `signal` \u2014 OPTIONAL passive-observation field (v0). When the\n implementation cleanly passes or cleanly fails your mode, you MAY emit a\n `signal` object conforming to the shape shown. See `docs/signal-block.md`\n for the full convention. Rules:\n - `issue` \u2014 a stable slug naming what was checked (e.g.\n `"verify-test-mode"`, `"verify-lint-mode"`, `"verify-design-review"`).\n Use the same slug across reruns of the same mode.\n - `stance` \u2014 `supports` when `status: "PASS"`; `opposes` when\n `status: "FAIL"`; `uncertain` when issues are real but ambiguous;\n `blocks` when the verification tool itself failed (e.g. test runner\n crashed).\n - `confidence` \u2014 how sure you are about the verdict, not how sure you\n are that the code is good overall.\n - `evidence` \u2014 at least one `file:line` citation matching an entry in\n `issues[]`, or pointing to a test/lint output. Empty array permitted\n when `status: "PASS"` and there is nothing to cite.\n - `claim` \u2014 one sentence summarizing your mode-specific verdict.\n - OMIT the entire `signal` field when verification was inconclusive\n (e.g., you could not run the tests). Do not fabricate a stance.\n'},"service-setup":{"system.md":"You are installing an AFK background process (telegram bot or daemon) as a macOS LaunchAgent so it auto-starts on login and relaunches on crash. The user-facing surface is the `afk service` command group; you orchestrate its lifecycle and refuse to install in states that would produce a `KeepAlive` crash loop.\n\n## Hard rules\n\n1. **macOS only.** Before doing anything, run `uname` and confirm output is `Darwin`. On anything else, tell the user `afk service` is macOS-only (uses `launchctl` and `~/Library/LaunchAgents/`) and stop. Do not attempt a workaround.\n2. **Use only the sanctioned subcommands.** Never invoke `launchctl` directly, never write to `~/Library/LaunchAgents/` yourself, never read `~/.afk/config/afk.env`. The sanctioned surface:\n - `afk service install <telegram|daemon> [--no-watch] [--dry-run]`\n - `afk service uninstall <name>`\n - `afk service status [name]`\n - `afk service restart <name>`\n - `afk service list`\n - `afk telegram check-token` \u2014 JSON `{set, valid, username?, botId?, reason?}` (only used during pre-flight for the telegram service)\n3. **Never install the telegram service if the token isn't valid.** `KeepAlive=true` + invalid token = infinite crash loop with the log file growing unbounded. If `check-token` doesn't return `valid: true`, route the user to `/telegram-setup` and stop.\n4. **`afk service status` and `afk service list` emit human-formatted text, not JSON.** Parse by looking for substrings: `Not installed`, `Running (PID <n>)`, `Installed but not running`. Do not invent fields.\n\n## The flow\n\n### Step 1 \u2014 Identify the target service\n\nIf the user named a service in the invocation args (`telegram` or `daemon`), use that. Otherwise ask:\n\n> Which AFK service do you want to install as always-on?\n>\n> - `telegram` \u2014 the bot that lets you drive AFK from your phone\n> - `daemon` \u2014 the cron-based headless runner for scheduled tasks\n>\n> (Reply `telegram` or `daemon`.)\n\nWait for their answer. Anything outside the two values: re-ask once, then bail with a clear message if still ambiguous.\n\n### Step 2 \u2014 Platform check\n\nRun `uname`. If the trimmed stdout is not `Darwin`, tell the user:\n\n> `afk service` only works on macOS \u2014 it uses `launchctl` and `~/Library/LaunchAgents/`. On Linux you'd want a systemd user unit (not yet shipped). Detected platform: `<output>`.\n\nThen stop.\n\n### Step 3 \u2014 Check current install state\n\nRun `afk service status <name>`. Three branches based on the human-formatted output:\n\n- Contains `Not installed` \u2192 not installed yet. Continue to Step 4.\n- Contains `Running (PID <n>)` \u2192 already installed and running. Tell the user:\n\n > \u2713 `<name>` is already installed and running (PID <n>). Manage it with:\n > - `afk service status <name>` \u2014 running state + log path\n > - `afk service restart <name>` \u2014 bounce the process\n > - `afk service uninstall <name>` \u2014 stop + remove plist\n > - Log file is shown in the status output above.\n\n Then stop. Do not reinstall.\n\n- Contains `Installed but not running` \u2192 installed but the process exited. Ask:\n\n > `<name>` is installed but not running (last exit may indicate why \u2014 see status output above). Want to restart it (`afk service restart <name>`) or uninstall and reinstall fresh?\n\n Honor the user's choice. If they pick restart, run `afk service restart <name>` and skip to Step 6. If reinstall, run `afk service uninstall <name>` and continue to Step 4.\n\n### Step 4 \u2014 Pre-flight prerequisites\n\nPer service:\n\n**For `telegram`:** run `afk telegram check-token` and parse the JSON.\n\n- `{set: true, valid: true, username: \"FooBot\"}` \u2192 proceed.\n- `{set: false}` or `{valid: false}` \u2192 tell the user:\n\n > Before I install the telegram bot as a LaunchAgent, the bot token needs to be set and valid \u2014 otherwise `KeepAlive` will crash-loop the service. Run `/telegram-setup` first to configure the token, then come back and run `/service-setup telegram`.\n\n Then stop. Do not attempt the install.\n\n**For `daemon`:** no automated pre-flight is run here (the daemon reads schedules from `~/.afk/config/schedules.json` at boot and gracefully handles an empty list). Just warn the user once:\n\n> Note: the daemon reads schedules from `~/.afk/config/schedules.json`. If you haven't created any with `afk schedule add` yet, the service will run idle until you do \u2014 that's fine.\n\nThen continue.\n\n### Step 5 \u2014 Install\n\nRun `afk service install <name>`. Read the human-formatted output:\n\n- `\u2713 Installed com.afk.<name>` \u2192 success. Note the WatchPaths line from the output (telegram only). Continue to Step 6.\n- `\u26A0 ... already installed` \u2192 race with Step 3 (or the user installed manually between steps). Re-run status; do not force-reinstall.\n- `\u2717 Install failed: <reason>` \u2192 surface the exact reason verbatim. Common causes worth naming when you see them:\n - \"Telegram entrypoint resolved to a `.ts` file\" \u2192 user is running from source without building. Tell them to run `pnpm build` first; launchd needs the compiled `.mjs` entrypoint.\n - \"Already bootstrapped\" \u2192 orphan plist from a prior install. Run `afk service uninstall <name>` and retry once.\n\n Then stop. Don't loop indefinitely.\n\n### Step 6 \u2014 Verify\n\nRun `afk service status <name>` again. If the output shows `Running (PID <n>)`:\n\n> \u2713 `<name>` is now running as a LaunchAgent (PID <n>). It will auto-start on login and relaunch if it crashes.\n\nIf it still shows `Installed but not running` after install:\n\n> Plist is installed but the process didn't start. Check the log:\n> ```\n> tail -50 ~/.afk/logs/service-<name>.log\n> ```\n> If you can share the tail, I can help diagnose. Otherwise try `afk service restart <name>` once.\n\nDon't loop \u2014 let the user inspect and come back.\n\n### Step 7 \u2014 Hand off the cheatsheet\n\nEnd with the management commands the user will need later:\n\n> Management:\n> - `afk service status <name>` \u2014 check running state, PID, last exit\n> - `afk service restart <name>` \u2014 bounce after config changes\n> - `afk service uninstall <name>` \u2014 stop and remove the plist\n> - Logs: `~/.afk/logs/service-<name>.log`\n>\n> Note: `afk telegram status` reports \"stopped\" when launchd is the supervisor \u2014 that's expected. Use `afk service status telegram` to introspect the LaunchAgent-managed instance.\n\nThen stop.\n\n## Tone\n\nTerse and operational. One line per step confirmation. Use `\u2713` / `\u2717` markers. Code-fence any command the user should run. Don't narrate the launchd internals unless asked \u2014 the user wants the service running, not a tutorial.\n\n## Surface awareness\n\nIf the user is reaching you over Telegram (mentioned phone, or session metadata indicates so), note once at Step 1:\n\n> Heads up \u2014 `afk service` installs a per-user LaunchAgent on the machine where AFK is installed. You'll need to be on that machine (SSH or local terminal) for the commands I'm about to run. I can still walk through them, but the install happens there.\n"},"telegram-setup":{"system.md":`You are walking the user through first-time Telegram bot setup for AFK (Agent AFK). Your job: get them from "no bot" to a working push-notification channel with the token never leaving their local machine.
|
|
763
763
|
|
|
764
764
|
## Hard rules (read before doing anything)
|
|
765
765
|
|
|
@@ -1068,7 +1068,7 @@ ${o}`;return s.includes("already checked out")||s.includes("is already used by w
|
|
|
1068
1068
|
Effective base URL: ${r}`)),r}return t}function wB(){if(df!==void 0)return df;if(!XS){let o=[Yi(process.cwd(),".env"),at(),Kb()];for(let s of o)pf(s)&&yB({path:s,override:!1});XS=!0}let e={},t=k.AFK_MODEL??k.CLAUDE_MODEL;if(t){let o=t.toLowerCase();e.model=Rm(o)?o:t}if(re(t)==="anthropic-direct"){let o=mf();o!==void 0&&(e.apiKey=o)}let r=k.AFK_LOCAL_BASE_URL;if(r&&r.length>0&&(e.baseUrl=r,e.apiKey=k.AFK_LOCAL_API_KEY||"local"),k.AFK_MAX_TOKENS&&(e.maxTokens=parseInt(k.AFK_MAX_TOKENS,10)),k.AFK_TEMPERATURE&&(e.temperature=parseFloat(k.AFK_TEMPERATURE)),k.AFK_SYSTEM_PROMPT&&(e.systemPrompt=k.AFK_SYSTEM_PROMPT),k.AFK_AUTO_ROUTING){let o=k.AFK_AUTO_ROUTING.toLowerCase()==="true";e.autoRouting={interactive:o,chat:o,telegram:o,daemon:o}}return k.AFK_OPENAI_BASE_URL&&(e.openaiBaseUrl=bB(k.AFK_OPENAI_BASE_URL)),df=e,e}function ev(){if(bs!==void 0)return bs;let e=[Yi(process.cwd(),"afk.config.json"),_t(),Al()];for(let t of e)if(pf(t))try{let n=QS(t,"utf-8"),r=JSON.parse(n),o={},s=_w(r.models);if(typeof r.model=="string"&&r.model.length>0){let i=r.model.toLowerCase();o.model=Rm(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),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 l={};if((a.mode==="primary"||a.mode==="broadcast"||a.mode==="custom")&&(l.mode=a.mode),typeof a.primaryChatId=="number"&&Number.isFinite(a.primaryChatId)&&(l.primaryChatId=a.primaryChatId),Array.isArray(a.targets)){let c=a.targets.filter(u=>typeof u=="number"&&Number.isFinite(u));c.length>0&&(l.targets=c)}i.notify=l}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),t!==Yi(process.cwd(),"afk.config.json")){let i=Ji(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=af(r.interactive.worktreeBranchPrefix,`${t}#/interactive/worktreeBranchPrefix`)),typeof r.interactive.worktreeBase=="string"&&r.interactive.worktreeBase.trim().length>0&&(lf(r.interactive.worktreeBase,`${t}#/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 bs={config:o,sourcePath:t,modelsPartial:s},bs}catch(n){console.error(`Warning: Failed to parse ${t}:`,n)}return bs={config:{},sourcePath:void 0,modelsPartial:{}},bs}function SB(){if(ws!==void 0)return ws.value;let e=[Yi(process.cwd(),"AFK.md"),Yi(Ae(),"AFK.md")];for(let t of e)if(pf(t))try{let n=QS(t,"utf-8").trim();if(n.length>0)return ws={value:{content:n,path:t}},ws.value}catch{}return ws={value:null},ws.value}function tv(){return ev().config.telegram??{}}function yt(e){let t=wB(),{config:n,sourcePath:r,modelsPartial:o}=ev(),s={...Vi,...t,...n,...e},i;if(t.systemPrompt!==void 0)i="env:AFK_SYSTEM_PROMPT";else if(n.systemPrompt!==void 0&&r!==void 0)i=`file:${r}`;else if(s.systemPrompt===void 0){let c=SB();c!==null&&(s.systemPrompt=c.content,i=`afk-md:${c.path}`)}let a={model:s.model??Vi.model,maxTokens:s.maxTokens??Vi.maxTokens,temperature:s.temperature??Vi.temperature,updatePolicy:s.updatePolicy??Vi.updatePolicy,...s.apiKey!==void 0?{apiKey:s.apiKey}:{},...s.baseUrl!==void 0?{baseUrl:s.baseUrl}:{},...s.openaiBaseUrl!==void 0?{openaiBaseUrl:s.openaiBaseUrl}:{},...s.systemPrompt!==void 0?{systemPrompt:s.systemPrompt}:{},...i!==void 0?{systemPromptSource:i}:{},...s.autoRouting!==void 0?{autoRouting:s.autoRouting}:{},...s.daemon!==void 0?{daemon:s.daemon}:{},...s.telegram!==void 0?{telegram:s.telegram}:{},...s.bgSummaries!==void 0?{bgSummaries:s.bgSummaries}:{},...s.maxSummaryCallsPerSession!==void 0?{maxSummaryCallsPerSession:s.maxSummaryCallsPerSession}:{},...s.interactive!==void 0?{interactive:s.interactive}:{},...s.hooks!==void 0?{hooks:s.hooks}:{},...s.enableShellHooks!==void 0?{enableShellHooks:s.enableShellHooks}:{},...s.importFrom!==void 0?{importFrom:s.importFrom}:{}},l=e?.models??xm(o);if(Wl(l),a.models=l,typeof a.model=="string"&&a.model.toLowerCase().startsWith("local-")&&(a.baseUrl===void 0||a.baseUrl.length===0))throw new Error(`Model '${a.model}' requires AFK_LOCAL_BASE_URL to be set (e.g. AFK_LOCAL_BASE_URL=http://127.0.0.1:8080). Point it at your local Anthropic-Messages-compatible server.`);return a}var Vi,XS,df,ZS,bs,ws,Hn=_(()=>{"use strict";Pn();Wt();Je();K();hs();qi();G();no();Vi={model:"sonnet",maxTokens:4096,temperature:1,updatePolicy:"notify"},XS=!1;ZS=new Set});function vB(e,t){return t!==void 0&&Number.isFinite(t)&&t!==0?t:e.find(r=>r>0)??e[0]}function kB(e,t={}){let n=[...e],r=t.mode??"primary";if(r==="broadcast")return n;if(r==="custom"){let s=(t.targets??[]).filter(i=>typeof i=="number"&&Number.isFinite(i)&&i!==0);if(s.length>0)return[...new Set(s)]}let o=vB(n,t.primaryChatId);return o!==void 0?[o]:[]}function xB(e){if(!e)return;let t=e.trim();if(!/^-?\d+$/.test(t))return;let n=Number(t);return Number.isFinite(n)&&n!==0?n:void 0}function EB(e){if(!e)return;let t=e.trim().toLowerCase();return t==="primary"||t==="broadcast"||t==="custom"?t:void 0}function TB(){let e=tv().notify??{},t=e.mode??EB(k.AFK_TELEGRAM_NOTIFY_MODE),n=e.primaryChatId??xB(k.AFK_TELEGRAM_PRIMARY_CHAT_ID);return{...t!==void 0?{mode:t}:{},...n!==void 0?{primaryChatId:n}:{},...e.targets!==void 0?{targets:e.targets}:{}}}function kc(){let e=OS(k.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return kB(e,TB())}var ff=_(()=>{"use strict";$S();Hn();G()});function nv(e,t=4096){if(e.length<=t)return[e];let n=[],r=e;for(;r.length>0;){if(r.length<=t){n.push(r);break}let o=t,s=r.lastIndexOf(`
|
|
1069
1069
|
`,t);if(s>t-500&&s>0)o=s+1;else{let i=r.slice(0,t).match(/[.!?]\s+(?=[A-Z])/g);if(i&&i.length>0){let a=i[i.length-1];if(a){let l=r.lastIndexOf(a,t);l>t-200&&l>0&&(o=l+2)}}else{let a=r.lastIndexOf(" ",t);a>t-100&&a>0&&(o=a+1)}}n.push(r.slice(0,o).trim()),r=r.slice(o).trim()}return n}var rv=_(()=>{"use strict"});var gf={};vl(gf,{push:()=>xc,pushIfConfigured:()=>Ss});async function xc(e){if(!e.token)throw new Error("push: token is required");if(e.chatId===""||e.chatId==null||e.chatId===0)throw new Error("push: chatId is required");let t=e.fetchImpl??fetch,r=`${e.apiBase??RB}/bot${e.token}/sendMessage`,o={chat_id:e.chatId,text:e.text.slice(0,4096)};e.parseMode&&(o.parse_mode=e.parseMode),e.replyMarkup&&(o.reply_markup=e.replyMarkup);let s=new AbortController,i=setTimeout(()=>s.abort(),1e4);try{let a=await t(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:s.signal});if(a.ok)return{ok:!0,status:a.status};let l;try{l=(await a.json()).description}catch{l=`HTTP ${a.status}`}return{ok:!1,status:a.status,...l!==void 0?{errorMessage:l}:{}}}catch(a){return{ok:!1,status:0,errorMessage:a instanceof Error?a.message:String(a)}}finally{clearTimeout(i)}}async function Ss(e,t={}){let n=k.TELEGRAM_BOT_TOKEN;if(!n)return null;let r=kc();if(r.length===0)return null;let o=nv(e),s=[];for(let i of r)for(let a=0;a<o.length;a++)s.push(await xc({token:n,chatId:i,text:o[a]??"",...t.parseMode!==void 0?{parseMode:t.parseMode}:{},...t.replyMarkup!==void 0&&a===0?{replyMarkup:t.replyMarkup}:{},...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{}}));return s}var RB,vs=_(()=>{"use strict";ff();rv();G();RB="https://api.telegram.org"});function CB(e=xc){return async(t,n)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let o=t.message;if(typeof o!="string")return{content:"Invalid input: message must be a string",isError:!0};if(o.length===0)return{content:"Invalid input: message must be non-empty",isError:!0};if(o.length>ov)return{content:`Invalid input: message exceeds Telegram's ${ov}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let s=k.TELEGRAM_BOT_TOKEN;if(!s)return{content:"Telegram is not configured: TELEGRAM_BOT_TOKEN is not set. Run the bot setup wizard or export the env var before using send_telegram.",isError:!0};let i=kc();if(i.length===0)return{content:"Telegram is not configured: AFK_TELEGRAM_ALLOWED_CHAT_IDS is empty or unset. Add the operator chat ID(s) before using send_telegram.",isError:!0};let a=[];for(let l of i){let c=await e({token:s,chatId:l,text:o});c.ok||a.push(`chat ${l}: ${c.errorMessage??`HTTP ${c.status}`}`)}return a.length===i.length?{content:`Failed to send Telegram message to any chat. ${a.join("; ")}`,isError:!0}:a.length>0?{content:`Sent Telegram message to ${i.length-a.length}/${i.length} chat(s); ${a.length} failed: ${a.join("; ")}`}:{content:i.length===1?`Sent Telegram message to chat ${i[0]}.`:`Sent Telegram message to ${i.length} chats.`}}}var ov,sv,iv=_(()=>{"use strict";G();vs();ff();ov=4096;sv=CB()});import{JSDOM as _B}from"jsdom";import{Readability as AB}from"@mozilla/readability";import IB from"turndown";function av(e){return e.replace(/\n{3,}/g,`
|
|
1070
1070
|
|
|
1071
|
-
`).trim()}function PB(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function cv(e,t){let r=new _B(e,{url:t}).window.document,o=(r.title??"").trim(),s=null;try{let c=r.cloneNode(!0);s=new AB(c).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let c=av(hf.turndown(s.content)),u=(s.title??"").trim()||o,d=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:u,markdown:c,textLength:d,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",l=av(hf.turndown(a));return{title:o,markdown:l,textLength:PB(i),usedFallback:!0}}var lv,hf,uv=_(()=>{"use strict";lv=200,hf=new IB({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});hf.remove(["script","style","noscript","iframe"])});import{readFileSync as MB}from"node:fs";import{join as OB}from"path";function $B(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function dv(e,t){return $B(t).test(e)}function FB(e,t){if(e!==void 0){let n=e.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(t!==void 0){if(DB.has(t))return!0;if(LB.has(t))return!1}return!1}function pv(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function NB(e){if(e===void 0||e===""||e==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${e}`)}function BB(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function UB(e){try{return MB(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function jB(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return n}function mv(e){let t=e?.env??k,n=e?.readFileSync??UB,r=e?.surface??t.AGENT_SURFACE,o=FB(t.AFK_BROWSER_HEADLESS,r),s=pv(t.AFK_BROWSER_ALLOWED_DOMAINS),i=pv(t.AFK_BROWSER_BLOCKED_DOMAINS),a=BB(t.AFK_BROWSER_DOM_SNAPSHOTS),l=NB(t.AFK_BROWSER_BACKEND),c={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null},u=t.AFK_BROWSER_CONFIG,d=u!==void 0&&u.trim()!==""?u.trim():OB(tn(),"browser.json"),m=n(d);if(m===void 0)return c;let f;try{f=JSON.parse(m)}catch(h){throw new Error(`Failed to parse browser config at ${d}: ${String(h)}`)}if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`Browser config at ${d} must be a JSON object`);let g=jB(c,f);return g.configPath=d,g}function yf(e,t){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${e}`}}for(let r of t.blockedDomains)if(dv(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>dv(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var DB,LB,bf=_(()=>{"use strict";G();K();DB=new Set(["daemon","subagent","telegram"]),LB=new Set(["repl","interactive","cli"])});import HB from"node:fs";import WB from"node:path";import{chromium as KB}from"playwright";function GB(){try{return"4.9.0"}catch{}try{let e=WB.resolve(import.meta.dirname,"../../../package.json"),t=HB.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var zB,Ec,fv=_(()=>{"use strict";zB=GB(),Ec=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(t){this.config=t}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=KB.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s={context:o,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),o}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",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(t){return this.sessions.get(t)?.page}async renderHtml(t,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(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await i.content(),c=i.url(),u=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${zB}`}}}});import{createHash as qB}from"crypto";function wf(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of JB)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function gv(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&VB.test(e.label))}function hv(e){return qB("sha256").update(e,"utf8").digest("hex").slice(0,8)}function yv(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var JB,VB,Xi=_(()=>{"use strict";JB=[{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}];VB=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as YB}from"node:crypto";function XB(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function ZB(e,t,n){return`el_${YB("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function QB(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function bv(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Sv(e,t){let n=e.role??"",r=e.name??"";wv.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let s of e.children??[])Sv(s,t)}async function eU(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let u=window.getComputedStyle(i);if(u.display==="none"||u.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},vv).catch(()=>[])}async function tU(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let h=s.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let u="value"in s?s.value:void 0,d=u!==void 0?String(u):void 0,m=s.disabled??!1,f=i==="input"?s.checked:void 0,g={role:c,name:l,disabled:m};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},vv).catch(()=>[])}function nU(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Tc(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],s=nU(e),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=eU(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,m,f,g,h]=await Promise.all([i,a,l,c,u]),b,y=!1;d!==null?(b=[],Sv(d,b)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,b=(await tU(e)).filter($=>wv.has($.role??"")));let v=new Map;for(let M of m){let $=bv(M.name),L=v.get($);(!L||L.bbox.w===0&&M.bbox.w>0)&&v.set($,M)}let w=b.map(M=>({ax:M,dom:v.get(bv(M.name??""))})),T=r?w:w.filter(M=>M.dom?M.dom.bbox.w>0||M.dom.bbox.h>0:!0);T.sort((M,$)=>{let L=M.dom?.bbox.y??0,B=$.dom?.bbox.y??0;if(L!==B)return L-B;let U=M.dom?.bbox.x??0,D=$.dom?.bbox.x??0;return U-D}),T.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=T.slice(0,n).map((M,$)=>{let L=M.ax.role??"generic",B=M.ax.name??"",U=ZB(L,B,$),D=M.dom?.bbox??{x:0,y:0,w:0,h:0},F=M.dom?.type??null,j=null;M.ax.value!==void 0&&M.ax.value!==null&&(j=String(M.ax.value)),M.ax.checked!==void 0&&(j=String(M.ax.checked)),gv({role:L,kind:F})&&(j="[redacted]");let N={disabled:M.ax.disabled??!1};M.ax.checked!==void 0&&(N.checked=M.ax.checked===!0||M.ax.checked==="mixed"),M.ax.selected!==void 0&&(N.selected=M.ax.selected),M.ax.expanded!==void 0&&(N.expanded=M.ax.expanded);let O;M.dom?.testId?O=`[data-testid="${M.dom.testId}"]`:M.dom?.id&&(O=`#${M.dom.id}`);let J={id:U,role:L,label:XB(B),kind:F,value:j,state:N,bbox:D};return O!==void 0&&(J.selector=O),J}),C="idle";try{let M=await e.evaluate(()=>document.readyState);M==="loading"?C="loading":M==="interactive"?C="navigating":C="idle"}catch{C="navigating"}C!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let S=QB(f),P=`obs_${t.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:P,url:g,title:h,textSummary:S,interactive:R,status:{httpStatus:t.httpStatus??null,loadingState:C,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:A}}var wv,vv,kv=_(()=>{"use strict";Xi();wv=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);vv="a[href], button, input, select, textarea, [role], [tabindex], label"});async function xv(e,t){try{let n=await e.nth(t).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.height)}}),r=`${n.role}:${n.label}:${t}`,o=0;for(let 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 Sf(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,s)=>xv(e,s)))).filter(o=>o!==null)}async function rU(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(i)||(t.add(i),n.push({key:i,locator:r,index:s}))}return n}async function vf(e,t,n){switch(t.kind){case"element_id":return oU(e,t,n);case"selector":return sU(e,t);case"semantic":return iU(e,t)}}async function oU(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:t};if(s===1)return{outcome:"resolved",locator:o};let i=await Sf(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function sU(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await Sf(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function iU(e,t){return t.role!==void 0?aU(e,t.text,t.role):lU(e,t.text,t)}async function aU(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Sf(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:s}}async function lU(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),s=e.getByLabel(t,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let u=[];i>0&&u.push({loc:r,count:i}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:s,count:l});let d=await rU(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let m=d.slice(0,5),f=[];for(let h=0;h<m.length;h++){let b=m[h];if(b===void 0)continue;let y=await xv(b.locator,b.index);if(y!==null){let v=`${y.role}:${y.label}:${h}`,w=0;for(let T=0;T<v.length;T++)w=w*31+v.charCodeAt(T)>>>0;f.push({...y,id:`el_${w.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var Ev=_(()=>{"use strict"});import{randomBytes as cU}from"crypto";import{mkdir as uU,stat as dU,writeFile as pU}from"fs/promises";import{join as kf}from"path";import{gzip as mU}from"zlib";import{promisify as fU}from"util";function gU(e){return kf(Yo(e),"browser")}function hU(e){return kf(gU(e),"screenshots")}function yU(){return new Date().toISOString().replace(/[:.]/g,"-")}function bU(){return cU(3).toString("hex")}async function xf(e,t,n){if(t.length>Tv)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Tv} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=hU(e);await uU(r,{recursive:!0});let o=`${yU()}-${bU()}-${n}.png`,s=kf(r,o);await pU(s,t);let{size:i}=await dU(s);return{path:s,bytes:i}}var ese,Tv,Rv=_(()=>{"use strict";K();Xi();ese=fU(mU);Tv=5*1024*1024});var _v={};vl(_v,{PlaywrightProvider:()=>Ef});function Cv(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var Ef,Av=_(()=>{"use strict";fv();kv();Ev();bf();Xi();Rv();Ef=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Ec(t)}async open(t){let n=yf(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(c){a=c}(t.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await Tc(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,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;t.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Tc(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=t.timeoutMs??3e4,a=await vf(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Cv(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=async()=>{switch(t.action){case"click":await l.click({timeout:i});break;case"fill":{let h=wf(t.value??"");await l.fill(t.value??"");break}case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=r.url();if(d!==s){let h=yf(d,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:d,reason:h.reason}}let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Tc(r,{observationCounter:o.observationCounter,screenshotPath:m,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(t.target!==void 0){let u=await vf(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Cv(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await u.locator.screenshot()}else s=await r.screenshot({fullPage:t.fullPage??!1});let{path:i,bytes:a}=await xf(n,s,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(t){let n=this.sessions.get(t);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(t,r),r}updateSessionFromObservation(t,n,r,o,s){t.knownElements=new Map(n.map(i=>[i.id,i])),t.currentUrl=r,t.currentTitle=o,t.lastAction=s,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:s}=await xf(n,o,r);return s}catch{return null}}}});var oo={};vl(oo,{__resetBrowserRegistryForTests:()=>xU,browserProviderActive:()=>vU,closeBrowserProvider:()=>Tf,getBrowserProvider:()=>SU,peekBrowserProvider:()=>kU});function Iv(){Promise.resolve(Tf()).then(()=>{process.exit(130)})}function Pv(){Promise.resolve(Tf()).then(()=>{process.exit(143)})}function Mv(){ln=null}function wU(){Rc||(process.on("SIGINT",Iv),process.on("SIGTERM",Pv),process.on("exit",Mv),Rc=!0)}function Ov(){Rc&&(process.removeListener("SIGINT",Iv),process.removeListener("SIGTERM",Pv),process.removeListener("exit",Mv),Rc=!1)}async function SU(e){return ln!==null?ln:(ro!==null||(ro=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(Av(),_v)),n=mv(e),r=new t(n);return wU(),ln=r,ro=null,r})()),ro)}async function Tf(){if(ln===null)return;let e=ln;ln=null,ro=null,Ov(),await e.shutdown()}function vU(){return ln!==null}function kU(){return ln}function xU(){ln=null,ro=null,Ov()}var ln,ro,Rc,so=_(()=>{"use strict";bf();ln=null,ro=null,Rc=!1});function $v(e,t){try{return cv(e,t)}catch(n){return V("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function _U(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(so(),oo));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function Dv(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??_U,o=null,s=e,i=null,a=null;try{let c=await n(e,{headers:CU,redirect:"follow",signal:t.signal});i=c.status,s=c.url||e;let u=c.headers.get("content-type")??"";if(c.ok){if(RU.test(u))throw new Error(`web_scrape markdown mode received binary content (${u.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let d=await c.text();if(TU.test(u)&&!EU.test(u))return{title:"",markdown:d.trim(),finalUrl:s,usedRender:!1};o=$v(d,s)}}catch(c){if(t.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<lv)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let c=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal}),u=$v(c.html,c.finalUrl);if(o===null||u.textLength>=o.textLength)return{title:u.title,markdown:u.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(t.signal.aborted)throw c;if(o===null){let u=c instanceof Error?c.message:String(c),d=a instanceof Error?a.message:`HTTP ${i??"error"}`,m=new Error(`web_scrape could not retrieve ${e}: fetch failed (${d}) and render failed (${u}).`);throw m.cause=c,m}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${i??"error"}).`)}var EU,TU,RU,CU,Lv=_(()=>{"use strict";uv();Pe();EU=/(text\/html|application\/xhtml\+xml)/i,TU=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,RU=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,CU={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function PU(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await t(AU,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),IU),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let u=await s.text(),d=pc(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}catch{}let c=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${c}${l}`)}let i;try{i=await s.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(i.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function Fv(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?PU({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function Nv(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
1071
|
+
`).trim()}function PB(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function cv(e,t){let r=new _B(e,{url:t}).window.document,o=(r.title??"").trim(),s=null;try{let c=r.cloneNode(!0);s=new AB(c).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let c=av(hf.turndown(s.content)),u=(s.title??"").trim()||o,d=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:u,markdown:c,textLength:d,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",l=av(hf.turndown(a));return{title:o,markdown:l,textLength:PB(i),usedFallback:!0}}var lv,hf,uv=_(()=>{"use strict";lv=200,hf=new IB({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});hf.remove(["script","style","noscript","iframe"])});import{readFileSync as MB}from"node:fs";import{join as OB}from"path";function $B(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function dv(e,t){return $B(t).test(e)}function FB(e,t){if(e!==void 0){let n=e.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(t!==void 0){if(DB.has(t))return!0;if(LB.has(t))return!1}return!1}function pv(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function NB(e){if(e===void 0||e===""||e==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${e}`)}function BB(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function UB(e){try{return MB(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function jB(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return n}function mv(e){let t=e?.env??k,n=e?.readFileSync??UB,r=e?.surface??t.AGENT_SURFACE,o=FB(t.AFK_BROWSER_HEADLESS,r),s=pv(t.AFK_BROWSER_ALLOWED_DOMAINS),i=pv(t.AFK_BROWSER_BLOCKED_DOMAINS),a=BB(t.AFK_BROWSER_DOM_SNAPSHOTS),l=NB(t.AFK_BROWSER_BACKEND),c={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null},u=t.AFK_BROWSER_CONFIG,d=u!==void 0&&u.trim()!==""?u.trim():OB(tn(),"browser.json"),m=n(d);if(m===void 0)return c;let f;try{f=JSON.parse(m)}catch(h){throw new Error(`Failed to parse browser config at ${d}: ${String(h)}`)}if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`Browser config at ${d} must be a JSON object`);let g=jB(c,f);return g.configPath=d,g}function yf(e,t){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${e}`}}for(let r of t.blockedDomains)if(dv(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>dv(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var DB,LB,bf=_(()=>{"use strict";G();K();DB=new Set(["daemon","subagent","telegram"]),LB=new Set(["repl","interactive","cli"])});import HB from"node:fs";import WB from"node:path";import{chromium as KB}from"playwright";function GB(){try{return"4.9.1"}catch{}try{let e=WB.resolve(import.meta.dirname,"../../../package.json"),t=HB.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var zB,Ec,fv=_(()=>{"use strict";zB=GB(),Ec=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(t){this.config=t}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=KB.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s={context:o,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),o}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",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(t){return this.sessions.get(t)?.page}async renderHtml(t,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(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await i.content(),c=i.url(),u=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${zB}`}}}});import{createHash as qB}from"crypto";function wf(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of JB)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function gv(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&VB.test(e.label))}function hv(e){return qB("sha256").update(e,"utf8").digest("hex").slice(0,8)}function yv(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var JB,VB,Xi=_(()=>{"use strict";JB=[{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}];VB=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as YB}from"node:crypto";function XB(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function ZB(e,t,n){return`el_${YB("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function QB(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function bv(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Sv(e,t){let n=e.role??"",r=e.name??"";wv.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let s of e.children??[])Sv(s,t)}async function eU(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let u=window.getComputedStyle(i);if(u.display==="none"||u.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},vv).catch(()=>[])}async function tU(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let h=s.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let u="value"in s?s.value:void 0,d=u!==void 0?String(u):void 0,m=s.disabled??!1,f=i==="input"?s.checked:void 0,g={role:c,name:l,disabled:m};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},vv).catch(()=>[])}function nU(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Tc(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],s=nU(e),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=eU(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,m,f,g,h]=await Promise.all([i,a,l,c,u]),b,y=!1;d!==null?(b=[],Sv(d,b)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,b=(await tU(e)).filter($=>wv.has($.role??"")));let v=new Map;for(let M of m){let $=bv(M.name),L=v.get($);(!L||L.bbox.w===0&&M.bbox.w>0)&&v.set($,M)}let w=b.map(M=>({ax:M,dom:v.get(bv(M.name??""))})),T=r?w:w.filter(M=>M.dom?M.dom.bbox.w>0||M.dom.bbox.h>0:!0);T.sort((M,$)=>{let L=M.dom?.bbox.y??0,B=$.dom?.bbox.y??0;if(L!==B)return L-B;let U=M.dom?.bbox.x??0,D=$.dom?.bbox.x??0;return U-D}),T.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=T.slice(0,n).map((M,$)=>{let L=M.ax.role??"generic",B=M.ax.name??"",U=ZB(L,B,$),D=M.dom?.bbox??{x:0,y:0,w:0,h:0},F=M.dom?.type??null,j=null;M.ax.value!==void 0&&M.ax.value!==null&&(j=String(M.ax.value)),M.ax.checked!==void 0&&(j=String(M.ax.checked)),gv({role:L,kind:F})&&(j="[redacted]");let N={disabled:M.ax.disabled??!1};M.ax.checked!==void 0&&(N.checked=M.ax.checked===!0||M.ax.checked==="mixed"),M.ax.selected!==void 0&&(N.selected=M.ax.selected),M.ax.expanded!==void 0&&(N.expanded=M.ax.expanded);let O;M.dom?.testId?O=`[data-testid="${M.dom.testId}"]`:M.dom?.id&&(O=`#${M.dom.id}`);let J={id:U,role:L,label:XB(B),kind:F,value:j,state:N,bbox:D};return O!==void 0&&(J.selector=O),J}),C="idle";try{let M=await e.evaluate(()=>document.readyState);M==="loading"?C="loading":M==="interactive"?C="navigating":C="idle"}catch{C="navigating"}C!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let S=QB(f),P=`obs_${t.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:P,url:g,title:h,textSummary:S,interactive:R,status:{httpStatus:t.httpStatus??null,loadingState:C,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:A}}var wv,vv,kv=_(()=>{"use strict";Xi();wv=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);vv="a[href], button, input, select, textarea, [role], [tabindex], label"});async function xv(e,t){try{let n=await e.nth(t).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.height)}}),r=`${n.role}:${n.label}:${t}`,o=0;for(let 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 Sf(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,s)=>xv(e,s)))).filter(o=>o!==null)}async function rU(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(i)||(t.add(i),n.push({key:i,locator:r,index:s}))}return n}async function vf(e,t,n){switch(t.kind){case"element_id":return oU(e,t,n);case"selector":return sU(e,t);case"semantic":return iU(e,t)}}async function oU(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:t};if(s===1)return{outcome:"resolved",locator:o};let i=await Sf(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function sU(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await Sf(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function iU(e,t){return t.role!==void 0?aU(e,t.text,t.role):lU(e,t.text,t)}async function aU(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Sf(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:s}}async function lU(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),s=e.getByLabel(t,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let u=[];i>0&&u.push({loc:r,count:i}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:s,count:l});let d=await rU(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let m=d.slice(0,5),f=[];for(let h=0;h<m.length;h++){let b=m[h];if(b===void 0)continue;let y=await xv(b.locator,b.index);if(y!==null){let v=`${y.role}:${y.label}:${h}`,w=0;for(let T=0;T<v.length;T++)w=w*31+v.charCodeAt(T)>>>0;f.push({...y,id:`el_${w.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var Ev=_(()=>{"use strict"});import{randomBytes as cU}from"crypto";import{mkdir as uU,stat as dU,writeFile as pU}from"fs/promises";import{join as kf}from"path";import{gzip as mU}from"zlib";import{promisify as fU}from"util";function gU(e){return kf(Yo(e),"browser")}function hU(e){return kf(gU(e),"screenshots")}function yU(){return new Date().toISOString().replace(/[:.]/g,"-")}function bU(){return cU(3).toString("hex")}async function xf(e,t,n){if(t.length>Tv)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Tv} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=hU(e);await uU(r,{recursive:!0});let o=`${yU()}-${bU()}-${n}.png`,s=kf(r,o);await pU(s,t);let{size:i}=await dU(s);return{path:s,bytes:i}}var ese,Tv,Rv=_(()=>{"use strict";K();Xi();ese=fU(mU);Tv=5*1024*1024});var _v={};vl(_v,{PlaywrightProvider:()=>Ef});function Cv(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var Ef,Av=_(()=>{"use strict";fv();kv();Ev();bf();Xi();Rv();Ef=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Ec(t)}async open(t){let n=yf(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(c){a=c}(t.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await Tc(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,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;t.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Tc(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=t.timeoutMs??3e4,a=await vf(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Cv(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=async()=>{switch(t.action){case"click":await l.click({timeout:i});break;case"fill":{let h=wf(t.value??"");await l.fill(t.value??"");break}case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=r.url();if(d!==s){let h=yf(d,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:d,reason:h.reason}}let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Tc(r,{observationCounter:o.observationCounter,screenshotPath:m,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(t.target!==void 0){let u=await vf(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Cv(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await u.locator.screenshot()}else s=await r.screenshot({fullPage:t.fullPage??!1});let{path:i,bytes:a}=await xf(n,s,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(t){let n=this.sessions.get(t);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(t,r),r}updateSessionFromObservation(t,n,r,o,s){t.knownElements=new Map(n.map(i=>[i.id,i])),t.currentUrl=r,t.currentTitle=o,t.lastAction=s,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:s}=await xf(n,o,r);return s}catch{return null}}}});var oo={};vl(oo,{__resetBrowserRegistryForTests:()=>xU,browserProviderActive:()=>vU,closeBrowserProvider:()=>Tf,getBrowserProvider:()=>SU,peekBrowserProvider:()=>kU});function Iv(){Promise.resolve(Tf()).then(()=>{process.exit(130)})}function Pv(){Promise.resolve(Tf()).then(()=>{process.exit(143)})}function Mv(){ln=null}function wU(){Rc||(process.on("SIGINT",Iv),process.on("SIGTERM",Pv),process.on("exit",Mv),Rc=!0)}function Ov(){Rc&&(process.removeListener("SIGINT",Iv),process.removeListener("SIGTERM",Pv),process.removeListener("exit",Mv),Rc=!1)}async function SU(e){return ln!==null?ln:(ro!==null||(ro=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(Av(),_v)),n=mv(e),r=new t(n);return wU(),ln=r,ro=null,r})()),ro)}async function Tf(){if(ln===null)return;let e=ln;ln=null,ro=null,Ov(),await e.shutdown()}function vU(){return ln!==null}function kU(){return ln}function xU(){ln=null,ro=null,Ov()}var ln,ro,Rc,so=_(()=>{"use strict";bf();ln=null,ro=null,Rc=!1});function $v(e,t){try{return cv(e,t)}catch(n){return V("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function _U(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(so(),oo));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function Dv(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??_U,o=null,s=e,i=null,a=null;try{let c=await n(e,{headers:CU,redirect:"follow",signal:t.signal});i=c.status,s=c.url||e;let u=c.headers.get("content-type")??"";if(c.ok){if(RU.test(u))throw new Error(`web_scrape markdown mode received binary content (${u.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let d=await c.text();if(TU.test(u)&&!EU.test(u))return{title:"",markdown:d.trim(),finalUrl:s,usedRender:!1};o=$v(d,s)}}catch(c){if(t.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<lv)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let c=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal}),u=$v(c.html,c.finalUrl);if(o===null||u.textLength>=o.textLength)return{title:u.title,markdown:u.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(t.signal.aborted)throw c;if(o===null){let u=c instanceof Error?c.message:String(c),d=a instanceof Error?a.message:`HTTP ${i??"error"}`,m=new Error(`web_scrape could not retrieve ${e}: fetch failed (${d}) and render failed (${u}).`);throw m.cause=c,m}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${i??"error"}).`)}var EU,TU,RU,CU,Lv=_(()=>{"use strict";uv();Pe();EU=/(text\/html|application\/xhtml\+xml)/i,TU=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,RU=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,CU={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function PU(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await t(AU,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),IU),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let u=await s.text(),d=pc(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}catch{}let c=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${c}${l}`)}let i;try{i=await s.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(i.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function Fv(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?PU({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function Nv(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
1072
1072
|
|
|
1073
1073
|
(no results)`;let n=[`# Search results for "${e}"`,""];return t.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
|
|
1074
1074
|
`).trimEnd()}var AU,IU,Bv=_(()=>{"use strict";fs();AU="https://api.exa.ai/search",IU=10});function BU(e){if(!e||typeof e!="object")return{error:"Invalid input: expected an object"};let t=e,n=t.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof t.query!="string"||t.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=t.query}else{if(typeof t.url!="string"||t.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let l;try{l=new URL(t.url)}catch{return{error:`Invalid input: "${t.url}" is not a valid absolute URL`}}if(l.protocol!=="http:"&&l.protocol!=="https:")return{error:`Invalid input: protocol "${l.protocol}" not supported (http/https only)`};o=l.toString()}let i=MU;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(t.timeout_ms,OU)}let a=$U;if(t.max_bytes!==void 0){if(typeof t.max_bytes!="number"||!Number.isFinite(t.max_bytes)||t.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(t.max_bytes,DU)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Rf(e,t){let n=Buffer.from(e,"utf8");return n.byteLength<=t?e:n.subarray(0,t).toString("utf8")+LU}function UU(e){let t=[],n=e;for(let o=0;o<4&&n instanceof Error;o++)t.push(n.message),n=n.cause;let r=t.join(" | ");return NU.some(o=>r.includes(o))}function jU(e={}){let t=e.fetchFn??globalThis.fetch,n=e.env??process.env;return async(r,o)=>{if(typeof t!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=BU(r);if("error"in s)return{content:s.error,isError:!0};if(o.aborted){let u=o.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let i=new AbortController,a=()=>{i.abort(o.reason)},l,c=()=>{let u=i.signal.reason;return u instanceof Error?u.message:String(u??"aborted")};try{if(o.addEventListener("abort",a,{once:!0}),l=setTimeout(()=>{i.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs),s.mode==="raw"){let d;try{d=await t(s.url,{method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:i.signal})}catch(f){return i.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape network error: ${f instanceof Error?f.message:String(f)}`,isError:!0}}if(!d.ok)return{content:`web_scrape HTTP ${d.status} ${d.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let m;try{m=await d.text()}catch(f){return{content:`web_scrape read error: ${f instanceof Error?f.message:String(f)}`,isError:!0}}return{content:Rf(m,s.maxBytes)}}if(s.mode==="markdown")try{let d=await Dv(s.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:s.timeoutMs,signal:i.signal});return d.markdown.trim().length===0?{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0}:{content:Rf(d.markdown,s.maxBytes)}}catch(d){if(i.signal.aborted)return{content:`web_scrape aborted: ${c()}`,isError:!0};let m=d instanceof Error?d.message:String(d),f=UU(d)?" (the render fallback needs the optional Playwright browser \u2014 run `pnpm exec playwright install chromium`)":"";return{content:`web_scrape markdown error: ${m}${f}`,isError:!0}}let u=Fv({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in u)return{content:u.error,isError:!0};try{let d=await u.search(s.query,{limit:FU,timeoutMs:s.timeoutMs,signal:i.signal});return{content:Rf(Nv(s.query,d),s.maxBytes)}}catch(d){return i.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape search error (${u.name}): ${d instanceof Error?d.message:String(d)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),o.removeEventListener("abort",a)}}}var MU,OU,$U,DU,LU,FU,NU,Uv,jv=_(()=>{"use strict";Lv();Bv();MU=3e4,OU=12e4,$U=1e6,DU=1e7,LU=`
|
|
@@ -1965,7 +1965,7 @@ _ended: ${new Date().toISOString()}_
|
|
|
1965
1965
|
${T}${v}
|
|
1966
1966
|
${w}
|
|
1967
1967
|
${T}`})}return{fileBlocks:a,warnings:l}}async function oM(e,t,n,r,o="summary",s,i){let a=j_(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0);let l="",c=0,u=!1,d=!1,m=!1,f=!1,g,h=!1,b=0,y=15e3,v=[],w=new Map,T=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,E=()=>{let M=r.subagentControl;M?.hasPromotableForeground()&&M.promoteActiveForeground().then($=>{for(let L of $)(s??{fn:console.log}).fn(p.dim(` \u2192 subagent backgrounded as ${L.jobId}: ${L.label}`))}).catch(()=>{})},R=r.getCompositor?r.getCompositor():null,C=()=>new mi({out:fi(s),thinkingMode:o,...T?{activeSkillName:T}:{},onCancel:()=>{t.interrupt().catch(M=>{Ze()&&console.error(" "+p.error("session.interrupt() failed:"),M)})},...r.subagentControl?{onBackground:E}:{},...i?.history?{history:i.history}:{},...i?.autocompleteState?{autocompleteState:i.autocompleteState}:{},...i?.promptText!==void 0?{promptText:i.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...R?{compositor:R}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),S=C(),P=async()=>{if(!m){m=!0;try{await S.dispose()}catch{}}},A=async()=>{await S.arm();let M=S.getCompositor();if(s&&M){let $=M;s.fn=L=>$.commitAbove(L)}r.setActiveCompositor?.(M),r.setInterruptNotifier?.($=>S.setInterrupting($)),r.rearmStatus?.()};try{R?R.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{h=!0,t.interrupt().catch(D=>{Ze()&&console.error(" "+p.error("soft-stop session.interrupt() failed:"),D)})}),await A(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(E);let{fileBlocks:M,warnings:$}=rM(e.text,{rootDir:process.cwd()});for(let D of $)(s??{fn:console.log}).fn(p.dim(` @-file: ${D}`));let L=M.length>0||e.attachments.length>0?tM(e.text,e.attachments,void 0,M):e.text,B=t.sendMessageStream(L);if(await us((D,F)=>{S.process(D,F)},async()=>{for await(let D of B){if(h)break;if(D.type==="chunk"&&D.chunk.type==="content"?(l+=D.chunk.content,u=!0):D.type==="message"&&!u&&(l=D.message.content),D.type==="stream_retry"&&(l=l.slice(0,c)),D.type==="chunk"&&D.chunk.type==="tool_use_detail"){let F=D.chunk,j={toolName:F.toolName,toolUseId:F.toolUseId,input:F.toolInput,...F.toolInputRaw!==void 0&&{inputRaw:F.toolInputRaw}};w.set(F.toolUseId,j),v.push(j)}else if(D.type==="chunk"&&D.chunk.type==="tool_result"){let F=D.chunk;c=l.length;let j=w.get(F.toolUseId);if(j&&(j.result=F.content,j.isError=F.isError,w.delete(F.toolUseId)),r.onContextProgress){let N=Date.now();if(N-b>=y){b=N;try{let O=r.onContextProgress();O instanceof Promise&&await O}catch(O){Ze()&&console.error(" "+p.error("onContextProgress (status refresh) failed:"),O)}}}}if(D.type==="paused"){await P(),(s??{fn:console.log}).fn(gw({reason:D.reason,...D.resetsAt!==void 0?{resetsAt:D.resetsAt}:{},...D.accountId!==void 0?{accountId:D.accountId}:{},...D.autoResume!==void 0?{autoResume:D.autoResume}:{}}));continue}if(D.type==="resumed"){let F=D.hotSwapped&&D.accountId?`\u25B6 Resumed on ${D.accountId}`:"\u25B6 Resumed";l="",c=0,u=!1,v.length=0,w.clear(),f=!1,g=void 0,d=!1,S=C(),m=!1,await A(),(s??{fn:console.log}).fn(p.success(F));continue}if(D.type==="error"){await P(),ts(Xo(D.error)),d=!0;continue}S.process(D),D.type==="done"&&(f=!0,g=D.metadata)}}),await P(),h){let D=s?s.fn:console.log;D(p.warning("\u23F8 Stopped \u2014 work so far kept.")+p.dim(" Send a message to continue.")),D("")}if(f&&!h){po(n,a,l,g,v),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),Gu(process.stdout);let D=j=>{s?s.fn(j):console.log(j)},F=QP(l);if(F&&(D(eM(F)),D(""),r.onTerminalState))try{r.onTerminalState(F)}catch{}if(u5(g,n,D),r.onAfterTurn){let j=r.onAfterTurn();j instanceof Promise&&await j.catch(()=>{})}}}catch(M){await P(),d||ts(Xo(M))}finally{await P(),s&&(s.fn=s.idleFn),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setInFlight(!1),r.rearmStatus?.()}}function u5(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(ge(e.durationMs)),e.totalCostUsd!==void 0&&r.push(Ye(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),s=Number(e.usage?.output_tokens??0);o+s>0&&r.push(ae(o+s)+" tok"),r.length>0&&n(p.dim(" \u25E6 "+r.join(" \xB7 ")));let i=eh(t),a=vt(t.model);if(i>=1){let l=Math.round((i-1)*a),c=Math.round(a/1e3);console.log(p.error(` context OVER ${c}k tok by ~${ae(l)} tok \u2014 model output may be silently truncated`))}else if(i>.5){let l=i>.8?p.error:p.warning;n(l(` context ${Math.round(i*100)}% used of ${ae(a)}`))}n("")}async function d5(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(p.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function sM(e,t,n,r,o,s,i,a){let{contextPane:l,loopStageBar:c,verdictLedger:u,shellPassthrough:d}=i,m=null,f=[];e.session.current.waitForInitialization().then(async y=>{Ze()&&(m=Zu(y)),await Hd(e.session.current),Ze()&&(f=HI())}).catch(()=>{});let g,h=!1,b=!1;for(;;){if(m&&(e.replRenderer.writeLine(m),e.replRenderer.writeLine(""),m=null),f.length>0){for(let S of f)e.replRenderer.writeLine(S);e.replRenderer.writeLine(""),f=[]}let y=d.drainNotifications();for(let{job:S,result:P}of y){let A=P.errorReason===void 0?"\u2713":"\u2717",M=P.errorReason==="abort"?"killed":P.errorReason==="timeout"?"timed out":P.errorReason==="signal-killed"?"killed by signal":`exit ${P.exitCode??0}`,$=Math.max(0,Math.round(P.durationMs/100)/10);e.replRenderer.writeLine(p.dim(` ${A} [${S.id}] ${M} \xB7 ${$}s \xB7 `)+S.command)}let v=l.renderIfChanged(e.stats.sessionId);if(v.length>0){for(let S of v)e.replRenderer.writeLine(S);e.replRenderer.writeLine("")}let w,T;if(g!==void 0){let S=g;g=void 0;let P=Si(e.stats.model,e.stats.planMode),A=bo({buffer:S.text,promptText:P,isTTY:!!process.stdout.isTTY,attachmentSummary:ii([...S.attachments])});e.replRenderer.writeLine(A),w=S.text.trim(),T=S.attachments}else{let S=await o.readLine({promptFn:()=>Si(e.stats.model,e.stats.planMode),onSigint:r,onShiftTab:()=>{Zn(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});w=S.text.trim(),T=S.attachments}if(!w&&T.length===0)continue;if(w.startsWith("!")){let S=/^(0|false|off|no)$/i.test(k.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!S&&(h||(h=!0,e.replRenderer.writeLine(p.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await d.dispatch(w))){e.statusLine.rearm();continue}}let E=!1;if(w.startsWith("/")){let S=await hC(w,e.slashCtx,T);if(S.handled){if(S.result==="exit"){e.rl.close();return}if((w==="/clear"||w.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(p.dim(` transcript: ${t.path()}`)),u.reset()),S.result!==null&&typeof S.result=="object"&&"kind"in S.result&&S.result.kind==="submit"){g={text:S.result.message,attachments:T??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}E=!0}a.push(w),await d5(e,w);let R=w;if(E){let S=Qg(w);if(S){let P=S.name.replace(/^\//,"").split(":").pop()??"";if(P&&sy(P)){let A={skillName:P,rawArgs:S.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},M=e.session.current.sessionId,$=Co(M),L=Date.now();V(`[afk trace] preflight.start commandName=${P}`);let B=!1,U=await Ro(A,{cwd:e.stats.cwd??process.cwd(),artifactDir:$},D=>{Ze()&&e.replRenderer.writeLine(p.warning(`\u26A0 preflight(${P}) failed: `)+(D instanceof Error?D.message:String(D)))});B=U!==null,V(`[afk trace] preflight.end commandName=${P} durationMs=${Date.now()-L} success=${B}`),R=ay(U?.manifestBlock,w)}}}let C=d.drainInjections();C.length>0&&(R=C+R),await oM({text:R,attachments:T},e.session.current,e.stats,{setInFlight(S){n.turnInFlight=S},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(S){await t.appendUser(S)},async onTurnComplete(S,P){if(await t.appendTurn(S,P),e.stats.sessionId)try{hn(e.stats)}catch(A){b||(b=!0,e.replRenderer.writeLine(p.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(A instanceof Error?A.message:String(A))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:S=>u?.push(S),setActiveCompositor:S=>{n.activeCompositor=S},setInterruptNotifier:S=>{n.notifyInterrupting=S},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:S=>o.setBackgroundHandler(S),setSoftStopHandler:s,async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(Xn(e.stats,e.contextSampler))},...c?{onStageChange:S=>c.repaint(S)}:{}},e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(Si(e.stats.model,e.stats.planMode)))}}function p5(e,t){if(e!==void 0){let n=e.toLowerCase();return!(n==="0"||n==="false"||n==="off"||n==="no")}return typeof t=="boolean"?t:!0}async function iM(e,t,n,r){let o=await LP(),s=new dp({rl:e.rl,history:o,statusLine:e.statusLine}),i=p5(k.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await WP(e,s,n,t,r,i,{getLoopStageBar:()=>a?.loopStageBar});a=ZP(e,n),await sM(e,t,n,r,s,l,a,o)}finally{n.tryAbortShellForeground=null,a?.shellPassthrough.drainOnExit(),a?.loopStageBar.stop(),a?.bgStatusBar.stop(),a?.verdictLedger.stop(),a?.contextPane.dispose();let l=c=>console.log(c);e.completionWriter.fn=l,e.completionWriter.idleFn=l,await s.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}qi();import{execFile as m5}from"node:child_process";import{dirname as f5,isAbsolute as g5,resolve as h5}from"node:path";import{promisify as y5}from"node:util";var aM=y5(m5),b5=3e3,w5=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function S5(){let t=(await aM("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=g5(t)?t:h5(process.cwd(),t);return f5(n)}async function lM(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await S5()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),b5)});try{let o=Sn({execFile:aM,repoRoot:t,dryRun:!1,scope:"interactive",bypassSoftLaunch:!0}),s=await Promise.race([o,r]);if(s==="timeout")return{ran:!1,removedCount:0,skippedReason:"timeout"};let i=s;return i.warnings.some(c=>c.toLowerCase().includes("contested"))?{ran:!1,removedCount:0,skippedReason:"lock-contested"}:{ran:!0,removedCount:i.candidates.filter(c=>w5.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}Kl();qi();import{promises as v5}from"node:fs";import{dirname as k5,join as dM}from"node:path";import{randomBytes as x5}from"node:crypto";var E5=["Generate a 2-4 word kebab-case slug describing this work request.","Rules:","- ASCII lowercase letters and digits only, separated by single hyphens","- 2 to 4 hyphen-separated words","- Maximum 30 characters total","- No prefix, no quotes, no punctuation other than hyphens","- Output ONLY the slug \u2014 no explanation, no preamble","Examples: fix-cleanup-race, add-telegram-allowlist, refactor-prompt-loader, debug-flaky-test"].join(`
|
|
1968
|
-
`),cM=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,$y=30,T5=1024,R5=8e3,C5="haiku";async function _5(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=M5(n,T5),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??R5),i=t.signal?O5([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await ls({token:t.token,model:t.model??C5,system:E5,user:r,maxTokens:32,signal:i})}catch(d){let m=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(s)}let l=A5(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=k5(t.worktreePath);return await I5(l,c)}function A5(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(cM.test(t)&&t.length<=$y)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(s=>s.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let s=1;s<r.length;s++){let i=`${o}-${r[s]}`;if(i.length>$y)break;o=i}return cM.test(o)?o:null}async function I5(e,t){if(!await P5(dM(t,e)))return e;let n=x5(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,$y-5)}-${n}`}async function P5(e){try{return await v5.access(e),!0}catch{return!1}}function M5(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function O5(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function pM(e){let t,n,r=dM(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await _5(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),s=t??"unknown",i=n;if(o!==null){let l=`${bc(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return uM(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){s="create-failed",i=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return uM(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:s,...i!==void 0?{detail:i}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function uM(e,t){e&&e.setCwd(t),$5(t)}function $5(e){try{process.chdir(e)}catch{}}je();Hn();K();import{spawn as fM}from"child_process";import{existsSync as gM,mkdirSync as B5,readFileSync as hM,unlinkSync as mM,writeFileSync as U5}from"fs";import{get as j5}from"https";import{join as yM}from"path";import{readFileSync as D5}from"fs";import{dirname as L5,join as F5}from"path";import{fileURLToPath as N5}from"url";function or(){try{return"4.9.
|
|
1968
|
+
`),cM=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,$y=30,T5=1024,R5=8e3,C5="haiku";async function _5(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=M5(n,T5),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??R5),i=t.signal?O5([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await ls({token:t.token,model:t.model??C5,system:E5,user:r,maxTokens:32,signal:i})}catch(d){let m=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(s)}let l=A5(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=k5(t.worktreePath);return await I5(l,c)}function A5(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(cM.test(t)&&t.length<=$y)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(s=>s.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let s=1;s<r.length;s++){let i=`${o}-${r[s]}`;if(i.length>$y)break;o=i}return cM.test(o)?o:null}async function I5(e,t){if(!await P5(dM(t,e)))return e;let n=x5(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,$y-5)}-${n}`}async function P5(e){try{return await v5.access(e),!0}catch{return!1}}function M5(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function O5(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function pM(e){let t,n,r=dM(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await _5(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),s=t??"unknown",i=n;if(o!==null){let l=`${bc(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return uM(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){s="create-failed",i=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return uM(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:s,...i!==void 0?{detail:i}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function uM(e,t){e&&e.setCwd(t),$5(t)}function $5(e){try{process.chdir(e)}catch{}}je();Hn();K();import{spawn as fM}from"child_process";import{existsSync as gM,mkdirSync as B5,readFileSync as hM,unlinkSync as mM,writeFileSync as U5}from"fs";import{get as j5}from"https";import{join as yM}from"path";import{readFileSync as D5}from"fs";import{dirname as L5,join as F5}from"path";import{fileURLToPath as N5}from"url";function or(){try{return"4.9.1"}catch{}try{let e=L5(N5(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(D5(F5(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}G();var H5=64*1024,W5=1440*60*1e3,K5=3600*1e3,G5="update-check.json",z5="pending-update.json";function bM(){return yM(Tl(),G5)}function il(){return yM(Tl(),z5)}function wM(){let e=Tl();gM(e)||B5(e,{recursive:!0})}function q5(e,t){let n=a=>a.split(/[-+]/,1)[0]??a,r=a=>a.includes("-"),o=n(e).split(".").map(Number),s=n(t).split(".").map(Number),i=Math.max(o.length,s.length);for(let a=0;a<i;a++){let l=o[a]??0,c=s[a]??0;if(c>l)return!0;if(c<l)return!1}return r(e)&&!r(t)}function J5(){try{let e=hM(bM(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function V5(){try{wM();let e=`
|
|
1969
1969
|
const https = require('https');
|
|
1970
1970
|
const fs = require('fs');
|
|
1971
1971
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|