agent-afk 5.21.0 → 5.21.1

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/telegram.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var _k=Object.defineProperty;var y=(t,e)=>()=>(t&&(e=t(t=0)),e);var ba=(t,e)=>{for(var n in e)_k(t,n,{get:e[n],enumerable:!0})};function fo(t){return po.find(e=>e.name===t)}function wa(t){return process.env[t]!==void 0}var po,E,H=y(()=>{"use strict";po=[{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_DEFAULT_SUBAGENT_MODEL",description:"Override the default model used when a subagent is dispatched without an explicit model.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_DIAGNOSE_BASELINE",description:"Kill switch for /diagnose reproducer baseline execution. When set to '0', the /diagnose skill skips executing the detected reproducer command for a ground-truth baseline; default enabled (runs). Set to '0' to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_DISABLE_PROMPT_CACHE",description:"Disable Anthropic prompt caching when set to 1/true/yes/on. Unset = caching enabled.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_DISABLE_BASH_INTERPRETER_GUARD",description:"Skip ONLY the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) when set to 1, leaving the rest of path-approval intact. Applies on interactive surfaces (REPL/Telegram), where the denylist is active but your workflow legitimately runs interpreter one-liners. The restricted-root substring check is unaffected. Default: denylist active on interactive surfaces; headless already fails open (opt in with AFK_FORCE_BASH_INTERPRETER_GUARD=1). To disable all of path-approval + bash restriction instead, use AFK_DISABLE_PATH_APPROVAL=1.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_DISABLE_PATH_APPROVAL",description:"Skip the path-approval + bash-restriction hooks entirely when set to 1. Use for headless flows that need wide-open file access (CI scripts, batch jobs). Default: hooks enabled. Note: on headless surfaces (afk chat, daemon) no grant manager is wired, so the interpreter denylist (python -c, node -e, sh -c, ...) fails OPEN by default \u2014 opt headless flows into it with AFK_FORCE_BASH_INTERPRETER_GUARD=1, or set this var to 1 to disable all of path-approval.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_FORCE_BASH_INTERPRETER_GUARD",description:"Apply the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) even on headless surfaces (afk chat, daemon) where no grant manager is wired. By default the denylist fires only on interactive surfaces (REPL/Telegram), failing open on headless so legitimate automation is not hard-blocked with no recourse. Set to 1 to opt headless flows back into the guard. Overridden by AFK_DISABLE_BASH_INTERPRETER_GUARD=1. Default: off (headless fails open).",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_EFFORT",description:"Effort hint guiding adaptive-thinking depth, forwarded as Anthropic output_config.effort (model-gated; ignored where unsupported). Accepts low | medium | high | xhigh | max.",type:"string",required:!1,example:"medium",category:"model"},{name:"AFK_MAX_BUDGET_USD",description:"Cumulative USD budget ceiling for the session. Aborts the turn when the running cost crosses this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. Falls back to provider default when unset.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Cap on total tokens per turn (input + output). Default 4096.",type:"number",required:!1,default:"4096",example:"8192",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_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), legacy aliases (opus, sonnet, haiku), the fixed-id fable alias (Claude Fable 5), or full model IDs.",type:"string",required:!1,default:"sonnet",example:"claude-opus-4-5",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-4-8",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-5",category:"model"},{name:"AFK_MODEL_MEDIUM_API_KEY",description:'Per-slot API key for the "medium" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_MEDIUM_BASE_URL",description:'Per-slot endpoint base URL for the "medium" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_SMALL",description:'Bind the "small" capability tier (cheap/fast) to a model id/alias. Overrides afk.config.json models.small.',type:"string",required:!1,example:"gpt-4o-mini",category:"model"},{name:"AFK_MODEL_SMALL_API_KEY",description:'Per-slot API key for the "small" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_SMALL_BASE_URL",description:'Per-slot endpoint base URL for the "small" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_PROMPT_CACHE_TTL",description:"TTL for Anthropic prompt-cache blocks. Accepts 5m or 1h.",type:"string",required:!1,default:"1h",example:"1h",category:"model"},{name:"AFK_SUGGEST_ENABLED",description:"Enable the LLM-backed ghost-text suggestion tier in the interactive REPL. Set to 1/true/yes/on to activate. Off by default.",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_GHOST",description:"Enable REPL ghost-text inline suggestions (Tier-1 history/dropdown + optional Tier-2 LLM). 1 = on (default), 0 = off. Set 0/false/off/no to disable all ghost text. Tier-2 LLM is separately gated by AFK_SUGGEST_ENABLED.",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_MODEL",description:"Override the small model used for REPL ghost-text suggestions. Falls back to AFK_COMPACT_MODEL or haiku-class for anthropic, or the session model for other providers.",type:"string",required:!1,category:"model"},{name:"AFK_TASK_BUDGET",description:"Per-task token budget ceiling. Aborts when cumulative usage would exceed it.",type:"number",required:!1,default:"100000",example:"200000",category:"model"},{name:"AFK_TEMPERATURE",description:"Numeric temperature override for model sampling. Provider default if unset.",type:"number",required:!1,example:"0.7",category:"model"},{name:"AFK_THINKING",description:"Extended-thinking mode. Accepts adaptive | disabled | enabled:<N> | enabled:max. Defaults to the model-appropriate mode when unset (adaptive on current models).",type:"string",required:!1,default:"adaptive",example:"adaptive",category:"model"},{name:"AFK_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_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 1 to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"1",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:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Controls auto-loading of MCP configuration from <cwd>/.mcp.json. Auto-loaded by default \u2014 set to 0 to disable (mitigates config-injection risk in shared/CI environments).",type:"boolean",required:!1,example:"0",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_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_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_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless for daemon and subagent surfaces and headed for repl/interactive \u2014 so an operator can watch the agent work in REPL mode.",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_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"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"}],E={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_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_OUTPUT_TOKENS(){return process.env.AFK_MAX_OUTPUT_TOKENS},get AFK_MAX_TOKENS(){return process.env.AFK_MAX_TOKENS},get AFK_MEMORY_EVIDENCE_GATE(){return process.env.AFK_MEMORY_EVIDENCE_GATE},get AFK_MODEL(){return process.env.AFK_MODEL},get AFK_MODEL_LARGE(){return process.env.AFK_MODEL_LARGE},get AFK_MODEL_LARGE_API_KEY(){return process.env.AFK_MODEL_LARGE_API_KEY},get AFK_MODEL_LARGE_BASE_URL(){return process.env.AFK_MODEL_LARGE_BASE_URL},get AFK_MODEL_LOCAL(){return process.env.AFK_MODEL_LOCAL},get AFK_MODEL_LOCAL_API_KEY(){return process.env.AFK_MODEL_LOCAL_API_KEY},get AFK_MODEL_LOCAL_BASE_URL(){return process.env.AFK_MODEL_LOCAL_BASE_URL},get AFK_MODEL_MEDIUM(){return process.env.AFK_MODEL_MEDIUM},get AFK_MODEL_MEDIUM_API_KEY(){return process.env.AFK_MODEL_MEDIUM_API_KEY},get AFK_MODEL_MEDIUM_BASE_URL(){return process.env.AFK_MODEL_MEDIUM_BASE_URL},get AFK_MODEL_SMALL(){return process.env.AFK_MODEL_SMALL},get AFK_MODEL_SMALL_API_KEY(){return process.env.AFK_MODEL_SMALL_API_KEY},get AFK_MODEL_SMALL_BASE_URL(){return process.env.AFK_MODEL_SMALL_BASE_URL},get AFK_VISION_MODELS(){return process.env.AFK_VISION_MODELS},get AFK_PROMPT_CACHE_TTL(){return process.env.AFK_PROMPT_CACHE_TTL},get AFK_SUGGEST_ENABLED(){return process.env.AFK_SUGGEST_ENABLED},get AFK_SUGGEST_GHOST(){return process.env.AFK_SUGGEST_GHOST},get AFK_SUGGEST_MODEL(){return process.env.AFK_SUGGEST_MODEL},get AFK_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_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_PRIMARY_CHAT_ID(){return process.env.AFK_TELEGRAM_PRIMARY_CHAT_ID},get AFK_TELEGRAM_NOTIFY_MODE(){return process.env.AFK_TELEGRAM_NOTIFY_MODE},get TELEGRAM_DATA_DIR(){return process.env.TELEGRAM_DATA_DIR},get TELEGRAM_VERBOSE(){return process.env.TELEGRAM_VERBOSE},get AFK_TELEGRAM_TRACE(){return process.env.AFK_TELEGRAM_TRACE},get AFK_TELEGRAM_CWD(){return process.env.AFK_TELEGRAM_CWD},get AFK_HOME(){return process.env.AFK_HOME},get AFK_STATE_DIR(){return process.env.AFK_STATE_DIR},get AFK_FRAMEWORK_DIR(){return process.env.AFK_FRAMEWORK_DIR},get HOME(){return process.env.HOME},get PATH(){return process.env.PATH},get AFK_DAEMON_CWD(){return process.env.AFK_DAEMON_CWD},get AFK_DAEMON_TASK(){return process.env.AFK_DAEMON_TASK},get AFK_DAEMON_TASK_ID(){return process.env.AFK_DAEMON_TASK_ID},get AFK_DAEMON_HOST(){return process.env.AFK_DAEMON_HOST},get AFK_SESSIONSTART_COOLDOWN_MS(){return process.env.AFK_SESSIONSTART_COOLDOWN_MS},get AFK_WORKTREE_AUTONAME(){return process.env.AFK_WORKTREE_AUTONAME},get AFK_WORKTREE_BRANCH_PREFIX(){return process.env.AFK_WORKTREE_BRANCH_PREFIX},get AFK_WORKTREE_BASE(){return process.env.AFK_WORKTREE_BASE},get AFK_WORKTREE_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BG_AUTO_DELIVER(){return process.env.AFK_BG_AUTO_DELIVER},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},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_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_BROWSER_DEFAULT_PROFILE(){return process.env.AFK_BROWSER_DEFAULT_PROFILE},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let e of po){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(E,e.name);n&&Object.defineProperty(E,e.name,{...n,enumerable:!1})}})()});import{existsSync as ku,mkdirSync as Ak,renameSync as Tk,cpSync as xk,rmSync as Rk}from"fs";import{join as G,dirname as Eu,isAbsolute as Au}from"path";import{homedir as va}from"os";import{fileURLToPath as Pk}from"url";function de(){let t=E.AFK_HOME;if(t!==void 0&&t!==""){if(!Au(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return G(va(),".afk")}function ot(){return G(de(),"agent-framework")}function mo(){return G(ot(),"forge-telemetry.jsonl")}function Tu(){return G(ot(),"briefs")}function xu(){return G(ot(),"facets")}function go(){return G(de(),"skills")}function bt(){return G(de(),"plugins")}function Ru(t=process.cwd()){return G(t,".afk")}function Pu(t=process.cwd()){return G(Ru(t),"skills")}function Iu(){return G(Ru(),"plugins")}function Cu(t=process.cwd()){return G(t,".afk","plans")}function ho(){return G(bt(),".index.json")}function Sa(){return G(st(),"schedules.json")}function Mu(){let t=Pk(import.meta.url),e=Eu(t);return G(e,"bundled-plugins")}function st(){return G(de(),"config")}function De(){let t=E.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!Au(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return G(de(),"state")}function me(){return G(De(),"sessions")}function yo(){return G(De(),"presence")}function bo(){return G(De(),"memory")}function rn(){return G(De(),"session-grants.jsonl")}function Vn(){return G(st(),"permissions.json")}function Ou(){return G(de(),"farms")}function Du(t){return G(Ou(),t)}function wo(t){if(!Ik.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function vo(t){return wo(t),G(De(),"witness",t)}function ka(){return G(De(),"receipts")}function Fu(t="default"){return G(De(),"daemon",`agent-afk@${t}`)}function Lu(){return G(De(),"worktree-sweep.lock")}function Lt(){return G(st(),"afk.env")}function wt(){return G(st(),"afk.config.json")}function Nu(){return G(st(),"settings.json")}function $u(t=process.cwd()){return G(t,".afk","settings.json")}function Uu(){return G(va(),".afk.env")}function So(){return G(va(),".afk.config.json")}function Ck(){return G(de(),"sessions")}function Mk(t,e){if(t!==e&&ku(t)&&!ku(e))try{Ak(Eu(e),{recursive:!0});try{Tk(t,e)}catch(n){if(n.code==="EXDEV")try{xk(t,e,{recursive:!0}),Rk(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
2
+ var _k=Object.defineProperty;var y=(t,e)=>()=>(t&&(e=t(t=0)),e);var ba=(t,e)=>{for(var n in e)_k(t,n,{get:e[n],enumerable:!0})};function fo(t){return po.find(e=>e.name===t)}function wa(t){return process.env[t]!==void 0}var po,E,H=y(()=>{"use strict";po=[{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_DEFAULT_SUBAGENT_MODEL",description:"Override the default model used when a subagent is dispatched without an explicit model.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_DIAGNOSE_BASELINE",description:"Kill switch for /diagnose reproducer baseline execution. When set to '0', the /diagnose skill skips executing the detected reproducer command for a ground-truth baseline; default enabled (runs). Set to '0' to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_DISABLE_PROMPT_CACHE",description:"Disable Anthropic prompt caching when set to 1/true/yes/on. Unset = caching enabled.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_DISABLE_BASH_INTERPRETER_GUARD",description:"Skip ONLY the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) when set to 1, leaving the rest of path-approval intact. Applies on interactive surfaces (REPL/Telegram), where the denylist is active but your workflow legitimately runs interpreter one-liners. The restricted-root substring check is unaffected. Default: denylist active on interactive surfaces; headless already fails open (opt in with AFK_FORCE_BASH_INTERPRETER_GUARD=1). To disable all of path-approval + bash restriction instead, use AFK_DISABLE_PATH_APPROVAL=1.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_DISABLE_PATH_APPROVAL",description:"Skip the path-approval + bash-restriction hooks entirely when set to 1. Use for headless flows that need wide-open file access (CI scripts, batch jobs). Default: hooks enabled. Note: on headless surfaces (afk chat, daemon) no grant manager is wired, so the interpreter denylist (python -c, node -e, sh -c, ...) fails OPEN by default \u2014 opt headless flows into it with AFK_FORCE_BASH_INTERPRETER_GUARD=1, or set this var to 1 to disable all of path-approval.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_FORCE_BASH_INTERPRETER_GUARD",description:"Apply the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) even on headless surfaces (afk chat, daemon) where no grant manager is wired. By default the denylist fires only on interactive surfaces (REPL/Telegram), failing open on headless so legitimate automation is not hard-blocked with no recourse. Set to 1 to opt headless flows back into the guard. Overridden by AFK_DISABLE_BASH_INTERPRETER_GUARD=1. Default: off (headless fails open).",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_EFFORT",description:"Effort hint guiding adaptive-thinking depth, forwarded as Anthropic output_config.effort (model-gated; ignored where unsupported). Accepts low | medium | high | xhigh | max.",type:"string",required:!1,example:"medium",category:"model"},{name:"AFK_MAX_BUDGET_USD",description:"Cumulative USD budget ceiling for the session. Aborts the turn when the running cost crosses this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. Falls back to provider default when unset.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Cap on total tokens per turn (input + output). Default 4096.",type:"number",required:!1,default:"4096",example:"8192",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_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), legacy aliases (opus, sonnet, haiku), the fixed-id fable alias (Claude Fable 5), or full model IDs.",type:"string",required:!1,default:"sonnet",example:"claude-opus-4-5",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-4-8",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-5",category:"model"},{name:"AFK_MODEL_MEDIUM_API_KEY",description:'Per-slot API key for the "medium" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_MEDIUM_BASE_URL",description:'Per-slot endpoint base URL for the "medium" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_SMALL",description:'Bind the "small" capability tier (cheap/fast) to a model id/alias. Overrides afk.config.json models.small.',type:"string",required:!1,example:"gpt-4o-mini",category:"model"},{name:"AFK_MODEL_SMALL_API_KEY",description:'Per-slot API key for the "small" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_SMALL_BASE_URL",description:'Per-slot endpoint base URL for the "small" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_PROMPT_CACHE_TTL",description:"TTL for Anthropic prompt-cache blocks. Accepts 5m or 1h.",type:"string",required:!1,default:"1h",example:"1h",category:"model"},{name:"AFK_SUGGEST_ENABLED",description:"Enable the LLM-backed ghost-text suggestion tier in the interactive REPL. Set to 1/true/yes/on to activate. Off by default.",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_GHOST",description:"Enable REPL ghost-text inline suggestions (Tier-1 history/dropdown + optional Tier-2 LLM). 1 = on (default), 0 = off. Set 0/false/off/no to disable all ghost text. Tier-2 LLM is separately gated by AFK_SUGGEST_ENABLED.",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_MODEL",description:"Override the small model used for REPL ghost-text suggestions. Falls back to AFK_COMPACT_MODEL or haiku-class for anthropic, or the session model for other providers.",type:"string",required:!1,category:"model"},{name:"AFK_TASK_BUDGET",description:"Per-task token budget ceiling. Aborts when cumulative usage would exceed it.",type:"number",required:!1,default:"100000",example:"200000",category:"model"},{name:"AFK_TEMPERATURE",description:"Numeric temperature override for model sampling. Provider default if unset.",type:"number",required:!1,example:"0.7",category:"model"},{name:"AFK_THINKING",description:"Extended-thinking mode. Accepts adaptive | disabled | enabled:<N> | enabled:max. Defaults to the model-appropriate mode when unset (adaptive on current models).",type:"string",required:!1,default:"adaptive",example:"adaptive",category:"model"},{name:"AFK_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_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 1 to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"1",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:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Controls auto-loading of MCP configuration from <cwd>/.mcp.json. Auto-loaded by default \u2014 set to 0 to disable (mitigates config-injection risk in shared/CI environments).",type:"boolean",required:!1,example:"0",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_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_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_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless for daemon and subagent surfaces and headed for repl/interactive \u2014 so an operator can watch the agent work in REPL mode.",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_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"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"}],E={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_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_OUTPUT_TOKENS(){return process.env.AFK_MAX_OUTPUT_TOKENS},get AFK_MAX_TOKENS(){return process.env.AFK_MAX_TOKENS},get AFK_MEMORY_EVIDENCE_GATE(){return process.env.AFK_MEMORY_EVIDENCE_GATE},get AFK_MODEL(){return process.env.AFK_MODEL},get AFK_MODEL_LARGE(){return process.env.AFK_MODEL_LARGE},get AFK_MODEL_LARGE_API_KEY(){return process.env.AFK_MODEL_LARGE_API_KEY},get AFK_MODEL_LARGE_BASE_URL(){return process.env.AFK_MODEL_LARGE_BASE_URL},get AFK_MODEL_LOCAL(){return process.env.AFK_MODEL_LOCAL},get AFK_MODEL_LOCAL_API_KEY(){return process.env.AFK_MODEL_LOCAL_API_KEY},get AFK_MODEL_LOCAL_BASE_URL(){return process.env.AFK_MODEL_LOCAL_BASE_URL},get AFK_MODEL_MEDIUM(){return process.env.AFK_MODEL_MEDIUM},get AFK_MODEL_MEDIUM_API_KEY(){return process.env.AFK_MODEL_MEDIUM_API_KEY},get AFK_MODEL_MEDIUM_BASE_URL(){return process.env.AFK_MODEL_MEDIUM_BASE_URL},get AFK_MODEL_SMALL(){return process.env.AFK_MODEL_SMALL},get AFK_MODEL_SMALL_API_KEY(){return process.env.AFK_MODEL_SMALL_API_KEY},get AFK_MODEL_SMALL_BASE_URL(){return process.env.AFK_MODEL_SMALL_BASE_URL},get AFK_VISION_MODELS(){return process.env.AFK_VISION_MODELS},get AFK_PROMPT_CACHE_TTL(){return process.env.AFK_PROMPT_CACHE_TTL},get AFK_SUGGEST_ENABLED(){return process.env.AFK_SUGGEST_ENABLED},get AFK_SUGGEST_GHOST(){return process.env.AFK_SUGGEST_GHOST},get AFK_SUGGEST_MODEL(){return process.env.AFK_SUGGEST_MODEL},get AFK_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_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_PRIMARY_CHAT_ID(){return process.env.AFK_TELEGRAM_PRIMARY_CHAT_ID},get AFK_TELEGRAM_NOTIFY_MODE(){return process.env.AFK_TELEGRAM_NOTIFY_MODE},get TELEGRAM_DATA_DIR(){return process.env.TELEGRAM_DATA_DIR},get TELEGRAM_VERBOSE(){return process.env.TELEGRAM_VERBOSE},get AFK_TELEGRAM_TRACE(){return process.env.AFK_TELEGRAM_TRACE},get AFK_TELEGRAM_CWD(){return process.env.AFK_TELEGRAM_CWD},get AFK_HOME(){return process.env.AFK_HOME},get AFK_STATE_DIR(){return process.env.AFK_STATE_DIR},get AFK_FRAMEWORK_DIR(){return process.env.AFK_FRAMEWORK_DIR},get HOME(){return process.env.HOME},get PATH(){return process.env.PATH},get AFK_DAEMON_CWD(){return process.env.AFK_DAEMON_CWD},get AFK_DAEMON_TASK(){return process.env.AFK_DAEMON_TASK},get AFK_DAEMON_TASK_ID(){return process.env.AFK_DAEMON_TASK_ID},get AFK_DAEMON_HOST(){return process.env.AFK_DAEMON_HOST},get AFK_SESSIONSTART_COOLDOWN_MS(){return process.env.AFK_SESSIONSTART_COOLDOWN_MS},get AFK_WORKTREE_AUTONAME(){return process.env.AFK_WORKTREE_AUTONAME},get AFK_WORKTREE_BRANCH_PREFIX(){return process.env.AFK_WORKTREE_BRANCH_PREFIX},get AFK_WORKTREE_BASE(){return process.env.AFK_WORKTREE_BASE},get AFK_WORKTREE_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BG_AUTO_DELIVER(){return process.env.AFK_BG_AUTO_DELIVER},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},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_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_BROWSER_DEFAULT_PROFILE(){return process.env.AFK_BROWSER_DEFAULT_PROFILE},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let e of po){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(E,e.name);n&&Object.defineProperty(E,e.name,{...n,enumerable:!1})}})()});import{existsSync as ku,mkdirSync as Ak,renameSync as Tk,cpSync as xk,rmSync as Rk}from"fs";import{join as G,dirname as Eu,isAbsolute as Au}from"path";import{homedir as va}from"os";import{fileURLToPath as Pk}from"url";function de(){let t=E.AFK_HOME;if(t!==void 0&&t!==""){if(!Au(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return G(va(),".afk")}function ot(){return G(de(),"agent-framework")}function mo(){return G(ot(),"forge-telemetry.jsonl")}function Tu(){return G(ot(),"briefs")}function xu(){return G(ot(),"facets")}function go(){return G(de(),"skills")}function bt(){return G(de(),"plugins")}function Ru(t=process.cwd()){return G(t,".afk")}function Pu(t=process.cwd()){return G(Ru(t),"skills")}function Iu(t=process.cwd()){return G(Ru(t),"plugins")}function Cu(t=process.cwd()){return G(t,".afk","plans")}function ho(){return G(bt(),".index.json")}function Sa(){return G(st(),"schedules.json")}function Mu(){let t=Pk(import.meta.url),e=Eu(t);return G(e,"bundled-plugins")}function st(){return G(de(),"config")}function De(){let t=E.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!Au(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return G(de(),"state")}function me(){return G(De(),"sessions")}function yo(){return G(De(),"presence")}function bo(){return G(De(),"memory")}function rn(){return G(De(),"session-grants.jsonl")}function Vn(){return G(st(),"permissions.json")}function Ou(){return G(de(),"farms")}function Du(t){return G(Ou(),t)}function wo(t){if(!Ik.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function vo(t){return wo(t),G(De(),"witness",t)}function ka(){return G(De(),"receipts")}function Fu(t="default"){return G(De(),"daemon",`agent-afk@${t}`)}function Lu(){return G(De(),"worktree-sweep.lock")}function Lt(){return G(st(),"afk.env")}function wt(){return G(st(),"afk.config.json")}function Nu(){return G(st(),"settings.json")}function $u(t=process.cwd()){return G(t,".afk","settings.json")}function Uu(){return G(va(),".afk.env")}function So(){return G(va(),".afk.config.json")}function Ck(){return G(de(),"sessions")}function Mk(t,e){if(t!==e&&ku(t)&&!ku(e))try{Ak(Eu(e),{recursive:!0});try{Tk(t,e)}catch(n){if(n.code==="EXDEV")try{xk(t,e,{recursive:!0}),Rk(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
3
3
  `)}}}catch{}}function Bu(){Mk(Ck(),me())}function _a(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>_u)throw new Error(`Invalid browser profile: exceeds ${_u} chars`);if(!Ok.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function Dk(){return G(De(),"browser")}function Fk(t){return _a(t),G(Dk(),t)}function Ea(t){return G(Fk(t),"storageState.json")}function Jn(t){return typeof t=="string"&&t.length>0&&t.length<=Nk&&Lk.test(t)}function Yn(t){if(!Jn(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return G(me(),t)}function ko(t){return G(Yn(t),"events.jsonl")}function ju(t){return G(Yn(t),"session.key")}function _o(){return G(De(),"mcp","server-status.json")}var Ik,Ok,_u,Lk,Nk,W=y(()=>{"use strict";H();Ik=/^[a-zA-Z0-9_-]+$/;Ok=/^[A-Za-z0-9_-]+$/,_u=128;Lk=/^[A-Za-z0-9_-]+$/,Nk=128});function $k(){return E.AFK_DEBUG==="1"||E.DEBUG==="1"}function j(...t){$k()&&console.log(...t)}var ue=y(()=>{"use strict";H()});import Uk from"better-sqlite3";import{existsSync as Xn,mkdirSync as Hu,readFileSync as Eo,writeFileSync as Ku,readdirSync as Bk,appendFileSync as jk,unlinkSync as Wu,copyFileSync as Hk,renameSync as Kk}from"fs";import{join as Ee,basename as Gu,resolve as Ao,relative as Wk}from"path";function Qu(t){return Math.ceil(t.length/3.5)}function Xk(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function Vu(t){if(!t||t.length>100||!Qk.test(t))throw new Error(`Invalid procedure name "${t}": must be 1-100 chars, alphanumeric/hyphens/underscores only`);return t}function t_(t){if(!t||typeof t!="object")return!1;let e=t;if(typeof e.type!="string"||!Zk.has(e.type)||typeof e.timestamp!="string"||!e.data||typeof e.data!="object")return!1;if(e.type==="fact"){let n=e.data;if(typeof n.category!="string"||!e_.has(n.category))return!1}return!0}function Ju(t,e){let n=Wk(e,t);if(n.startsWith("..")||n.startsWith("/"))throw new Error("Path traversal detected")}function Yu(t,e){let n=e.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!n)return{name:Gu(t,".md"),content:e,created:"",source_session:null,access_count:0};let r=n[1]??"",o=n[2]??"",s=l=>l.match(/^name:\s*(.+)$/m)?.[1]?.trim()??Gu(t,".md"),i=l=>l.match(/^created:\s*(.+)$/m)?.[1]?.trim()??"",a=l=>l.match(/^source_session:\s*(.+)$/m)?.[1]?.trim()??null,c=l=>{let d=l.match(/^access_count:\s*(\d+)$/m);return d?parseInt(d[1],10):0};return{name:s(r),content:o.trim(),created:i(r),source_session:a(r),access_count:c(r)}}var qu,Gk,qk,zu,To,zk,Ro,Vk,Jk,Xu,Aa,xo,Yk,we,Qk,Zk,e_,Po=y(()=>{"use strict";W();ue();qu="HOT.md",Gk="HOT.md.bak",qk="memory.db",zu="memory-wal.jsonl",To="procedures",zk="HOT.md.tmp",Ro=5250,Vk=Math.ceil(Ro/3.5),Jk=600,Xu=.8,Aa='<!-- HOT TRUNCATED to fit the ~1,500-token cap; move durable detail to the fact archive (memory_update target:"fact"). -->',xo=4,Yk=`
4
4
  CREATE TABLE IF NOT EXISTS sessions (
5
5
  session_id TEXT PRIMARY KEY,
@@ -1066,7 +1066,7 @@ Note: this search ran in basic-regex (BRE) mode, where '|' is a literal pipe \u2
1066
1066
  [output truncated]`,R=!0),d({content:k,...R?{truncated:!0}:{}})}),p.on("error",v=>{d({content:`Failed to execute grep: ${v.message}`,isError:!0})})})}}var Dm,Fm=y(()=>{"use strict";dt();xt();En();Dm=$c()});import{promises as lx}from"fs";var Lm,Nm=y(()=>{"use strict";xt();Lm=async(t,e,n)=>{if(!t||typeof t!="object")throw new Error("Invalid input: expected an object");let o=t.path;if(typeof o!="string")throw new Error("Invalid input: path must be a string");let s;try{s=Ie(o,n,"read")}catch(i){return{content:i instanceof Error?i.message:String(i),isError:!0}}try{let i=await lx.readdir(s,{withFileTypes:!0}),a=i.filter(u=>u.isDirectory()).map(u=>`${u.name}/`),c=i.filter(u=>!u.isDirectory()).map(u=>u.name);a.sort(),c.sort();let l=[...a,...c];return l.length===0?{content:"(empty directory)"}:{content:l.join(`
1067
1067
  `)}}catch(i){if(i instanceof Error){let a=i;return a.code==="ENOENT"?{content:`Directory not found: ${s}`,isError:!0}:a.code==="ENOTDIR"?{content:`Not a directory: ${s}`,isError:!0}:a.code==="EACCES"?{content:`Permission denied: ${s}`,isError:!0}:{content:`Error listing directory: ${i.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}}});function dx(t=hn){return async(e,n)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let o=e.message;if(typeof o!="string")return{content:"Invalid input: message must be a string",isError:!0};if(o.length===0)return{content:"Invalid input: message must be non-empty",isError:!0};if(o.length>$m)return{content:`Invalid input: message exceeds Telegram's ${$m}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let s=E.TELEGRAM_BOT_TOKEN;if(!s)return{content:"Telegram is not configured: TELEGRAM_BOT_TOKEN is not set. Run the bot setup wizard or export the env var before using send_telegram.",isError:!0};let i=rs();if(i.length===0)return{content:"Telegram is not configured: AFK_TELEGRAM_ALLOWED_CHAT_IDS is empty or unset. Add the operator chat ID(s) before using send_telegram.",isError:!0};let a=[];for(let c of i){let l=await t({token:s,chatId:c,text:o});l.ok||a.push(`chat ${c}: ${l.errorMessage??`HTTP ${l.status}`}`)}return a.length===i.length?{content:`Failed to send Telegram message to any chat. ${a.join("; ")}`,isError:!0}:a.length>0?{content:`Sent Telegram message to ${i.length-a.length}/${i.length} chat(s); ${a.length} failed: ${a.join("; ")}`}:{content:i.length===1?`Sent Telegram message to chat ${i[0]}.`:`Sent Telegram message to ${i.length} chats.`}}}var $m,Um,Bm=y(()=>{"use strict";H();os();sc();$m=4096;Um=dx()});import{JSDOM as ux}from"jsdom";import{Readability as px}from"@mozilla/readability";import fx from"turndown";function jm(t){return t.replace(/\n{3,}/g,`
1068
1068
 
1069
- `).trim()}function mx(t){return(t?.textContent??"").replace(/\s+/g," ").trim().length}function Km(t,e){let r=new ux(t,{url:e}).window.document,o=(r.title??"").trim(),s=null;try{let l=r.cloneNode(!0);s=new px(l).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let l=jm(Uc.turndown(s.content)),d=(s.title??"").trim()||o,u=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:d,markdown:l,textLength:u,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",c=jm(Uc.turndown(a));return{title:o,markdown:c,textLength:mx(i),usedFallback:!0}}var Hm,Uc,Wm=y(()=>{"use strict";Hm=200,Uc=new fx({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});Uc.remove(["script","style","noscript","iframe"])});function hx(t,e){return new Promise((n,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(e?.reason??new Error("aborted"))},s=setTimeout(()=>{e?.removeEventListener("abort",o),n()},t);e?.addEventListener("abort",o,{once:!0})})}function Gm(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function yx(t,e){let n=t.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,e)}async function $s(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??hx,c=n.signal??void 0,l;for(let d=0;d<=o;d++){if(c?.aborted)throw c.reason??new Error("aborted");try{let u=await t(e,n);if(!gx.has(u.status)||d===o)return u;let p=yx(u,i)??Gm(d,s,i);j("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,c)}catch(u){if(c?.aborted||(l=u,d===o))throw u;let p=Gm(d,s,i);j("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,c)}}throw l??new Error("retryFetch: exhausted without a result")}var gx,Bc=y(()=>{"use strict";ue();gx=new Set([429,502,503,504])});import{readFileSync as bx}from"node:fs";import{join as wx}from"path";function vx(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function qm(t,e){return vx(e).test(t)}function _x(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(Sx.has(e))return!0;if(kx.has(e))return!1}return!1}function zm(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function Ex(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function Vm(t){let e=t===void 0||t.trim()===""?"default":t.trim();return _a(e),e}function Ax(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Tx(t){try{return bx(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function xx(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=Vm(e.defaultProfile)),n}function Jm(t){let e=t?.env??E,n=t?.readFileSync??Tx,r=t?.surface??e.AGENT_SURFACE,o=_x(e.AFK_BROWSER_HEADLESS,r),s=zm(e.AFK_BROWSER_ALLOWED_DOMAINS),i=zm(e.AFK_BROWSER_BLOCKED_DOMAINS),a=Ax(e.AFK_BROWSER_DOM_SNAPSHOTS),c=Ex(e.AFK_BROWSER_BACKEND),l=Vm(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():wx(st(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(w){throw new Error(`Failed to parse browser config at ${p}: ${String(w)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let h=xx(d,m);return h.configPath=p,h}function jc(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(qm(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>qm(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Sx,kx,Hc=y(()=>{"use strict";H();W();Sx=new Set(["daemon","subagent","telegram","afk"]),kx=new Set(["repl","interactive","cli"])});import Jt from"node:fs";import Us from"node:path";import{randomBytes as Rx}from"node:crypto";import{chromium as Px}from"playwright";function Ix(){try{return"5.21.0"}catch{}try{let t=Us.resolve(import.meta.dirname,"../../../package.json"),e=Jt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Cx,Bs,Ym=y(()=>{"use strict";W();ue();Cx=Ix(),Bs=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(e){this.config=e}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=Px.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,e)).catch(e=>{throw this.launchPromise=void 0,e}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),c=await i.content(),l=i.url(),d=a!==null?a.status():null;return{html:c,finalUrl:l,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${Cx}`}}loadStorageState(e){let n=Ea(e);try{if(!Jt.existsSync(n))return;let r=JSON.parse(Jt.readFileSync(n,"utf8"));return j("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){j("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Ea(e);if(!Jt.existsSync(r))return;let o=await n.storageState(),s=Us.join(Us.dirname(r),`.${Us.basename(r)}.${process.pid}.${Rx(4).toString("hex")}.tmp`);Jt.writeFileSync(s,JSON.stringify(o),{mode:384}),Jt.chmodSync(s,384),Jt.renameSync(s,r),j("[browser/vault] saved session",{profile:e,file:r})}catch(r){j("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as Mx}from"crypto";function Kc(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of Ox)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function Xm(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&Dx.test(t.label))}function Qm(t){return Mx("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Zm(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var Ox,Dx,hr=y(()=>{"use strict";Ox=[{name:"aws-access-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"github-pat",regex:/ghp_[a-zA-Z0-9]{36}/g},{name:"openai-bearer",regex:/sk-[a-zA-Z0-9_-]{20,}/g},{name:"slack-token",regex:/xox[abp]-[a-zA-Z0-9-]{10,}/g},{name:"jwt",regex:/eyJ[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}/g},{name:"form-password",regex:/password=[^&\s]+/gi}];Dx=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Fx}from"node:crypto";function Lx(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Nx(t,e,n){return`el_${Fx("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function $x(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function eg(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function ng(t,e){let n=t.role??"",r=t.name??"";tg.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])ng(s,e)}async function Ux(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},rg).catch(()=>[])}async function Bx(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let h=s.type;h==="checkbox"?l="checkbox":h==="radio"?l="radio":h==="button"||h==="submit"||h==="reset"?l="button":h==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},rg).catch(()=>[])}function jx(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function js(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=jx(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Ux(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,h]=await Promise.all([i,a,c,l,d]),w,b=!1;u!==null?(w=[],ng(u,w)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,w=(await Bx(t)).filter(B=>tg.has(B.role??"")));let S=new Map;for(let I of p){let B=eg(I.name),D=S.get(B);(!D||D.bbox.w===0&&I.bbox.w>0)&&S.set(B,I)}let A=w.map(I=>({ax:I,dom:S.get(eg(I.name??""))})),v=r?A:A.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);v.sort((I,B)=>{let D=I.dom?.bbox.y??0,x=B.dom?.bbox.y??0;if(D!==x)return D-x;let C=I.dom?.bbox.x??0,L=B.dom?.bbox.x??0;return C-L}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=v.slice(0,n).map((I,B)=>{let D=I.ax.role??"generic",x=I.ax.name??"",C=Nx(D,x,B),L=I.dom?.bbox??{x:0,y:0,w:0,h:0},M=I.dom?.type??null,F=null;I.ax.value!==void 0&&I.ax.value!==null&&(F=String(I.ax.value)),I.ax.checked!==void 0&&(F=String(I.ax.checked)),Xm({role:D,kind:M})&&(F="[redacted]");let O={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(O.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(O.selected=I.ax.selected),I.ax.expanded!==void 0&&(O.expanded=I.ax.expanded);let N;I.dom?.testId?N=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(N=`#${I.dom.id}`);let q={id:C,role:D,label:Lx(x),kind:M,value:F,state:O,bbox:L};return N!==void 0&&(q.selector=N),q}),_="idle";try{let I=await t.evaluate(()=>document.readyState);I==="loading"?_="loading":I==="interactive"?_="navigating":_="idle"}catch{_="navigating"}_!=="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 P=$x(f),T=`obs_${e.observationCounter.toString(36)}`,U=new Date().toISOString();return{observationId:T,url:m,title:h,textSummary:P,interactive:R,status:{httpStatus:e.httpStatus??null,loadingState:_,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:U}}var tg,rg,og=y(()=>{"use strict";hr();tg=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);rg="a[href], button, input, select, textarea, [role], [tabindex], label"});async function sg(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Wc(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>sg(t,s)))).filter(o=>o!==null)}async function Hx(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Gc(t,e,n){switch(e.kind){case"element_id":return Kx(t,e,n);case"selector":return Wx(t,e);case"semantic":return Gx(t,e)}}async function Kx(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Wc(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Wx(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Wc(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function Gx(t,e){return e.role!==void 0?qx(t,e.text,e.role):zx(t,e.text,e)}async function qx(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Wc(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function zx(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await Hx(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=u.slice(0,5),f=[];for(let h=0;h<p.length;h++){let w=p[h];if(w===void 0)continue;let b=await sg(w.locator,w.index);if(b!==null){let S=`${b.role}:${b.label}:${h}`,A=0;for(let v=0;v<S.length;v++)A=A*31+S.charCodeAt(v)>>>0;f.push({...b,id:`el_${A.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var ig=y(()=>{"use strict"});import{randomBytes as Vx}from"crypto";import{mkdir as Jx,stat as Yx,writeFile as Xx}from"fs/promises";import{join as qc}from"path";import{gzip as Qx}from"zlib";import{promisify as Zx}from"util";function eR(t){return qc(vo(t),"browser")}function tR(t){return qc(eR(t),"screenshots")}function nR(){return new Date().toISOString().replace(/[:.]/g,"-")}function rR(){return Vx(3).toString("hex")}async function zc(t,e,n){if(e.length>ag)throw new Error(`writeScreenshotSidecar: buffer exceeds ${ag} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=tR(t);await Jx(r,{recursive:!0});let o=`${nR()}-${rR()}-${n}.png`,s=qc(r,o);await Xx(s,e);let{size:i}=await Yx(s);return{path:s,bytes:i}}var hK,ag,cg=y(()=>{"use strict";W();hr();hK=Zx(Qx);ag=5*1024*1024});var dg={};ba(dg,{PlaywrightProvider:()=>Vc});function lg(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var Vc,ug=y(()=>{"use strict";Ym();og();ig();Hc();hr();cg();Vc=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Bs(e)}async open(e){let n=jc(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(l){a=l}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let c=await js(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,c.interactive,c.url,c.title,"browser_open"),a!==null)throw a;return c}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await js(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await Gc(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${lg(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":{let h=Kc(e.value??"");await c.fill(e.value??"");break}case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(w){l=w}else l=h}let u=r.url();if(u!==s){let h=jc(u,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:h.reason}}let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await js(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Gc(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${lg(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await zc(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await zc(n,o,r);return s}catch{return null}}}});var Xt={};ba(Xt,{__resetBrowserRegistryForTests:()=>cR,browserProviderActive:()=>iR,closeBrowserProvider:()=>Jc,getBrowserProvider:()=>sR,peekBrowserProvider:()=>aR});function pg(){Promise.resolve(Jc()).then(()=>{process.exit(130)})}function fg(){Promise.resolve(Jc()).then(()=>{process.exit(143)})}function mg(){Qe=null}function oR(){Hs||(process.on("SIGINT",pg),process.on("SIGTERM",fg),process.on("exit",mg),Hs=!0)}function gg(){Hs&&(process.removeListener("SIGINT",pg),process.removeListener("SIGTERM",fg),process.removeListener("exit",mg),Hs=!1)}async function sR(t){return Qe!==null?Qe:(Yt!==null||(Yt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(ug(),dg)),n=Jm(t),r=new e(n);return oR(),Qe=r,Yt=null,r})()),Yt)}async function Jc(){if(Qe===null)return;let t=Qe;Qe=null,Yt=null,gg(),await t.shutdown()}function iR(){return Qe!==null}function aR(){return Qe}function cR(){Qe=null,Yt=null,gg()}var Qe,Yt,Hs,Qt=y(()=>{"use strict";Hc();Qe=null,Yt=null,Hs=!1});function hg(t,e){try{return Km(t,e)}catch(n){return j("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function fR(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Qt(),Xt));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function yg(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??fR,o=null,s=t,i=null,a=null;try{let l=await $s(n,t,{headers:pR,redirect:"follow",signal:e.signal});i=l.status,s=l.url||t;let d=l.headers.get("content-type")??"";if(l.ok){if(uR.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await l.text();if(dR.test(d)&&!lR.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};o=hg(u,s)}}catch(l){if(e.signal.aborted||l instanceof Error&&l.message.startsWith("web_scrape markdown mode received binary"))throw l;a=l}if(!(o===null||o.textLength<Hm)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let l=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal}),d=hg(l.html,l.finalUrl);if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:l.finalUrl,usedRender:!0}}catch(l){if(e.signal.aborted)throw l;if(o===null){let d=l instanceof Error?l.message:String(l),u=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${t}: fetch failed (${u}) and render failed (${d}).`);throw p.cause=l,p}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${i??"error"}).`)}var lR,dR,uR,pR,bg=y(()=>{"use strict";Wm();Bc();ue();lR=/(text\/html|application\/xhtml\+xml)/i,dR=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,uR=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,pR={"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 hR(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(mR,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),gR),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=ws(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function wg(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?hR({apiKey:t.exaApiKey,fetchFn:t.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function vg(t,e){if(e.length===0)return`# Search results for "${t}"
1069
+ `).trim()}function mx(t){return(t?.textContent??"").replace(/\s+/g," ").trim().length}function Km(t,e){let r=new ux(t,{url:e}).window.document,o=(r.title??"").trim(),s=null;try{let l=r.cloneNode(!0);s=new px(l).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let l=jm(Uc.turndown(s.content)),d=(s.title??"").trim()||o,u=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:d,markdown:l,textLength:u,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",c=jm(Uc.turndown(a));return{title:o,markdown:c,textLength:mx(i),usedFallback:!0}}var Hm,Uc,Wm=y(()=>{"use strict";Hm=200,Uc=new fx({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});Uc.remove(["script","style","noscript","iframe"])});function hx(t,e){return new Promise((n,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(e?.reason??new Error("aborted"))},s=setTimeout(()=>{e?.removeEventListener("abort",o),n()},t);e?.addEventListener("abort",o,{once:!0})})}function Gm(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function yx(t,e){let n=t.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,e)}async function $s(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??hx,c=n.signal??void 0,l;for(let d=0;d<=o;d++){if(c?.aborted)throw c.reason??new Error("aborted");try{let u=await t(e,n);if(!gx.has(u.status)||d===o)return u;let p=yx(u,i)??Gm(d,s,i);j("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,c)}catch(u){if(c?.aborted||(l=u,d===o))throw u;let p=Gm(d,s,i);j("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,c)}}throw l??new Error("retryFetch: exhausted without a result")}var gx,Bc=y(()=>{"use strict";ue();gx=new Set([429,502,503,504])});import{readFileSync as bx}from"node:fs";import{join as wx}from"path";function vx(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function qm(t,e){return vx(e).test(t)}function _x(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(Sx.has(e))return!0;if(kx.has(e))return!1}return!1}function zm(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function Ex(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function Vm(t){let e=t===void 0||t.trim()===""?"default":t.trim();return _a(e),e}function Ax(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Tx(t){try{return bx(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function xx(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=Vm(e.defaultProfile)),n}function Jm(t){let e=t?.env??E,n=t?.readFileSync??Tx,r=t?.surface??e.AGENT_SURFACE,o=_x(e.AFK_BROWSER_HEADLESS,r),s=zm(e.AFK_BROWSER_ALLOWED_DOMAINS),i=zm(e.AFK_BROWSER_BLOCKED_DOMAINS),a=Ax(e.AFK_BROWSER_DOM_SNAPSHOTS),c=Ex(e.AFK_BROWSER_BACKEND),l=Vm(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():wx(st(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(w){throw new Error(`Failed to parse browser config at ${p}: ${String(w)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let h=xx(d,m);return h.configPath=p,h}function jc(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(qm(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>qm(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Sx,kx,Hc=y(()=>{"use strict";H();W();Sx=new Set(["daemon","subagent","telegram","afk"]),kx=new Set(["repl","interactive","cli"])});import Jt from"node:fs";import Us from"node:path";import{randomBytes as Rx}from"node:crypto";import{chromium as Px}from"playwright";function Ix(){try{return"5.21.1"}catch{}try{let t=Us.resolve(import.meta.dirname,"../../../package.json"),e=Jt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Cx,Bs,Ym=y(()=>{"use strict";W();ue();Cx=Ix(),Bs=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(e){this.config=e}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=Px.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,e)).catch(e=>{throw this.launchPromise=void 0,e}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),c=await i.content(),l=i.url(),d=a!==null?a.status():null;return{html:c,finalUrl:l,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${Cx}`}}loadStorageState(e){let n=Ea(e);try{if(!Jt.existsSync(n))return;let r=JSON.parse(Jt.readFileSync(n,"utf8"));return j("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){j("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Ea(e);if(!Jt.existsSync(r))return;let o=await n.storageState(),s=Us.join(Us.dirname(r),`.${Us.basename(r)}.${process.pid}.${Rx(4).toString("hex")}.tmp`);Jt.writeFileSync(s,JSON.stringify(o),{mode:384}),Jt.chmodSync(s,384),Jt.renameSync(s,r),j("[browser/vault] saved session",{profile:e,file:r})}catch(r){j("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as Mx}from"crypto";function Kc(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of Ox)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function Xm(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&Dx.test(t.label))}function Qm(t){return Mx("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Zm(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var Ox,Dx,hr=y(()=>{"use strict";Ox=[{name:"aws-access-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"github-pat",regex:/ghp_[a-zA-Z0-9]{36}/g},{name:"openai-bearer",regex:/sk-[a-zA-Z0-9_-]{20,}/g},{name:"slack-token",regex:/xox[abp]-[a-zA-Z0-9-]{10,}/g},{name:"jwt",regex:/eyJ[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}/g},{name:"form-password",regex:/password=[^&\s]+/gi}];Dx=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Fx}from"node:crypto";function Lx(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Nx(t,e,n){return`el_${Fx("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function $x(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function eg(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function ng(t,e){let n=t.role??"",r=t.name??"";tg.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])ng(s,e)}async function Ux(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},rg).catch(()=>[])}async function Bx(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let h=s.type;h==="checkbox"?l="checkbox":h==="radio"?l="radio":h==="button"||h==="submit"||h==="reset"?l="button":h==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},rg).catch(()=>[])}function jx(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function js(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=jx(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Ux(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,h]=await Promise.all([i,a,c,l,d]),w,b=!1;u!==null?(w=[],ng(u,w)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,w=(await Bx(t)).filter(B=>tg.has(B.role??"")));let S=new Map;for(let I of p){let B=eg(I.name),D=S.get(B);(!D||D.bbox.w===0&&I.bbox.w>0)&&S.set(B,I)}let A=w.map(I=>({ax:I,dom:S.get(eg(I.name??""))})),v=r?A:A.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);v.sort((I,B)=>{let D=I.dom?.bbox.y??0,x=B.dom?.bbox.y??0;if(D!==x)return D-x;let C=I.dom?.bbox.x??0,L=B.dom?.bbox.x??0;return C-L}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=v.slice(0,n).map((I,B)=>{let D=I.ax.role??"generic",x=I.ax.name??"",C=Nx(D,x,B),L=I.dom?.bbox??{x:0,y:0,w:0,h:0},M=I.dom?.type??null,F=null;I.ax.value!==void 0&&I.ax.value!==null&&(F=String(I.ax.value)),I.ax.checked!==void 0&&(F=String(I.ax.checked)),Xm({role:D,kind:M})&&(F="[redacted]");let O={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(O.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(O.selected=I.ax.selected),I.ax.expanded!==void 0&&(O.expanded=I.ax.expanded);let N;I.dom?.testId?N=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(N=`#${I.dom.id}`);let q={id:C,role:D,label:Lx(x),kind:M,value:F,state:O,bbox:L};return N!==void 0&&(q.selector=N),q}),_="idle";try{let I=await t.evaluate(()=>document.readyState);I==="loading"?_="loading":I==="interactive"?_="navigating":_="idle"}catch{_="navigating"}_!=="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 P=$x(f),T=`obs_${e.observationCounter.toString(36)}`,U=new Date().toISOString();return{observationId:T,url:m,title:h,textSummary:P,interactive:R,status:{httpStatus:e.httpStatus??null,loadingState:_,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:U}}var tg,rg,og=y(()=>{"use strict";hr();tg=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);rg="a[href], button, input, select, textarea, [role], [tabindex], label"});async function sg(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Wc(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>sg(t,s)))).filter(o=>o!==null)}async function Hx(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Gc(t,e,n){switch(e.kind){case"element_id":return Kx(t,e,n);case"selector":return Wx(t,e);case"semantic":return Gx(t,e)}}async function Kx(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Wc(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Wx(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Wc(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function Gx(t,e){return e.role!==void 0?qx(t,e.text,e.role):zx(t,e.text,e)}async function qx(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Wc(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function zx(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await Hx(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=u.slice(0,5),f=[];for(let h=0;h<p.length;h++){let w=p[h];if(w===void 0)continue;let b=await sg(w.locator,w.index);if(b!==null){let S=`${b.role}:${b.label}:${h}`,A=0;for(let v=0;v<S.length;v++)A=A*31+S.charCodeAt(v)>>>0;f.push({...b,id:`el_${A.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var ig=y(()=>{"use strict"});import{randomBytes as Vx}from"crypto";import{mkdir as Jx,stat as Yx,writeFile as Xx}from"fs/promises";import{join as qc}from"path";import{gzip as Qx}from"zlib";import{promisify as Zx}from"util";function eR(t){return qc(vo(t),"browser")}function tR(t){return qc(eR(t),"screenshots")}function nR(){return new Date().toISOString().replace(/[:.]/g,"-")}function rR(){return Vx(3).toString("hex")}async function zc(t,e,n){if(e.length>ag)throw new Error(`writeScreenshotSidecar: buffer exceeds ${ag} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=tR(t);await Jx(r,{recursive:!0});let o=`${nR()}-${rR()}-${n}.png`,s=qc(r,o);await Xx(s,e);let{size:i}=await Yx(s);return{path:s,bytes:i}}var hK,ag,cg=y(()=>{"use strict";W();hr();hK=Zx(Qx);ag=5*1024*1024});var dg={};ba(dg,{PlaywrightProvider:()=>Vc});function lg(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var Vc,ug=y(()=>{"use strict";Ym();og();ig();Hc();hr();cg();Vc=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Bs(e)}async open(e){let n=jc(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(l){a=l}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let c=await js(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,c.interactive,c.url,c.title,"browser_open"),a!==null)throw a;return c}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await js(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await Gc(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${lg(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":{let h=Kc(e.value??"");await c.fill(e.value??"");break}case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(w){l=w}else l=h}let u=r.url();if(u!==s){let h=jc(u,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:h.reason}}let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await js(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Gc(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${lg(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await zc(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await zc(n,o,r);return s}catch{return null}}}});var Xt={};ba(Xt,{__resetBrowserRegistryForTests:()=>cR,browserProviderActive:()=>iR,closeBrowserProvider:()=>Jc,getBrowserProvider:()=>sR,peekBrowserProvider:()=>aR});function pg(){Promise.resolve(Jc()).then(()=>{process.exit(130)})}function fg(){Promise.resolve(Jc()).then(()=>{process.exit(143)})}function mg(){Qe=null}function oR(){Hs||(process.on("SIGINT",pg),process.on("SIGTERM",fg),process.on("exit",mg),Hs=!0)}function gg(){Hs&&(process.removeListener("SIGINT",pg),process.removeListener("SIGTERM",fg),process.removeListener("exit",mg),Hs=!1)}async function sR(t){return Qe!==null?Qe:(Yt!==null||(Yt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(ug(),dg)),n=Jm(t),r=new e(n);return oR(),Qe=r,Yt=null,r})()),Yt)}async function Jc(){if(Qe===null)return;let t=Qe;Qe=null,Yt=null,gg(),await t.shutdown()}function iR(){return Qe!==null}function aR(){return Qe}function cR(){Qe=null,Yt=null,gg()}var Qe,Yt,Hs,Qt=y(()=>{"use strict";Hc();Qe=null,Yt=null,Hs=!1});function hg(t,e){try{return Km(t,e)}catch(n){return j("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function fR(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Qt(),Xt));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function yg(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??fR,o=null,s=t,i=null,a=null;try{let l=await $s(n,t,{headers:pR,redirect:"follow",signal:e.signal});i=l.status,s=l.url||t;let d=l.headers.get("content-type")??"";if(l.ok){if(uR.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await l.text();if(dR.test(d)&&!lR.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};o=hg(u,s)}}catch(l){if(e.signal.aborted||l instanceof Error&&l.message.startsWith("web_scrape markdown mode received binary"))throw l;a=l}if(!(o===null||o.textLength<Hm)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let l=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal}),d=hg(l.html,l.finalUrl);if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:l.finalUrl,usedRender:!0}}catch(l){if(e.signal.aborted)throw l;if(o===null){let d=l instanceof Error?l.message:String(l),u=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${t}: fetch failed (${u}) and render failed (${d}).`);throw p.cause=l,p}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${i??"error"}).`)}var lR,dR,uR,pR,bg=y(()=>{"use strict";Wm();Bc();ue();lR=/(text\/html|application\/xhtml\+xml)/i,dR=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,uR=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,pR={"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 hR(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(mR,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),gR),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=ws(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function wg(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?hR({apiKey:t.exaApiKey,fetchFn:t.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function vg(t,e){if(e.length===0)return`# Search results for "${t}"
1070
1070
 
1071
1071
  (no results)`;let n=[`# Search results for "${t}"`,""];return e.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
1072
1072
  `).trimEnd()}var mR,gR,Sg=y(()=>{"use strict";En();mR="https://api.exa.ai/search",gR=10});function ER(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t,n=e.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof e.query!="string"||e.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=e.query}else{if(typeof e.url!="string"||e.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let c;try{c=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(c.protocol!=="http:"&&c.protocol!=="https:")return{error:`Invalid input: protocol "${c.protocol}" not supported (http/https only)`};o=c.toString()}let i=yR;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(e.timeout_ms,bR)}let a=wR;if(e.max_bytes!==void 0){if(typeof e.max_bytes!="number"||!Number.isFinite(e.max_bytes)||e.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(e.max_bytes,vR)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Yc(t,e){let n=Buffer.from(t,"utf8");return n.byteLength<=e?t:n.subarray(0,e).toString("utf8")+SR}function AR(t){let e=[],n=t;for(let o=0;o<4&&n instanceof Error;o++)e.push(n.message),n=n.cause;let r=e.join(" | ");return _R.some(o=>r.includes(o))}function TR(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env;return async(r,o)=>{if(typeof e!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=ER(r);if("error"in s)return{content:s.error,isError:!0};if(o.aborted){let d=o.reason;return{content:`web_scrape aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let i=new AbortController,a=()=>{i.abort(o.reason)},c,l=()=>{let d=i.signal.reason;return d instanceof Error?d.message:String(d??"aborted")};try{if(o.addEventListener("abort",a,{once:!0}),c=setTimeout(()=>{i.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs),s.mode==="raw"){let u;try{u=await $s(e,s.url,{method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:i.signal})}catch(f){return i.signal.aborted?{content:`web_scrape aborted: ${l()}`,isError:!0}:{content:`web_scrape network error: ${f instanceof Error?f.message:String(f)}`,isError:!0}}if(!u.ok)return{content:`web_scrape HTTP ${u.status} ${u.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let p;try{p=await u.text()}catch(f){return{content:`web_scrape read error: ${f instanceof Error?f.message:String(f)}`,isError:!0}}return{content:Yc(p,s.maxBytes)}}if(s.mode==="markdown")try{let u=await yg(s.url,{fetchFn:e,renderFn:t.renderFn,timeoutMs:s.timeoutMs,signal:i.signal});return u.markdown.trim().length===0?{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0}:{content:Yc(u.markdown,s.maxBytes)}}catch(u){if(i.signal.aborted)return{content:`web_scrape aborted: ${l()}`,isError:!0};let p=u instanceof Error?u.message:String(u),f=AR(u)?" (the render fallback needs the optional Playwright browser \u2014 run `pnpm exec playwright install chromium`)":"";return{content:`web_scrape markdown error: ${p}${f}`,isError:!0}}let d=wg({exaApiKey:n.EXA_API_KEY,fetchFn:e});if("error"in d)return{content:d.error,isError:!0};try{let u=await d.search(s.query,{limit:kR,timeoutMs:s.timeoutMs,signal:i.signal});return{content:Yc(vg(s.query,u),s.maxBytes)}}catch(u){return i.signal.aborted?{content:`web_scrape aborted: ${l()}`,isError:!0}:{content:`web_scrape search error (${d.name}): ${u instanceof Error?u.message:String(u)}`,isError:!0}}}finally{c!==void 0&&clearTimeout(c),o.removeEventListener("abort",a)}}}var yR,bR,wR,vR,SR,kR,_R,kg,_g=y(()=>{"use strict";bg();Sg();Bc();yR=3e4,bR=12e4,wR=1e6,vR=1e7,SR=`
@@ -1238,7 +1238,7 @@ Available agent types (pass via \`agent_type\`):
1238
1238
  `+e+"\nWhen `agent_type` is omitted, a general child agent with the default tool surface is dispatched.",input_schema:{...ke.input_schema,properties:{...ke.input_schema.properties,agent_type:{type:"string",description:"Named agent type to dispatch \u2014 one of the \"Available agent types\" listed in this tool's description. The type supplies the child's system prompt, tool allowlist (mechanically enforced), and default model/turn budget. Explicit `model`/`max_turns` on this call override the type's defaults. Unknown types fail with the available list. Alias: `subagent_type`."}}}}}var qy=y(()=>{"use strict";Be()});var Ql=y(()=>{"use strict";bi();Hy();Vl();Gy();qy()});import{isAbsolute as bC}from"node:path";function wC(t){if(typeof t!="object"||t===null)throw new Error("Agent tool input must be an object");let e=t,n=e.prompt;if(typeof n!="string")throw new Error('Agent tool input must have a "prompt" field of type string');if(n.trim().length===0)throw new Error("Agent tool prompt cannot be empty");let r,o=e.model;if(o!==void 0){if(typeof o!="string")throw new Error("Agent tool model must be a string");r=o}let s=10,i=!1,a=e.max_turns;if(a!==void 0){if(typeof a!="number")throw new Error("Agent tool max_turns must be a number");s=Math.max(1,Math.min(50,Math.floor(a))),i=!0}let c,l=e.agent_type??e.subagent_type;if(l!==void 0){if(typeof l!="string")throw new Error("Agent tool agent_type must be a string");let w=l.trim();w.length>0&&(c=w)}let d="agent-tool",u=e.id_prefix;if(u!==void 0){if(typeof u!="string")throw new Error("Agent tool id_prefix must be a string");d=u}let p="foreground",f=e.mode;if(f!==void 0){if(f!=="foreground"&&f!=="background")throw new Error(`Agent tool mode must be "foreground" or "background", got: ${JSON.stringify(f)}`);p=f}let m,h=e.cwd;if(h!==void 0){if(typeof h!="string")throw new Error(`Agent tool cwd must be a string, got: ${JSON.stringify(h)}`);if(h.length===0)throw new Error("Agent tool cwd must be a non-empty string");if(!bC(h))throw new Error(`Agent tool cwd must be an absolute path, got: ${JSON.stringify(h)}`);if(h.split(/[/\\]/).includes(".."))throw new Error(`Agent tool cwd must not contain '..' segments, got: ${JSON.stringify(h)}`);m=h}return{prompt:n,model:r,max_turns:s,max_turns_explicit:i,id_prefix:d,mode:p,...c!==void 0?{agent_type:c}:{},...m!==void 0?{cwd:m}:{}}}function Si(t){try{return oe(t).catch(()=>{})}catch{return Promise.resolve()}}function Dn(t,e=240){return t.length<=e?t:t.slice(0,e)+"\u2026"}function Vy(t){if(t!=null){if(typeof t=="string")return t.length;try{return JSON.stringify(t).length}catch{return}}}function SC(t){if(t==null)return;let e=Vy(t);return e!==void 0&&e>vC?{truncated:!0,chars:e}:t}function kC(t){let e={status:t.status,error:Dn(t.errorMessage,zy),subagent_id:t.subagentId};t.schemaErrorMessage&&(e.schemaError=Dn(t.schemaErrorMessage,zy));let n=SC(t.partialOutput);return n!==void 0&&(e.partialOutput=n),e}var vC,zy,Fn,Zl=y(()=>{"use strict";le();Ny();Se();gi();fn();Nn();Ql();dt();ue();En();St();Nn();vC=4096,zy=1024;Fn=class t{constructor(e){this.ctx=e;this.currentCwd=e.cwd}ctx;currentCwd;setCwd(e){this.currentCwd=e,this.ctx.subagentManager.setCwd(e)}describeAgentTool(){return Xl(this.ctx.agentRegistry)}promotionTriggers=new Map;activeForegroundHandles=new Map;hasPromotableForeground(){return this.ctx.backgroundRegistry!==void 0&&this.promotionTriggers.size>0}hasActiveForeground(){return this.activeForegroundHandles.size>0}async cancelActiveForeground(){let e=[...this.activeForegroundHandles.values()];return e.length===0?0:(await Promise.all(e.map(n=>n.cancel().catch(()=>{}))),e.length)}async promoteActiveForeground(){let e=[...this.promotionTriggers.values()];return e.forEach(r=>r.fire()),(await Promise.all(e.map(r=>r.ready))).filter(r=>r!==null)}getSubagentsLite(){let e=this.ctx.subagentManager.list().map(r=>({id:r.id,status:r.status})),n=this.ctx.backgroundRegistry?this.ctx.backgroundRegistry.list().map(r=>({jobId:r.jobId,status:r.status,startedAt:new Date(r.startedAt).toISOString(),label:r.label.length>0?r.label:null})):[];return{active:e,backgroundJobs:n}}async execute(e){if(e.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=wC(e.input)}catch(D){return{content:`Agent tool input validation failed: ${D instanceof Error?D.message:String(D)}`,isError:!0}}let r;if(n.agent_type!==void 0&&(r=this.ctx.agentRegistry?.get(n.agent_type),r===void 0)){let D=[...this.ctx.agentRegistry?.keys()??[]].sort().join(", ");return{content:`Agent type "${n.agent_type}" not found. Available agent types: ${D.length>0?D:"(none)"}`,isError:!0}}let o=this.ctx.depth,s=this.ctx.maxDepth??Ln,i,a=this.ctx.surface!==void 0?{origin:vt(this.ctx.surface),actor:He(o)}:{},c;if(r!==void 0){let D=r.definition.model;c=D!==void 0&&D!=="inherit"?D:this.ctx.parentModel}let l=n.model??c??this.ctx.defaultSubagentModel??"sonnet",d=Y(l)==="openai-compatible",u=r!==void 0?Gl(r,ki):void 0,p=this.ctx.allowedTools;if(u?.allowedTools!==void 0){let D=this.ctx.allowedTools;p=D!==void 0?u.allowedTools.filter(x=>D.includes(x)):u.allowedTools}let f=this.ctx.readOnlyBash===!0||u?.bashReadOnly===!0;u!==void 0&&u.droppedTokens.length>0&&process.stderr.write(`[afk] agents: agent_type ${JSON.stringify(r?.name)}: unknown tool token(s) dropped fail-closed: ${u.droppedTokens.join(", ")}
1239
1239
  `);let m=!n.max_turns_explicit&&r?.definition.maxTurns!==void 0?Math.max(1,Math.min(50,Math.floor(r.definition.maxTurns))):n.max_turns,h=Ir({childModel:l,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(l):at(l),parentApiKey:this.ctx.defaultConfig.apiKey}),w={model:l,apiKey:d?void 0:h,systemPrompt:r!==void 0?r.definition.prompt:this.ctx.defaultConfig.systemPrompt,baseUrl:d?void 0:this.ctx.defaultConfig.baseUrl,maxTurns:m,depth:o+1,maxDepth:s,...n.cwd!==void 0?{cwd:n.cwd}:{}},b;if(this.ctx.childProviderFactory&&o<s){i=new z({parentAbortSignal:e.signal,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),b=Fr(e.signal);let D=new t({subagentManager:i,parentSession:b,defaultConfig:this.ctx.defaultConfig,...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:o+1,maxDepth:s,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash?{readOnlyBash:!0}:{},...this.ctx.agentRegistry!==void 0?{agentRegistry:this.ctx.agentRegistry}:{},parentModel:l}),x=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(o+1,s,e.signal,this.currentCwd):void 0;w.provider=this.ctx.childProviderFactory({childExecutor:D,...x!==void 0?{childSkillExecutor:x}:{},...w.model!==void 0?{model:w.model}:{},...p!==void 0?{allowedTools:p}:{},...f?{readOnlyBash:!0}:{}})}else(p!==void 0||f)&&(w.provider=_i(p??[...ki],w.model,f,this.ctx.defaultConfig.openaiBaseUrl));let S;try{S=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:e.id,config:w,idPrefix:n.id_prefix,agentType:r!==void 0?r.name:n.id_prefix&&n.id_prefix!=="agent-tool"?lt(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":lt(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:!0}),b!==void 0&&(b.sessionId=S.id)}catch(D){let x=D instanceof Error?D.message:String(D);return Si({...a,event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:Dn(x),depth:o}),{content:`Failed to fork subagent: ${x}`,isError:!0}}if(n.mode==="background"){let D=this.ctx.backgroundRegistry;if(!D)return await S.teardown().catch(L=>j("subagent-executor: handle teardown failed: "+(L instanceof Error?L.message:String(L)))),{content:'Background mode is not available in this session \u2014 no BackgroundAgentRegistry is wired. Re-issue the call with mode="foreground" or run inside `afk interactive`.',isError:!0};let x;try{x=D.register({handle:S,prompt:n.prompt,model:w.model??"sonnet",parentSessionId:this.ctx.parentSession.sessionId})}catch(L){if(L instanceof mi)return await S.teardown().catch(M=>j("subagent-executor: handle teardown failed after cap error: "+(M instanceof Error?M.message:String(M)))),{content:L.message,isError:!0};throw L}let C={status:"running",jobId:x.jobId,subagentId:x.subagentId,label:x.label,message:`Background subagent started (jobId=${x.jobId}). It is running detached; its result will be delivered into this context automatically with the next user message once it finishes. /bgsub:join ${x.jobId} remains available for manual replay.`};return{content:JSON.stringify(C)}}let A=()=>{S.cancel()};e.signal.addEventListener("abort",A,{once:!0});let v=Date.now(),k=this.ctx.parentSession.sessionId,R=!1,_,P=new Promise(D=>{_=D}),T,U=new Promise(D=>{T=D});this.promotionTriggers.set(S.id,{fire:_,ready:U}),this.activeForegroundHandles.set(S.id,S);let I,B=S.runToResult(n.prompt);try{let D=await Promise.race([B.then(F=>({kind:"result",result:F})),P.then(()=>({kind:"promote"}))]);if(D.kind==="promote"){let F=this.ctx.backgroundRegistry;if(F)try{let O=F.adoptRunning({handle:S,runPromise:B,prompt:n.prompt,model:w.model??"sonnet",parentSessionId:k});return R=!0,e.signal.removeEventListener("abort",A),T({jobId:O.jobId,label:O.label}),{content:JSON.stringify({status:"running",jobId:O.jobId,subagentId:O.subagentId,label:O.label,message:`Subagent backgrounded by user (jobId=${O.jobId}). It keeps running detached; its result will be delivered into this context automatically with the next user message once it finishes. /bgsub:join ${O.jobId} remains available for manual replay.`})}}catch(O){j("subagent-executor: promotion failed, staying foreground: "+(O instanceof Error?O.message:String(O))),T(null)}else T(null)}let x=D.kind==="result"?D.result:await B;if(x.status==="succeeded"&&x.message){let F=x.message.content,O=typeof F=="string"?F:JSON.stringify(F),N=x.trace;return Si({...a,event:"subagent.completed",subagent_id:S.id,parent_session_id:k,status:x.status,duration_ms:Date.now()-v,content_chars:O.length,depth:o,tool_call_count:N?.toolCalls.length,thinking_present:N?.thinkingPresent,tool_names:N?.toolCalls.length?JSON.stringify([...new Set(N.toolCalls.map(q=>q.name))]):void 0}),I={content:O},I}let C=x.error?.message??"Subagent failed with no output",L=x.trace;Si({...a,event:"subagent.failed",subagent_id:S.id,id_prefix:n.id_prefix,parent_session_id:k,status:x.status,duration_ms:Date.now()-v,error_message:Dn(C),schema_error:x.schemaError?Dn(x.schemaError.message):void 0,partial_output_chars:Vy(x.partialOutput),depth:o,tool_call_count:L?.toolCalls.length,thinking_present:L?.thinkingPresent,tool_names:L?.toolCalls.length?JSON.stringify([...new Set(L.toolCalls.map(F=>F.name))]):void 0});let M=kC({status:x.status,errorMessage:C,schemaErrorMessage:x.schemaError?.message,partialOutput:x.partialOutput,subagentId:S.id});return I={content:JSON.stringify(M),isError:!0},I}catch(D){let x=D instanceof Error?D.message:String(D);throw Si({...a,event:"subagent.failed",subagent_id:S.id,id_prefix:n.id_prefix,parent_session_id:k,status:"failed",duration_ms:Date.now()-v,error_message:Dn(x),depth:o}),D}finally{if(this.promotionTriggers.delete(S.id),this.activeForegroundHandles.delete(S.id),T(null),!R){e.signal.removeEventListener("abort",A),await i?.teardownAll(),await S.teardown({deferInjectContextToCaller:!0});let D=S.getLastStopInjectContext?.();I!==void 0&&D!==void 0&&D.length>0&&(I.content=`${I.content}
1240
1240
 
1241
- ${D}`)}}}}});function Jy(t,e){return`Skill tool not available at nesting depth ${t} (max ${e}). ${_C}`}var _C,Yy=y(()=>{"use strict";_C="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});function Xy(t){return EC.has(t)}var EC,Qy=y(()=>{"use strict";EC=new Set});function Zy(t){for(let e of AC)e(t)}function eb(t){for(let e of TC)e(t)}var AC,TC,tb=y(()=>{"use strict";AC=new Set,TC=new Set});function nb(t){return xC.has(t)}function PC(t,e=RC){return t.length<=e?t:t.slice(0,e)+"\u2026"}function IC(t){if(typeof t!="object"||t===null)return;let e=t.name;if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}function CC(t){if(typeof t!="object"||t===null)throw new Error("Skill tool input must be an object");let e=t,n=e.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=e.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var xC,RC,$n,td=y(()=>{"use strict";Re();le();tn();Nn();Zl();Yy();gi();fn();qt();xe();dt();Qy();tb();ue();St();xC=new Set(["ask-gate","fanout-pace","right-size-delegation","premise-gate","intent-lock","long-bash-gate","exploration-gate","irreversible-action-gate","safe-destruct","plan-probe"]);RC=240;$n=class{constructor(e){this.ctx=e;this.currentCwd=e.cwd}ctx;pluginBodies=null;currentCwd;setCwd(e){this.currentCwd=e}sessionIdentity(){return this.ctx.surface!==void 0?{origin:vt(this.ctx.surface),actor:He(this.ctx.depth)}:{}}async execute(e){if(e.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??Ln;if(n>=r){let c=IC(e.input);return oe({...this.sessionIdentity(),event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:c}).catch(()=>{}),{content:Jy(n,r),isError:!0}}let o;try{o=CC(e.input)}catch(c){return{content:`Skill tool input validation failed: ${c instanceof Error?c.message:String(c)}`,isError:!0}}try{let c=$e(o.name);return await this.executeRegistrySkill(c,o.arguments,e)}catch{}let s=this.getPluginSkillBody(o.name);if(s){if(s.context==="fork"){let l=s.readOnly===!0||ed.has(o.name);return await this.executePluginSkill(o.name,s.body,s.pluginPath,o.arguments,e,l,s.allowedTools)}let c=s.body.replace(/\$\{PLUGIN_ROOT(?::-(?:[^{}]|\$\{[^{}]*\})*)?\}|\$PLUGIN_ROOT\b/g,()=>s.pluginPath);return this.executeLoadedPluginSkill(o.name,c,o.arguments,e)}let a=Lr(this.ctx.pluginConfigs,this.currentCwd!==void 0?{cwd:this.currentCwd}:void 0).map(c=>c.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${a||"(none)"}`,isError:!0}}async executeRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(e.context==="fork")return this.executeForkedRegistrySkill(e,n,r);if(e.context==="load")return this.executeLoadedRegistrySkill(e,n,r);let o=Xy(e.name);o&&eb(e.name);let s=this.ctx.depth??0;oe({...this.sessionIdentity(),event:"skill.dispatched",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...nb(e.name)?{is_gate:!0}:{},...e.model!==void 0?{model:e.model}:{}}).catch(()=>{});let i=Date.now(),a,c;try{c=await e.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel,callId:r.id,dispatchSkill:this.createDispatchSkillCallback(r),...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}})}catch(d){a=d}finally{let d=Date.now()-i;o&&Zy({skillName:e.name,durationMs:d,...a!==void 0?{isError:!0}:{}});let u=a!==void 0?a instanceof Error?a.message:String(a):void 0,p=a===void 0?typeof c=="string"?c.length:c!=null?JSON.stringify(c).length:0:void 0;oe({...this.sessionIdentity(),event:"skill.completed",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,status:a!==void 0?"failed":"succeeded",duration_ms:d,depth:s,...p!==void 0?{content_chars:p}:{},...u!==void 0?{error_message:PC(u)}:{},...e.model!==void 0?{model:e.model}:{}}).catch(()=>{})}return a!==void 0?{content:`Skill execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}:{content:typeof c=="string"?c:c!=null?JSON.stringify(c):"Skill completed successfully."}}buildForkedChildConfig(e,n,r=!1,o){let s=this.ctx.depth??0,i=this.ctx.maxDepth??Ln,a={...e},c=r&&o!==void 0?o.filter(f=>Ei.includes(f)):r?[...Ei]:o,l=r;if(!this.ctx.childProviderFactory||s>=i)return r?a.provider=rb(a.model,this.ctx.openaiBaseUrl):c!==void 0&&(a.provider=_i(c,a.model,l,this.ctx.openaiBaseUrl)),{childConfig:a,childManager:void 0};let d=new z({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),u=new Fn({subagentManager:d,parentSession:Fr(n),defaultConfig:{model:a.model,apiKey:this.ctx.apiKey,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.openaiBaseUrl!==void 0?{openaiBaseUrl:this.ctx.openaiBaseUrl}:{}},...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:s+1,maxDepth:i,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{},...this.ctx.backgroundRegistry!==void 0?{backgroundRegistry:this.ctx.backgroundRegistry}:{},...c!==void 0?{allowedTools:c}:{},...l?{readOnlyBash:!0}:{},...this.ctx.agentRegistry!==void 0?{agentRegistry:this.ctx.agentRegistry}:{},...a.model!==void 0?{parentModel:a.model}:{}}),p=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(s+1,i,n,this.currentCwd):void 0;return a.provider=this.ctx.childProviderFactory({childExecutor:u,...p!==void 0?{childSkillExecutor:p}:{},...a.model!==void 0?{model:a.model}:{},...c!==void 0?{allowedTools:c}:{},...l?{readOnlyBash:!0}:{}}),{childConfig:a,childManager:d}}async executeForkedRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o=e.readOnly===!0||ed.has(e.name),s;try{if(s=ee(e.name)["system.md"],!s)return{content:`Skill "${e.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(u){return{content:`Failed to load skill prompts: ${u instanceof Error?u.message:String(u)}`,isError:!0}}let i=e.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",a=Ir({childModel:i,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(i):at(i),parentApiKey:this.ctx.apiKey}),c=new z({parentAbortSignal:r.signal,apiKey:a,parentModel:i,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:Pe(),...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),{childConfig:l,childManager:d}=this.buildForkedChildConfig({model:i,systemPrompt:s,isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},r.signal,o);return this.runForkedSkillToResult({manager:c,childManager:d,childConfig:l,label:e.name,idPrefix:`skill-fork-${e.name}`,parentId:r.id,args:n,noOutputError:"Forked skill failed with no output",errorPrefix:"Forked skill execution error"})}formatLoadedSkillResult(e,n,r){let o=r&&r.trim().length>0?r.trim():"(none)";return{content:`${`[Skill "${e}" loaded into your current context \u2014 act on it now]
1241
+ ${D}`)}}}}});function Jy(t,e){return`Skill tool not available at nesting depth ${t} (max ${e}). ${_C}`}var _C,Yy=y(()=>{"use strict";_C="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});function Xy(t){return EC.has(t)}var EC,Qy=y(()=>{"use strict";EC=new Set});function Zy(t){for(let e of AC)e(t)}function eb(t){for(let e of TC)e(t)}var AC,TC,tb=y(()=>{"use strict";AC=new Set,TC=new Set});function nb(t){return xC.has(t)}function PC(t,e=RC){return t.length<=e?t:t.slice(0,e)+"\u2026"}function IC(t){if(typeof t!="object"||t===null)return;let e=t.name;if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}function CC(t){if(typeof t!="object"||t===null)throw new Error("Skill tool input must be an object");let e=t,n=e.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=e.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var xC,RC,$n,td=y(()=>{"use strict";Re();le();tn();Nn();Zl();Yy();gi();fn();qt();xe();dt();Qy();tb();ue();St();xC=new Set(["ask-gate","fanout-pace","right-size-delegation","premise-gate","intent-lock","long-bash-gate","exploration-gate","irreversible-action-gate","safe-destruct","plan-probe"]);RC=240;$n=class{constructor(e){this.ctx=e;this.currentCwd=e.cwd}ctx;pluginBodies=null;currentCwd;setCwd(e){this.currentCwd=e,this.pluginBodies=null}sessionIdentity(){return this.ctx.surface!==void 0?{origin:vt(this.ctx.surface),actor:He(this.ctx.depth)}:{}}async execute(e){if(e.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??Ln;if(n>=r){let c=IC(e.input);return oe({...this.sessionIdentity(),event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:c}).catch(()=>{}),{content:Jy(n,r),isError:!0}}let o;try{o=CC(e.input)}catch(c){return{content:`Skill tool input validation failed: ${c instanceof Error?c.message:String(c)}`,isError:!0}}try{let c=$e(o.name);return await this.executeRegistrySkill(c,o.arguments,e)}catch{}let s=this.getPluginSkillBody(o.name);if(s){if(s.context==="fork"){let l=s.readOnly===!0||ed.has(o.name);return await this.executePluginSkill(o.name,s.body,s.pluginPath,o.arguments,e,l,s.allowedTools)}let c=s.body.replace(/\$\{PLUGIN_ROOT(?::-(?:[^{}]|\$\{[^{}]*\})*)?\}|\$PLUGIN_ROOT\b/g,()=>s.pluginPath);return this.executeLoadedPluginSkill(o.name,c,o.arguments,e)}let a=Lr(this.ctx.pluginConfigs,this.currentCwd!==void 0?{cwd:this.currentCwd}:void 0).map(c=>c.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${a||"(none)"}`,isError:!0}}async executeRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(e.context==="fork")return this.executeForkedRegistrySkill(e,n,r);if(e.context==="load")return this.executeLoadedRegistrySkill(e,n,r);let o=Xy(e.name);o&&eb(e.name);let s=this.ctx.depth??0;oe({...this.sessionIdentity(),event:"skill.dispatched",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...nb(e.name)?{is_gate:!0}:{},...e.model!==void 0?{model:e.model}:{}}).catch(()=>{});let i=Date.now(),a,c;try{c=await e.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel,callId:r.id,dispatchSkill:this.createDispatchSkillCallback(r),...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}})}catch(d){a=d}finally{let d=Date.now()-i;o&&Zy({skillName:e.name,durationMs:d,...a!==void 0?{isError:!0}:{}});let u=a!==void 0?a instanceof Error?a.message:String(a):void 0,p=a===void 0?typeof c=="string"?c.length:c!=null?JSON.stringify(c).length:0:void 0;oe({...this.sessionIdentity(),event:"skill.completed",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,status:a!==void 0?"failed":"succeeded",duration_ms:d,depth:s,...p!==void 0?{content_chars:p}:{},...u!==void 0?{error_message:PC(u)}:{},...e.model!==void 0?{model:e.model}:{}}).catch(()=>{})}return a!==void 0?{content:`Skill execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}:{content:typeof c=="string"?c:c!=null?JSON.stringify(c):"Skill completed successfully."}}buildForkedChildConfig(e,n,r=!1,o){let s=this.ctx.depth??0,i=this.ctx.maxDepth??Ln,a={...e},c=r&&o!==void 0?o.filter(f=>Ei.includes(f)):r?[...Ei]:o,l=r;if(!this.ctx.childProviderFactory||s>=i)return r?a.provider=rb(a.model,this.ctx.openaiBaseUrl):c!==void 0&&(a.provider=_i(c,a.model,l,this.ctx.openaiBaseUrl)),{childConfig:a,childManager:void 0};let d=new z({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),u=new Fn({subagentManager:d,parentSession:Fr(n),defaultConfig:{model:a.model,apiKey:this.ctx.apiKey,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.openaiBaseUrl!==void 0?{openaiBaseUrl:this.ctx.openaiBaseUrl}:{}},...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:s+1,maxDepth:i,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{},...this.ctx.backgroundRegistry!==void 0?{backgroundRegistry:this.ctx.backgroundRegistry}:{},...c!==void 0?{allowedTools:c}:{},...l?{readOnlyBash:!0}:{},...this.ctx.agentRegistry!==void 0?{agentRegistry:this.ctx.agentRegistry}:{},...a.model!==void 0?{parentModel:a.model}:{}}),p=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(s+1,i,n,this.currentCwd):void 0;return a.provider=this.ctx.childProviderFactory({childExecutor:u,...p!==void 0?{childSkillExecutor:p}:{},...a.model!==void 0?{model:a.model}:{},...c!==void 0?{allowedTools:c}:{},...l?{readOnlyBash:!0}:{}}),{childConfig:a,childManager:d}}async executeForkedRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o=e.readOnly===!0||ed.has(e.name),s;try{if(s=ee(e.name)["system.md"],!s)return{content:`Skill "${e.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(u){return{content:`Failed to load skill prompts: ${u instanceof Error?u.message:String(u)}`,isError:!0}}let i=e.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",a=Ir({childModel:i,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(i):at(i),parentApiKey:this.ctx.apiKey}),c=new z({parentAbortSignal:r.signal,apiKey:a,parentModel:i,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:Pe(),...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),{childConfig:l,childManager:d}=this.buildForkedChildConfig({model:i,systemPrompt:s,isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},r.signal,o);return this.runForkedSkillToResult({manager:c,childManager:d,childConfig:l,label:e.name,idPrefix:`skill-fork-${e.name}`,parentId:r.id,args:n,noOutputError:"Forked skill failed with no output",errorPrefix:"Forked skill execution error"})}formatLoadedSkillResult(e,n,r){let o=r&&r.trim().length>0?r.trim():"(none)";return{content:`${`[Skill "${e}" loaded into your current context \u2014 act on it now]
1242
1242
  The instructions below are your operating procedure for THIS task. Execute them immediately, in this session, using the tools you already have. This is an instruction set, not reference material: follow it directly \u2014 do not merely summarize or describe it. No sub-agent was forked; you are the one carrying it out.
1243
1243
  Arguments: ${o}`}
1244
1244
 
@@ -1248,7 +1248,7 @@ ${n}`}}emitLoadTelemetry(e,n,r,o){let s=this.ctx.depth??0,i={...this.sessionIden
1248
1248
 
1249
1249
  ${m.partialOutput}`},p):(p={content:m.error?.message??l,isError:!0},p)}catch(f){let m=f instanceof Error?f.message:String(f);return{content:`${d}: ${m}`,isError:!0}}finally{u&&await u.teardown({deferInjectContextToCaller:!0}).catch(j);let f=u?.getLastStopInjectContext?.();p!==void 0&&f!==void 0&&f.length>0&&(p.content=`${p.content}
1250
1250
 
1251
- ${f}`),await r?.teardownAll(),await n.teardownAll()}}getPluginSkillBody(e){return this.pluginBodies||(this.pluginBodies=Nr(this.ctx.pluginConfigs)),this.pluginBodies.get(e)}createDispatchSkillCallback(e){return async(n,r)=>{let o={id:`${e.id}-dispatch-${n}`,name:"skill",input:{name:n,...r!==void 0?{arguments:r}:{}},signal:e.signal},s=await this.execute(o);if(s.isError)throw new Error(s.content);return s.content}}}});function Fr(t){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:t}}function ob(t={}){return({childExecutor:e,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:s})=>{let i={permissions:{allowedTools:o??ki},subagentExecutor:e,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{}};return Y(typeof r=="string"?r:void 0)==="openai-compatible"?new ye({...i,...t.openaiBaseUrl!==void 0?{baseURL:t.openaiBaseUrl}:{},readOnlyMemory:!0}):new be({...i,readOnlyMemory:!0})}}function rb(t,e){let n={allowedTools:[...Ei]};return Y(typeof t=="string"?t:void 0)==="openai-compatible"?new ye({permissions:n,readOnlyBash:!0,readOnlyMemory:!0,...e!==void 0?{baseURL:e}:{}}):new be({permissions:n,readOnlyBash:!0,readOnlyMemory:!0})}function sb(t,e,n,r,o,s,i,a,c,l,d,u){let p=(f,m,h,w)=>{let b=w??i;return new $n({parentSession:Fr(h),defaultModel:t,...l!==void 0?{defaultSubagentModel:l}:{},apiKey:e,...r!==void 0?{baseUrl:r}:{},...u!==void 0?{openaiBaseUrl:u}:{},depth:f,maxDepth:m,childProviderFactory:n,childSkillExecutorFactory:p,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{},...b!==void 0?{cwd:b}:{},...a!==void 0?{resolveApiKeyForModel:a}:{},...c!==void 0?{surface:c}:{},...d!==void 0?{agentRegistry:d}:{}})};return p}function _i(t,e,n=!1,r){let o={allowedTools:[...t]};return Y(typeof e=="string"?e:void 0)==="openai-compatible"?new ye({permissions:o,...n?{readOnlyBash:!0}:{},...r!==void 0?{baseURL:r}:{}}):new be({permissions:o,...n?{readOnlyBash:!0}:{}})}function ib(t,e){let n={allowedTools:[...Py]};return Y(typeof e=="string"?e:void 0)==="openai-compatible"?new ye({permissions:n}):new be({permissions:n})}var Ln,ki,Ei,ed,Nn=y(()=>{"use strict";Ai();Pr();Se();Be();pt();pi();td();Ln=3;ki=[...Ue,...ge,"memory_search","agent","skill"],Ei=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...ge,"memory_search","agent","skill"],ed=new Set(["ground-state"])});var Ti,ab=y(()=>{"use strict";ue();ps();qt();Ss();ne();_e();Ti=class{constructor(e,n,r,o,s,i,a,c,l,d,u,p,f,m,h){this.id=e;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=c;this.parentInputStreamRef=l;this.parentAbortSignal=d;this.agentType=u;this.traceWriter=m;this.onSubagentSucceeded=h;this.progressSink=p,this.parentId=f}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;lastStopInjectContext;progressSink;parentId;currentTrace=fi();lastStreamedContent="";get status(){return this.currentStatus}async run(e,n){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let r=Date.now(),o=us(this.streamToFinalMessage(e,n),this.timeoutMs,{controller:this.controller,label:this.id});this.inFlight=o;try{let s=await o;this.lastMessage=s.content,this.lastDurationMs=Date.now()-r,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",Bt(this.traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:this.lastDurationMs,turnCount:this.currentTrace.turnCount,outputBytes:Buffer.byteLength(this.lastMessage,"utf8")});let i=typeof s.metadata?.totalCostUsd=="number"?s.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this.currentTrace.usage,i),this.onTerminal(),s}catch(s){throw this.lastDurationMs=Date.now()-r,this.currentStatus!=="cancelled"&&(this.controller.signal.aborted?(Bt(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(Bt(this.traceWriter,{transition:"failed",subagentId:this.id,errorClass:s instanceof Error?s.constructor.name:"Unknown",errorMessage:s instanceof Error?s.message:String(s),partialOutputBytes:Buffer.byteLength(this.lastStreamedContent,"utf8")}),this.currentStatus="failed",this.latestTerminalStatus="failed")),this.onTerminal(),s}finally{this.inFlight=null}}async streamToFinalMessage(e,n){let r,o,s;this.lastStreamedContent="",this.currentTrace=fi();let i=n??this.progressSink??Pe(),a={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}};for await(let c of this.session.sendMessageStream(e)){if(i&&i(c,a),c.type==="chunk"){let l=c.chunk;l.type==="content"?this.lastStreamedContent+=l.content:l.type==="tool_use_detail"?this.currentTrace.toolCalls.push({id:l.toolUseId,name:l.toolName,inputBytes:Buffer.byteLength(l.toolInput,"utf8")}):l.type==="tool_result"?this.currentTrace.toolResults.push({toolUseId:l.toolUseId,isError:l.isError,truncated:l.truncated,sizeBytes:l.sizeBytes}):l.type==="thinking"&&(this.currentTrace.thinkingPresent=!0)}if(c.type==="message")r=c.message,this.currentTrace.turnCount++;else if(c.type==="error"){o=c.error;break}else if(c.type==="done"){if(typeof c.metadata?.stopReason=="string"&&(s=c.metadata.stopReason),typeof c.metadata?.usage=="object"&&c.metadata.usage!==null){let l=c.metadata.usage;this.currentTrace.usage={inputTokens:typeof l.input_tokens=="number"?l.input_tokens:void 0,outputTokens:typeof l.output_tokens=="number"?l.output_tokens:void 0,cacheReadTokens:typeof l.cache_read_input_tokens=="number"?l.cache_read_input_tokens:void 0,cacheCreationTokens:typeof l.cache_creation_input_tokens=="number"?l.cache_creation_input_tokens:void 0}}break}}if(o)throw o;if(r)return r;if(this.lastStreamedContent.length>0)return{role:"assistant",content:this.lastStreamedContent,timestamp:new Date};if(s==="tool_use_loop_capped")return{role:"assistant",content:`[subagent ${this.id} reached its tool-use iteration cap before producing a final message; returning a capped partial result]`,timestamp:new Date};throw new Error(`Subagent ${this.id} produced no terminal message`)}async runToResult(e,n){try{let r=await this.run(e,n);return Dy(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=Kl(this.id,this.currentStatus,r,this.currentTrace);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(e,n,r){let o;if(r){let s=this.progressSink??Pe();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{j("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",Bt(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"});try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async teardown(e){if(this.stopDispatched)return;let n=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(n,e)}}getLastStopInjectContext(){return this.lastStopInjectContext}async dispatchStopAndRelease(e,n){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let r=await om(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:e,lastMessage:this.lastMessage,agentType:this.agentType,durationMs:this.lastDurationMs,trace:this.currentTrace},this.traceWriter?{traceWriter:this.traceWriter}:{});if(r.injectContext){if(this.parentAbortSignal?.aborted)j(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else if(n?.deferInjectContextToCaller)this.lastStopInjectContext=r.injectContext;else if(this.parentInputStreamRef)try{let o=this.parentInputStreamRef;o.queueFrameworkContext?o.queueFrameworkContext(r.injectContext):o.pushUserMessage(r.injectContext)}catch(o){j(`Failed to inject context from SubagentStop handler: ${String(o)}`)}}this.onTerminal()}}});var MC,OC,z,le=y(()=>{"use strict";_f();bc();ps();Ss();ne();dt();qt();um();fm();Nn();gi();Se();ab();MC=async(t,e)=>({action:"decline"}),OC=50,z=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentProvider;parentCwd;worktreeMainRootCache=new Map;parentTraceWriter;parentSurface;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(e={}){if(this.parentCanUseTool=e.canUseTool,this.hookRegistry=e.hookRegistry,this.progressSink=e.progressSink,this.parentApiKey=e.apiKey,this.parentBaseUrl=e.baseUrl,this.parentProvider=e.parentModel!==void 0?Y(e.parentModel):void 0,this.parentCwd=e.cwd,this.parentTraceWriter=e.traceWriter,this.parentSurface=e.surface,this.onSubagentSucceededCb=e.onSubagentSucceeded,this.abortGraph=new as(e.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),e.parentAbortSignal){let n=e.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(e=>({id:e.id,status:e.status}))}get(e){return this.active.get(e)}onChildAborted(e){return this.abortGraph.onChildAborted(this.rootId,e)}setOnSubagentSucceeded(e){this.onSubagentSucceededCb=e}setCwd(e){this.parentCwd=e}async resolveMainRootForCwd(e){if(this.worktreeMainRootCache.has(e))return this.worktreeMainRootCache.get(e);let n=await pm(e);return this.worktreeMainRootCache.set(e,n),n}abortAll(e,n="user_signal"){this.abortGraph.abort(this.rootId,e,n)}async forkSubagent(e){if(e.phaseRole!==void 0&&e.phaseRole!=="read-write"&&e.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${e.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=`${e.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=e.parent.sessionId,o=e.config.hookRegistry??this.hookRegistry??e.parent.hookRegistry;o&&await rm(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal,...e.config.traceWriter?{traceWriter:e.config.traceWriter}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i=e.config.cwd??this.parentCwd,a;if(e.config.readRoots===void 0&&i!==void 0){let b=await this.resolveMainRootForCwd(i);b!==void 0&&b!==i&&(a=[i,b])}let c={...e.config,resume:r,forkSession:r?!0:e.config.forkSession,abortSignal:s.signal,apiKey:Uy({childModel:e.config.model,configApiKey:e.config.apiKey,parentApiKey:this.parentApiKey,parentProvider:this.parentProvider}),baseUrl:e.config.baseUrl??(Y(e.config.model)==="openai-compatible"?void 0:this.parentBaseUrl),isNonInteractive:e.config.isNonInteractive??!0,maxToolUseIterations:e.config.maxToolUseIterations??OC,...e.config.parentSessionId===void 0&&e.parent.sessionId!==void 0?{parentSessionId:e.parent.sessionId}:{},...e.config.phaseRole===void 0&&e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},...e.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},...a!==void 0?{readRoots:a}:{},...e.config.traceWriter===void 0&&this.parentTraceWriter!==void 0?{traceWriter:this.parentTraceWriter}:{},...e.config.surface===void 0&&this.parentSurface!==void 0?{surface:this.parentSurface}:{},hookRegistry:o,permissionBubbler:e.config.permissionBubbler??(this.parentCanUseTool!==void 0&&e.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...e.denyElicitations===!1?{}:{onElicitation:MC},...e.phaseRole==="read-only"?{provider:ib("read-only",e.config.model)}:{}};c.cwd!==void 0&&dm(c.cwd);let l;try{l=new Kt(c)}catch(b){throw this.abortGraph.dispose(n),b}let d=e.parent.getInputStreamRef?.(),u=e.parent.abortSignal,p=this.progressSink??Pe(),f=e.agentType?.trim()||void 0,m=e.parentId?.trim()||void 0,h=new Ti(n,l,s,this.abortGraph,e.outputSchema,e.config.timeoutMs??ds,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},d,u,f??e.idPrefix,p,m??e.parent.sessionId,e.config.traceWriter,this.onSubagentSucceededCb);this.active.set(n,h);let w=typeof e.config.model=="string"?e.config.model:JSON.stringify(e.config.model);return Bt(e.config.traceWriter,{transition:"started",subagentId:n,parentId:e.parent.sessionId??this.rootId,model:w,...c.tools?.allowedTools?{allowedTools:[...c.tools.allowedTools]}:{}}),await oe({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,model:w,parent_session_id:e.parent.sessionId}),h}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}}});async function xi(t,e={}){let{failFast:n=!0,teardown:r=!0,maxConcurrency:o=8}=e;if(t.length===0)return[];let s=new Array(t.length),i=new Set(t.map((c,l)=>l)),a=!1;return await An(t.map((c,l)=>l),o,async c=>{let l=t[c];n&&a&&await l.handle.cancel().catch(()=>{});let d=await l.handle.runToResult(l.prompt);if(s[c]=d,i.delete(c),n&&d.status!=="succeeded"){a=!0;for(let u of i){let p=t[u];p&&p.handle.status==="running"&&p.handle.cancel().catch(()=>{})}}}),r&&await Promise.allSettled(t.map(c=>c.handle.teardown())),s}var rd=y(()=>{"use strict";xs()});function $r(t){let e=new Set;for(let n of t){let r=Cr(n,DC);r!==void 0&&e.add(r)}return e}var DC,od=y(()=>{"use strict";Mr();Be();Cs();DC=new Set([...Ue,...ge,"memory_search","agent","skill"])});import{existsSync as FC,mkdirSync as yz,readFileSync as LC,renameSync as bz,writeFileSync as wz,unlinkSync as vz}from"fs";function cb(t=ho()){if(!FC(t))return Ri();try{let e=LC(t,"utf8"),n=JSON.parse(e);if(!n||typeof n!="object")return Ri();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 s=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:s}}return Ri()}catch{return Ri()}}function Ri(){return{version:2,plugins:{},marketplaces:{}}}var lb=y(()=>{"use strict";W()});import{existsSync as id,readFileSync as pb,readdirSync as NC,realpathSync as $C,statSync as UC}from"fs";import{join as Un,resolve as db}from"path";function nn(t=bt(),e={}){let n=e.trustAll===!0,r=n?`${t}\0trustAll`:t;Ur||(Ur=new Map);let o=Ur.get(r);if(o)return[...o];if(!id(t))return Ur.set(r,[]),[];let s=t===bt()?ho():Un(t,".index.json"),i=cb(s),a=[];return fb(t,t,0,a,new Set,i.plugins,n),Ur.set(r,a),[...a]}function fb(t,e,n,r,o,s,i){if(n>BC)return;let a;try{a=$C(e)}catch{a=e}if(o.has(a))return;if(o.add(a),id(Un(e,".claude-plugin","plugin.json"))){let l=ad(t,e);if(l===null){sd(r,e);return}if(l.layout==="cache"){if(!i){let u=s[l.key];if(!u||u.enabled===!1)return}sd(r,e);return}let d=s[l.key];if(d&&d.enabled===!1)return;sd(r,e);return}let c;try{c=NC(e)}catch{return}for(let l of c){if(l.startsWith("."))continue;let d=Un(e,l),u;try{u=UC(d)}catch{continue}u.isDirectory()&&fb(t,d,n+1,r,o,s,i)}}function jC(t){try{let e=pb(Un(t,".claude-plugin","plugin.json"),"utf8"),n=JSON.parse(e);if(n!==null&&typeof n=="object"&&"main"in n){let r=n.main;if(typeof r=="string"&&r.trim()!=="")return r}}catch{}}function sd(t,e){let n=jC(e);t.push(n!==void 0?{type:"local",path:e,main:n}:{type:"local",path:e})}function ad(t,e){if(!e.startsWith(t))return null;let n=e.slice(t.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(s=>s.length>0);if(r.length===0)return null;if(r[0]===ub&&r.length>=3){let s=r[1];if(s){let i=Un(t,ub,s),c=HC(i,e)??r[2];if(c)return{layout:"cache",key:`${s}:${c}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function HC(t,e){let n=Un(t,".claude-plugin","marketplace.json");if(!id(n))return null;let r;try{r=JSON.parse(pb(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=db(e);for(let i of o){if(!i||typeof i!="object")continue;let a=i;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&db(t,a.source)===s)return a.name}return null}var BC,ub,Ur,cd=y(()=>{"use strict";W();lb();BC=5,ub="cache"});import{existsSync as Ot,readdirSync as KC,readFileSync as WC}from"fs";import{join as ht}from"path";function gb(t=de()){let e=[],n=ht(t,"skills");if(Ot(n))for(let r of Pi(n)){let o=ht(n,r,"SKILL.md");Ot(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of mb){let o=ht(t,`${r}s`);if(Ot(o))for(let s of Pi(o))s.endsWith(".md")&&e.push({path:ht(o,s),type:r,source:"user"})}return e}function hb(t=bt()){if(!Ot(t))return[];let e=[],n=nn(t);for(let r of n){let s=ad(t,r.path)?.key,i=ht(r.path,"skills");if(Ot(i))for(let a of Pi(i)){let c=ht(i,a,"SKILL.md");if(!Ot(c))continue;let l={path:c,type:"skill",source:"plugin"};s&&(l.plugin_key=s),e.push(l)}for(let a of mb){let c=ht(r.path,`${a}s`);if(Ot(c))for(let l of Pi(c)){if(!l.endsWith(".md"))continue;let d={path:ht(c,l),type:a,source:"plugin"};s&&(d.plugin_key=s),e.push(d)}}}return e}function yb(t=ht(de(),"settings.json")){if(!Ot(t))return[];try{let e=WC(t,"utf8"),r=JSON.parse(e).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a=0;a<i.length;a++)o.push({event:s,index:a,raw:i[a]});return o}catch{return[]}}function Pi(t){try{return KC(t).filter(e=>!e.startsWith("."))}catch{return[]}}var mb,bb=y(()=>{"use strict";W();cd();mb=["command","agent"]});import{z as te}from"zod";import{mkdir as wb,appendFile as vb}from"fs/promises";import{join as ld}from"path";function zC(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function VC(t){let e=()=>{let s={};for(let i of _b)s[i]={correct:0,misfit:0,outlier:0};return s},n={user:e(),plugin:e()};for(let s of t)n[s.source][s.type][s.verdict]+=1;let r={high:0,med:1,low:2},o=t.filter(s=>s.verdict==="misfit").slice().sort((s,i)=>r[s.confidence]-r[i.confidence]);return{inventory:n,misfits:o}}function JC(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function YC(t){let e=t.filter(o=>o.source==="user"),n=t.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),e.length===0)r.push("(none discovered)");else for(let o of e)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 s=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${s})`)}return r.join(`
1251
+ ${f}`),await r?.teardownAll(),await n.teardownAll()}}getPluginSkillBody(e){return this.pluginBodies||(this.pluginBodies=Nr(this.ctx.pluginConfigs,this.currentCwd!==void 0?{cwd:this.currentCwd}:void 0)),this.pluginBodies.get(e)}createDispatchSkillCallback(e){return async(n,r)=>{let o={id:`${e.id}-dispatch-${n}`,name:"skill",input:{name:n,...r!==void 0?{arguments:r}:{}},signal:e.signal},s=await this.execute(o);if(s.isError)throw new Error(s.content);return s.content}}}});function Fr(t){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:t}}function ob(t={}){return({childExecutor:e,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:s})=>{let i={permissions:{allowedTools:o??ki},subagentExecutor:e,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{}};return Y(typeof r=="string"?r:void 0)==="openai-compatible"?new ye({...i,...t.openaiBaseUrl!==void 0?{baseURL:t.openaiBaseUrl}:{},readOnlyMemory:!0}):new be({...i,readOnlyMemory:!0})}}function rb(t,e){let n={allowedTools:[...Ei]};return Y(typeof t=="string"?t:void 0)==="openai-compatible"?new ye({permissions:n,readOnlyBash:!0,readOnlyMemory:!0,...e!==void 0?{baseURL:e}:{}}):new be({permissions:n,readOnlyBash:!0,readOnlyMemory:!0})}function sb(t,e,n,r,o,s,i,a,c,l,d,u){let p=(f,m,h,w)=>{let b=w??i;return new $n({parentSession:Fr(h),defaultModel:t,...l!==void 0?{defaultSubagentModel:l}:{},apiKey:e,...r!==void 0?{baseUrl:r}:{},...u!==void 0?{openaiBaseUrl:u}:{},depth:f,maxDepth:m,childProviderFactory:n,childSkillExecutorFactory:p,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{},...b!==void 0?{cwd:b}:{},...a!==void 0?{resolveApiKeyForModel:a}:{},...c!==void 0?{surface:c}:{},...d!==void 0?{agentRegistry:d}:{}})};return p}function _i(t,e,n=!1,r){let o={allowedTools:[...t]};return Y(typeof e=="string"?e:void 0)==="openai-compatible"?new ye({permissions:o,...n?{readOnlyBash:!0}:{},...r!==void 0?{baseURL:r}:{}}):new be({permissions:o,...n?{readOnlyBash:!0}:{}})}function ib(t,e){let n={allowedTools:[...Py]};return Y(typeof e=="string"?e:void 0)==="openai-compatible"?new ye({permissions:n}):new be({permissions:n})}var Ln,ki,Ei,ed,Nn=y(()=>{"use strict";Ai();Pr();Se();Be();pt();pi();td();Ln=3;ki=[...Ue,...ge,"memory_search","agent","skill"],Ei=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...ge,"memory_search","agent","skill"],ed=new Set(["ground-state"])});var Ti,ab=y(()=>{"use strict";ue();ps();qt();Ss();ne();_e();Ti=class{constructor(e,n,r,o,s,i,a,c,l,d,u,p,f,m,h){this.id=e;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=c;this.parentInputStreamRef=l;this.parentAbortSignal=d;this.agentType=u;this.traceWriter=m;this.onSubagentSucceeded=h;this.progressSink=p,this.parentId=f}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;lastStopInjectContext;progressSink;parentId;currentTrace=fi();lastStreamedContent="";get status(){return this.currentStatus}async run(e,n){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let r=Date.now(),o=us(this.streamToFinalMessage(e,n),this.timeoutMs,{controller:this.controller,label:this.id});this.inFlight=o;try{let s=await o;this.lastMessage=s.content,this.lastDurationMs=Date.now()-r,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",Bt(this.traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:this.lastDurationMs,turnCount:this.currentTrace.turnCount,outputBytes:Buffer.byteLength(this.lastMessage,"utf8")});let i=typeof s.metadata?.totalCostUsd=="number"?s.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this.currentTrace.usage,i),this.onTerminal(),s}catch(s){throw this.lastDurationMs=Date.now()-r,this.currentStatus!=="cancelled"&&(this.controller.signal.aborted?(Bt(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(Bt(this.traceWriter,{transition:"failed",subagentId:this.id,errorClass:s instanceof Error?s.constructor.name:"Unknown",errorMessage:s instanceof Error?s.message:String(s),partialOutputBytes:Buffer.byteLength(this.lastStreamedContent,"utf8")}),this.currentStatus="failed",this.latestTerminalStatus="failed")),this.onTerminal(),s}finally{this.inFlight=null}}async streamToFinalMessage(e,n){let r,o,s;this.lastStreamedContent="",this.currentTrace=fi();let i=n??this.progressSink??Pe(),a={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}};for await(let c of this.session.sendMessageStream(e)){if(i&&i(c,a),c.type==="chunk"){let l=c.chunk;l.type==="content"?this.lastStreamedContent+=l.content:l.type==="tool_use_detail"?this.currentTrace.toolCalls.push({id:l.toolUseId,name:l.toolName,inputBytes:Buffer.byteLength(l.toolInput,"utf8")}):l.type==="tool_result"?this.currentTrace.toolResults.push({toolUseId:l.toolUseId,isError:l.isError,truncated:l.truncated,sizeBytes:l.sizeBytes}):l.type==="thinking"&&(this.currentTrace.thinkingPresent=!0)}if(c.type==="message")r=c.message,this.currentTrace.turnCount++;else if(c.type==="error"){o=c.error;break}else if(c.type==="done"){if(typeof c.metadata?.stopReason=="string"&&(s=c.metadata.stopReason),typeof c.metadata?.usage=="object"&&c.metadata.usage!==null){let l=c.metadata.usage;this.currentTrace.usage={inputTokens:typeof l.input_tokens=="number"?l.input_tokens:void 0,outputTokens:typeof l.output_tokens=="number"?l.output_tokens:void 0,cacheReadTokens:typeof l.cache_read_input_tokens=="number"?l.cache_read_input_tokens:void 0,cacheCreationTokens:typeof l.cache_creation_input_tokens=="number"?l.cache_creation_input_tokens:void 0}}break}}if(o)throw o;if(r)return r;if(this.lastStreamedContent.length>0)return{role:"assistant",content:this.lastStreamedContent,timestamp:new Date};if(s==="tool_use_loop_capped")return{role:"assistant",content:`[subagent ${this.id} reached its tool-use iteration cap before producing a final message; returning a capped partial result]`,timestamp:new Date};throw new Error(`Subagent ${this.id} produced no terminal message`)}async runToResult(e,n){try{let r=await this.run(e,n);return Dy(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=Kl(this.id,this.currentStatus,r,this.currentTrace);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(e,n,r){let o;if(r){let s=this.progressSink??Pe();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{j("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",Bt(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"});try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async teardown(e){if(this.stopDispatched)return;let n=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(n,e)}}getLastStopInjectContext(){return this.lastStopInjectContext}async dispatchStopAndRelease(e,n){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let r=await om(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:e,lastMessage:this.lastMessage,agentType:this.agentType,durationMs:this.lastDurationMs,trace:this.currentTrace},this.traceWriter?{traceWriter:this.traceWriter}:{});if(r.injectContext){if(this.parentAbortSignal?.aborted)j(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else if(n?.deferInjectContextToCaller)this.lastStopInjectContext=r.injectContext;else if(this.parentInputStreamRef)try{let o=this.parentInputStreamRef;o.queueFrameworkContext?o.queueFrameworkContext(r.injectContext):o.pushUserMessage(r.injectContext)}catch(o){j(`Failed to inject context from SubagentStop handler: ${String(o)}`)}}this.onTerminal()}}});var MC,OC,z,le=y(()=>{"use strict";_f();bc();ps();Ss();ne();dt();qt();um();fm();Nn();gi();Se();ab();MC=async(t,e)=>({action:"decline"}),OC=50,z=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentProvider;parentCwd;worktreeMainRootCache=new Map;parentTraceWriter;parentSurface;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(e={}){if(this.parentCanUseTool=e.canUseTool,this.hookRegistry=e.hookRegistry,this.progressSink=e.progressSink,this.parentApiKey=e.apiKey,this.parentBaseUrl=e.baseUrl,this.parentProvider=e.parentModel!==void 0?Y(e.parentModel):void 0,this.parentCwd=e.cwd,this.parentTraceWriter=e.traceWriter,this.parentSurface=e.surface,this.onSubagentSucceededCb=e.onSubagentSucceeded,this.abortGraph=new as(e.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),e.parentAbortSignal){let n=e.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(e=>({id:e.id,status:e.status}))}get(e){return this.active.get(e)}onChildAborted(e){return this.abortGraph.onChildAborted(this.rootId,e)}setOnSubagentSucceeded(e){this.onSubagentSucceededCb=e}setCwd(e){this.parentCwd=e}async resolveMainRootForCwd(e){if(this.worktreeMainRootCache.has(e))return this.worktreeMainRootCache.get(e);let n=await pm(e);return this.worktreeMainRootCache.set(e,n),n}abortAll(e,n="user_signal"){this.abortGraph.abort(this.rootId,e,n)}async forkSubagent(e){if(e.phaseRole!==void 0&&e.phaseRole!=="read-write"&&e.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${e.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=`${e.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=e.parent.sessionId,o=e.config.hookRegistry??this.hookRegistry??e.parent.hookRegistry;o&&await rm(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal,...e.config.traceWriter?{traceWriter:e.config.traceWriter}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i=e.config.cwd??this.parentCwd,a;if(e.config.readRoots===void 0&&i!==void 0){let b=await this.resolveMainRootForCwd(i);b!==void 0&&b!==i&&(a=[i,b])}let c={...e.config,resume:r,forkSession:r?!0:e.config.forkSession,abortSignal:s.signal,apiKey:Uy({childModel:e.config.model,configApiKey:e.config.apiKey,parentApiKey:this.parentApiKey,parentProvider:this.parentProvider}),baseUrl:e.config.baseUrl??(Y(e.config.model)==="openai-compatible"?void 0:this.parentBaseUrl),isNonInteractive:e.config.isNonInteractive??!0,maxToolUseIterations:e.config.maxToolUseIterations??OC,...e.config.parentSessionId===void 0&&e.parent.sessionId!==void 0?{parentSessionId:e.parent.sessionId}:{},...e.config.phaseRole===void 0&&e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},...e.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},...a!==void 0?{readRoots:a}:{},...e.config.traceWriter===void 0&&this.parentTraceWriter!==void 0?{traceWriter:this.parentTraceWriter}:{},...e.config.surface===void 0&&this.parentSurface!==void 0?{surface:this.parentSurface}:{},hookRegistry:o,permissionBubbler:e.config.permissionBubbler??(this.parentCanUseTool!==void 0&&e.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...e.denyElicitations===!1?{}:{onElicitation:MC},...e.phaseRole==="read-only"?{provider:ib("read-only",e.config.model)}:{}};c.cwd!==void 0&&dm(c.cwd);let l;try{l=new Kt(c)}catch(b){throw this.abortGraph.dispose(n),b}let d=e.parent.getInputStreamRef?.(),u=e.parent.abortSignal,p=this.progressSink??Pe(),f=e.agentType?.trim()||void 0,m=e.parentId?.trim()||void 0,h=new Ti(n,l,s,this.abortGraph,e.outputSchema,e.config.timeoutMs??ds,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},d,u,f??e.idPrefix,p,m??e.parent.sessionId,e.config.traceWriter,this.onSubagentSucceededCb);this.active.set(n,h);let w=typeof e.config.model=="string"?e.config.model:JSON.stringify(e.config.model);return Bt(e.config.traceWriter,{transition:"started",subagentId:n,parentId:e.parent.sessionId??this.rootId,model:w,...c.tools?.allowedTools?{allowedTools:[...c.tools.allowedTools]}:{}}),await oe({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,model:w,parent_session_id:e.parent.sessionId}),h}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}}});async function xi(t,e={}){let{failFast:n=!0,teardown:r=!0,maxConcurrency:o=8}=e;if(t.length===0)return[];let s=new Array(t.length),i=new Set(t.map((c,l)=>l)),a=!1;return await An(t.map((c,l)=>l),o,async c=>{let l=t[c];n&&a&&await l.handle.cancel().catch(()=>{});let d=await l.handle.runToResult(l.prompt);if(s[c]=d,i.delete(c),n&&d.status!=="succeeded"){a=!0;for(let u of i){let p=t[u];p&&p.handle.status==="running"&&p.handle.cancel().catch(()=>{})}}}),r&&await Promise.allSettled(t.map(c=>c.handle.teardown())),s}var rd=y(()=>{"use strict";xs()});function $r(t){let e=new Set;for(let n of t){let r=Cr(n,DC);r!==void 0&&e.add(r)}return e}var DC,od=y(()=>{"use strict";Mr();Be();Cs();DC=new Set([...Ue,...ge,"memory_search","agent","skill"])});import{existsSync as FC,mkdirSync as yz,readFileSync as LC,renameSync as bz,writeFileSync as wz,unlinkSync as vz}from"fs";function cb(t=ho()){if(!FC(t))return Ri();try{let e=LC(t,"utf8"),n=JSON.parse(e);if(!n||typeof n!="object")return Ri();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 s=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:s}}return Ri()}catch{return Ri()}}function Ri(){return{version:2,plugins:{},marketplaces:{}}}var lb=y(()=>{"use strict";W()});import{existsSync as id,readFileSync as pb,readdirSync as NC,realpathSync as $C,statSync as UC}from"fs";import{join as Un,resolve as db}from"path";function nn(t=bt(),e={}){let n=e.trustAll===!0,r=n?`${t}\0trustAll`:t;Ur||(Ur=new Map);let o=Ur.get(r);if(o)return[...o];if(!id(t))return Ur.set(r,[]),[];let s=t===bt()?ho():Un(t,".index.json"),i=cb(s),a=[];return fb(t,t,0,a,new Set,i.plugins,n),Ur.set(r,a),[...a]}function fb(t,e,n,r,o,s,i){if(n>BC)return;let a;try{a=$C(e)}catch{a=e}if(o.has(a))return;if(o.add(a),id(Un(e,".claude-plugin","plugin.json"))){let l=ad(t,e);if(l===null){sd(r,e);return}if(l.layout==="cache"){if(!i){let u=s[l.key];if(!u||u.enabled===!1)return}sd(r,e);return}let d=s[l.key];if(d&&d.enabled===!1)return;sd(r,e);return}let c;try{c=NC(e)}catch{return}for(let l of c){if(l.startsWith("."))continue;let d=Un(e,l),u;try{u=UC(d)}catch{continue}u.isDirectory()&&fb(t,d,n+1,r,o,s,i)}}function jC(t){try{let e=pb(Un(t,".claude-plugin","plugin.json"),"utf8"),n=JSON.parse(e);if(n!==null&&typeof n=="object"&&"main"in n){let r=n.main;if(typeof r=="string"&&r.trim()!=="")return r}}catch{}}function sd(t,e){let n=jC(e);t.push(n!==void 0?{type:"local",path:e,main:n}:{type:"local",path:e})}function ad(t,e){if(!e.startsWith(t))return null;let n=e.slice(t.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(s=>s.length>0);if(r.length===0)return null;if(r[0]===ub&&r.length>=3){let s=r[1];if(s){let i=Un(t,ub,s),c=HC(i,e)??r[2];if(c)return{layout:"cache",key:`${s}:${c}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function HC(t,e){let n=Un(t,".claude-plugin","marketplace.json");if(!id(n))return null;let r;try{r=JSON.parse(pb(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=db(e);for(let i of o){if(!i||typeof i!="object")continue;let a=i;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&db(t,a.source)===s)return a.name}return null}var BC,ub,Ur,cd=y(()=>{"use strict";W();lb();BC=5,ub="cache"});import{existsSync as Ot,readdirSync as KC,readFileSync as WC}from"fs";import{join as ht}from"path";function gb(t=de()){let e=[],n=ht(t,"skills");if(Ot(n))for(let r of Pi(n)){let o=ht(n,r,"SKILL.md");Ot(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of mb){let o=ht(t,`${r}s`);if(Ot(o))for(let s of Pi(o))s.endsWith(".md")&&e.push({path:ht(o,s),type:r,source:"user"})}return e}function hb(t=bt()){if(!Ot(t))return[];let e=[],n=nn(t);for(let r of n){let s=ad(t,r.path)?.key,i=ht(r.path,"skills");if(Ot(i))for(let a of Pi(i)){let c=ht(i,a,"SKILL.md");if(!Ot(c))continue;let l={path:c,type:"skill",source:"plugin"};s&&(l.plugin_key=s),e.push(l)}for(let a of mb){let c=ht(r.path,`${a}s`);if(Ot(c))for(let l of Pi(c)){if(!l.endsWith(".md"))continue;let d={path:ht(c,l),type:a,source:"plugin"};s&&(d.plugin_key=s),e.push(d)}}}return e}function yb(t=ht(de(),"settings.json")){if(!Ot(t))return[];try{let e=WC(t,"utf8"),r=JSON.parse(e).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a=0;a<i.length;a++)o.push({event:s,index:a,raw:i[a]});return o}catch{return[]}}function Pi(t){try{return KC(t).filter(e=>!e.startsWith("."))}catch{return[]}}var mb,bb=y(()=>{"use strict";W();cd();mb=["command","agent"]});import{z as te}from"zod";import{mkdir as wb,appendFile as vb}from"fs/promises";import{join as ld}from"path";function zC(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function VC(t){let e=()=>{let s={};for(let i of _b)s[i]={correct:0,misfit:0,outlier:0};return s},n={user:e(),plugin:e()};for(let s of t)n[s.source][s.type][s.verdict]+=1;let r={high:0,med:1,low:2},o=t.filter(s=>s.verdict==="misfit").slice().sort((s,i)=>r[s.confidence]-r[i.confidence]);return{inventory:n,misfits:o}}function JC(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function YC(t){let e=t.filter(o=>o.source==="user"),n=t.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),e.length===0)r.push("(none discovered)");else for(let o of e)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 s=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${s})`)}return r.join(`
1252
1252
  `)}function XC(t,e){let n=["","## Discovered hooks (audit only these)",""];if(n.push(`Settings file (use this absolute path verbatim in each verdict's \`path\` field): \`${t}\``),n.push(""),e.length===0)return n.push("(no hooks discovered)"),n.join(`
1253
1253
  `);for(let r of e){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(`
1254
1254
  `)}function QC(t,e){if(!e)return{kind:"failure",message:`${t}: no result`};if(e.schemaError)return{kind:"failure",message:`${t}: schema mismatch \u2014 ${e.schemaError.message}`};if(e.status!=="succeeded"){let n=e.error?` \u2014 ${e.error.message}`:"";return{kind:"failure",message:`${t}: ${e.status}${n}`}}return e.output?{kind:"success",output:e.output}:{kind:"failure",message:`${t}: no output`}}async function ZC(t,e,n){let r=n?.apiKey,o=n?.defaultSubagentModel??n?.defaultModel??"sonnet",s=n?.callId,i=typeof t=="object"&&t!==null?t:{},a=GC.parse(i),c=a.writeBriefs??!0,l=a.scope??"all",d=zC(l);if(!e?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let u=e.sessionId,p=ee("audit-fit"),f={skill:p["01-skill-inspector.md"],command:p["02-command-inspector.md"],agent:p["03-agent-inspector.md"],hook:p["04-hook-inspector.md"]};for(let x of _b)if(!f[x])throw new Error(`audit-fit skill missing inspector prompt for ${x}`);let m=d.runUserDiscovery?gb():[],h=d.runPluginDiscovery?hb():[],w={skill:[],command:[],agent:[]};for(let x of[...m,...h])w[x.type].push(x);let b=new z({apiKey:r,...n?.defaultModel!==void 0?{parentModel:n.defaultModel}:{},...n?.traceWriter!==void 0?{traceWriter:n.traceWriter}:{}}),S=$r(Ce.allowedTools),A=()=>async x=>S.has(x)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${x} not allowed for audit-fit inspectors. Allowed tools: ${[...S].join(", ")}`},v=[];for(let x of qC){let C=w[x];if(C.length===0)continue;let L=f[x];L&&v.push({type:x,prompt:`${L}
@@ -1552,7 +1552,7 @@ ${e.body}`)}var NM,ww=y(()=>{"use strict";NM=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9
1552
1552
  `),0}let r=0;for(let o of n){if(!o.isDirectory()||o.name.startsWith("_")||o.name.startsWith("."))continue;let s;try{s=BM(vw(t,o.name,"SKILL.md"),"utf-8")}catch(l){let d=l;d.code!=="ENOENT"&&process.stderr.write(`[afk] skipping skill ${o.name}: ${d.message}
1553
1553
  `);continue}let i=HM(s,o.name);if(!i)continue;i.dir=vw(t,o.name);let c={name:WM(i.name,e),description:i.description,handler:KM(i),origin:e};i.argumentHint&&(c.argumentHint=i.argumentHint),i.flags&&i.flags.length>0&&(c.flags=i.flags),i.context!=="fork"&&(c.context="load",c.loadBody=i.body.replace(/\$\{?SKILL_ROOT\}?/g,()=>i.dir)),pe(c),r++}return r}var Sw,Td=y(()=>{"use strict";W();Re();ww();le();Sw=1024});var kw=y(()=>{"use strict";Eb();$b();Ub();mw();gw();hw();Td()});import{isAbsolute as GM,resolve as qM}from"path";import{pathToFileURL as zM}from"url";async function Ew(t,e={}){let n=e.importer??(r=>import(r));for(let r of t){if(r.main===void 0)continue;let o=GM(r.main)?r.main:qM(r.path,r.main);if(!_w.has(o)){_w.add(o);try{let i=(await n(zM(o).href))?.default;typeof i=="function"&&await i(e.pluginApi)}catch(s){e.onError?.(r,s)}}}}var _w,Aw=y(()=>{"use strict";_w=new Set});import{z as $}from"zod";var Hr,VM,JM,xd,Tw,xw,Rw,Pw,Kr,$i=y(()=>{"use strict";Hr=1,VM=$.object({toolName:$.string(),toolUseId:$.string().optional(),input:$.string().optional(),inputRaw:$.string().optional(),result:$.string().optional(),isError:$.boolean().optional()}).passthrough(),JM=$.object({user:$.string().default(""),assistant:$.string().default(""),timestamp:$.number().optional(),toolEvents:$.array(VM).optional()}).passthrough(),xd=$.object({sessionId:$.string().optional(),name:$.string().optional(),source:$.enum(["cli","telegram"]).optional(),telegramChatId:$.number().optional(),model:$.string(),startedAt:$.number(),savedAt:$.number(),totalTurns:$.number(),totalCostUsd:$.number().optional(),totalTokens:$.number().optional(),totalDurationMs:$.number().optional(),turns:$.array(JM).default([]),forkedFrom:$.string().optional(),forkedAt:$.number().optional()}).passthrough(),Tw=$.enum(["fully_achieved","partially_achieved","not_achieved","aborted"]),xw=$.enum(["not_persisted","persisted","unknown"]),Rw=$.object({tool:$.string(),label:$.string().optional()}),Pw=$.object({files_written:$.number().int(),files_edited:$.number().int(),bash_commands:$.number().int(),commits:$.number().int(),mutated:$.boolean()}),Kr=$.object({facet_version:$.number().int(),session_id:$.string(),source:$.enum(["cli","telegram","unknown"]),model:$.string(),derived_at:$.string(),derived_from:$.literal("afk-session"),source_session_path:$.string(),source_session_mtime_ms:$.number(),subagent_persistence:xw,start_time:$.string(),end_time:$.string(),duration_minutes:$.number(),underlying_goal:$.string(),first_prompt:$.string(),goal_categories:$.record($.string(),$.number()),session_type:$.string(),brief_summary:$.string(),total_turns:$.number().int(),user_message_count:$.number().int(),assistant_message_count:$.number().int(),tool_counts:$.record($.string(),$.number()),commands:$.array($.string()),skills:$.array($.string()),subagents:$.array(Rw),tool_errors:$.number().int(),tool_error_categories:$.record($.string(),$.number()),friction_counts:$.record($.string(),$.number()),friction_detail:$.string(),outcome:Tw,primary_success:$.string(),world_changes:Pw,decisions:$.array($.string()),evidence_pointers:$.array($.string())}).passthrough()});import{basename as YM}from"path";function nO(t){if(t)try{let e=JSON.parse(t);return e&&typeof e=="object"?e:void 0}catch{return}}function Ui(t){return typeof t=="string"?t:void 0}function Bi(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function rO(t){return t.replace(/[-_]+/g," ").trim()}function oO(t,e){return Cw.test(t)?"slash_command":e==="telegram"?"chat":"task"}function sO(t){let e=new Map,n=[];for(let r of t)r.toolUseId===void 0?n.push(r):e.set(r.toolUseId,r);return[...e.values(),...n]}function Wr(t,e={}){let n=t.turns??[],r=sO(n.flatMap(L=>L.toolEvents??[])),o={},s={},i=[],a=[],c=[],l=0,d=0,u=0,p=0,f=0;for(let L of r){let M=L.toolName;o[M]=(o[M]??0)+1,L.isError===!0&&(l+=1,s[M]=(s[M]??0)+1);let F=nO(L.inputRaw??L.input);if(M==="write_file"&&(d+=1),M==="edit_file"&&(u+=1),M==="bash"){p+=1;let O=Ui(F?.command)??L.input;O&&tO.test(O)&&(f+=1)}if(QM.has(M)){let O=Ui(F?.file_path);O&&!c.includes(O)&&c.length<eO&&c.push(O)}if(XM.has(M)){let O;M==="skill"?(O=Ui(F?.name),O&&!a.includes(O)&&a.push(O)):M==="agent"?O=Ui(F?.id_prefix):O="compose",i.push(O?{tool:M,label:O}:{tool:M})}}let m=n[0]?.user??"",h=t.source??"cli",w=oO(m,h),b=[];for(let L of n){let F=Cw.exec(L.user??"")?.[1];F&&!b.includes(F)&&b.push(F)}let S=n.filter(L=>(L.user??"").trim().length>0).length,A=n.filter(L=>(L.assistant??"").trim().length>0).length,v=[...n].reverse().find(L=>(L.assistant??"").trim().length>0)?.assistant??"",k;n.length===0?k="aborted":v.trim().length===0?k="partially_achieved":k="fully_achieved";let _=k==="fully_achieved"||k==="partially_achieved"?Bi(v||m||w,160)||w:"none",P=l>0?`${l} tool error(s): ${Object.entries(s).map(([L,M])=>`${L}\xD7${M}`).join(", ")}`:"",T=t.name?rO(t.name):Bi(m,80),U=Bi(v||m,ZM),I=Bi(T?`${T} \u2014 ${U}`:U,400)||"empty session",B=t.sessionId??(e.sourceSessionPath?YM(e.sourceSessionPath,".json"):"unknown"),D=t.totalDurationMs&&t.totalDurationMs>0?t.totalDurationMs:Math.max(0,t.savedAt-t.startedAt),x=e.sourceSessionPath?[...c,e.sourceSessionPath]:c,C={facet_version:Hr,session_id:B,source:h==="telegram"?"telegram":"cli",model:t.model,derived_at:(e.derivedAt??new Date).toISOString(),derived_from:"afk-session",source_session_path:e.sourceSessionPath??"",source_session_mtime_ms:e.sourceSessionMtimeMs??t.savedAt,subagent_persistence:"not_persisted",start_time:new Date(t.startedAt).toISOString(),end_time:new Date(t.savedAt).toISOString(),duration_minutes:Number((D/6e4).toFixed(2)),underlying_goal:m.slice(0,Iw),first_prompt:m.slice(0,Iw),goal_categories:{[w]:1},session_type:w,brief_summary:I,total_turns:n.length,user_message_count:S,assistant_message_count:A,tool_counts:o,commands:b,skills:a,subagents:i,tool_errors:l,tool_error_categories:s,friction_counts:{...s},friction_detail:P,outcome:k,primary_success:_,world_changes:{files_written:d,files_edited:u,bash_commands:p,commits:f,mutated:d>0||u>0||f>0},decisions:[],evidence_pointers:x};return Kr.parse(C)}var XM,QM,Iw,ZM,eO,tO,Cw,Rd=y(()=>{"use strict";$i();XM=new Set(["agent","compose","skill"]),QM=new Set(["read_file","write_file","edit_file"]),Iw=1e3,ZM=240,eO=50,tO=/\bgit\s+commit(?![\w-])/,Cw=/^\s*\/([a-zA-Z][\w-]*)/});import{existsSync as ji,mkdirSync as iO,readFileSync as Mw,readdirSync as aO,renameSync as cO,statSync as lO,writeFileSync as dO}from"fs";import{basename as uO,dirname as pO,join as Ow}from"path";function Dw(t,e){return wo(t),Ow(e,`${t}.json`)}function fO(t,e){return wo(t),Ow(e,`${t}.json`)}function Hi(t,e=me()){let n=Dw(t,e);if(ji(n))try{let r=JSON.parse(Mw(n,"utf8")),o=xd.safeParse(r);return o.success?o.data:void 0}catch{return}}function mO(t){if(ji(t))try{let e=JSON.parse(Mw(t,"utf8")),n=Kr.safeParse(e);return n.success?n.data:void 0}catch{return}}function gO(t,e){iO(pO(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;dO(n,`${JSON.stringify(e,null,2)}
1554
1554
  `,"utf8"),cO(n,t)}function hO(t,e){return t.facet_version===Hr&&t.source_session_mtime_ms===e}function Pd(t,e={}){let n=e.sessionsDir??me(),r=e.cacheDir??xu(),o=Dw(t,n);if(!ji(o))return;let s=lO(o).mtimeMs,i=fO(t,r);if(!e.force){let l=mO(i);if(l&&hO(l,s))return l}let a=Hi(t,n);if(!a)return;let c=Wr(a,{sourceSessionPath:o,sourceSessionMtimeMs:s});return gO(i,c),c}function Id(t={}){let e=t.sessionsDir??me();return ji(e)?aO(e).filter(n=>n.endsWith(".json")).map(n=>uO(n,".json")):[]}var Fw=y(()=>{"use strict";W();Rd();$i()});var Lw=y(()=>{"use strict";$i();Rd();Fw()});function di(t,e){let n=Lr(t,e);if(n.length===0)return"";let r=[];for(let o of n){let s=o.argumentHint?`${o.argumentHint}`:"",i=s?`- \`${o.name} ${s}\`: ${o.description}`:`- ${o.name}: ${o.description}`;r.push(i),o.whenToUse&&r.push(` When to use: ${o.whenToUse}`)}return["Available skills (invoke via the `skill` tool):","","Each skill either dispatches one or more context-isolated subagents (delegation \u2014 preserves the main session's context) or loads its instructions directly into your current context (`load` mode). Calling `skill` is the entry point for both; the executor picks the mode per skill. Prefer a skill over inline investigation when the task shape matches.","",...r].join(`
1555
- `)}function Lr(t,e){let n=[],r=new Set,o=E.AFK_INTERNAL==="1",s=ar(ir());jr(go(),"user"),kf("project"),jr(Pu(e?.cwd),"project");for(let{dir:a,origin:c}of s.skillRoots)jr(a,c);for(let a of dc()){let c=$e(a);lc(c,o)&&(n.push({name:a,description:c.description,source:c.origin==="user"?"user":c.origin==="project"?"project":c.origin?.startsWith("imported:")?"imported":"builtin",argumentHint:c.argumentHint,whenToUse:c.whenToUse}),r.add(a))}let i=t??Cd();for(let a of i){if(a.type!=="local")continue;let c=Wl(a.path);for(let l of c)!l.name||r.has(l.name)||lc({audience:l.audience},o)&&(n.push({name:l.name,description:l.description??`Skill from plugin at ${a.path}`,source:"plugin"}),r.add(l.name))}return n}function Nr(t){let e=new Map,n=t??Cd();for(let r of n){if(r.type!=="local")continue;let o=Wl(r.path);for(let s of o)s.name&&s.body&&s.body.length>0&&!e.has(s.name)&&e.set(s.name,{body:s.body,pluginPath:r.path,...s.allowedTools!==void 0?{allowedTools:s.allowedTools}:{},...s.context!==void 0?{context:s.context}:{},...s.readOnly===!0?{readOnly:!0}:{}})}return e}function Cd(){return[...nn(Iu()),...nn(),...nn(Mu()),...ar(ir()).pluginRoots.flatMap(t=>nn(t,{trustAll:!0}))]}async function Nw(){await Ew(Cd(),{pluginApi:{registerSkill:pe,listSkills:dc,getSkill:$e,loadSkillPrompts:ee,env:E,SubagentManager:z,describeFailure:se,discoverPluginSkillBodies:Nr,getAgentFrameworkDir:ot,getSkillsDir:go,getSessionsDir:me,getOrDeriveFacet:Pd,listSessionIds:Id,deriveSessionFacet:Wr,loadStoredSession:Hi}})}var tn=y(()=>{"use strict";kw();Re();xe();Td();cd();Aw();Mr();le();_e();Lw();W();H();ts()});function li(){try{let t=Lr();return Promise.resolve(t.map(e=>{let n={name:e.name,description:e.description};return e.argumentHint&&(n.argumentHint=e.argumentHint),n}))}catch{return Promise.resolve([])}}var Bl=y(()=>{"use strict";tn()});function $w(t){if(t.length===0)return;let e=t[t.length-1];if(!e||e.role!=="assistant"||typeof e.content=="string")return;let n=e.content,r=[];for(let s of n)s.type==="tool_use"&&typeof s.id=="string"&&r.push(s.id);if(r.length===0)return;let o={role:"user",content:r.map(s=>({type:"tool_result",tool_use_id:s,content:"Tool call interrupted before completing \u2014 no result recorded.",is_error:!0}))};t.push(o)}var Uw=y(()=>{"use strict"});function Bw(t){return{messages:t.initialMessages?[...t.initialMessages]:[],currentModel:t.model,requestedModel:t.requestedModel??t.model,currentPermissionMode:t.permissionMode,userSystem:t.userSystem,toolDispatcher:t.toolDispatcher,lastUsage:null,closed:!1,autoCompactThreshold:t.autoCompactThreshold}}var jw=y(()=>{"use strict"});var yO,Ki,Hw=y(()=>{"use strict";yO="__closed__",Ki=class{current=null;pendingReason=null;closedPromise;closeResolve=null;constructor(){this.closedPromise=new Promise(e=>{this.closeResolve=()=>e(yO)})}begin(){let e=new AbortController;return this.current=e,this.pendingReason!==null&&!e.signal.aborted&&(e.abort(this.pendingReason),this.pendingReason=null),e}clear(e){this.current===e&&(this.current=null)}requestAbort(e){let n=this.current;if(n&&!n.signal.aborted){n.abort(e);return}this.pendingReason=e}isIdle(){return this.current===null}markClosed(){this.closeResolve?.()}}});function wO(t,e,n,r,o){let s=bO.get(t);if(!s)return;let i=1e6,c=Math.max(0,e-r-o)/i*s.inputPerMTok,l=n/i*s.outputPerMTok,d=s.cacheWritePerMTok??s.inputPerMTok*1.25,u=s.cacheReadPerMTok??s.inputPerMTok*.1,p=o/i*d,f=r/i*u;return c+l+p+f}function Kw(t,e,n){if(!t)return{stopReason:e??null};let r={inputTokens:t.input_tokens,outputTokens:t.output_tokens,stopReason:e??null};if(t.cache_read_input_tokens!=null&&(r.cachedInputTokens=t.cache_read_input_tokens),t.cache_creation_input_tokens!=null&&(r.cacheCreationTokens=t.cache_creation_input_tokens),r.totalTokens=(t.input_tokens??0)+(t.output_tokens??0),n){let o=wO(n,t.input_tokens??0,t.output_tokens??0,t.cache_read_input_tokens??0,t.cache_creation_input_tokens??0);o!==void 0&&(r.totalCostUsd=o)}return r}var bO,Ww=y(()=>{"use strict";ml();bO=new Map([["claude-sonnet-5",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-sonnet-4-5-20250929",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-opus-4-5-20250929",{inputPerMTok:15,outputPerMTok:75,cacheWritePerMTok:18.75,cacheReadPerMTok:1.5}],["claude-haiku-4-5-20250929",{inputPerMTok:1,outputPerMTok:5,cacheWritePerMTok:1.25,cacheReadPerMTok:.1}],["claude-haiku-4-5-20251001",{inputPerMTok:1,outputPerMTok:5,cacheWritePerMTok:1.25,cacheReadPerMTok:.1}],["claude-3-7-sonnet-20250219",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20241022",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20240620",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-3-5-haiku-20241022",{inputPerMTok:.8,outputPerMTok:4,cacheWritePerMTok:1,cacheReadPerMTok:.08}],["claude-3-opus-20240229",{inputPerMTok:15,outputPerMTok:75,cacheWritePerMTok:18.75,cacheReadPerMTok:1.5}],["claude-3-sonnet-20240229",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-3-haiku-20240307",{inputPerMTok:.25,outputPerMTok:1.25,cacheWritePerMTok:.3,cacheReadPerMTok:.03}]])});function vO(t){let e=t.trim();if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function SO(t,e,n){let r=[],o=[];for(let a of t)a&&(a.kind==="text"?(r.push({type:"text",text:a.text}),o.push(a.text)):a.kind==="thinking"?a.thinking&&a.signature&&r.push({type:"thinking",thinking:a.thinking,signature:a.signature}):a.kind==="redacted_thinking"?r.push({type:"redacted_thinking",data:a.data}):r.push({type:"tool_use",id:a.id,name:a.name,input:vO(a.partialJson)}));let s=a=>a.type==="tool_use",i=r.filter(s);return{stopReason:e,assistantBlocks:r,toolUseBlocks:i,usage:n,text:o.join("")}}async function*Gw(t,e){let n=[],r=null,o=null,s=!1,i=!!E.AFK_TELEGRAM_TRACE;try{i&&console.log("[translate] starting SDK event iteration");for await(let a of t){switch(i&&console.log("[translate] SDK evt:",a.type),a.type){case"message_start":{let c=a.message?.usage;c&&(o={...c});break}case"content_block_start":{let c=a.content_block;c.type==="text"?n[a.index]={kind:"text",text:""}:c.type==="thinking"?n[a.index]={kind:"thinking",thinking:"",signature:""}:c.type==="redacted_thinking"?n[a.index]={kind:"redacted_thinking",data:c.data}:c.type==="tool_use"&&(n[a.index]={kind:"tool_use",id:c.id,name:c.name,partialJson:""},yield{kind:"event",event:{type:"tool.use.start",toolUseId:c.id,toolName:c.name,toolInput:" \u2026",sessionId:e.sessionId}});break}case"content_block_delta":{let c=n[a.index],l=a.delta;l.type==="text_delta"?(c&&c.kind==="text"&&(c.text+=l.text),yield{kind:"event",event:{type:"delta.text",text:l.text,sessionId:e.sessionId}}):l.type==="input_json_delta"?c&&c.kind==="tool_use"&&(c.partialJson+=l.partial_json):l.type==="thinking_delta"?(c&&c.kind==="thinking"&&(c.thinking+=l.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:l.thinking,sessionId:e.sessionId}}):l.type==="signature_delta"&&c&&c.kind==="thinking"&&(c.signature=l.signature);break}case"content_block_stop":{let c=n[a.index];c&&c.kind==="tool_use"&&(yield{kind:"event",event:{type:"tool.use",summary:c.name,toolUseIds:[c.id],sessionId:e.sessionId}});break}case"message_delta":{a.delta&&a.delta.stop_reason!==void 0&&(r=a.delta.stop_reason);let c=a.usage;c&&(o!==null?(o.output_tokens=c.output_tokens,c.cache_creation_input_tokens!=null&&(o.cache_creation_input_tokens=c.cache_creation_input_tokens),c.cache_read_input_tokens!=null&&(o.cache_read_input_tokens=c.cache_read_input_tokens),c.input_tokens!=null&&(o.input_tokens=c.input_tokens)):o={cache_creation:null,cache_creation_input_tokens:c.cache_creation_input_tokens??null,cache_read_input_tokens:c.cache_read_input_tokens??null,inference_geo:null,input_tokens:c.input_tokens??0,output_tokens:c.output_tokens,server_tool_use:null,service_tier:null});break}case"message_stop":{s=!0;break}default:break}if(s)break}i&&console.log("[translate] SDK iteration ended naturally, stopped=",s)}catch(a){i&&console.log("[translate] SDK iteration threw:",a.message),yield{kind:"event",event:{type:"error",error:a instanceof Error?a:new Error(String(a))}};return}i&&console.log("[translate] yielding turn-result"),yield{kind:"turn-result",result:SO(n,r,o)}}var qw=y(()=>{"use strict";H()});import{randomUUID as kO}from"node:crypto";function EO(t){let{name:e,description:n,input_schema:r}=t;return{name:e,...n!==void 0?{description:n}:{},input_schema:r}}function AO(t){if(!("status"in t))return!1;let e=t.status;return e===529||e===503}function zw(t){if(t===null||typeof t!="object")return!1;let e=t;if(e.status===529||e.status===503)return!0;let n=e.error;if(n===null||typeof n!="object")return!1;let r=n;return((r.error!==null&&typeof r.error=="object"?r.error.type:void 0)??r.type)==="overloaded_error"}async function TO(t,e,n,r){for(let o=0;;o++){if(o>0){let s=Vw*Math.pow(2,o-1);if(await Pt(s,r),r.aborted)throw new Error("aborted")}try{return await Promise.resolve(t.messages.create(e,{headers:n,signal:r}))}catch(s){if(r.aborted)throw s;let i=s instanceof Error?s:new Error(String(s));if(AO(i)&&o<Md)continue;throw i}}}async function*Od(t){let e=t.maxToolUseIterations??_O,n={stopReason:null},r=0,o=0,s=kO(),i=Date.now(),a=c=>({...c,durationMs:Date.now()-i});re(t.traceWriter,{phase:"loop_start"});try{for(;;){if(t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let c=Vo({baseUrl:t.baseUrl})?Qp(t.messages,Jo()):t.messages,l={model:t.model,max_tokens:t.maxTokens,messages:c,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0?{tools:t.tools.map(EO)}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{output_config:{effort:t.effort}}:{}},d=Date.now(),u;try{u=await TO(t.client,l,t.headers,t.signal)}catch(v){if(t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let k=v instanceof Error?v:new Error(String(v));k.message.includes("thinking")&&xO(t.messages,k),yield{type:"error",error:k};return}let p=null,f=!1,m=!1,h=!1;try{E.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let v of Gw(u,t.ctx))if(h||(h=!0,re(t.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-d,resolvedModel:t.model})),E.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",v.kind,v.kind==="event"?v.event.type:""),v.kind==="event"){if(v.event.type==="error"){if(zw(v.event.error)&&o<Md&&!t.signal.aborted){m=!0;break}yield v.event,f=!0;break}yield v.event}else{p=v.result;break}E.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",p?"set":"null")}catch(v){if(t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let k=v instanceof Error?v:new Error(String(v));if(zw(k)&&o<Md&&!t.signal.aborted)m=!0;else{yield{type:"error",error:k};return}}if(m){if(o+=1,re(t.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:o}}),yield{type:"stream.retry",sessionId:t.ctx.sessionId},await Pt(Vw*Math.pow(2,o-1),t.signal),t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}continue}if(o=0,f){t.signal.aborted&&(yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId});return}if(p===null){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let w=Kw(p.usage,p.stopReason,t.model);if(n=kr(n,w),n.contextWindowTokens=(w.inputTokens??0)+(w.outputTokens??0)+(w.cachedInputTokens??0)+(w.cacheCreationTokens??0),t.onUsageProgress?.(n),p.stopReason!=="tool_use"){if(p.stopReason==="refusal"){yield{type:"assistant.message",text:p.text.length>0?p.text:`The model stopped with a content-safety refusal (stop_reason: "refusal") and returned no output. This is Anthropic's safety system declining the request \u2014 not an afk error. Because the flagged context stays in the conversation, follow-up messages will likely be refused the same way; rephrase the request or start a fresh session to continue.`,sessionId:t.ctx.sessionId},yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}p.text.length>0&&(yield{type:"assistant.message",text:p.text,sessionId:t.ctx.sessionId},p.text.length<=200&&(yield{type:"suggestion",suggestion:p.text,sessionId:t.ctx.sessionId}));let v=p.assistantBlocks.filter(k=>k.type!=="tool_use");v.length>0&&t.messages.push({role:"assistant",content:v}),yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let b=t.messages.length;t.messages.push({role:"assistant",content:p.assistantBlocks});try{let v=[],k=new Map;for(let T of p.toolUseBlocks){v.push({id:T.id,name:T.name,input:T.input,signal:t.signal});let U=Date.now();k.set(T.id,U),pn(t.traceWriter,{phase:"started",toolUseId:T.id,name:T.name,inputBytes:Buffer.byteLength(JSON.stringify(T.input??{}),"utf8")}),yield{type:"tool.use.start",toolUseId:T.id,toolName:T.name,toolInput:On(T.name,T.input),toolInputRaw:ii(T.input),sessionId:t.ctx.sessionId}}if(t.signal.aborted){let T=v.map(U=>({type:"tool_result",tool_use_id:U.id,content:"Tool call aborted",is_error:!0}));t.messages.push({role:"user",content:T}),yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let R;if(t.toolDispatcher.executeBatch)try{R=await t.toolDispatcher.executeBatch(v)}catch(T){R=v.map(()=>({content:`Tool batch execution failed: ${T instanceof Error?T.message:String(T)}`,isError:!0}))}else{R=[];for(let T of v){if(t.signal.aborted){R.push({content:"Tool call aborted",isError:!0});continue}try{R.push(await t.toolDispatcher.execute(T))}catch(U){let I=U instanceof Error?U.message:String(U);R.push({content:`Tool execution threw: ${I}`,isError:!0})}}}let _=[];for(let T=0;T<v.length;T++){let U=v[T],I=R[T],B=k.get(U.id),D=typeof B=="number"?Date.now()-B:0,x=I.truncated===!0||I.content.includes("[output truncated");pn(t.traceWriter,{phase:"completed",toolUseId:U.id,name:U.name,resultBytes:Buffer.byteLength(I.content,"utf8"),isError:I.isError===!0,truncated:x,durationMs:D,...I.circuitBreaker===!0?{circuitBreaker:!0}:{},...I.failureClass?{failureClass:I.failureClass}:{}}),yield{type:"tool.output",toolUseId:U.id,toolName:U.name,content:I.content,...I.isError===!0?{isError:!0}:{},...x?{truncated:!0}:{},sessionId:t.ctx.sessionId},I.render?.diff&&(yield{type:"tool.diff",toolUseId:U.id,diff:I.render.diff,sessionId:t.ctx.sessionId});let{content:C,isError:L,image:M}=I,F=M!==void 0?[{type:"image",source:{type:"base64",media_type:M.mediaType,data:M.data}},...C.length>0?[{type:"text",text:C}]:[]]:C;_.push({type:"tool_result",tool_use_id:U.id,content:F,...L===!0?{is_error:!0}:{}})}let P={role:"user",content:_};t.messages.push(P)}catch(v){throw t.messages.splice(b),v}r+=1;let S=p.toolUseBlocks[p.toolUseBlocks.length-1],A=S?`${S.name}${On(S.name,S.input)}`:"unknown";if(yield{type:"progress",progress:{taskId:s,description:"Working",summary:`round ${r}: ${A}`,lastToolName:S?.name,totalTokens:n.totalTokens??0,toolUses:r,durationMs:Date.now()-i},sessionId:t.ctx.sessionId},e>0&&r>=e){yield{type:"turn.completed",usage:a({...n,stopReason:"tool_use_loop_capped"}),sessionId:t.ctx.sessionId};return}}}finally{re(t.traceWriter,{phase:"loop_end",durationMs:Date.now()-i})}}function xO(t,e){try{let n=[];for(let r=0;r<t.length;r++){let o=t[r];if(o.role!=="assistant"||typeof o.content=="string")continue;let s=o.content;for(let i=0;i<s.length;i++){let a=s[i];if(a.type==="thinking"){let c=a;(!c.thinking||!c.signature)&&n.push({msgIdx:r,blockIdx:i,thinking:c.thinking?`(${c.thinking.length} chars)`:"(empty)",sigLen:c.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",e.message),console.error(`[afk] messages.length=${t.length}, invalid thinking blocks:`,n.length>0?JSON.stringify(n):"none found (cause may be elsewhere)")}catch{}}var _O,Md,Vw,Jw=y(()=>{"use strict";Ww();qa();qw();ne();yl();H();Al();Tl();_O=0;Md=3,Vw=5e3});var Yw=y(()=>{"use strict";or()});import{randomUUID as Dd}from"node:crypto";var Xw,RO,Wi,Qw=y(()=>{"use strict";Jw();$t();zo();Yw();Xw=7200*1e3,RO=60*1e3,Wi=class{_client;_authMode;initSessionId;tokenRefresher;autoResumeOnUsageLimit;refreshPromise=null;usageLimitWaitPromise=null;constructor(e){this._client=e.client,this._authMode=e.authMode,this.initSessionId=e.initSessionId,this.tokenRefresher=e.tokenRefresher,this.autoResumeOnUsageLimit=e.autoResumeOnUsageLimit}get client(){return this._client}get authMode(){return this._authMode}async forceClientRefresh(){if(!this.tokenRefresher)return null;let e=Le(),n=null;try{if(this.refreshPromise)n=await this.refreshPromise;else{this.refreshPromise=this.tokenRefresher();try{n=await this.refreshPromise??null}finally{this.refreshPromise=null}}}catch{return this.refreshPromise=null,null}if(!n)return null;this._client=n;let r=Le();return{accountId:rr(r??""),swapped:e!==r}}async*turnWithRetries(e,n){yield*this.turnWithUsageLimitRetry(e,n)}async*turnWithUsageLimitRetry(e,n){let r=null,o=null,s=!1;for await(let l of this.turnWithAuthRetry(e,n)){if(l.type==="error"){let d=qo(l.error);if(d&&d.kind==="oauth-limit"){o=d.resetsAt,r=l;break}if(d&&d.kind==="oauth-limit-no-ts"){s=!0,r=l;break}}yield l}if(!r)return;if(s){let l=rr(Le()??"");if(yield{type:"paused",reason:"usage-limit",accountId:l,autoResume:this.autoResumeOnUsageLimit},!this.autoResumeOnUsageLimit){yield r;return}let d=Date.now(),u=!1;for(;;){let p;if(this.usageLimitWaitPromise)p="aborted";else{this.usageLimitWaitPromise=Jp({signal:e.signal,retryAfterMs:RO});try{p=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(p==="aborted")return;let f=l;if(p==="hot-swap"){let h=await this.forceClientRefresh();h&&(e.client=this._client,f=h.accountId)}e.headers=qe(this._authMode,this.initSessionId,Dd());let m=null;for await(let h of this.turnWithAuthRetry(e,n)){if(!u&&h.type==="error"){let w=qo(h.error);if(w&&(w.kind==="oauth-limit"||w.kind==="oauth-limit-no-ts")){m=h;break}}u||(yield{type:"resumed",hotSwapped:p==="hot-swap",accountId:f},u=!0),yield h}if(!m)return;if(Date.now()-d>Xw){yield m;return}}}if(!o)return;if(o.getTime()-Date.now()>Xw){yield r;return}let i=rr(Le()??"");if(yield{type:"paused",reason:"usage-limit",resetsAt:o,accountId:i,autoResume:this.autoResumeOnUsageLimit},!this.autoResumeOnUsageLimit){yield r;return}let a;if(this.usageLimitWaitPromise)a=await this.usageLimitWaitPromise;else{this.usageLimitWaitPromise=Vp({resetsAt:o,signal:e.signal});try{a=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(a==="aborted")return;let c=i;if(a==="hot-swap"){let l=await this.forceClientRefresh();l&&(e.client=this._client,c=l.accountId)}e.headers=qe(this._authMode,this.initSessionId,Dd()),yield{type:"resumed",hotSwapped:a==="hot-swap",accountId:c},yield*this.turnWithAuthRetry(e,n)}async*turnWithAuthRetry(e,n){let r=null;for await(let s of Od(e)){if(n())return;if(s.type==="error"&&this.isRetryableAuth(s.error)){r=s;break}yield s}if(!r)return;if(!await this.forceClientRefresh()){yield r;return}e.client=this._client,e.headers=qe(this._authMode,this.initSessionId,Dd()),yield*Od(e)}isRetryableAuth(e){return this._authMode==="oauth"&&this.tokenRefresher!==void 0&&"status"in e&&e.status===401}}});function IO(t){if(t.role!=="user")return!1;let e=t.content;if(typeof e=="string")return!0;if(!Array.isArray(e))return!1;for(let n of e)if(n.type==="tool_result")return!1;return!0}function tv(t,e){if(e<=0)return t.length;let n=0;for(let r=t.length-1;r>=0;r--){let o=t[r];if(o&&IO(o)&&(n+=1,n===e))return r}return-1}function nv(t,e,n){let r=CO(t);return{model:e,max_tokens:n,system:PO,messages:[{role:"user",content:`Summarize the following conversation transcript. Follow the system instructions exactly.
1555
+ `)}function Lr(t,e){let n=[],r=new Set,o=E.AFK_INTERNAL==="1",s=ar(ir());jr(go(),"user"),kf("project"),jr(Pu(e?.cwd),"project");for(let{dir:a,origin:c}of s.skillRoots)jr(a,c);for(let a of dc()){let c=$e(a);lc(c,o)&&(n.push({name:a,description:c.description,source:c.origin==="user"?"user":c.origin==="project"?"project":c.origin?.startsWith("imported:")?"imported":"builtin",argumentHint:c.argumentHint,whenToUse:c.whenToUse}),r.add(a))}let i=t??Cd(e);for(let a of i){if(a.type!=="local")continue;let c=Wl(a.path);for(let l of c)!l.name||r.has(l.name)||lc({audience:l.audience},o)&&(n.push({name:l.name,description:l.description??`Skill from plugin at ${a.path}`,source:"plugin"}),r.add(l.name))}return n}function Nr(t,e){let n=new Map,r=t??Cd(e);for(let o of r){if(o.type!=="local")continue;let s=Wl(o.path);for(let i of s)i.name&&i.body&&i.body.length>0&&!n.has(i.name)&&n.set(i.name,{body:i.body,pluginPath:o.path,...i.allowedTools!==void 0?{allowedTools:i.allowedTools}:{},...i.context!==void 0?{context:i.context}:{},...i.readOnly===!0?{readOnly:!0}:{}})}return n}function Cd(t){return[...nn(Iu(t?.cwd)),...nn(),...nn(Mu()),...ar(ir()).pluginRoots.flatMap(e=>nn(e,{trustAll:!0}))]}async function Nw(){await Ew(Cd(),{pluginApi:{registerSkill:pe,listSkills:dc,getSkill:$e,loadSkillPrompts:ee,env:E,SubagentManager:z,describeFailure:se,discoverPluginSkillBodies:Nr,getAgentFrameworkDir:ot,getSkillsDir:go,getSessionsDir:me,getOrDeriveFacet:Pd,listSessionIds:Id,deriveSessionFacet:Wr,loadStoredSession:Hi}})}var tn=y(()=>{"use strict";kw();Re();xe();Td();cd();Aw();Mr();le();_e();Lw();W();H();ts()});function li(){try{let t=Lr();return Promise.resolve(t.map(e=>{let n={name:e.name,description:e.description};return e.argumentHint&&(n.argumentHint=e.argumentHint),n}))}catch{return Promise.resolve([])}}var Bl=y(()=>{"use strict";tn()});function $w(t){if(t.length===0)return;let e=t[t.length-1];if(!e||e.role!=="assistant"||typeof e.content=="string")return;let n=e.content,r=[];for(let s of n)s.type==="tool_use"&&typeof s.id=="string"&&r.push(s.id);if(r.length===0)return;let o={role:"user",content:r.map(s=>({type:"tool_result",tool_use_id:s,content:"Tool call interrupted before completing \u2014 no result recorded.",is_error:!0}))};t.push(o)}var Uw=y(()=>{"use strict"});function Bw(t){return{messages:t.initialMessages?[...t.initialMessages]:[],currentModel:t.model,requestedModel:t.requestedModel??t.model,currentPermissionMode:t.permissionMode,userSystem:t.userSystem,toolDispatcher:t.toolDispatcher,lastUsage:null,closed:!1,autoCompactThreshold:t.autoCompactThreshold}}var jw=y(()=>{"use strict"});var yO,Ki,Hw=y(()=>{"use strict";yO="__closed__",Ki=class{current=null;pendingReason=null;closedPromise;closeResolve=null;constructor(){this.closedPromise=new Promise(e=>{this.closeResolve=()=>e(yO)})}begin(){let e=new AbortController;return this.current=e,this.pendingReason!==null&&!e.signal.aborted&&(e.abort(this.pendingReason),this.pendingReason=null),e}clear(e){this.current===e&&(this.current=null)}requestAbort(e){let n=this.current;if(n&&!n.signal.aborted){n.abort(e);return}this.pendingReason=e}isIdle(){return this.current===null}markClosed(){this.closeResolve?.()}}});function wO(t,e,n,r,o){let s=bO.get(t);if(!s)return;let i=1e6,c=Math.max(0,e-r-o)/i*s.inputPerMTok,l=n/i*s.outputPerMTok,d=s.cacheWritePerMTok??s.inputPerMTok*1.25,u=s.cacheReadPerMTok??s.inputPerMTok*.1,p=o/i*d,f=r/i*u;return c+l+p+f}function Kw(t,e,n){if(!t)return{stopReason:e??null};let r={inputTokens:t.input_tokens,outputTokens:t.output_tokens,stopReason:e??null};if(t.cache_read_input_tokens!=null&&(r.cachedInputTokens=t.cache_read_input_tokens),t.cache_creation_input_tokens!=null&&(r.cacheCreationTokens=t.cache_creation_input_tokens),r.totalTokens=(t.input_tokens??0)+(t.output_tokens??0),n){let o=wO(n,t.input_tokens??0,t.output_tokens??0,t.cache_read_input_tokens??0,t.cache_creation_input_tokens??0);o!==void 0&&(r.totalCostUsd=o)}return r}var bO,Ww=y(()=>{"use strict";ml();bO=new Map([["claude-sonnet-5",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-sonnet-4-5-20250929",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-opus-4-5-20250929",{inputPerMTok:15,outputPerMTok:75,cacheWritePerMTok:18.75,cacheReadPerMTok:1.5}],["claude-haiku-4-5-20250929",{inputPerMTok:1,outputPerMTok:5,cacheWritePerMTok:1.25,cacheReadPerMTok:.1}],["claude-haiku-4-5-20251001",{inputPerMTok:1,outputPerMTok:5,cacheWritePerMTok:1.25,cacheReadPerMTok:.1}],["claude-3-7-sonnet-20250219",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20241022",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20240620",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-3-5-haiku-20241022",{inputPerMTok:.8,outputPerMTok:4,cacheWritePerMTok:1,cacheReadPerMTok:.08}],["claude-3-opus-20240229",{inputPerMTok:15,outputPerMTok:75,cacheWritePerMTok:18.75,cacheReadPerMTok:1.5}],["claude-3-sonnet-20240229",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-3-haiku-20240307",{inputPerMTok:.25,outputPerMTok:1.25,cacheWritePerMTok:.3,cacheReadPerMTok:.03}]])});function vO(t){let e=t.trim();if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function SO(t,e,n){let r=[],o=[];for(let a of t)a&&(a.kind==="text"?(r.push({type:"text",text:a.text}),o.push(a.text)):a.kind==="thinking"?a.thinking&&a.signature&&r.push({type:"thinking",thinking:a.thinking,signature:a.signature}):a.kind==="redacted_thinking"?r.push({type:"redacted_thinking",data:a.data}):r.push({type:"tool_use",id:a.id,name:a.name,input:vO(a.partialJson)}));let s=a=>a.type==="tool_use",i=r.filter(s);return{stopReason:e,assistantBlocks:r,toolUseBlocks:i,usage:n,text:o.join("")}}async function*Gw(t,e){let n=[],r=null,o=null,s=!1,i=!!E.AFK_TELEGRAM_TRACE;try{i&&console.log("[translate] starting SDK event iteration");for await(let a of t){switch(i&&console.log("[translate] SDK evt:",a.type),a.type){case"message_start":{let c=a.message?.usage;c&&(o={...c});break}case"content_block_start":{let c=a.content_block;c.type==="text"?n[a.index]={kind:"text",text:""}:c.type==="thinking"?n[a.index]={kind:"thinking",thinking:"",signature:""}:c.type==="redacted_thinking"?n[a.index]={kind:"redacted_thinking",data:c.data}:c.type==="tool_use"&&(n[a.index]={kind:"tool_use",id:c.id,name:c.name,partialJson:""},yield{kind:"event",event:{type:"tool.use.start",toolUseId:c.id,toolName:c.name,toolInput:" \u2026",sessionId:e.sessionId}});break}case"content_block_delta":{let c=n[a.index],l=a.delta;l.type==="text_delta"?(c&&c.kind==="text"&&(c.text+=l.text),yield{kind:"event",event:{type:"delta.text",text:l.text,sessionId:e.sessionId}}):l.type==="input_json_delta"?c&&c.kind==="tool_use"&&(c.partialJson+=l.partial_json):l.type==="thinking_delta"?(c&&c.kind==="thinking"&&(c.thinking+=l.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:l.thinking,sessionId:e.sessionId}}):l.type==="signature_delta"&&c&&c.kind==="thinking"&&(c.signature=l.signature);break}case"content_block_stop":{let c=n[a.index];c&&c.kind==="tool_use"&&(yield{kind:"event",event:{type:"tool.use",summary:c.name,toolUseIds:[c.id],sessionId:e.sessionId}});break}case"message_delta":{a.delta&&a.delta.stop_reason!==void 0&&(r=a.delta.stop_reason);let c=a.usage;c&&(o!==null?(o.output_tokens=c.output_tokens,c.cache_creation_input_tokens!=null&&(o.cache_creation_input_tokens=c.cache_creation_input_tokens),c.cache_read_input_tokens!=null&&(o.cache_read_input_tokens=c.cache_read_input_tokens),c.input_tokens!=null&&(o.input_tokens=c.input_tokens)):o={cache_creation:null,cache_creation_input_tokens:c.cache_creation_input_tokens??null,cache_read_input_tokens:c.cache_read_input_tokens??null,inference_geo:null,input_tokens:c.input_tokens??0,output_tokens:c.output_tokens,server_tool_use:null,service_tier:null});break}case"message_stop":{s=!0;break}default:break}if(s)break}i&&console.log("[translate] SDK iteration ended naturally, stopped=",s)}catch(a){i&&console.log("[translate] SDK iteration threw:",a.message),yield{kind:"event",event:{type:"error",error:a instanceof Error?a:new Error(String(a))}};return}i&&console.log("[translate] yielding turn-result"),yield{kind:"turn-result",result:SO(n,r,o)}}var qw=y(()=>{"use strict";H()});import{randomUUID as kO}from"node:crypto";function EO(t){let{name:e,description:n,input_schema:r}=t;return{name:e,...n!==void 0?{description:n}:{},input_schema:r}}function AO(t){if(!("status"in t))return!1;let e=t.status;return e===529||e===503}function zw(t){if(t===null||typeof t!="object")return!1;let e=t;if(e.status===529||e.status===503)return!0;let n=e.error;if(n===null||typeof n!="object")return!1;let r=n;return((r.error!==null&&typeof r.error=="object"?r.error.type:void 0)??r.type)==="overloaded_error"}async function TO(t,e,n,r){for(let o=0;;o++){if(o>0){let s=Vw*Math.pow(2,o-1);if(await Pt(s,r),r.aborted)throw new Error("aborted")}try{return await Promise.resolve(t.messages.create(e,{headers:n,signal:r}))}catch(s){if(r.aborted)throw s;let i=s instanceof Error?s:new Error(String(s));if(AO(i)&&o<Md)continue;throw i}}}async function*Od(t){let e=t.maxToolUseIterations??_O,n={stopReason:null},r=0,o=0,s=kO(),i=Date.now(),a=c=>({...c,durationMs:Date.now()-i});re(t.traceWriter,{phase:"loop_start"});try{for(;;){if(t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let c=Vo({baseUrl:t.baseUrl})?Qp(t.messages,Jo()):t.messages,l={model:t.model,max_tokens:t.maxTokens,messages:c,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0?{tools:t.tools.map(EO)}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{output_config:{effort:t.effort}}:{}},d=Date.now(),u;try{u=await TO(t.client,l,t.headers,t.signal)}catch(v){if(t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let k=v instanceof Error?v:new Error(String(v));k.message.includes("thinking")&&xO(t.messages,k),yield{type:"error",error:k};return}let p=null,f=!1,m=!1,h=!1;try{E.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let v of Gw(u,t.ctx))if(h||(h=!0,re(t.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-d,resolvedModel:t.model})),E.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",v.kind,v.kind==="event"?v.event.type:""),v.kind==="event"){if(v.event.type==="error"){if(zw(v.event.error)&&o<Md&&!t.signal.aborted){m=!0;break}yield v.event,f=!0;break}yield v.event}else{p=v.result;break}E.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",p?"set":"null")}catch(v){if(t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let k=v instanceof Error?v:new Error(String(v));if(zw(k)&&o<Md&&!t.signal.aborted)m=!0;else{yield{type:"error",error:k};return}}if(m){if(o+=1,re(t.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:o}}),yield{type:"stream.retry",sessionId:t.ctx.sessionId},await Pt(Vw*Math.pow(2,o-1),t.signal),t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}continue}if(o=0,f){t.signal.aborted&&(yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId});return}if(p===null){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let w=Kw(p.usage,p.stopReason,t.model);if(n=kr(n,w),n.contextWindowTokens=(w.inputTokens??0)+(w.outputTokens??0)+(w.cachedInputTokens??0)+(w.cacheCreationTokens??0),t.onUsageProgress?.(n),p.stopReason!=="tool_use"){if(p.stopReason==="refusal"){yield{type:"assistant.message",text:p.text.length>0?p.text:`The model stopped with a content-safety refusal (stop_reason: "refusal") and returned no output. This is Anthropic's safety system declining the request \u2014 not an afk error. Because the flagged context stays in the conversation, follow-up messages will likely be refused the same way; rephrase the request or start a fresh session to continue.`,sessionId:t.ctx.sessionId},yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}p.text.length>0&&(yield{type:"assistant.message",text:p.text,sessionId:t.ctx.sessionId},p.text.length<=200&&(yield{type:"suggestion",suggestion:p.text,sessionId:t.ctx.sessionId}));let v=p.assistantBlocks.filter(k=>k.type!=="tool_use");v.length>0&&t.messages.push({role:"assistant",content:v}),yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let b=t.messages.length;t.messages.push({role:"assistant",content:p.assistantBlocks});try{let v=[],k=new Map;for(let T of p.toolUseBlocks){v.push({id:T.id,name:T.name,input:T.input,signal:t.signal});let U=Date.now();k.set(T.id,U),pn(t.traceWriter,{phase:"started",toolUseId:T.id,name:T.name,inputBytes:Buffer.byteLength(JSON.stringify(T.input??{}),"utf8")}),yield{type:"tool.use.start",toolUseId:T.id,toolName:T.name,toolInput:On(T.name,T.input),toolInputRaw:ii(T.input),sessionId:t.ctx.sessionId}}if(t.signal.aborted){let T=v.map(U=>({type:"tool_result",tool_use_id:U.id,content:"Tool call aborted",is_error:!0}));t.messages.push({role:"user",content:T}),yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let R;if(t.toolDispatcher.executeBatch)try{R=await t.toolDispatcher.executeBatch(v)}catch(T){R=v.map(()=>({content:`Tool batch execution failed: ${T instanceof Error?T.message:String(T)}`,isError:!0}))}else{R=[];for(let T of v){if(t.signal.aborted){R.push({content:"Tool call aborted",isError:!0});continue}try{R.push(await t.toolDispatcher.execute(T))}catch(U){let I=U instanceof Error?U.message:String(U);R.push({content:`Tool execution threw: ${I}`,isError:!0})}}}let _=[];for(let T=0;T<v.length;T++){let U=v[T],I=R[T],B=k.get(U.id),D=typeof B=="number"?Date.now()-B:0,x=I.truncated===!0||I.content.includes("[output truncated");pn(t.traceWriter,{phase:"completed",toolUseId:U.id,name:U.name,resultBytes:Buffer.byteLength(I.content,"utf8"),isError:I.isError===!0,truncated:x,durationMs:D,...I.circuitBreaker===!0?{circuitBreaker:!0}:{},...I.failureClass?{failureClass:I.failureClass}:{}}),yield{type:"tool.output",toolUseId:U.id,toolName:U.name,content:I.content,...I.isError===!0?{isError:!0}:{},...x?{truncated:!0}:{},sessionId:t.ctx.sessionId},I.render?.diff&&(yield{type:"tool.diff",toolUseId:U.id,diff:I.render.diff,sessionId:t.ctx.sessionId});let{content:C,isError:L,image:M}=I,F=M!==void 0?[{type:"image",source:{type:"base64",media_type:M.mediaType,data:M.data}},...C.length>0?[{type:"text",text:C}]:[]]:C;_.push({type:"tool_result",tool_use_id:U.id,content:F,...L===!0?{is_error:!0}:{}})}let P={role:"user",content:_};t.messages.push(P)}catch(v){throw t.messages.splice(b),v}r+=1;let S=p.toolUseBlocks[p.toolUseBlocks.length-1],A=S?`${S.name}${On(S.name,S.input)}`:"unknown";if(yield{type:"progress",progress:{taskId:s,description:"Working",summary:`round ${r}: ${A}`,lastToolName:S?.name,totalTokens:n.totalTokens??0,toolUses:r,durationMs:Date.now()-i},sessionId:t.ctx.sessionId},e>0&&r>=e){yield{type:"turn.completed",usage:a({...n,stopReason:"tool_use_loop_capped"}),sessionId:t.ctx.sessionId};return}}}finally{re(t.traceWriter,{phase:"loop_end",durationMs:Date.now()-i})}}function xO(t,e){try{let n=[];for(let r=0;r<t.length;r++){let o=t[r];if(o.role!=="assistant"||typeof o.content=="string")continue;let s=o.content;for(let i=0;i<s.length;i++){let a=s[i];if(a.type==="thinking"){let c=a;(!c.thinking||!c.signature)&&n.push({msgIdx:r,blockIdx:i,thinking:c.thinking?`(${c.thinking.length} chars)`:"(empty)",sigLen:c.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",e.message),console.error(`[afk] messages.length=${t.length}, invalid thinking blocks:`,n.length>0?JSON.stringify(n):"none found (cause may be elsewhere)")}catch{}}var _O,Md,Vw,Jw=y(()=>{"use strict";Ww();qa();qw();ne();yl();H();Al();Tl();_O=0;Md=3,Vw=5e3});var Yw=y(()=>{"use strict";or()});import{randomUUID as Dd}from"node:crypto";var Xw,RO,Wi,Qw=y(()=>{"use strict";Jw();$t();zo();Yw();Xw=7200*1e3,RO=60*1e3,Wi=class{_client;_authMode;initSessionId;tokenRefresher;autoResumeOnUsageLimit;refreshPromise=null;usageLimitWaitPromise=null;constructor(e){this._client=e.client,this._authMode=e.authMode,this.initSessionId=e.initSessionId,this.tokenRefresher=e.tokenRefresher,this.autoResumeOnUsageLimit=e.autoResumeOnUsageLimit}get client(){return this._client}get authMode(){return this._authMode}async forceClientRefresh(){if(!this.tokenRefresher)return null;let e=Le(),n=null;try{if(this.refreshPromise)n=await this.refreshPromise;else{this.refreshPromise=this.tokenRefresher();try{n=await this.refreshPromise??null}finally{this.refreshPromise=null}}}catch{return this.refreshPromise=null,null}if(!n)return null;this._client=n;let r=Le();return{accountId:rr(r??""),swapped:e!==r}}async*turnWithRetries(e,n){yield*this.turnWithUsageLimitRetry(e,n)}async*turnWithUsageLimitRetry(e,n){let r=null,o=null,s=!1;for await(let l of this.turnWithAuthRetry(e,n)){if(l.type==="error"){let d=qo(l.error);if(d&&d.kind==="oauth-limit"){o=d.resetsAt,r=l;break}if(d&&d.kind==="oauth-limit-no-ts"){s=!0,r=l;break}}yield l}if(!r)return;if(s){let l=rr(Le()??"");if(yield{type:"paused",reason:"usage-limit",accountId:l,autoResume:this.autoResumeOnUsageLimit},!this.autoResumeOnUsageLimit){yield r;return}let d=Date.now(),u=!1;for(;;){let p;if(this.usageLimitWaitPromise)p="aborted";else{this.usageLimitWaitPromise=Jp({signal:e.signal,retryAfterMs:RO});try{p=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(p==="aborted")return;let f=l;if(p==="hot-swap"){let h=await this.forceClientRefresh();h&&(e.client=this._client,f=h.accountId)}e.headers=qe(this._authMode,this.initSessionId,Dd());let m=null;for await(let h of this.turnWithAuthRetry(e,n)){if(!u&&h.type==="error"){let w=qo(h.error);if(w&&(w.kind==="oauth-limit"||w.kind==="oauth-limit-no-ts")){m=h;break}}u||(yield{type:"resumed",hotSwapped:p==="hot-swap",accountId:f},u=!0),yield h}if(!m)return;if(Date.now()-d>Xw){yield m;return}}}if(!o)return;if(o.getTime()-Date.now()>Xw){yield r;return}let i=rr(Le()??"");if(yield{type:"paused",reason:"usage-limit",resetsAt:o,accountId:i,autoResume:this.autoResumeOnUsageLimit},!this.autoResumeOnUsageLimit){yield r;return}let a;if(this.usageLimitWaitPromise)a=await this.usageLimitWaitPromise;else{this.usageLimitWaitPromise=Vp({resetsAt:o,signal:e.signal});try{a=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(a==="aborted")return;let c=i;if(a==="hot-swap"){let l=await this.forceClientRefresh();l&&(e.client=this._client,c=l.accountId)}e.headers=qe(this._authMode,this.initSessionId,Dd()),yield{type:"resumed",hotSwapped:a==="hot-swap",accountId:c},yield*this.turnWithAuthRetry(e,n)}async*turnWithAuthRetry(e,n){let r=null;for await(let s of Od(e)){if(n())return;if(s.type==="error"&&this.isRetryableAuth(s.error)){r=s;break}yield s}if(!r)return;if(!await this.forceClientRefresh()){yield r;return}e.client=this._client,e.headers=qe(this._authMode,this.initSessionId,Dd()),yield*Od(e)}isRetryableAuth(e){return this._authMode==="oauth"&&this.tokenRefresher!==void 0&&"status"in e&&e.status===401}}});function IO(t){if(t.role!=="user")return!1;let e=t.content;if(typeof e=="string")return!0;if(!Array.isArray(e))return!1;for(let n of e)if(n.type==="tool_result")return!1;return!0}function tv(t,e){if(e<=0)return t.length;let n=0;for(let r=t.length-1;r>=0;r--){let o=t[r];if(o&&IO(o)&&(n+=1,n===e))return r}return-1}function nv(t,e,n){let r=CO(t);return{model:e,max_tokens:n,system:PO,messages:[{role:"user",content:`Summarize the following conversation transcript. Follow the system instructions exactly.
1556
1556
 
1557
1557
  <transcript>
1558
1558
  `+r+`