agent-afk 5.2.0 → 5.3.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.
@@ -173,8 +173,8 @@ export declare const ScopeFreezeSchema: z.ZodObject<{
173
173
  }, z.core.$strip>;
174
174
  export type ScopeFreeze = z.infer<typeof ScopeFreezeSchema>;
175
175
  export declare const ProposalStatusSchema: z.ZodEnum<{
176
- rejected: "rejected";
177
176
  approved: "approved";
177
+ rejected: "rejected";
178
178
  draft: "draft";
179
179
  superseded: "superseded";
180
180
  }>;
@@ -240,8 +240,8 @@ export declare const ImprovementProposalSchema: z.ZodObject<{
240
240
  }>;
241
241
  createdAt: z.ZodString;
242
242
  status: z.ZodEnum<{
243
- rejected: "rejected";
244
243
  approved: "approved";
244
+ rejected: "rejected";
245
245
  draft: "draft";
246
246
  superseded: "superseded";
247
247
  }>;
@@ -306,8 +306,8 @@ export declare const EvalProvenanceSchema: z.ZodObject<{
306
306
  }, z.core.$strip>;
307
307
  export type EvalProvenance = z.infer<typeof EvalProvenanceSchema>;
308
308
  export declare const EvalCaseStatusSchema: z.ZodEnum<{
309
- rejected: "rejected";
310
309
  approved: "approved";
310
+ rejected: "rejected";
311
311
  draft: "draft";
312
312
  superseded: "superseded";
313
313
  }>;
@@ -352,8 +352,8 @@ export declare const EvalCaseSchema: z.ZodObject<{
352
352
  generatedBy: z.ZodLiteral<"replay-fixture">;
353
353
  }, z.core.$strip>;
