agent-afk 5.100.3 → 5.100.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 +15 -15
- package/dist/index.mjs +1 -1
- package/dist/telegram.mjs +1 -1
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
var N8=Object.defineProperty;var k=(e,t)=>()=>(e&&(t=e(e=0)),t);var Uc=(e,t)=>{for(var n in t)N8(e,n,{get:t[n],enumerable:!0})};function nt(){let e=T.AFK_PLAIN_OUTPUT;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"}function ia(e){return jc.find(t=>t.name===e)}function W_(e){return jc.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function Hc(e){return process.env[e]!==void 0}function KS(e){let t=process.env[e];return t===void 0||t===""?void 0:t}var jc,T,W=k(()=>{"use strict";jc=[{name:"AFK_COMPACT_KEEP_LAST_TURNS",description:"Number of recent turns the compactor keeps verbatim during /compact. Default tuned in compact-handler.ts.",type:"number",required:!1,example:"6",category:"model"},{name:"AFK_COMPACT_MODEL",description:"Override the model used by the /compact summarizer. Falls back to a cheap default (haiku-class).",type:"string",required:!1,example:"claude-haiku-4-5",category:"model"},{name:"AFK_COMPACT_SHRINK_FRACTION",description:"Context-fullness fraction (0\u20131, exclusive) at/above which /compact and auto-compaction relax the keep-window so a short-but-full session (few turns, huge tool exchanges) can still be summarized instead of no-oping on turn count. Default 0.7 (see shared/compaction.ts DEFAULT_COMPACT_SHRINK_THRESHOLD).",type:"number",required:!1,example:"0.8",category:"model"},{name:"AFK_DEFAULT_SUBAGENT_MODEL",description:"Override the default model used when a subagent is dispatched without an explicit model.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_DIAGNOSE_BASELINE",description:"Kill switch for /diagnose reproducer baseline execution. When set to '0', the /diagnose skill skips executing the detected reproducer command for a ground-truth baseline; default enabled (runs). Set to '0' to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_DISABLE_PROMPT_CACHE",description:"Disable Anthropic prompt caching when set to 1/true/yes/on. Unset = caching enabled.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_DISABLE_BASH_INTERPRETER_GUARD",description:"Skip ONLY the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) when set to 1, leaving the rest of path-approval intact. Applies on interactive surfaces (REPL/Telegram), where the denylist is active but your workflow legitimately runs interpreter one-liners. The restricted-root substring check is unaffected. Default: denylist active on interactive surfaces; headless already fails open (opt in with AFK_FORCE_BASH_INTERPRETER_GUARD=1). To disable all of path-approval + bash restriction instead, use AFK_DISABLE_PATH_APPROVAL=1.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_DISABLE_PATH_APPROVAL",description:"Skip the path-approval + bash-restriction hooks entirely when set to 1. Use for headless flows that need wide-open file access (CI scripts, batch jobs). Default: hooks enabled. Note: on headless surfaces (afk chat, daemon) no grant manager is wired, so the interpreter denylist (python -c, node -e, sh -c, ...) fails OPEN by default \u2014 opt headless flows into it with AFK_FORCE_BASH_INTERPRETER_GUARD=1, or set this var to 1 to disable all of path-approval.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_FORCE_BASH_INTERPRETER_GUARD",description:"Apply the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) even on headless surfaces (afk chat, daemon) where no grant manager is wired. By default the denylist fires only on interactive surfaces (REPL/Telegram), failing open on headless so legitimate automation is not hard-blocked with no recourse. Set to 1 to opt headless flows back into the guard. Overridden by AFK_DISABLE_BASH_INTERPRETER_GUARD=1. Default: off (headless fails open).",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_EFFORT",description:"Effort hint guiding adaptive-thinking depth, forwarded as Anthropic output_config.effort (model-gated; ignored where unsupported). Accepts low | medium | high | xhigh | max.",type:"string",required:!1,example:"medium",category:"model"},{name:"AFK_MAX_BUDGET_USD",description:"Cumulative USD budget ceiling for the session. Aborts the turn when the running cost crosses this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS",description:"Maximum concurrency-safe tool calls run simultaneously within one dispatcher batch. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"4",category:"model"},{name:"AFK_MAX_CONCURRENT_SUBAGENT_CALLS",description:"Maximum subagent calls run simultaneously from one compose/DAG layer or skill wave. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"2",category:"model"},{name:"AFK_MAX_CONCURRENT_BACKGROUND_JOBS",description:"Maximum background subagent jobs running simultaneously in one registry. Default 10; accepted range 1-64; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"10",example:"5",category:"model"},{name:"AFK_MAX_NESTING_DEPTH",description:"Maximum sub-agent/skill nesting depth; 0 disables nested delegation entirely (the agent, skill, AND compose tools all refuse). A top-level session is depth 0, so the default 3 permits three generations of forked descendants (depth 1 \u2192 2 \u2192 3) and refuses the agent and skill tools at depth 3. Resolved once at the root of each session and propagated down through child AgentConfig, so descendants inherit the root value rather than re-reading the environment. Raise with care: depth is a fan-out exponent (a width-N wave at depth D reaches ~N^D concurrent children), so values above 4 invite provider rate-limit (429) cascades. Accepted range 0-6; unset, empty, unparseable, negative, or out-of-range input falls back to the default. An explicit programmatic maxDepth (SubagentExecutorContext / SkillExecutorContext) still wins.",type:"number",required:!1,default:"3",example:"2",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. Falls back to provider default when unset.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Deprecated and inert: not read by the generation path. Use AFK_MAX_OUTPUT_TOKENS (or --max-output-tokens) to cap per-response output tokens; falls back to the model output ceiling when unset.",type:"number",required:!1,default:"4096",example:"8192",category:"model"},{name:"AFK_MAX_TOOL_USE_ITERATIONS",description:"Opt-in ceiling on tool-use rounds per turn for TOP-LEVEL (non-subagent) sessions, on both providers. Mirrors the maxToolUseIterations config key / max_tool_use_iterations tool param. Unset, non-numeric, or <=0 means unlimited (the default \u2014 zero behavior change): a top-level turn ends only when the model stops calling tools, the abort signal fires, the provider errors, or the dollar budget trips. A positive integer N makes top-level turns wind down gracefully after N tool rounds (one tools-stripped final round). An explicit config/CLI value wins over this env default. Does NOT affect subagent forks \u2014 they keep their own non-zero anti-hang default (SUBAGENT_DEFAULT_MAX_TOOL_USE_ITERATIONS) regardless of this var.",type:"number",required:!1,default:"0",example:"150",category:"model"},{name:"AFK_MEMORY_EVIDENCE_GATE",description:'Opt-in (set to 1) evidence gate for durable memory writes. When enabled, a codebase fact (memory_update category "convention") stored without an `evidence` citation is recalled as [unverified], and memory_search results carry a verification verdict. User preferences and agent reflections are never gated. Default off \u2014 memory behaves identically to legacy when unset.',type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_MICROCOMPACT_KEEP_LAST",description:"Number of the most-recent tool_result blocks that tool-result microcompaction keeps intact regardless of size, so the agent does not lose the tool output it is actively reasoning over. Older results are the safe ones to trim. Default 4 (see shared/compaction.ts DEFAULT_MICROCOMPACT_KEEP_LAST). Values <= 0 protect nothing.",type:"number",required:!1,default:"4",example:"3",category:"model"},{name:"AFK_MICROCOMPACT_TOOL_RESULT_BYTES",description:"Byte threshold (tool_result content length) at/above which a tool_result block becomes a microcompaction candidate. When /compact and auto-compaction would otherwise no-op on a short-but-full session, microcompaction clears large/old tool_result CONTENT in place (largest first) \u2014 replacing it with a short placeholder, never removing the block \u2014 to reclaim context deterministically (no LLM call). Blocks below this size are left intact. Default 2048 (see shared/compaction.ts DEFAULT_MICROCOMPACT_TOOL_RESULT_BYTES).",type:"number",required:!1,default:"2048",example:"4096",category:"model"},{name:"AFK_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), fixed-identity aliases (opus, sonnet, haiku, fable), or full model IDs. Migration: AFK_MODEL=sonnet now pins the fixed Sonnet identity rather than following a rebound medium tier.",type:"string",required:!1,default:"medium",example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_TTFB_TIMEOUT_MS",description:"Per-ROUND time-to-first-token budget (ms) for the anthropic-direct streaming loop. Bounds how long a round may stall BEFORE its first streamed CONTENT token (a text/thinking delta or tool_use); the connection-level message_start and keep-alive pings do NOT count. Once a content token streams, the timer is cleared and the rest of the response is governed instead by the progress-aware AFK_MODEL_STALL_TIMEOUT_MS window, so a normal slow call (below the bound) and any actively-streaming extended-thinking response are never aborted. The budget is divided into 3 shorter first-byte ATTEMPTS (each ~2/3 of this value, so the worst-case wall time per round is unchanged from the previous 2-attempt regime while a transient stall gets 3 chances instead of 2). NOTE: a request whose FIRST token takes longer than the per-attempt bound \u2014 e.g. a very large opus_1m prefill \u2014 is aborted and re-driven, then surfaces as an error once the budget is spent (raise this value or set 0 for such workloads); this trims the degrading-call tail instead of a silent ~10-min hang on the SDK default. Default 180000 (180s \u2248 2\xD7 the measured p99 ttfb), i.e. 3 \xD7 120s. Set to 0 to disable.",type:"number",required:!1,default:"180000",example:"120000",category:"model"},{name:"AFK_MODEL_STALL_TIMEOUT_MS",description:"Progress-aware POST-first-byte stall window (ms) for the anthropic-direct streaming loop. Bounds how long a stream that has ALREADY produced content may then go completely silent. Every streamed output event resets the window, so this is NOT a total-round cap: a legitimately long, actively-streaming round (large code emission, extended thinking) survives indefinitely, while a stream wedged mid-flight is aborted and surfaces as a real terminal error instead of hanging. Complements AFK_MODEL_TTFB_TIMEOUT_MS, which governs only the window BEFORE the first token; this one takes over after it. Default 1200000 (20min) \u2014 above the 18.5min maximum post-first-byte stream duration observed across 86,076 rounds in 12,381 local traces (p99 122s, p99.9 234s), so no healthy round trips it. Set to 0 to disable (issue #762).",type:"number",required:!1,default:"1200000",example:"600000",category:"model"},{name:"AFK_SUBAGENT_TIMEOUT_MS",description:"Foreground forked-subagent wall-clock budget in ms; 0 disables the cap; explicit per-fork config.timeoutMs and the 60-min background mode still win. Bounds how long a single forked child turn may run before `withTimeout` aborts its controller (cascading through the AbortGraph to descendants) and the parent receives a legible TimeoutError tool_result instead of hanging. Default 2700000 (45 min \u2248 headroom over the longest healthy review/research agent observed in production). Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to opt a whole session back into unbounded child turns. Does NOT affect the background dispatch budget (SUBAGENT_BACKGROUND_TIMEOUT_MS) or a per-fork config.timeoutMs \u2014 both take precedence.",type:"number",required:!1,default:"2700000",example:"3600000",category:"model"},{name:"AFK_SUBAGENT_IDLE_TIMEOUT_MS",description:"Forked-subagent progress-aware idle-watchdog window in ms; 0 disables the watchdog; an explicit per-fork config.idleTimeoutMs still wins. Fires when a forked child produces no observable output event for this window, aborting the same controller the wall-clock timeout targets so partial output is preserved and the run classifies as a failure. This is distinct from AFK_SUBAGENT_TIMEOUT_MS, the blunt wall-clock that bounds total turn time: the idle watchdog is the tighter first-to-fire bound and never fires while the stream is legitimately parked on a provider-communicated backoff (OAuth pause, or a rate-limit event carrying a retry-after), extending the deadline for the pause window instead. Default 480000 (8 min) clears the worst-case transient-429 backoff the watchdog is currently blind to (about 363s) with roughly 2 min of margin, while staying materially tighter than the 45-min wall-clock. Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to disable the idle watchdog for a whole session (the wall-clock still applies). v1 applies to forked sub-agent turns only, not top-level or daemon sessions.",type:"number",required:!1,default:"480000",example:"300000",category:"model"},{name:"AFK_VISION_MODELS",description:'Comma-separated override for image (vision) capability detection on the openai-compatible provider. Each token force-enables a model id by exact or substring match (e.g. "qwen2.5-vl" matches a local VL id); prefix a token with "!" to force-disable. Use to send images to a local vision-language model AFK does not recognise by name, or to blacklist a mis-detected id. Built-in detection already covers gpt-4o/4.1/5.x, o1/o3/o4-mini, Claude, and common VL families.',type:"string",required:!1,example:"qwen2.5-vl,!gpt-4o-mini",category:"model"},{name:"AFK_MODEL_LOCAL",description:'Bind the "local" capability tier (cheapest/fastest, user-configured) to a model id. Overrides afk.config.json models.local. Point at a local Ollama, LM Studio, or any OpenAI-compatible shim.',type:"string",required:!1,example:"llama3.2:3b",category:"model"},{name:"AFK_MODEL_LOCAL_API_KEY",description:'Per-slot API key for the "local" tier. Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LOCAL_BASE_URL",description:'Per-slot endpoint base URL for the "local" tier. Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:11434/v1",category:"model"},{name:"AFK_MODEL_LARGE",description:'Bind the "large" capability tier (most capable) to a model id/alias. Overrides afk.config.json models.large.',type:"string",required:!1,example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-5",category:"model"},{name:"AFK_MODEL_MEDIUM_API_KEY",description:'Per-slot API key for the "medium" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_MEDIUM_BASE_URL",description:'Per-slot endpoint base URL for the "medium" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_SMALL",description:'Bind the "small" capability tier (cheap/fast) to a model id/alias. Overrides afk.config.json models.small.',type:"string",required:!1,example:"gpt-4o-mini",category:"model"},{name:"AFK_MODEL_SMALL_API_KEY",description:'Per-slot API key for the "small" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_SMALL_BASE_URL",description:'Per-slot endpoint base URL for the "small" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_OVERLOAD_PAUSE_MS",description:"Wall-clock ceiling (ms) for the bounded pause after a mid-stream overload (529) exhausts its retry budget. Overrides the per-surface default for ALL surfaces: 0 disables the pause (fail fast). Interactive surfaces (cli/repl/telegram) default to 600000; daemon/cron default to 0 so an always-on runner never silently parks on upstream capacity.",type:"number",required:!1,example:"600000",category:"model"},{name:"AFK_PROMPT_CACHE_TTL",description:"TTL for Anthropic prompt-cache blocks. Accepts 5m or 1h.",type:"string",required:!1,default:"1h",example:"1h",category:"model"},{name:"AFK_SUGGEST_ENABLED",description:"Enable the LLM-backed ghost-text suggestion tier in the interactive REPL. Set to 1/true/yes/on to activate. Off by default.",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_PROMPT",description:"Enable LLM-generated empty-prompt suggestions \u2014 a proposed next action shown as ghost text when the prompt is blank, accepted with Tab or Right-arrow. Fires only after a turn has completed in the session: the startup prompt (and the prompt right after /clear) is left clean because there is no session context to ground a proposal in. Set to 1/true/yes/on to activate. Off by default. Requires AFK_SUGGEST_ENABLED (it reuses the same suggestion model and provider).",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_GHOST",description:"Enable REPL ghost-text inline suggestions (Tier-1 history/dropdown + optional Tier-2 LLM). 1 = on (default), 0 = off. Set 0/false/off/no to disable all ghost text. Tier-2 LLM is separately gated by AFK_SUGGEST_ENABLED.",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_MODEL",description:"Override the small model used for REPL ghost-text suggestions. Falls back to AFK_COMPACT_MODEL or haiku-class for anthropic, or the session model for other providers.",type:"string",required:!1,category:"model"},{name:"AFK_TASK_BUDGET",description:"Per-task token budget ceiling. Aborts when cumulative usage would exceed it.",type:"number",required:!1,default:"100000",example:"200000",category:"model"},{name:"AFK_TEMPERATURE",description:"Numeric temperature override for model sampling. Provider default if unset.",type:"number",required:!1,example:"0.7",category:"model"},{name:"AFK_THINKING",description:"Extended-thinking mode. Accepts adaptive | disabled | enabled:<N> | enabled:max. Defaults to the model-appropriate mode when unset (adaptive on current models).",type:"string",required:!1,default:"adaptive",example:"adaptive",category:"model"},{name:"AFK_THINKING_UI",description:"Default thinking-display mode for the interactive REPL: summary | live | digest | off. Display-only \u2014 controls how extended-thinking blocks render, never whether thinking runs (cost/latency unaffected). Overridden per-launch by --thinking-ui and mutable mid-session via /thinking. Precedence: --thinking-ui flag > this env > interactive.thinkingUi config > live. Invalid values are ignored.",type:"string",required:!1,default:"live",example:"digest",category:"misc"},{name:"AFK_TIMEOUT_MS",description:"Per-turn timeout in milliseconds. Provider/SDK default if unset.",type:"number",required:!1,example:"120000",category:"model"},{name:"CLAUDE_MODEL",description:"Legacy alias for AFK_MODEL \u2014 supported for back-compat with pre-AFK_* deployments.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_SYSTEM_PROMPT",description:'Raw operator-overlay prompt. Highest-priority overlay (over afk.config.json and AFK.md). Appended on top of the framework base (prompts/system-prompt.md) under an "# Operator configuration" header \u2014 it augments, never replaces, the base.',type:"string",required:!1,example:"You are a helpful agent.",category:"model"},{name:"AFK_DUMP_PROMPT",description:"Write the resolved system prompt to a file at startup. Accepts a path or 1 for default location.",type:"string",required:!1,example:"/tmp/afk-prompt.txt",category:"debug"},{name:"ANTHROPIC_API_KEY",description:"Anthropic API key. Tier-1 credential \u2014 overrides keychain OAuth and CLAUDE_CODE_OAUTH_TOKEN.",type:"string",required:!1,category:"auth",secret:!0},{name:"CLAUDE_CODE_OAUTH_TOKEN",description:"Claude Code OAuth token. Tier-2 credential \u2014 used when ANTHROPIC_API_KEY is unset; falls back to keychain.",type:"string",required:!1,category:"auth",secret:!0},{name:"OPENAI_API_KEY",description:"OpenAI API key for the openai-compatible provider (gpt-*, o1*, o3*, o4* models).",type:"string",required:!1,category:"auth",secret:!0},{name:"CODEX_API_KEY",description:"Fallback OpenAI API key for the openai-compatible provider, read after OPENAI_API_KEY. Legacy name from the removed @openai/codex-sdk integration \u2014 prefer OPENAI_API_KEY.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_LOCAL_API_KEY",description:"Placeholder API key for local Anthropic-compatible servers (vllm-mlx, etc.). Set when AFK_LOCAL_BASE_URL is configured.",type:"string",required:!1,default:"local",example:"local",category:"auth",secret:!0},{name:"AFK_LOCAL_BASE_URL",description:"Base URL for a self-hosted Anthropic-compatible server. When set, routes traffic away from api.anthropic.com.",type:"string",required:!1,example:"http://127.0.0.1:8080",category:"model"},{name:"AFK_OPENAI_BASE_URL",description:"Base URL override for the OpenAI-compatible provider. Used for local shims (mlx_lm.server, Ollama, vLLM, LM Studio). The OpenAI SDK appends `/chat/completions` itself \u2014 a value ending in `/chat/completions` will be stripped at config-load time with a one-shot warning.",type:"string",required:!1,example:"http://127.0.0.1:8000/v1",category:"model"},{name:"AFK_OPENAI_USE_RESPONSES",description:"Opt the OpenAI-compatible provider into the OpenAI Responses API instead of Chat Completions for API-key sessions. Truthy values: 1, true, yes, on. The ChatGPT-subscription OAuth path uses Responses automatically regardless of this flag.",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_OPENAI_CHATGPT_OAUTH",description:"Opt into using ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. Off by default. READ-ONLY: AFK never refreshes these tokens \u2014 re-run `codex` when the access token expires. Routes requests over the Responses API to the private ChatGPT backend (chatgpt.com/backend-api).",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_PROVIDER",description:"Force provider selection (anthropic | anthropic-direct | openai | openai-compatible | openai-codex). Overrides the model-name heuristic. Same surface as the --provider CLI flag; CLI flag wins when both are set.",type:"string",required:!1,example:"openai-compatible",category:"model"},{name:"EXA_API_KEY",description:"Exa (exa.ai) search API key, enabling web_scrape search mode. Free tier (20k requests/month) available at https://exa.ai. When unset, search mode returns an actionable error; markdown and raw modes are unaffected.",type:"string",required:!1,category:"auth",secret:!0},{name:"TELEGRAM_BOT_TOKEN",description:"Telegram bot token from @BotFather. Required to run the Telegram bot surface.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_BOT_TOKEN",description:"Alternative env var name for the Telegram bot token, accepted by the setup wizard.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_ALLOWED_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs allowed to interact with the bot. Required when the bot is running.",type:"string",required:!1,example:"123456789,987654321",category:"telegram"},{name:"AFK_TELEGRAM_TAG_ONLY_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs where the bot answers only when addressed (a reply to the bot, an @mention of the bot, or a text_mention resolving to the bot). Slash-commands are unaffected; chats not listed behave as usual. The afk.config.json telegram.tagOnlyChats block takes precedence. Requires Telegram privacy mode OFF (BotFather /setprivacy Disable) for non-addressed group messages to reach the bot.",type:"string",required:!1,example:"-100987654321,123456789",category:"telegram"},{name:"AFK_TELEGRAM_PRIMARY_CHAT_ID",description:"Default chat ID for outbound notifications (primary-mode routing). When unset, notifications go to the first private/DM chat in AFK_TELEGRAM_ALLOWED_CHAT_IDS. The afk.config.json telegram.notify block takes precedence.",type:"string",required:!1,example:"123456789",category:"telegram"},{name:"AFK_TELEGRAM_NOTIFY_MODE",description:"Outbound notification fan-out: primary (default \u2014 one chat), broadcast (every allowed chat), or custom (afk.config.json telegram.notify.targets). The afk.config.json telegram.notify.mode takes precedence.",type:"string",required:!1,example:"broadcast",category:"telegram"},{name:"TELEGRAM_DATA_DIR",description:"Override the directory where Telegram bot state is stored. Defaults to ~/.afk/state/telegram/.",type:"string",required:!1,category:"telegram"},{name:"TELEGRAM_VERBOSE",description:"Set to 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:"AFK_TELEGRAM_TRACE",description:"Set to 1 to dump raw bridge traffic between the agent and the Telegram bot \u2014 debugging only.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_TELEGRAM_CWD",description:"Override the working directory used by the Telegram bot when spawning agent sessions.",type:"string",required:!1,category:"telegram"},{name:"AFK_HOME",description:"Override the AFK home directory. Default: ~/.afk/.",type:"string",required:!1,default:"~/.afk",example:"/opt/afk",category:"paths"},{name:"AFK_STATE_DIR",description:"Override the entire AFK state tier (sessions/, todos/, transcripts/, memory/, daemon/, etc.), not just one subdirectory. Must be an absolute path (not /). Default: $AFK_HOME/state/.",type:"string",required:!1,category:"paths"},{name:"AFK_FRAMEWORK_DIR",description:"Override the AFK agent-framework directory used for telemetry and briefs. Default: $AFK_HOME/agent-framework/.",type:"string",required:!1,category:"paths"},{name:"AFK_COMPANION_PRIMER",description:'Opt-in: absolute path to a single companion-primer file. When set, its content is bounded (capped, fenced as <companion-primer>) and appended to the system prompt at session start for top-level sessions (chat/REPL/telegram/daemon), as lower-authority "reflections, not facts" context. Unset (default) = no-op. Only the one named file is ever read \u2014 never a directory or repo walk.',type:"string",required:!1,example:"/Users/me/Projects/afk-companion/PRIMER.md",category:"paths"},{name:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_ON_EXIT",description:"Clean-worktree quit policy for interactive --worktree sessions: ask, keep, or remove.",type:"string",required:!1,example:"ask",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Opt-in to loading + spawning MCP servers declared in <cwd>/.mcp.json. Fail-closed: when unset (or 0), project-local servers are NOT spawned; set to a truthy value (1/true/yes/on) to load them. A project-local .mcp.json spawns arbitrary commands on session start, so it is off by default to prevent code execution when entering an untrusted repo (issue #571). Skipped servers are listed in a startup warning with the opt-in instruction.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BG_AUTO_DELIVER",description:"Auto-deliver background subagent results into the model context on the next user turn (interactive REPL). On by default. Set to 0, false, off, or no (case-insensitive) to disable, restoring the manual /bgsub:join retrieval flow.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_PLAIN_OUTPUT",description:"Force the interactive REPL to fully behave like a non-TTY surface for rendering purposes, even when stdout/stdin ARE a TTY: append-only plain-stdout output instead of the TerminalCompositor live overlay (both the persistent between-turn compositor AND the per-turn StreamRenderer overlay), AND the input surface downgrades to the simple non-TTY line reader instead of the fancy compositor-backed input box. Same code path already used for non-TTY surfaces (pipes, CI). Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM scroll regions misbehave \u2014 trades the live overlay and fancy input UX for reliability. Opt-in \u2014 default TTY behavior (live overlay + fancy input) is unchanged unless this var is set. Truthy values: 1, true (case-insensitive).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_GOBLIN_SPINNER",description:"Goblin-themed working spinner (olive frames + goblin verbs) while the agent runs tools. 1 = on (default), 0 = classic dim spinner.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_GOBLIN_MASCOT",description:"Reacting goblin mini-sprite in the reserved footer band while the agent runs tools (3 rows, animated). 1 = on, unset/0 = off (default). Claims terminal rows, so it is opt-in.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_TERM_TITLE",description:'Set the terminal/tab title (OSC 2) to reflect afk state \u2014 "afk \u2014 <cwd> \xB7 running" during a turn, "afk \u2014 <cwd>" when idle, cleared on exit. 1 = on (default when stdout is a TTY), 0 = leave the title alone. TTY-only.',type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_NOTIFY",description:"Emit a desktop completion notification (OSC 9) on turn completion, for terminals that map OSC 9 to system notifications (iTerm2, kitty, WezTerm). Opt-in and off by default (intrusive). 1 = on. TTY-only.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_THEME",description:"TUI color palette for the interactive REPL and all CLI rendering: dark | light | umber | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark; umber matches the Umber terminal, is dark-only, and is never chosen by auto. Overridden per-launch by --theme and mutable mid-session via /theme. Precedence: --theme flag > this env > config theme > auto-detect > dark. Invalid values are ignored (dark).",type:"string",required:!1,default:"dark",example:"light",category:"misc"},{name:"AFK_TEXT_MEASURE",description:"Maximum line length (columns) for unbordered streamed text in the interactive REPL: assistant prose, thinking blocks, tool-lane text, and subagent text. Display-only \u2014 affects wrapping, never behavior. Bordered elements (cards, error boxes) already cap at 100; this applies the same ceiling to the unbordered surfaces, which previously scaled to the full terminal width. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable capping and restore full-width wrapping. Unparseable or below-minimum values fall back to the default. No-op on terminals at or below the measure, so narrow terminals are unaffected.",type:"string",required:!1,default:"100",example:"full",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_CAPTURE_SUBAGENT_PROMPTS",description:"Opt-in: when set to 1, every prompt a parent session sends to a subagent is written as a redacted markdown file under state/witness/<label>/prompts/. Off by default because nothing prunes the witness tree and prompts may carry secrets the regex redactor cannot catch (connection strings, PEM blocks, PII).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_CAPTURE_SUBAGENT_OUTPUT",description:"Opt-in: when set to 1, a subagent's conversational OUTPUT (assistant text plus each tool call with its arguments) is appended incrementally to a redacted markdown transcript under state/witness/<label>/outputs/. Flushed at every tool-call boundary, so a child killed by a timeout still leaves a usable partial record \u2014 the case where final-message capture yields nothing. Off by default for the same reasons as AFK_CAPTURE_SUBAGENT_PROMPTS (unpruned witness tree, best-effort regex redaction).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless on every AFK surface \u2014 the CLI entrypoint reports surface `afk`, which is in the headless set \u2014 so watching the agent work in a visible window is opt-in via `AFK_BROWSER_HEADLESS=0`, not implied by running the REPL. Note headed and headless use different chromium downloads (`chromium-*` vs `chromium_headless_shell-*`).",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_ALLOWED_DOMAINS",description:"Comma-separated allowlist of URL host globs. When set, browser_open and any navigation that targets a host outside the list returns status: blocked_by_policy. Unset means no allowlist (permissive). Patterns use simple `*` glob matching against the URL host. Combines with AFK_BROWSER_BLOCKED_DOMAINS \u2014 block wins.",type:"string",required:!1,example:"github.com,*.atlassian.net",category:"browser"},{name:"AFK_BROWSER_BLOCKED_DOMAINS",description:"Comma-separated blocklist of URL host globs. Browser navigation that matches any entry returns status: blocked_by_policy regardless of the allowlist.",type:"string",required:!1,example:"*.ads.example.com",category:"browser"},{name:"AFK_BROWSER_DOM_SNAPSHOTS",description:"Phase 2 opt-in: when set to 1, every browser_act writes a gzipped DOM snapshot sidecar under ~/.afk/state/witness/<sid>/browser/dom-snapshots/. Off by default because snapshots are large; useful for post-mortem analysis of failed actions.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_BACKEND",description:"Select the browser provider backend. Phase 1 supports only `playwright`. Reserved for future `cdp` / `mcp` adapters. Unset defaults to `playwright`.",type:"string",required:!1,example:"playwright",category:"browser"},{name:"AFK_BROWSER_CONFIG",description:"Absolute path to an alternate browser config file. Overrides the default ~/.afk/config/browser.json lookup. Useful for per-project overrides in CI.",type:"string",required:!1,example:"/path/to/browser.json",category:"browser"},{name:"AFK_BROWSER_DEFAULT_PROFILE",description:"Name of the persistent session-vault profile the agent reuses for browser sessions. The context restores its login from (and saves it back to) ~/.afk/state/browser/<profile>/storageState.json, so a human runs `afk browser login --profile <name>` once and the agent reuses that authenticated session across unattended runs. Unset defaults to `default` (a fresh, empty profile \u2014 identical to pre-vault behavior). Allowed charset: [A-Za-z0-9_-], max 128 chars.",type:"string",required:!1,example:"work",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_READ_DENYLIST",description:"Colon-separated list of additional absolute paths the read_file/grep/glob/list_directory tools refuse to read, and that the bash-restriction hook refuses to let a shell command reference on interactive surfaces (REPL, Telegram) \u2014 on headless surfaces (afk chat, daemon) bash fails open regardless of this list. A leading ~/ is expanded (~user/ is not \u2014 spell those absolutely). Built-in credential entries (~/.ssh, ~/.aws, ~/.afk/config, \u2026) always apply on top and cannot be removed. One built-in exception exists: ~/.afk/config/mcp.json (the MCP registry) IS readable \u2014 paths listed here outrank that carve-out, so set this to ~/.afk/config/mcp.json if your registry holds inline secrets rather than ${VAR} placeholders.",type:"string",required:!1,example:"/Users/me/project/.env:/Users/me/secrets",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_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"}],T={get AFK_COMPACT_KEEP_LAST_TURNS(){return process.env.AFK_COMPACT_KEEP_LAST_TURNS},get AFK_COMPACT_MODEL(){return process.env.AFK_COMPACT_MODEL},get AFK_COMPACT_SHRINK_FRACTION(){return process.env.AFK_COMPACT_SHRINK_FRACTION},get AFK_COMPANION_PRIMER(){return process.env.AFK_COMPANION_PRIMER},get AFK_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_CONCURRENT_BACKGROUND_JOBS(){return process.env.AFK_MAX_CONCURRENT_BACKGROUND_JOBS},get AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS(){return process.env.AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS},get AFK_MAX_CONCURRENT_SUBAGENT_CALLS(){return process.env.AFK_MAX_CONCURRENT_SUBAGENT_CALLS},get AFK_MAX_NESTING_DEPTH(){return process.env.AFK_MAX_NESTING_DEPTH},get AFK_MAX_OUTPUT_TOKENS(){return process.env.AFK_MAX_OUTPUT_TOKENS},get AFK_MAX_TOKENS(){return process.env.AFK_MAX_TOKENS},get AFK_MAX_TOOL_USE_ITERATIONS(){return process.env.AFK_MAX_TOOL_USE_ITERATIONS},get AFK_MEMORY_EVIDENCE_GATE(){return process.env.AFK_MEMORY_EVIDENCE_GATE},get AFK_MICROCOMPACT_KEEP_LAST(){return process.env.AFK_MICROCOMPACT_KEEP_LAST},get AFK_MICROCOMPACT_TOOL_RESULT_BYTES(){return process.env.AFK_MICROCOMPACT_TOOL_RESULT_BYTES},get AFK_MODEL(){return process.env.AFK_MODEL},get AFK_MODEL_TTFB_TIMEOUT_MS(){return process.env.AFK_MODEL_TTFB_TIMEOUT_MS},get AFK_MODEL_STALL_TIMEOUT_MS(){return process.env.AFK_MODEL_STALL_TIMEOUT_MS},get AFK_MODEL_LARGE(){return process.env.AFK_MODEL_LARGE},get AFK_MODEL_LARGE_API_KEY(){return process.env.AFK_MODEL_LARGE_API_KEY},get AFK_MODEL_LARGE_BASE_URL(){return process.env.AFK_MODEL_LARGE_BASE_URL},get AFK_MODEL_LOCAL(){return process.env.AFK_MODEL_LOCAL},get AFK_MODEL_LOCAL_API_KEY(){return process.env.AFK_MODEL_LOCAL_API_KEY},get AFK_MODEL_LOCAL_BASE_URL(){return process.env.AFK_MODEL_LOCAL_BASE_URL},get AFK_MODEL_MEDIUM(){return process.env.AFK_MODEL_MEDIUM},get AFK_MODEL_MEDIUM_API_KEY(){return process.env.AFK_MODEL_MEDIUM_API_KEY},get AFK_MODEL_MEDIUM_BASE_URL(){return process.env.AFK_MODEL_MEDIUM_BASE_URL},get AFK_MODEL_SMALL(){return process.env.AFK_MODEL_SMALL},get AFK_MODEL_SMALL_API_KEY(){return process.env.AFK_MODEL_SMALL_API_KEY},get AFK_MODEL_SMALL_BASE_URL(){return process.env.AFK_MODEL_SMALL_BASE_URL},get AFK_VISION_MODELS(){return process.env.AFK_VISION_MODELS},get AFK_OVERLOAD_PAUSE_MS(){return process.env.AFK_OVERLOAD_PAUSE_MS},get AFK_PROMPT_CACHE_TTL(){return process.env.AFK_PROMPT_CACHE_TTL},get AFK_SUGGEST_ENABLED(){return process.env.AFK_SUGGEST_ENABLED},get AFK_SUGGEST_PROMPT(){return process.env.AFK_SUGGEST_PROMPT},get AFK_SUGGEST_GHOST(){return process.env.AFK_SUGGEST_GHOST},get AFK_SUGGEST_MODEL(){return process.env.AFK_SUGGEST_MODEL},get AFK_SUBAGENT_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_TIMEOUT_MS},get AFK_SUBAGENT_IDLE_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_IDLE_TIMEOUT_MS},get AFK_TASK_BUDGET(){return process.env.AFK_TASK_BUDGET},get AFK_TEMPERATURE(){return process.env.AFK_TEMPERATURE},get AFK_THINKING(){return process.env.AFK_THINKING},get AFK_THINKING_UI(){return process.env.AFK_THINKING_UI},get AFK_TIMEOUT_MS(){return process.env.AFK_TIMEOUT_MS},get CLAUDE_MODEL(){return process.env.CLAUDE_MODEL},get AFK_SYSTEM_PROMPT(){return process.env.AFK_SYSTEM_PROMPT},get AFK_DUMP_PROMPT(){return process.env.AFK_DUMP_PROMPT},get ANTHROPIC_API_KEY(){return process.env.ANTHROPIC_API_KEY},get CLAUDE_CODE_OAUTH_TOKEN(){return process.env.CLAUDE_CODE_OAUTH_TOKEN},get OPENAI_API_KEY(){return process.env.OPENAI_API_KEY},get CODEX_API_KEY(){return process.env.CODEX_API_KEY},get AFK_LOCAL_API_KEY(){return process.env.AFK_LOCAL_API_KEY},get AFK_LOCAL_BASE_URL(){return process.env.AFK_LOCAL_BASE_URL},get AFK_OPENAI_BASE_URL(){return process.env.AFK_OPENAI_BASE_URL},get AFK_OPENAI_USE_RESPONSES(){return process.env.AFK_OPENAI_USE_RESPONSES},get AFK_OPENAI_CHATGPT_OAUTH(){return process.env.AFK_OPENAI_CHATGPT_OAUTH},get AFK_PROVIDER(){return process.env.AFK_PROVIDER},get EXA_API_KEY(){return process.env.EXA_API_KEY},get TELEGRAM_BOT_TOKEN(){return process.env.TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_BOT_TOKEN(){return process.env.AFK_TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_ALLOWED_CHAT_IDS(){return process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS},get AFK_TELEGRAM_TAG_ONLY_CHAT_IDS(){return process.env.AFK_TELEGRAM_TAG_ONLY_CHAT_IDS},get AFK_TELEGRAM_PRIMARY_CHAT_ID(){return process.env.AFK_TELEGRAM_PRIMARY_CHAT_ID},get AFK_TELEGRAM_NOTIFY_MODE(){return process.env.AFK_TELEGRAM_NOTIFY_MODE},get TELEGRAM_DATA_DIR(){return process.env.TELEGRAM_DATA_DIR},get TELEGRAM_VERBOSE(){return process.env.TELEGRAM_VERBOSE},get AFK_TELEGRAM_TRACE(){return process.env.AFK_TELEGRAM_TRACE},get AFK_TELEGRAM_CWD(){return process.env.AFK_TELEGRAM_CWD},get AFK_HOME(){return process.env.AFK_HOME},get AFK_STATE_DIR(){return process.env.AFK_STATE_DIR},get AFK_FRAMEWORK_DIR(){return process.env.AFK_FRAMEWORK_DIR},get HOME(){return process.env.HOME},get PATH(){return process.env.PATH},get AFK_DAEMON_CWD(){return process.env.AFK_DAEMON_CWD},get AFK_DAEMON_TASK(){return process.env.AFK_DAEMON_TASK},get AFK_DAEMON_TASK_ID(){return process.env.AFK_DAEMON_TASK_ID},get AFK_DAEMON_HOST(){return process.env.AFK_DAEMON_HOST},get AFK_SESSIONSTART_COOLDOWN_MS(){return process.env.AFK_SESSIONSTART_COOLDOWN_MS},get AFK_WORKTREE_AUTONAME(){return process.env.AFK_WORKTREE_AUTONAME},get AFK_WORKTREE_BRANCH_PREFIX(){return process.env.AFK_WORKTREE_BRANCH_PREFIX},get AFK_WORKTREE_BASE(){return process.env.AFK_WORKTREE_BASE},get AFK_WORKTREE_ON_EXIT(){return process.env.AFK_WORKTREE_ON_EXIT},get AFK_WORKTREE_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BG_AUTO_DELIVER(){return process.env.AFK_BG_AUTO_DELIVER},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_PLAIN_OUTPUT(){return process.env.AFK_PLAIN_OUTPUT},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},get AFK_GOBLIN_SPINNER(){return process.env.AFK_GOBLIN_SPINNER},get AFK_GOBLIN_MASCOT(){return process.env.AFK_GOBLIN_MASCOT},get AFK_TERM_TITLE(){return process.env.AFK_TERM_TITLE},get AFK_NOTIFY(){return process.env.AFK_NOTIFY},get AFK_SHOW_DIFFS(){return process.env.AFK_SHOW_DIFFS},get AFK_SKILL_STREAM_VERBOSE(){return process.env.AFK_SKILL_STREAM_VERBOSE},get FORCE_COLOR(){return process.env.FORCE_COLOR},get NO_COLOR(){return process.env.NO_COLOR},get AFK_THEME(){return process.env.AFK_THEME},get AFK_TEXT_MEASURE(){return process.env.AFK_TEXT_MEASURE},get COLORFGBG(){return process.env.COLORFGBG},get AFK_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get AFK_CAPTURE_SUBAGENT_PROMPTS(){return process.env.AFK_CAPTURE_SUBAGENT_PROMPTS},get AFK_CAPTURE_SUBAGENT_OUTPUT(){return process.env.AFK_CAPTURE_SUBAGENT_OUTPUT},get DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_BROWSER_DEFAULT_PROFILE(){return process.env.AFK_BROWSER_DEFAULT_PROFILE},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_READ_DENYLIST(){return process.env.AFK_READ_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_WEB_ALLOW_PRIVATE_HOSTS(){return process.env.AFK_WEB_ALLOW_PRIVATE_HOSTS},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get VISUAL(){return process.env.VISUAL},get EDITOR(){return process.env.EDITOR},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let t of jc){if(!t.secret)continue;let n=Object.getOwnPropertyDescriptor(T,t.name);n&&Object.defineProperty(T,t.name,{...n,enumerable:!1})}})()});import{existsSync as K_,mkdirSync as B8,renameSync as U8,cpSync as j8,rmSync as H8}from"fs";import{join as ne,dirname as GS,basename as W8,isAbsolute as qS}from"path";import{homedir as zS}from"os";import{fileURLToPath as K8}from"url";function Te(){let e=T.AFK_HOME;if(e!==void 0&&e!==""){if(!qS(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return ne(zS(),".afk")}function bt(){let e=T.AFK_FRAMEWORK_DIR;if(e!==void 0&&e!==""){if(!qS(e)||e==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${e}`);return e}return ne(Te(),"agent-framework")}function Zn(){return ne(bt(),"forge-telemetry.jsonl")}function z_(){return ne(bt(),"routing-decisions.jsonl")}function V_(){return ne(bt(),"briefs")}function J_(){return ne(bt(),"facets")}function Wc(){return ne(Te(),"skills")}function Ke(){return ne(Te(),"plugins")}function Y_(e=process.cwd()){return ne(e,".afk")}function tm(e=process.cwd()){return ne(Y_(e),"skills")}function nm(e=process.cwd()){return ne(Y_(e),"plugins")}function rm(e=process.cwd()){return ne(e,".afk","plans")}function Ee(){return ne(Ke(),".index.json")}function VS(){return ne(Pn(),"schedules.json")}function Mr(){return ne(Ke(),"cache")}function Kc(e){return ne(Mr(),e)}function sa(){let e=K8(import.meta.url),t=GS(e);return ne(t,"bundled-plugins")}function Pn(){return ne(Te(),"config")}function me(){let e=T.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!qS(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return ne(Te(),"state")}function aa(){return ne(Te(),"cache")}function ho(){return ne(Te(),"logs")}function pt(){return ne(me(),"sessions")}function om(){return ne(me(),"presence")}function JS(){return ne(me(),"todos")}function Gc(){return ne(me(),"transcripts")}function im(){return ne(me(),"memory")}function wt(){return ne(me(),"queue")}function sm(){return ne(me(),"session-grants.jsonl")}function qc(){return ne(Pn(),"permissions.json")}function X_(){return ne(Te(),"farms")}function YS(e){return ne(X_(),e)}function am(e){if(!G8.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function er(e){return am(e),ne(me(),"witness",e)}function Q_(e){return ne(er(e),"inbound-attachments")}function Z_(e){return ne(er(e),"prompts")}function eI(e){return ne(er(e),"outputs")}function zc(e){return!e||e.startsWith("in-memory:")?null:W8(GS(e))}function XS(){return ne(me(),"receipts")}function lm(e="default"){return ne(me(),"daemon",`agent-afk@${e}`)}function tI(){return ne(me(),"worktree-sweep.lock")}function cm(){return ne(me(),"worktree-roots.json")}function xt(){return ne(Pn(),"afk.env")}function Kt(){return ne(Pn(),"afk.config.json")}function QS(){return ne(Pn(),"settings.json")}function nI(e=process.cwd()){return ne(e,".afk","settings.json")}function um(){return ne(Te(),"AFK.md")}function dm(e=process.cwd()){return ne(e,"AFK.md")}function rI(){return ne(zS(),".afk.env")}function pm(){return ne(zS(),".afk.config.json")}function q8(){return ne(Te(),"sessions")}function z8(){return ne(Te(),"todos")}function V8(){return ne(Te(),"transcripts")}function ZS(e,t){if(e!==t&&K_(e)&&!K_(t))try{B8(GS(t),{recursive:!0});try{U8(e,t)}catch(n){if(n.code==="EXDEV")try{j8(e,t,{recursive:!0}),H8(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
|
|
3
|
-
`)}}}catch{}}function oI(){ZS(q8(),pt())}function iI(){ZS(z8(),JS())}function sI(){ZS(V8(),Gc())}function ev(){return ne(me(),"repl-history.jsonl")}function Y8(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(e.length>G_)throw new Error(`Invalid jobId: exceeds ${G_} chars`);if(!J8.test(e))throw new Error(`Invalid jobId: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function Vc(){return ne(me(),"bg")}function Ti(e){return Y8(e),ne(Vc(),e)}function mm(e){return ne(Ti(e),"events.jsonl")}function tv(e){return ne(Ti(e),"meta.json")}function Jc(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(e.length>q_)throw new Error(`Invalid browser profile: exceeds ${q_} chars`);if(!X8.test(e))throw new Error(`Invalid browser profile: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function nv(){return ne(me(),"browser")}function rv(e){return Jc(e),ne(nv(),e)}function Yc(e){return ne(rv(e),"storageState.json")}function Xc(e){return typeof e=="string"&&e.length>0&&e.length<=Z8&&Q8.test(e)}function Qc(e){if(!Xc(e))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(e)}`);return ne(pt(),e)}function fm(e){return ne(Qc(e),"events.jsonl")}function ov(e){return ne(Qc(e),"session.key")}function Zc(){return ne(me(),"mcp","server-status.json")}var G8,J8,G_,X8,q_,Q8,Z8,G=k(()=>{"use strict";W();G8=/^[a-zA-Z0-9_-]+$/;J8=/^[A-Za-z0-9_-]+$/,G_=128;X8=/^[A-Za-z0-9_-]+$/,q_=128;Q8=/^[A-Za-z0-9_-]+$/,Z8=128});import{randomBytes as e5}from"node:crypto";import{mkdirSync as t5,renameSync as n5,rmSync as aI,writeFileSync as r5}from"node:fs";import{dirname as o5,isAbsolute as i5,join as s5}from"node:path";function gm(){return s5(me(),"last-cwd")}function lI(){try{aI(gm(),{force:!0})}catch{}}function cI(e){if(!i5(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=gm();t5(o5(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${e5(6).toString("hex")}`;try{r5(n,e,{encoding:"utf8",mode:384}),n5(n,t)}catch(r){try{aI(n,{force:!0})}catch{}throw r}}catch{}}function uI(){let e=T.AFK_SHELL_WRAPPER;return e==="1"||e==="true"}var hm=k(()=>{"use strict";W();G()});var mt,rt,Sm,xe,or,ir,la,vm,Le=k(()=>{"use strict";mt=class extends Error{constructor(t){super(t),this.name="AbortError"}},rt=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Sm=class extends rt{constructor(t,n){super(t,n),this.name="IdleWatchdogError"}},xe=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)}event;reason;cause},or=class extends Error{constructor(t){super(t),this.name="StreamIncompleteError"}},ir=class extends Error{constructor(n,r,o){super(o??`Budget ceiling reached: $${n.toFixed(4)} cumulative >= $${r.toFixed(4)} limit`);this.runningCostUsd=n;this.maxBudgetUsd=r;this.name="BudgetExceededError"}runningCostUsd;maxBudgetUsd},la=class extends Error{constructor(t){super(t),this.name="DenialCircuitBreakerError"}},vm=class extends Error{constructor(n,r,o){super(o??`${n} provider does not support AgentConfig.${r}.`);this.provider=n;this.field=r;this.name="UnsupportedProviderConfigError"}provider;field}});function
|
|
3
|
+
`)}}}catch{}}function oI(){ZS(q8(),pt())}function iI(){ZS(z8(),JS())}function sI(){ZS(V8(),Gc())}function ev(){return ne(me(),"repl-history.jsonl")}function Y8(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(e.length>G_)throw new Error(`Invalid jobId: exceeds ${G_} chars`);if(!J8.test(e))throw new Error(`Invalid jobId: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function Vc(){return ne(me(),"bg")}function Ti(e){return Y8(e),ne(Vc(),e)}function mm(e){return ne(Ti(e),"events.jsonl")}function tv(e){return ne(Ti(e),"meta.json")}function Jc(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(e.length>q_)throw new Error(`Invalid browser profile: exceeds ${q_} chars`);if(!X8.test(e))throw new Error(`Invalid browser profile: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function nv(){return ne(me(),"browser")}function rv(e){return Jc(e),ne(nv(),e)}function Yc(e){return ne(rv(e),"storageState.json")}function Xc(e){return typeof e=="string"&&e.length>0&&e.length<=Z8&&Q8.test(e)}function Qc(e){if(!Xc(e))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(e)}`);return ne(pt(),e)}function fm(e){return ne(Qc(e),"events.jsonl")}function ov(e){return ne(Qc(e),"session.key")}function Zc(){return ne(me(),"mcp","server-status.json")}var G8,J8,G_,X8,q_,Q8,Z8,G=k(()=>{"use strict";W();G8=/^[a-zA-Z0-9_-]+$/;J8=/^[A-Za-z0-9_-]+$/,G_=128;X8=/^[A-Za-z0-9_-]+$/,q_=128;Q8=/^[A-Za-z0-9_-]+$/,Z8=128});import{randomBytes as e5}from"node:crypto";import{mkdirSync as t5,renameSync as n5,rmSync as aI,writeFileSync as r5}from"node:fs";import{dirname as o5,isAbsolute as i5,join as s5}from"node:path";function gm(){return s5(me(),"last-cwd")}function lI(){try{aI(gm(),{force:!0})}catch{}}function cI(e){if(!i5(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=gm();t5(o5(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${e5(6).toString("hex")}`;try{r5(n,e,{encoding:"utf8",mode:384}),n5(n,t)}catch(r){try{aI(n,{force:!0})}catch{}throw r}}catch{}}function uI(){let e=T.AFK_SHELL_WRAPPER;return e==="1"||e==="true"}var hm=k(()=>{"use strict";W();G()});var mt,rt,Sm,xe,or,ir,la,vm,Le=k(()=>{"use strict";mt=class extends Error{constructor(t){super(t),this.name="AbortError"}},rt=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Sm=class extends rt{constructor(t,n){super(t,n),this.name="IdleWatchdogError"}},xe=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)}event;reason;cause},or=class extends Error{constructor(t){super(t),this.name="StreamIncompleteError"}},ir=class extends Error{constructor(n,r,o){super(o??`Budget ceiling reached: $${n.toFixed(4)} cumulative >= $${r.toFixed(4)} limit`);this.runningCostUsd=n;this.maxBudgetUsd=r;this.name="BudgetExceededError"}runningCostUsd;maxBudgetUsd},la=class extends Error{constructor(t){super(t),this.name="DenialCircuitBreakerError"}},vm=class extends Error{constructor(n,r,o){super(o??`${n} provider does not support AgentConfig.${r}.`);this.provider=n;this.field=r;this.name="UnsupportedProviderConfigError"}provider;field}});function He(){return T.AFK_DEBUG==="1"||T.DEBUG==="1"}function B(...e){He()&&console.log(...e)}var ue=k(()=>{"use strict";W()});import{mkdirSync as Z5,appendFileSync as e3,existsSync as t3}from"fs";import{resolve as n3}from"path";import{dirname as r3}from"path";function De(e){let t=e;for(let[n,r]of s3)t=t.replace(n,(...o)=>{let i=o.slice(0,o.length-2);return r(i)});return t}function wv(e){return typeof e=="string"?De(e):Array.isArray(e)?e.map(wv):e}function a3(e){if(e===null||typeof e!="object")return e;let t=e,n={...t},r=t.env;if(r&&typeof r=="object"){let o={};for(let[i,s]of Object.entries(r))i3.test(i)&&typeof s=="string"?o[i]=`<REDACTED length=${s.length}>`:o[i]=s;n.env=o}return"system"in t&&(n.system=wv(t.system)),"systemPrompt"in t&&(n.systemPrompt=wv(t.systemPrompt)),n}function l3(e){if(e==null)return{kind:"undefined",note:"SDK uses minimal prompt; claude_code preset NOT loaded"};if(typeof e=="string")return{kind:"custom-string",note:"SDK uses this string as full system prompt; claude_code preset NOT loaded"};if(Array.isArray(e))return{kind:"custom-string-array",note:"SDK uses array as full system prompt with cache boundaries; claude_code preset NOT loaded"};if(typeof e=="object"){let t=e;if(t.type==="preset"&&t.preset==="claude_code"){let n={kind:"preset-claude-code",note:"claude_code preset loaded"};return typeof t.append=="string"&&(n.append={length:t.append.length}),t.excludeDynamicSections===!0&&(n.excludeDynamicSections=!0),n}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}function HI(e){let t=T.AFK_DUMP_PROMPT;if(!t||t===""||t==="0"||t.toLowerCase()==="false")return;process.stderr.write(`[--dump-prompt] WARNING: dump may contain secrets from system prompt or messages. Inspect before sharing.
|
|
4
4
|
`);let n=e.options,r=typeof n=="object"&&n!==null?n.systemPrompt:void 0,o=l3(r),i={timestamp:new Date().toISOString(),prompt:e.prompt,options:a3(e.options),provenance:e.provenance,resolution:o};if(t==="1"||t.toLowerCase()==="true"||t.toLowerCase()==="stderr"){let l=JSON.stringify(i,null,2)+`
|
|
5
5
|
`;process.stderr.write(l);return}let s=n3(t),a=r3(s);try{Z5(a,{recursive:!0});let c=(!t3(s)?o3:"")+JSON.stringify(i)+`
|
|
6
6
|
`;e3(s,c)}catch(l){let c=`[prompt-dump] Failed to write to ${s}: ${String(l)}
|
|
@@ -179,7 +179,7 @@ Remedy: these paths are outside the fork's granted read roots. Re-dispatch with
|
|
|
179
179
|
`).find(n=>n.trim()!=="")?.trim()??"";return t.length<=fM?t:`${t.slice(0,fM)}\u2026`}var ok,nQ,fM,ff,gM=k(()=>{"use strict";rk();ok=3,nQ=new Set(["timeout_ms","timeoutMs","timeout"]),fM=240;ff=class{streaks=new Map;check(t){let n=this.streaks.get(vu(t));return n===void 0||n.count<ok?null:{count:n.count,tool:t.name,result:{content:`Repeat-failure guard: "${t.name}" has already failed ${n.count} times in a row with the same arguments, so this call was NOT executed again. The last failure was: ${n.lastError}
|
|
180
180
|
|
|
181
181
|
Retrying it verbatim will fail the same way. Fix the underlying cause, change the arguments, use a different tool, or stop and report the blocker.`,isError:!0,failureClass:"repeat-failure"}}}note(t,n){let r=vu(t);if(n.isError!==!0){this.streaks.delete(r);return}let o=this.streaks.get(r);this.streaks.set(r,{count:(o?.count??0)+1,lastError:oQ(n)})}streakFor(t){return this.streaks.get(vu(t))?.count??0}}});var Ia,ik,Ot,Pa=k(()=>{"use strict";pu();ue();Le();Di();Km();Gm();Vm();Fv();Li();Hm();pe();ek();aM();pf();rk();gM();ek();Ia=8,ik=new Set,Ot=class{handlers;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;skillExecutor;composeExecutor;classifier;maxConcurrentSafeCalls;resolveBase;_readRoots;_writeRoots;_allowAll;_env;sessionId;parentSessionId;subagentId;sessionGrantManager;traceWriter;readOnlyBash;maxOutputBytes;repeatBreaker=null;repeatFailureGuard=new ff;denialBreaker=null;suspectedLoopWindow=null;grantManager;constructor(t){this.handlers=t.handlers,this.schemas=t.schemas,this.hookRegistry=t.hookRegistry,this.permissions=t.permissions,this.canUseTool=t.canUseTool,this.subagentExecutor=t.subagentExecutor,this.skillExecutor=t.skillExecutor,this.composeExecutor=t.composeExecutor,this.classifier=t.concurrencyClassifier??Zv,this.maxConcurrentSafeCalls=typeof t.maxConcurrentSafeCalls=="number"&&Number.isFinite(t.maxConcurrentSafeCalls)&&t.maxConcurrentSafeCalls>=1?Math.floor(t.maxConcurrentSafeCalls):TP(),this.resolveBase=t.cwd,this._env=t.env,this.sessionId=t.sessionId,this.parentSessionId=t.parentSessionId,this.subagentId=t.subagentId,this.sessionGrantManager=t.sessionGrantManager,this.traceWriter=t.traceWriter,this.readOnlyBash=t.readOnlyBash===!0,this.maxOutputBytes=typeof t.maxOutputBytes=="number"&&Number.isFinite(t.maxOutputBytes)&&t.maxOutputBytes>0?t.maxOutputBytes:void 0,this._allowAll=t.allowAll===!0;let n=t.cwd?[t.cwd]:[];this._readRoots=t.readRoots??n.slice(),this._writeRoots=t.writeRoots??n.slice(),this.grantManager=new Eo({getReadRoots:()=>this._readRoots,getWriteRoots:()=>this._writeRoots,getProtectedRoot:()=>this.resolveBase,getAllowAll:()=>this._allowAll,getDefaultSessionId:()=>this.sessionId})}get handlerContext(){return{cwd:this.resolveBase,resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),...this._allowAll?{allowAll:!0}:{},...this._env!==void 0?{env:this._env}:{},...this.sessionId!==void 0?{sessionId:this.sessionId}:{}}}callHandlerContext(t){return{...this.handlerContext,toolUseId:t.id,...this.traceWriter!==void 0?{traceWriter:this.traceWriter}:{}}}addReadRoot(t,n="slash"){this.grantManager.addReadRoot(t,n)}addWriteRoot(t,n="slash"){this.grantManager.addWriteRoot(t,n)}revokeRoot(t,n="slash"){this.grantManager.revokeRoot(t,n)}getGrants(){return this.grantManager.getGrants()}setAllowAll(t){this._allowAll=t}setResolveBase(t){let n=this.resolveBase;if(n!==t){if(this.resolveBase=t,n!==void 0){let r=this._readRoots.indexOf(n);r!==-1?this._readRoots[r]=t:this._readRoots.includes(t)||this._readRoots.push(t);let o=this._writeRoots.indexOf(n);o!==-1?this._writeRoots[o]=t:this._writeRoots.includes(t)||this._writeRoots.push(t)}else this._readRoots.includes(t)||this._readRoots.push(t),this._writeRoots.includes(t)||this._writeRoots.push(t);this.subagentExecutor?.setCwd(t),this.skillExecutor?.setCwd(t),this.composeExecutor?.setCwd(t)}}get toolDefs(){let t=this.permissions?.allowedTools;if(!t)return this.schemas;let n=new Set(t);return this.schemas.filter(r=>n.has(r.name))}async checkReadOnlyBash(t){if(!this.readOnlyBash||t.name!=="bash")return null;let n=t.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=Ym(r);if(!o.mutating)return null;let i=`Bash command blocked: read-only skill may not run mutating commands (${o.reason??"mutation detected"}). Allowed: read-only recon (git status/log/diff/show/ls-remote, ls, cat, find, grep, gh pr view/diff). For a remote ref you have not fetched, \`gh pr diff <n>\`, \`gh pr view <n>\` and \`git ls-remote\` need no local ref \u2014 \`git fetch\` is blocked. Do NOT retry variants of a blocked command: if the task genuinely requires a mutation, stop and report that requirement to your caller instead.`;return await this.emitPreToolUseBlock(t.name,i),{content:i,isError:!0,failureClass:"permission-denied"}}async emitPreToolUseBlock(t,n){await sn(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:t,reason:n,...this.subagentId!==void 0?{subagentId:this.subagentId}:{}})}checkRepeatCircuitBreaker(t){if(ik.has(t.name))return null;let n=sM(t);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<Ia?null:{content:`Loop circuit breaker: "${t.name}" has been called ${this.repeatBreaker.count} times in a row with byte-identical input. The result will not change. Stop repeating this call \u2014 reuse the previous result, change the input, try a different tool, or end the turn.`,isError:!0,circuitBreaker:!0}}checkRepeatFailureGuard(t){if(ik.has(t.name))return null;let n=this.repeatFailureGuard.check(t);return n===null?null:(B(`[repeat-failure-guard #723] refused ${n.tool} after ${n.count} identical failures`),n.result)}observeSuspectedLoop(t){if(this.parentSessionId===void 0)return;this.suspectedLoopWindow===null&&(this.suspectedLoopWindow=pM());let n=mf(t),r=mM(this.suspectedLoopWindow,n);r.fired&&re(this.traceWriter,{phase:"suspected_loop",metadata:{tool:t.name,count:r.count,windowSize:nk}})}recordForkReadDenial(t,n,r){if(this.parentSessionId===void 0||!lM.has(t.name)||!cM(n))return r;let o=this.denialBreaker??{count:0,deniedPaths:[]};o.count+=1;let i=uM(t);return o.deniedPaths.includes(i)||o.deniedPaths.push(i),this.denialBreaker=o,o.count<5?r:{content:dM(o.deniedPaths,o.count),isError:!0,failureClass:_a}}resetDenialBreaker(){this.denialBreaker=null}async runCanUseTool(t){if(!this.canUseTool)return null;let n;try{n=await this.canUseTool(t.name,t.input??{},{signal:t.signal,toolUseID:t.id})}catch(r){let o=`Tool "${t.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`;return await this.emitPreToolUseBlock(t.name,o),{content:o,isError:!0,failureClass:"permission-denied"}}if(n.behavior==="deny"){let r=n.message||`Tool "${t.name}" denied by permission policy`;return await this.emitPreToolUseBlock(t.name,r),{content:r,isError:!0,failureClass:"permission-denied"}}return n.updatedInput!==void 0&&(t.input=n.updatedInput),null}async runPreDispatchGates(t){if(this.hookRegistry){let a={event:"PreToolUse",toolName:t.name,input:t.input,...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.resolveBase!==void 0?{cwd:this.resolveBase}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{}};try{await CP(this.hookRegistry,a,{signal:t.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(l){if(l instanceof xe)return this.recordForkReadDenial(t,l.reason,{content:`Tool "${t.name}" blocked by PreToolUse hook: ${l.message}`,isError:!0,failureClass:"hook-block"});throw l}}let n=PP(t.name,this.permissions);if(!n.allowed){let a=n.reason??`Tool "${t.name}" is not permitted`;return await this.emitPreToolUseBlock(t.name,a),{content:a,isError:!0,failureClass:"permission-denied"}}let r=await this.runCanUseTool(t);if(r)return r;let o=await this.checkReadOnlyBash(t);if(o)return o;let i=this.checkRepeatCircuitBreaker(t);if(i)return i;let s=this.checkRepeatFailureGuard(t);return s||(this.observeSuspectedLoop(t),null)}async execute(t){if(t.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:Pt(t.signal)};let n=await this.runPreDispatchGates(t);if(n)return n;let r=await this.executeCore(t);return this.repeatFailureGuard.note(t,r),r.isError!==!0&&this.resetDenialBreaker(),r}async executeBatch(t){if(t.length===0)return[];if(t.length===1)return[await this.execute(t[0])];let n=new Array(t.length),r=new Set;for(let s=0;s<t.length;s++){let a=t[s];if(a.signal.aborted){n[s]={content:"Tool call aborted",isError:!0,failureClass:Pt(a.signal)},r.add(s);continue}let l=await this.runPreDispatchGates(a);if(l){n[s]=l,r.add(s);continue}}let o=t.map((s,a)=>({call:s,originalIndex:a})).filter((s,a)=>!r.has(a));if(o.length===0)return n;let i=iM(o.map(s=>s.call),this.classifier);for(let s of i){if(s.isConcurrencySafe){let l=[...s.indices];for(;l.length>0;){let c=new Map,u=[],d=[];for(let f of l){let{call:g,originalIndex:h}=o[f],y=this.checkRepeatFailureGuard(g);if(y){n[h]=y;continue}if(ik.has(g.name)){u.push(f);continue}let b=vu(g),w=ok-this.repeatFailureGuard.streakFor(g),v=c.get(b)??0;v<w?(c.set(b,v+1),u.push(f)):d.push(f)}l=d;let m=await Ra(u,this.maxConcurrentSafeCalls,async f=>{let{call:g,originalIndex:h}=o[f];return g.signal.aborted?{result:{content:"Tool call aborted",isError:!0,failureClass:Pt(g.signal)},originalIndex:h}:{result:await this.executeCore(g),originalIndex:h}});for(let f of m)if(f.status==="fulfilled")n[f.value.originalIndex]=f.value.result;else{let g=f.reason instanceof Error?f.reason.message:String(f.reason),h=u[m.indexOf(f)];n[o[h].originalIndex]={content:`Tool execution error: ${g}`,isError:!0}}for(let f of u){let{call:g,originalIndex:h}=o[f],y=n[h];y!==void 0&&y.failureClass!=="abort"&&this.repeatFailureGuard.note(g,y)}}}else for(let l of s.indices){let{call:c,originalIndex:u}=o[l];if(c.signal.aborted){n[u]={content:"Tool call aborted",isError:!0,failureClass:Pt(c.signal)};continue}let d=this.checkRepeatFailureGuard(c);if(d){n[u]=d;continue}let m=await this.executeCore(c);n[u]=m,this.repeatFailureGuard.note(c,m)}let a=s.indices.length;s.indices.forEach((l,c)=>{let u=n[o[l].originalIndex];u&&(u.batchIndex=c+1,u.batchSize=a)})}return n.some(s=>s!==void 0&&s.isError!==!0)&&this.resetDenialBreaker(),n}async executeCore(t){let n=await this.executeCoreInner(t);return this.applyOutputCap(n)}applyOutputCap(t){let n=this.maxOutputBytes;if(n===void 0)return t;let r=Buffer.byteLength(t.content,"utf8");return r<=n||(t.content=$r(t.content,n),t.truncated=!0,B(`[output-cap #661] fork tool result capped: original=${r}B capped=${Buffer.byteLength(t.content,"utf8")}B (cap=${n}B)`)),t}async executeCoreInner(t){if(t.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let s,a=!1,l="";try{s=await this.subagentExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),s={content:`Agent tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,s.content,t.signal,t.input,s),s}if(t.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let s,a=!1,l="";try{s=await this.skillExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),s={content:`Skill tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,s.content,t.signal,t.input,s),s}if(t.name==="compose"){let s=await this.executeCompose(t);return this.firePostToolUse(t.name,s.content,t.signal,t.input,s),s}let n=this.handlers.get(t.name);if(!n)return{content:`Unknown tool "${t.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let r,o=!1,i="";try{r=await n(t.input,t.signal,this.callHandlerContext(t))}catch(s){o=!0,i=s instanceof Error?s.message:String(s),r={content:`Tool execution error: ${i}`,isError:!0}}return o?this.firePostToolUseFailure(t.name,i,t.signal,t.input):this.firePostToolUse(t.name,r.content,t.signal,t.input,r),r}async executeCompose(t){if(!this.composeExecutor)return{content:"Compose tool is not available in this session configuration",isError:!0};try{return await this.composeExecutor.execute(t)}catch(n){return{content:`Compose tool error: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}firePostToolUse(t,n,r,o,i){if(!this.hookRegistry)return;let s={event:"PostToolUse",toolName:t,output:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{},...i?.incomplete===!0?{incomplete:!0}:{},...i?.incompleteReason?{incompleteReason:i.incompleteReason}:{}};_P(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(()=>{})}firePostToolUseFailure(t,n,r,o){if(!this.hookRegistry)return;let i={event:"PostToolUseFailure",toolName:t,error:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};IP(this.hookRegistry,i,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(s=>{B(`firePostToolUseFailure outer catch (tool=${t}): ${String(s)}`)})}}});import{mkdir as sQ,writeFile as aQ}from"fs/promises";import{dirname as lQ,join as cQ}from"path";function uQ(){return cQ(bt(),"routing-decisions.jsonl")}function dQ(e){let t={surface:"afk"};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}async function Me(e){if(!(T.VITEST||T.NODE_ENV==="test"))try{let t=uQ();await sQ(lQ(t),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,...dQ(e)})+`
|
|
182
|
-
`;await aQ(t,r,{flag:"a"})}catch{}}var Dn=k(()=>{"use strict";W();G()});function kQ(e){let t=e.match(pQ);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"vitest",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function TQ(e){let t=e.match(mQ);if(!t)return null;let n=parseInt(t[1]??"0",10);return{runner:"jest",passed:parseInt(t[2]??"0",10),failed:n}}function EQ(e){let t=e.match(fQ);if(!t)return null;if(t[2]!==void 0){let n=parseInt(t[2],10),r=parseInt(t[1]??"0",10);return{runner:"pytest",passed:n,failed:r}}return t[4]!==void 0?{runner:"pytest",passed:parseInt(t[4],10),failed:0}:null}function RQ(e){let t=e.match(gQ);if(!t)return null;let n=parseInt(t[1]??"0",10),r=e.match(hQ),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function xQ(e){let t=[...e.matchAll(yQ)];if(t.length===0)return null;let n=0,r=0;for(let o of t)o[1]==="ok"?n++:o[1]==="FAIL"&&r++;return{runner:"go-test",passed:n,failed:r}}function AQ(e){let t=e.match(bQ);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"cargo",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function CQ(e){let t=e.match(wQ);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10);return{runner:"rspec",passed:n-r,failed:r}}function _Q(e){let t=e.match(SQ);if(t)return{runner:"phpunit",passed:parseInt(t[1]??"0",10),failed:0};let n=e.match(vQ);if(n){let r=parseInt(n[1]??"0",10),o=parseInt(n[2]??"0",10);return{runner:"phpunit",passed:r-o,failed:o}}return null}function sk(e){return kQ(e)??TQ(e)??EQ(e)??RQ(e)??xQ(e)??AQ(e)??CQ(e)??_Q(e)??null}var pQ,mQ,fQ,gQ,hQ,yQ,bQ,wQ,SQ,vQ,hM=k(()=>{"use strict";pQ=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,mQ=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,fQ=/={3,}\s*(?:(\d+)\s+failed,\s*)?(\d+)\s+passed(?:,\s*(\d+)\s+warning)?.*in\s+[\d.]+s\s*={3,}|={3,}\s*(\d+)\s+passed.*in\s+[\d.]+s\s*={3,}/,gQ=/(\d+)\s+passing/,hQ=/(\d+)\s+failing/,yQ=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,bQ=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,wQ=/(\d+) examples?, (\d+) failures?/,SQ=/OK \((\d+) tests?/,vQ=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/});function Dr(e){return e.replace(yM,"").replace(IQ," ").trim()}function dr(e){return e.replace(yM,"")}var yM,IQ,Ao=k(()=>{"use strict";yM=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,IQ=/[\x00-\x1F\x7F-\x9F]/g});import{statSync as PQ}from"node:fs";function ku(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.code==="ENOENT"&&typeof t.syscall=="string"&&t.syscall.startsWith("spawn")}function MQ(e){if(e===void 0)return!1;try{return PQ(e),!1}catch{return!0}}function Ma(e,t){let n=e instanceof Error?e.message:typeof e?.message=="string"?String(e.message):String(e);return ku(e)&&MQ(t)?`working directory does not exist: ${t} (deleted worktree?) \u2014 underlying: ${n}`:n}var ak=k(()=>{"use strict"});function pr(e){if(bM)return;bM=!0;let t=e instanceof Error?e.message:String(e);console.warn(`[afk-home] Malformed AFK home/state env var ignored while deriving the credential floor: ${t}. The relocated tree is NOT protected \u2014 the default ~/.afk entries still apply. Fix the env var to restore coverage.`)}var bM,Tu=k(()=>{"use strict";bM=!1});import{statSync as ck}from"node:fs";import{homedir as OQ}from"node:os";import{basename as $Q,dirname as SM,join as DQ}from"node:path";function vM(e){return typeof e=="object"&&e!==null&&"code"in e?String(e.code):void 0}function FQ(e){let t=$Q(e),n=t===t.toLowerCase()?t.toUpperCase():t.toLowerCase();if(n===t)return;let r;try{r=ck(e)}catch{return}let o=lk.get(r.dev);if(o!==void 0)return o;try{let i=ck(DQ(SM(e),n)),s=r.dev===i.dev&&r.ino===i.ino;return lk.set(r.dev,s),s}catch(i){let s=vM(i);return s==="ENOENT"||s==="ENOTDIR"?(lk.set(r.dev,!1),!1):void 0}}function kM(e=OQ()){if(wM!==void 0)return wM;let t=e;for(;;)try{return ck(t),FQ(t)??!0}catch(n){let r=vM(n);if(r!=="ENOENT"&&r!=="ENOTDIR")return!0;let o=SM(t);if(o===t)return!0;t=o}}function Oa(e,t,n=t){if(e===t||e.startsWith(t+"/"))return!0;if(!kM(n))return!1;let r=e.toLowerCase(),o=t.toLowerCase();return r===o||r.startsWith(o+"/")}function uk(e,t){return e.includes(t)?!0:kM(t)?e.toLowerCase().includes(t.toLowerCase()):!1}var wM,lk,gf=k(()=>{"use strict";lk=new Map});import{realpathSync as TM}from"fs";import{dirname as LQ,resolve as Hi,join as dk}from"path";import{homedir as Co}from"os";function BQ(){let e=[];try{let t=Te();e.push(je(Hi(dk(t,"config")))),e.push(je(Hi(dk(t,"state"))))}catch(t){pr(t)}try{e.push(je(Hi(me())))}catch(t){pr(t)}return e}function pk(){let e=T.AFK_WRITE_DENYLIST,t=e?e.split(":").map(r=>je(Hi(r))).filter(Boolean):[];return[...[...new Set([...NQ.map(r=>je(Hi(r))),...BQ()])],...t]}function je(e){let t=Hi(e);try{return TM(t)}catch{}let n=[],r=t;for(let o=0;o<64;o++){let i=LQ(r);if(i===r)break;n.unshift(r.slice(i.length+1)),r=i;try{let s=TM(r);return dk(s,...n)}catch{}}return t}function hf(e,t="write_file"){let n=je(Hi(e));for(let r of pk())if(Oa(n,r))throw new Error(`${t}: refusing to write to protected path: ${n} (matches denylist entry: ${r})`)}var NQ,Wi=k(()=>{"use strict";W();G();Tu();gf();NQ=[`${Co()}/.ssh`,`${Co()}/.aws`,`${Co()}/.gnupg`,`${Co()}/.config/gcloud`,"/etc","/System","/private/etc","/usr/local/etc",`${Co()}/.afk/config`,`${Co()}/.afk/state`,`${Co()}/.npmrc`,`${Co()}/.docker/config.json`]});import{isAbsolute as UQ,relative as jQ,sep as HQ}from"node:path";import{homedir as mk}from"node:os";function WQ(e,t){let n=jQ(t,e);return n===""||n!==".."&&!n.startsWith(`..${HQ}`)&&!UQ(n)}function fk(e,t){return e.filter(n=>!t.some(r=>WQ(n,r)))}function KQ(e,t){return e.filter(({source:n})=>n!==t).map(({root:n})=>n)}function EM(e,t){return e.flatMap(({rel:n,resolved:r})=>fk([r],KQ(t,GQ[n])))}var GQ,RM=k(()=>{"use strict";GQ={".afk/config/mcp.json":`${mk()}/.afk/config`,".ssh/config":`${mk()}/.ssh`,".ssh/known_hosts":`${mk()}/.ssh`}});import{existsSync as xM}from"fs";import{isAbsolute as qQ,resolve as _M}from"path";import{homedir as AM}from"os";function Ki(e){return e==="~"?AM():e.startsWith("~/")?_M(AM(),e.slice(2)):e}function yf(e){if(!e.startsWith("https://"))throw new Error(`Plugin source must use https:// (got: ${e}). git://, http://, ssh://, file://, and git@ are rejected to avoid downgrade attacks and unauthenticated clones.`)}function $a(e){let t=e.trim();if(!t)throw new Error('plugin source is required (examples: "owner/repo", "https://github.com/owner/repo.git", "./my-plugin")');if(YQ(t)){let o=CM(t);if(!xM(o))throw new Error(`could not resolve plugin source: "${t}" looks like a local path but does not exist on disk`);return{type:"local",path:o}}if(zQ.test(t))return{type:"git",url:t};let n=JQ.exec(t);if(n&&n[1]&&n[2])return{type:"marketplace-ref",marketplace:n[1],plugin:n[2]};let r=VQ.exec(t);if(r&&r[1]&&r[2]){let o=r[1],i=r[2];return{type:"github",owner:o,repo:i,url:`https://github.com/${o}/${i}.git`}}if(xM(t))return{type:"local",path:CM(t)};throw new Error(`could not resolve plugin source: "${t}". Use a git URL (https://\u2026/repo.git), GitHub shorthand (owner/repo), or a local path to a directory that exists on disk.`)}function YQ(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("~")||e.startsWith("/")}function CM(e){let t=Ki(e);return qQ(t)?t:_M(process.cwd(),t)}var zQ,VQ,JQ,Da=k(()=>{"use strict";zQ=/^(?:https?:\/\/|git:\/\/|ssh:\/\/|git\+ssh:\/\/|file:\/\/|git@[^:]+:)/,VQ=/^([a-zA-Z0-9][a-zA-Z0-9_.-]*)\/([a-zA-Z0-9][a-zA-Z0-9._-]*?)(?:\.git)?$/,JQ=/^([a-zA-Z0-9][a-zA-Z0-9_.-]*):([a-zA-Z0-9][a-zA-Z0-9_.-]*)$/});import{basename as XQ,dirname as QQ,join as gk,relative as ZQ,resolve as Fa,sep as Eu}from"path";import{homedir as Ge}from"os";function PM(e){let t=Fa(e);return gk(je(QQ(t)),XQ(t))}function yk(e){return e?e.split(":").map(t=>t.trim()).filter(Boolean).map(t=>t==="~"||t.startsWith("~/")?Ki(t.replace(/^~\/+/,"~/")):t).map(t=>Fa(t)):[]}function t7(){try{return[je(Fa(gk(Te(),"config")))]}catch(e){return pr(e),[]}}function n7(){try{let e=Te();return Fr.filter(t=>t.startsWith(IM)).map(t=>PM(gk(e,t.slice(IM.length))))}catch(e){return pr(e),[]}}function MM(){let e=`${T.AFK_READ_DENYLIST??""}\0${T.AFK_HOME??""}`;if(Ru&&Ru.key===e)return Ru;let t=yk(T.AFK_READ_DENYLIST).map(s=>je(s)).filter(Boolean),n=hk.map(s=>({source:s,root:je(Fa(s))})),r=t7(),o=[...new Set([...n.map(({root:s})=>s),...r])],i=n.filter(({source:s,root:a})=>s!==e7||!r.includes(a)).map(({root:s})=>s);return Ru={key:e,builtins:o,extras:t,allow:[...new Set([...EM(Fr.map(s=>({rel:s,resolved:PM(`${Ge()}/${s}`)})),n),...fk(n7(),i)])]},Ru}function bk(){let{builtins:e,extras:t}=MM();return[...e,...t]}function OM(e){let t=je(Fa(e));return bk().filter(n=>n!==t&&Oa(n,t,n)).map(n=>(n.startsWith(t+Eu)?ZQ(t,n):n.split(Eu).slice(t.split(Eu).length).join(Eu)).split(Eu).join("/"))}function $t(e){let t=je(Fa(e)),{builtins:n,extras:r,allow:o}=MM();for(let i of r)if(Oa(t,i))return{denied:!0,matched:i};if(o.includes(t))return{denied:!1};for(let i of n)if(Oa(t,i))return{denied:!0,matched:i};return{denied:!1}}var hk,Fr,e7,fDe,Ru,IM,Lr=k(()=>{"use strict";W();Wi();G();Tu();RM();gf();Da();hk=[`${Ge()}/.ssh`,`${Ge()}/.aws`,`${Ge()}/.gnupg`,`${Ge()}/.config/gcloud`,`${Ge()}/.afk/config`,`${Ge()}/.npmrc`,`${Ge()}/.docker/config.json`,`${Ge()}/.git-credentials`,`${Ge()}/.netrc`,`${Ge()}/.config/gh/hosts.yml`,`${Ge()}/.kube/config`,"/etc/shadow","/etc/sudoers","/private/etc/master.passwd",`${Ge()}/.password-store`,`${Ge()}/Library/Application Support/Google/Chrome`,`${Ge()}/Library/Application Support/Chromium`,`${Ge()}/Library/Application Support/BraveSoftware`,`${Ge()}/Library/Application Support/Microsoft Edge`,`${Ge()}/Library/Application Support/Arc`,`${Ge()}/Library/Application Support/Firefox`],Fr=[".afk/config/mcp.json",".ssh/config",".ssh/known_hosts"],e7=`${Ge()}/.afk/config`,fDe=Fr.map(e=>`${Ge()}/${e}`);IM=".afk/"});import Gi from"path";import{realpathSync as r7}from"fs";function cn(e){try{return r7.native(e)}catch{let t=Gi.dirname(e),n=Gi.basename(e);return t===e?e:Gi.join(cn(t),n)}}function o7(e){let t=$M.get(e);if(t!==void 0)return t;let n=cn(e);return $M.set(e,n),n}function DM(e,t,n,r){let o=t?.resolveBase??t?.cwd??r,i=Gi.isAbsolute(e)?e:Gi.resolve(o??process.cwd(),e);if(t?.allowAll===!0)return{restricted:!1,resolved:i,roots:[]};if(o===void 0)return{restricted:!1,resolved:i,roots:[]};let s=cn(i),a=n==="read"?t?.readRoots??[o]:t?.writeRoots??[o];for(let l of a){let c=o7(l),u=Gi.relative(c,s);if(!u.startsWith("..")&&!Gi.isAbsolute(u))return{restricted:!1,resolved:i,roots:a}}return{restricted:!0,resolved:i,roots:a}}function Dt(e,t,n="read",r){let{restricted:o,resolved:i,roots:s}=DM(e,t,n,r);if(n==="read"){let a=$t(i);if(a.denied)throw new Error(`Path \`${e}\` is a protected credential/secret path (read-denylist entry: \`${a.matched}\`) and cannot be read.`)}if(o){let a=s.map(c=>`\`${c}\``).join(", "),l=n==="read"?"read roots":"write roots";throw new Error(`Path \`${e}\` is outside the allowed ${l} [${a}].`)}return i}function xu(e,t,n="read",r){return DM(e,t,n,r)}function FM(e){let t=new Set,n=[];for(let r of e.split(/\s+/)){if(r.length===0)continue;let o=r.replace(/^\d*[<>|&]+/,"").replace(/^['"]/,"").replace(/['";,)]+$/,"");if(o.length===0)continue;let i=o.startsWith("/"),s=o==="~"||o.startsWith("~/");!i&&!s||t.has(o)||(t.add(o),n.push(o))}return n}var $M,un=k(()=>{"use strict";Lr();$M=new Map});import{spawn as i7}from"child_process";import s7 from"os";function a7(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e;if(typeof t.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(t.timeout_ms<0||t.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=t.timeout_ms}return{command:t.command,timeout_ms:n}}function bf(e,t){let n=!1,r=!1;function o(){n||e==="bypassPermissions"&&(n=!0,console.warn("[security] bash handler: shell=true with bypassPermissions \u2014 all shell metacharacters are interpreted without confirmation. Migrate to execFile to eliminate this risk (tracked: C4)."))}function i(s,a){if(r)return;let l=a.resolveBase??a.cwd??t,c=s7.homedir(),u=[];for(let d of FM(s)){let m=d==="~"?c:d.startsWith("~/")?c+d.slice(1):d,f=xu(m,a,"write",l);f.restricted&&u.push(f.resolved)}u.length!==0&&(r=!0,console.warn(`[security] bash: command references path(s) outside writeRoots: ${u.join(", ")} \u2014 bash containment is best-effort (tracked C4); use file tools for contained writes.`),Me({event:"tool.bash_path_escape",tool:"bash",restricted_count:u.length,mode:"write"}))}return async(s,a,l)=>{let{command:c,timeout_ms:u}=a7(s);if(a.aborted)return{content:"Command aborted",isError:!0};if(o(),l!==void 0)try{i(c,l)}catch{}return new Promise(d=>{let m=!1;function f(x){m||(m=!0,clearTimeout(h),a.removeEventListener("abort",E),d(x))}let g=i7(c,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...(l?.resolveBase??l?.cwd??t)!==void 0?{cwd:l?.resolveBase??l?.cwd??t}:{},...l?.env!==void 0?{env:{...process.env,...l.env}}:{}});g.unref();let h=setTimeout(()=>{g.pid!==void 0&&process.kill(-g.pid,"SIGKILL"),f({content:`Command timed out after ${u}ms`,isError:!0})},u),y="",b="",w=0,v=!1;function S(x){if(v||m||w<8e6)return;v=!0,console.warn(`[bash] overflow kill: stream=${x} totalBytes=${w} command="${c}"`),Me({event:"tool.overflow_kill",tool:"bash",total_bytes:w,stream:x}),g.kill("SIGKILL");let D=dr((y+b).trimEnd()),I=sk(D)??void 0,A=$r(D,1e5)+Xm;f({content:A,truncated:!0,...I!==void 0?{testResult:I}:{}})}g.stdout.on("data",x=>{let D=8e6-w,I=x.length<=D?x:x.subarray(0,Math.max(0,D));w+=I.length,y+=I.toString("utf8"),S("stdout")}),g.stderr.on("data",x=>{let D=8e6-w,I=x.length<=D?x:x.subarray(0,Math.max(0,D));w+=I.length,b+=I.toString("utf8"),S("stderr")});let E=()=>{g.pid!==void 0&&process.kill(-g.pid,"SIGKILL"),f({content:"Command aborted",isError:!0})};a.addEventListener("abort",E),a.aborted&&E(),g.on("close",x=>{if(a.aborted){f({content:"Command aborted",isError:!0});return}if(x!==null&&x!==0){let C=Ro(b.trimEnd()||y.trimEnd());f({content:`Command exited with code ${x}${C.content?`
|
|
182
|
+
`;await aQ(t,r,{flag:"a"})}catch{}}var Dn=k(()=>{"use strict";W();G()});function kQ(e){let t=e.match(pQ);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"vitest",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function TQ(e){let t=e.match(mQ);if(!t)return null;let n=parseInt(t[1]??"0",10);return{runner:"jest",passed:parseInt(t[2]??"0",10),failed:n}}function EQ(e){let t=e.match(fQ);if(!t)return null;if(t[2]!==void 0){let n=parseInt(t[2],10),r=parseInt(t[1]??"0",10);return{runner:"pytest",passed:n,failed:r}}return t[4]!==void 0?{runner:"pytest",passed:parseInt(t[4],10),failed:0}:null}function RQ(e){let t=e.match(gQ);if(!t)return null;let n=parseInt(t[1]??"0",10),r=e.match(hQ),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function xQ(e){let t=[...e.matchAll(yQ)];if(t.length===0)return null;let n=0,r=0;for(let o of t)o[1]==="ok"?n++:o[1]==="FAIL"&&r++;return{runner:"go-test",passed:n,failed:r}}function AQ(e){let t=e.match(bQ);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"cargo",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function CQ(e){let t=e.match(wQ);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10);return{runner:"rspec",passed:n-r,failed:r}}function _Q(e){let t=e.match(SQ);if(t)return{runner:"phpunit",passed:parseInt(t[1]??"0",10),failed:0};let n=e.match(vQ);if(n){let r=parseInt(n[1]??"0",10),o=parseInt(n[2]??"0",10);return{runner:"phpunit",passed:r-o,failed:o}}return null}function sk(e){return kQ(e)??TQ(e)??EQ(e)??RQ(e)??xQ(e)??AQ(e)??CQ(e)??_Q(e)??null}var pQ,mQ,fQ,gQ,hQ,yQ,bQ,wQ,SQ,vQ,hM=k(()=>{"use strict";pQ=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,mQ=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,fQ=/={3,}\s*(?:(\d+)\s+failed,\s*)?(\d+)\s+passed(?:,\s*(\d+)\s+warning)?.*in\s+[\d.]+s\s*={3,}|={3,}\s*(\d+)\s+passed.*in\s+[\d.]+s\s*={3,}/,gQ=/(\d+)\s+passing/,hQ=/(\d+)\s+failing/,yQ=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,bQ=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,wQ=/(\d+) examples?, (\d+) failures?/,SQ=/OK \((\d+) tests?/,vQ=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/});function Dr(e){return e.replace(yM,"").replace(IQ," ").trim()}function dr(e){return e.replace(yM,"")}var yM,IQ,Ao=k(()=>{"use strict";yM=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,IQ=/[\x00-\x1F\x7F-\x9F]/g});import{statSync as PQ}from"node:fs";function ku(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.code==="ENOENT"&&typeof t.syscall=="string"&&t.syscall.startsWith("spawn")}function MQ(e){if(e===void 0)return!1;try{return PQ(e),!1}catch{return!0}}function Ma(e,t){let n=e instanceof Error?e.message:typeof e?.message=="string"?String(e.message):String(e);return ku(e)&&MQ(t)?`working directory does not exist: ${t} (deleted worktree?) \u2014 underlying: ${n}`:n}var ak=k(()=>{"use strict"});function pr(e){if(bM)return;bM=!0;let t=e instanceof Error?e.message:String(e);console.warn(`[afk-home] Malformed AFK home/state env var ignored while deriving the credential floor: ${t}. The relocated tree is NOT protected \u2014 the default ~/.afk entries still apply. Fix the env var to restore coverage.`)}var bM,Tu=k(()=>{"use strict";bM=!1});import{statSync as ck}from"node:fs";import{homedir as OQ}from"node:os";import{basename as $Q,dirname as SM,join as DQ}from"node:path";function vM(e){return typeof e=="object"&&e!==null&&"code"in e?String(e.code):void 0}function FQ(e){let t=$Q(e),n=t===t.toLowerCase()?t.toUpperCase():t.toLowerCase();if(n===t)return;let r;try{r=ck(e)}catch{return}let o=lk.get(r.dev);if(o!==void 0)return o;try{let i=ck(DQ(SM(e),n)),s=r.dev===i.dev&&r.ino===i.ino;return lk.set(r.dev,s),s}catch(i){let s=vM(i);return s==="ENOENT"||s==="ENOTDIR"?(lk.set(r.dev,!1),!1):void 0}}function kM(e=OQ()){if(wM!==void 0)return wM;let t=e;for(;;)try{return ck(t),FQ(t)??!0}catch(n){let r=vM(n);if(r!=="ENOENT"&&r!=="ENOTDIR")return!0;let o=SM(t);if(o===t)return!0;t=o}}function Oa(e,t,n=t){if(e===t||e.startsWith(t+"/"))return!0;if(!kM(n))return!1;let r=e.toLowerCase(),o=t.toLowerCase();return r===o||r.startsWith(o+"/")}function uk(e,t){return e.includes(t)?!0:kM(t)?e.toLowerCase().includes(t.toLowerCase()):!1}var wM,lk,gf=k(()=>{"use strict";lk=new Map});import{realpathSync as TM}from"fs";import{dirname as LQ,resolve as Hi,join as dk}from"path";import{homedir as Co}from"os";function BQ(){let e=[];try{let t=Te();e.push(Ue(Hi(dk(t,"config")))),e.push(Ue(Hi(dk(t,"state"))))}catch(t){pr(t)}try{e.push(Ue(Hi(me())))}catch(t){pr(t)}return e}function pk(){let e=T.AFK_WRITE_DENYLIST,t=e?e.split(":").map(r=>Ue(Hi(r))).filter(Boolean):[];return[...[...new Set([...NQ.map(r=>Ue(Hi(r))),...BQ()])],...t]}function Ue(e){let t=Hi(e);try{return TM(t)}catch{}let n=[],r=t;for(let o=0;o<64;o++){let i=LQ(r);if(i===r)break;n.unshift(r.slice(i.length+1)),r=i;try{let s=TM(r);return dk(s,...n)}catch{}}return t}function hf(e,t="write_file"){let n=Ue(Hi(e));for(let r of pk())if(Oa(n,r))throw new Error(`${t}: refusing to write to protected path: ${n} (matches denylist entry: ${r})`)}var NQ,Wi=k(()=>{"use strict";W();G();Tu();gf();NQ=[`${Co()}/.ssh`,`${Co()}/.aws`,`${Co()}/.gnupg`,`${Co()}/.config/gcloud`,"/etc","/System","/private/etc","/usr/local/etc",`${Co()}/.afk/config`,`${Co()}/.afk/state`,`${Co()}/.npmrc`,`${Co()}/.docker/config.json`]});import{isAbsolute as UQ,relative as jQ,sep as HQ}from"node:path";import{homedir as mk}from"node:os";function WQ(e,t){let n=jQ(t,e);return n===""||n!==".."&&!n.startsWith(`..${HQ}`)&&!UQ(n)}function fk(e,t){return e.filter(n=>!t.some(r=>WQ(n,r)))}function KQ(e,t){return e.filter(({source:n})=>n!==t).map(({root:n})=>n)}function EM(e,t){return e.flatMap(({rel:n,resolved:r})=>fk([r],KQ(t,GQ[n])))}var GQ,RM=k(()=>{"use strict";GQ={".afk/config/mcp.json":`${mk()}/.afk/config`,".ssh/config":`${mk()}/.ssh`,".ssh/known_hosts":`${mk()}/.ssh`}});import{existsSync as xM}from"fs";import{isAbsolute as qQ,resolve as _M}from"path";import{homedir as AM}from"os";function Ki(e){return e==="~"?AM():e.startsWith("~/")?_M(AM(),e.slice(2)):e}function yf(e){if(!e.startsWith("https://"))throw new Error(`Plugin source must use https:// (got: ${e}). git://, http://, ssh://, file://, and git@ are rejected to avoid downgrade attacks and unauthenticated clones.`)}function $a(e){let t=e.trim();if(!t)throw new Error('plugin source is required (examples: "owner/repo", "https://github.com/owner/repo.git", "./my-plugin")');if(YQ(t)){let o=CM(t);if(!xM(o))throw new Error(`could not resolve plugin source: "${t}" looks like a local path but does not exist on disk`);return{type:"local",path:o}}if(zQ.test(t))return{type:"git",url:t};let n=JQ.exec(t);if(n&&n[1]&&n[2])return{type:"marketplace-ref",marketplace:n[1],plugin:n[2]};let r=VQ.exec(t);if(r&&r[1]&&r[2]){let o=r[1],i=r[2];return{type:"github",owner:o,repo:i,url:`https://github.com/${o}/${i}.git`}}if(xM(t))return{type:"local",path:CM(t)};throw new Error(`could not resolve plugin source: "${t}". Use a git URL (https://\u2026/repo.git), GitHub shorthand (owner/repo), or a local path to a directory that exists on disk.`)}function YQ(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("~")||e.startsWith("/")}function CM(e){let t=Ki(e);return qQ(t)?t:_M(process.cwd(),t)}var zQ,VQ,JQ,Da=k(()=>{"use strict";zQ=/^(?:https?:\/\/|git:\/\/|ssh:\/\/|git\+ssh:\/\/|file:\/\/|git@[^:]+:)/,VQ=/^([a-zA-Z0-9][a-zA-Z0-9_.-]*)\/([a-zA-Z0-9][a-zA-Z0-9._-]*?)(?:\.git)?$/,JQ=/^([a-zA-Z0-9][a-zA-Z0-9_.-]*):([a-zA-Z0-9][a-zA-Z0-9_.-]*)$/});import{basename as XQ,dirname as QQ,join as gk,relative as ZQ,resolve as Fa,sep as Eu}from"path";import{homedir as Ge}from"os";function PM(e){let t=Fa(e);return gk(Ue(QQ(t)),XQ(t))}function yk(e){return e?e.split(":").map(t=>t.trim()).filter(Boolean).map(t=>t==="~"||t.startsWith("~/")?Ki(t.replace(/^~\/+/,"~/")):t).map(t=>Fa(t)):[]}function t7(){try{return[Ue(Fa(gk(Te(),"config")))]}catch(e){return pr(e),[]}}function n7(){try{let e=Te();return Fr.filter(t=>t.startsWith(IM)).map(t=>PM(gk(e,t.slice(IM.length))))}catch(e){return pr(e),[]}}function MM(){let e=`${T.AFK_READ_DENYLIST??""}\0${T.AFK_HOME??""}`;if(Ru&&Ru.key===e)return Ru;let t=yk(T.AFK_READ_DENYLIST).map(s=>Ue(s)).filter(Boolean),n=hk.map(s=>({source:s,root:Ue(Fa(s))})),r=t7(),o=[...new Set([...n.map(({root:s})=>s),...r])],i=n.filter(({source:s,root:a})=>s!==e7||!r.includes(a)).map(({root:s})=>s);return Ru={key:e,builtins:o,extras:t,allow:[...new Set([...EM(Fr.map(s=>({rel:s,resolved:PM(`${Ge()}/${s}`)})),n),...fk(n7(),i)])]},Ru}function bk(){let{builtins:e,extras:t}=MM();return[...e,...t]}function OM(e){let t=Ue(Fa(e));return bk().filter(n=>n!==t&&Oa(n,t,n)).map(n=>(n.startsWith(t+Eu)?ZQ(t,n):n.split(Eu).slice(t.split(Eu).length).join(Eu)).split(Eu).join("/"))}function $t(e){let t=Ue(Fa(e)),{builtins:n,extras:r,allow:o}=MM();for(let i of r)if(Oa(t,i))return{denied:!0,matched:i};if(o.includes(t))return{denied:!1};for(let i of n)if(Oa(t,i))return{denied:!0,matched:i};return{denied:!1}}var hk,Fr,e7,fDe,Ru,IM,Lr=k(()=>{"use strict";W();Wi();G();Tu();RM();gf();Da();hk=[`${Ge()}/.ssh`,`${Ge()}/.aws`,`${Ge()}/.gnupg`,`${Ge()}/.config/gcloud`,`${Ge()}/.afk/config`,`${Ge()}/.npmrc`,`${Ge()}/.docker/config.json`,`${Ge()}/.git-credentials`,`${Ge()}/.netrc`,`${Ge()}/.config/gh/hosts.yml`,`${Ge()}/.kube/config`,"/etc/shadow","/etc/sudoers","/private/etc/master.passwd",`${Ge()}/.password-store`,`${Ge()}/Library/Application Support/Google/Chrome`,`${Ge()}/Library/Application Support/Chromium`,`${Ge()}/Library/Application Support/BraveSoftware`,`${Ge()}/Library/Application Support/Microsoft Edge`,`${Ge()}/Library/Application Support/Arc`,`${Ge()}/Library/Application Support/Firefox`],Fr=[".afk/config/mcp.json",".ssh/config",".ssh/known_hosts"],e7=`${Ge()}/.afk/config`,fDe=Fr.map(e=>`${Ge()}/${e}`);IM=".afk/"});import Gi from"path";import{realpathSync as r7}from"fs";function cn(e){try{return r7.native(e)}catch{let t=Gi.dirname(e),n=Gi.basename(e);return t===e?e:Gi.join(cn(t),n)}}function o7(e){let t=$M.get(e);if(t!==void 0)return t;let n=cn(e);return $M.set(e,n),n}function DM(e,t,n,r){let o=t?.resolveBase??t?.cwd??r,i=Gi.isAbsolute(e)?e:Gi.resolve(o??process.cwd(),e);if(t?.allowAll===!0)return{restricted:!1,resolved:i,roots:[]};if(o===void 0)return{restricted:!1,resolved:i,roots:[]};let s=cn(i),a=n==="read"?t?.readRoots??[o]:t?.writeRoots??[o];for(let l of a){let c=o7(l),u=Gi.relative(c,s);if(!u.startsWith("..")&&!Gi.isAbsolute(u))return{restricted:!1,resolved:i,roots:a}}return{restricted:!0,resolved:i,roots:a}}function Dt(e,t,n="read",r){let{restricted:o,resolved:i,roots:s}=DM(e,t,n,r);if(n==="read"){let a=$t(i);if(a.denied)throw new Error(`Path \`${e}\` is a protected credential/secret path (read-denylist entry: \`${a.matched}\`) and cannot be read.`)}if(o){let a=s.map(c=>`\`${c}\``).join(", "),l=n==="read"?"read roots":"write roots";throw new Error(`Path \`${e}\` is outside the allowed ${l} [${a}].`)}return i}function xu(e,t,n="read",r){return DM(e,t,n,r)}function FM(e){let t=new Set,n=[];for(let r of e.split(/\s+/)){if(r.length===0)continue;let o=r.replace(/^\d*[<>|&]+/,"").replace(/^['"]/,"").replace(/['";,)]+$/,"");if(o.length===0)continue;let i=o.startsWith("/"),s=o==="~"||o.startsWith("~/");!i&&!s||t.has(o)||(t.add(o),n.push(o))}return n}var $M,un=k(()=>{"use strict";Lr();$M=new Map});import{spawn as i7}from"child_process";import s7 from"os";function a7(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e;if(typeof t.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(t.timeout_ms<0||t.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=t.timeout_ms}return{command:t.command,timeout_ms:n}}function bf(e,t){let n=!1,r=!1;function o(){n||e==="bypassPermissions"&&(n=!0,console.warn("[security] bash handler: shell=true with bypassPermissions \u2014 all shell metacharacters are interpreted without confirmation. Migrate to execFile to eliminate this risk (tracked: C4)."))}function i(s,a){if(r)return;let l=a.resolveBase??a.cwd??t,c=s7.homedir(),u=[];for(let d of FM(s)){let m=d==="~"?c:d.startsWith("~/")?c+d.slice(1):d,f=xu(m,a,"write",l);f.restricted&&u.push(f.resolved)}u.length!==0&&(r=!0,console.warn(`[security] bash: command references path(s) outside writeRoots: ${u.join(", ")} \u2014 bash containment is best-effort (tracked C4); use file tools for contained writes.`),Me({event:"tool.bash_path_escape",tool:"bash",restricted_count:u.length,mode:"write"}))}return async(s,a,l)=>{let{command:c,timeout_ms:u}=a7(s);if(a.aborted)return{content:"Command aborted",isError:!0};if(o(),l!==void 0)try{i(c,l)}catch{}return new Promise(d=>{let m=!1;function f(x){m||(m=!0,clearTimeout(h),a.removeEventListener("abort",E),d(x))}let g=i7(c,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...(l?.resolveBase??l?.cwd??t)!==void 0?{cwd:l?.resolveBase??l?.cwd??t}:{},...l?.env!==void 0?{env:{...process.env,...l.env}}:{}});g.unref();let h=setTimeout(()=>{g.pid!==void 0&&process.kill(-g.pid,"SIGKILL"),f({content:`Command timed out after ${u}ms`,isError:!0})},u),y="",b="",w=0,v=!1;function S(x){if(v||m||w<8e6)return;v=!0,console.warn(`[bash] overflow kill: stream=${x} totalBytes=${w} command="${c}"`),Me({event:"tool.overflow_kill",tool:"bash",total_bytes:w,stream:x}),g.kill("SIGKILL");let D=dr((y+b).trimEnd()),I=sk(D)??void 0,A=$r(D,1e5)+Xm;f({content:A,truncated:!0,...I!==void 0?{testResult:I}:{}})}g.stdout.on("data",x=>{let D=8e6-w,I=x.length<=D?x:x.subarray(0,Math.max(0,D));w+=I.length,y+=I.toString("utf8"),S("stdout")}),g.stderr.on("data",x=>{let D=8e6-w,I=x.length<=D?x:x.subarray(0,Math.max(0,D));w+=I.length,b+=I.toString("utf8"),S("stderr")});let E=()=>{g.pid!==void 0&&process.kill(-g.pid,"SIGKILL"),f({content:"Command aborted",isError:!0})};a.addEventListener("abort",E),a.aborted&&E(),g.on("close",x=>{if(a.aborted){f({content:"Command aborted",isError:!0});return}if(x!==null&&x!==0){let C=Ro(b.trimEnd()||y.trimEnd());f({content:`Command exited with code ${x}${C.content?`
|
|
183
183
|
`+C.content:""}`,isError:!0,...C.truncated?{truncated:!0}:{}});return}if(v)return;let D=dr((y+b).trimEnd()),I=sk(D)??void 0,A=Ro(D);f({content:A.content,...A.truncated?{truncated:!0}:{},...I!==void 0?{testResult:I}:{}})}),g.on("error",x=>{let D=l?.resolveBase??l?.cwd??t,I;if(D===void 0&&ku(x))try{let A=process.cwd();I=Ma(x,A)}catch{I=`working directory does not exist (process cwd deleted \u2014 deleted worktree?) \u2014 underlying: ${x.message}`}else I=Ma(x,D);f({content:`Failed to execute: ${I}`,isError:!0})})})}}var LM,NM=k(()=>{"use strict";Dn();hM();Ao();ak();Li();un();LM=bf("default")});import{promises as l7}from"fs";function wk(e){return(t,n,r)=>c7(t,n,r,e)}var c7,BM,UM=k(()=>{"use strict";un();c7=async(e,t,n,r)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let o=e,i=o.file_path,s=o.offset??1,a=o.limit??2e3;if(typeof i!="string")return{content:"Invalid input: file_path must be a string",isError:!0};if(typeof s!="number"||s<1)return{content:"Invalid input: offset must be a positive number",isError:!0};if(typeof a!="number"||a<1)return{content:"Invalid input: limit must be a positive number",isError:!0};let l;try{l=Dt(i,n,"read",r)}catch(c){return{content:c instanceof Error?c.message:String(c),isError:!0}}try{let c=await l7.readFile(l),u=Math.min(8192,c.length);for(let v=0;v<u;v++)if(c[v]===0)return{content:`File appears to be binary: ${l}`,isError:!0};let d=c.toString("utf-8");if(d.length===0)return{content:""};let m=d.split(`
|
|
184
184
|
`),f=Math.max(0,s-1),g=Math.min(m.length,f+a),h=m.slice(f,g),y=m.length;if(h.length===0)return{content:`... (offset ${s} is past end of file \u2014 file has ${y} lines)`};let b=String(y).length,w=h.map((v,S)=>{let E=f+S+1;return`${String(E).padStart(b," ")} ${v}`}).join(`
|
|
185
185
|
`);if(h.length<y){let v=f+1,S=f+h.length,E=S<y?` \u2014 pass offset=${S+1} to continue`:"";return{content:`${w}
|
|
@@ -267,7 +267,7 @@ ${o}`,paths:[t,n]}:o!==null?i={content:o,paths:[n]}:r!==null?i={content:r,paths:
|
|
|
267
267
|
|
|
268
268
|
`).trim()}function yee(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}async function cO(e,t){let{JSDOM:n,Readability:r,turndown:o}=await hee(),s=new n(e,{url:t}).window.document,a=(s.title??"").trim(),l=(()=>{try{let m=s.cloneNode(!0);return new r(m).parse()}catch{return null}})();if(l&&typeof l.content=="string"&&l.content.trim().length>0){let m=lO(o.turndown(l.content)),f=(l.title??"").trim()||a,g=typeof l.length=="number"&&l.length>0?l.length:(l.textContent??"").replace(/\s+/g," ").trim().length;return{title:f,markdown:m,textLength:g,usedFallback:!1}}let c=s.body,u=c?.innerHTML??"",d=lO(o.turndown(u));return{title:a,markdown:d,textLength:yee(c),usedFallback:!0}}var Wk,uO=k(()=>{"use strict";Wk=null});function wee(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 dO(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function See(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 pO(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??wee,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(!bee.has(d.status)||u===o)return d;let m=See(d,s)??dO(u,i,s);B("[web/retryFetch] retrying",{url:t,attempt:u,status:d.status,waitMs:m}),await d.body?.cancel().catch(()=>{}),await a(m,l)}catch(d){if(l?.aborted||(c=d,u===o))throw d;let m=dO(u,i,s);B("[web/retryFetch] retrying after error",{url:t,attempt:u,waitMs:m}),await a(m,l)}}throw c??new Error("retryFetch: exhausted without a result")}var bee,mO=k(()=>{"use strict";ue();bee=new Set([429,502,503,504])});import{BlockList as vee,isIP as Gk}from"node:net";import{lookup as kee}from"node:dns/promises";import{Agent as Tee}from"undici";function gO(){let e=T.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return e==="1"||e==="true"}function Aee(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function Kk(e){let t=Gk(e);return t===0?!1:xee.check(e,t===4?"ipv4":"ipv6")}async function hO(e){return kee(e,{all:!0,verbatim:!0})}async function qk(e,t={}){if(t.allowPrivateHosts??gO())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=Aee(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(Gk(r)!==0)return Kk(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let i=t.lookupFn??hO,s;try{s=await i(r)}catch{return{allowed:!0}}for(let a of s)if(Kk(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function ju(e,t={}){let n=await qk(e,t);if(!n.allowed)throw new Ln(n.reason)}async function Bf(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<=fO;s++){await ju(i,o);let a={...n,redirect:"manual",...e===globalThis.fetch&&!(r.allowPrivateHosts??gO())?{dispatcher:Cee}:{}},l=await pO(e,i,a,r.retry??{});if(!_ee.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 Ln(`too many redirects (>${fO}) starting from ${t}`)}var Eee,Ree,xee,Ln,Cee,fO,_ee,zk=k(()=>{"use strict";W();mO();Eee=[["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]],Ree=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],xee=(()=>{let e=new vee;for(let[t,n]of Eee)e.addSubnet(t,n,"ipv4");for(let[t,n]of Ree)e.addSubnet(t,n,"ipv6");return e})(),Ln=class extends Error{constructor(t){super(t),this.name="EgressBlockedError"}};Cee=new Tee({connect:{lookup(e,t,n){hO(e).then(r=>{let o=r.find(s=>Kk(s.address));if(o!==void 0){n(new Ln(`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,Gk(i.address))},r=>n(r,"",0))}}});fO=20,_ee=new Set([301,302,303,307,308])});import{readFileSync as Iee}from"node:fs";import{join as Pee}from"path";function Mee(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function yO(e,t){return Mee(t).test(e)}function Dee(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(Oee.has(t))return!0;if($ee.has(t))return!1}return!1}function bO(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function Fee(e){if(e===void 0||e===""||e==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${e}`)}function wO(e){let t=e===void 0||e.trim()===""?"default":e.trim();return Jc(t),t}function Lee(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function Nee(e){try{return Iee(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function Bee(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return typeof t.defaultProfile=="string"&&(n.defaultProfile=wO(t.defaultProfile)),n}function SO(e){let t=e?.env??T,n=e?.readFileSync??Nee,r=e?.surface??t.AGENT_SURFACE,o=Dee(t.AFK_BROWSER_HEADLESS,r),i=bO(t.AFK_BROWSER_ALLOWED_DOMAINS),s=bO(t.AFK_BROWSER_BLOCKED_DOMAINS),a=Lee(t.AFK_BROWSER_DOM_SNAPSHOTS),l=Fee(t.AFK_BROWSER_BACKEND),c=wO(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,m=d!==void 0&&d.trim()!==""?d.trim():Pee(Pn(),"browser.json"),f=n(m);if(f===void 0)return u;let g;try{g=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${m}: ${String(y)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${m} must be a JSON object`);let h=Bee(u,g);return h.configPath=m,h}function Uf(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(yO(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>yO(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Oee,$ee,jf=k(()=>{"use strict";W();G();Oee=new Set(["daemon","subagent","telegram","afk"]),$ee=new Set(["repl","interactive","cli"])});import{existsSync as Uee,readFileSync as jee}from"node:fs";import{createRequire as Hee}from"node:module";import{dirname as Wee,join as Kee}from"node:path";function TO(e){if(typeof e=="string")return e;let t=[],n=e;for(let r=0;r<qee&&n instanceof Error;r++)t.push(n.message),n=n.cause;return t.length>0?t.join(" | "):String(e)}function Lt(e){let t=TO(e);return kO.some(n=>t.includes(n))}function zee(){try{let t=Hee(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(jee(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=Kee(Wee(t),o);return Uee(i)?`node ${/\s/.test(i)?`"${i}"`:i} install chromium`:void 0}catch{return}}function Hu(){return vO??=zee()??Gee,vO}function Vk(e){return e.includes("install chromium")}function pn(e,t){let n=TO(e),r=t?.latched===!0?` ${Vee}`:"";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: ${Hu()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${Hu()}). Or pick a different tool.${r}`}function Wu(e,t,n=!1){if(!Lt(e))return e;let r=e instanceof Error?e.message:String(e);return new Error(`${r}
|
|
269
269
|
|
|
270
|
-
${pn(e,{headless:t,latched:n})}`,{cause:e})}var kO,Gee,qee,vO,Vee,Hf=k(()=>{"use strict";kO=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],Gee="pnpm exec playwright install chromium",qee=4;Vee="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 Vi from"node:fs";import Wf from"node:path";import{randomBytes as Jee}from"node:crypto";import{chromium as Yee}from"playwright";function Xee(){try{return"5.100.3"}catch{}try{let e=Wf.resolve(import.meta.dirname,"../../../package.json"),t=Vi.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Qee,Kf,EO=k(()=>{"use strict";Hf();G();ue();Qee=Xee(),Kf=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=Yee.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,this.clearLaunchFailure(),t)).catch(t=>{this.launchPromise=void 0;let n=Wu(t,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),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(m){throw i??m}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/${Qee}`}}loadStorageState(t){let n=Yc(t);try{if(!Vi.existsSync(n))return;let r=JSON.parse(Vi.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=Yc(t);if(!Vi.existsSync(r))return;let o=await n.storageState(),i=Wf.join(Wf.dirname(r),`.${Wf.basename(r)}.${process.pid}.${Jee(4).toString("hex")}.tmp`);Vi.writeFileSync(i,JSON.stringify(o),{mode:384}),Vi.chmodSync(i,384),Vi.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 Zee}from"crypto";function RO(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&ete.test(e.label))}function xO(e){return Zee("sha256").update(e,"utf8").digest("hex").slice(0,8)}function AO(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var ete,Gf=k(()=>{"use strict";ete=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as tte}from"node:crypto";function nte(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function rte(e,t,n){return`el_${tte("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function ote(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function CO(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function IO(e,t){let n=e.role??"",r=e.name??"";_O.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])IO(i,t)}async function ite(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},PO).catch(()=>[])}async function ste(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,m=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:m};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},PO).catch(()=>[])}function ate(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function qf(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=ate(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=ite(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,m,f,g,h]=await Promise.all([s,a,l,c,u]),y,b=!1;d!==null?(y=[],IO(d,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await ste(e)).filter(N=>_O.has(N.role??"")));let w=new Map;for(let P of m){let N=CO(P.name),z=w.get(N);(!z||z.bbox.w===0&&P.bbox.w>0)&&w.set(N,P)}let v=y.map(P=>({ax:P,dom:w.get(CO(P.name??""))})),S=r?v:v.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);S.sort((P,N)=>{let z=P.dom?.bbox.y??0,O=N.dom?.bbox.y??0;if(z!==O)return z-O;let H=P.dom?.bbox.x??0,K=N.dom?.bbox.x??0;return H-K}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let x=S.slice(0,n).map((P,N)=>{let z=P.ax.role??"generic",O=P.ax.name??"",H=rte(z,O,N),K=P.dom?.bbox??{x:0,y:0,w:0,h:0},_=P.dom?.type??null,F=null;P.ax.value!==void 0&&P.ax.value!==null&&(F=String(P.ax.value)),P.ax.checked!==void 0&&(F=String(P.ax.checked)),RO({role:z,kind:_})&&(F="[redacted]");let M={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(M.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(M.selected=P.ax.selected),P.ax.expanded!==void 0&&(M.expanded=P.ax.expanded);let $;P.dom?.testId?$=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&($=`#${P.dom.id}`);let U={id:H,role:z,label:nte(O),kind:_,value:F,state:M,bbox:K};return $!==void 0&&(U.selector=$),U}),D="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?D="loading":P==="interactive"?D="navigating":D="idle"}catch{D="navigating"}D!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=ote(f),A=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:A,url:g,title:h,textSummary:I,interactive:x,status:{httpStatus:t.httpStatus??null,loadingState:D,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var _O,PO,MO=k(()=>{"use strict";Gf();_O=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);PO="a[href], button, input, select, textarea, [role], [tabindex], label"});async function OO(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 Jk(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>OO(e,i)))).filter(o=>o!==null)}async function lte(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 Yk(e,t,n){switch(t.kind){case"element_id":return cte(e,t,n);case"selector":return ute(e,t);case"semantic":return dte(e,t)}}async function cte(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 Jk(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function ute(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 Jk(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function dte(e,t){return t.role!==void 0?pte(e,t.text,t.role):mte(e,t.text,t)}async function pte(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 Jk(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function mte(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 lte(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let m=d.slice(0,5),f=[];for(let h=0;h<m.length;h++){let y=m[h];if(y===void 0)continue;let b=await OO(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,v=0;for(let S=0;S<w.length;S++)v=v*31+w.charCodeAt(S)>>>0;f.push({...b,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var $O=k(()=>{"use strict"});async function Xk(e,t,n,r){let o=e.url();if(o===n)return null;let i=Uf(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 DO=k(()=>{"use strict";jf()});import{randomBytes as fte}from"crypto";import{mkdir as gte,stat as hte,writeFile as yte}from"fs/promises";import{join as Qk}from"path";import{gzip as bte}from"zlib";import{promisify as wte}from"util";function Ste(e){return Qk(er(e),"browser")}function vte(e){return Qk(Ste(e),"screenshots")}function kte(){return new Date().toISOString().replace(/[:.]/g,"-")}function Tte(){return fte(3).toString("hex")}async function Zk(e,t,n){if(t.length>FO)throw new Error(`writeScreenshotSidecar: buffer exceeds ${FO} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=vte(e);await gte(r,{recursive:!0});let o=`${kte()}-${Tte()}-${n}.png`,i=Qk(r,o);await yte(i,t);let{size:s}=await hte(i);return{path:i,bytes:s}}var VNe,FO,LO=k(()=>{"use strict";G();Gf();VNe=wte(bte);FO=5*1024*1024});var BO={};Uc(BO,{PlaywrightProvider:()=>eT});function NO(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 eT,UO=k(()=>{"use strict";EO();MO();$O();jf();DO();LO();eT=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Kf(t)}async open(t){let n=Uf(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 Xk(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 qf(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 qf(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 Yk(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${NO(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(y){c=y}else c=h}let d=await Xk(r,this.config,i,()=>this.close({sessionId:n}));if(d!==null)return d;let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await qf(r,{observationCounter:o.observationCounter,screenshotPath:m,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal,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 Yk(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${NO(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 Zk(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 Zk(n,o,r);return i}catch{return null}}}});var Yi={};Uc(Yi,{__resetBrowserRegistryForTests:()=>Cte,browserProviderActive:()=>xte,closeBrowserProvider:()=>tT,getBrowserProvider:()=>Rte,peekBrowserProvider:()=>Ate});function jO(){Promise.resolve(tT()).then(()=>{process.exit(130)})}function HO(){Promise.resolve(tT()).then(()=>{process.exit(143)})}function WO(){gr=null}function Ete(){zf||(process.on("SIGINT",jO),process.on("SIGTERM",HO),process.on("exit",WO),zf=!0)}function KO(){zf&&(process.removeListener("SIGINT",jO),process.removeListener("SIGTERM",HO),process.removeListener("exit",WO),zf=!1)}async function Rte(e){return gr!==null?gr:(Ji!==null||(Ji=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(UO(),BO)),n=SO(e),r=new t(n);return Ete(),gr=r,Ji=null,r})()),Ji)}async function tT(){if(gr===null)return;let e=gr;gr=null,Ji=null,KO(),await e.shutdown()}function xte(){return gr!==null}function Ate(){return gr}function Cte(){gr=null,Ji=null,KO()}var gr,Ji,zf,Xi=k(()=>{"use strict";jf();gr=null,Ji=null,zf=!1});async function GO(e,t){try{return await cO(e,t)}catch(n){return B("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function $te(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Xi(),Yi));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function qO(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??$te,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s=e,a=null,l=null;try{let u=await Bf(n,e,{headers:Ote,signal:t.signal},o);a=u.status,s=u.url||e;let d=u.headers.get("content-type")??"";if(u.ok){if(Mte.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let m=await u.text();if(Pte.test(d)&&!Ite.test(d))return{title:"",markdown:m.trim(),finalUrl:s,usedRender:!1};if(i=await GO(m,s),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(u){if(t.signal.aborted||u instanceof Ln||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;l=u}if(!(i===null||i.textLength<200)&&i!==null)return{title:i.title,markdown:i.markdown,finalUrl:s,usedRender:!1};try{await ju(e,o);let u=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:m=>ju(m,o)});u.finalUrl!==e&&/^https?:\/\//i.test(u.finalUrl)&&await ju(u.finalUrl,o);let d=await GO(u.html,u.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||d.textLength>=i.textLength)return{title:d.title,markdown:d.markdown,finalUrl:u.finalUrl,usedRender:!0}}catch(u){if(t.signal.aborted||u instanceof Ln)throw u;if(i===null){let d=u instanceof Error?u.message:String(u),m=l instanceof Error?l.message:`HTTP ${a??"error"}`,f=new Error(`web_scrape could not retrieve ${e}: fetch failed (${m}) and render failed (${d}).`);throw f.cause=u,f}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${a??"error"}).`)}var Ite,Pte,Mte,Ote,zO=k(()=>{"use strict";uO();zk();ue();Ite=/(text\/html|application\/xhtml\+xml)/i,Pte=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,Mte=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,Ote={"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 Lte(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(Dte,{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),Fte),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let u=await i.text(),d=Dr(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 VO(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?Lte({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 JO(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
270
|
+
${pn(e,{headless:t,latched:n})}`,{cause:e})}var kO,Gee,qee,vO,Vee,Hf=k(()=>{"use strict";kO=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],Gee="pnpm exec playwright install chromium",qee=4;Vee="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 Vi from"node:fs";import Wf from"node:path";import{randomBytes as Jee}from"node:crypto";import{chromium as Yee}from"playwright";function Xee(){try{return"5.100.4"}catch{}try{let e=Wf.resolve(import.meta.dirname,"../../../package.json"),t=Vi.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Qee,Kf,EO=k(()=>{"use strict";Hf();G();ue();Qee=Xee(),Kf=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=Yee.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,this.clearLaunchFailure(),t)).catch(t=>{this.launchPromise=void 0;let n=Wu(t,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),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(m){throw i??m}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/${Qee}`}}loadStorageState(t){let n=Yc(t);try{if(!Vi.existsSync(n))return;let r=JSON.parse(Vi.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=Yc(t);if(!Vi.existsSync(r))return;let o=await n.storageState(),i=Wf.join(Wf.dirname(r),`.${Wf.basename(r)}.${process.pid}.${Jee(4).toString("hex")}.tmp`);Vi.writeFileSync(i,JSON.stringify(o),{mode:384}),Vi.chmodSync(i,384),Vi.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 Zee}from"crypto";function RO(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&ete.test(e.label))}function xO(e){return Zee("sha256").update(e,"utf8").digest("hex").slice(0,8)}function AO(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var ete,Gf=k(()=>{"use strict";ete=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as tte}from"node:crypto";function nte(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function rte(e,t,n){return`el_${tte("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function ote(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function CO(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function IO(e,t){let n=e.role??"",r=e.name??"";_O.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])IO(i,t)}async function ite(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},PO).catch(()=>[])}async function ste(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,m=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:m};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},PO).catch(()=>[])}function ate(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function qf(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=ate(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=ite(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,m,f,g,h]=await Promise.all([s,a,l,c,u]),y,b=!1;d!==null?(y=[],IO(d,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await ste(e)).filter(N=>_O.has(N.role??"")));let w=new Map;for(let P of m){let N=CO(P.name),z=w.get(N);(!z||z.bbox.w===0&&P.bbox.w>0)&&w.set(N,P)}let v=y.map(P=>({ax:P,dom:w.get(CO(P.name??""))})),S=r?v:v.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);S.sort((P,N)=>{let z=P.dom?.bbox.y??0,O=N.dom?.bbox.y??0;if(z!==O)return z-O;let H=P.dom?.bbox.x??0,K=N.dom?.bbox.x??0;return H-K}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let x=S.slice(0,n).map((P,N)=>{let z=P.ax.role??"generic",O=P.ax.name??"",H=rte(z,O,N),K=P.dom?.bbox??{x:0,y:0,w:0,h:0},_=P.dom?.type??null,F=null;P.ax.value!==void 0&&P.ax.value!==null&&(F=String(P.ax.value)),P.ax.checked!==void 0&&(F=String(P.ax.checked)),RO({role:z,kind:_})&&(F="[redacted]");let M={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(M.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(M.selected=P.ax.selected),P.ax.expanded!==void 0&&(M.expanded=P.ax.expanded);let $;P.dom?.testId?$=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&($=`#${P.dom.id}`);let U={id:H,role:z,label:nte(O),kind:_,value:F,state:M,bbox:K};return $!==void 0&&(U.selector=$),U}),D="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?D="loading":P==="interactive"?D="navigating":D="idle"}catch{D="navigating"}D!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=ote(f),A=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:A,url:g,title:h,textSummary:I,interactive:x,status:{httpStatus:t.httpStatus??null,loadingState:D,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var _O,PO,MO=k(()=>{"use strict";Gf();_O=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);PO="a[href], button, input, select, textarea, [role], [tabindex], label"});async function OO(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 Jk(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>OO(e,i)))).filter(o=>o!==null)}async function lte(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 Yk(e,t,n){switch(t.kind){case"element_id":return cte(e,t,n);case"selector":return ute(e,t);case"semantic":return dte(e,t)}}async function cte(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 Jk(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function ute(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 Jk(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function dte(e,t){return t.role!==void 0?pte(e,t.text,t.role):mte(e,t.text,t)}async function pte(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 Jk(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function mte(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 lte(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let m=d.slice(0,5),f=[];for(let h=0;h<m.length;h++){let y=m[h];if(y===void 0)continue;let b=await OO(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,v=0;for(let S=0;S<w.length;S++)v=v*31+w.charCodeAt(S)>>>0;f.push({...b,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var $O=k(()=>{"use strict"});async function Xk(e,t,n,r){let o=e.url();if(o===n)return null;let i=Uf(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 DO=k(()=>{"use strict";jf()});import{randomBytes as fte}from"crypto";import{mkdir as gte,stat as hte,writeFile as yte}from"fs/promises";import{join as Qk}from"path";import{gzip as bte}from"zlib";import{promisify as wte}from"util";function Ste(e){return Qk(er(e),"browser")}function vte(e){return Qk(Ste(e),"screenshots")}function kte(){return new Date().toISOString().replace(/[:.]/g,"-")}function Tte(){return fte(3).toString("hex")}async function Zk(e,t,n){if(t.length>FO)throw new Error(`writeScreenshotSidecar: buffer exceeds ${FO} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=vte(e);await gte(r,{recursive:!0});let o=`${kte()}-${Tte()}-${n}.png`,i=Qk(r,o);await yte(i,t);let{size:s}=await hte(i);return{path:i,bytes:s}}var VNe,FO,LO=k(()=>{"use strict";G();Gf();VNe=wte(bte);FO=5*1024*1024});var BO={};Uc(BO,{PlaywrightProvider:()=>eT});function NO(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 eT,UO=k(()=>{"use strict";EO();MO();$O();jf();DO();LO();eT=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Kf(t)}async open(t){let n=Uf(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 Xk(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 qf(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 qf(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 Yk(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${NO(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(y){c=y}else c=h}let d=await Xk(r,this.config,i,()=>this.close({sessionId:n}));if(d!==null)return d;let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await qf(r,{observationCounter:o.observationCounter,screenshotPath:m,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal,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 Yk(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${NO(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 Zk(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 Zk(n,o,r);return i}catch{return null}}}});var Yi={};Uc(Yi,{__resetBrowserRegistryForTests:()=>Cte,browserProviderActive:()=>xte,closeBrowserProvider:()=>tT,getBrowserProvider:()=>Rte,peekBrowserProvider:()=>Ate});function jO(){Promise.resolve(tT()).then(()=>{process.exit(130)})}function HO(){Promise.resolve(tT()).then(()=>{process.exit(143)})}function WO(){gr=null}function Ete(){zf||(process.on("SIGINT",jO),process.on("SIGTERM",HO),process.on("exit",WO),zf=!0)}function KO(){zf&&(process.removeListener("SIGINT",jO),process.removeListener("SIGTERM",HO),process.removeListener("exit",WO),zf=!1)}async function Rte(e){return gr!==null?gr:(Ji!==null||(Ji=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(UO(),BO)),n=SO(e),r=new t(n);return Ete(),gr=r,Ji=null,r})()),Ji)}async function tT(){if(gr===null)return;let e=gr;gr=null,Ji=null,KO(),await e.shutdown()}function xte(){return gr!==null}function Ate(){return gr}function Cte(){gr=null,Ji=null,KO()}var gr,Ji,zf,Xi=k(()=>{"use strict";jf();gr=null,Ji=null,zf=!1});async function GO(e,t){try{return await cO(e,t)}catch(n){return B("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function $te(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Xi(),Yi));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function qO(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??$te,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s=e,a=null,l=null;try{let u=await Bf(n,e,{headers:Ote,signal:t.signal},o);a=u.status,s=u.url||e;let d=u.headers.get("content-type")??"";if(u.ok){if(Mte.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let m=await u.text();if(Pte.test(d)&&!Ite.test(d))return{title:"",markdown:m.trim(),finalUrl:s,usedRender:!1};if(i=await GO(m,s),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(u){if(t.signal.aborted||u instanceof Ln||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;l=u}if(!(i===null||i.textLength<200)&&i!==null)return{title:i.title,markdown:i.markdown,finalUrl:s,usedRender:!1};try{await ju(e,o);let u=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:m=>ju(m,o)});u.finalUrl!==e&&/^https?:\/\//i.test(u.finalUrl)&&await ju(u.finalUrl,o);let d=await GO(u.html,u.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||d.textLength>=i.textLength)return{title:d.title,markdown:d.markdown,finalUrl:u.finalUrl,usedRender:!0}}catch(u){if(t.signal.aborted||u instanceof Ln)throw u;if(i===null){let d=u instanceof Error?u.message:String(u),m=l instanceof Error?l.message:`HTTP ${a??"error"}`,f=new Error(`web_scrape could not retrieve ${e}: fetch failed (${m}) and render failed (${d}).`);throw f.cause=u,f}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${a??"error"}).`)}var Ite,Pte,Mte,Ote,zO=k(()=>{"use strict";uO();zk();ue();Ite=/(text\/html|application\/xhtml\+xml)/i,Pte=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,Mte=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,Ote={"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 Lte(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(Dte,{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),Fte),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let u=await i.text(),d=Dr(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 VO(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?Lte({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 JO(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
271
271
|
|
|
272
272
|
(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(`
|
|
273
273
|
`).trimEnd()}var Dte,Fte,YO=k(()=>{"use strict";Ao();Dte="https://api.exa.ai/search",Fte=10});function Vf(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 Qi=k(()=>{"use strict";Hf()});function Wte(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=Nte;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,Bte)}let a=Ute;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,jte)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function nT(e,t){return Buffer.byteLength(e,"utf8")<=t?{content:e,truncated:!1}:{content:$r(e,t),truncated:!0}}function Kte(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=Wte(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 m=await qk(s.url,r);if(a.signal.aborted)return{content:`web_scrape aborted: ${u()}`,isError:!0};if(!m.allowed)return{content:`web_scrape blocked: ${m.reason}`,isError:!0}}if(s.mode==="raw"){let m;try{let h={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};m=await Bf(t,s.url,h,r)}catch(h){return a.signal.aborted?{content:`web_scrape aborted: ${u()}`,isError:!0}:h instanceof Ln?{content:`web_scrape blocked: ${h.message}`,isError:!0}:{content:`web_scrape network error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}if(!m.ok)return{content:`web_scrape HTTP ${m.status} ${m.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let f;try{f=await m.text()}catch(h){return{content:`web_scrape read error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}let g=nT(f,s.maxBytes);return{content:g.content,...g.truncated?{truncated:!0}:{}}}if(s.mode==="markdown")try{let m=await qO(s.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:s.timeoutMs,signal:a.signal,...e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{}});if(m.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0};let f=nT(m.markdown,s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(m){if(a.signal.aborted)return{content:`web_scrape aborted: ${u()}`,isError:!0};if(m instanceof Ln)return{content:`web_scrape blocked: ${m.message}`,isError:!0};let f=m instanceof Error?m.message:String(m),g=Lt(m)&&!Vk(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${Hu()}\`)`:"";return{content:`web_scrape markdown error: ${f}${g}`,isError:!0}}let d=VO({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in d)return{content:d.error,isError:!0};try{let m=await d.search(s.query,{limit:Hte,timeoutMs:s.timeoutMs,signal:a.signal}),f=nT(JO(s.query,m),s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(m){return a.signal.aborted?{content:`web_scrape aborted: ${u()}`,isError:!0}:{content:`web_scrape search error (${d.name}): ${m instanceof Error?m.message:String(m)}`,isError:!0}}}finally{c!==void 0&&clearTimeout(c),i.removeEventListener("abort",l)}}}var Nte,Bte,Ute,jte,Hte,XO,QO=k(()=>{"use strict";zO();YO();zk();Li();Qi();Nte=3e4,Bte=12e4,Ute=1e5,jte=1e6,Hte=10;XO=Kte()});import{existsSync as e$,mkdirSync as Gte,readFileSync as qte,renameSync as zte,unlinkSync as Vte,writeFileSync as Jte}from"node:fs";import{dirname as ZO,join as Yte}from"node:path";import{randomBytes as Xte}from"node:crypto";function mn(e){let t=e??VS();if(!e$(t))return[];try{let n=qte(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 Zi(e,t){let n=t??VS();Gte(ZO(n),{recursive:!0});let r=Yte(ZO(n),`.schedules.json.${process.pid}.${Xte(4).toString("hex")}.tmp`),o=JSON.stringify(e,null,2);try{Jte(r,o,"utf-8"),zte(r,n)}catch(i){try{e$(r)&&Vte(r)}catch{}throw i}}function Jf(e,t){let n=mn(t),r=n.map(l=>l.id),o=Qte(e.name),i=Zte(o,r),s=new Date().toISOString(),a={...e,notifyOn:e.notifyOn??"failure",id:i,createdAt:s,updatedAt:s};return n.push(a),Zi(n,t),a}function Yf(e,t){let n=mn(t),r=n.length,o=n.filter(i=>i.id!==e);return o.length===r?!1:(Zi(o,t),!0)}function Ku(e,t){return mn(t).find(n=>n.id===e)}function Qte(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function Zte(e,t){if(!t.includes(e))return e;let n=2;for(;t.includes(`${e}-${n}`);)n+=1;return`${e}-${n}`}function t$(e){return{taskId:e.id,command:e.command,trigger:e.trigger??"cron",...e.cron!==void 0?{cronExpression:e.cron}:{},...e.notifyOn!==void 0?{notifyOn:e.notifyOn}:{},...e.notifyChat!==void 0?{notifyChat:e.notifyChat}:{}}}var Xf=k(()=>{"use strict";G()});import{existsSync as ene,readFileSync as tne}from"node:fs";import{join as nne}from"node:path";async function Nn(e,t,n){let r;try{let o=nne(lm("default"),"port");if(!ene(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=tne(o,"utf-8").trim();if(r=parseInt(i,10),Number.isNaN(r))return{synced:!1,detail:"daemon-not-detected (invalid port file)"}}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let o=await fetch(`http://localhost:${r}${t}`,{method:e,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return o.ok?{synced:!0,detail:"synced"}:e==="POST"&&o.status===409?{synced:!0,detail:"already-registered"}:e==="DELETE"&&o.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${o.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}var Po,rT=k(()=>{"use strict";G();Po="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 rne}from"node:fs";import{readFile as one}from"node:fs/promises";var n$,r$,o$,i$,s$=k(()=>{"use strict";Xf();G();rT();n$=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=Jf({name:n.name,command:n.command,cron:n.cron,trigger:n.trigger??"cron",notifyOn:n.notifyOn,...o!==void 0?{notifyChat:o}:{},enabled:typeof n.enabled=="boolean"?n.enabled:!0}),s=i.enabled?await Nn("POST","/tasks",{taskId:i.id,command:i.command,cron:i.cron,trigger:i.trigger,notifyOn:i.notifyOn,...i.notifyChat!==void 0?{notifyChat:i.notifyChat}:{}}):await Nn("DELETE",`/tasks/${i.id}`);return{content:JSON.stringify({id:i.id,name:i.name,cron:i.cron,enabled:i.enabled,daemonSynced:s.synced,syncDetail:s.detail,...s.synced?{}:{syncNote:Po}})}},r$=async(e,t)=>{let n=mn();return{content:JSON.stringify(n.map(r=>({id:r.id,name:r.name,cron:r.cron,trigger:r.trigger,enabled:r.enabled,notifyOn:r.notifyOn})))}},o$=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=Zn();if(!rne(i))return{content:JSON.stringify([])};let s;try{let c=await one(i);s=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=s.split(`
|
|
@@ -1092,14 +1092,14 @@ ${l}`:f,h=await d.runToResult(g);return m=oN(h,c),m}catch(f){let g=f instanceof
|
|
|
1092
1092
|
${n}`}:{...e,systemPrompt:n};if(r&&typeof r=="object"&&"type"in r&&r.type==="preset"){let o=r.append??"";return{...e,systemPrompt:{...r,append:o.length>0?`${o}
|
|
1093
1093
|
|
|
1094
1094
|
${n}`:n}}}return{...e,systemPrompt:n}}var xN=k(()=>{"use strict"});import Pse from"path";var Se,Qe=k(()=>{"use strict";KD();yl();Gm();pe();Dn();qr();KT();VD();os();G();Kn();Li();bh();Ne();bN();vN();cR();xN();Uo();Se=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentProvider;parentModel;parentCwd;parentReadRoots;worktreeMainRootCache=new Map;parentTraceWriter;parentSurface;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(t={}){if(this.parentCanUseTool=t.canUseTool,this.hookRegistry=t.hookRegistry,this.progressSink=t.progressSink,this.parentApiKey=t.apiKey,this.parentBaseUrl=t.baseUrl,this.parentProvider=t.parentModel!==void 0?ie(t.parentModel):void 0,this.parentModel=t.parentModel,this.parentCwd=t.cwd,this.parentReadRoots=t.parentReadRoots,this.parentTraceWriter=t.traceWriter,this.parentSurface=t.surface,this.onSubagentSucceededCb=t.onSubagentSucceeded,this.abortGraph=new Og(t.traceWriter),this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),t.parentAbortSignal){let n=t.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(t=>({id:t.id,status:t.status}))}get(t){return this.active.get(t)}onChildAborted(t){return this.abortGraph.onChildAborted(this.rootId,t)}setOnSubagentSucceeded(t){this.onSubagentSucceededCb=t}setCwd(t){this.parentCwd=t,this.worktreeMainRootCache.delete(t)}getReadScopeInputs(){return{parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd}}async resolveMainRootForCwd(t){if(this.worktreeMainRootCache.has(t))return this.worktreeMainRootCache.get(t);let n=await zD(t);return this.worktreeMainRootCache.set(t,n),n}abortAll(t,n="user_signal"){this.abortGraph.abort(this.rootId,t,n)}async forkSubagent(t){if(t.phaseRole!==void 0&&t.phaseRole!=="read-write"&&t.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${t.phaseRole}" is mutually exclusive with config.provider. Remove one \u2014 either let the manager construct the phase-restricted provider, or use config.provider with phaseRole: "read-write" (default).`);let n=`${t.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=t.parent.sessionId,o=t.config.hookRegistry??this.hookRegistry??t.parent.hookRegistry,i=t.config.traceWriter??this.parentTraceWriter;o&&await xP(o,{event:"SubagentStart",subagentId:n,parentSessionId:t.parent.sessionId},{signal:this.rootController.signal,...i?{traceWriter:i}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let a=t.config.cwd??this.parentCwd,l;if(t.config.readRoots===void 0){let S=this.parentReadRoots===void 0&&this.parentCwd===void 0,E;!S&&a!==void 0&&(E=await this.resolveMainRootForCwd(a),E===void 0&&this.parentCwd!==void 0&&this.parentCwd!==a&&(E=await this.resolveMainRootForCwd(this.parentCwd))),l=Zu({parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd,childCwd:a,worktreeMainRoot:E,...S?{}:{afkStateRoot:me()},...S?{}:{afkFrameworkRoot:bt()}})}if(t.config.readRoots===void 0&&t.config.extraReadRoots!==void 0&&t.config.extraReadRoots.length>0&&(l!==void 0||a!==void 0)){let E=l??(a!==void 0?[a]:[]);l=[...new Set([...E,...t.config.extraReadRoots.map(x=>Pse.resolve(x))])]}let c;if(t.config.writeRoots!==void 0&&t.config.writeRoots.length>0){let S=a!==void 0?[a]:[];c=[...new Set([...S,...t.config.writeRoots])]}let u=SN(t.config.model,this.parentModel),d=u.model??t.config.model;u.coercedFrom!==void 0&&process.stderr.write(`[afk] subagent: child model "${u.coercedFrom}" cannot run on this session's OpenAI/ChatGPT backend \u2014 running it as "${d??""}" instead (set AFK_DEFAULT_SUBAGENT_MODEL to choose a different one).
|
|
1095
|
-
`);let m=t.config.timeoutMs??Wh(),f=RN({...t.config,isSubagentFork:!0,model:d,resume:r,forkSession:r?!0:t.config.forkSession,subagentId:n,subagentToolOutputCapBytes:1e5,abortSignal:s.signal,apiKey:rL({childModel:d,configApiKey:t.config.apiKey,parentApiKey:this.parentApiKey,parentProvider:this.parentProvider}),baseUrl:t.config.baseUrl??(ie(d)==="openai-compatible"?void 0:this.parentBaseUrl),isNonInteractive:t.config.isNonInteractive??!0,maxToolUseIterations:t.config.maxToolUseIterations??TN,softDeadlineMs:t.config.softDeadlineMs??uh(m),autoResumeOnUsageLimit:t.config.autoResumeOnUsageLimit??!1,...t.config.parentSessionId===void 0&&t.parent.sessionId!==void 0?{parentSessionId:t.parent.sessionId}:{},...t.config.phaseRole===void 0&&t.phaseRole!==void 0?{phaseRole:t.phaseRole}:{},...t.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},...l!==void 0?{readRoots:l}:{},...c!==void 0?{writeRoots:c}:{},...t.config.traceWriter===void 0&&this.parentTraceWriter!==void 0?{traceWriter:this.parentTraceWriter}:{},...t.config.surface===void 0&&this.parentSurface!==void 0?{surface:this.parentSurface}:{},hookRegistry:o,permissionBubbler:t.config.permissionBubbler??(this.parentCanUseTool!==void 0&&t.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...t.denyElicitations===!1?{}:{onElicitation:kN},...t.phaseRole==="read-only"?{provider:mN("read-only",d)}:{}}),g=()=>{};f.cwd!==void 0&&(WT(f.cwd),g=qD(f.cwd));let h,y,b,w;try{h=new _t(f);let S=t.parent.getInputStreamRef?.(),E=t.parent.abortSignal,x=this.progressSink??Un();b=t.agentType?.trim()||void 0,w=t.resolvedAgentType?.trim()||void 0;let D=t.parentId?.trim()||void 0;y=new Hh(n,h,s,this.abortGraph,t.outputSchema,m,o,()=>{g(),this.active.delete(n),this.abortGraph.dispose(n)},S,E,b??t.idPrefix,x,D??t.parent.sessionId,i,this.onSubagentSucceededCb,t.config.idleTimeoutMs??EN()),this.active.set(n,y)}catch(S){throw g(),this.abortGraph.dispose(n),S}let v=typeof d=="string"?d:JSON.stringify(d);return Ai(i,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:v,...f.tools?.allowedTools?{allowedTools:[...f.tools.allowedTools]}:{},...t.promptHead&&t.promptHead.trim()!==""?{promptHead:t.promptHead.slice(0,80)}:{},...b?{agentType:b}:{},...w?{resolvedAgentType:w}:{}}),await Me({event:"subagent.dispatched",subagent_id:n,id_prefix:t.idPrefix,model:v,parent_session_id:t.parent.sessionId,resolved_agent_type:w}),y}async kill(t){let n=this.active.get(t);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(t=>t.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(t=>t.teardown()))}}});async function AN(e,t={}){let{failFast:n=!0,teardown:r=!0,maxConcurrency:o=du()}=t;if(e.length===0)return[];let i=new Array(e.length),s=new Set(e.map((l,c)=>c)),a=!1;return await Ra(e.map((l,c)=>c),o,async l=>{let c=e[l];n&&a&&await c.handle.cancel().catch(()=>{});let u=await c.handle.runToResult(c.prompt);if(i[l]=u,s.delete(l),n&&u.status!=="succeeded"){a=!0;for(let d of s){let m=e[d];m&&m.handle.status==="running"&&m.handle.cancel().catch(()=>{})}}}),r&&await Promise.allSettled(e.map(l=>l.handle.teardown())),i}var CN=k(()=>{"use strict";Km()});function _N(e){let t=new Set;for(let n of e){let r=yd(n,Mse);r!==void 0&&t.add(r)}return t}var Mse,IN=k(()=>{"use strict";bd();Vt();cf();Mse=new Set([...Mt,...st,"memory_search","agent","skill"])});import{existsSync as MN,mkdirSync as Ose,readFileSync as $se,renameSync as Dse,writeFileSync as Fse,unlinkSync as Lse}from"fs";import{dirname as PN,join as Nse}from"path";import{randomBytes as Bse}from"crypto";function Pe(e=Ee()){if(!MN(e))return Kh();try{let t=$se(e,"utf8"),n=JSON.parse(t);if(!n||typeof n!="object")return Kh();let r=n,o=r.plugins&&typeof r.plugins=="object"?r.plugins:{};if(r.version===1)return{version:2,plugins:o,marketplaces:{}};if(r.version===2){let i=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:i}}return Kh()}catch{return Kh()}}function Ad(e,t=Ee()){Ose(PN(t),{recursive:!0});let n=Nse(PN(t),`.index.json.${process.pid}.${Bse(4).toString("hex")}.tmp`),r=JSON.stringify(e,null,2);try{Fse(n,r,"utf8"),Dse(n,t)}catch(o){try{MN(n)&&Lse(n)}catch{}throw o}}function Yo(e,t,n=Ee()){let r=Pe(n);return r.plugins[e]=t,Ad(r,n),r}function ON(e,t=Ee()){let n=Pe(t);return e in n.plugins&&(delete n.plugins[e],Ad(n,t)),n}function uR(e,t,n=Ee()){let r=Pe(n),o=r.plugins[e];if(!o)throw new Error(`plugin "${e}" is not in the index`);return o.enabled=t,o.updatedAt=new Date().toISOString(),Ad(r,n),r}function Cd(e,t,n=Ee()){let r=Pe(n);return r.marketplaces[e]=t,Ad(r,n),r}function $N(e,t=Ee()){let n=Pe(t),r=!1;e in n.marketplaces&&(delete n.marketplaces[e],r=!0);for(let[o,i]of Object.entries(n.plugins))i.marketplace===e&&(delete n.plugins[o],r=!0);return r&&Ad(n,t),n}function Kh(){return{version:2,plugins:{},marketplaces:{}}}var Zt=k(()=>{"use strict";G()});import{existsSync as dR,readFileSync as LN,readdirSync as Use,realpathSync as jse,statSync as Hse}from"fs";import{join as wl,resolve as DN}from"path";function Vr(){bl=void 0}function qn(e=Ke(),t={}){let n=t.trustAll===!0,r=t.sourceEnabled,o=n?`${e}\0trustAll`:e;if(n&&r&&r.size>0){let c=[...r.entries()].map(([u,d])=>`${u}=${d?1:0}`).sort().join(",");o=`${o}\0${c}`}bl||(bl=new Map);let i=bl.get(o);if(i)return[...i];if(!dR(e))return bl.set(o,[]),[];let s=e===Ke()?Ee():wl(e,".index.json"),a=Pe(s),l=[];return NN(e,e,0,l,new Set,a.plugins,n,r),bl.set(o,l),[...l]}function NN(e,t,n,r,o,i,s,a){if(n>Wse)return;let l;try{l=jse(t)}catch{l=t}if(o.has(l))return;if(o.add(l),dR(wl(t,".claude-plugin","plugin.json"))){let u=pR(e,t);if(u===null){Gh(r,t);return}if(s){if(a&&a.get(Gse(u))===!1)return;Gh(r,t);return}if(u.layout==="cache"){let m=i[u.key];if(!m||m.enabled===!1)return;Gh(r,t);return}let d=i[u.key];if(d&&d.enabled===!1)return;Gh(r,t);return}let c;try{c=Use(t)}catch{return}for(let u of c){if(u.startsWith("."))continue;let d=wl(t,u),m;try{m=Hse(d)}catch{continue}m.isDirectory()&&NN(e,d,n+1,r,o,i,s,a)}}function Kse(e){try{let t=LN(wl(e,".claude-plugin","plugin.json"),"utf8"),n=JSON.parse(t);if(n!==null&&typeof n=="object"&&"main"in n){let r=n.main;if(typeof r=="string"&&r.trim()!=="")return r}}catch{}}function Gh(e,t){let n=Kse(t);e.push(n!==void 0?{type:"local",path:t,main:n}:{type:"local",path:t})}function Gse(e){if(e.layout!=="cache")return e.key;let t=e.key.indexOf(":");if(t<=0)return e.key;let n=e.key.slice(0,t);return`${e.key.slice(t+1)}@${n}`}function pR(e,t){if(!t.startsWith(e))return null;let n=t.slice(e.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(i=>i.length>0);if(r.length===0)return null;if(r[0]===FN&&r.length>=3){let i=r[1];if(i){let s=wl(e,FN,i),l=qse(s,t)??r[2];if(l)return{layout:"cache",key:`${i}:${l}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function qse(e,t){let n=wl(e,".claude-plugin","marketplace.json");if(!dR(n))return null;let r;try{r=JSON.parse(LN(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let i=DN(t);for(let s of o){if(!s||typeof s!="object")continue;let a=s;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&DN(e,a.source)===i)return a.name}return null}var Wse,FN,bl,Jr=k(()=>{"use strict";G();Zt();Wse=5,FN="cache"});import{existsSync as Xo,readdirSync as zse,readFileSync as Vse}from"fs";import{join as Yr}from"path";function UN(e=Te()){let t=[],n=Yr(e,"skills");if(Xo(n))for(let r of qh(n)){let o=Yr(n,r,"SKILL.md");Xo(o)&&t.push({path:o,type:"skill",source:"user"})}for(let r of BN){let o=Yr(e,`${r}s`);if(Xo(o))for(let i of qh(o))i.endsWith(".md")&&t.push({path:Yr(o,i),type:r,source:"user"})}return t}function jN(e=Ke()){if(!Xo(e))return[];let t=[],n=qn(e);for(let r of n){let i=pR(e,r.path)?.key,s=Yr(r.path,"skills");if(Xo(s))for(let a of qh(s)){let l=Yr(s,a,"SKILL.md");if(!Xo(l))continue;let c={path:l,type:"skill",source:"plugin"};i&&(c.plugin_key=i),t.push(c)}for(let a of BN){let l=Yr(r.path,`${a}s`);if(Xo(l))for(let c of qh(l)){if(!c.endsWith(".md"))continue;let u={path:Yr(l,c),type:a,source:"plugin"};i&&(u.plugin_key=i),t.push(u)}}}return t}function HN(e=Yr(Te(),"settings.json")){if(!Xo(e))return[];try{let t=Vse(e,"utf8"),r=JSON.parse(t).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[i,s]of Object.entries(r))if(Array.isArray(s))for(let a=0;a<s.length;a++)o.push({event:i,index:a,raw:s[a]});return o}catch{return[]}}function qh(e){try{return zse(e).filter(t=>!t.startsWith("."))}catch{return[]}}var BN,WN=k(()=>{"use strict";G();Jr();BN=["command","agent"]});import{z as
|
|
1095
|
+
`);let m=t.config.timeoutMs??Wh(),f=RN({...t.config,isSubagentFork:!0,model:d,resume:r,forkSession:r?!0:t.config.forkSession,subagentId:n,subagentToolOutputCapBytes:1e5,abortSignal:s.signal,apiKey:rL({childModel:d,configApiKey:t.config.apiKey,parentApiKey:this.parentApiKey,parentProvider:this.parentProvider}),baseUrl:t.config.baseUrl??(ie(d)==="openai-compatible"?void 0:this.parentBaseUrl),isNonInteractive:t.config.isNonInteractive??!0,maxToolUseIterations:t.config.maxToolUseIterations??TN,softDeadlineMs:t.config.softDeadlineMs??uh(m),autoResumeOnUsageLimit:t.config.autoResumeOnUsageLimit??!1,...t.config.parentSessionId===void 0&&t.parent.sessionId!==void 0?{parentSessionId:t.parent.sessionId}:{},...t.config.phaseRole===void 0&&t.phaseRole!==void 0?{phaseRole:t.phaseRole}:{},...t.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},...l!==void 0?{readRoots:l}:{},...c!==void 0?{writeRoots:c}:{},...t.config.traceWriter===void 0&&this.parentTraceWriter!==void 0?{traceWriter:this.parentTraceWriter}:{},...t.config.surface===void 0&&this.parentSurface!==void 0?{surface:this.parentSurface}:{},hookRegistry:o,permissionBubbler:t.config.permissionBubbler??(this.parentCanUseTool!==void 0&&t.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...t.denyElicitations===!1?{}:{onElicitation:kN},...t.phaseRole==="read-only"?{provider:mN("read-only",d)}:{}}),g=()=>{};f.cwd!==void 0&&(WT(f.cwd),g=qD(f.cwd));let h,y,b,w;try{h=new _t(f);let S=t.parent.getInputStreamRef?.(),E=t.parent.abortSignal,x=this.progressSink??Un();b=t.agentType?.trim()||void 0,w=t.resolvedAgentType?.trim()||void 0;let D=t.parentId?.trim()||void 0;y=new Hh(n,h,s,this.abortGraph,t.outputSchema,m,o,()=>{g(),this.active.delete(n),this.abortGraph.dispose(n)},S,E,b??t.idPrefix,x,D??t.parent.sessionId,i,this.onSubagentSucceededCb,t.config.idleTimeoutMs??EN()),this.active.set(n,y)}catch(S){throw g(),this.abortGraph.dispose(n),S}let v=typeof d=="string"?d:JSON.stringify(d);return Ai(i,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:v,...f.tools?.allowedTools?{allowedTools:[...f.tools.allowedTools]}:{},...t.promptHead&&t.promptHead.trim()!==""?{promptHead:t.promptHead.slice(0,80)}:{},...b?{agentType:b}:{},...w?{resolvedAgentType:w}:{}}),await Me({event:"subagent.dispatched",subagent_id:n,id_prefix:t.idPrefix,model:v,parent_session_id:t.parent.sessionId,resolved_agent_type:w}),y}async kill(t){let n=this.active.get(t);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(t=>t.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(t=>t.teardown()))}}});async function AN(e,t={}){let{failFast:n=!0,teardown:r=!0,maxConcurrency:o=du()}=t;if(e.length===0)return[];let i=new Array(e.length),s=new Set(e.map((l,c)=>c)),a=!1;return await Ra(e.map((l,c)=>c),o,async l=>{let c=e[l];n&&a&&await c.handle.cancel().catch(()=>{});let u=await c.handle.runToResult(c.prompt);if(i[l]=u,s.delete(l),n&&u.status!=="succeeded"){a=!0;for(let d of s){let m=e[d];m&&m.handle.status==="running"&&m.handle.cancel().catch(()=>{})}}}),r&&await Promise.allSettled(e.map(l=>l.handle.teardown())),i}var CN=k(()=>{"use strict";Km()});function _N(e){let t=new Set;for(let n of e){let r=yd(n,Mse);r!==void 0&&t.add(r)}return t}var Mse,IN=k(()=>{"use strict";bd();Vt();cf();Mse=new Set([...Mt,...st,"memory_search","agent","skill"])});import{existsSync as MN,mkdirSync as Ose,readFileSync as $se,renameSync as Dse,writeFileSync as Fse,unlinkSync as Lse}from"fs";import{dirname as PN,join as Nse}from"path";import{randomBytes as Bse}from"crypto";function Pe(e=Ee()){if(!MN(e))return Kh();try{let t=$se(e,"utf8"),n=JSON.parse(t);if(!n||typeof n!="object")return Kh();let r=n,o=r.plugins&&typeof r.plugins=="object"?r.plugins:{};if(r.version===1)return{version:2,plugins:o,marketplaces:{}};if(r.version===2){let i=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:i}}return Kh()}catch{return Kh()}}function Ad(e,t=Ee()){Ose(PN(t),{recursive:!0});let n=Nse(PN(t),`.index.json.${process.pid}.${Bse(4).toString("hex")}.tmp`),r=JSON.stringify(e,null,2);try{Fse(n,r,"utf8"),Dse(n,t)}catch(o){try{MN(n)&&Lse(n)}catch{}throw o}}function Yo(e,t,n=Ee()){let r=Pe(n);return r.plugins[e]=t,Ad(r,n),r}function ON(e,t=Ee()){let n=Pe(t);return e in n.plugins&&(delete n.plugins[e],Ad(n,t)),n}function uR(e,t,n=Ee()){let r=Pe(n),o=r.plugins[e];if(!o)throw new Error(`plugin "${e}" is not in the index`);return o.enabled=t,o.updatedAt=new Date().toISOString(),Ad(r,n),r}function Cd(e,t,n=Ee()){let r=Pe(n);return r.marketplaces[e]=t,Ad(r,n),r}function $N(e,t=Ee()){let n=Pe(t),r=!1;e in n.marketplaces&&(delete n.marketplaces[e],r=!0);for(let[o,i]of Object.entries(n.plugins))i.marketplace===e&&(delete n.plugins[o],r=!0);return r&&Ad(n,t),n}function Kh(){return{version:2,plugins:{},marketplaces:{}}}var Zt=k(()=>{"use strict";G()});import{existsSync as dR,readFileSync as LN,readdirSync as Use,realpathSync as jse,statSync as Hse}from"fs";import{join as wl,resolve as DN}from"path";function Vr(){bl=void 0}function qn(e=Ke(),t={}){let n=t.trustAll===!0,r=t.sourceEnabled,o=n?`${e}\0trustAll`:e;if(n&&r&&r.size>0){let c=[...r.entries()].map(([u,d])=>`${u}=${d?1:0}`).sort().join(",");o=`${o}\0${c}`}bl||(bl=new Map);let i=bl.get(o);if(i)return[...i];if(!dR(e))return bl.set(o,[]),[];let s=e===Ke()?Ee():wl(e,".index.json"),a=Pe(s),l=[];return NN(e,e,0,l,new Set,a.plugins,n,r),bl.set(o,l),[...l]}function NN(e,t,n,r,o,i,s,a){if(n>Wse)return;let l;try{l=jse(t)}catch{l=t}if(o.has(l))return;if(o.add(l),dR(wl(t,".claude-plugin","plugin.json"))){let u=pR(e,t);if(u===null){Gh(r,t);return}if(s){if(a&&a.get(Gse(u))===!1)return;Gh(r,t);return}if(u.layout==="cache"){let m=i[u.key];if(!m||m.enabled===!1)return;Gh(r,t);return}let d=i[u.key];if(d&&d.enabled===!1)return;Gh(r,t);return}let c;try{c=Use(t)}catch{return}for(let u of c){if(u.startsWith("."))continue;let d=wl(t,u),m;try{m=Hse(d)}catch{continue}m.isDirectory()&&NN(e,d,n+1,r,o,i,s,a)}}function Kse(e){try{let t=LN(wl(e,".claude-plugin","plugin.json"),"utf8"),n=JSON.parse(t);if(n!==null&&typeof n=="object"&&"main"in n){let r=n.main;if(typeof r=="string"&&r.trim()!=="")return r}}catch{}}function Gh(e,t){let n=Kse(t);e.push(n!==void 0?{type:"local",path:t,main:n}:{type:"local",path:t})}function Gse(e){if(e.layout!=="cache")return e.key;let t=e.key.indexOf(":");if(t<=0)return e.key;let n=e.key.slice(0,t);return`${e.key.slice(t+1)}@${n}`}function pR(e,t){if(!t.startsWith(e))return null;let n=t.slice(e.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(i=>i.length>0);if(r.length===0)return null;if(r[0]===FN&&r.length>=3){let i=r[1];if(i){let s=wl(e,FN,i),l=qse(s,t)??r[2];if(l)return{layout:"cache",key:`${i}:${l}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function qse(e,t){let n=wl(e,".claude-plugin","marketplace.json");if(!dR(n))return null;let r;try{r=JSON.parse(LN(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let i=DN(t);for(let s of o){if(!s||typeof s!="object")continue;let a=s;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&DN(e,a.source)===i)return a.name}return null}var Wse,FN,bl,Jr=k(()=>{"use strict";G();Zt();Wse=5,FN="cache"});import{existsSync as Xo,readdirSync as zse,readFileSync as Vse}from"fs";import{join as Yr}from"path";function UN(e=Te()){let t=[],n=Yr(e,"skills");if(Xo(n))for(let r of qh(n)){let o=Yr(n,r,"SKILL.md");Xo(o)&&t.push({path:o,type:"skill",source:"user"})}for(let r of BN){let o=Yr(e,`${r}s`);if(Xo(o))for(let i of qh(o))i.endsWith(".md")&&t.push({path:Yr(o,i),type:r,source:"user"})}return t}function jN(e=Ke()){if(!Xo(e))return[];let t=[],n=qn(e);for(let r of n){let i=pR(e,r.path)?.key,s=Yr(r.path,"skills");if(Xo(s))for(let a of qh(s)){let l=Yr(s,a,"SKILL.md");if(!Xo(l))continue;let c={path:l,type:"skill",source:"plugin"};i&&(c.plugin_key=i),t.push(c)}for(let a of BN){let l=Yr(r.path,`${a}s`);if(Xo(l))for(let c of qh(l)){if(!c.endsWith(".md"))continue;let u={path:Yr(l,c),type:a,source:"plugin"};i&&(u.plugin_key=i),t.push(u)}}}return t}function HN(e=Yr(Te(),"settings.json")){if(!Xo(e))return[];try{let t=Vse(e,"utf8"),r=JSON.parse(t).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[i,s]of Object.entries(r))if(Array.isArray(s))for(let a=0;a<s.length;a++)o.push({event:i,index:a,raw:s[a]});return o}catch{return[]}}function qh(e){try{return zse(e).filter(t=>!t.startsWith("."))}catch{return[]}}var BN,WN=k(()=>{"use strict";G();Jr();BN=["command","agent"]});import{z as je}from"zod";import{mkdir as KN,appendFile as GN}from"fs/promises";import{join as mR}from"path";function Xse(e){return{runUserDiscovery:e!=="plugin",runPluginDiscovery:e!=="user",runHookInspector:e!=="plugin"}}function Qse(e){let t=()=>{let i={};for(let s of VN)i[s]={correct:0,misfit:0,outlier:0};return i},n={user:t(),plugin:t()};for(let i of e)n[i.source][i.type][i.verdict]+=1;let r={high:0,med:1,low:2},o=e.filter(i=>i.verdict==="misfit").slice().sort((i,s)=>r[i.confidence]-r[s.confidence]);return{inventory:n,misfits:o}}function Zse(e){return e.verdict==="misfit"&&e.confidence==="high"&&e.source==="user"}function eae(e){let t=e.filter(o=>o.source==="user"),n=e.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),t.length===0)r.push("(none discovered)");else for(let o of t)r.push(`- ${o.path}`);if(r.push(""),r.push('### Plugin-scope artifacts (set `"source": "plugin"`, copy `plugin_key` from each entry)'),n.length===0)r.push("(none discovered)");else for(let o of n){let i=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${i})`)}return r.join(`
|
|
1096
1096
|
`)}function tae(e,t){let n=["","## Discovered hooks (audit only these)",""];if(n.push(`Settings file (use this absolute path verbatim in each verdict's \`path\` field): \`${e}\``),n.push(""),t.length===0)return n.push("(no hooks discovered)"),n.join(`
|
|
1097
1097
|
`);for(let r of t){let o=`${r.event}-${r.index}`;n.push(`### Hook \`${o}\``),n.push(""),n.push("```json"),n.push(JSON.stringify(r.raw,null,2)),n.push("```"),n.push("")}return n.join(`
|
|
1098
1098
|
`)}function nae(e,t){if(!t)return{kind:"failure",message:`${e}: no result`};if(t.schemaError)return{kind:"failure",message:`${e}: schema mismatch \u2014 ${t.schemaError.message}`};if(t.status!=="succeeded"){let n=t.error?` \u2014 ${t.error.message}`:"";return{kind:"failure",message:`${e}: ${t.status}${n}`}}return t.output?{kind:"success",output:t.output}:{kind:"failure",message:`${e}: no output`}}async function rae(e,t,n){let r=n?.apiKey,o=n?.defaultSubagentModel??n?.defaultModel??"sonnet",i=n?.callId,s=typeof e=="object"&&e!==null?e:{},a=Jse.parse(s),l=a.writeBriefs??!0,c=a.scope??"all",u=Xse(c);if(!t?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let d=t.sessionId,m=We("audit-fit"),f={skill:m["01-skill-inspector.md"],command:m["02-command-inspector.md"],agent:m["03-agent-inspector.md"],hook:m["04-hook-inspector.md"]};for(let O of VN)if(!f[O])throw new Error(`audit-fit skill missing inspector prompt for ${O}`);let g=u.runUserDiscovery?UN():[],h=u.runPluginDiscovery?jN():[],y={skill:[],command:[],agent:[]};for(let O of[...g,...h])y[O.type].push(O);let b=new Se({apiKey:r,...n?.defaultModel!==void 0?{parentModel:n.defaultModel}:{},...n?.traceWriter!==void 0?{traceWriter:n.traceWriter}:{}}),w=_N(Ko.allowedTools),v=()=>async O=>w.has(O)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${O} not allowed for audit-fit inspectors. Allowed tools: ${[...w].join(", ")}`},S=[];for(let O of Yse){let H=y[O];if(H.length===0)continue;let K=f[O];K&&S.push({type:O,prompt:`${K}
|
|
1099
1099
|
${eae(H)}`,artifacts:H,runPrompt:`Inspect every ${O} listed in the artifact section.`})}if(u.runHookInspector){let O=f.hook;if(O){let H=mR(Te(),"settings.json"),K=HN(H);S.push({type:"hook",prompt:`${O}
|
|
1100
1100
|
${tae(H,K)}`,artifacts:[],runPrompt:`Inspect every hook listed in the Discovered hooks section. Settings file: ${H}.`})}}let E=[];if(S.length>0){let O=await Promise.all(S.map(_=>b.forkSubagent({parent:{sessionId:d},config:{model:o,systemPrompt:`${Ko.systemPrompt}
|
|
1101
1101
|
|
|
1102
|
-
${_.prompt}`,canUseTool:v()},idPrefix:`inspector-${_.type}`,agentType:`inspector-${_.type}`,outputSchema:
|
|
1102
|
+
${_.prompt}`,canUseTool:v()},idPrefix:`inspector-${_.type}`,agentType:`inspector-${_.type}`,outputSchema:je.array(zN),...i?{parentId:i}:{}}))),H=await AN(S.map((_,F)=>{let M=O[F];if(!M)throw new Error(`audit-fit: missing handle for ${_.type} inspector`);return{handle:M,prompt:_.runPrompt}}),{failFast:!1}),K=[];for(let _=0;_<H.length;_++){let F=H[_],M=S[_];if(!M)continue;let $=nae(M.type,F);if($.kind==="failure"){K.push($.message);continue}let U=new Map;for(let X of M.artifacts)U.set(X.path,X.source);for(let X of $.output){if(M.type==="hook"){if(X.source!=="user"){K.push(`${M.type}: hook verdict has source=${X.source} (must be 'user')`);continue}}else{let j=U.get(X.path);if(j===void 0){K.push(`${M.type}: verdict for unknown path ${X.path} (not in discovered list)`);continue}if(X.source!==j){K.push(`${M.type}: verdict source mismatch for ${X.path} (expected ${j}, got ${X.source})`);continue}}E.push(X)}}if(K.length>0){let _=K.map(F=>` - ${F}`).join(`
|
|
1103
1103
|
`);throw new Error(`audit-fit: ${K.length} inspector failure(s):
|
|
1104
1104
|
${_}`)}}let{inventory:x,misfits:D}=Qse(E),I=0;if(l){let O=V_();await KN(O,{recursive:!0});for(let H of D.filter(Zse)){let K=H.path.replace(/[^a-z0-9]+/gi,"-").toLowerCase().slice(0,30),_=mR(O,`audit-fit-${K}.md`),F=`---
|
|
1105
1105
|
theme: audit-fit
|
|
@@ -1124,7 +1124,7 @@ ${H.rationale}
|
|
|
1124
1124
|
---
|
|
1125
1125
|
Generated by audit-fit on ${new Date().toISOString().split(".")[0]}Z
|
|
1126
1126
|
`;await GN(_,F),I++}}let A=bt();await KN(A,{recursive:!0});let C=O=>{let H=0;for(let K of Object.values(O))for(let _ of Object.values(K))H+=_;return H},P=O=>{let H=x.user[O]??{},K=x.plugin[O]??{},_=F=>Object.values(F).reduce((M,$)=>M+$,0);return _(H)+_(K)},N={timestamp:new Date().toISOString(),surface:"afk",scope:c,total_artifacts:E.length,misfits_count:D.length,briefs_written:I,by_source:{user:C(x.user),plugin:C(x.plugin)},by_type:{skill:P("skill"),command:P("command"),agent:P("agent"),hook:P("hook")}},z=mR(A,"audit-fit-telemetry.jsonl");return await GN(z,JSON.stringify(N)+`
|
|
1127
|
-
`),{inventory:x,misfits:D,briefs_written:I,total_artifacts:E.length}}var zN,qN,RVe,Jse,Yse,VN,oae,JN=k(()=>{"use strict";yn();Bt();Qe();CN();$E();IN();G();WN();zN=
|
|
1127
|
+
`),{inventory:x,misfits:D,briefs_written:I,total_artifacts:E.length}}var zN,qN,RVe,Jse,Yse,VN,oae,JN=k(()=>{"use strict";yn();Bt();Qe();CN();$E();IN();G();WN();zN=je.object({path:je.string(),type:je.enum(["skill","command","agent","hook"]),source:je.enum(["user","plugin"]),plugin_key:je.string().optional(),verdict:je.enum(["correct","misfit","outlier"]),recommended_type:je.string(),rationale:je.string(),confidence:je.enum(["high","med","low"])}),qN=je.record(je.string(),je.record(je.string(),je.number())),RVe=je.object({inventory:je.object({user:qN,plugin:qN}),misfits:je.array(zN),briefs_written:je.number(),total_artifacts:je.number()}),Jse=je.object({writeBriefs:je.boolean().optional(),scope:je.enum(["user","plugin","all"]).optional()}),Yse=["skill","command","agent"],VN=["skill","command","agent","hook"];oae={name:"audit-fit",description:"Audit ~/.afk artifacts (skills, commands, agents, hooks) for correct type categorization. Walks user-scope dirs (~/.afk/{skills,commands,agents}/) and every plugin installed under ~/.afk/plugins/ (flat and marketplace-cache layouts), plus ~/.afk/settings.json for hooks. Dispatches per-type inspectors in parallel, applies decision heuristics (progressive-disclosure value, isolation need, deterministic vs. reasoning), flags misfits. Generates migration briefs only for user-scope misfits (plugin misfits are inventory-only \u2014 refactoring vendored plugin code is the maintainer's job). Optional `scope` input filters to `user`, `plugin`, or `all` (default). Use for inventory audits after bulk authoring, imports, or periodic hygiene.",handler:rae,argumentHint:"[--write-briefs]",whenToUse:"When the user wants ~/.afk artifacts (skills, commands, agents, hooks) audited for correct type categorization.",flags:["--write-briefs"],audience:"internal"};Nt(oae)});async function iae(){throw new Error("get-started is a load skill; its handler should never be called directly. Invoke via the `skill` tool or `/get-started` slash command.")}var sae,YN=k(()=>{"use strict";Bt();sae={name:"get-started",description:"Guided first-run onboarding for AFK. Runs a preflight check (git repo, model provider, AFK.md, Exa/Telegram/service config), asks the user their name and gives a brief intro, detects importable Claude Code / Codex assets and offers `afk migrate`, walks optional capability setup (Exa Search, Telegram via /telegram-setup, background service via /service-setup), then recommends /init to generate project context and /clear to start fresh \u2014 ending by routing the user to their first task. Runs interactively in the current session.",handler:iae,context:"load",audience:"public",whenToUse:"When someone is setting up AFK for the first time or asks how to get going \u2014 triggers on `/get-started`, 'how do I start', 'set me up', 'onboard me', or a fresh install with no AFK.md and unconfigured capabilities. Best run in the interactive REPL."};Nt(sae)});async function XN(e,t,n,r,o="sonnet",i,s){let l=We("mint")["spec.md"];if(!l)throw new Error("mint skill missing spec.md prompt");let d=await(await new Se({...n!==void 0?{cwd:n}:{},...i!==void 0?{parentReadRoots:i}:{},...s!==void 0?{traceWriter:s}:{}}).forkSubagent({parent:{sessionId:t},config:{model:o,systemPrompt:l,apiKey:Fe(o)},idPrefix:"mint-spec",agentType:"mint-spec",phaseRole:"read-only",...r?{parentId:r}:{}})).runToResult(`Create a detailed specification for: ${e}`);if(d.status!=="succeeded"||!d.message)throw new Error(`spec phase failed: ${Rt(d)}`);if(Et(d.stopReason))throw new Error(`spec phase returned an incomplete result (stopReason=${d.stopReason})`);return d.message.content}var QN=k(()=>{"use strict";Qe();ct();Ct();yn()});async function ZN(e,t,n,r,o="sonnet",i,s){let l=We("mint")["research.md"];if(!l)throw new Error("mint skill missing research.md prompt");let d=await(await new Se({...n!==void 0?{cwd:n}:{},...i!==void 0?{parentReadRoots:i}:{},...s!==void 0?{traceWriter:s}:{}}).forkSubagent({parent:{sessionId:t},config:{model:o,systemPrompt:l,apiKey:Fe(o)},idPrefix:"mint-research",agentType:"mint-research",phaseRole:"read-only",...r?{parentId:r}:{}})).runToResult(`Gather context and research for this specification:
|
|
1128
1128
|
|
|
1129
1129
|
${e}`);if(d.status!=="succeeded"||!d.message)throw new Error(`research phase failed: ${Rt(d)}`);if(Et(d.stopReason))throw new Error(`research phase returned an incomplete result (stopReason=${d.stopReason})`);return d.message.content}var eB=k(()=>{"use strict";Qe();ct();Ct();yn()});async function tB(e,t,n,r,o,i="sonnet",s,a){let c=We("mint")["plan.md"];if(!c)throw new Error("mint skill missing plan.md prompt");let d=await new Se({...r!==void 0?{cwd:r}:{},...s!==void 0?{parentReadRoots:s}:{},...a!==void 0?{traceWriter:a}:{}}).forkSubagent({parent:{sessionId:n},config:{model:i,systemPrompt:c,apiKey:Fe(i)},idPrefix:"mint-plan",agentType:"mint-plan",phaseRole:"read-only",...o?{parentId:o}:{}}),m=`Specification:
|
|
1130
1130
|
${e}
|
|
@@ -1274,7 +1274,7 @@ Status written to: ${Zc()}
|
|
|
1274
1274
|
`);return u+`
|
|
1275
1275
|
`+m}function Q5(e,t,n){let r=J5(e),o=n.map(wo),i=Math.max(Z(t)+4,...o.map(l=>Z(l))),s=Math.max(40,i)+4,a=Math.min(s,Math.min(oe()-4,100));return a=Math.min(a,on()),fa(o,{border:r,title:t,width:a,padding:2})}function ge(e){let t=Math.min(oe(),120);if(e===void 0)return p.dim("\u2500".repeat(t));let n=p.dim("\u2500\u2500")+" "+p.bold(e)+" ",r="\u2500\u2500 "+e+" ",o=Math.max(0,t-Z(r));return n+p.dim("\u2500".repeat(o))}ue();function ha(e,t){let n=t?.isTTY??process.stdout.isTTY??!1,r=t?.write??(o=>{process.stderr.write(o)});if(n)r(Rm(e.userMessage,e.hint)+`
|
|
1276
1276
|
`);else{let o=e.hint?` (${e.hint})`:"";r(`afk: error: ${e.userMessage}${o}
|
|
1277
|
-
`)}
|
|
1277
|
+
`)}He()&&e.raw instanceof Error&&e.raw.stack&&r(e.raw.stack+`
|
|
1278
1278
|
`)}function V(e){let t=ca(e);ha(t),process.exit(t.exitCode)}yl();import*as CW from"node:os";import*as _W from"node:path";import{existsSync as ume}from"node:fs";Rg();var _ce=["shadow-verify","shadow_verify","resolve","diagnose","appmap","mint","review","verify","verifier"],Ice=[/\bverdict(s)?\b/i,/\brecommend(ation)?s?\b/i,/\bshould\s+(delete|remove|rewrite|refactor|rename|reject|merge|revert|disable)\b/i,/\b(USELESS|KEEP|REJECT|APPROVE|SALVAGE|BLOCK|FAIL)\b/,/\b(redundant|duplicated|superseded|obsolete)\b/i,/\bvulnerab\w*\b/i,/\bunused\b/i,/\bbroken\b/i,/\bregress\w*\b/i,/\|\s*(status|verdict|decision|severity|risk|finding|priority|holds\??)\s*\|/i,/\bfound\s+\d+\s*(issue|problem|bug|error|finding|vulnerabilit)/i,/\b(critical|high|medium|low)\s+(severity|priority|risk)\b/i,/\bclaim(s)?\b[^\n]{0,80}\b(holds?|refuted|verified|partial|confirmed|disputed)\b/i,/\b(root\s*cause|incident)\b/i,/\brecommend\s+(removing|deleting|rewriting|refactoring|merging|reverting)\b/i,/\bI\s+(applied|committed|pushed|edited|wrote|fixed|patched|reset|restored|staged)\b/i,/\b(applied|committed|pushed|fixed|patched)\s+(the|these|those)\s+(change|commit|fix|patch|edit)/i],Pce=[/\bverifier_verdict\b/i,/"\s*claim\s*"\s*:/i,/\bre-derived\b[^.\n]{0,80}\bindependent/i,/\bindependently\s+(re-derived|re-verified|verified|checked)\b/i,/\bverifier\s+(agrees|disagrees|confirms|refutes)\b/i,/\b(CONFIRMED|REFUTED|UNVERIFIABLE)\b[\s\S]*?\b(CONFIRMED|REFUTED|UNVERIFIABLE)\b/,/\|\s*(claims?|verdicts?)\s*\|/i],Mce=`[framework-generated context: shadow-verify nudge]
|
|
1279
1279
|
|
|
1280
1280
|
The sub-agent that just finished returned output that reads like **decision-driving findings** (verdicts, recommendations, audit conclusions, or claim-style results that could drive file edits, deletions, commits, or external side-effects).
|
|
@@ -1282,7 +1282,7 @@ The sub-agent that just finished returned output that reads like **decision-driv
|
|
|
1282
1282
|
Single-pass sub-agent reports are prone to confident hallucination \u2014 polished output that falls apart on re-derivation. Before acting on these conclusions, consider dispatching \`/shadow-verify\`. Independent verifiers will re-derive the 2\u20133 most load-bearing claims from scratch (without seeing the original reasoning) and flag any that don't hold up.
|
|
1283
1283
|
|
|
1284
1284
|
Skip when: the findings are purely exploratory, the sub-agent ran inside an already-verifying orchestrator, the user is about to dismiss the report, or the stakes are low (read-only Q&A).`,Oce=_ce.map(e=>new RegExp(`(?:^|-)${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:-|$)`,"i"));function $ce(e){return e?Oce.some(t=>t.test(e)):!1}function Dce(e){return Pce.some(t=>t.test(e))}function Fce(e){let t=0;for(let n of Ice)n.test(e)&&t++;return t}function v1(){let e=!1,t=new Set;return n=>{if(n.event==="Stop")return e=!1,{};if(n.event!=="SubagentStop")return{};let r=n.lastMessage??"";return r.length<600?{}:$ce(n.agentType)?{}:Dce(r)?{}:Fce(r)<2?{}:e||t.has(n.subagentId)?{}:(e=!0,t.add(n.subagentId),{injectContext:Mce})}}Kr();jr();var k1=300,Lce="ask_question gate: no interactive operator is attached to this surface (no elicitation handler \u2014 daemon/scheduled/one-shot run), so the question cannot be answered now. The operator has been notified asynchronously. Do not re-ask or wait. Choose the most reasonable interpretation, state the assumption explicitly in your final report for async review, and proceed. If no safe assumption exists and the next action would be irreversible, end the turn with a Blocked terminal state naming exactly what the operator must supply.";function Nce(e){dn(e).catch(()=>{})}function T1(e={}){let t=e.hasHandler??(()=>Xe.hasHandler()),n=e.notify??Nce;return function(o){if(o.event!=="PreToolUse")return{};if(o.toolName!=="ask_question")return{};if(t())return{};try{let s=(typeof o.input=="object"&&o.input!==null?String(o.input.question??""):"").trim(),a=s.length<=k1?s:`${s.slice(0,k1)}\u2026(truncated)`;n(`\u{1F514} AFK question (auto-gated; agent proceeds on a stated assumption):
|
|
1285
|
-
`+(a!==""?a:"(question text unavailable)"))}catch{}return{decision:"block",reason:Lce}}}var Bce="safe-destruct observe-only: destructive-command attempt",Uce=[{id:"rm-recursive-force",re:/\brm\s+-(?=[a-z]*r)(?=[a-z]*f)[a-z]+/i},{id:"rm-recursive-force-split",re:/\brm\s+-[a-z]*r[a-z]*\s+-[a-z]*f|\brm\s+-[a-z]*f[a-z]*\s+-[a-z]*r/i},{id:"rm-recursive-force-long",re:/\brm\s+[^|&;\n]*--recursive\b[^|&;\n]*--force\b|\brm\s+[^|&;\n]*--force\b[^|&;\n]*--recursive\b/i},{id:"rm-no-preserve-root",re:/\brm\b[^|&;\n]*--no-preserve-root\b/i},{id:"git-reset-hard",re:/\bgit\s+reset\s+--hard\b/i},{id:"git-clean-force",re:/\bgit\s+clean\s+-[a-z]*f|\bgit\s+clean\s+[^|&;\n]*--force\b/i},{id:"git-push-force",re:/\bgit\s+push\b[^|&;\n]*--force\b|\bgit\s+push\b[^|&;\n]*(?<![\w-])-f\b/i},{id:"git-branch-force-delete",re:/\bgit\s+branch\s+[^|&;\n]*-D\b/},{id:"dd-to-device",re:/\bof=\/dev\/(?!null\b|zero\b|random\b|urandom\b|stdout\b|stderr\b|tty\b)\S/i},{id:"mkfs",re:/\bmkfs(\.\w+)?\b/i},{id:"redirect-to-block-device",re:/>\s*\/dev\/(sd|nvme|hd|disk|mmcblk|vd)\w*/i},{id:"find-delete",re:/\bfind\b[^|&;\n]*-delete\b|\bfind\b[^|&;\n]*-exec\s+rm\b/i},{id:"shred",re:/\bshred\b/i},{id:"sql-drop-truncate-delete",re:/\b(drop\s+(table|database|schema|index)\b|truncate\s+table\b|delete\s+from\b)/i},{id:"docker-destructive",re:/\bdocker\s+(system\s+prune|volume\s+(rm|prune)|image\s+prune|container\s+prune|network\s+prune)\b|\bdocker\b[^|&;\n]*\brmi?\s+[^|&;\n]*-f/i},{id:"kubectl-delete",re:/\bkubectl\s+delete\b/i},{id:"terraform-destroy",re:/\bterraform\s+destroy\b/i}];function jce(e){if(!e)return[];let t=[];for(let{id:n,re:r}of Uce)r.test(e)&&t.push(n);return t}function E1(){return function(t){if(t.event!=="PreToolUse")return{};if(t.toolName!=="bash")return{};let n=t.input,r=typeof n?.command=="string"?n.command:"";if(!r)return{};let o=jce(r);return o.length===0?{}:{decision:"approve",reason:`${Bce} [${o.join(", ")}]`}}}var Hce="release-boundary observe-only: publish/deploy/sync-boundary command",Wce=[{id:"npm-publish",re:/\bnpm\s+publish\b/i},{id:"pnpm-publish",re:/\bpnpm\s+publish\b/i},{id:"yarn-publish",re:/\byarn\s+(?:npm\s+)?publish\b/i},{id:"cargo-publish",re:/\bcargo\s+publish\b/i},{id:"pypi-twine-upload",re:/\btwine\s+upload\b/i},{id:"poetry-publish",re:/\bpoetry\s+publish\b/i},{id:"gem-push",re:/\bgem\s+push\b/i},{id:"docker-push",re:/\bdocker\s+(?:image\s+)?push\b/i},{id:"gh-release-create",re:/\bgh\s+release\s+create\b/i},{id:"terraform-apply",re:/\bterraform\s+apply\b/i},{id:"kubectl-apply",re:/\bkubectl\s+apply\b/i},{id:"git-push-mirror",re:/\bgit\s+push\b[^|&;\n]*--mirror\b/i},{id:"git-push-tags",re:/\bgit\s+push\b[^|&;\n]*--(?:tags|follow-tags)\b/i}];function Kce(e){if(!e)return[];let t=[];for(let{id:n,re:r}of Wce)r.test(e)&&t.push(n);return t}function R1(){return function(t){if(t.event!=="PreToolUse")return{};if(t.toolName!=="bash")return{};let n=t.input,r=typeof n?.command=="string"?n.command:"";if(!r)return{};let o=Kce(r);return o.length===0?{}:{decision:"approve",reason:`${Hce} [${o.join(", ")}]`}}}kt();ls();Fv();function x1(e){return function(n){if(n.event!=="PreToolUse")return{};if(n.parentSessionId)return{};if(e()!=="plan")return{};let{toolName:r}=n;if(wn(r)==="write")return{decision:"block",reason:`plan mode: ${r} is refused. Use /plan off to exit plan mode.`};if(r==="worktree"){let o=typeof n.input=="object"&&n.input!==null?String(n.input.action??""):"";if(o!=="list")return{decision:"block",reason:`plan mode: worktree "${o}" is refused (mutates the worktree registry). Only action "list" is allowed in plan mode. Use /plan off to act.`}}if(r==="bash"){let o=typeof n.input=="object"&&n.input!==null?String(n.input.command??""):"",i=Ym(o);if(i.mutating)return{decision:"block",reason:`plan mode: bash refused \u2014 command looks state-mutating (${i.reason??"mutation detected"}). Read-only investigation (git status/log/diff, ls, cat, grep, find) is allowed. Use /plan off to act.`}}return{}}}import Cl from"path";Wi();ls();import A1 from"path";var Gce=["rm -rf","rm ","sudo","eval ","chmod","chown","git push --force","git push -f","git reset --hard","mkfs","fdisk","diskutil eraseDisk","dd if=","dd of=","| sh","| bash","|sh","|bash"],qce=["git push","git reset","git commit","git stash drop","git stash clear","npm install","pnpm install","yarn","pip install","apt ","apt-get ","brew install","tee "," > "," >> ","mv ","cp ","mkdir","touch","pnpm build","tsc ","eslint --fix"],zce=["pnpm test","vitest","jest","pytest","cargo test","go test","git status","git log","git diff","git show","ls ","cat ","head ","tail ","find ","grep ","echo ","printf "];function Vce(e){return typeof e=="object"&&e!==null&&"command"in e?String(e.command??""):typeof e=="string"?e:""}function Jce(e){if(typeof e!="object"||e===null)return"";let t=e;return typeof t.file_path=="string"?t.file_path:typeof t.path=="string"?t.path:""}function Yce(e){for(let t of Gce)if(e.includes(t))return"high";for(let t of qce)if(e.includes(t))return"medium";for(let t of zce)if(e.includes(t))return"safe";return"medium"}function Xce(e,t){if(!e)return"safe";let n=
|
|
1285
|
+
`+(a!==""?a:"(question text unavailable)"))}catch{}return{decision:"block",reason:Lce}}}var Bce="safe-destruct observe-only: destructive-command attempt",Uce=[{id:"rm-recursive-force",re:/\brm\s+-(?=[a-z]*r)(?=[a-z]*f)[a-z]+/i},{id:"rm-recursive-force-split",re:/\brm\s+-[a-z]*r[a-z]*\s+-[a-z]*f|\brm\s+-[a-z]*f[a-z]*\s+-[a-z]*r/i},{id:"rm-recursive-force-long",re:/\brm\s+[^|&;\n]*--recursive\b[^|&;\n]*--force\b|\brm\s+[^|&;\n]*--force\b[^|&;\n]*--recursive\b/i},{id:"rm-no-preserve-root",re:/\brm\b[^|&;\n]*--no-preserve-root\b/i},{id:"git-reset-hard",re:/\bgit\s+reset\s+--hard\b/i},{id:"git-clean-force",re:/\bgit\s+clean\s+-[a-z]*f|\bgit\s+clean\s+[^|&;\n]*--force\b/i},{id:"git-push-force",re:/\bgit\s+push\b[^|&;\n]*--force\b|\bgit\s+push\b[^|&;\n]*(?<![\w-])-f\b/i},{id:"git-branch-force-delete",re:/\bgit\s+branch\s+[^|&;\n]*-D\b/},{id:"dd-to-device",re:/\bof=\/dev\/(?!null\b|zero\b|random\b|urandom\b|stdout\b|stderr\b|tty\b)\S/i},{id:"mkfs",re:/\bmkfs(\.\w+)?\b/i},{id:"redirect-to-block-device",re:/>\s*\/dev\/(sd|nvme|hd|disk|mmcblk|vd)\w*/i},{id:"find-delete",re:/\bfind\b[^|&;\n]*-delete\b|\bfind\b[^|&;\n]*-exec\s+rm\b/i},{id:"shred",re:/\bshred\b/i},{id:"sql-drop-truncate-delete",re:/\b(drop\s+(table|database|schema|index)\b|truncate\s+table\b|delete\s+from\b)/i},{id:"docker-destructive",re:/\bdocker\s+(system\s+prune|volume\s+(rm|prune)|image\s+prune|container\s+prune|network\s+prune)\b|\bdocker\b[^|&;\n]*\brmi?\s+[^|&;\n]*-f/i},{id:"kubectl-delete",re:/\bkubectl\s+delete\b/i},{id:"terraform-destroy",re:/\bterraform\s+destroy\b/i}];function jce(e){if(!e)return[];let t=[];for(let{id:n,re:r}of Uce)r.test(e)&&t.push(n);return t}function E1(){return function(t){if(t.event!=="PreToolUse")return{};if(t.toolName!=="bash")return{};let n=t.input,r=typeof n?.command=="string"?n.command:"";if(!r)return{};let o=jce(r);return o.length===0?{}:{decision:"approve",reason:`${Bce} [${o.join(", ")}]`}}}var Hce="release-boundary observe-only: publish/deploy/sync-boundary command",Wce=[{id:"npm-publish",re:/\bnpm\s+publish\b/i},{id:"pnpm-publish",re:/\bpnpm\s+publish\b/i},{id:"yarn-publish",re:/\byarn\s+(?:npm\s+)?publish\b/i},{id:"cargo-publish",re:/\bcargo\s+publish\b/i},{id:"pypi-twine-upload",re:/\btwine\s+upload\b/i},{id:"poetry-publish",re:/\bpoetry\s+publish\b/i},{id:"gem-push",re:/\bgem\s+push\b/i},{id:"docker-push",re:/\bdocker\s+(?:image\s+)?push\b/i},{id:"gh-release-create",re:/\bgh\s+release\s+create\b/i},{id:"terraform-apply",re:/\bterraform\s+apply\b/i},{id:"kubectl-apply",re:/\bkubectl\s+apply\b/i},{id:"git-push-mirror",re:/\bgit\s+push\b[^|&;\n]*--mirror\b/i},{id:"git-push-tags",re:/\bgit\s+push\b[^|&;\n]*--(?:tags|follow-tags)\b/i}];function Kce(e){if(!e)return[];let t=[];for(let{id:n,re:r}of Wce)r.test(e)&&t.push(n);return t}function R1(){return function(t){if(t.event!=="PreToolUse")return{};if(t.toolName!=="bash")return{};let n=t.input,r=typeof n?.command=="string"?n.command:"";if(!r)return{};let o=Kce(r);return o.length===0?{}:{decision:"approve",reason:`${Hce} [${o.join(", ")}]`}}}kt();ls();Fv();function x1(e){return function(n){if(n.event!=="PreToolUse")return{};if(n.parentSessionId)return{};if(e()!=="plan")return{};let{toolName:r}=n;if(wn(r)==="write")return{decision:"block",reason:`plan mode: ${r} is refused. Use /plan off to exit plan mode.`};if(r==="worktree"){let o=typeof n.input=="object"&&n.input!==null?String(n.input.action??""):"";if(o!=="list")return{decision:"block",reason:`plan mode: worktree "${o}" is refused (mutates the worktree registry). Only action "list" is allowed in plan mode. Use /plan off to act.`}}if(r==="bash"){let o=typeof n.input=="object"&&n.input!==null?String(n.input.command??""):"",i=Ym(o);if(i.mutating)return{decision:"block",reason:`plan mode: bash refused \u2014 command looks state-mutating (${i.reason??"mutation detected"}). Read-only investigation (git status/log/diff, ls, cat, grep, find) is allowed. Use /plan off to act.`}}return{}}}import Cl from"path";Wi();ls();import A1 from"path";var Gce=["rm -rf","rm ","sudo","eval ","chmod","chown","git push --force","git push -f","git reset --hard","mkfs","fdisk","diskutil eraseDisk","dd if=","dd of=","| sh","| bash","|sh","|bash"],qce=["git push","git reset","git commit","git stash drop","git stash clear","npm install","pnpm install","yarn","pip install","apt ","apt-get ","brew install","tee "," > "," >> ","mv ","cp ","mkdir","touch","pnpm build","tsc ","eslint --fix"],zce=["pnpm test","vitest","jest","pytest","cargo test","go test","git status","git log","git diff","git show","ls ","cat ","head ","tail ","find ","grep ","echo ","printf "];function Vce(e){return typeof e=="object"&&e!==null&&"command"in e?String(e.command??""):typeof e=="string"?e:""}function Jce(e){if(typeof e!="object"||e===null)return"";let t=e;return typeof t.file_path=="string"?t.file_path:typeof t.path=="string"?t.path:""}function Yce(e){for(let t of Gce)if(e.includes(t))return"high";for(let t of qce)if(e.includes(t))return"medium";for(let t of zce)if(e.includes(t))return"safe";return"medium"}function Xce(e,t){if(!e)return"safe";let n=Ue(A1.resolve(t.cwd,e)),r=pk();for(let o of r)if(n===o||n.startsWith(o+"/"))return"high";if(n.includes("/.git/"))return"high";if(t.workspaceRoot!==void 0){let o=Ue(t.workspaceRoot);if(A1.relative(o,n).startsWith(".."))return"high"}return n.includes("/node_modules/")?"medium":"safe"}var Qce=new Set(["delete","drop","remove","destroy","truncate","purge","wipe","write","create","update","insert","upsert","patch","rename","exec","execute","run","eval","send","push","publish","deploy","post","merge","rollback","reset","terminate","provision","scale","disable","charge","refund","revoke"]);function Zce(e){return e.split("__").slice(1).join("__").split(/[_-]+/).filter(Boolean)}function C1(e,t,n){let r=e.toLowerCase();if(r==="bash"){let o=Vce(t);return Yce(o)}if(r==="write_file"||r==="edit_file"){let o=Jce(t);return Xce(o,n)}if(wn(e)==="read")return"safe";if(r==="send_telegram")return"medium";if(r.startsWith("mcp__"))return Zce(r).some(i=>Qce.has(i))?"high":"medium";if(r==="create_schedule"||r==="cancel_schedule")return"high";if(r==="worktree"){let o=typeof t=="object"&&t!==null?t:{},i=typeof o.action=="string"?o.action:"";return i==="list"?"safe":i==="remove"&&o.force===!0?"high":"medium"}return r==="browser_act"||r==="browser_open"||r==="web_scrape"?"medium":"safe"}Kr();pe();vo();KT();Wi();import nx from"path";import{lstatSync as eue}from"fs";import{spawnSync as tue}from"child_process";var nue=new Set(["node_modules","dist","build",".next","coverage",".cache","__pycache__",".turbo",".parcel-cache","out","target"]),rue=/[*?$`(){};|&<>'"\\\r\n]/;function oue(e){return e==="--recursive"?!0:e.startsWith("--")?!1:/^-[A-Za-z]+$/.test(e)&&/[rR]/.test(e)}function iue(e){if(!/^rm\b/.test(e)||rue.test(e))return null;let t=e.trim().split(/\s+/),n=[],r=!1,o=!1;for(let i of t.slice(1)){if(!o&&i==="--"){o=!0;continue}if(!o&&i.startsWith("-")){oue(i)&&(r=!0);continue}n.push(i)}return n.length===0?null:{targets:n,recursive:r}}function sue(e,t){try{return eue(e).isDirectory()?tue("git",["check-ignore","--quiet","--",e],{cwd:t,stdio:"ignore"}).status===0:!1}catch(n){return n.code==="ENOENT"}}function _1(e,t,n){let r=iue(e);if(r===null||!r.recursive)return!1;let o=Ue(n);for(let i of r.targets){if(i==="/"||i==="."||i===".."||i==="~"||i.startsWith("~/")||i==="$HOME"||i.startsWith("$HOME/")||i===".git"||i.startsWith(".git/"))return!1;let s=Ue(nx.resolve(t,i));if(s===o||!s.startsWith(o+nx.sep)||!nue.has(nx.basename(s))||!sue(s,o))return!1}return!0}var aue=3e5,I1=300;function P1(e,t,n,r){let o=r?.approvalTimeoutMs??aue,i=r?.promptForApproval??!0,s=r?.traceWriter,a=r?.sessionId,l=r?.route??((u,d)=>Xe.route(u,d));async function c(u,d,m,f){let g=Date.now(),h=lue(u,d),y=new AbortController,b=()=>y.abort();m&&(m.aborted?y.abort():m.addEventListener("abort",b,{once:!0}));let w=Symbol("afk-approval-timeout"),v,S,E=new Promise(A=>{S=()=>{v||(v=setTimeout(()=>{y.abort(),A(w)},o),v.unref?.())}});function x(A,C){let P=Date.now()-g,N=A.decision==="block";return sn(s,{hookEvent:"PreToolUse",...N?{decision:"block"}:{},...N&&A.reason!==void 0?{reason:A.reason}:{},...N?{blockedTool:u}:{},durationMs:P,approvalOutcome:C}),A}let D;try{let A=f??a;D=await Promise.race([l(h,{signal:y.signal,onActive:S,...A!==void 0?{sessionId:A}:{}}),E])}finally{v&&clearTimeout(v),m&&m.removeEventListener("abort",b)}if(D===w)return x(Nd(u,`no approval arrived within ${Math.round(o/1e3)}s`),"timeout");if(D.action!=="accept")return x(Nd(u,D.action==="cancel"?"the operator cancelled the approval prompt":"no operator approval was available"),D.action==="cancel"?"cancel":"decline");let I=String(D.content?.choice??"").toLowerCase();return I==="approve"?x({},"approved"):I==="deny"?x(Nd(u,"the operator denied it"),"denied"):x(Nd(u,"the approval prompt returned an unrecognised choice"),"unrecognised")}return function(d,m){if(d.event!=="PreToolUse")return{};if(e()!=="autonomous")return{};let{toolName:f}=d,g=Date.now();if(f==="send_telegram")return{};let h=n?.()??t??process.cwd(),y=d.cwd,b=y??h,v=(y!==void 0?uue(y,h):void 0)??h,S=C1(f,d.input,{cwd:b,workspaceRoot:v});if(S==="high"&&f==="bash"){let E=typeof d.input=="object"&&d.input!==null&&"command"in d.input?String(d.input.command??""):"";if(E&&_1(E,b,v))return sn(s,{hookEvent:"PreToolUse",blockedTool:f,durationMs:Date.now()-g,approvalOutcome:"carve-out"}),{}}if(S!=="high")return{};if(d.parentSessionId!==void 0||!i){let E=Nd(f,"AFK mode runs autonomously without a human watching");return sn(s,{hookEvent:"PreToolUse",decision:"block",...E.reason!==void 0?{reason:E.reason}:{},blockedTool:f,durationMs:Date.now()-g,approvalOutcome:"hard-block"}),E}return c(f,d.input,m,d.sessionId)}}function lue(e,t){let n=cue(t);return{serverName:"agent-afk",message:`AFK: \`${e}\` is high-risk / irreversible and AFK mode runs unattended. Approve this single call?`+(n?`
|
|
1286
1286
|
|
|
1287
1287
|
Input: ${n}`:""),mode:"form",title:"AFK high-risk approval",requestedSchema:{type:"object",properties:{choice:{type:"string",title:"Approve this high-risk operation?",enum:["approve","deny"],description:"'approve' runs this single call. 'deny' refuses it (the model gets an error and should push an Asking summary or take a safe path)."}},required:["choice"]}}}function cue(e){let t;try{t=typeof e=="string"?e:JSON.stringify(e)}catch{t=String(e)}return t?(t=De(t),t.length>I1?`${t.slice(0,I1)}\u2026 [truncated]`:t):""}function Nd(e,t){return{decision:"block",reason:`AFK mode: ${e} is refused \u2014 this op is high-risk or irreversible, and ${t}. Push an Asking summary to Telegram (send_telegram) and stop, or have the operator run /afk off and take over.`}}function uue(e,t){let n=Cl.resolve(e),r=Cl.resolve(t);if(n===r)return r;let o=Cl.relative(r,n);if(o!==""&&!o.startsWith("..")&&!Cl.isAbsolute(o))return Qa(n)??n;let i=Qa(r),s=Qa(n);if(i!==void 0&&s!==void 0&&Cl.dirname(i)===Cl.dirname(s))return s}Qe();os();import{mkdirSync as mue,rmSync as fue,writeFileSync as gue}from"fs";import{join as rx}from"path";Le();Km();function due(e){let t=new Set;for(let a of e.nodes){if(t.has(a.id))throw new Error(`Duplicate node ID: ${a.id}`);t.add(a.id)}let n=new Set;for(let a of e.edges){if(!t.has(a.from))throw new Error(`Edge references non-existent node: ${a.from}`);if(!t.has(a.to))throw new Error(`Edge references non-existent node: ${a.to}`);let l=`${a.from}->${a.to}`;if(n.has(l))throw new Error(`Duplicate edge: ${a.from} -> ${a.to}`);n.add(l)}let r=M1(e),o=new Map(r.inDegree),i=[];for(let[a,l]of o)l===0&&i.push(a);let s=0;for(;i.length>0;){let a=i.shift();s+=1;for(let l of r.downstream.get(a)??[]){let c=o.get(l)-1;o.set(l,c),c===0&&i.push(l)}}if(s!==t.size)throw new Error("Cycle detected in DAG")}function M1(e){let t=new Map,n=new Map,r=new Map;for(let o of e.nodes)t.set(o.id,new Set),n.set(o.id,new Set),r.set(o.id,0);for(let o of e.edges)t.get(o.from).add(o.to),n.get(o.to).add(o.from),r.set(o.to,r.get(o.to)+1);return{downstream:t,upstream:n,inDegree:r}}function pue(e,t,n){let r=[e];for(;r.length>0;){let o=r.shift();for(let i of t.get(o)??[])n.has(i)||(n.add(i),r.push(i))}}async function O1(e,t,n={}){if(e.nodes.length===0)return{outputs:{},failed:[],skipped:[]};due(e);let{failFast:r=!0,nodeTimeoutMs:o,maxConcurrency:i=du()}=n,s=o!==void 0&&Number.isFinite(o)&&o>0,a=M1(e),l=new Map(e.nodes.map(y=>[y.id,y])),c={},u=[],d=new Set,m=new Set,f=new Map(a.inDegree),g=new AbortController,h=()=>{g.signal.aborted||g.abort(t.reason)};t.aborted?g.abort(t.reason):t.addEventListener("abort",h,{once:!0});try{for(;!g.signal.aborted;){let y=[];for(let[w,v]of f)v===0&&!m.has(w)&&!d.has(w)&&y.push(w);if(y.length===0)break;let b=await Ra(y,i,async w=>{let v=l.get(w),S=new AbortController,E=()=>{S.signal.aborted||S.abort(g.signal.reason)};g.signal.aborted?S.abort(g.signal.reason):g.signal.addEventListener("abort",E,{once:!0});let x;s&&!S.signal.aborted&&(x=setTimeout(()=>{S.signal.aborted||S.abort(new rt(`DAG node "${w}" exceeded nodeTimeoutMs of ${o}ms`,o))},o));let D={};for(let I of a.upstream.get(w)??[])D[I]=c[I];try{let I=await v.run(D,S.signal);return{id:w,result:I}}finally{x!==void 0&&clearTimeout(x),g.signal.removeEventListener("abort",E)}});for(let w=0;w<b.length;w++){let v=b[w];if(v.status==="fulfilled"){let{id:S,result:E}=v.value;c[S]=E,m.add(S),f.delete(S);for(let x of a.downstream.get(S)??[])f.set(x,f.get(x)-1)}else{let S=v.reason instanceof Error?v.reason:new Error(String(v.reason)),E=y[w];u.push({id:E,error:S}),m.add(E),f.delete(E),pue(E,a.downstream,d),r&&g.abort("fail-fast")}}}}finally{t.removeEventListener("abort",h)}return{outputs:c,failed:u,skipped:Array.from(d)}}ct();Le();Uo();cR();async function Ty(e){let{manager:t,parentSession:n,nodes:r,edges:o,failFast:i,nodeTimeoutMs:s}=e,a=n.abortSignal??new AbortController().signal,l=[s??0,Wh()].filter(d=>d>0),c=l.length>0?uh(Math.min(...l)):0,u=r.map(d=>({id:d.id,async run(m,f){let g=await t.forkSubagent({parent:{sessionId:n.sessionId},config:{model:d.model??"sonnet",systemPrompt:d.systemPrompt,...d.canUseTool!==void 0?{canUseTool:d.canUseTool}:{},...d.cwd!==void 0?{cwd:d.cwd}:{},...d.readRoots!==void 0?{readRoots:d.readRoots}:{},...d.writeRoots!==void 0?{writeRoots:d.writeRoots}:{},...d.apiKey!==void 0?{apiKey:d.apiKey}:{},...d.maxToolUseIterations!==void 0?{maxToolUseIterations:d.maxToolUseIterations}:{},...c!==0?{softDeadlineMs:c}:{}},idPrefix:d.idPrefix??`dag-${d.id}`,...d.outputSchema!==void 0?{outputSchema:d.outputSchema}:{},agentType:d.agentType??d.idPrefix??`dag-${d.id}`,...d.parentId!==void 0?{parentId:d.parentId}:{}}),h=()=>{g.cancel().catch(()=>{})};f.aborted?g.cancel().catch(()=>{}):f.addEventListener("abort",h,{once:!0});try{if(f.aborted)throw new DOMException("Aborted","AbortError");let y=d.promptBuilder(m),b=await g.runToResult(y);if(b.status!=="succeeded"){let v,S=f.reason;throw S instanceof rt?v=new Error(`Subagent ${d.id} aborted: ${S.message}`,b.error?{cause:b.error}:{}):v=b.error??new Error(`Subagent ${d.id} ${b.status}`),FL(v,{partialOutput:b.partialOutput,subagentId:b.id})}if(b.output!==void 0)return b.output;let w=b.message?.content;return typeof w=="string"?Gn(w,b.stopReason):w}finally{f.removeEventListener("abort",h),await g.teardown().catch(()=>{})}}}));return O1({nodes:u,edges:o},a,{failFast:i,nodeTimeoutMs:s})}Ne();Dn();ns();qr();Kn();gd();G();var $1=1e3,Ey=36e5,D1=1,F1=1e3;function hue(e){if(typeof e!="object"||e===null)throw new Error("Compose tool input must be an object");let t=e,n=t.nodes;if(!Array.isArray(n)||n.length===0)throw new Error('Compose tool requires a non-empty "nodes" array');let r=20;if(n.length>r)throw new Error(`Compose tool supports at most ${r} nodes (got ${n.length}). Split into multiple compose calls for larger workloads.`);let o=[],i=new Set;for(let g of n){if(typeof g!="object"||g===null)throw new Error("Each node must be an object");let h=g,y=h.id;if(typeof y!="string"||y.trim().length===0)throw new Error('Each node must have a non-empty "id" string');if(!/^[A-Za-z0-9_-]+$/.test(y)){let v=y.replace(/[\x00-\x1f\x7f]/g,"?").slice(0,32);throw new Error(`Node id "${v}" must match /^[A-Za-z0-9_-]+$/ (alphanumeric, underscore, hyphen)`)}if(i.has(y))throw new Error(`Duplicate node ID: ${y}`);i.add(y);let b=h.prompt;if(typeof b!="string"||b.trim().length===0)throw new Error(`Node "${y}" must have a non-empty "prompt" string`);let w;if(h.model!==void 0){if(typeof h.model!="string")throw new Error(`Node "${y}" model must be a string`);w=h.model}o.push({id:y,prompt:b,model:w})}let s;if(t.edges!==void 0){if(!Array.isArray(t.edges))throw new Error('"edges" must be an array');s=[];for(let g of t.edges){if(typeof g!="object"||g===null)throw new Error("Each edge must be an object");let h=g;if(typeof h.from!="string"||typeof h.to!="string")throw new Error('Each edge must have "from" and "to" strings');if(!i.has(h.from))throw new Error(`Edge references non-existent node: ${h.from}`);if(!i.has(h.to))throw new Error(`Edge references non-existent node: ${h.to}`);s.push({from:h.from,to:h.to})}}let a;if(t.fail_fast!==void 0){if(typeof t.fail_fast!="boolean")throw new Error('"fail_fast" must be a boolean');a=t.fail_fast}let l=[],c;if(t.node_timeout_ms!==void 0){let g=t.node_timeout_ms;if(typeof g!="number"||!Number.isFinite(g)||g<=0)throw new Error('"node_timeout_ms" must be a positive finite number (milliseconds)');if(g<$1)throw new Error(`"node_timeout_ms" must be at least ${$1}ms (got ${g}). Sub-second timeouts are almost always a unit mistake.`);c=Math.min(Ey,g),g>Ey&&l.push(`node_timeout_ms clamped: requested ${g}ms exceeds the maximum ${Ey}ms; using ${Ey}ms.`)}let u="max_tool_rounds_per_node",d="max_tool_calls_per_node",m=t[u]!==void 0?u:d;t[u]!==void 0&&t[d]!==void 0?l.push(`both "${u}" and the deprecated "${d}" were supplied; using "${u}" and ignoring the deprecated key.`):t[d]!==void 0&&l.push(`"${d}" is deprecated \u2014 use "${u}". The unit is tool-use ROUNDS (a round with N parallel calls costs 1), and spending the budget now triggers a tools-stripped wind-down round instead of cancelling the node.`);let f;if(t[m]!==void 0){let g=t[m];if(typeof g!="number"||!Number.isFinite(g)||g<=0)throw new Error(`"${m}" must be a positive finite number`);if(!Number.isInteger(g))throw new Error(`"${m}" must be an integer (got ${g}). Tool-use rounds are discrete events; fractional budgets are not meaningful.`);if(g<D1)throw new Error(`"${m}" must be at least ${D1}`);if(g>F1)throw new Error(`"${m}" must be at most ${F1} (got ${g}). A larger budget no longer constrains useful work.`);f=g}return{parsed:{nodes:o,edges:s,fail_fast:a,node_timeout_ms:c,max_tool_rounds_per_node:f},warnings:l}}var Bd=8e3,L1=500,N1=4e3;function yue(e){if(e==null)return;let t=typeof e=="string"?e:JSON.stringify(e);if(t.length!==0)return t.length>N1?t.slice(0,N1)+`
|
|
1288
1288
|
\u2026 (truncated)`:t}function bue(e,t,n,r){try{let o=rx(pt(),e,"compose",t);mue(o,{recursive:!0});let i=rx(o,`${n}.txt`);return gue(i,r,"utf8"),i}catch{return}}function wue(e,t){let n=[],r=[];for(let[o,i]of Object.entries(e.outputs)){let s=typeof i=="string"?i:i!=null?JSON.stringify(i):"(no output)",a;if(s.length>Bd){let l=bue(t.sessionId,t.callId,o,s);r.push({nodeId:o,emittedChars:Bd,totalChars:s.length,...l!==void 0?{spillPath:l}:{}});let c=l!==void 0?`
|
|
@@ -1628,7 +1628,7 @@ Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
|
1628
1628
|
`)){let l=bx(a),c=fe(l,o);for(let u of c.split(`
|
|
1629
1629
|
`))s.push(i+r+u)}return s}var UG=6,hp=class{entries=new Map;order=[];agentIdStack=[];addStart(t,n,r){let o=$e(r),i=ro(n+o),s=this.agentIdStack.at(-1)??void 0,a={kind:"tool",toolUseId:t,toolName:n,toolInput:o,prefix:i,...s!==void 0?{agentContext:s}:{}};this.entries.set(t,a),this.order.push(t),Ho.has(n)&&this.agentIdStack.push(t)}addStartWithAgentContext(t,n,r,o,i){let s=$e(r),a=this.entries.get(t);if(a?.kind==="tool"){a.toolInput=s,a.prefix=ro(n+s,i),o!==void 0&&(a.agentContext=o);return}let l=ro(n+s,i),c={kind:"tool",toolUseId:t,toolName:n,toolInput:s,prefix:l,...o!==void 0?{agentContext:o}:{}};this.entries.set(t,c),this.order.push(t)}mergeAgentLabel(t,n,r){let o=this.entries.get(t);if(o?.kind!=="tool"||!Ho.has(o.toolName)||o.toolName==="Agent")return!1;let s=`(${$e(n)})`;return o.toolName="Agent",o.toolInput=s,o.prefix=ro("Agent"+s,r),!0}setAgentContext(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(n===void 0?delete r.agentContext:r.agentContext=n)}setAgentResultSummary(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(r.agentResultSummary=n)}setThinkingTail(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(n===void 0?delete r.thinkingTail:r.thinkingTail=n)}addResult(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(r.result=n),this.agentIdStack.at(-1)===t&&this.agentIdStack.pop()}addDiff(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(r.diff=n)}upsertTextChild(t,n,r){let o=this.entries.get(t);if(o?.kind==="text"){o.text=r,o.agentContext=n;return}let i={kind:"text",toolUseId:t,text:r,agentContext:n};this.entries.set(t,i),this.order.push(t)}removeTextChildrenUnder(t){let n=[];for(let[r,o]of this.entries)o.kind==="text"&&o.agentContext===t&&n.push(r);for(let r of n)this.entries.delete(r);if(n.length>0){let r=new Set(n);this.order=this.order.filter(o=>!r.has(o))}}hasPending(){return this.entries.size>0}hasEntry(t){return this.entries.get(t)?.kind==="tool"}findLastSkillEntryId(){for(let t=this.order.length-1;t>=0;t--){let n=this.order[t],r=this.entries.get(n);if(r?.kind==="tool"&&md.has(r.toolName))return n}}peekTrailingCompletedRootToolName(){for(let t=this.order.length-1;t>=0;t--){let n=this.order[t],r=this.entries.get(n);if(!(!r||r.kind!=="tool")&&!r.agentContext)return r.result===void 0||ze.has(r.toolName)?void 0:r.toolName}}getOverlay(){let t=this.buildChildMap(),n=[],r=Vn(),o=xn(),i=d=>ae(d,o),s=[];for(let d of this.order){let m=this.entries.get(d);!m||m.kind!=="tool"||m.agentContext||s.push(m)}let a=s,l=0;if(s.length>UG){let d=s.filter(h=>!h.result),m=s.filter(h=>h.result),f=Math.max(0,UG-d.length),g=new Set(m.slice(-f));l=m.length-g.size,a=s.filter(h=>!h.result||g.has(h))}let u=a.some(d=>ze.has(d.toolName))?p.dim(r.turnRoot):" ";for(let d of a){let m=t.get(d.toolUseId);if(ze.has(d.toolName)&&m&&m.length>0)d.headerEmitted?n.push(i(p.dim(r.turnRoot))):n.push(i(p.dim(r.turnRoot)+d.prefix)),Rb(m,t,n,o,void 0,r),d.thinkingTail&&n.push(i(p.dim(r.spine)+p.thinking("\u2307 "+Oe(d.thinkingTail))));else if(!(ze.has(d.toolName)&&d.headerEmitted))if(ze.has(d.toolName))d.result?n.push(i(p.dim(r.turnRoot)+d.prefix+p.dim(" \u2014 ")+ci(d.result.isError,d.result.failureClass)+" "+lo(d.result,void 0,60,d.toolName)+Ds(d.result))):n.push(i(p.dim(r.turnRoot)+d.prefix+p.dim(" \u2026"))),d.thinkingTail&&n.push(i(p.dim(r.spine)+p.thinking("\u2307 "+Oe(d.thinkingTail))));else if(d.result){if(n.push(i(u+d.prefix+p.dim(" \u2014 ")+ci(d.result.isError,d.result.failureClass)+" "+lo(d.result,void 0,60,d.toolName)+Ds(d.result))),d.diff&&!d.result.isError)for(let f of ao(d.diff,"overlay"," "))n.push(i(f))}else n.push(i(u+d.prefix+p.dim(" \u2026"))),d.thinkingTail&&n.push(i(p.dim(r.spine)+p.thinking("\u2307 "+Oe(d.thinkingTail))))}return l>0&&n.push(i(" "+p.dim(`\u2026 +${l} done`))),n.join(`
|
|
1630
1630
|
`)}ancestorDepthOf(t){let n=new Set([t]),r=0,o=t,i=32;for(;o!==void 0&&r<i;){let s=this.entries.get(o);if(!s||s.kind!=="tool")break;let a=s.agentContext;if(a===void 0||n.has(a))break;n.add(a);let l=this.entries.get(a);if(!l||l.kind!=="tool")break;r+=1,o=a}return r}flushSource(t,n){let r=this.entries.get(t);if(!r||r.kind!=="tool")return[];let o=Array.from({length:this.ancestorDepthOf(t)},()=>!1),i=[];{let m=[],f=new Set([t]),g=r.agentContext;for(;g!==void 0&&!f.has(g);){f.add(g);let h=this.entries.get(g);if(!h||h.kind!=="tool")break;m.push({entry:h,depth:this.ancestorDepthOf(h.toolUseId)}),g=h.agentContext}m.reverse();for(let{entry:h,depth:y}of m)h.headerEmitted||(i.push(tA(h,Array.from({length:y},()=>!1))),h.headerEmitted=!0)}let s=new Set([t]),a=[t];for(;a.length>0;){let m=a.shift();for(let[f,g]of this.entries){if(s.has(f))continue;(g.kind==="tool",g.agentContext)===m&&(s.add(f),g.kind==="tool"&&a.push(f))}}let l=new Map;for(let m of this.order){if(!s.has(m))continue;let f=this.entries.get(m);if(!f)continue;let g=(f.kind==="tool",f.agentContext);if(!g)continue;let h=l.get(g);h||(h=[],l.set(g,h)),h.push(f)}let c=l.get(r.toolUseId)??[],u=r.headerEmitted?gp(r,c,l,n,o).join(`
|
|
1631
|
-
`):fp(r,c,l,n,o);for(let m of s)this.entries.delete(m);this.order=this.order.filter(m=>!s.has(m));let d=u===""?[]:[u];return[...i,...d]}flushCompletedRoots(t){if(this.entries.size===0)return[];let n=this.buildChildMap(),r=[];for(let c of this.order){let u=this.entries.get(c);!u||u.kind!=="tool"||u.agentContext||u.result!==void 0&&r.push(c)}if(r.length===0)return[];let o=[],i=new Map,s=[];for(let c of r){let u=this.entries.get(c);if(!u||u.kind!=="tool")continue;let d=n.get(u.toolUseId);if(ze.has(u.toolName))if(o.push(...rc(i,s,t)),i.clear(),s.length=0,u.headerEmitted){let m=gp(u,d??[],n,t,[]);o.push(...m)}else o.push(fp(u,d??[],n,t));else i.has(u.toolName)||(i.set(u.toolName,[]),s.push(u.toolName)),i.get(u.toolName).push(u)}o.push(...rc(i,s,t));let a=new Set(r),l=[...r];for(;l.length>0;){let c=l.shift();for(let[u,d]of this.entries){if(a.has(u))continue;(d.kind==="tool",d.agentContext)===c&&(a.add(u),d.kind==="tool"&&l.push(u))}}for(let c of a)this.entries.delete(c);return this.order=this.order.filter(c=>!a.has(c)),o}flush(t){if(this.entries.size===0)return[];let n=this.buildChildMap(),r=[];for(let a of this.order){let l=this.entries.get(a);!l||l.kind!=="tool"||l.agentContext||r.push(a)}let o=[],i=new Map,s=[];for(let a of r){let l=this.entries.get(a);if(!l||l.kind!=="tool")continue;let c=n.get(l.toolUseId);if(ze.has(l.toolName))if(o.push(...rc(i,s,t)),i.clear(),s.length=0,l.headerEmitted){let u=gp(l,c??[],n,t,[]);o.push(...u)}else o.push(fp(l,c??[],n,t));else i.has(l.toolName)||(i.set(l.toolName,[]),s.push(l.toolName)),i.get(l.toolName).push(l)}return o.push(...rc(i,s,t)),this.entries.clear(),this.order=[],this.agentIdStack=[],o}buildChildMap(){let t=new Map;for(let n of this.order){let r=this.entries.get(n);if(!r)continue;let o=(r.kind==="tool",r.agentContext);if(!o)continue;let i=t.get(o);i||(i=[],t.set(o,i)),i.push(r)}return t}};ue();function rA(e,t){let n=Math.max(0,e),r=n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`,o=Math.ceil(t/4);return` ${p.thinking("\u25C6 thought for "+r+" \xB7 "+o+" tok")}`}var oc=class{buffer="";startedAt=null;endedAt=null;hasEmitted=!1;committedUpTo=0;push(t){this.hasEmitted||(this.buffer+=t,this.startedAt||(this.startedAt=Date.now()))}markEnded(){this.endedAt===null&&this.startedAt!==null&&(this.endedAt=Date.now())}isActive(){return!this.hasEmitted}hasBufferedContent(){return this.buffer.trim().length>0}peek(){return this.buffer}consume(){return this.hasEmitted=!0,this.buffer}peekPhase(){return this.buffer.slice(this.committedUpTo)}drainPhase(){let t=this.buffer.slice(this.committedUpTo);return this.committedUpTo=this.buffer.length,t}collapse(){if(this.hasEmitted||!this.startedAt)return!this.startedAt&&!this.hasEmitted&&
|
|
1631
|
+
`):fp(r,c,l,n,o);for(let m of s)this.entries.delete(m);this.order=this.order.filter(m=>!s.has(m));let d=u===""?[]:[u];return[...i,...d]}flushCompletedRoots(t){if(this.entries.size===0)return[];let n=this.buildChildMap(),r=[];for(let c of this.order){let u=this.entries.get(c);!u||u.kind!=="tool"||u.agentContext||u.result!==void 0&&r.push(c)}if(r.length===0)return[];let o=[],i=new Map,s=[];for(let c of r){let u=this.entries.get(c);if(!u||u.kind!=="tool")continue;let d=n.get(u.toolUseId);if(ze.has(u.toolName))if(o.push(...rc(i,s,t)),i.clear(),s.length=0,u.headerEmitted){let m=gp(u,d??[],n,t,[]);o.push(...m)}else o.push(fp(u,d??[],n,t));else i.has(u.toolName)||(i.set(u.toolName,[]),s.push(u.toolName)),i.get(u.toolName).push(u)}o.push(...rc(i,s,t));let a=new Set(r),l=[...r];for(;l.length>0;){let c=l.shift();for(let[u,d]of this.entries){if(a.has(u))continue;(d.kind==="tool",d.agentContext)===c&&(a.add(u),d.kind==="tool"&&l.push(u))}}for(let c of a)this.entries.delete(c);return this.order=this.order.filter(c=>!a.has(c)),o}flush(t){if(this.entries.size===0)return[];let n=this.buildChildMap(),r=[];for(let a of this.order){let l=this.entries.get(a);!l||l.kind!=="tool"||l.agentContext||r.push(a)}let o=[],i=new Map,s=[];for(let a of r){let l=this.entries.get(a);if(!l||l.kind!=="tool")continue;let c=n.get(l.toolUseId);if(ze.has(l.toolName))if(o.push(...rc(i,s,t)),i.clear(),s.length=0,l.headerEmitted){let u=gp(l,c??[],n,t,[]);o.push(...u)}else o.push(fp(l,c??[],n,t));else i.has(l.toolName)||(i.set(l.toolName,[]),s.push(l.toolName)),i.get(l.toolName).push(l)}return o.push(...rc(i,s,t)),this.entries.clear(),this.order=[],this.agentIdStack=[],o}buildChildMap(){let t=new Map;for(let n of this.order){let r=this.entries.get(n);if(!r)continue;let o=(r.kind==="tool",r.agentContext);if(!o)continue;let i=t.get(o);i||(i=[],t.set(o,i)),i.push(r)}return t}};ue();function rA(e,t){let n=Math.max(0,e),r=n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`,o=Math.ceil(t/4);return` ${p.thinking("\u25C6 thought for "+r+" \xB7 "+o+" tok")}`}var oc=class{buffer="";startedAt=null;endedAt=null;hasEmitted=!1;committedUpTo=0;push(t){this.hasEmitted||(this.buffer+=t,this.startedAt||(this.startedAt=Date.now()))}markEnded(){this.endedAt===null&&this.startedAt!==null&&(this.endedAt=Date.now())}isActive(){return!this.hasEmitted}hasBufferedContent(){return this.buffer.trim().length>0}peek(){return this.buffer}consume(){return this.hasEmitted=!0,this.buffer}peekPhase(){return this.buffer.slice(this.committedUpTo)}drainPhase(){let t=this.buffer.slice(this.committedUpTo);return this.committedUpTo=this.buffer.length,t}collapse(){if(this.hasEmitted||!this.startedAt)return!this.startedAt&&!this.hasEmitted&&He()&&console.error("[afk:thinking] collapse() short-circuited: no thinking chunks received this turn. Model may not support extended thinking, or API ignored the thinking parameter."),null;this.hasEmitted=!0;let t=this.endedAt??Date.now();return rA(t-this.startedAt,this.buffer.length)}inlineSummary(){if(!this.startedAt||!this.hasBufferedContent())return null;let t=this.endedAt??Date.now(),n=Math.max(0,t-this.startedAt),r=n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`,o=Math.ceil(this.buffer.length/4);return`thought ${r} \xB7 ${o} tok`}};var Fs="__main__";function HG(e){let t={startedAt:Date.now(),lastEventAt:Date.now(),stats:{tokens:0,toolUses:0},contentBuffer:"",done:!1,errored:!1,stalledTicks:0};return e!==void 0&&(t.agentType=e),t}function yp(e,t){return{type:"tool_result",toolUseId:"synthetic",content:e,isError:t}}function WG(e){let t=["Done"],n=[];e.stats.toolUses&&n.push(Qo(e.stats.toolUses)),e.stats.tokens&&n.push(`${he(e.stats.tokens)} tok`);let r=e.responseMetadata?.durationMs,o=Date.now()-e.startedAt;typeof r=="number"&&(n.push(Ae(r)),o>r*1.5&&o-r>=1e3&&n.push(`${Ae(o)} wall`)),n.length===0&&o>0&&n.push(Ae(o));let i=e.thinkingLane?.inlineSummary();return i&&n.push(i),n.length>0&&t.push(`(${n.join(" \xB7 ")})`),t.join(" ")}var bge=3e3,Ab=8e3;function wge(e,t){let n=[];for(let[r,o]of e)r!==Fs&&(o.done||o.errored||n.push({sourceId:r,source:o,silentMs:Math.max(0,t-o.lastEventAt)}));return n}function Sge(e){if(e.silentMs>=Ab)return"no output (waiting)";let t=e.source.lastProgressSummary;if(t)return t;let n=e.source.stats.toolUses;if(n>0)return Qo(n)}var xb=class{prev;select(t,n=Date.now()){let r=wge(t,n);if(r.length===0){this.prev=void 0;return}r.sort((c,u)=>c.silentMs-u.silentMs||c.sourceId.localeCompare(u.sourceId));let o=r[0],i=this.prev?r.find(c=>c.sourceId===this.prev):void 0,a=i!==void 0&&(i.silentMs<bge||o.sourceId===i.sourceId)?i:o;this.prev=a.sourceId;let l=Sge(a);if(l!==void 0)return{sourceId:a.sourceId,label:a.source.agentType??a.sourceId,clause:l,quiet:a.silentMs>=Ab}}reset(){this.prev=void 0}};function vge(e){return`${e.label} \xB7 ${e.clause}`}function Cb(e,t=Date.now()){if(!e.sources||!e.childActivity)return;let n=e.childActivity.select(e.sources,t);if(!n)return;let r=e.sources.get(n.sourceId);if(r)return{activity:vge(n),stats:{toolUses:r.stats.toolUses,totalTokens:r.stats.tokens,durationMs:Math.max(0,t-r.startedAt)}}}var kge="__child_activity__";function _b(e){return{taskId:kge,description:"Working",totalTokens:e.totalTokens,toolUses:e.toolUses,durationMs:e.durationMs}}function iA(e){let t=Math.max(1,oe()-2);return Math.max(1,Ut(t-e))}function KG(e,t){return Tge(e)?So(e,{maxWidth:t}):fe(e,t,{breakLongWords:!0})}function GG(e,t,n){if(!n||!e.trim())return"";let r;return oA(e)?r=`
|
|
1632
1632
|
\u258D streaming code\u2026
|
|
1633
1633
|
`:Ege(e)?r=`
|
|
1634
1634
|
\u258D streaming table\u2026
|
|
@@ -1663,9 +1663,9 @@ Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
|
1663
1663
|
`);if(s!==-1){let a=n.contentBuffer.slice(0,s);n.contentBuffer=n.contentBuffer.slice(s+1),Iy(a,r)}}else if(i.type==="thinking"){if(r.thinkingMode==="off")return;if(n.thinkingLane||(n.thinkingLane=new oc),n.thinkingLane.push(i.content),r.thinkingMode==="live"&&r.isTTY&&r.orchestratorCtx){let s=oe(),a=Ut(Math.max(20,s-14)),l=jd(n.thinkingLane.peek(),a);l&&r.toolLane.setThinkingTail(o,l);{let c=Date.now(),u=ac.get(o)??0;c-u>=1500&&(ac.set(o,c),et(r.orchestratorCtx))}}}return}case"message":return;case"error":n.errored=!0,r.toolLane.setThinkingTail(o,void 0),Ub.delete(o),ac.delete(o);{let i=`error \u2014 ${e.error.message}`;r.toolLane.setAgentResultSummary(o,i),r.toolLane.addResult(o,yp(i,!0))}r.isTTY&&r.orchestratorCtx&&et(r.orchestratorCtx);return;case"done":n.done=!0,e.metadata&&(n.responseMetadata=e.metadata),Nge(t,n,r);return;case"suggestion":return;case"panel":Lge(e.spec,t,n,r);return}}function Lge(e,t,n,r){if(r.isTTY){let s=n.syntheticAgentToolUseId;s&&r.toolLane.setThinkingTail(s,void 0),n.contentBuffer=""}else n.contentBuffer.trim()&&(Iy(n.contentBuffer,r),n.contentBuffer="");let i=ga(e).split(`
|
|
1664
1664
|
`);if(r.isTTY&&r.compositor)en(r.compositor,i);else for(let s of i)r.out.line(s);r.isTTY&&r.compositor?r.compositor.commitAbove(""):r.out.line("")}function Nge(e,t,n){let r=t.syntheticAgentToolUseId;if(!r||t.errored)return;if(!n.isTTY&&t.contentBuffer&&Iy(t.contentBuffer,n),t.contentBuffer="",!n.isTTY&&t.thinkingLane?.hasBufferedContent()){let i=t.thinkingLane.collapse();i&&(n.out.line(i),n.out.line(""))}n.toolLane.setThinkingTail(r,void 0),Ub.delete(r),ac.delete(r);let o=WG(t);n.toolLane.setAgentResultSummary(r,o),n.toolLane.addResult(r,yp(o,!1)),n.isTTY&&n.orchestratorCtx&&et(n.orchestratorCtx)}var jb=class{sink;order;slots=new Map;dirty=!1;constructor(t,n){this.sink=t,this.order=[...n]}register(t){this.slots.set(t.key,t),this.dirty=!0}markDirty(t){this.slots.has(t)&&(this.dirty=!0)}flush(){if(!this.dirty)return;this.dirty=!1;let t=[];for(let n of this.order){let r=this.slots.get(n);if(r===void 0)continue;let o=r.render();o.length>0&&t.push(o)}this.sink.setOverlay(t.join(`
|
|
1665
1665
|
`))}invalidate(){this.dirty=!0}};function i2(e,t=2){if(t<1||!Number.isInteger(t))throw new RangeError(`makeDedupingLineWriter: maxRepeat must be a positive integer, got ${t}`);let n=null,r=0,o=()=>{if(n!==null&&r>t){let i=r-t;e.line(` \u2026 (line repeated ${i} more time${i===1?"":"s"})`)}};return{line(i){let s=i??"";s===n?(r++,r<=t&&e.line(s)):(o(),n=s,r=1,e.line(s))},raw(i){o(),n=null,r=0,e.raw(i)},success(i){o(),n=null,r=0,e.success(i)},info(i){o(),n=null,r=0,e.info(i)},warn(i){o(),n=null,r=0,e.warn(i)},error(i){o(),n=null,r=0,e.error(i)},flush(){o(),n=null,r=0}}}ue();var Bge=3e4,Uge=" \xB7 waiting ",jge=375;function s2(e,t){e.register({key:"thinking-live",render:()=>t.thinkingMode!=="live"&&t.thinkingMode!=="digest"||!t.thinkingLane.isActive()||!t.thinkingLane.hasBufferedContent()?"":ic(t.thinkingLane.peekPhase(),{cols:oe()})??""}),e.register({key:"markdown-pending",render:()=>{let n=t.streamingMarkdownRef.current;return n?n.renderPending():""}}),e.register({key:"tool-lane",render:()=>t.toolLane.hasPending()?t.toolLane.getOverlay():""}),e.register({key:"progress-banner",render:()=>{let n=[],r=t.getSoftStopping(),o=$y(t.thinkingLane.peekPhase()),i=o?void 0:Cb(t),s=o??i?.activity;for(let a of t.lastProgressByTask.values()){let l=i?{...a,...i.stats,lastToolName:void 0}:a;n.push(...ws(l,void 0,s,r))}return r&&n.length===0&&n.push(...ws({taskId:"__soft_stop__",description:"Turn",totalTokens:0,toolUses:0,durationMs:0},void 0,void 0,!0)),i&&n.length===0&&n.push(...ws(_b(i.stats),void 0,s,r)),n.length>0?n.join(`
|
|
1666
|
-
`):""}}),e.register({key:"interrupt",render:()=>Hge(t.getInterrupting())})}function Hge(e){return e?" "+p.warning("\u26A0 interrupting\u2026 (Ctrl+C again to exit)"):""}function a2(e,t){return Be.subscribe(()=>{t||!e||(e.invalidate(),e.flush())})}function l2(e){if(e.disposed)return!1;let t=!1,n=Date.now();for(let[r,o]of e.sources){if(o.done||o.errored||!o.syntheticAgentToolUseId)continue;let i=n-o.lastEventAt;if(i>Bge)if(o.stalledTicks+=1,o.stalledTicks>=jge*2)
|
|
1667
|
-
`),e.toolLane.addResult(o.syntheticAgentToolUseId,yp("[no-result \u2014 timed out]",!0)),o.done=!0,t=!0;else{let s=o.agentType??r,a=Uge+Ae(i);o.pauseAnnotation!==a&&(o.pauseAnnotation=a,e.toolLane.addStartWithAgentContext(o.syntheticAgentToolUseId,"Agent",`(${s})${a}`,void 0),t=!0)}}return t&&e.isTTY&&e.overlayComposer&&(e.overlayComposer.markDirty("tool-lane"),e.overlayComposer.flush()),t}ue();function c2(e){let t=e.overlayComposer;if(e.disposed||!e.isTTY||!t)return!1;let n=Date.now(),r=!1;for(let[o,i]of e.sources){if(o===Fs||i.done||i.errored)continue;let s=Math.max(0,n-i.lastEventAt);if(s<Ab){i.quietBannerAnnounced=!1;continue}i.quietBannerAnnounced||(i.quietBannerAnnounced=!0,r=!0,
|
|
1668
|
-
`))}return r&&(t.markDirty("progress-banner"),t.flush()),r}ue();function u2(e){return{out:e.out,isTTY:e.isTTY,compositor:e.compositor,overlayComposer:e.overlayComposer,toolLane:e.toolLane,thinkingLane:e.thinkingLane,thinkingMode:e.thinkingMode,streamingMarkdown:e.streamingMarkdown,coordinator:e.coordinator,lastProgressByTask:e.lastProgressByTask,...e.sources?{sources:e.sources}:{},...e.childActivity?{childActivity:e.childActivity}:{},...e.isTTY&&e.stageTracker?{stageTracker:e.stageTracker}:{},...e.activeSkillName?{activeSkillName:e.activeSkillName}:{}}}function fA(e){return{isTTY:e.isTTY,compositor:e.compositor,toolLane:e.toolLane,out:e.out,streamingMarkdown:e.streamingMarkdown,thinkingMode:e.thinkingMode,orchestratorCtx:e.orchestratorCtx}}function d2(e){if(e.parentId===void 0)return;let t=e.sources.get(e.parentId);if(t!==void 0)return t.syntheticAgentToolUseId;if(e.toolLane.hasEntry(e.parentId))return e.parentId;
|
|
1666
|
+
`):""}}),e.register({key:"interrupt",render:()=>Hge(t.getInterrupting())})}function Hge(e){return e?" "+p.warning("\u26A0 interrupting\u2026 (Ctrl+C again to exit)"):""}function a2(e,t){return Be.subscribe(()=>{t||!e||(e.invalidate(),e.flush())})}function l2(e){if(e.disposed)return!1;let t=!1,n=Date.now();for(let[r,o]of e.sources){if(o.done||o.errored||!o.syntheticAgentToolUseId)continue;let i=n-o.lastEventAt;if(i>Bge)if(o.stalledTicks+=1,o.stalledTicks>=jge*2)He()&&process.stderr.write(`[stream-renderer] auto_settle_timeout ${JSON.stringify({sourceId:r,elapsedMs:i,syntheticAgentToolUseId:o.syntheticAgentToolUseId})}
|
|
1667
|
+
`),e.toolLane.addResult(o.syntheticAgentToolUseId,yp("[no-result \u2014 timed out]",!0)),o.done=!0,t=!0;else{let s=o.agentType??r,a=Uge+Ae(i);o.pauseAnnotation!==a&&(o.pauseAnnotation=a,e.toolLane.addStartWithAgentContext(o.syntheticAgentToolUseId,"Agent",`(${s})${a}`,void 0),t=!0)}}return t&&e.isTTY&&e.overlayComposer&&(e.overlayComposer.markDirty("tool-lane"),e.overlayComposer.flush()),t}ue();function c2(e){let t=e.overlayComposer;if(e.disposed||!e.isTTY||!t)return!1;let n=Date.now(),r=!1;for(let[o,i]of e.sources){if(o===Fs||i.done||i.errored)continue;let s=Math.max(0,n-i.lastEventAt);if(s<Ab){i.quietBannerAnnounced=!1;continue}i.quietBannerAnnounced||(i.quietBannerAnnounced=!0,r=!0,He()&&process.stderr.write(`[stream-renderer] progress_banner_quiet ${JSON.stringify({sourceId:o,silentMs:s})}
|
|
1668
|
+
`))}return r&&(t.markDirty("progress-banner"),t.flush()),r}ue();function u2(e){return{out:e.out,isTTY:e.isTTY,compositor:e.compositor,overlayComposer:e.overlayComposer,toolLane:e.toolLane,thinkingLane:e.thinkingLane,thinkingMode:e.thinkingMode,streamingMarkdown:e.streamingMarkdown,coordinator:e.coordinator,lastProgressByTask:e.lastProgressByTask,...e.sources?{sources:e.sources}:{},...e.childActivity?{childActivity:e.childActivity}:{},...e.isTTY&&e.stageTracker?{stageTracker:e.stageTracker}:{},...e.activeSkillName?{activeSkillName:e.activeSkillName}:{}}}function fA(e){return{isTTY:e.isTTY,compositor:e.compositor,toolLane:e.toolLane,out:e.out,streamingMarkdown:e.streamingMarkdown,thinkingMode:e.thinkingMode,orchestratorCtx:e.orchestratorCtx}}function d2(e){if(e.parentId===void 0)return;let t=e.sources.get(e.parentId);if(t!==void 0)return t.syntheticAgentToolUseId;if(e.toolLane.hasEntry(e.parentId))return e.parentId;He()&&process.stderr.write(`[stream-renderer] parentId_fallback_unresolved ${JSON.stringify({parentId:e.parentId,sourceId:e.sourceId})}
|
|
1669
1669
|
`)}var lc=class{out;thinkingMode;isTTY;captureMode;reducedMotion;onCancel;onBackground;activeSkillName;history;autocompleteState;promptText;scrollRegion;onStageChange;ownsCompositor=!0;borrowedCompositor=null;priorOnCancel=void 0;interrupting=!1;softStopping=!1;coordinator=new Bb;compositor=null;overlayComposer=null;streamingMarkdownRef={current:null};toolLane=new hp;thinkingLane=new oc;stageTracker=XG();sources=new Map;subagentMarkdown=new Map;lastProgressByTask=new Map;childActivity=new xb;inFlightTools=new lb;disposed=!1;pauseTickInterval=null;resizeUnsub=null;sink;constructor(t){this.captureMode=t.captureMode??eb(),this.reducedMotion=t.reducedMotion??tb(),this.out=this.captureMode?i2(t.out,2):t.out;let n=t.thinkingMode??(t.verbose===!0?"live":"summary");this.thinkingMode=this.captureMode&&n==="live"?"summary":n,this.onCancel=t.onCancel,this.onBackground=t.onBackground,this.isTTY=!(t.forceNonTty??!1)&&!nt()&&!!process.stdout.isTTY&&!!process.stdin.isTTY,this.activeSkillName=t.activeSkillName,this.history=t.history,this.autocompleteState=t.autocompleteState,this.promptText=t.promptText,this.scrollRegion=t.scrollRegion,this.onStageChange=t.onStageChange,t.compositor&&(this.borrowedCompositor=t.compositor,this.ownsCompositor=!1),this.sink=(r,o)=>this.process(r,o)}async arm(){if(this.disposed||!this.isTTY||this.compositor)return;let t;if(this.borrowedCompositor)t=this.borrowedCompositor,t.setInputMode("streaming"),this.priorOnCancel=t.getOnCancel(),this.onCancel&&t.setOnCancel(this.onCancel);else{let n=Vl();t=new tc({stdout:process.stdout,stdin:process.stdin,...this.onCancel?{onCancel:this.onCancel}:{},...this.onBackground?{onBackground:this.onBackground}:{},...this.history?{history:this.history}:{},...this.autocompleteState?{autocompleteState:this.autocompleteState}:{},...this.promptText!==void 0?{promptText:this.promptText}:{},formatInputBuffer:r=>li(r,n),...this.scrollRegion?{scrollRegion:this.scrollRegion}:{},captureMode:this.captureMode,goblinSpinner:nb()}),await t.arm()}this.compositor=t,this.overlayComposer=new jb(t,["thinking-live","markdown-pending","tool-lane","progress-banner","interrupt"]),s2(this.overlayComposer,{stageTracker:this.stageTracker,thinkingMode:this.thinkingMode,thinkingLane:this.thinkingLane,streamingMarkdownRef:this.streamingMarkdownRef,toolLane:this.toolLane,lastProgressByTask:this.lastProgressByTask,sources:this.sources,childActivity:this.childActivity,getInterrupting:()=>this.interrupting,getSoftStopping:()=>this.softStopping}),t.setSpinner({enabled:!this.reducedMotion,rotateVerbEveryMs:3500}),this.pauseTickInterval=setInterval(()=>this.checkPauseAnnotations(),80),this.resizeUnsub=a2(this.overlayComposer,!1)}getCompositor(){return this.compositor}setInterrupting(t){this.disposed||(this.interrupting=t,this.overlayComposer&&(this.overlayComposer.markDirty("interrupt"),this.overlayComposer.flush()))}setSoftStopping(t){this.disposed||(this.softStopping=t,this.overlayComposer&&(this.overlayComposer.markDirty("progress-banner"),this.overlayComposer.flush()))}buildOrchestratorCtx(){return u2({out:this.out,isTTY:this.isTTY,compositor:this.compositor,overlayComposer:this.overlayComposer,toolLane:this.toolLane,thinkingLane:this.thinkingLane,thinkingMode:this.thinkingMode,streamingMarkdown:this.streamingMarkdownRef,coordinator:this.coordinator,lastProgressByTask:this.lastProgressByTask,sources:this.sources,childActivity:this.childActivity,...this.isTTY?{stageTracker:this.stageTracker}:{},...this.activeSkillName?{activeSkillName:this.activeSkillName}:{}})}process(t,n){if(this.disposed)return;mK(t,this.inFlightTools,this.compositor);let r=n?.subagentId??Fs,o=r===Fs,i=this.sources.get(r);if(!i&&(i=HG(n?.agentType),this.sources.set(r,i),!o)){let s=d2({parentId:n?.parentId,sources:this.sources,toolLane:this.toolLane,sourceId:r});gx(r,i,fA({isTTY:this.isTTY,compositor:this.compositor,toolLane:this.toolLane,out:this.out,streamingMarkdown:this.subagentMarkdown,thinkingMode:this.thinkingMode,orchestratorCtx:this.buildOrchestratorCtx()}),s)}if(o){let s=this.stageTracker.stage;r2(t,i,this.buildOrchestratorCtx());let a=t.type==="chunk"&&t.chunk.type==="tool_result"&&t.chunk.isError===!0;if(this.onStageChange&&(this.stageTracker.stage!==s||a))try{a?this.onStageChange(this.stageTracker.stage,{toolErrored:!0}):this.onStageChange(this.stageTracker.stage)}catch{}}else{if(o2(t,r,i,fA({isTTY:this.isTTY,compositor:this.compositor,toolLane:this.toolLane,out:this.out,streamingMarkdown:this.subagentMarkdown,thinkingMode:this.thinkingMode,orchestratorCtx:this.buildOrchestratorCtx()})),i.lastEventAt=Date.now(),i.quietBannerAnnounced=!1,i.pauseAnnotation!==void 0&&i.syntheticAgentToolUseId){i.pauseAnnotation=void 0,i.stalledTicks=0;let a=i.agentType??r;this.toolLane.addStartWithAgentContext(i.syntheticAgentToolUseId,"Agent",`(${a})`,void 0)}if((t.type==="done"||t.type==="error")&&this.isTTY){let a=i.syntheticAgentToolUseId;if(a&&this.toolLane.hasEntry(a)){let l=this.toolLane.flushSource(a),c=this.compositor,u=this.overlayComposer,d=this.toolLane,m=this.out;this.coordinator.schedule({anchor:`after-subagent:${r}`,commits:[()=>{if(c)en(c,l),c.commitAbove(""),u?(u.markDirty("tool-lane"),u.flush()):c.setOverlay(d.getOverlay());else{for(let f of l)m.line(f);m.line("")}}]});try{this.streamingMarkdownRef.current&&this.streamingMarkdownRef.current.commitPending()}finally{this.coordinator.drainSubagent(r)}}et(this.buildOrchestratorCtx())}}}async dispose(){if(this.disposed)return;this.disposed=!0,this.resizeUnsub&&(this.resizeUnsub(),this.resizeUnsub=null),this.lastProgressByTask.clear(),this.softStopping=!1;let t=this.streamingMarkdownRef.current?()=>this.streamingMarkdownRef.current.flush():void 0;await this.coordinator.flushAll(t),this.streamingMarkdownRef.current&&(this.streamingMarkdownRef.current.dispose(),this.streamingMarkdownRef.current=null);for(let r of this.subagentMarkdown.values()){try{await r.flush()}catch{}r.dispose()}if(this.subagentMarkdown.clear(),this.toolLane.hasPending()){let r=this.toolLane.flush();if(this.isTTY&&this.compositor)en(this.compositor,r),this.compositor.commitAbove(""),this.overlayComposer?(this.overlayComposer.markDirty("tool-lane"),this.overlayComposer.flush()):this.compositor.setOverlay(this.toolLane.getOverlay());else{for(let o of r)this.out.line(o);this.out.line("")}}if(this.pauseTickInterval&&(clearInterval(this.pauseTickInterval),this.pauseTickInterval=null),this.compositor){if(this.ownsCompositor)try{this.compositor.disarm()}catch{}else{try{this.compositor.setSpinner({enabled:!1})}catch(r){B("[stream-renderer] borrow-dispose setSpinner: "+String(r))}try{this.overlayComposer?(this.overlayComposer.invalidate(),this.overlayComposer.flush()):this.compositor.setOverlay("")}catch(r){B("[stream-renderer] borrow-dispose setOverlay: "+String(r))}try{this.compositor.setInputMode("idle")}catch(r){B("[stream-renderer] borrow-dispose setInputMode: "+String(r))}try{this.compositor.setOnCancel(this.priorOnCancel??null)}catch(r){B("[stream-renderer] borrow-dispose setOnCancel: "+String(r))}this.priorOnCancel=void 0}this.compositor=null,this.borrowedCompositor=null}let n=this.out;if(typeof n.flush=="function")try{n.flush()}catch{}}checkPauseAnnotations(){let t={compositor:this.compositor,disposed:this.disposed,sources:this.sources,toolLane:this.toolLane,isTTY:this.isTTY,overlayComposer:this.overlayComposer,stageTracker:this.stageTracker,thinkingMode:this.thinkingMode,thinkingLane:this.thinkingLane,streamingMarkdownRef:this.streamingMarkdownRef,lastProgressByTask:this.lastProgressByTask,out:this.out,pauseTickInterval:this.pauseTickInterval,resizeUnsub:this.resizeUnsub};c2(t),l2(t)}};function Hb(e,t){let n=t.verbose??T.AFK_SKILL_STREAM_VERBOSE==="1",r=t.out??e.out,o=e.getCompositor?.()??null;return new lc({out:r,verbose:n,activeSkillName:t.skillName,onCancel:t.onCancel??(()=>{}),...o?{compositor:o}:{},...e.onStageChange?{onStageChange:e.onStageChange}:{}})}qr();Ed();fl();async function p2(e,t,n,r,o){let i=Db(e.name,t),s=e.context==="fork"?" This skill runs with context: 'fork' \u2014 the executor will fork a subagent.":"",a=`Use the \`skill\` tool with {"name": "${e.name}", "arguments": "${t}"} to dispatch this skill.${s}`,l=[];return n&&n.trim().length>0&&l.push({type:"text",text:n}),l.push({type:"text",text:i}),l.push({type:"text",text:a}),r!==void 0&&r.length>0&&o!==void 0?await Dh(l,o,r):Jo(l,r),l}var Wge=15e3;async function Wb(e,t){let n=Hb(e,{skillName:t.skillName,onCancel:()=>{e.session.current.interrupt().catch(()=>{})}}),r=!1,o=`/${t.skillName}${t.args?" "+t.args:""}`;await e.transcript?.appendUser?.(o).catch(()=>{});let i="",s=!1,a,l=0,c=[],u=new Map;try{await n.arm(),e.setSoftStopHandler?.(()=>{r=!0,e.session.current.interrupt().catch(()=>{})});let d;if(t.preflight)try{d=await t.preflight()}catch{d=void 0}let m=await p2(t.skillMeta,t.args,d,t.attachments,e.stats.sessionId);await Xa(n.sink,async()=>{for await(let f of e.session.current.sendMessageStream(m)){if(r)break;if(f.type==="message"&&f.message.role==="assistant"&&(i=f.message.content),f.type==="chunk"&&f.chunk.type==="tool_use_detail"){let g=f.chunk,h={toolName:g.toolName,toolUseId:g.toolUseId,input:g.toolInput};u.set(g.toolUseId,h),c.push(h)}else if(f.type==="chunk"&&f.chunk.type==="tool_result"){let g=f.chunk,h=u.get(g.toolUseId);if(h&&(h.result=g.content,h.isError=g.isError,u.delete(g.toolUseId)),e.onContextProgress){let y=Date.now();if(y-l>=Wge){l=y;try{let b=e.onContextProgress();b instanceof Promise&&await b}catch{}}}}else f.type==="done"&&(s=!0,a=f.metadata);n.sink(f)}})}finally{e.setSoftStopHandler?.(null),await n.dispose();try{e.onStageChange?.("observing")}catch{}}if(s&&!r){ks(e.stats,o,i,a,c);try{e.ui.repaintStatusLine()}catch{}await e.transcript?.appendTurn(o,i).catch(()=>{})}return i}W();import{execFile as Kge}from"child_process";import{promisify as Gge}from"util";import{writeFileSync as qge}from"fs";import{join as zge}from"path";var Vge=Gge(Kge),Jge=4*1024*1024,gA=!1;function hA(e){let t=e.trim();if(!t)return null;if(/^#?\d+$/.test(t)){let r=t.replace(/^#/,""),o=parseInt(r,10);if(!(o>0&&o<1e6))throw new Error(`[afk preflight] Invalid PR number: ${r}. Must be 1\u2013999999.`);return r}let n=t.match(/github\.com\/[^/]+\/[^/]+\/pull\/(\d+)/);if(n&&n[1]){let r=n[1],o=parseInt(r,10);if(!(o>0&&o<1e6))throw new Error(`[afk preflight] Invalid PR number in URL: ${r}. Must be 1\u2013999999.`);return r}return null}async function Yge(e,t,n){try{let{stdout:r}=await Vge(e,t,{encoding:"utf-8",...n?.cwd?{cwd:n.cwd}:{},maxBuffer:n?.maxBuffer??Jge,timeout:8e3});return r}catch(r){if(T.AFK_DEBUG==="1"&&r instanceof Error&&"stderr"in r){let i=String(r.stderr??"").replace(/\x1b\[[0-9;]*m/g,"").slice(0,200).trim();i&&process.stderr.write(`[afk preflight] ${e} stderr: ${i}
|
|
1670
1670
|
`)}return null}}async function Xge(e,t,n={}){let r=n.exec??Yge,o=n.writeFile??((f,g)=>qge(f,g,"utf-8")),[i,s,a]=await Promise.all([r("gh",["pr","view",e,"--json","title,baseRefName,headRefName,additions,deletions,changedFiles,files"],{cwd:t.cwd}),r("gh",["pr","diff",e],{cwd:t.cwd}),r("git",["status","--porcelain"],{cwd:t.cwd})]),l=null;if(i)try{l=JSON.parse(i)}catch{l=null}let c=null,u=null;if(s!==null){let f=zge(t.artifactDir,`pr-${e}.diff`);try{o(f,s),c=f,u=s.trimEnd().split(`
|
|
1671
1671
|
`).length}catch{}}let d=a?a.split(`
|
|
@@ -1834,13 +1834,13 @@ ${t.partialOutput}`:"";return`Subagent failed \u2014 ${r}${o}`}let n=t.message?.
|
|
|
1834
1834
|
`).find(y=>y.trim().length>0)?.trim()??"",g=f.length>0?f:`${e.kind} (no structured fields)`,h=fe(wo(g),n).split(`
|
|
1835
1835
|
`);for(let y of h)d.push(s+" "+ot(y,n)+" "+s)}else for(let f of l){let g=p.dim(ot(f.label,c)),h=fe(wo(f.value),u).split(`
|
|
1836
1836
|
`),y=h[0]??"";d.push(s+" "+g+" "+ot(y,u)+" "+s);for(let b of h.slice(1))d.push(s+" "+" ".repeat(c)+" "+ot(b,u)+" "+s)}d.push(a);let m=p.dim(ae(t.affordance,n));return d.push(s+" "+ot(m,n)+" "+s),d.push(i),d.join(`
|
|
1837
|
-
`)}function Jve(e){let t=[],n=(r,o)=>{o&&o.trim().length>0&&t.push({label:r,value:o.trim()})};switch(e.kind){case"done":n("done",e.whatWasDone),n("evidence",e.evidence),e.deferred?.trim()!==e.whatWasDone?.trim()&&n("deferred",e.deferred);break;case"blocked":n("blocks",e.whatBlocks),n("unblock",e.unblockCondition),n("progress",e.alreadyDone);break;case"asking":n("question",e.question),n("resolves",e.assumption),n("after",e.followup);break;case"interrupted":n("was doing",e.whatWasInProgress),n("saved at",e.stateLocation),n("resume",e.resumeRequires);break}return t}vt();fl();Ed();async function fJ(e,t,n,r,o){let i=[];return n&&n.trim().length>0&&i.push({type:"text",text:n}),r&&r.length>0&&i.push(...r),e&&i.push({type:"text",text:e}),t.length>0&&o!==void 0?await Dh(i,o,t):Jo(i,t),i}import{readFileSync as Yve,statSync as Xve}from"fs";import{extname as Qve,join as AC}from"path";import{homedir as Zve}from"os";Wi();Lr();var eke=100*1024,tke=400*1024,nke=/(?<=\s|^)@([~\w./-]+)(?=\s|$)/g,rke=/(^|\/)\.(ssh|aws|gnupg|kube|docker)(\/|$)|(^|\/)[^/]*\.env(\.[^/]+)?$|(^|\/)\.(netrc|npmrc|pypirc)$|(^|\/)id_(rsa|ed25519|ecdsa|dsa)(\.pub)?$|\.(pem|key|p12|pfx)$|(^|\/)credentials$|(^|\/)\.git\/config$|(^|\/)\.git-credentials$|(^|\/)\.(bash|zsh|fish|sh)_history$/i,oke=[".afk/config",".afk/state",".config/gcloud",".config/gh"];function ike(e){let t=0,n=e.match(/`+/g);if(n)for(let r of n)r.length>t&&(t=r.length);return"`".repeat(Math.max(3,t+1))}function ske(e,t,n){if(n.includes(e))return $t(e).denied;if(rke.test(e))return!0;for(let r of t)if(e===r||e.startsWith(r+"/"))return!0;return!1}var ake={".ts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"jsx",".mjs":"javascript",".cjs":"javascript",".json":"json",".md":"markdown",".py":"python",".sh":"bash",".bash":"bash",".zsh":"bash",".yaml":"yaml",".yml":"yaml",".toml":"toml",".rs":"rust",".go":"go",".rb":"ruby",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cs":"csharp",".html":"html",".css":"css",".scss":"scss",".sql":"sql",".xml":"xml",".txt":""};function lke(e){return ake[e.toLowerCase()]??""}function cke(e=process.env){return e.AFK_AT_FILE_INJECT!=="0"}function gJ(e,t={}){let n={fileBlocks:[],warnings:[]};if(!cke(t.env))return n;let r=[];for(let m of e.matchAll(nke)){let f=m[1];f&&r.push(f)}if(r.length===0)return n;let o=t.rootDir??process.cwd(),i=t.homeDir??Zve(),s=oke.map(m=>
|
|
1837
|
+
`)}function Jve(e){let t=[],n=(r,o)=>{o&&o.trim().length>0&&t.push({label:r,value:o.trim()})};switch(e.kind){case"done":n("done",e.whatWasDone),n("evidence",e.evidence),e.deferred?.trim()!==e.whatWasDone?.trim()&&n("deferred",e.deferred);break;case"blocked":n("blocks",e.whatBlocks),n("unblock",e.unblockCondition),n("progress",e.alreadyDone);break;case"asking":n("question",e.question),n("resolves",e.assumption),n("after",e.followup);break;case"interrupted":n("was doing",e.whatWasInProgress),n("saved at",e.stateLocation),n("resume",e.resumeRequires);break}return t}vt();fl();Ed();async function fJ(e,t,n,r,o){let i=[];return n&&n.trim().length>0&&i.push({type:"text",text:n}),r&&r.length>0&&i.push(...r),e&&i.push({type:"text",text:e}),t.length>0&&o!==void 0?await Dh(i,o,t):Jo(i,t),i}import{readFileSync as Yve,statSync as Xve}from"fs";import{extname as Qve,join as AC}from"path";import{homedir as Zve}from"os";Wi();Lr();var eke=100*1024,tke=400*1024,nke=/(?<=\s|^)@([~\w./-]+)(?=\s|$)/g,rke=/(^|\/)\.(ssh|aws|gnupg|kube|docker)(\/|$)|(^|\/)[^/]*\.env(\.[^/]+)?$|(^|\/)\.(netrc|npmrc|pypirc)$|(^|\/)id_(rsa|ed25519|ecdsa|dsa)(\.pub)?$|\.(pem|key|p12|pfx)$|(^|\/)credentials$|(^|\/)\.git\/config$|(^|\/)\.git-credentials$|(^|\/)\.(bash|zsh|fish|sh)_history$/i,oke=[".afk/config",".afk/state",".config/gcloud",".config/gh"];function ike(e){let t=0,n=e.match(/`+/g);if(n)for(let r of n)r.length>t&&(t=r.length);return"`".repeat(Math.max(3,t+1))}function ske(e,t,n){if(n.includes(e))return $t(e).denied;if(rke.test(e))return!0;for(let r of t)if(e===r||e.startsWith(r+"/"))return!0;return!1}var ake={".ts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"jsx",".mjs":"javascript",".cjs":"javascript",".json":"json",".md":"markdown",".py":"python",".sh":"bash",".bash":"bash",".zsh":"bash",".yaml":"yaml",".yml":"yaml",".toml":"toml",".rs":"rust",".go":"go",".rb":"ruby",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cs":"csharp",".html":"html",".css":"css",".scss":"scss",".sql":"sql",".xml":"xml",".txt":""};function lke(e){return ake[e.toLowerCase()]??""}function cke(e=process.env){return e.AFK_AT_FILE_INJECT!=="0"}function gJ(e,t={}){let n={fileBlocks:[],warnings:[]};if(!cke(t.env))return n;let r=[];for(let m of e.matchAll(nke)){let f=m[1];f&&r.push(f)}if(r.length===0)return n;let o=t.rootDir??process.cwd(),i=t.homeDir??Zve(),s=oke.map(m=>Ue(AC(i,m))),a=Fr.map(m=>Ue(AC(i,m))),l=[],c=[],u=new Set,d=0;for(let m of r){let{scanDir:f,leafPrefix:g}=_s(m,o,i),h=g?AC(f,g):f,y=Ue(h);if(u.has(y))continue;if(u.add(y),ske(y,s,a)){c.push(`@${m}: sensitive path, not injected`);continue}let b;try{b=Xve(y)}catch{c.push(`@${m}: not found, left as text`);continue}if(b.isDirectory()){c.push(`@${m}: is a directory, skipped`);continue}if(!b.isFile()){c.push(`@${m}: not a regular file, skipped`);continue}if(b.size>eke){c.push(`@${m}: too large (${Math.round(b.size/1024)} KB > 100 KB), skipped`);continue}if(d+b.size>tke){c.push(`@${m}: 400 KB total injection budget exceeded, skipped`);continue}let w;try{w=Yve(y)}catch{c.push(`@${m}: could not read, skipped`);continue}if(w.includes(0)){c.push(`@${m}: binary file, skipped`);continue}d+=b.size;let v=lke(Qve(y)),S=w.toString("utf8"),E=ike(S);l.push({type:"text",text:`Contents of ${m}:
|
|
1838
1838
|
${E}${v}
|
|
1839
1839
|
${S}
|
|
1840
|
-
${E}`})}return{fileBlocks:l,warnings:c}}function hJ(e){let t=e.replace(/\s+/g," ").trim();return t.length<=60?t:`${t.slice(0,59)}\u2026`}async function yJ(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}}async function bJ(e,t,n,r,o="summary",i,s){let a=YK(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0),zl(process.stdout,Jd(process.cwd(),!0));let l="",c=0,u=!1,d=!1,m=!1,f=!1,g=!1,h,y=!1,b=!1,w={abort:null},v=0,S=3e3,E=[],x=new Map,D=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,I=()=>{let O=r.subagentControl;O?.hasPromotableForeground()&&yJ(O,A,r.onQueuedUserMessage).then(({jobs:H,flushedText:K,flushedPreview:_})=>{let F=(i??{fn:console.log}).fn;for(let M of H)F(p.dim(` \u2192 subagent backgrounded as ${M.jobId}: ${M.label}`));K!==void 0&&F(p.dim(` \u2192 queued message sent to this turn: ${hJ(_??K)}`))}).catch(()=>{})},A=r.getCompositor?r.getCompositor():null,C=()=>new lc({out:cc(i),thinkingMode:o,...D?{activeSkillName:D}:{},onCancel:()=>{t.interrupt().catch(O=>{Ue()&&console.error(" "+p.error("session.interrupt() failed:"),O)})},...r.subagentControl?{onBackground:I}:{},...s?.history?{history:s.history}:{},...s?.autocompleteState?{autocompleteState:s.autocompleteState}:{},...s?.promptText!==void 0?{promptText:s.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...A?{compositor:A}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),P=C(),N=async()=>{if(!f){f=!0;try{await P.dispose()}catch{}}},z=async()=>{await P.arm();let O=P.getCompositor();if(i&&O){let H=O;i.fn=K=>H.commitAbove(K),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.(O),r.setInterruptNotifier?.(H=>P.setInterrupting(H)),r.rearmStatus?.()};try{A?A.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{y=!0,P.setSoftStopping(!0),t.interrupt().catch($=>{Ue()&&console.error(" "+p.error("soft-stop session.interrupt() failed:"),$)});let M=r.subagentControl;M?.hasActiveForeground()&&M.cancelActiveForeground().catch($=>{Ue()&&console.error(" "+p.error("soft-stop cancelActiveForeground() failed:"),$)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{b=!0,t.interrupt().catch(M=>{Ue()&&console.error(" "+p.error("pause-interrupt session.interrupt() failed:"),M)})}),await z(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(I);let{fileBlocks:O,warnings:H}=gJ(e.text,{rootDir:process.cwd()});for(let M of H)(i??{fn:console.log}).fn(p.dim(` @-file: ${M}`));if(e.attachments.length>0&&(await t.waitForInitialization(),t.sessionId===void 0))throw new Error("CLI session initialized without a session id");let K=O.length>0||e.attachments.length>0?await fJ(e.text,e.attachments,void 0,O,t.sessionId):e.text,_=t.sendMessageStream(K);if(await Xa((M,$)=>{P.process(M,$)},async()=>{for await(let M of _){if(y||b)break;if(M.type==="chunk"&&M.chunk.type==="content"?(l=u?pJ(l,M.chunk.content):l+M.chunk.content,u=!1,d=!0):M.type==="message"&&!d&&(l=M.message.content),M.type==="stream_retry"&&(l=l.slice(0,c),u=l.length>0),M.type==="chunk"&&M.chunk.type==="tool_use_detail"){let $=M.chunk,U={toolName:$.toolName,toolUseId:$.toolUseId,input:$.toolInput,...$.toolInputRaw!==void 0&&{inputRaw:$.toolInputRaw}};x.set($.toolUseId,U),E.push(U)}else if(M.type==="chunk"&&M.chunk.type==="tool_result"){let $=M.chunk;c=l.length,u=!0;let U=x.get($.toolUseId);if(U&&(U.result=$.content,U.isError=$.isError,x.delete($.toolUseId)),r.onContextProgress){let X=Date.now();if(X-v>=S){v=X;try{let j=r.onContextProgress();j instanceof Promise&&await j}catch(j){Ue()&&console.error(" "+p.error("onContextProgress (status refresh) failed:"),j)}}}}if(M.type==="paused"){if(r.setPausedState?.(!0),await N(),A&&M.autoResume===!0){let $=new AbortController;w.abort=$;let U=M.resetsAt?M.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,X=U?`Keep waiting \u2014 auto-resumes at ${U}`:"Keep waiting \u2014 auto-resume in progress",j="Switch model / provider (type /model after)",ee="Stop waiting",se=[p.warning(" \u23F3 Usage limit reached.")+(U?p.dim(` Auto-resumes at ${U}.`):""),p.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];Cn(A,{header:se,options:[X,j,ee],signal:$.signal,initialIndex:0}).then(q=>{if(w.abort=null,!q)return;let te=q[0];te===void 0||te===X||(b=!0,te===j&&(i??{fn:console.log}).fn(p.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(le=>{Ue()&&console.error(" "+p.error("picker pause-interrupt session.interrupt() failed:"),le)}))}).catch(q=>{Ue()&&console.error(" "+p.error("picker promise rejected:"),q)})}else(i??{fn:console.log}).fn(NI({reason:M.reason,...M.resetsAt!==void 0?{resetsAt:M.resetsAt}:{},...M.accountId!==void 0?{accountId:M.accountId}:{},...M.autoResume!==void 0?{autoResume:M.autoResume}:{}}));continue}if(M.type==="resumed"){r.setPausedState?.(!1),w.abort?.abort(),w.abort=null;let $=M.hotSwapped&&M.accountId?`\u25B6 Resumed on ${M.accountId}`:"\u25B6 Resumed";l="",c=0,u=!1,d=!1,E.length=0,x.clear(),g=!1,h=void 0,m=!1,P=C(),f=!1,await z(),(i??{fn:console.log}).fn(p.success($));continue}if(M.type==="error"){await N(),ha(ca(M.error)),m=!0;continue}P.process(M),M.type==="done"&&(g=!0,h=M.metadata)}}),await N(),y){let M=i?i.fn:console.log,$=A?A.getPendingCount():0,U=$>0?` \xB7 ${$} queued`:"";M(p.warning(`\u23F8 Stopped${U} \u2014 work so far kept.`)+p.dim(" Send a message to continue.")),M("")}if(b){let M=i?i.fn:console.log;M(p.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),M("")}if(g&&!y&&!b){ks(n,a,l,h,E),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),ql(process.stdout),DW(process.stdout,"afk: turn complete");let M=U=>{i?i.fn(U):console.log(U)},$=Vw(l);if($){M(mJ($)),M("");let U=Eq(E);if(r.onTerminalState)try{r.onTerminalState($,{doneHasCorroboratingEvidence:U})}catch{}if(n.permissionMode==="autonomous"){let X=$.kind==="done"&&Bu().verifyDone===!0&&!U;xq($,void 0,{unverified:X})}}if(dke(h,n,M),r.onAfterTurn){let U=r.onAfterTurn();U instanceof Promise&&await U.catch(()=>{})}}}catch(O){await N(),m||ha(ca(O))}finally{await N(),zl(process.stdout,Jd(process.cwd(),!1)),i&&(i.fn=i.idleFn,i.suppressSubagentCompletion=!1),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setPausedState?.(!1),r.setPauseInterruptHandler?.(null),w.abort?.abort(),w.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}function uke(e,t){let n=Math.round(e*100),r=he(t);if(e>=1){let o=Math.round((e-1)*t);return{tier:"over",text:` context OVER ${Math.round(t/1e3)}k tok by ~${he(o)} tok \u2014 model output may be silently truncated`}}return e>=.95?{tier:"near",text:` context ${n}% used of ${r} \u2014 near limit; output may soon truncate (consider /clear or a fresh session)`}:e>=.8?{tier:"caution",text:` context ${n}% used of ${r} \u2014 approaching limit`}:e>.5?{tier:"normal",text:` context ${n}% used of ${r}`}:{tier:"quiet",text:null}}function dke(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(Ae(e.durationMs)),e.totalCostUsd!==void 0&&r.push(dt(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),i=Number(e.usage?.output_tokens??0);o+i>0&&r.push(he(o+i)+" tok"),r.length>0&&n(p.dim(" \u25E6 "+r.join(" \xB7 ")));let s=RA(t),a=Gt(t.model),l=uke(s,a);if(l.text!==null){let u=l.tier==="over"||l.tier==="near"?p.error:l.tier==="caution"?p.warning:p.dim;n(u(l.text))}let c=dJ(zb(Mg()),new Date,{autoResume:eO()});if(c.text!==null){let u=c.tier==="over"||c.tier==="near"?p.error:c.tier==="caution"?p.warning:p.dim;n(u(c.text))}n("")}var pke=5e3,mke=3,fke="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function gke(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(p.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function wJ(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,mascotBar:u,verdictLedger:d,shellPassthrough:m,bgResultNotifier:f}=s,g=null,h=[];e.session.current.waitForInitialization().then(async I=>{Ue()&&(g=cw(I)),await bp(e.session.current),Ue()&&(h=kA())}).catch(()=>{});let y=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,b,w=!1,v=!1,S,E,x,D=0;for(f.onInjectable=()=>{D>=mke||!o.isAwaitingInput()||!o.bufferIsEmpty()||(D++,ql(process.stdout),y={text:fke,attachments:[]},o.abortPendingRead())};;){if(g&&(e.replRenderer.writeLine(g),e.replRenderer.writeLine(""),g=null),h.length>0){for(let _ of h)e.replRenderer.writeLine(_);e.replRenderer.writeLine(""),h=[]}let I=m.drainNotifications();for(let{job:_,result:F}of I){let M=F.errorReason===void 0?"\u2713":"\u2717",$=F.errorReason==="abort"?"killed":F.errorReason==="timeout"?"timed out":F.errorReason==="signal-killed"?"killed by signal":`exit ${F.exitCode??0}`,U=Math.max(0,Math.round(F.durationMs/100)/10);e.replRenderer.writeLine(p.dim(` ${M} [${_.id}] ${$} \xB7 ${U}s \xB7 `)+_.command)}let A=f.drainNotifications();for(let{job:_}of A){let F=_.status==="completed"?"\u2713":_.status==="failed"?"\u2717":"\u2298",M=_.endedAt!==void 0?Math.max(0,Math.round((_.endedAt-_.startedAt)/100)/10):0,$=ae(_.label,60);e.replRenderer.writeLine(p.dim(` ${F} [${_.jobId}] subagent ${_.status} \xB7 ${M}s \xB7 `)+$)}let C=l.renderIfChanged(e.stats.sessionId);if(C.length>0){for(let _ of C)e.replRenderer.writeLine(_);e.replRenderer.writeLine("")}let P,N;if(y===void 0){let _=await e.session.current.takePendingPlanExitSeed();_!==void 0&&(e.stats.permissionMode=_.mode,y={text:_.message,attachments:[]})}if(y!==void 0){let _=y;y=void 0;let F=hc(e.stats.permissionMode),M=As({buffer:_.text,promptText:F,isTTY:!!process.stdout.isTTY,attachmentSummary:Zl([..._.attachments])});e.replRenderer.writeLine(M),P=_.text.trim(),N=_.attachments}else{let _=b;b=void 0;let F=await o.readLine({promptFn:()=>hc(e.stats.permissionMode),..._!==void 0?{initialBuffer:_}:{},primePromptSuggestion:!0,onSigint:r,onShiftTab:()=>{Ww(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});P=F.text.trim(),N=F.attachments}if(!P&&N.length===0)continue;if(P.startsWith("!")){let _=/^(0|false|off|no)$/i.test(T.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!_&&(w||(w=!0,e.replRenderer.writeLine(p.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await m.dispatch(P))){e.statusLine.rearm();continue}}let z=!1;if(P.startsWith("/")){let _=await NW(P,e.slashCtx,N);if(_.handled){if(_.result==="exit"){await e.resolveWorktreeDisposition?.(!0),e.rl.close();return}if((P==="/clear"||P.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(p.dim(` transcript: ${t.path()}`)),d.reset(),S=void 0),_.result!==null&&typeof _.result=="object"&&"kind"in _.result&&_.result.kind==="submit"){y={text:_.result.message,attachments:N??[]},e.statusLine.rearm();continue}if(_.result!==null&&typeof _.result=="object"&&"kind"in _.result&&_.result.kind==="prefill"){b=_.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}z=!0}a.push(P),await gke(e,P);let O=P;if(z){let _=Px(P);if(_){let F=_.name.replace(/^\//,"").split(":").pop()??"";if(F&&bA(F)){let M={skillName:F,rawArgs:_.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},$=e.session.current.sessionId,U=Ns($),X=Date.now();B(`[afk trace] preflight.start commandName=${F}`);let j=!1,ee=await Ls(M,{cwd:e.stats.cwd??process.cwd(),artifactDir:U},se=>{Ue()&&e.replRenderer.writeLine(p.warning(`\u26A0 preflight(${F}) failed: `)+(se instanceof Error?se.message:String(se)))});j=ee!==null,B(`[afk trace] preflight.end commandName=${F} durationMs=${Date.now()-X} success=${j}`),O=SA(ee?.manifestBlock,P)}}}let H=m.drainInjections();H.length>0&&(O=H+O);let K=f.drainInjections();if(K.length>0&&(O=K+O),S!==void 0&&(O=S+`
|
|
1840
|
+
${E}`})}return{fileBlocks:l,warnings:c}}function hJ(e){let t=e.replace(/\s+/g," ").trim();return t.length<=60?t:`${t.slice(0,59)}\u2026`}async function yJ(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}}async function bJ(e,t,n,r,o="summary",i,s){let a=YK(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0),zl(process.stdout,Jd(process.cwd(),!0));let l="",c=0,u=!1,d=!1,m=!1,f=!1,g=!1,h,y=!1,b=!1,w={abort:null},v=0,S=3e3,E=[],x=new Map,D=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,I=()=>{let O=r.subagentControl;O?.hasPromotableForeground()&&yJ(O,A,r.onQueuedUserMessage).then(({jobs:H,flushedText:K,flushedPreview:_})=>{let F=(i??{fn:console.log}).fn;for(let M of H)F(p.dim(` \u2192 subagent backgrounded as ${M.jobId}: ${M.label}`));K!==void 0&&F(p.dim(` \u2192 queued message sent to this turn: ${hJ(_??K)}`))}).catch(()=>{})},A=r.getCompositor?r.getCompositor():null,C=()=>new lc({out:cc(i),thinkingMode:o,...D?{activeSkillName:D}:{},onCancel:()=>{t.interrupt().catch(O=>{He()&&console.error(" "+p.error("session.interrupt() failed:"),O)})},...r.subagentControl?{onBackground:I}:{},...s?.history?{history:s.history}:{},...s?.autocompleteState?{autocompleteState:s.autocompleteState}:{},...s?.promptText!==void 0?{promptText:s.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...A?{compositor:A}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),P=C(),N=async()=>{if(!f){f=!0;try{await P.dispose()}catch{}}},z=async()=>{await P.arm();let O=P.getCompositor();if(i&&O){let H=O;i.fn=K=>H.commitAbove(K),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.(O),r.setInterruptNotifier?.(H=>P.setInterrupting(H)),r.rearmStatus?.()};try{A?A.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{y=!0,P.setSoftStopping(!0),t.interrupt().catch($=>{He()&&console.error(" "+p.error("soft-stop session.interrupt() failed:"),$)});let M=r.subagentControl;M?.hasActiveForeground()&&M.cancelActiveForeground().catch($=>{He()&&console.error(" "+p.error("soft-stop cancelActiveForeground() failed:"),$)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{b=!0,t.interrupt().catch(M=>{He()&&console.error(" "+p.error("pause-interrupt session.interrupt() failed:"),M)})}),await z(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(I);let{fileBlocks:O,warnings:H}=gJ(e.text,{rootDir:process.cwd()});for(let M of H)(i??{fn:console.log}).fn(p.dim(` @-file: ${M}`));if(e.attachments.length>0&&(await t.waitForInitialization(),t.sessionId===void 0))throw new Error("CLI session initialized without a session id");let K=O.length>0||e.attachments.length>0?await fJ(e.text,e.attachments,void 0,O,t.sessionId):e.text,_=t.sendMessageStream(K);if(await Xa((M,$)=>{P.process(M,$)},async()=>{for await(let M of _){if(y||b)break;if(M.type==="chunk"&&M.chunk.type==="content"?(l=u?pJ(l,M.chunk.content):l+M.chunk.content,u=!1,d=!0):M.type==="message"&&!d&&(l=M.message.content),M.type==="stream_retry"&&(l=l.slice(0,c),u=l.length>0),M.type==="chunk"&&M.chunk.type==="tool_use_detail"){let $=M.chunk,U={toolName:$.toolName,toolUseId:$.toolUseId,input:$.toolInput,...$.toolInputRaw!==void 0&&{inputRaw:$.toolInputRaw}};x.set($.toolUseId,U),E.push(U)}else if(M.type==="chunk"&&M.chunk.type==="tool_result"){let $=M.chunk;c=l.length,u=!0;let U=x.get($.toolUseId);if(U&&(U.result=$.content,U.isError=$.isError,x.delete($.toolUseId)),r.onContextProgress){let X=Date.now();if(X-v>=S){v=X;try{let j=r.onContextProgress();j instanceof Promise&&await j}catch(j){He()&&console.error(" "+p.error("onContextProgress (status refresh) failed:"),j)}}}}if(M.type==="paused"){if(r.setPausedState?.(!0),await N(),A&&M.autoResume===!0){let $=new AbortController;w.abort=$;let U=M.resetsAt?M.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,X=U?`Keep waiting \u2014 auto-resumes at ${U}`:"Keep waiting \u2014 auto-resume in progress",j="Switch model / provider (type /model after)",ee="Stop waiting",se=[p.warning(" \u23F3 Usage limit reached.")+(U?p.dim(` Auto-resumes at ${U}.`):""),p.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];Cn(A,{header:se,options:[X,j,ee],signal:$.signal,initialIndex:0}).then(q=>{if(w.abort=null,!q)return;let te=q[0];te===void 0||te===X||(b=!0,te===j&&(i??{fn:console.log}).fn(p.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(le=>{He()&&console.error(" "+p.error("picker pause-interrupt session.interrupt() failed:"),le)}))}).catch(q=>{He()&&console.error(" "+p.error("picker promise rejected:"),q)})}else(i??{fn:console.log}).fn(NI({reason:M.reason,...M.resetsAt!==void 0?{resetsAt:M.resetsAt}:{},...M.accountId!==void 0?{accountId:M.accountId}:{},...M.autoResume!==void 0?{autoResume:M.autoResume}:{}}));continue}if(M.type==="resumed"){r.setPausedState?.(!1),w.abort?.abort(),w.abort=null;let $=M.hotSwapped&&M.accountId?`\u25B6 Resumed on ${M.accountId}`:"\u25B6 Resumed";l="",c=0,u=!1,d=!1,E.length=0,x.clear(),g=!1,h=void 0,m=!1,P=C(),f=!1,await z(),(i??{fn:console.log}).fn(p.success($));continue}if(M.type==="error"){await N(),ha(ca(M.error)),m=!0;continue}P.process(M),M.type==="done"&&(g=!0,h=M.metadata)}}),await N(),y){let M=i?i.fn:console.log,$=A?A.getPendingCount():0,U=$>0?` \xB7 ${$} queued`:"";M(p.warning(`\u23F8 Stopped${U} \u2014 work so far kept.`)+p.dim(" Send a message to continue.")),M("")}if(b){let M=i?i.fn:console.log;M(p.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),M("")}if(g&&!y&&!b){ks(n,a,l,h,E),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),ql(process.stdout),DW(process.stdout,"afk: turn complete");let M=U=>{i?i.fn(U):console.log(U)},$=Vw(l);if($){M(mJ($)),M("");let U=Eq(E);if(r.onTerminalState)try{r.onTerminalState($,{doneHasCorroboratingEvidence:U})}catch{}if(n.permissionMode==="autonomous"){let X=$.kind==="done"&&Bu().verifyDone===!0&&!U;xq($,void 0,{unverified:X})}}if(dke(h,n,M),r.onAfterTurn){let U=r.onAfterTurn();U instanceof Promise&&await U.catch(()=>{})}}}catch(O){await N(),m||ha(ca(O))}finally{await N(),zl(process.stdout,Jd(process.cwd(),!1)),i&&(i.fn=i.idleFn,i.suppressSubagentCompletion=!1),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setPausedState?.(!1),r.setPauseInterruptHandler?.(null),w.abort?.abort(),w.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}function uke(e,t){let n=Math.round(e*100),r=he(t);if(e>=1){let o=Math.round((e-1)*t);return{tier:"over",text:` context OVER ${Math.round(t/1e3)}k tok by ~${he(o)} tok \u2014 model output may be silently truncated`}}return e>=.95?{tier:"near",text:` context ${n}% used of ${r} \u2014 near limit; output may soon truncate (consider /clear or a fresh session)`}:e>=.8?{tier:"caution",text:` context ${n}% used of ${r} \u2014 approaching limit`}:e>.5?{tier:"normal",text:` context ${n}% used of ${r}`}:{tier:"quiet",text:null}}function dke(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(Ae(e.durationMs)),e.totalCostUsd!==void 0&&r.push(dt(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),i=Number(e.usage?.output_tokens??0);o+i>0&&r.push(he(o+i)+" tok"),r.length>0&&n(p.dim(" \u25E6 "+r.join(" \xB7 ")));let s=RA(t),a=Gt(t.model),l=uke(s,a);if(l.text!==null){let u=l.tier==="over"||l.tier==="near"?p.error:l.tier==="caution"?p.warning:p.dim;n(u(l.text))}let c=dJ(zb(Mg()),new Date,{autoResume:eO()});if(c.text!==null){let u=c.tier==="over"||c.tier==="near"?p.error:c.tier==="caution"?p.warning:p.dim;n(u(c.text))}n("")}var pke=5e3,mke=3,fke="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function gke(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(p.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function wJ(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,mascotBar:u,verdictLedger:d,shellPassthrough:m,bgResultNotifier:f}=s,g=null,h=[];e.session.current.waitForInitialization().then(async I=>{He()&&(g=cw(I)),await bp(e.session.current),h=kA()}).catch(()=>{});let y=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,b,w=!1,v=!1,S,E,x,D=0;for(f.onInjectable=()=>{D>=mke||!o.isAwaitingInput()||!o.bufferIsEmpty()||(D++,ql(process.stdout),y={text:fke,attachments:[]},o.abortPendingRead())};;){if(g&&(e.replRenderer.writeLine(g),e.replRenderer.writeLine(""),g=null),h.length>0){for(let _ of h)e.replRenderer.writeLine(_);e.replRenderer.writeLine(""),h=[]}let I=m.drainNotifications();for(let{job:_,result:F}of I){let M=F.errorReason===void 0?"\u2713":"\u2717",$=F.errorReason==="abort"?"killed":F.errorReason==="timeout"?"timed out":F.errorReason==="signal-killed"?"killed by signal":`exit ${F.exitCode??0}`,U=Math.max(0,Math.round(F.durationMs/100)/10);e.replRenderer.writeLine(p.dim(` ${M} [${_.id}] ${$} \xB7 ${U}s \xB7 `)+_.command)}let A=f.drainNotifications();for(let{job:_}of A){let F=_.status==="completed"?"\u2713":_.status==="failed"?"\u2717":"\u2298",M=_.endedAt!==void 0?Math.max(0,Math.round((_.endedAt-_.startedAt)/100)/10):0,$=ae(_.label,60);e.replRenderer.writeLine(p.dim(` ${F} [${_.jobId}] subagent ${_.status} \xB7 ${M}s \xB7 `)+$)}let C=l.renderIfChanged(e.stats.sessionId);if(C.length>0){for(let _ of C)e.replRenderer.writeLine(_);e.replRenderer.writeLine("")}let P,N;if(y===void 0){let _=await e.session.current.takePendingPlanExitSeed();_!==void 0&&(e.stats.permissionMode=_.mode,y={text:_.message,attachments:[]})}if(y!==void 0){let _=y;y=void 0;let F=hc(e.stats.permissionMode),M=As({buffer:_.text,promptText:F,isTTY:!!process.stdout.isTTY,attachmentSummary:Zl([..._.attachments])});e.replRenderer.writeLine(M),P=_.text.trim(),N=_.attachments}else{let _=b;b=void 0;let F=await o.readLine({promptFn:()=>hc(e.stats.permissionMode),..._!==void 0?{initialBuffer:_}:{},primePromptSuggestion:!0,onSigint:r,onShiftTab:()=>{Ww(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});P=F.text.trim(),N=F.attachments}if(!P&&N.length===0)continue;if(P.startsWith("!")){let _=/^(0|false|off|no)$/i.test(T.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!_&&(w||(w=!0,e.replRenderer.writeLine(p.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await m.dispatch(P))){e.statusLine.rearm();continue}}let z=!1;if(P.startsWith("/")){let _=await NW(P,e.slashCtx,N);if(_.handled){if(_.result==="exit"){await e.resolveWorktreeDisposition?.(!0),e.rl.close();return}if((P==="/clear"||P.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(p.dim(` transcript: ${t.path()}`)),d.reset(),S=void 0),_.result!==null&&typeof _.result=="object"&&"kind"in _.result&&_.result.kind==="submit"){y={text:_.result.message,attachments:N??[]},e.statusLine.rearm();continue}if(_.result!==null&&typeof _.result=="object"&&"kind"in _.result&&_.result.kind==="prefill"){b=_.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}z=!0}a.push(P),await gke(e,P);let O=P;if(z){let _=Px(P);if(_){let F=_.name.replace(/^\//,"").split(":").pop()??"";if(F&&bA(F)){let M={skillName:F,rawArgs:_.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},$=e.session.current.sessionId,U=Ns($),X=Date.now();B(`[afk trace] preflight.start commandName=${F}`);let j=!1,ee=await Ls(M,{cwd:e.stats.cwd??process.cwd(),artifactDir:U},se=>{He()&&e.replRenderer.writeLine(p.warning(`\u26A0 preflight(${F}) failed: `)+(se instanceof Error?se.message:String(se)))});j=ee!==null,B(`[afk trace] preflight.end commandName=${F} durationMs=${Date.now()-X} success=${j}`),O=SA(ee?.manifestBlock,P)}}}let H=m.drainInjections();H.length>0&&(O=H+O);let K=f.drainInjections();if(K.length>0&&(O=K+O),S!==void 0&&(O=S+`
|
|
1841
1841
|
|
|
1842
1842
|
`+O,S=void 0),e.hookRegistry)try{let _={event:"UserPromptSubmit",prompt:O,sessionId:e.stats.sessionId},F=await e.hookRegistry.dispatch(_);F.injectContext&&(O=F.injectContext+O)}catch(_){if(_ instanceof xe){e.replRenderer.writeLine(p.warning("\u2298 Turn blocked by hook")+(_.reason?p.dim(`: ${Dr(_.reason)}`):"")),e.statusLine.rearm();continue}if(_ instanceof lr){e.replRenderer.writeLine(p.warning("\u2298 Turn blocked by hook")+p.dim(`: handler timed out after ${_.timeoutMs}ms`)),e.statusLine.rearm();continue}throw _}if(E=void 0,x=void 0,await bJ({text:O,attachments:N},e.session.current,e.stats,{setInFlight(_){n.turnInFlight=_},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(_){await t.appendUser(_)},async onQueuedUserMessage(_){await t.appendQueuedUser(_)},async onTurnComplete(_,F){if(await t.appendTurn(_,F),e.stats.sessionId)try{ni(e.stats)}catch(M){v||(v=!0,e.replRenderer.writeLine(p.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(M instanceof Error?M.message:String(M))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:(_,F)=>{d?.push(_),E=_.kind,x=F?.doneHasCorroboratingEvidence},setActiveCompositor:_=>{n.activeCompositor=_},setInterruptNotifier:_=>{n.notifyInterrupting=_},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:_=>o.setBackgroundHandler(_),setSoftStopHandler:i,setPausedState:_=>o.setPausedState(_),setPauseInterruptHandler:_=>o.setPauseInterruptHandler(_),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(Jn(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:(_,F)=>{c.repaint(_),u?.onStage(_,F)}}:{}},e.stats.thinkingUi??e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(hc(e.stats.permissionMode))),e.hookRegistry)try{let _=await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId,...E!==void 0?{terminalState:E}:{},...x!==void 0?{doneHasCorroboratingEvidence:x}:{}},void 0,pke);_.injectContext&&_.injectContext.trim().length>0&&(S=_.injectContext)}catch(_){if(_ instanceof mt)throw _;_ instanceof lr?(B("[stop hook] handler timed out"),e.completionWriter.fn(p.dim(" [stop hook] timed out"))):_ instanceof xe?e.completionWriter.fn(p.dim(` [stop hook] blocked: ${Dr(_.reason??"no reason given")}`)):B("[stop hook] unexpected error: "+String(_))}}}function hke(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 SJ(e,t,n,r){let o=await jV(),i=new Hw({rl:e.rl,history:o,statusLine:e.statusLine}),s=hke(T.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await qV(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar,getMascotBar:()=>a?.mascotBar});a=cJ(e,n),await wJ(e,t,n,r,i,l,a,o),await e.resolveWorktreeDisposition?.(!0)}finally{n.tryAbortShellForeground=null,a?.shellPassthrough.drainOnExit(),a?.bgResultNotifier.dispose(),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)}}Pu();Ka();import{execFile as yke}from"node:child_process";import{dirname as bke,isAbsolute as wke,resolve as Ske}from"node:path";import{promisify as vke}from"node:util";var vJ=vke(yke),kke=3e3,Tke=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function Eke(){let t=(await vJ("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=wke(t)?t:Ske(process.cwd(),t);return bke(n)}async function kJ(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await Eke()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),kke)});try{let o=gn({execFile:vJ,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=>Tke.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}$m();Pu();import{promises as Rke}from"node:fs";import{dirname as xke,join as RJ}from"node:path";import{randomBytes as Ake}from"node:crypto";var Cke=["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(`
|
|
1843
|
-
`),TJ=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,CC=30,_ke=1024,Ike=8e3,Pke="haiku";async function Mke(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=Fke(n,_ke),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??Ike),s=t.signal?Lke([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await va({token:t.token,model:t.model??Pke,system:Cke,user:r,maxTokens:32,signal:s})}catch(d){let m=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(i)}let l=Oke(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=xke(t.worktreePath);return await $ke(l,c)}function Oke(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(TJ.test(t)&&t.length<=CC)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>CC)break;o=s}return TJ.test(o)?o:null}async function $ke(e,t){if(!await Dke(RJ(t,e)))return e;let n=Ake(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,CC-5)}-${n}`}async function Dke(e){try{return await Rke.access(e),!0}catch{return!1}}function Fke(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 Lke(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 xJ(e){let t,n,r=RJ(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await Mke(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=`${Pf(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return EJ(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 EJ(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 EJ(e,t){e&&e.setCwd(t),Nke(t)}function Nke(e){try{process.chdir(e)}catch{}}vt();G();import{spawn as CJ}from"child_process";import{existsSync as _J,mkdirSync as Wke,readFileSync as IJ,unlinkSync as AJ,writeFileSync as PJ}from"fs";import{get as Kke}from"https";import{join as MJ}from"path";import{readFileSync as Bke}from"fs";import{dirname as Uke,join as jke}from"path";import{fileURLToPath as Hke}from"url";function Ar(){try{return"5.100.
|
|
1843
|
+
`),TJ=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,CC=30,_ke=1024,Ike=8e3,Pke="haiku";async function Mke(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=Fke(n,_ke),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??Ike),s=t.signal?Lke([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await va({token:t.token,model:t.model??Pke,system:Cke,user:r,maxTokens:32,signal:s})}catch(d){let m=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(i)}let l=Oke(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=xke(t.worktreePath);return await $ke(l,c)}function Oke(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(TJ.test(t)&&t.length<=CC)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>CC)break;o=s}return TJ.test(o)?o:null}async function $ke(e,t){if(!await Dke(RJ(t,e)))return e;let n=Ake(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,CC-5)}-${n}`}async function Dke(e){try{return await Rke.access(e),!0}catch{return!1}}function Fke(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 Lke(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 xJ(e){let t,n,r=RJ(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await Mke(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=`${Pf(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return EJ(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 EJ(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 EJ(e,t){e&&e.setCwd(t),Nke(t)}function Nke(e){try{process.chdir(e)}catch{}}vt();G();import{spawn as CJ}from"child_process";import{existsSync as _J,mkdirSync as Wke,readFileSync as IJ,unlinkSync as AJ,writeFileSync as PJ}from"fs";import{get as Kke}from"https";import{join as MJ}from"path";import{readFileSync as Bke}from"fs";import{dirname as Uke,join as jke}from"path";import{fileURLToPath as Hke}from"url";function Ar(){try{return"5.100.4"}catch{}try{let e=Uke(Hke(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(Bke(jke(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}W();var Gke=64*1024,qke=10800*1e3,zke=800,Vke=3600*1e3,Jke="update-check.json",Yke="pending-update.json";function _C(){return MJ(aa(),Jke)}function Ip(){return MJ(aa(),Yke)}function IC(){let e=aa();_J(e)||Wke(e,{recursive:!0})}function OJ(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 $J(){try{let e=IJ(_C(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function DJ(){try{IC();let e=`
|
|
1844
1844
|
const https = require('https');
|
|
1845
1845
|
const fs = require('fs');
|
|
1846
1846
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|