agent-afk 5.176.2 → 5.176.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/daemon/task-lifecycle.d.ts +2 -0
- package/dist/cli.mjs +95 -95
- package/dist/index.mjs +2 -2
- package/dist/telegram.mjs +2 -2
- package/package.json +1 -1
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.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.
|
|
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.3"}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)+`
|
|
@@ -299,7 +299,7 @@ ${e}`}C();import{BlockList as VO,isIP as Ld}from"node:net";import{lookup as YO}f
|
|
|
299
299
|
`)}finally{f&&await f.close().catch(()=>{})}}if(o){if(yield*l(),c)return}else try{i=(await yn.stat(n)).size}catch{}let d=null,u=null,p=()=>new Promise(f=>{let m=setTimeout(()=>{u=null,f()},oN);u=()=>{clearTimeout(m),u=null,f()},s?.addEventListener("abort",()=>{clearTimeout(m),u=null,f()},{once:!0})});try{d=Xn.watch(r,{persistent:!1},()=>{u?.()})}catch{}try{for(;!s?.aborted&&!c&&(await p(),!s?.aborted);)yield*l()}finally{d?.close()}}M();import{readdir as sN,stat as iN}from"node:fs/promises";import{join as aN}from"node:path";async function Su(){let t=Pr(),e;try{e=await sN(t)}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of e){let o=aN(t,r,"trace.jsonl");try{let s=await iN(o);s.isFile()&&n.push({sessionId:r,tracePath:o,mtimeMs:s.mtimeMs,exists:!0})}catch{}}return n.sort((r,o)=>o.mtimeMs-r.mtimeMs),n}async function Yw(){return(await Su())[0]?.sessionId??null}M();import{existsSync as cN,readdirSync as lN,readFileSync as dN}from"node:fs";import{basename as uN,join as pN}from"node:path";var fN=3;function mN(t){try{let e=JSON.parse(dN(t,"utf-8"));if(typeof e!="object"||e===null)return;let n=e;return{sessionId:typeof n.sessionId=="string"?n.sessionId:void 0,name:typeof n.name=="string"?n.name:void 0,savedAt:typeof n.savedAt=="number"?n.savedAt:void 0}}catch{return}}function gN(t){if(!cN(t))return[];let e;try{e=lN(t)}catch{return[]}let n=[];for(let r of e){if(!r.endsWith(".json"))continue;let o=pN(t,r),s=mN(o);s&&n.push({sidecarId:uN(r,".json"),filePath:o,data:s})}return n}function Qw(t,e=de()){let n=gN(e);n.sort((r,o)=>{let s=r.data.savedAt??-1/0;return(o.data.savedAt??-1/0)-s});for(let r of n){if(r.sidecarId===t)return{sessionId:r.data.sessionId??r.sidecarId,sidecarId:r.sidecarId,reason:"exact-id"};if(r.data.sessionId===t)return{sessionId:r.data.sessionId,sidecarId:r.sidecarId,reason:"exact-session-id"};if(r.data.name===t)return{sessionId:r.data.sessionId??r.sidecarId,sidecarId:r.sidecarId,reason:"exact-name"}}if(t.length>=fN){let r=n.filter(o=>o.data.name!==void 0&&o.data.name.startsWith(t));if(r.length===1){let o=r[0];return{sessionId:o.data.sessionId??o.sidecarId,sidecarId:o.sidecarId,reason:"prefix-name"}}}}import{existsSync as hN}from"node:fs";import{readFile as yN}from"node:fs/promises";var Zw=2097152;async function ku(t){if(!hN(t))return{content:"",truncated:!1};try{let e=await yN(t);if(e.length<=Zw)return{content:e.toString("utf-8"),truncated:!1};let n=e.subarray(e.length-Zw),r=n.indexOf(10);return r!==-1&&(n=n.subarray(r+1)),{content:n.toString("utf-8"),truncated:!0}}catch{return{content:"",truncated:!1}}}var bN=50,wN=200,SN=200,kN=20,vN=100;function tS(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.kind=="string"&&typeof e.seq=="number"&&typeof e.payload=="object"&&e.payload!==null}function TN(t){return Vr(t,{guard:tS})}function _N(t){return typeof t!="number"?bN:Math.min(Math.max(1,Math.round(t)),wN)}function EN(t){return typeof t!="number"?kN:Math.min(Math.max(1,Math.round(t)),vN)}function AN(t,e){if(e.kinds&&!e.kinds.has(t.kind)||e.toolName&&(t.kind!=="tool_call"||t.payload.name!==e.toolName))return!1;if(e.errorsOnly)if(t.kind==="tool_call"){let n=t.payload;if(n.phase!=="completed"||!n.isError)return!1}else if(t.kind==="subagent_lifecycle"){if(t.payload.transition!=="failed")return!1}else if(t.kind==="background_agent"){if(t.payload.transition!=="failed")return!1}else return!1;return!0}async function xN(t){let e=async r=>{let o=eS(At(r),"trace.jsonl");if(!vu(o))try{for await(let s of Jw(r))if(s.kind==="meta"){if(s.traceLabel===null)return{tracePath:o,disabledNote:r};if(typeof s.traceLabel=="string"&&s.traceLabel.length>0){let i=eS(At(s.traceLabel),"trace.jsonl");vu(i)&&(o=i)}break}}catch{}return{tracePath:o,disabledNote:void 0}},n=await e(t);if(n.disabledNote!==void 0||vu(n.tracePath))return n;try{let r=Qw(t);if(r&&r.sessionId!==t){let o=await e(r.sessionId);return o.disabledNote!==void 0?{tracePath:o.tracePath,disabledNote:r.sessionId}:o}}catch{}return n}async function nS(t){let e=t.session==="latest"||!t.session?await Yw():t.session;if(!e)return{sessionId:"(none)",events:[],totalInTrace:0,filtered:0};let{tracePath:n,disabledNote:r}=await xN(e);if(r!==void 0)return{sessionId:e,events:[],totalInTrace:0,filtered:0,note:`Session "${r}" ran with tracing disabled (traceLabel: null).`};let{content:o}=await ku(n),s=TN(o),i={kinds:t.kinds?new Set(t.kinds):void 0,toolName:t.toolName,errorsOnly:t.errorsOnly},a=_N(t.limit),c=[];for(let l=s.length-1;l>=0;l--){let d=s[l];if(AN(d,i)&&(c.push(d),c.length>=a))break}return c.reverse(),{sessionId:e,events:c,totalInTrace:s.length,filtered:c.length}}async function rS(t){let e=EN(t.sessions),r=(await Su()).slice(0,e),o=r.length,s=r;if(t.since){let p=Date.parse(t.since);if(Number.isNaN(p))throw new Error(`Invalid "since" date: ${t.since}`);s=r.filter(f=>f.mtimeMs>=p)}let i=t.kinds?new Set(t.kinds):void 0,a=t.query.toLowerCase(),c=[],l=SN,d=[],u=0;for(let p of s){if(c.length>=l)break;let{content:f,truncated:m}=await ku(p.tracePath);u++,m&&d.push(p.sessionId);let g=f.split(`
|
|
300
300
|
`).filter(h=>h.trim()!==""&&h.toLowerCase().includes(a));for(let h of g){if(c.length>=l)break;let[b]=Vr(h,{guard:tS});b&&(i&&!i.has(b.kind)||t.toolName&&(b.kind!=="tool_call"||b.payload.name!==t.toolName)||c.push({sessionId:p.sessionId,event:b,matchLine:h.length>500?h.slice(0,500)+"\u2026":h}))}}return{query:t.query,sessionsAvailable:o,sessionsSearched:u,sessionsScanned:u,matches:c,...d.length>0?{truncatedSessions:d}:{}}}function oS(t){return!t||typeof t!="object"?null:t}function sS(t){if(Array.isArray(t))return t.filter(e=>typeof e=="string")}var iS=async t=>{let e=oS(t);if(!e)return{content:"Invalid input: expected object",isError:!0};let n=typeof e.session=="string"?e.session:void 0,r=sS(e.kinds),o=typeof e.tool_name=="string"?e.tool_name:void 0,s=typeof e.errors_only=="boolean"?e.errors_only:!1,i=typeof e.limit=="number"?e.limit:void 0;try{let a=await nS({session:n,kinds:r,toolName:o,errorsOnly:s,limit:i});return{content:JSON.stringify(a)}}catch(a){return{content:`read_witness failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},aS=async t=>{let e=oS(t);if(!e)return{content:"Invalid input: expected object",isError:!0};if(typeof e.query!="string"||!e.query)return{content:"Invalid input: query (string) is required",isError:!0};let n=e.query,r=typeof e.sessions=="number"?e.sessions:void 0,o=sS(e.kinds),s=typeof e.since=="string"?e.since:void 0,i=typeof e.tool_name=="string"?e.tool_name:void 0;try{let a=await rS({query:n,sessions:r,kinds:o,since:s,toolName:i});return{content:JSON.stringify(a)}}catch(a){return{content:`search_witness failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}};var zn={action:"decline"},cS=300;function RN(t){return t.length<=cS?t:`${t.slice(0,cS)}\u2026(truncated)`}function IN(t){try{let n=[`\u{1F514} AFK needs you \u2014 stuck on: ${t.title??t.serverName}`,RN(t.message)];t.url!==void 0&&t.url!==""&&n.push(t.url),Ny(n.join(`
|
|
301
301
|
`)).catch(()=>{})}catch{}}function lS(t,e){if(!(t===void 0||t===""))try{nd(t,e).catch(()=>{})}catch{}}var Tu=class{handler=null;queue=Promise.resolve();queueDepth=0;install(e){this.handler=e}uninstall(){this.handler=null}hasHandler(){return this.handler!==null}pendingCount(){return this.queueDepth}route(e,n){if(n.signal.aborted)return Promise.resolve(zn);this.queueDepth+=1;let r,o=new Promise(i=>{r=i}),s=this.handler;return this.queue=this.queue.then(async()=>{try{if(n.signal.aborted){r(zn);return}if(!s){IN(e),r(zn);return}let i,a=new Promise(c=>{i=()=>c(zn),n.signal.addEventListener("abort",i,{once:!0})});try{try{n.onActive?.()}catch{}lS(n.sessionId,!0);let c=await Promise.race([s(e,n).catch(()=>zn),a]);r(c)}finally{lS(n.sessionId,!1),n.signal.removeEventListener("abort",i)}}finally{this.queueDepth-=1,r(zn)}}).catch(()=>{}),o}},bn=new Tu;var dS=async(t,e,n)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let r=t,o=r.question;if(typeof o!="string"||o.trim()==="")return{content:"Invalid input: question must be a non-empty string",isError:!0};let s=new Set(["text","confirm","choice","multi_choice","number"]),i=r.type??"text";if(typeof i!="string"||!s.has(i))return{content:"Invalid input: type must be one of: text, confirm, choice, multi_choice, number",isError:!0};if(i==="choice"||i==="multi_choice"){let m=r.choices;if(!Array.isArray(m)||m.length===0)return{content:`Invalid input: choices array is required and must be non-empty for type "${i}"`,isError:!0};if(m.length>100)return{content:`Invalid input: choices array must not exceed 100 items, got ${m.length}`,isError:!0};for(let g of m)if(typeof g!="string")return{content:"Invalid input: all choices must be strings",isError:!0}}let a=r.min,c=r.max;if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)))return{content:"Invalid input: min must be a finite number",isError:!0};if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)))return{content:"Invalid input: max must be a finite number",isError:!0};if(a!==void 0&&c!==void 0&&a>c)return{content:`Invalid input: min (${a}) must be \u2264 max (${c})`,isError:!0};let l=r.min_length,d=r.max_length;if(l!==void 0&&typeof l!="number")return{content:"Invalid input: min_length must be a number",isError:!0};if(d!==void 0&&typeof d!="number")return{content:"Invalid input: max_length must be a number",isError:!0};if((l!==void 0||d!==void 0)&&i!=="text")return{content:`Invalid input: min_length/max_length are only valid for type "text", got "${i}"`,isError:!0};if(r.allow_custom!==void 0&&i!=="choice"&&i!=="multi_choice")return{content:`Invalid input: allow_custom is only valid for type "choice" or "multi_choice", got "${i}"`,isError:!0};let u={serverName:"agent",message:o.trim(),origin:"agent",type:i,...r.choices!==void 0&&{choices:r.choices},...r.context!==void 0&&typeof r.context=="string"&&{context:r.context},...r.default!==void 0&&{questionDefault:r.default},...l!==void 0&&{minLength:l},...d!==void 0&&{maxLength:d},...a!==void 0&&{min:a},...c!==void 0&&{max:c},...r.allow_skip!==void 0&&{allowSkip:!!r.allow_skip},...r.allow_custom!==void 0&&{allowCustom:!!r.allow_custom}},p=await bn.route(u,{signal:e,...n?.sessionId!==void 0?{sessionId:n.sessionId}:{}}),f=p.action==="decline"||p.action==="cancel";return{content:JSON.stringify(p),...f&&{isError:!0,failureClass:"elicitation-declined"}}};C();var uS=["load","domcontentloaded","networkidle"];function CN(t){if(!t||typeof t!="object")return{error:"browser_open: input must be an object"};let e=t,n=e.url;if(typeof n!="string"||n.length===0)return{error:'browser_open: "url" is required and must be a non-empty string'};let r;try{r=new URL(n)}catch{return{error:`browser_open: "${n}" is not a valid absolute URL`}}if(r.protocol!=="http:"&&r.protocol!=="https:")return{error:`browser_open: protocol "${r.protocol}" is not supported (http/https only)`};let o;if(e.wait_for!==void 0){if(!uS.includes(e.wait_for))return{error:`browser_open: "wait_for" must be one of ${uS.map(a=>`"${a}"`).join(", ")} (got ${JSON.stringify(e.wait_for)})`};o=e.wait_for}let s;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_open: "screenshot" must be a boolean'};s=e.screenshot}let i;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'browser_open: "timeout_ms" must be a positive finite number'};i=e.timeout_ms}return{url:r.toString(),waitFor:o,screenshot:s,timeoutMs:i}}function PN(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_open aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0,failureClass:ye(n)}}let o=CN(e);if("error"in o)return{content:o.error,isError:!0};let s=y.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(gn(),mn));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return xe(u)?{content:He(u),isError:!0}:{content:`browser_open failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.open({sessionId:s,url:o.url,waitFor:o.waitFor,screenshot:o.screenshot,timeoutMs:o.timeoutMs}),u=Date.now()-l;if("outcome"in d&&d.outcome==="blocked_by_policy")return ie(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:u}),{content:`browser_open blocked: ${d.reason}`,isError:!0,failureClass:"policy-refusal"};let p=d;return ie(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:p.url,status:"ok",durationMs:u,...p.screenshotPath!==null?{screenshotPath:p.screenshotPath}:{}}),{content:JSON.stringify(p,null,2)}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);ie(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}});let f=Hi(d);return{content:`browser_open failed: ${p}`,isError:!0,...f?{failureClass:f}:{}}}}}var pS=PN();C();function MN(t){if(t!=null&&typeof t!="object")return{error:"browser_observe: input must be an object or omitted"};if(!t)return{};let e=t,n;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_observe: "screenshot" must be a boolean'};n=e.screenshot}let r;if(e.include_hidden!==void 0){if(typeof e.include_hidden!="boolean")return{error:'browser_observe: "include_hidden" must be a boolean'};r=e.include_hidden}let o;if(e.max_elements!==void 0){if(typeof e.max_elements!="number"||!Number.isFinite(e.max_elements)||e.max_elements<=0||!Number.isInteger(e.max_elements))return{error:'browser_observe: "max_elements" must be a positive integer'};o=e.max_elements}return{screenshot:n,includeHidden:r,maxElements:o}}function ON(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_observe aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let o=MN(e);if("error"in o)return{content:o.error,isError:!0};let s=y.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(gn(),mn));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return xe(u)?{content:He(u),isError:!0}:{content:`browser_observe failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.observe({sessionId:s,screenshot:o.screenshot,includeHidden:o.includeHidden,maxElements:o.maxElements}),u=Date.now()-l;return ie(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:d.url,urlAfter:d.url,status:"ok",durationMs:u,...d.screenshotPath!==null?{screenshotPath:d.screenshotPath}:{}}),{content:JSON.stringify(d,null,2)}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);return ie(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}}),{content:`browser_observe failed: ${p}`,isError:!0}}}}var fS=ON();Fi();C();var mS=["click","fill","press","select","hover","scroll_to","wait_for"],gS=["semantic","element_id","selector"];function DN(t){if(!t||typeof t!="object")return{error:"browser_act: input must be an object"};let e=t;if(typeof e.action!="string")return{error:'browser_act: "action" is required and must be a string'};if(!mS.includes(e.action))return{error:`browser_act: "action" must be one of ${mS.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(e.action)})`};let n=e.action,r=e.target;if(!r||typeof r!="object")return{error:'browser_act: "target" is required and must be an object'};let o=r;if(typeof o.kind!="string"||!gS.includes(o.kind))return{error:`browser_act: "target.kind" must be one of ${gS.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(o.kind)})`};let s,i=o.kind;if(i==="semantic"){if(typeof o.text!="string"||o.text.length===0)return{error:'browser_act: target.kind=semantic requires "target.text" (non-empty string)'};s={kind:"semantic",text:o.text,...typeof o.role=="string"&&o.role.length>0?{role:o.role}:{}}}else if(i==="element_id"){if(typeof o.element_id!="string"||o.element_id.length===0)return{error:'browser_act: target.kind=element_id requires "target.element_id" (non-empty string)'};s={kind:"element_id",elementId:o.element_id}}else{if(typeof o.selector!="string"||o.selector.length===0)return{error:'browser_act: target.kind=selector requires "target.selector" (non-empty string)'};s={kind:"selector",selector:o.selector}}let a;if(e.value!==void 0){if(typeof e.value!="string")return{error:'browser_act: "value" must be a string when provided'};a=e.value}let c;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'browser_act: "timeout_ms" must be a positive finite number'};c=e.timeout_ms}let l;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_act: "screenshot" must be a boolean'};l=e.screenshot}return{action:n,target:s,value:a,timeoutMs:c,screenshot:l}}function FN(t,e){let n=t.role?`"${t.text}" (role: ${t.role})`:`"${t.text}"`;return[`browser_act: ambiguous target \u2014 ${e.length} elements matched ${n}.`,'Retry with target.kind="element_id" using one of the following:',...e.map(o=>` id=${o.id} role=${o.role} label=${o.label}`)].join(`
|
|
302
|
-
`)}function LN(t){return t.kind==="semantic"?{kind:"semantic",text:nb(t.text),...t.role!==void 0?{role:t.role}:{}}:t.kind==="element_id"?{kind:"element_id",elementId:t.elementId}:{kind:"selector",selectorHash:tb(t.selector)}}function NN(t={}){return async(e,n,r)=>{if(n.aborted){let u=n.reason;return{content:`browser_act aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0,failureClass:ye(n)}}let o=DN(e);if("error"in o)return{content:o.error,isError:!0};let s=LN(o.target),i=y.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let a,c,l;try{if(t.getBrowserProvider)a=await t.getBrowserProvider();else{let{getBrowserProvider:u,getLastRoutingDecision:p}=await Promise.resolve().then(()=>(gn(),mn));a=await u();let f=p();f&&(c=f.backend,l=f.reason)}}catch(u){let p=u instanceof Error?u.message:String(u);return xe(p)?{content:He(p),isError:!0}:{content:`browser_act failed to get provider: ${p}`,isError:!0}}let d=Date.now();try{let u=await a.act({sessionId:i,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),p=Date.now()-d;if("outcome"in u){if(u.outcome==="ambiguous_target")return ie(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:p}),{content:FN(u.query,u.candidates),isError:!0};if(u.outcome==="blocked_by_policy")return ie(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:p}),{content:`browser_act blocked: ${u.reason}`,isError:!0,failureClass:"policy-refusal"}}return ie(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:u.url,urlAfter:u.url,status:"ok",durationMs:p,...u.screenshotPath!==null?{screenshotPath:u.screenshotPath}:{}}),{content:JSON.stringify(u,null,2)}}catch(u){let p=Date.now()-d,f=u instanceof Error?u.message:String(u);ie(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"error",durationMs:p,error:{reason:f,recoverable:!1}});let m=Hi(u);return{content:`browser_act failed: ${f}`,isError:!0,...m?{failureClass:m}:{}}}}}var hS=NN();C();var yS=["semantic","element_id","selector"],_u=8e3;function UN(t){if(typeof t.kind!="string"||!yS.includes(t.kind))return{error:`browser_screenshot: "target.kind" must be one of ${yS.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(t.kind)})`};let e=t.kind;return e==="semantic"?typeof t.text!="string"||t.text.length===0?{error:'browser_screenshot: target.kind=semantic requires "target.text" (non-empty string)'}:{kind:"semantic",text:t.text,...typeof t.role=="string"&&t.role.length>0?{role:t.role}:{}}:e==="element_id"?typeof t.element_id!="string"||t.element_id.length===0?{error:'browser_screenshot: target.kind=element_id requires "target.element_id" (non-empty string)'}:{kind:"element_id",elementId:t.element_id}:typeof t.selector!="string"||t.selector.length===0?{error:'browser_screenshot: target.kind=selector requires "target.selector" (non-empty string)'}:{kind:"selector",selector:t.selector}}function $N(t){if(t!=null&&typeof t!="object")return{error:"browser_screenshot: input must be an object or omitted"};if(!t)return{};let e=t,n;if(e.target!==void 0){if(!e.target||typeof e.target!="object")return{error:'browser_screenshot: "target" must be an object when provided'};let o=UN(e.target);if("error"in o)return o;n=o}let r;if(e.full_page!==void 0){if(typeof e.full_page!="boolean")return{error:'browser_screenshot: "full_page" must be a boolean'};r=e.full_page}return{target:n,fullPage:r}}function BN(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_screenshot aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let o=$N(e);if("error"in o)return{content:o.error,isError:!0};let s=y.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(gn(),mn));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return xe(u)?{content:He(u),isError:!0}:{content:`browser_screenshot failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.screenshot({sessionId:s,target:o.target,fullPage:o.fullPage}),u=Date.now()-l,{dataBase64:p,mediaType:f,...m}=d;return ie(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:u,screenshotPath:m.path}),m.width>_u||m.height>_u?{content:JSON.stringify({...m,imageOmitted:`dimensions ${m.width}x${m.height}px exceed the ${_u}px model-vision limit; the PNG was saved to the sidecar path but not attached. Use full_page:false (viewport) or target a specific element for a model-visible image.`},null,2)}:{content:JSON.stringify(m,null,2),image:{mediaType:f,data:p}}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);return ie(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}}),{content:`browser_screenshot failed: ${p}`,isError:!0}}}}var bS=BN();C();function jN(t={}){return async(e,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_close aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=y.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(o))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(o)}`,isError:!0};let s,i,a;try{if(t.getBrowserProvider)s=await t.getBrowserProvider();else{let{getBrowserProvider:l,getLastRoutingDecision:d}=await Promise.resolve().then(()=>(gn(),mn));s=await l();let u=d();u&&(i=u.backend,a=u.reason)}}catch(l){let d=l instanceof Error?l.message:String(l);return xe(d)?{content:He(d),isError:!0}:{content:`browser_close failed to get provider: ${d}`,isError:!0}}let c=Date.now();try{await s.close({sessionId:o});let l=Date.now()-c;return ie(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:l}),{content:"Browser session closed."}}catch(l){let d=Date.now()-c,u=l instanceof Error?l.message:String(l);return ie(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:d,error:{reason:u,recoverable:!1}}),{content:`browser_close failed: ${u}`,isError:!0}}}}var wS=jN();import US from"node:path";import*as ra from"node:fs/promises";import{execSync as nU}from"node:child_process";import ES from"path";var HN=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","workspace_query","read_witness","search_witness"]),WN=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","patch_apply","memory_update","procedure_write","terminal_font_size","config_set","workspace_publish"]),KN=new Set(["Bash","BashOutput","KillBash","bash","test_run","wait_for"]),SS=new Set(["Agent","Task","agent","cancel_background_job"]),kS=new Set(["Skill","skill"]),vS=new Set(["Compose","compose"]),ZQ=new Set([...SS,...vS,...kS]),GN=new Set(["WebFetch","WebSearch","send_telegram","web_scrape","web_request"]),qN=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),XN=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),zN=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);function Bt(t,e){if(t.has(e))return!0;let n=e.charAt(0).toUpperCase()+e.slice(1);return n!==e&&t.has(n)}var Eu=["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness","workspace_publish","workspace_query",...Ue],TS=[...Eu,"web_scrape","agent"];function _S(t){return t.startsWith("mcp__")||t.startsWith("MCP__")?"mcp":Bt(HN,t)?"read":Bt(WN,t)?"write":Bt(KN,t)?"shell":Bt(SS,t)?"subagent":Bt(kS,t)?"skill":Bt(vS,t)?"dag":Bt(GN,t)?"web":qN.has(t)?"browser":Bt(XN,t)?"planning":zN.has(t)?"schedule":"other"}var JN=["rm -rf","rm ","sudo","eval ","chmod","chown","git push --force","git push -f","git reset --hard","mkfs","fdisk","diskutil eraseDisk","dd if=","dd of=","| sh","| bash","|sh","|bash","-X POST","-X PUT","-X PATCH","-X DELETE","-XPOST","-XPUT","-XPATCH","-XDELETE","--request POST","--request PUT","--request PATCH","--request DELETE","curl --data","curl -d","curl -F","wget --post-data","wget --post-file","launchctl load","launchctl bootstrap","launchctl submit","launchctl start ","launchctl kickstart","launchctl enable ","systemctl enable ","systemctl start ","systemctl daemon-reload"],VN=["git push","git reset","git commit","git stash drop","git stash clear","npm install","pnpm install","yarn","pip install","apt ","apt-get ","brew install","tee "," > "," >> ","mv ","cp ","mkdir","touch","pnpm build","tsc ","eslint --fix"],YN=["pnpm test","vitest","jest","pytest","cargo test","go test","git status","git log","git diff","git show","ls ","cat ","head ","tail ","find ","grep ","echo ","printf "];function QN(t){return typeof t=="object"&&t!==null&&"command"in t?String(t.command??""):typeof t=="string"?t:""}function ZN(t){if(typeof t!="object"||t===null)return"";let e=t;return typeof e.file_path=="string"?e.file_path:typeof e.path=="string"?e.path:""}function AS(t){for(let e of JN)if(t.includes(e))return"high";for(let e of VN)if(t.includes(e))return"medium";for(let e of YN)if(t.includes(e))return"safe";return"medium"}function xS(t,e){if(!t)return"safe";let n=je(ES.resolve(e.cwd,t)),r=ld();for(let o of r)if(n===o||n.startsWith(o+"/"))return"high";if(n.includes("/.git/"))return"high";if(e.workspaceRoot!==void 0){let o=je(e.workspaceRoot);if(ES.relative(o,n).startsWith(".."))return"high"}return n.includes("/node_modules/")?"medium":"safe"}var eU=new Set(["delete","drop","remove","destroy","truncate","purge","wipe","write","create","update","insert","upsert","patch","rename","exec","execute","run","eval","send","push","publish","deploy","post","merge","rollback","reset","terminate","provision","scale","disable","charge","refund","revoke"]);function tU(t){return t.split("__").slice(1).join("__").split(/[_-]+/).filter(Boolean)}function RS(t,e,n){let r=t.toLowerCase();if(r==="bash"){let o=QN(e);return AS(o)}if(r==="write_file"||r==="edit_file"){let o=ZN(e);return xS(o,n)}if(r==="patch_apply"){let o=typeof e=="object"&&e!==null?e:{},s=Array.isArray(o.changes)?o.changes:[],i="safe";for(let a of s){if(typeof a!="object"||a===null)continue;let c=a.path,d=xS(typeof c=="string"?c:"",n);if(d==="high")return"high";d==="medium"&&(i="medium")}return i}if(_S(t)==="read")return"safe";if(r==="send_telegram")return"medium";if(r.startsWith("mcp__"))return tU(r).some(s=>eU.has(s))?"high":"medium";if(r==="create_schedule"||r==="cancel_schedule")return"high";if(r==="worktree"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.action=="string"?o.action:"";return s==="list"?"safe":s==="remove"&&o.force===!0?"high":"medium"}if(r==="browser_act"||r==="browser_open"||r==="web_scrape")return"medium";if(r==="web_request"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.method=="string"?o.method.toUpperCase():"";return s==="DELETE"?"high":s==="GET"||s==="HEAD"||s==="OPTIONS"?"safe":"medium"}if(r==="wait_for"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.type=="string"?o.type:"";if(s==="command"){let i=typeof o.command=="string"?o.command:"";return AS(i)}return s==="file"||s==="process"?"safe":"medium"}return"safe"}async function IS(t,e){let n=t.method??"HEAD",r;try{r=await Nt(globalThis.fetch,t.url,{method:n,signal:e})}catch(a){let c=a instanceof Error?a.message:String(a);return{met:!1,detail:c.startsWith("refusing to")?`SSRF blocked: ${c}`:`fetch error: ${c}`,data:c.startsWith("refusing to")?{blocked:!0}:void 0}}let{status:o}=r,s={status:o};if(!(t.expected_status!==void 0?o===t.expected_status:o>=200&&o<300))return{met:!1,detail:`HTTP ${o} (want ${t.expected_status??"2xx"})`,data:s};if(t.body_contains!==void 0){let a=await r.text().catch(()=>"");if(s.bodyLength=a.length,!a.includes(t.body_contains))return{met:!1,detail:`body does not contain "${t.body_contains}"`,data:s}}else n==="HEAD"&&await r.body?.cancel().catch(()=>{});return{met:!0,detail:`HTTP ${o}`,data:s}}async function CS(t,e){let n;try{let o=t.workspaceRoot?{resolveBase:t.workspaceRoot,cwd:t.workspaceRoot}:void 0;n=oe(t.path,o,"read")}catch(o){return{met:!1,detail:`path rejected: ${o instanceof Error?o.message:String(o)}`,data:{blocked:!0}}}let r;try{let o=await ra.stat(n);r={mtimeMs:o.mtimeMs,size:o.size}}catch{return{met:!1,detail:`file not found: ${t.path}`}}if(t.content_contains!==void 0){let o;try{o=await ra.readFile(n,{encoding:"utf8",signal:e})}catch(s){return{met:!1,detail:`read error: ${s instanceof Error?s.message:String(s)}`,data:r}}if(!o.includes(t.content_contains))return{met:!1,detail:`file exists but does not contain "${t.content_contains}"`,data:r}}return{met:!0,detail:`file exists (${r.size} bytes)`,data:r}}function PS(t,e){if(!Number.isInteger(t.pid)||t.pid<=1)return{met:!1,detail:`pid ${t.pid} is not a valid target (must be integer > 1)`,data:{pid:t.pid,blocked:!0}};if(e!==void 0&&!e.has(t.pid))return{met:!1,detail:`pid ${t.pid} is not a session-owned process (not in spawned PID registry)`,data:{pid:t.pid,blocked:!0}};try{return process.kill(t.pid,0),{met:!1,detail:`pid ${t.pid} is still alive`,data:{pid:t.pid}}}catch(n){let r=n.code;return r==="ESRCH"?{met:!0,detail:`pid ${t.pid} has exited`,data:{pid:t.pid}}:{met:!1,detail:`pid ${t.pid} is alive (${r??"unknown"})`,data:{pid:t.pid}}}}function MS(t){let e=RS("bash",{command:t.command},{cwd:t.cwd??process.cwd()});if(e!=="safe")return{met:!1,detail:`command blocked by risk classifier (${e} risk): ${t.command}`,data:{command:t.command,blocked:!0}};try{return nU(t.command,{cwd:t.cwd,stdio:"pipe",timeout:3e4}),{met:!0,detail:"command exited 0",data:{command:t.command}}}catch(n){let r=n;if(r.killed===!0&&r.signal==="SIGTERM")return{met:!1,detail:"command timed out (30s limit)",data:{command:t.command,timedOut:!0}};let o=r.status??-1;return{met:!1,detail:`command exited ${o}`,data:{command:t.command,exitCode:o}}}}function Re(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=()=>{clearTimeout(o),n()},o=setTimeout(()=>{e.removeEventListener("abort",r),n()},t);o.unref(),e.addEventListener("abort",r,{once:!0})})}var OS=12e4,DS=6e5,FS=5e3,LS=1e3;function rU(t,e,n){switch(n){case"linear":return t+e*1e3;case"exponential":return Math.min(t*Math.pow(2,e),6e4);default:return t}}async function NS(t,e){let{timeout_ms:n,poll_interval_ms:r,backoff:o,signal:s}=e,i=Date.now()+n,a=0,c;for(;;){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};let l=i-Date.now(),d=AbortSignal.any([s,AbortSignal.timeout(Math.max(1,Math.min(r,l)))]),u;try{u=await t(d)}catch(m){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};if(m instanceof Error&&m.name==="AbortError"){if(Date.now()>=i)return{status:"timed_out",elapsed_ms:Date.now()-(i-n),attempts:a,result:c};continue}let g=m instanceof Error?m.message:String(m);return{status:"failed",elapsed_ms:Date.now()-(i-n),attempts:a,error:g}}if(c=u,a++,u.met)return{status:"succeeded",elapsed_ms:Date.now()-(i-n),attempts:a,result:u};let p=Date.now();if(p>=i)return{status:"timed_out",elapsed_ms:p-(i-n),attempts:a,result:c};let f=Math.min(rU(r,a-1,o),i-p);await Re(f,s)}}function oU(t,e){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let n=t,r=n.type;if(typeof r!="string")throw new Error('"type" is required and must be a string');let o=OS;if(n.timeout_ms!==void 0){if(typeof n.timeout_ms!="number"||!Number.isFinite(n.timeout_ms))throw new Error('"timeout_ms" must be a finite number');o=Math.min(Math.max(0,n.timeout_ms),DS)}let s=FS;if(n.poll_interval_ms!==void 0){if(typeof n.poll_interval_ms!="number"||!Number.isFinite(n.poll_interval_ms))throw new Error('"poll_interval_ms" must be a finite number');s=Math.max(LS,n.poll_interval_ms)}let i=["none","linear","exponential"],a="none";if(n.backoff!==void 0){if(!i.includes(n.backoff))throw new Error(`"backoff" must be one of: ${i.join(", ")}`);a=n.backoff}switch(r){case"url":{if(typeof n.url!="string"||n.url.trim()==="")throw new Error('"url" is required for type "url"');let c=n.body_contains!==void 0,l=n.method??(c?"GET":"HEAD");if(l!=="HEAD"&&l!=="GET")throw new Error('"method" must be "HEAD" or "GET"');return{condition:{type:"url",url:n.url,method:l,...n.expected_status!==void 0?{expected_status:Number(n.expected_status)}:{},...c?{body_contains:String(n.body_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"file":{if(typeof n.path!="string"||n.path.trim()==="")throw new Error('"path" is required for type "file"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"file",path:c!==void 0&&!US.isAbsolute(n.path)?US.resolve(c,n.path):n.path,workspaceRoot:c,...n.content_contains!==void 0?{content_contains:String(n.content_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"process":{if(typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=0)throw new Error('"pid" is required for type "process" and must be a positive integer');return{condition:{type:"process",pid:n.pid},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"command":{if(typeof n.command!="string"||n.command.trim()==="")throw new Error('"command" is required for type "command"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"command",command:n.command,...c!==void 0?{cwd:c}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}default:throw new Error(`Unknown type "${r}". Must be one of: url, file, process, command`)}}var $S=async(t,e,n)=>{let r;try{r=oU(t,n)}catch(u){return{content:u instanceof Error?u.message:String(u),isError:!0}}let{condition:o,timeoutMs:s,pollIntervalMs:i,backoff:a}=r;if(o.type==="url"){let u=await un(o.url);if(!u.allowed)return{content:`SSRF guard blocked: ${u.reason}`,isError:!0}}let l=await NS(u=>{switch(o.type){case"url":return IS(o,u);case"file":return CS(o,u);case"process":return Promise.resolve(PS(o,n?.spawnedPidRegistry));case"command":return Promise.resolve(MS(o))}},{timeout_ms:s,poll_interval_ms:i,backoff:a,signal:e});return{content:`Wait ${l.status}: ${o.type} condition (${l.elapsed_ms}ms elapsed, ${l.attempts} attempt${l.attempts===1?"":"s"})`+(l.result?` \u2014 ${l.result.detail}`:"")+(l.error?` \u2014 error: ${l.error}`:""),isError:l.status==="failed"}};import{resolve as kU}from"path";import{createHash as sU}from"crypto";import{readFile as iU}from"fs/promises";function aU(t){return sU("sha256").update(t,"utf8").digest("hex")}function cU(t,e){if(e.length===0)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=e.length;return n}async function BS(t,e,n){let r=[],o=new Map;for(let s of t){let i=s.path,a;try{a=oe(i,n,"write",e)}catch(l){r.push({path:i,error:"path_containment",detail:l instanceof Error?l.message:String(l)});continue}try{Un(a,"patch_apply")}catch(l){r.push({path:i,error:"write_denied",detail:l instanceof Error?l.message:String(l)});continue}if(s.edits!==void 0&&s.content!==void 0){r.push({path:i,error:"mutually_exclusive",detail:"`edits` and `content` cannot both be provided for the same file."});continue}if(s.edits===void 0&&s.content===void 0){r.push({path:i,error:"no_change_specified",detail:"At least one of `edits` or `content` must be provided."});continue}let c;try{c=await iU(a,"utf-8")}catch(l){if(s.expected_hash!==void 0||s.edits!==void 0){r.push({path:i,error:"file_read_failed",detail:l instanceof Error?l.message:String(l)});continue}o.set(a,null),c=""}if(o.has(a)||o.set(a,c),s.expected_hash!==void 0){let l="sha256:";if(!s.expected_hash.startsWith(l)){r.push({path:i,error:"invalid_hash_format",detail:`expected_hash must start with "sha256:". Got: "${s.expected_hash}"`});continue}let d=s.expected_hash.slice(l.length),u=aU(c);if(u!==d){r.push({path:i,error:"hash_mismatch",detail:`File hash mismatch. Expected sha256:${d}, got sha256:${u}. The file may have been modified.`});continue}}if(s.edits!==void 0){let l=c;for(let d=0;d<s.edits.length;d++){let u=s.edits[d],p=cU(l,u.old);if(p===0){r.push({path:i,error:"edit_not_found",detail:`Edit #${d+1}: \`old\` string not found in file.`});break}else if(p>1)r.push({path:i,error:"edit_ambiguous",detail:`Edit #${d+1}: \`old\` string matches ${p} locations. Provide enough context to make it unique.`});else{let f=l.indexOf(u.old);l=l.slice(0,f)+u.new+l.slice(f+u.old.length)}}}}return{valid:r.length===0,errors:r,fileContents:o}}import{createHash as lU,randomBytes as dU}from"crypto";import{writeFile as jS,rename as uU,mkdir as pU,unlink as Au,chmod as fU,stat as mU}from"fs/promises";import{dirname as WS,join as gU,isAbsolute as hU,resolve as yU}from"path";function HS(t){return lU("sha256").update(t,"utf8").digest("hex")}function bU(t,e,n){let r=Hn(e,n);if(!r)return"";let o=[`--- a/${t}`,`+++ b/${t}`];for(let s of r.hunks){o.push(`@@ -${s.oldStart},${s.oldLines} +${s.newStart},${s.newLines} @@`);for(let i of s.lines)o.push(`${i.kind}${i.text}`)}return o.join(`
|
|
302
|
+
`)}function LN(t){return t.kind==="semantic"?{kind:"semantic",text:nb(t.text),...t.role!==void 0?{role:t.role}:{}}:t.kind==="element_id"?{kind:"element_id",elementId:t.elementId}:{kind:"selector",selectorHash:tb(t.selector)}}function NN(t={}){return async(e,n,r)=>{if(n.aborted){let u=n.reason;return{content:`browser_act aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0,failureClass:ye(n)}}let o=DN(e);if("error"in o)return{content:o.error,isError:!0};let s=LN(o.target),i=y.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let a,c,l;try{if(t.getBrowserProvider)a=await t.getBrowserProvider();else{let{getBrowserProvider:u,getLastRoutingDecision:p}=await Promise.resolve().then(()=>(gn(),mn));a=await u();let f=p();f&&(c=f.backend,l=f.reason)}}catch(u){let p=u instanceof Error?u.message:String(u);return xe(p)?{content:He(p),isError:!0}:{content:`browser_act failed to get provider: ${p}`,isError:!0}}let d=Date.now();try{let u=await a.act({sessionId:i,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),p=Date.now()-d;if("outcome"in u){if(u.outcome==="ambiguous_target")return ie(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:p}),{content:FN(u.query,u.candidates),isError:!0};if(u.outcome==="blocked_by_policy")return ie(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:p}),{content:`browser_act blocked: ${u.reason}`,isError:!0,failureClass:"policy-refusal"}}return ie(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:u.url,urlAfter:u.url,status:"ok",durationMs:p,...u.screenshotPath!==null?{screenshotPath:u.screenshotPath}:{}}),{content:JSON.stringify(u,null,2)}}catch(u){let p=Date.now()-d,f=u instanceof Error?u.message:String(u);ie(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"error",durationMs:p,error:{reason:f,recoverable:!1}});let m=Hi(u);return{content:`browser_act failed: ${f}`,isError:!0,...m?{failureClass:m}:{}}}}}var hS=NN();C();var yS=["semantic","element_id","selector"],_u=8e3;function UN(t){if(typeof t.kind!="string"||!yS.includes(t.kind))return{error:`browser_screenshot: "target.kind" must be one of ${yS.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(t.kind)})`};let e=t.kind;return e==="semantic"?typeof t.text!="string"||t.text.length===0?{error:'browser_screenshot: target.kind=semantic requires "target.text" (non-empty string)'}:{kind:"semantic",text:t.text,...typeof t.role=="string"&&t.role.length>0?{role:t.role}:{}}:e==="element_id"?typeof t.element_id!="string"||t.element_id.length===0?{error:'browser_screenshot: target.kind=element_id requires "target.element_id" (non-empty string)'}:{kind:"element_id",elementId:t.element_id}:typeof t.selector!="string"||t.selector.length===0?{error:'browser_screenshot: target.kind=selector requires "target.selector" (non-empty string)'}:{kind:"selector",selector:t.selector}}function $N(t){if(t!=null&&typeof t!="object")return{error:"browser_screenshot: input must be an object or omitted"};if(!t)return{};let e=t,n;if(e.target!==void 0){if(!e.target||typeof e.target!="object")return{error:'browser_screenshot: "target" must be an object when provided'};let o=UN(e.target);if("error"in o)return o;n=o}let r;if(e.full_page!==void 0){if(typeof e.full_page!="boolean")return{error:'browser_screenshot: "full_page" must be a boolean'};r=e.full_page}return{target:n,fullPage:r}}function BN(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_screenshot aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let o=$N(e);if("error"in o)return{content:o.error,isError:!0};let s=y.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(gn(),mn));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return xe(u)?{content:He(u),isError:!0}:{content:`browser_screenshot failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.screenshot({sessionId:s,target:o.target,fullPage:o.fullPage}),u=Date.now()-l,{dataBase64:p,mediaType:f,...m}=d;return ie(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:u,screenshotPath:m.path}),m.width>_u||m.height>_u?{content:JSON.stringify({...m,imageOmitted:`dimensions ${m.width}x${m.height}px exceed the ${_u}px model-vision limit; the PNG was saved to the sidecar path but not attached. Use full_page:false (viewport) or target a specific element for a model-visible image.`},null,2)}:{content:JSON.stringify(m,null,2),image:{mediaType:f,data:p}}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);return ie(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}}),{content:`browser_screenshot failed: ${p}`,isError:!0}}}}var bS=BN();C();function jN(t={}){return async(e,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_close aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=y.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(o))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(o)}`,isError:!0};let s,i,a;try{if(t.getBrowserProvider)s=await t.getBrowserProvider();else{let{getBrowserProvider:l,getLastRoutingDecision:d}=await Promise.resolve().then(()=>(gn(),mn));s=await l();let u=d();u&&(i=u.backend,a=u.reason)}}catch(l){let d=l instanceof Error?l.message:String(l);return xe(d)?{content:He(d),isError:!0}:{content:`browser_close failed to get provider: ${d}`,isError:!0}}let c=Date.now();try{await s.close({sessionId:o});let l=Date.now()-c;return ie(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:l}),{content:"Browser session closed."}}catch(l){let d=Date.now()-c,u=l instanceof Error?l.message:String(l);return ie(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:d,error:{reason:u,recoverable:!1}}),{content:`browser_close failed: ${u}`,isError:!0}}}}var wS=jN();import US from"node:path";import*as ra from"node:fs/promises";import{execSync as nU}from"node:child_process";import ES from"path";var HN=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","workspace_query","read_witness","search_witness"]),WN=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","patch_apply","memory_update","procedure_write","terminal_font_size","config_set","workspace_publish"]),KN=new Set(["Bash","BashOutput","KillBash","bash","test_run","wait_for"]),SS=new Set(["Agent","Task","agent","cancel_background_job"]),kS=new Set(["Skill","skill"]),vS=new Set(["Compose","compose"]),ZQ=new Set([...SS,...vS,...kS]),GN=new Set(["WebFetch","WebSearch","send_telegram","web_scrape","web_request"]),qN=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),XN=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),zN=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);function Bt(t,e){if(t.has(e))return!0;let n=e.charAt(0).toUpperCase()+e.slice(1);return n!==e&&t.has(n)}var Eu=["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness","workspace_publish","workspace_query",...Ue],TS=[...Eu,"web_scrape","agent"];function _S(t){return t.startsWith("mcp__")||t.startsWith("MCP__")?"mcp":Bt(HN,t)?"read":Bt(WN,t)?"write":Bt(KN,t)?"shell":Bt(SS,t)?"subagent":Bt(kS,t)?"skill":Bt(vS,t)?"dag":Bt(GN,t)?"web":qN.has(t)?"browser":Bt(XN,t)?"planning":zN.has(t)?"schedule":"other"}var JN=["rm -rf","rm ","sudo","eval ","chmod","chown","git push --force","git push -f","git reset --hard","mkfs","fdisk","diskutil eraseDisk","dd if=","dd of=","| sh","| bash","|sh","|bash","-X POST","-X PUT","-X PATCH","-X DELETE","-XPOST","-XPUT","-XPATCH","-XDELETE","--request POST","--request PUT","--request PATCH","--request DELETE","curl --data","curl -d","curl -F","wget --post-data","wget --post-file","launchctl load","launchctl bootstrap","launchctl submit","launchctl start ","launchctl kickstart","launchctl enable ","systemctl enable ","systemctl start ","systemctl daemon-reload"],VN=["git push","git reset","git commit","git stash drop","git stash clear","npm install","pnpm install","yarn","pip install","apt ","apt-get ","brew install","tee "," > "," >> ","mv ","cp ","mkdir","touch","pnpm build","tsc ","eslint --fix"],YN=["pnpm test","vitest","jest","pytest","cargo test","go test","git status","git log","git diff","git show","ls ","cat ","head ","tail ","find ","grep ","echo ","printf "];function QN(t){return typeof t=="object"&&t!==null&&"command"in t?String(t.command??""):typeof t=="string"?t:""}function ZN(t){if(typeof t!="object"||t===null)return"";let e=t;return typeof e.file_path=="string"?e.file_path:typeof e.path=="string"?e.path:""}function AS(t){for(let e of JN)if(t.includes(e))return"high";for(let e of VN)if(t.includes(e))return"medium";for(let e of YN)if(t.includes(e))return"safe";return"medium"}function xS(t,e){if(!t)return"safe";let n=je(ES.resolve(e.cwd,t)),r=ld();for(let o of r)if(n===o||n.startsWith(o+"/"))return"high";if(n.includes("/.git/"))return"high";if(e.workspaceRoot!==void 0){let o=je(e.workspaceRoot);if(ES.relative(o,n).startsWith(".."))return"high"}return n.includes("/node_modules/")?"medium":"safe"}var eU=new Set(["delete","drop","remove","destroy","truncate","purge","wipe","write","create","update","insert","upsert","patch","rename","exec","execute","run","eval","send","push","publish","deploy","post","merge","rollback","reset","terminate","provision","scale","disable","charge","refund","revoke"]);function tU(t){return t.split("__").slice(1).join("__").split(/[_-]+/).filter(Boolean)}function RS(t,e,n){let r=t.toLowerCase();if(r==="bash"){let o=QN(e);return AS(o)}if(r==="write_file"||r==="edit_file"){let o=ZN(e);return xS(o,n)}if(r==="patch_apply"){let o=typeof e=="object"&&e!==null?e:{},s=Array.isArray(o.changes)?o.changes:[],i="safe";for(let a of s){if(typeof a!="object"||a===null)continue;let c=a.path,d=xS(typeof c=="string"?c:"",n);if(d==="high")return"high";d==="medium"&&(i="medium")}return i}if(_S(t)==="read")return"safe";if(r==="send_telegram")return"medium";if(r.startsWith("mcp__"))return tU(r).some(s=>eU.has(s))?"high":"medium";if(r==="create_schedule"||r==="cancel_schedule")return"high";if(r==="worktree"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.action=="string"?o.action:"";return s==="list"?"safe":s==="remove"&&o.force===!0?"high":"medium"}if(r==="browser_act"||r==="browser_open"||r==="web_scrape")return"medium";if(r==="web_request"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.method=="string"?o.method.toUpperCase():"";return s==="DELETE"?"high":s==="GET"||s==="HEAD"||s==="OPTIONS"?"safe":"medium"}if(r==="wait_for"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.type=="string"?o.type:"";if(s==="command"){let i=typeof o.command=="string"?o.command:"";return AS(i)}return s==="file"||s==="process"?"safe":"medium"}return"safe"}async function IS(t,e){let n=t.method??"HEAD",r;try{r=await Nt(globalThis.fetch,t.url,{method:n,signal:e})}catch(a){let c=a instanceof Error?a.message:String(a);return{met:!1,detail:c.startsWith("refusing to")?`SSRF blocked: ${c}`:`fetch error: ${c}`,data:c.startsWith("refusing to")?{blocked:!0}:void 0}}let{status:o}=r,s={status:o};if(!(t.expected_status!==void 0?o===t.expected_status:o>=200&&o<300))return{met:!1,detail:`HTTP ${o} (want ${t.expected_status??"2xx"})`,data:s};if(t.body_contains!==void 0){let a=await r.text().catch(()=>"");if(s.bodyLength=a.length,!a.includes(t.body_contains))return{met:!1,detail:`body does not contain "${t.body_contains}"`,data:s}}else n==="HEAD"&&await r.body?.cancel().catch(()=>{});return{met:!0,detail:`HTTP ${o}`,data:s}}async function CS(t,e){let n;try{let o=t.workspaceRoot?{resolveBase:t.workspaceRoot,cwd:t.workspaceRoot}:void 0;n=oe(t.path,o,"read")}catch(o){return{met:!1,detail:`path rejected: ${o instanceof Error?o.message:String(o)}`,data:{blocked:!0}}}let r;try{let o=await ra.stat(n);r={mtimeMs:o.mtimeMs,size:o.size}}catch{return{met:!1,detail:`file not found: ${t.path}`}}if(t.content_contains!==void 0){let o;try{o=await ra.readFile(n,{encoding:"utf8",signal:e})}catch(s){return{met:!1,detail:`read error: ${s instanceof Error?s.message:String(s)}`,data:r}}if(!o.includes(t.content_contains))return{met:!1,detail:`file exists but does not contain "${t.content_contains}"`,data:r}}return{met:!0,detail:`file exists (${r.size} bytes)`,data:r}}function PS(t,e){if(!Number.isInteger(t.pid)||t.pid<=1)return{met:!1,detail:`pid ${t.pid} is not a valid target (must be integer > 1)`,data:{pid:t.pid,blocked:!0}};if(e!==void 0&&!e.has(t.pid))return{met:!1,detail:`pid ${t.pid} is not a session-owned process (not in spawned PID registry)`,data:{pid:t.pid,blocked:!0}};try{return process.kill(t.pid,0),{met:!1,detail:`pid ${t.pid} is still alive`,data:{pid:t.pid}}}catch(n){let r=n.code;return r==="ESRCH"?{met:!0,detail:`pid ${t.pid} has exited`,data:{pid:t.pid}}:{met:!1,detail:`pid ${t.pid} is alive (${r??"unknown"})`,data:{pid:t.pid}}}}function MS(t){let e=RS("bash",{command:t.command},{cwd:t.cwd??process.cwd()});if(e!=="safe")return{met:!1,detail:`command blocked by risk classifier (${e} risk): ${t.command}`,data:{command:t.command,blocked:!0}};try{return nU(t.command,{cwd:t.cwd,stdio:"pipe",timeout:3e4}),{met:!0,detail:"command exited 0",data:{command:t.command}}}catch(n){let r=n;if(r.killed===!0&&r.signal==="SIGTERM")return{met:!1,detail:"command timed out (30s limit)",data:{command:t.command,timedOut:!0}};let o=r.status??-1;return{met:!1,detail:`command exited ${o}`,data:{command:t.command,exitCode:o}}}}function Re(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=()=>{clearTimeout(o),n()},o=setTimeout(()=>{e.removeEventListener("abort",r),n()},t);o.unref(),e.addEventListener("abort",r,{once:!0})})}var OS=12e4,DS=6e5,FS=5e3,LS=1e3;function rU(t,e,n){switch(n){case"linear":return t+e*1e3;case"exponential":return Math.min(t*Math.pow(2,e),6e4);default:return t}}async function NS(t,e){let{timeout_ms:n,poll_interval_ms:r,backoff:o,signal:s}=e,i=Date.now()+n,a=0,c;for(;;){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};let l=i-Date.now(),d=AbortSignal.any([s,AbortSignal.timeout(Math.max(1,Math.min(r,l)))]),u;try{u=await t(d)}catch(m){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};if(m instanceof Error&&m.name==="AbortError"){if(Date.now()>=i)return{status:"timed_out",elapsed_ms:Date.now()-(i-n),attempts:a,result:c};continue}let g=m instanceof Error?m.message:String(m);return{status:"failed",elapsed_ms:Date.now()-(i-n),attempts:a,error:g}}if(c=u,a++,u.met)return{status:"succeeded",elapsed_ms:Date.now()-(i-n),attempts:a,result:u};let p=Date.now();if(p>=i)return{status:"timed_out",elapsed_ms:p-(i-n),attempts:a,result:c};let f=Math.min(rU(r,a-1,o),i-p);await Re(f,s)}}function oU(t,e){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let n=t,r=n.type;if(typeof r!="string")throw new Error('"type" is required and must be a string');let o=OS;if(n.timeout_ms!==void 0){if(typeof n.timeout_ms!="number"||!Number.isFinite(n.timeout_ms))throw new Error('"timeout_ms" must be a finite number');o=Math.min(Math.max(0,n.timeout_ms),DS)}let s=FS;if(n.poll_interval_ms!==void 0){if(typeof n.poll_interval_ms!="number"||!Number.isFinite(n.poll_interval_ms))throw new Error('"poll_interval_ms" must be a finite number');s=Math.max(LS,n.poll_interval_ms)}let i=["none","linear","exponential"],a="none";if(n.backoff!==void 0){if(!i.includes(n.backoff))throw new Error(`"backoff" must be one of: ${i.join(", ")}`);a=n.backoff}switch(r){case"url":{if(typeof n.url!="string"||n.url.trim()==="")throw new Error('"url" is required for type "url"');let c=n.body_contains!==void 0,l=n.method??(c?"GET":"HEAD");if(l!=="HEAD"&&l!=="GET")throw new Error('"method" must be "HEAD" or "GET"');return{condition:{type:"url",url:n.url,method:l,...n.expected_status!==void 0?{expected_status:Number(n.expected_status)}:{},...c?{body_contains:String(n.body_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"file":{if(typeof n.path!="string"||n.path.trim()==="")throw new Error('"path" is required for type "file"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"file",path:c!==void 0&&!US.isAbsolute(n.path)?US.resolve(c,n.path):n.path,workspaceRoot:c,...n.content_contains!==void 0?{content_contains:String(n.content_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"process":{if(typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=1)throw new Error('"pid" is required for type "process" and must be an integer > 1');return{condition:{type:"process",pid:n.pid},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"command":{if(typeof n.command!="string"||n.command.trim()==="")throw new Error('"command" is required for type "command"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"command",command:n.command,...c!==void 0?{cwd:c}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}default:throw new Error(`Unknown type "${r}". Must be one of: url, file, process, command`)}}var $S=async(t,e,n)=>{let r;try{r=oU(t,n)}catch(u){return{content:u instanceof Error?u.message:String(u),isError:!0}}let{condition:o,timeoutMs:s,pollIntervalMs:i,backoff:a}=r;if(o.type==="url"){let u=await un(o.url);if(!u.allowed)return{content:`SSRF guard blocked: ${u.reason}`,isError:!0}}let l=await NS(u=>{switch(o.type){case"url":return IS(o,u);case"file":return CS(o,u);case"process":return Promise.resolve(PS(o,n?.spawnedPidRegistry));case"command":return Promise.resolve(MS(o))}},{timeout_ms:s,poll_interval_ms:i,backoff:a,signal:e});return{content:`Wait ${l.status}: ${o.type} condition (${l.elapsed_ms}ms elapsed, ${l.attempts} attempt${l.attempts===1?"":"s"})`+(l.result?` \u2014 ${l.result.detail}`:"")+(l.error?` \u2014 error: ${l.error}`:""),isError:l.status==="failed"}};import{resolve as kU}from"path";import{createHash as sU}from"crypto";import{readFile as iU}from"fs/promises";function aU(t){return sU("sha256").update(t,"utf8").digest("hex")}function cU(t,e){if(e.length===0)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=e.length;return n}async function BS(t,e,n){let r=[],o=new Map;for(let s of t){let i=s.path,a;try{a=oe(i,n,"write",e)}catch(l){r.push({path:i,error:"path_containment",detail:l instanceof Error?l.message:String(l)});continue}try{Un(a,"patch_apply")}catch(l){r.push({path:i,error:"write_denied",detail:l instanceof Error?l.message:String(l)});continue}if(s.edits!==void 0&&s.content!==void 0){r.push({path:i,error:"mutually_exclusive",detail:"`edits` and `content` cannot both be provided for the same file."});continue}if(s.edits===void 0&&s.content===void 0){r.push({path:i,error:"no_change_specified",detail:"At least one of `edits` or `content` must be provided."});continue}let c;try{c=await iU(a,"utf-8")}catch(l){if(s.expected_hash!==void 0||s.edits!==void 0){r.push({path:i,error:"file_read_failed",detail:l instanceof Error?l.message:String(l)});continue}o.set(a,null),c=""}if(o.has(a)||o.set(a,c),s.expected_hash!==void 0){let l="sha256:";if(!s.expected_hash.startsWith(l)){r.push({path:i,error:"invalid_hash_format",detail:`expected_hash must start with "sha256:". Got: "${s.expected_hash}"`});continue}let d=s.expected_hash.slice(l.length),u=aU(c);if(u!==d){r.push({path:i,error:"hash_mismatch",detail:`File hash mismatch. Expected sha256:${d}, got sha256:${u}. The file may have been modified.`});continue}}if(s.edits!==void 0){let l=c;for(let d=0;d<s.edits.length;d++){let u=s.edits[d],p=cU(l,u.old);if(p===0){r.push({path:i,error:"edit_not_found",detail:`Edit #${d+1}: \`old\` string not found in file.`});break}else if(p>1)r.push({path:i,error:"edit_ambiguous",detail:`Edit #${d+1}: \`old\` string matches ${p} locations. Provide enough context to make it unique.`});else{let f=l.indexOf(u.old);l=l.slice(0,f)+u.new+l.slice(f+u.old.length)}}}}return{valid:r.length===0,errors:r,fileContents:o}}import{createHash as lU,randomBytes as dU}from"crypto";import{writeFile as jS,rename as uU,mkdir as pU,unlink as Au,chmod as fU,stat as mU}from"fs/promises";import{dirname as WS,join as gU,isAbsolute as hU,resolve as yU}from"path";function HS(t){return lU("sha256").update(t,"utf8").digest("hex")}function bU(t,e,n){let r=Hn(e,n);if(!r)return"";let o=[`--- a/${t}`,`+++ b/${t}`];for(let s of r.hunks){o.push(`@@ -${s.oldStart},${s.oldLines} +${s.newStart},${s.newLines} @@`);for(let i of s.lines)o.push(`${i.kind}${i.text}`)}return o.join(`
|
|
303
303
|
`)+`
|
|
304
304
|
`}function wU(t,e){let n=t;for(let r of e){let o=n.indexOf(r.old);if(o===-1)throw new Error("patch_apply engine: edit old-string not found at apply time (validation may have passed a stale snapshot).");n=n.slice(0,o)+r.new+n.slice(o+r.old.length)}return n}function SU(t){let e=dU(8).toString("hex");return gU(WS(t),`.patch-tmp-${e}`)}async function KS(t,e,n,r){let o=[];for(let u of t){let p=hU(u.path)?u.path:yU(n,u.path),f=e.get(p),m=f===null,g=f??"",h;if(u.content!==void 0)h=u.content;else if(u.edits!==void 0)h=wU(g,u.edits);else throw new Error(`patch_apply engine: change for ${u.path} has neither content nor edits.`);let b=bU(u.path,g,h);o.push({resolvedPath:p,originalContent:g,newContent:h,diffBlock:b,isNewFile:m})}let s=o.map(u=>u.diffBlock).filter(Boolean).join(`
|
|
305
305
|
`),i=o.map(u=>({path:u.resolvedPath,before_hash:`sha256:${HS(u.originalContent)}`,after_hash:`sha256:${HS(u.newContent)}`}));if(r)return{status:"dry_run",diff:s,files_changed:i,errors:[]};let a=[],c=[];for(let u of o){let p=SU(u.resolvedPath);try{let f;if(!u.isNewFile)try{f=(await mU(u.resolvedPath)).mode}catch{}await pU(WS(u.resolvedPath),{recursive:!0}),await jS(p,u.newContent,"utf-8"),f!==void 0&&await fU(p,f),a.push({tempPath:p,targetPath:u.resolvedPath,originalMode:f})}catch(f){c.push({path:u.resolvedPath,error:"temp_write_failed",detail:f instanceof Error?f.message:String(f)})}}if(c.length>0){for(let u of a)try{await Au(u.tempPath)}catch{}return{status:"partial_failure",diff:s,files_changed:i,errors:c}}let l=[],d=[];for(let u=0;u<a.length;u++){let p=a[u];try{await uU(p.tempPath,p.targetPath),d.push({targetPath:p.targetPath,originalContent:o[u].originalContent,isNewFile:o[u].isNewFile})}catch(f){l.push({path:p.targetPath,error:"rename_failed",detail:f instanceof Error?f.message:String(f)})}}if(l.length>0){for(let u of d)try{u.isNewFile?await Au(u.targetPath):await jS(u.targetPath,u.originalContent,"utf-8")}catch{}for(let u of a)try{await Au(u.tempPath)}catch{}return{status:"partial_failure",diff:s,files_changed:i,errors:l}}return{status:"applied",diff:s,files_changed:i,errors:[]}}function vU(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object.");let e=t;if(!Array.isArray(e.changes))throw new Error('Input must have a "changes" field of type array.');let n=[];for(let o=0;o<e.changes.length;o++){let s=e.changes[o];if(typeof s!="object"||s===null)throw new Error(`changes[${o}] must be an object.`);let i=s;if(typeof i.path!="string"||i.path.trim()==="")throw new Error(`changes[${o}].path must be a non-empty string.`);let a={path:i.path};if(i.expected_hash!==void 0){if(typeof i.expected_hash!="string")throw new Error(`changes[${o}].expected_hash must be a string.`);a.expected_hash=i.expected_hash}if(i.content!==void 0){if(typeof i.content!="string")throw new Error(`changes[${o}].content must be a string.`);a.content=i.content}if(i.edits!==void 0){if(!Array.isArray(i.edits))throw new Error(`changes[${o}].edits must be an array.`);let c=[];for(let l=0;l<i.edits.length;l++){let d=i.edits[l];if(typeof d!="object"||d===null)throw new Error(`changes[${o}].edits[${l}] must be an object.`);let u=d;if(typeof u.old!="string")throw new Error(`changes[${o}].edits[${l}].old must be a string.`);if(typeof u.new!="string")throw new Error(`changes[${o}].edits[${l}].new must be a string.`);c.push({old:u.old,new:u.new})}a.edits=c}n.push(a)}let r=!1;if(e.dry_run!==void 0){if(typeof e.dry_run!="boolean")throw new Error("dry_run must be a boolean.");r=e.dry_run}return{changes:n,dry_run:r}}function xu(t){return async(e,n,r)=>{let o=r?.resolveBase??r?.cwd??t??kU(process.cwd()),s;try{s=vU(e)}catch(u){return{content:u instanceof Error?u.message:String(u),isError:!0}}let{changes:i,dry_run:a}=s;if(i.length===0)return{content:JSON.stringify({status:"applied",diff:"",files_changed:[],errors:[]},null,2),isError:!1};let c=await BS(i,o,r);if(!c.valid){let u={status:"validation_failed",diff:"",files_changed:[],errors:c.errors};return{content:JSON.stringify(u,null,2),isError:!0}}let l=await KS(i,c.fileContents,o,a),d=l.status==="validation_failed"||l.status==="partial_failure";return{content:JSON.stringify({status:l.status,diff:l.diff,files_changed:l.files_changed,errors:l.errors},null,2),isError:d}}}var GS=xu();import{spawn as LU}from"child_process";import Ru from"fs";import Pe from"path";function ot(t){try{return Ru.accessSync(t),!0}catch{return!1}}function Iu(t){try{return Ru.readFileSync(t,"utf8")}catch{return null}}function TU(t){return ot(Pe.join(t,"pnpm-lock.yaml"))?"pnpm":ot(Pe.join(t,"yarn.lock"))?"yarn":ot(Pe.join(t,"bun.lockb"))?"bun":"npm"}function _U(t){return/\bvitest\b/.test(t)?"vitest":/\bjest\b/.test(t)?"jest":/\bmocha\b/.test(t)?"mocha":null}function EU(t){let e=Pe.join(t,"package.json"),n=Iu(e);if(!n)return null;let r;try{r=JSON.parse(n)}catch{return null}let o=r.scripts;if(!o||typeof o!="object")return null;let s=TU(t);for(let i of["test:unit","test:integration","test"]){let a=o[i];if(typeof a!="string"||!a.trim())continue;let c=_U(a)??"node-generic",l=`${s} run ${i}`;return{runner:c,command:l,args:[s,"run",i]}}return null}function AU(t){let e=Pe.join(t,"pyproject.toml"),n=Iu(e);return n?/\[tool\.pytest/.test(n)?{runner:"pytest",command:"pytest",args:["pytest"]}:ot(Pe.join(t,"pytest.ini"))||ot(Pe.join(t,"setup.cfg"))?{runner:"pytest",command:"pytest",args:["pytest"]}:null:null}function xU(t){return ot(Pe.join(t,"Cargo.toml"))?{runner:"cargo",command:"cargo test",args:["cargo","test"]}:null}function RU(t){let n=(()=>{try{return Ru.readdirSync(t)}catch{return[]}})().some(r=>r.endsWith("_test.go"));return(n||ot(Pe.join(t,"go.mod")))&&(n||ot(Pe.join(t,"go.mod")))?{runner:"go-test",command:"go test ./...",args:["go","test","./..."]}:null}function IU(t){return ot(Pe.join(t,"Gemfile"))&&ot(Pe.join(t,"spec"))?{runner:"rspec",command:"bundle exec rspec",args:["bundle","exec","rspec"]}:null}function CU(t){let e=Iu(Pe.join(t,"Makefile"));return e&&/^test:/m.test(e)?{runner:"node-generic",command:"make test",args:["make","test"]}:null}function qS(t){return EU(t)??AU(t)??xU(t)??RU(t)??IU(t)??CU(t)??null}function PU(t){let e=[],n=/^\s*●\s+(.+?)\s*$/gm,r=/^FAIL\s+(.+\.(?:test|spec)\.[jt]sx?)\s*$/gm,o=t.split(`
|