agent-afk 5.176.0 → 5.176.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var Zx=Object.defineProperty;var re=(t,e)=>()=>(t&&(e=t(t=0)),e);var As=(t,e)=>{for(var n in e)Zx(t,n,{get:e[n],enumerable:!0})};function xr(t){return Rr.find(e=>e.name===t)}function xs(t){return process.env[t]!==void 0}var Kf=re(()=>{"use strict";C()});var Rr,Gf,y,C=re(()=>{"use strict";Kf();Rr=[{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_CONCURRENT_SAFE_TOOL_CALLS",description:"Maximum concurrency-safe tool calls run simultaneously within one dispatcher batch. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"4",category:"model"},{name:"AFK_MAX_CONCURRENT_SUBAGENT_CALLS",description:"Maximum subagent calls run simultaneously from one compose/DAG layer or skill wave. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"2",category:"model"},{name:"AFK_MAX_CONCURRENT_BACKGROUND_JOBS",description:"Maximum background subagent jobs running simultaneously in one registry. Default 10; accepted range 1-64; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"10",example:"5",category:"model"},{name:"AFK_MAX_NESTING_DEPTH",description:"Maximum sub-agent/skill nesting depth; 0 disables nested delegation entirely (the agent, skill, AND compose tools all refuse). A top-level session is depth 0, so the default 3 permits three generations of forked descendants (depth 1 \u2192 2 \u2192 3) and refuses the agent and skill tools at depth 3. Resolved once at the root of each session and propagated down through child AgentConfig, so descendants inherit the root value rather than re-reading the environment. Raise with care: depth is a fan-out exponent (a width-N wave at depth D reaches ~N^D concurrent children), so values above 4 invite provider rate-limit (429) cascades. Accepted range 0-6; unset, empty, unparseable, negative, or out-of-range input falls back to the default. An explicit programmatic maxDepth (SubagentExecutorContext / SkillExecutorContext) still wins.",type:"number",required:!1,default:"3",example:"2",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. When unset, falls back to the model output ceiling (AFK's own per-model limit, 64k\u2013128k \u2014 NOT a small provider default), so every request advertises the full ceiling by default. An over-ceiling value is clamped down with a warning.",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-ROUND time-to-first-token budget (ms) for the anthropic-direct streaming loop. Bounds how long a round may stall BEFORE its first streamed CONTENT token (a text/thinking delta or tool_use); the connection-level message_start and keep-alive pings do NOT count. Once a content token streams, the timer is cleared and the rest of the response is governed instead by the progress-aware AFK_MODEL_STALL_TIMEOUT_MS window, so a normal slow call (below the bound) and any actively-streaming extended-thinking response are never aborted. The budget is divided into 3 shorter first-byte ATTEMPTS (each ~2/3 of this value, so the worst-case wall time per round is unchanged from the previous 2-attempt regime while a transient stall gets 3 chances instead of 2). NOTE: a request whose FIRST token takes longer than the per-attempt bound \u2014 e.g. a very large opus_1m prefill \u2014 is aborted and re-driven, then surfaces as an error once the budget is spent (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), i.e. 3 \xD7 120s. Set to 0 to disable.",type:"number",required:!1,default:"180000",example:"120000",category:"model"},{name:"AFK_MODEL_STALL_TIMEOUT_MS",description:"Progress-aware POST-first-byte stall window (ms) for the anthropic-direct streaming loop. Bounds how long a stream that has ALREADY produced content may then go completely silent. Every streamed output event resets the window, so this is NOT a total-round cap: a legitimately long, actively-streaming round (large code emission, extended thinking) survives indefinitely, while a stream wedged mid-flight is aborted and surfaces as a real terminal error instead of hanging. Complements AFK_MODEL_TTFB_TIMEOUT_MS, which governs only the window BEFORE the first token; this one takes over after it. Default 1200000 (20min) \u2014 above the 18.5min maximum post-first-byte stream duration observed across 86,076 rounds in 12,381 local traces (p99 122s, p99.9 234s), so no healthy round trips it. Set to 0 to disable (issue #762).",type:"number",required:!1,default:"1200000",example:"600000",category:"model"},{name:"AFK_SUBAGENT_TIMEOUT_MS",description:"Foreground forked-subagent wall-clock budget in ms; 0 disables the cap; explicit per-fork config.timeoutMs and the 60-min background mode still win. Bounds how long a single forked child turn may run before `withTimeout` aborts its controller (cascading through the AbortGraph to descendants) and the parent receives a legible TimeoutError tool_result instead of hanging. Default 2700000 (45 min \u2248 headroom over the longest healthy review/research agent observed in production). Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to opt a whole session back into unbounded child turns. Does NOT affect the background dispatch budget (SUBAGENT_BACKGROUND_TIMEOUT_MS) or a per-fork config.timeoutMs \u2014 both take precedence.",type:"number",required:!1,default:"2700000",example:"3600000",category:"model"},{name:"AFK_SUBAGENT_IDLE_TIMEOUT_MS",description:"Forked-subagent progress-aware idle-watchdog window in ms; 0 disables the watchdog; an explicit per-fork config.idleTimeoutMs still wins. Fires when a forked child produces no observable output event for this window, aborting the same controller the wall-clock timeout targets so partial output is preserved and the run classifies as a failure. This is distinct from AFK_SUBAGENT_TIMEOUT_MS, the blunt wall-clock that bounds total turn time: the idle watchdog is the tighter first-to-fire bound and never fires while the stream is legitimately parked on a provider-communicated backoff (OAuth pause, or a rate-limit event carrying a retry-after), extending the deadline for the pause window instead. Default 480000 (8 min) clears the worst-case transient-429 backoff the watchdog is currently blind to (about 363s) with roughly 2 min of margin, while staying materially tighter than the 45-min wall-clock. Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to disable the idle watchdog for a whole session (the wall-clock still applies). v1 applies to forked sub-agent turns only, not top-level or daemon sessions.",type:"number",required:!1,default:"480000",example:"300000",category:"model"},{name:"AFK_VISION_MODELS",description:'Comma-separated override for image (vision) capability detection on the openai-compatible provider. Each token force-enables a model id by exact or substring match (e.g. "qwen2.5-vl" matches a local VL id); prefix a token with "!" to force-disable. Use to send images to a local vision-language model AFK does not recognise by name, or to blacklist a mis-detected id. Built-in detection already covers gpt-4o/4.1/5.x, o1/o3/o4-mini, Claude, and common VL families.',type:"string",required:!1,example:"qwen2.5-vl,!gpt-4o-mini",category:"model"},{name:"AFK_MODEL_LOCAL",description:'Bind the "local" capability tier (cheapest/fastest, user-configured) to a model id. Overrides afk.config.json models.local. Point at a local Ollama, LM Studio, or any OpenAI-compatible shim.',type:"string",required:!1,example:"llama3.2:3b",category:"model"},{name:"AFK_MODEL_LOCAL_API_KEY",description:'Per-slot API key for the "local" tier. Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LOCAL_BASE_URL",description:'Per-slot endpoint base URL for the "local" tier. Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:11434/v1",category:"model"},{name:"AFK_MODEL_LARGE",description:'Bind the "large" capability tier (most capable) to a model id/alias. Overrides afk.config.json models.large.',type:"string",required:!1,example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-5",category:"model"},{name:"AFK_MODEL_MEDIUM_API_KEY",description:'Per-slot API key for the "medium" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_MEDIUM_BASE_URL",description:'Per-slot endpoint base URL for the "medium" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_SMALL",description:'Bind the "small" capability tier (cheap/fast) to a model id/alias. Overrides afk.config.json models.small.',type:"string",required:!1,example:"gpt-4o-mini",category:"model"},{name:"AFK_MODEL_SMALL_API_KEY",description:'Per-slot API key for the "small" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_SMALL_BASE_URL",description:'Per-slot endpoint base URL for the "small" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_OVERLOAD_PAUSE_MS",description:"Wall-clock ceiling (ms) for the bounded pause after a mid-stream overload (529) exhausts its retry budget. Overrides the per-surface default for ALL surfaces: 0 disables the pause (fail fast). Interactive surfaces (cli/repl/telegram) default to 600000; daemon/cron default to 0 so an always-on runner never silently parks on upstream capacity.",type:"number",required:!1,example:"600000",category:"model"},{name:"AFK_PROMPT_CACHE_TTL",description:"TTL for Anthropic prompt-cache blocks. Accepts 5m or 1h.",type:"string",required:!1,default:"1h",example:"1h",category:"model"},{name:"AFK_SUGGEST_ENABLED",description:"Enable the LLM-backed ghost-text suggestion tier in the interactive REPL. Set to 1/true/yes/on to activate. Off by default.",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_PROMPT",description:"Enable LLM-generated empty-prompt suggestions \u2014 a proposed next action shown as ghost text when the prompt is blank, accepted with Tab or Right-arrow. Fires only after a turn has completed in the session: the startup prompt (and the prompt right after /clear) is left clean because there is no session context to ground a proposal in. Set to 1/true/yes/on to activate. Off by default. Requires AFK_SUGGEST_ENABLED (it reuses the same suggestion model and provider).",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 | max | 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:"AFK_WORKSPACE_DISABLED",description:"Disable the shared agent workspace (WorkspaceStore + workspace_publish/workspace_query tools + preamble injection). When set to 1, subagents do not get workspace tools and no workspace preamble is injected at fork time \u2014 each agent works in full isolation as before v5.133. Used as the control arm of the file-read deduplication A/B experiment. Default: workspace enabled (unset or 0).",type:"boolean",required:!1,default:"0",example:"1",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:"XAI_API_KEY",description:"xAI API key for the xai provider (Grok models) in API-key mode. Metered; distinct from SuperGrok / SuperGrok Heavy / X Premium+ OAuth.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_XAI_BASE_URL",description:"Base URL for xAI API-key mode. Default https://api.x.ai/v1. The OpenAI SDK appends /chat/completions.",type:"string",required:!1,example:"https://api.x.ai/v1",category:"model"},{name:"AFK_XAI_OAUTH_BASE_URL",description:"Base URL for xAI SuperGrok / SuperGrok Heavy / X Premium+ OAuth inference. Default https://cli-chat-proxy.grok.com/v1 (subscription path). Some accounts work on https://api.x.ai/v1 with OAuth \u2014 override if needed. Distinct from AFK_XAI_BASE_URL (API-key mode).",type:"string",required:!1,example:"https://cli-chat-proxy.grok.com/v1",category:"model"},{name:"AFK_XAI_GROK_CLIENT_VERSION",description:"Override the semver sent as x-grok-client-version to the xAI OAuth CLI chat proxy. Use only if the proxy raises its required Grok CLI version before agent-afk is updated; invalid values fall back to the official Grok Build version file or built-in compatible default.",type:"string",required:!1,example:"1.0.6",category:"model"},{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 | xai | xai-oauth). Overrides the model-name heuristic. Same surface as the --provider CLI flag; CLI flag wins when both are set.",type:"string",required:!1,example:"openai-compatible",category:"model"},{name:"EXA_API_KEY",description:"Exa (exa.ai) search API key, enabling web_scrape search mode. Free tier (20k requests/month) available at https://exa.ai. When unset, search mode returns an actionable error; markdown and raw modes are unaffected.",type:"string",required:!1,category:"auth",secret:!0},{name:"TELEGRAM_BOT_TOKEN",description:"Telegram bot token from @BotFather. Required to run the Telegram bot surface.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_BOT_TOKEN",description:"Alternative env var name for the Telegram bot token, accepted by the setup wizard.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_ALLOWED_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs allowed to interact with the bot. Required when the bot is running.",type:"string",required:!1,example:"123456789,987654321",category:"telegram"},{name:"AFK_TELEGRAM_TAG_ONLY_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs where the bot answers only when addressed (a reply to the bot, an @mention of the bot, or a text_mention resolving to the bot). Slash-commands are unaffected; chats not listed behave as usual. The afk.config.json telegram.tagOnlyChats block takes precedence. Requires Telegram privacy mode OFF (BotFather /setprivacy Disable) for non-addressed group messages to reach the bot.",type:"string",required:!1,example:"-100987654321,123456789",category:"telegram"},{name:"AFK_TELEGRAM_PRIMARY_CHAT_ID",description:"Default chat ID for outbound notifications (primary-mode routing). When unset, notifications go to the first private/DM chat in AFK_TELEGRAM_ALLOWED_CHAT_IDS. The afk.config.json telegram.notify block takes precedence.",type:"string",required:!1,example:"123456789",category:"telegram"},{name:"AFK_TELEGRAM_NOTIFY_MODE",description:"Outbound notification fan-out: primary (default \u2014 one chat), broadcast (every allowed chat), or custom (afk.config.json telegram.notify.targets). The afk.config.json telegram.notify.mode takes precedence.",type:"string",required:!1,example:"broadcast",category:"telegram"},{name:"TELEGRAM_DATA_DIR",description:"Override the directory where Telegram bot state is stored. Defaults to ~/.afk/state/telegram/.",type:"string",required:!1,category:"telegram"},{name:"TELEGRAM_VERBOSE",description:"Set to a truthy value ('1'/'true'/'yes'/'on', case-insensitive) to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"true",category:"telegram"},{name:"TMUX",description:"OS-level tmux session identifier. Set automatically by tmux to the socket path and session info (e.g. /tmp/tmux-501/default,12345,0) inside any tmux pane. Not set by AFK. Read by configureColor() to detect a tmux environment; for truecolor support on Node \u2264 24, set FORCE_COLOR=3 in your shell or ~/.afk/config/afk.env.",type:"string",required:!1,example:"/tmp/tmux-501/default,12345,0",category:"process"},{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:"APPDATA",description:"Windows %APPDATA% (Roaming). Used for VS Code/Cursor settings discovery and credential denylist paths.",type:"string",required:!1,category:"process"},{name:"LOCALAPPDATA",description:"Windows %LOCALAPPDATA%. Used for browser credential denylist paths (Chrome, Firefox, Edge, etc.).",type:"string",required:!1,category:"process"},{name:"USERPROFILE",description:"Windows %USERPROFILE%. Used for credential denylist paths (.ssh, .aws, .gnupg) on win32.",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_WEB_PORT",description:"Port for the `afk web` browser surface. Defaults to 4141; falls back to an ephemeral port when taken. Overridden by --port.",type:"number",required:!1,example:"4141",category:"daemon"},{name:"AFK_WEB_HOST",description:"Bind address for the `afk web` browser surface. Defaults to 127.0.0.1. Unlike the daemon control surface, a non-loopback bind is REFUSED unless AFK_WEB_TOKEN (or --token) is also set, because this surface can submit prompts and approve tool use. Overridden by --host.",type:"string",required:!1,example:"127.0.0.1",category:"daemon"},{name:"AFK_WEB_TOKEN",description:"Bearer token for the `afk web` surface. When unset, a random per-run token is minted and printed in the startup URL. Setting this explicitly is also what permits a non-loopback bind.",type:"string",required:!1,category:"daemon",secret:!0},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_ON_EXIT",description:"Clean-worktree quit policy for interactive --worktree sessions: ask, keep, or remove.",type:"string",required:!1,example:"ask",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Opt-in to loading + spawning MCP servers declared in <cwd>/.mcp.json. Fail-closed: when unset (or 0), project-local servers are NOT spawned; set to a truthy value (1/true/yes/on) to load them. A project-local .mcp.json spawns arbitrary commands on session start, so it is off by default to prevent code execution when entering an untrusted repo (issue #571). Skipped servers are listed in a startup warning with the opt-in instruction.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BG_AUTO_DELIVER",description:"Auto-deliver background subagent results into the model context on the next user turn (interactive REPL). On by default. Set to 0, false, off, or no (case-insensitive) to disable, restoring the manual /bgsub:join retrieval flow.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_PLAIN_OUTPUT",description:"Force the interactive REPL to fully behave like a non-TTY surface for rendering purposes, even when stdout/stdin ARE a TTY: append-only plain-stdout output instead of the TerminalCompositor live overlay (both the persistent between-turn compositor AND the per-turn StreamRenderer overlay), AND the input surface downgrades to the simple non-TTY line reader instead of the fancy compositor-backed input box. Same code path already used for non-TTY surfaces (pipes, CI). Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM scroll regions misbehave \u2014 trades the live overlay and fancy input UX for reliability. Opt-in \u2014 default TTY behavior (live overlay + fancy input) is unchanged unless this var is set. Truthy values: 1, true (case-insensitive).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_GOBLIN_SPINNER",description:"Goblin-themed working spinner (olive frames + goblin verbs) while the agent runs tools. 1 = on (default), 0 = classic dim spinner.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_GOBLIN_MASCOT",description:"Reacting goblin mini-sprite in the reserved footer band while the agent runs tools (3 rows, animated). 1 = on, unset/0 = off (default). Claims terminal rows, so it is opt-in.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_TERM_TITLE",description:'Set the terminal/tab title (OSC 2) to reflect afk state \u2014 "afk \u2014 <cwd> \xB7 running" during a turn, "afk \u2014 <cwd>" when idle, cleared on exit. 1 = on (default when stdout is a TTY), 0 = leave the title alone. TTY-only.',type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_NOTIFY",description:"Emit a desktop completion notification (OSC 9) on turn completion, for terminals that map OSC 9 to system notifications (iTerm2, kitty, WezTerm). Opt-in and off by default (intrusive). 1 = on. TTY-only.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_THEME",description:"TUI color palette for the interactive REPL and all CLI rendering: dark | light | umber | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark; umber matches the Umber terminal, is dark-only, and is never chosen by auto. Overridden per-launch by --theme and mutable mid-session via /theme. Precedence: --theme flag > this env > config theme > auto-detect > dark. Invalid values are ignored (dark).",type:"string",required:!1,default:"dark",example:"light",category:"misc"},{name:"AFK_TEXT_MEASURE",description:"Maximum line length (columns) for unbordered streamed text in the interactive REPL: assistant prose, thinking blocks, tool-lane text, and subagent text. Display-only \u2014 affects wrapping, never behavior. Bordered elements (cards, error boxes) already cap at 100; this applies the same ceiling to the unbordered surfaces, which previously scaled to the full terminal width. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable capping and restore full-width wrapping. Unparseable or below-minimum values fall back to the default. No-op on terminals at or below the measure, so narrow terminals are unaffected.",type:"string",required:!1,default:"100",example:"full",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"COLORTERM",description:"OS-level terminal color-depth hint. Accepted values: truecolor or 24bit (24-bit color), 256color (256-color). Set by the outer terminal emulator, not by AFK. Read by chalk's supports-color to set its initial color level; also read by configureColor() to recommend FORCE_COLOR=3 for tmux truecolor users on Node \u2264 24.",type:"string",required:!1,example:"truecolor",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_WITNESS_RETENTION_DISABLE",description:"Disable the witness-tree retention sweep entirely, so no session directory is ever evicted.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_MAX_AGE_DAYS",description:"Evict a witness session directory once its newest content is older than this many days. Default 30.",type:"number",required:!1,default:"30",category:"debug"},{name:"AFK_WITNESS_MAX_BYTES",description:"Aggregate byte cap for the witness tree; oldest session directories are evicted first once exceeded. Default 2147483648 (2 GiB).",type:"number",required:!1,default:"2147483648",category:"debug"},{name:"AFK_SESSION_RETENTION_DISABLE",description:"Disable the session sidecar retention sweep entirely, so no state/sessions/*.json file is ever evicted.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_MAX_AGE_DAYS",description:"Evict a session sidecar file once it is older than this many days (based on savedAt). Default 30.",type:"number",required:!1,default:"30",category:"debug"},{name:"AFK_SESSION_MAX_COUNT",description:"Count-based safety valve: evict oldest session sidecars first once the total exceeds this number. Default 1000.",type:"number",required:!1,default:"1000",category:"debug"},{name:"AFK_WAVE_MANIFEST_DISABLED",description:"Disable the wave manifest system entirely. When set to 1, no manifest is written for parallel subagent waves, and no resumption offer is made at session start.",type:"boolean",required:!1,default:"0",example:"1",category:"misc"},{name:"AFK_WAVE_MANIFEST_TTL_HOURS",description:"Time-to-live for wave manifests in hours. Manifests older than this are deleted on reconciliation and by the witness sweep. Default 48 (two days).",type:"number",required:!1,default:"48",example:"24",category:"misc"},{name:"AFK_WAVE_RESUME_UNATTENDED",description:"When set to 1, surface wave resumption offers even on non-interactive surfaces (daemon, one-shot chat). By default, offers are only made on interactive surfaces (REPL, Telegram).",type:"boolean",required:!1,default:"0",example:"1",category:"misc"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_CAPTURE_SUBAGENT_PROMPTS",description:"Opt-in: when set to 1, every prompt a parent session sends to a subagent is written as a redacted markdown file under state/witness/<label>/prompts/. Off by default because nothing prunes the witness tree and prompts may carry secrets the regex redactor cannot catch (connection strings, PEM blocks, PII).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_CAPTURE_SUBAGENT_OUTPUT",description:"Opt-in: when set to 1, a subagent's conversational OUTPUT (assistant text plus each tool call with its arguments) is appended incrementally to a redacted markdown transcript under state/witness/<label>/outputs/. Flushed at every tool-call boundary, so a child killed by a timeout still leaves a usable partial record \u2014 the case where final-message capture yields nothing. Off by default for the same reasons as AFK_CAPTURE_SUBAGENT_PROMPTS (unpruned witness tree, best-effort regex redaction).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SUBAGENT_LOG",description:"Opt-in per-subagent conversation log. Writes OutputEvent JSONL to state/subagent-logs/<sessionLabel>/<subagentId>.jsonl for both foreground and background subagents. Powers /tasks:view replay. OFF by default (raw tool arguments are written without redaction \u2014 consistent with AFK_CAPTURE_SUBAGENT_PROMPTS / AFK_CAPTURE_SUBAGENT_OUTPUT). Set to 1 to enable.",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:"Browser provider backend: auto (default, prefer Agent Browser, fall back to Playwright), agent-browser (require Agent Browser), or playwright (headless only).",type:"string",required:!1,default:"auto",example:"agent-browser",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_RATE_LIMIT_ADMISSION_DISABLED",description:"Bypass the process-wide rate-limit admission gate (issue #941). Set to 1 to skip pre-request capacity checks. Default 0 (gate active). OAuth subscription accounts already pass through automatically when no per-minute headers are returned.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_RATE_LIMIT_STAGGER_MAX_MS",description:"Jitter ceiling (ms) for the rate-limit admission bucket: each waiter at a window boundary wakes at reset + random(0..ceiling) to avoid re-storming the API. Default 500. Set to 0 in tests for deterministic timing.",type:"number",required:!1,default:"500",example:"0",category:"model"},{name:"AFK_WEB_ALLOW_PRIVATE_HOSTS",description:"Opt out of the web_scrape SSRF egress guard. When unset (default) the guard is ACTIVE: the markdown, raw, and headless-render paths refuse loopback (127/8, ::1), link-local (169.254/16 \u2014 including the 169.254.169.254 cloud instance-metadata endpoint), RFC1918 (10/8, 172.16/12, 192.168/16), carrier-grade NAT (100.64/10), IPv6 unique-local (fc00::/7), 0.0.0.0/8, and the IPv4-mapped/compatible IPv6 forms of all of those. Hostnames are resolved and the RESOLVED addresses are classified (DNS-rebinding guard), and the check is re-applied on every redirect hop. Set to 1/true to allow private-host access \u2014 needed only to scrape a local dev server. Enabling it restores a model-reachable SSRF path (issue #575).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"VISUAL",description:"Standard POSIX env var naming the user's preferred full-screen editor (with optional flags). Consulted FIRST by the /editor slash command (and its key chord) to compose a long prompt externally; takes precedence over EDITOR. No fallback editor is assumed \u2014 if neither VISUAL nor EDITOR is set, /editor prints a hint instead of guessing.",type:"string",required:!1,example:"nvim",category:"process"},{name:"EDITOR",description:"Standard POSIX env var naming the user's preferred editor (with optional flags). Consulted by the /editor slash command AFTER VISUAL, as the standard fallback. No default editor is assumed when both are unset \u2014 /editor prints a hint telling the user to set one.",type:"string",required:!1,example:"vim",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"},{name:"AFK_LEASE_TTL_MS",description:"Lease TTL in milliseconds for durable task execution (issue #1411). A leased task whose lease expires before it completes is recovered and re-enqueued (or dead-lettered if maxAttempts is exhausted). Default: 600000 (10 minutes).",type:"number",required:!1,example:"600000",category:"misc"}],Gf={};for(let t of Rr){let e=t.name;Object.defineProperty(Gf,e,{get(){return process.env[e]},enumerable:!("secret"in t&&t.secret),configurable:!0})}y=Gf});function eR(){return y.AFK_DEBUG==="1"||y.DEBUG==="1"}function P(...t){eR()&&console.log(...t)}var J=re(()=>{"use strict";C()});import{existsSync as qf,mkdirSync as tR,renameSync as nR,cpSync as rR,rmSync as oR}from"fs";import{join as L,dirname as bl,basename as sR,isAbsolute as wl}from"path";import{homedir as Jf}from"os";import{fileURLToPath as iR}from"url";function ee(){let t=y.AFK_HOME;if(t!==void 0&&t!==""){if(!wl(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return L(Jf(),".afk")}function Oe(){let t=y.AFK_FRAMEWORK_DIR;if(t!==void 0&&t!==""){if(!wl(t)||t==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${t}`);return t}return L(ee(),"agent-framework")}function Rs(){return L(Oe(),"forge-telemetry.jsonl")}function Vf(){return L(Oe(),"briefs")}function Yf(){return L(Oe(),"facets")}function Ir(){return L(ee(),"skills")}function Tn(){return L(ee(),"plugins")}function Qf(t=process.cwd()){return L(t,".afk")}function Zf(t=process.cwd()){return L(Qf(t),"skills")}function em(t=process.cwd()){return L(Qf(t),"plugins")}function tm(t=process.cwd()){return L(t,".afk","plans")}function Is(){return L(Tn(),".index.json")}function Sl(){return L(Cr(),"schedules.json")}function nm(){let t=iR(import.meta.url),e=bl(t);return L(e,"bundled-plugins")}function Cr(){return L(ee(),"config")}function te(){let t=y.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!wl(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return L(ee(),"state")}function de(){return L(te(),"sessions")}function Cs(){return L(te(),"presence")}function Ps(){return L(te(),"memory")}function Ms(){return L(te(),"session-grants.jsonl")}function rm(){return L(ee(),"farms")}function om(t){return L(rm(),t)}function Os(t){if(!aR.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function Pr(){return L(te(),"witness")}function At(t){return Os(t),L(Pr(),t)}function sm(t){return L(At(t),"inbound-attachments")}function im(t){return L(At(t),"prompts")}function am(t){return L(At(t),"outputs")}function _n(t){return!t||t.startsWith("in-memory:")?null:sR(bl(t))}function cm(t="default"){return L(te(),"daemon",`agent-afk@${t}`)}function lm(){return L(te(),"worktree-sweep.lock")}function Ds(){return L(te(),"worktree-roots.json")}function kl(){return L(Cr(),"afk.env")}function En(){return L(Cr(),"afk.config.json")}function Fs(){return L(Jf(),".afk.config.json")}function cR(){return L(ee(),"sessions")}function lR(t,e){if(t!==e&&qf(t)&&!qf(e))try{tR(bl(e),{recursive:!0});try{nR(t,e)}catch(n){if(n.code==="EXDEV")try{rR(t,e,{recursive:!0}),oR(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 dm(){lR(cR(),de())}function um(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(t.length>Xf)throw new Error(`Invalid jobId: exceeds ${Xf} chars`);if(!dR.test(t))throw new Error(`Invalid jobId: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function vl(){return L(te(),"subagent-logs")}function Tl(t){return um(t),L(vl(),t)}function pm(t,e){return um(e),L(Tl(t),`${e}.jsonl`)}function _l(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>zf)throw new Error(`Invalid browser profile: exceeds ${zf} chars`);if(!uR.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function pR(){return L(te(),"browser")}function fR(t){return _l(t),L(pR(),t)}function El(t){return L(fR(t),"storageState.json")}function An(t){return typeof t=="string"&&t.length>0&&t.length<=gR&&mR.test(t)}function Mr(t){if(!An(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return L(de(),t)}function Or(t){return L(Mr(t),"events.jsonl")}function fm(t){return L(Mr(t),"session.key")}function Dr(){return L(te(),"waves")}function Fr(t){return L(Dr(),`${t}.json`)}var aR,dR,Xf,uR,zf,mR,gR,M=re(()=>{"use strict";C();aR=/^[a-zA-Z0-9_-]+$/;dR=/^[A-Za-z0-9_-]+$/,Xf=128;uR=/^[A-Za-z0-9_-]+$/,zf=128;mR=/^[A-Za-z0-9_-]+$/,gR=128});var Ud={};As(Ud,{enforceDomainPolicy:()=>Ye,loadBrowserConfig:()=>Nd});import{readFileSync as sD}from"node:fs";import{join as iD}from"path";function aD(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function zy(t,e){return aD(e).test(t)}function dD(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(cD.has(e))return!0;if(lD.has(e))return!1}return!1}function Jy(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function uD(t){if(t===void 0||t==="")return"auto";if(t==="playwright"||t==="agent-browser"||t==="auto")return t;throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${t}`)}function Vy(t){let e=t===void 0||t.trim()===""?"default":t.trim();return _l(e),e}function pD(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function fD(t){try{return sD(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function mD(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"||e.backend==="agent-browser"||e.backend==="auto")n.backend=e.backend;else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=Vy(e.defaultProfile)),n}function Nd(t){let e=t?.env??y,n=t?.readFileSync??fD,r=t?.surface??e.AGENT_SURFACE,o=dD(e.AFK_BROWSER_HEADLESS,r),s=Jy(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Jy(e.AFK_BROWSER_BLOCKED_DOMAINS),a=pD(e.AFK_BROWSER_DOM_SNAPSHOTS),c=uD(e.AFK_BROWSER_BACKEND),l=Vy(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():iD(Cr(),"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=mD(d,m);return g.configPath=p,g}function Ye(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(zy(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>zy(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var cD,lD,Ut=re(()=>{"use strict";C();M();cD=new Set(["daemon","subagent","telegram","afk"]),lD=new Set(["repl","interactive","cli"])});import{readFileSync as gD}from"node:fs";import{join as hD}from"node:path";import{homedir as yD}from"node:os";function wD(t){let e=t??bD,n;try{n=gD(e,"utf8")}catch{return null}let r;try{r=JSON.parse(n)}catch{return null}if(typeof r!="object"||r===null||Array.isArray(r))return null;let o=r;if(typeof o.url!="string"||typeof o.token!="string"||typeof o.pid!="number")return null;let s;try{s=new URL(o.url)}catch{return null}let{hostname:i,protocol:a}=s;if(!(i==="127.0.0.1"||i==="localhost"||i==="::1")||a!=="http:")throw new Error(`Agent Browser connection file contains an untrusted URL: ${o.url}. Only http://127.0.0.1 or http://localhost is permitted.`);return{url:o.url,token:o.token,pid:o.pid,version:typeof o.version=="string"?o.version:"unknown"}}function SD(t){try{return process.kill(t,0),!0}catch{return!1}}async function kD(t,e,n=2e3){try{let r=new AbortController,o=setTimeout(()=>r.abort(),n),s=await fetch(`${t}/health`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Host:"127.0.0.1:8833"},signal:r.signal});return clearTimeout(o),s.ok}catch{return!1}}async function $d(t){let e=wD(t);return e===null?{available:!1,connection:null,reason:"connection file missing or invalid"}:SD(e.pid)?await kD(e.url,e.token)?{available:!0,connection:e,reason:null}:{available:!1,connection:e,reason:`health probe failed at ${e.url}`}:{available:!1,connection:e,reason:`stale connection file: PID ${e.pid} not alive`}}var bD,Yy=re(()=>{"use strict";bD=hD(yD(),".config","agent-browser","connection.json")});async function Qy(t){let{config:e,surface:n}=t;if(e.backend==="playwright")return{backend:"playwright",reason:"explicit config: backend=playwright",probeMs:0,availability:null};if(e.backend==="agent-browser"){let i=Date.now(),a=await $d(),c=Date.now()-i;if(!a.available)throw new Error(`AFK_BROWSER_BACKEND=agent-browser but Agent Browser is not available: ${a.reason}`);return{backend:"agent-browser",reason:"explicit config: backend=agent-browser",probeMs:c,availability:a}}if(n&&vD.has(n))return{backend:"playwright",reason:`auto: surface "${n}" excluded from Agent Browser`,probeMs:0,availability:null};if(e.headless)return{backend:"playwright",reason:"auto: headless mode requires Playwright",probeMs:0,availability:null};let r=Date.now(),o=await $d(),s=Date.now()-r;return o.available?{backend:"agent-browser",reason:"auto: Agent Browser available and preferred",probeMs:s,availability:o}:{backend:"playwright",reason:`auto: Agent Browser unavailable (${o.reason})`,probeMs:s,availability:o}}var vD,Zy=re(()=>{"use strict";Yy();vD=new Set(["daemon","subagent"])});import{createHash as TD}from"crypto";function eb(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&_D.test(t.label))}function tb(t){return TD("sha256").update(t,"utf8").digest("hex").slice(0,8)}function nb(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var _D,Fi=re(()=>{"use strict";_D=/password|secret|token|api[_-]?key|otp|2fa/i});import{randomBytes as ED}from"crypto";import{mkdir as AD,stat as xD,writeFile as RD}from"fs/promises";import{join as Bd}from"path";import{gzip as ID}from"zlib";import{promisify as CD}from"util";function PD(t){return Bd(At(t),"browser")}function MD(t){return Bd(PD(t),"screenshots")}function OD(){return new Date().toISOString().replace(/[:.]/g,"-")}function DD(){return ED(3).toString("hex")}async function Kn(t,e,n){if(e.length>rb)throw new Error(`writeScreenshotSidecar: buffer exceeds ${rb} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=MD(t);await AD(r,{recursive:!0});let o=`${OD()}-${DD()}-${n}.png`,s=Bd(r,o);await RD(s,e);let{size:i}=await xD(s);return{path:s,bytes:i}}var F6,rb,jd=re(()=>{"use strict";M();Fi();F6=CD(ID);rb=5*1024*1024});var Li,ob=re(()=>{"use strict";Li=class{baseUrl;token;constructor(e){this.baseUrl=e.url,this.token=e.token}async call(e,n,r=3e4){let o={version:1,method:e,params:n},s=new AbortController,i=setTimeout(()=>s.abort(),r);try{let a=await fetch(`${this.baseUrl}/agent`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,Host:new URL(this.baseUrl).host},body:JSON.stringify(o),signal:s.signal});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Agent Browser ${e} failed (HTTP ${a.status}): ${c}`)}return await a.json()}finally{clearTimeout(i)}}async listTabs(){return(await this.call("tabs.list",null)).tabs}async openTab(e){return{tabId:(await this.call("tabs.open",{url:e},6e4)).tab_id}}async closeTab(e){await this.call("tabs.close",{tab_id:e})}async read(e,n){return this.call("page.read",{tab_id:e,mode:n?.mode??"main",...n?.query?{query:n.query}:{},...n?.budget?{budget:n.budget}:{}})}async inspect(e,n){return this.call("page.inspect",{tab_id:e,mode:n?.mode??"interactive",...n?.query?{query:n.query}:{},...n?.limit?{limit:n.limit}:{}})}async click(e,n){await this.call("page.click",{tab_id:e,element_id:n})}async fill(e,n,r){await this.call("page.fill",{tab_id:e,element_id:n,value:r})}async press(e,n,r){await this.call("page.press",{tab_id:e,key:n,...r?{element_id:r}:{}})}async select(e,n,r){await this.call("page.select",{tab_id:e,element_id:n,value:r})}async waitFor(e,n,r){await this.call("page.wait",{tab_id:e,condition:n,...r?.value?{value:r.value}:{},...r?.timeout?{timeout:r.timeout}:{}},(r?.timeout??3e4)+5e3)}async evalScript(e,n){return this.call("page.eval",{tab_id:e,script:n})}async screenshot(e){return this.call("page.screenshot",{tab_id:e})}}});function Hd(t){return{id:t.id,role:t.role,label:t.label,kind:t.kind,value:t.value,state:{disabled:t.disabled,...t.checked!==void 0?{checked:t.checked}:{},...t.selected!==void 0?{selected:t.selected}:{},...t.expanded!==void 0?{expanded:t.expanded}:{}},bbox:t.bbox,...t.selector?{selector:t.selector}:{}}}function sb(t,e){switch(e.kind){case"element_id":if(t.has(e.elementId))return e.elementId;throw new Error(`Element ${e.elementId} not found in current observation. Call browser_observe to refresh.`);case"selector":return null;case"semantic":return null}}async function Wd(t,e,n,r,o,s){switch(n){case"click":await t.click(e,r);break;case"fill":if(o===void 0)throw new Error("fill requires a value");await t.fill(e,r,o);break;case"press":if(o===void 0)throw new Error("press requires a value (key combo)");await t.press(e,o,r);break;case"select":if(o===void 0)throw new Error("select requires a value");await t.select(e,r,o);break;case"hover":throw new Error("hover is not supported by Agent Browser; use element_id from a prior observation to target clicks instead");case"scroll_to":{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');await t.evalScript(e,`document.querySelector('[data-element-id="${i}"]')?.scrollIntoView({behavior:'smooth',block:'center'})`);break}case"wait_for":await t.waitFor(e,"element",{value:r,timeout:s??1e4});break;default:throw new Error(`Unknown action: ${n}`)}}async function ib(t,e){if(e.target.kind!=="semantic")throw new Error("resolveSemanticAndAct called with non-semantic target");let{elements:n}=await t.client.inspect(t.tabId,{mode:"interactive",query:e.target.text,limit:10}),r=n;if(e.target.role){let c=e.target.role.toLowerCase();r=n.filter(l=>l.role.toLowerCase()===c)}if(r.length===0)throw new Error(`No element found matching semantic target: text="${e.target.text}"`+(e.target.role?`, role="${e.target.role}"`:""));if(r.length>1)return{outcome:"ambiguous_target",query:{text:e.target.text,...e.target.role?{role:e.target.role}:{}},candidates:r.slice(0,5).map(Hd)};let s=r[0].id;await Wd(t.client,t.tabId,e.action,s,e.value,e.timeoutMs);let i=await t.client.read(t.tabId,{mode:"main"}),a=Ye(i.url,t.config);return a.allowed?{elementId:s}:{outcome:"blocked_by_policy",url:i.url,reason:`action navigated to blocked domain: ${a.reason}`}}var ab=re(()=>{"use strict";Ut()});var cb={};As(cb,{AgentBrowserProvider:()=>Kd});var Kd,lb=re(()=>{"use strict";Ut();jd();ob();ab();Kd=class{name="agent-browser";config;client;sessions=new Map;constructor(e,n){this.config=e,this.client=new Li(n)}async open(e){let n=Ye(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let r=this.sessions.get(e.sessionId);if(r)await this.client.evalScript(r.tabId,`window.location.href = ${JSON.stringify(e.url)}`),await this.client.waitFor(r.tabId,"load",{timeout:e.timeoutMs??3e4});else{let{tabId:i}=await this.client.openTab(e.url);await this.client.waitFor(i,"load",{timeout:e.timeoutMs??3e4}),r={tabId:i,observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null},this.sessions.set(e.sessionId,r)}let o=await this.client.read(r.tabId,{mode:"main"}),s=Ye(o.url,this.config);return s.allowed?this.buildObservation(r,e.sessionId,e.screenshot,void 0,"browser_open"):(await this.client.evalScript(r.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`redirected to blocked domain: ${s.reason}`})}async observe(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);return this.buildObservation(n,e.sessionId,e.screenshot,e.maxElements,"browser_observe")}async act(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);let r=sb(n.knownElements,e.target);if(r===null){if(e.target.kind==="semantic"){let i=await ib({client:this.client,config:this.config,tabId:n.tabId},e);return"outcome"in i?i:(n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString(),this.buildObservation(n,e.sessionId,e.screenshot,void 0,"browser_act"))}throw e.target.kind==="selector"?new Error("selector targets are not supported by Agent Browser; use element_id or semantic targets"):new Error(`Cannot resolve target: ${JSON.stringify(e.target)}`)}await Wd(this.client,n.tabId,e.action,r,e.value,e.timeoutMs),n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString();let o=await this.client.read(n.tabId,{mode:"main"}),s=Ye(o.url,this.config);return s.allowed?this.buildObservation(n,e.sessionId,e.screenshot,void 0,"browser_act"):(await this.client.evalScript(n.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`action navigated to blocked domain: ${s.reason}`})}async render(e){throw new Error("AgentBrowserProvider does not support render(). Use PlaywrightProvider for one-shot content fetches.")}async screenshot(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);if(e.target!==void 0||e.fullPage)throw new Error("Agent Browser does not support element or full-page screenshots; omit target and fullPage.");let r=await this.client.screenshot(n.tabId),o=Buffer.from(r.data,"base64"),s=o.length>=24?o.readUInt32BE(16):0,i=o.length>=24?o.readUInt32BE(20):0;return{path:(await Kn(e.sessionId,o,"browser_screenshot")).path,bytes:o.length,width:s,height:i,dataBase64:r.data,mediaType:"image/png"}}async extract(e){throw new Error("AgentBrowserProvider does not support extract() yet.")}async close(e){let n=this.sessions.get(e.sessionId);if(n){try{await this.client.closeTab(n.tabId)}catch{}this.sessions.delete(e.sessionId)}}describe(e){let n=this.sessions.get(e);return n?{active:!0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:1}:null}async shutdown(){let e=Array.from(this.sessions.entries()).map(async([,n])=>{try{await this.client.closeTab(n.tabId)}catch{}});await Promise.all(e),this.sessions.clear()}async buildObservation(e,n,r,o,s="browser_open"){let[i,a]=await Promise.all([this.client.read(e.tabId,{mode:"main",budget:4e3}),this.client.inspect(e.tabId,{mode:"interactive",limit:o??80})]),c=a.elements.map(Hd),l=o??80,d=c.slice(0,l);e.observationCounter+=1,e.knownElements=new Map(d.map(g=>[g.id,g])),e.currentUrl=i.url,e.currentTitle=i.title;let u=[];c.length>l&&u.push(`page has ${c.length} interactive elements; showing first ${l}`);let p=null;if(r)try{let g=await this.client.screenshot(e.tabId),h=Buffer.from(g.data,"base64");p=(await Kn(n,h,s)).path}catch{u.push("screenshot capture failed")}let f=`obs_${e.observationCounter.toString(36)}`,m={httpStatus:null,loadingState:"idle",hasDialog:!1,consoleErrors:0};return{observationId:f,url:i.url,title:i.title,textSummary:i.content.slice(0,4e3),interactive:d,status:m,warnings:u,screenshotPath:p,capturedAt:new Date().toISOString()}}}});import{existsSync as FD,readFileSync as LD}from"node:fs";import{createRequire as ND}from"node:module";import{dirname as UD,join as $D}from"node:path";function pb(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<jD&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function xe(t){let e=pb(t);return ub.some(n=>e.includes(n))}function HD(){try{let e=ND(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(LD(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=$D(UD(e),o);return FD(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function To(){return db??=HD()??BD,db}function Gd(t){return t.includes("install chromium")}function He(t,e){let n=pb(t),r=e?.latched===!0?` ${WD}`:"";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: ${To()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${To()}). Or pick a different tool.${r}`}function Ni(t,e,n=!1){if(!xe(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
3
3
|
|
|
4
|
-
${He(t,{headless:e,latched:n})}`,{cause:t})}var ub,BD,jD,db,WD,qd=re(()=>{"use strict";ub=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],BD="pnpm exec playwright install chromium",jD=4;WD="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 pn from"node:fs";import Ui from"node:path";import{randomBytes as KD}from"node:crypto";function GD(){try{return"5.176.0"}catch{}try{let t=Ui.resolve(import.meta.dirname,"../../../package.json"),e=pn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var qD,$i,fb=re(()=>{"use strict";qd();M();J();qD=GD(),$i=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=(async()=>{let e;try{({chromium:e}=await import("playwright"))}catch(n){let r=Ni(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await e.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=Ni(n,this.config.headless,!0);throw this.latchLaunchFailure(r),r}finally{this.launchPromise=void 0}})(),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${qD}`}}loadStorageState(e){let n=El(e);try{if(!pn.existsSync(n))return;let r=JSON.parse(pn.readFileSync(n,"utf8"));return P("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){P("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=El(e);if(!pn.existsSync(r))return;let o=await n.storageState(),s=Ui.join(Ui.dirname(r),`.${Ui.basename(r)}.${process.pid}.${KD(4).toString("hex")}.tmp`);pn.writeFileSync(s,JSON.stringify(o),{mode:384}),pn.chmodSync(s,384),pn.renameSync(s,r),P("[browser/vault] saved session",{profile:e,file:r})}catch(r){P("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as XD}from"node:crypto";function zD(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function JD(t,e,n){return`el_${XD("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function VD(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function mb(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function hb(t,e){let n=t.role??"",r=t.name??"";gb.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])hb(s,e)}async function YD(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},yb).catch(()=>[])}async function QD(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},yb).catch(()=>[])}function ZD(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Bi(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=ZD(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=YD(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,c,l,d]),h,b=!1;u!==null?(h=[],hb(u,h)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,h=(await QD(t)).filter(D=>gb.has(D.role??"")));let w=new Map;for(let A of p){let D=mb(A.name),q=w.get(D);(!q||q.bbox.w===0&&A.bbox.w>0)&&w.set(D,A)}let k=h.map(A=>({ax:A,dom:w.get(mb(A.name??""))})),v=r?k:k.filter(A=>A.dom?A.dom.bbox.w>0||A.dom.bbox.h>0:!0);v.sort((A,D)=>{let q=A.dom?.bbox.y??0,F=D.dom?.bbox.y??0;if(q!==F)return q-F;let N=A.dom?.bbox.x??0,O=D.dom?.bbox.x??0;return N-O}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=v.slice(0,n).map((A,D)=>{let q=A.ax.role??"generic",F=A.ax.name??"",N=JD(q,F,D),O=A.dom?.bbox??{x:0,y:0,w:0,h:0},U=A.dom?.type??null,G=null;A.ax.value!==void 0&&A.ax.value!==null&&(G=String(A.ax.value)),A.ax.checked!==void 0&&(G=String(A.ax.checked)),eb({role:q,kind:U})&&(G="[redacted]");let H={disabled:A.ax.disabled??!1};A.ax.checked!==void 0&&(H.checked=A.ax.checked===!0||A.ax.checked==="mixed"),A.ax.selected!==void 0&&(H.selected=A.ax.selected),A.ax.expanded!==void 0&&(H.expanded=A.ax.expanded);let le;A.dom?.testId?le=`[data-testid="${A.dom.testId}"]`:A.dom?.id&&(le=`#${A.dom.id}`);let dt={id:N,role:q,label:zD(F),kind:U,value:G,state:H,bbox:O};return le!==void 0&&(dt.selector=le),dt}),x="idle";try{let A=await t.evaluate(()=>document.readyState);A==="loading"?x="loading":A==="interactive"?x="navigating":x="idle"}catch{x="navigating"}x!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=VD(f),S=`obs_${e.observationCounter.toString(36)}`,_=new Date().toISOString();return{observationId:S,url:m,title:g,textSummary:I,interactive:T,status:{httpStatus:e.httpStatus??null,loadingState:x,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:_}}var gb,yb,bb=re(()=>{"use strict";Fi();gb=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);yb="a[href], button, input, select, textarea, [role], [tabindex], label"});async function wb(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Xd(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>wb(t,s)))).filter(o=>o!==null)}async function eF(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function zd(t,e,n){switch(e.kind){case"element_id":return tF(t,e,n);case"selector":return nF(t,e);case"semantic":return rF(t,e)}}async function tF(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Xd(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function nF(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 Xd(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function rF(t,e){return e.role!==void 0?oF(t,e.text,e.role):sF(t,e.text,e)}async function oF(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 Xd(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function sF(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await eF(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 b=await wb(h.locator,h.index);if(b!==null){let w=`${b.role}:${b.label}:${g}`,k=0;for(let v=0;v<w.length;v++)k=k*31+w.charCodeAt(v)>>>0;f.push({...b,id:`el_${k.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Sb=re(()=>{"use strict"});async function Jd(t,e,n,r){let o=t.url();if(o===n)return null;let s=Ye(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 kb=re(()=>{"use strict";Ut()});var Yd={};As(Yd,{PlaywrightProvider:()=>Vd});function vb(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 Vd,Qd=re(()=>{"use strict";fb();bb();Sb();Ut();kb();jd();Vd=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new $i(e)}async open(e){let n=Ye(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 c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await Jd(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 Bi(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 Bi(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 zd(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${vb(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){l=h}else l=g}let u=await Jd(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Bi(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),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await zd(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${vb(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 Kn(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Kn(n,o,r);return s}catch{return null}}}});var mn={};As(mn,{__resetBrowserRegistryForTests:()=>uF,browserProviderActive:()=>cF,closeBrowserProvider:()=>eu,getBrowserProvider:()=>aF,getLastRoutingDecision:()=>dF,peekBrowserProvider:()=>lF});function Tb(){Promise.resolve(eu()).then(()=>{process.exit(130)})}function _b(){Promise.resolve(eu()).then(()=>{process.exit(143)})}function Eb(){rt=null}function iF(){ji||(process.on("SIGINT",Tb),process.on("SIGTERM",_b),process.on("exit",Eb),ji=!0)}function Ab(){ji&&(process.removeListener("SIGINT",Tb),process.removeListener("SIGTERM",_b),process.removeListener("exit",Eb),ji=!1)}async function aF(t){return rt!==null?rt:(fn!==null||(fn=(async()=>{let e=Nd(t),n=t?.surface??(t?.env??{}).AGENT_SURFACE??y.AGENT_SURFACE,r=await Qy({config:e,surface:n});Zd=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:s}=await Promise.resolve().then(()=>(lb(),cb)),i=r.availability.connection;o=new s(e,i)}else{let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(Qd(),Yd));o=new s(e)}return iF(),rt=o,fn=null,o})()),fn)}async function eu(){if(rt===null)return;let t=rt;rt=null,fn=null,Ab(),await t.shutdown()}function cF(){return rt!==null}function lF(){return rt}function dF(){return Zd}function uF(){rt=null,fn=null,Zd=null,Ab()}var rt,fn,ji,Zd,gn=re(()=>{"use strict";Ut();Zy();C();rt=null,fn=null,ji=!1,Zd=null});J();C();M();import{randomBytes as CR}from"node:crypto";import{mkdir as PR,writeFile as MR}from"node:fs/promises";import{join as OR}from"node:path";J();var hR=256,mm=new WeakMap,Lr=new Map;function yR(t){return t instanceof Error?t.message:String(t)}function bR(t,e){if(typeof e=="object"&&e!==null){let r=mm.get(e);return r||(r=new Set,mm.set(e,r)),r.has(t)?!1:(r.add(t),!0)}let n=`${t}\0${String(e)}`;if(Lr.has(n))return!1;if(Lr.set(n,!0),Lr.size>hR){let r=Lr.keys().next().value;r!==void 0&&Lr.delete(r)}return!0}function fe(t,e,n,r){try{let o=`[afk] ${t} artifact write failed (${n}): ${yR(r)}`;if(!bR(t,e)){P(o);return}console.error(`${o} \u2014 further failures in this subsystem for this session are logged only under AFK_DEBUG=1.`)}catch{}}C();import{mkdirSync as SR,appendFileSync as kR,existsSync as vR}from"fs";import{resolve as TR}from"path";import{dirname as _R}from"path";function xt(t){return t.replace(/\bauthorization:\s*bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]").replace(/\bsk-ant-[A-Za-z0-9_-]{20,}/g,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,"[REDACTED]").replace(/\b(?:AKIA|ASIA|AROA|AIDA|AGPA|AIPA|ANPA|ANVA|APKA|ABIA|ACCA)[A-Z0-9]{16}\b/g,"[REDACTED]").replace(/(?<![/.\w])[A-Za-z0-9+/=_-]{32,}(?![/.\w])/g,e=>Al(e)||wR(e)?e:"[REDACTED]")}function Al(t){if(!t.includes("/")||/[+=]/.test(t))return!1;let e=n=>n.length>=32&&!n.includes(".")&&/[A-Za-z]/.test(n)&&/[0-9]/.test(n);return!t.split("/").some(e)}function wR(t){if(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(t))return!0;let e=/^([A-Za-z_][A-Za-z0-9_]*)=(?:[0-9a-f]{40}|[0-9a-f]{64})$/.exec(t);return e!==null&&/^(?:ref|sha|commit|base)$/i.test(e[1]??"")}var ER=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
|
|
4
|
+
${He(t,{headless:e,latched:n})}`,{cause:t})}var ub,BD,jD,db,WD,qd=re(()=>{"use strict";ub=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],BD="pnpm exec playwright install chromium",jD=4;WD="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 pn from"node:fs";import Ui from"node:path";import{randomBytes as KD}from"node:crypto";function GD(){try{return"5.176.2"}catch{}try{let t=Ui.resolve(import.meta.dirname,"../../../package.json"),e=pn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var qD,$i,fb=re(()=>{"use strict";qd();M();J();qD=GD(),$i=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=(async()=>{let e;try{({chromium:e}=await import("playwright"))}catch(n){let r=Ni(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await e.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=Ni(n,this.config.headless,!0);throw this.latchLaunchFailure(r),r}finally{this.launchPromise=void 0}})(),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${qD}`}}loadStorageState(e){let n=El(e);try{if(!pn.existsSync(n))return;let r=JSON.parse(pn.readFileSync(n,"utf8"));return P("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){P("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=El(e);if(!pn.existsSync(r))return;let o=await n.storageState(),s=Ui.join(Ui.dirname(r),`.${Ui.basename(r)}.${process.pid}.${KD(4).toString("hex")}.tmp`);pn.writeFileSync(s,JSON.stringify(o),{mode:384}),pn.chmodSync(s,384),pn.renameSync(s,r),P("[browser/vault] saved session",{profile:e,file:r})}catch(r){P("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as XD}from"node:crypto";function zD(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function JD(t,e,n){return`el_${XD("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function VD(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function mb(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function hb(t,e){let n=t.role??"",r=t.name??"";gb.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])hb(s,e)}async function YD(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},yb).catch(()=>[])}async function QD(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},yb).catch(()=>[])}function ZD(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Bi(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=ZD(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=YD(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,c,l,d]),h,b=!1;u!==null?(h=[],hb(u,h)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,h=(await QD(t)).filter(D=>gb.has(D.role??"")));let w=new Map;for(let A of p){let D=mb(A.name),q=w.get(D);(!q||q.bbox.w===0&&A.bbox.w>0)&&w.set(D,A)}let k=h.map(A=>({ax:A,dom:w.get(mb(A.name??""))})),v=r?k:k.filter(A=>A.dom?A.dom.bbox.w>0||A.dom.bbox.h>0:!0);v.sort((A,D)=>{let q=A.dom?.bbox.y??0,F=D.dom?.bbox.y??0;if(q!==F)return q-F;let N=A.dom?.bbox.x??0,O=D.dom?.bbox.x??0;return N-O}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=v.slice(0,n).map((A,D)=>{let q=A.ax.role??"generic",F=A.ax.name??"",N=JD(q,F,D),O=A.dom?.bbox??{x:0,y:0,w:0,h:0},U=A.dom?.type??null,G=null;A.ax.value!==void 0&&A.ax.value!==null&&(G=String(A.ax.value)),A.ax.checked!==void 0&&(G=String(A.ax.checked)),eb({role:q,kind:U})&&(G="[redacted]");let H={disabled:A.ax.disabled??!1};A.ax.checked!==void 0&&(H.checked=A.ax.checked===!0||A.ax.checked==="mixed"),A.ax.selected!==void 0&&(H.selected=A.ax.selected),A.ax.expanded!==void 0&&(H.expanded=A.ax.expanded);let le;A.dom?.testId?le=`[data-testid="${A.dom.testId}"]`:A.dom?.id&&(le=`#${A.dom.id}`);let dt={id:N,role:q,label:zD(F),kind:U,value:G,state:H,bbox:O};return le!==void 0&&(dt.selector=le),dt}),x="idle";try{let A=await t.evaluate(()=>document.readyState);A==="loading"?x="loading":A==="interactive"?x="navigating":x="idle"}catch{x="navigating"}x!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=VD(f),S=`obs_${e.observationCounter.toString(36)}`,_=new Date().toISOString();return{observationId:S,url:m,title:g,textSummary:I,interactive:T,status:{httpStatus:e.httpStatus??null,loadingState:x,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:_}}var gb,yb,bb=re(()=>{"use strict";Fi();gb=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);yb="a[href], button, input, select, textarea, [role], [tabindex], label"});async function wb(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Xd(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>wb(t,s)))).filter(o=>o!==null)}async function eF(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function zd(t,e,n){switch(e.kind){case"element_id":return tF(t,e,n);case"selector":return nF(t,e);case"semantic":return rF(t,e)}}async function tF(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Xd(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function nF(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 Xd(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function rF(t,e){return e.role!==void 0?oF(t,e.text,e.role):sF(t,e.text,e)}async function oF(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 Xd(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function sF(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await eF(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 b=await wb(h.locator,h.index);if(b!==null){let w=`${b.role}:${b.label}:${g}`,k=0;for(let v=0;v<w.length;v++)k=k*31+w.charCodeAt(v)>>>0;f.push({...b,id:`el_${k.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Sb=re(()=>{"use strict"});async function Jd(t,e,n,r){let o=t.url();if(o===n)return null;let s=Ye(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 kb=re(()=>{"use strict";Ut()});var Yd={};As(Yd,{PlaywrightProvider:()=>Vd});function vb(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 Vd,Qd=re(()=>{"use strict";fb();bb();Sb();Ut();kb();jd();Vd=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new $i(e)}async open(e){let n=Ye(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 c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await Jd(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 Bi(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 Bi(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 zd(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${vb(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){l=h}else l=g}let u=await Jd(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Bi(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),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await zd(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${vb(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 Kn(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Kn(n,o,r);return s}catch{return null}}}});var mn={};As(mn,{__resetBrowserRegistryForTests:()=>uF,browserProviderActive:()=>cF,closeBrowserProvider:()=>eu,getBrowserProvider:()=>aF,getLastRoutingDecision:()=>dF,peekBrowserProvider:()=>lF});function Tb(){Promise.resolve(eu()).then(()=>{process.exit(130)})}function _b(){Promise.resolve(eu()).then(()=>{process.exit(143)})}function Eb(){rt=null}function iF(){ji||(process.on("SIGINT",Tb),process.on("SIGTERM",_b),process.on("exit",Eb),ji=!0)}function Ab(){ji&&(process.removeListener("SIGINT",Tb),process.removeListener("SIGTERM",_b),process.removeListener("exit",Eb),ji=!1)}async function aF(t){return rt!==null?rt:(fn!==null||(fn=(async()=>{let e=Nd(t),n=t?.surface??(t?.env??{}).AGENT_SURFACE??y.AGENT_SURFACE,r=await Qy({config:e,surface:n});Zd=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:s}=await Promise.resolve().then(()=>(lb(),cb)),i=r.availability.connection;o=new s(e,i)}else{let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(Qd(),Yd));o=new s(e)}return iF(),rt=o,fn=null,o})()),fn)}async function eu(){if(rt===null)return;let t=rt;rt=null,fn=null,Ab(),await t.shutdown()}function cF(){return rt!==null}function lF(){return rt}function dF(){return Zd}function uF(){rt=null,fn=null,Zd=null,Ab()}var rt,fn,ji,Zd,gn=re(()=>{"use strict";Ut();Zy();C();rt=null,fn=null,ji=!1,Zd=null});J();C();M();import{randomBytes as CR}from"node:crypto";import{mkdir as PR,writeFile as MR}from"node:fs/promises";import{join as OR}from"node:path";J();var hR=256,mm=new WeakMap,Lr=new Map;function yR(t){return t instanceof Error?t.message:String(t)}function bR(t,e){if(typeof e=="object"&&e!==null){let r=mm.get(e);return r||(r=new Set,mm.set(e,r)),r.has(t)?!1:(r.add(t),!0)}let n=`${t}\0${String(e)}`;if(Lr.has(n))return!1;if(Lr.set(n,!0),Lr.size>hR){let r=Lr.keys().next().value;r!==void 0&&Lr.delete(r)}return!0}function fe(t,e,n,r){try{let o=`[afk] ${t} artifact write failed (${n}): ${yR(r)}`;if(!bR(t,e)){P(o);return}console.error(`${o} \u2014 further failures in this subsystem for this session are logged only under AFK_DEBUG=1.`)}catch{}}C();import{mkdirSync as SR,appendFileSync as kR,existsSync as vR}from"fs";import{resolve as TR}from"path";import{dirname as _R}from"path";function xt(t){return t.replace(/\bauthorization:\s*bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]").replace(/\bsk-ant-[A-Za-z0-9_-]{20,}/g,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,"[REDACTED]").replace(/\b(?:AKIA|ASIA|AROA|AIDA|AGPA|AIPA|ANPA|ANVA|APKA|ABIA|ACCA)[A-Z0-9]{16}\b/g,"[REDACTED]").replace(/(?<![/.\w])[A-Za-z0-9+/=_-]{32,}(?![/.\w])/g,e=>Al(e)||wR(e)?e:"[REDACTED]")}function Al(t){if(!t.includes("/")||/[+=]/.test(t))return!1;let e=n=>n.length>=32&&!n.includes(".")&&/[A-Za-z]/.test(n)&&/[0-9]/.test(n);return!t.split("/").some(e)}function wR(t){if(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(t))return!0;let e=/^([A-Za-z_][A-Za-z0-9_]*)=(?:[0-9a-f]{40}|[0-9a-f]{64})$/.exec(t);return e!==null&&/^(?:ref|sha|commit|base)$/i.test(e[1]??"")}var ER=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
|
|
5
5
|
`,AR=/key|token|secret|password|credential|auth/i;function gm(t){let e=t[1],n=t[2],r=n[0],o=(r==='"'||r==="'")&&n.at(-1)===r?n.slice(1,-1):n,s=/(?:^|_)(?:PATH|FILE)(?:_|$)/i.test(e),i=o.startsWith("/")||o.startsWith("~/"),c=o.split("/").filter(Boolean).some(l=>/[A-Z0-9.\-]/.test(l));return s&&i&&c&&Al(o)?`${e}=${n}`:`${e}=<REDACTED length=${n.length}>`}var xR=[[/sk-ant-[A-Za-z0-9_\-]{8,200}/g,t=>`<REDACTED sk-ant length=${t[0].length}>`],[/sk-(?!ant-)[A-Za-z0-9_\-]{20,200}/g,t=>`<REDACTED sk- length=${t[0].length}>`],[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,t=>`<REDACTED Bearer length=${t[0].length}>`],[/AKIA[A-Z0-9]{16}/g,t=>`<REDACTED AKIA length=${t[0].length}>`],[/xox[baprs]-[A-Za-z0-9\-]{10,200}/g,t=>`<REDACTED xox token length=${t[0].length}>`],[/\d{8,12}:[A-Za-z0-9_\-]{35}/g,t=>`<REDACTED Telegram token length=${t[0].length}>`],[/([A-Za-z_]{3,}(?:[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]|[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll])[A-Za-z_]*)=([^\s]{16,})/g,gm],[/([A-Z_]{3,}(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=([^\s]{16,})/g,gm]];function Nr(t){let e=t;for(let[n,r]of xR)e=e.replace(n,(...o)=>{let s=o.slice(0,o.length-2);return r(s)});return e}function xl(t){return typeof t=="string"?Nr(t):Array.isArray(t)?t.map(xl):t}function RR(t){if(t===null||typeof t!="object")return t;let e=t,n={...e},r=e.env;if(r&&typeof r=="object"){let o={};for(let[s,i]of Object.entries(r))AR.test(s)&&typeof i=="string"?o[s]=`<REDACTED length=${i.length}>`:o[s]=i;n.env=o}return"system"in e&&(n.system=xl(e.system)),"systemPrompt"in e&&(n.systemPrompt=xl(e.systemPrompt)),n}function IR(t){if(t==null)return{kind:"undefined",note:"SDK uses minimal prompt; claude_code preset NOT loaded"};if(typeof t=="string")return{kind:"custom-string",note:"SDK uses this string as full system prompt; claude_code preset NOT loaded"};if(Array.isArray(t))return{kind:"custom-string-array",note:"SDK uses array as full system prompt with cache boundaries; claude_code preset NOT loaded"};if(typeof t=="object"){let e=t;if(e.type==="preset"&&e.preset==="claude_code"){let n={kind:"preset-claude-code",note:"claude_code preset loaded"};return typeof e.append=="string"&&(n.append={length:e.append.length}),e.excludeDynamicSections===!0&&(n.excludeDynamicSections=!0),n}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}function hm(t){let e=y.AFK_DUMP_PROMPT;if(!e||e===""||e==="0"||e.toLowerCase()==="false")return;process.stderr.write(`[--dump-prompt] WARNING: dump may contain secrets from system prompt or messages. Inspect before sharing.
|
|
6
6
|
`);let n=t.options,r=typeof n=="object"&&n!==null?n.systemPrompt:void 0,o=IR(r),s={timestamp:new Date().toISOString(),prompt:t.prompt,options:RR(t.options),provenance:t.provenance,resolution:o};if(e==="1"||e.toLowerCase()==="true"||e.toLowerCase()==="stderr"){let c=JSON.stringify(s,null,2)+`
|
|
7
7
|
`;process.stderr.write(c);return}let i=TR(e),a=_R(i);try{SR(a,{recursive:!0});let l=(!vR(i)?ER:"")+JSON.stringify(s)+`
|
package/dist/telegram.mjs
CHANGED
|
@@ -315,7 +315,7 @@ ${o}`,paths:[e,n]}:o!==null?s={content:o,paths:[n]}:r!==null?s={content:r,paths:
|
|
|
315
315
|
|
|
316
316
|
${e}`}var e2,$g=g(()=>{"use strict";e2=new Set(["script","style","noscript","template","svg"])});function r2(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 zE(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function o2(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 VE(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??r2,c=n.signal??void 0,l;for(let d=0;d<=o;d++){if(c?.aborted)throw c.reason??new Error("aborted");try{let u=await t(e,n);if(!n2.has(u.status)||d===o)return u;let p=o2(u,i)??zE(d,s,i);O("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,c)}catch(u){if(c?.aborted||(l=u,d===o))throw u;let p=zE(d,s,i);O("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,c)}}throw l??new Error("retryFetch: exhausted without a result")}var n2,JE=g(()=>{"use strict";ie();n2=new Set([429,502,503,504])});import{BlockList as s2,isIP as Bg}from"node:net";import{lookup as i2}from"node:dns/promises";import{Agent as a2}from"undici";function QE(){let t=k.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return t==="1"||t==="true"}function u2(t){return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Ug(t){let e=Bg(t);return e===0?!1:d2.check(t,e===4?"ipv4":"ipv6")}async function ZE(t){return i2(t,{all:!0,verbatim:!0})}async function kr(t,e={}){if(e.allowPrivateHosts??QE())return{allowed:!0};let n;try{n=new URL(t)}catch{return{allowed:!1,reason:`"${t}" is not a valid absolute URL`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{allowed:!1,reason:`protocol "${n.protocol}" not supported (http/https only)`};let r=u2(n.hostname),o=(a,c)=>`refusing to fetch ${c} \u2014 internal/private address ${a} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`;if(Bg(r)!==0)return Ug(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let s=e.lookupFn??ZE,i;try{i=await s(r)}catch{return{allowed:!0}}for(let a of i)if(Ug(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function Pi(t,e={}){let n=await kr(t,e);if(!n.allowed)throw new Ie(n.reason)}async function Rn(t,e,n={},r={}){let o={...r.lookupFn!==void 0?{lookupFn:r.lookupFn}:{},...r.allowPrivateHosts!==void 0?{allowPrivateHosts:r.allowPrivateHosts}:{}},s=e;for(let i=0;i<=YE;i++){await Pi(s,o);let a={...n,redirect:"manual",...t===globalThis.fetch&&!(r.allowPrivateHosts??QE())?{dispatcher:p2}:{}},c=await VE(t,s,a,r.retry??{});if(!f2.has(c.status))return c;let l=c.headers.get("location");if(l===null||l.trim()==="")return c;let d;try{d=new URL(l,c.url||s).toString()}catch{return c}await c.body?.cancel().catch(()=>{}),s=d}throw new Ie(`too many redirects (>${YE}) starting from ${e}`)}var c2,l2,d2,Ie,p2,YE,f2,vr=g(()=>{"use strict";L();JE();c2=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.168.0.0",16]],l2=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],d2=(()=>{let t=new s2;for(let[e,n]of c2)t.addSubnet(e,n,"ipv4");for(let[e,n]of l2)t.addSubnet(e,n,"ipv6");return t})(),Ie=class extends Error{constructor(e){super(e),this.name="EgressBlockedError"}};p2=new a2({connect:{lookup(t,e,n){ZE(t).then(r=>{let o=r.find(i=>Ug(i.address));if(o!==void 0){n(new Ie(`refusing to connect to ${t} (resolved) \u2014 internal/private address ${o.address} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`),"",0);return}let s=r[0];if(s===void 0){n(new Error(`DNS lookup returned no addresses for ${t}`),"",0);return}n(null,s.address,Bg(s.address))},r=>n(r,"",0))}}});YE=20,f2=new Set([301,302,303,307,308])});var Hg={};Ms(Hg,{enforceDomainPolicy:()=>_t,loadBrowserConfig:()=>jg});import{readFileSync as m2}from"node:fs";import{join as g2}from"path";function h2(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function eA(t,e){return h2(e).test(t)}function w2(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(y2.has(e))return!0;if(b2.has(e))return!1}return!1}function tA(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function S2(t){if(t===void 0||t==="")return"auto";if(t==="playwright"||t==="agent-browser"||t==="auto")return t;throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${t}`)}function nA(t){let e=t===void 0||t.trim()===""?"default":t.trim();return jf(e),e}function k2(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function v2(t){try{return m2(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function T2(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"||e.backend==="agent-browser"||e.backend==="auto")n.backend=e.backend;else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=nA(e.defaultProfile)),n}function jg(t){let e=t?.env??k,n=t?.readFileSync??v2,r=t?.surface??e.AGENT_SURFACE,o=w2(e.AFK_BROWSER_HEADLESS,r),s=tA(e.AFK_BROWSER_ALLOWED_DOMAINS),i=tA(e.AFK_BROWSER_BLOCKED_DOMAINS),a=k2(e.AFK_BROWSER_DOM_SNAPSHOTS),c=S2(e.AFK_BROWSER_BACKEND),l=nA(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():g2(Yt(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${p}: ${String(y)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let h=T2(d,m);return h.configPath=p,h}function _t(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(eA(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>eA(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var y2,b2,In=g(()=>{"use strict";L();j();y2=new Set(["daemon","subagent","telegram","afk"]),b2=new Set(["repl","interactive","cli"])});import{readFileSync as _2}from"node:fs";import{join as E2}from"node:path";import{homedir as A2}from"node:os";function R2(t){let e=t??x2,n;try{n=_2(e,"utf8")}catch{return null}let r;try{r=JSON.parse(n)}catch{return null}if(typeof r!="object"||r===null||Array.isArray(r))return null;let o=r;if(typeof o.url!="string"||typeof o.token!="string"||typeof o.pid!="number")return null;let s;try{s=new URL(o.url)}catch{return null}let{hostname:i,protocol:a}=s;if(!(i==="127.0.0.1"||i==="localhost"||i==="::1")||a!=="http:")throw new Error(`Agent Browser connection file contains an untrusted URL: ${o.url}. Only http://127.0.0.1 or http://localhost is permitted.`);return{url:o.url,token:o.token,pid:o.pid,version:typeof o.version=="string"?o.version:"unknown"}}function I2(t){try{return process.kill(t,0),!0}catch{return!1}}async function C2(t,e,n=2e3){try{let r=new AbortController,o=setTimeout(()=>r.abort(),n),s=await fetch(`${t}/health`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Host:"127.0.0.1:8833"},signal:r.signal});return clearTimeout(o),s.ok}catch{return!1}}async function Wg(t){let e=R2(t);return e===null?{available:!1,connection:null,reason:"connection file missing or invalid"}:I2(e.pid)?await C2(e.url,e.token)?{available:!0,connection:e,reason:null}:{available:!1,connection:e,reason:`health probe failed at ${e.url}`}:{available:!1,connection:e,reason:`stale connection file: PID ${e.pid} not alive`}}var x2,rA=g(()=>{"use strict";x2=E2(A2(),".config","agent-browser","connection.json")});async function oA(t){let{config:e,surface:n}=t;if(e.backend==="playwright")return{backend:"playwright",reason:"explicit config: backend=playwright",probeMs:0,availability:null};if(e.backend==="agent-browser"){let i=Date.now(),a=await Wg(),c=Date.now()-i;if(!a.available)throw new Error(`AFK_BROWSER_BACKEND=agent-browser but Agent Browser is not available: ${a.reason}`);return{backend:"agent-browser",reason:"explicit config: backend=agent-browser",probeMs:c,availability:a}}if(n&&P2.has(n))return{backend:"playwright",reason:`auto: surface "${n}" excluded from Agent Browser`,probeMs:0,availability:null};if(e.headless)return{backend:"playwright",reason:"auto: headless mode requires Playwright",probeMs:0,availability:null};let r=Date.now(),o=await Wg(),s=Date.now()-r;return o.available?{backend:"agent-browser",reason:"auto: Agent Browser available and preferred",probeMs:s,availability:o}:{backend:"playwright",reason:`auto: Agent Browser unavailable (${o.reason})`,probeMs:s,availability:o}}var P2,sA=g(()=>{"use strict";rA();P2=new Set(["daemon","subagent"])});import{createHash as M2}from"crypto";function iA(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&O2.test(t.label))}function aA(t){return M2("sha256").update(t,"utf8").digest("hex").slice(0,8)}function cA(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var O2,Vl=g(()=>{"use strict";O2=/password|secret|token|api[_-]?key|otp|2fa/i});import{randomBytes as D2}from"crypto";import{mkdir as F2,stat as L2,writeFile as N2}from"fs/promises";import{join as Kg}from"path";import{gzip as $2}from"zlib";import{promisify as U2}from"util";function B2(t){return Kg(Pt(t),"browser")}function j2(t){return Kg(B2(t),"screenshots")}function H2(){return new Date().toISOString().replace(/[:.]/g,"-")}function W2(){return D2(3).toString("hex")}async function xo(t,e,n){if(e.length>lA)throw new Error(`writeScreenshotSidecar: buffer exceeds ${lA} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=j2(t);await F2(r,{recursive:!0});let o=`${H2()}-${W2()}-${n}.png`,s=Kg(r,o);await N2(s,e);let{size:i}=await L2(s);return{path:s,bytes:i}}var Ppe,lA,Gg=g(()=>{"use strict";j();Vl();Ppe=U2($2);lA=5*1024*1024});var Jl,dA=g(()=>{"use strict";Jl=class{baseUrl;token;constructor(e){this.baseUrl=e.url,this.token=e.token}async call(e,n,r=3e4){let o={version:1,method:e,params:n},s=new AbortController,i=setTimeout(()=>s.abort(),r);try{let a=await fetch(`${this.baseUrl}/agent`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,Host:new URL(this.baseUrl).host},body:JSON.stringify(o),signal:s.signal});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Agent Browser ${e} failed (HTTP ${a.status}): ${c}`)}return await a.json()}finally{clearTimeout(i)}}async listTabs(){return(await this.call("tabs.list",null)).tabs}async openTab(e){return{tabId:(await this.call("tabs.open",{url:e},6e4)).tab_id}}async closeTab(e){await this.call("tabs.close",{tab_id:e})}async read(e,n){return this.call("page.read",{tab_id:e,mode:n?.mode??"main",...n?.query?{query:n.query}:{},...n?.budget?{budget:n.budget}:{}})}async inspect(e,n){return this.call("page.inspect",{tab_id:e,mode:n?.mode??"interactive",...n?.query?{query:n.query}:{},...n?.limit?{limit:n.limit}:{}})}async click(e,n){await this.call("page.click",{tab_id:e,element_id:n})}async fill(e,n,r){await this.call("page.fill",{tab_id:e,element_id:n,value:r})}async press(e,n,r){await this.call("page.press",{tab_id:e,key:n,...r?{element_id:r}:{}})}async select(e,n,r){await this.call("page.select",{tab_id:e,element_id:n,value:r})}async waitFor(e,n,r){await this.call("page.wait",{tab_id:e,condition:n,...r?.value?{value:r.value}:{},...r?.timeout?{timeout:r.timeout}:{}},(r?.timeout??3e4)+5e3)}async evalScript(e,n){return this.call("page.eval",{tab_id:e,script:n})}async screenshot(e){return this.call("page.screenshot",{tab_id:e})}}});function qg(t){return{id:t.id,role:t.role,label:t.label,kind:t.kind,value:t.value,state:{disabled:t.disabled,...t.checked!==void 0?{checked:t.checked}:{},...t.selected!==void 0?{selected:t.selected}:{},...t.expanded!==void 0?{expanded:t.expanded}:{}},bbox:t.bbox,...t.selector?{selector:t.selector}:{}}}function uA(t,e){switch(e.kind){case"element_id":if(t.has(e.elementId))return e.elementId;throw new Error(`Element ${e.elementId} not found in current observation. Call browser_observe to refresh.`);case"selector":return null;case"semantic":return null}}async function Xg(t,e,n,r,o,s){switch(n){case"click":await t.click(e,r);break;case"fill":if(o===void 0)throw new Error("fill requires a value");await t.fill(e,r,o);break;case"press":if(o===void 0)throw new Error("press requires a value (key combo)");await t.press(e,o,r);break;case"select":if(o===void 0)throw new Error("select requires a value");await t.select(e,r,o);break;case"hover":throw new Error("hover is not supported by Agent Browser; use element_id from a prior observation to target clicks instead");case"scroll_to":{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');await t.evalScript(e,`document.querySelector('[data-element-id="${i}"]')?.scrollIntoView({behavior:'smooth',block:'center'})`);break}case"wait_for":await t.waitFor(e,"element",{value:r,timeout:s??1e4});break;default:throw new Error(`Unknown action: ${n}`)}}async function pA(t,e){if(e.target.kind!=="semantic")throw new Error("resolveSemanticAndAct called with non-semantic target");let{elements:n}=await t.client.inspect(t.tabId,{mode:"interactive",query:e.target.text,limit:10}),r=n;if(e.target.role){let c=e.target.role.toLowerCase();r=n.filter(l=>l.role.toLowerCase()===c)}if(r.length===0)throw new Error(`No element found matching semantic target: text="${e.target.text}"`+(e.target.role?`, role="${e.target.role}"`:""));if(r.length>1)return{outcome:"ambiguous_target",query:{text:e.target.text,...e.target.role?{role:e.target.role}:{}},candidates:r.slice(0,5).map(qg)};let s=r[0].id;await Xg(t.client,t.tabId,e.action,s,e.value,e.timeoutMs);let i=await t.client.read(t.tabId,{mode:"main"}),a=_t(i.url,t.config);return a.allowed?{elementId:s}:{outcome:"blocked_by_policy",url:i.url,reason:`action navigated to blocked domain: ${a.reason}`}}var fA=g(()=>{"use strict";In()});var mA={};Ms(mA,{AgentBrowserProvider:()=>zg});var zg,gA=g(()=>{"use strict";In();Gg();dA();fA();zg=class{name="agent-browser";config;client;sessions=new Map;constructor(e,n){this.config=e,this.client=new Jl(n)}async open(e){let n=_t(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let r=this.sessions.get(e.sessionId);if(r)await this.client.evalScript(r.tabId,`window.location.href = ${JSON.stringify(e.url)}`),await this.client.waitFor(r.tabId,"load",{timeout:e.timeoutMs??3e4});else{let{tabId:i}=await this.client.openTab(e.url);await this.client.waitFor(i,"load",{timeout:e.timeoutMs??3e4}),r={tabId:i,observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null},this.sessions.set(e.sessionId,r)}let o=await this.client.read(r.tabId,{mode:"main"}),s=_t(o.url,this.config);return s.allowed?this.buildObservation(r,e.sessionId,e.screenshot,void 0,"browser_open"):(await this.client.evalScript(r.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`redirected to blocked domain: ${s.reason}`})}async observe(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);return this.buildObservation(n,e.sessionId,e.screenshot,e.maxElements,"browser_observe")}async act(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);let r=uA(n.knownElements,e.target);if(r===null){if(e.target.kind==="semantic"){let i=await pA({client:this.client,config:this.config,tabId:n.tabId},e);return"outcome"in i?i:(n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString(),this.buildObservation(n,e.sessionId,e.screenshot,void 0,"browser_act"))}throw e.target.kind==="selector"?new Error("selector targets are not supported by Agent Browser; use element_id or semantic targets"):new Error(`Cannot resolve target: ${JSON.stringify(e.target)}`)}await Xg(this.client,n.tabId,e.action,r,e.value,e.timeoutMs),n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString();let o=await this.client.read(n.tabId,{mode:"main"}),s=_t(o.url,this.config);return s.allowed?this.buildObservation(n,e.sessionId,e.screenshot,void 0,"browser_act"):(await this.client.evalScript(n.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`action navigated to blocked domain: ${s.reason}`})}async render(e){throw new Error("AgentBrowserProvider does not support render(). Use PlaywrightProvider for one-shot content fetches.")}async screenshot(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);if(e.target!==void 0||e.fullPage)throw new Error("Agent Browser does not support element or full-page screenshots; omit target and fullPage.");let r=await this.client.screenshot(n.tabId),o=Buffer.from(r.data,"base64"),s=o.length>=24?o.readUInt32BE(16):0,i=o.length>=24?o.readUInt32BE(20):0;return{path:(await xo(e.sessionId,o,"browser_screenshot")).path,bytes:o.length,width:s,height:i,dataBase64:r.data,mediaType:"image/png"}}async extract(e){throw new Error("AgentBrowserProvider does not support extract() yet.")}async close(e){let n=this.sessions.get(e.sessionId);if(n){try{await this.client.closeTab(n.tabId)}catch{}this.sessions.delete(e.sessionId)}}describe(e){let n=this.sessions.get(e);return n?{active:!0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:1}:null}async shutdown(){let e=Array.from(this.sessions.entries()).map(async([,n])=>{try{await this.client.closeTab(n.tabId)}catch{}});await Promise.all(e),this.sessions.clear()}async buildObservation(e,n,r,o,s="browser_open"){let[i,a]=await Promise.all([this.client.read(e.tabId,{mode:"main",budget:4e3}),this.client.inspect(e.tabId,{mode:"interactive",limit:o??80})]),c=a.elements.map(qg),l=o??80,d=c.slice(0,l);e.observationCounter+=1,e.knownElements=new Map(d.map(h=>[h.id,h])),e.currentUrl=i.url,e.currentTitle=i.title;let u=[];c.length>l&&u.push(`page has ${c.length} interactive elements; showing first ${l}`);let p=null;if(r)try{let h=await this.client.screenshot(e.tabId),y=Buffer.from(h.data,"base64");p=(await xo(n,y,s)).path}catch{u.push("screenshot capture failed")}let f=`obs_${e.observationCounter.toString(36)}`,m={httpStatus:null,loadingState:"idle",hasDialog:!1,consoleErrors:0};return{observationId:f,url:i.url,title:i.title,textSummary:i.content.slice(0,4e3),interactive:d,status:m,warnings:u,screenshotPath:p,capturedAt:new Date().toISOString()}}}});import{existsSync as K2,readFileSync as G2}from"node:fs";import{createRequire as q2}from"node:module";import{dirname as X2,join as z2}from"node:path";function bA(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<J2&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function Ge(t){let e=bA(t);return yA.some(n=>e.includes(n))}function Y2(){try{let e=q2(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(G2(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=z2(X2(e),o);return K2(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function Mi(){return hA??=Y2()??V2,hA}function Vg(t){return t.includes("install chromium")}function ut(t,e){let n=bA(t),r=e?.latched===!0?` ${Q2}`:"";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: ${Mi()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${Mi()}). Or pick a different tool.${r}`}function Yl(t,e,n=!1){if(!Ge(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
317
317
|
|
|
318
|
-
${ut(t,{headless:e,latched:n})}`,{cause:t})}var yA,V2,J2,hA,Q2,Jg=g(()=>{"use strict";yA=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],V2="pnpm exec playwright install chromium",J2=4;Q2="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 Tr from"node:fs";import Ql from"node:path";import{randomBytes as Z2}from"node:crypto";function eX(){try{return"5.176.0"}catch{}try{let t=Ql.resolve(import.meta.dirname,"../../../package.json"),e=Tr.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var tX,Zl,wA=g(()=>{"use strict";Jg();j();ie();tX=eX(),Zl=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=(async()=>{let e;try{({chromium:e}=await import("playwright"))}catch(n){let r=Yl(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await e.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=Yl(n,this.config.headless,!0);throw this.latchLaunchFailure(r),r}finally{this.launchPromise=void 0}})(),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${tX}`}}loadStorageState(e){let n=Hf(e);try{if(!Tr.existsSync(n))return;let r=JSON.parse(Tr.readFileSync(n,"utf8"));return O("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){O("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Hf(e);if(!Tr.existsSync(r))return;let o=await n.storageState(),s=Ql.join(Ql.dirname(r),`.${Ql.basename(r)}.${process.pid}.${Z2(4).toString("hex")}.tmp`);Tr.writeFileSync(s,JSON.stringify(o),{mode:384}),Tr.chmodSync(s,384),Tr.renameSync(s,r),O("[browser/vault] saved session",{profile:e,file:r})}catch(r){O("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as nX}from"node:crypto";function rX(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function oX(t,e,n){return`el_${nX("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function sX(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function SA(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function vA(t,e){let n=t.role??"",r=t.name??"";kA.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])vA(s,e)}async function iX(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},TA).catch(()=>[])}async function aX(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let h=s.type;h==="checkbox"?l="checkbox":h==="radio"?l="radio":h==="button"||h==="submit"||h==="reset"?l="button":h==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},TA).catch(()=>[])}function cX(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function ed(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=cX(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=iX(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,h]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],vA(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await aX(t)).filter(P=>kA.has(P.role??"")));let v=new Map;for(let C of p){let P=SA(C.name),G=v.get(P);(!G||G.bbox.w===0&&C.bbox.w>0)&&v.set(P,C)}let T=y.map(C=>({ax:C,dom:v.get(SA(C.name??""))})),_=r?T:T.filter(C=>C.dom?C.dom.bbox.w>0||C.dom.bbox.h>0:!0);_.sort((C,P)=>{let G=C.dom?.bbox.y??0,M=P.dom?.bbox.y??0;if(G!==M)return G-M;let U=C.dom?.bbox.x??0,D=P.dom?.bbox.x??0;return U-D}),_.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=_.slice(0,n).map((C,P)=>{let G=C.ax.role??"generic",M=C.ax.name??"",U=oX(G,M,P),D=C.dom?.bbox??{x:0,y:0,w:0,h:0},N=C.dom?.type??null,B=null;C.ax.value!==void 0&&C.ax.value!==null&&(B=String(C.ax.value)),C.ax.checked!==void 0&&(B=String(C.ax.checked)),iA({role:G,kind:N})&&(B="[redacted]");let K={disabled:C.ax.disabled??!1};C.ax.checked!==void 0&&(K.checked=C.ax.checked===!0||C.ax.checked==="mixed"),C.ax.selected!==void 0&&(K.selected=C.ax.selected),C.ax.expanded!==void 0&&(K.expanded=C.ax.expanded);let Q;C.dom?.testId?Q=`[data-testid="${C.dom.testId}"]`:C.dom?.id&&(Q=`#${C.dom.id}`);let je={id:U,role:G,label:rX(M),kind:N,value:B,state:K,bbox:D};return Q!==void 0&&(je.selector=Q),je}),I="idle";try{let C=await t.evaluate(()=>document.readyState);C==="loading"?I="loading":C==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let R=sX(f),S=`obs_${e.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:S,url:m,title:h,textSummary:R,interactive:E,status:{httpStatus:e.httpStatus??null,loadingState:I,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:A}}var kA,TA,_A=g(()=>{"use strict";Vl();kA=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);TA="a[href], button, input, select, textarea, [role], [tabindex], label"});async function EA(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Yg(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>EA(t,s)))).filter(o=>o!==null)}async function lX(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Qg(t,e,n){switch(e.kind){case"element_id":return dX(t,e,n);case"selector":return uX(t,e);case"semantic":return pX(t,e)}}async function dX(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Yg(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function uX(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 Yg(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function pX(t,e){return e.role!==void 0?fX(t,e.text,e.role):mX(t,e.text,e)}async function fX(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 Yg(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function mX(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await lX(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=u.slice(0,5),f=[];for(let h=0;h<p.length;h++){let y=p[h];if(y===void 0)continue;let b=await EA(y.locator,y.index);if(b!==null){let v=`${b.role}:${b.label}:${h}`,T=0;for(let _=0;_<v.length;_++)T=T*31+v.charCodeAt(_)>>>0;f.push({...b,id:`el_${T.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var AA=g(()=>{"use strict"});async function Zg(t,e,n,r){let o=t.url();if(o===n)return null;let s=_t(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 xA=g(()=>{"use strict";In()});var th={};Ms(th,{PlaywrightProvider:()=>eh});function RA(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 eh,nh=g(()=>{"use strict";wA();_A();AA();In();xA();Gg();eh=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Zl(e)}async open(e){let n=_t(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 c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await Zg(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 ed(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 ed(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 Qg(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${RA(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(y){l=y}else l=h}let u=await Zg(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await ed(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),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Qg(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${RA(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 xo(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await xo(n,o,r);return s}catch{return null}}}});var Er={};Ms(Er,{__resetBrowserRegistryForTests:()=>SX,browserProviderActive:()=>yX,closeBrowserProvider:()=>oh,getBrowserProvider:()=>hX,getLastRoutingDecision:()=>wX,peekBrowserProvider:()=>bX});function IA(){Promise.resolve(oh()).then(()=>{process.exit(130)})}function CA(){Promise.resolve(oh()).then(()=>{process.exit(143)})}function PA(){Ht=null}function gX(){td||(process.on("SIGINT",IA),process.on("SIGTERM",CA),process.on("exit",PA),td=!0)}function MA(){td&&(process.removeListener("SIGINT",IA),process.removeListener("SIGTERM",CA),process.removeListener("exit",PA),td=!1)}async function hX(t){return Ht!==null?Ht:(_r!==null||(_r=(async()=>{let e=jg(t),n=t?.surface??(t?.env??{}).AGENT_SURFACE??k.AGENT_SURFACE,r=await oA({config:e,surface:n});rh=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:s}=await Promise.resolve().then(()=>(gA(),mA)),i=r.availability.connection;o=new s(e,i)}else{let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(nh(),th));o=new s(e)}return gX(),Ht=o,_r=null,o})()),_r)}async function oh(){if(Ht===null)return;let t=Ht;Ht=null,_r=null,MA(),await t.shutdown()}function yX(){return Ht!==null}function bX(){return Ht}function wX(){return rh}function SX(){Ht=null,_r=null,rh=null,MA()}var Ht,_r,td,rh,Ar=g(()=>{"use strict";In();sA();L();Ht=null,_r=null,td=!1,rh=null});async function OA(t,e){try{return await GE(t,e)}catch(n){return O("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function AX(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Ar(),Er)),r=await n();try{return await r.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}catch(o){if(r.name==="agent-browser"){let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(nh(),th)),{loadBrowserConfig:i}=await Promise.resolve().then(()=>(In(),Hg)),a=i(),c=new s(a);try{return await c.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}finally{await c.shutdown()}}throw o}}async function DA(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??AX,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,c=null,l=null;try{let u=await Rn(n,t,{headers:EX,signal:e.signal},o);c=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(_X.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await u.text();if(TX.test(p)&&!vX.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await OA(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof Ie||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;l=u}if(!(s===null||s.textLength<200)&&s!==null){let u=Ng({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await Pi(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>Pi(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await Pi(u.finalUrl,o);let p=await OA(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=Ng({html:u.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:u.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(u){if(e.signal.aborted||u instanceof Ie)throw u;if(s===null){let p=u instanceof Error?u.message:String(u),f=l instanceof Error?l.message:`HTTP ${c??"error"}`,m=new Error(`web_scrape could not retrieve ${t}: fetch failed (${f}) and render failed (${p}).`);throw m.cause=u,m}}if(s!==null)return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${c??"error"}).`)}var vX,TX,_X,EX,FA=g(()=>{"use strict";qE();$g();vr();ie();vX=/(text\/html|application\/xhtml\+xml)/i,TX=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,_X=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,EX={"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 IX(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(xX,{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),RX),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=Z(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function LA(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?IX({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 NA(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
318
|
+
${ut(t,{headless:e,latched:n})}`,{cause:t})}var yA,V2,J2,hA,Q2,Jg=g(()=>{"use strict";yA=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],V2="pnpm exec playwright install chromium",J2=4;Q2="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 Tr from"node:fs";import Ql from"node:path";import{randomBytes as Z2}from"node:crypto";function eX(){try{return"5.176.2"}catch{}try{let t=Ql.resolve(import.meta.dirname,"../../../package.json"),e=Tr.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var tX,Zl,wA=g(()=>{"use strict";Jg();j();ie();tX=eX(),Zl=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=(async()=>{let e;try{({chromium:e}=await import("playwright"))}catch(n){let r=Yl(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await e.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=Yl(n,this.config.headless,!0);throw this.latchLaunchFailure(r),r}finally{this.launchPromise=void 0}})(),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${tX}`}}loadStorageState(e){let n=Hf(e);try{if(!Tr.existsSync(n))return;let r=JSON.parse(Tr.readFileSync(n,"utf8"));return O("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){O("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Hf(e);if(!Tr.existsSync(r))return;let o=await n.storageState(),s=Ql.join(Ql.dirname(r),`.${Ql.basename(r)}.${process.pid}.${Z2(4).toString("hex")}.tmp`);Tr.writeFileSync(s,JSON.stringify(o),{mode:384}),Tr.chmodSync(s,384),Tr.renameSync(s,r),O("[browser/vault] saved session",{profile:e,file:r})}catch(r){O("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as nX}from"node:crypto";function rX(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function oX(t,e,n){return`el_${nX("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function sX(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function SA(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function vA(t,e){let n=t.role??"",r=t.name??"";kA.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])vA(s,e)}async function iX(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},TA).catch(()=>[])}async function aX(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let h=s.type;h==="checkbox"?l="checkbox":h==="radio"?l="radio":h==="button"||h==="submit"||h==="reset"?l="button":h==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},TA).catch(()=>[])}function cX(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function ed(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=cX(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=iX(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,h]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],vA(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await aX(t)).filter(P=>kA.has(P.role??"")));let v=new Map;for(let C of p){let P=SA(C.name),G=v.get(P);(!G||G.bbox.w===0&&C.bbox.w>0)&&v.set(P,C)}let T=y.map(C=>({ax:C,dom:v.get(SA(C.name??""))})),_=r?T:T.filter(C=>C.dom?C.dom.bbox.w>0||C.dom.bbox.h>0:!0);_.sort((C,P)=>{let G=C.dom?.bbox.y??0,M=P.dom?.bbox.y??0;if(G!==M)return G-M;let U=C.dom?.bbox.x??0,D=P.dom?.bbox.x??0;return U-D}),_.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=_.slice(0,n).map((C,P)=>{let G=C.ax.role??"generic",M=C.ax.name??"",U=oX(G,M,P),D=C.dom?.bbox??{x:0,y:0,w:0,h:0},N=C.dom?.type??null,B=null;C.ax.value!==void 0&&C.ax.value!==null&&(B=String(C.ax.value)),C.ax.checked!==void 0&&(B=String(C.ax.checked)),iA({role:G,kind:N})&&(B="[redacted]");let K={disabled:C.ax.disabled??!1};C.ax.checked!==void 0&&(K.checked=C.ax.checked===!0||C.ax.checked==="mixed"),C.ax.selected!==void 0&&(K.selected=C.ax.selected),C.ax.expanded!==void 0&&(K.expanded=C.ax.expanded);let Q;C.dom?.testId?Q=`[data-testid="${C.dom.testId}"]`:C.dom?.id&&(Q=`#${C.dom.id}`);let je={id:U,role:G,label:rX(M),kind:N,value:B,state:K,bbox:D};return Q!==void 0&&(je.selector=Q),je}),I="idle";try{let C=await t.evaluate(()=>document.readyState);C==="loading"?I="loading":C==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let R=sX(f),S=`obs_${e.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:S,url:m,title:h,textSummary:R,interactive:E,status:{httpStatus:e.httpStatus??null,loadingState:I,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:A}}var kA,TA,_A=g(()=>{"use strict";Vl();kA=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);TA="a[href], button, input, select, textarea, [role], [tabindex], label"});async function EA(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Yg(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>EA(t,s)))).filter(o=>o!==null)}async function lX(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Qg(t,e,n){switch(e.kind){case"element_id":return dX(t,e,n);case"selector":return uX(t,e);case"semantic":return pX(t,e)}}async function dX(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Yg(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function uX(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 Yg(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function pX(t,e){return e.role!==void 0?fX(t,e.text,e.role):mX(t,e.text,e)}async function fX(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 Yg(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function mX(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await lX(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=u.slice(0,5),f=[];for(let h=0;h<p.length;h++){let y=p[h];if(y===void 0)continue;let b=await EA(y.locator,y.index);if(b!==null){let v=`${b.role}:${b.label}:${h}`,T=0;for(let _=0;_<v.length;_++)T=T*31+v.charCodeAt(_)>>>0;f.push({...b,id:`el_${T.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var AA=g(()=>{"use strict"});async function Zg(t,e,n,r){let o=t.url();if(o===n)return null;let s=_t(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 xA=g(()=>{"use strict";In()});var th={};Ms(th,{PlaywrightProvider:()=>eh});function RA(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 eh,nh=g(()=>{"use strict";wA();_A();AA();In();xA();Gg();eh=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Zl(e)}async open(e){let n=_t(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 c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await Zg(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 ed(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 ed(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 Qg(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${RA(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(y){l=y}else l=h}let u=await Zg(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await ed(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),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Qg(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${RA(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 xo(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await xo(n,o,r);return s}catch{return null}}}});var Er={};Ms(Er,{__resetBrowserRegistryForTests:()=>SX,browserProviderActive:()=>yX,closeBrowserProvider:()=>oh,getBrowserProvider:()=>hX,getLastRoutingDecision:()=>wX,peekBrowserProvider:()=>bX});function IA(){Promise.resolve(oh()).then(()=>{process.exit(130)})}function CA(){Promise.resolve(oh()).then(()=>{process.exit(143)})}function PA(){Ht=null}function gX(){td||(process.on("SIGINT",IA),process.on("SIGTERM",CA),process.on("exit",PA),td=!0)}function MA(){td&&(process.removeListener("SIGINT",IA),process.removeListener("SIGTERM",CA),process.removeListener("exit",PA),td=!1)}async function hX(t){return Ht!==null?Ht:(_r!==null||(_r=(async()=>{let e=jg(t),n=t?.surface??(t?.env??{}).AGENT_SURFACE??k.AGENT_SURFACE,r=await oA({config:e,surface:n});rh=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:s}=await Promise.resolve().then(()=>(gA(),mA)),i=r.availability.connection;o=new s(e,i)}else{let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(nh(),th));o=new s(e)}return gX(),Ht=o,_r=null,o})()),_r)}async function oh(){if(Ht===null)return;let t=Ht;Ht=null,_r=null,MA(),await t.shutdown()}function yX(){return Ht!==null}function bX(){return Ht}function wX(){return rh}function SX(){Ht=null,_r=null,rh=null,MA()}var Ht,_r,td,rh,Ar=g(()=>{"use strict";In();sA();L();Ht=null,_r=null,td=!1,rh=null});async function OA(t,e){try{return await GE(t,e)}catch(n){return O("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function AX(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Ar(),Er)),r=await n();try{return await r.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}catch(o){if(r.name==="agent-browser"){let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(nh(),th)),{loadBrowserConfig:i}=await Promise.resolve().then(()=>(In(),Hg)),a=i(),c=new s(a);try{return await c.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}finally{await c.shutdown()}}throw o}}async function DA(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??AX,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,c=null,l=null;try{let u=await Rn(n,t,{headers:EX,signal:e.signal},o);c=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(_X.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await u.text();if(TX.test(p)&&!vX.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await OA(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof Ie||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;l=u}if(!(s===null||s.textLength<200)&&s!==null){let u=Ng({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await Pi(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>Pi(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await Pi(u.finalUrl,o);let p=await OA(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=Ng({html:u.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:u.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(u){if(e.signal.aborted||u instanceof Ie)throw u;if(s===null){let p=u instanceof Error?u.message:String(u),f=l instanceof Error?l.message:`HTTP ${c??"error"}`,m=new Error(`web_scrape could not retrieve ${t}: fetch failed (${f}) and render failed (${p}).`);throw m.cause=u,m}}if(s!==null)return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${c??"error"}).`)}var vX,TX,_X,EX,FA=g(()=>{"use strict";qE();$g();vr();ie();vX=/(text\/html|application\/xhtml\+xml)/i,TX=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,_X=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,EX={"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 IX(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(xX,{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),RX),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=Z(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function LA(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?IX({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 NA(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
319
319
|
|
|
320
320
|
(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(`
|
|
321
321
|
`).trimEnd()}var xX,RX,$A=g(()=>{"use strict";ot();xX="https://api.exa.ai/search",RX=10});function nd(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 xr=g(()=>{"use strict";Jg()});function FX(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 c;try{c=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(c.protocol!=="http:"&&c.protocol!=="https:")return{error:`Invalid input: protocol "${c.protocol}" not supported (http/https only)`};o=c.toString()}let i=CX;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,PX)}let a=MX;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,OX)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function sh(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:tn(t,e),truncated:!0}}function LX(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env,r=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{};return async(o,s)=>{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 i=FX(o);if("error"in i)return{content:i.error,isError:!0};if(s.aborted){let u=s.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let a=new AbortController,c=()=>{a.abort(s.reason)},l,d=()=>{let u=a.signal.reason;return u instanceof Error?u.message:String(u??"aborted")};try{if(s.addEventListener("abort",c,{once:!0}),l=setTimeout(()=>{a.abort(new Error(`web_scrape timeout after ${i.timeoutMs}ms`))},i.timeoutMs),i.url!==void 0){let p=await kr(i.url,r);if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(!p.allowed)return{content:`web_scrape blocked: ${p.reason}`,isError:!0}}if(i.mode==="raw"){let p;try{let h={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};p=await Rn(e,i.url,h,r)}catch(h){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:h instanceof Ie?{content:`web_scrape blocked: ${h.message}`,isError:!0}:{content:`web_scrape network error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}if(!p.ok)return{content:`web_scrape HTTP ${p.status} ${p.statusText||""}`.trimEnd()+` for ${i.url}`,isError:!0};let f;try{f=await p.text()}catch(h){return{content:`web_scrape read error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}let m=sh(f,i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}if(i.mode==="markdown")try{let p=await DA(i.url,{fetchFn:e,renderFn:t.renderFn,timeoutMs:i.timeoutMs,signal:a.signal,...t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{}});if(p.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${i.url}.`,isError:!0};let f=sh(XE(p.markdown,p.advisory),i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(p instanceof Ie)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),m=Ge(p)&&!Vg(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${Mi()}\`)`:"";return{content:`web_scrape markdown error: ${f}${m}`,isError:!0}}let u=LA({exaApiKey:n.EXA_API_KEY,fetchFn:e});if("error"in u)return{content:u.error,isError:!0};try{let p=await u.search(i.query,{limit:DX,timeoutMs:i.timeoutMs,signal:a.signal}),f=sh(NA(i.query,p),i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:{content:`web_scrape search error (${u.name}): ${p instanceof Error?p.message:String(p)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),s.removeEventListener("abort",c)}}}var CX,PX,MX,OX,DX,UA,BA=g(()=>{"use strict";FA();$A();vr();nn();$g();xr();CX=3e4,PX=12e4,MX=1e5,OX=1e6,DX=10;UA=LX()});function UX(t){return NX.has(t)?"low":t==="DELETE"?"high":"medium"}function BX(t){return $X.has(t)}function WX(t){let e={};return t.forEach((n,r)=>{let o=r.toLowerCase();HX.has(o)||jX.some(s=>o.startsWith(s))||(e[r]=n)}),e}function KX(t,e){if(t==null)return{serialized:void 0,inferredContentType:void 0};let n=Object.keys(e).some(o=>o.toLowerCase()==="content-type");return typeof t=="string"?{serialized:t,inferredContentType:n?void 0:"text/plain"}:{serialized:JSON.stringify(t),inferredContentType:n?void 0:"application/json"}}function GX(t,e,n){let r=Buffer.byteLength(t,"utf8"),o=t,s=!1;if(r>n&&(o=tn(t,n),s=!0),!s&&/application\/json/i.test(e))try{return{body:JSON.parse(o),truncated:!1}}catch{}return{body:o,truncated:s}}async function WA(t){let{url:e,method:n,signal:r,domainCheck:o,recordEffect:s}=t,i=Math.min(t.maxResponseBytes??ih,ah),a={...t.headers},c=t.fetchFn??globalThis.fetch,l=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},d=UX(n);if(o!==void 0){let S=o(e);if(!S.allowed)throw Object.assign(new Error(`web_request blocked by domain policy: ${S.reason}`),{name:"DomainPolicyError"})}let u=await kr(e,l);if(!u.allowed)throw new Ie(u.reason);let{serialized:p,inferredContentType:f}=KX(t.body,a);f!==void 0&&(a["content-type"]=f);let m={method:n,headers:Object.keys(a).length>0?a:void 0,body:p,signal:r},y=BX(n)?{retries:2,baseDelayMs:300,maxDelayMs:5e3}:{retries:0},b=Date.now(),v;try{v=await Rn(c,e,m,{...l,retry:y})}catch(S){throw S instanceof Ie,S}let T=Date.now()-b,_=v.headers.get("content-type")??"",x;try{let S=v.body?.getReader();if(!S)x="";else{let A=[],C=0,P=i*2;for(;;){let{done:G,value:M}=await S.read();if(G||!M)break;if(A.push(M),C+=M.byteLength,C>=P){await S.cancel();break}}x=new TextDecoder().decode(Buffer.concat(A,C))}}catch{x=""}let{body:E,truncated:I}=GX(x,_,i),R=WX(v.headers);return s!==void 0&&Promise.resolve(s({url:e,method:n,status:v.status,risk:d,timing_ms:T})).catch(()=>{}),{status:v.status,headers:R,body:E,truncated:I,timing_ms:T,risk:d}}function KA(t){if(typeof t!="string"||t.trim().length===0)return{error:"method must be a non-empty string (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS)"};let e=t.trim().toUpperCase(),n=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];return n.includes(e)?e:{error:`method "${t}" is not supported \u2014 must be one of: ${n.join(", ")}`}}var jA,HA,ih,ah,NX,$X,jX,HX,GA=g(()=>{"use strict";vr();nn();jA=3e4,HA=12e4,ih=1e5,ah=1e6,NX=new Set(["GET","HEAD","OPTIONS"]),$X=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]);jX=["set-cookie","x-"],HX=new Set(["server","via","age","vary","authorization","www-authenticate"])});function qX(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t;if(typeof e.url!="string"||e.url.length===0)return{error:'Invalid input: "url" must be a non-empty string'};let n;try{n=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{error:`Invalid input: protocol "${n.protocol}" not supported (http/https only)`};n.username="",n.password="";let r=n.toString(),o=KA(e.method);if(typeof o=="object"&&"error"in o)return{error:`Invalid input: ${o.error}`};let s=o,i;if(e.body!==void 0&&e.body!==null){if(typeof e.body!="string"&&typeof e.body!="object")return{error:'Invalid input: "body" must be a string, object, or array'};i=e.body}let a={};if(e.headers!==void 0){if(typeof e.headers!="object"||e.headers===null||Array.isArray(e.headers))return{error:'Invalid input: "headers" must be a string-keyed object'};let u=e.headers;for(let[p,f]of Object.entries(u)){if(typeof f!="string")return{error:`Invalid input: header value for "${p}" must be a string`};a[p]=f}}let c=jA;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'};c=Math.min(e.timeout_ms,HA)}let l=ih;if(e.max_response_bytes!==void 0){if(typeof e.max_response_bytes!="number"||!Number.isFinite(e.max_response_bytes)||e.max_response_bytes<=0)return{error:'Invalid input: "max_response_bytes" must be a positive finite number'};l=Math.min(e.max_response_bytes,ah)}let d;if(e.credential!==void 0){if(typeof e.credential!="string"||e.credential.length===0)return{error:'Invalid input: "credential" must be a non-empty string (an env var name)'};d=e.credential}return{url:r,method:s,body:i,headers:a,timeoutMs:c,maxResponseBytes:l,credential:d}}function XX(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env;async function r(){if(t.domainCheck!==void 0)return t.domainCheck;try{let{loadBrowserConfig:o,enforceDomainPolicy:s}=await Promise.resolve().then(()=>(In(),Hg)),i=o();return a=>s(a,i)}catch{return}}return async(o,s)=>{if(typeof e!="function")return{content:"web_request unavailable: global fetch() is not present (agent-afk requires Node 20+).",isError:!0};let i=qX(o);if("error"in i)return{content:i.error,isError:!0};if(s.aborted){let p=s.reason;return{content:`web_request aborted: ${p instanceof Error?p.message:String(p??"aborted")}`,isError:!0}}let a={...i.headers};if(i.credential!==void 0){let p=n[i.credential];if(p===void 0||p.trim().length===0)return{content:`web_request credential error: environment variable "${i.credential}" is not set. Set it in afk.env or export it in the shell before starting AFK.`,isError:!0};if(Object.keys(a).some(m=>m.toLowerCase()==="authorization"))return{content:'web_request credential error: both "credential" and an explicit Authorization header were provided. Use one or the other.',isError:!0};a.Authorization=`Bearer ${p}`}let c=new AbortController,l=()=>c.abort(s.reason),d,u=()=>{let p=c.signal.reason;return p instanceof Error?p.message:String(p??"aborted")};try{s.addEventListener("abort",l,{once:!0}),d=setTimeout(()=>{c.abort(new Error(`web_request timeout after ${i.timeoutMs}ms`))},i.timeoutMs);let p=await r(),f={url:i.url,method:i.method,body:i.body,headers:a,maxResponseBytes:i.maxResponseBytes,signal:c.signal,fetchFn:e,lookupFn:t.lookupFn,domainCheck:p,recordEffect:t.recordEffect},m;try{m=await WA(f)}catch(v){if(c.signal.aborted)return{content:`web_request aborted: ${u()}`,isError:!0};if(v instanceof Ie)return{content:`web_request blocked: ${v.message}`,isError:!0};let T=v instanceof Error&&v.name==="DomainPolicyError"?"blocked":"network error",_=v instanceof Error?v.message:String(v);return{content:`web_request ${T}: ${_}`,isError:!0}}if(c.signal.aborted)return{content:`web_request aborted: ${u()}`,isError:!0};let h=m.body;if(typeof h=="string")h=Zt(h);else if(typeof h=="object"&&h!==null){let v=Zt(JSON.stringify(h));try{h=JSON.parse(v)}catch{h=v}}let y={status:m.status,headers:m.headers,body:h,timing_ms:m.timing_ms,...m.truncated?{truncated:!0}:{}};return{content:JSON.stringify(y,null,2),...m.truncated?{truncated:!0}:{}}}finally{d!==void 0&&clearTimeout(d),s.removeEventListener("abort",l)}}}var qA,XA=g(()=>{"use strict";GA();vr();Zr();qA=XX()});import{existsSync as VA,mkdirSync as zX,readFileSync as VX,renameSync as JX,unlinkSync as YX,writeFileSync as QX}from"node:fs";import{dirname as zA,join as ZX}from"node:path";import{randomBytes as ez}from"node:crypto";function Rr(t){let e=t??Ff();if(!VA(e))return[];try{let n=VX(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 Oi(t,e){let n=e??Ff();zX(zA(n),{recursive:!0});let r=ZX(zA(n),`.schedules.json.${process.pid}.${ez(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{QX(r,o,"utf-8"),JX(r,n)}catch(s){try{VA(r)&&YX(r)}catch{}throw s}}function JA(t,e){let n=Rr(e),r=n.map(c=>c.id),o=tz(t.name),s=nz(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),Oi(n,e),a}function YA(t,e){let n=Rr(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(Oi(o,e),!0)}function QA(t,e){return Rr(e).find(n=>n.id===t)}function tz(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function nz(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}function ZA(t){return{taskId:t.id,command:t.command,trigger:t.trigger??"cron",...t.cron!==void 0?{cronExpression:t.cron}:{},...t.notifyOn!==void 0?{notifyOn:t.notifyOn}:{},...t.notifyChat!==void 0?{notifyChat:t.notifyChat}:{}}}var ex=g(()=>{"use strict";j()});import{existsSync as rz,readFileSync as oz}from"node:fs";import{join as sz}from"node:path";async function Ro(t,e,n){let r,o;try{let s=sz(JS("default"),"port");if(!rz(s))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=oz(s,"utf-8").trim(),a=iz(i);if(!a)return{synced:!1,detail:"daemon-not-detected (invalid port file)"};({host:r,port:o}=a)}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let s=r.includes(":")?`[${r}]`:r,i=await fetch(`http://${s}:${o}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return i.ok?{synced:!0,detail:"synced"}:t==="POST"&&i.status===409?{synced:!0,detail:"already-registered"}:t==="DELETE"&&i.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${i.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}function iz(t){let e=parseInt(t,10);if(String(e)===t&&!Number.isNaN(e))return e<1||e>65535?null:{host:"localhost",port:e};let n=t.lastIndexOf(":");if(n<1)return null;let r=t.slice(0,n),o=t.slice(n+1);if(!/^\d+$/.test(o))return null;let s=parseInt(o,10);return Number.isNaN(s)||s<1||s>65535||/^:+$/.test(r)?null:{host:r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r,port:s}}var ch,tx=g(()=>{"use strict";j();ch="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 az}from"node:fs";import{readFile as cz}from"node:fs/promises";var nx,rx,ox,sx,ix=g(()=>{"use strict";ex();j();tx();nx=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=JA({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 Ro("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 Ro("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:ch}})}},rx=async(t,e)=>{let n=Rr();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})))}},ox=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=dc();if(!az(s))return{content:JSON.stringify([])};let i;try{let l=await cz(s);i=(l.length>1048576?l.subarray(l.length-1048576):l).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.176.
|
|
3
|
+
"version": "5.176.2",
|
|
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",
|