354
354
  status: z.ZodEnum<{
355
- rejected: "rejected";
356
355
  approved: "approved";
356
+ rejected: "rejected";
357
357
  draft: "draft";
358
358
  superseded: "superseded";
359
359
  }>;
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  var Of=Object.defineProperty;var ge=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ui=(t,e)=>{for(var n in e)Of(t,n,{get:e[n],enumerable:!0})};function Fn(t){return Dn.find(e=>e.name===t)}function xo(t){return process.env[t]!==void 0}var Dn,w,N=ge(()=>{"use strict";Dn=[{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-4-6",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_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_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"}],w={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_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_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 Dn){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(w,e.name);n&&Object.defineProperty(w,e.name,{...n,enumerable:!1})}})()});import{existsSync as ga,mkdirSync as om,renameSync as sm,cpSync as im,rmSync as am}from"fs";import{join as H,dirname as ha,isAbsolute as ya}from"path";import{homedir as ba}from"os";import{fileURLToPath as cm}from"url";function re(){let t=w.AFK_HOME;if(t!==void 0&&t!==""){if(!ya(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return H(ba(),".afk")}function lt(){return H(re(),"agent-framework")}function wa(){return H(lt(),"forge-telemetry.jsonl")}function Sa(){return H(lt(),"briefs")}function Uo(){return H(re(),"skills")}function dt(){return H(re(),"plugins")}function va(){return H(process.cwd(),".afk")}function ka(){return H(va(),"skills")}function _a(){return H(va(),"plugins")}function Ea(t=process.cwd()){return H(t,".afk","plans")}function Wn(){return H(dt(),".index.json")}function Bo(){return H(Vt(),"schedules.json")}function Aa(){let t=cm(import.meta.url),e=ha(t);return H(e,"bundled-plugins")}function Vt(){return H(re(),"config")}function Xe(){let t=w.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!ya(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return H(re(),"state")}function ut(){return H(Xe(),"sessions")}function Gn(){return H(Xe(),"presence")}function qn(){return H(Xe(),"memory")}function pt(){return H(Xe(),"session-grants.jsonl")}function xa(){return H(re(),"farms")}function Ta(t){return H(xa(),t)}function dm(t){if(!lm.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function Ra(t){return dm(t),H(Xe(),"witness",t)}function Ia(t="default"){return H(Xe(),"daemon",`agent-afk@${t}`)}function Ho(){return H(Vt(),"afk.env")}function ft(){return H(Vt(),"afk.config.json")}function Vn(){return H(ba(),".afk.config.json")}function um(){return H(re(),"sessions")}function pm(t,e){if(t!==e&&ga(t)&&!ga(e))try{om(ha(e),{recursive:!0});try{sm(t,e)}catch(n){if(n.code==="EXDEV")try{im(t,e,{recursive:!0}),am(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
2
- `)}}}catch{}}function Pa(){pm(um(),ut())}function zt(t){return typeof t=="string"&&t.length>0&&t.length<=mm&&fm.test(t)}function Jt(t){if(!zt(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return H(ut(),t)}function zn(t){return H(Jt(t),"events.jsonl")}function Ca(t){return H(Jt(t),"session.key")}var lm,fm,mm,B=ge(()=>{"use strict";N();lm=/^[a-zA-Z0-9_-]+$/;fm=/^[A-Za-z0-9_-]+$/,mm=128});import{readFileSync as My}from"node:fs";import{join as Oy}from"path";function Dy(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Uc(t,e){return Dy(e).test(t)}function Ny(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(Fy.has(e))return!0;if(Ly.has(e))return!1}return!1}function Bc(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function $y(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 Uy(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function By(t){try{return My(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function Hy(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 n}function Hc(t){let e=t?.env??w,n=t?.readFileSync??By,r=t?.surface??e.AGENT_SURFACE,o=Ny(e.AFK_BROWSER_HEADLESS,r),s=Bc(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Bc(e.AFK_BROWSER_BLOCKED_DOMAINS),a=Uy(e.AFK_BROWSER_DOM_SNAPSHOTS),c=$y(e.AFK_BROWSER_BACKEND),l={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null},d=e.AFK_BROWSER_CONFIG,u=d!==void 0&&d.trim()!==""?d.trim():Oy(Vt(),"browser.json"),p=n(u);if(p===void 0)return l;let f;try{f=JSON.parse(p)}catch(m){throw new Error(`Failed to parse browser config at ${u}: ${String(m)}`)}if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`Browser config at ${u} must be a JSON object`);let g=Hy(l,f);return g.configPath=u,g}function ds(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(Uc(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Uc(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Fy,Ly,us=ge(()=>{"use strict";N();B();Fy=new Set(["daemon","subagent","telegram","afk"]),Ly=new Set(["repl","interactive","cli"])});import jy from"node:fs";import Ky from"node:path";import{chromium as Wy}from"playwright";function Gy(){try{return"5.2.0"}catch{}try{let t=Ky.resolve(import.meta.dirname,"../../../package.json"),e=jy.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var qy,gr,jc=ge(()=>{"use strict";qy=Gy(),gr=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=Wy.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 o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s={context:o,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,s),o}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),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/${qy}`}}}});import{createHash as Vy}from"crypto";function ps(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of zy)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function Kc(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&Jy.test(t.label))}function Wc(t){return Vy("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Gc(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var zy,Jy,cn=ge(()=>{"use strict";zy=[{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}];Jy=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Yy}from"node:crypto";function Xy(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Qy(t,e,n){return`el_${Yy("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function Zy(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function qc(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function zc(t,e){let n=t.role??"",r=t.name??"";Vc.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])zc(s,e)}async function eb(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},Jc).catch(()=>[])}async function tb(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 m=s.type;m==="checkbox"?l="checkbox":m==="radio"?l="radio":m==="button"||m==="submit"||m==="reset"?l="button":m==="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,g={role:l,name:c,disabled:p};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},Jc).catch(()=>[])}function nb(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function hr(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=nb(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=eb(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,g,m]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],zc(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await tb(t)).filter($=>Vc.has($.role??"")));let k=new Map;for(let v of p){let $=qc(v.name),P=k.get($);(!P||P.bbox.w===0&&v.bbox.w>0)&&k.set($,v)}let h=y.map(v=>({ax:v,dom:k.get(qc(v.name??""))})),S=r?h:h.filter(v=>v.dom?v.dom.bbox.w>0||v.dom.bbox.h>0:!0);S.sort((v,$)=>{let P=v.dom?.bbox.y??0,M=$.dom?.bbox.y??0;if(P!==M)return P-M;let T=v.dom?.bbox.x??0,A=$.dom?.bbox.x??0;return T-A}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=S.slice(0,n).map((v,$)=>{let P=v.ax.role??"generic",M=v.ax.name??"",T=Qy(P,M,$),A=v.dom?.bbox??{x:0,y:0,w:0,h:0},x=v.dom?.type??null,L=null;v.ax.value!==void 0&&v.ax.value!==null&&(L=String(v.ax.value)),v.ax.checked!==void 0&&(L=String(v.ax.checked)),Kc({role:P,kind:x})&&(L="[redacted]");let W={disabled:v.ax.disabled??!1};v.ax.checked!==void 0&&(W.checked=v.ax.checked===!0||v.ax.checked==="mixed"),v.ax.selected!==void 0&&(W.selected=v.ax.selected),v.ax.expanded!==void 0&&(W.expanded=v.ax.expanded);let U;v.dom?.testId?U=`[data-testid="${v.dom.testId}"]`:v.dom?.id&&(U=`#${v.dom.id}`);let V={id:T,role:P,label:Xy(M),kind:x,value:L,state:W,bbox:A};return U!==void 0&&(V.selector=U),V}),R="idle";try{let v=await t.evaluate(()=>document.readyState);v==="loading"?R="loading":v==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=Zy(f),C=`obs_${e.observationCounter.toString(36)}`,F=new Date().toISOString();return{observationId:C,url:g,title:m,textSummary:I,interactive:E,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:F}}var Vc,Jc,Yc=ge(()=>{"use strict";cn();Vc=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Jc="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Xc(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 fs(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Xc(t,s)))).filter(o=>o!==null)}async function rb(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 ms(t,e,n){switch(e.kind){case"element_id":return ob(t,e,n);case"selector":return sb(t,e);case"semantic":return ib(t,e)}}async function ob(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 fs(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function sb(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 fs(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function ib(t,e){return e.role!==void 0?ab(t,e.text,e.role):cb(t,e.text,e)}async function ab(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 fs(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function cb(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 rb(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let m=u[0];return m===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:m.locator.nth(m.index)}}let p=u.slice(0,5),f=[];for(let m=0;m<p.length;m++){let y=p[m];if(y===void 0)continue;let b=await Xc(y.locator,y.index);if(b!==null){let k=`${b.role}:${b.label}:${m}`,h=0;for(let S=0;S<k.length;S++)h=h*31+k.charCodeAt(S)>>>0;f.push({...b,id:`el_${h.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Qc=ge(()=>{"use strict"});import{randomBytes as lb}from"crypto";import{mkdir as db,stat as ub,writeFile as pb}from"fs/promises";import{join as gs}from"path";import{gzip as fb}from"zlib";import{promisify as mb}from"util";function gb(t){return gs(Ra(t),"browser")}function hb(t){return gs(gb(t),"screenshots")}function yb(){return new Date().toISOString().replace(/[:.]/g,"-")}function bb(){return lb(3).toString("hex")}async function hs(t,e,n){if(e.length>Zc)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Zc} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=hb(t);await db(r,{recursive:!0});let o=`${yb()}-${bb()}-${n}.png`,s=gs(r,o);await pb(s,e);let{size:i}=await ub(s);return{path:s,bytes:i}}var oI,Zc,el=ge(()=>{"use strict";B();cn();oI=mb(fb);Zc=5*1024*1024});var nl={};Ui(nl,{PlaywrightProvider:()=>ys});function tl(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 ys,rl=ge(()=>{"use strict";jc();Yc();Qc();us();cn();el();ys=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new gr(e)}async open(e){let n=ds(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 hr(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 hr(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 ms(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${tl(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 m=ps(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(m){if(m instanceof Error&&/navigation|net::ERR/i.test(m.message))try{await d()}catch(y){l=y}else l=m}let u=r.url();if(u!==s){let m=ds(u,this.config);if(!m.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:m.reason}}let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await hr(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),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 ms(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${tl(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 hs(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 hs(n,o,r);return s}catch{return null}}}});var et={};Ui(et,{__resetBrowserRegistryForTests:()=>_b,browserProviderActive:()=>vb,closeBrowserProvider:()=>bs,getBrowserProvider:()=>Sb,peekBrowserProvider:()=>kb});function ol(){Promise.resolve(bs()).then(()=>{process.exit(130)})}function sl(){Promise.resolve(bs()).then(()=>{process.exit(143)})}function il(){ve=null}function wb(){yr||(process.on("SIGINT",ol),process.on("SIGTERM",sl),process.on("exit",il),yr=!0)}function al(){yr&&(process.removeListener("SIGINT",ol),process.removeListener("SIGTERM",sl),process.removeListener("exit",il),yr=!1)}async function Sb(t){return ve!==null?ve:(Ze!==null||(Ze=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(rl(),nl)),n=Hc(t),r=new e(n);return wb(),ve=r,Ze=null,r})()),Ze)}async function bs(){if(ve===null)return;let t=ve;ve=null,Ze=null,al(),await t.shutdown()}function vb(){return ve!==null}function kb(){return ve}function _b(){ve=null,Ze=null,al()}var ve,Ze,yr,tt=ge(()=>{"use strict";us();ve=null,Ze=null,yr=!1});N();function Df(){return w.AFK_DEBUG==="1"||w.DEBUG==="1"}function O(...t){Df()&&console.log(...t)}var oe=class extends Error{constructor(e){super(e),this.name="AbortError"}},Le=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},q=class extends Error{constructor(n,r,o,s){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",s?.cause!==void 0&&(this.cause=s.cause)}event;reason;cause};var ot=class extends Error{constructor(n,r,o){super(o??`Budget ceiling reached: $${n.toFixed(4)} cumulative >= $${r.toFixed(4)} limit`);this.runningCostUsd=n;this.maxBudgetUsd=r;this.name="BudgetExceededError"}runningCostUsd;maxBudgetUsd};async function st(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){O(`trace.emit tool_call failed: ${xe(n)}`)}}async function it(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){O(`trace.emit hook_decision failed: ${xe(n)}`)}}async function ze(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){O(`trace.emit subagent_lifecycle failed: ${xe(n)}`)}}async function Bi(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){O(`trace.emit budget failed: ${xe(n)}`)}}async function Hi(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){O(`trace.emit abort failed: ${xe(n)}`)}}async function ji(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){O(`trace.emit compaction failed: ${xe(n)}`)}}async function Ki(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){O(`trace.emit closure failed: ${xe(n)}`)}}async function X(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){O(`trace.emit browser_event failed: ${xe(n)}`)}}async function se(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){O(`trace.emit session_phase failed: ${xe(n)}`)}}function xe(t){return t instanceof Error?t.message:String(t)}import Si from"path";import{appendFileSync as e_,mkdirSync as t_}from"fs";import{dirname as n_}from"path";import yp from"@anthropic-ai/sdk";var Wi="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",Ff="effort-2025-11-24",Lf="claude-cli/1.0.0 (external, cli)",Nf="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function Ln(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Ht(t,e,n){let r=e==="oauth"?{authToken:t}:{apiKey:t};return typeof n=="string"&&n.length>0?{...r,baseURL:n}:r}function he(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${Wi},${Ff}`:Wi,"x-app":"cli","User-Agent":Lf,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Gi(t){return t!=="oauth"?null:[{type:"text",text:Nf}]}import Wf from"@anthropic-ai/sdk";N();var Io=["local","small","medium","large"],Je={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-4-6"},large:{id:"claude-opus-4-8"}},$f={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},Uf="auto",Po="claude-fable-5",Bf={fable:Po},Ro;function Co(t){Ro=t}function To(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function Nn(t,e,n){let r={},o=To(t);o&&(r.id=o);let s=To(e);s&&(r.baseUrl=s);let i=To(n);return i&&(r.apiKey=i),r}function Hf(){return{local:Nn(w.AFK_MODEL_LOCAL,w.AFK_MODEL_LOCAL_BASE_URL,w.AFK_MODEL_LOCAL_API_KEY),small:Nn(w.AFK_MODEL_SMALL,w.AFK_MODEL_SMALL_BASE_URL,w.AFK_MODEL_SMALL_API_KEY),medium:Nn(w.AFK_MODEL_MEDIUM,w.AFK_MODEL_MEDIUM_BASE_URL,w.AFK_MODEL_MEDIUM_API_KEY),large:Nn(w.AFK_MODEL_LARGE,w.AFK_MODEL_LARGE_BASE_URL,w.AFK_MODEL_LARGE_API_KEY)}}function qi(t){let e=Hf(),n={};for(let r of Io){let o=Je[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},c=s?.name;c&&(a.name=c);let l=s?.provider;l&&(a.provider=l);let d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function at(t){return t||Ro||qi()}function ct(t,e=at()){let n=t.trim().toLowerCase();if(!n||n===Uf)return;for(let o of Io){let s=e[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:$f[n]}function Mo(t,e=at()){if(t===void 0)return{id:""};let n=ct(t,e);if(n)return e[n];let r=Bf[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function Ye(t,e=at()){if(t!==void 0)return Mo(t,e).id}function Vi(t,e=at()){if(t===void 0)return;let n=ct(t,e);if(n&&e[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function zi(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of Io){let o=Kf(n[r]);o&&(e[r]=o)}return e}function jf(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="anthropic"||e==="anthropic-direct")return"anthropic";if(e==="openai"||e==="openai-compatible")return"openai"}function $n(t){return typeof t=="string"?t.trim():""}function Kf(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=$n(e.id);if(!n)return;let r={id:n},o=$n(e.name);o&&(r.name=o);let s=jf(e.provider);s&&(r.provider=s);let i=$n(e.baseUrl);i&&(r.baseUrl=i);let a=$n(e.apiKey);return a&&(r.apiKey=a),r}}var Oo={opus:Je.large.id,opus_1m:Je.large.id,sonnet:Je.medium.id,sonnet_1m:Je.medium.id,haiku:Je.small.id,fable:Po};function Ji(t){return t in Oo}function te(t){return Ye(t)}import{randomUUID as Yi}from"node:crypto";async function Xi(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let c=Ln(e),l=Ht(e,c),d=a?a(l):new Wf(l),u=Yi(),p=Yi(),f=he(c,u,p),g=te(n)??n,m={};Object.keys(f).length>0&&(m.headers=f),i&&(m.signal=i);let y=await d.messages.create({model:g,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(m).length>0?m:void 0),b=[];for(let h of y.content)h.type==="text"&&b.push(h.text);let k=b.join("").trim();return k.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),k}import{execFileSync as Qi}from"child_process";import{existsSync as Gf,readFileSync as qf,writeFileSync as Vf}from"fs";import{homedir as Zi,userInfo as ea}from"os";import{join as ta}from"path";var zf="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Jf="https://platform.claude.com/v1/oauth/token",Yf=300*1e3;function le(){let t=na();if(t===void 0)return;let e=ra(t);if(e!==void 0){if(e.expiresAt!==void 0&&e.expiresAt<=Date.now()){process.stderr.write("agent-afk: Claude Code OAuth token in keychain is expired. Run `claude login` to refresh.\n");return}return e.accessToken}}async function Do(){let t=na();if(t===void 0)return;let e=ra(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+Yf)return e.accessToken;if(!e.refreshToken){process.stderr.write("agent-afk: OAuth token expired and no refresh token available. Run `claude login` to refresh.\n");return}let n=await Xf(e.refreshToken);if(!n){process.stderr.write("agent-afk: OAuth token refresh failed. Run `claude login` to refresh.\n");return}try{let r={};try{r=JSON.parse(t)}catch{}let o=r.claudeAiOauth??{};r.claudeAiOauth={...o,accessToken:n.accessToken,expiresAt:n.expiresAt,...n.refreshToken!==void 0?{refreshToken:n.refreshToken}:{}},Qf(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
2
+ `)}}}catch{}}function Pa(){pm(um(),ut())}function zt(t){return typeof t=="string"&&t.length>0&&t.length<=mm&&fm.test(t)}function Jt(t){if(!zt(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return H(ut(),t)}function zn(t){return H(Jt(t),"events.jsonl")}function Ca(t){return H(Jt(t),"session.key")}var lm,fm,mm,B=ge(()=>{"use strict";N();lm=/^[a-zA-Z0-9_-]+$/;fm=/^[A-Za-z0-9_-]+$/,mm=128});import{readFileSync as My}from"node:fs";import{join as Oy}from"path";function Dy(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Uc(t,e){return Dy(e).test(t)}function Ny(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(Fy.has(e))return!0;if(Ly.has(e))return!1}return!1}function Bc(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function $y(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 Uy(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function By(t){try{return My(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function Hy(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 n}function Hc(t){let e=t?.env??w,n=t?.readFileSync??By,r=t?.surface??e.AGENT_SURFACE,o=Ny(e.AFK_BROWSER_HEADLESS,r),s=Bc(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Bc(e.AFK_BROWSER_BLOCKED_DOMAINS),a=Uy(e.AFK_BROWSER_DOM_SNAPSHOTS),c=$y(e.AFK_BROWSER_BACKEND),l={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null},d=e.AFK_BROWSER_CONFIG,u=d!==void 0&&d.trim()!==""?d.trim():Oy(Vt(),"browser.json"),p=n(u);if(p===void 0)return l;let f;try{f=JSON.parse(p)}catch(m){throw new Error(`Failed to parse browser config at ${u}: ${String(m)}`)}if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`Browser config at ${u} must be a JSON object`);let g=Hy(l,f);return g.configPath=u,g}function ds(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(Uc(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Uc(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Fy,Ly,us=ge(()=>{"use strict";N();B();Fy=new Set(["daemon","subagent","telegram","afk"]),Ly=new Set(["repl","interactive","cli"])});import jy from"node:fs";import Ky from"node:path";import{chromium as Wy}from"playwright";function Gy(){try{return"5.3.1"}catch{}try{let t=Ky.resolve(import.meta.dirname,"../../../package.json"),e=jy.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var qy,gr,jc=ge(()=>{"use strict";qy=Gy(),gr=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=Wy.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 o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s={context:o,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,s),o}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),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/${qy}`}}}});import{createHash as Vy}from"crypto";function ps(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of zy)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function Kc(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&Jy.test(t.label))}function Wc(t){return Vy("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Gc(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var zy,Jy,cn=ge(()=>{"use strict";zy=[{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}];Jy=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Yy}from"node:crypto";function Xy(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Qy(t,e,n){return`el_${Yy("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function Zy(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function qc(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function zc(t,e){let n=t.role??"",r=t.name??"";Vc.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])zc(s,e)}async function eb(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},Jc).catch(()=>[])}async function tb(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 m=s.type;m==="checkbox"?l="checkbox":m==="radio"?l="radio":m==="button"||m==="submit"||m==="reset"?l="button":m==="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,g={role:l,name:c,disabled:p};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},Jc).catch(()=>[])}function nb(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function hr(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=nb(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=eb(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,g,m]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],zc(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await tb(t)).filter($=>Vc.has($.role??"")));let k=new Map;for(let v of p){let $=qc(v.name),P=k.get($);(!P||P.bbox.w===0&&v.bbox.w>0)&&k.set($,v)}let h=y.map(v=>({ax:v,dom:k.get(qc(v.name??""))})),S=r?h:h.filter(v=>v.dom?v.dom.bbox.w>0||v.dom.bbox.h>0:!0);S.sort((v,$)=>{let P=v.dom?.bbox.y??0,M=$.dom?.bbox.y??0;if(P!==M)return P-M;let T=v.dom?.bbox.x??0,A=$.dom?.bbox.x??0;return T-A}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=S.slice(0,n).map((v,$)=>{let P=v.ax.role??"generic",M=v.ax.name??"",T=Qy(P,M,$),A=v.dom?.bbox??{x:0,y:0,w:0,h:0},x=v.dom?.type??null,L=null;v.ax.value!==void 0&&v.ax.value!==null&&(L=String(v.ax.value)),v.ax.checked!==void 0&&(L=String(v.ax.checked)),Kc({role:P,kind:x})&&(L="[redacted]");let W={disabled:v.ax.disabled??!1};v.ax.checked!==void 0&&(W.checked=v.ax.checked===!0||v.ax.checked==="mixed"),v.ax.selected!==void 0&&(W.selected=v.ax.selected),v.ax.expanded!==void 0&&(W.expanded=v.ax.expanded);let U;v.dom?.testId?U=`[data-testid="${v.dom.testId}"]`:v.dom?.id&&(U=`#${v.dom.id}`);let V={id:T,role:P,label:Xy(M),kind:x,value:L,state:W,bbox:A};return U!==void 0&&(V.selector=U),V}),R="idle";try{let v=await t.evaluate(()=>document.readyState);v==="loading"?R="loading":v==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=Zy(f),C=`obs_${e.observationCounter.toString(36)}`,F=new Date().toISOString();return{observationId:C,url:g,title:m,textSummary:I,interactive:E,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:F}}var Vc,Jc,Yc=ge(()=>{"use strict";cn();Vc=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Jc="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Xc(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 fs(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Xc(t,s)))).filter(o=>o!==null)}async function rb(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 ms(t,e,n){switch(e.kind){case"element_id":return ob(t,e,n);case"selector":return sb(t,e);case"semantic":return ib(t,e)}}async function ob(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 fs(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function sb(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 fs(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function ib(t,e){return e.role!==void 0?ab(t,e.text,e.role):cb(t,e.text,e)}async function ab(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 fs(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function cb(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 rb(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let m=u[0];return m===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:m.locator.nth(m.index)}}let p=u.slice(0,5),f=[];for(let m=0;m<p.length;m++){let y=p[m];if(y===void 0)continue;let b=await Xc(y.locator,y.index);if(b!==null){let k=`${b.role}:${b.label}:${m}`,h=0;for(let S=0;S<k.length;S++)h=h*31+k.charCodeAt(S)>>>0;f.push({...b,id:`el_${h.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Qc=ge(()=>{"use strict"});import{randomBytes as lb}from"crypto";import{mkdir as db,stat as ub,writeFile as pb}from"fs/promises";import{join as gs}from"path";import{gzip as fb}from"zlib";import{promisify as mb}from"util";function gb(t){return gs(Ra(t),"browser")}function hb(t){return gs(gb(t),"screenshots")}function yb(){return new Date().toISOString().replace(/[:.]/g,"-")}function bb(){return lb(3).toString("hex")}async function hs(t,e,n){if(e.length>Zc)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Zc} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=hb(t);await db(r,{recursive:!0});let o=`${yb()}-${bb()}-${n}.png`,s=gs(r,o);await pb(s,e);let{size:i}=await ub(s);return{path:s,bytes:i}}var oI,Zc,el=ge(()=>{"use strict";B();cn();oI=mb(fb);Zc=5*1024*1024});var nl={};Ui(nl,{PlaywrightProvider:()=>ys});function tl(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 ys,rl=ge(()=>{"use strict";jc();Yc();Qc();us();cn();el();ys=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new gr(e)}async open(e){let n=ds(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 hr(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 hr(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 ms(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${tl(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 m=ps(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(m){if(m instanceof Error&&/navigation|net::ERR/i.test(m.message))try{await d()}catch(y){l=y}else l=m}let u=r.url();if(u!==s){let m=ds(u,this.config);if(!m.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:m.reason}}let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await hr(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),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 ms(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${tl(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 hs(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 hs(n,o,r);return s}catch{return null}}}});var et={};Ui(et,{__resetBrowserRegistryForTests:()=>_b,browserProviderActive:()=>vb,closeBrowserProvider:()=>bs,getBrowserProvider:()=>Sb,peekBrowserProvider:()=>kb});function ol(){Promise.resolve(bs()).then(()=>{process.exit(130)})}function sl(){Promise.resolve(bs()).then(()=>{process.exit(143)})}function il(){ve=null}function wb(){yr||(process.on("SIGINT",ol),process.on("SIGTERM",sl),process.on("exit",il),yr=!0)}function al(){yr&&(process.removeListener("SIGINT",ol),process.removeListener("SIGTERM",sl),process.removeListener("exit",il),yr=!1)}async function Sb(t){return ve!==null?ve:(Ze!==null||(Ze=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(rl(),nl)),n=Hc(t),r=new e(n);return wb(),ve=r,Ze=null,r})()),Ze)}async function bs(){if(ve===null)return;let t=ve;ve=null,Ze=null,al(),await t.shutdown()}function vb(){return ve!==null}function kb(){return ve}function _b(){ve=null,Ze=null,al()}var ve,Ze,yr,tt=ge(()=>{"use strict";us();ve=null,Ze=null,yr=!1});N();function Df(){return w.AFK_DEBUG==="1"||w.DEBUG==="1"}function O(...t){Df()&&console.log(...t)}var oe=class extends Error{constructor(e){super(e),this.name="AbortError"}},Le=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},q=class extends Error{constructor(n,r,o,s){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",s?.cause!==void 0&&(this.cause=s.cause)}event;reason;cause};var ot=class extends Error{constructor(n,r,o){super(o??`Budget ceiling reached: $${n.toFixed(4)} cumulative >= $${r.toFixed(4)} limit`);this.runningCostUsd=n;this.maxBudgetUsd=r;this.name="BudgetExceededError"}runningCostUsd;maxBudgetUsd};async function st(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){O(`trace.emit tool_call failed: ${xe(n)}`)}}async function it(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){O(`trace.emit hook_decision failed: ${xe(n)}`)}}async function ze(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){O(`trace.emit subagent_lifecycle failed: ${xe(n)}`)}}async function Bi(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){O(`trace.emit budget failed: ${xe(n)}`)}}async function Hi(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){O(`trace.emit abort failed: ${xe(n)}`)}}async function ji(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){O(`trace.emit compaction failed: ${xe(n)}`)}}async function Ki(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){O(`trace.emit closure failed: ${xe(n)}`)}}async function X(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){O(`trace.emit browser_event failed: ${xe(n)}`)}}async function se(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){O(`trace.emit session_phase failed: ${xe(n)}`)}}function xe(t){return t instanceof Error?t.message:String(t)}import Si from"path";import{appendFileSync as e_,mkdirSync as t_}from"fs";import{dirname as n_}from"path";import yp from"@anthropic-ai/sdk";var Wi="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",Ff="effort-2025-11-24",Lf="claude-cli/1.0.0 (external, cli)",Nf="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function Ln(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Ht(t,e,n){let r=e==="oauth"?{authToken:t}:{apiKey:t};return typeof n=="string"&&n.length>0?{...r,baseURL:n}:r}function he(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${Wi},${Ff}`:Wi,"x-app":"cli","User-Agent":Lf,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Gi(t){return t!=="oauth"?null:[{type:"text",text:Nf}]}import Wf from"@anthropic-ai/sdk";N();var Io=["local","small","medium","large"],Je={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-4-6"},large:{id:"claude-opus-4-8"}},$f={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},Uf="auto",Po="claude-fable-5",Bf={fable:Po},Ro;function Co(t){Ro=t}function To(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function Nn(t,e,n){let r={},o=To(t);o&&(r.id=o);let s=To(e);s&&(r.baseUrl=s);let i=To(n);return i&&(r.apiKey=i),r}function Hf(){return{local:Nn(w.AFK_MODEL_LOCAL,w.AFK_MODEL_LOCAL_BASE_URL,w.AFK_MODEL_LOCAL_API_KEY),small:Nn(w.AFK_MODEL_SMALL,w.AFK_MODEL_SMALL_BASE_URL,w.AFK_MODEL_SMALL_API_KEY),medium:Nn(w.AFK_MODEL_MEDIUM,w.AFK_MODEL_MEDIUM_BASE_URL,w.AFK_MODEL_MEDIUM_API_KEY),large:Nn(w.AFK_MODEL_LARGE,w.AFK_MODEL_LARGE_BASE_URL,w.AFK_MODEL_LARGE_API_KEY)}}function qi(t){let e=Hf(),n={};for(let r of Io){let o=Je[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},c=s?.name;c&&(a.name=c);let l=s?.provider;l&&(a.provider=l);let d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function at(t){return t||Ro||qi()}function ct(t,e=at()){let n=t.trim().toLowerCase();if(!n||n===Uf)return;for(let o of Io){let s=e[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:$f[n]}function Mo(t,e=at()){if(t===void 0)return{id:""};let n=ct(t,e);if(n)return e[n];let r=Bf[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function Ye(t,e=at()){if(t!==void 0)return Mo(t,e).id}function Vi(t,e=at()){if(t===void 0)return;let n=ct(t,e);if(n&&e[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function zi(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of Io){let o=Kf(n[r]);o&&(e[r]=o)}return e}function jf(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="anthropic"||e==="anthropic-direct")return"anthropic";if(e==="openai"||e==="openai-compatible")return"openai"}function $n(t){return typeof t=="string"?t.trim():""}function Kf(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=$n(e.id);if(!n)return;let r={id:n},o=$n(e.name);o&&(r.name=o);let s=jf(e.provider);s&&(r.provider=s);let i=$n(e.baseUrl);i&&(r.baseUrl=i);let a=$n(e.apiKey);return a&&(r.apiKey=a),r}}var Oo={opus:Je.large.id,opus_1m:Je.large.id,sonnet:Je.medium.id,sonnet_1m:Je.medium.id,haiku:Je.small.id,fable:Po};function Ji(t){return t in Oo}function te(t){return Ye(t)}import{randomUUID as Yi}from"node:crypto";async function Xi(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let c=Ln(e),l=Ht(e,c),d=a?a(l):new Wf(l),u=Yi(),p=Yi(),f=he(c,u,p),g=te(n)??n,m={};Object.keys(f).length>0&&(m.headers=f),i&&(m.signal=i);let y=await d.messages.create({model:g,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(m).length>0?m:void 0),b=[];for(let h of y.content)h.type==="text"&&b.push(h.text);let k=b.join("").trim();return k.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),k}import{execFileSync as Qi}from"child_process";import{existsSync as Gf,readFileSync as qf,writeFileSync as Vf}from"fs";import{homedir as Zi,userInfo as ea}from"os";import{join as ta}from"path";var zf="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Jf="https://platform.claude.com/v1/oauth/token",Yf=300*1e3;function le(){let t=na();if(t===void 0)return;let e=ra(t);if(e!==void 0){if(e.expiresAt!==void 0&&e.expiresAt<=Date.now()){process.stderr.write("agent-afk: Claude Code OAuth token in keychain is expired. Run `claude login` to refresh.\n");return}return e.accessToken}}async function Do(){let t=na();if(t===void 0)return;let e=ra(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+Yf)return e.accessToken;if(!e.refreshToken){process.stderr.write("agent-afk: OAuth token expired and no refresh token available. Run `claude login` to refresh.\n");return}let n=await Xf(e.refreshToken);if(!n){process.stderr.write("agent-afk: OAuth token refresh failed. Run `claude login` to refresh.\n");return}try{let r={};try{r=JSON.parse(t)}catch{}let o=r.claudeAiOauth??{};r.claudeAiOauth={...o,accessToken:n.accessToken,expiresAt:n.expiresAt,...n.refreshToken!==void 0?{refreshToken:n.refreshToken}:{}},Qf(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
3
3
  `)}return n.accessToken}function na(){if(process.platform==="darwin")try{return Qi("security",["find-generic-password","-s","Claude Code-credentials","-a",ea().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=ta(Zi(),".claude",".credentials.json");if(!Gf(t))return;try{return qf(t,"utf-8")}catch{return}}}function ra(t){let e;try{e=JSON.parse(t)}catch{return}if(typeof e!="object"||e===null)return;let n=e.claudeAiOauth;if(typeof n!="object"||n===null)return;let r=n,o=r.accessToken;if(typeof o!="string"||o.length===0)return;let s={accessToken:o},i=r.refreshToken;typeof i=="string"&&i.length>0&&(s.refreshToken=i);let a=r.expiresAt;return typeof a=="number"&&(s.expiresAt=a),s}async function Xf(t){try{let e=await fetch(Jf,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:zf})});if(!e.ok)return;let n=await e.json(),r=n.access_token,o=n.expires_in;if(typeof r!="string"||typeof o!="number")return;let s=n.refresh_token;return{accessToken:r,expiresAt:Date.now()+o*1e3,...typeof s=="string"&&s.length>0?{refreshToken:s}:{}}}catch{return}}function jt(t){if(!t||t.length<3)return"token:(unknown)";try{let n=t.split(".");if(n.length<2)throw new Error("not a JWT");let r=Buffer.from(n[1],"base64url").toString("utf-8"),o=JSON.parse(r),s=typeof o.email=="string"&&o.email||typeof o.sub=="string"&&o.sub||typeof o.account_id=="string"&&o.account_id||typeof o.preferred_username=="string"&&o.preferred_username;if(s)return s}catch{}return`token:${t.length>=8?t.slice(-8):t}`}function Qf(t){if(process.platform==="darwin")Qi("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",ea().username,"-w",t],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let e=ta(Zi(),".claude",".credentials.json");Zf(e,t)}}function Zf(t,e){Vf(t,e,{encoding:"utf-8",mode:384})}import{randomUUID as pp}from"node:crypto";function ye(t){return t==="bypassPermissions"||t==="autonomous"}N();var em="1h";function Un(t){if(typeof t?.baseUrl=="string"&&t.baseUrl.length>0)return!1;let e=w.AFK_DISABLE_PROMPT_CACHE;if(e===void 0||e.length===0)return!0;let n=e.toLowerCase();return!(n==="1"||n==="true"||n==="yes"||n==="on")}function Bn(){let t=w.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":t==="1h"?"1h":em}function oa(t,e){if(t.length===0)return t;let n=t[t.length-1],r=ia(n,e);return r===n?t:[...t.slice(0,-1),r]}function sa(t,e){if(t.length===0)return t;let n=t[t.length-1],r=tm(n,e);return r===n?t:[...t.slice(0,-1),r]}function tm(t,e){let n=t.content;if(typeof n=="string")return n.length===0?t:{...t,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:e}}]};if(!Array.isArray(n)||n.length===0)return t;let r=n[n.length-1],o=ia(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function ia(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}var Fo=["## Plan mode is active","","File and memory write tools (`write_file`, `edit_file`, `memory_update`, `procedure_write`) are refused at the hook layer.","`bash` runs for read-only investigation (git status/log/diff, ls, cat, grep, find \u2014 chained or not); state-mutating bash (file writes, rm, installs, commits, pushes) is refused while planning. The user has asked you to plan, not yet to act \u2014 exit plan mode to make changes.","Treat this turn as planning work.","","Traverse the shape that matches the work \u2014 skip steps the terrain already covers, do not skip steps the terrain hides:",""," unknown field \u2192 ground the current terrain \u2192 gather missing codebase context \u2192"," research missing external context \u2192 reveal chaos / constraints / risks \u2192"," name the failure geometry \u2192 form a candidate plan \u2192 apply adversarial pressure \u2192 embody the final plan","","Reach for these skills (invoke via the `skill` tool) when the cost of skipping exceeds the cost of dispatching:"," - `ground-state` \u2014 survey git, infra, memory before non-trivial work"," - `gather` \u2014 parallel context-gathering for a code area"," - `research` \u2014 parallel external + local context for the current task"," - `devils-advocate` \u2014 generate alternatives and rank them before committing"," - `shadow-verify` \u2014 independently re-derive load-bearing claims","","Do not declare readiness silently. When the plan is ready, state: chosen approach, risks named, and alternatives considered.","","Then, IF the task requires implementation (writing code or files), call the `exit_plan_mode` tool to present your plan. The user picks how to proceed (approve and implement, or keep planning). After calling it, END YOUR TURN \u2014 on approval you will receive a separate instruction to save the plan to a file and implement it. Do NOT use `ask_question` to ask whether the plan is OK; that is exactly what `exit_plan_mode` does \u2014 use `ask_question` only to resolve open requirement questions first. For research / read-only tasks that need no code changes, do NOT call `exit_plan_mode` \u2014 just answer.","","Manual fallbacks remain: the user can exit with `/plan off` (same save-and-implement handoff), and Shift+Tab advances the permission-mode ring without saving or implementing. Keep the plan concrete and complete enough to act on directly."].join(`
4
4
  `);function aa(t){return t!=="plan"?null:{type:"text",text:Fo}}var Lo=["## AFK mode is active","","The operator is away from keyboard. Your channel to them is Telegram via the `send_telegram` tool \u2014 not this transcript, which no one is watching live. At the end of each turn, push your terminal state (Done / Blocked / Asking) to Telegram so the operator can review asynchronously.","","Posture \u2014 bounded autonomy, not unchecked action:"," - Proceed autonomously on reversible work. Do not stop to confirm actions you are already authorized to take and can undo (edits, reads, tests, local commits, non-force pushes, installs)."," - At a one-way door \u2014 anything irreversible, externally visible, credential- or payment-touching, or where multiple readings lead to materially different work \u2014 do NOT guess. Push a concise Asking summary to Telegram naming the decision and your recommended default, then stop and end the turn in the Asking state."," - A mechanical gate refuses high-risk and irreversible operations at the hook layer regardless of this text. Treat a gate refusal as a signal to surface the decision to the operator, not an obstacle to work around.","","Communication discipline:"," - Batch updates. Send a Telegram message at terminal state (and at a genuinely blocking fork), not a play-by-play \u2014 the operator gets a push notification for every message."," - Keep pushes short and scannable: what happened, what changed, what (if anything) you need. Never paste raw tool output, logs, secrets, or full file contents into a push.","","Exit: the operator returns and runs `/afk off` (or Shift+Tab) to restore default permissions and terminal-channel interaction."].join(`
5
5
  `);function ca(t){return t!=="autonomous"?null:{type:"text",text:Lo}}import{z}from"zod";import{mkdir as au,appendFile as cu}from"fs/promises";import{join as Xs}from"path";var la={"audit-fit":{"01-skill-inspector.md":`# Skill Inspector
@@ -1049,7 +1049,7 @@ ${e}`:`\u{1F3F7}\uFE0F Named: ${t} (saves on first turn)`}function sn(t){if(!t)r
1049
1049
  ?`,"m");if(!r.test(n))return!1;let o=n.replace(r,"");return vr(t,o,384),!0}function Tl(t,e){if(!dn(t))return;let r=Sr(t,"utf-8").match(new RegExp(`^${wr(e)}=(.*)$`,"m"));return r?r[1]:void 0}function Rl(t){let e={};if(!dn(t))return e;let n=Sr(t,"utf-8");for(let r of n.split(`
1050
1050
  `)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s<=0)continue;let i=o.slice(0,s).trim(),a=o.slice(s+1);e[i]=a}return e}N();var hw=new Set(["HOME","PATH","SHELL","PAGER","NODE_ENV","CI","VITEST","DEBUG","FORCE_COLOR","NO_COLOR","AGENT_SURFACE","AFK_SESSION_ID","NO_UPDATE_NOTIFIER","SCRIPT","ASCIINEMA_REC"]),yw=new Set(["AFK_MODEL_SMALL_BASE_URL","AFK_MODEL_MEDIUM_BASE_URL","AFK_MODEL_LARGE_BASE_URL","AFK_LOCAL_BASE_URL","AFK_OPENAI_BASE_URL","AFK_SYSTEM_PROMPT","AFK_DAEMON_TASK","AFK_DAEMON_TASK_ID","AFK_DAEMON_CWD","AFK_DAEMON_HOST","AFK_BROWSER_ALLOWED_DOMAINS","AFK_BROWSER_BLOCKED_DOMAINS","AFK_BROWSER_CONFIG","AFK_ALLOW_PROJECT_MCP","AFK_INTERNAL","AFK_WORKTREE_BASE","AFK_WORKTREE_BRANCH_PREFIX","AFK_TELEGRAM_ALLOWED_CHAT_IDS","AFK_TELEGRAM_NOTIFY_MODE","AFK_TELEGRAM_PRIMARY_CHAT_ID","AFK_HOME","AFK_STATE_DIR","AFK_FRAMEWORK_DIR","TELEGRAM_DATA_DIR","AFK_TELEGRAM_CWD"]);function kr(t){let e=Fn(t);return e?hw.has(t)?"non-config":e.secret?"secret":yw.has(t)||t.endsWith("_BASE_URL")?"protected":"settable":"unknown"}function Il(t,e){if(e.includes(`
1051
1051
  `))return{ok:!1,error:`value for ${t.name} must not contain newlines`};switch(t.type){case"number":{let n=Number(e);return Number.isFinite(n)?{ok:!0,value:e.trim()}:{ok:!1,error:`${t.name} expects a number, got ${JSON.stringify(e)}`}}case"boolean":{let n=e.trim().toLowerCase();return["true","false","1","0","yes","no","on","off"].includes(n)?{ok:!0,value:n}:{ok:!1,error:`${t.name} expects a boolean (true/false/1/0/yes/no/on/off), got ${JSON.stringify(e)}`}}case"json":{try{JSON.parse(e)}catch{return{ok:!1,error:`${t.name} expects valid JSON`}}return{ok:!0,value:e}}default:return{ok:!0,value:e}}}var bw=[{path:"model",tier:"agent",type:"string",description:"Default model id / alias."},{path:"models.local",tier:"agent",type:"string",description:"Local-tier model id (OpenAI-compatible shim: Ollama, LM Studio, vLLM, MLX)."},{path:"models.small",tier:"agent",type:"string",description:"Small-tier model id."},{path:"models.medium",tier:"agent",type:"string",description:"Medium-tier model id."},{path:"models.large",tier:"agent",type:"string",description:"Large-tier model id."},{path:"maxTokens",tier:"agent",type:"number",clamp:{min:1,max:1e6,integer:!0},description:"Max tokens per turn."},{path:"temperature",tier:"agent",type:"number",clamp:{min:0,max:2},description:"Sampling temperature."},{path:"autoRouting.interactive",tier:"agent",type:"boolean",description:"Auto-route model in the REPL."},{path:"autoRouting.chat",tier:"agent",type:"boolean",description:"Auto-route model for chat."},{path:"autoRouting.telegram",tier:"agent",type:"boolean",description:"Auto-route model for Telegram."},{path:"autoRouting.daemon",tier:"agent",type:"boolean",description:"Auto-route model for the daemon."},{path:"telegram.notify.mode",tier:"human",type:"enum",enumValues:["primary","broadcast","custom"],description:"Telegram notify routing mode (human-tier: notification-redirect vector)."},{path:"telegram.notify.primaryChatId",tier:"human",type:"number",clamp:{min:-1e15,max:1e15,integer:!0},description:"Primary Telegram chat id (human-tier: notification-redirect vector)."},{path:"telegram.notify.targets",tier:"human",type:"number-array",description:"Custom Telegram target chat ids (human-tier: notification-redirect vector)."},{path:"telegram.verifyDone",tier:"human",type:"boolean",description:`Opt-in AFK "Done" verification gate (human-tier: a self-honesty check on the agent's own completion reporting \u2014 the agent must not be able to disable it on its own config, same rationale as enableShellHooks/permissionMode).`},{path:"interactive.worktreeAutoname",tier:"agent",type:"boolean",description:"Auto-name worktrees."},{path:"interactive.suggestGhost",tier:"agent",type:"boolean",description:"Ghost-text suggestions in the REPL."},{path:"updatePolicy",tier:"human",type:"enum",enumValues:["notify","auto","off"],description:"Self-update policy (human-tier: auto self-update is scope-widening)."},{path:"autoResumeOnUsageLimit",tier:"agent",type:"boolean",description:"Auto-resume after a usage-limit pause."},{path:"bgSummaries",tier:"agent",type:"boolean",description:"Background summarisation."},{path:"maxSummaryCallsPerSession",tier:"agent",type:"number",clamp:{min:1,max:500,integer:!0},description:"Cap on summary calls per session."},{path:"systemPrompt",tier:"human",type:"string",description:"Operator system-prompt overlay."},{path:"permissionMode",tier:"human",type:"enum",enumValues:["default","plan","autonomous","bypassPermissions"],description:"Session permission mode for afk chat/interactive (human-tier: privilege-escalation vector). Unset \u2192 bypassPermissions (new-install default); set `default` to re-enable path containment + the approval prompt."},{path:"enableShellHooks",tier:"human",type:"boolean",description:"Enable shell hooks (trust gate)."},{path:"interactive.worktreeBranchPrefix",tier:"human",type:"string",description:"Worktree branch prefix (git-flag sensitive)."},{path:"interactive.worktreeBase",tier:"human",type:"string",description:"Worktree base ref (git-flag sensitive)."},{path:"daemon.task",tier:"human",type:"string",description:"Daemon task prompt."},{path:"daemon.taskId",tier:"human",type:"string",description:"Daemon task id."}],Pl=new Map(bw.map(t=>[t.path,t]));function Cl(t){return Pl.get(t)}function As(t){let e=Pl.get(t);return e?e.tier:"unknown"}function Ml(t,e){switch(t.type){case"boolean":{if(typeof e=="boolean")return{ok:!0,value:e};if(typeof e=="string"){let n=e.trim().toLowerCase();if(["true","1","yes","on"].includes(n))return{ok:!0,value:!0};if(["false","0","no","off"].includes(n))return{ok:!0,value:!1}}return{ok:!1,error:`${t.path} expects a boolean`}}case"number":{let n=typeof e=="number"?e:typeof e=="string"?Number(e):NaN;return Number.isFinite(n)?t.clamp?t.clamp.integer&&!Number.isInteger(n)?{ok:!1,error:`${t.path} expects an integer`}:{ok:!0,value:Math.min(t.clamp.max,Math.max(t.clamp.min,n))}:{ok:!0,value:n}:{ok:!1,error:`${t.path} expects a number`}}case"enum":return typeof e=="string"&&t.enumValues?.includes(e)?{ok:!0,value:e}:{ok:!1,error:`${t.path} expects one of: ${t.enumValues?.join(", ")}`};case"number-array":{let n;if(Array.isArray(e))n=e;else if(typeof e=="string")n=e.split(",").map(o=>o.trim()).filter(o=>o.length>0).map(o=>Number(o));else return{ok:!1,error:`${t.path} expects an array of numbers`};let r=[];for(let o of n){let s=typeof o=="number"?o:Number(o);if(!Number.isFinite(s))return{ok:!1,error:`${t.path} contains a non-number`};r.push(s)}return{ok:!0,value:r}}default:return typeof e!="string"?{ok:!1,error:`${t.path} expects a string`}:e.trim().length===0?{ok:!1,error:`${t.path} must not be empty`}:{ok:!0,value:e}}}function Ol(t,e){let n=t;for(let r of e.split(".")){if(n===null||typeof n!="object")return;n=n[r]}return n}function Dl(t,e,n){let r=e.split("."),o=t;for(let s=0;s<r.length-1;s++){let i=r[s],a=o[i];(a===null||typeof a!="object"||Array.isArray(a))&&(o[i]={}),o=o[i]}o[r[r.length-1]]=n}function Fl(t,e){let n=e.split("."),r=[t],o=t;for(let i=0;i<n.length-1;i++){let a=n[i],c=o[a];if(c===null||typeof c!="object"||Array.isArray(c))return!1;o=c,r.push(o)}let s=n[n.length-1];if(!(s in o))return!1;delete o[s];for(let i=r.length-1;i>=1;i--){let a=r[i];if(Object.keys(a).length===0){let c=n[i-1];delete r[i-1][c]}else break}return!0}var pn="effective on the next session/daemon restart; the current session is unchanged",un=class extends Error{constructor(e){super(`unknown config key: ${e}`),this.name="UnknownKeyError"}},xs=class extends Error{constructor(e){super(`${e} is a process/inherited env var and is not afk-configurable`),this.name="NonConfigKeyError"}},Ts=class extends Error{constructor(e){super(`${e} holds a credential; the agent cannot set it. A human must run \`afk config env set ${e}\` (the value is entered masked and never enters the model context).`),this.name="SecretWriteRefused"}},Rs=class extends Error{constructor(e){super(`${e} controls identity, safety, capability, autonomous runs, request routing, or where AFK's own state lives; the agent cannot set it. A human must run \`afk config env set ${e}\`.`),this.name="ProtectedEnvKeyRefused"}},Is=class extends Error{constructor(e){super(`${e} is human-gated (prompt/hooks/identity); the agent cannot set it. A human must run \`afk config set ${e}\`.`),this.name="HumanOnlyKeyRefused"}},_r=class extends Error{constructor(e){super(e),this.name="ConfigValidationError"}},Er=class extends Error{constructor(e){super(`refusing to write: existing ${e} is not valid JSON (fix or remove it by hand first)`),this.name="MalformedConfigError"}};function Ps(t){return t===void 0||t.length===0?"<unset>":t.length<=4?"set (****)":`set (****${t.slice(-4)})`}function Ar(t){return t?.filePath??Ho()}function Nl(t,e,n){let r=kr(t);if(r==="unknown")throw new un(t);if(r==="non-config")throw new xs(t);if(r==="secret"&&!e)throw new Ts(t);if(r==="protected"&&!n)throw new Rs(t);return r}function $l(t,e,n){let r=Nl(t,n?.allowSecret,n?.allowProtected),o=Fn(t),s=Il(o,e);if(!s.ok)throw new _r(s.error);let i=Ar(n);return Al(i,t,s.value),{key:t,class:r,persistedTo:i,display:r==="secret"?Ps(s.value):s.value}}function Ul(t,e){let n=Nl(t,e?.allowSecret,e?.allowProtected),r=Ar(e),o=xl(r,t);return{key:t,class:n,removed:o,persistedTo:r}}function Bl(t,e){let n=kr(t);if(n==="unknown")throw new un(t);let r=Ar(e),o=Tl(r,t),s=xo(t),i=n==="secret"?o!==void 0?Ps(o):void 0:o;return{key:t,class:n,persisted:i,activeInProcess:s}}function Hl(t){let e=Ar(t),n=Rl(e),r=[];for(let o of Dn){let s=o.name,i=kr(s),a=n[s],c=xo(s);if(!t?.all&&a===void 0&&!c)continue;let l=i==="secret"?a!==void 0?Ps(a):void 0:a;r.push({key:s,class:i,persisted:l,activeInProcess:c})}return r}function xr(t){return t?.filePath??ft()}function Tr(t){if(!Ll(t))return{};let e;try{e=JSON.parse(ww(t,"utf-8"))}catch{throw new Er(t)}if(e===null||typeof e!="object"||Array.isArray(e))throw new Er(t);return e}function jl(t,e){if(Ll(t))try{Sw(t,`${t}.bak`),vw(`${t}.bak`,384)}catch{}vr(t,JSON.stringify(e,null,2)+`
1052
- `,384)}function Kl(t,e){let n=As(t);if(n==="unknown")throw new un(t);if(n==="human"&&!e)throw new Is(t);return n}function Wl(t,e,n){let r=Kl(t,n?.allowHumanOnly),o=Cl(t),s=Ml(o,e);if(!s.ok)throw new _r(s.error);let i=xr(n),a=Tr(i);return Dl(a,t,s.value),jl(i,a),{path:t,class:r,value:s.value,persistedTo:i}}function Gl(t,e){let n=Kl(t,e?.allowHumanOnly),r=xr(e),o=Tr(r),s=Fl(o,t);return s&&jl(r,o),{path:t,class:n,removed:s,persistedTo:r}}function ql(t,e){let n=As(t),r=xr(e),o=Tr(r);return{path:t,class:n,value:Ol(o,t)}}function Vl(t){return Tr(xr(t))}function zl(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Jl(t){return t==="env"||t==="config"?t:void 0}function Ce(t){return{content:t,isError:!0}}var Yl=async t=>{let e=zl(t);if(!e)return Ce("config_get: expected an object input");let n=Jl(e.target);if(!n)return Ce("config_get: `target` must be 'env' or 'config'");let r=typeof e.key=="string"?e.key:void 0,o=e.all===!0;try{if(n==="env"){if(r){let s=Bl(r);return{content:JSON.stringify(s,null,2)}}return{content:JSON.stringify(Hl({all:o}),null,2)}}if(r){let s=ql(r);return{content:JSON.stringify(s,null,2)}}return{content:JSON.stringify(Vl(),null,2)}}catch(s){return Ce(`config_get: ${s.message}`)}},Xl=async t=>{let e=zl(t);if(!e)return Ce("config_set: expected an object input");let n=Jl(e.target);if(!n)return Ce("config_set: `target` must be 'env' or 'config'");let r=typeof e.key=="string"?e.key:void 0;if(!r)return Ce("config_set: `key` is required");let o=e.action==="unset"?"unset":"set",s=e.value;try{if(o==="unset"){if(n==="env"){let c=Ul(r);return{content:c.removed?`Removed ${c.key} from afk.env (${c.persistedTo}). ${pn}.`:`${c.key} was not set in afk.env; nothing to remove.`}}let a=Gl(r);return{content:a.removed?`Removed ${a.path} from afk.config.json (${a.persistedTo}). ${pn}.`:`${a.path} was not set in afk.config.json; nothing to remove.`}}if(s==null)return Ce(`config_set: \`value\` is required to set ${r}`);if(n==="env"){if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")return Ce("config_set: env values must be a string, number, or boolean");let a=$l(r,String(s));return{content:`Set ${a.key} = ${a.display} in afk.env (${a.persistedTo}). ${pn}.`}}let i=Wl(r,s);return{content:`Set ${i.path} = ${JSON.stringify(i.value)} in afk.config.json (${i.persistedTo}). ${pn}.`}}catch(i){return Ce(`config_set: ${i.message}`)}};var _t={action:"decline"},Cs=class{handler=null;queue=Promise.resolve();queueDepth=0;install(e){this.handler=e}uninstall(){this.handler=null}pendingCount(){return this.queueDepth}route(e,n){if(n.signal.aborted)return Promise.resolve(_t);this.queueDepth+=1;let r,o=new Promise(i=>{r=i}),s=this.handler;return this.queue=this.queue.then(async()=>{try{if(n.signal.aborted){r(_t);return}if(!s){r(_t);return}let i,a=new Promise(c=>{i=()=>c(_t),n.signal.addEventListener("abort",i,{once:!0})});try{let c=await Promise.race([s(e,n).catch(()=>_t),a]);r(c)}finally{n.signal.removeEventListener("abort",i)}}finally{this.queueDepth-=1,r(_t)}}).catch(()=>{}),o}},nt=new Cs;var Ql=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let n=t,r=n.question;if(typeof r!="string"||r.trim()==="")return{content:"Invalid input: question must be a non-empty string",isError:!0};let o=new Set(["text","confirm","choice","multi_choice","number"]),s=n.type??"text";if(typeof s!="string"||!o.has(s))return{content:"Invalid input: type must be one of: text, confirm, choice, multi_choice, number",isError:!0};if(s==="choice"||s==="multi_choice"){let f=n.choices;if(!Array.isArray(f)||f.length===0)return{content:`Invalid input: choices array is required and must be non-empty for type "${s}"`,isError:!0};if(f.length>100)return{content:`Invalid input: choices array must not exceed 100 items, got ${f.length}`,isError:!0};for(let g of f)if(typeof g!="string")return{content:"Invalid input: all choices must be strings",isError:!0}}let i=n.min,a=n.max;if(i!==void 0&&(typeof i!="number"||!Number.isFinite(i)))return{content:"Invalid input: min must be a finite number",isError:!0};if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)))return{content:"Invalid input: max must be a finite number",isError:!0};if(i!==void 0&&a!==void 0&&i>a)return{content:`Invalid input: min (${i}) must be \u2264 max (${a})`,isError:!0};let c=n.min_length,l=n.max_length;if(c!==void 0&&typeof c!="number")return{content:"Invalid input: min_length must be a number",isError:!0};if(l!==void 0&&typeof l!="number")return{content:"Invalid input: max_length must be a number",isError:!0};if((c!==void 0||l!==void 0)&&s!=="text")return{content:`Invalid input: min_length/max_length are only valid for type "text", got "${s}"`,isError:!0};if(n.allow_custom!==void 0&&s!=="choice"&&s!=="multi_choice")return{content:`Invalid input: allow_custom is only valid for type "choice" or "multi_choice", got "${s}"`,isError:!0};let d={serverName:"agent",message:r.trim(),origin:"agent",type:s,...n.choices!==void 0&&{choices:n.choices},...n.context!==void 0&&typeof n.context=="string"&&{context:n.context},...n.default!==void 0&&{questionDefault:n.default},...c!==void 0&&{minLength:c},...l!==void 0&&{maxLength:l},...i!==void 0&&{min:i},...a!==void 0&&{max:a},...n.allow_skip!==void 0&&{allowSkip:!!n.allow_skip},...n.allow_custom!==void 0&&{allowCustom:!!n.allow_custom}},u=await nt.route(d,{signal:e}),p=u.action==="decline"||u.action==="cancel";return{content:JSON.stringify(u),...p&&{isError:!0,failureClass:"elicitation-declined"}}};N();function Rr(t){if(t instanceof Error&&t.name==="TimeoutError")return"timeout";let e=t instanceof Error?t.message:String(t);return/Timeout\s+\d+\s*ms exceeded/i.test(e)?"timeout":void 0}var kw=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"];function ke(t){return kw.some(e=>t.includes(e))}function _e(t){return t.includes("Executable doesn't exist")?"browser tools require the Playwright chromium binary. Install via: pnpm exec playwright install chromium.":"browser tools require the optional `playwright` peer dependency. Install via: pnpm add playwright (then pnpm exec playwright install chromium). Or pick a different tool."}var Zl=["load","domcontentloaded","networkidle"];function _w(t){if(!t||typeof t!="object")return{error:"browser_open: input must be an object"};let e=t,n=e.url;if(typeof n!="string"||n.length===0)return{error:'browser_open: "url" is required and must be a non-empty string'};let r;try{r=new URL(n)}catch{return{error:`browser_open: "${n}" is not a valid absolute URL`}}if(r.protocol!=="http:"&&r.protocol!=="https:")return{error:`browser_open: protocol "${r.protocol}" is not supported (http/https only)`};let o;if(e.wait_for!==void 0){if(!Zl.includes(e.wait_for))return{error:`browser_open: "wait_for" must be one of ${Zl.map(a=>`"${a}"`).join(", ")} (got ${JSON.stringify(e.wait_for)})`};o=e.wait_for}let s;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_open: "screenshot" must be a boolean'};s=e.screenshot}let i;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'browser_open: "timeout_ms" must be a positive finite number'};i=e.timeout_ms}return{url:r.toString(),waitFor:o,screenshot:s,timeoutMs:i}}function Ew(t={}){return async(e,n,r)=>{if(n.aborted){let c=n.reason;return{content:`browser_open aborted: ${c instanceof Error?c.message:String(c??"aborted")}`,isError:!0,failureClass:"abort"}}let o=_w(e);if("error"in o)return{content:o.error,isError:!0};let s=w.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:c}=await Promise.resolve().then(()=>(tt(),et));i=await c()}}catch(c){let l=c instanceof Error?c.message:String(c);return ke(l)?{content:_e(l),isError:!0}:{content:`browser_open failed to get provider: ${l}`,isError:!0}}let a=Date.now();try{let c=await i.open({sessionId:s,url:o.url,waitFor:o.waitFor,screenshot:o.screenshot,timeoutMs:o.timeoutMs}),l=Date.now()-a;if("outcome"in c&&c.outcome==="blocked_by_policy")return X(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:l}),{content:`browser_open blocked: ${c.reason}`,isError:!0,failureClass:"policy-refusal"};let d=c;return X(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:d.url,status:"ok",durationMs:l,...d.screenshotPath!==null?{screenshotPath:d.screenshotPath}:{}}),{content:JSON.stringify(d,null,2)}}catch(c){let l=Date.now()-a,d=c instanceof Error?c.message:String(c);X(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:l,error:{reason:d,recoverable:!1}});let u=Rr(c);return{content:`browser_open failed: ${d}`,isError:!0,...u?{failureClass:u}:{}}}}}var ed=Ew();N();function Aw(t){if(t!=null&&typeof t!="object")return{error:"browser_observe: input must be an object or omitted"};if(!t)return{};let e=t,n;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_observe: "screenshot" must be a boolean'};n=e.screenshot}let r;if(e.include_hidden!==void 0){if(typeof e.include_hidden!="boolean")return{error:'browser_observe: "include_hidden" must be a boolean'};r=e.include_hidden}let o;if(e.max_elements!==void 0){if(typeof e.max_elements!="number"||!Number.isFinite(e.max_elements)||e.max_elements<=0||!Number.isInteger(e.max_elements))return{error:'browser_observe: "max_elements" must be a positive integer'};o=e.max_elements}return{screenshot:n,includeHidden:r,maxElements:o}}function xw(t={}){return async(e,n,r)=>{if(n.aborted){let c=n.reason;return{content:`browser_observe aborted: ${c instanceof Error?c.message:String(c??"aborted")}`,isError:!0}}let o=Aw(e);if("error"in o)return{content:o.error,isError:!0};let s=w.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:c}=await Promise.resolve().then(()=>(tt(),et));i=await c()}}catch(c){let l=c instanceof Error?c.message:String(c);return ke(l)?{content:_e(l),isError:!0}:{content:`browser_observe failed to get provider: ${l}`,isError:!0}}let a=Date.now();try{let c=await i.observe({sessionId:s,screenshot:o.screenshot,includeHidden:o.includeHidden,maxElements:o.maxElements}),l=Date.now()-a;return X(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:c.url,urlAfter:c.url,status:"ok",durationMs:l,...c.screenshotPath!==null?{screenshotPath:c.screenshotPath}:{}}),{content:JSON.stringify(c,null,2)}}catch(c){let l=Date.now()-a,d=c instanceof Error?c.message:String(c);return X(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:l,error:{reason:d,recoverable:!1}}),{content:`browser_observe failed: ${d}`,isError:!0}}}}var td=xw();cn();N();var nd=["click","fill","press","select","hover","scroll_to","wait_for"],rd=["semantic","element_id","selector"];function Tw(t){if(!t||typeof t!="object")return{error:"browser_act: input must be an object"};let e=t;if(typeof e.action!="string")return{error:'browser_act: "action" is required and must be a string'};if(!nd.includes(e.action))return{error:`browser_act: "action" must be one of ${nd.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(e.action)})`};let n=e.action,r=e.target;if(!r||typeof r!="object")return{error:'browser_act: "target" is required and must be an object'};let o=r;if(typeof o.kind!="string"||!rd.includes(o.kind))return{error:`browser_act: "target.kind" must be one of ${rd.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(o.kind)})`};let s,i=o.kind;if(i==="semantic"){if(typeof o.text!="string"||o.text.length===0)return{error:'browser_act: target.kind=semantic requires "target.text" (non-empty string)'};s={kind:"semantic",text:o.text,...typeof o.role=="string"&&o.role.length>0?{role:o.role}:{}}}else if(i==="element_id"){if(typeof o.element_id!="string"||o.element_id.length===0)return{error:'browser_act: target.kind=element_id requires "target.element_id" (non-empty string)'};s={kind:"element_id",elementId:o.element_id}}else{if(typeof o.selector!="string"||o.selector.length===0)return{error:'browser_act: target.kind=selector requires "target.selector" (non-empty string)'};s={kind:"selector",selector:o.selector}}let a;if(e.value!==void 0){if(typeof e.value!="string")return{error:'browser_act: "value" must be a string when provided'};a=e.value}let c;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'browser_act: "timeout_ms" must be a positive finite number'};c=e.timeout_ms}let l;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_act: "screenshot" must be a boolean'};l=e.screenshot}return{action:n,target:s,value:a,timeoutMs:c,screenshot:l}}function Rw(t,e){let n=t.role?`"${t.text}" (role: ${t.role})`:`"${t.text}"`;return[`browser_act: ambiguous target \u2014 ${e.length} elements matched ${n}.`,'Retry with target.kind="element_id" using one of the following:',...e.map(o=>` id=${o.id} role=${o.role} label=${o.label}`)].join(`
1052
+ `,384)}function Kl(t,e){let n=As(t);if(n==="unknown")throw new un(t);if(n==="human"&&!e)throw new Is(t);return n}function Wl(t,e,n){let r=Kl(t,n?.allowHumanOnly),o=Cl(t),s=Ml(o,e);if(!s.ok)throw new _r(s.error);let i=xr(n),a=Tr(i);return Dl(a,t,s.value),jl(i,a),{path:t,class:r,value:s.value,persistedTo:i}}function Gl(t,e){let n=Kl(t,e?.allowHumanOnly),r=xr(e),o=Tr(r),s=Fl(o,t);return s&&jl(r,o),{path:t,class:n,removed:s,persistedTo:r}}function ql(t,e){let n=As(t),r=xr(e),o=Tr(r);return{path:t,class:n,value:Ol(o,t)}}function Vl(t){return Tr(xr(t))}function zl(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Jl(t){return t==="env"||t==="config"?t:void 0}function Ce(t){return{content:t,isError:!0}}var Yl=async t=>{let e=zl(t);if(!e)return Ce("config_get: expected an object input");let n=Jl(e.target);if(!n)return Ce("config_get: `target` must be 'env' or 'config'");let r=typeof e.key=="string"?e.key:void 0,o=e.all===!0;try{if(n==="env"){if(r){let s=Bl(r);return{content:JSON.stringify(s,null,2)}}return{content:JSON.stringify(Hl({all:o}),null,2)}}if(r){let s=ql(r);return{content:JSON.stringify(s,null,2)}}return{content:JSON.stringify(Vl(),null,2)}}catch(s){return Ce(`config_get: ${s.message}`)}},Xl=async t=>{let e=zl(t);if(!e)return Ce("config_set: expected an object input");let n=Jl(e.target);if(!n)return Ce("config_set: `target` must be 'env' or 'config'");let r=typeof e.key=="string"?e.key:void 0;if(!r)return Ce("config_set: `key` is required");let o=e.action==="unset"?"unset":"set",s=e.value;try{if(o==="unset"){if(n==="env"){let c=Ul(r);return{content:c.removed?`Removed ${c.key} from afk.env (${c.persistedTo}). ${pn}.`:`${c.key} was not set in afk.env; nothing to remove.`}}let a=Gl(r);return{content:a.removed?`Removed ${a.path} from afk.config.json (${a.persistedTo}). ${pn}.`:`${a.path} was not set in afk.config.json; nothing to remove.`}}if(s==null)return Ce(`config_set: \`value\` is required to set ${r}`);if(n==="env"){if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")return Ce("config_set: env values must be a string, number, or boolean");let a=$l(r,String(s));return{content:`Set ${a.key} = ${a.display} in afk.env (${a.persistedTo}). ${pn}.`}}let i=Wl(r,s);return{content:`Set ${i.path} = ${JSON.stringify(i.value)} in afk.config.json (${i.persistedTo}). ${pn}.`}}catch(i){return Ce(`config_set: ${i.message}`)}};var _t={action:"decline"},Cs=class{handler=null;queue=Promise.resolve();queueDepth=0;install(e){this.handler=e}uninstall(){this.handler=null}pendingCount(){return this.queueDepth}route(e,n){if(n.signal.aborted)return Promise.resolve(_t);this.queueDepth+=1;let r,o=new Promise(i=>{r=i}),s=this.handler;return this.queue=this.queue.then(async()=>{try{if(n.signal.aborted){r(_t);return}if(!s){r(_t);return}let i,a=new Promise(c=>{i=()=>c(_t),n.signal.addEventListener("abort",i,{once:!0})});try{try{n.onActive?.()}catch{}let c=await Promise.race([s(e,n).catch(()=>_t),a]);r(c)}finally{n.signal.removeEventListener("abort",i)}}finally{this.queueDepth-=1,r(_t)}}).catch(()=>{}),o}},nt=new Cs;var Ql=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let n=t,r=n.question;if(typeof r!="string"||r.trim()==="")return{content:"Invalid input: question must be a non-empty string",isError:!0};let o=new Set(["text","confirm","choice","multi_choice","number"]),s=n.type??"text";if(typeof s!="string"||!o.has(s))return{content:"Invalid input: type must be one of: text, confirm, choice, multi_choice, number",isError:!0};if(s==="choice"||s==="multi_choice"){let f=n.choices;if(!Array.isArray(f)||f.length===0)return{content:`Invalid input: choices array is required and must be non-empty for type "${s}"`,isError:!0};if(f.length>100)return{content:`Invalid input: choices array must not exceed 100 items, got ${f.length}`,isError:!0};for(let g of f)if(typeof g!="string")return{content:"Invalid input: all choices must be strings",isError:!0}}let i=n.min,a=n.max;if(i!==void 0&&(typeof i!="number"||!Number.isFinite(i)))return{content:"Invalid input: min must be a finite number",isError:!0};if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)))return{content:"Invalid input: max must be a finite number",isError:!0};if(i!==void 0&&a!==void 0&&i>a)return{content:`Invalid input: min (${i}) must be \u2264 max (${a})`,isError:!0};let c=n.min_length,l=n.max_length;if(c!==void 0&&typeof c!="number")return{content:"Invalid input: min_length must be a number",isError:!0};if(l!==void 0&&typeof l!="number")return{content:"Invalid input: max_length must be a number",isError:!0};if((c!==void 0||l!==void 0)&&s!=="text")return{content:`Invalid input: min_length/max_length are only valid for type "text", got "${s}"`,isError:!0};if(n.allow_custom!==void 0&&s!=="choice"&&s!=="multi_choice")return{content:`Invalid input: allow_custom is only valid for type "choice" or "multi_choice", got "${s}"`,isError:!0};let d={serverName:"agent",message:r.trim(),origin:"agent",type:s,...n.choices!==void 0&&{choices:n.choices},...n.context!==void 0&&typeof n.context=="string"&&{context:n.context},...n.default!==void 0&&{questionDefault:n.default},...c!==void 0&&{minLength:c},...l!==void 0&&{maxLength:l},...i!==void 0&&{min:i},...a!==void 0&&{max:a},...n.allow_skip!==void 0&&{allowSkip:!!n.allow_skip},...n.allow_custom!==void 0&&{allowCustom:!!n.allow_custom}},u=await nt.route(d,{signal:e}),p=u.action==="decline"||u.action==="cancel";return{content:JSON.stringify(u),...p&&{isError:!0,failureClass:"elicitation-declined"}}};N();function Rr(t){if(t instanceof Error&&t.name==="TimeoutError")return"timeout";let e=t instanceof Error?t.message:String(t);return/Timeout\s+\d+\s*ms exceeded/i.test(e)?"timeout":void 0}var kw=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"];function ke(t){return kw.some(e=>t.includes(e))}function _e(t){return t.includes("Executable doesn't exist")?"browser tools require the Playwright chromium binary. Install via: pnpm exec playwright install chromium.":"browser tools require the optional `playwright` peer dependency. Install via: pnpm add playwright (then pnpm exec playwright install chromium). Or pick a different tool."}var Zl=["load","domcontentloaded","networkidle"];function _w(t){if(!t||typeof t!="object")return{error:"browser_open: input must be an object"};let e=t,n=e.url;if(typeof n!="string"||n.length===0)return{error:'browser_open: "url" is required and must be a non-empty string'};let r;try{r=new URL(n)}catch{return{error:`browser_open: "${n}" is not a valid absolute URL`}}if(r.protocol!=="http:"&&r.protocol!=="https:")return{error:`browser_open: protocol "${r.protocol}" is not supported (http/https only)`};let o;if(e.wait_for!==void 0){if(!Zl.includes(e.wait_for))return{error:`browser_open: "wait_for" must be one of ${Zl.map(a=>`"${a}"`).join(", ")} (got ${JSON.stringify(e.wait_for)})`};o=e.wait_for}let s;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_open: "screenshot" must be a boolean'};s=e.screenshot}let i;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'browser_open: "timeout_ms" must be a positive finite number'};i=e.timeout_ms}return{url:r.toString(),waitFor:o,screenshot:s,timeoutMs:i}}function Ew(t={}){return async(e,n,r)=>{if(n.aborted){let c=n.reason;return{content:`browser_open aborted: ${c instanceof Error?c.message:String(c??"aborted")}`,isError:!0,failureClass:"abort"}}let o=_w(e);if("error"in o)return{content:o.error,isError:!0};let s=w.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:c}=await Promise.resolve().then(()=>(tt(),et));i=await c()}}catch(c){let l=c instanceof Error?c.message:String(c);return ke(l)?{content:_e(l),isError:!0}:{content:`browser_open failed to get provider: ${l}`,isError:!0}}let a=Date.now();try{let c=await i.open({sessionId:s,url:o.url,waitFor:o.waitFor,screenshot:o.screenshot,timeoutMs:o.timeoutMs}),l=Date.now()-a;if("outcome"in c&&c.outcome==="blocked_by_policy")return X(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:l}),{content:`browser_open blocked: ${c.reason}`,isError:!0,failureClass:"policy-refusal"};let d=c;return X(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:d.url,status:"ok",durationMs:l,...d.screenshotPath!==null?{screenshotPath:d.screenshotPath}:{}}),{content:JSON.stringify(d,null,2)}}catch(c){let l=Date.now()-a,d=c instanceof Error?c.message:String(c);X(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:l,error:{reason:d,recoverable:!1}});let u=Rr(c);return{content:`browser_open failed: ${d}`,isError:!0,...u?{failureClass:u}:{}}}}}var ed=Ew();N();function Aw(t){if(t!=null&&typeof t!="object")return{error:"browser_observe: input must be an object or omitted"};if(!t)return{};let e=t,n;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_observe: "screenshot" must be a boolean'};n=e.screenshot}let r;if(e.include_hidden!==void 0){if(typeof e.include_hidden!="boolean")return{error:'browser_observe: "include_hidden" must be a boolean'};r=e.include_hidden}let o;if(e.max_elements!==void 0){if(typeof e.max_elements!="number"||!Number.isFinite(e.max_elements)||e.max_elements<=0||!Number.isInteger(e.max_elements))return{error:'browser_observe: "max_elements" must be a positive integer'};o=e.max_elements}return{screenshot:n,includeHidden:r,maxElements:o}}function xw(t={}){return async(e,n,r)=>{if(n.aborted){let c=n.reason;return{content:`browser_observe aborted: ${c instanceof Error?c.message:String(c??"aborted")}`,isError:!0}}let o=Aw(e);if("error"in o)return{content:o.error,isError:!0};let s=w.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:c}=await Promise.resolve().then(()=>(tt(),et));i=await c()}}catch(c){let l=c instanceof Error?c.message:String(c);return ke(l)?{content:_e(l),isError:!0}:{content:`browser_observe failed to get provider: ${l}`,isError:!0}}let a=Date.now();try{let c=await i.observe({sessionId:s,screenshot:o.screenshot,includeHidden:o.includeHidden,maxElements:o.maxElements}),l=Date.now()-a;return X(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:c.url,urlAfter:c.url,status:"ok",durationMs:l,...c.screenshotPath!==null?{screenshotPath:c.screenshotPath}:{}}),{content:JSON.stringify(c,null,2)}}catch(c){let l=Date.now()-a,d=c instanceof Error?c.message:String(c);return X(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:l,error:{reason:d,recoverable:!1}}),{content:`browser_observe failed: ${d}`,isError:!0}}}}var td=xw();cn();N();var nd=["click","fill","press","select","hover","scroll_to","wait_for"],rd=["semantic","element_id","selector"];function Tw(t){if(!t||typeof t!="object")return{error:"browser_act: input must be an object"};let e=t;if(typeof e.action!="string")return{error:'browser_act: "action" is required and must be a string'};if(!nd.includes(e.action))return{error:`browser_act: "action" must be one of ${nd.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(e.action)})`};let n=e.action,r=e.target;if(!r||typeof r!="object")return{error:'browser_act: "target" is required and must be an object'};let o=r;if(typeof o.kind!="string"||!rd.includes(o.kind))return{error:`browser_act: "target.kind" must be one of ${rd.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(o.kind)})`};let s,i=o.kind;if(i==="semantic"){if(typeof o.text!="string"||o.text.length===0)return{error:'browser_act: target.kind=semantic requires "target.text" (non-empty string)'};s={kind:"semantic",text:o.text,...typeof o.role=="string"&&o.role.length>0?{role:o.role}:{}}}else if(i==="element_id"){if(typeof o.element_id!="string"||o.element_id.length===0)return{error:'browser_act: target.kind=element_id requires "target.element_id" (non-empty string)'};s={kind:"element_id",elementId:o.element_id}}else{if(typeof o.selector!="string"||o.selector.length===0)return{error:'browser_act: target.kind=selector requires "target.selector" (non-empty string)'};s={kind:"selector",selector:o.selector}}let a;if(e.value!==void 0){if(typeof e.value!="string")return{error:'browser_act: "value" must be a string when provided'};a=e.value}let c;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'browser_act: "timeout_ms" must be a positive finite number'};c=e.timeout_ms}let l;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_act: "screenshot" must be a boolean'};l=e.screenshot}return{action:n,target:s,value:a,timeoutMs:c,screenshot:l}}function Rw(t,e){let n=t.role?`"${t.text}" (role: ${t.role})`:`"${t.text}"`;return[`browser_act: ambiguous target \u2014 ${e.length} elements matched ${n}.`,'Retry with target.kind="element_id" using one of the following:',...e.map(o=>` id=${o.id} role=${o.role} label=${o.label}`)].join(`
1053
1053
  `)}function Iw(t){return t.kind==="semantic"?{kind:"semantic",text:Gc(t.text),...t.role!==void 0?{role:t.role}:{}}:t.kind==="element_id"?{kind:"element_id",elementId:t.elementId}:{kind:"selector",selectorHash:Wc(t.selector)}}function Pw(t={}){return async(e,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_act aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0,failureClass:"abort"}}let o=Tw(e);if("error"in o)return{content:o.error,isError:!0};let s=Iw(o.target),i=w.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let a;try{if(t.getBrowserProvider)a=await t.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(tt(),et));a=await l()}}catch(l){let d=l instanceof Error?l.message:String(l);return ke(d)?{content:_e(d),isError:!0}:{content:`browser_act failed to get provider: ${d}`,isError:!0}}let c=Date.now();try{let l=await a.act({sessionId:i,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),d=Date.now()-c;if("outcome"in l){if(l.outcome==="ambiguous_target")return X(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:d}),{content:Rw(l.query,l.candidates),isError:!0};if(l.outcome==="blocked_by_policy")return X(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:d}),{content:`browser_act blocked: ${l.reason}`,isError:!0,failureClass:"policy-refusal"}}return X(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:l.url,urlAfter:l.url,status:"ok",durationMs:d,...l.screenshotPath!==null?{screenshotPath:l.screenshotPath}:{}}),{content:JSON.stringify(l,null,2)}}catch(l){let d=Date.now()-c,u=l instanceof Error?l.message:String(l);X(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"error",durationMs:d,error:{reason:u,recoverable:!1}});let p=Rr(l);return{content:`browser_act failed: ${u}`,isError:!0,...p?{failureClass:p}:{}}}}}var od=Pw();N();var sd=["semantic","element_id","selector"],Ms=8e3;function Cw(t){if(typeof t.kind!="string"||!sd.includes(t.kind))return{error:`browser_screenshot: "target.kind" must be one of ${sd.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(t.kind)})`};let e=t.kind;return e==="semantic"?typeof t.text!="string"||t.text.length===0?{error:'browser_screenshot: target.kind=semantic requires "target.text" (non-empty string)'}:{kind:"semantic",text:t.text,...typeof t.role=="string"&&t.role.length>0?{role:t.role}:{}}:e==="element_id"?typeof t.element_id!="string"||t.element_id.length===0?{error:'browser_screenshot: target.kind=element_id requires "target.element_id" (non-empty string)'}:{kind:"element_id",elementId:t.element_id}:typeof t.selector!="string"||t.selector.length===0?{error:'browser_screenshot: target.kind=selector requires "target.selector" (non-empty string)'}:{kind:"selector",selector:t.selector}}function Mw(t){if(t!=null&&typeof t!="object")return{error:"browser_screenshot: input must be an object or omitted"};if(!t)return{};let e=t,n;if(e.target!==void 0){if(!e.target||typeof e.target!="object")return{error:'browser_screenshot: "target" must be an object when provided'};let o=Cw(e.target);if("error"in o)return o;n=o}let r;if(e.full_page!==void 0){if(typeof e.full_page!="boolean")return{error:'browser_screenshot: "full_page" must be a boolean'};r=e.full_page}return{target:n,fullPage:r}}function Ow(t={}){return async(e,n,r)=>{if(n.aborted){let c=n.reason;return{content:`browser_screenshot aborted: ${c instanceof Error?c.message:String(c??"aborted")}`,isError:!0}}let o=Mw(e);if("error"in o)return{content:o.error,isError:!0};let s=w.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:c}=await Promise.resolve().then(()=>(tt(),et));i=await c()}}catch(c){let l=c instanceof Error?c.message:String(c);return ke(l)?{content:_e(l),isError:!0}:{content:`browser_screenshot failed to get provider: ${l}`,isError:!0}}let a=Date.now();try{let c=await i.screenshot({sessionId:s,target:o.target,fullPage:o.fullPage}),l=Date.now()-a,{dataBase64:d,mediaType:u,...p}=c;return X(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:l,screenshotPath:p.path}),p.width>Ms||p.height>Ms?{content:JSON.stringify({...p,imageOmitted:`dimensions ${p.width}x${p.height}px exceed the ${Ms}px model-vision limit; the PNG was saved to the sidecar path but not attached. Use full_page:false (viewport) or target a specific element for a model-visible image.`},null,2)}:{content:JSON.stringify(p,null,2),image:{mediaType:u,data:d}}}catch(c){let l=Date.now()-a,d=c instanceof Error?c.message:String(c);return X(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:l,error:{reason:d,recoverable:!1}}),{content:`browser_screenshot failed: ${d}`,isError:!0}}}}var id=Ow();N();function Dw(t={}){return async(e,n,r)=>{if(n.aborted){let a=n.reason;return{content:`browser_close aborted: ${a instanceof Error?a.message:String(a??"aborted")}`,isError:!0}}let o=w.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(o))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(o)}`,isError:!0};let s;try{if(t.getBrowserProvider)s=await t.getBrowserProvider();else{let{getBrowserProvider:a}=await Promise.resolve().then(()=>(tt(),et));s=await a()}}catch(a){let c=a instanceof Error?a.message:String(a);return ke(c)?{content:_e(c),isError:!0}:{content:`browser_close failed to get provider: ${c}`,isError:!0}}let i=Date.now();try{await s.close({sessionId:o});let a=Date.now()-i;return X(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:a}),{content:"Browser session closed."}}catch(a){let c=Date.now()-i,l=a instanceof Error?a.message:String(a);return X(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:l,recoverable:!1}}),{content:`browser_close failed: ${l}`,isError:!0}}}}var ad=Dw();function Et(t,e){let n=t!==void 0?cr(t,e):e!==void 0?cr("default",e):ac,r=e!==void 0?Qo(e):hc,o=e!==void 0?Zo(e):yc,s=Es();return new Map([["bash",n],["read_file",lc],["write_file",pc],["edit_file",fc],["glob",r],["grep",o],["list_directory",bc],["send_telegram",Fc],["web_scrape",pl],["create_schedule",bl],["list_schedules",wl],["get_schedule_history",Sl],["cancel_schedule",vl],["terminal_font_size",s],["config_get",Yl],["config_set",Xl],["ask_question",Ql],["browser_open",ed],["browser_observe",td],["browser_act",od],["browser_screenshot",id],["browser_close",ad]])}function cd(t){return["The user has switched off plan mode. Writes are now permitted. Do two things, in order:","",`1. Save the plan. Write the plan you developed in this conversation to a new markdown file under \`${t}/\` \u2014 pick a short, descriptive kebab-case filename (e.g. \`${t}/refactor-auth-flow.md\`). Capture the full plan: the chosen approach, the concrete step-by-step changes, the risks named, and the alternatives considered. This is the durable record.`,"","2. Implement the plan. Work through the steps you just recorded, verifying as you go \u2014 run the project's lint/test gates where they apply. End in a terminal state: Done with evidence, Blocked with the exact unblock condition, or Asking one precise question."].join(`
1054
1054
  `)}B();var At="exit_plan_mode",Fw="Approve \u2014 implement now (default mode: writes ask for confirmation, contained to the workspace)",Lw="Approve \u2014 implement now (bypass mode: no prompts, read/write any path)",ld="Keep planning",Ir={name:At,category:"other",concurrencySafe:!1,description:`Signal that your plan is ready and present it to the user for approval. The user is shown a picker: approve and implement (you pick neither mode \u2014 the user does), or keep planning.
1055
1055