agent-afk 4.27.0 → 4.27.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +9 -9
- package/dist/index.mjs +4 -4
- package/dist/telegram.mjs +6 -6
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
var Xp=Object.defineProperty;var me=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ai=(t,e)=>{for(var n in e)Xp(t,n,{get:e[n],enumerable:!0})};function xn(t){return An.find(e=>e.name===t)}function uo(t){return process.env[t]!==void 0}var An,b,L=me(()=>{"use strict";An=[{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_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"}],b={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_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 An){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(b,e.name);n&&Object.defineProperty(b,e.name,{...n,enumerable:!1})}})()});import{existsSync as ea,mkdirSync as _f,renameSync as Ef,cpSync as Af,rmSync as xf}from"fs";import{join as U,dirname as ta,isAbsolute as na}from"path";import{homedir as ra}from"os";import{fileURLToPath as Tf}from"url";function ne(){let t=b.AFK_HOME;if(t!==void 0&&t!==""){if(!na(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return U(ra(),".afk")}function Ve(){return U(ne(),"agent-framework")}function oa(){return U(Ve(),"forge-telemetry.jsonl")}function sa(){return U(Ve(),"briefs")}function Ao(){return U(ne(),"skills")}function st(){return U(ne(),"plugins")}function ia(){return U(process.cwd(),".afk")}function aa(){return U(ia(),"skills")}function xo(){return U(ia(),"plugins")}function Fn(){return U(st(),".index.json")}function To(){return U($t(),"schedules.json")}function Ro(){let t=Tf(import.meta.url),e=ta(t);return U(e,"bundled-plugins")}function $t(){return U(ne(),"config")}function Je(){let t=b.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!na(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return U(ne(),"state")}function it(){return U(Je(),"sessions")}function Ln(){return U(Je(),"presence")}function Nn(){return U(Je(),"memory")}function at(){return U(Je(),"session-grants.jsonl")}function ca(){return U(ne(),"farms")}function la(t){return U(ca(),t)}function If(t){if(!Rf.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function da(t){return If(t),U(Je(),"witness",t)}function ua(t="default"){return U(Je(),"daemon",`agent-afk@${t}`)}function Io(){return U($t(),"afk.env")}function ct(){return U($t(),"afk.config.json")}function $n(){return U(ra(),".afk.config.json")}function Pf(){return U(ne(),"sessions")}function Cf(t,e){if(t!==e&&ea(t)&&!ea(e))try{_f(ta(e),{recursive:!0});try{Ef(t,e)}catch(n){if(n.code==="EXDEV")try{Af(t,e,{recursive:!0}),xf(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(){Cf(Pf(),it())}function Ut(t){return typeof t=="string"&&t.length>0&&t.length<=Of&&Mf.test(t)}function Bt(t){if(!Ut(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return U(it(),t)}function Un(t){return U(Bt(t),"events.jsonl")}function fa(t){return U(Bt(t),"session.key")}var Rf,Mf,Of,N=me(()=>{"use strict";L();Rf=/^[a-zA-Z0-9_-]+$/;Mf=/^[A-Za-z0-9_-]+$/,Of=128});import{readFileSync as Vh}from"node:fs";import{join as Jh}from"path";function zh(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function gc(t,e){return zh(e).test(t)}function Qh(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(Yh.has(e))return!0;if(Xh.has(e))return!1}return!1}function hc(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function Zh(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 ey(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function ty(t){try{return Vh(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function ny(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 yc(t){let e=t?.env??b,n=t?.readFileSync??ty,r=t?.surface??e.AGENT_SURFACE,o=Qh(e.AFK_BROWSER_HEADLESS,r),s=hc(e.AFK_BROWSER_ALLOWED_DOMAINS),i=hc(e.AFK_BROWSER_BLOCKED_DOMAINS),a=ey(e.AFK_BROWSER_DOM_SNAPSHOTS),c=Zh(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():Jh($t(),"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=ny(l,f);return g.configPath=u,g}function Xo(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(gc(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>gc(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Yh,Xh,Qo=me(()=>{"use strict";L();N();Yh=new Set(["daemon","subagent","telegram","afk"]),Xh=new Set(["repl","interactive","cli"])});import ry from"node:fs";import oy from"node:path";import{chromium as sy}from"playwright";function iy(){try{return"4.27.0"}catch{}try{let t=oy.resolve(import.meta.dirname,"../../../package.json"),e=ry.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var ay,rr,bc=me(()=>{"use strict";ay=iy(),rr=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=sy.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/${ay}`}}}});import{createHash as cy}from"crypto";function Zo(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of ly)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function wc(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&dy.test(t.label))}function Sc(t){return cy("sha256").update(t,"utf8").digest("hex").slice(0,8)}function vc(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var ly,dy,Zt=me(()=>{"use strict";ly=[{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}];dy=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as uy}from"node:crypto";function py(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function fy(t,e,n){return`el_${uy("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function my(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function kc(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Ec(t,e){let n=t.role??"",r=t.name??"";_c.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Ec(s,e)}async function gy(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},Ac).catch(()=>[])}async function hy(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},Ac).catch(()=>[])}function yy(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function or(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=yy(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=gy(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]),S,v=!1;u!==null?(S=[],Ec(u,S)):(o.push("observation skipped accessibility tree (returned null)"),v=!0,S=(await hy(t)).filter(A=>_c.has(A.role??"")));let k=new Map;for(let w of p){let A=kc(w.name),x=k.get(A);(!x||x.bbox.w===0&&w.bbox.w>0)&&k.set(A,w)}let h=S.map(w=>({ax:w,dom:k.get(kc(w.name??""))})),y=r?h:h.filter(w=>w.dom?w.dom.bbox.w>0||w.dom.bbox.h>0:!0);y.sort((w,A)=>{let x=w.dom?.bbox.y??0,I=A.dom?.bbox.y??0;if(x!==I)return x-I;let R=w.dom?.bbox.x??0,P=A.dom?.bbox.x??0;return R-P}),y.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=y.slice(0,n).map((w,A)=>{let x=w.ax.role??"generic",I=w.ax.name??"",R=fy(x,I,A),P=w.dom?.bbox??{x:0,y:0,w:0,h:0},W=w.dom?.type??null,H=null;w.ax.value!==void 0&&w.ax.value!==null&&(H=String(w.ax.value)),w.ax.checked!==void 0&&(H=String(w.ax.checked)),wc({role:x,kind:W})&&(H="[redacted]");let Q={disabled:w.ax.disabled??!1};w.ax.checked!==void 0&&(Q.checked=w.ax.checked===!0||w.ax.checked==="mixed"),w.ax.selected!==void 0&&(Q.selected=w.ax.selected),w.ax.expanded!==void 0&&(Q.expanded=w.ax.expanded);let G;w.dom?.testId?G=`[data-testid="${w.dom.testId}"]`:w.dom?.id&&(G=`#${w.dom.id}`);let V={id:R,role:x,label:py(I),kind:W,value:H,state:Q,bbox:P};return G!==void 0&&(V.selector=G),V}),T="idle";try{let w=await t.evaluate(()=>document.readyState);w==="loading"?T="loading":w==="interactive"?T="navigating":T="idle"}catch{T="navigating"}T!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),v&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let C=my(f),O=`obs_${e.observationCounter.toString(36)}`,F=new Date().toISOString();return{observationId:O,url:g,title:m,textSummary:C,interactive:E,status:{httpStatus:e.httpStatus??null,loadingState:T,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:F}}var _c,Ac,xc=me(()=>{"use strict";Zt();_c=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Ac="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Tc(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 es(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Tc(t,s)))).filter(o=>o!==null)}async function by(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 ts(t,e,n){switch(e.kind){case"element_id":return wy(t,e,n);case"selector":return Sy(t,e);case"semantic":return vy(t,e)}}async function wy(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 es(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Sy(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 es(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function vy(t,e){return e.role!==void 0?ky(t,e.text,e.role):_y(t,e.text,e)}async function ky(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 es(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function _y(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 by(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 S=p[m];if(S===void 0)continue;let v=await Tc(S.locator,S.index);if(v!==null){let k=`${v.role}:${v.label}:${m}`,h=0;for(let y=0;y<k.length;y++)h=h*31+k.charCodeAt(y)>>>0;f.push({...v,id:`el_${h.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Rc=me(()=>{"use strict"});import{randomBytes as Ey}from"crypto";import{mkdir as Ay,stat as xy,writeFile as Ty}from"fs/promises";import{join as ns}from"path";import{gzip as Ry}from"zlib";import{promisify as Iy}from"util";function Py(t){return ns(da(t),"browser")}function Cy(t){return ns(Py(t),"screenshots")}function My(){return new Date().toISOString().replace(/[:.]/g,"-")}function Oy(){return Ey(3).toString("hex")}async function rs(t,e,n){if(e.length>Ic)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Ic} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=Cy(t);await Ay(r,{recursive:!0});let o=`${My()}-${Oy()}-${n}.png`,s=ns(r,o);await Ty(s,e);let{size:i}=await xy(s);return{path:s,bytes:i}}var tR,Ic,Pc=me(()=>{"use strict";N();Zt();tR=Iy(Ry);Ic=5*1024*1024});var Mc={};Ai(Mc,{PlaywrightProvider:()=>os});function Cc(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 os,Oc=me(()=>{"use strict";bc();xc();Rc();Qo();Zt();Pc();os=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new rr(e)}async open(e){let n=Xo(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 or(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 or(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 ts(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Cc(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=Zo(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(S){l=S}else l=m}let u=r.url();if(u!==s){let m=Xo(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 or(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 ts(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Cc(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 rs(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 rs(n,o,r);return s}catch{return null}}}});var Qe={};Ai(Qe,{__resetBrowserRegistryForTests:()=>$y,browserProviderActive:()=>Ly,closeBrowserProvider:()=>ss,getBrowserProvider:()=>Fy,peekBrowserProvider:()=>Ny});function Dc(){Promise.resolve(ss()).then(()=>{process.exit(130)})}function Fc(){Promise.resolve(ss()).then(()=>{process.exit(143)})}function Lc(){ye=null}function Dy(){sr||(process.on("SIGINT",Dc),process.on("SIGTERM",Fc),process.on("exit",Lc),sr=!0)}function Nc(){sr&&(process.removeListener("SIGINT",Dc),process.removeListener("SIGTERM",Fc),process.removeListener("exit",Lc),sr=!1)}async function Fy(t){return ye!==null?ye:(Xe!==null||(Xe=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Oc(),Mc)),n=yc(t),r=new e(n);return Dy(),ye=r,Xe=null,r})()),Xe)}async function ss(){if(ye===null)return;let t=ye;ye=null,Xe=null,Nc(),await t.shutdown()}function Ly(){return ye!==null}function Ny(){return ye}function $y(){ye=null,Xe=null,Nc()}var ye,Xe,sr,Ze=me(()=>{"use strict";Qo();ye=null,Xe=null,sr=!1});L();function Qp(){return b.AFK_DEBUG==="1"||b.DEBUG==="1"}function D(...t){Qp()&&console.log(...t)}var ie=class extends Error{constructor(e){super(e),this.name="AbortError"}},Ie=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 tt=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 po(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){D(`trace.emit tool_call failed: ${Pe(n)}`)}}async function nt(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){D(`trace.emit hook_decision failed: ${Pe(n)}`)}}async function Ke(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){D(`trace.emit subagent_lifecycle failed: ${Pe(n)}`)}}async function xi(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){D(`trace.emit budget failed: ${Pe(n)}`)}}async function Ti(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){D(`trace.emit abort failed: ${Pe(n)}`)}}async function Ri(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){D(`trace.emit compaction failed: ${Pe(n)}`)}}async function Ii(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){D(`trace.emit closure failed: ${Pe(n)}`)}}async function We(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){D(`trace.emit session_phase failed: ${Pe(n)}`)}}function Pe(t){return t instanceof Error?t.message:String(t)}import ai from"path";import{appendFileSync as ak,mkdirSync as ck}from"fs";import{dirname as lk}from"path";import Uu from"@anthropic-ai/sdk";var Pi="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",Zp="effort-2025-11-24",ef="claude-cli/1.0.0 (external, cli)",tf="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function Tn(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Mt(t,e,n){let r=e==="oauth"?{authToken:t}:{apiKey:t};return typeof n=="string"&&n.length>0?{...r,baseURL:n}:r}function ge(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${Pi},${Zp}`:Pi,"x-app":"cli","User-Agent":ef,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Ci(t){return t!=="oauth"?null:[{type:"text",text:tf}]}import lf from"@anthropic-ai/sdk";L();var go=["local","small","medium","large"],Ge={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-4-6"},large:{id:"claude-opus-4-8"}},nf={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},rf="auto",ho="claude-fable-5",of={fable:ho},mo;function yo(t){mo=t}function fo(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function Rn(t,e,n){let r={},o=fo(t);o&&(r.id=o);let s=fo(e);s&&(r.baseUrl=s);let i=fo(n);return i&&(r.apiKey=i),r}function sf(){return{local:Rn(b.AFK_MODEL_LOCAL,b.AFK_MODEL_LOCAL_BASE_URL,b.AFK_MODEL_LOCAL_API_KEY),small:Rn(b.AFK_MODEL_SMALL,b.AFK_MODEL_SMALL_BASE_URL,b.AFK_MODEL_SMALL_API_KEY),medium:Rn(b.AFK_MODEL_MEDIUM,b.AFK_MODEL_MEDIUM_BASE_URL,b.AFK_MODEL_MEDIUM_API_KEY),large:Rn(b.AFK_MODEL_LARGE,b.AFK_MODEL_LARGE_BASE_URL,b.AFK_MODEL_LARGE_API_KEY)}}function Mi(t){let e=sf(),n={};for(let r of go){let o=Ge[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 rt(t){return t||mo||Mi()}function ot(t,e=rt()){let n=t.trim().toLowerCase();if(!n||n===rf)return;for(let o of go){let s=e[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:nf[n]}function bo(t,e=rt()){if(t===void 0)return{id:""};let n=ot(t,e);if(n)return e[n];let r=of[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function qe(t,e=rt()){if(t!==void 0)return bo(t,e).id}function Oi(t,e=rt()){if(t===void 0)return;let n=ot(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 Di(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of go){let o=cf(n[r]);o&&(e[r]=o)}return e}function af(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 In(t){return typeof t=="string"?t.trim():""}function cf(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=In(e.id);if(!n)return;let r={id:n},o=In(e.name);o&&(r.name=o);let s=af(e.provider);s&&(r.provider=s);let i=In(e.baseUrl);i&&(r.baseUrl=i);let a=In(e.apiKey);return a&&(r.apiKey=a),r}}var wo={opus:Ge.large.id,opus_1m:Ge.large.id,sonnet:Ge.medium.id,sonnet_1m:Ge.medium.id,haiku:Ge.small.id,fable:ho};function Fi(t){return t in wo}function ee(t){return qe(t)}import{randomUUID as Li}from"node:crypto";async function Ni(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=Tn(e),l=Mt(e,c),d=a?a(l):new lf(l),u=Li(),p=Li(),f=ge(c,u,p),g=ee(n)??n,m={};Object.keys(f).length>0&&(m.headers=f),i&&(m.signal=i);let S=await d.messages.create({model:g,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(m).length>0?m:void 0),v=[];for(let h of S.content)h.type==="text"&&v.push(h.text);let k=v.join("").trim();return k.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),k}import{execFileSync as $i}from"child_process";import{existsSync as df,readFileSync as uf,writeFileSync as pf}from"fs";import{homedir as Ui,userInfo as Bi}from"os";import{join as Hi}from"path";var ff="9d1c250a-e61b-44d9-88ed-5944d1962f5e",mf="https://platform.claude.com/v1/oauth/token",gf=300*1e3;function ae(){let t=ji();if(t===void 0)return;let e=Ki(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 So(){let t=ji();if(t===void 0)return;let e=Ki(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+gf)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 hf(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}:{}},yf(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
2
|
+
`)}}}catch{}}function pa(){Cf(Pf(),it())}function Ut(t){return typeof t=="string"&&t.length>0&&t.length<=Of&&Mf.test(t)}function Bt(t){if(!Ut(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return U(it(),t)}function Un(t){return U(Bt(t),"events.jsonl")}function fa(t){return U(Bt(t),"session.key")}var Rf,Mf,Of,N=me(()=>{"use strict";L();Rf=/^[a-zA-Z0-9_-]+$/;Mf=/^[A-Za-z0-9_-]+$/,Of=128});import{readFileSync as Vh}from"node:fs";import{join as Jh}from"path";function zh(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function gc(t,e){return zh(e).test(t)}function Qh(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(Yh.has(e))return!0;if(Xh.has(e))return!1}return!1}function hc(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function Zh(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 ey(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function ty(t){try{return Vh(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function ny(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 yc(t){let e=t?.env??b,n=t?.readFileSync??ty,r=t?.surface??e.AGENT_SURFACE,o=Qh(e.AFK_BROWSER_HEADLESS,r),s=hc(e.AFK_BROWSER_ALLOWED_DOMAINS),i=hc(e.AFK_BROWSER_BLOCKED_DOMAINS),a=ey(e.AFK_BROWSER_DOM_SNAPSHOTS),c=Zh(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():Jh($t(),"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=ny(l,f);return g.configPath=u,g}function Xo(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(gc(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>gc(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Yh,Xh,Qo=me(()=>{"use strict";L();N();Yh=new Set(["daemon","subagent","telegram","afk"]),Xh=new Set(["repl","interactive","cli"])});import ry from"node:fs";import oy from"node:path";import{chromium as sy}from"playwright";function iy(){try{return"4.27.2"}catch{}try{let t=oy.resolve(import.meta.dirname,"../../../package.json"),e=ry.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var ay,rr,bc=me(()=>{"use strict";ay=iy(),rr=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=sy.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/${ay}`}}}});import{createHash as cy}from"crypto";function Zo(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of ly)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function wc(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&dy.test(t.label))}function Sc(t){return cy("sha256").update(t,"utf8").digest("hex").slice(0,8)}function vc(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var ly,dy,Zt=me(()=>{"use strict";ly=[{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}];dy=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as uy}from"node:crypto";function py(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function fy(t,e,n){return`el_${uy("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function my(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function kc(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Ec(t,e){let n=t.role??"",r=t.name??"";_c.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Ec(s,e)}async function gy(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},Ac).catch(()=>[])}async function hy(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},Ac).catch(()=>[])}function yy(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function or(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=yy(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=gy(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]),S,v=!1;u!==null?(S=[],Ec(u,S)):(o.push("observation skipped accessibility tree (returned null)"),v=!0,S=(await hy(t)).filter(A=>_c.has(A.role??"")));let k=new Map;for(let w of p){let A=kc(w.name),x=k.get(A);(!x||x.bbox.w===0&&w.bbox.w>0)&&k.set(A,w)}let h=S.map(w=>({ax:w,dom:k.get(kc(w.name??""))})),y=r?h:h.filter(w=>w.dom?w.dom.bbox.w>0||w.dom.bbox.h>0:!0);y.sort((w,A)=>{let x=w.dom?.bbox.y??0,I=A.dom?.bbox.y??0;if(x!==I)return x-I;let R=w.dom?.bbox.x??0,P=A.dom?.bbox.x??0;return R-P}),y.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=y.slice(0,n).map((w,A)=>{let x=w.ax.role??"generic",I=w.ax.name??"",R=fy(x,I,A),P=w.dom?.bbox??{x:0,y:0,w:0,h:0},W=w.dom?.type??null,H=null;w.ax.value!==void 0&&w.ax.value!==null&&(H=String(w.ax.value)),w.ax.checked!==void 0&&(H=String(w.ax.checked)),wc({role:x,kind:W})&&(H="[redacted]");let Q={disabled:w.ax.disabled??!1};w.ax.checked!==void 0&&(Q.checked=w.ax.checked===!0||w.ax.checked==="mixed"),w.ax.selected!==void 0&&(Q.selected=w.ax.selected),w.ax.expanded!==void 0&&(Q.expanded=w.ax.expanded);let G;w.dom?.testId?G=`[data-testid="${w.dom.testId}"]`:w.dom?.id&&(G=`#${w.dom.id}`);let V={id:R,role:x,label:py(I),kind:W,value:H,state:Q,bbox:P};return G!==void 0&&(V.selector=G),V}),T="idle";try{let w=await t.evaluate(()=>document.readyState);w==="loading"?T="loading":w==="interactive"?T="navigating":T="idle"}catch{T="navigating"}T!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),v&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let C=my(f),O=`obs_${e.observationCounter.toString(36)}`,F=new Date().toISOString();return{observationId:O,url:g,title:m,textSummary:C,interactive:E,status:{httpStatus:e.httpStatus??null,loadingState:T,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:F}}var _c,Ac,xc=me(()=>{"use strict";Zt();_c=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Ac="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Tc(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 es(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Tc(t,s)))).filter(o=>o!==null)}async function by(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 ts(t,e,n){switch(e.kind){case"element_id":return wy(t,e,n);case"selector":return Sy(t,e);case"semantic":return vy(t,e)}}async function wy(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 es(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Sy(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 es(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function vy(t,e){return e.role!==void 0?ky(t,e.text,e.role):_y(t,e.text,e)}async function ky(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 es(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function _y(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 by(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 S=p[m];if(S===void 0)continue;let v=await Tc(S.locator,S.index);if(v!==null){let k=`${v.role}:${v.label}:${m}`,h=0;for(let y=0;y<k.length;y++)h=h*31+k.charCodeAt(y)>>>0;f.push({...v,id:`el_${h.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Rc=me(()=>{"use strict"});import{randomBytes as Ey}from"crypto";import{mkdir as Ay,stat as xy,writeFile as Ty}from"fs/promises";import{join as ns}from"path";import{gzip as Ry}from"zlib";import{promisify as Iy}from"util";function Py(t){return ns(da(t),"browser")}function Cy(t){return ns(Py(t),"screenshots")}function My(){return new Date().toISOString().replace(/[:.]/g,"-")}function Oy(){return Ey(3).toString("hex")}async function rs(t,e,n){if(e.length>Ic)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Ic} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=Cy(t);await Ay(r,{recursive:!0});let o=`${My()}-${Oy()}-${n}.png`,s=ns(r,o);await Ty(s,e);let{size:i}=await xy(s);return{path:s,bytes:i}}var tR,Ic,Pc=me(()=>{"use strict";N();Zt();tR=Iy(Ry);Ic=5*1024*1024});var Mc={};Ai(Mc,{PlaywrightProvider:()=>os});function Cc(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 os,Oc=me(()=>{"use strict";bc();xc();Rc();Qo();Zt();Pc();os=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new rr(e)}async open(e){let n=Xo(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 or(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 or(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 ts(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Cc(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=Zo(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(S){l=S}else l=m}let u=r.url();if(u!==s){let m=Xo(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 or(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 ts(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Cc(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 rs(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 rs(n,o,r);return s}catch{return null}}}});var Qe={};Ai(Qe,{__resetBrowserRegistryForTests:()=>$y,browserProviderActive:()=>Ly,closeBrowserProvider:()=>ss,getBrowserProvider:()=>Fy,peekBrowserProvider:()=>Ny});function Dc(){Promise.resolve(ss()).then(()=>{process.exit(130)})}function Fc(){Promise.resolve(ss()).then(()=>{process.exit(143)})}function Lc(){ye=null}function Dy(){sr||(process.on("SIGINT",Dc),process.on("SIGTERM",Fc),process.on("exit",Lc),sr=!0)}function Nc(){sr&&(process.removeListener("SIGINT",Dc),process.removeListener("SIGTERM",Fc),process.removeListener("exit",Lc),sr=!1)}async function Fy(t){return ye!==null?ye:(Xe!==null||(Xe=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Oc(),Mc)),n=yc(t),r=new e(n);return Dy(),ye=r,Xe=null,r})()),Xe)}async function ss(){if(ye===null)return;let t=ye;ye=null,Xe=null,Nc(),await t.shutdown()}function Ly(){return ye!==null}function Ny(){return ye}function $y(){ye=null,Xe=null,Nc()}var ye,Xe,sr,Ze=me(()=>{"use strict";Qo();ye=null,Xe=null,sr=!1});L();function Qp(){return b.AFK_DEBUG==="1"||b.DEBUG==="1"}function D(...t){Qp()&&console.log(...t)}var ie=class extends Error{constructor(e){super(e),this.name="AbortError"}},Ie=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 tt=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 po(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){D(`trace.emit tool_call failed: ${Pe(n)}`)}}async function nt(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){D(`trace.emit hook_decision failed: ${Pe(n)}`)}}async function Ke(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){D(`trace.emit subagent_lifecycle failed: ${Pe(n)}`)}}async function xi(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){D(`trace.emit budget failed: ${Pe(n)}`)}}async function Ti(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){D(`trace.emit abort failed: ${Pe(n)}`)}}async function Ri(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){D(`trace.emit compaction failed: ${Pe(n)}`)}}async function Ii(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){D(`trace.emit closure failed: ${Pe(n)}`)}}async function We(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){D(`trace.emit session_phase failed: ${Pe(n)}`)}}function Pe(t){return t instanceof Error?t.message:String(t)}import ai from"path";import{appendFileSync as ak,mkdirSync as ck}from"fs";import{dirname as lk}from"path";import Uu from"@anthropic-ai/sdk";var Pi="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",Zp="effort-2025-11-24",ef="claude-cli/1.0.0 (external, cli)",tf="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function Tn(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Mt(t,e,n){let r=e==="oauth"?{authToken:t}:{apiKey:t};return typeof n=="string"&&n.length>0?{...r,baseURL:n}:r}function ge(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${Pi},${Zp}`:Pi,"x-app":"cli","User-Agent":ef,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Ci(t){return t!=="oauth"?null:[{type:"text",text:tf}]}import lf from"@anthropic-ai/sdk";L();var go=["local","small","medium","large"],Ge={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-4-6"},large:{id:"claude-opus-4-8"}},nf={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},rf="auto",ho="claude-fable-5",of={fable:ho},mo;function yo(t){mo=t}function fo(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function Rn(t,e,n){let r={},o=fo(t);o&&(r.id=o);let s=fo(e);s&&(r.baseUrl=s);let i=fo(n);return i&&(r.apiKey=i),r}function sf(){return{local:Rn(b.AFK_MODEL_LOCAL,b.AFK_MODEL_LOCAL_BASE_URL,b.AFK_MODEL_LOCAL_API_KEY),small:Rn(b.AFK_MODEL_SMALL,b.AFK_MODEL_SMALL_BASE_URL,b.AFK_MODEL_SMALL_API_KEY),medium:Rn(b.AFK_MODEL_MEDIUM,b.AFK_MODEL_MEDIUM_BASE_URL,b.AFK_MODEL_MEDIUM_API_KEY),large:Rn(b.AFK_MODEL_LARGE,b.AFK_MODEL_LARGE_BASE_URL,b.AFK_MODEL_LARGE_API_KEY)}}function Mi(t){let e=sf(),n={};for(let r of go){let o=Ge[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 rt(t){return t||mo||Mi()}function ot(t,e=rt()){let n=t.trim().toLowerCase();if(!n||n===rf)return;for(let o of go){let s=e[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:nf[n]}function bo(t,e=rt()){if(t===void 0)return{id:""};let n=ot(t,e);if(n)return e[n];let r=of[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function qe(t,e=rt()){if(t!==void 0)return bo(t,e).id}function Oi(t,e=rt()){if(t===void 0)return;let n=ot(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 Di(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of go){let o=cf(n[r]);o&&(e[r]=o)}return e}function af(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 In(t){return typeof t=="string"?t.trim():""}function cf(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=In(e.id);if(!n)return;let r={id:n},o=In(e.name);o&&(r.name=o);let s=af(e.provider);s&&(r.provider=s);let i=In(e.baseUrl);i&&(r.baseUrl=i);let a=In(e.apiKey);return a&&(r.apiKey=a),r}}var wo={opus:Ge.large.id,opus_1m:Ge.large.id,sonnet:Ge.medium.id,sonnet_1m:Ge.medium.id,haiku:Ge.small.id,fable:ho};function Fi(t){return t in wo}function ee(t){return qe(t)}import{randomUUID as Li}from"node:crypto";async function Ni(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=Tn(e),l=Mt(e,c),d=a?a(l):new lf(l),u=Li(),p=Li(),f=ge(c,u,p),g=ee(n)??n,m={};Object.keys(f).length>0&&(m.headers=f),i&&(m.signal=i);let S=await d.messages.create({model:g,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(m).length>0?m:void 0),v=[];for(let h of S.content)h.type==="text"&&v.push(h.text);let k=v.join("").trim();return k.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),k}import{execFileSync as $i}from"child_process";import{existsSync as df,readFileSync as uf,writeFileSync as pf}from"fs";import{homedir as Ui,userInfo as Bi}from"os";import{join as Hi}from"path";var ff="9d1c250a-e61b-44d9-88ed-5944d1962f5e",mf="https://platform.claude.com/v1/oauth/token",gf=300*1e3;function ae(){let t=ji();if(t===void 0)return;let e=Ki(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 So(){let t=ji();if(t===void 0)return;let e=Ki(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+gf)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 hf(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}:{}},yf(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 ji(){if(process.platform==="darwin")try{return $i("security",["find-generic-password","-s","Claude Code-credentials","-a",Bi().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=Hi(Ui(),".claude",".credentials.json");if(!df(t))return;try{return uf(t,"utf-8")}catch{return}}}function Ki(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 hf(t){try{let e=await fetch(mf,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:ff})});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 Ot(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 yf(t){if(process.platform==="darwin")$i("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",Bi().username,"-w",t],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let e=Hi(Ui(),".claude",".credentials.json");bf(e,t)}}function bf(t,e){pf(t,e,{encoding:"utf-8",mode:384})}import{randomUUID as Du}from"node:crypto";L();var wf="1h";function Pn(t){if(typeof t?.baseUrl=="string"&&t.baseUrl.length>0)return!1;let e=b.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 Cn(){let t=b.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":t==="1h"?"1h":wf}function Wi(t,e){if(t.length===0)return t;let n=t[t.length-1],r=qi(n,e);return r===n?t:[...t.slice(0,-1),r]}function Gi(t,e){if(t.length===0)return t;let n=t[t.length-1],r=Sf(n,e);return r===n?t:[...t.slice(0,-1),r]}function Sf(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=qi(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function qi(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}var vo=["## 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. The user will then exit plan mode with `/plan off`, which has you save this plan to a file and implement it (Shift+Tab instead advances the permission-mode ring without saving or implementing) \u2014 so keep the plan concrete and complete enough to act on directly."].join(`
|
|
4
4
|
`);function Vi(t){return t!=="plan"?null:{type:"text",text:vo}}var ko=["## 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 Ji(t){return t!=="autonomous"?null:{type:"text",text:ko}}import{z as K}from"zod";import{mkdir as Pd,appendFile as Cd}from"fs/promises";import{join as $s}from"path";var zi={"audit-fit":{"01-skill-inspector.md":`# Skill Inspector
|
|
@@ -988,7 +988,7 @@ ${Po}
|
|
|
988
988
|
`,"utf-8")}catch(r){D("WAL append failed (non-fatal):",String(r))}}};function sg(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}var ig=/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;function _a(t){if(!t||t.length>100||!ig.test(t))throw new Error(`Invalid procedure name "${t}": must be 1-100 chars, alphanumeric/hyphens/underscores only`);return t}var ag=new Set(["fact","session_start","session_end","supersede"]),cg=new Set(["preference","convention","decision","learning"]);function lg(t){if(!t||typeof t!="object")return!1;let e=t;if(typeof e.type!="string"||!ag.has(e.type)||typeof e.timestamp!="string"||!e.data||typeof e.data!="object")return!1;if(e.type==="fact"){let n=e.data;if(typeof n.category!="string"||!cg.has(n.category))return!1}return!0}function Ea(t,e){let n=Qm(e,t);if(n.startsWith("..")||n.startsWith("/"))throw new Error("Path traversal detected")}function Aa(t,e){let n=e.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!n)return{name:Sa(t,".md"),content:e,created:"",source_session:null,access_count:0};let r=n[1]??"",o=n[2]??"",s=l=>l.match(/^name:\s*(.+)$/m)?.[1]?.trim()??Sa(t,".md"),i=l=>l.match(/^created:\s*(.+)$/m)?.[1]?.trim()??"",a=l=>l.match(/^source_session:\s*(.+)$/m)?.[1]?.trim()??null,c=l=>{let d=l.match(/^access_count:\s*(\d+)$/m);return d?parseInt(d[1],10):0};return{name:s(r),content:o.trim(),created:i(r),source_session:a(r),access_count:c(r)}}var dt={name:"memory_search",category:"read",concurrencySafe:!0,description:'Search cross-session memory for facts and procedures. Returns results ranked by relevance. Use this to recall information from prior sessions. Supports FTS5 match syntax: AND, OR, NOT, "exact phrase", prefix*',input_schema:{type:"object",properties:{query:{type:"string",description:'Search query (supports FTS5 match syntax: AND, OR, NOT, "exact phrase", prefix*)'},category:{type:"string",enum:["preference","convention","decision","learning"],description:"Optional: filter by fact category"},since:{type:"string",description:"Optional: ISO date \u2014 only return facts created after this date"},limit:{type:"number",description:"Max results (default 10)"}},required:["query"]}},Ra={name:"memory_update",category:"write",concurrencySafe:!1,description:'Store a fact in cross-session memory or update hot memory. Hot memory (target: "hot") persists in the system prompt across all future sessions. Facts (target: "fact") are stored in the searchable archive.',input_schema:{type:"object",properties:{target:{type:"string",enum:["hot","fact"],description:'"hot" writes to HOT.md (system prompt), "fact" writes to the searchable archive'},action:{type:"string",enum:["set","supersede","remove"],description:"Operation: set (create/overwrite), supersede (replace while keeping history), remove (delete)"},content:{type:"string",description:"The content to store (for set/supersede)"},category:{type:"string",enum:["preference","convention","decision","learning"],description:"Required for fact target"},supersedes:{type:"number",description:"Fact ID being superseded (for supersede action)"},id:{type:"number",description:"Fact ID to remove (for remove action)"}},required:["target","action"]}},Ia={name:"procedure_write",category:"write",concurrencySafe:!1,description:"Write a reusable procedure to memory. Procedures are markdown files describing how to perform recurring tasks. They persist across sessions and are searchable via memory_search.",input_schema:{type:"object",properties:{name:{type:"string",description:"Procedure name (kebab-case, becomes the filename)"},content:{type:"string",description:"Procedure content (markdown)"}},required:["name","content"]}},Le=[dt,Ra,Ia],Pa=Le.map(t=>t.name);function Kt(t,e,n){let r=async i=>{try{let a=dg(i),c=t.search(a.query,{category:a.category,since:a.since,limit:a.limit??10});return{content:JSON.stringify(c)}}catch(a){return{content:`memory_search error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},o=async i=>{try{let a=ug(i);if(a.target==="hot"){if(a.action!=="set")return{content:'Hot memory only supports action: "set". Use supersede/remove only for facts.',isError:!0};if(!a.content)return{content:'content is required for action: "set"',isError:!0};let c=t.saveHot(a.content),l={saved:!0,target:"hot",usage:{tokens:c.tokens,maxTokens:c.maxTokens,pct:c.pct}};return c.truncated?(l.truncated=!0,l.note='Hot memory exceeded the ~1,500-token cap and was truncated from the end (lowest-priority lines dropped; a sentinel marks the cut). Keep hot memory to a few durable essentials \u2014 move detail to the fact archive with target:"fact".'):c.pct>=xa*100&&(l.warning=`Hot memory is at ${c.pct}% of the ~1,500-token cap. Move non-essential lines to the fact archive (target:"fact") before it truncates.`),{content:JSON.stringify(l)}}if(a.action==="set"){if(!a.category)return{content:"category is required for fact storage",isError:!0};if(!a.content)return{content:'content is required for action: "set"',isError:!0};let c=t.storeFact({session_id:e,category:a.category,content:a.content,source_surface:n??"cli"});return{content:JSON.stringify({id:c,action:"set",target:"fact"})}}if(a.action==="supersede"){if(!a.supersedes)return{content:'supersedes (fact ID) is required for action: "supersede"',isError:!0};if(!a.content)return{content:'content is required for action: "supersede"',isError:!0};let c=t.supersedeFact(a.supersedes,a.content,a.category??void 0);return{content:JSON.stringify({id:c,action:"supersede",target:"fact",supersedes:a.supersedes})}}if(a.action==="remove"){if(!a.id)return{content:'id (fact ID) is required for action: "remove"',isError:!0};let c=t.removeFact(a.id);return{content:JSON.stringify({removed:c,action:"remove",target:"fact"})}}return{content:`Unknown action: ${a.action}`,isError:!0}}catch(a){return{content:`memory_update error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},s=async i=>{try{let a=pg(i);return t.writeProcedure(a.name,a.content,e),{content:JSON.stringify({name:a.name,written:!0})}}catch(a){return{content:`procedure_write error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}};return new Map([["memory_search",r],["memory_update",o],["procedure_write",s]])}function dg(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.query!="string")throw new Error("query (string) is required");let n={query:e.query};if(e.category!==void 0){if(typeof e.category!="string")throw new Error("category must be a string");let r=["preference","convention","decision","learning"];if(!r.includes(e.category))throw new Error(`category must be one of: ${r.join(", ")}`);n.category=e.category}if(e.since!==void 0){if(typeof e.since!="string")throw new Error("since must be a string (ISO date)");n.since=e.since}if(e.limit!==void 0){if(typeof e.limit!="number"||e.limit<=0)throw new Error("limit must be a positive number");n.limit=e.limit}return n}function ug(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t,n=["hot","fact"];if(typeof e.target!="string"||!n.includes(e.target))throw new Error(`target must be one of: ${n.join(", ")}`);let r=["set","supersede","remove"];if(typeof e.action!="string"||!r.includes(e.action))throw new Error(`action must be one of: ${r.join(", ")}`);let o={target:e.target,action:e.action};if(e.content!==void 0){if(typeof e.content!="string")throw new Error("content must be a string");o.content=e.content}if(e.category!==void 0){if(typeof e.category!="string")throw new Error("category must be a string");let s=["preference","convention","decision","learning"];if(!s.includes(e.category))throw new Error(`category must be one of: ${s.join(", ")}`);o.category=e.category}if(e.supersedes!==void 0){if(typeof e.supersedes!="number"||e.supersedes<=0)throw new Error("supersedes must be a positive fact ID");o.supersedes=e.supersedes}if(e.id!==void 0){if(typeof e.id!="number"||e.id<=0)throw new Error("id must be a positive fact ID");o.id=e.id}return o}function pg(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.name!="string")throw new Error("name (string) is required");if(typeof e.content!="string")throw new Error("content (string) is required");return{name:e.name,content:e.content}}function Co(t,e="all"){switch(e){case"self":return{self:t.getSelf()};case"tools":return{tools:t.getTools()};case"subagents":return{subagents:t.getSubagents()};case"workspace":return{workspace:t.getWorkspace()};default:return{self:t.getSelf(),tools:t.getTools(),subagents:t.getSubagents(),workspace:t.getWorkspace()}}}function Mo(t){return t==="self"||t==="tools"||t==="subagents"||t==="workspace"||t==="all"?t:"all"}function ut(t){let n=[`- Working directory: ${t.cwd.replace(/[\r\n]/g," ")}`],r=typeof t.sessionId=="string"&&t.sessionId.length>0?t.sessionId.slice(0,8):null,o=t.surface&&t.surface!=="unknown"?t.surface:null,s=typeof t.depth=="number"?typeof t.maxDepth=="number"?`depth ${t.depth}/${t.maxDepth}`:`depth ${t.depth}`:null,i=[o,s].filter(a=>typeof a=="string");if(r!==null||i.length>0){let a=["- Session:"];r!==null&&a.push(r),i.length>0&&a.push(`(${i.join(", ")})`),n.push(a.join(" "))}if(t.workspace!==void 0&&t.workspace!==null){let a=t.workspace;if(a.branch!==null||a.headSha!==null){let c=a.branch??"(detached)",l=a.headSha!==null?` @ ${a.headSha}`:"",d;a.dirty===null?d="":a.dirty?d=` (${a.dirtyCount!==null?a.dirtyCount:"?"} dirty)`:d=" (clean)",n.push(`- Workspace: ${c}${l}${d}`)}}return`# Environment
|
|
989
989
|
${n.join(`
|
|
990
990
|
`)}`}import{spawnSync as fg}from"child_process";var mg={branch:null,headSha:null,dirty:null,dirtyCount:null,remoteUrl:null};function Jn(t,e){try{let n=fg("git",e,{cwd:t,encoding:"utf8",maxBuffer:4096,shell:!1});if(n.status!==0||n.signal!==null||n.error!==void 0)return null;let r=typeof n.stdout=="string"?n.stdout.trim():null;return r!==null&&r.length>0?r:null}catch{return null}}function Oo(t){let e=Jn(t,["rev-parse","--short","HEAD"]);if(e===null)return{...mg};let n=Jn(t,["symbolic-ref","--short","HEAD"]),r=Jn(t,["status","--porcelain"]),o=!1,s=0;if(r!==null){let a=r.split(`
|
|
991
|
-
`).filter(c=>c.trim().length>0);o=a.length>0,s=a.length}r===null&&(o=null,s=null);let i=Jn(t,["remote","get-url","origin"]);return{branch:n,headSha:e,dirty:o,dirtyCount:s,remoteUrl:i}}function Wt(t){return{getSelf(){return{sessionId:t.sessionId??null,surface:hg(t.surface),parentSessionId:t.parentSessionId??null,depth:t.depth??null,maxDepth:t.maxDepth??null,phaseRole:t.phaseRole??null,cwd:t.cwd,model:{provider:t.providerName,name:t.modelName},permissionMode:gg(t.permissionMode)}},getTools(){return{enabled:t.getEnabledToolNames(),mcpServers:yg(t.getMcpTools())}},getSubagents(){return t.getSubagents()},getWorkspace(){return Oo(t.cwd)}}}function gg(t){switch(t){case"bypassPermissions":case"acceptEdits":case"dontAsk":case"auto":return"elevated";default:return"default"}}function hg(t){switch(t){case"cli":case"repl":case"daemon":case"telegram":case"subagent":return t;default:return"unknown"}}function yg(t){let e=new Map;for(let n of t){if(!n.name.startsWith("mcp__"))continue;let r=n.name.split("__");if(r.length<3)continue;let o=r[1];typeof o!="string"||o.length===0||e.set(o,(e.get(o)??0)+1)}return[...e.entries()].map(([n,r])=>({name:n,toolCount:r})).sort((n,r)=>n.name.localeCompare(r.name))}var he={name:"get_runtime_state",category:"other",concurrencySafe:!0,description:"Inspect what the runtime knows about this session: identity (sessionId, surface, depth, parent), tool affordances (currently-enabled tool names and MCP server summary), delegation state (active subagent handles, background jobs), and git workspace state (branch, HEAD SHA, dirty count, remote URL). Returns a compact JSON snapshot.\n\nUse when uncertain about: your current nesting depth, whether a tool you want is actually available right now, what MCP servers are wired, whether earlier subagents you dispatched are still running, or what git branch / commit the session started on.\n\nViews:\n- `self` \u2014 identity + model + permissions + cwd only\n- `tools` \u2014 enabled tool names + MCP server summary only\n- `subagents` \u2014 active subagent handles + background jobs only\n- `workspace` \u2014 git state (branch, headSha, dirty, dirtyCount, remoteUrl)\n- `all` \u2014 union of the four above (default)\n\nThis is a read-only, in-memory inspection. It does not probe the file system or network. Fields the runtime does not know (e.g. depth for a top-level session) come back as `null` rather than synthesised defaults.",input_schema:{type:"object",properties:{view:{type:"string",enum:["self","tools","subagents","workspace","all"],description:'Which slice of state to return. Defaults to "all". Use a narrower view when only one slice is needed to keep the response compact.'}},required:[]}},_e=[he.name];function pt(t){return async(e,n)=>{let r=e&&typeof e=="object"?Mo(e.view):"all",o=Co(t,r);return{content:JSON.stringify(o)}}}function Gt(t,e){let n=pt(e),r=t,o=Array.isArray(r.toolDefs)?r.toolDefs:null,s={async execute(i){return i.name==="get_runtime_state"?n(i.input,i.signal):t.execute(i)}};if(o!==null){let i=o.some(a=>a.name==="get_runtime_state");s.toolDefs=i?o:[...o,he]}return s}N();import{mkdir as bg,writeFile as Ca,unlink as lA,readdir as wg,readFile as Ma}from"fs/promises";import{unlinkSync as Sg,existsSync as vg}from"fs";import{join as Oa}from"path";function Do(t){return Oa(Ln(),`${t}.json`)}async function kg(){try{return await bg(Ln(),{recursive:!0}),!0}catch{return!1}}async function qt(t){try{if(!await kg())return;let n=Do(t.sessionId);await Ca(n,JSON.stringify(t,null,2),"utf8")}catch{}}async function Da(t,e){try{let n=Do(t),r=await Ma(n,"utf8"),o=JSON.parse(r);o.cwd=e,await Ca(n,JSON.stringify(o,null,2),"utf8")}catch{}}function Ee(t){try{let e=Do(t);vg(e)&&Sg(e)}catch{}}async function Vt(){let t=Ln(),e;try{e=await wg(t)}catch{return[]}let n=[];for(let r of e){if(!r.endsWith(".json"))continue;let o=Oa(t,r);try{let s=await Ma(o,"utf8"),i=JSON.parse(s);i!==null&&typeof i=="object"&&"sessionId"in i&&typeof i.sessionId=="string"&&n.push({...i,path:o})}catch{}}return n}var Tg=new Set([...le,Oe,De,Fe,...Le,he].filter(t=>t.concurrencySafe===!0).map(t=>t.name));function Fa(t){return Tg.has(t)}var Rg=8,Ig=new Set;function Pg(t){let e;try{e=JSON.stringify(t.input)??"null"}catch{e=String(t.input)}return xg("sha256").update(t.name).update("\0").update(e).digest("hex")}function Cg(t,e){return t.reduce((n,r,o)=>{let s=e(r.name,r.input),i=n[n.length-1];return i&&s&&i.isConcurrencySafe?i.indices.push(o):n.push({isConcurrencySafe:s,indices:[o]}),n},[])}var de=class{handlers;schemas;hookRegistry;permissions;subagentExecutor;skillExecutor;composeExecutor;classifier;resolveBase;_readRoots;_writeRoots;_allowAll;_env;sessionId;parentSessionId;traceWriter;readOnlyBash;repeatBreaker=null;constructor(e){this.handlers=e.handlers,this.schemas=e.schemas,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.subagentExecutor=e.subagentExecutor,this.skillExecutor=e.skillExecutor,this.composeExecutor=e.composeExecutor,this.classifier=e.concurrencyClassifier??Fa,this.resolveBase=e.cwd,this._env=e.env,this.sessionId=e.sessionId,this.parentSessionId=e.parentSessionId,this.traceWriter=e.traceWriter,this.readOnlyBash=e.readOnlyBash===!0,this._allowAll=e.allowAll===!0;let n=e.cwd?[e.cwd]:[];this._readRoots=e.readRoots??n.slice(),this._writeRoots=e.writeRoots??n.slice()}get handlerContext(){return{cwd:this.resolveBase,resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),...this._allowAll?{allowAll:!0}:{},...this._env!==void 0?{env:this._env}:{}}}addReadRoot(e,n="slash"){let r=Fo.resolve(e);this._readRoots.includes(r)||this._readRoots.push(r),this.appendAuditLog({action:"grant-read",path:r,source:n})}addWriteRoot(e,n="slash"){let r=Fo.resolve(e);this._readRoots.includes(r)||this._readRoots.push(r),this._writeRoots.includes(r)||this._writeRoots.push(r),this.appendAuditLog({action:"grant-write",path:r,source:n})}revokeRoot(e,n="slash"){let r=Fo.resolve(e);if(r===this.resolveBase)return;let o=this._readRoots.indexOf(r);o!==-1&&this._readRoots.splice(o,1);let s=this._writeRoots.indexOf(r);s!==-1&&this._writeRoots.splice(s,1),this.appendAuditLog({action:"revoke",path:r,source:n})}getGrants(){return{resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),allowAll:this._allowAll}}setAllowAll(e){this._allowAll=e}setResolveBase(e){let n=this.resolveBase;if(n!==e){if(this.resolveBase=e,n!==void 0){let r=this._readRoots.indexOf(n);r!==-1?this._readRoots[r]=e:this._readRoots.includes(e)||this._readRoots.push(e);let o=this._writeRoots.indexOf(n);o!==-1?this._writeRoots[o]=e:this._writeRoots.includes(e)||this._writeRoots.push(e)}else this._readRoots.includes(e)||this._readRoots.push(e),this._writeRoots.includes(e)||this._writeRoots.push(e);this.subagentExecutor?.setCwd(e),this.skillExecutor?.setCwd(e)}}appendAuditLog(e){try{let n=at();Eg(Ag(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:this.sessionId??null,action:e.action,path:e.path,source:e.source});_g(n,r+`
|
|
991
|
+
`).filter(c=>c.trim().length>0);o=a.length>0,s=a.length}r===null&&(o=null,s=null);let i=Jn(t,["remote","get-url","origin"]);return{branch:n,headSha:e,dirty:o,dirtyCount:s,remoteUrl:i}}function Wt(t){return{getSelf(){return{sessionId:t.sessionId??null,surface:hg(t.surface),parentSessionId:t.parentSessionId??null,depth:t.depth??null,maxDepth:t.maxDepth??null,phaseRole:t.phaseRole??null,cwd:t.cwd,model:{provider:t.providerName,name:t.modelName},permissionMode:gg(t.permissionMode)}},getTools(){return{enabled:t.getEnabledToolNames(),mcpServers:yg(t.getMcpTools())}},getSubagents(){return t.getSubagents()},getWorkspace(){return Oo(t.cwd)}}}function gg(t){switch(t){case"bypassPermissions":case"acceptEdits":case"dontAsk":case"auto":return"elevated";default:return"default"}}function hg(t){switch(t){case"cli":case"repl":case"daemon":case"telegram":case"subagent":return t;default:return"unknown"}}function yg(t){let e=new Map;for(let n of t){if(!n.name.startsWith("mcp__"))continue;let r=n.name.split("__");if(r.length<3)continue;let o=r[1];typeof o!="string"||o.length===0||e.set(o,(e.get(o)??0)+1)}return[...e.entries()].map(([n,r])=>({name:n,toolCount:r})).sort((n,r)=>n.name.localeCompare(r.name))}var he={name:"get_runtime_state",category:"other",concurrencySafe:!0,description:"Inspect what the runtime knows about this session: identity (sessionId, surface, depth, parent), tool affordances (currently-enabled tool names and MCP server summary), delegation state (active subagent handles, background jobs), and git workspace state (branch, HEAD SHA, dirty count, remote URL). Returns a compact JSON snapshot.\n\nUse when uncertain about: your current nesting depth, whether a tool you want is actually available right now, what MCP servers are wired, whether earlier subagents you dispatched are still running, or what git branch / commit the session started on.\n\nViews:\n- `self` \u2014 identity + model + permissions + cwd only\n- `tools` \u2014 enabled tool names + MCP server summary only\n- `subagents` \u2014 active subagent handles + background jobs only\n- `workspace` \u2014 git state (branch, headSha, dirty, dirtyCount, remoteUrl)\n- `all` \u2014 union of the four above (default)\n\nThis is a read-only, in-memory inspection. It does not probe the file system or network. Fields the runtime does not know (e.g. depth for a top-level session) come back as `null` rather than synthesised defaults.",input_schema:{type:"object",properties:{view:{type:"string",enum:["self","tools","subagents","workspace","all"],description:'Which slice of state to return. Defaults to "all". Use a narrower view when only one slice is needed to keep the response compact.'}},required:[]}},_e=[he.name];function pt(t){return async(e,n)=>{let r=e&&typeof e=="object"?Mo(e.view):"all",o=Co(t,r);return{content:JSON.stringify(o)}}}function Gt(t,e){let n=pt(e),r=t,o=Array.isArray(r.toolDefs)?r.toolDefs:null,s={async execute(i){return i.name==="get_runtime_state"?n(i.input,i.signal):t.execute(i)}};if(o!==null){let i=o.some(a=>a.name==="get_runtime_state");s.toolDefs=i?o:[...o,he]}return s}N();import{mkdir as bg,writeFile as Ca,unlink as lA,readdir as wg,readFile as Ma}from"fs/promises";import{unlinkSync as Sg,existsSync as vg}from"fs";import{join as Oa}from"path";function Do(t){return Oa(Ln(),`${t}.json`)}async function kg(){try{return await bg(Ln(),{recursive:!0}),!0}catch{return!1}}async function qt(t){try{if(!await kg())return;let n=Do(t.sessionId);await Ca(n,JSON.stringify(t,null,2),"utf8")}catch{}}async function Da(t,e){try{let n=Do(t),r=await Ma(n,"utf8"),o=JSON.parse(r);o.cwd=e,await Ca(n,JSON.stringify(o,null,2),"utf8")}catch{}}function Ee(t){try{let e=Do(t);vg(e)&&Sg(e)}catch{}}async function Vt(){let t=Ln(),e;try{e=await wg(t)}catch{return[]}let n=[];for(let r of e){if(!r.endsWith(".json"))continue;let o=Oa(t,r);try{let s=await Ma(o,"utf8"),i=JSON.parse(s);i!==null&&typeof i=="object"&&"sessionId"in i&&typeof i.sessionId=="string"&&n.push({...i,path:o})}catch{}}return n}var Tg=new Set([...le,Oe,De,Fe,...Le,he].filter(t=>t.concurrencySafe===!0).map(t=>t.name));function Fa(t){return Tg.has(t)}var Rg=8,Ig=new Set;function Pg(t){let e;try{e=JSON.stringify(t.input)??"null"}catch{e=String(t.input)}return xg("sha256").update(t.name).update("\0").update(e).digest("hex")}function Cg(t,e){return t.reduce((n,r,o)=>{let s=e(r.name,r.input),i=n[n.length-1];return i&&s&&i.isConcurrencySafe?i.indices.push(o):n.push({isConcurrencySafe:s,indices:[o]}),n},[])}var de=class{handlers;schemas;hookRegistry;permissions;subagentExecutor;skillExecutor;composeExecutor;classifier;resolveBase;_readRoots;_writeRoots;_allowAll;_env;sessionId;parentSessionId;traceWriter;readOnlyBash;repeatBreaker=null;constructor(e){this.handlers=e.handlers,this.schemas=e.schemas,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.subagentExecutor=e.subagentExecutor,this.skillExecutor=e.skillExecutor,this.composeExecutor=e.composeExecutor,this.classifier=e.concurrencyClassifier??Fa,this.resolveBase=e.cwd,this._env=e.env,this.sessionId=e.sessionId,this.parentSessionId=e.parentSessionId,this.traceWriter=e.traceWriter,this.readOnlyBash=e.readOnlyBash===!0,this._allowAll=e.allowAll===!0;let n=e.cwd?[e.cwd]:[];this._readRoots=e.readRoots??n.slice(),this._writeRoots=e.writeRoots??n.slice()}get handlerContext(){return{cwd:this.resolveBase,resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),...this._allowAll?{allowAll:!0}:{},...this._env!==void 0?{env:this._env}:{}}}addReadRoot(e,n="slash"){let r=Fo.resolve(e);this._readRoots.includes(r)||this._readRoots.push(r),this.appendAuditLog({action:"grant-read",path:r,source:n})}addWriteRoot(e,n="slash"){let r=Fo.resolve(e);this._readRoots.includes(r)||this._readRoots.push(r),this._writeRoots.includes(r)||this._writeRoots.push(r),this.appendAuditLog({action:"grant-write",path:r,source:n})}revokeRoot(e,n="slash"){let r=Fo.resolve(e);if(r===this.resolveBase)return;let o=this._readRoots.indexOf(r);o!==-1&&this._readRoots.splice(o,1);let s=this._writeRoots.indexOf(r);s!==-1&&this._writeRoots.splice(s,1),this.appendAuditLog({action:"revoke",path:r,source:n})}getGrants(){return{resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),allowAll:this._allowAll}}setAllowAll(e){this._allowAll=e}setResolveBase(e){let n=this.resolveBase;if(n!==e){if(this.resolveBase=e,n!==void 0){let r=this._readRoots.indexOf(n);r!==-1?this._readRoots[r]=e:this._readRoots.includes(e)||this._readRoots.push(e);let o=this._writeRoots.indexOf(n);o!==-1?this._writeRoots[o]=e:this._writeRoots.includes(e)||this._writeRoots.push(e)}else this._readRoots.includes(e)||this._readRoots.push(e),this._writeRoots.includes(e)||this._writeRoots.push(e);this.subagentExecutor?.setCwd(e),this.skillExecutor?.setCwd(e),this.composeExecutor?.setCwd(e)}}appendAuditLog(e){try{let n=at();Eg(Ag(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:this.sessionId??null,action:e.action,path:e.path,source:e.source});_g(n,r+`
|
|
992
992
|
`)}catch{}}get toolDefs(){return this.schemas}checkReadOnlyBash(e){if(!this.readOnlyBash||e.name!=="bash")return null;let n=e.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=ha(r);return o.mutating?{content:`Bash command blocked: read-only skill may not run mutating commands (${o.reason??"mutation detected"}). Allowed: read-only recon (git status/log/diff, ls, cat, find, grep).`,isError:!0,failureClass:"permission-denied"}:null}checkRepeatCircuitBreaker(e){if(Ig.has(e.name))return null;let n=Pg(e);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<Rg?null:{content:`Loop circuit breaker: "${e.name}" has been called ${this.repeatBreaker.count} times in a row with byte-identical input. The result will not change. Stop repeating this call \u2014 reuse the previous result, change the input, try a different tool, or end the turn.`,isError:!0,circuitBreaker:!0}}async execute(e){if(e.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:"abort"};if(this.hookRegistry){let a={event:"PreToolUse",toolName:e.name,input:e.input,...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};try{await Eo(this.hookRegistry,a,{signal:e.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(c){if(c instanceof q)return{content:`Tool "${e.name}" blocked by PreToolUse hook: ${c.message}`,isError:!0,failureClass:"hook-block"};throw c}}let n=Ht(e.name,this.permissions);if(!n.allowed)return{content:n.reason??`Tool "${e.name}" is not permitted`,isError:!0,failureClass:"permission-denied"};let r=this.checkReadOnlyBash(e);if(r)return r;let o=this.checkRepeatCircuitBreaker(e);if(o)return o;if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let a;try{a=await this.subagentExecutor.execute(e)}catch(c){a={content:`Agent tool error: ${c instanceof Error?c.message:String(c)}`,isError:!0}}return this.firePostToolUse(e.name,a.content,e.signal,e.input),a}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let a;try{a=await this.skillExecutor.execute(e)}catch(c){a={content:`Skill tool error: ${c instanceof Error?c.message:String(c)}`,isError:!0}}return this.firePostToolUse(e.name,a.content,e.signal,e.input),a}if(e.name==="compose"){let a=await this.executeCompose(e);return this.firePostToolUse(e.name,a.content,e.signal,e.input),a}let s=this.handlers.get(e.name);if(!s)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let i;try{i=await s(e.input,e.signal,this.handlerContext)}catch(a){i={content:`Tool execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}return this.firePostToolUse(e.name,i.content,e.signal,e.input),i}async executeBatch(e){if(e.length===0)return[];if(e.length===1)return[await this.execute(e[0])];let n=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){let a=e[i];if(a.signal.aborted){n[i]={content:"Tool call aborted",isError:!0,failureClass:"abort"},r.add(i);continue}if(this.hookRegistry){let u={event:"PreToolUse",toolName:a.name,input:a.input,...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};try{await Eo(this.hookRegistry,u,{signal:a.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(p){if(p instanceof q){n[i]={content:`Tool "${a.name}" blocked by PreToolUse hook: ${p.message}`,isError:!0,failureClass:"hook-block"},r.add(i);continue}throw p}}let c=Ht(a.name,this.permissions);if(!c.allowed){n[i]={content:c.reason??`Tool "${a.name}" is not permitted`,isError:!0,failureClass:"permission-denied"},r.add(i);continue}let l=this.checkReadOnlyBash(a);if(l){n[i]=l,r.add(i);continue}let d=this.checkRepeatCircuitBreaker(a);if(d){n[i]=d,r.add(i);continue}}let o=e.map((i,a)=>({call:i,originalIndex:a})).filter((i,a)=>!r.has(a));if(o.length===0)return n;let s=Cg(o.map(i=>i.call),this.classifier);for(let i of s)if(i.isConcurrencySafe){let a=await Promise.allSettled(i.indices.map(async c=>{let{call:l,originalIndex:d}=o[c];return l.signal.aborted?{result:{content:"Tool call aborted",isError:!0,failureClass:"abort"},originalIndex:d}:{result:await this.executeCore(l),originalIndex:d}}));for(let c of a)if(c.status==="fulfilled")n[c.value.originalIndex]=c.value.result;else{let l=c.reason instanceof Error?c.reason.message:String(c.reason),d=i.indices[a.indexOf(c)];n[o[d].originalIndex]={content:`Tool execution error: ${l}`,isError:!0}}}else for(let a of i.indices){let{call:c,originalIndex:l}=o[a];if(c.signal.aborted){n[l]={content:"Tool call aborted",isError:!0,failureClass:"abort"};continue}n[l]=await this.executeCore(c)}return n}async executeCore(e){if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let o;try{o=await this.subagentExecutor.execute(e)}catch(s){o={content:`Agent tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}return this.firePostToolUse(e.name,o.content,e.signal,e.input),o}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let o;try{o=await this.skillExecutor.execute(e)}catch(s){o={content:`Skill tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}return this.firePostToolUse(e.name,o.content,e.signal,e.input),o}if(e.name==="compose"){let o=await this.executeCompose(e);return this.firePostToolUse(e.name,o.content,e.signal,e.input),o}let n=this.handlers.get(e.name);if(!n)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let r;try{r=await n(e.input,e.signal,this.handlerContext)}catch(o){r={content:`Tool execution error: ${o instanceof Error?o.message:String(o)}`,isError:!0}}return this.firePostToolUse(e.name,r.content,e.signal,e.input),r}async executeCompose(e){if(!this.composeExecutor)return{content:"Compose tool is not available in this session configuration",isError:!0};try{return await this.composeExecutor.execute(e)}catch(n){return{content:`Compose tool error: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}firePostToolUse(e,n,r,o){if(!this.hookRegistry)return;let s={event:"PostToolUse",toolName:e,output:n,...o!==void 0?{input:o}:{}};Zi(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(()=>{})}};import{spawn as Xg}from"child_process";var Mg=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,Og=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,Dg=/={3,}\s*(?:(\d+)\s+failed,\s*)?(\d+)\s+passed(?:,\s*(\d+)\s+warning)?.*in\s+[\d.]+s\s*={3,}|={3,}\s*(\d+)\s+passed.*in\s+[\d.]+s\s*={3,}/,Fg=/(\d+)\s+passing/,Lg=/(\d+)\s+failing/,Ng=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,$g=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,Ug=/(\d+) examples?, (\d+) failures?/,Bg=/OK \((\d+) tests?/,Hg=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/;function jg(t){let e=t.match(Mg);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10),o=e[3]!==void 0?parseInt(e[3],10):void 0;return{runner:"vitest",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function Kg(t){let e=t.match(Og);if(!e)return null;let n=parseInt(e[1]??"0",10);return{runner:"jest",passed:parseInt(e[2]??"0",10),failed:n}}function Wg(t){let e=t.match(Dg);if(!e)return null;if(e[2]!==void 0){let n=parseInt(e[2],10),r=parseInt(e[1]??"0",10);return{runner:"pytest",passed:n,failed:r}}return e[4]!==void 0?{runner:"pytest",passed:parseInt(e[4],10),failed:0}:null}function Gg(t){let e=t.match(Fg);if(!e)return null;let n=parseInt(e[1]??"0",10),r=t.match(Lg),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function qg(t){let e=[...t.matchAll(Ng)];if(e.length===0)return null;let n=0,r=0;for(let o of e)o[1]==="ok"?n++:o[1]==="FAIL"&&r++;return{runner:"go-test",passed:n,failed:r}}function Vg(t){let e=t.match($g);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10),o=e[3]!==void 0?parseInt(e[3],10):void 0;return{runner:"cargo",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function Jg(t){let e=t.match(Ug);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10);return{runner:"rspec",passed:n-r,failed:r}}function zg(t){let e=t.match(Bg);if(e)return{runner:"phpunit",passed:parseInt(e[1]??"0",10),failed:0};let n=t.match(Hg);if(n){let r=parseInt(n[1]??"0",10),o=parseInt(n[2]??"0",10);return{runner:"phpunit",passed:r-o,failed:o}}return null}function Lo(t){return jg(t)??Kg(t)??Wg(t)??Gg(t)??qg(t)??Vg(t)??Jg(t)??zg(t)??null}var La=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,Yg=/[\x00-\x1F\x7F-\x9F]/g;function zn(t){return t.replace(La,"").replace(Yg," ").trim()}function ze(t){return t.replace(La,"")}function Qg(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(e.timeout_ms<0||e.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=e.timeout_ms}return{command:e.command,timeout_ms:n}}function Yn(t,e){let n=!1;function r(){n||t==="bypassPermissions"&&(n=!0,console.warn("[security] bash handler: shell=true with bypassPermissions \u2014 all shell metacharacters are interpreted without confirmation. Migrate to execFile to eliminate this risk (tracked: C4)."))}return async(o,s,i)=>{let{command:a,timeout_ms:c}=Qg(o);return s.aborted?{content:"Command aborted",isError:!0}:(r(),new Promise(l=>{let d=!1;function u(_){d||(d=!0,clearTimeout(f),s.removeEventListener("abort",y),l(_))}let p=Xg(a,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...(i?.resolveBase??i?.cwd??e)!==void 0?{cwd:i?.resolveBase??i?.cwd??e}:{},...i?.env!==void 0?{env:{...process.env,...i.env}}:{}});p.unref();let f=setTimeout(()=>{p.pid!==void 0&&process.kill(-p.pid,"SIGKILL"),u({content:`Command timed out after ${c}ms`,isError:!0})},c),g="",m="",S=1e5,v=0,k=!1;function h(_){if(k||d||v<S)return;k=!0,console.warn(`[bash] overflow kill: stream=${_} totalBytes=${v} command="${a}"`),ce({event:"tool.overflow_kill",tool:"bash",total_bytes:v,stream:_}),p.kill("SIGKILL");let E=(g+m).trimEnd();E=ze(E);let T=Lo(E)??void 0;E.length>S&&(E=E.slice(0,S)),E+=`
|
|
993
993
|
[output truncated \u2014 exceeded 100KB]`,u({content:E,truncated:!0,...T!==void 0?{testResult:T}:{}})}p.stdout.on("data",_=>{let E=S-v,T=_.length<=E?_:_.subarray(0,Math.max(0,E));v+=T.length,g+=T.toString("utf8"),h("stdout")}),p.stderr.on("data",_=>{let E=S-v,T=_.length<=E?_:_.subarray(0,Math.max(0,E));v+=T.length,m+=T.toString("utf8"),h("stderr")});let y=()=>{p.pid!==void 0&&process.kill(-p.pid,"SIGKILL"),u({content:"Command aborted",isError:!0})};s.addEventListener("abort",y),p.on("close",_=>{if(s.aborted){u({content:"Command aborted",isError:!0});return}if(_!==null&&_!==0){let O=m.trimEnd()||g.trimEnd();u({content:`Command exited with code ${_}${O?`
|
|
994
994
|
`+O:""}`,isError:!0});return}if(k)return;let E=(g+m).trimEnd();E=ze(E);let T=Lo(E)??void 0,C=!1;E.length>S&&(E=E.slice(0,S)+`
|
|
@@ -1283,7 +1283,7 @@ ${e.body}`)}function cv(t,e){return t.length===0||t.length>64?{valid:!1,reason:`
|
|
|
1283
1283
|
</transcript>`}],stream:!0}}function Iu(t,e,n){return[{role:"user",content:Au+`
|
|
1284
1284
|
|
|
1285
1285
|
`+n},{role:"assistant",content:xu},...t.slice(e)]}function Pu(t,e,n){let r=$v(t.slice(0,e)),o=Au.length+2+n.length+xu.length,s=Math.max(0,r-o);return Math.round(s/4)}function Nv(t){let e=[];for(let n of t){let r=n.role==="user"?"User":"Assistant";if(e.push(r+":"),typeof n.content=="string")e.push(n.content);else if(Array.isArray(n.content))for(let o of n.content){let s=o.type;if(s==="text"&&"text"in o)e.push(o.text);else if(s==="tool_use"){let i=o.name??"unknown",a=Cu(o.input);e.push(`[tool call: ${i} ${a}]`)}else if(s==="tool_result"){let i=o.content;e.push(`[tool result: ${Mu(i)}]`)}else s==="image"?e.push("[image]"):s==="document"&&e.push("[document]")}e.push("")}return e.join(`
|
|
1286
|
-
`).trim()}function Cu(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function Mu(t){if(typeof t=="string")return t.length>320?t.slice(0,317)+"...":t;if(Array.isArray(t)){let e=[];for(let r of t)r.type==="text"&&"text"in r&&e.push(r.text);let n=e.join(" ");return n.length>320?n.slice(0,317)+"...":n}return""}function $v(t){let e=0;for(let n of t)if(typeof n.content=="string")e+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content){let o=r.type;o==="text"&&"text"in r?e+=r.text.length:o==="tool_use"?e+=Cu(r.input).length:o==="tool_result"&&(e+=Mu(r.content).length)}return e}L();var Bv=2,Hv="claude-haiku-4-5-20251001",jv=1024;async function Ou(t){let{state:e,abort:n,retry:r,initSessionId:o,traceWriter:s}=t,i=e.messages.length;if(e.closed)return{compacted:!1,reason:"session-closed",messagesBefore:i,messagesAfter:i};if(!n.isIdle())return{compacted:!1,reason:"turn-in-flight",messagesBefore:i,messagesAfter:i};let a=Kv(),c=Tu(e.messages,a);if(c<0)return{compacted:!1,reason:"history-too-short",messagesBefore:i,messagesAfter:i};if(c===0)return{compacted:!1,reason:"nothing-to-summarize",messagesBefore:i,messagesAfter:i};let l=e.messages.slice(0,c),d=Wv(),u=Ru(l,d,jv),p=n.begin(),f;try{if(p.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let v=ge(r.authMode,o,Uv()),k=r.client,h=await Promise.resolve(k.messages.create(u,{headers:v,signal:p.signal}));f=await Gv(h)}catch(v){return p.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i}:{compacted:!1,reason:"summarization-failed: "+(v instanceof Error?v.message:String(v)),messagesBefore:i,messagesAfter:i}}finally{n.clear(p)}if(f.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:i,messagesAfter:i};let g=Pu(e.messages,c,f),m=Iu(e.messages,c,f);e.messages.splice(0,e.messages.length,...m);let S=e.messages.length;return Ri(s,{trigger:"manual",preCompactionMessages:l,summary:f,keptTailCount:i-c,keepLastNConfig:a,messagesBefore:i,messagesAfter:S,tokensSavedEstimate:g}),{compacted:!0,messagesBefore:i,messagesAfter:S,tokensSavedEstimate:g}}function Kv(){let t=b.AFK_COMPACT_KEEP_LAST_TURNS;if(t!==void 0&&t.length>0){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return Bv}function Wv(){let t=b.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?ee(t)??t:Hv}async function Gv(t){let e="";for await(let n of t)if(n.type==="content_block_delta"){let r=n.delta;r.type==="text_delta"&&typeof r.text=="string"&&(e+=r.text)}return e}var qv=[{value:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",description:"Latest balanced Claude \u2014 recommended default"},{value:"claude-opus-4-5-20250929",displayName:"Claude Opus 4.5",description:"Highest-capability Claude"},{value:"claude-haiku-4-5-20250929",displayName:"Claude Haiku 4.5",description:"Fastest, cheapest Claude"}],$r=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;baseUrl;traceWriter;state;abort;retry;cwdDependentsFactory;onPermissionMode;mcpManager;constructor(e){this.initSessionId=e.sessionId??Du(),this.promptStream=e.promptStream,this.maxTokens=e.maxTokens,this.tools=e.tools,this.systemPrefix=e.systemPrefix,this.thinking=e.thinking,e.effort!==void 0&&(this.effort=e.effort),e.baseUrl!==void 0&&(this.baseUrl=e.baseUrl),this.traceWriter=e.traceWriter,this.cwdDependentsFactory=e.cwdDependentsFactory,this.onPermissionMode=e.onPermissionMode,this.mcpManager=e.mcpManager,this.retry=new Nr({client:e.client,authMode:e.authMode,initSessionId:this.initSessionId,...e.tokenRefresher?{tokenRefresher:e.tokenRefresher}:{},autoResumeOnUsageLimit:e.autoResumeOnUsageLimit??!0}),this.state=hu({model:e.model,...e.requestedModel!==void 0?{requestedModel:e.requestedModel}:{},permissionMode:e.permissionMode??"default",userSystem:e.userSystem,toolDispatcher:e.toolDispatcher,...e.initialMessages?{initialMessages:e.initialMessages}:{},...e.autoCompactThreshold!==void 0?{autoCompactThreshold:e.autoCompactThreshold}:{}}),this.abort=new Fr}async*[Symbol.asyncIterator](){yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.state.currentModel,permissionMode:this.state.currentPermissionMode,cwd:process.cwd(),tools:[],slashCommands:[],skills:[],plugins:[],mcpServers:this.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:this.retry.authMode,version:"anthropic-direct-v1"}};let n=this.promptStream[Symbol.asyncIterator]();try{for(;!this.state.closed;){let r=await Promise.race([n.next(),this.abort.closedPromise]);if(r==="__closed__")break;let o=r;if(o.done)break;let s=o.value,i=this.abort.begin();if(i.signal.aborted){this.abort.clear(i);return}gu(this.state.messages),this.state.messages.push({role:"user",content:s.content});let a=this.composeSystem(),c=ge(this.retry.authMode,this.initSessionId,Du(),this.effort!==void 0),l={client:this.retry.client,messages:this.state.messages,system:a,tools:this.tools,toolDispatcher:this.state.toolDispatcher,model:this.state.currentModel,maxTokens:this.maxTokens,headers:c,signal:i.signal,ctx:{sessionId:this.initSessionId},...this.thinking!==void 0?{thinking:this.thinking}:{},...this.effort!==void 0?{effort:this.effort}:{},...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{},...this.traceWriter?{traceWriter:this.traceWriter}:{},onUsageProgress:d=>{this.state.lastUsage=d}};try{for await(let d of this.retry.turnWithRetries(l,()=>this.state.closed)){if(this.state.closed)return;d.type==="turn.completed"&&(this.state.lastUsage=d.usage,this.abort.clear(i)),yield d}}catch(d){if(i.signal.aborted)return;yield{type:"error",error:d instanceof Error?d:new Error(String(d))};return}finally{this.abort.clear(i)}if(this.state.autoCompactThreshold!==void 0&&!this.state.closed){let d=this.state.lastUsage,u=an(this.state.requestedModel);if(d!==null&&u>0){let p=St(d);od(p,u,this.state.autoCompactThreshold)&&await this.compact()}}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}composeSystem(){let e=this.systemPrefix,n=this.state.userSystem,r=[];e&&e.length>0&&r.push(...e),n&&n.length>0&&r.push({type:"text",text:n});let o=Vi(this.state.currentPermissionMode);o!==null&&r.push(o);let s=Ji(this.state.currentPermissionMode);return s!==null&&r.push(s),r.length===0?null:Pn({baseUrl:this.baseUrl})?Wi(r,Cn()):r}async interrupt(){this.abort.requestAbort("interrupted")}async setModel(e){e!==void 0&&e.length>0&&(this.state.requestedModel=e,this.state.currentModel=ee(e)??e)}async setPermissionMode(e){this.state.currentPermissionMode=e;let n=e==="bypassPermissions";this.state.toolDispatcher.setAllowAll?.(n),this.onPermissionMode?.(e)}setCwd(e){if(this.state.toolDispatcher.setResolveBase?.(e),!this.cwdDependentsFactory)return;let{userSystem:n,dispatcher:r}=this.cwdDependentsFactory(e);this.state.userSystem=n,this.state.toolDispatcher=r}async supportedCommands(){try{return vt().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return qv.map(e=>({...e}))}async supportedAgents(){return[]}async getContextUsage(){let e=this.state.lastUsage,n=an(this.state.requestedModel),r;if(e&&n>0){let i=St(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=Sr(e);return{tools:[],agents:[],isAutoCompactEnabled:this.state.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.mcpManager?this.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{subscriptionType:this.retry.authMode==="oauth"?"claude-subscription":"api-key"}}async reauth(){return this.retry.forceClientRefresh()}async rewindFiles(e,n){return{canRewind:!1,error:"anthropic-direct provider does not support file checkpoint rewind"}}async compact(){return Ou({state:this.state,abort:this.abort,retry:this.retry,initSessionId:this.initSessionId,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}close(){this.state.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed()}};var Vv=t=>/opus-4-(7|[89])/.test(t),Jv=.9;function ei(t){if(t===void 0||t===!1)return;if(t===!0)return Jv;let e=t.threshold;if(!(typeof e!="number"||!Number.isFinite(e)||e<=0||e>=1))return e}var Ur=new Set,zv=.25;function ti(t,e){let n=br(e),r=t.maxOutputTokens;if(typeof r=="number"&&Number.isFinite(r)&&r>0){let o=Math.floor(r);if(o>n){let s=`max:${e}:${o}`;return Ur.has(s)||(Ur.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${e} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function Fu(t){if(!t||t.length===0)return;let e=[];for(let n of t)n.user.length>0&&e.push({role:"user",content:n.user}),n.assistant.length>0&&e.push({role:"assistant",content:n.assistant});return e.length>0?e:void 0}function ni(t,e,n){switch(t.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&Vv(n))return{type:"adaptive",display:"summarized"};let r=Math.floor(e*zv),o=Math.max(1024,e-1-r),s=t.budgetTokens!==void 0&&Number.isFinite(t.budgetTokens)?Math.floor(t.budgetTokens):void 0,i=Math.min(Math.max(s??o,1024),o);if(s!==void 0&&s>o){let a=`think:${n??"default"}:${s}:${e}`;Ur.has(a)||(Ur.add(a),console.warn(`[afk] thinking budgetTokens ${s} leaves too little of max_tokens ${e} for the reply; clamping to ${o}.`))}return{type:"enabled",budget_tokens:i,display:"summarized"}}}}function ri(t,e){if(t!==void 0)return t;let n=e.toLowerCase();if(/(claude-)?(opus|sonnet)-4-[678]/.test(n))return"max"}var Br=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
|
|
1286
|
+
`).trim()}function Cu(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function Mu(t){if(typeof t=="string")return t.length>320?t.slice(0,317)+"...":t;if(Array.isArray(t)){let e=[];for(let r of t)r.type==="text"&&"text"in r&&e.push(r.text);let n=e.join(" ");return n.length>320?n.slice(0,317)+"...":n}return""}function $v(t){let e=0;for(let n of t)if(typeof n.content=="string")e+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content){let o=r.type;o==="text"&&"text"in r?e+=r.text.length:o==="tool_use"?e+=Cu(r.input).length:o==="tool_result"&&(e+=Mu(r.content).length)}return e}L();var Bv=2,Hv="claude-haiku-4-5-20251001",jv=1024;async function Ou(t){let{state:e,abort:n,retry:r,initSessionId:o,traceWriter:s}=t,i=e.messages.length;if(e.closed)return{compacted:!1,reason:"session-closed",messagesBefore:i,messagesAfter:i};if(!n.isIdle())return{compacted:!1,reason:"turn-in-flight",messagesBefore:i,messagesAfter:i};let a=Kv(),c=Tu(e.messages,a);if(c<0)return{compacted:!1,reason:"history-too-short",messagesBefore:i,messagesAfter:i};if(c===0)return{compacted:!1,reason:"nothing-to-summarize",messagesBefore:i,messagesAfter:i};let l=e.messages.slice(0,c),d=Wv(),u=Ru(l,d,jv),p=n.begin(),f;try{if(p.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let v=ge(r.authMode,o,Uv()),k=r.client,h=await Promise.resolve(k.messages.create(u,{headers:v,signal:p.signal}));f=await Gv(h)}catch(v){return p.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i}:{compacted:!1,reason:"summarization-failed: "+(v instanceof Error?v.message:String(v)),messagesBefore:i,messagesAfter:i}}finally{n.clear(p)}if(f.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:i,messagesAfter:i};let g=Pu(e.messages,c,f),m=Iu(e.messages,c,f);e.messages.splice(0,e.messages.length,...m);let S=e.messages.length;return Ri(s,{trigger:"manual",preCompactionMessages:l,summary:f,keptTailCount:i-c,keepLastNConfig:a,messagesBefore:i,messagesAfter:S,tokensSavedEstimate:g}),{compacted:!0,messagesBefore:i,messagesAfter:S,tokensSavedEstimate:g}}function Kv(){let t=b.AFK_COMPACT_KEEP_LAST_TURNS;if(t!==void 0&&t.length>0){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return Bv}function Wv(){let t=b.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?ee(t)??t:Hv}async function Gv(t){let e="";for await(let n of t)if(n.type==="content_block_delta"){let r=n.delta;r.type==="text_delta"&&typeof r.text=="string"&&(e+=r.text)}return e}var qv=[{value:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",description:"Latest balanced Claude \u2014 recommended default"},{value:"claude-opus-4-5-20250929",displayName:"Claude Opus 4.5",description:"Highest-capability Claude"},{value:"claude-haiku-4-5-20250929",displayName:"Claude Haiku 4.5",description:"Fastest, cheapest Claude"}],$r=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;baseUrl;traceWriter;state;abort;retry;cwdDependentsFactory;onPermissionMode;mcpManager;constructor(e){this.initSessionId=e.sessionId??Du(),this.promptStream=e.promptStream,this.maxTokens=e.maxTokens,this.tools=e.tools,this.systemPrefix=e.systemPrefix,this.thinking=e.thinking,e.effort!==void 0&&(this.effort=e.effort),e.baseUrl!==void 0&&(this.baseUrl=e.baseUrl),this.traceWriter=e.traceWriter,this.cwdDependentsFactory=e.cwdDependentsFactory,this.onPermissionMode=e.onPermissionMode,this.mcpManager=e.mcpManager,this.retry=new Nr({client:e.client,authMode:e.authMode,initSessionId:this.initSessionId,...e.tokenRefresher?{tokenRefresher:e.tokenRefresher}:{},autoResumeOnUsageLimit:e.autoResumeOnUsageLimit??!0}),this.state=hu({model:e.model,...e.requestedModel!==void 0?{requestedModel:e.requestedModel}:{},permissionMode:e.permissionMode??"default",userSystem:e.userSystem,toolDispatcher:e.toolDispatcher,...e.initialMessages?{initialMessages:e.initialMessages}:{},...e.autoCompactThreshold!==void 0?{autoCompactThreshold:e.autoCompactThreshold}:{}}),this.abort=new Fr}async*[Symbol.asyncIterator](){yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.state.currentModel,permissionMode:this.state.currentPermissionMode,cwd:process.cwd(),tools:[],slashCommands:[],skills:[],plugins:[],mcpServers:this.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:this.retry.authMode,version:"anthropic-direct-v1"}};let n=this.promptStream[Symbol.asyncIterator]();try{for(;!this.state.closed;){let r=await Promise.race([n.next(),this.abort.closedPromise]);if(r==="__closed__")break;let o=r;if(o.done)break;let s=o.value,i=this.abort.begin();if(i.signal.aborted){this.abort.clear(i);return}gu(this.state.messages),this.state.messages.push({role:"user",content:s.content});let a=this.composeSystem(),c=ge(this.retry.authMode,this.initSessionId,Du(),this.effort!==void 0),l={client:this.retry.client,messages:this.state.messages,system:a,tools:this.tools,toolDispatcher:this.state.toolDispatcher,model:this.state.currentModel,maxTokens:this.maxTokens,headers:c,signal:i.signal,ctx:{sessionId:this.initSessionId},...this.thinking!==void 0?{thinking:this.thinking}:{},...this.effort!==void 0?{effort:this.effort}:{},...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{},...this.traceWriter?{traceWriter:this.traceWriter}:{},onUsageProgress:d=>{this.state.lastUsage=d}};try{for await(let d of this.retry.turnWithRetries(l,()=>this.state.closed)){if(this.state.closed)return;d.type==="turn.completed"&&(this.state.lastUsage=d.usage,this.abort.clear(i)),yield d}}catch(d){if(i.signal.aborted)return;yield{type:"error",error:d instanceof Error?d:new Error(String(d))};return}finally{this.abort.clear(i)}if(i.signal.aborted)return;if(this.state.autoCompactThreshold!==void 0&&!this.state.closed){let d=this.state.lastUsage,u=an(this.state.requestedModel);if(d!==null&&u>0){let p=St(d);od(p,u,this.state.autoCompactThreshold)&&await this.compact()}}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}composeSystem(){let e=this.systemPrefix,n=this.state.userSystem,r=[];e&&e.length>0&&r.push(...e),n&&n.length>0&&r.push({type:"text",text:n});let o=Vi(this.state.currentPermissionMode);o!==null&&r.push(o);let s=Ji(this.state.currentPermissionMode);return s!==null&&r.push(s),r.length===0?null:Pn({baseUrl:this.baseUrl})?Wi(r,Cn()):r}async interrupt(){this.abort.requestAbort("interrupted")}async setModel(e){e!==void 0&&e.length>0&&(this.state.requestedModel=e,this.state.currentModel=ee(e)??e)}async setPermissionMode(e){this.state.currentPermissionMode=e;let n=e==="bypassPermissions";this.state.toolDispatcher.setAllowAll?.(n),this.onPermissionMode?.(e)}setCwd(e){if(this.state.toolDispatcher.setResolveBase?.(e),!this.cwdDependentsFactory)return;let{userSystem:n,dispatcher:r}=this.cwdDependentsFactory(e);this.state.userSystem=n,this.state.toolDispatcher=r}async supportedCommands(){try{return vt().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return qv.map(e=>({...e}))}async supportedAgents(){return[]}async getContextUsage(){let e=this.state.lastUsage,n=an(this.state.requestedModel),r;if(e&&n>0){let i=St(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=Sr(e);return{tools:[],agents:[],isAutoCompactEnabled:this.state.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.mcpManager?this.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{subscriptionType:this.retry.authMode==="oauth"?"claude-subscription":"api-key"}}async reauth(){return this.retry.forceClientRefresh()}async rewindFiles(e,n){return{canRewind:!1,error:"anthropic-direct provider does not support file checkpoint rewind"}}async compact(){return Ou({state:this.state,abort:this.abort,retry:this.retry,initSessionId:this.initSessionId,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}close(){this.state.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed()}};var Vv=t=>/opus-4-(7|[89])/.test(t),Jv=.9;function ei(t){if(t===void 0||t===!1)return;if(t===!0)return Jv;let e=t.threshold;if(!(typeof e!="number"||!Number.isFinite(e)||e<=0||e>=1))return e}var Ur=new Set,zv=.25;function ti(t,e){let n=br(e),r=t.maxOutputTokens;if(typeof r=="number"&&Number.isFinite(r)&&r>0){let o=Math.floor(r);if(o>n){let s=`max:${e}:${o}`;return Ur.has(s)||(Ur.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${e} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function Fu(t){if(!t||t.length===0)return;let e=[];for(let n of t)n.user.length>0&&e.push({role:"user",content:n.user}),n.assistant.length>0&&e.push({role:"assistant",content:n.assistant});return e.length>0?e:void 0}function ni(t,e,n){switch(t.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&Vv(n))return{type:"adaptive",display:"summarized"};let r=Math.floor(e*zv),o=Math.max(1024,e-1-r),s=t.budgetTokens!==void 0&&Number.isFinite(t.budgetTokens)?Math.floor(t.budgetTokens):void 0,i=Math.min(Math.max(s??o,1024),o);if(s!==void 0&&s>o){let a=`think:${n??"default"}:${s}:${e}`;Ur.has(a)||(Ur.add(a),console.warn(`[afk] thinking budgetTokens ${s} leaves too little of max_tokens ${e} for the reply; clamping to ${o}.`))}return{type:"enabled",budget_tokens:i,display:"summarized"}}}}function ri(t,e){if(t!==void 0)return t;let n=e.toLowerCase();if(/(claude-)?(opus|sonnet)-4-[678]/.test(n))return"max"}var Br=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
|
|
1287
1287
|
|
|
1288
1288
|
- Use read_file before editing to verify the exact content you want to change.
|
|
1289
1289
|
- Prefer edit_file over write_file for modifying existing files \u2014 write_file is for new files or complete rewrites.
|
|
@@ -1347,7 +1347,7 @@ ${oi}
|
|
|
1347
1347
|
|
|
1348
1348
|
${si}`,E=this.readOnlyMemory?Nu:Lu,T=[_,E];T.push(ut({cwd:y,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.surface,...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:m.getWorkspace()})),h.length>0&&T.push(h),d&&T.push(d);let C=T.join(`
|
|
1349
1349
|
|
|
1350
|
-
`),O=[_,E];h.length>0&&O.push(h),d&&O.push(d),$u({prompt:e.prompt,options:{model:u,maxTokens:p,system:C},provenance:{systemPrompt:{source:n.systemPromptSource??"none",shape:typeof n.systemPrompt=="string"?"string":Array.isArray(n.systemPrompt)?"string[]":n.systemPrompt!=null?"preset":"undefined",...typeof n.systemPrompt=="string"?{length:n.systemPrompt.length}:{}},...n.apiKey?{apiKey:{source:"config"}}:{}}});let F;if(s==="oauth"&&!r){let R=this.providerFactory??ci;F=async()=>{let P=await So();if(!P)return null;let W=Mt(P,"oauth",n.baseUrl);return R?R(W):new Uu(W)}}let w=n.sessionId??n.resume,A=Fu(n.resumeHistory),x=this.externalTools?void 0:R=>{let P=this._currentCwd;if(this._sharedReadRoots&&P!==void 0&&P!==R){let G=this._sharedReadRoots.indexOf(P);G!==-1?this._sharedReadRoots[G]=R:this._sharedReadRoots.includes(R)||this._sharedReadRoots.push(R)}if(this._sharedWriteRoots&&P!==void 0&&P!==R){let G=this._sharedWriteRoots.indexOf(P);G!==-1?this._sharedWriteRoots[G]=R:this._sharedWriteRoots.includes(R)||this._sharedWriteRoots.push(R)}this._currentCwd=R,this.subagentExecutor?.setCwd(R),this.skillExecutor?.setCwd(R);let H=[O[0],O[1],ut({cwd:R,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.surface,...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:m.getWorkspace()}),...O.slice(2)].join(`
|
|
1350
|
+
`),O=[_,E];h.length>0&&O.push(h),d&&O.push(d),$u({prompt:e.prompt,options:{model:u,maxTokens:p,system:C},provenance:{systemPrompt:{source:n.systemPromptSource??"none",shape:typeof n.systemPrompt=="string"?"string":Array.isArray(n.systemPrompt)?"string[]":n.systemPrompt!=null?"preset":"undefined",...typeof n.systemPrompt=="string"?{length:n.systemPrompt.length}:{}},...n.apiKey?{apiKey:{source:"config"}}:{}}});let F;if(s==="oauth"&&!r){let R=this.providerFactory??ci;F=async()=>{let P=await So();if(!P)return null;let W=Mt(P,"oauth",n.baseUrl);return R?R(W):new Uu(W)}}let w=n.sessionId??n.resume,A=Fu(n.resumeHistory),x=this.externalTools?void 0:R=>{let P=this._currentCwd;if(this._sharedReadRoots&&P!==void 0&&P!==R){let G=this._sharedReadRoots.indexOf(P);G!==-1?this._sharedReadRoots[G]=R:this._sharedReadRoots.includes(R)||this._sharedReadRoots.push(R)}if(this._sharedWriteRoots&&P!==void 0&&P!==R){let G=this._sharedWriteRoots.indexOf(P);G!==-1?this._sharedWriteRoots[G]=R:this._sharedWriteRoots.includes(R)||this._sharedWriteRoots.push(R)}this._currentCwd=R,this.subagentExecutor?.setCwd(R),this.skillExecutor?.setCwd(R),this.composeExecutor?.setCwd(R);let H=[O[0],O[1],ut({cwd:R,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.surface,...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:m.getWorkspace()}),...O.slice(2)].join(`
|
|
1351
1351
|
|
|
1352
1352
|
`),Q=this.buildDispatcher(this._currentPermissionMode,{cwd:R,readRoots:this._sharedReadRoots,writeRoots:this._sharedWriteRoots,...n.env!==void 0?{env:n.env}:{},sessionId:n.sessionId,parentSessionId:n.parentSessionId,traceWriter:n.traceWriter,runtimeStateSource:m,hookRegistry:n.hookRegistry});return{userSystem:H,dispatcher:Q}},I=ri(n.effort,u);return new $r({client:c,authMode:r?"api-key":s,promptStream:e.prompt,toolDispatcher:g,...w!==void 0?{sessionId:w}:{},...A!==void 0?{initialMessages:A}:{},model:u,requestedModel:typeof n.model=="string"&&n.model.length>0?n.model:u,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:p,tools:k,userSystem:C,systemPrefix:l,tokenRefresher:F,...n.thinking!==void 0?{thinking:ni(n.thinking,p,u)}:{},...I!==void 0?{effort:I}:{},...r?{baseUrl:n.baseUrl}:{},...n.traceWriter?{traceWriter:n.traceWriter}:{},...n.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:n.autoResumeOnUsageLimit}:{},...x!==void 0?{cwdDependentsFactory:x}:{},onPermissionMode:R=>{this._currentPermissionMode=R},...this.mcpManager!==void 0?{mcpManager:this.mcpManager}:{},...ei(n.autoCompact)!==void 0?{autoCompactThreshold:ei(n.autoCompact)}:{}})}};function dk(t){if(t===void 0)return null;if(typeof t=="string")return t.length>0?t:null;if(typeof t=="object"&&t!==null&&"append"in t){let e=t.append;return e&&e.length>0?e:null}return null}var uk=new xe;L();var pk=new Set([...Object.keys(wo),"auto"]);function fk(t){if(!t)return;let e=t.trim().toLowerCase();if(e){if(e==="anthropic"||e==="anthropic-direct")return"anthropic-direct";if(e==="openai"||e==="openai-compatible"||e==="openai-codex")return"openai-compatible"}}function Y(t,e){let n=e?.explicit??b.AFK_PROVIDER,r=e?.openaiBaseUrl??b.AFK_OPENAI_BASE_URL,o=fk(n);if(o)return o;let s=bo(t,e?.slots);if(s.provider==="anthropic")return"anthropic-direct";if(s.provider==="openai")return"openai-compatible";let i=s.id.trim().toLowerCase();return i&&(pk.has(i)||i.startsWith("claude-")||i.startsWith("claude_")||i.startsWith("local-")||i.startsWith("local_"))?"anthropic-direct":i&&(i.startsWith("gpt-")||i.startsWith("gpt_")||i.startsWith("o1")||i.startsWith("o3")||i.startsWith("o4")||i.startsWith("codex-")||i.startsWith("codex_")||i==="codex"||i.startsWith("deepseek-")||i.startsWith("deepseek_")||i.startsWith("mistral-")||i.startsWith("mistral_")||i.startsWith("mixtral-")||i.startsWith("mixtral_")||i.startsWith("llama-")||i.startsWith("llama_")||i.startsWith("qwen-")||i.startsWith("qwen_")||i.includes("/"))||s.baseUrl&&s.baseUrl.trim()||r&&r.trim()?"openai-compatible":"anthropic-direct"}function Hr(t,e){switch(Y(t,e)){case"openai-compatible":case"openai-codex":return new pe;default:return new xe}}var Et=class{pendingResolve=null;bufferedMessages=[];getSessionId;constructor(e){this.getSessionId=e}pushUserMessage(e){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:e,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessages.push(e)}createIterable(){let e=this;return{[Symbol.asyncIterator](){return{next(){if(e.bufferedMessages.length>0){let n=e.bufferedMessages.shift(),r=e.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{e.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}};function jr(t,e){let n=e??rt(),r=ot(t.model,n);if(!r)return;let o=n[r],s=o.provider==="anthropic"?"anthropic-direct":o.provider==="openai"?"openai-compatible":Y(t.model,e?{slots:e}:void 0);o.apiKey!==void 0?t.apiKey=o.apiKey:(s==="openai-compatible"||o.baseUrl!==void 0)&&(t.apiKey=void 0),o.baseUrl!==void 0&&(s==="openai-compatible"?t.openaiBaseUrl=o.baseUrl:t.baseUrl=o.baseUrl)}function mk(t){return typeof t=="string"?t:t.map(e=>{let n=e;return n.type==="text"&&typeof n.text=="string"?n.text:""}).filter(e=>e.length>0).join(`
|
|
1353
1353
|
`)}var Kr=class{outerIterator;baseConfig;deps;currentModel;currentPermissionMode;currentCwd;startupFamily;active;closed=!1;shadowHistory;pendingUserText;pendingAssistantText="";lastSessionId;constructor(e,n){this.outerIterator=e.prompt[Symbol.asyncIterator](),this.baseConfig=e.config,this.deps=n,this.currentModel=typeof e.config.model=="string"?e.config.model:void 0,this.currentPermissionMode=e.config.permissionMode,this.currentCwd=e.config.cwd,this.startupFamily=n.providerNameForModel(this.currentModel),this.shadowHistory=[...e.config.resumeHistory??[]]}buildInner(e,n){let r=this.deps.resolveProvider(e),o=new Et(()=>this.lastSessionId),s={...this.baseConfig};s.model=e??this.baseConfig.model;let i=r.name===this.startupFamily&&this.baseConfig.apiKey!==void 0?this.baseConfig.apiKey:this.deps.resolveApiKey(e);i!==void 0?s.apiKey=i:delete s.apiKey,jr(s),this.currentPermissionMode!==void 0&&(s.permissionMode=this.currentPermissionMode),this.currentCwd!==void 0&&(s.cwd=this.currentCwd),n&&(s.resumeHistory=[...this.shadowHistory]);let a=r.query({prompt:o.createIterable(),config:s});return{family:r.name,query:a,iterator:a[Symbol.asyncIterator](),input:o}}async closeActive(){let e=this.active;if(e){this.active=void 0;try{await e.iterator.return?.(void 0)}catch{}try{await e.query.close()}catch{}}}observeEvent(e){e.type==="assistant.message"&&(this.pendingAssistantText+=(this.pendingAssistantText?`
|