agent-afk 5.222.3 → 5.222.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +3 -3
- package/dist/config/env.d.ts +8 -0
- package/dist/index.mjs +225 -225
- package/dist/telegram/session-manager.d.ts +1 -0
- package/dist/telegram/session-manager.demand-load.d.ts +3 -0
- package/dist/telegram.mjs +303 -303
- package/dist/web-ui-assets/assets/{index-DpEHdhDh.js → index-D7vSiG8f.js} +1 -1
- package/dist/web-ui-assets/assets/{index-C8iQq5Dx.js → index-pNhgW5dG.js} +47 -47
- package/dist/web-ui-assets/index.html +1 -1
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Jye=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var lt=(e,t)=>{for(var n in t)Jye(e,n,{get:t[n],enumerable:!0})};function Sa(e){return Fc.find(t=>t.name===e)}function NC(e){return Fc.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function Lc(e){return process.env[e]!==void 0}function hb(e){let t=process.env[e];return t===void 0||t===""?void 0:t}function BC(e){return/^(0|false|no|off)$/i.test(e.trim())}function va(e){return/^(1|true|yes|on)$/i.test(e.trim())}var OU=y(()=>{"use strict";F()});function Ke(){let e=k.AFK_PLAIN_OUTPUT;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"}var Fc,DU,k,F=y(()=>{"use strict";OU();Fc=[{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_DISABLE_SPINE_UPDATE",description:"Disable the SPINE.md SessionEnd hook when set to 1. The hook runs a single LLM call at the end of each top-level session to classify architectural signals in the git diff against SPINE.md. Set to 1 to opt out globally (useful in CI or when the LLM call is unwanted).",type:"boolean",required:!1,default:"0",example:"1",category:"misc"},{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:'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. On by default. Set to 0 to disable.',type:"boolean",required:!1,default:"1",example:"0",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. On by default. Set to 0/false/no/off to disable.",type:"boolean",required:!1,default:"1",example:"0",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. On by default. Set to 0/false/no/off to disable. Requires AFK_SUGGEST_ENABLED (it reuses the same suggestion model and provider).",type:"boolean",required:!1,default:"1",example:"0",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 (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:"Use ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. Off by default. Set to 1/true/yes/on to enable. 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_DAEMON_SHELL_TIMEOUT_MS",description:"Wall-clock timeout in milliseconds for executor:shell scheduled tasks. Defaults to 300000 (5 minutes). The child process is killed on timeout.",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_BASH_PREVIEW_HEAD_LINES",description:"Number of leading non-empty lines shown in the bash output head block of the TUI outcome preview. 0 (default) disables the head block entirely. Accepted range 0\u2013200; non-integer, negative, or out-of-range input falls back to the default. When head + tail >= total non-empty lines, all lines are shown without a hidden-line notice. Keep preview preferences separate from model-context caps (AFK_BASH_PREVIEW_TAIL_LINES).",type:"number",required:!1,default:"0",example:"3",category:"misc"},{name:"AFK_BASH_PREVIEW_TAIL_LINES",description:"Number of trailing non-empty lines shown in the bash output tail block of the TUI outcome preview. Default 7 (compact tail-first preview). Accepted range 0\u2013200; non-integer, negative, or out-of-range input falls back to the default. When head + tail >= total non-empty lines, all lines are shown without a hidden-line notice. Keep preview preferences separate from model-context caps (AFK_BASH_PREVIEW_HEAD_LINES).",type:"number",required:!1,default:"7",example:"10",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_TURN_SEPARATOR",description:"Render a dim horizontal rule between conversation turns in the REPL. 0 = off, unset/1 = on (default). TTY-only: piped/one-shot output (afk chat) never emits the rule.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_STREAM_BUFFER_MS",description:"Input buffer window for TUI streaming in milliseconds. When set to a positive value, incoming tokens are micro-batched before parsing and rendering, producing smoother visual output. The first token after idle always passes through immediately (leading-edge). 0 = disabled (every token is parsed individually). Reasonable range: 8-50.",type:"number",required:!1,default:"0",example:"16",category:"display"},{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:"AFK_PROSE_MEASURE",description:"Maximum line length (columns) for prose-only blocks (paragraphs, list items, blockquotes) in the interactive REPL. Code fences use the wider AFK_TEXT_MEASURE (default 100). When AFK_TEXT_MEASURE is explicitly set, it overrides this value for backward compatibility. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable. Unparseable or below-minimum values fall back to the default.",type:"string",required:!1,default:"80",example:"72",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:"Capture subagent conversational OUTPUT (assistant text plus each tool call with its arguments) as 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. Set to 1 to enable. Note: best-effort regex redaction only \u2014 connection strings, PEM blocks, and PII are not caught.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SUBAGENT_RESULT_CAP_BYTES",description:"Foreground subagent result size cap in bytes. When a subagent's final message exceeds this threshold, the full output is spilled to a sidecar file (state/sessions/<id>/subagent-handoffs/<subagentId>.txt) and the parent receives a head+tail slice with a read_file pointer. Prevents large subagent outputs from bloating parent context. Set to 0 to disable the cap entirely. Default 32768 (32KB). Note: sidecar files contain unredacted subagent output (same caveats as AFK_CAPTURE_SUBAGENT_OUTPUT). No automatic GC covers subagent-handoffs/ today; retention is tied to session-directory cleanup.",type:"number",required:!1,default:"32768",example:"16384",category:"model"},{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"}],DU={};for(let e of Fc){let t=e.name;Object.defineProperty(DU,t,{get(){return process.env[t]},enumerable:!("secret"in e&&e.secret),configurable:!0})}k=DU});import{basename as Vye,dirname as Yye,join as ka}from"path";function Nc(e){if(!Xye.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function _t(){return ka(ce(),"witness")}function en(e){return Nc(e),ka(_t(),e)}function yb(e){return ka(en(e),"inbound-attachments")}function bb(e){return ka(en(e),"prompts")}function wb(e){return ka(en(e),"outputs")}function Sb(e){if(!(!e||e===""))return ka(en(e),"bash-captures")}function Zo(e){return!e||e.startsWith("in-memory:")?null:Vye(Yye(e))}function xm(){return ka(ce(),"receipts")}var Xye,$U=y(()=>{"use strict";N();Xye=/^[a-zA-Z0-9_-]+$/});var jU={};lt(jU,{assertSafeBrowserProfile:()=>Kc,assertSafeJobId:()=>ao,ensureSessionsMigrated:()=>QC,ensureTodosMigrated:()=>ZC,ensureTranscriptsMigrated:()=>e_,getAfkCacheDir:()=>xa,getAfkConfigDir:()=>Tn,getAfkHome:()=>ye,getAfkStateDir:()=>ce,getAgentFrameworkDir:()=>Pt,getBashCapturesDir:()=>Sb,getBgJobDir:()=>Bi,getBgJobLog:()=>Fm,getBgJobMeta:()=>Rb,getBgJobsRoot:()=>Wc,getBriefsDir:()=>KC,getBrowserProfileStateDir:()=>Pb,getBrowserStateRoot:()=>_b,getBrowserStorageStatePath:()=>Gc,getBundledPluginsDir:()=>Ta,getDaemonStateDir:()=>Ea,getEffectLedgerPath:()=>t_,getEnvConfigPath:()=>tn,getFacetCacheDir:()=>Em,getFarmDir:()=>Tb,getFarmsDir:()=>zC,getFirstRunMarkerPath:()=>Eb,getHandoffsDir:()=>ti,getInboundAttachmentsDir:()=>yb,getJsonConfigPath:()=>xn,getLegacyEnvConfigPath:()=>YC,getLegacyJsonConfigPath:()=>$m,getLogsDir:()=>ei,getMarketplaceCacheDir:()=>so,getMarketplaceDir:()=>jc,getMemoryDir:()=>Pm,getOauthPendingPath:()=>qc,getPermissionsStorePath:()=>Hc,getPluginsDir:()=>nt,getPluginsIndexPath:()=>xe,getPresenceDir:()=>_m,getProjectAfkDir:()=>GC,getProjectAfkMdPath:()=>Dm,getProjectPlansDir:()=>Cm,getProjectPluginsDir:()=>Am,getProjectSettingsPath:()=>VC,getProjectSkillsDir:()=>Rm,getPromptsDir:()=>bb,getQueueDir:()=>rt,getReceiptsDir:()=>xm,getReplHistoryPath:()=>Lm,getRoutingDecisionsPath:()=>WC,getSchedulesPath:()=>vb,getSdkHomeDir:()=>nbe,getSdkSchemaViolationsPath:()=>rbe,getSessionGrantsPath:()=>Im,getSessionKeyPath:()=>Ib,getSessionLedgerDir:()=>Ra,getSessionLedgerPath:()=>ji,getSessionsDir:()=>Fe,getSettingsPath:()=>xb,getSkillsDir:()=>Bc,getStateDatabasePath:()=>dn,getSubagentLogPath:()=>Cb,getSubagentLogSessionDir:()=>Nm,getSubagentLogsRoot:()=>Ab,getSubagentOutputsDir:()=>wb,getTelemetryPath:()=>jn,getTodosDir:()=>kb,getTraceDir:()=>en,getTranscriptsDir:()=>Uc,getUserAfkMdPath:()=>Om,getWaveManifestPath:()=>Ca,getWavesDir:()=>Aa,getWebUiAssetsDir:()=>qC,getWitnessRoot:()=>_t,getWorktreeRootsRegistryPath:()=>Mm,getWorktreeSweepLockPath:()=>JC,isSafeLedgerSessionId:()=>_r,sessionLabelFromTracePath:()=>Zo,validateSessionId:()=>Nc});import{existsSync as LU,mkdirSync as Qye,renameSync as Zye,cpSync as ebe,rmSync as tbe}from"fs";import{join as ne,dirname as jC,isAbsolute as UC}from"path";import{homedir as HC}from"os";import{fileURLToPath as BU}from"url";function ye(){let e=k.AFK_HOME;if(e!==void 0&&e!==""){if(!UC(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return ne(HC(),".afk")}function nbe(){return ye()}function Pt(){let e=k.AFK_FRAMEWORK_DIR;if(e!==void 0&&e!==""){if(!UC(e)||e==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${e}`);return e}return ne(ye(),"agent-framework")}function jn(){return ne(Pt(),"forge-telemetry.jsonl")}function WC(){return ne(Pt(),"routing-decisions.jsonl")}function rbe(){return ne(Pt(),"sdk-schema-violations.jsonl")}function KC(){return ne(Pt(),"briefs")}function Em(){return ne(Pt(),"facets")}function Bc(){return ne(ye(),"skills")}function nt(){return ne(ye(),"plugins")}function GC(e=process.cwd()){return ne(e,".afk")}function Rm(e=process.cwd()){return ne(GC(e),"skills")}function Am(e=process.cwd()){return ne(GC(e),"plugins")}function Cm(e=process.cwd()){return ne(e,".afk","plans")}function xe(){return ne(nt(),".index.json")}function vb(){return ne(Tn(),"schedules.json")}function so(){return ne(nt(),"cache")}function jc(e){return ne(so(),e)}function Ta(){let e=BU(import.meta.url),t=jC(e);return ne(t,"bundled-plugins")}function qC(){let e=BU(import.meta.url),t=jC(e);return ne(t,"web-ui-assets")}function Tn(){return ne(ye(),"config")}function ce(){let e=k.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!UC(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return ne(ye(),"state")}function xa(){return ne(ye(),"cache")}function ei(){return ne(ye(),"logs")}function Fe(){return ne(ce(),"sessions")}function _m(){return ne(ce(),"presence")}function kb(){return ne(ce(),"todos")}function Uc(){return ne(ce(),"transcripts")}function Pm(){return ne(ce(),"memory")}function dn(){return ne(ce(),"kv","kv.db")}function rt(){return ne(ce(),"queue")}function ti(){return ne(ce(),"handoffs")}function Im(){return ne(ce(),"session-grants.jsonl")}function Hc(){return ne(Tn(),"permissions.json")}function zC(){return ne(ye(),"farms")}function Tb(e){return ne(zC(),e)}function Ea(e="default"){return ne(ce(),"daemon",`agent-afk@${e}`)}function JC(){return ne(ce(),"worktree-sweep.lock")}function Mm(){return ne(ce(),"worktree-roots.json")}function tn(){return ne(Tn(),"afk.env")}function xn(){return ne(Tn(),"afk.config.json")}function xb(){return ne(Tn(),"settings.json")}function VC(e=process.cwd()){return ne(e,".afk","settings.json")}function Om(){return ne(ye(),"AFK.md")}function Dm(e=process.cwd()){return ne(e,"AFK.md")}function YC(){return ne(HC(),".afk.env")}function $m(){return ne(HC(),".afk.config.json")}function obe(){return ne(ye(),"sessions")}function ibe(){return ne(ye(),"todos")}function sbe(){return ne(ye(),"transcripts")}function XC(e,t){if(e!==t&&LU(e)&&!LU(t))try{Qye(jC(t),{recursive:!0});try{Zye(e,t)}catch(n){if(n.code==="EXDEV")try{ebe(e,t,{recursive:!0}),tbe(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
|
|
2
|
+
var Jye=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var lt=(e,t)=>{for(var n in t)Jye(e,n,{get:t[n],enumerable:!0})};function Sa(e){return Fc.find(t=>t.name===e)}function NC(e){return Fc.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function Lc(e){return process.env[e]!==void 0}function hb(e){let t=process.env[e];return t===void 0||t===""?void 0:t}function BC(e){return/^(0|false|no|off)$/i.test(e.trim())}function va(e){return/^(1|true|yes|on)$/i.test(e.trim())}var OU=y(()=>{"use strict";F()});function Ke(){let e=k.AFK_PLAIN_OUTPUT;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"}var Fc,DU,k,F=y(()=>{"use strict";OU();Fc=[{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_DISABLE_SPINE_UPDATE",description:"Disable the SPINE.md SessionEnd hook when set to 1. The hook runs a single LLM call at the end of each top-level session to classify architectural signals in the git diff against SPINE.md. Set to 1 to opt out globally (useful in CI or when the LLM call is unwanted).",type:"boolean",required:!1,default:"0",example:"1",category:"misc"},{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:'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. On by default. Set to 0 to disable.',type:"boolean",required:!1,default:"1",example:"0",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. On by default. Set to 0/false/no/off to disable.",type:"boolean",required:!1,default:"1",example:"0",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. On by default. Set to 0/false/no/off to disable. Requires AFK_SUGGEST_ENABLED (it reuses the same suggestion model and provider).",type:"boolean",required:!1,default:"1",example:"0",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 (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:"Use ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. Off by default. Set to 1/true/yes/on to enable. 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_TELEGRAM_SESSION_IDLE_MS",description:"Milliseconds of inactivity after which an idle AgentSession is closed and its memory freed. sessionData (model/cwd preferences) is kept in-memory and reloaded on demand from disk. Default: 14400000 (4 hours).",type:"number",required:!1,default:"14400000",example:"3600000",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_DAEMON_SHELL_TIMEOUT_MS",description:"Wall-clock timeout in milliseconds for executor:shell scheduled tasks. Defaults to 300000 (5 minutes). The child process is killed on timeout.",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_BASH_PREVIEW_HEAD_LINES",description:"Number of leading non-empty lines shown in the bash output head block of the TUI outcome preview. 0 (default) disables the head block entirely. Accepted range 0\u2013200; non-integer, negative, or out-of-range input falls back to the default. When head + tail >= total non-empty lines, all lines are shown without a hidden-line notice. Keep preview preferences separate from model-context caps (AFK_BASH_PREVIEW_TAIL_LINES).",type:"number",required:!1,default:"0",example:"3",category:"misc"},{name:"AFK_BASH_PREVIEW_TAIL_LINES",description:"Number of trailing non-empty lines shown in the bash output tail block of the TUI outcome preview. Default 7 (compact tail-first preview). Accepted range 0\u2013200; non-integer, negative, or out-of-range input falls back to the default. When head + tail >= total non-empty lines, all lines are shown without a hidden-line notice. Keep preview preferences separate from model-context caps (AFK_BASH_PREVIEW_HEAD_LINES).",type:"number",required:!1,default:"7",example:"10",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_TURN_SEPARATOR",description:"Render a dim horizontal rule between conversation turns in the REPL. 0 = off, unset/1 = on (default). TTY-only: piped/one-shot output (afk chat) never emits the rule.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_STREAM_BUFFER_MS",description:"Input buffer window for TUI streaming in milliseconds. When set to a positive value, incoming tokens are micro-batched before parsing and rendering, producing smoother visual output. The first token after idle always passes through immediately (leading-edge). 0 = disabled (every token is parsed individually). Reasonable range: 8-50.",type:"number",required:!1,default:"0",example:"16",category:"display"},{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:"AFK_PROSE_MEASURE",description:"Maximum line length (columns) for prose-only blocks (paragraphs, list items, blockquotes) in the interactive REPL. Code fences use the wider AFK_TEXT_MEASURE (default 100). When AFK_TEXT_MEASURE is explicitly set, it overrides this value for backward compatibility. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable. Unparseable or below-minimum values fall back to the default.",type:"string",required:!1,default:"80",example:"72",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:"Capture subagent conversational OUTPUT (assistant text plus each tool call with its arguments) as 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. Set to 1 to enable. Note: best-effort regex redaction only \u2014 connection strings, PEM blocks, and PII are not caught.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SUBAGENT_RESULT_CAP_BYTES",description:"Foreground subagent result size cap in bytes. When a subagent's final message exceeds this threshold, the full output is spilled to a sidecar file (state/sessions/<id>/subagent-handoffs/<subagentId>.txt) and the parent receives a head+tail slice with a read_file pointer. Prevents large subagent outputs from bloating parent context. Set to 0 to disable the cap entirely. Default 32768 (32KB). Note: sidecar files contain unredacted subagent output (same caveats as AFK_CAPTURE_SUBAGENT_OUTPUT). No automatic GC covers subagent-handoffs/ today; retention is tied to session-directory cleanup.",type:"number",required:!1,default:"32768",example:"16384",category:"model"},{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"}],DU={};for(let e of Fc){let t=e.name;Object.defineProperty(DU,t,{get(){return process.env[t]},enumerable:!("secret"in e&&e.secret),configurable:!0})}k=DU});import{basename as Vye,dirname as Yye,join as ka}from"path";function Nc(e){if(!Xye.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function _t(){return ka(ce(),"witness")}function en(e){return Nc(e),ka(_t(),e)}function yb(e){return ka(en(e),"inbound-attachments")}function bb(e){return ka(en(e),"prompts")}function wb(e){return ka(en(e),"outputs")}function Sb(e){if(!(!e||e===""))return ka(en(e),"bash-captures")}function Zo(e){return!e||e.startsWith("in-memory:")?null:Vye(Yye(e))}function xm(){return ka(ce(),"receipts")}var Xye,$U=y(()=>{"use strict";N();Xye=/^[a-zA-Z0-9_-]+$/});var jU={};lt(jU,{assertSafeBrowserProfile:()=>Kc,assertSafeJobId:()=>ao,ensureSessionsMigrated:()=>QC,ensureTodosMigrated:()=>ZC,ensureTranscriptsMigrated:()=>e_,getAfkCacheDir:()=>xa,getAfkConfigDir:()=>Tn,getAfkHome:()=>ye,getAfkStateDir:()=>ce,getAgentFrameworkDir:()=>Pt,getBashCapturesDir:()=>Sb,getBgJobDir:()=>Bi,getBgJobLog:()=>Fm,getBgJobMeta:()=>Rb,getBgJobsRoot:()=>Wc,getBriefsDir:()=>KC,getBrowserProfileStateDir:()=>Pb,getBrowserStateRoot:()=>_b,getBrowserStorageStatePath:()=>Gc,getBundledPluginsDir:()=>Ta,getDaemonStateDir:()=>Ea,getEffectLedgerPath:()=>t_,getEnvConfigPath:()=>tn,getFacetCacheDir:()=>Em,getFarmDir:()=>Tb,getFarmsDir:()=>zC,getFirstRunMarkerPath:()=>Eb,getHandoffsDir:()=>ti,getInboundAttachmentsDir:()=>yb,getJsonConfigPath:()=>xn,getLegacyEnvConfigPath:()=>YC,getLegacyJsonConfigPath:()=>$m,getLogsDir:()=>ei,getMarketplaceCacheDir:()=>so,getMarketplaceDir:()=>jc,getMemoryDir:()=>Pm,getOauthPendingPath:()=>qc,getPermissionsStorePath:()=>Hc,getPluginsDir:()=>nt,getPluginsIndexPath:()=>xe,getPresenceDir:()=>_m,getProjectAfkDir:()=>GC,getProjectAfkMdPath:()=>Dm,getProjectPlansDir:()=>Cm,getProjectPluginsDir:()=>Am,getProjectSettingsPath:()=>VC,getProjectSkillsDir:()=>Rm,getPromptsDir:()=>bb,getQueueDir:()=>rt,getReceiptsDir:()=>xm,getReplHistoryPath:()=>Lm,getRoutingDecisionsPath:()=>WC,getSchedulesPath:()=>vb,getSdkHomeDir:()=>nbe,getSdkSchemaViolationsPath:()=>rbe,getSessionGrantsPath:()=>Im,getSessionKeyPath:()=>Ib,getSessionLedgerDir:()=>Ra,getSessionLedgerPath:()=>ji,getSessionsDir:()=>Fe,getSettingsPath:()=>xb,getSkillsDir:()=>Bc,getStateDatabasePath:()=>dn,getSubagentLogPath:()=>Cb,getSubagentLogSessionDir:()=>Nm,getSubagentLogsRoot:()=>Ab,getSubagentOutputsDir:()=>wb,getTelemetryPath:()=>jn,getTodosDir:()=>kb,getTraceDir:()=>en,getTranscriptsDir:()=>Uc,getUserAfkMdPath:()=>Om,getWaveManifestPath:()=>Ca,getWavesDir:()=>Aa,getWebUiAssetsDir:()=>qC,getWitnessRoot:()=>_t,getWorktreeRootsRegistryPath:()=>Mm,getWorktreeSweepLockPath:()=>JC,isSafeLedgerSessionId:()=>_r,sessionLabelFromTracePath:()=>Zo,validateSessionId:()=>Nc});import{existsSync as LU,mkdirSync as Qye,renameSync as Zye,cpSync as ebe,rmSync as tbe}from"fs";import{join as ne,dirname as jC,isAbsolute as UC}from"path";import{homedir as HC}from"os";import{fileURLToPath as BU}from"url";function ye(){let e=k.AFK_HOME;if(e!==void 0&&e!==""){if(!UC(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return ne(HC(),".afk")}function nbe(){return ye()}function Pt(){let e=k.AFK_FRAMEWORK_DIR;if(e!==void 0&&e!==""){if(!UC(e)||e==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${e}`);return e}return ne(ye(),"agent-framework")}function jn(){return ne(Pt(),"forge-telemetry.jsonl")}function WC(){return ne(Pt(),"routing-decisions.jsonl")}function rbe(){return ne(Pt(),"sdk-schema-violations.jsonl")}function KC(){return ne(Pt(),"briefs")}function Em(){return ne(Pt(),"facets")}function Bc(){return ne(ye(),"skills")}function nt(){return ne(ye(),"plugins")}function GC(e=process.cwd()){return ne(e,".afk")}function Rm(e=process.cwd()){return ne(GC(e),"skills")}function Am(e=process.cwd()){return ne(GC(e),"plugins")}function Cm(e=process.cwd()){return ne(e,".afk","plans")}function xe(){return ne(nt(),".index.json")}function vb(){return ne(Tn(),"schedules.json")}function so(){return ne(nt(),"cache")}function jc(e){return ne(so(),e)}function Ta(){let e=BU(import.meta.url),t=jC(e);return ne(t,"bundled-plugins")}function qC(){let e=BU(import.meta.url),t=jC(e);return ne(t,"web-ui-assets")}function Tn(){return ne(ye(),"config")}function ce(){let e=k.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!UC(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return ne(ye(),"state")}function xa(){return ne(ye(),"cache")}function ei(){return ne(ye(),"logs")}function Fe(){return ne(ce(),"sessions")}function _m(){return ne(ce(),"presence")}function kb(){return ne(ce(),"todos")}function Uc(){return ne(ce(),"transcripts")}function Pm(){return ne(ce(),"memory")}function dn(){return ne(ce(),"kv","kv.db")}function rt(){return ne(ce(),"queue")}function ti(){return ne(ce(),"handoffs")}function Im(){return ne(ce(),"session-grants.jsonl")}function Hc(){return ne(Tn(),"permissions.json")}function zC(){return ne(ye(),"farms")}function Tb(e){return ne(zC(),e)}function Ea(e="default"){return ne(ce(),"daemon",`agent-afk@${e}`)}function JC(){return ne(ce(),"worktree-sweep.lock")}function Mm(){return ne(ce(),"worktree-roots.json")}function tn(){return ne(Tn(),"afk.env")}function xn(){return ne(Tn(),"afk.config.json")}function xb(){return ne(Tn(),"settings.json")}function VC(e=process.cwd()){return ne(e,".afk","settings.json")}function Om(){return ne(ye(),"AFK.md")}function Dm(e=process.cwd()){return ne(e,"AFK.md")}function YC(){return ne(HC(),".afk.env")}function $m(){return ne(HC(),".afk.config.json")}function obe(){return ne(ye(),"sessions")}function ibe(){return ne(ye(),"todos")}function sbe(){return ne(ye(),"transcripts")}function XC(e,t){if(e!==t&&LU(e)&&!LU(t))try{Qye(jC(t),{recursive:!0});try{Zye(e,t)}catch(n){if(n.code==="EXDEV")try{ebe(e,t,{recursive:!0}),tbe(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
|
|
3
3
|
`)}}}catch{}}function QC(){XC(obe(),Fe())}function ZC(){XC(ibe(),kb())}function e_(){XC(sbe(),Uc())}function Lm(){return ne(ce(),"repl-history.jsonl")}function Eb(){return ne(ce(),".first-run-shown")}function ao(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(e.length>FU)throw new Error(`Invalid jobId: exceeds ${FU} chars`);if(!abe.test(e))throw new Error(`Invalid jobId: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function Wc(){return ne(ce(),"bg")}function Bi(e){return ao(e),ne(Wc(),e)}function Fm(e){return ne(Bi(e),"events.jsonl")}function Rb(e){return ne(Bi(e),"meta.json")}function Ab(){return ne(ce(),"subagent-logs")}function Nm(e){return ao(e),ne(Ab(),e)}function Cb(e,t){return ao(t),ne(Nm(e),`${t}.jsonl`)}function Kc(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(e.length>NU)throw new Error(`Invalid browser profile: exceeds ${NU} chars`);if(!lbe.test(e))throw new Error(`Invalid browser profile: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function _b(){return ne(ce(),"browser")}function Pb(e){return Kc(e),ne(_b(),e)}function Gc(e){return ne(Pb(e),"storageState.json")}function _r(e){return typeof e=="string"&&e.length>0&&e.length<=ube&&cbe.test(e)}function Ra(e){if(!_r(e))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(e)}`);return ne(Fe(),e)}function ji(e){return ne(Ra(e),"events.jsonl")}function Ib(e){return ne(Ra(e),"session.key")}function qc(){return ne(ce(),"mcp","server-status.json")}function Aa(){return ne(ce(),"waves")}function Ca(e){return ne(Aa(),`${e}.json`)}function t_(){return ne(ce(),"effect-ledger.jsonl")}var abe,FU,lbe,NU,cbe,ube,N=y(()=>{"use strict";F();$U();abe=/^[A-Za-z0-9_-]+$/,FU=128;lbe=/^[A-Za-z0-9_-]+$/,NU=128;cbe=/^[A-Za-z0-9_-]+$/,ube=128});import{randomBytes as dbe}from"node:crypto";import{mkdirSync as pbe,renameSync as mbe,rmSync as UU,writeFileSync as fbe}from"node:fs";import{dirname as gbe,isAbsolute as hbe,join as ybe}from"node:path";function Mb(){return ybe(ce(),"last-cwd")}function HU(){try{UU(Mb(),{force:!0})}catch{}}function WU(e){if(!hbe(e))throw new Error(`recordCdIntent: target must be an absolute path, got ${JSON.stringify(e)}`);if(/[\n\r\0]/.test(e))throw new Error(`recordCdIntent: target must not contain newline/CR/NUL, got ${JSON.stringify(e)}`);try{let t=Mb();pbe(gbe(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${dbe(6).toString("hex")}`;try{fbe(n,e,{encoding:"utf8",mode:384}),mbe(n,t)}catch(r){try{UU(n,{force:!0})}catch{}throw r}}catch{}}function KU(){let e=k.AFK_SHELL_WRAPPER;return e==="1"||e==="true"}var Ob=y(()=>{"use strict";F();N()});import X from"chalk";var qU,bbe,wbe,zU,JU,VU,m,L=y(()=>{"use strict";qU={brand:X.hex("#E67E4C"),mint:X.hex("#5FE3A1"),shell:X.hex("#A8E060"),goblin:X.hex("#9CB04A"),user:X.cyan,caret:X.hex("#7AA2F7"),tool:X.hex("#DCDCAA"),chrome:X.hex("#B0B8C2"),syntaxString:X.italic.hex("#8AB07A"),toolArg:X.dim.white,thinking:X.italic.hex("#B5888F"),success:X.green,error:X.red,warning:X.yellow,plan:X.hex("#9F7CE0"),bypass:X.bold.hex("#FF6AC1"),meta:X.blackBright,info:X.hex("#5BA8FF"),fileRef:X.hex("#5B8FA8"),heading:X.bold.white,label:X.dim,dim:X.dim,bold:X.bold,italic:X.italic,diffAdd:X.green,diffRemove:X.red,diffHunk:X.blackBright},bbe={brand:X.hex("#C0562A"),mint:X.hex("#1B9E63"),shell:X.hex("#4F7F14"),goblin:X.hex("#6B7D2A"),user:X.hex("#0E7490"),caret:X.hex("#3B5BDB"),tool:X.hex("#7A6E00"),chrome:X.hex("#5A6470"),syntaxString:X.italic.hex("#3F7A3F"),toolArg:X.hex("#6B7280"),thinking:X.italic.hex("#8A5D64"),success:X.hex("#2E7D32"),error:X.hex("#C62828"),warning:X.hex("#B8860B"),plan:X.hex("#7048C0"),bypass:X.bold.hex("#D6297F"),meta:X.hex("#6B7280"),info:X.hex("#1D6FD6"),fileRef:X.hex("#2D5B7A"),heading:X.bold.hex("#1F2937"),label:X.dim,dim:X.dim,bold:X.bold,italic:X.italic,diffAdd:X.hex("#2E7D32"),diffRemove:X.hex("#C62828"),diffHunk:X.hex("#6B7280")},wbe={brand:X.hex("#FF9B5A"),mint:X.hex("#B4FCC3"),shell:X.hex("#B4FCC3"),goblin:X.hex("#A5AC55"),user:X.hex("#42CBC8"),caret:X.hex("#9DBEFC"),tool:X.hex("#F7D179"),chrome:X.hex("#D3CDC5"),syntaxString:X.italic.hex("#96C182"),toolArg:X.dim.hex("#D3CDC5"),thinking:X.italic.hex("#C4929A"),success:X.hex("#8AE49E"),error:X.hex("#EF7F74"),warning:X.hex("#D7AA32"),plan:X.hex("#AE93DE"),bypass:X.bold.hex("#FFACE9"),meta:X.hex("#AAA19B"),info:X.hex("#739EF0"),fileRef:X.hex("#78ACB8"),heading:X.bold.hex("#F9F6F2"),label:X.dim,dim:X.dim,bold:X.bold,italic:X.italic,diffAdd:X.hex("#8AE49E"),diffRemove:X.hex("#EF7F74"),diffHunk:X.hex("#AAA19B")},zU=qU,JU=bbe,VU=wbe,m={...qU}});function YU(){return{keyword:m.brand,built_in:m.brand,literal:m.brand,tag:m.brand,string:m.syntaxString,regexp:m.syntaxString,attr:m.syntaxString,comment:m.meta,meta:m.meta,quote:m.meta,number:m.warning,function:m.tool,title:m.tool,class:m.tool,"selector-tag":m.tool}}var XU=y(()=>{"use strict";L()});import Sbe from"chalk";import{createEmphasize as vbe,common as kbe}from"emphasize";function ZU(){lo.clear()}function Rbe(e){let t=lo.get(e);if(t!==void 0)return lo.delete(e),lo.set(e,t),t}function Abe(e,t){if(lo.has(e)&&lo.delete(e),lo.set(e,t),lo.size>Ebe){let n=lo.keys().next().value;n!==void 0&&lo.delete(n)}}function e1(e,t){if(Sbe.level===0||e.length>Tbe)return e;let n=e.length<xbe,r=n?`${t} ${e}`:"";if(n){let i=Rbe(r);if(i!==void 0)return i}let o;try{if(!t||!QU.registered(t))o=e;else{let i=QU.highlight(t,e,YU());o=typeof i?.value=="string"?i.value:e}}catch{o=e}return n&&Abe(r,o),o}var QU,Tbe,xbe,Ebe,lo,r_=y(()=>{"use strict";XU();QU=vbe(kbe),Tbe=2048,xbe=512,Ebe=32,lo=new Map});function r1(){return n1}function co(e){Object.assign(m,t1[e]),ZU(),n1=e}function Ui(e){if(e==null)return;let t=e.trim().toLowerCase();return t==="auto"||Db.includes(t)?t:void 0}function Cbe(){let e=k.COLORFGBG;if(!e)return"dark";let t=e.split(";"),n=t[t.length-1]?.trim();if(!n)return"dark";let r=Number.parseInt(n,10);return Number.isInteger(r)&&(r===7||r>=9)?"light":"dark"}function uo(e){return e==="auto"?Cbe():e!==void 0?e:"dark"}function $b(e){let t=Ui(e);if(t!==void 0)return t;throw new Error(`Invalid --theme value: ${e}. Expected ${[...Db,"auto"].join("|")}`)}function Lb(e,t){if(e!==void 0)return e;let n=Ui(k.AFK_THEME);return n!==void 0?n:t}var t1,Db,n1,zc=y(()=>{"use strict";L();r_();F();t1={dark:zU,light:JU,umber:VU},Db=Object.keys(t1),n1="dark"});var It,Mt,Fb,_e,or,po,Jc,Nb,Be=y(()=>{"use strict";It=class extends Error{constructor(t){super(t),this.name="AbortError"}},Mt=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Fb=class extends Mt{constructor(t,n){super(t,n),this.name="IdleWatchdogError"}},_e=class extends Error{constructor(n,r,o,i){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",i?.cause!==void 0&&(this.cause=i.cause),i?.injectContext!==void 0&&(this.injectContext=i.injectContext)}event;reason;cause;injectContext},or=class extends Error{toolResultsGathered;constructor(t){super(t),this.name="StreamIncompleteError"}},po=class extends Error{constructor(n,r,o){super(o??`Budget ceiling reached: $${n.toFixed(4)} cumulative >= $${r.toFixed(4)} limit`);this.runningCostUsd=n;this.maxBudgetUsd=r;this.name="BudgetExceededError"}runningCostUsd;maxBudgetUsd},Jc=class extends Error{constructor(t){super(t),this.name="DenialCircuitBreakerError"}},Nb=class extends Error{constructor(n,r,o){super(o??`${n} provider does not support AgentConfig.${r}.`);this.provider=n;this.field=r;this.name="UnsupportedProviderConfigError"}provider;field}});import _be from"string-width";function Pe(e){return e.replace(o_,"")}function G(e){return _be(e)}function _a(e){return e.length===0?[]:s1?Array.from(s1.segment(e),t=>t.segment):Array.from(e)}function Pbe(e){let t=[],n=0,r;for(o_.lastIndex=0;(r=o_.exec(e))!==null;){if(r.index>n)for(let o of _a(e.slice(n,r.index)))t.push({type:"text",value:o});t.push({type:"ansi",value:r[0]}),n=r.index+r[0].length}if(n<e.length)for(let o of _a(e.slice(n)))t.push({type:"text",value:o});return t}function ct(e,t){let n=G(e);return n>t?te(e,t,""):e+" ".repeat(t-n)}function Ibe(e,t){let n=Math.max(0,t-G(e));return" ".repeat(n)+e}function Bb(e,t,n="left"){let r=Math.max(0,t-G(e));if(r===0)return e;if(n==="right")return Ibe(e,t);if(n==="center"){let o=Math.floor(r/2);return" ".repeat(o)+e+" ".repeat(r-o)}return ct(e,t)}function te(e,t,n="\u2026"){if(t<=0)return"";if(G(e)<=t)return e;let r=G(n),o=Math.max(0,t-r),i=0,s="",a=!1,l=!1;for(let c of Pbe(e)){if(c.type==="ansi"){s+=c.value,a=!0;let d=Mbe.exec(c.value);d&&(l=(d[1]??"").length>0);continue}let u=i+G(c.value);if(u>o)break;s+=c.value,i=u}return s+n+(l?Obe:"")+(a?"\x1B[0m":"")}function a1(e,t,n="\u2026"){if(t<=0)return"";if(G(e)<=t)return e;let r=G(n);if(r>t)return"";let o=Math.max(0,t-r),i=_a(e),s=0,a=i.length;for(let l=i.length-1;l>=0;l--){let c=G(i[l]);if(s+c>o)break;s+=c,a=l}return n+i.slice(a).join("")}function l1(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.trunc(e))):0}function Bm(e,t){let n=l1(t,e.length);if(n===0||e.length===0)return 0;let r=0;for(let o of _a(e)){let i=r+o.length;if(i>=n)return r;r=i}return r}function Pa(e,t){let n=l1(t,e.length);if(n>=e.length||e.length===0)return e.length;let r=0;for(let o of _a(e)){let i=r+o.length;if(r>=n||n>r&&n<i)return i;r=i}return e.length}var o_,s1,Mbe,Obe,pe=y(()=>{"use strict";o_=/\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P^_X][^\x1B]*\x1B\\|[@-OQ-WYZ\\\-])/g,s1=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;Mbe=/^\x1b\]8;[^;\x07\x1b]*;(.*?)(?:\x07|\x1b\\)$/s,Obe="\x1B]8;;\x1B\\"});function oe(){let e=process.stdout.columns;return typeof e=="number"&&e>0?e:80}function jm(){let e=process.stdout.rows;return typeof e=="number"&&e>0?e:24}function Dbe(){for(let e of jb)try{e()}catch{}}function $be(){for(let e of Ub)try{e()}catch{}}function Lbe(){Ia!==null&&clearTimeout(Ia),Ia=setTimeout(()=>{Ia=null,Dbe()},150)}function i_(){$be(),Lbe()}function Fbe(e){return jb.add(e),Yc||(process.stdout.on("resize",i_),Yc=!0),()=>{jb.delete(e),c1()}}function Nbe(e){return Ub.add(e),Yc||(process.stdout.on("resize",i_),Yc=!0),()=>{Ub.delete(e),c1()}}function c1(){jb.size===0&&Ub.size===0&&(Yc&&(process.stdout.off("resize",i_),Yc=!1),Ia!==null&&(clearTimeout(Ia),Ia=null))}var jb,Ub,Yc,Ia,qe,be=y(()=>{"use strict";jb=new Set,Ub=new Set,Yc=!1,Ia=null;qe={subscribe:Fbe,subscribeImmediate:Nbe}});import u1 from"wrap-ansi";function he(e,t,n={}){if(!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY)return e;let r=Math.floor(t);return e.replaceAll(`\r
|
|
4
4
|
`,`
|
|
5
5
|
`).split(`
|
|
@@ -426,7 +426,7 @@ ${o}`,paths:[t,n]}:o!==null?i={content:o,paths:[n]}:r!==null?i={content:r,paths:
|
|
|
426
426
|
|
|
427
427
|
${t}`}var vAe,PI=y(()=>{"use strict";vAe=new Set(["script","style","noscript","template","svg"])});function xAe(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new Error("aborted"));return}let o=()=>{clearTimeout(i),r(t?.reason??new Error("aborted"))},i=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})})}function aq(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function EAe(e,t){let n=e.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,t)}async function lq(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??xAe,l=n.signal??void 0,c;for(let u=0;u<=o;u++){if(l?.aborted)throw l.reason??new Error("aborted");try{let d=await e(t,n);if(!TAe.has(d.status)||u===o)return d;let p=EAe(d,s)??aq(u,i,s);B("[web/retryFetch] retrying",{url:t,attempt:u,status:d.status,waitMs:p}),await d.body?.cancel().catch(()=>{}),await a(p,l)}catch(d){if(l?.aborted||(c=d,u===o))throw d;let p=aq(u,i,s);B("[web/retryFetch] retrying after error",{url:t,attempt:u,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var TAe,cq=y(()=>{"use strict";me();TAe=new Set([429,502,503,504])});import{BlockList as RAe,isIP as MI}from"node:net";import{lookup as AAe}from"node:dns/promises";import{Agent as CAe}from"undici";function dq(){let e=k.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return e==="1"||e==="true"}function MAe(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function II(e){let t=MI(e);return t===0?!1:IAe.check(e,t===4?"ipv4":"ipv6")}async function pq(e){return AAe(e,{all:!0,verbatim:!0})}async function ol(e,t={}){if(t.allowPrivateHosts??dq())return{allowed:!0};let n;try{n=new URL(e)}catch{return{allowed:!1,reason:`"${e}" is not a valid absolute URL`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{allowed:!1,reason:`protocol "${n.protocol}" not supported (http/https only)`};let r=MAe(n.hostname),o=(a,l)=>`refusing to fetch ${l} \u2014 internal/private address ${a} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`;if(MI(r)!==0)return II(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let i=t.lookupFn??pq,s;try{s=await i(r)}catch{return{allowed:!0}}for(let a of s)if(II(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function Vf(e,t={}){let n=await ol(e,t);if(!n.allowed)throw new rn(n.reason)}async function cs(e,t,n={},r={}){let o={...r.lookupFn!==void 0?{lookupFn:r.lookupFn}:{},...r.allowPrivateHosts!==void 0?{allowPrivateHosts:r.allowPrivateHosts}:{}},i=t;for(let s=0;s<=uq;s++){await Vf(i,o);let a={...n,redirect:"manual",...e===globalThis.fetch&&!(r.allowPrivateHosts??dq())?{dispatcher:OAe}:{}},l=await lq(e,i,a,r.retry??{});if(!DAe.has(l.status))return l;let c=l.headers.get("location");if(c===null||c.trim()==="")return l;let u;try{u=new URL(c,l.url||i).toString()}catch{return l}await l.body?.cancel().catch(()=>{}),i=u}throw new rn(`too many redirects (>${uq}) starting from ${t}`)}var _Ae,PAe,IAe,rn,OAe,uq,DAe,il=y(()=>{"use strict";F();cq();_Ae=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.168.0.0",16]],PAe=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],IAe=(()=>{let e=new RAe;for(let[t,n]of _Ae)e.addSubnet(t,n,"ipv4");for(let[t,n]of PAe)e.addSubnet(t,n,"ipv6");return e})(),rn=class extends Error{constructor(t){super(t),this.name="EgressBlockedError"}};OAe=new CAe({connect:{lookup(e,t,n){pq(e).then(r=>{let o=r.find(s=>II(s.address));if(o!==void 0){n(new rn(`refusing to connect to ${e} (resolved) \u2014 internal/private address ${o.address} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`),"",0);return}let i=r[0];if(i===void 0){n(new Error(`DNS lookup returned no addresses for ${e}`),"",0);return}n(null,i.address,MI(i.address))},r=>n(r,"",0))}}});uq=20,DAe=new Set([301,302,303,307,308])});var DI={};lt(DI,{enforceDomainPolicy:()=>Br,loadBrowserConfig:()=>OI});import{readFileSync as $Ae}from"node:fs";import{join as LAe}from"path";function FAe(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function mq(e,t){return FAe(t).test(e)}function jAe(e,t){if(e!==void 0){let n=e.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(t!==void 0){if(NAe.has(t))return!0;if(BAe.has(t))return!1}return!1}function fq(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function UAe(e){if(e===void 0||e==="")return"auto";if(e==="playwright"||e==="agent-browser"||e==="auto")return e;throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${e}`)}function gq(e){let t=e===void 0||e.trim()===""?"default":e.trim();return Kc(t),t}function HAe(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function WAe(e){try{return $Ae(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function KAe(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright"||t.backend==="agent-browser"||t.backend==="auto")n.backend=t.backend;else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${String(t.backend)}`);return typeof t.defaultProfile=="string"&&(n.defaultProfile=gq(t.defaultProfile)),n}function OI(e){let t=e?.env??k,n=e?.readFileSync??WAe,r=e?.surface??t.AGENT_SURFACE,o=jAe(t.AFK_BROWSER_HEADLESS,r),i=fq(t.AFK_BROWSER_ALLOWED_DOMAINS),s=fq(t.AFK_BROWSER_BLOCKED_DOMAINS),a=HAe(t.AFK_BROWSER_DOM_SNAPSHOTS),l=UAe(t.AFK_BROWSER_BACKEND),c=gq(t.AFK_BROWSER_DEFAULT_PROFILE),u={headless:o,allowedDomains:i,blockedDomains:s,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},d=t.AFK_BROWSER_CONFIG,p=d!==void 0&&d.trim()!==""?d.trim():LAe(Tn(),"browser.json"),f=n(p);if(f===void 0)return u;let g;try{g=JSON.parse(f)}catch(b){throw new Error(`Failed to parse browser config at ${p}: ${String(b)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${p} must be a JSON object`);let h=KAe(u,g);return h.configPath=p,h}function Br(e,t){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${e}`}}for(let r of t.blockedDomains)if(mq(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>mq(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var NAe,BAe,us=y(()=>{"use strict";F();N();NAe=new Set(["daemon","subagent","telegram","afk"]),BAe=new Set(["repl","interactive","cli"])});import{readFileSync as GAe}from"node:fs";import{join as qAe}from"node:path";import{homedir as zAe}from"node:os";function VAe(e){let t=e??JAe,n;try{n=GAe(t,"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 i;try{i=new URL(o.url)}catch{return null}let{hostname:s,protocol:a}=i;if(!(s==="127.0.0.1"||s==="localhost"||s==="::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 YAe(e){try{return process.kill(e,0),!0}catch{return!1}}async function XAe(e,t,n=2e3){try{let r=new AbortController,o=setTimeout(()=>r.abort(),n),i=await fetch(`${e}/health`,{method:"GET",headers:{Authorization:`Bearer ${t}`,Host:"127.0.0.1:8833"},signal:r.signal});return clearTimeout(o),i.ok}catch{return!1}}async function $I(e){let t=VAe(e);return t===null?{available:!1,connection:null,reason:"connection file missing or invalid"}:YAe(t.pid)?await XAe(t.url,t.token)?{available:!0,connection:t,reason:null}:{available:!1,connection:t,reason:`health probe failed at ${t.url}`}:{available:!1,connection:t,reason:`stale connection file: PID ${t.pid} not alive`}}var JAe,hq=y(()=>{"use strict";JAe=qAe(zAe(),".config","agent-browser","connection.json")});async function yq(e){let{config:t,surface:n}=e;if(t.backend==="playwright")return{backend:"playwright",reason:"explicit config: backend=playwright",probeMs:0,availability:null};if(t.backend==="agent-browser"){let s=Date.now(),a=await $I(),l=Date.now()-s;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:l,availability:a}}if(n&&QAe.has(n))return{backend:"playwright",reason:`auto: surface "${n}" excluded from Agent Browser`,probeMs:0,availability:null};if(t.headless)return{backend:"playwright",reason:"auto: headless mode requires Playwright",probeMs:0,availability:null};let r=Date.now(),o=await $I(),i=Date.now()-r;return o.available?{backend:"agent-browser",reason:"auto: Agent Browser available and preferred",probeMs:i,availability:o}:{backend:"playwright",reason:`auto: Agent Browser unavailable (${o.reason})`,probeMs:i,availability:o}}var QAe,bq=y(()=>{"use strict";hq();QAe=new Set(["daemon","subagent"])});import{createHash as ZAe}from"crypto";function wq(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&eCe.test(e.label))}function Sq(e){return ZAe("sha256").update(e,"utf8").digest("hex").slice(0,8)}function vq(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var eCe,MS=y(()=>{"use strict";eCe=/password|secret|token|api[_-]?key|otp|2fa/i});import{randomBytes as tCe}from"crypto";import{mkdir as nCe,stat as rCe,writeFile as oCe}from"fs/promises";import{join as LI}from"path";import{gzip as iCe}from"zlib";import{promisify as sCe}from"util";function aCe(e){return LI(en(e),"browser")}function lCe(e){return LI(aCe(e),"screenshots")}function cCe(){return new Date().toISOString().replace(/[:.]/g,"-")}function uCe(){return tCe(3).toString("hex")}async function Fu(e,t,n){if(t.length>kq)throw new Error(`writeScreenshotSidecar: buffer exceeds ${kq} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=lCe(e);await nCe(r,{recursive:!0});let o=`${cCe()}-${uCe()}-${n}.png`,i=LI(r,o);await oCe(i,t);let{size:s}=await rCe(i);return{path:i,bytes:s}}var Omt,kq,FI=y(()=>{"use strict";N();MS();Omt=sCe(iCe);kq=5*1024*1024});var OS,Tq=y(()=>{"use strict";me();OS=class{baseUrl;token;constructor(t){this.baseUrl=t.url,this.token=t.token}async call(t,n,r=3e4){let o={version:1,method:t,params:n},i=new AbortController,s=setTimeout(()=>i.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:i.signal});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Agent Browser ${t} failed (HTTP ${a.status}): ${c}`)}let l=await a.json();if(l.ok===!1){let c=l.error,u=c?.code??"UNKNOWN",d=c?.message??JSON.stringify(l);throw new Error(`Agent Browser ${t} failed: [${String(u)}] ${String(d)}`)}return l.result}finally{clearTimeout(s)}}async listTabs(){return this.call("tabs.list",null)}async openTab(t){return{tabId:(await this.call("tabs.open",{url:t},6e4)).id}}async closeTab(t){await this.call("page.eval",{id:t,script:"window.close()"}).catch(n=>{B("[browser/agent-browser] closeTab window.close() failed (tab leak expected)",{tabId:t,err:n})})}async read(t,n){return this.call("page.read",{id:t,mode:n?.mode??"main",...n?.query?{query:n.query}:{},...n?.budget?{budget:n.budget}:{}})}async inspect(t,n){return this.call("page.inspect",{id:t,mode:n?.mode??"interactive",...n?.query?{query:n.query}:{},...n?.limit?{limit:n.limit}:{}})}async click(t,n){await this.call("page.click",{id:t,elementId:n})}async fill(t,n,r){await this.call("page.fill",{id:t,elementId:n,value:r})}async press(t,n,r){await this.call("page.press",{id:t,key:n,...r?{elementId:r}:{}})}async select(t,n,r){await this.call("page.select",{id:t,elementId:n,value:r})}async waitFor(t,n,r){await this.call("page.wait",{id:t,condition:n,...r?.value?{value:r.value}:{},...r?.timeout?{timeout:r.timeout}:{}},(r?.timeout??3e4)+5e3)}async evalScript(t,n){return this.call("page.eval",{id:t,script:n})}async screenshot(t){return this.call("page.screenshot",{id:t})}}});function NI(e){return{id:e.id,role:e.role,label:e.label,kind:e.kind,value:e.value,state:{disabled:e.disabled,...e.checked!==void 0?{checked:e.checked}:{},...e.selected!==void 0?{selected:e.selected}:{},...e.expanded!==void 0?{expanded:e.expanded}:{}},bbox:e.bbox,...e.selector?{selector:e.selector}:{}}}function xq(e,t){switch(t.kind){case"element_id":if(e.has(t.elementId))return t.elementId;throw new Error(`Element ${t.elementId} not found in current observation. Call browser_observe to refresh.`);case"selector":return null;case"semantic":return null}}async function BI(e,t,n,r,o,i){switch(n){case"click":await e.click(t,r);break;case"fill":if(o===void 0)throw new Error("fill requires a value");await e.fill(t,r,o);break;case"press":if(o===void 0)throw new Error("press requires a value (key combo)");await e.press(t,o,r);break;case"select":if(o===void 0)throw new Error("select requires a value");await e.select(t,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 s=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');await e.evalScript(t,`document.querySelector('[data-element-id="${s}"]')?.scrollIntoView({behavior:'smooth',block:'center'})`);break}case"wait_for":await e.waitFor(t,"element",{value:r,timeout:i??1e4});break;default:throw new Error(`Unknown action: ${n}`)}}async function Eq(e,t){if(t.target.kind!=="semantic")throw new Error("resolveSemanticAndAct called with non-semantic target");let{elements:n}=await e.client.inspect(e.tabId,{mode:"interactive",query:t.target.text,limit:10}),r=n;if(t.target.role){let l=t.target.role.toLowerCase();r=n.filter(c=>c.role.toLowerCase()===l)}if(r.length===0)throw new Error(`No element found matching semantic target: text="${t.target.text}"`+(t.target.role?`, role="${t.target.role}"`:""));if(r.length>1)return{outcome:"ambiguous_target",query:{text:t.target.text,...t.target.role?{role:t.target.role}:{}},candidates:r.slice(0,5).map(NI)};let i=r[0].id;await BI(e.client,e.tabId,t.action,i,t.value,t.timeoutMs);let s=await e.client.read(e.tabId,{mode:"main"}),a=Br(s.url,e.config);return a.allowed?{elementId:i}:{outcome:"blocked_by_policy",url:s.url,reason:`action navigated to blocked domain: ${a.reason}`}}var Rq=y(()=>{"use strict";us()});var Aq={};lt(Aq,{AgentBrowserProvider:()=>jI});var jI,Cq=y(()=>{"use strict";us();FI();Tq();Rq();jI=class{name="agent-browser";config;client;sessions=new Map;constructor(t,n){this.config=t,this.client=new OS(n)}async open(t){let n=Br(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let r=this.sessions.get(t.sessionId);if(r)await this.client.evalScript(r.tabId,`window.location.href = ${JSON.stringify(t.url)}`),await this.client.waitFor(r.tabId,"load",{timeout:t.timeoutMs??3e4});else{let{tabId:s}=await this.client.openTab(t.url);await this.client.waitFor(s,"load",{timeout:t.timeoutMs??3e4}),r={tabId:s,observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null},this.sessions.set(t.sessionId,r)}let o=await this.client.read(r.tabId,{mode:"main"}),i=Br(o.url,this.config);return i.allowed?this.buildObservation(r,t.sessionId,t.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: ${i.reason}`})}async observe(t){let n=this.sessions.get(t.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${t.sessionId}. Call browser_open first.`);return this.buildObservation(n,t.sessionId,t.screenshot,t.maxElements,"browser_observe")}async act(t){let n=this.sessions.get(t.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${t.sessionId}. Call browser_open first.`);let r=xq(n.knownElements,t.target);if(r===null){if(t.target.kind==="semantic"){let s=await Eq({client:this.client,config:this.config,tabId:n.tabId},t);return"outcome"in s?s:(n.lastAction=`browser_act:${t.action}`,n.lastActionAt=new Date().toISOString(),this.buildObservation(n,t.sessionId,t.screenshot,void 0,"browser_act"))}throw t.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(t.target)}`)}await BI(this.client,n.tabId,t.action,r,t.value,t.timeoutMs),n.lastAction=`browser_act:${t.action}`,n.lastActionAt=new Date().toISOString();let o=await this.client.read(n.tabId,{mode:"main"}),i=Br(o.url,this.config);return i.allowed?this.buildObservation(n,t.sessionId,t.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: ${i.reason}`})}async render(t){throw new Error("AgentBrowserProvider does not support render(). Use PlaywrightProvider for one-shot content fetches.")}async screenshot(t){let n=this.sessions.get(t.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${t.sessionId}. Call browser_open first.`);if(t.target!==void 0||t.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"),i=o.length>=24?o.readUInt32BE(16):0,s=o.length>=24?o.readUInt32BE(20):0;return{path:(await Fu(t.sessionId,o,"browser_screenshot")).path,bytes:o.length,width:i,height:s,dataBase64:r.data,mediaType:"image/png"}}async extract(t){throw new Error("AgentBrowserProvider does not support extract() yet.")}async close(t){let n=this.sessions.get(t.sessionId);if(n){try{await this.client.closeTab(n.tabId)}catch{}this.sessions.delete(t.sessionId)}}describe(t){let n=this.sessions.get(t);return n?{active:!0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:1}:null}async shutdown(){let t=Array.from(this.sessions.entries()).map(async([,n])=>{try{await this.client.closeTab(n.tabId)}catch{}});await Promise.all(t),this.sessions.clear()}async buildObservation(t,n,r,o,i="browser_open"){let[s,a]=await Promise.all([this.client.read(t.tabId,{mode:"main",budget:4e3}),this.client.inspect(t.tabId,{mode:"interactive",limit:o??80})]),l=a.elements.map(NI),c=o??80,u=l.slice(0,c);t.observationCounter+=1,t.knownElements=new Map(u.map(h=>[h.id,h])),t.currentUrl=s.url,t.currentTitle=s.title;let d=[];l.length>c&&d.push(`page has ${l.length} interactive elements; showing first ${c}`);let p=null;if(r)try{let h=await this.client.screenshot(t.tabId),b=Buffer.from(h.data,"base64");p=(await Fu(n,b,i)).path}catch{d.push("screenshot capture failed")}let f=`obs_${t.observationCounter.toString(36)}`,g={httpStatus:null,loadingState:"idle",hasDialog:!1,consoleErrors:0};return{observationId:f,url:s.url,title:s.title,textSummary:s.content.slice(0,4e3),interactive:u,status:g,warnings:d,screenshotPath:p,capturedAt:new Date().toISOString()}}}});import{existsSync as dCe,readFileSync as pCe}from"node:fs";import{createRequire as mCe}from"node:module";import{dirname as fCe,join as gCe}from"node:path";function Iq(e){if(typeof e=="string")return e;let t=[],n=e;for(let r=0;r<yCe&&n instanceof Error;r++)t.push(n.message),n=n.cause;return t.length>0?t.join(" | "):String(e)}function In(e){let t=Iq(e);return Pq.some(n=>t.includes(n))}function bCe(){try{let t=mCe(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(pCe(t,"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 i=gCe(fCe(t),o);return dCe(i)?`node ${/\s/.test(i)?`"${i}"`:i} install chromium`:void 0}catch{return}}function Yf(){return _q??=bCe()??hCe,_q}function UI(e){return e.includes("install chromium")}function ur(e,t){let n=Iq(e),r=t?.latched===!0?` ${wCe}`:"";if(n.includes("Executable doesn't exist")){let o="";return t?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":t?.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: ${Yf()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${Yf()}). Or pick a different tool.${r}`}function Nu(e,t,n=!1){if(!In(e))return e;let r=e instanceof Error?e.message:String(e);return new Error(`${r}
|
|
428
428
|
|
|
429
|
-
${ur(e,{headless:t,latched:n})}`,{cause:e})}var Pq,hCe,yCe,_q,wCe,DS=y(()=>{"use strict";Pq=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],hCe="pnpm exec playwright install chromium",yCe=4;wCe="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 sl from"node:fs";import $S from"node:path";import{randomBytes as SCe}from"node:crypto";function vCe(){try{return"5.222.3"}catch{}try{let e=$S.resolve(import.meta.dirname,"../../../package.json"),t=sl.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var kCe,LS,Mq=y(()=>{"use strict";DS();N();me();kCe=vCe(),LS=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(t){this.config=t}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(t){this.launchFailure={error:t}}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 t;try{({chromium:t}=await import("playwright"))}catch(n){let r=Nu(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await t.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=Nu(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(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){i=l,await a.abort("blockedbyclient")}});let s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw i??p}if(i!==void 0)throw i;let c=await a.content();if(i!==void 0)throw i;let u=a.url(),d=l!==null?l.status():null;return{html:c,finalUrl:u,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){this.clearLaunchFailure();let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),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 t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${kCe}`}}loadStorageState(t){let n=Gc(t);try{if(!sl.existsSync(n))return;let r=JSON.parse(sl.readFileSync(n,"utf8"));return B("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){B("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Gc(t);if(!sl.existsSync(r))return;let o=await n.storageState(),i=$S.join($S.dirname(r),`.${$S.basename(r)}.${process.pid}.${SCe(4).toString("hex")}.tmp`);sl.writeFileSync(i,JSON.stringify(o),{mode:384}),sl.chmodSync(i,384),sl.renameSync(i,r),B("[browser/vault] saved session",{profile:t,file:r})}catch(r){B("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as TCe}from"node:crypto";function xCe(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function ECe(e,t,n){return`el_${TCe("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function RCe(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function Oq(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function $q(e,t){let n=e.role??"",r=e.name??"";Dq.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])$q(i,t)}async function ACe(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let i=o.getBoundingClientRect(),s=o;if(i.width===0&&i.height===0){let u=window.getComputedStyle(s);if(u.display==="none"||u.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},Lq).catch(()=>[])}async function CCe(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let i of r){let s=i.tagName.toLowerCase(),a=i.getAttribute("role")??"",l=i.getAttribute("aria-label")??i.getAttribute("placeholder")??(i.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[s]??"");if(s==="input"){let h=i.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let u="value"in i?i.value:void 0,d=u!==void 0?String(u):void 0,p=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},Lq).catch(()=>[])}function _Ce(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function FS(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=_Ce(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=ACe(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,f,g,h]=await Promise.all([s,a,l,c,u]),b,w=!1;d!==null?(b=[],$q(d,b)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,b=(await CCe(e)).filter(M=>Dq.has(M.role??"")));let S=new Map;for(let _ of p){let M=Oq(_.name),j=S.get(M);(!j||j.bbox.w===0&&_.bbox.w>0)&&S.set(M,_)}let v=b.map(_=>({ax:_,dom:S.get(Oq(_.name??""))})),x=r?v:v.filter(_=>_.dom?_.dom.bbox.w>0||_.dom.bbox.h>0:!0);x.sort((_,M)=>{let j=_.dom?.bbox.y??0,O=M.dom?.bbox.y??0;if(j!==O)return j-O;let H=_.dom?.bbox.x??0,q=M.dom?.bbox.x??0;return H-q}),x.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=x.slice(0,n).map((_,M)=>{let j=_.ax.role??"generic",O=_.ax.name??"",H=ECe(j,O,M),q=_.dom?.bbox??{x:0,y:0,w:0,h:0},W=_.dom?.type??null,K=null;_.ax.value!==void 0&&_.ax.value!==null&&(K=String(_.ax.value)),_.ax.checked!==void 0&&(K=String(_.ax.checked)),wq({role:j,kind:W})&&(K="[redacted]");let Y={disabled:_.ax.disabled??!1};_.ax.checked!==void 0&&(Y.checked=_.ax.checked===!0||_.ax.checked==="mixed"),_.ax.selected!==void 0&&(Y.selected=_.ax.selected),_.ax.expanded!==void 0&&(Y.expanded=_.ax.expanded);let ie;_.dom?.testId?ie=`[data-testid="${_.dom.testId}"]`:_.dom?.id&&(ie=`#${_.dom.id}`);let D={id:H,role:j,label:xCe(O),kind:W,value:K,state:Y,bbox:q};return ie!==void 0&&(D.selector=ie),D}),C="idle";try{let _=await e.evaluate(()=>document.readyState);_==="loading"?C="loading":_==="interactive"?C="navigating":C="idle"}catch{C="navigating"}C!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=RCe(f),A=`obs_${t.observationCounter.toString(36)}`,P=new Date().toISOString();return{observationId:A,url:g,title:h,textSummary:I,interactive:E,status:{httpStatus:t.httpStatus??null,loadingState:C,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:P}}var Dq,Lq,Fq=y(()=>{"use strict";MS();Dq=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Lq="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Nq(e,t){try{let n=await e.nth(t).evaluate(s=>{let a=s,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.height)}}),r=`${n.role}:${n.label}:${t}`,o=0;for(let s=0;s<r.length;s++)o=o*31+r.charCodeAt(s)>>>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 HI(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>Nq(e,i)))).filter(o=>o!==null)}async function PCe(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let i=0;i<o;i++){let s;try{s=await r.nth(i).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(s)||(t.add(s),n.push({key:s,locator:r,index:i}))}return n}async function WI(e,t,n){switch(t.kind){case"element_id":return ICe(e,t,n);case"selector":return MCe(e,t);case"semantic":return OCe(e,t)}}async function ICe(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),i=await o.count();if(i===0)return{outcome:"not_found",query:t};if(i===1)return{outcome:"resolved",locator:o};let s=await HI(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function MCe(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await HI(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function OCe(e,t){return t.role!==void 0?DCe(e,t.text,t.role):$Ce(e,t.text,t)}async function DCe(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let i=await HI(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function $Ce(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),i=e.getByLabel(t,{exact:!1}),[s,a,l]=await Promise.all([r.count(),o.count(),i.count()]);if(s+a+l===0)return{outcome:"not_found",query:n};let u=[];s>0&&u.push({loc:r,count:s}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:i,count:l});let d=await PCe(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=d.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let w=await Nq(b.locator,b.index);if(w!==null){let S=`${w.role}:${w.label}:${h}`,v=0;for(let x=0;x<S.length;x++)v=v*31+S.charCodeAt(x)>>>0;f.push({...w,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var Bq=y(()=>{"use strict"});async function KI(e,t,n,r){let o=e.url();if(o===n)return null;let i=Br(o,t);if(i.allowed)return null;try{await e.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:i.reason}}var jq=y(()=>{"use strict";us()});var qI={};lt(qI,{PlaywrightProvider:()=>GI});function Uq(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var GI,zI=y(()=>{"use strict";Mq();Fq();Bq();us();jq();FI();GI=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new LS(t)}async open(t){let n=Br(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(d){a=d}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let d=await KI(o,this.config,t.url,()=>this.close({sessionId:r}));if(d!==null)return d}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let u=await FS(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,u.interactive,u.url,u.title,"browser_open"),a!==null)throw a;return u}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await FS(r,{observationCounter:o.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,s.interactive,s.url,s.title,"browser_observe"),s}async act(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),i=r.url(),s=t.timeoutMs??3e4,a=await WI(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Uq(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":await l.fill(t.value??"");break;case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=await KI(r,this.config,i,()=>this.close({sessionId:n}));if(d!==null)return d;let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await FS(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal,requestGuard:t.requestGuard})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),i;if(t.target!==void 0){let u=await WI(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Uq(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await u.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await Fu(n,i,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}return{path:s,bytes:a,width:l,height:c,dataBase64:i.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(t){let n=this.sessions.get(t);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(t,r),r}updateSessionFromObservation(t,n,r,o,i){t.knownElements=new Map(n.map(s=>[s.id,s])),t.currentUrl=r,t.currentTitle=o,t.lastAction=i,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:i}=await Fu(n,o,r);return i}catch{return null}}}});var ll={};lt(ll,{__resetBrowserRegistryForTests:()=>UCe,browserProviderActive:()=>NCe,closeBrowserProvider:()=>VI,getBrowserProvider:()=>FCe,getLastRoutingDecision:()=>jCe,peekBrowserProvider:()=>BCe});function Hq(){Promise.resolve(VI()).then(()=>{process.exit(130)})}function Wq(){Promise.resolve(VI()).then(()=>{process.exit(143)})}function Kq(){_o=null}function LCe(){NS||(process.on("SIGINT",Hq),process.on("SIGTERM",Wq),process.on("exit",Kq),NS=!0)}function Gq(){NS&&(process.removeListener("SIGINT",Hq),process.removeListener("SIGTERM",Wq),process.removeListener("exit",Kq),NS=!1)}async function FCe(e){return _o!==null?_o:(al!==null||(al=(async()=>{let t=OI(e),n=e?.surface??(e?.env??{}).AGENT_SURFACE??k.AGENT_SURFACE,r=await yq({config:t,surface:n});JI=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:i}=await Promise.resolve().then(()=>(Cq(),Aq)),s=r.availability.connection;o=new i(t,s)}else{let{PlaywrightProvider:i}=await Promise.resolve().then(()=>(zI(),qI));o=new i(t)}return LCe(),_o=o,al=null,o})()),al)}async function VI(){if(_o===null)return;let e=_o;_o=null,al=null,Gq(),await e.shutdown()}function NCe(){return _o!==null}function BCe(){return _o}function jCe(){return JI}function UCe(){_o=null,al=null,JI=null,Gq()}var _o,al,NS,JI,cl=y(()=>{"use strict";us();bq();F();_o=null,al=null,NS=!1,JI=null});async function qq(e,t){try{return await oq(e,t)}catch(n){return B("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function zCe(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(cl(),ll)),r=await n();try{return await r.render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}catch(o){if(r.name==="agent-browser"){let{PlaywrightProvider:i}=await Promise.resolve().then(()=>(zI(),qI)),{loadBrowserConfig:s}=await Promise.resolve().then(()=>(us(),DI)),a=s(),l=new i(a);try{return await l.render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}finally{await l.shutdown()}}throw o}}async function zq(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??zCe,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let d=await cs(n,e,{headers:qCe,signal:t.signal},o);l=d.status,a=d.url||e;let p=d.headers.get("content-type")??"";if(d.ok){if(GCe.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await d.text();if(KCe.test(p)&&!WCe.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await qq(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof rn||d instanceof Error&&d.message.startsWith("web_scrape markdown mode received binary"))throw d;c=d}if(!(i===null||i.textLength<200)&&i!==null){let d=_I({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...d!==void 0?{advisory:d}:{}}}try{await Vf(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>Vf(f,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await Vf(d.finalUrl,o);let p=await qq(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||p.textLength>=i.textLength){let f=_I({html:d.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:d.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(d){if(t.signal.aborted||d instanceof rn)throw d;if(i===null){let p=d instanceof Error?d.message:String(d),f=c instanceof Error?c.message:`HTTP ${l??"error"}`,g=new Error(`web_scrape could not retrieve ${e}: fetch failed (${f}) and render failed (${p}).`);throw g.cause=d,g}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${l??"error"}).`)}var WCe,KCe,GCe,qCe,Jq=y(()=>{"use strict";iq();PI();il();me();WCe=/(text\/html|application\/xhtml\+xml)/i,KCe=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,GCe=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,qCe={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function YCe(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(JCe,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),VCe),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let u=await i.text(),d=se(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}catch{}let c=i.statusText?` ${i.statusText}`:"";throw new Error(`Exa Search HTTP ${i.status}${c}${l}`)}let s;try{s=await i.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(s.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function Vq(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?YCe({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function Yq(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
429
|
+
${ur(e,{headless:t,latched:n})}`,{cause:e})}var Pq,hCe,yCe,_q,wCe,DS=y(()=>{"use strict";Pq=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],hCe="pnpm exec playwright install chromium",yCe=4;wCe="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 sl from"node:fs";import $S from"node:path";import{randomBytes as SCe}from"node:crypto";function vCe(){try{return"5.222.4"}catch{}try{let e=$S.resolve(import.meta.dirname,"../../../package.json"),t=sl.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var kCe,LS,Mq=y(()=>{"use strict";DS();N();me();kCe=vCe(),LS=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(t){this.config=t}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(t){this.launchFailure={error:t}}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 t;try{({chromium:t}=await import("playwright"))}catch(n){let r=Nu(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await t.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=Nu(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(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){i=l,await a.abort("blockedbyclient")}});let s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw i??p}if(i!==void 0)throw i;let c=await a.content();if(i!==void 0)throw i;let u=a.url(),d=l!==null?l.status():null;return{html:c,finalUrl:u,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){this.clearLaunchFailure();let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),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 t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${kCe}`}}loadStorageState(t){let n=Gc(t);try{if(!sl.existsSync(n))return;let r=JSON.parse(sl.readFileSync(n,"utf8"));return B("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){B("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Gc(t);if(!sl.existsSync(r))return;let o=await n.storageState(),i=$S.join($S.dirname(r),`.${$S.basename(r)}.${process.pid}.${SCe(4).toString("hex")}.tmp`);sl.writeFileSync(i,JSON.stringify(o),{mode:384}),sl.chmodSync(i,384),sl.renameSync(i,r),B("[browser/vault] saved session",{profile:t,file:r})}catch(r){B("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as TCe}from"node:crypto";function xCe(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function ECe(e,t,n){return`el_${TCe("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function RCe(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function Oq(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function $q(e,t){let n=e.role??"",r=e.name??"";Dq.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])$q(i,t)}async function ACe(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let i=o.getBoundingClientRect(),s=o;if(i.width===0&&i.height===0){let u=window.getComputedStyle(s);if(u.display==="none"||u.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},Lq).catch(()=>[])}async function CCe(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let i of r){let s=i.tagName.toLowerCase(),a=i.getAttribute("role")??"",l=i.getAttribute("aria-label")??i.getAttribute("placeholder")??(i.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[s]??"");if(s==="input"){let h=i.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let u="value"in i?i.value:void 0,d=u!==void 0?String(u):void 0,p=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},Lq).catch(()=>[])}function _Ce(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function FS(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=_Ce(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=ACe(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,f,g,h]=await Promise.all([s,a,l,c,u]),b,w=!1;d!==null?(b=[],$q(d,b)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,b=(await CCe(e)).filter(M=>Dq.has(M.role??"")));let S=new Map;for(let _ of p){let M=Oq(_.name),j=S.get(M);(!j||j.bbox.w===0&&_.bbox.w>0)&&S.set(M,_)}let v=b.map(_=>({ax:_,dom:S.get(Oq(_.name??""))})),x=r?v:v.filter(_=>_.dom?_.dom.bbox.w>0||_.dom.bbox.h>0:!0);x.sort((_,M)=>{let j=_.dom?.bbox.y??0,O=M.dom?.bbox.y??0;if(j!==O)return j-O;let H=_.dom?.bbox.x??0,q=M.dom?.bbox.x??0;return H-q}),x.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=x.slice(0,n).map((_,M)=>{let j=_.ax.role??"generic",O=_.ax.name??"",H=ECe(j,O,M),q=_.dom?.bbox??{x:0,y:0,w:0,h:0},W=_.dom?.type??null,K=null;_.ax.value!==void 0&&_.ax.value!==null&&(K=String(_.ax.value)),_.ax.checked!==void 0&&(K=String(_.ax.checked)),wq({role:j,kind:W})&&(K="[redacted]");let Y={disabled:_.ax.disabled??!1};_.ax.checked!==void 0&&(Y.checked=_.ax.checked===!0||_.ax.checked==="mixed"),_.ax.selected!==void 0&&(Y.selected=_.ax.selected),_.ax.expanded!==void 0&&(Y.expanded=_.ax.expanded);let ie;_.dom?.testId?ie=`[data-testid="${_.dom.testId}"]`:_.dom?.id&&(ie=`#${_.dom.id}`);let D={id:H,role:j,label:xCe(O),kind:W,value:K,state:Y,bbox:q};return ie!==void 0&&(D.selector=ie),D}),C="idle";try{let _=await e.evaluate(()=>document.readyState);_==="loading"?C="loading":_==="interactive"?C="navigating":C="idle"}catch{C="navigating"}C!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=RCe(f),A=`obs_${t.observationCounter.toString(36)}`,P=new Date().toISOString();return{observationId:A,url:g,title:h,textSummary:I,interactive:E,status:{httpStatus:t.httpStatus??null,loadingState:C,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:P}}var Dq,Lq,Fq=y(()=>{"use strict";MS();Dq=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Lq="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Nq(e,t){try{let n=await e.nth(t).evaluate(s=>{let a=s,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.height)}}),r=`${n.role}:${n.label}:${t}`,o=0;for(let s=0;s<r.length;s++)o=o*31+r.charCodeAt(s)>>>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 HI(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>Nq(e,i)))).filter(o=>o!==null)}async function PCe(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let i=0;i<o;i++){let s;try{s=await r.nth(i).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(s)||(t.add(s),n.push({key:s,locator:r,index:i}))}return n}async function WI(e,t,n){switch(t.kind){case"element_id":return ICe(e,t,n);case"selector":return MCe(e,t);case"semantic":return OCe(e,t)}}async function ICe(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),i=await o.count();if(i===0)return{outcome:"not_found",query:t};if(i===1)return{outcome:"resolved",locator:o};let s=await HI(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function MCe(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await HI(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function OCe(e,t){return t.role!==void 0?DCe(e,t.text,t.role):$Ce(e,t.text,t)}async function DCe(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let i=await HI(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function $Ce(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),i=e.getByLabel(t,{exact:!1}),[s,a,l]=await Promise.all([r.count(),o.count(),i.count()]);if(s+a+l===0)return{outcome:"not_found",query:n};let u=[];s>0&&u.push({loc:r,count:s}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:i,count:l});let d=await PCe(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=d.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let w=await Nq(b.locator,b.index);if(w!==null){let S=`${w.role}:${w.label}:${h}`,v=0;for(let x=0;x<S.length;x++)v=v*31+S.charCodeAt(x)>>>0;f.push({...w,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var Bq=y(()=>{"use strict"});async function KI(e,t,n,r){let o=e.url();if(o===n)return null;let i=Br(o,t);if(i.allowed)return null;try{await e.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:i.reason}}var jq=y(()=>{"use strict";us()});var qI={};lt(qI,{PlaywrightProvider:()=>GI});function Uq(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var GI,zI=y(()=>{"use strict";Mq();Fq();Bq();us();jq();FI();GI=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new LS(t)}async open(t){let n=Br(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(d){a=d}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let d=await KI(o,this.config,t.url,()=>this.close({sessionId:r}));if(d!==null)return d}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let u=await FS(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,u.interactive,u.url,u.title,"browser_open"),a!==null)throw a;return u}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await FS(r,{observationCounter:o.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,s.interactive,s.url,s.title,"browser_observe"),s}async act(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),i=r.url(),s=t.timeoutMs??3e4,a=await WI(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Uq(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":await l.fill(t.value??"");break;case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=await KI(r,this.config,i,()=>this.close({sessionId:n}));if(d!==null)return d;let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await FS(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal,requestGuard:t.requestGuard})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),i;if(t.target!==void 0){let u=await WI(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Uq(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await u.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await Fu(n,i,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}return{path:s,bytes:a,width:l,height:c,dataBase64:i.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(t){let n=this.sessions.get(t);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(t,r),r}updateSessionFromObservation(t,n,r,o,i){t.knownElements=new Map(n.map(s=>[s.id,s])),t.currentUrl=r,t.currentTitle=o,t.lastAction=i,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:i}=await Fu(n,o,r);return i}catch{return null}}}});var ll={};lt(ll,{__resetBrowserRegistryForTests:()=>UCe,browserProviderActive:()=>NCe,closeBrowserProvider:()=>VI,getBrowserProvider:()=>FCe,getLastRoutingDecision:()=>jCe,peekBrowserProvider:()=>BCe});function Hq(){Promise.resolve(VI()).then(()=>{process.exit(130)})}function Wq(){Promise.resolve(VI()).then(()=>{process.exit(143)})}function Kq(){_o=null}function LCe(){NS||(process.on("SIGINT",Hq),process.on("SIGTERM",Wq),process.on("exit",Kq),NS=!0)}function Gq(){NS&&(process.removeListener("SIGINT",Hq),process.removeListener("SIGTERM",Wq),process.removeListener("exit",Kq),NS=!1)}async function FCe(e){return _o!==null?_o:(al!==null||(al=(async()=>{let t=OI(e),n=e?.surface??(e?.env??{}).AGENT_SURFACE??k.AGENT_SURFACE,r=await yq({config:t,surface:n});JI=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:i}=await Promise.resolve().then(()=>(Cq(),Aq)),s=r.availability.connection;o=new i(t,s)}else{let{PlaywrightProvider:i}=await Promise.resolve().then(()=>(zI(),qI));o=new i(t)}return LCe(),_o=o,al=null,o})()),al)}async function VI(){if(_o===null)return;let e=_o;_o=null,al=null,Gq(),await e.shutdown()}function NCe(){return _o!==null}function BCe(){return _o}function jCe(){return JI}function UCe(){_o=null,al=null,JI=null,Gq()}var _o,al,NS,JI,cl=y(()=>{"use strict";us();bq();F();_o=null,al=null,NS=!1,JI=null});async function qq(e,t){try{return await oq(e,t)}catch(n){return B("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function zCe(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(cl(),ll)),r=await n();try{return await r.render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}catch(o){if(r.name==="agent-browser"){let{PlaywrightProvider:i}=await Promise.resolve().then(()=>(zI(),qI)),{loadBrowserConfig:s}=await Promise.resolve().then(()=>(us(),DI)),a=s(),l=new i(a);try{return await l.render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}finally{await l.shutdown()}}throw o}}async function zq(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??zCe,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let d=await cs(n,e,{headers:qCe,signal:t.signal},o);l=d.status,a=d.url||e;let p=d.headers.get("content-type")??"";if(d.ok){if(GCe.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await d.text();if(KCe.test(p)&&!WCe.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await qq(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof rn||d instanceof Error&&d.message.startsWith("web_scrape markdown mode received binary"))throw d;c=d}if(!(i===null||i.textLength<200)&&i!==null){let d=_I({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...d!==void 0?{advisory:d}:{}}}try{await Vf(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>Vf(f,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await Vf(d.finalUrl,o);let p=await qq(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||p.textLength>=i.textLength){let f=_I({html:d.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:d.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(d){if(t.signal.aborted||d instanceof rn)throw d;if(i===null){let p=d instanceof Error?d.message:String(d),f=c instanceof Error?c.message:`HTTP ${l??"error"}`,g=new Error(`web_scrape could not retrieve ${e}: fetch failed (${f}) and render failed (${p}).`);throw g.cause=d,g}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${l??"error"}).`)}var WCe,KCe,GCe,qCe,Jq=y(()=>{"use strict";iq();PI();il();me();WCe=/(text\/html|application\/xhtml\+xml)/i,KCe=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,GCe=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,qCe={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function YCe(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(JCe,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),VCe),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let u=await i.text(),d=se(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}catch{}let c=i.statusText?` ${i.statusText}`:"";throw new Error(`Exa Search HTTP ${i.status}${c}${l}`)}let s;try{s=await i.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(s.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function Vq(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?YCe({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function Yq(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
430
430
|
|
|
431
431
|
(no results)`;let n=[`# Search results for "${e}"`,""];return t.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
|
|
432
432
|
`).trimEnd()}var JCe,VCe,Xq=y(()=>{"use strict";Ne();JCe="https://api.exa.ai/search",VCe=10});function BS(e){if(e instanceof Error&&e.name==="TimeoutError")return"timeout";let t=e instanceof Error?e.message:String(e);return/Timeout\s+\d+\s*ms exceeded/i.test(t)?"timeout":void 0}var ul=y(()=>{"use strict";DS()});function n_e(e){if(!e||typeof e!="object")return{error:"Invalid input: expected an object"};let t=e,n=t.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,i;if(r==="search"){if(typeof t.query!="string"||t.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};i=t.query}else{if(typeof t.url!="string"||t.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let l;try{l=new URL(t.url)}catch{return{error:`Invalid input: "${t.url}" is not a valid absolute URL`}}if(l.protocol!=="http:"&&l.protocol!=="https:")return{error:`Invalid input: protocol "${l.protocol}" not supported (http/https only)`};o=l.toString()}let s=XCe;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};s=Math.min(t.timeout_ms,QCe)}let a=ZCe;if(t.max_bytes!==void 0){if(typeof t.max_bytes!="number"||!Number.isFinite(t.max_bytes)||t.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(t.max_bytes,e_e)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function YI(e,t){return Buffer.byteLength(e,"utf8")<=t?{content:e,truncated:!1}:{content:Lr(e,t),truncated:!0}}function r_e(e={}){let t=e.fetchFn??globalThis.fetch,n=e.env??process.env,r=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{};return async(o,i)=>{if(typeof t!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=n_e(o);if("error"in s)return{content:s.error,isError:!0};if(i.aborted){let d=i.reason;return{content:`web_scrape aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let a=new AbortController,l=()=>{a.abort(i.reason)},c,u=()=>{let d=a.signal.reason;return d instanceof Error?d.message:String(d??"aborted")};try{if(i.addEventListener("abort",l,{once:!0}),c=setTimeout(()=>{a.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs),s.url!==void 0){let p=await ol(s.url,r);if(a.signal.aborted)return{content:`web_scrape aborted: ${u()}`,isError:!0};if(!p.allowed)return{content:`web_scrape blocked: ${p.reason}`,isError:!0}}if(s.mode==="raw"){let p;try{let h={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};p=await cs(t,s.url,h,r)}catch(h){return a.signal.aborted?{content:`web_scrape aborted: ${u()}`,isError:!0}:h instanceof rn?{content:`web_scrape blocked: ${h.message}`,isError:!0}:{content:`web_scrape network error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}if(!p.ok)return{content:`web_scrape HTTP ${p.status} ${p.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let f;try{f=await p.text()}catch(h){return{content:`web_scrape read error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}let g=YI(f,s.maxBytes);return{content:g.content,...g.truncated?{truncated:!0}:{}}}if(s.mode==="markdown")try{let p=await zq(s.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:s.timeoutMs,signal:a.signal,...e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{}});if(p.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0};let f=YI(sq(p.markdown,p.advisory),s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){if(a.signal.aborted)return{content:`web_scrape aborted: ${u()}`,isError:!0};if(p instanceof rn)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),g=In(p)&&!UI(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${Yf()}\`)`:"";return{content:`web_scrape markdown error: ${f}${g}`,isError:!0}}let d=Vq({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in d)return{content:d.error,isError:!0};try{let p=await d.search(s.query,{limit:t_e,timeoutMs:s.timeoutMs,signal:a.signal}),f=YI(Yq(s.query,p),s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){return a.signal.aborted?{content:`web_scrape aborted: ${u()}`,isError:!0}:{content:`web_scrape search error (${d.name}): ${p instanceof Error?p.message:String(p)}`,isError:!0}}}finally{c!==void 0&&clearTimeout(c),i.removeEventListener("abort",l)}}}var XCe,QCe,ZCe,e_e,t_e,Qq,Zq=y(()=>{"use strict";Jq();Xq();il();vo();PI();ul();XCe=3e4,QCe=12e4,ZCe=1e5,e_e=1e6,t_e=10;Qq=r_e()});function s_e(e){return o_e.has(e)?"low":e==="DELETE"?"high":"medium"}function a_e(e){return i_e.has(e)}function u_e(e){let t={};return e.forEach((n,r)=>{let o=r.toLowerCase();c_e.has(o)||l_e.some(i=>o.startsWith(i))||(t[r]=n)}),t}function d_e(e,t){if(e==null)return{serialized:void 0,inferredContentType:void 0};let n=Object.keys(t).some(o=>o.toLowerCase()==="content-type");return typeof e=="string"?{serialized:e,inferredContentType:n?void 0:"text/plain"}:{serialized:JSON.stringify(e),inferredContentType:n?void 0:"application/json"}}function p_e(e,t,n){let r=Buffer.byteLength(e,"utf8"),o=e,i=!1;if(r>n&&(o=Lr(e,n),i=!0),!i&&/application\/json/i.test(t))try{return{body:JSON.parse(o),truncated:!1}}catch{}return{body:o,truncated:i}}async function nz(e){let{url:t,method:n,signal:r,domainCheck:o,recordEffect:i}=e,s=Math.min(e.maxResponseBytes??XI,QI),a={...e.headers},l=e.fetchFn??globalThis.fetch,c=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},u=s_e(n);if(o!==void 0){let A=o(t);if(!A.allowed)throw Object.assign(new Error(`web_request blocked by domain policy: ${A.reason}`),{name:"DomainPolicyError"})}let d=await ol(t,c);if(!d.allowed)throw new rn(d.reason);let{serialized:p,inferredContentType:f}=d_e(e.body,a);f!==void 0&&(a["content-type"]=f);let g={method:n,headers:Object.keys(a).length>0?a:void 0,body:p,signal:r},b=a_e(n)?{retries:2,baseDelayMs:300,maxDelayMs:5e3}:{retries:0},w=Date.now(),S;try{S=await cs(l,t,g,{...c,retry:b})}catch(A){throw A instanceof rn,A}let v=Date.now()-w,x=S.headers.get("content-type")??"",T;try{let A=S.body?.getReader();if(!A)T="";else{let P=[],_=0,M=s*2;for(;;){let{done:j,value:O}=await A.read();if(j||!O)break;if(P.push(O),_+=O.byteLength,_>=M){await A.cancel();break}}T=new TextDecoder().decode(Buffer.concat(P,_))}}catch{T=""}let{body:E,truncated:C}=p_e(T,x,s),I=u_e(S.headers);return i!==void 0&&Promise.resolve(i({url:t,method:n,status:S.status,risk:u,timing_ms:v})).catch(()=>{}),{status:S.status,headers:I,body:E,truncated:C,timing_ms:v,risk:u}}function rz(e){if(typeof e!="string"||e.trim().length===0)return{error:"method must be a non-empty string (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS)"};let t=e.trim().toUpperCase(),n=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];return n.includes(t)?t:{error:`method "${e}" is not supported \u2014 must be one of: ${n.join(", ")}`}}var ez,tz,XI,QI,o_e,i_e,l_e,c_e,oz=y(()=>{"use strict";il();vo();ez=3e4,tz=12e4,XI=1e5,QI=1e6,o_e=new Set(["GET","HEAD","OPTIONS"]),i_e=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]);l_e=["set-cookie","x-"],c_e=new Set(["server","via","age","vary","authorization","www-authenticate"])});function m_e(e){if(!e||typeof e!="object")return{error:"Invalid input: expected an object"};let t=e;if(typeof t.url!="string"||t.url.length===0)return{error:'Invalid input: "url" must be a non-empty string'};let n;try{n=new URL(t.url)}catch{return{error:`Invalid input: "${t.url}" is not a valid absolute URL`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{error:`Invalid input: protocol "${n.protocol}" not supported (http/https only)`};n.username="",n.password="";let r=n.toString(),o=rz(t.method);if(typeof o=="object"&&"error"in o)return{error:`Invalid input: ${o.error}`};let i=o,s;if(t.body!==void 0&&t.body!==null){if(typeof t.body!="string"&&typeof t.body!="object")return{error:'Invalid input: "body" must be a string, object, or array'};s=t.body}let a={};if(t.headers!==void 0){if(typeof t.headers!="object"||t.headers===null||Array.isArray(t.headers))return{error:'Invalid input: "headers" must be a string-keyed object'};let d=t.headers;for(let[p,f]of Object.entries(d)){if(typeof f!="string")return{error:`Invalid input: header value for "${p}" must be a string`};a[p]=f}}let l=ez;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:'Invalid input: "timeout_ms" must be a positive finite number'};l=Math.min(t.timeout_ms,tz)}let c=XI;if(t.max_response_bytes!==void 0){if(typeof t.max_response_bytes!="number"||!Number.isFinite(t.max_response_bytes)||t.max_response_bytes<=0)return{error:'Invalid input: "max_response_bytes" must be a positive finite number'};c=Math.min(t.max_response_bytes,QI)}let u;if(t.credential!==void 0){if(typeof t.credential!="string"||t.credential.length===0)return{error:'Invalid input: "credential" must be a non-empty string (an env var name)'};u=t.credential}return{url:r,method:i,body:s,headers:a,timeoutMs:l,maxResponseBytes:c,credential:u}}function f_e(e={}){let t=e.fetchFn??globalThis.fetch,n=e.env??process.env;async function r(){if(e.domainCheck!==void 0)return e.domainCheck;try{let{loadBrowserConfig:o,enforceDomainPolicy:i}=await Promise.resolve().then(()=>(us(),DI)),s=o();return a=>i(a,s)}catch{return}}return async(o,i)=>{if(typeof t!="function")return{content:"web_request unavailable: global fetch() is not present (agent-afk requires Node 20+).",isError:!0};let s=m_e(o);if("error"in s)return{content:s.error,isError:!0};if(i.aborted){let p=i.reason;return{content:`web_request aborted: ${p instanceof Error?p.message:String(p??"aborted")}`,isError:!0}}let a={...s.headers};if(s.credential!==void 0){let p=n[s.credential];if(p===void 0||p.trim().length===0)return{content:`web_request credential error: environment variable "${s.credential}" is not set. Set it in afk.env or export it in the shell before starting AFK.`,isError:!0};if(Object.keys(a).some(g=>g.toLowerCase()==="authorization"))return{content:'web_request credential error: both "credential" and an explicit Authorization header were provided. Use one or the other.',isError:!0};a.Authorization=`Bearer ${p}`}let l=new AbortController,c=()=>l.abort(i.reason),u,d=()=>{let p=l.signal.reason;return p instanceof Error?p.message:String(p??"aborted")};try{i.addEventListener("abort",c,{once:!0}),u=setTimeout(()=>{l.abort(new Error(`web_request timeout after ${s.timeoutMs}ms`))},s.timeoutMs);let p=await r(),f={url:s.url,method:s.method,body:s.body,headers:a,maxResponseBytes:s.maxResponseBytes,signal:l.signal,fetchFn:t,lookupFn:e.lookupFn,domainCheck:p,recordEffect:e.recordEffect},g;try{g=await nz(f)}catch(S){if(l.signal.aborted)return{content:`web_request aborted: ${d()}`,isError:!0};if(S instanceof rn)return{content:`web_request blocked: ${S.message}`,isError:!0};let v=S instanceof Error&&S.name==="DomainPolicyError"?"blocked":"network error",x=S instanceof Error?S.message:String(S);return{content:`web_request ${v}: ${x}`,isError:!0}}if(l.signal.aborted)return{content:`web_request aborted: ${d()}`,isError:!0};let h=g.body;if(typeof h=="string")h=ft(h);else if(typeof h=="object"&&h!==null){let S=ft(JSON.stringify(h));try{h=JSON.parse(S)}catch{h=S}}let b={status:g.status,headers:g.headers,body:h,timing_ms:g.timing_ms,...g.truncated?{truncated:!0}:{}};return{content:JSON.stringify(b,null,2),...g.truncated?{truncated:!0}:{}}}finally{u!==void 0&&clearTimeout(u),i.removeEventListener("abort",c)}}}var iz,sz=y(()=>{"use strict";oz();il();Ir();iz=f_e()});import{existsSync as lz,mkdirSync as g_e,readFileSync as h_e,renameSync as y_e,unlinkSync as b_e,writeFileSync as w_e}from"node:fs";import{dirname as az,join as S_e}from"node:path";import{randomBytes as v_e}from"node:crypto";function zt(e){let t=e??vb();if(!lz(t))return[];try{let n=h_e(t,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);return console.error(`[schedule-store] failed to parse ${t}: ${r}`),[]}}function jr(e,t){let n=t??vb();g_e(az(n),{recursive:!0});let r=S_e(az(n),`.schedules.json.${process.pid}.${v_e(4).toString("hex")}.tmp`),o=JSON.stringify(e,null,2);try{w_e(r,o,"utf-8"),y_e(r,n)}catch(i){try{lz(r)&&b_e(r)}catch{}throw i}}function Bu(e,t){let n=zt(t),r=n.map(l=>l.id),o=k_e(e.name),i=T_e(o,r),s=new Date().toISOString(),a={...e,notifyOn:e.notifyOn??"failure",id:i,createdAt:s,updatedAt:s};return n.push(a),jr(n,t),a}function ju(e,t){let n=zt(t),r=n.length,o=n.filter(i=>i.id!==e);return o.length===r?!1:(jr(o,t),!0)}function dl(e,t){return zt(t).find(n=>n.id===e)}function k_e(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function T_e(e,t){if(!t.includes(e))return e;let n=2;for(;t.includes(`${e}-${n}`);)n+=1;return`${e}-${n}`}function ds(e){return{taskId:e.id,command:e.command,trigger:e.trigger??"cron",...e.executor!==void 0?{executor:e.executor}:{},...e.cron!==void 0?{cronExpression:e.cron}:{},...e.notifyOn!==void 0?{notifyOn:e.notifyOn}:{},...e.notifyChat!==void 0?{notifyChat:e.notifyChat}:{}}}var Xf=y(()=>{"use strict";N()});import{existsSync as x_e,readFileSync as E_e}from"node:fs";import{join as R_e}from"node:path";async function gt(e,t,n){let r,o;try{let i=R_e(Ea("default"),"port");if(!x_e(i))return{synced:!1,detail:"daemon-not-detected (no port file)"};let s=E_e(i,"utf-8").trim(),a=ZI(s);if(!a)return{synced:!1,detail:"daemon-not-detected (invalid port file)"};({host:r,port:o}=a)}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let i=r.includes(":")?`[${r}]`:r,s=await fetch(`http://${i}:${o}${t}`,{method:e,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return s.ok?{synced:!0,detail:"synced"}:e==="POST"&&s.status===409?{synced:!0,detail:"already-registered"}:e==="DELETE"&&s.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${s.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}function ZI(e){let t=parseInt(e,10);if(String(t)===e&&!Number.isNaN(t))return t<1||t>65535?null:{host:"localhost",port:t};let n=e.lastIndexOf(":");if(n<1)return null;let r=e.slice(0,n),o=e.slice(n+1);if(!/^\d+$/.test(o))return null;let i=parseInt(o,10);return Number.isNaN(i)||i<1||i>65535||/^:+$/.test(r)?null:{host:r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r,port:i}}var Kn,jS=y(()=>{"use strict";N();Kn="Change saved to schedules.json, but a running daemon (if any) did not pick it up \u2014 it will apply on the next daemon (re)start."});import{existsSync as A_e}from"node:fs";import{readFile as C_e}from"node:fs/promises";var cz,uz,dz,pz,mz=y(()=>{"use strict";Xf();N();jS();cz=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected object",isError:!0};let n=e;if(typeof n.name!="string"||!n.name)return{content:"Invalid input: name required",isError:!0};if(typeof n.command!="string"||!n.command)return{content:"Invalid input: command required",isError:!0};if(typeof n.cron!="string"||!n.cron)return{content:"Invalid input: cron required",isError:!0};let r=n.cron.trim().split(/\s+/);if(r.length!==5&&r.length!==6)return{content:"Invalid input: cron must be a 5 or 6-field expression",isError:!0};let o=n.notifyChat;if(o!==void 0&&typeof o!="number"&&typeof o!="string")return{content:"Invalid input: notifyChat must be a number (chat id) or string (chat id or alias name)",isError:!0};let i=n.executor;if(i!==void 0&&i!=="agent"&&i!=="shell")return{content:'Invalid input: executor must be "agent" or "shell"',isError:!0};let s=Bu({name:n.name,command:n.command,cron:n.cron,...i!==void 0?{executor:i}:{},trigger:n.trigger??"cron",notifyOn:n.notifyOn,...o!==void 0?{notifyChat:o}:{},enabled:typeof n.enabled=="boolean"?n.enabled:!0}),a=s.enabled?await gt("POST","/tasks",{taskId:s.id,command:s.command,cron:s.cron,...s.executor!==void 0?{executor:s.executor}:{},trigger:s.trigger,notifyOn:s.notifyOn,...s.notifyChat!==void 0?{notifyChat:s.notifyChat}:{}}):await gt("DELETE",`/tasks/${s.id}`);return{content:JSON.stringify({id:s.id,name:s.name,cron:s.cron,enabled:s.enabled,daemonSynced:a.synced,syncDetail:a.detail,...a.synced?{}:{syncNote:Kn}})}},uz=async(e,t)=>{let n=zt();return{content:JSON.stringify(n.map(r=>({id:r.id,name:r.name,cron:r.cron,executor:r.executor??"agent",trigger:r.trigger,enabled:r.enabled,notifyOn:r.notifyOn})))}},dz=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected object",isError:!0};let n=e;if(typeof n.taskId!="string"||!n.taskId)return{content:"Invalid input: taskId required",isError:!0};let r=n.taskId,o=typeof n.limit=="number"?Math.min(Math.max(1,n.limit),50):10,i=jn();if(!A_e(i))return{content:JSON.stringify([])};let s;try{let c=await C_e(i);s=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=s.split(`
|
|
@@ -2352,7 +2352,7 @@ ${x}
|
|
|
2352
2352
|
${T}`})}return{fileBlocks:l,warnings:c}}function tde(e){let t=e.replace(/\s+/g," ").trim();return t.length<=60?t:`${t.slice(0,59)}\u2026`}async function nde(e,t,n){let r=t?.peekQueuedText(),o=r!==void 0?{text:r.text,claimed:!1}:void 0;r!==void 0&&t?.reserveQueued?.(r);let i;try{i=await e.promoteActiveForeground(o)}catch(s){throw r!==void 0&&t?.releaseQueued?.(r),s}if(o?.claimed===!0&&t!==null&&r!==void 0){try{await n?.(o.text)}catch{}return t.dropQueued(r),{jobs:i,flushedText:o.text,flushedPreview:r.preview}}return r!==void 0&&t?.releaseQueued?.(r),{jobs:i}}F();L();F();Ze();L();Nl();function rde(){return{toolStartTimes:new Map,subagentStartTimes:new Map,subagentLabels:new Map}}function ode(e,t){Ke()&&(t.pending||e.toolStartTimes.has(t.toolUseId)||e.toolStartTimes.set(t.toolUseId,Date.now()))}function ide(e,t,n,r){if(!Ke())return;let o=e.toolStartTimes.get(t.toolUseId),i=o!==void 0?Date.now()-o:void 0;e.toolStartTimes.delete(t.toolUseId);let s=$e(n??"tool"),a=t.isError?m.error("err"):m.success("ok"),l=i!==void 0?` \xB7 ${Se(i)}`:"";r.fn(m.dim(` \u25E6 ${s}${l} \xB7 `)+a)}function sde(e,t,n,r){if(!Ke())return;let{subagentId:o,agentType:i}=n,s=$e(i??o);if(e.subagentStartTimes.has(o)||(e.subagentStartTimes.set(o,Date.now()),e.subagentLabels.set(o,s),r.fn(m.dim(` \u25E6 worker ${s} started`))),t.type==="done"||t.type==="error"){let l=e.subagentStartTimes.get(o),c=l!==void 0?Date.now()-l:void 0;e.subagentStartTimes.delete(o),e.subagentLabels.delete(o);let u=c!==void 0?` \xB7 ${Se(c)}`:"",d=t.type==="error"?m.error("failed"):m.success("done");r.fn(m.dim(` \u25E6 worker ${s}${u} \xB7 `)+d)}}var AA=class{state;writer;ttfb;constructor(t,n){this.state=rde(),this.writer=t,this.ttfb=n}onToolStart(t){ode(this.state,t)}onToolResult(t,n){ide(this.state,t,n,this.writer)}onSubagentEvent(t,n){sde(this.state,t,n,this.writer)}onFirstContent(t){this.ttfb.waitingLineEmitted&&(this.ttfb.waitingLineEmitted=!1,t.write("\r\x1B[2K"))}};function ade(e){return{startedAt:e,received:!1,waitingLineEmitted:!1}}function lde(e){return e.received?{}:{turnStartedAt:e.startedAt}}function cde(e,t,n){let r=t.type==="chunk"&&t.chunk.type==="content"&&!n;return r&&(e.received=!0),r}function ude(e,t=process.stdout,n){if(!Ke()||!t.isTTY)return;(e?.fn??console.log)(m.dim(" \u25E6 waiting for response\u2026")),n&&(n.waitingLineEmitted=!0,e&&(n.plainHooks=new AA(e,n)))}me();L();var lXe=3e3;async function dde(e,t){if(!e)return t;let n=Date.now();if(n-t<lXe)return t;try{let r=e();r instanceof Promise&&await r}catch(r){ze()&&console.error(" "+m.error("onContextProgress (status refresh) failed:"),r)}return n}L();me();wt();oa();var cXe="Keep waiting \u2014 auto-resume in progress",pde="Switch model / provider (type /model after)",uXe="Stop waiting";async function mde(e){let{event:t,session:n,borrowedCompositor:r,pickerRef:o,completionWriter:i,disposeRendererOnce:s,setPausedState:a,onPauseInterrupt:l}=e;if(a?.(!0),await s(),r&&t.autoResume===!0){let c=new AbortController;o.abort=c;let u=t.resetsAt?t.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,d=u?`Keep waiting \u2014 auto-resumes at ${u}`:cXe,p=[m.warning(" \u23F3 Usage limit reached.")+(u?m.dim(` Auto-resumes at ${u}.`):""),m.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];Fn(r,{header:p,options:[d,pde,uXe],signal:c.signal,initialIndex:0}).then(f=>{if(o.abort=null,!f)return;let g=f[0];g===void 0||g===d||(l(),g===pde&&(i??{fn:console.log}).fn(m.dim(" Hint: type /model <name> to switch, then send your message again.")),n.interrupt().catch(h=>{ze()&&console.error(" "+m.error("picker pause-interrupt session.interrupt() failed:"),h)}))}).catch(f=>{ze()&&console.error(" "+m.error("picker promise rejected:"),f)})}else(i??{fn:console.log}).fn(T1({reason:t.reason,...t.resetsAt!==void 0?{resetsAt:t.resetsAt}:{},...t.accountId!==void 0?{accountId:t.accountId}:{},...t.autoResume!==void 0?{autoResume:t.autoResume}:{}}))}CE();async function fde(e,t,n,r,o="summary",i,s){let a=dre(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0);let l=Date.now(),c=ade(l);ude(i,process.stdout,c),gp(process.stdout,Mh(process.cwd(),!0));let u="",d=0,p=!1,f=!1,g=!1,h=!1,b=!1,w,S=!1,v=!1,x={abort:null},T=0,E=[],C=new Map,I=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,A=()=>{let H=r.subagentControl;H?.hasPromotableForeground()&&nde(H,P,r.onQueuedUserMessage).then(({jobs:q,flushedText:W,flushedPreview:K})=>{let Y=(i??{fn:console.log}).fn;for(let ie of q)Y(m.dim(` \u2192 subagent backgrounded as ${ie.jobId}: ${ie.label}`));q.some(ie=>ie.sharesWorktree)&&Y(m.warning("\u26A0 Background child is writing to your worktree \u2014 edits may conflict until it finishes")),W!==void 0&&Y(m.dim(` \u2192 queued message sent to this turn: ${tde(K??W)}`))}).catch(()=>{})},P=r.getCompositor?r.getCompositor():null,_=()=>new jp({out:Hp(i),thinkingMode:o,...I?{activeSkillName:I}:{},onCancel:()=>{t.interrupt().catch(H=>{ze()&&console.error(" "+m.error("session.interrupt() failed:"),H)})},...r.subagentControl?{onBackground:A}:{},...s?.history?{history:s.history}:{},...s?.autocompleteState?{autocompleteState:s.autocompleteState}:{},...s?.promptText!==void 0?{promptText:s.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...P?{compositor:P}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{},...lde(c),...r.addPreviewDiffRef?{addPreviewDiffRef:r.addPreviewDiffRef}:{}}),M=_();r.bashTailSetter&&(r.bashTailSetter.current=(H,q)=>M.setBashOutputTail(H,q));let j=async()=>{if(!h){h=!0,r.bashTailSetter&&(r.bashTailSetter.current=void 0);try{await M.dispose()}catch{}}},O=async()=>{await M.arm();let H=M.getCompositor();if(i&&H){let q=H;i.fn=W=>q.commitAbove(W),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.(H),r.setInterruptNotifier?.(q=>M.setInterrupting(q)),r.rearmStatus?.()};try{P?P.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{S=!0,M.setSoftStopping(!0),t.interrupt().catch(Q=>{ze()&&console.error(" "+m.error("soft-stop session.interrupt() failed:"),Q)});let U=r.subagentControl;U?.hasActiveForeground()&&U.cancelActiveForeground().catch(Q=>{ze()&&console.error(" "+m.error("soft-stop cancelActiveForeground() failed:"),Q)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{v=!0,t.interrupt().catch(U=>{ze()&&console.error(" "+m.error("pause-interrupt session.interrupt() failed:"),U)})}),await O(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(A),r.setTaskViewHandler?.(Vue(r));let{fileBlocks:H,warnings:q}=ede(e.text,{rootDir:process.cwd()});for(let U of q)(i??{fn:console.log}).fn(m.dim(` @-file: ${U}`));if(e.attachments.length>0&&(await t.waitForInitialization(),t.sessionId===void 0))throw new Error("CLI session initialized without a session id");let W=H.length>0||e.attachments.length>0?await Zue(e.text,e.attachments,void 0,H,t.sessionId):e.text,K=t.sendMessageStream(W);await Zu((U,Q)=>{M.process(U,Q),Q&&c.plainHooks?.onSubagentEvent(U,Q)},async()=>{for await(let U of K){if(S||v)break;let Q=cde(c,U,f);if(U.type==="chunk"&&U.chunk.type==="content"?(u=p?zue(u,U.chunk.content):u+U.chunk.content,p=!1,f=!0,r.onTextDelta?.(U.chunk.content.length)):U.type==="message"&&!f&&(u=U.message.content),U.type==="stream_retry"&&(u=u.slice(0,d),p=u.length>0),U.type==="chunk"&&U.chunk.type==="tool_use_detail"){let le=U.chunk,Z={toolName:le.toolName,toolUseId:le.toolUseId,input:le.toolInput,...le.toolInputRaw!==void 0&&{inputRaw:le.toolInputRaw}};C.set(le.toolUseId,Z),E.push(Z),c.plainHooks?.onToolStart(le)}else if(U.type==="chunk"&&U.chunk.type==="tool_result"){let le=U.chunk;d=u.length,p=!0;let Z=C.get(le.toolUseId);Z&&(Z.result=le.content,Z.isError=le.isError,C.delete(le.toolUseId)),c.plainHooks?.onToolResult(le,Z?.toolName),T=await dde(r.onContextProgress,T)}if(U.type==="paused"){await mde({event:U,session:t,borrowedCompositor:P,pickerRef:x,completionWriter:i,disposeRendererOnce:j,setPausedState:r.setPausedState,onPauseInterrupt:()=>{v=!0}});continue}if(U.type==="resumed"){r.setPausedState?.(!1),x.abort?.abort(),x.abort=null;let le=U.hotSwapped&&U.accountId?`\u25B6 Resumed on ${U.accountId}`:"\u25B6 Resumed";u="",d=0,p=!1,f=!1,E.length=0,C.clear(),b=!1,w=void 0,g=!1,M=_(),h=!1,await O(),(i??{fn:console.log}).fn(m.success(le));continue}if(U.type==="error"){await j(),ou(Vc(U.error)),g=!0;continue}M.process(U),Q&&(c.plainHooks?.onFirstContent(process.stdout),M.notifyFirstContent()),U.type==="done"&&(b=!0,w=U.metadata)}});let ie=!1;if(b&&!S&&!v){let U=Gue(M.getPendingBuffer());U>=0?M.stripPendingTerminalState(U):Py(u)!==null&&(ie=!0)}await j();let D=i?i.fn:console.log;if(S){let U=P?P.getPendingCount():0,Q=U>0?` \xB7 ${U} queued`:"";D(m.warning(`\u23F8 Stopped${Q} \u2014 work so far kept.`)+m.dim(" Send a message to continue.")),D("")}if(v&&(D(m.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),D("")),b&&!S&&!v){Kl(n,a,u,w,E),await r.onTurnComplete?.(a,u).catch(()=>{}),fp(process.stdout),bte(process.stdout,"afk: turn complete");let U=le=>{i?i.fn(le):console.log(le)},Q=Py(u);if(Q&&!ie){U(Jue(Q,{durationMs:w?.durationMs,totalCostUsd:w?.totalCostUsd,toolCount:E.length})),U("");let le=ON(E),Z=Bse(E);if(r.onTerminalState)try{r.onTerminalState(Q,{doneHasCorroboratingEvidence:Z,doneEvidenceClassification:le})}catch{}if(n.permissionMode==="autonomous"){let De=Q.kind==="done"&&qf().verifyDone===!0&&!Z;Use(Q,void 0,{unverified:De})}}if(WB(w,n,U),KB(U,process.stdout),r.onAfterTurn){let le=r.onAfterTurn();le instanceof Promise&&await le.catch(()=>{})}}}catch(H){await j(),g||ou(Vc(H))}finally{await j(),gp(process.stdout,Mh(process.cwd(),!1)),i&&(i.fn=i.idleFn,i.suppressSubagentCompletion=!1),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setTaskViewHandler?.(null),r.setSoftStopHandler?.(null),r.setPausedState?.(!1),r.setPauseInterruptHandler?.(null),x.abort?.abort(),x.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}zs();Wm();var CA=class{onRepaint;running=!1;smoothedRate=null;lastSampleMs=null;pendingChars=0;lastRepaintMs=0;constructor(t){this.onRepaint=t}start(){this.running=!0,this.smoothedRate=null,this.lastSampleMs=null,this.pendingChars=0,this.lastRepaintMs=0}update(t){if(!this.running||t<=0)return;this.pendingChars+=t;let n=Date.now();if(this.lastSampleMs===null){this.lastSampleMs=n;return}let r=n-this.lastSampleMs;if(r<50)return;if(r>3e3){this.lastSampleMs=n,this.pendingChars=0;return}let o=this.pendingChars/4/r*1e3;this.smoothedRate=this.smoothedRate===null?o:.25*o+(1-.25)*this.smoothedRate,this.lastSampleMs=n,this.pendingChars=0,this.onRepaint&&n-this.lastRepaintMs>=300&&(this.lastRepaintMs=n,this.onRepaint(this.smoothedRate))}getCurrentRate(){return this.running?this.smoothedRate:null}stop(){this.running=!1,this.smoothedRate=null,this.lastSampleMs=null,this.pendingChars=0,this.lastRepaintMs=0,this.onRepaint?.(null)}};L();async function gde(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(m.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}var dXe=5e3,pXe=3,mXe="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function hde(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,mascotBar:u,healthRail:d,verdictLedger:p,shellPassthrough:f,bgResultNotifier:g}=s,h=null,b=[];e.session.current.waitForInitialization().then(async _=>{ze()&&(h=PR(_)),await ay(e.session.current),ze()&&(b=tN())}).catch(()=>{});let w=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,S,v=!1,x=!1,T;e.clearPendingStopInjection=()=>{T=void 0};let E,C,I,A=(()=>{let _=parseInt(e.options.maxTurns,10);return _>0?_:void 0})(),P=0;for(g.onInjectable=()=>{P>=pXe||!o.isAwaitingInput()||!o.bufferIsEmpty()||(P++,fp(process.stdout),w={text:mXe,attachments:[]},o.abortPendingRead())};;){if(P=0,h&&(e.replRenderer.writeLine(h),e.replRenderer.writeLine(""),h=null),b.length>0){for(let D of b)e.replRenderer.writeLine(D);e.replRenderer.writeLine(""),b=[]}let _=f.drainNotifications();for(let{job:D,result:U}of _){let Q=U.errorReason===void 0?"\u2713":"\u2717",le=U.errorReason==="abort"?"killed":U.errorReason==="timeout"?"timed out":U.errorReason==="signal-killed"?"killed by signal":`exit ${U.exitCode??0}`,Z=Math.max(0,Math.round(U.durationMs/100)/10);e.replRenderer.writeLine(m.dim(` ${Q} [${D.id}] ${le} \xB7 ${Z}s \xB7 `)+D.command)}let M=g.drainNotifications();for(let{job:D}of M){let U=D.status==="completed"?"\u2713":D.status==="failed"?"\u2717":"\u2298",Q=D.endedAt!==void 0?Math.max(0,Math.round((D.endedAt-D.startedAt)/100)/10):0,le=te(D.label,60);e.replRenderer.writeLine(m.dim(` ${U} [${D.jobId}] subagent ${D.status} \xB7 ${Q}s \xB7 `)+le)}let j=l.renderIfChanged(e.stats.sessionId);if(j.length>0){for(let D of j)e.replRenderer.writeLine(D);e.replRenderer.writeLine("")}let O,H;if(w===void 0){let D=await e.session.current.takePendingPlanExitSeed();D!==void 0&&(e.stats.permissionMode=D.mode,w={text:D.message,attachments:[]})}if(w!==void 0){let D=w;w=void 0;let U=Xp(e.stats.permissionMode,D.text),Q=Yl({buffer:D.text,promptText:U,isTTY:!!process.stdout.isTTY,attachmentSummary:Rp([...D.attachments])});e.replRenderer.writeLine(Q),O=D.text.trim(),H=D.attachments}else{let D=S;S=void 0;let U=await o.readLine({promptFn:Q=>Xp(e.stats.permissionMode,Q),...D!==void 0?{initialBuffer:D}:{},primePromptSuggestion:!0,onSigint:r,onShiftTab:()=>{SA(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});O=U.text.trim(),H=U.attachments}if(!O&&H.length===0)continue;if(O.startsWith("!")){let D=/^(0|false|off|no)$/i.test(k.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!D&&(v||(v=!0,e.replRenderer.writeLine(m.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await f.dispatch(O))){e.statusLine.rearm();continue}}let q=!1;if(O.startsWith("/")){let D=await bL(O,e.slashCtx,H);if(D.handled){if(D.result==="exit"){await e.resolveWorktreeDisposition?.(!0),e.rl.close();return}if((O==="/clear"||O.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(m.dim(` transcript: ${t.path()}`)),p.reset(),T=void 0),D.result!==null&&typeof D.result=="object"&&"kind"in D.result&&D.result.kind==="submit"){w={text:D.result.message,attachments:H??[]},e.statusLine.rearm();continue}if(D.result!==null&&typeof D.result=="object"&&"kind"in D.result&&D.result.kind==="prefill"){S=D.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}q=!0}a.push(O),await gde(e,O);let W=O;if(q){let D=zx(O);if(D){let U=D.name.replace(/^\//,"").split(":").pop()??"";if(U&&rR(U)){let Q={skillName:U,rawArgs:D.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},le=e.session.current.sessionId,Z=na(le),De=Date.now();B(`[afk trace] preflight.start commandName=${U}`);let Je=!1,Qo=await ta(Q,{cwd:e.stats.cwd??process.cwd(),artifactDir:Z},Ge=>{ze()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${U}) failed: `)+(Ge instanceof Error?Ge.message:String(Ge)))});Je=Qo!==null,B(`[afk trace] preflight.end commandName=${U} durationMs=${Date.now()-De} success=${Je}`),W=oR(Qo?.manifestBlock,O)}}}let K=f.drainInjections();K.length>0&&(W=K+W);let Y=g.drainInjections();if(Y.length>0&&(W=Y+W),T!==void 0&&(W=T+`
|
|
2353
2353
|
|
|
2354
2354
|
`+W,T=void 0),e.hookRegistry)try{let D={event:"UserPromptSubmit",prompt:W,sessionId:e.stats.sessionId},U=await e.hookRegistry.dispatch(D);U.injectContext&&(W=U.injectContext+W)}catch(D){if(D instanceof _e){e.replRenderer.writeLine(m.warning("\u2298 Turn blocked by hook")+(D.reason?m.dim(`: ${se(D.reason)}`):"")),e.statusLine.rearm();continue}if(D instanceof wo){e.replRenderer.writeLine(m.warning("\u2298 Turn blocked by hook")+m.dim(`: handler timed out after ${D.timeoutMs}ms`)),e.statusLine.rearm();continue}throw D}E=C=I=void 0,P1(),D1();let ie=new CA(D=>{e.statusLine.repaint({...Zn(e.stats,e.contextSampler,e.gitStatusSampler,A),tokPerSec:D??void 0})});if(ie.start(),await fde({text:W,attachments:H},e.session.current,e.stats,{setInFlight(D){n.turnInFlight=D},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(D){await t.appendUser(D)},async onQueuedUserMessage(D){await t.appendQueuedUser(D)},async onTurnComplete(D,U){if(await t.appendTurn(D,U),e.stats.sessionId)try{qs(e.stats)}catch(Q){x||(x=!0,e.replRenderer.writeLine(m.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(Q instanceof Error?Q.message:String(Q))))}},async onAfterTurn(){ie.stop(),await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.repaint(Zn(e.stats,e.contextSampler,e.gitStatusSampler,A)),e.statusLine.rearm(),c?.repaint("observing"),d?.update(e.stats)},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:(D,U)=>{p?.push(D),E=D.kind,C=U?.doneHasCorroboratingEvidence,I=U?.doneEvidenceClassification},setActiveCompositor:D=>{n.activeCompositor=D,D===null&&n.interruptPickerAbort&&(n.interruptPickerAbort.abort(),n.interruptPickerAbort=null)},setInterruptNotifier:D=>{n.notifyInterrupting=D},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:D=>o.setBackgroundHandler(D),setTaskViewHandler:D=>o.setTaskViewHandler(D),setSoftStopHandler:i,setPausedState:D=>o.setPausedState(D),setPauseInterruptHandler:D=>o.setPauseInterruptHandler(D),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(Zn(e.stats,e.contextSampler,e.gitStatusSampler,A)),d?.update(e.stats,e.contextSampler.getRatio())},...c?{onStageChange:(D,U)=>{c.repaint(D),u?.onStage(D,U)}}:{},...e.addPreviewDiffRef?{addPreviewDiffRef:e.addPreviewDiffRef}:{},bashTailSetter:e.bashTailSetter,onTextDelta:D=>ie.update(D)},e.stats.thinkingUi??e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(Xp(e.stats.permissionMode))),e.hookRegistry)try{let D=await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId,...E!==void 0?{terminalState:E}:{},...C!==void 0?{doneHasCorroboratingEvidence:C}:{},...I!==void 0?{doneEvidenceClassification:I}:{}},void 0,dXe);D.injectContext&&D.injectContext.trim().length>0&&(T=D.injectContext)}catch(D){if(D instanceof It)throw D;D instanceof wo?(B("[stop hook] handler timed out"),e.completionWriter.fn(m.dim(" [stop hook] timed out"))):D instanceof _e?e.completionWriter.fn(m.dim(` [stop hook] blocked: ${se(D.reason??"no reason given")}`)):B("[stop hook] unexpected error: "+String(D))}}}function fXe(e,t){if(e!==void 0){let n=e.toLowerCase();return!(n==="0"||n==="false"||n==="off"||n==="no")}return typeof t=="boolean"?t:!0}async function yde(e,t,n,r){let o=await iue(),i=new wA({rl:e.rl,history:o,statusLine:e.statusLine}),s=fXe(k.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await Aue(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar,getMascotBar:()=>a?.mascotBar});a=Kue(e,n);let c=a;e.slashCtx.suspendFooter=()=>{c.bgStatusBar.stop(),c.mascotBar.stop(),c.healthRail.stop(),e.statusLine.stop()},e.slashCtx.resumeFooter=()=>{e.statusLine.start(),c.healthRail.start(),c.mascotBar.start(),c.bgStatusBar.start(),c.bgStatusBar.redraw()},await hde(e,t,n,r,i,l,a,o),await e.resolveWorktreeDisposition?.(!0)}finally{n.tryAbortShellForeground=null,a?.shellPassthrough.drainOnExit(),a?.bgResultNotifier.dispose(),a?.healthRail.stop(),a?.loopStageBar.stop(),a?.mascotBar.stop(),a?.bgStatusBar.stop(),a?.verdictLedger.stop(),a?.contextPane.dispose();let l=c=>console.log(c);e.completionWriter.fn=l,e.completionWriter.idleFn=l,await i.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}Nf();Uu();import{execFile as gXe}from"node:child_process";import{dirname as hXe,isAbsolute as yXe,resolve as bXe}from"node:path";import{promisify as wXe}from"node:util";var bde=wXe(gXe),SXe=3e3,vXe=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function kXe(){let t=(await bde("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=yXe(t)?t:bXe(process.cwd(),t);return hXe(n)}async function wde(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await kXe()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),SXe)});try{let o=pr({execFile:bde,repoRoot:t,dryRun:!1,scope:"interactive",bypassSoftLaunch:!0}),i=await Promise.race([o,r]);if(i==="timeout")return{ran:!1,removedCount:0,skippedReason:"timeout"};let s=i;return s.warnings.some(c=>c.toLowerCase().includes("contested"))?{ran:!1,removedCount:0,skippedReason:"lock-contested"}:{ran:!0,removedCount:s.candidates.filter(c=>vXe.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}Zm();Nf();import{promises as TXe}from"node:fs";import{dirname as xXe,join as kde}from"node:path";import{randomBytes as EXe}from"node:crypto";var RXe=["Generate a 2-4 word kebab-case slug describing this work request.","Rules:","- ASCII lowercase letters and digits only, separated by single hyphens","- 2 to 4 hyphen-separated words","- Maximum 30 characters total","- No prefix, no quotes, no punctuation other than hyphens","- Output ONLY the slug \u2014 no explanation, no preamble","Examples: fix-cleanup-race, add-telegram-allowlist, refactor-prompt-loader, debug-flaky-test"].join(`
|
|
2355
|
-
`),Sde=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,qB=30,AXe=1024,CXe=8e3,_Xe="haiku";async function PXe(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=DXe(n,AXe),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??CXe),s=t.signal?$Xe([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await ri({token:t.token,model:t.model??_Xe,system:RXe,user:r,maxTokens:32,signal:s})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(i)}let l=IXe(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=xXe(t.worktreePath);return await MXe(l,c)}function IXe(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(Sde.test(t)&&t.length<=qB)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(i=>i.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let i=1;i<r.length;i++){let s=`${o}-${r[i]}`;if(s.length>qB)break;o=s}return Sde.test(o)?o:null}async function MXe(e,t){if(!await OXe(kde(t,e)))return e;let n=EXe(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,qB-5)}-${n}`}async function OXe(e){try{return await TXe.access(e),!0}catch{return!1}}function DXe(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function $Xe(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function Tde(e){let t,n,r=kde(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await PXe(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),i=t??"unknown",s=n;if(o!==null){let l=`${xS(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return vde(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){i="create-failed",s=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return vde(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:i,...s!==void 0?{detail:s}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function vde(e,t){e&&e.setCwd(t),LXe(t)}function LXe(e){try{process.chdir(e)}catch{}}mt();xt();zc();qo();N();import{spawn as Ede}from"child_process";import{existsSync as Rde,mkdirSync as UXe,readFileSync as Ade,unlinkSync as xde,writeFileSync as Cde}from"fs";import{get as HXe}from"https";import{join as _de}from"path";import{readFileSync as FXe}from"fs";import{dirname as NXe,join as BXe}from"path";import{fileURLToPath as jXe}from"url";function er(){try{return"5.222.
|
|
2355
|
+
`),Sde=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,qB=30,AXe=1024,CXe=8e3,_Xe="haiku";async function PXe(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=DXe(n,AXe),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??CXe),s=t.signal?$Xe([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await ri({token:t.token,model:t.model??_Xe,system:RXe,user:r,maxTokens:32,signal:s})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(i)}let l=IXe(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=xXe(t.worktreePath);return await MXe(l,c)}function IXe(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(Sde.test(t)&&t.length<=qB)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(i=>i.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let i=1;i<r.length;i++){let s=`${o}-${r[i]}`;if(s.length>qB)break;o=s}return Sde.test(o)?o:null}async function MXe(e,t){if(!await OXe(kde(t,e)))return e;let n=EXe(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,qB-5)}-${n}`}async function OXe(e){try{return await TXe.access(e),!0}catch{return!1}}function DXe(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function $Xe(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function Tde(e){let t,n,r=kde(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await PXe(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),i=t??"unknown",s=n;if(o!==null){let l=`${xS(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return vde(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){i="create-failed",s=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return vde(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:i,...s!==void 0?{detail:s}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function vde(e,t){e&&e.setCwd(t),LXe(t)}function LXe(e){try{process.chdir(e)}catch{}}mt();xt();zc();qo();N();import{spawn as Ede}from"child_process";import{existsSync as Rde,mkdirSync as UXe,readFileSync as Ade,unlinkSync as xde,writeFileSync as Cde}from"fs";import{get as HXe}from"https";import{join as _de}from"path";import{readFileSync as FXe}from"fs";import{dirname as NXe,join as BXe}from"path";import{fileURLToPath as jXe}from"url";function er(){try{return"5.222.4"}catch{}try{let e=NXe(jXe(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(FXe(BXe(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}L();F();var WXe=64*1024,KXe=10800*1e3,GXe=800,qXe=3600*1e3,zXe="update-check.json",JXe="pending-update.json";function zB(){return _de(xa(),zXe)}function Iy(){return _de(xa(),JXe)}function JB(){let e=xa();Rde(e)||UXe(e,{recursive:!0})}function Pde(e,t){let n=a=>a.split(/[-+]/,1)[0]??a,r=a=>a.includes("-"),o=n(e).split(".").map(Number),i=n(t).split(".").map(Number),s=Math.max(o.length,i.length);for(let a=0;a<s;a++){let l=o[a]??0,c=i[a]??0;if(c>l)return!0;if(c<l)return!1}return r(e)&&!r(t)}function Ide(){try{let e=Ade(zB(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function Mde(){try{JB();let e=`
|
|
2356
2356
|
const https = require('https');
|
|
2357
2357
|
const fs = require('fs');
|
|
2358
2358
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|