agent-afk 5.82.2 → 5.82.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var jb=Object.defineProperty;var ye=(t,e)=>()=>(t&&(e=t(t=0)),e);var Bc=(t,e)=>{for(var n in e)jb(t,n,{get:e[n],enumerable:!0})};function Xr(t){return Vr.find(e=>e.name===t)}function Ji(t){return process.env[t]!==void 0}var Vr,b,N=ye(()=>{"use strict";Vr=[{name:"AFK_COMPACT_KEEP_LAST_TURNS",description:"Number of recent turns the compactor keeps verbatim during /compact. Default tuned in compact-handler.ts.",type:"number",required:!1,example:"6",category:"model"},{name:"AFK_COMPACT_MODEL",description:"Override the model used by the /compact summarizer. Falls back to a cheap default (haiku-class).",type:"string",required:!1,example:"claude-haiku-4-5",category:"model"},{name:"AFK_COMPACT_SHRINK_FRACTION",description:"Context-fullness fraction (0\u20131, exclusive) at/above which /compact and auto-compaction relax the keep-window so a short-but-full session (few turns, huge tool exchanges) can still be summarized instead of no-oping on turn count. Default 0.7 (see shared/compaction.ts DEFAULT_COMPACT_SHRINK_THRESHOLD).",type:"number",required:!1,example:"0.8",category:"model"},{name:"AFK_DEFAULT_SUBAGENT_MODEL",description:"Override the default model used when a subagent is dispatched without an explicit model.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_DIAGNOSE_BASELINE",description:"Kill switch for /diagnose reproducer baseline execution. When set to '0', the /diagnose skill skips executing the detected reproducer command for a ground-truth baseline; default enabled (runs). Set to '0' to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_DISABLE_PROMPT_CACHE",description:"Disable Anthropic prompt caching when set to 1/true/yes/on. Unset = caching enabled.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_DISABLE_BASH_INTERPRETER_GUARD",description:"Skip ONLY the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) when set to 1, leaving the rest of path-approval intact. Applies on interactive surfaces (REPL/Telegram), where the denylist is active but your workflow legitimately runs interpreter one-liners. The restricted-root substring check is unaffected. Default: denylist active on interactive surfaces; headless already fails open (opt in with AFK_FORCE_BASH_INTERPRETER_GUARD=1). To disable all of path-approval + bash restriction instead, use AFK_DISABLE_PATH_APPROVAL=1.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_DISABLE_PATH_APPROVAL",description:"Skip the path-approval + bash-restriction hooks entirely when set to 1. Use for headless flows that need wide-open file access (CI scripts, batch jobs). Default: hooks enabled. Note: on headless surfaces (afk chat, daemon) no grant manager is wired, so the interpreter denylist (python -c, node -e, sh -c, ...) fails OPEN by default \u2014 opt headless flows into it with AFK_FORCE_BASH_INTERPRETER_GUARD=1, or set this var to 1 to disable all of path-approval.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_FORCE_BASH_INTERPRETER_GUARD",description:"Apply the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) even on headless surfaces (afk chat, daemon) where no grant manager is wired. By default the denylist fires only on interactive surfaces (REPL/Telegram), failing open on headless so legitimate automation is not hard-blocked with no recourse. Set to 1 to opt headless flows back into the guard. Overridden by AFK_DISABLE_BASH_INTERPRETER_GUARD=1. Default: off (headless fails open).",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_EFFORT",description:"Effort hint guiding adaptive-thinking depth, forwarded as Anthropic output_config.effort (model-gated; ignored where unsupported). Accepts low | medium | high | xhigh | max.",type:"string",required:!1,example:"medium",category:"model"},{name:"AFK_MAX_BUDGET_USD",description:"Cumulative USD budget ceiling for the session. Aborts the turn when the running cost crosses this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. Falls back to provider default when unset.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Deprecated and inert: not read by the generation path. Use AFK_MAX_OUTPUT_TOKENS (or --max-output-tokens) to cap per-response output tokens; falls back to the model output ceiling when unset.",type:"number",required:!1,default:"4096",example:"8192",category:"model"},{name:"AFK_MAX_TOOL_USE_ITERATIONS",description:"Opt-in ceiling on tool-use rounds per turn for TOP-LEVEL (non-subagent) sessions, on both providers. Mirrors the maxToolUseIterations config key / max_tool_use_iterations tool param. Unset, non-numeric, or <=0 means unlimited (the default \u2014 zero behavior change): a top-level turn ends only when the model stops calling tools, the abort signal fires, the provider errors, or the dollar budget trips. A positive integer N makes top-level turns wind down gracefully after N tool rounds (one tools-stripped final round). An explicit config/CLI value wins over this env default. Does NOT affect subagent forks \u2014 they keep their own non-zero anti-hang default (SUBAGENT_DEFAULT_MAX_TOOL_USE_ITERATIONS) regardless of this var.",type:"number",required:!1,default:"0",example:"150",category:"model"},{name:"AFK_MEMORY_EVIDENCE_GATE",description:'Opt-in (set to 1) evidence gate for durable memory writes. When enabled, a codebase fact (memory_update category "convention") stored without an `evidence` citation is recalled as [unverified], and memory_search results carry a verification verdict. User preferences and agent reflections are never gated. Default off \u2014 memory behaves identically to legacy when unset.',type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_MICROCOMPACT_KEEP_LAST",description:"Number of the most-recent tool_result blocks that tool-result microcompaction keeps intact regardless of size, so the agent does not lose the tool output it is actively reasoning over. Older results are the safe ones to trim. Default 4 (see shared/compaction.ts DEFAULT_MICROCOMPACT_KEEP_LAST). Values <= 0 protect nothing.",type:"number",required:!1,default:"4",example:"3",category:"model"},{name:"AFK_MICROCOMPACT_TOOL_RESULT_BYTES",description:"Byte threshold (tool_result content length) at/above which a tool_result block becomes a microcompaction candidate. When /compact and auto-compaction would otherwise no-op on a short-but-full session, microcompaction clears large/old tool_result CONTENT in place (largest first) \u2014 replacing it with a short placeholder, never removing the block \u2014 to reclaim context deterministically (no LLM call). Blocks below this size are left intact. Default 2048 (see shared/compaction.ts DEFAULT_MICROCOMPACT_TOOL_RESULT_BYTES).",type:"number",required:!1,default:"2048",example:"4096",category:"model"},{name:"AFK_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), fixed-identity aliases (opus, sonnet, haiku, fable), or full model IDs. Migration: AFK_MODEL=sonnet now pins the fixed Sonnet identity rather than following a rebound medium tier.",type:"string",required:!1,default:"medium",example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_TTFB_TIMEOUT_MS",description:"Per-request time-to-first-token timeout (ms) for the anthropic-direct streaming loop. Bounds how long a single model call may stall BEFORE its first streamed CONTENT token (a text/thinking delta or tool_use); the connection-level message_start and keep-alive pings do NOT count. Once a content token streams, the timer is cleared and the rest of the response runs unbounded, so a normal slow call (below the bound) and any actively-streaming extended-thinking response are never aborted. NOTE: a request whose FIRST token takes longer than the bound \u2014 e.g. a very large opus_1m prefill \u2014 is aborted, retried once, then surfaces as an error (raise this value or set 0 for such workloads); this trims the degrading-call tail instead of a silent ~10-min hang on the SDK default. Default 180000 (180s \u2248 2\xD7 the measured p99 ttfb). Set to 0 to disable.",type:"number",required:!1,default:"180000",example:"120000",category:"model"},{name:"AFK_SUBAGENT_TIMEOUT_MS",description:"Foreground forked-subagent wall-clock budget in ms; 0 disables the cap; explicit per-fork config.timeoutMs and the 60-min background mode still win. Bounds how long a single forked child turn may run before `withTimeout` aborts its controller (cascading through the AbortGraph to descendants) and the parent receives a legible TimeoutError tool_result instead of hanging. Default 2700000 (45 min \u2248 headroom over the longest healthy review/research agent observed in production). Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to opt a whole session back into unbounded child turns. Does NOT affect the background dispatch budget (SUBAGENT_BACKGROUND_TIMEOUT_MS) or a per-fork config.timeoutMs \u2014 both take precedence.",type:"number",required:!1,default:"2700000",example:"3600000",category:"model"},{name:"AFK_SUBAGENT_IDLE_TIMEOUT_MS",description:"Forked-subagent progress-aware idle-watchdog window in ms; 0 disables the watchdog; an explicit per-fork config.idleTimeoutMs still wins. Fires when a forked child produces no observable output event for this window, aborting the same controller the wall-clock timeout targets so partial output is preserved and the run classifies as a failure. This is distinct from AFK_SUBAGENT_TIMEOUT_MS, the blunt wall-clock that bounds total turn time: the idle watchdog is the tighter first-to-fire bound and never fires while the stream is legitimately parked on a provider-communicated backoff (OAuth pause, or a rate-limit event carrying a retry-after), extending the deadline for the pause window instead. Default 480000 (8 min) clears the worst-case transient-429 backoff the watchdog is currently blind to (about 363s) with roughly 2 min of margin, while staying materially tighter than the 45-min wall-clock. Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to disable the idle watchdog for a whole session (the wall-clock still applies). v1 applies to forked sub-agent turns only, not top-level or daemon sessions.",type:"number",required:!1,default:"480000",example:"300000",category:"model"},{name:"AFK_VISION_MODELS",description:'Comma-separated override for image (vision) capability detection on the openai-compatible provider. Each token force-enables a model id by exact or substring match (e.g. "qwen2.5-vl" matches a local VL id); prefix a token with "!" to force-disable. Use to send images to a local vision-language model AFK does not recognise by name, or to blacklist a mis-detected id. Built-in detection already covers gpt-4o/4.1/5.x, o1/o3/o4-mini, Claude, and common VL families.',type:"string",required:!1,example:"qwen2.5-vl,!gpt-4o-mini",category:"model"},{name:"AFK_MODEL_LOCAL",description:'Bind the "local" capability tier (cheapest/fastest, user-configured) to a model id. Overrides afk.config.json models.local. Point at a local Ollama, LM Studio, or any OpenAI-compatible shim.',type:"string",required:!1,example:"llama3.2:3b",category:"model"},{name:"AFK_MODEL_LOCAL_API_KEY",description:'Per-slot API key for the "local" tier. Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LOCAL_BASE_URL",description:'Per-slot endpoint base URL for the "local" tier. Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:11434/v1",category:"model"},{name:"AFK_MODEL_LARGE",description:'Bind the "large" capability tier (most capable) to a model id/alias. Overrides afk.config.json models.large.',type:"string",required:!1,example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-5",category:"model"},{name:"AFK_MODEL_MEDIUM_API_KEY",description:'Per-slot API key for the "medium" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_MEDIUM_BASE_URL",description:'Per-slot endpoint base URL for the "medium" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_SMALL",description:'Bind the "small" capability tier (cheap/fast) to a model id/alias. Overrides afk.config.json models.small.',type:"string",required:!1,example:"gpt-4o-mini",category:"model"},{name:"AFK_MODEL_SMALL_API_KEY",description:'Per-slot API key for the "small" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_SMALL_BASE_URL",description:'Per-slot endpoint base URL for the "small" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_PROMPT_CACHE_TTL",description:"TTL for Anthropic prompt-cache blocks. Accepts 5m or 1h.",type:"string",required:!1,default:"1h",example:"1h",category:"model"},{name:"AFK_SUGGEST_ENABLED",description:"Enable the LLM-backed ghost-text suggestion tier in the interactive REPL. Set to 1/true/yes/on to activate. Off by default.",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_GHOST",description:"Enable REPL ghost-text inline suggestions (Tier-1 history/dropdown + optional Tier-2 LLM). 1 = on (default), 0 = off. Set 0/false/off/no to disable all ghost text. Tier-2 LLM is separately gated by AFK_SUGGEST_ENABLED.",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_MODEL",description:"Override the small model used for REPL ghost-text suggestions. Falls back to AFK_COMPACT_MODEL or haiku-class for anthropic, or the session model for other providers.",type:"string",required:!1,category:"model"},{name:"AFK_TASK_BUDGET",description:"Per-task token budget ceiling. Aborts when cumulative usage would exceed it.",type:"number",required:!1,default:"100000",example:"200000",category:"model"},{name:"AFK_TEMPERATURE",description:"Numeric temperature override for model sampling. Provider default if unset.",type:"number",required:!1,example:"0.7",category:"model"},{name:"AFK_THINKING",description:"Extended-thinking mode. Accepts adaptive | disabled | enabled:<N> | enabled:max. Defaults to the model-appropriate mode when unset (adaptive on current models).",type:"string",required:!1,default:"adaptive",example:"adaptive",category:"model"},{name:"AFK_THINKING_UI",description:"Default thinking-display mode for the interactive REPL: summary | live | digest | off. Display-only \u2014 controls how extended-thinking blocks render, never whether thinking runs (cost/latency unaffected). Overridden per-launch by --thinking-ui and mutable mid-session via /thinking. Precedence: --thinking-ui flag > this env > interactive.thinkingUi config > live. Invalid values are ignored.",type:"string",required:!1,default:"live",example:"digest",category:"misc"},{name:"AFK_TIMEOUT_MS",description:"Per-turn timeout in milliseconds. Provider/SDK default if unset.",type:"number",required:!1,example:"120000",category:"model"},{name:"CLAUDE_MODEL",description:"Legacy alias for AFK_MODEL \u2014 supported for back-compat with pre-AFK_* deployments.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_SYSTEM_PROMPT",description:'Raw operator-overlay prompt. Highest-priority overlay (over afk.config.json and AFK.md). Appended on top of the framework base (prompts/system-prompt.md) under an "# Operator configuration" header \u2014 it augments, never replaces, the base.',type:"string",required:!1,example:"You are a helpful agent.",category:"model"},{name:"AFK_DUMP_PROMPT",description:"Write the resolved system prompt to a file at startup. Accepts a path or 1 for default location.",type:"string",required:!1,example:"/tmp/afk-prompt.txt",category:"debug"},{name:"ANTHROPIC_API_KEY",description:"Anthropic API key. Tier-1 credential \u2014 overrides keychain OAuth and CLAUDE_CODE_OAUTH_TOKEN.",type:"string",required:!1,category:"auth",secret:!0},{name:"CLAUDE_CODE_OAUTH_TOKEN",description:"Claude Code OAuth token. Tier-2 credential \u2014 used when ANTHROPIC_API_KEY is unset; falls back to keychain.",type:"string",required:!1,category:"auth",secret:!0},{name:"OPENAI_API_KEY",description:"OpenAI API key for the openai-compatible provider (gpt-*, o1*, o3*, o4* models).",type:"string",required:!1,category:"auth",secret:!0},{name:"CODEX_API_KEY",description:"Fallback OpenAI API key for the openai-compatible provider, read after OPENAI_API_KEY. Legacy name from the removed @openai/codex-sdk integration \u2014 prefer OPENAI_API_KEY.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_LOCAL_API_KEY",description:"Placeholder API key for local Anthropic-compatible servers (vllm-mlx, etc.). Set when AFK_LOCAL_BASE_URL is configured.",type:"string",required:!1,default:"local",example:"local",category:"auth",secret:!0},{name:"AFK_LOCAL_BASE_URL",description:"Base URL for a self-hosted Anthropic-compatible server. When set, routes traffic away from api.anthropic.com.",type:"string",required:!1,example:"http://127.0.0.1:8080",category:"model"},{name:"AFK_OPENAI_BASE_URL",description:"Base URL override for the OpenAI-compatible provider. Used for local shims (mlx_lm.server, Ollama, vLLM, LM Studio). The OpenAI SDK appends `/chat/completions` itself \u2014 a value ending in `/chat/completions` will be stripped at config-load time with a one-shot warning.",type:"string",required:!1,example:"http://127.0.0.1:8000/v1",category:"model"},{name:"AFK_OPENAI_USE_RESPONSES",description:"Opt the OpenAI-compatible provider into the OpenAI Responses API instead of Chat Completions for API-key sessions. Truthy values: 1, true, yes, on. The ChatGPT-subscription OAuth path uses Responses automatically regardless of this flag.",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_OPENAI_CHATGPT_OAUTH",description:"Opt into using ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. Off by default. READ-ONLY: AFK never refreshes these tokens \u2014 re-run `codex` when the access token expires. Routes requests over the Responses API to the private ChatGPT backend (chatgpt.com/backend-api).",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_PROVIDER",description:"Force provider selection (anthropic | anthropic-direct | openai | openai-compatible | openai-codex). Overrides the model-name heuristic. Same surface as the --provider CLI flag; CLI flag wins when both are set.",type:"string",required:!1,example:"openai-compatible",category:"model"},{name:"EXA_API_KEY",description:"Exa (exa.ai) search API key, enabling web_scrape search mode. Free tier (20k requests/month) available at https://exa.ai. When unset, search mode returns an actionable error; markdown and raw modes are unaffected.",type:"string",required:!1,category:"auth",secret:!0},{name:"TELEGRAM_BOT_TOKEN",description:"Telegram bot token from @BotFather. Required to run the Telegram bot surface.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_BOT_TOKEN",description:"Alternative env var name for the Telegram bot token, accepted by the setup wizard.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_ALLOWED_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs allowed to interact with the bot. Required when the bot is running.",type:"string",required:!1,example:"123456789,987654321",category:"telegram"},{name:"AFK_TELEGRAM_TAG_ONLY_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs where the bot answers only when addressed (a reply to the bot, an @mention of the bot, or a text_mention resolving to the bot). Slash-commands are unaffected; chats not listed behave as usual. The afk.config.json telegram.tagOnlyChats block takes precedence. Requires Telegram privacy mode OFF (BotFather /setprivacy Disable) for non-addressed group messages to reach the bot.",type:"string",required:!1,example:"-100987654321,123456789",category:"telegram"},{name:"AFK_TELEGRAM_PRIMARY_CHAT_ID",description:"Default chat ID for outbound notifications (primary-mode routing). When unset, notifications go to the first private/DM chat in AFK_TELEGRAM_ALLOWED_CHAT_IDS. The afk.config.json telegram.notify block takes precedence.",type:"string",required:!1,example:"123456789",category:"telegram"},{name:"AFK_TELEGRAM_NOTIFY_MODE",description:"Outbound notification fan-out: primary (default \u2014 one chat), broadcast (every allowed chat), or custom (afk.config.json telegram.notify.targets). The afk.config.json telegram.notify.mode takes precedence.",type:"string",required:!1,example:"broadcast",category:"telegram"},{name:"TELEGRAM_DATA_DIR",description:"Override the directory where Telegram bot state is stored. Defaults to ~/.afk/state/telegram/.",type:"string",required:!1,category:"telegram"},{name:"TELEGRAM_VERBOSE",description:"Set to 'true' to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency. (The code checks the literal string 'true'.)",type:"boolean",required:!1,example:"true",category:"telegram"},{name:"AFK_TELEGRAM_TRACE",description:"Set to 1 to dump raw bridge traffic between the agent and the Telegram bot \u2014 debugging only.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_TELEGRAM_CWD",description:"Override the working directory used by the Telegram bot when spawning agent sessions.",type:"string",required:!1,category:"telegram"},{name:"AFK_HOME",description:"Override the AFK home directory. Default: ~/.afk/.",type:"string",required:!1,default:"~/.afk",example:"/opt/afk",category:"paths"},{name:"AFK_STATE_DIR",description:"Override the entire AFK state tier (sessions/, todos/, transcripts/, memory/, daemon/, etc.), not just one subdirectory. Must be an absolute path (not /). Default: $AFK_HOME/state/.",type:"string",required:!1,category:"paths"},{name:"AFK_FRAMEWORK_DIR",description:"Override the AFK agent-framework directory used for telemetry and briefs. Default: $AFK_HOME/agent-framework/.",type:"string",required:!1,category:"paths"},{name:"AFK_COMPANION_PRIMER",description:'Opt-in: absolute path to a single companion-primer file. When set, its content is bounded (capped, fenced as <companion-primer>) and appended to the system prompt at session start for top-level sessions (chat/REPL/telegram/daemon), as lower-authority "reflections, not facts" context. Unset (default) = no-op. Only the one named file is ever read \u2014 never a directory or repo walk.',type:"string",required:!1,example:"/Users/me/Projects/afk-companion/PRIMER.md",category:"paths"},{name:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Opt-in to loading + spawning MCP servers declared in <cwd>/.mcp.json. Fail-closed: when unset (or 0), project-local servers are NOT spawned; set to a truthy value (1/true/yes/on) to load them. A project-local .mcp.json spawns arbitrary commands on session start, so it is off by default to prevent code execution when entering an untrusted repo (issue #571). Skipped servers are listed in a startup warning with the opt-in instruction.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BG_AUTO_DELIVER",description:"Auto-deliver background subagent results into the model context on the next user turn (interactive REPL). On by default. Set to 0, false, off, or no (case-insensitive) to disable, restoring the manual /bgsub:join retrieval flow.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_PLAIN_OUTPUT",description:"Force the interactive REPL to fully behave like a non-TTY surface for rendering purposes, even when stdout/stdin ARE a TTY: append-only plain-stdout output instead of the TerminalCompositor live overlay (both the persistent between-turn compositor AND the per-turn StreamRenderer overlay), AND the input surface downgrades to the simple non-TTY line reader instead of the fancy compositor-backed input box. Same code path already used for non-TTY surfaces (pipes, CI). Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM scroll regions misbehave \u2014 trades the live overlay and fancy input UX for reliability. Opt-in \u2014 default TTY behavior (live overlay + fancy input) is unchanged unless this var is set. Truthy values: 1, true (case-insensitive).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_GOBLIN_SPINNER",description:"Goblin-themed working spinner (olive frames + goblin verbs) while the agent runs tools. 1 = on (default), 0 = classic dim spinner.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_TERM_TITLE",description:'Set the terminal/tab title (OSC 2) to reflect afk state \u2014 "afk \u2014 <cwd> \xB7 running" during a turn, "afk \u2014 <cwd>" when idle, cleared on exit. 1 = on (default when stdout is a TTY), 0 = leave the title alone. TTY-only.',type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_NOTIFY",description:"Emit a desktop completion notification (OSC 9) on turn completion, for terminals that map OSC 9 to system notifications (iTerm2, kitty, WezTerm). Opt-in and off by default (intrusive). 1 = on. TTY-only.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_THEME",description:"TUI color palette for the interactive REPL and all CLI rendering: dark | light | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark. Overridden per-launch by --theme and mutable mid-session via /theme. Precedence: --theme flag > this env > config theme > auto-detect > dark. Invalid values are ignored (dark).",type:"string",required:!1,default:"dark",example:"light",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless on every AFK surface \u2014 the CLI entrypoint reports surface `afk`, which is in the headless set \u2014 so watching the agent work in a visible window is opt-in via `AFK_BROWSER_HEADLESS=0`, not implied by running the REPL. Note headed and headless use different chromium downloads (`chromium-*` vs `chromium_headless_shell-*`).",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_ALLOWED_DOMAINS",description:"Comma-separated allowlist of URL host globs. When set, browser_open and any navigation that targets a host outside the list returns status: blocked_by_policy. Unset means no allowlist (permissive). Patterns use simple `*` glob matching against the URL host. Combines with AFK_BROWSER_BLOCKED_DOMAINS \u2014 block wins.",type:"string",required:!1,example:"github.com,*.atlassian.net",category:"browser"},{name:"AFK_BROWSER_BLOCKED_DOMAINS",description:"Comma-separated blocklist of URL host globs. Browser navigation that matches any entry returns status: blocked_by_policy regardless of the allowlist.",type:"string",required:!1,example:"*.ads.example.com",category:"browser"},{name:"AFK_BROWSER_DOM_SNAPSHOTS",description:"Phase 2 opt-in: when set to 1, every browser_act writes a gzipped DOM snapshot sidecar under ~/.afk/state/witness/<sid>/browser/dom-snapshots/. Off by default because snapshots are large; useful for post-mortem analysis of failed actions.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_BACKEND",description:"Select the browser provider backend. Phase 1 supports only `playwright`. Reserved for future `cdp` / `mcp` adapters. Unset defaults to `playwright`.",type:"string",required:!1,example:"playwright",category:"browser"},{name:"AFK_BROWSER_CONFIG",description:"Absolute path to an alternate browser config file. Overrides the default ~/.afk/config/browser.json lookup. Useful for per-project overrides in CI.",type:"string",required:!1,example:"/path/to/browser.json",category:"browser"},{name:"AFK_BROWSER_DEFAULT_PROFILE",description:"Name of the persistent session-vault profile the agent reuses for browser sessions. The context restores its login from (and saves it back to) ~/.afk/state/browser/<profile>/storageState.json, so a human runs `afk browser login --profile <name>` once and the agent reuses that authenticated session across unattended runs. Unset defaults to `default` (a fresh, empty profile \u2014 identical to pre-vault behavior). Allowed charset: [A-Za-z0-9_-], max 128 chars.",type:"string",required:!1,example:"work",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_READ_DENYLIST",description:"Colon-separated list of additional absolute paths the read_file/grep/glob/list_directory tools refuse to read, and that the bash-restriction hook refuses to let a shell command reference on interactive surfaces (REPL, Telegram) \u2014 on headless surfaces (afk chat, daemon) bash fails open regardless of this list. A leading ~/ is expanded (~user/ is not \u2014 spell those absolutely). Built-in credential entries (~/.ssh, ~/.aws, ~/.afk/config, \u2026) always apply on top and cannot be removed. One built-in exception exists: ~/.afk/config/mcp.json (the MCP registry) IS readable \u2014 paths listed here outrank that carve-out, so set this to ~/.afk/config/mcp.json if your registry holds inline secrets rather than ${VAR} placeholders.",type:"string",required:!1,example:"/Users/me/project/.env:/Users/me/secrets",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"VISUAL",description:"Standard POSIX env var naming the user's preferred full-screen editor (with optional flags). Consulted FIRST by the /editor slash command (and its key chord) to compose a long prompt externally; takes precedence over EDITOR. No fallback editor is assumed \u2014 if neither VISUAL nor EDITOR is set, /editor prints a hint instead of guessing.",type:"string",required:!1,example:"nvim",category:"process"},{name:"EDITOR",description:"Standard POSIX env var naming the user's preferred editor (with optional flags). Consulted by the /editor slash command AFTER VISUAL, as the standard fallback. No default editor is assumed when both are unset \u2014 /editor prints a hint telling the user to set one.",type:"string",required:!1,example:"vim",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],b={get AFK_COMPACT_KEEP_LAST_TURNS(){return process.env.AFK_COMPACT_KEEP_LAST_TURNS},get AFK_COMPACT_MODEL(){return process.env.AFK_COMPACT_MODEL},get AFK_COMPACT_SHRINK_FRACTION(){return process.env.AFK_COMPACT_SHRINK_FRACTION},get AFK_COMPANION_PRIMER(){return process.env.AFK_COMPANION_PRIMER},get AFK_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_OUTPUT_TOKENS(){return process.env.AFK_MAX_OUTPUT_TOKENS},get AFK_MAX_TOKENS(){return process.env.AFK_MAX_TOKENS},get AFK_MAX_TOOL_USE_ITERATIONS(){return process.env.AFK_MAX_TOOL_USE_ITERATIONS},get AFK_MEMORY_EVIDENCE_GATE(){return process.env.AFK_MEMORY_EVIDENCE_GATE},get AFK_MICROCOMPACT_KEEP_LAST(){return process.env.AFK_MICROCOMPACT_KEEP_LAST},get AFK_MICROCOMPACT_TOOL_RESULT_BYTES(){return process.env.AFK_MICROCOMPACT_TOOL_RESULT_BYTES},get AFK_MODEL(){return process.env.AFK_MODEL},get AFK_MODEL_TTFB_TIMEOUT_MS(){return process.env.AFK_MODEL_TTFB_TIMEOUT_MS},get AFK_MODEL_LARGE(){return process.env.AFK_MODEL_LARGE},get AFK_MODEL_LARGE_API_KEY(){return process.env.AFK_MODEL_LARGE_API_KEY},get AFK_MODEL_LARGE_BASE_URL(){return process.env.AFK_MODEL_LARGE_BASE_URL},get AFK_MODEL_LOCAL(){return process.env.AFK_MODEL_LOCAL},get AFK_MODEL_LOCAL_API_KEY(){return process.env.AFK_MODEL_LOCAL_API_KEY},get AFK_MODEL_LOCAL_BASE_URL(){return process.env.AFK_MODEL_LOCAL_BASE_URL},get AFK_MODEL_MEDIUM(){return process.env.AFK_MODEL_MEDIUM},get AFK_MODEL_MEDIUM_API_KEY(){return process.env.AFK_MODEL_MEDIUM_API_KEY},get AFK_MODEL_MEDIUM_BASE_URL(){return process.env.AFK_MODEL_MEDIUM_BASE_URL},get AFK_MODEL_SMALL(){return process.env.AFK_MODEL_SMALL},get AFK_MODEL_SMALL_API_KEY(){return process.env.AFK_MODEL_SMALL_API_KEY},get AFK_MODEL_SMALL_BASE_URL(){return process.env.AFK_MODEL_SMALL_BASE_URL},get AFK_VISION_MODELS(){return process.env.AFK_VISION_MODELS},get AFK_PROMPT_CACHE_TTL(){return process.env.AFK_PROMPT_CACHE_TTL},get AFK_SUGGEST_ENABLED(){return process.env.AFK_SUGGEST_ENABLED},get AFK_SUGGEST_GHOST(){return process.env.AFK_SUGGEST_GHOST},get AFK_SUGGEST_MODEL(){return process.env.AFK_SUGGEST_MODEL},get AFK_SUBAGENT_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_TIMEOUT_MS},get AFK_SUBAGENT_IDLE_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_IDLE_TIMEOUT_MS},get AFK_TASK_BUDGET(){return process.env.AFK_TASK_BUDGET},get AFK_TEMPERATURE(){return process.env.AFK_TEMPERATURE},get AFK_THINKING(){return process.env.AFK_THINKING},get AFK_THINKING_UI(){return process.env.AFK_THINKING_UI},get AFK_TIMEOUT_MS(){return process.env.AFK_TIMEOUT_MS},get CLAUDE_MODEL(){return process.env.CLAUDE_MODEL},get AFK_SYSTEM_PROMPT(){return process.env.AFK_SYSTEM_PROMPT},get AFK_DUMP_PROMPT(){return process.env.AFK_DUMP_PROMPT},get ANTHROPIC_API_KEY(){return process.env.ANTHROPIC_API_KEY},get CLAUDE_CODE_OAUTH_TOKEN(){return process.env.CLAUDE_CODE_OAUTH_TOKEN},get OPENAI_API_KEY(){return process.env.OPENAI_API_KEY},get CODEX_API_KEY(){return process.env.CODEX_API_KEY},get AFK_LOCAL_API_KEY(){return process.env.AFK_LOCAL_API_KEY},get AFK_LOCAL_BASE_URL(){return process.env.AFK_LOCAL_BASE_URL},get AFK_OPENAI_BASE_URL(){return process.env.AFK_OPENAI_BASE_URL},get AFK_OPENAI_USE_RESPONSES(){return process.env.AFK_OPENAI_USE_RESPONSES},get AFK_OPENAI_CHATGPT_OAUTH(){return process.env.AFK_OPENAI_CHATGPT_OAUTH},get AFK_PROVIDER(){return process.env.AFK_PROVIDER},get EXA_API_KEY(){return process.env.EXA_API_KEY},get TELEGRAM_BOT_TOKEN(){return process.env.TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_BOT_TOKEN(){return process.env.AFK_TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_ALLOWED_CHAT_IDS(){return process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS},get AFK_TELEGRAM_TAG_ONLY_CHAT_IDS(){return process.env.AFK_TELEGRAM_TAG_ONLY_CHAT_IDS},get AFK_TELEGRAM_PRIMARY_CHAT_ID(){return process.env.AFK_TELEGRAM_PRIMARY_CHAT_ID},get AFK_TELEGRAM_NOTIFY_MODE(){return process.env.AFK_TELEGRAM_NOTIFY_MODE},get TELEGRAM_DATA_DIR(){return process.env.TELEGRAM_DATA_DIR},get TELEGRAM_VERBOSE(){return process.env.TELEGRAM_VERBOSE},get AFK_TELEGRAM_TRACE(){return process.env.AFK_TELEGRAM_TRACE},get AFK_TELEGRAM_CWD(){return process.env.AFK_TELEGRAM_CWD},get AFK_HOME(){return process.env.AFK_HOME},get AFK_STATE_DIR(){return process.env.AFK_STATE_DIR},get AFK_FRAMEWORK_DIR(){return process.env.AFK_FRAMEWORK_DIR},get HOME(){return process.env.HOME},get PATH(){return process.env.PATH},get AFK_DAEMON_CWD(){return process.env.AFK_DAEMON_CWD},get AFK_DAEMON_TASK(){return process.env.AFK_DAEMON_TASK},get AFK_DAEMON_TASK_ID(){return process.env.AFK_DAEMON_TASK_ID},get AFK_DAEMON_HOST(){return process.env.AFK_DAEMON_HOST},get AFK_SESSIONSTART_COOLDOWN_MS(){return process.env.AFK_SESSIONSTART_COOLDOWN_MS},get AFK_WORKTREE_AUTONAME(){return process.env.AFK_WORKTREE_AUTONAME},get AFK_WORKTREE_BRANCH_PREFIX(){return process.env.AFK_WORKTREE_BRANCH_PREFIX},get AFK_WORKTREE_BASE(){return process.env.AFK_WORKTREE_BASE},get AFK_WORKTREE_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BG_AUTO_DELIVER(){return process.env.AFK_BG_AUTO_DELIVER},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_PLAIN_OUTPUT(){return process.env.AFK_PLAIN_OUTPUT},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},get AFK_GOBLIN_SPINNER(){return process.env.AFK_GOBLIN_SPINNER},get AFK_TERM_TITLE(){return process.env.AFK_TERM_TITLE},get AFK_NOTIFY(){return process.env.AFK_NOTIFY},get AFK_SHOW_DIFFS(){return process.env.AFK_SHOW_DIFFS},get AFK_SKILL_STREAM_VERBOSE(){return process.env.AFK_SKILL_STREAM_VERBOSE},get FORCE_COLOR(){return process.env.FORCE_COLOR},get NO_COLOR(){return process.env.NO_COLOR},get AFK_THEME(){return process.env.AFK_THEME},get COLORFGBG(){return process.env.COLORFGBG},get AFK_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_BROWSER_DEFAULT_PROFILE(){return process.env.AFK_BROWSER_DEFAULT_PROFILE},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_READ_DENYLIST(){return process.env.AFK_READ_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get VISUAL(){return process.env.VISUAL},get EDITOR(){return process.env.EDITOR},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let e of Vr){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(b,e.name);n&&Object.defineProperty(b,e.name,{...n,enumerable:!1})}})()});function Kb(){return b.AFK_DEBUG==="1"||b.DEBUG==="1"}function C(...t){Kb()&&console.log(...t)}var re=ye(()=>{"use strict";N()});import{existsSync as Sd,mkdirSync as fw,renameSync as mw,cpSync as gw,rmSync as hw}from"fs";import{join as W,dirname as la,basename as yw,isAbsolute as kd}from"path";import{homedir as _d}from"os";import{fileURLToPath as bw}from"url";function ge(){let t=b.AFK_HOME;if(t!==void 0&&t!==""){if(!kd(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return W(_d(),".afk")}function $e(){return W(ge(),"agent-framework")}function uo(){return W($e(),"forge-telemetry.jsonl")}function Ad(){return W($e(),"briefs")}function Ed(){return W($e(),"facets")}function Dn(){return W(ge(),"skills")}function Vt(){return W(ge(),"plugins")}function Td(t=process.cwd()){return W(t,".afk")}function xd(t=process.cwd()){return W(Td(t),"skills")}function Rd(t=process.cwd()){return W(Td(t),"plugins")}function Id(t=process.cwd()){return W(t,".afk","plans")}function po(){return W(Vt(),".index.json")}function ca(){return W(Fn(),"schedules.json")}function Cd(){let t=bw(import.meta.url),e=la(t);return W(e,"bundled-plugins")}function Fn(){return W(ge(),"config")}function Me(){let t=b.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!kd(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return W(ge(),"state")}function we(){return W(Me(),"sessions")}function fo(){return W(Me(),"presence")}function mo(){return W(Me(),"memory")}function go(){return W(Me(),"session-grants.jsonl")}function Pd(){return W(ge(),"farms")}function Md(t){return W(Pd(),t)}function ho(t){if(!ww.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function Od(t){return ho(t),W(Me(),"witness",t)}function Dd(t){return!t||t.startsWith("in-memory:")?null:yw(la(t))}function Fd(t="default"){return W(Me(),"daemon",`agent-afk@${t}`)}function Ld(){return W(Me(),"worktree-sweep.lock")}function da(){return W(Fn(),"afk.env")}function Xt(){return W(Fn(),"afk.config.json")}function yo(){return W(_d(),".afk.config.json")}function Sw(){return W(ge(),"sessions")}function vw(t,e){if(t!==e&&Sd(t)&&!Sd(e))try{fw(la(e),{recursive:!0});try{mw(t,e)}catch(n){if(n.code==="EXDEV")try{gw(t,e,{recursive:!0}),hw(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
|
|
2
2
|
`)}}}catch{}}function Nd(){vw(Sw(),we())}function ua(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>vd)throw new Error(`Invalid browser profile: exceeds ${vd} chars`);if(!kw.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function _w(){return W(Me(),"browser")}function Aw(t){return ua(t),W(_w(),t)}function pa(t){return W(Aw(t),"storageState.json")}function Ln(t){return typeof t=="string"&&t.length>0&&t.length<=Tw&&Ew.test(t)}function Nn(t){if(!Ln(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return W(we(),t)}function bo(t){return W(Nn(t),"events.jsonl")}function Ud(t){return W(Nn(t),"session.key")}var ww,kw,vd,Ew,Tw,K=ye(()=>{"use strict";N();ww=/^[a-zA-Z0-9_-]+$/;kw=/^[A-Za-z0-9_-]+$/,vd=128;Ew=/^[A-Za-z0-9_-]+$/,Tw=128});import{readFileSync as K_}from"node:fs";import{join as W_}from"path";function G_(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Dp(t,e){return G_(e).test(t)}function J_(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(q_.has(e))return!0;if(z_.has(e))return!1}return!1}function Fp(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function Y_(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function Lp(t){let e=t===void 0||t.trim()===""?"default":t.trim();return ua(e),e}function V_(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function X_(t){try{return K_(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function Q_(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=Lp(e.defaultProfile)),n}function Np(t){let e=t?.env??b,n=t?.readFileSync??X_,r=t?.surface??e.AGENT_SURFACE,o=J_(e.AFK_BROWSER_HEADLESS,r),s=Fp(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Fp(e.AFK_BROWSER_BLOCKED_DOMAINS),a=V_(e.AFK_BROWSER_DOM_SNAPSHOTS),l=Y_(e.AFK_BROWSER_BACKEND),c=Lp(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():W_(Fn(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(h){throw new Error(`Failed to parse browser config at ${p}: ${String(h)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=Q_(d,m);return g.configPath=p,g}function ts(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(Dp(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Dp(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var q_,z_,ns=ye(()=>{"use strict";N();K();q_=new Set(["daemon","subagent","telegram","afk"]),z_=new Set(["repl","interactive","cli"])});import{existsSync as Z_,readFileSync as eA}from"node:fs";import{createRequire as tA}from"node:module";import{dirname as nA,join as rA}from"node:path";function Bp(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<sA&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function he(t){let e=Bp(t);return $p.some(n=>e.includes(n))}function iA(){try{let e=tA(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(eA(e,"utf8"));if(typeof n!="object"||n===null)return;let r=n.bin,o=typeof r=="string"?r:typeof r=="object"&&r!==null?r.playwright:void 0;if(typeof o!="string"||o.length===0)return;let s=rA(nA(e),o);return Z_(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function ar(){return Up??=iA()??oA,Up}function Ya(t){return t.includes("install chromium")}function Re(t,e){let n=Bp(t),r=e?.latched===!0?` ${aA}`:"";if(n.includes("Executable doesn't exist")){let o="";return e?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":e?.headless===!1&&(o=" This launch was headed, which needs the full `chromium-*` build \u2014 the headless shell alone does not satisfy it."),`browser tools require the Playwright chromium binary. Install via: ${ar()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${ar()}). Or pick a different tool.${r}`}function Va(t,e,n=!1){if(!he(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
3
3
|
|
|
4
|
-
${Re(t,{headless:e,latched:n})}`,{cause:t})}var $p,oA,sA,Up,aA,Xa=ye(()=>{"use strict";$p=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],oA="pnpm exec playwright install chromium",sA=4;aA="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Mt from"node:fs";import rs from"node:path";import{randomBytes as lA}from"node:crypto";import{chromium as cA}from"playwright";function dA(){try{return"5.82.2"}catch{}try{let t=rs.resolve(import.meta.dirname,"../../../package.json"),e=Mt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var uA,os,Hp=ye(()=>{"use strict";Xa();K();re();uA=dA(),os=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=cA.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Va(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await i.content(),c=i.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${uA}`}}loadStorageState(e){let n=pa(e);try{if(!Mt.existsSync(n))return;let r=JSON.parse(Mt.readFileSync(n,"utf8"));return C("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){C("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=pa(e);if(!Mt.existsSync(r))return;let o=await n.storageState(),s=rs.join(rs.dirname(r),`.${rs.basename(r)}.${process.pid}.${lA(4).toString("hex")}.tmp`);Mt.writeFileSync(s,JSON.stringify(o),{mode:384}),Mt.chmodSync(s,384),Mt.renameSync(s,r),C("[browser/vault] saved session",{profile:e,file:r})}catch(r){C("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as pA}from"crypto";function jp(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&fA.test(t.label))}function Kp(t){return pA("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Wp(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var fA,ss=ye(()=>{"use strict";fA=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as mA}from"node:crypto";function gA(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function hA(t,e,n){return`el_${mA("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function yA(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Gp(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function zp(t,e){let n=t.role??"",r=t.name??"";qp.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])zp(s,e)}async function bA(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},Jp).catch(()=>[])}async function wA(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},Jp).catch(()=>[])}function SA(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function is(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=SA(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=bA(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,y=!1;u!==null?(h=[],zp(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await wA(t)).filter(z=>qp.has(z.role??"")));let w=new Map;for(let R of p){let z=Gp(R.name),J=w.get(z);(!J||J.bbox.w===0&&R.bbox.w>0)&&w.set(z,R)}let E=h.map(R=>({ax:R,dom:w.get(Gp(R.name??""))})),v=r?E:E.filter(R=>R.dom?R.dom.bbox.w>0||R.dom.bbox.h>0:!0);v.sort((R,z)=>{let J=R.dom?.bbox.y??0,_=z.dom?.bbox.y??0;if(J!==_)return J-_;let O=R.dom?.bbox.x??0,P=z.dom?.bbox.x??0;return O-P}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=v.slice(0,n).map((R,z)=>{let J=R.ax.role??"generic",_=R.ax.name??"",O=hA(J,_,z),P=R.dom?.bbox??{x:0,y:0,w:0,h:0},x=R.dom?.type??null,B=null;R.ax.value!==void 0&&R.ax.value!==null&&(B=String(R.ax.value)),R.ax.checked!==void 0&&(B=String(R.ax.checked)),jp({role:J,kind:x})&&(B="[redacted]");let L={disabled:R.ax.disabled??!1};R.ax.checked!==void 0&&(L.checked=R.ax.checked===!0||R.ax.checked==="mixed"),R.ax.selected!==void 0&&(L.selected=R.ax.selected),R.ax.expanded!==void 0&&(L.expanded=R.ax.expanded);let D;R.dom?.testId?D=`[data-testid="${R.dom.testId}"]`:R.dom?.id&&(D=`#${R.dom.id}`);let F={id:O,role:J,label:gA(_),kind:x,value:B,state:L,bbox:P};return D!==void 0&&(F.selector=D),F}),I="idle";try{let R=await t.evaluate(()=>document.readyState);R==="loading"?I="loading":R==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let S=yA(f),M=`obs_${e.observationCounter.toString(36)}`,H=new Date().toISOString();return{observationId:M,url:m,title:g,textSummary:S,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:I,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:H}}var qp,Jp,Yp=ye(()=>{"use strict";ss();qp=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Jp="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Vp(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Qa(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Vp(t,s)))).filter(o=>o!==null)}async function vA(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Za(t,e,n){switch(e.kind){case"element_id":return kA(t,e,n);case"selector":return _A(t,e);case"semantic":return AA(t,e)}}async function kA(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Qa(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function _A(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Qa(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function AA(t,e){return e.role!==void 0?EA(t,e.text,e.role):TA(t,e.text,e)}async function EA(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Qa(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function TA(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:s,count:l});let u=await vA(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let h=p[g];if(h===void 0)continue;let y=await Vp(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,E=0;for(let v=0;v<w.length;v++)E=E*31+w.charCodeAt(v)>>>0;f.push({...y,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Xp=ye(()=>{"use strict"});async function el(t,e,n,r){let o=t.url();if(o===n)return null;let s=ts(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var Qp=ye(()=>{"use strict";ns()});import{randomBytes as xA}from"crypto";import{mkdir as RA,stat as IA,writeFile as CA}from"fs/promises";import{join as tl}from"path";import{gzip as PA}from"zlib";import{promisify as MA}from"util";function OA(t){return tl(Od(t),"browser")}function DA(t){return tl(OA(t),"screenshots")}function FA(){return new Date().toISOString().replace(/[:.]/g,"-")}function LA(){return xA(3).toString("hex")}async function nl(t,e,n){if(e.length>Zp)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Zp} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=DA(t);await RA(r,{recursive:!0});let o=`${FA()}-${LA()}-${n}.png`,s=tl(r,o);await CA(s,e);let{size:i}=await IA(s);return{path:s,bytes:i}}var UU,Zp,ef=ye(()=>{"use strict";K();ss();UU=MA(PA);Zp=5*1024*1024});var nf={};Bc(nf,{PlaywrightProvider:()=>rl});function tf(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var rl,rf=ye(()=>{"use strict";Hp();Yp();Xp();ns();Qp();ef();rl=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new os(e)}async open(e){let n=ts(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await el(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await is(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await is(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await Za(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${tf(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){c=h}else c=g}let u=await el(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await is(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Za(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${tf(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await nl(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await nl(n,o,r);return s}catch{return null}}}});var Dt={};Bc(Dt,{__resetBrowserRegistryForTests:()=>HA,browserProviderActive:()=>$A,closeBrowserProvider:()=>ol,getBrowserProvider:()=>UA,peekBrowserProvider:()=>BA});function of(){Promise.resolve(ol()).then(()=>{process.exit(130)})}function sf(){Promise.resolve(ol()).then(()=>{process.exit(143)})}function af(){je=null}function NA(){as||(process.on("SIGINT",of),process.on("SIGTERM",sf),process.on("exit",af),as=!0)}function lf(){as&&(process.removeListener("SIGINT",of),process.removeListener("SIGTERM",sf),process.removeListener("exit",af),as=!1)}async function UA(t){return je!==null?je:(Ot!==null||(Ot=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(rf(),nf)),n=Np(t),r=new e(n);return NA(),je=r,Ot=null,r})()),Ot)}async function ol(){if(je===null)return;let t=je;je=null,Ot=null,lf(),await t.shutdown()}function $A(){return je!==null}function BA(){return je}function HA(){je=null,Ot=null,lf()}var je,Ot,as,Ft=ye(()=>{"use strict";ns();je=null,Ot=null,as=!1});re();var _e=class extends Error{constructor(e){super(e),this.name="AbortError"}},Ae=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Qr=class extends Ae{constructor(e,n){super(e,n),this.name="IdleWatchdogError"}},q=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},Ne=class extends Error{constructor(e){super(e),this.name="StreamIncompleteError"}},it=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},Wt=class extends Error{constructor(e){super(e),this.name="DenialCircuitBreakerError"}};re();async function Gt(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){C(`trace.emit tool_call failed: ${Ge(n)}`)}}async function at(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){C(`trace.emit hook_decision failed: ${Ge(n)}`)}}async function kt(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){C(`trace.emit subagent_lifecycle failed: ${Ge(n)}`)}}async function Hc(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){C(`trace.emit budget failed: ${Ge(n)}`)}}async function jc(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){C(`trace.emit abort failed: ${Ge(n)}`)}}async function Zr(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){C(`trace.emit compaction failed: ${Ge(n)}`)}}async function Kc(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){C(`trace.emit closure failed: ${Ge(n)}`)}}async function le(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){C(`trace.emit browser_event failed: ${Ge(n)}`)}}async function G(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){C(`trace.emit session_phase failed: ${Ge(n)}`)}}function Ge(t){return t instanceof Error?t.message:String(t)}import ry from"@anthropic-ai/sdk";var Wc="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",Wb="effort-2025-11-24",Gb="claude-cli/1.0.0 (external, cli)",qb="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function eo(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Cn(t,e,n,r){let o=e==="oauth"?{authToken:t}:{apiKey:t},s=typeof n=="string"&&n.length>0?{...o,baseURL:n}:o;return r?{...s,fetch:r}:s}function Pe(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${Wc},${Wb}`:Wc,"x-app":"cli","User-Agent":Gb,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Gc(t){return t!=="oauth"?null:[{type:"text",text:qb}]}import Vb from"@anthropic-ai/sdk";N();var Pn=["local","small","medium","large"],zc="claude-haiku-4-5-20251001",Vi="claude-sonnet-5",Xi="claude-opus-5",Zi="claude-fable-5",_t={local:{id:""},small:{id:zc},medium:{id:Vi},large:{id:Xi}},Jc="auto",ea={opus:Xi,opus_1m:Xi,sonnet:Vi,sonnet_1m:Vi,haiku:zc,fable:Zi},zt=[...Pn,...Object.keys(ea)],Qi;function ta(t){Qi=t}function Yi(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function to(t,e,n){let r={},o=Yi(t);o&&(r.id=o);let s=Yi(e);s&&(r.baseUrl=s);let i=Yi(n);return i&&(r.apiKey=i),r}function zb(){return{local:to(b.AFK_MODEL_LOCAL,b.AFK_MODEL_LOCAL_BASE_URL,b.AFK_MODEL_LOCAL_API_KEY),small:to(b.AFK_MODEL_SMALL,b.AFK_MODEL_SMALL_BASE_URL,b.AFK_MODEL_SMALL_API_KEY),medium:to(b.AFK_MODEL_MEDIUM,b.AFK_MODEL_MEDIUM_BASE_URL,b.AFK_MODEL_MEDIUM_API_KEY),large:to(b.AFK_MODEL_LARGE,b.AFK_MODEL_LARGE_BASE_URL,b.AFK_MODEL_LARGE_API_KEY)}}function Yc(t){let e=zb(),n={};for(let r of Pn){let o=_t[r],s=t?.[r],i=e[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 d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function Jt(t){return t||Qi||Yc()}function Yt(t,e=Jt()){let n=t.trim().toLowerCase();if(!(!n||n===Jc)){for(let r of Pn){let o=e[r].name;if(o&&o.trim().toLowerCase()===n)return r}if(n==="local"||n==="small"||n==="medium"||n==="large")return n}}function At(t,e=Jt()){if(t===void 0)return{id:""};let n=Yt(t,e);if(n)return e[n];let r=ea[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function lt(t,e=Jt()){if(t!==void 0)return At(t,e).id}function Vc(t,e=Jt()){if(t===void 0)return;let n=Yt(t,e);if(n&&e[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function Xc(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of Pn){let o=Yb(n[r]);o&&(e[r]=o)}return e}function Qc(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="anthropic"||e==="anthropic-direct")return"anthropic";if(e==="openai"||e==="openai-compatible")return"openai";if(e==="chatgpt-oauth"||e==="chatgpt")return"chatgpt-oauth"}function qt(t){return typeof t=="string"?t.trim():""}function qc(t){return/[\x00-\x1f\x7f]/.test(t)}var Jb=new Set([...Pn,Jc,...Object.keys(ea)]);function Yb(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=qt(e.id);if(!n)return;let r={id:n},o=qt(e.name);o&&(r.name=o);let s=Qc(e.provider);s&&(r.provider=s);let i=qt(e.baseUrl);i&&(r.baseUrl=i);let a=qt(e.apiKey);return a&&(r.apiKey=a),r}}function Zc(t){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:'model binding must be an object with at least an "id"'};let e=t;if("apiKey"in e||"api_key"in e)return{ok:!1,error:"per-slot API keys are credentials; set AFK_MODEL_<TIER>_API_KEY via `afk config env set` instead of afk.config.json"};if("baseUrl"in e||"base_url"in e)return{ok:!1,error:"per-slot baseUrl is an endpoint-redirect credential vector; set AFK_MODEL_<TIER>_BASE_URL via `afk config env set` instead of afk.config.json"};let n=qt(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(qc(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=qt(e.name);if(o){if(qc(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(Jb.has(o.trim().toLowerCase()))return{ok:!1,error:`model binding "name" must not shadow a built-in alias ("${o}")`};r.name=o}if(e.provider!==void 0&&e.provider!==""){let s=Qc(e.provider);if(!s)return{ok:!1,error:'model binding "provider" must be one of: anthropic, openai (aliases: anthropic-direct, openai-compatible)'};r.provider=s}return{ok:!0,value:r}}var na={opus:_t.large.id,opus_1m:_t.large.id,sonnet:_t.medium.id,sonnet_1m:_t.medium.id,haiku:_t.small.id,fable:Zi};function no(t){return t in na}function fe(t){return lt(t)}import{randomUUID as ed}from"node:crypto";async function td(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let l=eo(e),c=Cn(e,l),d=a?a(c):new Vb(c),u=ed(),p=ed(),f=Pe(l,u,p),m=fe(n)??n,g={};Object.keys(f).length>0&&(g.headers=f),i&&(g.signal=i);let h=await d.messages.create({model:m,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(g).length>0?g:void 0),y=[];for(let E of h.content)E.type==="text"&&y.push(E.text);let w=y.join("").trim();return w.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),w}import{execFileSync as nd}from"child_process";import{existsSync as Xb,readFileSync as Qb,writeFileSync as Zb}from"fs";import{homedir as rd,userInfo as od}from"os";import{join as sd}from"path";var ew="9d1c250a-e61b-44d9-88ed-5944d1962f5e",tw="https://platform.claude.com/v1/oauth/token",nw=300*1e3;function be(){let t=id();if(t===void 0)return;let e=ad(t);if(e!==void 0){if(e.expiresAt!==void 0&&e.expiresAt<=Date.now()){process.stderr.write("agent-afk: Claude Code OAuth token in keychain is expired. Run `claude login` to refresh.\n");return}return e.accessToken}}async function ra(){let t=id();if(t===void 0)return;let e=ad(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+nw)return e.accessToken;if(!e.refreshToken){process.stderr.write("agent-afk: OAuth token expired and no refresh token available. Run `claude login` to refresh.\n");return}let n=await rw(e.refreshToken);if(!n){process.stderr.write("agent-afk: OAuth token refresh failed. Run `claude login` to refresh.\n");return}try{let r={};try{r=JSON.parse(t)}catch{}let o=r.claudeAiOauth??{};r.claudeAiOauth={...o,accessToken:n.accessToken,expiresAt:n.expiresAt,...n.refreshToken!==void 0?{refreshToken:n.refreshToken}:{}},ow(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
4
|
+
${Re(t,{headless:e,latched:n})}`,{cause:t})}var $p,oA,sA,Up,aA,Xa=ye(()=>{"use strict";$p=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],oA="pnpm exec playwright install chromium",sA=4;aA="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Mt from"node:fs";import rs from"node:path";import{randomBytes as lA}from"node:crypto";import{chromium as cA}from"playwright";function dA(){try{return"5.82.3"}catch{}try{let t=rs.resolve(import.meta.dirname,"../../../package.json"),e=Mt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var uA,os,Hp=ye(()=>{"use strict";Xa();K();re();uA=dA(),os=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=cA.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Va(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await i.content(),c=i.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${uA}`}}loadStorageState(e){let n=pa(e);try{if(!Mt.existsSync(n))return;let r=JSON.parse(Mt.readFileSync(n,"utf8"));return C("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){C("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=pa(e);if(!Mt.existsSync(r))return;let o=await n.storageState(),s=rs.join(rs.dirname(r),`.${rs.basename(r)}.${process.pid}.${lA(4).toString("hex")}.tmp`);Mt.writeFileSync(s,JSON.stringify(o),{mode:384}),Mt.chmodSync(s,384),Mt.renameSync(s,r),C("[browser/vault] saved session",{profile:e,file:r})}catch(r){C("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as pA}from"crypto";function jp(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&fA.test(t.label))}function Kp(t){return pA("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Wp(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var fA,ss=ye(()=>{"use strict";fA=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as mA}from"node:crypto";function gA(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function hA(t,e,n){return`el_${mA("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function yA(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Gp(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function zp(t,e){let n=t.role??"",r=t.name??"";qp.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])zp(s,e)}async function bA(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},Jp).catch(()=>[])}async function wA(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},Jp).catch(()=>[])}function SA(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function is(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=SA(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=bA(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,y=!1;u!==null?(h=[],zp(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await wA(t)).filter(z=>qp.has(z.role??"")));let w=new Map;for(let R of p){let z=Gp(R.name),J=w.get(z);(!J||J.bbox.w===0&&R.bbox.w>0)&&w.set(z,R)}let E=h.map(R=>({ax:R,dom:w.get(Gp(R.name??""))})),v=r?E:E.filter(R=>R.dom?R.dom.bbox.w>0||R.dom.bbox.h>0:!0);v.sort((R,z)=>{let J=R.dom?.bbox.y??0,_=z.dom?.bbox.y??0;if(J!==_)return J-_;let O=R.dom?.bbox.x??0,P=z.dom?.bbox.x??0;return O-P}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=v.slice(0,n).map((R,z)=>{let J=R.ax.role??"generic",_=R.ax.name??"",O=hA(J,_,z),P=R.dom?.bbox??{x:0,y:0,w:0,h:0},x=R.dom?.type??null,B=null;R.ax.value!==void 0&&R.ax.value!==null&&(B=String(R.ax.value)),R.ax.checked!==void 0&&(B=String(R.ax.checked)),jp({role:J,kind:x})&&(B="[redacted]");let L={disabled:R.ax.disabled??!1};R.ax.checked!==void 0&&(L.checked=R.ax.checked===!0||R.ax.checked==="mixed"),R.ax.selected!==void 0&&(L.selected=R.ax.selected),R.ax.expanded!==void 0&&(L.expanded=R.ax.expanded);let D;R.dom?.testId?D=`[data-testid="${R.dom.testId}"]`:R.dom?.id&&(D=`#${R.dom.id}`);let F={id:O,role:J,label:gA(_),kind:x,value:B,state:L,bbox:P};return D!==void 0&&(F.selector=D),F}),I="idle";try{let R=await t.evaluate(()=>document.readyState);R==="loading"?I="loading":R==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let S=yA(f),M=`obs_${e.observationCounter.toString(36)}`,H=new Date().toISOString();return{observationId:M,url:m,title:g,textSummary:S,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:I,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:H}}var qp,Jp,Yp=ye(()=>{"use strict";ss();qp=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Jp="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Vp(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Qa(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Vp(t,s)))).filter(o=>o!==null)}async function vA(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Za(t,e,n){switch(e.kind){case"element_id":return kA(t,e,n);case"selector":return _A(t,e);case"semantic":return AA(t,e)}}async function kA(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Qa(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function _A(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Qa(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function AA(t,e){return e.role!==void 0?EA(t,e.text,e.role):TA(t,e.text,e)}async function EA(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Qa(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function TA(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:s,count:l});let u=await vA(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let h=p[g];if(h===void 0)continue;let y=await Vp(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,E=0;for(let v=0;v<w.length;v++)E=E*31+w.charCodeAt(v)>>>0;f.push({...y,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Xp=ye(()=>{"use strict"});async function el(t,e,n,r){let o=t.url();if(o===n)return null;let s=ts(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var Qp=ye(()=>{"use strict";ns()});import{randomBytes as xA}from"crypto";import{mkdir as RA,stat as IA,writeFile as CA}from"fs/promises";import{join as tl}from"path";import{gzip as PA}from"zlib";import{promisify as MA}from"util";function OA(t){return tl(Od(t),"browser")}function DA(t){return tl(OA(t),"screenshots")}function FA(){return new Date().toISOString().replace(/[:.]/g,"-")}function LA(){return xA(3).toString("hex")}async function nl(t,e,n){if(e.length>Zp)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Zp} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=DA(t);await RA(r,{recursive:!0});let o=`${FA()}-${LA()}-${n}.png`,s=tl(r,o);await CA(s,e);let{size:i}=await IA(s);return{path:s,bytes:i}}var UU,Zp,ef=ye(()=>{"use strict";K();ss();UU=MA(PA);Zp=5*1024*1024});var nf={};Bc(nf,{PlaywrightProvider:()=>rl});function tf(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var rl,rf=ye(()=>{"use strict";Hp();Yp();Xp();ns();Qp();ef();rl=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new os(e)}async open(e){let n=ts(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await el(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await is(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await is(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await Za(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${tf(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){c=h}else c=g}let u=await el(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await is(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Za(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${tf(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await nl(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await nl(n,o,r);return s}catch{return null}}}});var Dt={};Bc(Dt,{__resetBrowserRegistryForTests:()=>HA,browserProviderActive:()=>$A,closeBrowserProvider:()=>ol,getBrowserProvider:()=>UA,peekBrowserProvider:()=>BA});function of(){Promise.resolve(ol()).then(()=>{process.exit(130)})}function sf(){Promise.resolve(ol()).then(()=>{process.exit(143)})}function af(){je=null}function NA(){as||(process.on("SIGINT",of),process.on("SIGTERM",sf),process.on("exit",af),as=!0)}function lf(){as&&(process.removeListener("SIGINT",of),process.removeListener("SIGTERM",sf),process.removeListener("exit",af),as=!1)}async function UA(t){return je!==null?je:(Ot!==null||(Ot=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(rf(),nf)),n=Np(t),r=new e(n);return NA(),je=r,Ot=null,r})()),Ot)}async function ol(){if(je===null)return;let t=je;je=null,Ot=null,lf(),await t.shutdown()}function $A(){return je!==null}function BA(){return je}function HA(){je=null,Ot=null,lf()}var je,Ot,as,Ft=ye(()=>{"use strict";ns();je=null,Ot=null,as=!1});re();var _e=class extends Error{constructor(e){super(e),this.name="AbortError"}},Ae=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Qr=class extends Ae{constructor(e,n){super(e,n),this.name="IdleWatchdogError"}},q=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},Ne=class extends Error{constructor(e){super(e),this.name="StreamIncompleteError"}},it=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},Wt=class extends Error{constructor(e){super(e),this.name="DenialCircuitBreakerError"}};re();async function Gt(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){C(`trace.emit tool_call failed: ${Ge(n)}`)}}async function at(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){C(`trace.emit hook_decision failed: ${Ge(n)}`)}}async function kt(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){C(`trace.emit subagent_lifecycle failed: ${Ge(n)}`)}}async function Hc(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){C(`trace.emit budget failed: ${Ge(n)}`)}}async function jc(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){C(`trace.emit abort failed: ${Ge(n)}`)}}async function Zr(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){C(`trace.emit compaction failed: ${Ge(n)}`)}}async function Kc(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){C(`trace.emit closure failed: ${Ge(n)}`)}}async function le(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){C(`trace.emit browser_event failed: ${Ge(n)}`)}}async function G(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){C(`trace.emit session_phase failed: ${Ge(n)}`)}}function Ge(t){return t instanceof Error?t.message:String(t)}import ry from"@anthropic-ai/sdk";var Wc="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",Wb="effort-2025-11-24",Gb="claude-cli/1.0.0 (external, cli)",qb="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function eo(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Cn(t,e,n,r){let o=e==="oauth"?{authToken:t}:{apiKey:t},s=typeof n=="string"&&n.length>0?{...o,baseURL:n}:o;return r?{...s,fetch:r}:s}function Pe(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${Wc},${Wb}`:Wc,"x-app":"cli","User-Agent":Gb,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Gc(t){return t!=="oauth"?null:[{type:"text",text:qb}]}import Vb from"@anthropic-ai/sdk";N();var Pn=["local","small","medium","large"],zc="claude-haiku-4-5-20251001",Vi="claude-sonnet-5",Xi="claude-opus-5",Zi="claude-fable-5",_t={local:{id:""},small:{id:zc},medium:{id:Vi},large:{id:Xi}},Jc="auto",ea={opus:Xi,opus_1m:Xi,sonnet:Vi,sonnet_1m:Vi,haiku:zc,fable:Zi},zt=[...Pn,...Object.keys(ea)],Qi;function ta(t){Qi=t}function Yi(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function to(t,e,n){let r={},o=Yi(t);o&&(r.id=o);let s=Yi(e);s&&(r.baseUrl=s);let i=Yi(n);return i&&(r.apiKey=i),r}function zb(){return{local:to(b.AFK_MODEL_LOCAL,b.AFK_MODEL_LOCAL_BASE_URL,b.AFK_MODEL_LOCAL_API_KEY),small:to(b.AFK_MODEL_SMALL,b.AFK_MODEL_SMALL_BASE_URL,b.AFK_MODEL_SMALL_API_KEY),medium:to(b.AFK_MODEL_MEDIUM,b.AFK_MODEL_MEDIUM_BASE_URL,b.AFK_MODEL_MEDIUM_API_KEY),large:to(b.AFK_MODEL_LARGE,b.AFK_MODEL_LARGE_BASE_URL,b.AFK_MODEL_LARGE_API_KEY)}}function Yc(t){let e=zb(),n={};for(let r of Pn){let o=_t[r],s=t?.[r],i=e[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 d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function Jt(t){return t||Qi||Yc()}function Yt(t,e=Jt()){let n=t.trim().toLowerCase();if(!(!n||n===Jc)){for(let r of Pn){let o=e[r].name;if(o&&o.trim().toLowerCase()===n)return r}if(n==="local"||n==="small"||n==="medium"||n==="large")return n}}function At(t,e=Jt()){if(t===void 0)return{id:""};let n=Yt(t,e);if(n)return e[n];let r=ea[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function lt(t,e=Jt()){if(t!==void 0)return At(t,e).id}function Vc(t,e=Jt()){if(t===void 0)return;let n=Yt(t,e);if(n&&e[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function Xc(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of Pn){let o=Yb(n[r]);o&&(e[r]=o)}return e}function Qc(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="anthropic"||e==="anthropic-direct")return"anthropic";if(e==="openai"||e==="openai-compatible")return"openai";if(e==="chatgpt-oauth"||e==="chatgpt")return"chatgpt-oauth"}function qt(t){return typeof t=="string"?t.trim():""}function qc(t){return/[\x00-\x1f\x7f]/.test(t)}var Jb=new Set([...Pn,Jc,...Object.keys(ea)]);function Yb(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=qt(e.id);if(!n)return;let r={id:n},o=qt(e.name);o&&(r.name=o);let s=Qc(e.provider);s&&(r.provider=s);let i=qt(e.baseUrl);i&&(r.baseUrl=i);let a=qt(e.apiKey);return a&&(r.apiKey=a),r}}function Zc(t){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:'model binding must be an object with at least an "id"'};let e=t;if("apiKey"in e||"api_key"in e)return{ok:!1,error:"per-slot API keys are credentials; set AFK_MODEL_<TIER>_API_KEY via `afk config env set` instead of afk.config.json"};if("baseUrl"in e||"base_url"in e)return{ok:!1,error:"per-slot baseUrl is an endpoint-redirect credential vector; set AFK_MODEL_<TIER>_BASE_URL via `afk config env set` instead of afk.config.json"};let n=qt(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(qc(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=qt(e.name);if(o){if(qc(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(Jb.has(o.trim().toLowerCase()))return{ok:!1,error:`model binding "name" must not shadow a built-in alias ("${o}")`};r.name=o}if(e.provider!==void 0&&e.provider!==""){let s=Qc(e.provider);if(!s)return{ok:!1,error:'model binding "provider" must be one of: anthropic, openai (aliases: anthropic-direct, openai-compatible)'};r.provider=s}return{ok:!0,value:r}}var na={opus:_t.large.id,opus_1m:_t.large.id,sonnet:_t.medium.id,sonnet_1m:_t.medium.id,haiku:_t.small.id,fable:Zi};function no(t){return t in na}function fe(t){return lt(t)}import{randomUUID as ed}from"node:crypto";async function td(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let l=eo(e),c=Cn(e,l),d=a?a(c):new Vb(c),u=ed(),p=ed(),f=Pe(l,u,p),m=fe(n)??n,g={};Object.keys(f).length>0&&(g.headers=f),i&&(g.signal=i);let h=await d.messages.create({model:m,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(g).length>0?g:void 0),y=[];for(let E of h.content)E.type==="text"&&y.push(E.text);let w=y.join("").trim();return w.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),w}import{execFileSync as nd}from"child_process";import{existsSync as Xb,readFileSync as Qb,writeFileSync as Zb}from"fs";import{homedir as rd,userInfo as od}from"os";import{join as sd}from"path";var ew="9d1c250a-e61b-44d9-88ed-5944d1962f5e",tw="https://platform.claude.com/v1/oauth/token",nw=300*1e3;function be(){let t=id();if(t===void 0)return;let e=ad(t);if(e!==void 0){if(e.expiresAt!==void 0&&e.expiresAt<=Date.now()){process.stderr.write("agent-afk: Claude Code OAuth token in keychain is expired. Run `claude login` to refresh.\n");return}return e.accessToken}}async function ra(){let t=id();if(t===void 0)return;let e=ad(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+nw)return e.accessToken;if(!e.refreshToken){process.stderr.write("agent-afk: OAuth token expired and no refresh token available. Run `claude login` to refresh.\n");return}let n=await rw(e.refreshToken);if(!n){process.stderr.write("agent-afk: OAuth token refresh failed. Run `claude login` to refresh.\n");return}try{let r={};try{r=JSON.parse(t)}catch{}let o=r.claudeAiOauth??{};r.claudeAiOauth={...o,accessToken:n.accessToken,expiresAt:n.expiresAt,...n.refreshToken!==void 0?{refreshToken:n.refreshToken}:{}},ow(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
5
5
|
`)}return n.accessToken}function id(){if(process.platform==="darwin")try{return nd("security",["find-generic-password","-s","Claude Code-credentials","-a",od().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=sd(rd(),".claude",".credentials.json");if(!Xb(t))return;try{return Qb(t,"utf-8")}catch{return}}}function ad(t){let e;try{e=JSON.parse(t)}catch{return}if(typeof e!="object"||e===null)return;let n=e.claudeAiOauth;if(typeof n!="object"||n===null)return;let r=n,o=r.accessToken;if(typeof o!="string"||o.length===0)return;let s={accessToken:o},i=r.refreshToken;typeof i=="string"&&i.length>0&&(s.refreshToken=i);let a=r.expiresAt;return typeof a=="number"&&(s.expiresAt=a),s}async function rw(t){try{let e=await fetch(tw,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:ew})});if(!e.ok)return;let n=await e.json(),r=n.access_token,o=n.expires_in;if(typeof r!="string"||typeof o!="number")return;let s=n.refresh_token;return{accessToken:r,expiresAt:Date.now()+o*1e3,...typeof s=="string"&&s.length>0?{refreshToken:s}:{}}}catch{return}}function Mn(t){if(!t||t.length<3)return"token:(unknown)";try{let n=t.split(".");if(n.length<2)throw new Error("not a JWT");let r=Buffer.from(n[1],"base64url").toString("utf-8"),o=JSON.parse(r),s=typeof o.email=="string"&&o.email||typeof o.sub=="string"&&o.sub||typeof o.account_id=="string"&&o.account_id||typeof o.preferred_username=="string"&&o.preferred_username;if(s)return s}catch{}return`token:${t.length>=8?t.slice(-8):t}`}function ow(t){if(process.platform==="darwin")nd("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",od().username,"-w",t],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let e=sd(rd(),".claude",".credentials.json");sw(e,t)}}function sw(t,e){Zb(t,e,{encoding:"utf-8",mode:384})}function pe(t,e){if(t===null||typeof t!="object")return;let n=t.headers;if(n==null)return;if(typeof n.get=="function")return n.get(e)??void 0;if(typeof n=="object"){let o=n,s=o[e]??o[e.toUpperCase()];return typeof s=="string"?s:void 0}}function Et(t){let e=pe(t,"retry-after-ms");if(e!==void 0){let r=Number(e);if(Number.isFinite(r)&&r>=0)return r}let n=pe(t,"retry-after");if(n!==void 0){let r=Number(n);if(Number.isFinite(r)&&r>=0)return Math.round(r*1e3);let o=Date.parse(n);if(!Number.isNaN(o)){let s=o-Date.now();if(s>=0)return s}}}var iw=300*1e3;var aw=864e13;function ld(t){if(!Number.isFinite(t)||t<=0)return;let e=t*1e3;if(!(e>aw))return new Date(e)}function ro(t){if(!("status"in t))return null;let e=t.status;if(e===429){let n=t.message.split("|");if(n.length>=2){let l=ld(parseInt(n[1].trim(),10));if(l!==void 0)return{kind:"oauth-limit",resetsAt:l}}let r=pe(t,"anthropic-ratelimit-unified-representative-claim"),o=pe(t,"anthropic-ratelimit-unified-overage-status"),s=pe(t,"anthropic-ratelimit-unified-status");if(r!==void 0||o!==void 0||s==="rejected"){let l=pe(t,"anthropic-ratelimit-unified-reset");if(l!==void 0){let c=ld(Number(l));if(c!==void 0)return{kind:"oauth-limit",resetsAt:c}}return{kind:"oauth-limit-no-ts"}}if(pe(t,"anthropic-ratelimit-requests-remaining")!==void 0||pe(t,"anthropic-ratelimit-requests-limit")!==void 0||pe(t,"anthropic-ratelimit-requests-reset")!==void 0||pe(t,"anthropic-ratelimit-input-tokens-remaining")!==void 0||pe(t,"anthropic-ratelimit-input-tokens-limit")!==void 0||pe(t,"anthropic-ratelimit-input-tokens-reset")!==void 0||pe(t,"anthropic-ratelimit-output-tokens-remaining")!==void 0||pe(t,"anthropic-ratelimit-output-tokens-limit")!==void 0||pe(t,"anthropic-ratelimit-output-tokens-reset")!==void 0)return{kind:"rate-limit-transient",retryAfterMs:Et(t)};let a=Et(t);return a!==void 0&&a<=iw?{kind:"rate-limit-transient",retryAfterMs:a}:{kind:"oauth-limit-no-ts"}}return e===400&&t.message.includes("invalid_request_error")&&t.message.includes("credit balance")?{kind:"credit-exhausted"}:null}async function cd(t){let{resetsAt:e,signal:n,readToken:r=be}=t,o=r(),s=e.getTime()+3e4;return new Promise(i=>{let a,l=!1,c=p=>{l||(l=!0,a!==void 0&&clearInterval(a),n.removeEventListener("abort",d),i(p))},d=()=>{c("aborted")},u=()=>n.aborted?(c("aborted"),!0):Date.now()>=s?(c("timer"),!0):r()!==o?(c("hot-swap"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),n.addEventListener("abort",d,{once:!0}))})}async function dd(t){let{signal:e,readToken:n=be,retryAfterMs:r}=t,o=n(),s=r!==void 0?Date.now()+r:void 0;return new Promise(i=>{let a,l=!1,c=p=>{l||(l=!0,a!==void 0&&clearInterval(a),e.removeEventListener("abort",d),i(p))},d=()=>{c("aborted")},u=()=>e.aborted?(c("aborted"),!0):n()!==o?(c("hot-swap"),!0):s!==void 0&&Date.now()>=s?(c("timer"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),e.addEventListener("abort",d,{once:!0}))})}var lw=new Set([429,503,529]);function oa(t,e=fetch,n,r){return!t&&!n&&!r?e:async(o,s)=>{let i=await e(o,s);if(r)try{r(i.headers)}catch{}if(lw.has(i.status)){let a=Et({headers:i.headers});if(n)try{n({status:i.status,...a!==void 0?{retryAfterMs:a}:{}})}catch{}if(t){let l={status:i.status,reason:i.status===429?"rate-limit":"overloaded",source:"sdk-fetch"};a!==void 0&&(l.retryAfterMs=a),G(t,{phase:"rate_limit",...a!==void 0?{durationMs:a}:{},metadata:l})}}return i}}var oo=class{items=[];waiter=null;attempts=0;push(e){this.attempts+=1;let n={status:e.status,attempt:this.attempts,...e.retryAfterMs!==void 0?{retryAfterMs:e.retryAfterMs}:{}};this.items.push(n);let r=this.waiter;this.waiter=null,r&&r()}takeAll(){return this.items.length===0?[]:this.items.splice(0,this.items.length)}waitForItem(){return this.items.length>0?Promise.resolve():new Promise(e=>{this.waiter=e})}resetAttempts(){this.attempts=0}};function ud(t){if(t===null)return;let e=Number(t);if(Number.isFinite(e))return Math.min(1,Math.max(0,e))}var cw=Date.UTC(2100,0,1)/1e3;function pd(t){if(t===null)return;let e=Number(t);if(!(!Number.isFinite(e)||e<0||e>cw))return new Date(e*1e3)}function md(t){try{let e=ud(t.get("anthropic-ratelimit-unified-5h-utilization")),n=pd(t.get("anthropic-ratelimit-unified-5h-reset")),r=ud(t.get("anthropic-ratelimit-unified-7d-utilization")),o=pd(t.get("anthropic-ratelimit-unified-7d-reset"));return e===void 0&&r===void 0?void 0:{...e!==void 0?{fiveHourUtilization:e}:{},...n!==void 0?{fiveHourResetsAt:n}:{},...r!==void 0?{sevenDayUtilization:r}:{},...o!==void 0?{sevenDayResetsAt:o}:{},observedAt:new Date}}catch{return}}var fd,dw=new Set;function so(t){return t===void 0?void 0:Math.round(t*100)}function gd(t){let e=fd,n=e===void 0||so(e.fiveHourUtilization)!==so(t.fiveHourUtilization)||so(e.sevenDayUtilization)!==so(t.sevenDayUtilization);if(fd=t,!!n)for(let r of dw)try{r()}catch{}}import{randomUUID as Qh}from"node:crypto";function Ue(t){return t==="bypassPermissions"||t==="autonomous"}N();var uw="1h";function io(t){if(typeof t?.baseUrl=="string"&&t.baseUrl.length>0)return!1;let e=b.AFK_DISABLE_PROMPT_CACHE;if(e===void 0||e.length===0)return!0;let n=e.toLowerCase();return!(n==="1"||n==="true"||n==="yes"||n==="on")}function ao(){let t=b.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":t==="1h"?"1h":uw}function hd(t,e){if(t.length===0)return t;let n=t[t.length-1],r=bd(n,e);return r===n?t:[...t.slice(0,-1),r]}function yd(t,e){if(t.length===0)return t;let n=t[t.length-1],r=pw(n,e);return r===n?t:[...t.slice(0,-1),r]}function pw(t,e){let n=t.content;if(typeof n=="string")return n.length===0?t:{...t,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:e}}]};if(!Array.isArray(n)||n.length===0)return t;let r=n[n.length-1],o=bd(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function bd(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}var lo=["## Plan mode is active","","File and memory write tools (`write_file`, `edit_file`, `memory_update`, `procedure_write`) are refused at the hook layer.","`bash` runs for read-only investigation (git status/log/diff, ls, cat, grep, find \u2014 chained or not); state-mutating bash (file writes, rm, installs, commits, pushes) is refused while planning. The user has asked you to plan, not yet to act \u2014 exit plan mode to make changes.","Treat this turn as planning work.","","Traverse the shape that matches the work \u2014 skip steps the terrain already covers, do not skip steps the terrain hides:",""," unknown field \u2192 ground the current terrain \u2192 gather missing codebase context \u2192"," research missing external context \u2192 reveal chaos / constraints / risks \u2192"," name the failure geometry \u2192 form a candidate plan \u2192 apply adversarial pressure \u2192 embody the final plan","","Reach for these skills (invoke via the `skill` tool) when the cost of skipping exceeds the cost of dispatching:"," - `ground-state` \u2014 survey git, infra, memory before non-trivial work"," - `gather` \u2014 parallel context-gathering for a code area"," - `research` \u2014 parallel external + local context for the current task"," - `devils-advocate` \u2014 generate alternatives and rank them before committing"," - `shadow-verify` \u2014 independently re-derive load-bearing claims","","Do not declare readiness silently. When the plan is ready, state: chosen approach, risks named, and alternatives considered.","","Then, IF the task requires implementation (writing code or files), call the `exit_plan_mode` tool to present your plan. The user picks how to proceed (approve and implement, or keep planning). After calling it, END YOUR TURN \u2014 on approval you will receive a separate instruction to save the plan to a file and implement it. Do NOT use `ask_question` to ask whether the plan is OK; that is exactly what `exit_plan_mode` does \u2014 use `ask_question` only to resolve open requirement questions first. For research / read-only tasks that need no code changes, do NOT call `exit_plan_mode` \u2014 just answer.","","Manual fallbacks remain: the user can exit with `/plan off` (same save-and-implement handoff), and Shift+Tab advances the permission-mode ring without saving or implementing. Keep the plan concrete and complete enough to act on directly."].join(`
|
|
6
6
|
`);function sa(t){return t!=="plan"?null:{type:"text",text:lo}}var co=["## AFK mode is active","","The operator is away from keyboard. Your channel to them is Telegram via the `send_telegram` tool \u2014 not this transcript, which no one is watching live. At the end of each turn, push your terminal state (Done / Blocked / Asking) to Telegram so the operator can review asynchronously.","","Posture \u2014 bounded autonomy, not unchecked action:"," - Proceed autonomously on reversible work. Do not stop to confirm actions you are already authorized to take and can undo (edits, reads, tests, local commits, non-force pushes, installs)."," - At a one-way door \u2014 anything irreversible, externally visible, credential- or payment-touching, or where multiple readings lead to materially different work \u2014 do NOT guess. Push a concise Asking summary to Telegram naming the decision and your recommended default, then stop and end the turn in the Asking state."," - A mechanical gate refuses high-risk and irreversible operations at the hook layer regardless of this text. Treat a gate refusal as a signal to surface the decision to the operator, not an obstacle to work around.","","Communication discipline:"," - Batch updates. Send a Telegram message at terminal state (and at a genuinely blocking fork), not a play-by-play \u2014 the operator gets a push notification for every message."," - Keep pushes short and scannable: what happened, what changed, what (if anything) you need. Never paste raw tool output, logs, secrets, or full file contents into a push.","","Exit: the operator returns and runs `/afk off` (or Shift+Tab) to restore default permissions and terminal-channel interaction."].join(`
|
|
7
7
|
`);function ia(t){return t!=="autonomous"?null:{type:"text",text:co}}function On(t,e=()=>{}){let n=new Set;if(!t)return n;for(let r of t.split(",")){let o=r.trim();if(o){if(!/^-?\d+$/.test(o)){e("[allowlist] Ignoring non-numeric chat ID:",o);continue}n.add(Number(o))}}return n}function wd(t,e){return e.has(t)}function aa(t,e=()=>{}){return async(n,r)=>{let o=n.chat?.id;if(o===void 0||!t.has(o)){e("[allowlist] Rejecting update from chat:",o??"<unknown>");return}await r()}}import{config as v0}from"dotenv";K();N();function wo(){return b.ANTHROPIC_API_KEY||b.CLAUDE_CODE_OAUTH_TOKEN||be()}function fa(){return b.OPENAI_API_KEY||b.CODEX_API_KEY||void 0}function oe(t){let e=X(t);return e==="openai-compatible"||e==="openai-codex"?fa():wo()}N();import{readFileSync as Mw,existsSync as Ow}from"fs";import{join as Dw}from"path";K();N();import{execFile as xw}from"node:child_process";import{promisify as Rw}from"node:util";N();K();N();var K0=Rw(xw);var Iw=/^[A-Za-z0-9_\-./]*$/,$d=64;function Bd(t,e){if(t.length>$d)throw new Error(`Invalid branch prefix from ${e}: length ${t.length} exceeds ${$d}.`);if(!Iw.test(t))throw new Error(`Invalid branch prefix from ${e}: '${t}' \u2014 only [A-Za-z0-9_-./] are allowed.`);if(t.startsWith("-"))throw new Error(`Invalid branch prefix from ${e}: '${t}' \u2014 must not start with '-' (would be parsed by git as a flag).`);return t}function Hd(t,e){if(t.trim().length===0)throw new Error(`Invalid worktree base ref from ${e}: '' \u2014 base ref cannot be empty.`);if(t.startsWith("-"))throw new Error(`Invalid worktree base ref from ${e}: '${t}' \u2014 must not start with '-' (would be parsed by git as a flag).`);if(t.includes("\0"))throw new Error(`Invalid worktree base ref from ${e}: contains a NUL byte.`);if(/\s/.test(t))throw new Error(`Invalid worktree base ref from ${e}: '${t}' \u2014 must not contain whitespace.`)}K();import{existsSync as $n,readdirSync as q0,readFileSync as jd,realpathSync as z0,statSync as J0}from"fs";import{homedir as Kd}from"os";import{join as qe}from"path";var Wd=["claude-code","codex"],Un=new Map,So={"claude-code":{label:"Claude Code",pluginRoots:t=>[qe(t,".claude","plugins")],skillRoots:t=>[qe(t,".claude","skills")],mcpConfigCandidates:t=>[qe(t,".claude","mcp.json"),qe(t,".claude",".mcp.json"),qe(t,".claude","claude-code","mcp.json")],mcpFormat:"json",pluginEnabledState:t=>Pw(t)},codex:{label:"Codex",pluginRoots:t=>[qe(t,".codex","plugins")],skillRoots:t=>[qe(t,".codex","skills")],mcpConfigCandidates:t=>[qe(t,".codex","config.toml")],mcpFormat:"toml",pluginEnabledState:()=>Un}},Q0={"claude-code":So["claude-code"].label,codex:So.codex.label};function ma(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e={};for(let n of Wd){let r=t[n];if(r!==void 0){if(r===!0){e[n]={plugins:!0,skills:!0,mcp:!0};continue}if(r!==!1&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=r;e[n]={plugins:o.plugins===!0,skills:o.skills===!0,mcp:o.mcp===!0}}}}return Object.keys(e).length>0?e:void 0}function ga(){return[Xt(),yo()]}function ha(t=ga()){for(let e of t)if($n(e))try{let n=JSON.parse(jd(e,"utf-8")),r=ma(n.importFrom);if(r!==void 0)return r}catch{}}function ya(t,e=Kd()){let n={pluginRoots:[],skillRoots:[],mcpConfigs:[]};if(!t)return n;for(let r of Wd){let o=t[r];if(!o)continue;let s=So[r];if(o.plugins)for(let i of s.pluginRoots(e))$n(i)&&n.pluginRoots.push({dir:i,binary:r});if(o.skills){let i=`imported:${r}`;for(let a of s.skillRoots(e))$n(a)&&n.skillRoots.push({dir:a,origin:i})}if(o.mcp){let i=Cw(s.mcpConfigCandidates(e));i&&n.mcpConfigs.push({source:i,format:s.mcpFormat})}}return n}function Gd(t,e=Kd()){return So[t].pluginEnabledState(e)}function Cw(t){for(let e of t)if($n(e))return e;return null}function Pw(t){let e=qe(t,".claude","settings.json");if(!$n(e))return Un;let n;try{n=JSON.parse(jd(e,"utf-8"))}catch{return Un}if(!n||typeof n!="object")return Un;let r=n.enabledPlugins;if(!r||typeof r!="object"||Array.isArray(r))return Un;let o=new Map;for(let[s,i]of Object.entries(r))typeof i=="boolean"&&o.set(s,i);return o}var vo;function qd(){if(vo!==void 0)return vo;let t=[Dw(process.cwd(),"afk.config.json"),Xt(),yo()],e=!1;for(let r of t)if(Ow(r))try{let o=Mw(r,"utf-8"),s=JSON.parse(o),i={},a=Xc(s.models);if(typeof s.model=="string"&&s.model.length>0){let c=s.model.toLowerCase();i.model=no(c)?c:s.model}if(typeof s.maxTokens=="number"&&(i.maxTokens=s.maxTokens),typeof s.temperature=="number"&&(i.temperature=s.temperature),typeof s.systemPrompt=="string"&&s.systemPrompt.length>0&&(i.systemPrompt=s.systemPrompt),typeof s.permissionMode=="string"){let c=s.permissionMode;(c==="default"||c==="plan"||c==="autonomous"||c==="bypassPermissions")&&(i.permissionMode=c)}if(s.autoRouting&&typeof s.autoRouting=="object"){let c={};typeof s.autoRouting.interactive=="boolean"&&(c.interactive=s.autoRouting.interactive),typeof s.autoRouting.chat=="boolean"&&(c.chat=s.autoRouting.chat),typeof s.autoRouting.telegram=="boolean"&&(c.telegram=s.autoRouting.telegram),typeof s.autoRouting.daemon=="boolean"&&(c.daemon=s.autoRouting.daemon),i.autoRouting=c}if(s.daemon&&typeof s.daemon=="object"){let c={};typeof s.daemon.task=="string"&&(c.task=s.daemon.task),typeof s.daemon.taskId=="string"&&(c.taskId=s.daemon.taskId);let d=s.daemon.worktreePrune;d&&typeof d=="object"&&(c.worktreePrune={enabled:typeof d.enabled=="boolean"?d.enabled:!0,cron:typeof d.cron=="string"?d.cron:"0 4 * * *",maxAgeDaysClean:typeof d.maxAgeDaysClean=="number"?d.maxAgeDaysClean:14,maxAgeDaysDirty:typeof d.maxAgeDaysDirty=="number"?d.maxAgeDaysDirty:30,scope:typeof d.scope=="string"?d.scope:"all"}),typeof s.daemon.verifyDone=="boolean"&&(c.verifyDone=s.daemon.verifyDone),i.daemon=c}if(s.telegram&&typeof s.telegram=="object"){let c={},d=s.telegram.notify;if(d&&typeof d=="object"){let u={};if((d.mode==="primary"||d.mode==="broadcast"||d.mode==="custom")&&(u.mode=d.mode),typeof d.primaryChatId=="number"&&Number.isFinite(d.primaryChatId)&&(u.primaryChatId=d.primaryChatId),Array.isArray(d.targets)){let p=d.targets.filter(f=>typeof f=="number"&&Number.isFinite(f));p.length>0&&(u.targets=p)}c.notify=u}if(typeof s.telegram.verifyDone=="boolean"&&(c.verifyDone=s.telegram.verifyDone),Array.isArray(s.telegram.tagOnlyChats)){let u=s.telegram.tagOnlyChats.filter(p=>typeof p=="number"&&Number.isFinite(p));u.length>0&&(c.tagOnlyChats=u)}if(s.telegram.chatAliases&&typeof s.telegram.chatAliases=="object"&&!Array.isArray(s.telegram.chatAliases)){let u={};for(let[p,f]of Object.entries(s.telegram.chatAliases))typeof f=="number"&&Number.isFinite(f)&&f!==0&&(u[p]=f);Object.keys(u).length>0&&(c.chatAliases=u)}i.telegram=c}if(s.updatePolicy&&["notify","auto","off"].includes(s.updatePolicy)&&(i.updatePolicy=s.updatePolicy),s.theme&&["dark","light","auto"].includes(s.theme)&&(i.theme=s.theme),typeof s.autoResumeOnUsageLimit=="boolean"&&(i.autoResumeOnUsageLimit=s.autoResumeOnUsageLimit),typeof s.enforceDoneEvidence=="boolean"&&(i.enforceDoneEvidence=s.enforceDoneEvidence),typeof s.bgSummaries=="boolean"&&(i.bgSummaries=s.bgSummaries),typeof s.maxSummaryCallsPerSession=="number"&&(i.maxSummaryCallsPerSession=Math.min(500,Math.max(1,s.maxSummaryCallsPerSession))),s.hooks!==null&&typeof s.hooks=="object"&&!Array.isArray(s.hooks)&&(i.hooks=s.hooks),typeof s.enableShellHooks=="boolean"&&(i.enableShellHooks=s.enableShellHooks),typeof s.enablePluginHooks=="boolean"&&(i.enablePluginHooks=s.enablePluginHooks),ga().includes(r)){let c=ma(s.importFrom);c!==void 0&&(i.importFrom=c)}if(s.interactive&&typeof s.interactive=="object"){let c={};typeof s.interactive.worktreeAutoname=="boolean"&&(c.worktreeAutoname=s.interactive.worktreeAutoname),typeof s.interactive.worktreeBranchPrefix=="string"&&(c.worktreeBranchPrefix=Bd(s.interactive.worktreeBranchPrefix,`${r}#/interactive/worktreeBranchPrefix`)),typeof s.interactive.worktreeBase=="string"&&s.interactive.worktreeBase.trim().length>0&&(Hd(s.interactive.worktreeBase,`${r}#/interactive/worktreeBase`),c.worktreeBase=s.interactive.worktreeBase),typeof s.interactive.suggestGhost=="boolean"&&(c.suggestGhost=s.interactive.suggestGhost),(s.interactive.thinkingUi==="summary"||s.interactive.thinkingUi==="live"||s.interactive.thinkingUi==="digest"||s.interactive.thinkingUi==="off")&&(c.thinkingUi=s.interactive.thinkingUi),Object.keys(c).length>0&&(i.interactive=c)}let l={config:i,sourcePath:r,modelsPartial:a};return e||(vo=l),l}catch(o){console.error(`Warning: Failed to parse ${r}:`,o),e=!0}let n={config:{},sourcePath:void 0,modelsPartial:{}};return e||(vo=n),n}K();function ba(){return qd().config.telegram??{}}N();function Lw(t,e){return e!==void 0&&Number.isFinite(e)&&e!==0?e:t.find(r=>r>0)??t[0]}function Nw(t,e={}){let n=[...t],r=e.mode??"primary";if(r==="broadcast")return n;if(r==="custom"){let s=(e.targets??[]).filter(i=>typeof i=="number"&&Number.isFinite(i)&&i!==0);if(s.length>0)return[...new Set(s)]}let o=Lw(n,e.primaryChatId);return o!==void 0?[o]:[]}function zd(t,e={}){if(typeof t=="number")return!Number.isFinite(t)||t===0?{ok:!1,reason:"invalid",message:`Invalid chat id: ${t}`}:{ok:!0,id:t};let n=t.trim();if(n.length===0)return{ok:!1,reason:"invalid",message:"Invalid chat: empty string"};let r=Jd(n);if(r!==void 0)return{ok:!0,id:r};let o=Object.keys(e),s=Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0;if(s!==void 0&&Number.isFinite(s)&&s!==0)return{ok:!0,id:s};let i=o.length>0?`Available aliases: ${o.join(", ")}.`:"No chat aliases are configured (set telegram.chatAliases in afk.config.json).";return{ok:!1,reason:"unknown-alias",message:`Unknown chat alias "${n}". ${i}`}}function Jd(t){if(!t)return;let e=t.trim();if(!/^-?\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)&&n!==0?n:void 0}function Uw(t){if(!t)return;let e=t.trim().toLowerCase();return e==="primary"||e==="broadcast"||e==="custom"?e:void 0}function $w(){let t=ba().notify??{},e=t.mode??Uw(b.AFK_TELEGRAM_NOTIFY_MODE),n=t.primaryChatId??Jd(b.AFK_TELEGRAM_PRIMARY_CHAT_ID);return{...e!==void 0?{mode:e}:{},...n!==void 0?{primaryChatId:n}:{},...t.targets!==void 0?{targets:t.targets}:{}}}function ko(){let t=On(b.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return Nw(t,$w())}function Yd(){return ba().chatAliases??{}}function ve(t,e=4096){if(t.length<=e)return[t];let n=[],r=t;for(;r.length>0;){if(r.length<=e){n.push(r);break}let o=e,s=r.lastIndexOf(`
|
package/dist/telegram.mjs
CHANGED
|
@@ -857,7 +857,7 @@ Remedy: these paths are outside the fork's granted read roots. Re-dispatch with
|
|
|
857
857
|
|
|
858
858
|
`).trim()}function wO(t){return(t?.textContent??"").replace(/\s+/g," ").trim().length}async function Db(t,e){let{JSDOM:n,Readability:r,turndown:o}=await bO(),i=new n(t,{url:e}).window.document,a=(i.title??"").trim(),l=(()=>{try{let p=i.cloneNode(!0);return new r(p).parse()}catch{return null}})();if(l&&typeof l.content=="string"&&l.content.trim().length>0){let p=Ob(o.turndown(l.content)),f=(l.title??"").trim()||a,m=typeof l.length=="number"&&l.length>0?l.length:(l.textContent??"").replace(/\s+/g," ").trim().length;return{title:f,markdown:p,textLength:m,usedFallback:!1}}let c=i.body,d=c?.innerHTML??"",u=Ob(o.turndown(d));return{title:a,markdown:u,textLength:wO(c),usedFallback:!0}}var vu,Fb=b(()=>{"use strict";vu=null});function vO(t,e){return new Promise((n,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(e?.reason??new Error("aborted"))},s=setTimeout(()=>{e?.removeEventListener("abort",o),n()},t);e?.addEventListener("abort",o,{once:!0})})}function Lb(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function kO(t,e){let n=t.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,e)}async function ua(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??vO,l=n.signal??void 0,c;for(let d=0;d<=o;d++){if(l?.aborted)throw l.reason??new Error("aborted");try{let u=await t(e,n);if(!SO.has(u.status)||d===o)return u;let p=kO(u,i)??Lb(d,s,i);U("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,l)}catch(u){if(l?.aborted||(c=u,d===o))throw u;let p=Lb(d,s,i);U("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var SO,ku=b(()=>{"use strict";fe();SO=new Set([429,502,503,504])});import{readFileSync as _O}from"node:fs";import{join as AO}from"path";function EO(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Nb(t,e){return EO(e).test(t)}function RO(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(TO.has(e))return!0;if(xO.has(e))return!1}return!1}function $b(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function CO(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function Ub(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Fc(e),e}function IO(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function PO(t){try{return _O(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function MO(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=Ub(e.defaultProfile)),n}function Bb(t){let e=t?.env??_,n=t?.readFileSync??PO,r=t?.surface??e.AGENT_SURFACE,o=RO(e.AFK_BROWSER_HEADLESS,r),s=$b(e.AFK_BROWSER_ALLOWED_DOMAINS),i=$b(e.AFK_BROWSER_BLOCKED_DOMAINS),a=IO(e.AFK_BROWSER_DOM_SNAPSHOTS),l=CO(e.AFK_BROWSER_BACKEND),c=Ub(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():AO(St(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(h){throw new Error(`Failed to parse browser config at ${p}: ${String(h)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=MO(d,m);return g.configPath=p,g}function pa(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(Nb(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Nb(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var TO,xO,fa=b(()=>{"use strict";W();z();TO=new Set(["daemon","subagent","telegram","afk"]),xO=new Set(["repl","interactive","cli"])});import{existsSync as OO,readFileSync as DO}from"node:fs";import{createRequire as FO}from"node:module";import{dirname as LO,join as NO}from"node:path";function Wb(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<UO&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function Ie(t){let e=Wb(t);return jb.some(n=>e.includes(n))}function BO(){try{let e=FO(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(DO(e,"utf8"));if(typeof n!="object"||n===null)return;let r=n.bin,o=typeof r=="string"?r:typeof r=="object"&&r!==null?r.playwright:void 0;if(typeof o!="string"||o.length===0)return;let s=NO(LO(e),o);return OO(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function Ao(){return Hb??=BO()??$O,Hb}function _u(t){return t.includes("install chromium")}function Xe(t,e){let n=Wb(t),r=e?.latched===!0?` ${HO}`:"";if(n.includes("Executable doesn't exist")){let o="";return e?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":e?.headless===!1&&(o=" This launch was headed, which needs the full `chromium-*` build \u2014 the headless shell alone does not satisfy it."),`browser tools require the Playwright chromium binary. Install via: ${Ao()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${Ao()}). Or pick a different tool.${r}`}function Au(t,e,n=!1){if(!Ie(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
859
859
|
|
|
860
|
-
${Xe(t,{headless:e,latched:n})}`,{cause:t})}var jb,$O,UO,Hb,HO,Eu=b(()=>{"use strict";jb=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],$O="pnpm exec playwright install chromium",UO=4;HO="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Rn from"node:fs";import ma from"node:path";import{randomBytes as jO}from"node:crypto";import{chromium as WO}from"playwright";function KO(){try{return"5.82.2"}catch{}try{let t=ma.resolve(import.meta.dirname,"../../../package.json"),e=Rn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var GO,ga,Kb=b(()=>{"use strict";Eu();z();fe();GO=KO(),ga=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=WO.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Au(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await i.content(),c=i.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${GO}`}}loadStorageState(e){let n=Lc(e);try{if(!Rn.existsSync(n))return;let r=JSON.parse(Rn.readFileSync(n,"utf8"));return U("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){U("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Lc(e);if(!Rn.existsSync(r))return;let o=await n.storageState(),s=ma.join(ma.dirname(r),`.${ma.basename(r)}.${process.pid}.${jO(4).toString("hex")}.tmp`);Rn.writeFileSync(s,JSON.stringify(o),{mode:384}),Rn.chmodSync(s,384),Rn.renameSync(s,r),U("[browser/vault] saved session",{profile:e,file:r})}catch(r){U("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as qO}from"crypto";function Gb(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&zO.test(t.label))}function qb(t){return qO("sha256").update(t,"utf8").digest("hex").slice(0,8)}function zb(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var zO,ha=b(()=>{"use strict";zO=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as JO}from"node:crypto";function VO(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function YO(t,e,n){return`el_${JO("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function XO(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Jb(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Yb(t,e){let n=t.role??"",r=t.name??"";Vb.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Yb(s,e)}async function QO(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},Xb).catch(()=>[])}async function ZO(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},Xb).catch(()=>[])}function e0(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function ya(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=e0(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=QO(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,w=!1;u!==null?(h=[],Yb(u,h)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,h=(await ZO(t)).filter(N=>Vb.has(N.role??"")));let v=new Map;for(let I of p){let N=Jb(I.name),j=v.get(N);(!j||j.bbox.w===0&&I.bbox.w>0)&&v.set(N,I)}let E=h.map(I=>({ax:I,dom:v.get(Jb(I.name??""))})),k=r?E:E.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);k.sort((I,N)=>{let j=I.dom?.bbox.y??0,C=N.dom?.bbox.y??0;if(j!==C)return j-C;let $=I.dom?.bbox.x??0,L=N.dom?.bbox.x??0;return $-L}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=k.slice(0,n).map((I,N)=>{let j=I.ax.role??"generic",C=I.ax.name??"",$=YO(j,C,N),L=I.dom?.bbox??{x:0,y:0,w:0,h:0},P=I.dom?.type??null,O=null;I.ax.value!==void 0&&I.ax.value!==null&&(O=String(I.ax.value)),I.ax.checked!==void 0&&(O=String(I.ax.checked)),Gb({role:j,kind:P})&&(O="[redacted]");let H={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(H.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(H.selected=I.ax.selected),I.ax.expanded!==void 0&&(H.expanded=I.ax.expanded);let F;I.dom?.testId?F=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(F=`#${I.dom.id}`);let B={id:$,role:j,label:VO(C),kind:P,value:O,state:H,bbox:L};return F!==void 0&&(B.selector=F),B}),x="idle";try{let I=await t.evaluate(()=>document.readyState);I==="loading"?x="loading":I==="interactive"?x="navigating":x="idle"}catch{x="navigating"}x!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let S=XO(f),R=`obs_${e.observationCounter.toString(36)}`,M=new Date().toISOString();return{observationId:R,url:m,title:g,textSummary:S,interactive:T,status:{httpStatus:e.httpStatus??null,loadingState:x,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:M}}var Vb,Xb,Qb=b(()=>{"use strict";ha();Vb=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Xb="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Zb(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Tu(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Zb(t,s)))).filter(o=>o!==null)}async function t0(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function xu(t,e,n){switch(e.kind){case"element_id":return n0(t,e,n);case"selector":return r0(t,e);case"semantic":return o0(t,e)}}async function n0(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Tu(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function r0(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Tu(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function o0(t,e){return e.role!==void 0?s0(t,e.text,e.role):i0(t,e.text,e)}async function s0(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Tu(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function i0(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:s,count:l});let u=await t0(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let h=p[g];if(h===void 0)continue;let w=await Zb(h.locator,h.index);if(w!==null){let v=`${w.role}:${w.label}:${g}`,E=0;for(let k=0;k<v.length;k++)E=E*31+v.charCodeAt(k)>>>0;f.push({...w,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var ew=b(()=>{"use strict"});async function Ru(t,e,n,r){let o=t.url();if(o===n)return null;let s=pa(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var tw=b(()=>{"use strict";fa()});import{randomBytes as a0}from"crypto";import{mkdir as l0,stat as c0,writeFile as d0}from"fs/promises";import{join as Cu}from"path";import{gzip as u0}from"zlib";import{promisify as p0}from"util";function f0(t){return Cu(Bs(t),"browser")}function m0(t){return Cu(f0(t),"screenshots")}function g0(){return new Date().toISOString().replace(/[:.]/g,"-")}function h0(){return a0(3).toString("hex")}async function Iu(t,e,n){if(e.length>nw)throw new Error(`writeScreenshotSidecar: buffer exceeds ${nw} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=m0(t);await l0(r,{recursive:!0});let o=`${g0()}-${h0()}-${n}.png`,s=Cu(r,o);await d0(s,e);let{size:i}=await c0(s);return{path:s,bytes:i}}var zY,nw,rw=b(()=>{"use strict";z();ha();zY=p0(u0);nw=5*1024*1024});var sw={};Rc(sw,{PlaywrightProvider:()=>Pu});function ow(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var Pu,iw=b(()=>{"use strict";Kb();Qb();ew();fa();tw();rw();Pu=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new ga(e)}async open(e){let n=pa(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await Ru(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await ya(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await ya(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await xu(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${ow(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){c=h}else c=g}let u=await Ru(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await ya(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await xu(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${ow(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await Iu(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Iu(n,o,r);return s}catch{return null}}}});var In={};Rc(In,{__resetBrowserRegistryForTests:()=>v0,browserProviderActive:()=>w0,closeBrowserProvider:()=>Mu,getBrowserProvider:()=>b0,peekBrowserProvider:()=>S0});function aw(){Promise.resolve(Mu()).then(()=>{process.exit(130)})}function lw(){Promise.resolve(Mu()).then(()=>{process.exit(143)})}function cw(){ht=null}function y0(){ba||(process.on("SIGINT",aw),process.on("SIGTERM",lw),process.on("exit",cw),ba=!0)}function dw(){ba&&(process.removeListener("SIGINT",aw),process.removeListener("SIGTERM",lw),process.removeListener("exit",cw),ba=!1)}async function b0(t){return ht!==null?ht:(Cn!==null||(Cn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(iw(),sw)),n=Bb(t),r=new e(n);return y0(),ht=r,Cn=null,r})()),Cn)}async function Mu(){if(ht===null)return;let t=ht;ht=null,Cn=null,dw(),await t.shutdown()}function w0(){return ht!==null}function S0(){return ht}function v0(){ht=null,Cn=null,dw()}var ht,Cn,ba,Pn=b(()=>{"use strict";fa();ht=null,Cn=null,ba=!1});async function uw(t,e){try{return await Db(t,e)}catch(n){return U("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function x0(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Pn(),In));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function pw(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??x0,o=null,s=t,i=null,a=null;try{let c=await ua(n,t,{headers:T0,redirect:"follow",signal:e.signal});i=c.status,s=c.url||t;let d=c.headers.get("content-type")??"";if(c.ok){if(E0.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await c.text();if(A0.test(d)&&!_0.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};if(o=await uw(u,s),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(c){if(e.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<200)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let c=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal}),d=await uw(c.html,c.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(e.signal.aborted)throw c;if(o===null){let d=c instanceof Error?c.message:String(c),u=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${t}: fetch failed (${u}) and render failed (${d}).`);throw p.cause=c,p}}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 ${t} (HTTP ${i??"error"}).`)}var _0,A0,E0,T0,fw=b(()=>{"use strict";Fb();ku();fe();_0=/(text\/html|application\/xhtml\+xml)/i,A0=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,E0=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,T0={"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 I0(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(R0,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),C0),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let d=await s.text(),u=ir(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}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 mw(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?I0({apiKey:t.exaApiKey,fetchFn:t.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function gw(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
860
|
+
${Xe(t,{headless:e,latched:n})}`,{cause:t})}var jb,$O,UO,Hb,HO,Eu=b(()=>{"use strict";jb=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],$O="pnpm exec playwright install chromium",UO=4;HO="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Rn from"node:fs";import ma from"node:path";import{randomBytes as jO}from"node:crypto";import{chromium as WO}from"playwright";function KO(){try{return"5.82.3"}catch{}try{let t=ma.resolve(import.meta.dirname,"../../../package.json"),e=Rn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var GO,ga,Kb=b(()=>{"use strict";Eu();z();fe();GO=KO(),ga=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=WO.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Au(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await i.content(),c=i.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${GO}`}}loadStorageState(e){let n=Lc(e);try{if(!Rn.existsSync(n))return;let r=JSON.parse(Rn.readFileSync(n,"utf8"));return U("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){U("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Lc(e);if(!Rn.existsSync(r))return;let o=await n.storageState(),s=ma.join(ma.dirname(r),`.${ma.basename(r)}.${process.pid}.${jO(4).toString("hex")}.tmp`);Rn.writeFileSync(s,JSON.stringify(o),{mode:384}),Rn.chmodSync(s,384),Rn.renameSync(s,r),U("[browser/vault] saved session",{profile:e,file:r})}catch(r){U("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as qO}from"crypto";function Gb(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&zO.test(t.label))}function qb(t){return qO("sha256").update(t,"utf8").digest("hex").slice(0,8)}function zb(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var zO,ha=b(()=>{"use strict";zO=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as JO}from"node:crypto";function VO(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function YO(t,e,n){return`el_${JO("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function XO(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Jb(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Yb(t,e){let n=t.role??"",r=t.name??"";Vb.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Yb(s,e)}async function QO(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},Xb).catch(()=>[])}async function ZO(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},Xb).catch(()=>[])}function e0(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function ya(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=e0(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=QO(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,w=!1;u!==null?(h=[],Yb(u,h)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,h=(await ZO(t)).filter(N=>Vb.has(N.role??"")));let v=new Map;for(let I of p){let N=Jb(I.name),j=v.get(N);(!j||j.bbox.w===0&&I.bbox.w>0)&&v.set(N,I)}let E=h.map(I=>({ax:I,dom:v.get(Jb(I.name??""))})),k=r?E:E.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);k.sort((I,N)=>{let j=I.dom?.bbox.y??0,C=N.dom?.bbox.y??0;if(j!==C)return j-C;let $=I.dom?.bbox.x??0,L=N.dom?.bbox.x??0;return $-L}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=k.slice(0,n).map((I,N)=>{let j=I.ax.role??"generic",C=I.ax.name??"",$=YO(j,C,N),L=I.dom?.bbox??{x:0,y:0,w:0,h:0},P=I.dom?.type??null,O=null;I.ax.value!==void 0&&I.ax.value!==null&&(O=String(I.ax.value)),I.ax.checked!==void 0&&(O=String(I.ax.checked)),Gb({role:j,kind:P})&&(O="[redacted]");let H={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(H.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(H.selected=I.ax.selected),I.ax.expanded!==void 0&&(H.expanded=I.ax.expanded);let F;I.dom?.testId?F=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(F=`#${I.dom.id}`);let B={id:$,role:j,label:VO(C),kind:P,value:O,state:H,bbox:L};return F!==void 0&&(B.selector=F),B}),x="idle";try{let I=await t.evaluate(()=>document.readyState);I==="loading"?x="loading":I==="interactive"?x="navigating":x="idle"}catch{x="navigating"}x!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let S=XO(f),R=`obs_${e.observationCounter.toString(36)}`,M=new Date().toISOString();return{observationId:R,url:m,title:g,textSummary:S,interactive:T,status:{httpStatus:e.httpStatus??null,loadingState:x,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:M}}var Vb,Xb,Qb=b(()=>{"use strict";ha();Vb=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Xb="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Zb(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Tu(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Zb(t,s)))).filter(o=>o!==null)}async function t0(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function xu(t,e,n){switch(e.kind){case"element_id":return n0(t,e,n);case"selector":return r0(t,e);case"semantic":return o0(t,e)}}async function n0(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Tu(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function r0(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Tu(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function o0(t,e){return e.role!==void 0?s0(t,e.text,e.role):i0(t,e.text,e)}async function s0(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Tu(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function i0(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:s,count:l});let u=await t0(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let h=p[g];if(h===void 0)continue;let w=await Zb(h.locator,h.index);if(w!==null){let v=`${w.role}:${w.label}:${g}`,E=0;for(let k=0;k<v.length;k++)E=E*31+v.charCodeAt(k)>>>0;f.push({...w,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var ew=b(()=>{"use strict"});async function Ru(t,e,n,r){let o=t.url();if(o===n)return null;let s=pa(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var tw=b(()=>{"use strict";fa()});import{randomBytes as a0}from"crypto";import{mkdir as l0,stat as c0,writeFile as d0}from"fs/promises";import{join as Cu}from"path";import{gzip as u0}from"zlib";import{promisify as p0}from"util";function f0(t){return Cu(Bs(t),"browser")}function m0(t){return Cu(f0(t),"screenshots")}function g0(){return new Date().toISOString().replace(/[:.]/g,"-")}function h0(){return a0(3).toString("hex")}async function Iu(t,e,n){if(e.length>nw)throw new Error(`writeScreenshotSidecar: buffer exceeds ${nw} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=m0(t);await l0(r,{recursive:!0});let o=`${g0()}-${h0()}-${n}.png`,s=Cu(r,o);await d0(s,e);let{size:i}=await c0(s);return{path:s,bytes:i}}var zY,nw,rw=b(()=>{"use strict";z();ha();zY=p0(u0);nw=5*1024*1024});var sw={};Rc(sw,{PlaywrightProvider:()=>Pu});function ow(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var Pu,iw=b(()=>{"use strict";Kb();Qb();ew();fa();tw();rw();Pu=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new ga(e)}async open(e){let n=pa(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await Ru(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await ya(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await ya(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await xu(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${ow(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){c=h}else c=g}let u=await Ru(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await ya(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await xu(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${ow(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await Iu(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Iu(n,o,r);return s}catch{return null}}}});var In={};Rc(In,{__resetBrowserRegistryForTests:()=>v0,browserProviderActive:()=>w0,closeBrowserProvider:()=>Mu,getBrowserProvider:()=>b0,peekBrowserProvider:()=>S0});function aw(){Promise.resolve(Mu()).then(()=>{process.exit(130)})}function lw(){Promise.resolve(Mu()).then(()=>{process.exit(143)})}function cw(){ht=null}function y0(){ba||(process.on("SIGINT",aw),process.on("SIGTERM",lw),process.on("exit",cw),ba=!0)}function dw(){ba&&(process.removeListener("SIGINT",aw),process.removeListener("SIGTERM",lw),process.removeListener("exit",cw),ba=!1)}async function b0(t){return ht!==null?ht:(Cn!==null||(Cn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(iw(),sw)),n=Bb(t),r=new e(n);return y0(),ht=r,Cn=null,r})()),Cn)}async function Mu(){if(ht===null)return;let t=ht;ht=null,Cn=null,dw(),await t.shutdown()}function w0(){return ht!==null}function S0(){return ht}function v0(){ht=null,Cn=null,dw()}var ht,Cn,ba,Pn=b(()=>{"use strict";fa();ht=null,Cn=null,ba=!1});async function uw(t,e){try{return await Db(t,e)}catch(n){return U("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function x0(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Pn(),In));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function pw(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??x0,o=null,s=t,i=null,a=null;try{let c=await ua(n,t,{headers:T0,redirect:"follow",signal:e.signal});i=c.status,s=c.url||t;let d=c.headers.get("content-type")??"";if(c.ok){if(E0.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await c.text();if(A0.test(d)&&!_0.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};if(o=await uw(u,s),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(c){if(e.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<200)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let c=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal}),d=await uw(c.html,c.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(e.signal.aborted)throw c;if(o===null){let d=c instanceof Error?c.message:String(c),u=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${t}: fetch failed (${u}) and render failed (${d}).`);throw p.cause=c,p}}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 ${t} (HTTP ${i??"error"}).`)}var _0,A0,E0,T0,fw=b(()=>{"use strict";Fb();ku();fe();_0=/(text\/html|application\/xhtml\+xml)/i,A0=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,E0=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,T0={"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 I0(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(R0,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),C0),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let d=await s.text(),u=ir(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}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 mw(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?I0({apiKey:t.exaApiKey,fetchFn:t.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function gw(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
861
861
|
|
|
862
862
|
(no results)`;let n=[`# Search results for "${t}"`,""];return e.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
|
|
863
863
|
`).trimEnd()}var R0,C0,hw=b(()=>{"use strict";hn();R0="https://api.exa.ai/search",C0=10});function wa(t){if(t instanceof Error&&t.name==="TimeoutError")return"timeout";let e=t instanceof Error?t.message:String(t);return/Timeout\s+\d+\s*ms exceeded/i.test(e)?"timeout":void 0}var Mn=b(()=>{"use strict";Eu()});function L0(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t,n=e.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof e.query!="string"||e.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=e.query}else{if(typeof e.url!="string"||e.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let l;try{l=new URL(e.url)}catch{return{error:`Invalid input: "${e.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=P0;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(e.timeout_ms,M0)}let a=O0;if(e.max_bytes!==void 0){if(typeof e.max_bytes!="number"||!Number.isFinite(e.max_bytes)||e.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(e.max_bytes,D0)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Ou(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:Tt(t,e),truncated:!0}}function N0(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env;return async(r,o)=>{if(typeof e!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=L0(r);if("error"in s)return{content:s.error,isError:!0};if(o.aborted){let d=o.reason;return{content:`web_scrape aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let i=new AbortController,a=()=>{i.abort(o.reason)},l,c=()=>{let d=i.signal.reason;return d instanceof Error?d.message:String(d??"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 u;try{u=await ua(e,s.url,{method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:i.signal})}catch(m){return i.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape network error: ${m instanceof Error?m.message:String(m)}`,isError:!0}}if(!u.ok)return{content:`web_scrape HTTP ${u.status} ${u.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let p;try{p=await u.text()}catch(m){return{content:`web_scrape read error: ${m instanceof Error?m.message:String(m)}`,isError:!0}}let f=Ou(p,s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}if(s.mode==="markdown")try{let u=await pw(s.url,{fetchFn:e,renderFn:t.renderFn,timeoutMs:s.timeoutMs,signal:i.signal});if(u.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0};let p=Ou(u.markdown,s.maxBytes);return{content:p.content,...p.truncated?{truncated:!0}:{}}}catch(u){if(i.signal.aborted)return{content:`web_scrape aborted: ${c()}`,isError:!0};let p=u instanceof Error?u.message:String(u),f=Ie(u)&&!_u(p)?` (the render fallback needs the optional Playwright browser \u2014 run \`${Ao()}\`)`:"";return{content:`web_scrape markdown error: ${p}${f}`,isError:!0}}let d=mw({exaApiKey:n.EXA_API_KEY,fetchFn:e});if("error"in d)return{content:d.error,isError:!0};try{let u=await d.search(s.query,{limit:F0,timeoutMs:s.timeoutMs,signal:i.signal}),p=Ou(gw(s.query,u),s.maxBytes);return{content:p.content,...p.truncated?{truncated:!0}:{}}}catch(u){return i.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape search error (${d.name}): ${u instanceof Error?u.message:String(u)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),o.removeEventListener("abort",a)}}}var P0,M0,O0,D0,F0,yw,bw=b(()=>{"use strict";fw();hw();ku();cr();Mn();P0=3e4,M0=12e4,O0=1e5,D0=1e6,F0=10;yw=N0()});import{existsSync as Sw,mkdirSync as $0,readFileSync as U0,renameSync as B0,unlinkSync as H0,writeFileSync as j0}from"node:fs";import{dirname as ww,join as W0}from"node:path";import{randomBytes as K0}from"node:crypto";function fr(t){let e=t??Mc();if(!Sw(e))return[];try{let n=U0(e,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);return console.error(`[schedule-store] failed to parse ${e}: ${r}`),[]}}function Sa(t,e){let n=e??Mc();$0(ww(n),{recursive:!0});let r=W0(ww(n),`.schedules.json.${process.pid}.${K0(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{j0(r,o,"utf-8"),B0(r,n)}catch(s){try{Sw(r)&&H0(r)}catch{}throw s}}function vw(t,e){let n=fr(e),r=n.map(l=>l.id),o=G0(t.name),s=q0(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),Sa(n,e),a}function kw(t,e){let n=fr(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(Sa(o,e),!0)}function _w(t,e){return fr(e).find(n=>n.id===t)}function G0(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function q0(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}var Aw=b(()=>{"use strict";z()});import{existsSync as z0,readFileSync as J0}from"node:fs";import{join as V0}from"node:path";async function Eo(t,e,n){let r;try{let o=V0(Em("default"),"port");if(!z0(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let s=J0(o,"utf-8").trim();if(r=parseInt(s,10),Number.isNaN(r))return{synced:!1,detail:"daemon-not-detected (invalid port file)"}}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let o=await fetch(`http://localhost:${r}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return o.ok?{synced:!0,detail:"synced"}:t==="POST"&&o.status===409?{synced:!0,detail:"already-registered"}:t==="DELETE"&&o.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${o.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}var Du,Ew=b(()=>{"use strict";z();Du="Change saved to schedules.json, but a running daemon (if any) did not pick it up \u2014 it will apply on the next daemon (re)start."});import{existsSync as Y0}from"node:fs";import{readFile as X0}from"node:fs/promises";var Tw,xw,Rw,Cw,Iw=b(()=>{"use strict";Aw();z();Ew();Tw=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;if(typeof n.name!="string"||!n.name)return{content:"Invalid input: name required",isError:!0};if(typeof n.command!="string"||!n.command)return{content:"Invalid input: command required",isError:!0};if(typeof n.cron!="string"||!n.cron)return{content:"Invalid input: cron required",isError:!0};let r=n.cron.trim().split(/\s+/);if(r.length!==5&&r.length!==6)return{content:"Invalid input: cron must be a 5 or 6-field expression",isError:!0};let o=n.notifyChat;if(o!==void 0&&typeof o!="number"&&typeof o!="string")return{content:"Invalid input: notifyChat must be a number (chat id) or string (chat id or alias name)",isError:!0};let s=vw({name:n.name,command:n.command,cron:n.cron,trigger:n.trigger??"cron",notifyOn:n.notifyOn,...o!==void 0?{notifyChat:o}:{},enabled:typeof n.enabled=="boolean"?n.enabled:!0}),i=s.enabled?await Eo("POST","/tasks",{taskId:s.id,command:s.command,cron:s.cron,trigger:s.trigger,notifyOn:s.notifyOn,...s.notifyChat!==void 0?{notifyChat:s.notifyChat}:{}}):await Eo("DELETE",`/tasks/${s.id}`);return{content:JSON.stringify({id:s.id,name:s.name,cron:s.cron,enabled:s.enabled,daemonSynced:i.synced,syncDetail:i.detail,...i.synced?{}:{syncNote:Du}})}},xw=async(t,e)=>{let n=fr();return{content:JSON.stringify(n.map(r=>({id:r.id,name:r.name,cron:r.cron,trigger:r.trigger,enabled:r.enabled,notifyOn:r.notifyOn})))}},Rw=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;if(typeof n.taskId!="string"||!n.taskId)return{content:"Invalid input: taskId required",isError:!0};let r=n.taskId,o=typeof n.limit=="number"?Math.min(Math.max(1,n.limit),50):10,s=Os();if(!Y0(s))return{content:JSON.stringify([])};let i;try{let c=await X0(s);i=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=i.split(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-afk",
|
|
3
|
-
"version": "5.82.
|
|
3
|
+
"version": "5.82.3",
|
|
4
4
|
"description": "Open-source coding-agent harness you can actually change — own the loop (prompts, gates, routing, skills, terminal states), use any model, run long tasks while you're away.",
|
|
5
5
|
"main": "dist/index.mjs",
|
|
6
6
|
"types": "dist/index.d.ts",
|