agent-afk 5.3.0 → 5.3.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 +53 -53
- package/dist/index.mjs +1 -1
- package/dist/telegram.mjs +1 -1
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var qF=Object.defineProperty;var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var ac=(e,t)=>{for(var n in t)qF(e,n,{get:t[n],enumerable:!0})};function lc(e){return fa.find(t=>t.name===e)}function LS(e){return fa.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function ff(e){return process.env[e]!==void 0}var fa,v,q=_(()=>{"use strict";fa=[{name:"AFK_COMPACT_KEEP_LAST_TURNS",description:"Number of recent turns the compactor keeps verbatim during /compact. Default tuned in compact-handler.ts.",type:"number",required:!1,example:"6",category:"model"},{name:"AFK_COMPACT_MODEL",description:"Override the model used by the /compact summarizer. Falls back to a cheap default (haiku-class).",type:"string",required:!1,example:"claude-haiku-4-5",category:"model"},{name:"AFK_DEFAULT_SUBAGENT_MODEL",description:"Override the default model used when a subagent is dispatched without an explicit model.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_DIAGNOSE_BASELINE",description:"Kill switch for /diagnose reproducer baseline execution. When set to '0', the /diagnose skill skips executing the detected reproducer command for a ground-truth baseline; default enabled (runs). Set to '0' to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_DISABLE_PROMPT_CACHE",description:"Disable Anthropic prompt caching when set to 1/true/yes/on. Unset = caching enabled.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_DISABLE_BASH_INTERPRETER_GUARD",description:"Skip ONLY the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) when set to 1, leaving the rest of path-approval intact. Applies on interactive surfaces (REPL/Telegram), where the denylist is active but your workflow legitimately runs interpreter one-liners. The restricted-root substring check is unaffected. Default: denylist active on interactive surfaces; headless already fails open (opt in with AFK_FORCE_BASH_INTERPRETER_GUARD=1). To disable all of path-approval + bash restriction instead, use AFK_DISABLE_PATH_APPROVAL=1.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_DISABLE_PATH_APPROVAL",description:"Skip the path-approval + bash-restriction hooks entirely when set to 1. Use for headless flows that need wide-open file access (CI scripts, batch jobs). Default: hooks enabled. Note: on headless surfaces (afk chat, daemon) no grant manager is wired, so the interpreter denylist (python -c, node -e, sh -c, ...) fails OPEN by default \u2014 opt headless flows into it with AFK_FORCE_BASH_INTERPRETER_GUARD=1, or set this var to 1 to disable all of path-approval.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_FORCE_BASH_INTERPRETER_GUARD",description:"Apply the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) even on headless surfaces (afk chat, daemon) where no grant manager is wired. By default the denylist fires only on interactive surfaces (REPL/Telegram), failing open on headless so legitimate automation is not hard-blocked with no recourse. Set to 1 to opt headless flows back into the guard. Overridden by AFK_DISABLE_BASH_INTERPRETER_GUARD=1. Default: off (headless fails open).",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_EFFORT",description:"Effort hint guiding adaptive-thinking depth, forwarded as Anthropic output_config.effort (model-gated; ignored where unsupported). Accepts low | medium | high | xhigh | max.",type:"string",required:!1,example:"medium",category:"model"},{name:"AFK_MAX_BUDGET_USD",description:"Cumulative USD budget ceiling for the session. Aborts the turn when the running cost crosses this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. Falls back to provider default when unset.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Cap on total tokens per turn (input + output). Default 4096.",type:"number",required:!1,default:"4096",example:"8192",category:"model"},{name:"AFK_MEMORY_EVIDENCE_GATE",description:'Opt-in (set to 1) evidence gate for durable memory writes. When enabled, a codebase fact (memory_update category "convention") stored without an `evidence` citation is recalled as [unverified], and memory_search results carry a verification verdict. User preferences and agent reflections are never gated. Default off \u2014 memory behaves identically to legacy when unset.',type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), legacy aliases (opus, sonnet, haiku), the fixed-id fable alias (Claude Fable 5), or full model IDs.",type:"string",required:!1,default:"sonnet",example:"claude-opus-4-5",category:"model"},{name:"AFK_VISION_MODELS",description:'Comma-separated override for image (vision) capability detection on the openai-compatible provider. Each token force-enables a model id by exact or substring match (e.g. "qwen2.5-vl" matches a local VL id); prefix a token with "!" to force-disable. Use to send images to a local vision-language model AFK does not recognise by name, or to blacklist a mis-detected id. Built-in detection already covers gpt-4o/4.1/5.x, o1/o3/o4-mini, Claude, and common VL families.',type:"string",required:!1,example:"qwen2.5-vl,!gpt-4o-mini",category:"model"},{name:"AFK_MODEL_LOCAL",description:'Bind the "local" capability tier (cheapest/fastest, user-configured) to a model id. Overrides afk.config.json models.local. Point at a local Ollama, LM Studio, or any OpenAI-compatible shim.',type:"string",required:!1,example:"llama3.2:3b",category:"model"},{name:"AFK_MODEL_LOCAL_API_KEY",description:'Per-slot API key for the "local" tier. Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LOCAL_BASE_URL",description:'Per-slot endpoint base URL for the "local" tier. Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:11434/v1",category:"model"},{name:"AFK_MODEL_LARGE",description:'Bind the "large" capability tier (most capable) to a model id/alias. Overrides afk.config.json models.large.',type:"string",required:!1,example:"claude-opus-4-8",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-4-6",category:"model"},{name:"AFK_MODEL_MEDIUM_API_KEY",description:'Per-slot API key for the "medium" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_MEDIUM_BASE_URL",description:'Per-slot endpoint base URL for the "medium" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_SMALL",description:'Bind the "small" capability tier (cheap/fast) to a model id/alias. Overrides afk.config.json models.small.',type:"string",required:!1,example:"gpt-4o-mini",category:"model"},{name:"AFK_MODEL_SMALL_API_KEY",description:'Per-slot API key for the "small" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_SMALL_BASE_URL",description:'Per-slot endpoint base URL for the "small" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_PROMPT_CACHE_TTL",description:"TTL for Anthropic prompt-cache blocks. Accepts 5m or 1h.",type:"string",required:!1,default:"1h",example:"1h",category:"model"},{name:"AFK_SUGGEST_ENABLED",description:"Enable the LLM-backed ghost-text suggestion tier in the interactive REPL. Set to 1/true/yes/on to activate. Off by default.",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_GHOST",description:"Enable REPL ghost-text inline suggestions (Tier-1 history/dropdown + optional Tier-2 LLM). 1 = on (default), 0 = off. Set 0/false/off/no to disable all ghost text. Tier-2 LLM is separately gated by AFK_SUGGEST_ENABLED.",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_MODEL",description:"Override the small model used for REPL ghost-text suggestions. Falls back to AFK_COMPACT_MODEL or haiku-class for anthropic, or the session model for other providers.",type:"string",required:!1,category:"model"},{name:"AFK_TASK_BUDGET",description:"Per-task token budget ceiling. Aborts when cumulative usage would exceed it.",type:"number",required:!1,default:"100000",example:"200000",category:"model"},{name:"AFK_TEMPERATURE",description:"Numeric temperature override for model sampling. Provider default if unset.",type:"number",required:!1,example:"0.7",category:"model"},{name:"AFK_THINKING",description:"Extended-thinking mode. Accepts adaptive | disabled | enabled:<N> | enabled:max. Defaults to the model-appropriate mode when unset (adaptive on current models).",type:"string",required:!1,default:"adaptive",example:"adaptive",category:"model"},{name:"AFK_TIMEOUT_MS",description:"Per-turn timeout in milliseconds. Provider/SDK default if unset.",type:"number",required:!1,example:"120000",category:"model"},{name:"CLAUDE_MODEL",description:"Legacy alias for AFK_MODEL \u2014 supported for back-compat with pre-AFK_* deployments.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_SYSTEM_PROMPT",description:'Raw operator-overlay prompt. Highest-priority overlay (over afk.config.json and AFK.md). Appended on top of the framework base (prompts/system-prompt.md) under an "# Operator configuration" header \u2014 it augments, never replaces, the base.',type:"string",required:!1,example:"You are a helpful agent.",category:"model"},{name:"AFK_DUMP_PROMPT",description:"Write the resolved system prompt to a file at startup. Accepts a path or 1 for default location.",type:"string",required:!1,example:"/tmp/afk-prompt.txt",category:"debug"},{name:"ANTHROPIC_API_KEY",description:"Anthropic API key. Tier-1 credential \u2014 overrides keychain OAuth and CLAUDE_CODE_OAUTH_TOKEN.",type:"string",required:!1,category:"auth",secret:!0},{name:"CLAUDE_CODE_OAUTH_TOKEN",description:"Claude Code OAuth token. Tier-2 credential \u2014 used when ANTHROPIC_API_KEY is unset; falls back to keychain.",type:"string",required:!1,category:"auth",secret:!0},{name:"OPENAI_API_KEY",description:"OpenAI API key for the openai-compatible provider (gpt-*, o1*, o3*, o4* models).",type:"string",required:!1,category:"auth",secret:!0},{name:"CODEX_API_KEY",description:"Fallback OpenAI API key for the openai-compatible provider, read after OPENAI_API_KEY. Legacy name from the removed @openai/codex-sdk integration \u2014 prefer OPENAI_API_KEY.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_LOCAL_API_KEY",description:"Placeholder API key for local Anthropic-compatible servers (vllm-mlx, etc.). Set when AFK_LOCAL_BASE_URL is configured.",type:"string",required:!1,default:"local",example:"local",category:"auth",secret:!0},{name:"AFK_LOCAL_BASE_URL",description:"Base URL for a self-hosted Anthropic-compatible server. When set, routes traffic away from api.anthropic.com.",type:"string",required:!1,example:"http://127.0.0.1:8080",category:"model"},{name:"AFK_OPENAI_BASE_URL",description:"Base URL override for the OpenAI-compatible provider. Used for local shims (mlx_lm.server, Ollama, vLLM, LM Studio). The OpenAI SDK appends `/chat/completions` itself \u2014 a value ending in `/chat/completions` will be stripped at config-load time with a one-shot warning.",type:"string",required:!1,example:"http://127.0.0.1:8000/v1",category:"model"},{name:"AFK_OPENAI_USE_RESPONSES",description:"Opt the OpenAI-compatible provider into the OpenAI Responses API instead of Chat Completions for API-key sessions. Truthy values: 1, true, yes, on. The ChatGPT-subscription OAuth path uses Responses automatically regardless of this flag.",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_OPENAI_CHATGPT_OAUTH",description:"Opt into using ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. Off by default. READ-ONLY: AFK never refreshes these tokens \u2014 re-run `codex` when the access token expires. Routes requests over the Responses API to the private ChatGPT backend (chatgpt.com/backend-api).",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_PROVIDER",description:"Force provider selection (anthropic | anthropic-direct | openai | openai-compatible | openai-codex). Overrides the model-name heuristic. Same surface as the --provider CLI flag; CLI flag wins when both are set.",type:"string",required:!1,example:"openai-compatible",category:"model"},{name:"EXA_API_KEY",description:"Exa (exa.ai) search API key, enabling web_scrape search mode. Free tier (20k requests/month) available at https://exa.ai. When unset, search mode returns an actionable error; markdown and raw modes are unaffected.",type:"string",required:!1,category:"auth",secret:!0},{name:"TELEGRAM_BOT_TOKEN",description:"Telegram bot token from @BotFather. Required to run the Telegram bot surface.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_BOT_TOKEN",description:"Alternative env var name for the Telegram bot token, accepted by the setup wizard.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_ALLOWED_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs allowed to interact with the bot. Required when the bot is running.",type:"string",required:!1,example:"123456789,987654321",category:"telegram"},{name:"AFK_TELEGRAM_PRIMARY_CHAT_ID",description:"Default chat ID for outbound notifications (primary-mode routing). When unset, notifications go to the first private/DM chat in AFK_TELEGRAM_ALLOWED_CHAT_IDS. The afk.config.json telegram.notify block takes precedence.",type:"string",required:!1,example:"123456789",category:"telegram"},{name:"AFK_TELEGRAM_NOTIFY_MODE",description:"Outbound notification fan-out: primary (default \u2014 one chat), broadcast (every allowed chat), or custom (afk.config.json telegram.notify.targets). The afk.config.json telegram.notify.mode takes precedence.",type:"string",required:!1,example:"broadcast",category:"telegram"},{name:"TELEGRAM_DATA_DIR",description:"Override the directory where Telegram bot state is stored. Defaults to ~/.afk/state/telegram/.",type:"string",required:!1,category:"telegram"},{name:"TELEGRAM_VERBOSE",description:"Set to 1 to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"1",category:"telegram"},{name:"AFK_TELEGRAM_TRACE",description:"Set to 1 to dump raw bridge traffic between the agent and the Telegram bot \u2014 debugging only.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_TELEGRAM_CWD",description:"Override the working directory used by the Telegram bot when spawning agent sessions.",type:"string",required:!1,category:"telegram"},{name:"AFK_HOME",description:"Override the AFK home directory. Default: ~/.afk/.",type:"string",required:!1,default:"~/.afk",example:"/opt/afk",category:"paths"},{name:"AFK_STATE_DIR",description:"Override the entire AFK state tier (sessions/, todos/, transcripts/, memory/, daemon/, etc.), not just one subdirectory. Must be an absolute path (not /). Default: $AFK_HOME/state/.",type:"string",required:!1,category:"paths"},{name:"AFK_FRAMEWORK_DIR",description:"Override the AFK agent-framework directory used for telemetry and briefs. Default: $AFK_HOME/agent-framework/.",type:"string",required:!1,category:"paths"},{name:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Controls auto-loading of MCP configuration from <cwd>/.mcp.json. Auto-loaded by default \u2014 set to 0 to disable (mitigates config-injection risk in shared/CI environments).",type:"boolean",required:!1,example:"0",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless for daemon and subagent surfaces and headed for repl/interactive \u2014 so an operator can watch the agent work in REPL mode.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_ALLOWED_DOMAINS",description:"Comma-separated allowlist of URL host globs. When set, browser_open and any navigation that targets a host outside the list returns status: blocked_by_policy. Unset means no allowlist (permissive). Patterns use simple `*` glob matching against the URL host. Combines with AFK_BROWSER_BLOCKED_DOMAINS \u2014 block wins.",type:"string",required:!1,example:"github.com,*.atlassian.net",category:"browser"},{name:"AFK_BROWSER_BLOCKED_DOMAINS",description:"Comma-separated blocklist of URL host globs. Browser navigation that matches any entry returns status: blocked_by_policy regardless of the allowlist.",type:"string",required:!1,example:"*.ads.example.com",category:"browser"},{name:"AFK_BROWSER_DOM_SNAPSHOTS",description:"Phase 2 opt-in: when set to 1, every browser_act writes a gzipped DOM snapshot sidecar under ~/.afk/state/witness/<sid>/browser/dom-snapshots/. Off by default because snapshots are large; useful for post-mortem analysis of failed actions.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_BACKEND",description:"Select the browser provider backend. Phase 1 supports only `playwright`. Reserved for future `cdp` / `mcp` adapters. Unset defaults to `playwright`.",type:"string",required:!1,example:"playwright",category:"browser"},{name:"AFK_BROWSER_CONFIG",description:"Absolute path to an alternate browser config file. Overrides the default ~/.afk/config/browser.json lookup. Useful for per-project overrides in CI.",type:"string",required:!1,example:"/path/to/browser.json",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],v={get AFK_COMPACT_KEEP_LAST_TURNS(){return process.env.AFK_COMPACT_KEEP_LAST_TURNS},get AFK_COMPACT_MODEL(){return process.env.AFK_COMPACT_MODEL},get AFK_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_OUTPUT_TOKENS(){return process.env.AFK_MAX_OUTPUT_TOKENS},get AFK_MAX_TOKENS(){return process.env.AFK_MAX_TOKENS},get AFK_MEMORY_EVIDENCE_GATE(){return process.env.AFK_MEMORY_EVIDENCE_GATE},get AFK_MODEL(){return process.env.AFK_MODEL},get AFK_MODEL_LARGE(){return process.env.AFK_MODEL_LARGE},get AFK_MODEL_LARGE_API_KEY(){return process.env.AFK_MODEL_LARGE_API_KEY},get AFK_MODEL_LARGE_BASE_URL(){return process.env.AFK_MODEL_LARGE_BASE_URL},get AFK_MODEL_LOCAL(){return process.env.AFK_MODEL_LOCAL},get AFK_MODEL_LOCAL_API_KEY(){return process.env.AFK_MODEL_LOCAL_API_KEY},get AFK_MODEL_LOCAL_BASE_URL(){return process.env.AFK_MODEL_LOCAL_BASE_URL},get AFK_MODEL_MEDIUM(){return process.env.AFK_MODEL_MEDIUM},get AFK_MODEL_MEDIUM_API_KEY(){return process.env.AFK_MODEL_MEDIUM_API_KEY},get AFK_MODEL_MEDIUM_BASE_URL(){return process.env.AFK_MODEL_MEDIUM_BASE_URL},get AFK_MODEL_SMALL(){return process.env.AFK_MODEL_SMALL},get AFK_MODEL_SMALL_API_KEY(){return process.env.AFK_MODEL_SMALL_API_KEY},get AFK_MODEL_SMALL_BASE_URL(){return process.env.AFK_MODEL_SMALL_BASE_URL},get AFK_VISION_MODELS(){return process.env.AFK_VISION_MODELS},get AFK_PROMPT_CACHE_TTL(){return process.env.AFK_PROMPT_CACHE_TTL},get AFK_SUGGEST_ENABLED(){return process.env.AFK_SUGGEST_ENABLED},get AFK_SUGGEST_GHOST(){return process.env.AFK_SUGGEST_GHOST},get AFK_SUGGEST_MODEL(){return process.env.AFK_SUGGEST_MODEL},get AFK_TASK_BUDGET(){return process.env.AFK_TASK_BUDGET},get AFK_TEMPERATURE(){return process.env.AFK_TEMPERATURE},get AFK_THINKING(){return process.env.AFK_THINKING},get AFK_TIMEOUT_MS(){return process.env.AFK_TIMEOUT_MS},get CLAUDE_MODEL(){return process.env.CLAUDE_MODEL},get AFK_SYSTEM_PROMPT(){return process.env.AFK_SYSTEM_PROMPT},get AFK_DUMP_PROMPT(){return process.env.AFK_DUMP_PROMPT},get ANTHROPIC_API_KEY(){return process.env.ANTHROPIC_API_KEY},get CLAUDE_CODE_OAUTH_TOKEN(){return process.env.CLAUDE_CODE_OAUTH_TOKEN},get OPENAI_API_KEY(){return process.env.OPENAI_API_KEY},get CODEX_API_KEY(){return process.env.CODEX_API_KEY},get AFK_LOCAL_API_KEY(){return process.env.AFK_LOCAL_API_KEY},get AFK_LOCAL_BASE_URL(){return process.env.AFK_LOCAL_BASE_URL},get AFK_OPENAI_BASE_URL(){return process.env.AFK_OPENAI_BASE_URL},get AFK_OPENAI_USE_RESPONSES(){return process.env.AFK_OPENAI_USE_RESPONSES},get AFK_OPENAI_CHATGPT_OAUTH(){return process.env.AFK_OPENAI_CHATGPT_OAUTH},get AFK_PROVIDER(){return process.env.AFK_PROVIDER},get EXA_API_KEY(){return process.env.EXA_API_KEY},get TELEGRAM_BOT_TOKEN(){return process.env.TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_BOT_TOKEN(){return process.env.AFK_TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_ALLOWED_CHAT_IDS(){return process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS},get AFK_TELEGRAM_PRIMARY_CHAT_ID(){return process.env.AFK_TELEGRAM_PRIMARY_CHAT_ID},get AFK_TELEGRAM_NOTIFY_MODE(){return process.env.AFK_TELEGRAM_NOTIFY_MODE},get TELEGRAM_DATA_DIR(){return process.env.TELEGRAM_DATA_DIR},get TELEGRAM_VERBOSE(){return process.env.TELEGRAM_VERBOSE},get AFK_TELEGRAM_TRACE(){return process.env.AFK_TELEGRAM_TRACE},get AFK_TELEGRAM_CWD(){return process.env.AFK_TELEGRAM_CWD},get AFK_HOME(){return process.env.AFK_HOME},get AFK_STATE_DIR(){return process.env.AFK_STATE_DIR},get AFK_FRAMEWORK_DIR(){return process.env.AFK_FRAMEWORK_DIR},get HOME(){return process.env.HOME},get PATH(){return process.env.PATH},get AFK_DAEMON_CWD(){return process.env.AFK_DAEMON_CWD},get AFK_DAEMON_TASK(){return process.env.AFK_DAEMON_TASK},get AFK_DAEMON_TASK_ID(){return process.env.AFK_DAEMON_TASK_ID},get AFK_DAEMON_HOST(){return process.env.AFK_DAEMON_HOST},get AFK_SESSIONSTART_COOLDOWN_MS(){return process.env.AFK_SESSIONSTART_COOLDOWN_MS},get AFK_WORKTREE_AUTONAME(){return process.env.AFK_WORKTREE_AUTONAME},get AFK_WORKTREE_BRANCH_PREFIX(){return process.env.AFK_WORKTREE_BRANCH_PREFIX},get AFK_WORKTREE_BASE(){return process.env.AFK_WORKTREE_BASE},get AFK_WORKTREE_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},get AFK_SHOW_DIFFS(){return process.env.AFK_SHOW_DIFFS},get AFK_SKILL_STREAM_VERBOSE(){return process.env.AFK_SKILL_STREAM_VERBOSE},get FORCE_COLOR(){return process.env.FORCE_COLOR},get NO_COLOR(){return process.env.NO_COLOR},get AFK_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let t of fa){if(!t.secret)continue;let n=Object.getOwnPropertyDescriptor(v,t.name);n&&Object.defineProperty(v,t.name,{...n,enumerable:!1})}})()});import{existsSync as FS,mkdirSync as zF,renameSync as JF,cpSync as VF,rmSync as YF}from"fs";import{join as Z,dirname as BS,isAbsolute as US}from"path";import{homedir as gf}from"os";import{fileURLToPath as XF}from"url";function $e(){let e=v.AFK_HOME;if(e!==void 0&&e!==""){if(!US(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return Z(gf(),".afk")}function gn(){return Z($e(),"agent-framework")}function Tr(){return Z(gn(),"forge-telemetry.jsonl")}function Ss(){return Z(gn(),"briefs")}function cc(){return Z($e(),"skills")}function Ve(){return Z($e(),"plugins")}function jS(){return Z(process.cwd(),".afk")}function uc(){return Z(jS(),"skills")}function dc(){return Z(jS(),"plugins")}function pc(e=process.cwd()){return Z(e,".afk","plans")}function ce(){return Z(Ve(),".index.json")}function hf(){return Z(Qt(),"schedules.json")}function Kn(){return Z(Ve(),"cache")}function ga(e){return Z(Kn(),e)}function vs(){let e=XF(import.meta.url),t=BS(e);return Z(t,"bundled-plugins")}function Qt(){return Z($e(),"config")}function Te(){let e=v.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!US(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return Z($e(),"state")}function mc(){return Z($e(),"cache")}function ks(){return Z($e(),"logs")}function Gn(){return Z(Te(),"sessions")}function fc(){return Z(Te(),"presence")}function yf(){return Z(Te(),"todos")}function ha(){return Z(Te(),"transcripts")}function gc(){return Z(Te(),"memory")}function hn(){return Z(Te(),"queue")}function Es(){return Z(Te(),"session-grants.jsonl")}function ya(){return Z(Qt(),"permissions.json")}function HS(){return Z($e(),"farms")}function bf(e){return Z(HS(),e)}function QF(e){if(!ZF.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function Ts(e){return QF(e),Z(Te(),"witness",e)}function wf(){return Z(Te(),"receipts")}function hc(e="default"){return Z(Te(),"daemon",`agent-afk@${e}`)}function WS(){return Z(Te(),"worktree-sweep.lock")}function gt(){return Z(Qt(),"afk.env")}function Bt(){return Z(Qt(),"afk.config.json")}function KS(){return Z(Qt(),"settings.json")}function GS(e=process.cwd()){return Z(e,".afk","settings.json")}function qS(){return Z(gf(),".afk.env")}function yc(){return Z(gf(),".afk.config.json")}function eN(){return Z($e(),"sessions")}function tN(){return Z($e(),"todos")}function nN(){return Z($e(),"transcripts")}function Sf(e,t){if(e!==t&&FS(e)&&!FS(t))try{zF(BS(t),{recursive:!0});try{JF(e,t)}catch(n){if(n.code==="EXDEV")try{VF(e,t,{recursive:!0}),YF(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
|
|
3
|
-
`)}}}catch{}}function zS(){Sf(eN(),Gn())}function JS(){Sf(tN(),yf())}function VS(){Sf(nN(),ha())}function vf(){return Z(Te(),"repl-history.jsonl")}function oN(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(e.length>NS)throw new Error(`Invalid jobId: exceeds ${NS} chars`);if(!rN.test(e))throw new Error(`Invalid jobId: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function ba(){return Z(Te(),"bg")}function yo(e){return oN(e),Z(ba(),e)}function bc(e){return Z(yo(e),"events.jsonl")}function kf(e){return Z(yo(e),"meta.json")}function wc(e){return typeof e=="string"&&e.length>0&&e.length<=iN&&sN.test(e)}function wa(e){if(!wc(e))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(e)}`);return Z(Gn(),e)}function Ef(e){return Z(wa(e),"events.jsonl")}function Tf(e){return Z(wa(e),"session.key")}function Sa(){return Z(Te(),"mcp","server-status.json")}var ZF,rN,NS,sN,iN,G=_(()=>{"use strict";q();ZF=/^[a-zA-Z0-9_-]+$/;rN=/^[A-Za-z0-9_-]+$/,NS=128;sN=/^[A-Za-z0-9_-]+$/,iN=128});import{randomBytes as aN}from"node:crypto";import{mkdirSync as lN,renameSync as cN,rmSync as YS,writeFileSync as uN}from"node:fs";import{dirname as dN,isAbsolute as pN,join as mN}from"node:path";function Sc(){return mN(Te(),"last-cwd")}function XS(){try{YS(Sc(),{force:!0})}catch{}}function ZS(e){if(!pN(e))throw new Error(`recordCdIntent: target must be an absolute path, got ${JSON.stringify(e)}`);if(/[\n\r\0]/.test(e))throw new Error(`recordCdIntent: target must not contain newline/CR/NUL, got ${JSON.stringify(e)}`);try{let t=Sc();lN(dN(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${aN(6).toString("hex")}`;try{uN(n,e,{encoding:"utf8",mode:384}),cN(n,t)}catch(r){try{YS(n,{force:!0})}catch{}throw r}}catch{}}function QS(){let e=v.AFK_SHELL_WRAPPER;return e==="1"||e==="true"}var vc=_(()=>{"use strict";q();G()});var it,Ut,be,xr,kc,Rt=_(()=>{"use strict";it=class extends Error{constructor(t){super(t),this.name="AbortError"}},Ut=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},be=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},xr=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},kc=class extends Error{constructor(n,r,o){super(o??`${n} provider does not support AgentConfig.${r}.`);this.provider=n;this.field=r;this.name="UnsupportedProviderConfigError"}provider;field}});function We(){return v.AFK_DEBUG==="1"||v.DEBUG==="1"}function z(...e){We()&&console.log(...e)}var _e=_(()=>{"use strict";q()});async function Is(e,t){if(e)try{await e.write({kind:"tool_call",payload:t})}catch(n){z(`trace.emit tool_call failed: ${yn(n)}`)}}async function Ar(e,t){if(e)try{await e.write({kind:"hook_decision",payload:t})}catch(n){z(`trace.emit hook_decision failed: ${yn(n)}`)}}async function So(e,t){if(e)try{await e.write({kind:"subagent_lifecycle",payload:t})}catch(n){z(`trace.emit subagent_lifecycle failed: ${yn(n)}`)}}async function Ps(e,t){if(e)try{await e.write({kind:"background_agent",payload:t})}catch(n){z(`trace.emit background_agent failed: ${yn(n)}`)}}async function Ev(e,t){if(e)try{await e.write({kind:"budget",payload:t})}catch(n){z(`trace.emit budget failed: ${yn(n)}`)}}async function Tv(e,t){if(e)try{await e.write({kind:"abort",payload:t})}catch(n){z(`trace.emit abort failed: ${yn(n)}`)}}async function xv(e,t){if(e)try{await e.write({kind:"compaction",payload:t})}catch(n){z(`trace.emit compaction failed: ${yn(n)}`)}}async function Rv(e,t){if(e)try{await e.write({kind:"closure",payload:t})}catch(n){z(`trace.emit closure failed: ${yn(n)}`)}}async function et(e,t){if(e)try{await e.write({kind:"browser_event",payload:t})}catch(n){z(`trace.emit browser_event failed: ${yn(n)}`)}}async function De(e,t){if(e)try{await e.write({kind:"session_phase",payload:t})}catch(n){z(`trace.emit session_phase failed: ${yn(n)}`)}}function yn(e){return e instanceof Error?e.message:String(e)}var je=_(()=>{"use strict";_e()});function Ic(e){return e.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Ta(e,t,n){let r=t==="oauth"?{authToken:e}:{apiKey:e};return typeof n=="string"&&n.length>0?{...r,baseURL:n}:r}function bn(e,t,n,r){return e!=="oauth"?{}:{"anthropic-beta":r?`${Cv},${VN}`:Cv,"x-app":"cli","User-Agent":YN,"X-Claude-Code-Session-Id":t,"x-client-request-id":n}}function Av(e){return e!=="oauth"?null:[{type:"text",text:XN}]}var Cv,VN,YN,XN,Ms=_(()=>{"use strict";Cv="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",VN="effort-2025-11-24",YN="claude-cli/1.0.0 (external, cli)",XN="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;"});function Oc(e){Ff=e}function Lf(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}function Pc(e,t,n){let r={},o=Lf(e);o&&(r.id=o);let s=Lf(t);s&&(r.baseUrl=s);let i=Lf(n);return i&&(r.apiKey=i),r}function tB(){return{local:Pc(v.AFK_MODEL_LOCAL,v.AFK_MODEL_LOCAL_BASE_URL,v.AFK_MODEL_LOCAL_API_KEY),small:Pc(v.AFK_MODEL_SMALL,v.AFK_MODEL_SMALL_BASE_URL,v.AFK_MODEL_SMALL_API_KEY),medium:Pc(v.AFK_MODEL_MEDIUM,v.AFK_MODEL_MEDIUM_BASE_URL,v.AFK_MODEL_MEDIUM_API_KEY),large:Pc(v.AFK_MODEL_LARGE,v.AFK_MODEL_LARGE_BASE_URL,v.AFK_MODEL_LARGE_API_KEY)}}function Uf(e){let t=tB(),n={};for(let r of Nf){let o=vo[r],s=e?.[r],i=t[r],a={id:i.id??s?.id??o.id},l=s?.name;l&&(a.name=l);let c=s?.provider;c&&(a.provider=c);let u=i.baseUrl??s?.baseUrl;u&&(a.baseUrl=u);let d=i.apiKey??s?.apiKey;d&&(a.apiKey=d),n[r]=a}return n}function Os(e){return e||Ff||Uf()}function $s(e,t=Os()){let n=e.trim().toLowerCase();if(!n||n===QN)return;for(let o of Nf){let s=t[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:ZN[n]}function jf(e,t=Os()){if(e===void 0)return{id:""};let n=$s(e,t);if(n)return t[n];let r=eB[e.trim().toLowerCase()];return r?{id:r}:{id:e}}function ko(e,t=Os()){if(e!==void 0)return jf(e,t).id}function Ds(e,t=Os()){if(e===void 0)return;let n=$s(e,t);if(n&&t[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 _v(e){let t={};if(!e||typeof e!="object")return t;let n=e;for(let r of Nf){let o=rB(n[r]);o&&(t[r]=o)}return t}function nB(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();if(t==="anthropic"||t==="anthropic-direct")return"anthropic";if(t==="openai"||t==="openai-compatible")return"openai"}function Mc(e){return typeof e=="string"?e.trim():""}function rB(e){if(typeof e=="string"){let t=e.trim();return t?{id:t}:void 0}if(e&&typeof e=="object"){let t=e,n=Mc(t.id);if(!n)return;let r={id:n},o=Mc(t.name);o&&(r.name=o);let s=nB(t.provider);s&&(r.provider=s);let i=Mc(t.baseUrl);i&&(r.baseUrl=i);let a=Mc(t.apiKey);return a&&(r.apiKey=a),r}}var Nf,vo,ZN,QN,Bf,eB,Ff,en=_(()=>{"use strict";q();Nf=["local","small","medium","large"],vo={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-4-6"},large:{id:"claude-opus-4-8"}},ZN={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},QN="auto",Bf="claude-fable-5",eB={fable:Bf}});function Wf(e){return e in Hf}function
|
|
2
|
+
var qF=Object.defineProperty;var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var ac=(e,t)=>{for(var n in t)qF(e,n,{get:t[n],enumerable:!0})};function lc(e){return fa.find(t=>t.name===e)}function LS(e){return fa.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function ff(e){return process.env[e]!==void 0}var fa,v,q=_(()=>{"use strict";fa=[{name:"AFK_COMPACT_KEEP_LAST_TURNS",description:"Number of recent turns the compactor keeps verbatim during /compact. Default tuned in compact-handler.ts.",type:"number",required:!1,example:"6",category:"model"},{name:"AFK_COMPACT_MODEL",description:"Override the model used by the /compact summarizer. Falls back to a cheap default (haiku-class).",type:"string",required:!1,example:"claude-haiku-4-5",category:"model"},{name:"AFK_DEFAULT_SUBAGENT_MODEL",description:"Override the default model used when a subagent is dispatched without an explicit model.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_DIAGNOSE_BASELINE",description:"Kill switch for /diagnose reproducer baseline execution. When set to '0', the /diagnose skill skips executing the detected reproducer command for a ground-truth baseline; default enabled (runs). Set to '0' to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_DISABLE_PROMPT_CACHE",description:"Disable Anthropic prompt caching when set to 1/true/yes/on. Unset = caching enabled.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_DISABLE_BASH_INTERPRETER_GUARD",description:"Skip ONLY the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) when set to 1, leaving the rest of path-approval intact. Applies on interactive surfaces (REPL/Telegram), where the denylist is active but your workflow legitimately runs interpreter one-liners. The restricted-root substring check is unaffected. Default: denylist active on interactive surfaces; headless already fails open (opt in with AFK_FORCE_BASH_INTERPRETER_GUARD=1). To disable all of path-approval + bash restriction instead, use AFK_DISABLE_PATH_APPROVAL=1.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_DISABLE_PATH_APPROVAL",description:"Skip the path-approval + bash-restriction hooks entirely when set to 1. Use for headless flows that need wide-open file access (CI scripts, batch jobs). Default: hooks enabled. Note: on headless surfaces (afk chat, daemon) no grant manager is wired, so the interpreter denylist (python -c, node -e, sh -c, ...) fails OPEN by default \u2014 opt headless flows into it with AFK_FORCE_BASH_INTERPRETER_GUARD=1, or set this var to 1 to disable all of path-approval.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_FORCE_BASH_INTERPRETER_GUARD",description:"Apply the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) even on headless surfaces (afk chat, daemon) where no grant manager is wired. By default the denylist fires only on interactive surfaces (REPL/Telegram), failing open on headless so legitimate automation is not hard-blocked with no recourse. Set to 1 to opt headless flows back into the guard. Overridden by AFK_DISABLE_BASH_INTERPRETER_GUARD=1. Default: off (headless fails open).",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_EFFORT",description:"Effort hint guiding adaptive-thinking depth, forwarded as Anthropic output_config.effort (model-gated; ignored where unsupported). Accepts low | medium | high | xhigh | max.",type:"string",required:!1,example:"medium",category:"model"},{name:"AFK_MAX_BUDGET_USD",description:"Cumulative USD budget ceiling for the session. Aborts the turn when the running cost crosses this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. Falls back to provider default when unset.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Cap on total tokens per turn (input + output). Default 4096.",type:"number",required:!1,default:"4096",example:"8192",category:"model"},{name:"AFK_MEMORY_EVIDENCE_GATE",description:'Opt-in (set to 1) evidence gate for durable memory writes. When enabled, a codebase fact (memory_update category "convention") stored without an `evidence` citation is recalled as [unverified], and memory_search results carry a verification verdict. User preferences and agent reflections are never gated. Default off \u2014 memory behaves identically to legacy when unset.',type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), legacy aliases (opus, sonnet, haiku), the fixed-id fable alias (Claude Fable 5), or full model IDs.",type:"string",required:!1,default:"sonnet",example:"claude-opus-4-5",category:"model"},{name:"AFK_VISION_MODELS",description:'Comma-separated override for image (vision) capability detection on the openai-compatible provider. Each token force-enables a model id by exact or substring match (e.g. "qwen2.5-vl" matches a local VL id); prefix a token with "!" to force-disable. Use to send images to a local vision-language model AFK does not recognise by name, or to blacklist a mis-detected id. Built-in detection already covers gpt-4o/4.1/5.x, o1/o3/o4-mini, Claude, and common VL families.',type:"string",required:!1,example:"qwen2.5-vl,!gpt-4o-mini",category:"model"},{name:"AFK_MODEL_LOCAL",description:'Bind the "local" capability tier (cheapest/fastest, user-configured) to a model id. Overrides afk.config.json models.local. Point at a local Ollama, LM Studio, or any OpenAI-compatible shim.',type:"string",required:!1,example:"llama3.2:3b",category:"model"},{name:"AFK_MODEL_LOCAL_API_KEY",description:'Per-slot API key for the "local" tier. Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LOCAL_BASE_URL",description:'Per-slot endpoint base URL for the "local" tier. Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:11434/v1",category:"model"},{name:"AFK_MODEL_LARGE",description:'Bind the "large" capability tier (most capable) to a model id/alias. Overrides afk.config.json models.large.',type:"string",required:!1,example:"claude-opus-4-8",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-4-6",category:"model"},{name:"AFK_MODEL_MEDIUM_API_KEY",description:'Per-slot API key for the "medium" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_MEDIUM_BASE_URL",description:'Per-slot endpoint base URL for the "medium" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_SMALL",description:'Bind the "small" capability tier (cheap/fast) to a model id/alias. Overrides afk.config.json models.small.',type:"string",required:!1,example:"gpt-4o-mini",category:"model"},{name:"AFK_MODEL_SMALL_API_KEY",description:'Per-slot API key for the "small" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_SMALL_BASE_URL",description:'Per-slot endpoint base URL for the "small" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_PROMPT_CACHE_TTL",description:"TTL for Anthropic prompt-cache blocks. Accepts 5m or 1h.",type:"string",required:!1,default:"1h",example:"1h",category:"model"},{name:"AFK_SUGGEST_ENABLED",description:"Enable the LLM-backed ghost-text suggestion tier in the interactive REPL. Set to 1/true/yes/on to activate. Off by default.",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_GHOST",description:"Enable REPL ghost-text inline suggestions (Tier-1 history/dropdown + optional Tier-2 LLM). 1 = on (default), 0 = off. Set 0/false/off/no to disable all ghost text. Tier-2 LLM is separately gated by AFK_SUGGEST_ENABLED.",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_MODEL",description:"Override the small model used for REPL ghost-text suggestions. Falls back to AFK_COMPACT_MODEL or haiku-class for anthropic, or the session model for other providers.",type:"string",required:!1,category:"model"},{name:"AFK_TASK_BUDGET",description:"Per-task token budget ceiling. Aborts when cumulative usage would exceed it.",type:"number",required:!1,default:"100000",example:"200000",category:"model"},{name:"AFK_TEMPERATURE",description:"Numeric temperature override for model sampling. Provider default if unset.",type:"number",required:!1,example:"0.7",category:"model"},{name:"AFK_THINKING",description:"Extended-thinking mode. Accepts adaptive | disabled | enabled:<N> | enabled:max. Defaults to the model-appropriate mode when unset (adaptive on current models).",type:"string",required:!1,default:"adaptive",example:"adaptive",category:"model"},{name:"AFK_TIMEOUT_MS",description:"Per-turn timeout in milliseconds. Provider/SDK default if unset.",type:"number",required:!1,example:"120000",category:"model"},{name:"CLAUDE_MODEL",description:"Legacy alias for AFK_MODEL \u2014 supported for back-compat with pre-AFK_* deployments.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_SYSTEM_PROMPT",description:'Raw operator-overlay prompt. Highest-priority overlay (over afk.config.json and AFK.md). Appended on top of the framework base (prompts/system-prompt.md) under an "# Operator configuration" header \u2014 it augments, never replaces, the base.',type:"string",required:!1,example:"You are a helpful agent.",category:"model"},{name:"AFK_DUMP_PROMPT",description:"Write the resolved system prompt to a file at startup. Accepts a path or 1 for default location.",type:"string",required:!1,example:"/tmp/afk-prompt.txt",category:"debug"},{name:"ANTHROPIC_API_KEY",description:"Anthropic API key. Tier-1 credential \u2014 overrides keychain OAuth and CLAUDE_CODE_OAUTH_TOKEN.",type:"string",required:!1,category:"auth",secret:!0},{name:"CLAUDE_CODE_OAUTH_TOKEN",description:"Claude Code OAuth token. Tier-2 credential \u2014 used when ANTHROPIC_API_KEY is unset; falls back to keychain.",type:"string",required:!1,category:"auth",secret:!0},{name:"OPENAI_API_KEY",description:"OpenAI API key for the openai-compatible provider (gpt-*, o1*, o3*, o4* models).",type:"string",required:!1,category:"auth",secret:!0},{name:"CODEX_API_KEY",description:"Fallback OpenAI API key for the openai-compatible provider, read after OPENAI_API_KEY. Legacy name from the removed @openai/codex-sdk integration \u2014 prefer OPENAI_API_KEY.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_LOCAL_API_KEY",description:"Placeholder API key for local Anthropic-compatible servers (vllm-mlx, etc.). Set when AFK_LOCAL_BASE_URL is configured.",type:"string",required:!1,default:"local",example:"local",category:"auth",secret:!0},{name:"AFK_LOCAL_BASE_URL",description:"Base URL for a self-hosted Anthropic-compatible server. When set, routes traffic away from api.anthropic.com.",type:"string",required:!1,example:"http://127.0.0.1:8080",category:"model"},{name:"AFK_OPENAI_BASE_URL",description:"Base URL override for the OpenAI-compatible provider. Used for local shims (mlx_lm.server, Ollama, vLLM, LM Studio). The OpenAI SDK appends `/chat/completions` itself \u2014 a value ending in `/chat/completions` will be stripped at config-load time with a one-shot warning.",type:"string",required:!1,example:"http://127.0.0.1:8000/v1",category:"model"},{name:"AFK_OPENAI_USE_RESPONSES",description:"Opt the OpenAI-compatible provider into the OpenAI Responses API instead of Chat Completions for API-key sessions. Truthy values: 1, true, yes, on. The ChatGPT-subscription OAuth path uses Responses automatically regardless of this flag.",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_OPENAI_CHATGPT_OAUTH",description:"Opt into using ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. Off by default. READ-ONLY: AFK never refreshes these tokens \u2014 re-run `codex` when the access token expires. Routes requests over the Responses API to the private ChatGPT backend (chatgpt.com/backend-api).",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_PROVIDER",description:"Force provider selection (anthropic | anthropic-direct | openai | openai-compatible | openai-codex). Overrides the model-name heuristic. Same surface as the --provider CLI flag; CLI flag wins when both are set.",type:"string",required:!1,example:"openai-compatible",category:"model"},{name:"EXA_API_KEY",description:"Exa (exa.ai) search API key, enabling web_scrape search mode. Free tier (20k requests/month) available at https://exa.ai. When unset, search mode returns an actionable error; markdown and raw modes are unaffected.",type:"string",required:!1,category:"auth",secret:!0},{name:"TELEGRAM_BOT_TOKEN",description:"Telegram bot token from @BotFather. Required to run the Telegram bot surface.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_BOT_TOKEN",description:"Alternative env var name for the Telegram bot token, accepted by the setup wizard.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_ALLOWED_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs allowed to interact with the bot. Required when the bot is running.",type:"string",required:!1,example:"123456789,987654321",category:"telegram"},{name:"AFK_TELEGRAM_PRIMARY_CHAT_ID",description:"Default chat ID for outbound notifications (primary-mode routing). When unset, notifications go to the first private/DM chat in AFK_TELEGRAM_ALLOWED_CHAT_IDS. The afk.config.json telegram.notify block takes precedence.",type:"string",required:!1,example:"123456789",category:"telegram"},{name:"AFK_TELEGRAM_NOTIFY_MODE",description:"Outbound notification fan-out: primary (default \u2014 one chat), broadcast (every allowed chat), or custom (afk.config.json telegram.notify.targets). The afk.config.json telegram.notify.mode takes precedence.",type:"string",required:!1,example:"broadcast",category:"telegram"},{name:"TELEGRAM_DATA_DIR",description:"Override the directory where Telegram bot state is stored. Defaults to ~/.afk/state/telegram/.",type:"string",required:!1,category:"telegram"},{name:"TELEGRAM_VERBOSE",description:"Set to 1 to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"1",category:"telegram"},{name:"AFK_TELEGRAM_TRACE",description:"Set to 1 to dump raw bridge traffic between the agent and the Telegram bot \u2014 debugging only.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_TELEGRAM_CWD",description:"Override the working directory used by the Telegram bot when spawning agent sessions.",type:"string",required:!1,category:"telegram"},{name:"AFK_HOME",description:"Override the AFK home directory. Default: ~/.afk/.",type:"string",required:!1,default:"~/.afk",example:"/opt/afk",category:"paths"},{name:"AFK_STATE_DIR",description:"Override the entire AFK state tier (sessions/, todos/, transcripts/, memory/, daemon/, etc.), not just one subdirectory. Must be an absolute path (not /). Default: $AFK_HOME/state/.",type:"string",required:!1,category:"paths"},{name:"AFK_FRAMEWORK_DIR",description:"Override the AFK agent-framework directory used for telemetry and briefs. Default: $AFK_HOME/agent-framework/.",type:"string",required:!1,category:"paths"},{name:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Controls auto-loading of MCP configuration from <cwd>/.mcp.json. Auto-loaded by default \u2014 set to 0 to disable (mitigates config-injection risk in shared/CI environments).",type:"boolean",required:!1,example:"0",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless for daemon and subagent surfaces and headed for repl/interactive \u2014 so an operator can watch the agent work in REPL mode.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_ALLOWED_DOMAINS",description:"Comma-separated allowlist of URL host globs. When set, browser_open and any navigation that targets a host outside the list returns status: blocked_by_policy. Unset means no allowlist (permissive). Patterns use simple `*` glob matching against the URL host. Combines with AFK_BROWSER_BLOCKED_DOMAINS \u2014 block wins.",type:"string",required:!1,example:"github.com,*.atlassian.net",category:"browser"},{name:"AFK_BROWSER_BLOCKED_DOMAINS",description:"Comma-separated blocklist of URL host globs. Browser navigation that matches any entry returns status: blocked_by_policy regardless of the allowlist.",type:"string",required:!1,example:"*.ads.example.com",category:"browser"},{name:"AFK_BROWSER_DOM_SNAPSHOTS",description:"Phase 2 opt-in: when set to 1, every browser_act writes a gzipped DOM snapshot sidecar under ~/.afk/state/witness/<sid>/browser/dom-snapshots/. Off by default because snapshots are large; useful for post-mortem analysis of failed actions.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_BACKEND",description:"Select the browser provider backend. Phase 1 supports only `playwright`. Reserved for future `cdp` / `mcp` adapters. Unset defaults to `playwright`.",type:"string",required:!1,example:"playwright",category:"browser"},{name:"AFK_BROWSER_CONFIG",description:"Absolute path to an alternate browser config file. Overrides the default ~/.afk/config/browser.json lookup. Useful for per-project overrides in CI.",type:"string",required:!1,example:"/path/to/browser.json",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],v={get AFK_COMPACT_KEEP_LAST_TURNS(){return process.env.AFK_COMPACT_KEEP_LAST_TURNS},get AFK_COMPACT_MODEL(){return process.env.AFK_COMPACT_MODEL},get AFK_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_OUTPUT_TOKENS(){return process.env.AFK_MAX_OUTPUT_TOKENS},get AFK_MAX_TOKENS(){return process.env.AFK_MAX_TOKENS},get AFK_MEMORY_EVIDENCE_GATE(){return process.env.AFK_MEMORY_EVIDENCE_GATE},get AFK_MODEL(){return process.env.AFK_MODEL},get AFK_MODEL_LARGE(){return process.env.AFK_MODEL_LARGE},get AFK_MODEL_LARGE_API_KEY(){return process.env.AFK_MODEL_LARGE_API_KEY},get AFK_MODEL_LARGE_BASE_URL(){return process.env.AFK_MODEL_LARGE_BASE_URL},get AFK_MODEL_LOCAL(){return process.env.AFK_MODEL_LOCAL},get AFK_MODEL_LOCAL_API_KEY(){return process.env.AFK_MODEL_LOCAL_API_KEY},get AFK_MODEL_LOCAL_BASE_URL(){return process.env.AFK_MODEL_LOCAL_BASE_URL},get AFK_MODEL_MEDIUM(){return process.env.AFK_MODEL_MEDIUM},get AFK_MODEL_MEDIUM_API_KEY(){return process.env.AFK_MODEL_MEDIUM_API_KEY},get AFK_MODEL_MEDIUM_BASE_URL(){return process.env.AFK_MODEL_MEDIUM_BASE_URL},get AFK_MODEL_SMALL(){return process.env.AFK_MODEL_SMALL},get AFK_MODEL_SMALL_API_KEY(){return process.env.AFK_MODEL_SMALL_API_KEY},get AFK_MODEL_SMALL_BASE_URL(){return process.env.AFK_MODEL_SMALL_BASE_URL},get AFK_VISION_MODELS(){return process.env.AFK_VISION_MODELS},get AFK_PROMPT_CACHE_TTL(){return process.env.AFK_PROMPT_CACHE_TTL},get AFK_SUGGEST_ENABLED(){return process.env.AFK_SUGGEST_ENABLED},get AFK_SUGGEST_GHOST(){return process.env.AFK_SUGGEST_GHOST},get AFK_SUGGEST_MODEL(){return process.env.AFK_SUGGEST_MODEL},get AFK_TASK_BUDGET(){return process.env.AFK_TASK_BUDGET},get AFK_TEMPERATURE(){return process.env.AFK_TEMPERATURE},get AFK_THINKING(){return process.env.AFK_THINKING},get AFK_TIMEOUT_MS(){return process.env.AFK_TIMEOUT_MS},get CLAUDE_MODEL(){return process.env.CLAUDE_MODEL},get AFK_SYSTEM_PROMPT(){return process.env.AFK_SYSTEM_PROMPT},get AFK_DUMP_PROMPT(){return process.env.AFK_DUMP_PROMPT},get ANTHROPIC_API_KEY(){return process.env.ANTHROPIC_API_KEY},get CLAUDE_CODE_OAUTH_TOKEN(){return process.env.CLAUDE_CODE_OAUTH_TOKEN},get OPENAI_API_KEY(){return process.env.OPENAI_API_KEY},get CODEX_API_KEY(){return process.env.CODEX_API_KEY},get AFK_LOCAL_API_KEY(){return process.env.AFK_LOCAL_API_KEY},get AFK_LOCAL_BASE_URL(){return process.env.AFK_LOCAL_BASE_URL},get AFK_OPENAI_BASE_URL(){return process.env.AFK_OPENAI_BASE_URL},get AFK_OPENAI_USE_RESPONSES(){return process.env.AFK_OPENAI_USE_RESPONSES},get AFK_OPENAI_CHATGPT_OAUTH(){return process.env.AFK_OPENAI_CHATGPT_OAUTH},get AFK_PROVIDER(){return process.env.AFK_PROVIDER},get EXA_API_KEY(){return process.env.EXA_API_KEY},get TELEGRAM_BOT_TOKEN(){return process.env.TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_BOT_TOKEN(){return process.env.AFK_TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_ALLOWED_CHAT_IDS(){return process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS},get AFK_TELEGRAM_PRIMARY_CHAT_ID(){return process.env.AFK_TELEGRAM_PRIMARY_CHAT_ID},get AFK_TELEGRAM_NOTIFY_MODE(){return process.env.AFK_TELEGRAM_NOTIFY_MODE},get TELEGRAM_DATA_DIR(){return process.env.TELEGRAM_DATA_DIR},get TELEGRAM_VERBOSE(){return process.env.TELEGRAM_VERBOSE},get AFK_TELEGRAM_TRACE(){return process.env.AFK_TELEGRAM_TRACE},get AFK_TELEGRAM_CWD(){return process.env.AFK_TELEGRAM_CWD},get AFK_HOME(){return process.env.AFK_HOME},get AFK_STATE_DIR(){return process.env.AFK_STATE_DIR},get AFK_FRAMEWORK_DIR(){return process.env.AFK_FRAMEWORK_DIR},get HOME(){return process.env.HOME},get PATH(){return process.env.PATH},get AFK_DAEMON_CWD(){return process.env.AFK_DAEMON_CWD},get AFK_DAEMON_TASK(){return process.env.AFK_DAEMON_TASK},get AFK_DAEMON_TASK_ID(){return process.env.AFK_DAEMON_TASK_ID},get AFK_DAEMON_HOST(){return process.env.AFK_DAEMON_HOST},get AFK_SESSIONSTART_COOLDOWN_MS(){return process.env.AFK_SESSIONSTART_COOLDOWN_MS},get AFK_WORKTREE_AUTONAME(){return process.env.AFK_WORKTREE_AUTONAME},get AFK_WORKTREE_BRANCH_PREFIX(){return process.env.AFK_WORKTREE_BRANCH_PREFIX},get AFK_WORKTREE_BASE(){return process.env.AFK_WORKTREE_BASE},get AFK_WORKTREE_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},get AFK_SHOW_DIFFS(){return process.env.AFK_SHOW_DIFFS},get AFK_SKILL_STREAM_VERBOSE(){return process.env.AFK_SKILL_STREAM_VERBOSE},get FORCE_COLOR(){return process.env.FORCE_COLOR},get NO_COLOR(){return process.env.NO_COLOR},get AFK_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let t of fa){if(!t.secret)continue;let n=Object.getOwnPropertyDescriptor(v,t.name);n&&Object.defineProperty(v,t.name,{...n,enumerable:!1})}})()});import{existsSync as FS,mkdirSync as zF,renameSync as JF,cpSync as VF,rmSync as YF}from"fs";import{join as Z,dirname as BS,isAbsolute as US}from"path";import{homedir as gf}from"os";import{fileURLToPath as XF}from"url";function $e(){let e=v.AFK_HOME;if(e!==void 0&&e!==""){if(!US(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return Z(gf(),".afk")}function gn(){return Z($e(),"agent-framework")}function Tr(){return Z(gn(),"forge-telemetry.jsonl")}function Ss(){return Z(gn(),"briefs")}function cc(){return Z($e(),"skills")}function Ve(){return Z($e(),"plugins")}function jS(){return Z(process.cwd(),".afk")}function uc(){return Z(jS(),"skills")}function dc(){return Z(jS(),"plugins")}function pc(e=process.cwd()){return Z(e,".afk","plans")}function ce(){return Z(Ve(),".index.json")}function hf(){return Z(Qt(),"schedules.json")}function Kn(){return Z(Ve(),"cache")}function ga(e){return Z(Kn(),e)}function vs(){let e=XF(import.meta.url),t=BS(e);return Z(t,"bundled-plugins")}function Qt(){return Z($e(),"config")}function Te(){let e=v.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!US(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return Z($e(),"state")}function mc(){return Z($e(),"cache")}function ks(){return Z($e(),"logs")}function Gn(){return Z(Te(),"sessions")}function fc(){return Z(Te(),"presence")}function yf(){return Z(Te(),"todos")}function ha(){return Z(Te(),"transcripts")}function gc(){return Z(Te(),"memory")}function hn(){return Z(Te(),"queue")}function Es(){return Z(Te(),"session-grants.jsonl")}function ya(){return Z(Qt(),"permissions.json")}function HS(){return Z($e(),"farms")}function bf(e){return Z(HS(),e)}function QF(e){if(!ZF.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function Ts(e){return QF(e),Z(Te(),"witness",e)}function wf(){return Z(Te(),"receipts")}function hc(e="default"){return Z(Te(),"daemon",`agent-afk@${e}`)}function WS(){return Z(Te(),"worktree-sweep.lock")}function ht(){return Z(Qt(),"afk.env")}function Bt(){return Z(Qt(),"afk.config.json")}function KS(){return Z(Qt(),"settings.json")}function GS(e=process.cwd()){return Z(e,".afk","settings.json")}function qS(){return Z(gf(),".afk.env")}function yc(){return Z(gf(),".afk.config.json")}function eN(){return Z($e(),"sessions")}function tN(){return Z($e(),"todos")}function nN(){return Z($e(),"transcripts")}function Sf(e,t){if(e!==t&&FS(e)&&!FS(t))try{zF(BS(t),{recursive:!0});try{JF(e,t)}catch(n){if(n.code==="EXDEV")try{VF(e,t,{recursive:!0}),YF(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
|
|
3
|
+
`)}}}catch{}}function zS(){Sf(eN(),Gn())}function JS(){Sf(tN(),yf())}function VS(){Sf(nN(),ha())}function vf(){return Z(Te(),"repl-history.jsonl")}function oN(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(e.length>NS)throw new Error(`Invalid jobId: exceeds ${NS} chars`);if(!rN.test(e))throw new Error(`Invalid jobId: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function ba(){return Z(Te(),"bg")}function yo(e){return oN(e),Z(ba(),e)}function bc(e){return Z(yo(e),"events.jsonl")}function kf(e){return Z(yo(e),"meta.json")}function wc(e){return typeof e=="string"&&e.length>0&&e.length<=iN&&sN.test(e)}function wa(e){if(!wc(e))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(e)}`);return Z(Gn(),e)}function Ef(e){return Z(wa(e),"events.jsonl")}function Tf(e){return Z(wa(e),"session.key")}function Sa(){return Z(Te(),"mcp","server-status.json")}var ZF,rN,NS,sN,iN,G=_(()=>{"use strict";q();ZF=/^[a-zA-Z0-9_-]+$/;rN=/^[A-Za-z0-9_-]+$/,NS=128;sN=/^[A-Za-z0-9_-]+$/,iN=128});import{randomBytes as aN}from"node:crypto";import{mkdirSync as lN,renameSync as cN,rmSync as YS,writeFileSync as uN}from"node:fs";import{dirname as dN,isAbsolute as pN,join as mN}from"node:path";function Sc(){return mN(Te(),"last-cwd")}function XS(){try{YS(Sc(),{force:!0})}catch{}}function ZS(e){if(!pN(e))throw new Error(`recordCdIntent: target must be an absolute path, got ${JSON.stringify(e)}`);if(/[\n\r\0]/.test(e))throw new Error(`recordCdIntent: target must not contain newline/CR/NUL, got ${JSON.stringify(e)}`);try{let t=Sc();lN(dN(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${aN(6).toString("hex")}`;try{uN(n,e,{encoding:"utf8",mode:384}),cN(n,t)}catch(r){try{YS(n,{force:!0})}catch{}throw r}}catch{}}function QS(){let e=v.AFK_SHELL_WRAPPER;return e==="1"||e==="true"}var vc=_(()=>{"use strict";q();G()});var it,Ut,be,xr,kc,Rt=_(()=>{"use strict";it=class extends Error{constructor(t){super(t),this.name="AbortError"}},Ut=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},be=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},xr=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},kc=class extends Error{constructor(n,r,o){super(o??`${n} provider does not support AgentConfig.${r}.`);this.provider=n;this.field=r;this.name="UnsupportedProviderConfigError"}provider;field}});function We(){return v.AFK_DEBUG==="1"||v.DEBUG==="1"}function z(...e){We()&&console.log(...e)}var _e=_(()=>{"use strict";q()});async function Is(e,t){if(e)try{await e.write({kind:"tool_call",payload:t})}catch(n){z(`trace.emit tool_call failed: ${yn(n)}`)}}async function Ar(e,t){if(e)try{await e.write({kind:"hook_decision",payload:t})}catch(n){z(`trace.emit hook_decision failed: ${yn(n)}`)}}async function So(e,t){if(e)try{await e.write({kind:"subagent_lifecycle",payload:t})}catch(n){z(`trace.emit subagent_lifecycle failed: ${yn(n)}`)}}async function Ps(e,t){if(e)try{await e.write({kind:"background_agent",payload:t})}catch(n){z(`trace.emit background_agent failed: ${yn(n)}`)}}async function Ev(e,t){if(e)try{await e.write({kind:"budget",payload:t})}catch(n){z(`trace.emit budget failed: ${yn(n)}`)}}async function Tv(e,t){if(e)try{await e.write({kind:"abort",payload:t})}catch(n){z(`trace.emit abort failed: ${yn(n)}`)}}async function xv(e,t){if(e)try{await e.write({kind:"compaction",payload:t})}catch(n){z(`trace.emit compaction failed: ${yn(n)}`)}}async function Rv(e,t){if(e)try{await e.write({kind:"closure",payload:t})}catch(n){z(`trace.emit closure failed: ${yn(n)}`)}}async function et(e,t){if(e)try{await e.write({kind:"browser_event",payload:t})}catch(n){z(`trace.emit browser_event failed: ${yn(n)}`)}}async function De(e,t){if(e)try{await e.write({kind:"session_phase",payload:t})}catch(n){z(`trace.emit session_phase failed: ${yn(n)}`)}}function yn(e){return e instanceof Error?e.message:String(e)}var je=_(()=>{"use strict";_e()});function Ic(e){return e.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Ta(e,t,n){let r=t==="oauth"?{authToken:e}:{apiKey:e};return typeof n=="string"&&n.length>0?{...r,baseURL:n}:r}function bn(e,t,n,r){return e!=="oauth"?{}:{"anthropic-beta":r?`${Cv},${VN}`:Cv,"x-app":"cli","User-Agent":YN,"X-Claude-Code-Session-Id":t,"x-client-request-id":n}}function Av(e){return e!=="oauth"?null:[{type:"text",text:XN}]}var Cv,VN,YN,XN,Ms=_(()=>{"use strict";Cv="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",VN="effort-2025-11-24",YN="claude-cli/1.0.0 (external, cli)",XN="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;"});function Oc(e){Ff=e}function Lf(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}function Pc(e,t,n){let r={},o=Lf(e);o&&(r.id=o);let s=Lf(t);s&&(r.baseUrl=s);let i=Lf(n);return i&&(r.apiKey=i),r}function tB(){return{local:Pc(v.AFK_MODEL_LOCAL,v.AFK_MODEL_LOCAL_BASE_URL,v.AFK_MODEL_LOCAL_API_KEY),small:Pc(v.AFK_MODEL_SMALL,v.AFK_MODEL_SMALL_BASE_URL,v.AFK_MODEL_SMALL_API_KEY),medium:Pc(v.AFK_MODEL_MEDIUM,v.AFK_MODEL_MEDIUM_BASE_URL,v.AFK_MODEL_MEDIUM_API_KEY),large:Pc(v.AFK_MODEL_LARGE,v.AFK_MODEL_LARGE_BASE_URL,v.AFK_MODEL_LARGE_API_KEY)}}function Uf(e){let t=tB(),n={};for(let r of Nf){let o=vo[r],s=e?.[r],i=t[r],a={id:i.id??s?.id??o.id},l=s?.name;l&&(a.name=l);let c=s?.provider;c&&(a.provider=c);let u=i.baseUrl??s?.baseUrl;u&&(a.baseUrl=u);let d=i.apiKey??s?.apiKey;d&&(a.apiKey=d),n[r]=a}return n}function Os(e){return e||Ff||Uf()}function $s(e,t=Os()){let n=e.trim().toLowerCase();if(!n||n===QN)return;for(let o of Nf){let s=t[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:ZN[n]}function jf(e,t=Os()){if(e===void 0)return{id:""};let n=$s(e,t);if(n)return t[n];let r=eB[e.trim().toLowerCase()];return r?{id:r}:{id:e}}function ko(e,t=Os()){if(e!==void 0)return jf(e,t).id}function Ds(e,t=Os()){if(e===void 0)return;let n=$s(e,t);if(n&&t[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 _v(e){let t={};if(!e||typeof e!="object")return t;let n=e;for(let r of Nf){let o=rB(n[r]);o&&(t[r]=o)}return t}function nB(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();if(t==="anthropic"||t==="anthropic-direct")return"anthropic";if(t==="openai"||t==="openai-compatible")return"openai"}function Mc(e){return typeof e=="string"?e.trim():""}function rB(e){if(typeof e=="string"){let t=e.trim();return t?{id:t}:void 0}if(e&&typeof e=="object"){let t=e,n=Mc(t.id);if(!n)return;let r={id:n},o=Mc(t.name);o&&(r.name=o);let s=nB(t.provider);s&&(r.provider=s);let i=Mc(t.baseUrl);i&&(r.baseUrl=i);let a=Mc(t.apiKey);return a&&(r.apiKey=a),r}}var Nf,vo,ZN,QN,Bf,eB,Ff,en=_(()=>{"use strict";q();Nf=["local","small","medium","large"],vo={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-4-6"},large:{id:"claude-opus-4-8"}},ZN={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},QN="auto",Bf="claude-fable-5",eB={fable:Bf}});function Wf(e){return e in Hf}function yt(e){return ko(e)}var Hf,Jn=_(()=>{"use strict";en();Hf={opus:vo.large.id,opus_1m:vo.large.id,sonnet:vo.medium.id,sonnet_1m:vo.medium.id,haiku:vo.small.id,fable:Bf}});import oB from"@anthropic-ai/sdk";import{randomUUID as Iv}from"node:crypto";async function Ls(e){let{token:t,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=e;if(!t)throw new Error("oneShotCompletion: token required");let l=Ic(t),c=Ta(t,l),u=a?a(c):new oB(c),d=Iv(),p=Iv(),m=bn(l,d,p),g=yt(n)??n,h={};Object.keys(m).length>0&&(h.headers=m),i&&(h.signal=i);let b=await u.messages.create({model:g,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(h).length>0?h:void 0),y=[];for(let w of b.content)w.type==="text"&&y.push(w.text);let S=y.join("").trim();return S.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),S}var $c=_(()=>{"use strict";Ms();Jn()});import{execFileSync as Pv}from"child_process";import{existsSync as sB,readFileSync as iB,writeFileSync as aB}from"fs";import{homedir as Mv,userInfo as Ov}from"os";import{join as $v}from"path";function bt(){let e=Dv();if(e===void 0)return;let t=Lv(e);if(t!==void 0){if(t.expiresAt!==void 0&&t.expiresAt<=Date.now()){process.stderr.write("agent-afk: Claude Code OAuth token in keychain is expired. Run `claude login` to refresh.\n");return}return t.accessToken}}async function Kf(){let e=Dv();if(e===void 0)return;let t=Lv(e);if(t===void 0)return;if(t.expiresAt!==void 0&&t.expiresAt>Date.now()+uB)return t.accessToken;if(!t.refreshToken){process.stderr.write("agent-afk: OAuth token expired and no refresh token available. Run `claude login` to refresh.\n");return}let n=await dB(t.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(e)}catch{}let o=r.claudeAiOauth??{};r.claudeAiOauth={...o,accessToken:n.accessToken,expiresAt:n.expiresAt,...n.refreshToken!==void 0?{refreshToken:n.refreshToken}:{}},pB(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
4
4
|
`)}return n.accessToken}function Dv(){if(process.platform==="darwin")try{return Pv("security",["find-generic-password","-s","Claude Code-credentials","-a",Ov().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let e=$v(Mv(),".claude",".credentials.json");if(!sB(e))return;try{return iB(e,"utf-8")}catch{return}}}function Lv(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null)return;let n=t.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 dB(e){try{let t=await fetch(cB,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:lB})});if(!t.ok)return;let n=await t.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 _r(e){if(!e||e.length<3)return"token:(unknown)";try{let n=e.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:${e.length>=8?e.slice(-8):e}`}function pB(e){if(process.platform==="darwin")Pv("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",Ov().username,"-w",e],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let t=$v(Mv(),".claude",".credentials.json");mB(t,e)}}function mB(e,t){aB(e,t,{encoding:"utf-8",mode:384})}var lB,cB,uB,Fs=_(()=>{"use strict";lB="9d1c250a-e61b-44d9-88ed-5944d1962f5e",cB="https://platform.claude.com/v1/oauth/token",uB=300*1e3});function wn(e){return e==="bypassPermissions"||e==="autonomous"}var xa=_(()=>{"use strict"});function Dc(e){if(typeof e?.baseUrl=="string"&&e.baseUrl.length>0)return!1;let t=v.AFK_DISABLE_PROMPT_CACHE;if(t===void 0||t.length===0)return!0;let n=t.toLowerCase();return!(n==="1"||n==="true"||n==="yes"||n==="on")}function Lc(){let e=v.AFK_PROMPT_CACHE_TTL;return e==="5m"?"5m":e==="1h"?"1h":fB}function Fv(e,t){if(e.length===0)return e;let n=e[e.length-1],r=Bv(n,t);return r===n?e:[...e.slice(0,-1),r]}function Nv(e,t){if(e.length===0)return e;let n=e[e.length-1],r=gB(n,t);return r===n?e:[...e.slice(0,-1),r]}function gB(e,t){let n=e.content;if(typeof n=="string")return n.length===0?e:{...e,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:t}}]};if(!Array.isArray(n)||n.length===0)return e;let r=n[n.length-1],o=Bv(r,t);return o===r?e:{...e,content:[...n.slice(0,-1),o]}}function Bv(e,t){return e.type==="thinking"||e.type==="redacted_thinking"?e:{...e,cache_control:{type:"ephemeral",ttl:t}}}var fB,Gf=_(()=>{"use strict";q();fB="1h"});function Uv(e){return e!=="plan"?null:{type:"text",text:qf}}var qf,zf=_(()=>{"use strict";qf=["## Plan mode is active","","File and memory write tools (`write_file`, `edit_file`, `memory_update`, `procedure_write`) are refused at the hook layer.","`bash` runs for read-only investigation (git status/log/diff, ls, cat, grep, find \u2014 chained or not); state-mutating bash (file writes, rm, installs, commits, pushes) is refused while planning. The user has asked you to plan, not yet to act \u2014 exit plan mode to make changes.","Treat this turn as planning work.","","Traverse the shape that matches the work \u2014 skip steps the terrain already covers, do not skip steps the terrain hides:",""," unknown field \u2192 ground the current terrain \u2192 gather missing codebase context \u2192"," research missing external context \u2192 reveal chaos / constraints / risks \u2192"," name the failure geometry \u2192 form a candidate plan \u2192 apply adversarial pressure \u2192 embody the final plan","","Reach for these skills (invoke via the `skill` tool) when the cost of skipping exceeds the cost of dispatching:"," - `ground-state` \u2014 survey git, infra, memory before non-trivial work"," - `gather` \u2014 parallel context-gathering for a code area"," - `research` \u2014 parallel external + local context for the current task"," - `devils-advocate` \u2014 generate alternatives and rank them before committing"," - `shadow-verify` \u2014 independently re-derive load-bearing claims","","Do not declare readiness silently. When the plan is ready, state: chosen approach, risks named, and alternatives considered.","","Then, IF the task requires implementation (writing code or files), call the `exit_plan_mode` tool to present your plan. The user picks how to proceed (approve and implement, or keep planning). After calling it, END YOUR TURN \u2014 on approval you will receive a separate instruction to save the plan to a file and implement it. Do NOT use `ask_question` to ask whether the plan is OK; that is exactly what `exit_plan_mode` does \u2014 use `ask_question` only to resolve open requirement questions first. For research / read-only tasks that need no code changes, do NOT call `exit_plan_mode` \u2014 just answer.","","Manual fallbacks remain: the user can exit with `/plan off` (same save-and-implement handoff), and Shift+Tab advances the permission-mode ring without saving or implementing. Keep the plan concrete and complete enough to act on directly."].join(`
|
|
5
5
|
`)});function jv(e){return e!=="autonomous"?null:{type:"text",text:Jf}}var Jf,Vf=_(()=>{"use strict";Jf=["## 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(`
|
|
6
6
|
`)});function He(e){let t=Hv[e];if(!t){let n=Object.keys(Hv).sort(),r=n.length>0?"Available: "+n.join(", "):"";throw new Error("Unknown skill: "+e+". "+r)}return t}var Hv,tn=_(()=>{"use strict";Hv={"audit-fit":{"01-skill-inspector.md":`# Skill Inspector
|
|
@@ -855,7 +855,7 @@ Don't refuse the flow; just clarify where the wizard runs.
|
|
|
855
855
|
|
|
856
856
|
Be terse and operational. The user is doing one-time setup; they want it done, not narrated. Confirm each step in one line, don't over-explain. Use \`\u2713\` for success, \`\u2717\` for failure, and code fences for any command they should run.
|
|
857
857
|
`}}});function nn(e,t){return t?!0:(e.audience??"public")==="public"}function Ct(e){Fc.set(e.name,e)}function Ke(e){let t=Fc.get(e);if(t)return t;let n=Array.from(Fc.keys()).sort(),r=n.length>0?`
|
|
858
|
-
Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${e}${r}`)}function Vn(){return Array.from(Fc.keys()).sort()}function Yf(e){return Vn().filter(t=>nn(Ke(t),e))}var Fc,
|
|
858
|
+
Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${e}${r}`)}function Vn(){return Array.from(Fc.keys()).sort()}function Yf(e){return Vn().filter(t=>nn(Ke(t),e))}var Fc,wt=_(()=>{"use strict";Fc=new Map});function hB(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}var Nc,Wv=_(()=>{"use strict";je();Nc=class{nodes=new Map;traceWriter;constructor(t){this.traceWriter=t}register(t,n){this.nodes.has(t)||this.nodes.set(t,{controller:n,children:new Set,listeners:new Set,cascading:!1})}has(t){return this.nodes.has(t)}getController(t){return this.nodes.get(t)?.controller}childrenOf(t){let n=this.nodes.get(t);return n?Array.from(n.children):[]}linkChild(t,n){let r=this.nodes.get(t),o=this.nodes.get(n);if(!r)throw new Error(`AbortGraph: parent ${t} not registered`);if(!o)throw new Error(`AbortGraph: child ${n} not registered`);if(o.parentId=t,r.children.add(n),r.controller.signal.aborted){o.controller.signal.aborted||(o.cascading=!0,o.controller.abort(r.controller.signal.reason));return}r.controller.signal.addEventListener("abort",()=>{let s=this.nodes.get(n);!s||s.parentId!==t||s.controller.signal.aborted||(s.cascading=!0,s.controller.abort(r.controller.signal.reason))},{once:!0}),o.controller.signal.addEventListener("abort",()=>{let s=this.nodes.get(n);if(!s||s.parentId!==t||s.cascading)return;let i=this.nodes.get(t);if(!i)return;let a={parentId:t,childId:n,reason:s.controller.signal.reason};for(let l of i.listeners)try{l(a)}catch{}},{once:!0})}onChildAborted(t,n){let r=this.nodes.get(t);if(!r)throw new Error(`AbortGraph: ${t} not registered`);return r.listeners.add(n),()=>{r.listeners.delete(n)}}abort(t,n,r="user_signal"){let o=this.nodes.get(t);if(!o||o.controller.signal.aborted)return;let s=[],i=[...o.children],a=new Set;for(;i.length;){let l=i.shift();if(a.has(l))continue;a.add(l);let c=this.nodes.get(l);if(c){c.cascading=!0,s.push(l);for(let u of c.children)i.push(u)}}Tv(this.traceWriter,{origin:r,cascadedTo:s,...n!==void 0?{reason:hB(n)}:{}}),o.controller.abort(n);for(let l of s){let c=this.nodes.get(l);c&&!c.controller.signal.aborted&&c.controller.abort(n)}}dispose(t){let n=this.nodes.get(t);if(n){n.parentId&&this.nodes.get(n.parentId)?.children.delete(t);for(let r of n.children){let o=this.nodes.get(r);o&&(o.parentId=void 0)}this.nodes.delete(t)}}}});async function Uc(e,t,n={}){if(!Number.isFinite(t)||t<=0)return e;let r,o=new Promise((s,i)=>{r=setTimeout(()=>{let a=n.label?` (${n.label})`:"",l=new Ut(`Operation timed out after ${t}ms${a}`,t);n.controller&&!n.controller.signal.aborted&&n.controller.abort(l),i(l)},t)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}var Bc,Xf,jc=_(()=>{"use strict";Rt();Bc=0,Xf=5e3});function yB(e,t,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new Sn(n,t)))},t);i.unref(),Promise.resolve(e).then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}function bB(e){return e.continue===!1||e.decision==="block"}function Zf(e,t){if(e?.aborted){let n=e.reason,r=`aborted during ${t}${n?`: ${String(n)}`:""}`;throw new it(r)}}function Kv(){return new Qf}var Eo,Sn,Qf,Ra=_(()=>{"use strict";Rt();Eo=3e4;Sn=class extends Error{constructor(n,r){super(`hook handler timed out after ${r}ms during ${n}`);this.hookEvent=n;this.timeoutMs=r;this.name="HookHandlerTimeoutError"}hookEvent;timeoutMs;code="HOOK_HANDLER_TIMEOUT"},Qf=class{handlers=new Map;register(t,n,r={}){let o=this.handlers.get(t);o||(o=[],this.handlers.set(t,o));let s={handler:n,options:r};return o.push(s),()=>{let i=this.handlers.get(t);if(!i)return;let a=i.indexOf(s);a>=0&&i.splice(a,1)}}count(t){return this.handlers.get(t)?.length??0}async dispatch(t,n,r=Eo){Zf(n,t.event);let o=this.handlers.get(t.event);if(!o||o.length===0)return{};let s=o.slice(),i={};for(let a of s){Zf(n,t.event);let l;try{let c=a.handler(t,n);l=!a.options.longRunning&&r>0&&Number.isFinite(r)?await yB(c,r,t.event):await c}catch(c){throw c instanceof Sn?c:new be(`hook handler threw during ${t.event}`,t.event,c instanceof Error?c.message:String(c),{cause:c})}if(Zf(n,t.event),bB(l))throw new be(`hook handler blocked ${t.event}${l.reason?`: ${l.reason}`:""}`,t.event,l.reason);i=l}return i}}});async function vn(e,t,n,r){if(!e)return;if(r.kind==="blocked"){await Ar(e,{hookEvent:t,decision:"block",...r.err.reason!==void 0?{reason:r.err.reason}:{},...t==="PreToolUse"&&n.toolName!==void 0?{blockedTool:n.toolName}:{}});return}let o=r.decision;await Ar(e,{hookEvent:t,decision:o.decision,...o.reason!==void 0?{reason:o.reason}:{},...o.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(o.injectContext,"utf8")}:{}})}async function Gv(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await vn(n.traceWriter,"SubagentStart",{},{kind:"decision",decision:r})}catch(r){throw r instanceof be&&await vn(n.traceWriter,"SubagentStart",{},{kind:"blocked",err:r}),r}}function wB(e,t,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new Sn(n,t)))},t);i.unref(),e.then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}async function qv(e,t,n={}){if(!e)return{};try{let r=await wB(e.dispatch(t,n.signal,Eo),Eo,"SubagentStop");return await vn(n.traceWriter,"SubagentStop",{},{kind:"decision",decision:r}),r}catch(r){return r instanceof Sn?(console.warn(`[afk] SubagentStop hook timed out after ${Eo}ms (subagentId=${t.subagentId}): ${r.message}`),n.onError?.(r),{}):(r instanceof be&&await vn(n.traceWriter,"SubagentStop",{},{kind:"blocked",err:r}),r instanceof be||r instanceof it?(z(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):(z(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{}))}}async function eg(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await vn(n.traceWriter,"PreToolUse",{toolName:t.toolName},{kind:"decision",decision:r})}catch(r){throw r instanceof be&&await vn(n.traceWriter,"PreToolUse",{toolName:t.toolName},{kind:"blocked",err:r}),r}}async function zv(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await vn(n.traceWriter,"PostToolUse",{toolName:t.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof be&&await vn(n.traceWriter,"PostToolUse",{toolName:t.toolName},{kind:"blocked",err:r}),r instanceof be||r instanceof it){z(`PostToolUse hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}z(`PostToolUse hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}async function Jv(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await vn(n.traceWriter,"PostToolUseFailure",{toolName:t.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof be&&await vn(n.traceWriter,"PostToolUseFailure",{toolName:t.toolName},{kind:"blocked",err:r}),r instanceof be||r instanceof it){z(`PostToolUseFailure hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}z(`PostToolUseFailure hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var Hc=_(()=>{"use strict";_e();Rt();Ra();je()});import{mkdir as SB,writeFile as vB}from"fs/promises";import{dirname as kB,join as EB}from"path";function TB(){return EB(gn(),"routing-decisions.jsonl")}function xB(e){let t={surface:"afk"};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}async function Be(e){if(!(v.VITEST||v.NODE_ENV==="test"))try{let t=TB();await SB(kB(t),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,...xB(e)})+`
|
|
859
859
|
`;await vB(t,r,{flag:"a"})}catch{}}var Yn=_(()=>{"use strict";q();G()});import{AsyncLocalStorage as RB}from"node:async_hooks";function Ns(e,t){return Vv.run(e,t)}function Ht(){return Vv.getStore()}var Vv,Xn=_(()=>{"use strict";Vv=new RB});function Yv(){return Kv()}function Wc(e,t){return e??t}var Kc=_(()=>{"use strict";Ra()});function tg(e,t){return t?.allowedTools?t.allowedTools.includes(e)?{allowed:!0}:{allowed:!1,reason:`Tool "${e}" is not in the configured allowlist`}:{allowed:!0}}function Gc(e,t){return Xv(e,t)}function qc(e,t){return Xv(e,t)}function Xv(e,t){if(!e?.allowedTools||t.length===0)return e;let n=new Set(e.allowedTools),r=!1;for(let o of t)n.has(o)||(n.add(o),r=!0);return r?{...e,allowedTools:[...n]}:e}var zc=_(()=>{"use strict"});function cU(e){return e.replace(/'[^']*'/g," ").replace(/"(?:[^"\\]|\\.)*"/g,t=>/\$\(|`/.test(t)?t:" ")}function Vc(e){if(typeof e!="string"||e.trim().length===0)return{mutating:!1};let t=e.replace(OB," ");for(let s of aU)if(s.re.test(t))return{mutating:!0,reason:s.reason};let n=e.match(ZB)?.[1];if(n&&QB.test(n))return{mutating:!0,reason:"interpreter one-liner file write (`-c`/`-e`)"};let r=cU(e);for(let s of lU)if(s.re.test(r))return{mutating:!0,reason:s.reason};let o=r.replace(sU," ").replace(oU," ").replace(/&(>>?)/g,"$1");return iU.test(o)?{mutating:!0,reason:"output redirection to a file (`>`/`>>`)"}:{mutating:!1}}var CB,AB,_B,IB,PB,MB,OB,$B,DB,LB,FB,NB,BB,UB,jB,HB,WB,Jc,KB,GB,qB,zB,JB,VB,YB,XB,ZB,QB,eU,tU,nU,rU,oU,sU,iU,aU,lU,ng=_(()=>{"use strict";CB=/\bgit\b[^|;&]*\s(commit|push|pull|merge|rebase|reset|checkout|switch|restore|cherry-pick|revert|am|apply|clean|add|rm|mv|init)\b/i,AB=/\bgit\b[^|;&]*\s+tag\s+-/i,_B=/\bgit\b[^|;&]*\s+branch\s+-[dDmM]\b/i,IB=/\bgit\b[^|;&]*\s+remote\s+(add|remove|rm|set-url|rename)\b/i,PB=/\bgit\b[^|;&]*\s+worktree\s+(remove|prune|move|lock|unlock)\b/i,MB=/\bgit\b[^|;&]*\s+stash\b(?!\s+(list|show)\b)/i,OB=/\bstash@\{[^}]*\}/gi,$B=/\bgit\s+config\b[^|;&]*\s(--add|--unset|--unset-all|--replace-all|--rename-section|--remove-section|--edit|-e)\b/i,DB=/\bgit\s+config\s+(?:--(?:global|system|local|worktree)\s+|(?:--file|-f)\s+\S+\s+)*[\w][\w.-]*\s+\S/i,LB=/\bgh\s+\w[\w-]*\s+(create|merge|close|edit|delete|comment|review|reopen|sync|fork|clone|ready)\b/i,FB=/\bgh\s+api\b.*(-X|--method)\s+(POST|PUT|PATCH|DELETE)\b/i,NB=/\bgh\s+api\b.*(\s-f\b|\s-F\b|--field\b)/i,BB=/\bgh\s+(secret|variable|workflow|release|run|cache|ssh-key|gpg-key)\s+(set|run|rerun|cancel|upload|delete|enable|disable)\b/i,UB=/\|\s*(sh|bash|zsh|dash)\b/i,jB=/\b(rm|rmdir|unlink|mv|cp|mkdir|touch|dd|truncate|tee|sponge|ln|chmod|chown|chgrp|shred|rsync)\b/i,HB=/\bfind\b[^|;&]*\s-delete\b/i,WB=/\bfind\b[^|;&]*\s-exec\s+['"]?\s*(rm|rmdir|unlink|mv|cp|dd|truncate|shred|tee|chmod|chown|chgrp|install|patch)\b/i,Jc=String.raw`(?:^|[\n;|&(]|\$\()\s*`,KB=new RegExp(Jc+String.raw`patch\b`,"i"),GB=new RegExp(Jc+String.raw`install\b`,"i"),qB=new RegExp(Jc+String.raw`(?:source\b|\.\s+\S)`,"i"),zB=/\btar\s+-?[a-zA-Z]*[cxruA][a-zA-Z]*\b/i,JB=new RegExp(Jc+String.raw`unzip\b`,"i"),VB=/\bcpio\b[^|;&]*\s-[a-zA-Z]*i\b/i,YB=/\bsed\b[^|;&]*\s-[a-zA-Z]*i\b/i,XB=/\bperl\b[^|;&]*\s-[a-zA-Z]*i\b/i,ZB=/\b(?:python3?|nodejs|node|bun|ruby|perl|php)\b[^|;&]*?\s-(?:c|e)\b\s*("(?:[^"\\]|\\.)*"|'[^']*'|`[^`]*`)/i,QB=/open\s*\([^)]*,\s*['"][wax]|writeFileSync|writeFile\b|appendFileSync|appendFile\b|createWriteStream|File\.(?:write|delete)\b|IO\.write\b|FileUtils\.|\bBun\.write\b|os\.remove\b|shutil\.\w|\.write_text\b|\.write_bytes\b/i,eU=/\b(npm|pnpm|yarn|pip|pip3|brew|cargo|go|apt|apt-get|gem|poetry|bundle|composer)\s+(install|add|remove|uninstall|i|ci|up|update|upgrade|dlx|get|require)\b/i,tU=/\b(curl|wget)\b[^|;&]*\s(-o\b|-O\b|--output\b)/i,nU=/\bcurl\b[^|;&]*\s-X\s+(POST|PUT|PATCH|DELETE)\b/i,rU=/\bcurl\b[^|;&]*\s(-d\b|--data\b|-F\b|--form\b)/i,oU=/(\d*&?>>?\s*\/dev\/null|\d*>&\d+|&>\s*\/dev\/null|&>>\s*\/dev\/null)/gi,sU=/\$\(\(.*?\)\)/g,iU=/(?<![=<>-])>>?(?!&)/,aU=[{re:CB,reason:"git repository mutation"},{re:AB,reason:"git tag create/delete"},{re:_B,reason:"git branch delete/rename"},{re:IB,reason:"git remote mutation"},{re:MB,reason:"git stash mutation (only `stash list`/`stash show` allowed)"},{re:$B,reason:"git config write flag (only reads allowed)"},{re:DB,reason:"git config set (`<key> <value>`; only reads allowed)"},{re:LB,reason:"gh write operation"},{re:FB,reason:"gh api write method (POST/PUT/PATCH/DELETE)"},{re:NB,reason:"gh api field payload (-f/-F/--field)"},{re:BB,reason:"gh extended write operation (secret/variable/workflow/run/cache)"},{re:PB,reason:"git worktree mutation (remove/prune/move)"},{re:YB,reason:"sed in-place edit (-i)"},{re:XB,reason:"perl in-place edit (-i)"},{re:eU,reason:"package install/modify"},{re:tU,reason:"curl/wget output-to-file"},{re:nU,reason:"curl write method (POST/PUT/PATCH/DELETE)"},{re:rU,reason:"curl data/form payload"},{re:WB,reason:"find -exec with mutating verb"}],lU=[{re:UB,reason:"pipe-to-shell (RCE via piped interpreter)"},{re:jB,reason:"filesystem mutation"},{re:HB,reason:"find -delete (file removal)"},{re:KB,reason:"patch (applies a diff to files)"},{re:GB,reason:"install (writes files)"},{re:qB,reason:"source/dot-source executes a script"},{re:zB,reason:"tar create/extract/append/update (writes files/archive)"},{re:JB,reason:"unzip (writes files)"},{re:VB,reason:"cpio extract (-i mode writes files)"}]});var uU,dU,pU,mU,fU,gU,hU,yU,bU,To,xo,Ro,wU,SU,vU,kU,EU,TU,xU,RU,CU,AU,_U,IU,PU,Zn,Wt,sae,kn=_(()=>{"use strict";uU={name:"bash",category:"shell",concurrencySafe:!1,description:"Execute a shell command and return its stdout and stderr. Use for running programs, installing packages, git operations, and any task that requires a shell. Commands run in the user's default shell. Long-running commands should use timeout_ms. Output is capped at ~100KB; excess is truncated with a notice.",input_schema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute."},timeout_ms:{type:"number",description:"Optional timeout in milliseconds (default 120000, max 600000). The command is killed if it exceeds this duration."}},required:["command"]}},dU={name:"read_file",category:"read",concurrencySafe:!0,description:"Read a file from the filesystem. Returns the file content with line numbers. Use offset and limit to read specific sections of large files. When the read returns a partial view, the response ends with a `... (showing lines X-Y of Z [\u2014 pass offset=N to continue])` annotation indicating the full file size and how to continue. Binary files are detected and rejected. Missing files return an error.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to read."},offset:{type:"number",description:"Line number to start reading from (1-based). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to read. Defaults to 2000."}},required:["file_path"]}},pU={name:"write_file",category:"write",concurrencySafe:!1,description:"Write content to a file, creating it if it does not exist or overwriting if it does. Parent directories are created automatically. Prefer edit_file for modifying existing files \u2014 use write_file only for new files or complete rewrites.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to write."},content:{type:"string",description:"The full content to write to the file."}},required:["file_path","content"]}},mU={name:"edit_file",category:"write",concurrencySafe:!1,description:"Perform an exact string replacement in a file. Finds old_string and replaces it with new_string. The edit fails if old_string is not found or matches multiple locations (unless replace_all is true). Always use read_file first to verify the exact content before editing.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to edit."},old_string:{type:"string",description:"The exact string to find and replace. Must match file content exactly."},new_string:{type:"string",description:"The replacement string."},replace_all:{type:"boolean",description:"If true, replace all occurrences. If false (default), fail when multiple matches exist."}},required:["file_path","old_string","new_string"]}},fU={name:"glob",category:"read",concurrencySafe:!0,description:'Find files matching a glob pattern. Returns matching file paths, capped at 500 results. Use for discovering files before reading them. Patterns follow standard glob syntax (e.g., "src/**/*.ts", "*.json").',input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "src/**/*.ts").'},path:{type:"string",description:"Base directory to search from. Defaults to the current working directory."}},required:["pattern"]}},gU={name:"grep",category:"read",concurrencySafe:!0,description:"Search file contents for lines matching a pattern. Returns matches in file:line:content format. Runs `grep -rn` in basic-regex (BRE) mode by default, where `|` is a LITERAL pipe \u2014 not alternation; set extended: true for extended-regex (ERE) alternation. A no-match result on a pattern containing `|` is often a false negative \u2014 re-read the returned hint. Output is capped to prevent overflow. Use for finding symbols, strings, or patterns across the codebase.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Search pattern. Basic regex (BRE) by default: `|` `+` `?` `(` `)` `{` `}` are LITERAL characters. Set extended: true for extended regex (ERE) where `|` means alternation."},path:{type:"string",description:"Directory or file to search. Defaults to current working directory."},include:{type:"string",description:'File glob to restrict search (e.g., "*.ts"). Passed as --include to grep.'},extended:{type:"boolean",description:"Use extended regex (ERE, `grep -E`) so `|` is alternation and `+ ? ( ) { }` are metacharacters. Default false (BRE \u2014 those characters match literally)."}},required:["pattern"]}},hU={name:"list_directory",category:"read",concurrencySafe:!0,description:"List the contents of a directory. Returns file and subdirectory names with type annotations (directories end with /). Use for exploring project structure.",input_schema:{type:"object",properties:{path:{type:"string",description:"Absolute path to the directory to list."}},required:["path"]}},yU={name:"send_telegram",category:"web",concurrencySafe:!1,riskClass:"caution",description:"Send a Telegram message to the operator. Use to surface terminal-state notifications, blocking questions, or important status updates when the user is away from keyboard (AFK). The message is delivered through the same Telegram bot the operator uses to drive this session. By default the message goes to your primary chat (the first private chat in `AFK_TELEGRAM_ALLOWED_CHAT_IDS`, or `AFK_TELEGRAM_PRIMARY_CHAT_ID` if set); set `telegram.notify` in afk.config.json to broadcast to all allowed chats or target a custom set.\n\nPlain text only \u2014 Telegram's 4096-character limit per message is enforced. Returns an error if Telegram is not configured (missing `TELEGRAM_BOT_TOKEN` or empty allowlist) so the tool is safe to attempt unconditionally.\n\nUse sparingly: this is a real push notification to a human. Reserve for terminal states (Done/Blocked/Asking) and material progress, not running commentary. When running inside the Telegram bot, prefer replying normally \u2014 your response already reaches the operator through the bot. Use this tool only from CLI or daemon sessions.",input_schema:{type:"object",properties:{message:{type:"string",description:"Plain-text message body to send to the operator. Max 4096 characters (Telegram API limit). Must be non-empty."}},required:["message"]}},bU={name:"web_scrape",category:"web",concurrencySafe:!0,description:'Scrape a web page or run a web search and return text content suitable for reasoning over. Three modes:\n\n- `markdown` (default): fetches the URL and extracts the main content as clean markdown (Readability + Turndown). Handles JS-rendered pages: if the plain fetch yields thin content, it escalates to a headless-browser render and re-extracts. Use this for articles, docs, blog posts, and most "I want to read this page" cases. No API key required (the render fallback needs the Playwright chromium binary \u2014 `pnpm exec playwright install chromium`).\n- `raw`: GETs the URL directly with no transformation. Use for JSON APIs, robots.txt, RSS, plain-text endpoints, or when you need the literal bytes. No API key required.\n- `search`: runs a web search and returns ranked markdown results. Use when you need to FIND a URL, not read one. Provide `query` instead of `url`. Requires `EXA_API_KEY` (free tier at https://exa.ai); the handler returns a clear error if it is unset.\n\nOutputs are capped at `max_bytes` UTF-8 bytes (default 1MB, ceiling 10MB) and the request is aborted after `timeout_ms` (default 30000, ceiling 120000).',input_schema:{type:"object",properties:{mode:{type:"string",enum:["markdown","raw","search"],description:'Fetch mode. Defaults to "markdown".'},url:{type:"string",description:"Absolute http(s) URL. Required for markdown and raw modes. Ignored in search mode."},query:{type:"string",description:"Search query string. Required for search mode. Ignored otherwise."},timeout_ms:{type:"number",description:"Request timeout in milliseconds (default 30000, clamped to 120000)."},max_bytes:{type:"number",description:"Maximum UTF-8 bytes returned. Content beyond this is truncated with a marker. Default 1000000, clamped to 10000000."}},required:[]}},To={name:"agent",category:"subagent",concurrencySafe:!0,description:`Dispatch an independent subagent with its own context window and tool access. Use for tasks that protect the main session's context: codebase exploration, multi-file inspection, repo search, verification, debugging, failing-test investigation, PR review, parallel hypothesis testing, independent re-derivation of a claim, audit work, stale-path detection, feature-wiring checks, and any research-shaped investigation.
|
|
860
860
|
|
|
861
861
|
Parallelize: dispatch multiple \`agent\` calls in a single tool-use turn to run independent investigations concurrently.
|
|
@@ -1008,7 +1008,7 @@ ${n.join(`
|
|
|
1008
1008
|
|
|
1009
1009
|
Note: this search ran in basic-regex (BRE) mode, where '|' is a literal pipe \u2014 not alternation. If you intended "A or B", retry with extended: true (extended regex / ERE). If you meant the literal character '|', this empty result stands.`),u({content:R});return}if(T===2){u({content:`grep error: ${g.trim()}`,isError:!0});return}let x=m.trimEnd();x=tr(x);let C=!1;x.length>h&&(x=x.slice(0,h)+`
|
|
1010
1010
|
[output truncated]`,C=!0),u({content:x,...C?{truncated:!0}:{}})}),p.on("error",T=>{u({content:`Failed to execute grep: ${T.message}`,isError:!0})})})}}var Nk,Bk=_(()=>{"use strict";Yn();Pr();Ao();Nk=kg()});import{promises as d1}from"fs";var Uk,jk=_(()=>{"use strict";Pr();Uk=async(e,t,n)=>{if(!e||typeof e!="object")throw new Error("Invalid input: expected an object");let o=e.path;if(typeof o!="string")throw new Error("Invalid input: path must be a string");let s;try{s=Gt(o,n,"read")}catch(i){return{content:i instanceof Error?i.message:String(i),isError:!0}}try{let i=await d1.readdir(s,{withFileTypes:!0}),a=i.filter(d=>d.isDirectory()).map(d=>`${d.name}/`),l=i.filter(d=>!d.isDirectory()).map(d=>d.name);a.sort(),l.sort();let c=[...a,...l];return c.length===0?{content:"(empty directory)"}:{content:c.join(`
|
|
1011
|
-
`)}}catch(i){if(i instanceof Error){let a=i;return a.code==="ENOENT"?{content:`Directory not found: ${s}`,isError:!0}:a.code==="ENOTDIR"?{content:`Not a directory: ${s}`,isError:!0}:a.code==="EACCES"?{content:`Permission denied: ${s}`,isError:!0}:{content:`Error listing directory: ${i.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}}});function Hk(e,t=()=>{}){let n=new Set;if(!e)return n;for(let r of e.split(",")){let o=r.trim();if(o){if(!/^-?\d+$/.test(o)){t("[allowlist] Ignoring non-numeric chat ID:",o);continue}n.add(Number(o))}}return n}var Wk=_(()=>{"use strict"});function Eg(){return v.ANTHROPIC_API_KEY||v.CLAUDE_CODE_OAUTH_TOKEN||
|
|
1011
|
+
`)}}catch(i){if(i instanceof Error){let a=i;return a.code==="ENOENT"?{content:`Directory not found: ${s}`,isError:!0}:a.code==="ENOTDIR"?{content:`Not a directory: ${s}`,isError:!0}:a.code==="EACCES"?{content:`Permission denied: ${s}`,isError:!0}:{content:`Error listing directory: ${i.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}}});function Hk(e,t=()=>{}){let n=new Set;if(!e)return n;for(let r of e.split(",")){let o=r.trim();if(o){if(!/^-?\d+$/.test(o)){t("[allowlist] Ignoring non-numeric chat ID:",o);continue}n.add(Number(o))}}return n}var Wk=_(()=>{"use strict"});function Eg(){return v.ANTHROPIC_API_KEY||v.CLAUDE_CODE_OAUTH_TOKEN||bt()}function Tg(){return v.OPENAI_API_KEY||v.CODEX_API_KEY||void 0}function or(e){let t=re(e);return t==="openai-compatible"||t==="openai-codex"?Tg():Eg()}var Ks=_(()=>{"use strict";tt();Fs();q()});import{basename as Kk}from"node:path";function p1(e){return`# >>> afk shell-init >>>
|
|
1012
1012
|
# Auto-cd into a preserved worktree after \`afk\` exits.
|
|
1013
1013
|
# REQUIRES: bash or zsh. Uses \`local\` (also works in dash/ash but
|
|
1014
1014
|
# breaks in ksh93). For fish, use \`afk shell-init fish | source\`.
|
|
@@ -1075,10 +1075,10 @@ end
|
|
|
1075
1075
|
${o}`;return s.includes("already checked out")||s.includes("is already used by worktree")?new Error(`Branch '${t}' is already checked out in another worktree. Pick a different name.`):s.includes("already exists")?new Error(`Worktree path '${n}' already exists. Remove it or pick a different branch name.`):new Error(o||r||"git worktree add failed")}async function du(e,t){let n=t?.execFile??zk,r=uu(t?.branchPrefix),o=await Jk(n);return await Vk(o),eE(o,e,{execFile:n,prefix:r,baseRef:t?.baseRef})}async function Yk(e){let t=e?.execFile??zk,n=uu(e?.branchPrefix),r=await Jk(t);await Vk(r);let o=await Xk(r,e?.baseRef,t),s;return{repoRoot:r,handle:()=>s,async create(i){return s===void 0&&(s=await eE(r,i,{execFile:t,prefix:n,preResolvedBase:o})),s}}}async function Xk(e,t,n){let r=C1(t);if(r!==void 0)return Ig(r,"worktree base ref"),await Zk(e,r,n),{ref:r,sha:await Qk(e,r,n)}}function Ig(e,t){if(e.trim().length===0)throw new Error(`Invalid worktree base ref from ${t}: '' \u2014 base ref cannot be empty.`);if(e.startsWith("-"))throw new Error(`Invalid worktree base ref from ${t}: '${e}' \u2014 must not start with '-' (would be parsed by git as a flag).`);if(e.includes("\0"))throw new Error(`Invalid worktree base ref from ${t}: contains a NUL byte.`);if(/\s/.test(e))throw new Error(`Invalid worktree base ref from ${t}: '${e}' \u2014 must not contain whitespace.`)}function C1(e){let t=e??v.AFK_WORKTREE_BASE;if(!(t===void 0||t.length===0))return t}async function Zk(e,t,n){let r=t.indexOf("/");if(r<=0)return;let o=t.slice(0,r),s;try{let{stdout:a}=await n("git",["-C",e,"remote"]);s=a.split(`
|
|
1076
1076
|
`).map(l=>l.trim()).filter(l=>l.length>0)}catch{return}if(!s.includes(o))return;let i=t.slice(r+1).replace(/[~^@:].*$/,"");if(i.length!==0)try{await n("git",["-C",e,"fetch","--no-tags",o,i])}catch(a){let l=Or(a)?a.message||a.stderr||"":String(a);console.warn(`Worktree base: could not fetch '${o}/${i}' (${l.trim()}). Using the local copy of '${t}', which may be stale.`)}}async function Qk(e,t,n){try{let{stdout:r}=await n("git",["-C",e,"rev-parse","--verify",`${t}^{commit}`]),o=r.trim();if(o.length===0)throw new Error("empty rev-parse output");return o}catch(r){let o=Or(r)?r.message||r.stderr||"":String(r);throw new Error(`Cannot resolve worktree base ref '${t}': ${o.trim()} \u2014 check the ref exists (for a remote branch, make sure the remote is reachable so it can be fetched).`)}}async function A1(e,t){try{let{stdout:n}=await t("git",["-C",e,"symbolic-ref","--short","--quiet","refs/remotes/origin/HEAD"]),r=n.trim();if(r.length>0)return r}catch{}for(let n of["origin/main","origin/master"])try{let{stdout:r}=await t("git",["-C",e,"rev-parse","--verify","--quiet",`${n}^{commit}`]);if(r.trim().length>0)return n}catch{}}async function _1(e,t,n){try{return await Qk(e,t,n)}catch{return}}async function eE(e,t,n){let{execFile:r,prefix:o}=n,s=t===!0?T1(o):t;x1(s);let i=s.replaceAll("/","-"),a=Ag(e,".afk-worktrees",i),l,c,u=n.preResolvedBase??await Xk(e,n.baseRef,r);if(u!==void 0)c=u.sha,l=u.ref;else{let m=await A1(e,r);if(m!==void 0){await Zk(e,m,r);let g=await _1(e,m,r);g!==void 0&&(c=g,l=m)}}let d=["-C",e,"worktree","add","-b",s,a];c!==void 0&&d.push(c);try{await r("git",d)}catch(m){throw R1(m,s,a)}let p={path:a,branch:s,cleanup:async m=>{let g=p.path,h=p.branch;if(m?.force===!0){console.log(`Worktree removed (zero turns \u2014 no work done): ${g}`);try{await r("git",["-C",e,"worktree","remove","--force",g])}catch(y){let S=Or(y)?y.message||y.stderr||"":String(y);console.warn(`Worktree cleanup: 'git worktree remove --force ${g}' failed (${S}). Manual removal may be needed.`);return}try{await r("git",["-C",e,"branch","-d",h])}catch(y){let S=Or(y)?y.message||y.stderr||"":String(y);console.warn(`Could not delete branch '${h}': ${S}`)}return}let b;try{b=await r("git",["-C",g,"status","--porcelain"])}catch(y){let S=Or(y)?y.message||y.stderr||"":String(y);console.warn(`Worktree cleanup: could not check status at ${g} (${S}). Skipping removal \u2014 manual cleanup may be needed.`);return}if(b.stdout.trim().length>0){if(console.log(`Worktree preserved at ${g} (branch: ${h}) \u2014 uncommitted changes.`),ZS(g),!QS()){let S=xg(v.SHELL)==="fish"?"afk shell-init fish | source (add to ~/.config/fish/config.fish)":'eval "$(afk shell-init)" (add to ~/.zshrc or ~/.bashrc)';console.log(` \u2192 cd ${g}
|
|
1077
1077
|
\u2192 Or install one-time: ${S}`)}return}try{await r("git",["-C",e,"worktree","remove","--force",g])}catch(y){let S=Or(y)?y.message||y.stderr||"":String(y);console.warn(`Worktree cleanup: 'git worktree remove --force ${g}' failed (${S}). Manual removal may be needed.`);return}try{await r("git",["-C",e,"branch","-d",h])}catch(y){let S=Or(y)?y.message||y.stderr||"":String(y);console.warn(`Could not delete branch '${h}': ${S}`)}}};try{let m=c??"",g=l??"";if(c===void 0){try{m=(await r("git",["-C",e,"rev-parse","HEAD"])).stdout.trim()}catch{}try{g=(await r("git",["-C",e,"symbolic-ref","--short","HEAD"])).stdout.trim()}catch{}}let h={owner:"interactive",pid:process.pid,createdAt:new Date().toISOString(),baseSha:m,baseBranch:g};await Cg.writeFile(Ag(a,".afk-worktree-meta.json"),JSON.stringify(h,null,2),"utf-8")}catch{}return p}var zk,v1,k1,qk,Da=_(()=>{"use strict";q();vc();Rg();zk=h1(g1),v1="afk/",k1=/^[A-Za-z0-9_\-./]*$/,qk=64});import{existsSync as sr,readdirSync as nE,readFileSync as Mg,realpathSync as I1,statSync as P1}from"fs";import{homedir as rE}from"os";import{join as It}from"path";function La(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Gs){let r=e[n];if(r!==void 0){if(r===!0){t[n]={plugins:!0,skills:!0,mcp:!0};continue}if(r!==!1&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=r;t[n]={plugins:o.plugins===!0,skills:o.skills===!0,mcp:o.mcp===!0}}}}return Object.keys(t).length>0?t:void 0}function O1(){return[Bt(),yc()]}function Pt(e=O1()){for(let t of e)if(sr(t))try{let n=JSON.parse(Mg(t,"utf-8")),r=La(n.importFrom);if(r!==void 0)return r}catch{}}function rn(e,t=rE()){let n={pluginRoots:[],skillRoots:[],mcpConfigs:[]};if(!e)return n;for(let r of Gs){let o=e[r];if(!o)continue;let s=pu[r];if(o.plugins)for(let i of s.pluginRoots(t))sr(i)&&n.pluginRoots.push(i);if(o.skills){let i=`imported:${r}`;for(let a of s.skillRoots(t))sr(a)&&n.skillRoots.push({dir:a,origin:i})}if(o.mcp){let i=oE(s.mcpConfigCandidates(t));i&&n.mcpConfigs.push({source:i,format:s.mcpFormat})}}return n}function mu(e=rE()){return Gs.map(t=>$1(t,e))}function $1(e,t){let n=pu[e],r=[];for(let l of n.pluginRoots(t))r.push(...L1(l));let o=[];for(let l of n.skillRoots(t))o.push(...F1(l));let s=oE(n.mcpConfigCandidates(t)),i=s?N1(s,n.mcpFormat):[],a=r.length>0||o.length>0||s!==null||n.pluginRoots(t).some(sr)||n.skillRoots(t).some(sr);return{binary:e,label:n.label,present:a,plugins:r,skills:o,mcpServers:i,mcpConfigPath:s,mcpFormat:n.mcpFormat}}function oE(e){for(let t of e)if(sr(t))return t;return null}function D1(e){try{let t=JSON.parse(Mg(It(e,".claude-plugin","plugin.json"),"utf-8"));return typeof t.name=="string"&&t.name.length>0?t.name:null}catch{return null}}function L1(e){if(!sr(e))return[];let t=[];return sE(e,0,t,new Set),t}function sE(e,t,n,r){let o;try{o=I1(e)}catch{o=e}if(t>M1||r.has(o))return;if(r.add(o),sr(It(e,".claude-plugin","plugin.json"))){let i=D1(e)??e.split("/").filter(Boolean).pop()??e;n.push({name:i,path:e});return}let s;try{s=nE(e)}catch{return}for(let i of s){if(i.startsWith("."))continue;let a=It(e,i);try{P1(a).isDirectory()&&sE(a,t+1,n,r)}catch{}}}function F1(e){let t;try{t=nE(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t)!r.isDirectory()||r.name.startsWith("_")||r.name.startsWith(".")||sr(It(e,r.name,"SKILL.md"))&&n.push({name:r.name,path:It(e,r.name)});return n}function N1(e,t){let n;try{n=Mg(e,"utf-8")}catch{return[]}return t==="json"?B1(n):U1(n)}function B1(e){let t;try{t=JSON.parse(e)}catch{return[]}if(t===null||typeof t!="object")return[];let n=t.mcpServers;if(n===null||typeof n!="object"||Array.isArray(n))return[];let r=[];for(let[o,s]of Object.entries(n))r.push({name:o,command:H1(s)});return r}function U1(e){let t=[],n=e.split(/\r?\n/),r=!1,o=null,s=null,i=null,a=[],l=()=>{if(r&&o){let u;i!==null?u=i:s!==null?u=a.length>0?[s,...a].join(" "):s:u="(no command)",t.push({name:o,command:u})}o=null,s=null,i=null,a=[]},c=/^\[mcp_servers\.([^\]]+)\]\s*$/;for(let u of n){let d=u.trim();if(d===""||d.startsWith("#"))continue;let p=c.exec(d);if(p){l(),r=!0,o=p[1]??null;continue}if(d.startsWith("[")){l(),r=!1;continue}if(!r)continue;let m=d.indexOf("=");if(m===-1)continue;let g=d.slice(0,m).trim(),h=d.slice(m+1).trim();g==="command"?s=Pg(tE(h)):g==="url"?i=Pg(tE(h)):g==="args"&&(a=j1(h))}return l(),t}function tE(e){if(e.startsWith('"')||e.startsWith("'"))return e;let t=e.indexOf(" #");return t===-1?e:e.slice(0,t).trimEnd()}function j1(e){let t=e.trim();if(!t.startsWith("["))return[];let n=t.slice(1,t.lastIndexOf("]"));if(!n.trim())return[];try{return n.split(",").map(r=>Pg(r.trim())).filter(r=>r.length>0)}catch{return[]}}function Pg(e){let t=e.match(/^"([^"]*)"$/)??e.match(/^'([^']*)'$/);return t&&t[1]!==void 0?t[1]:e.startsWith('"')||e.startsWith("'")?e.slice(1):e.endsWith('"')||e.endsWith("'")?e.slice(0,-1):e}function H1(e){if(e===null||typeof e!="object")return"(invalid)";let t=e;if(typeof t.url=="string")return t.url;if(typeof t.command=="string"){let n=Array.isArray(t.args)?t.args.filter(r=>typeof r=="string"):[];return[t.command,...n].join(" ")}return"(no command)"}var Gs,pu,dce,M1,ir=_(()=>{"use strict";G();Gs=["claude-code","codex"],pu={"claude-code":{label:"Claude Code",pluginRoots:e=>[It(e,".claude","plugins")],skillRoots:e=>[It(e,".claude","skills")],mcpConfigCandidates:e=>[It(e,".claude","mcp.json"),It(e,".claude",".mcp.json"),It(e,".claude","claude-code","mcp.json")],mcpFormat:"json"},codex:{label:"Codex",pluginRoots:e=>[It(e,".codex","plugins")],skillRoots:e=>[It(e,".codex","skills")],mcpConfigCandidates:e=>[It(e,".codex","config.toml")],mcpFormat:"toml"}},dce={"claude-code":pu["claude-code"].label,codex:pu.codex.label},M1=5});import{readFileSync as lE,existsSync as $g}from"fs";import{join as Na}from"path";import{config as W1}from"dotenv";function Dg(){return Eg()}function K1(e){let t=e.trim();if(!t)return t;let n="/chat/completions";if(t.endsWith(n)){let r=t.slice(0,-n.length);return aE.has(t)||(aE.add(t),console.warn(`[afk] AFK_OPENAI_BASE_URL: stripped trailing "/chat/completions" \u2014 the OpenAI SDK appends it automatically.
|
|
1078
|
-
Effective base URL: ${r}`)),r}return t}function G1(){if(Og!==void 0)return Og;if(!iE){let o=[Na(process.cwd(),".env"),
|
|
1078
|
+
Effective base URL: ${r}`)),r}return t}function G1(){if(Og!==void 0)return Og;if(!iE){let o=[Na(process.cwd(),".env"),ht(),qS()];for(let s of o)$g(s)&&W1({path:s,override:!1});iE=!0}let e={},t=v.AFK_MODEL??v.CLAUDE_MODEL;if(t){let o=t.toLowerCase();e.model=Wf(o)?o:t}if(re(t)==="anthropic-direct"){let o=Dg();o!==void 0&&(e.apiKey=o)}let r=v.AFK_LOCAL_BASE_URL;if(r&&r.length>0&&(e.baseUrl=r,e.apiKey=v.AFK_LOCAL_API_KEY||"local"),v.AFK_MAX_TOKENS&&(e.maxTokens=parseInt(v.AFK_MAX_TOKENS,10)),v.AFK_TEMPERATURE&&(e.temperature=parseFloat(v.AFK_TEMPERATURE)),v.AFK_SYSTEM_PROMPT&&(e.systemPrompt=v.AFK_SYSTEM_PROMPT),v.AFK_AUTO_ROUTING){let o=v.AFK_AUTO_ROUTING.toLowerCase()==="true";e.autoRouting={interactive:o,chat:o,telegram:o,daemon:o}}return v.AFK_OPENAI_BASE_URL&&(e.openaiBaseUrl=K1(v.AFK_OPENAI_BASE_URL)),Og=e,e}function Lg(){if(qs!==void 0)return qs;let e=[Na(process.cwd(),"afk.config.json"),Bt(),yc()];for(let t of e)if($g(t))try{let n=lE(t,"utf-8"),r=JSON.parse(n),o={},s=_v(r.models);if(typeof r.model=="string"&&r.model.length>0){let i=r.model.toLowerCase();o.model=Wf(i)?i:r.model}if(typeof r.maxTokens=="number"&&(o.maxTokens=r.maxTokens),typeof r.temperature=="number"&&(o.temperature=r.temperature),r.systemPrompt&&(o.systemPrompt=r.systemPrompt),typeof r.permissionMode=="string"){let i=r.permissionMode;(i==="default"||i==="plan"||i==="autonomous"||i==="bypassPermissions")&&(o.permissionMode=i)}if(r.autoRouting&&typeof r.autoRouting=="object"){let i={};typeof r.autoRouting.interactive=="boolean"&&(i.interactive=r.autoRouting.interactive),typeof r.autoRouting.chat=="boolean"&&(i.chat=r.autoRouting.chat),typeof r.autoRouting.telegram=="boolean"&&(i.telegram=r.autoRouting.telegram),typeof r.autoRouting.daemon=="boolean"&&(i.daemon=r.autoRouting.daemon),o.autoRouting=i}if(r.daemon&&typeof r.daemon=="object"){let i={};typeof r.daemon.task=="string"&&(i.task=r.daemon.task),typeof r.daemon.taskId=="string"&&(i.taskId=r.daemon.taskId);let a=r.daemon.worktreePrune;a&&typeof a=="object"&&(i.worktreePrune={enabled:typeof a.enabled=="boolean"?a.enabled:!0,cron:typeof a.cron=="string"?a.cron:"0 4 * * *",maxAgeDaysClean:typeof a.maxAgeDaysClean=="number"?a.maxAgeDaysClean:14,maxAgeDaysDirty:typeof a.maxAgeDaysDirty=="number"?a.maxAgeDaysDirty:30,scope:typeof a.scope=="string"?a.scope:"all"}),o.daemon=i}if(r.telegram&&typeof r.telegram=="object"){let i={},a=r.telegram.notify;if(a&&typeof a=="object"){let l={};if((a.mode==="primary"||a.mode==="broadcast"||a.mode==="custom")&&(l.mode=a.mode),typeof a.primaryChatId=="number"&&Number.isFinite(a.primaryChatId)&&(l.primaryChatId=a.primaryChatId),Array.isArray(a.targets)){let c=a.targets.filter(u=>typeof u=="number"&&Number.isFinite(u));c.length>0&&(l.targets=c)}i.notify=l}typeof r.telegram.verifyDone=="boolean"&&(i.verifyDone=r.telegram.verifyDone),o.telegram=i}if(r.updatePolicy&&["notify","auto","off"].includes(r.updatePolicy)&&(o.updatePolicy=r.updatePolicy),typeof r.autoResumeOnUsageLimit=="boolean"&&(o.autoResumeOnUsageLimit=r.autoResumeOnUsageLimit),typeof r.bgSummaries=="boolean"&&(o.bgSummaries=r.bgSummaries),typeof r.maxSummaryCallsPerSession=="number"&&(o.maxSummaryCallsPerSession=Math.min(500,Math.max(1,r.maxSummaryCallsPerSession))),r.hooks!==null&&typeof r.hooks=="object"&&!Array.isArray(r.hooks)&&(o.hooks=r.hooks),typeof r.enableShellHooks=="boolean"&&(o.enableShellHooks=r.enableShellHooks),t!==Na(process.cwd(),"afk.config.json")){let i=La(r.importFrom);i!==void 0&&(o.importFrom=i)}if(r.interactive&&typeof r.interactive=="object"){let i={};typeof r.interactive.worktreeAutoname=="boolean"&&(i.worktreeAutoname=r.interactive.worktreeAutoname),typeof r.interactive.worktreeBranchPrefix=="string"&&(i.worktreeBranchPrefix=_g(r.interactive.worktreeBranchPrefix,`${t}#/interactive/worktreeBranchPrefix`)),typeof r.interactive.worktreeBase=="string"&&r.interactive.worktreeBase.trim().length>0&&(Ig(r.interactive.worktreeBase,`${t}#/interactive/worktreeBase`),i.worktreeBase=r.interactive.worktreeBase),typeof r.interactive.suggestGhost=="boolean"&&(i.suggestGhost=r.interactive.suggestGhost),Object.keys(i).length>0&&(o.interactive=i)}return qs={config:o,sourcePath:t,modelsPartial:s},qs}catch(n){console.error(`Warning: Failed to parse ${t}:`,n)}return qs={config:{},sourcePath:void 0,modelsPartial:{}},qs}function q1(){if(zs!==void 0)return zs.value;let e=[Na(process.cwd(),"AFK.md"),Na($e(),"AFK.md")];for(let t of e)if($g(t))try{let n=lE(t,"utf-8").trim();if(n.length>0)return zs={value:{content:n,path:t}},zs.value}catch{}return zs={value:null},zs.value}function fu(){return Lg().config.telegram??{}}function Js(){return Lg().config.permissionMode??cE}function At(e){let t=G1(),{config:n,sourcePath:r,modelsPartial:o}=Lg(),s={...Fa,...t,...n,...e},i;if(t.systemPrompt!==void 0)i="env:AFK_SYSTEM_PROMPT";else if(n.systemPrompt!==void 0&&r!==void 0)i=`file:${r}`;else if(s.systemPrompt===void 0){let c=q1();c!==null&&(s.systemPrompt=c.content,i=`afk-md:${c.path}`)}let a={model:s.model??Fa.model,maxTokens:s.maxTokens??Fa.maxTokens,temperature:s.temperature??Fa.temperature,updatePolicy:s.updatePolicy??Fa.updatePolicy,...s.apiKey!==void 0?{apiKey:s.apiKey}:{},...s.baseUrl!==void 0?{baseUrl:s.baseUrl}:{},...s.openaiBaseUrl!==void 0?{openaiBaseUrl:s.openaiBaseUrl}:{},...s.systemPrompt!==void 0?{systemPrompt:s.systemPrompt}:{},...i!==void 0?{systemPromptSource:i}:{},permissionMode:s.permissionMode??cE,...s.autoRouting!==void 0?{autoRouting:s.autoRouting}:{},...s.daemon!==void 0?{daemon:s.daemon}:{},...s.telegram!==void 0?{telegram:s.telegram}:{},...s.bgSummaries!==void 0?{bgSummaries:s.bgSummaries}:{},...s.maxSummaryCallsPerSession!==void 0?{maxSummaryCallsPerSession:s.maxSummaryCallsPerSession}:{},...s.interactive!==void 0?{interactive:s.interactive}:{},...s.hooks!==void 0?{hooks:s.hooks}:{},...s.enableShellHooks!==void 0?{enableShellHooks:s.enableShellHooks}:{},...s.importFrom!==void 0?{importFrom:s.importFrom}:{}},l=e?.models??Uf(o);if(Oc(l),a.models=l,typeof a.model=="string"&&a.model.toLowerCase().startsWith("local-")&&(a.baseUrl===void 0||a.baseUrl.length===0))throw new Error(`Model '${a.model}' requires AFK_LOCAL_BASE_URL to be set (e.g. AFK_LOCAL_BASE_URL=http://127.0.0.1:8080). Point it at your local Anthropic-Messages-compatible server.`);return a}var Fa,cE,iE,Og,aE,qs,zs,Mt=_(()=>{"use strict";Jn();en();tt();G();Ks();Da();q();ir();Fa={model:"sonnet",maxTokens:4096,temperature:1,updatePolicy:"notify"},cE="bypassPermissions",iE=!1;aE=new Set});function z1(e,t){return t!==void 0&&Number.isFinite(t)&&t!==0?t:e.find(r=>r>0)??e[0]}function J1(e,t={}){let n=[...e],r=t.mode??"primary";if(r==="broadcast")return n;if(r==="custom"){let s=(t.targets??[]).filter(i=>typeof i=="number"&&Number.isFinite(i)&&i!==0);if(s.length>0)return[...new Set(s)]}let o=z1(n,t.primaryChatId);return o!==void 0?[o]:[]}function V1(e){if(!e)return;let t=e.trim();if(!/^-?\d+$/.test(t))return;let n=Number(t);return Number.isFinite(n)&&n!==0?n:void 0}function Y1(e){if(!e)return;let t=e.trim().toLowerCase();return t==="primary"||t==="broadcast"||t==="custom"?t:void 0}function X1(){let e=fu().notify??{},t=e.mode??Y1(v.AFK_TELEGRAM_NOTIFY_MODE),n=e.primaryChatId??V1(v.AFK_TELEGRAM_PRIMARY_CHAT_ID);return{...t!==void 0?{mode:t}:{},...n!==void 0?{primaryChatId:n}:{},...e.targets!==void 0?{targets:e.targets}:{}}}function Vs(){let e=Hk(v.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return J1(e,X1())}var gu=_(()=>{"use strict";Wk();Mt();q()});function Fg(e,t=4096){if(e.length<=t)return[e];let n=[],r=e;for(;r.length>0;){if(r.length<=t){n.push(r);break}let o=t,s=r.lastIndexOf(`
|
|
1079
1079
|
`,t);if(s>t-500&&s>0)o=s+1;else{let i=r.slice(0,t).match(/[.!?]\s+(?=[A-Z])/g);if(i&&i.length>0){let a=i[i.length-1];if(a){let l=r.lastIndexOf(a,t);l>t-200&&l>0&&(o=l+2)}}else{let a=r.lastIndexOf(" ",t);a>t-100&&a>0&&(o=a+1)}}n.push(r.slice(0,o).trim()),r=r.slice(o).trim()}return n}function uE(e){e=e.replace(/[\x02\x03]/g,"");let t=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),n=[];t=t.replace(/^ {0,3}```([\w]*)\n([\s\S]*?)```/gm,(o,s,i)=>{let a=n.length;if(i.trim()===""){let l=s?`(empty ${s} block)`:"(empty code block)";n.push(`<i>${l}</i>`)}else n.push(`<pre>${i}</pre>`);return`FENCED${a}`});let r=[];return t=t.replace(/`([^`]+)`/g,(o,s)=>{let i=r.length;return r.push(`<code>${s}</code>`),`CODE${i}`}),t=t.replace(/\*\*([^*]+)\*\*/g,"<b>$1</b>"),t=t.replace(/__([^_]+)__/g,"<b>$1</b>"),t=t.replace(/\*([^*]+)\*/g,"<i>$1</i>"),t=t.replace(/(^|[^\w])_([^_\n]+?)_(?!\w)/gm,"$1<i>$2</i>"),t=t.replace(/~~([^~]+)~~/g,"<s>$1</s>"),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(o,s,i)=>'<a href="'+i.replace(/"/g,""")+'">'+s+"</a>"),t=t.replace(/^#{1,6}\s+/gm,""),t=t.replace(/\x02CODE(\d+)\x03/g,(o,s)=>r[Number(s)]??o),t=t.replace(/\x02FENCED(\d+)\x03/g,(o,s)=>n[Number(s)]??o),t}var dE=_(()=>{"use strict"});var Ng={};ac(Ng,{push:()=>Ys,pushIfConfigured:()=>$r,pushMarkdown:()=>pE});async function Ys(e){if(!e.token)throw new Error("push: token is required");if(e.chatId===""||e.chatId==null||e.chatId===0)throw new Error("push: chatId is required");let t=e.fetchImpl??fetch,r=`${e.apiBase??Z1}/bot${e.token}/sendMessage`,o={chat_id:e.chatId,text:e.text.slice(0,4096)};e.parseMode&&(o.parse_mode=e.parseMode),e.replyMarkup&&(o.reply_markup=e.replyMarkup);let s=new AbortController,i=setTimeout(()=>s.abort(),1e4);try{let a=await t(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:s.signal});if(a.ok)return{ok:!0,status:a.status};let l;try{l=(await a.json()).description}catch{l=`HTTP ${a.status}`}return{ok:!1,status:a.status,...l!==void 0?{errorMessage:l}:{}}}catch(a){return{ok:!1,status:0,errorMessage:a instanceof Error?a.message:String(a)}}finally{clearTimeout(i)}}async function pE(e){let t=uE(e.text),n=Fg(t),r={ok:!0,status:200};for(let o of n)if(r=await Ys({...e,text:o,parseMode:"HTML"}),!r.ok)return r.status===400&&/can't parse entities/i.test(r.errorMessage??"")?Ys({...e}):r;return r}async function $r(e,t={}){let n=v.TELEGRAM_BOT_TOKEN;if(!n)return null;let r=Vs();if(r.length===0)return null;let o=Fg(e),s=[];for(let i of r)for(let a=0;a<o.length;a++){let l={token:n,chatId:i,text:o[a]??"",...t.replyMarkup!==void 0&&a===0?{replyMarkup:t.replyMarkup}:{},...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{}};s.push(t.markdown?await pE(l):await Ys({...l,...t.parseMode!==void 0?{parseMode:t.parseMode}:{}}))}return s}var Z1,_o=_(()=>{"use strict";gu();dE();q();Z1="https://api.telegram.org"});function Q1(e=Ys){return async(t,n)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let o=t.message;if(typeof o!="string")return{content:"Invalid input: message must be a string",isError:!0};if(o.length===0)return{content:"Invalid input: message must be non-empty",isError:!0};if(o.length>mE)return{content:`Invalid input: message exceeds Telegram's ${mE}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let s=v.TELEGRAM_BOT_TOKEN;if(!s)return{content:"Telegram is not configured: TELEGRAM_BOT_TOKEN is not set. Run the bot setup wizard or export the env var before using send_telegram.",isError:!0};let i=Vs();if(i.length===0)return{content:"Telegram is not configured: AFK_TELEGRAM_ALLOWED_CHAT_IDS is empty or unset. Add the operator chat ID(s) before using send_telegram.",isError:!0};let a=[];for(let l of i){let c=await e({token:s,chatId:l,text:o});c.ok||a.push(`chat ${l}: ${c.errorMessage??`HTTP ${c.status}`}`)}return a.length===i.length?{content:`Failed to send Telegram message to any chat. ${a.join("; ")}`,isError:!0}:a.length>0?{content:`Sent Telegram message to ${i.length-a.length}/${i.length} chat(s); ${a.length} failed: ${a.join("; ")}`}:{content:i.length===1?`Sent Telegram message to chat ${i[0]}.`:`Sent Telegram message to ${i.length} chats.`}}}var mE,fE,gE=_(()=>{"use strict";q();_o();gu();mE=4096;fE=Q1()});import{JSDOM as eH}from"jsdom";import{Readability as tH}from"@mozilla/readability";import nH from"turndown";function hE(e){return e.replace(/\n{3,}/g,`
|
|
1080
1080
|
|
|
1081
|
-
`).trim()}function rH(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function bE(e,t){let r=new eH(e,{url:t}).window.document,o=(r.title??"").trim(),s=null;try{let c=r.cloneNode(!0);s=new tH(c).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let c=hE(Bg.turndown(s.content)),u=(s.title??"").trim()||o,d=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:u,markdown:c,textLength:d,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",l=hE(Bg.turndown(a));return{title:o,markdown:l,textLength:rH(i),usedFallback:!0}}var yE,Bg,wE=_(()=>{"use strict";yE=200,Bg=new nH({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});Bg.remove(["script","style","noscript","iframe"])});import{readFileSync as oH}from"node:fs";import{join as sH}from"path";function iH(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function SE(e,t){return iH(t).test(e)}function cH(e,t){if(e!==void 0){let n=e.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(t!==void 0){if(aH.has(t))return!0;if(lH.has(t))return!1}return!1}function vE(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function uH(e){if(e===void 0||e===""||e==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${e}`)}function dH(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function pH(e){try{return oH(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function mH(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return n}function kE(e){let t=e?.env??v,n=e?.readFileSync??pH,r=e?.surface??t.AGENT_SURFACE,o=cH(t.AFK_BROWSER_HEADLESS,r),s=vE(t.AFK_BROWSER_ALLOWED_DOMAINS),i=vE(t.AFK_BROWSER_BLOCKED_DOMAINS),a=dH(t.AFK_BROWSER_DOM_SNAPSHOTS),l=uH(t.AFK_BROWSER_BACKEND),c={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null},u=t.AFK_BROWSER_CONFIG,d=u!==void 0&&u.trim()!==""?u.trim():sH(Qt(),"browser.json"),p=n(d);if(p===void 0)return c;let m;try{m=JSON.parse(p)}catch(h){throw new Error(`Failed to parse browser config at ${d}: ${String(h)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${d} must be a JSON object`);let g=mH(c,m);return g.configPath=d,g}function Ug(e,t){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${e}`}}for(let r of t.blockedDomains)if(SE(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>SE(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var aH,lH,jg=_(()=>{"use strict";q();G();aH=new Set(["daemon","subagent","telegram","afk"]),lH=new Set(["repl","interactive","cli"])});import fH from"node:fs";import gH from"node:path";import{chromium as hH}from"playwright";function yH(){try{return"5.3.0"}catch{}try{let e=gH.resolve(import.meta.dirname,"../../../package.json"),t=fH.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var bH,hu,EE=_(()=>{"use strict";bH=yH(),hu=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(t){this.config=t}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=hH.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let 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(t,s),o}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",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(t){return this.sessions.get(t)?.page}async renderHtml(t,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(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await i.content(),c=i.url(),u=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${bH}`}}}});import{createHash as wH}from"crypto";function Hg(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of SH)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function TE(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&vH.test(e.label))}function xE(e){return wH("sha256").update(e,"utf8").digest("hex").slice(0,8)}function RE(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var SH,vH,Ba=_(()=>{"use strict";SH=[{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}];vH=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as kH}from"node:crypto";function EH(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function TH(e,t,n){return`el_${kH("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function xH(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function CE(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function _E(e,t){let n=e.role??"",r=e.name??"";AE.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let s of e.children??[])_E(s,t)}async function RH(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let u=window.getComputedStyle(i);if(u.display==="none"||u.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},IE).catch(()=>[])}async function CH(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let h=s.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let u="value"in s?s.value:void 0,d=u!==void 0?String(u):void 0,p=s.disabled??!1,m=i==="input"?s.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),m!==void 0&&(g.checked=m),o.push(g)}return o},IE).catch(()=>[])}function AH(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function yu(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],s=AH(e),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=RH(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,m,g,h]=await Promise.all([i,a,l,c,u]),b,y=!1;d!==null?(b=[],_E(d,b)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,b=(await CH(e)).filter(F=>AE.has(F.role??"")));let S=new Map;for(let P of p){let F=CE(P.name),D=S.get(F);(!D||D.bbox.w===0&&P.bbox.w>0)&&S.set(F,P)}let w=b.map(P=>({ax:P,dom:S.get(CE(P.name??""))})),T=r?w:w.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);T.sort((P,F)=>{let D=P.dom?.bbox.y??0,N=F.dom?.bbox.y??0;if(D!==N)return D-N;let B=P.dom?.bbox.x??0,H=F.dom?.bbox.x??0;return B-H}),T.length>200&&o.push("page has 200+ interactive elements; consider scoping");let C=T.slice(0,n).map((P,F)=>{let D=P.ax.role??"generic",N=P.ax.name??"",B=TH(D,N,F),H=P.dom?.bbox??{x:0,y:0,w:0,h:0},L=P.dom?.type??null,I=null;P.ax.value!==void 0&&P.ax.value!==null&&(I=String(P.ax.value)),P.ax.checked!==void 0&&(I=String(P.ax.checked)),TE({role:D,kind:L})&&(I="[redacted]");let U={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(U.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(U.selected=P.ax.selected),P.ax.expanded!==void 0&&(U.expanded=P.ax.expanded);let M;P.dom?.testId?M=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(M=`#${P.dom.id}`);let j={id:B,role:D,label:EH(N),kind:L,value:I,state:U,bbox:H};return M!==void 0&&(j.selector=M),j}),R="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?R="loading":P==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let k=xH(m),$=`obs_${t.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:$,url:g,title:h,textSummary:k,interactive:C,status:{httpStatus:t.httpStatus??null,loadingState:R,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:A}}var AE,IE,PE=_(()=>{"use strict";Ba();AE=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);IE="a[href], button, input, select, textarea, [role], [tabindex], label"});async function ME(e,t){try{let n=await e.nth(t).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.height)}}),r=`${n.role}:${n.label}:${t}`,o=0;for(let 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 Wg(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,s)=>ME(e,s)))).filter(o=>o!==null)}async function _H(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(i)||(t.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Kg(e,t,n){switch(t.kind){case"element_id":return IH(e,t,n);case"selector":return PH(e,t);case"semantic":return MH(e,t)}}async function IH(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:t};if(s===1)return{outcome:"resolved",locator:o};let i=await Wg(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function PH(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await Wg(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function MH(e,t){return t.role!==void 0?OH(e,t.text,t.role):$H(e,t.text,t)}async function OH(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Wg(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:s}}async function $H(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),s=e.getByLabel(t,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let u=[];i>0&&u.push({loc:r,count:i}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:s,count:l});let d=await _H(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=d.slice(0,5),m=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let y=await ME(b.locator,b.index);if(y!==null){let S=`${y.role}:${y.label}:${h}`,w=0;for(let T=0;T<S.length;T++)w=w*31+S.charCodeAt(T)>>>0;m.push({...y,id:`el_${w.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:m}}var OE=_(()=>{"use strict"});import{randomBytes as DH}from"crypto";import{mkdir as LH,stat as FH,writeFile as NH}from"fs/promises";import{join as Gg}from"path";import{gzip as BH}from"zlib";import{promisify as UH}from"util";function jH(e){return Gg(Ts(e),"browser")}function HH(e){return Gg(jH(e),"screenshots")}function WH(){return new Date().toISOString().replace(/[:.]/g,"-")}function KH(){return DH(3).toString("hex")}async function qg(e,t,n){if(t.length>$E)throw new Error(`writeScreenshotSidecar: buffer exceeds ${$E} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=HH(e);await LH(r,{recursive:!0});let o=`${WH()}-${KH()}-${n}.png`,s=Gg(r,o);await NH(s,t);let{size:i}=await FH(s);return{path:s,bytes:i}}var uue,$E,DE=_(()=>{"use strict";G();Ba();uue=UH(BH);$E=5*1024*1024});var FE={};ac(FE,{PlaywrightProvider:()=>zg});function LE(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var zg,NE=_(()=>{"use strict";EE();PE();OE();jg();Ba();DE();zg=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new hu(t)}async open(t){let n=Ug(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(c){a=c}(t.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await yu(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,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;t.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await yu(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=t.timeoutMs??3e4,a=await Kg(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${LE(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=async()=>{switch(t.action){case"click":await l.click({timeout:i});break;case"fill":{let h=Hg(t.value??"");await l.fill(t.value??"");break}case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=r.url();if(d!==s){let h=Ug(d,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:d,reason:h.reason}}let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let m=await yu(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,m.interactive,m.url,m.title,g),c!==null)throw c;return m}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(t.target!==void 0){let u=await Kg(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${LE(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await u.locator.screenshot()}else s=await r.screenshot({fullPage:t.fullPage??!1});let{path:i,bytes:a}=await qg(n,s,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(t){let n=this.sessions.get(t);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(t,r),r}updateSessionFromObservation(t,n,r,o,s){t.knownElements=new Map(n.map(i=>[i.id,i])),t.currentUrl=r,t.currentTitle=o,t.lastAction=s,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:s}=await qg(n,o,r);return s}catch{return null}}}});var Po={};ac(Po,{__resetBrowserRegistryForTests:()=>VH,browserProviderActive:()=>zH,closeBrowserProvider:()=>Jg,getBrowserProvider:()=>qH,peekBrowserProvider:()=>JH});function BE(){Promise.resolve(Jg()).then(()=>{process.exit(130)})}function UE(){Promise.resolve(Jg()).then(()=>{process.exit(143)})}function jE(){xn=null}function GH(){bu||(process.on("SIGINT",BE),process.on("SIGTERM",UE),process.on("exit",jE),bu=!0)}function HE(){bu&&(process.removeListener("SIGINT",BE),process.removeListener("SIGTERM",UE),process.removeListener("exit",jE),bu=!1)}async function qH(e){return xn!==null?xn:(Io!==null||(Io=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(NE(),FE)),n=kE(e),r=new t(n);return GH(),xn=r,Io=null,r})()),Io)}async function Jg(){if(xn===null)return;let e=xn;xn=null,Io=null,HE(),await e.shutdown()}function zH(){return xn!==null}function JH(){return xn}function VH(){xn=null,Io=null,HE()}var xn,Io,bu,Mo=_(()=>{"use strict";jg();xn=null,Io=null,bu=!1});function WE(e,t){try{return bE(e,t)}catch(n){return z("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function eW(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Mo(),Po));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function KE(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??eW,o=null,s=e,i=null,a=null;try{let c=await n(e,{headers:QH,redirect:"follow",signal:t.signal});i=c.status,s=c.url||e;let u=c.headers.get("content-type")??"";if(c.ok){if(ZH.test(u))throw new Error(`web_scrape markdown mode received binary content (${u.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let d=await c.text();if(XH.test(u)&&!YH.test(u))return{title:"",markdown:d.trim(),finalUrl:s,usedRender:!1};o=WE(d,s)}}catch(c){if(t.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<yE)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let c=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal}),u=WE(c.html,c.finalUrl);if(o===null||u.textLength>=o.textLength)return{title:u.title,markdown:u.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(t.signal.aborted)throw c;if(o===null){let u=c instanceof Error?c.message:String(c),d=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${e}: fetch failed (${d}) and render failed (${u}).`);throw p.cause=c,p}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${i??"error"}).`)}var YH,XH,ZH,QH,GE=_(()=>{"use strict";wE();_e();YH=/(text\/html|application\/xhtml\+xml)/i,XH=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,ZH=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,QH={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function rW(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await t(tW,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),nW),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let u=await s.text(),d=Co(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}catch{}let c=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${c}${l}`)}let i;try{i=await s.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(i.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function qE(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?rW({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function zE(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
1081
|
+
`).trim()}function rH(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function bE(e,t){let r=new eH(e,{url:t}).window.document,o=(r.title??"").trim(),s=null;try{let c=r.cloneNode(!0);s=new tH(c).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let c=hE(Bg.turndown(s.content)),u=(s.title??"").trim()||o,d=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:u,markdown:c,textLength:d,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",l=hE(Bg.turndown(a));return{title:o,markdown:l,textLength:rH(i),usedFallback:!0}}var yE,Bg,wE=_(()=>{"use strict";yE=200,Bg=new nH({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});Bg.remove(["script","style","noscript","iframe"])});import{readFileSync as oH}from"node:fs";import{join as sH}from"path";function iH(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function SE(e,t){return iH(t).test(e)}function cH(e,t){if(e!==void 0){let n=e.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(t!==void 0){if(aH.has(t))return!0;if(lH.has(t))return!1}return!1}function vE(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function uH(e){if(e===void 0||e===""||e==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${e}`)}function dH(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function pH(e){try{return oH(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function mH(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return n}function kE(e){let t=e?.env??v,n=e?.readFileSync??pH,r=e?.surface??t.AGENT_SURFACE,o=cH(t.AFK_BROWSER_HEADLESS,r),s=vE(t.AFK_BROWSER_ALLOWED_DOMAINS),i=vE(t.AFK_BROWSER_BLOCKED_DOMAINS),a=dH(t.AFK_BROWSER_DOM_SNAPSHOTS),l=uH(t.AFK_BROWSER_BACKEND),c={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null},u=t.AFK_BROWSER_CONFIG,d=u!==void 0&&u.trim()!==""?u.trim():sH(Qt(),"browser.json"),p=n(d);if(p===void 0)return c;let m;try{m=JSON.parse(p)}catch(h){throw new Error(`Failed to parse browser config at ${d}: ${String(h)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${d} must be a JSON object`);let g=mH(c,m);return g.configPath=d,g}function Ug(e,t){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${e}`}}for(let r of t.blockedDomains)if(SE(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>SE(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var aH,lH,jg=_(()=>{"use strict";q();G();aH=new Set(["daemon","subagent","telegram","afk"]),lH=new Set(["repl","interactive","cli"])});import fH from"node:fs";import gH from"node:path";import{chromium as hH}from"playwright";function yH(){try{return"5.3.2"}catch{}try{let e=gH.resolve(import.meta.dirname,"../../../package.json"),t=fH.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var bH,hu,EE=_(()=>{"use strict";bH=yH(),hu=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(t){this.config=t}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=hH.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let 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(t,s),o}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",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(t){return this.sessions.get(t)?.page}async renderHtml(t,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(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await i.content(),c=i.url(),u=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${bH}`}}}});import{createHash as wH}from"crypto";function Hg(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of SH)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function TE(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&vH.test(e.label))}function xE(e){return wH("sha256").update(e,"utf8").digest("hex").slice(0,8)}function RE(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var SH,vH,Ba=_(()=>{"use strict";SH=[{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}];vH=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as kH}from"node:crypto";function EH(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function TH(e,t,n){return`el_${kH("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function xH(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function CE(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function _E(e,t){let n=e.role??"",r=e.name??"";AE.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let s of e.children??[])_E(s,t)}async function RH(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let u=window.getComputedStyle(i);if(u.display==="none"||u.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},IE).catch(()=>[])}async function CH(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let h=s.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let u="value"in s?s.value:void 0,d=u!==void 0?String(u):void 0,p=s.disabled??!1,m=i==="input"?s.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),m!==void 0&&(g.checked=m),o.push(g)}return o},IE).catch(()=>[])}function AH(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function yu(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],s=AH(e),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=RH(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,m,g,h]=await Promise.all([i,a,l,c,u]),b,y=!1;d!==null?(b=[],_E(d,b)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,b=(await CH(e)).filter(F=>AE.has(F.role??"")));let S=new Map;for(let P of p){let F=CE(P.name),D=S.get(F);(!D||D.bbox.w===0&&P.bbox.w>0)&&S.set(F,P)}let w=b.map(P=>({ax:P,dom:S.get(CE(P.name??""))})),T=r?w:w.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);T.sort((P,F)=>{let D=P.dom?.bbox.y??0,N=F.dom?.bbox.y??0;if(D!==N)return D-N;let B=P.dom?.bbox.x??0,H=F.dom?.bbox.x??0;return B-H}),T.length>200&&o.push("page has 200+ interactive elements; consider scoping");let C=T.slice(0,n).map((P,F)=>{let D=P.ax.role??"generic",N=P.ax.name??"",B=TH(D,N,F),H=P.dom?.bbox??{x:0,y:0,w:0,h:0},L=P.dom?.type??null,I=null;P.ax.value!==void 0&&P.ax.value!==null&&(I=String(P.ax.value)),P.ax.checked!==void 0&&(I=String(P.ax.checked)),TE({role:D,kind:L})&&(I="[redacted]");let U={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(U.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(U.selected=P.ax.selected),P.ax.expanded!==void 0&&(U.expanded=P.ax.expanded);let M;P.dom?.testId?M=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(M=`#${P.dom.id}`);let j={id:B,role:D,label:EH(N),kind:L,value:I,state:U,bbox:H};return M!==void 0&&(j.selector=M),j}),R="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?R="loading":P==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let k=xH(m),$=`obs_${t.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:$,url:g,title:h,textSummary:k,interactive:C,status:{httpStatus:t.httpStatus??null,loadingState:R,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:A}}var AE,IE,PE=_(()=>{"use strict";Ba();AE=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);IE="a[href], button, input, select, textarea, [role], [tabindex], label"});async function ME(e,t){try{let n=await e.nth(t).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.height)}}),r=`${n.role}:${n.label}:${t}`,o=0;for(let 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 Wg(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,s)=>ME(e,s)))).filter(o=>o!==null)}async function _H(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(i)||(t.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Kg(e,t,n){switch(t.kind){case"element_id":return IH(e,t,n);case"selector":return PH(e,t);case"semantic":return MH(e,t)}}async function IH(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:t};if(s===1)return{outcome:"resolved",locator:o};let i=await Wg(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function PH(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await Wg(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function MH(e,t){return t.role!==void 0?OH(e,t.text,t.role):$H(e,t.text,t)}async function OH(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Wg(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:s}}async function $H(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),s=e.getByLabel(t,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let u=[];i>0&&u.push({loc:r,count:i}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:s,count:l});let d=await _H(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=d.slice(0,5),m=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let y=await ME(b.locator,b.index);if(y!==null){let S=`${y.role}:${y.label}:${h}`,w=0;for(let T=0;T<S.length;T++)w=w*31+S.charCodeAt(T)>>>0;m.push({...y,id:`el_${w.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:m}}var OE=_(()=>{"use strict"});import{randomBytes as DH}from"crypto";import{mkdir as LH,stat as FH,writeFile as NH}from"fs/promises";import{join as Gg}from"path";import{gzip as BH}from"zlib";import{promisify as UH}from"util";function jH(e){return Gg(Ts(e),"browser")}function HH(e){return Gg(jH(e),"screenshots")}function WH(){return new Date().toISOString().replace(/[:.]/g,"-")}function KH(){return DH(3).toString("hex")}async function qg(e,t,n){if(t.length>$E)throw new Error(`writeScreenshotSidecar: buffer exceeds ${$E} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=HH(e);await LH(r,{recursive:!0});let o=`${WH()}-${KH()}-${n}.png`,s=Gg(r,o);await NH(s,t);let{size:i}=await FH(s);return{path:s,bytes:i}}var uue,$E,DE=_(()=>{"use strict";G();Ba();uue=UH(BH);$E=5*1024*1024});var FE={};ac(FE,{PlaywrightProvider:()=>zg});function LE(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var zg,NE=_(()=>{"use strict";EE();PE();OE();jg();Ba();DE();zg=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new hu(t)}async open(t){let n=Ug(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(c){a=c}(t.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await yu(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,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;t.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await yu(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=t.timeoutMs??3e4,a=await Kg(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${LE(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=async()=>{switch(t.action){case"click":await l.click({timeout:i});break;case"fill":{let h=Hg(t.value??"");await l.fill(t.value??"");break}case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=r.url();if(d!==s){let h=Ug(d,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:d,reason:h.reason}}let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let m=await yu(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,m.interactive,m.url,m.title,g),c!==null)throw c;return m}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(t.target!==void 0){let u=await Kg(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${LE(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await u.locator.screenshot()}else s=await r.screenshot({fullPage:t.fullPage??!1});let{path:i,bytes:a}=await qg(n,s,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(t){let n=this.sessions.get(t);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(t,r),r}updateSessionFromObservation(t,n,r,o,s){t.knownElements=new Map(n.map(i=>[i.id,i])),t.currentUrl=r,t.currentTitle=o,t.lastAction=s,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:s}=await qg(n,o,r);return s}catch{return null}}}});var Po={};ac(Po,{__resetBrowserRegistryForTests:()=>VH,browserProviderActive:()=>zH,closeBrowserProvider:()=>Jg,getBrowserProvider:()=>qH,peekBrowserProvider:()=>JH});function BE(){Promise.resolve(Jg()).then(()=>{process.exit(130)})}function UE(){Promise.resolve(Jg()).then(()=>{process.exit(143)})}function jE(){xn=null}function GH(){bu||(process.on("SIGINT",BE),process.on("SIGTERM",UE),process.on("exit",jE),bu=!0)}function HE(){bu&&(process.removeListener("SIGINT",BE),process.removeListener("SIGTERM",UE),process.removeListener("exit",jE),bu=!1)}async function qH(e){return xn!==null?xn:(Io!==null||(Io=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(NE(),FE)),n=kE(e),r=new t(n);return GH(),xn=r,Io=null,r})()),Io)}async function Jg(){if(xn===null)return;let e=xn;xn=null,Io=null,HE(),await e.shutdown()}function zH(){return xn!==null}function JH(){return xn}function VH(){xn=null,Io=null,HE()}var xn,Io,bu,Mo=_(()=>{"use strict";jg();xn=null,Io=null,bu=!1});function WE(e,t){try{return bE(e,t)}catch(n){return z("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function eW(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Mo(),Po));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function KE(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??eW,o=null,s=e,i=null,a=null;try{let c=await n(e,{headers:QH,redirect:"follow",signal:t.signal});i=c.status,s=c.url||e;let u=c.headers.get("content-type")??"";if(c.ok){if(ZH.test(u))throw new Error(`web_scrape markdown mode received binary content (${u.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let d=await c.text();if(XH.test(u)&&!YH.test(u))return{title:"",markdown:d.trim(),finalUrl:s,usedRender:!1};o=WE(d,s)}}catch(c){if(t.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<yE)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let c=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal}),u=WE(c.html,c.finalUrl);if(o===null||u.textLength>=o.textLength)return{title:u.title,markdown:u.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(t.signal.aborted)throw c;if(o===null){let u=c instanceof Error?c.message:String(c),d=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${e}: fetch failed (${d}) and render failed (${u}).`);throw p.cause=c,p}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${i??"error"}).`)}var YH,XH,ZH,QH,GE=_(()=>{"use strict";wE();_e();YH=/(text\/html|application\/xhtml\+xml)/i,XH=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,ZH=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,QH={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function rW(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await t(tW,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),nW),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let u=await s.text(),d=Co(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}catch{}let c=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${c}${l}`)}let i;try{i=await s.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(i.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function qE(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?rW({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function zE(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
1082
1082
|
|
|
1083
1083
|
(no results)`;let n=[`# Search results for "${e}"`,""];return t.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
|
|
1084
1084
|
`).trimEnd()}var tW,nW,JE=_(()=>{"use strict";Ao();tW="https://api.exa.ai/search",nW=10});function dW(e){if(!e||typeof e!="object")return{error:"Invalid input: expected an object"};let t=e,n=t.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof t.query!="string"||t.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=t.query}else{if(typeof t.url!="string"||t.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let l;try{l=new URL(t.url)}catch{return{error:`Invalid input: "${t.url}" is not a valid absolute URL`}}if(l.protocol!=="http:"&&l.protocol!=="https:")return{error:`Invalid input: protocol "${l.protocol}" not supported (http/https only)`};o=l.toString()}let i=oW;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(t.timeout_ms,sW)}let a=iW;if(t.max_bytes!==void 0){if(typeof t.max_bytes!="number"||!Number.isFinite(t.max_bytes)||t.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(t.max_bytes,aW)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Vg(e,t){let n=Buffer.from(e,"utf8");return n.byteLength<=t?e:n.subarray(0,t).toString("utf8")+lW}function pW(e){let t=[],n=e;for(let o=0;o<4&&n instanceof Error;o++)t.push(n.message),n=n.cause;let r=t.join(" | ");return uW.some(o=>r.includes(o))}function mW(e={}){let t=e.fetchFn??globalThis.fetch,n=e.env??process.env;return async(r,o)=>{if(typeof t!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=dW(r);if("error"in s)return{content:s.error,isError:!0};if(o.aborted){let u=o.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let i=new AbortController,a=()=>{i.abort(o.reason)},l,c=()=>{let u=i.signal.reason;return u instanceof Error?u.message:String(u??"aborted")};try{if(o.addEventListener("abort",a,{once:!0}),l=setTimeout(()=>{i.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs),s.mode==="raw"){let d;try{d=await t(s.url,{method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:i.signal})}catch(m){return i.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape network error: ${m instanceof Error?m.message:String(m)}`,isError:!0}}if(!d.ok)return{content:`web_scrape HTTP ${d.status} ${d.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let p;try{p=await d.text()}catch(m){return{content:`web_scrape read error: ${m instanceof Error?m.message:String(m)}`,isError:!0}}return{content:Vg(p,s.maxBytes)}}if(s.mode==="markdown")try{let d=await KE(s.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:s.timeoutMs,signal:i.signal});return d.markdown.trim().length===0?{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0}:{content:Vg(d.markdown,s.maxBytes)}}catch(d){if(i.signal.aborted)return{content:`web_scrape aborted: ${c()}`,isError:!0};let p=d instanceof Error?d.message:String(d),m=pW(d)?" (the render fallback needs the optional Playwright browser \u2014 run `pnpm exec playwright install chromium`)":"";return{content:`web_scrape markdown error: ${p}${m}`,isError:!0}}let u=qE({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in u)return{content:u.error,isError:!0};try{let d=await u.search(s.query,{limit:cW,timeoutMs:s.timeoutMs,signal:i.signal});return{content:Vg(zE(s.query,d),s.maxBytes)}}catch(d){return i.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape search error (${u.name}): ${d instanceof Error?d.message:String(d)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),o.removeEventListener("abort",a)}}}var oW,sW,iW,aW,lW,cW,uW,VE,YE=_(()=>{"use strict";GE();JE();oW=3e4,sW=12e4,iW=1e6,aW=1e7,lW=`
|
|
@@ -1095,7 +1095,7 @@ ${o}`;return s.includes("already checked out")||s.includes("is already used by w
|
|
|
1095
1095
|
`),Tu(e,o,384)}function lT(e,t){if(!ja(e))return!1;let n=Eu(e,"utf-8"),r=new RegExp(`^${ku(t)}=.*$
|
|
1096
1096
|
?`,"m");if(!r.test(n))return!1;let o=n.replace(r,"");return Tu(e,o,384),!0}function cT(e,t){if(!ja(e))return;let r=Eu(e,"utf-8").match(new RegExp(`^${ku(t)}=(.*)$`,"m"));return r?r[1]:void 0}function uT(e){let t={};if(!ja(e))return t;let n=Eu(e,"utf-8");for(let r of n.split(`
|
|
1097
1097
|
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s<=0)continue;let i=o.slice(0,s).trim(),a=o.slice(s+1);t[i]=a}return t}var xu=_(()=>{"use strict"});function Xs(e){let t=lc(e);return t?jW.has(e)?"non-config":t.secret?"secret":HW.has(e)||e.endsWith("_BASE_URL")?"protected":"settable":"unknown"}function dT(e,t){if(t.includes(`
|
|
1098
|
-
`))return{ok:!1,error:`value for ${e.name} must not contain newlines`};switch(e.type){case"number":{let n=Number(t);return Number.isFinite(n)?{ok:!0,value:t.trim()}:{ok:!1,error:`${e.name} expects a number, got ${JSON.stringify(t)}`}}case"boolean":{let n=t.trim().toLowerCase();return["true","false","1","0","yes","no","on","off"].includes(n)?{ok:!0,value:n}:{ok:!1,error:`${e.name} expects a boolean (true/false/1/0/yes/no/on/off), got ${JSON.stringify(t)}`}}case"json":{try{JSON.parse(t)}catch{return{ok:!1,error:`${e.name} expects valid JSON`}}return{ok:!0,value:t}}default:return{ok:!0,value:t}}}function mT(e){return pT.get(e)}function rh(e){let t=pT.get(e);return t?t.tier:"unknown"}function fT(e,t){switch(e.type){case"boolean":{if(typeof t=="boolean")return{ok:!0,value:t};if(typeof t=="string"){let n=t.trim().toLowerCase();if(["true","1","yes","on"].includes(n))return{ok:!0,value:!0};if(["false","0","no","off"].includes(n))return{ok:!0,value:!1}}return{ok:!1,error:`${e.path} expects a boolean`}}case"number":{let n=typeof t=="number"?t:typeof t=="string"?Number(t):NaN;return Number.isFinite(n)?e.clamp?e.clamp.integer&&!Number.isInteger(n)?{ok:!1,error:`${e.path} expects an integer`}:{ok:!0,value:Math.min(e.clamp.max,Math.max(e.clamp.min,n))}:{ok:!0,value:n}:{ok:!1,error:`${e.path} expects a number`}}case"enum":return typeof t=="string"&&e.enumValues?.includes(t)?{ok:!0,value:t}:{ok:!1,error:`${e.path} expects one of: ${e.enumValues?.join(", ")}`};case"number-array":{let n;if(Array.isArray(t))n=t;else if(typeof t=="string")n=t.split(",").map(o=>o.trim()).filter(o=>o.length>0).map(o=>Number(o));else return{ok:!1,error:`${e.path} expects an array of numbers`};let r=[];for(let o of n){let s=typeof o=="number"?o:Number(o);if(!Number.isFinite(s))return{ok:!1,error:`${e.path} contains a non-number`};r.push(s)}return{ok:!0,value:r}}default:return typeof t!="string"?{ok:!1,error:`${e.path} expects a string`}:t.trim().length===0?{ok:!1,error:`${e.path} must not be empty`}:{ok:!0,value:t}}}function gT(e,t){let n=e;for(let r of t.split(".")){if(n===null||typeof n!="object")return;n=n[r]}return n}function hT(e,t,n){let r=t.split("."),o=e;for(let s=0;s<r.length-1;s++){let i=r[s],a=o[i];(a===null||typeof a!="object"||Array.isArray(a))&&(o[i]={}),o=o[i]}o[r[r.length-1]]=n}function yT(e,t){let n=t.split("."),r=[e],o=e;for(let i=0;i<n.length-1;i++){let a=n[i],l=o[a];if(l===null||typeof l!="object"||Array.isArray(l))return!1;o=l,r.push(o)}let s=n[n.length-1];if(!(s in o))return!1;delete o[s];for(let i=r.length-1;i>=1;i--){let a=r[i];if(Object.keys(a).length===0){let l=n[i-1];delete r[i-1][l]}else break}return!0}var jW,HW,WW,pT,oh=_(()=>{"use strict";q();jW=new Set(["HOME","PATH","SHELL","PAGER","NODE_ENV","CI","VITEST","DEBUG","FORCE_COLOR","NO_COLOR","AGENT_SURFACE","AFK_SESSION_ID","NO_UPDATE_NOTIFIER","SCRIPT","ASCIINEMA_REC"]),HW=new Set(["AFK_MODEL_SMALL_BASE_URL","AFK_MODEL_MEDIUM_BASE_URL","AFK_MODEL_LARGE_BASE_URL","AFK_LOCAL_BASE_URL","AFK_OPENAI_BASE_URL","AFK_SYSTEM_PROMPT","AFK_DAEMON_TASK","AFK_DAEMON_TASK_ID","AFK_DAEMON_CWD","AFK_DAEMON_HOST","AFK_BROWSER_ALLOWED_DOMAINS","AFK_BROWSER_BLOCKED_DOMAINS","AFK_BROWSER_CONFIG","AFK_ALLOW_PROJECT_MCP","AFK_INTERNAL","AFK_WORKTREE_BASE","AFK_WORKTREE_BRANCH_PREFIX","AFK_TELEGRAM_ALLOWED_CHAT_IDS","AFK_TELEGRAM_NOTIFY_MODE","AFK_TELEGRAM_PRIMARY_CHAT_ID","AFK_HOME","AFK_STATE_DIR","AFK_FRAMEWORK_DIR","TELEGRAM_DATA_DIR","AFK_TELEGRAM_CWD"]);WW=[{path:"model",tier:"agent",type:"string",description:"Default model id / alias."},{path:"models.local",tier:"agent",type:"string",description:"Local-tier model id (OpenAI-compatible shim: Ollama, LM Studio, vLLM, MLX)."},{path:"models.small",tier:"agent",type:"string",description:"Small-tier model id."},{path:"models.medium",tier:"agent",type:"string",description:"Medium-tier model id."},{path:"models.large",tier:"agent",type:"string",description:"Large-tier model id."},{path:"maxTokens",tier:"agent",type:"number",clamp:{min:1,max:1e6,integer:!0},description:"Max tokens per turn."},{path:"temperature",tier:"agent",type:"number",clamp:{min:0,max:2},description:"Sampling temperature."},{path:"autoRouting.interactive",tier:"agent",type:"boolean",description:"Auto-route model in the REPL."},{path:"autoRouting.chat",tier:"agent",type:"boolean",description:"Auto-route model for chat."},{path:"autoRouting.telegram",tier:"agent",type:"boolean",description:"Auto-route model for Telegram."},{path:"autoRouting.daemon",tier:"agent",type:"boolean",description:"Auto-route model for the daemon."},{path:"telegram.notify.mode",tier:"human",type:"enum",enumValues:["primary","broadcast","custom"],description:"Telegram notify routing mode (human-tier: notification-redirect vector)."},{path:"telegram.notify.primaryChatId",tier:"human",type:"number",clamp:{min:-1e15,max:1e15,integer:!0},description:"Primary Telegram chat id (human-tier: notification-redirect vector)."},{path:"telegram.notify.targets",tier:"human",type:"number-array",description:"Custom Telegram target chat ids (human-tier: notification-redirect vector)."},{path:"telegram.verifyDone",tier:"human",type:"boolean",description:`Opt-in AFK "Done" verification gate (human-tier: a self-honesty check on the agent's own completion reporting \u2014 the agent must not be able to disable it on its own config, same rationale as enableShellHooks/permissionMode).`},{path:"interactive.worktreeAutoname",tier:"agent",type:"boolean",description:"Auto-name worktrees."},{path:"interactive.suggestGhost",tier:"agent",type:"boolean",description:"Ghost-text suggestions in the REPL."},{path:"updatePolicy",tier:"human",type:"enum",enumValues:["notify","auto","off"],description:"Self-update policy (human-tier: auto self-update is scope-widening)."},{path:"autoResumeOnUsageLimit",tier:"agent",type:"boolean",description:"Auto-resume after a usage-limit pause."},{path:"bgSummaries",tier:"agent",type:"boolean",description:"Background summarisation."},{path:"maxSummaryCallsPerSession",tier:"agent",type:"number",clamp:{min:1,max:500,integer:!0},description:"Cap on summary calls per session."},{path:"systemPrompt",tier:"human",type:"string",description:"Operator system-prompt overlay."},{path:"permissionMode",tier:"human",type:"enum",enumValues:["default","plan","autonomous","bypassPermissions"],description:"Session permission mode for afk chat/interactive (human-tier: privilege-escalation vector). Unset \u2192 bypassPermissions (new-install default); set `default` to re-enable path containment + the approval prompt."},{path:"enableShellHooks",tier:"human",type:"boolean",description:"Enable shell hooks (trust gate)."},{path:"interactive.worktreeBranchPrefix",tier:"human",type:"string",description:"Worktree branch prefix (git-flag sensitive)."},{path:"interactive.worktreeBase",tier:"human",type:"string",description:"Worktree base ref (git-flag sensitive)."},{path:"daemon.task",tier:"human",type:"string",description:"Daemon task prompt."},{path:"daemon.taskId",tier:"human",type:"string",description:"Daemon task id."}],pT=new Map(WW.map(e=>[e.path,e]))});import{existsSync as bT,readFileSync as KW,copyFileSync as GW,chmodSync as qW}from"fs";function ch(e){return e===void 0||e.length===0?"<unset>":e.length<=4?"set (****)":`set (****${e.slice(-4)})`}function Au(e){return e?.filePath??
|
|
1098
|
+
`))return{ok:!1,error:`value for ${e.name} must not contain newlines`};switch(e.type){case"number":{let n=Number(t);return Number.isFinite(n)?{ok:!0,value:t.trim()}:{ok:!1,error:`${e.name} expects a number, got ${JSON.stringify(t)}`}}case"boolean":{let n=t.trim().toLowerCase();return["true","false","1","0","yes","no","on","off"].includes(n)?{ok:!0,value:n}:{ok:!1,error:`${e.name} expects a boolean (true/false/1/0/yes/no/on/off), got ${JSON.stringify(t)}`}}case"json":{try{JSON.parse(t)}catch{return{ok:!1,error:`${e.name} expects valid JSON`}}return{ok:!0,value:t}}default:return{ok:!0,value:t}}}function mT(e){return pT.get(e)}function rh(e){let t=pT.get(e);return t?t.tier:"unknown"}function fT(e,t){switch(e.type){case"boolean":{if(typeof t=="boolean")return{ok:!0,value:t};if(typeof t=="string"){let n=t.trim().toLowerCase();if(["true","1","yes","on"].includes(n))return{ok:!0,value:!0};if(["false","0","no","off"].includes(n))return{ok:!0,value:!1}}return{ok:!1,error:`${e.path} expects a boolean`}}case"number":{let n=typeof t=="number"?t:typeof t=="string"?Number(t):NaN;return Number.isFinite(n)?e.clamp?e.clamp.integer&&!Number.isInteger(n)?{ok:!1,error:`${e.path} expects an integer`}:{ok:!0,value:Math.min(e.clamp.max,Math.max(e.clamp.min,n))}:{ok:!0,value:n}:{ok:!1,error:`${e.path} expects a number`}}case"enum":return typeof t=="string"&&e.enumValues?.includes(t)?{ok:!0,value:t}:{ok:!1,error:`${e.path} expects one of: ${e.enumValues?.join(", ")}`};case"number-array":{let n;if(Array.isArray(t))n=t;else if(typeof t=="string")n=t.split(",").map(o=>o.trim()).filter(o=>o.length>0).map(o=>Number(o));else return{ok:!1,error:`${e.path} expects an array of numbers`};let r=[];for(let o of n){let s=typeof o=="number"?o:Number(o);if(!Number.isFinite(s))return{ok:!1,error:`${e.path} contains a non-number`};r.push(s)}return{ok:!0,value:r}}default:return typeof t!="string"?{ok:!1,error:`${e.path} expects a string`}:t.trim().length===0?{ok:!1,error:`${e.path} must not be empty`}:{ok:!0,value:t}}}function gT(e,t){let n=e;for(let r of t.split(".")){if(n===null||typeof n!="object")return;n=n[r]}return n}function hT(e,t,n){let r=t.split("."),o=e;for(let s=0;s<r.length-1;s++){let i=r[s],a=o[i];(a===null||typeof a!="object"||Array.isArray(a))&&(o[i]={}),o=o[i]}o[r[r.length-1]]=n}function yT(e,t){let n=t.split("."),r=[e],o=e;for(let i=0;i<n.length-1;i++){let a=n[i],l=o[a];if(l===null||typeof l!="object"||Array.isArray(l))return!1;o=l,r.push(o)}let s=n[n.length-1];if(!(s in o))return!1;delete o[s];for(let i=r.length-1;i>=1;i--){let a=r[i];if(Object.keys(a).length===0){let l=n[i-1];delete r[i-1][l]}else break}return!0}var jW,HW,WW,pT,oh=_(()=>{"use strict";q();jW=new Set(["HOME","PATH","SHELL","PAGER","NODE_ENV","CI","VITEST","DEBUG","FORCE_COLOR","NO_COLOR","AGENT_SURFACE","AFK_SESSION_ID","NO_UPDATE_NOTIFIER","SCRIPT","ASCIINEMA_REC"]),HW=new Set(["AFK_MODEL_SMALL_BASE_URL","AFK_MODEL_MEDIUM_BASE_URL","AFK_MODEL_LARGE_BASE_URL","AFK_LOCAL_BASE_URL","AFK_OPENAI_BASE_URL","AFK_SYSTEM_PROMPT","AFK_DAEMON_TASK","AFK_DAEMON_TASK_ID","AFK_DAEMON_CWD","AFK_DAEMON_HOST","AFK_BROWSER_ALLOWED_DOMAINS","AFK_BROWSER_BLOCKED_DOMAINS","AFK_BROWSER_CONFIG","AFK_ALLOW_PROJECT_MCP","AFK_INTERNAL","AFK_WORKTREE_BASE","AFK_WORKTREE_BRANCH_PREFIX","AFK_TELEGRAM_ALLOWED_CHAT_IDS","AFK_TELEGRAM_NOTIFY_MODE","AFK_TELEGRAM_PRIMARY_CHAT_ID","AFK_HOME","AFK_STATE_DIR","AFK_FRAMEWORK_DIR","TELEGRAM_DATA_DIR","AFK_TELEGRAM_CWD"]);WW=[{path:"model",tier:"agent",type:"string",description:"Default model id / alias."},{path:"models.local",tier:"agent",type:"string",description:"Local-tier model id (OpenAI-compatible shim: Ollama, LM Studio, vLLM, MLX)."},{path:"models.small",tier:"agent",type:"string",description:"Small-tier model id."},{path:"models.medium",tier:"agent",type:"string",description:"Medium-tier model id."},{path:"models.large",tier:"agent",type:"string",description:"Large-tier model id."},{path:"maxTokens",tier:"agent",type:"number",clamp:{min:1,max:1e6,integer:!0},description:"Max tokens per turn."},{path:"temperature",tier:"agent",type:"number",clamp:{min:0,max:2},description:"Sampling temperature."},{path:"autoRouting.interactive",tier:"agent",type:"boolean",description:"Auto-route model in the REPL."},{path:"autoRouting.chat",tier:"agent",type:"boolean",description:"Auto-route model for chat."},{path:"autoRouting.telegram",tier:"agent",type:"boolean",description:"Auto-route model for Telegram."},{path:"autoRouting.daemon",tier:"agent",type:"boolean",description:"Auto-route model for the daemon."},{path:"telegram.notify.mode",tier:"human",type:"enum",enumValues:["primary","broadcast","custom"],description:"Telegram notify routing mode (human-tier: notification-redirect vector)."},{path:"telegram.notify.primaryChatId",tier:"human",type:"number",clamp:{min:-1e15,max:1e15,integer:!0},description:"Primary Telegram chat id (human-tier: notification-redirect vector)."},{path:"telegram.notify.targets",tier:"human",type:"number-array",description:"Custom Telegram target chat ids (human-tier: notification-redirect vector)."},{path:"telegram.verifyDone",tier:"human",type:"boolean",description:`Opt-in AFK "Done" verification gate (human-tier: a self-honesty check on the agent's own completion reporting \u2014 the agent must not be able to disable it on its own config, same rationale as enableShellHooks/permissionMode).`},{path:"interactive.worktreeAutoname",tier:"agent",type:"boolean",description:"Auto-name worktrees."},{path:"interactive.suggestGhost",tier:"agent",type:"boolean",description:"Ghost-text suggestions in the REPL."},{path:"updatePolicy",tier:"human",type:"enum",enumValues:["notify","auto","off"],description:"Self-update policy (human-tier: auto self-update is scope-widening)."},{path:"autoResumeOnUsageLimit",tier:"agent",type:"boolean",description:"Auto-resume after a usage-limit pause."},{path:"bgSummaries",tier:"agent",type:"boolean",description:"Background summarisation."},{path:"maxSummaryCallsPerSession",tier:"agent",type:"number",clamp:{min:1,max:500,integer:!0},description:"Cap on summary calls per session."},{path:"systemPrompt",tier:"human",type:"string",description:"Operator system-prompt overlay."},{path:"permissionMode",tier:"human",type:"enum",enumValues:["default","plan","autonomous","bypassPermissions"],description:"Session permission mode for afk chat/interactive (human-tier: privilege-escalation vector). Unset \u2192 bypassPermissions (new-install default); set `default` to re-enable path containment + the approval prompt."},{path:"enableShellHooks",tier:"human",type:"boolean",description:"Enable shell hooks (trust gate)."},{path:"interactive.worktreeBranchPrefix",tier:"human",type:"string",description:"Worktree branch prefix (git-flag sensitive)."},{path:"interactive.worktreeBase",tier:"human",type:"string",description:"Worktree base ref (git-flag sensitive)."},{path:"daemon.task",tier:"human",type:"string",description:"Daemon task prompt."},{path:"daemon.taskId",tier:"human",type:"string",description:"Daemon task id."}],pT=new Map(WW.map(e=>[e.path,e]))});import{existsSync as bT,readFileSync as KW,copyFileSync as GW,chmodSync as qW}from"fs";function ch(e){return e===void 0||e.length===0?"<unset>":e.length<=4?"set (****)":`set (****${e.slice(-4)})`}function Au(e){return e?.filePath??ht()}function wT(e,t,n){let r=Xs(e);if(r==="unknown")throw new Ha(e);if(r==="non-config")throw new sh(e);if(r==="secret"&&!t)throw new ih(e);if(r==="protected"&&!n)throw new ah(e);return r}function _u(e,t,n){let r=wT(e,n?.allowSecret,n?.allowProtected),o=lc(e),s=dT(o,t);if(!s.ok)throw new Ru(s.error);let i=Au(n);return sn(i,e,s.value),{key:e,class:r,persistedTo:i,display:r==="secret"?ch(s.value):s.value}}function Iu(e,t){let n=wT(e,t?.allowSecret,t?.allowProtected),r=Au(t),o=lT(r,e);return{key:e,class:n,removed:o,persistedTo:r}}function Pu(e,t){let n=Xs(e);if(n==="unknown")throw new Ha(e);let r=Au(t),o=cT(r,e),s=ff(e),i=n==="secret"?o!==void 0?ch(o):void 0:o;return{key:e,class:n,persisted:i,activeInProcess:s}}function Mu(e){let t=Au(e),n=uT(t),r=[];for(let o of fa){let s=o.name,i=Xs(s),a=n[s],l=ff(s);if(!e?.all&&a===void 0&&!l)continue;let c=i==="secret"?a!==void 0?ch(a):void 0:a;r.push({key:s,class:i,persisted:c,activeInProcess:l})}return r}function Ou(e){return e?.filePath??Bt()}function $u(e){if(!bT(e))return{};let t;try{t=JSON.parse(KW(e,"utf-8"))}catch{throw new Cu(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Cu(e);return t}function ST(e,t){if(bT(e))try{GW(e,`${e}.bak`),qW(`${e}.bak`,384)}catch{}Tu(e,JSON.stringify(t,null,2)+`
|
|
1099
1099
|
`,384)}function vT(e,t){let n=rh(e);if(n==="unknown")throw new Ha(e);if(n==="human"&&!t)throw new lh(e);return n}function Du(e,t,n){let r=vT(e,n?.allowHumanOnly),o=mT(e),s=fT(o,t);if(!s.ok)throw new Ru(s.error);let i=Ou(n),a=$u(i);return hT(a,e,s.value),ST(i,a),{path:e,class:r,value:s.value,persistedTo:i}}function Lu(e,t){let n=vT(e,t?.allowHumanOnly),r=Ou(t),o=$u(r),s=yT(o,e);return s&&ST(r,o),{path:e,class:n,removed:s,persistedTo:r}}function Fu(e,t){let n=rh(e),r=Ou(t),o=$u(r);return{path:e,class:n,value:gT(o,e)}}function Nu(e){return $u(Ou(e))}var Lr,Ha,sh,ih,ah,lh,Ru,Cu,uh=_(()=>{"use strict";G();q();xu();oh();Lr="effective on the next session/daemon restart; the current session is unchanged",Ha=class extends Error{constructor(t){super(`unknown config key: ${t}`),this.name="UnknownKeyError"}},sh=class extends Error{constructor(t){super(`${t} is a process/inherited env var and is not afk-configurable`),this.name="NonConfigKeyError"}},ih=class extends Error{constructor(t){super(`${t} holds a credential; the agent cannot set it. A human must run \`afk config env set ${t}\` (the value is entered masked and never enters the model context).`),this.name="SecretWriteRefused"}},ah=class extends Error{constructor(t){super(`${t} controls identity, safety, capability, autonomous runs, request routing, or where AFK's own state lives; the agent cannot set it. A human must run \`afk config env set ${t}\`.`),this.name="ProtectedEnvKeyRefused"}},lh=class extends Error{constructor(t){super(`${t} is human-gated (prompt/hooks/identity); the agent cannot set it. A human must run \`afk config set ${t}\`.`),this.name="HumanOnlyKeyRefused"}},Ru=class extends Error{constructor(t){super(t),this.name="ConfigValidationError"}},Cu=class extends Error{constructor(t){super(`refusing to write: existing ${t} is not valid JSON (fix or remove it by hand first)`),this.name="MalformedConfigError"}}});function kT(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ET(e){return e==="env"||e==="config"?e:void 0}function ar(e){return{content:e,isError:!0}}var TT,xT,RT=_(()=>{"use strict";uh();TT=async e=>{let t=kT(e);if(!t)return ar("config_get: expected an object input");let n=ET(t.target);if(!n)return ar("config_get: `target` must be 'env' or 'config'");let r=typeof t.key=="string"?t.key:void 0,o=t.all===!0;try{if(n==="env"){if(r){let s=Pu(r);return{content:JSON.stringify(s,null,2)}}return{content:JSON.stringify(Mu({all:o}),null,2)}}if(r){let s=Fu(r);return{content:JSON.stringify(s,null,2)}}return{content:JSON.stringify(Nu(),null,2)}}catch(s){return ar(`config_get: ${s.message}`)}},xT=async e=>{let t=kT(e);if(!t)return ar("config_set: expected an object input");let n=ET(t.target);if(!n)return ar("config_set: `target` must be 'env' or 'config'");let r=typeof t.key=="string"?t.key:void 0;if(!r)return ar("config_set: `key` is required");let o=t.action==="unset"?"unset":"set",s=t.value;try{if(o==="unset"){if(n==="env"){let l=Iu(r);return{content:l.removed?`Removed ${l.key} from afk.env (${l.persistedTo}). ${Lr}.`:`${l.key} was not set in afk.env; nothing to remove.`}}let a=Lu(r);return{content:a.removed?`Removed ${a.path} from afk.config.json (${a.persistedTo}). ${Lr}.`:`${a.path} was not set in afk.config.json; nothing to remove.`}}if(s==null)return ar(`config_set: \`value\` is required to set ${r}`);if(n==="env"){if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")return ar("config_set: env values must be a string, number, or boolean");let a=_u(r,String(s));return{content:`Set ${a.key} = ${a.display} in afk.env (${a.persistedTo}). ${Lr}.`}}let i=Du(r,s);return{content:`Set ${i.path} = ${JSON.stringify(i.value)} in afk.config.json (${i.persistedTo}). ${Lr}.`}}catch(i){return ar(`config_set: ${i.message}`)}}});var Zs,dh,lt,Fr=_(()=>{"use strict";Zs={action:"decline"},dh=class{handler=null;queue=Promise.resolve();queueDepth=0;install(t){this.handler=t}uninstall(){this.handler=null}pendingCount(){return this.queueDepth}route(t,n){if(n.signal.aborted)return Promise.resolve(Zs);this.queueDepth+=1;let r,o=new Promise(i=>{r=i}),s=this.handler;return this.queue=this.queue.then(async()=>{try{if(n.signal.aborted){r(Zs);return}if(!s){r(Zs);return}let i,a=new Promise(l=>{i=()=>l(Zs),n.signal.addEventListener("abort",i,{once:!0})});try{try{n.onActive?.()}catch{}let l=await Promise.race([s(t,n).catch(()=>Zs),a]);r(l)}finally{n.signal.removeEventListener("abort",i)}}finally{this.queueDepth-=1,r(Zs)}}).catch(()=>{}),o}},lt=new dh});var CT,AT=_(()=>{"use strict";Fr();CT=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let n=e,r=n.question;if(typeof r!="string"||r.trim()==="")return{content:"Invalid input: question must be a non-empty string",isError:!0};let o=new Set(["text","confirm","choice","multi_choice","number"]),s=n.type??"text";if(typeof s!="string"||!o.has(s))return{content:"Invalid input: type must be one of: text, confirm, choice, multi_choice, number",isError:!0};if(s==="choice"||s==="multi_choice"){let m=n.choices;if(!Array.isArray(m)||m.length===0)return{content:`Invalid input: choices array is required and must be non-empty for type "${s}"`,isError:!0};if(m.length>100)return{content:`Invalid input: choices array must not exceed 100 items, got ${m.length}`,isError:!0};for(let g of m)if(typeof g!="string")return{content:"Invalid input: all choices must be strings",isError:!0}}let i=n.min,a=n.max;if(i!==void 0&&(typeof i!="number"||!Number.isFinite(i)))return{content:"Invalid input: min must be a finite number",isError:!0};if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)))return{content:"Invalid input: max must be a finite number",isError:!0};if(i!==void 0&&a!==void 0&&i>a)return{content:`Invalid input: min (${i}) must be \u2264 max (${a})`,isError:!0};let l=n.min_length,c=n.max_length;if(l!==void 0&&typeof l!="number")return{content:"Invalid input: min_length must be a number",isError:!0};if(c!==void 0&&typeof c!="number")return{content:"Invalid input: max_length must be a number",isError:!0};if((l!==void 0||c!==void 0)&&s!=="text")return{content:`Invalid input: min_length/max_length are only valid for type "text", got "${s}"`,isError:!0};if(n.allow_custom!==void 0&&s!=="choice"&&s!=="multi_choice")return{content:`Invalid input: allow_custom is only valid for type "choice" or "multi_choice", got "${s}"`,isError:!0};let u={serverName:"agent",message:r.trim(),origin:"agent",type:s,...n.choices!==void 0&&{choices:n.choices},...n.context!==void 0&&typeof n.context=="string"&&{context:n.context},...n.default!==void 0&&{questionDefault:n.default},...l!==void 0&&{minLength:l},...c!==void 0&&{maxLength:c},...i!==void 0&&{min:i},...a!==void 0&&{max:a},...n.allow_skip!==void 0&&{allowSkip:!!n.allow_skip},...n.allow_custom!==void 0&&{allowCustom:!!n.allow_custom}},d=await lt.route(u,{signal:t}),p=d.action==="decline"||d.action==="cancel";return{content:JSON.stringify(d),...p&&{isError:!0,failureClass:"elicitation-declined"}}}});function Bu(e){if(e instanceof Error&&e.name==="TimeoutError")return"timeout";let t=e instanceof Error?e.message:String(e);return/Timeout\s+\d+\s*ms exceeded/i.test(t)?"timeout":void 0}function Rn(e){return zW.some(t=>e.includes(t))}function Cn(e){return e.includes("Executable doesn't exist")?"browser tools require the Playwright chromium binary. Install via: pnpm exec playwright install chromium.":"browser tools require the optional `playwright` peer dependency. Install via: pnpm add playwright (then pnpm exec playwright install chromium). Or pick a different tool."}var zW,Qs=_(()=>{"use strict";zW=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"]});function JW(e){if(!e||typeof e!="object")return{error:"browser_open: input must be an object"};let t=e,n=t.url;if(typeof n!="string"||n.length===0)return{error:'browser_open: "url" is required and must be a non-empty string'};let r;try{r=new URL(n)}catch{return{error:`browser_open: "${n}" is not a valid absolute URL`}}if(r.protocol!=="http:"&&r.protocol!=="https:")return{error:`browser_open: protocol "${r.protocol}" is not supported (http/https only)`};let o;if(t.wait_for!==void 0){if(!_T.includes(t.wait_for))return{error:`browser_open: "wait_for" must be one of ${_T.map(a=>`"${a}"`).join(", ")} (got ${JSON.stringify(t.wait_for)})`};o=t.wait_for}let s;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_open: "screenshot" must be a boolean'};s=t.screenshot}let i;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:'browser_open: "timeout_ms" must be a positive finite number'};i=t.timeout_ms}return{url:r.toString(),waitFor:o,screenshot:s,timeoutMs:i}}function VW(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_open aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0,failureClass:"abort"}}let o=JW(t);if("error"in o)return{content:o.error,isError:!0};let s=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i;try{if(e.getBrowserProvider)i=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(Mo(),Po));i=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Rn(c)?{content:Cn(c),isError:!0}:{content:`browser_open failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await i.open({sessionId:s,url:o.url,waitFor:o.waitFor,screenshot:o.screenshot,timeoutMs:o.timeoutMs}),c=Date.now()-a;if("outcome"in l&&l.outcome==="blocked_by_policy")return et(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:c}),{content:`browser_open blocked: ${l.reason}`,isError:!0,failureClass:"policy-refusal"};let u=l;return et(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:u.url,status:"ok",durationMs:c,...u.screenshotPath!==null?{screenshotPath:u.screenshotPath}:{}}),{content:JSON.stringify(u,null,2)}}catch(l){let c=Date.now()-a,u=l instanceof Error?l.message:String(l);et(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:u,recoverable:!1}});let d=Bu(l);return{content:`browser_open failed: ${u}`,isError:!0,...d?{failureClass:d}:{}}}}}var _T,IT,PT=_(()=>{"use strict";q();je();Qs();_T=["load","domcontentloaded","networkidle"];IT=VW()});function YW(e){if(e!=null&&typeof e!="object")return{error:"browser_observe: input must be an object or omitted"};if(!e)return{};let t=e,n;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_observe: "screenshot" must be a boolean'};n=t.screenshot}let r;if(t.include_hidden!==void 0){if(typeof t.include_hidden!="boolean")return{error:'browser_observe: "include_hidden" must be a boolean'};r=t.include_hidden}let o;if(t.max_elements!==void 0){if(typeof t.max_elements!="number"||!Number.isFinite(t.max_elements)||t.max_elements<=0||!Number.isInteger(t.max_elements))return{error:'browser_observe: "max_elements" must be a positive integer'};o=t.max_elements}return{screenshot:n,includeHidden:r,maxElements:o}}function XW(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_observe aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=YW(t);if("error"in o)return{content:o.error,isError:!0};let s=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i;try{if(e.getBrowserProvider)i=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(Mo(),Po));i=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Rn(c)?{content:Cn(c),isError:!0}:{content:`browser_observe failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await i.observe({sessionId:s,screenshot:o.screenshot,includeHidden:o.includeHidden,maxElements:o.maxElements}),c=Date.now()-a;return et(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:l.url,urlAfter:l.url,status:"ok",durationMs:c,...l.screenshotPath!==null?{screenshotPath:l.screenshotPath}:{}}),{content:JSON.stringify(l,null,2)}}catch(l){let c=Date.now()-a,u=l instanceof Error?l.message:String(l);return et(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:u,recoverable:!1}}),{content:`browser_observe failed: ${u}`,isError:!0}}}}var MT,OT=_(()=>{"use strict";q();je();Qs();MT=XW()});function ZW(e){if(!e||typeof e!="object")return{error:"browser_act: input must be an object"};let t=e;if(typeof t.action!="string")return{error:'browser_act: "action" is required and must be a string'};if(!$T.includes(t.action))return{error:`browser_act: "action" must be one of ${$T.map(u=>`"${u}"`).join(", ")} (got ${JSON.stringify(t.action)})`};let n=t.action,r=t.target;if(!r||typeof r!="object")return{error:'browser_act: "target" is required and must be an object'};let o=r;if(typeof o.kind!="string"||!DT.includes(o.kind))return{error:`browser_act: "target.kind" must be one of ${DT.map(u=>`"${u}"`).join(", ")} (got ${JSON.stringify(o.kind)})`};let s,i=o.kind;if(i==="semantic"){if(typeof o.text!="string"||o.text.length===0)return{error:'browser_act: target.kind=semantic requires "target.text" (non-empty string)'};s={kind:"semantic",text:o.text,...typeof o.role=="string"&&o.role.length>0?{role:o.role}:{}}}else if(i==="element_id"){if(typeof o.element_id!="string"||o.element_id.length===0)return{error:'browser_act: target.kind=element_id requires "target.element_id" (non-empty string)'};s={kind:"element_id",elementId:o.element_id}}else{if(typeof o.selector!="string"||o.selector.length===0)return{error:'browser_act: target.kind=selector requires "target.selector" (non-empty string)'};s={kind:"selector",selector:o.selector}}let a;if(t.value!==void 0){if(typeof t.value!="string")return{error:'browser_act: "value" must be a string when provided'};a=t.value}let l;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:'browser_act: "timeout_ms" must be a positive finite number'};l=t.timeout_ms}let c;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_act: "screenshot" must be a boolean'};c=t.screenshot}return{action:n,target:s,value:a,timeoutMs:l,screenshot:c}}function QW(e,t){let n=e.role?`"${e.text}" (role: ${e.role})`:`"${e.text}"`;return[`browser_act: ambiguous target \u2014 ${t.length} elements matched ${n}.`,'Retry with target.kind="element_id" using one of the following:',...t.map(o=>` id=${o.id} role=${o.role} label=${o.label}`)].join(`
|
|
1100
1100
|
`)}function eK(e){return e.kind==="semantic"?{kind:"semantic",text:RE(e.text),...e.role!==void 0?{role:e.role}:{}}:e.kind==="element_id"?{kind:"element_id",elementId:e.elementId}:{kind:"selector",selectorHash:xE(e.selector)}}function tK(e={}){return async(t,n,r)=>{if(n.aborted){let c=n.reason;return{content:`browser_act aborted: ${c instanceof Error?c.message:String(c??"aborted")}`,isError:!0,failureClass:"abort"}}let o=ZW(t);if("error"in o)return{content:o.error,isError:!0};let s=eK(o.target),i=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let a;try{if(e.getBrowserProvider)a=await e.getBrowserProvider();else{let{getBrowserProvider:c}=await Promise.resolve().then(()=>(Mo(),Po));a=await c()}}catch(c){let u=c instanceof Error?c.message:String(c);return Rn(u)?{content:Cn(u),isError:!0}:{content:`browser_act failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let c=await a.act({sessionId:i,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),u=Date.now()-l;if("outcome"in c){if(c.outcome==="ambiguous_target")return et(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:u}),{content:QW(c.query,c.candidates),isError:!0};if(c.outcome==="blocked_by_policy")return et(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:u}),{content:`browser_act blocked: ${c.reason}`,isError:!0,failureClass:"policy-refusal"}}return et(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:c.url,urlAfter:c.url,status:"ok",durationMs:u,...c.screenshotPath!==null?{screenshotPath:c.screenshotPath}:{}}),{content:JSON.stringify(c,null,2)}}catch(c){let u=Date.now()-l,d=c instanceof Error?c.message:String(c);et(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:d,recoverable:!1}});let p=Bu(c);return{content:`browser_act failed: ${d}`,isError:!0,...p?{failureClass:p}:{}}}}}var $T,DT,LT,FT=_(()=>{"use strict";Ba();q();je();Qs();$T=["click","fill","press","select","hover","scroll_to","wait_for"],DT=["semantic","element_id","selector"];LT=tK()});function nK(e){if(typeof e.kind!="string"||!NT.includes(e.kind))return{error:`browser_screenshot: "target.kind" must be one of ${NT.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e.kind)})`};let t=e.kind;return t==="semantic"?typeof e.text!="string"||e.text.length===0?{error:'browser_screenshot: target.kind=semantic requires "target.text" (non-empty string)'}:{kind:"semantic",text:e.text,...typeof e.role=="string"&&e.role.length>0?{role:e.role}:{}}:t==="element_id"?typeof e.element_id!="string"||e.element_id.length===0?{error:'browser_screenshot: target.kind=element_id requires "target.element_id" (non-empty string)'}:{kind:"element_id",elementId:e.element_id}:typeof e.selector!="string"||e.selector.length===0?{error:'browser_screenshot: target.kind=selector requires "target.selector" (non-empty string)'}:{kind:"selector",selector:e.selector}}function rK(e){if(e!=null&&typeof e!="object")return{error:"browser_screenshot: input must be an object or omitted"};if(!e)return{};let t=e,n;if(t.target!==void 0){if(!t.target||typeof t.target!="object")return{error:'browser_screenshot: "target" must be an object when provided'};let o=nK(t.target);if("error"in o)return o;n=o}let r;if(t.full_page!==void 0){if(typeof t.full_page!="boolean")return{error:'browser_screenshot: "full_page" must be a boolean'};r=t.full_page}return{target:n,fullPage:r}}function oK(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_screenshot aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=rK(t);if("error"in o)return{content:o.error,isError:!0};let s=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i;try{if(e.getBrowserProvider)i=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(Mo(),Po));i=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Rn(c)?{content:Cn(c),isError:!0}:{content:`browser_screenshot failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await i.screenshot({sessionId:s,target:o.target,fullPage:o.fullPage}),c=Date.now()-a,{dataBase64:u,mediaType:d,...p}=l;return et(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:c,screenshotPath:p.path}),p.width>ph||p.height>ph?{content:JSON.stringify({...p,imageOmitted:`dimensions ${p.width}x${p.height}px exceed the ${ph}px model-vision limit; the PNG was saved to the sidecar path but not attached. Use full_page:false (viewport) or target a specific element for a model-visible image.`},null,2)}:{content:JSON.stringify(p,null,2),image:{mediaType:d,data:u}}}catch(l){let c=Date.now()-a,u=l instanceof Error?l.message:String(l);return et(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:u,recoverable:!1}}),{content:`browser_screenshot failed: ${u}`,isError:!0}}}}var NT,ph,BT,UT=_(()=>{"use strict";q();je();Qs();NT=["semantic","element_id","selector"],ph=8e3;BT=oK()});function sK(e={}){return async(t,n,r)=>{if(n.aborted){let a=n.reason;return{content:`browser_close aborted: ${a instanceof Error?a.message:String(a??"aborted")}`,isError:!0}}let o=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(o))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(o)}`,isError:!0};let s;try{if(e.getBrowserProvider)s=await e.getBrowserProvider();else{let{getBrowserProvider:a}=await Promise.resolve().then(()=>(Mo(),Po));s=await a()}}catch(a){let l=a instanceof Error?a.message:String(a);return Rn(l)?{content:Cn(l),isError:!0}:{content:`browser_close failed to get provider: ${l}`,isError:!0}}let i=Date.now();try{await s.close({sessionId:o});let a=Date.now()-i;return et(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:a}),{content:"Browser session closed."}}catch(a){let l=Date.now()-i,c=a instanceof Error?a.message:String(a);return et(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:l,error:{reason:c,recoverable:!1}}),{content:`browser_close failed: ${c}`,isError:!0}}}}var jT,HT=_(()=>{"use strict";q();je();Qs();jT=sK()});function Uu(e,t){let n=e!==void 0?iu(e,t):t!==void 0?iu("default",t):kk,r=t!==void 0?vg(t):Lk,o=t!==void 0?kg(t):Nk,s=eh();return new Map([["bash",n],["read_file",Rk],["write_file",Ik],["edit_file",Mk],["glob",r],["grep",o],["list_directory",Uk],["send_telegram",fE],["web_scrape",VE],["create_schedule",eT],["list_schedules",tT],["get_schedule_history",nT],["cancel_schedule",rT],["terminal_font_size",s],["config_get",TT],["config_set",xT],["ask_question",CT],["browser_open",IT],["browser_observe",MT],["browser_act",LT],["browser_screenshot",BT],["browser_close",jT]])}var mh=_(()=>{"use strict";Ek();Ck();Pk();Ok();Fk();Bk();jk();gE();YE();oT();nh();RT();AT();PT();OT();FT();UT();HT()});function ju(e){return["The user has switched off plan mode. Writes are now permitted. Do two things, in order:","",`1. Save the plan. Write the plan you developed in this conversation to a new markdown file under \`${e}/\` \u2014 pick a short, descriptive kebab-case filename (e.g. \`${e}/refactor-auth-flow.md\`). Capture the full plan: the chosen approach, the concrete step-by-step changes, the risks named, and the alternatives considered. This is the durable record.`,"","2. Implement the plan. Work through the steps you just recorded, verifying as you go \u2014 run the project's lint/test gates where they apply. End in a terminal state: Done with evidence, Blocked with the exact unblock condition, or Asking one precise question."].join(`
|
|
1101
1101
|
`)}var fh=_(()=>{"use strict"});function Wu(e){return async(t,n,r)=>{let o={serverName:"agent",origin:"agent",type:"choice",message:"Plan ready. How do you want to proceed? (Your plan is in the conversation above.)",choices:[iK,aK,WT]},s=await lt.route(o,{signal:n});if(s.action!=="accept")return{content:"Plan exit not confirmed (the user did not approve). Stay in plan mode \u2014 keep refining the plan; do not implement. Call exit_plan_mode again when ready."};let i=typeof s.content?.value=="string"?s.content.value:"";if(i.startsWith("Keep")||i===WT)return{content:"User chose to keep planning. Stay in plan mode and refine the plan; do not implement. Call exit_plan_mode again when ready."};let a=i.includes("bypass")?"bypassPermissions":"default",l=pc(r?.resolveBase??r?.cwd??process.cwd());return e.requestImplementSeed(ju(l),a),{content:`Plan approved (mode=${a}). The implementation instruction will follow as a new message \u2014 end your turn now.`}}}var $o,iK,aK,WT,Hu,Ku=_(()=>{"use strict";Fr();fh();G();$o="exit_plan_mode",iK="Approve \u2014 implement now (default mode: writes ask for confirmation, contained to the workspace)",aK="Approve \u2014 implement now (bypass mode: no prompts, read/write any path)",WT="Keep planning",Hu={name:$o,category:"other",concurrencySafe:!1,description:`Signal that your plan is ready and present it to the user for approval. The user is shown a picker: approve and implement (you pick neither mode \u2014 the user does), or keep planning.
|
|
@@ -1119,11 +1119,11 @@ ${s}`:s}function VT(e,t){if(typeof e=="string")return e;if(!t.vision)return JT(e
|
|
|
1119
1119
|
${o}`:o}function AK(e){let t=e.systemPrompt;if(t!==void 0){if(typeof t=="string")return t.length>0?t:void 0;if(typeof t=="object"&&t!==null&&"append"in t){let n=t.append;return n&&n.length>0?n:void 0}}}function YT(e){let t=[],n=AK(e.config);if(n!==void 0&&t.push({role:"system",content:n}),e.resumeHistory)for(let r of e.resumeHistory)r.user&&t.push({role:"user",content:r.user}),r.assistant&&t.push({role:"assistant",content:r.assistant});if(e.priorTurns)for(let r of e.priorTurns)t.push(r);return e.currentUserText!==void 0&&t.push({role:"user",content:e.currentUserText}),e.vision===!1?t.map(r=>Array.isArray(r.content)?{...r,content:CK(r.content)}:r):t}var XT=_(()=>{"use strict"});function PK(){let e=v.AFK_VISION_MODELS,t=[],n=[];if(e)for(let r of e.split(",")){let o=r.trim().toLowerCase();if(o)if(o.startsWith("!")){let s=o.slice(1).trim();s&&n.push(s)}else t.push(o)}return{enable:t,disable:n}}function ZT(e,t){return e===t||e.includes(t)}function QT(e){if(!e)return!1;let t=(ko(e)??e).trim();if(!t)return!1;let n=t.toLowerCase(),{enable:r,disable:o}=PK();return o.some(s=>ZT(n,s))?!1:r.some(s=>ZT(n,s))||_K.has(n)?!0:IK.some(s=>s.test(t))}var _K,IK,ex=_(()=>{"use strict";q();en();_K=new Set(["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4-turbo","o1","o3","o4-mini"]),IK=[/^claude-/i,/^gpt-4o/i,/^gpt-4\.1/i,/^gpt-4-turbo/i,/^gpt-4-vision/i,/^gpt-5/i,/(?:^|[/_-])(?:vl|vlm)(?:[/_.-]|$)/i,/(?:^|[/_-])(?:llava|pixtral|internvl|cogvlm|idefics|moondream|janus)/i,/(?:vision|minicpm-?[vo]|qwen[\d.]*-?vl|llama-?3\.2-\d+b-vision|gemma-3|phi-3\.5-vision|phi-4-multimodal)/i]});function bh(){return{assistantText:"",reasoningText:"",toolCallsByIndex:new Map,finishReason:null,usage:null,model:null,id:null}}function*tx(e,t,n){e.id&&!t.id&&(t.id=e.id),e.model&&!t.model&&(t.model=e.model),e.usage&&(t.usage=e.usage);let r=e.choices?.[0];if(!r)return;r.finish_reason&&(t.finishReason=r.finish_reason);let o=r.delta;if(!o)return;let s=o.reasoning_content??o.reasoning;if(typeof s=="string"&&s.length>0&&(t.reasoningText+=s,yield{type:"delta.reasoning",text:s,sessionId:n}),typeof o.content=="string"&&o.content.length>0&&(t.assistantText+=o.content,yield{type:"delta.text",text:o.content,sessionId:n}),o.tool_calls&&o.tool_calls.length>0)for(let i of o.tool_calls){let a=t.toolCallsByIndex.get(i.index)??{index:i.index,id:"",name:"",argumentsRaw:"",startEmitted:!1};i.id&&(a.id=i.id),i.function?.name&&(a.name=i.function.name),i.function?.arguments&&(a.argumentsRaw+=i.function.arguments),t.toolCallsByIndex.set(i.index,a)}}function nx(e){let t=e.usage;if(!t)return{stopReason:e.finishReason??null,resultSubtype:"success",isError:!1};let n=t.prompt_tokens_details?.cached_tokens??0,r=t.prompt_tokens??0,o=t.completion_tokens??0;return{inputTokens:r,outputTokens:o,cachedInputTokens:n,totalTokens:t.total_tokens??r+o,stopReason:e.finishReason??null,resultSubtype:"success",isError:!1,raw:{...t}}}function wh(e){return[...e.toolCallsByIndex.values()].sort((t,n)=>t.index-n.index)}function Sh(e){return e.finishReason==="tool_calls"||e.finishReason==="function_call"?!0:e.finishReason!==null||e.toolCallsByIndex.size===0?!1:[...e.toolCallsByIndex.values()].every(t=>t.id.length>0&&t.name.length>0)}var rx=_(()=>{"use strict"});function ox(e){return e.map(t=>{let n={name:t.name,parameters:t.input_schema};return t.description!==void 0&&(n.description=t.description),{type:"function",function:n}})}function sx(e,t){let n=[],r=new Map;for(let o of e){let s={};if(o.argumentsRaw.length>0)try{s=JSON.parse(o.argumentsRaw)}catch(i){let a=i instanceof Error?i.message:String(i);r.set(o.id,`Failed to parse tool arguments as JSON: ${a}`),s={}}n.push({id:o.id,name:o.name,input:s,signal:t})}return{calls:n,parseErrors:r}}function ix(e,t,n=""){let r={role:"assistant",content:e.length>0?e:null,tool_calls:t.map(o=>({id:o.id,type:"function",function:{name:o.name,arguments:o.argumentsRaw}}))};return n.length>0&&(r.reasoning_content=n),r}function ax(e){return e.map(({call:t,result:n})=>({role:"tool",tool_call_id:t.id,content:n.isError?`[error] ${n.content}`:n.content}))}function lx(e,t){if(!t.vision)return;let n=[],r=[];for(let{call:s,result:i}of e)i.image&&(n.push({type:"image_url",image_url:{url:`data:${i.image.mediaType};base64,${i.image.data}`}}),r.push(s.name));return n.length===0?void 0:{role:"user",content:[{type:"text",text:r.length===1?`Image output from the \`${r[0]}\` tool call (referenced above):`:`Image output from ${r.length} tool calls (${r.join(", ")}):`},...n]}}var cx=_(()=>{"use strict"});function*ux(e,t,n){switch(e.type){case"response.output_text.delta":{typeof e.delta=="string"&&e.delta.length>0&&(t.assistantText+=e.delta,yield{type:"delta.text",text:e.delta,sessionId:n});return}case"response.reasoning_text.delta":case"response.reasoning_summary_text.delta":{typeof e.delta=="string"&&e.delta.length>0&&(t.reasoningText+=e.delta,yield{type:"delta.reasoning",text:e.delta,sessionId:n});return}case"response.output_item.added":{let r=e.item;if(r?.type==="function_call"&&typeof e.output_index=="number"){let o=t.toolCallsByIndex.get(e.output_index),s=o?.argumentsRaw??"";t.toolCallsByIndex.set(e.output_index,{index:e.output_index,id:r.call_id??o?.id??"",name:r.name??o?.name??"",argumentsRaw:s.length>0?s:r.arguments??"",startEmitted:o?.startEmitted??!1})}return}case"response.function_call_arguments.delta":{if(typeof e.output_index=="number"&&typeof e.delta=="string"){let r=t.toolCallsByIndex.get(e.output_index)??{index:e.output_index,id:"",name:"",argumentsRaw:"",startEmitted:!1};r.argumentsRaw+=e.delta,t.toolCallsByIndex.set(e.output_index,r)}return}case"response.completed":{vh(t,e),t.finishReason=t.toolCallsByIndex.size>0?"tool_calls":"stop";return}case"response.incomplete":{vh(t,e),t.finishReason=e.response?.incomplete_details?.reason??"incomplete";return}case"response.failed":{vh(t,e),t.finishReason="failed";return}default:return}}function vh(e,t){let n=t.response?.usage;if(!n)return;let r=n.input_tokens??0,o=n.output_tokens??0;e.usage={prompt_tokens:r,completion_tokens:o,total_tokens:n.total_tokens??r+o,prompt_tokens_details:{cached_tokens:n.input_tokens_details?.cached_tokens??0}}}var dx=_(()=>{"use strict"});function px(e,t){let n=[],r=[];for(let i of e){if(i.role==="system"){typeof i.content=="string"&&i.content.length>0&&n.push(i.content);continue}if(i.role==="tool"){r.push({type:"function_call_output",call_id:i.tool_call_id??"",output:typeof i.content=="string"?i.content:""});continue}if(i.role==="assistant"){if(typeof i.content=="string"&&i.content.length>0&&r.push({role:"assistant",content:i.content}),Array.isArray(i.tool_calls))for(let a of i.tool_calls)r.push({type:"function_call",call_id:a.id,name:a.function.name,arguments:a.function.arguments});continue}r.push({role:"user",content:MK(i.content)})}let o={input:r};n.length>0&&(o.instructions=n.join(`
|
|
1120
1120
|
|
|
1121
1121
|
`));let s=OK(t);return s.length>0&&(o.tools=s),o}function MK(e){if(e===null)return"";if(typeof e=="string")return e;let t=[];for(let n of e)n.type==="text"?t.push({type:"input_text",text:n.text}):t.push({type:"input_image",image_url:n.image_url.url,detail:"auto"});return t}function OK(e){return!e||e.length===0?[]:e.map(t=>{let n={type:"function",name:t.function.name,parameters:t.function.parameters};return t.function.description!==void 0&&(n.description=t.function.description),n})}var mx=_(()=>{"use strict"});function gx(e){let t=(e??"").trim().toLowerCase();return t?t.startsWith("claude-")||t.startsWith("claude_")||t==="claude"||t.startsWith("local-")||t.startsWith("local_")?!0:/^(opus|sonnet|haiku)(?:[._-].*)?$/.test(t):!1}function hx(e){if(!e)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function DK(e){let t={"OpenAI-Beta":"responses=experimental",originator:"agent-afk"};return e&&(t["chatgpt-account-id"]=e),t}function yx(e,t=!1){return e.source==="chatgpt-oauth"?{mode:"responses",baseURL:$K,headers:DK(e.accountId)}:t?{mode:"responses"}:{mode:"chat-completions"}}var $K,fx,bx=_(()=>{"use strict";$K="https://chatgpt.com/backend-api/codex",fx="You are a helpful assistant."});function LK(e){return(e.inputTokens??0)+(e.outputTokens??0)}function ti(e){return e.contextWindowTokens??LK(e)}function Ju(e){return e?{totalTokens:ti(e),apiUsage:{input_tokens:e.inputTokens??0,output_tokens:e.outputTokens??0,cache_read_input_tokens:e.cachedInputTokens??0,cache_creation_input_tokens:e.cacheCreationTokens??0}}:{totalTokens:0,apiUsage:null}}function wx(e,t,n){return t<=0||e<=0||n<=0||n>=1?!1:e/t>=n}var kh=_(()=>{"use strict"});import FK from"openai";import{randomUUID as Sx}from"node:crypto";function Ax(e){if(e===null||typeof e!="object")return;let t=e;return typeof t.status=="number"?t.status:void 0}function Ex(e){let t=Ax(e);return t===void 0?!1:Cx.has(t)}function Tx(e){let t=Ax(e);return t===void 0?!1:Cx.has(t)}function Yu(e,t){return new Promise(n=>{if(t.aborted){n();return}let r=setTimeout(n,e);r.unref(),t.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}function _x(e,t){let n=Ka(e);return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):n}function UK(e,t){let n=_x(e,t);return Ix(e)?{max_completion_tokens:n}:{max_tokens:n}}function xx(e){return e??"default"}function Ix(e){let t=e.includes("/")?e.slice(e.lastIndexOf("/")+1):e;return/^o[0-9]/.test(t)}function jK(e){switch(e){case"low":return"low";case"medium":return"medium";case"high":case"xhigh":case"max":return"high"}}function Rx(e,t){if(e!==void 0&&Ix(t))return jK(e)}function HK(e){let t={apiKey:e.apiKey};return e.baseURL!==void 0&&(t.baseURL=e.baseURL),e.defaultHeaders!==void 0&&(t.defaultHeaders=e.defaultHeaders),new FK(t)}function WK(e,t){if(!t||typeof t!="object")return"";let n=t;if(e==="skill"||e==="Skill"){let i=n.name;return typeof i=="string"&&i.length>0?`(${i.length>60?i.slice(0,59)+"\u2026":i})`:""}let r=n.file_path??n.path??n.filePath;if(typeof r=="string")return" "+r;let o=n.command??n.cmd;if(typeof o=="string"){let i=o.split(`
|
|
1122
|
-
`)[0];return" "+(i.length>80?i.slice(0,77)+"\u2026":i)}let s=n.query??n.pattern??n.url??n.description;return typeof s=="string"?" "+s:""}function Px(e,t,n={}){let r=Do(e.apiKey,n.authDeps),o=e.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=typeof e.model=="string"?e.model:"gpt-4o-mini",i=
|
|
1122
|
+
`)[0];return" "+(i.length>80?i.slice(0,77)+"\u2026":i)}let s=n.query??n.pattern??n.url??n.description;return typeof s=="string"?" "+s:""}function Px(e,t,n={}){let r=Do(e.apiKey,n.authDeps),o=e.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=typeof e.model=="string"?e.model:"gpt-4o-mini",i=yt(s)??s,a={auth:r,model:i,synthesizedSessionId:o,promptStream:t,config:e};return n.baseURL!==void 0&&(a.baseURL=n.baseURL),n.toolDispatcher!==void 0&&(a.toolDispatcher=n.toolDispatcher),n.onPermissionMode!==void 0&&(a.onPermissionMode=n.onPermissionMode),n.mcpManager!==void 0&&(a.mcpManager=n.mcpManager),n.useResponsesApi!==void 0&&(a.useResponsesApi=n.useResponsesApi),e.traceWriter!==void 0&&(a.traceWriter=e.traceWriter),new Xu(a)}var Eh,NK,Cx,vx,kx,Vu,BK,Xu,Th=_(()=>{"use strict";je();xa();hh();Ga();Jn();Ur();yh();_e();Ja();XT();ex();rx();cx();dx();mx();bx();q();kh();zf();Vf();Eh="openai-compatible",NK=50,Cx=new Set([429,500,502,503,529]),vx=3,kx=3,Vu=2e3;BK=null;Xu=class{client;opts;initSessionId;toolDispatcher;onPermissionMode;openAITools;wireMode;traceWriter;priorTurns=[];currentModel;currentPermissionMode;abortController=null;pendingAbortReason=null;closed=!1;closeResolve=null;closedPromise;lastUsage=null;constructor(t){if(this.opts=t,this.initSessionId=t.synthesizedSessionId,this.currentModel=t.model,this.currentPermissionMode=xx(t.config.permissionMode),this.toolDispatcher=t.toolDispatcher,this.onPermissionMode=t.onPermissionMode,this.traceWriter=t.traceWriter,this.toolDispatcher){let o=this.toolDispatcher;Array.isArray(o.toolDefs)&&o.toolDefs.length>0&&(this.openAITools=ox(o.toolDefs))}let n=(t.useResponsesApi??!1)||hx(v.AFK_OPENAI_USE_RESPONSES),r=yx(t.auth,n);if(this.wireMode=r.mode,t.auth.apiKey===null)this.client=null;else{let o=BK??HK,s={apiKey:t.auth.apiKey},i=r.baseURL??t.baseURL;i!==void 0&&(s.baseURL=i),r.headers!==void 0&&(s.defaultHeaders=r.headers),this.client=o(s)}this.closedPromise=new Promise(o=>{this.closeResolve=()=>o("__closed__")})}async*[Symbol.asyncIterator](){if(yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.currentModel,permissionMode:this.currentPermissionMode,cwd:process.cwd(),tools:this.openAITools?this.openAITools.map(r=>r.function.name):[],slashCommands:[],skills:[],plugins:[],mcpServers:this.opts.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:this.opts.auth.source,version:Eh}},this.opts.auth.apiKey===null){yield{type:"error",error:new Error(za(this.opts.auth))};return}let n=this.opts.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let r=await Promise.race([n.next(),this.closedPromise]);if(r==="__closed__")break;let o=r;if(o.done)break;yield*this.runTurn(o.value.content)}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}async*runTurn(t){let n=new AbortController;if(this.abortController=n,this.pendingAbortReason!==null&&!n.signal.aborted&&(n.abort(this.pendingAbortReason),this.pendingAbortReason=null),n.signal.aborted)return;let r=Date.now(),o=Sx();De(this.traceWriter,{phase:"loop_start"});try{yield*this._runTurnInner(t,n,r,o)}finally{De(this.traceWriter,{phase:"loop_end",durationMs:Date.now()-r})}}async*_runTurnInner(t,n,r,o){let s=QT(this.currentModel);this.priorTurns.push({role:"user",content:VT(t,{vision:s,model:this.currentModel})});let i={stopReason:null,resultSubtype:"success",isError:!1},a="",l="";for(let c=0;c<NK;c++){if(n.signal.aborted){this.abortController===n&&(this.abortController=null),yield*this.finishTurn(i,r);return}let u=yield*this.runIteration(n,s);if(u===null){this.abortController===n&&(this.abortController=null),(n.signal.aborted||this.closed)&&(yield*this.finishTurn(i,r));return}let d=nx(u.state);if(i=Wa(i,d),i.contextWindowTokens=(d.inputTokens??0)+(d.outputTokens??0),this.lastUsage=i,u.text.length>0&&(a=u.text),l=u.state.reasoningText,!u.needsToolDispatch)break;yield*this.dispatchAndAppend(u.state,n.signal,s);{let p=wh(u.state).at(-1)?.name;yield{type:"progress",progress:{taskId:o,description:"Tool-use loop",summary:`Iteration ${c+1}: used ${p??"unknown"}`,lastToolName:p,totalTokens:i.totalTokens??0,toolUses:c+1,durationMs:Date.now()-r},sessionId:this.initSessionId}}if(n.signal.aborted){this.abortController===n&&(this.abortController=null),yield*this.finishTurn(i,r);return}}if(this.abortController===n&&(this.abortController=null),a.length>0){let c={role:"assistant",content:a};l.length>0&&(c.reasoning_content=l),this.priorTurns.push(c)}yield{type:"assistant.message",text:a,sessionId:this.initSessionId},yield*this.finishTurn(i,r)}*finishTurn(t,n){this.lastUsage=t,yield{type:"turn.completed",usage:{...t,durationMs:Date.now()-n},sessionId:this.initSessionId}}clarifyResponsesError(t,n){let r=t instanceof Error?t:new Error(String(t));if(!n||(t&&typeof t=="object"&&"status"in t?t.status:void 0)!==400&&!/\b400\b/.test(r.message))return r;let s,i=t?.error;if(i&&typeof i=="object"){let a=i;typeof a.detail=="string"?s=a.detail:typeof a.message=="string"&&(s=a.message)}return new Error(`ChatGPT/Codex backend rejected model "${this.currentModel}" (HTTP 400). A ChatGPT subscription only serves certain OpenAI models on this backend (gpt-5.5 works; gpt-5, gpt-5.1, gpt-5.2 and *-codex do not). `+(s?`Backend said: ${s}`:"No error body was returned."))}async*runIteration(t,n){let r=YT({config:this.opts.config,...this.opts.config.resumeHistory!==void 0?{resumeHistory:this.opts.config.resumeHistory}:{},priorTurns:this.priorTurns,vision:n});if(r[0]?.role==="system"){let o=this.currentPermissionMode==="plan"?qf:this.currentPermissionMode==="autonomous"?Jf:null;o!==null&&(r[0]={...r[0],content:r[0].content+`
|
|
1123
1123
|
|
|
1124
1124
|
`+o})}if(this.wireMode==="responses"){let o=this.opts.auth.source==="chatgpt-oauth";if(o&&gx(this.currentModel))return yield{type:"error",error:new Error(`Model "${this.currentModel}" can't run on a ChatGPT subscription \u2014 the ChatGPT/Codex backend only supports OpenAI gpt-5.x models. This usually means a subagent or skill requested a Claude model. Pass a gpt-5.x model to it (e.g. model: "gpt-5.5"), or run it on a provider configured with the matching API key.`)},null;let s=px(r,this.openAITools),i={model:this.currentModel,input:s.input,stream:!0};o||(i.max_output_tokens=_x(this.currentModel,this.opts.config.maxOutputTokens));let a=s.instructions??(o?fx:void 0);a!==void 0&&(i.instructions=a),o&&(i.store=!1),s.tools&&s.tools.length>0&&(i.tools=s.tools);let l=Rx(this.opts.config.effort,this.currentModel);l!==void 0&&(i.reasoning={effort:l});let c=0;for(;;){let u=bh(),d=Date.now(),p,m=null;for(let b=0;;b++)try{p=await this.client.responses.create(i,{signal:t.signal});break}catch(y){if(t.signal.aborted)return null;if(Ex(y)&&b<vx){let S=Vu*Math.pow(2,b);if(await Yu(S,t.signal),t.signal.aborted)return null;continue}m=y;break}if(m!==null)return yield{type:"error",error:this.clarifyResponsesError(m,o)},null;let g=null,h=!1;try{for await(let b of p){if(this.closed)return null;for(let y of ux(b,u,this.initSessionId))h||(h=!0,De(this.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-d,resolvedModel:this.currentModel})),yield y}}catch(b){if(t.signal.aborted)return null;if(Tx(b)&&c<kx){if(c++,yield{type:"stream.retry",sessionId:this.initSessionId},await Yu(Vu*Math.pow(2,c-1),t.signal),t.signal.aborted)return null;continue}g=b}return g!==null?(yield{type:"error",error:this.clarifyResponsesError(g,o)},null):{state:u,events:[],text:u.assistantText,needsToolDispatch:Sh(u)&&u.toolCallsByIndex.size>0}}}else{let o={model:this.currentModel,messages:r,stream:!0,stream_options:{include_usage:!0}};Object.assign(o,UK(this.currentModel,this.opts.config.maxOutputTokens)),this.openAITools&&this.openAITools.length>0&&(o.tools=this.openAITools);let s=Rx(this.opts.config.effort,this.currentModel);s!==void 0&&(o.reasoning_effort=s);let i=0;for(;;){let a=bh(),l=Date.now(),c,u=null;for(let m=0;;m++)try{c=await this.client.chat.completions.create(o,{signal:t.signal});break}catch(g){if(t.signal.aborted)return null;if(Ex(g)&&m<vx){let h=Vu*Math.pow(2,m);if(await Yu(h,t.signal),t.signal.aborted)return null;continue}u=g;break}if(u!==null)return yield{type:"error",error:u instanceof Error?u:new Error(String(u))},null;let d=null,p=!1;try{for await(let m of c){if(this.closed)return null;for(let g of tx(m,a,this.initSessionId))p||(p=!0,De(this.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-l,resolvedModel:this.currentModel})),yield g}}catch(m){if(t.signal.aborted)return null;if(Tx(m)&&i<kx){if(i++,yield{type:"stream.retry",sessionId:this.initSessionId},await Yu(Vu*Math.pow(2,i-1),t.signal),t.signal.aborted)return null;continue}d=m}return d!==null?(yield{type:"error",error:d instanceof Error?d:new Error(String(d))},null):{state:a,events:[],text:a.assistantText,needsToolDispatch:Sh(a)&&a.toolCallsByIndex.size>0}}}}async*dispatchAndAppend(t,n,r){if(!this.toolDispatcher)return;let o=wh(t);for(let u of o)u.id.length===0&&(u.id=Sx());let{calls:s,parseErrors:i}=sx(o,n),a=new Map;for(let u of s){let d=Date.now();a.set(u.id,d),Is(this.traceWriter,{phase:"started",toolUseId:u.id,name:u.name,inputBytes:Buffer.byteLength(JSON.stringify(u.input??{}),"utf8")}),yield{type:"tool.use.start",toolUseId:u.id,toolName:u.name,toolInput:WK(u.name,u.input),toolInputRaw:zu(u.input),sessionId:this.initSessionId}}let l=[];if(n.aborted)for(let u of s){let d={content:"Tool call aborted",isError:!0};l.push({call:u,result:d}),yield{type:"tool.output",toolUseId:u.id,toolName:u.name,content:d.content,isError:!0,sessionId:this.initSessionId}}else{let u;try{if(this.toolDispatcher.executeBatch)u=await this.toolDispatcher.executeBatch(s);else{u=[];for(let d of s){if(n.aborted){u.push({content:"Tool call aborted",isError:!0});continue}try{u.push(await this.toolDispatcher.execute(d))}catch(p){let m=p instanceof Error?p.message:String(p);u.push({content:`Tool execution threw: ${m}`,isError:!0})}}}}catch(d){let p=d instanceof Error?d.message:String(d);u=s.map(()=>({content:`Tool batch execution failed: ${p}`,isError:!0}))}for(let d=0;d<s.length;d++){let p=s[d],m=u[d],g=i.get(p.id);g!==void 0&&(m={content:`${g}
|
|
1125
1125
|
--
|
|
1126
|
-
${m.content}`,isError:!0,...m.truncated===!0?{truncated:!0}:{}}),l.push({call:p,result:m});let h=a.get(p.id),b=typeof h=="number"?Date.now()-h:0,y=m.truncated===!0||m.content.includes("[output truncated");Is(this.traceWriter,{phase:"completed",toolUseId:p.id,name:p.name,resultBytes:Buffer.byteLength(m.content,"utf8"),isError:m.isError===!0,truncated:y,durationMs:b,...m.circuitBreaker===!0?{circuitBreaker:!0}:{},...m.failureClass?{failureClass:m.failureClass}:{}}),yield{type:"tool.output",toolUseId:p.id,toolName:p.name,content:m.content,...m.isError===!0?{isError:!0}:{},...m.truncated===!0?{truncated:!0}:{},sessionId:this.initSessionId},m.render?.diff&&(yield{type:"tool.diff",toolUseId:p.id,diff:m.render.diff,sessionId:this.initSessionId})}}this.priorTurns.push(ix(t.assistantText,o,t.reasoningText));for(let u of ax(l))this.priorTurns.push(u);let c=lx(l,{vision:r});c&&this.priorTurns.push(c)}async interrupt(){let t=this.abortController;if(t&&!t.signal.aborted){t.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(t){t!==void 0&&(this.currentModel=
|
|
1126
|
+
${m.content}`,isError:!0,...m.truncated===!0?{truncated:!0}:{}}),l.push({call:p,result:m});let h=a.get(p.id),b=typeof h=="number"?Date.now()-h:0,y=m.truncated===!0||m.content.includes("[output truncated");Is(this.traceWriter,{phase:"completed",toolUseId:p.id,name:p.name,resultBytes:Buffer.byteLength(m.content,"utf8"),isError:m.isError===!0,truncated:y,durationMs:b,...m.circuitBreaker===!0?{circuitBreaker:!0}:{},...m.failureClass?{failureClass:m.failureClass}:{}}),yield{type:"tool.output",toolUseId:p.id,toolName:p.name,content:m.content,...m.isError===!0?{isError:!0}:{},...m.truncated===!0?{truncated:!0}:{},sessionId:this.initSessionId},m.render?.diff&&(yield{type:"tool.diff",toolUseId:p.id,diff:m.render.diff,sessionId:this.initSessionId})}}this.priorTurns.push(ix(t.assistantText,o,t.reasoningText));for(let u of ax(l))this.priorTurns.push(u);let c=lx(l,{vision:r});c&&this.priorTurns.push(c)}async interrupt(){let t=this.abortController;if(t&&!t.signal.aborted){t.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(t){t!==void 0&&(this.currentModel=yt(t)??t)}async setPermissionMode(t){this.currentPermissionMode=xx(t);let n=wn(this.currentPermissionMode);this.toolDispatcher?.setAllowAll?.(n),this.onPermissionMode?.(this.currentPermissionMode)}setCwd(t){this.toolDispatcher?.setResolveBase?.(t)}async supportedCommands(){try{return cr().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return[{value:"gpt-4o",displayName:"GPT-4o",description:"OpenAI flagship multimodal"},{value:"gpt-4o-mini",displayName:"GPT-4o mini",description:"Fast/cheap GPT-4o"},{value:"gpt-4.1",displayName:"GPT-4.1",description:"Long-context GPT-4"},{value:"gpt-4.1-mini",displayName:"GPT-4.1 mini",description:"Fast 4.1 variant"},{value:"o1",displayName:"o1",description:"Reasoning model"},{value:"o1-mini",displayName:"o1 mini",description:"Fast reasoning"},{value:"o3-mini",displayName:"o3 mini",description:"Newer reasoning, faster"}]}async supportedAgents(){return[]}async getContextUsage(){let t=this.lastUsage,n=Ot(this.currentModel),r;if(t&&n>0){let i=ti(t);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=Ju(t);return{tools:[],agents:[],isAutoCompactEnabled:!1,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.opts.mcpManager?this.opts.mcpManager.getServerStates().map(t=>({name:t.serverName,status:t.status})):[]}async accountInfo(){return{authSource:this.opts.auth.source}}async rewindFiles(t,n){return{canRewind:!1,error:`${Eh} provider does not support file checkpoint rewind yet.`}}close(){this.closed=!0;let t=this.abortController;t&&!t.signal.aborted?t.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.(),z(`\u{1F7E2} ${Eh}: closed`)}}});import KK from"openai";async function Mx(e){let{apiKey:t,baseURL:n,model:r,system:o,user:s,maxTokens:i=64,signal:a,clientFactory:l}=e,c=Do(t);if(c.apiKey===null)throw new Error("oneShotChatCompletion: no usable OpenAI auth (set OPENAI_API_KEY or pass apiKey)");let u={apiKey:c.apiKey};n!==void 0&&(u.baseURL=n);let d=l??GK,p=d?d(u):new KK(u),m=r.includes("/")?r.slice(r.lastIndexOf("/")+1):r,g=/^o[0-9]/.test(m)?{max_completion_tokens:i}:{max_tokens:i},b=(await p.chat.completions.create({model:r,...g,stream:!1,messages:[{role:"system",content:o},{role:"user",content:s}]},a?{signal:a}:void 0)).choices?.[0]?.message?.content;return typeof b=="string"?b.trim():""}var GK,Ox=_(()=>{"use strict";Ja();GK=null});import xh from"path";import{appendFileSync as qK,mkdirSync as zK}from"fs";import{dirname as JK}from"path";var Rh,$t,VK,Va=_(()=>{"use strict";G();Kc();zc();Oa();xa();mh();Ku();kn();an();Th();Ox();Tn();Br();Ja();Th();Rh="openai-compatible",$t=class{name=Rh;providerOpts;memoryStore;schemas;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_presenceSessionId=null;constructor(t={}){this.providerOpts=t,this.memoryStore=t.memoryStore??new at;let n=[...Zn];t.subagentExecutor&&n.push(To),t.skillExecutor&&n.push(xo),t.composeExecutor&&n.push(Ro),t.readOnlyMemory===!0?n.push(Bs):n.push(...Ir),n.push(En);for(let r of t.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);this.schemas=n}query(t){let n=t.config,r=n.permissionMode??"default";this._currentPermissionMode=r,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let o,s=typeof n.model=="string"?n.model:String(n.model),i=_a({surface:this.providerOpts.surface??"cli",cwd:n.cwd??process.cwd(),modelName:s,providerName:Rh,permissionMode:r,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>o instanceof _t?o.toolDefs.map(m=>m.name):[],getMcpTools:()=>this.providerOpts.mcpManager?.getMcpTools()??[],getSubagents:()=>this.providerOpts.subagentExecutor?this.providerOpts.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});o=this.providerOpts.tools?Ia(this.providerOpts.tools,i):this.buildDispatcher(r,{...n.cwd!==void 0?{cwd:n.cwd}:{},...this._sharedReadRoots!==void 0?{readRoots:this._sharedReadRoots}:{},...this._sharedWriteRoots!==void 0?{writeRoots:this._sharedWriteRoots}:{},...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},runtimeStateSource:i,...n.isSkillDispatch?{isSkillDispatch:!0}:{},...n.isNonInteractive?{isNonInteractive:!0}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{},...n.planExitControls!==void 0?{planExitControls:n.planExitControls}:{}});let a={},l=n.openaiBaseUrl??this.providerOpts.baseURL;if(l!==void 0&&(a.baseURL=l),a.toolDispatcher=o,a.onPermissionMode=m=>{this._currentPermissionMode=m},this.providerOpts.mcpManager!==void 0&&(a.mcpManager=this.providerOpts.mcpManager),(n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let m=n.sessionId,g=i.getWorkspace();Pa({sessionId:m,surface:this.providerOpts.surface??"cli",actor:An(n.depth),cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:Rh,name:s},workspace:g,pid:process.pid}),process.once("exit",()=>{er(m)}),process.once("SIGINT",()=>{er(m),process.exit(130)}),process.once("SIGTERM",()=>{er(m),process.exit(143)})}let u=Us({cwd:n.cwd??process.cwd(),...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:i.getWorkspace()}),d=typeof n.systemPrompt=="string"?n.systemPrompt:void 0,p={...n,systemPrompt:d!==void 0?`${d}
|
|
1127
1127
|
|
|
1128
1128
|
${u}`:u};return Px(p,t.prompt,a)}buildDispatcher(t,n){let r=Uu(t,n.cwd),o=Aa(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[u,d]of o)this.providerOpts.readOnlyMemory===!0&&u!=="memory_search"||r.set(u,d);n.runtimeStateSource&&r.set("get_runtime_state",js(n.runtimeStateSource));for(let u of this.providerOpts.customTools??[])r.has(u.schema.name)||r.set(u.schema.name,u.handler);let s=t==="plan"?n.planExitControls:void 0;s&&r.set($o,Wu(s));let i=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[u,d]of this.providerOpts.mcpManager.getMcpHandlers())r.set(u,d);let a=n.isSkillDispatch?this.schemas.filter(u=>u.name!=="ask_question"&&u.name!=="terminal_font_size"):n.isNonInteractive?this.schemas.filter(u=>u.name!=="ask_question"):this.schemas,l={handlers:r,schemas:[...a,...i,...s?[Hu]:[]],hookRegistry:Wc(n.hookRegistry,this.providerOpts.hookRegistry)},c=qc(this.providerOpts.mcpManager?Gc(this.providerOpts.permissions,this.providerOpts.mcpManager.getMcpToolWireNames()):this.providerOpts.permissions,(this.providerOpts.customTools??[]).map(u=>u.schema.name));return c!==void 0&&(l.permissions=c),this.providerOpts.subagentExecutor!==void 0&&(l.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(l.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(l.composeExecutor=this.providerOpts.composeExecutor),n.cwd!==void 0&&(l.cwd=n.cwd),n.readRoots!==void 0&&(l.readRoots=n.readRoots),n.writeRoots!==void 0&&(l.writeRoots=n.writeRoots),n.sessionId!==void 0&&(l.sessionId=n.sessionId),n.parentSessionId!==void 0&&(l.parentSessionId=n.parentSessionId),n.traceWriter!==void 0&&(l.traceWriter=n.traceWriter),this.providerOpts.readOnlyBash===!0&&(l.readOnlyBash=!0),l.allowAll=wn(t),new _t(l)}ensureSharedRoots(t){if(!this._sharedReadRoots){let n=t?[t]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),t&&!this._initialResolveBase&&(this._initialResolveBase=t)}}addReadRoot(t,n="slash",r){this.ensureSharedRoots();let o=xh.resolve(t);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this.appendProviderAuditLog({action:"grant-read",path:o,source:n,sessionId:r})}addWriteRoot(t,n="slash",r){this.ensureSharedRoots();let o=xh.resolve(t);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this._sharedWriteRoots.includes(o)||this._sharedWriteRoots.push(o),this.appendProviderAuditLog({action:"grant-write",path:o,source:n,sessionId:r})}revokeRoot(t,n="slash",r){if(!this._sharedReadRoots)return;let o=xh.resolve(t);if(this._initialResolveBase&&o===this._initialResolveBase)return;let s=this._sharedReadRoots.indexOf(o);if(s!==-1&&this._sharedReadRoots.splice(s,1),this._sharedWriteRoots){let i=this._sharedWriteRoots.indexOf(o);i!==-1&&this._sharedWriteRoots.splice(i,1)}this.appendProviderAuditLog({action:"revoke",path:o,source:n,sessionId:r})}getGrants(){return{resolveBase:this._initialResolveBase,readRoots:this._sharedReadRoots?.slice()??[],writeRoots:this._sharedWriteRoots?.slice()??[],allowAll:wn(this._currentPermissionMode)}}appendProviderAuditLog(t){try{let n=Es();zK(JK(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:t.sessionId??null,action:t.action,path:t.path,source:t.source});qK(n,r+`
|
|
1129
1129
|
`)}catch{}}close(){this.memoryStore.close()}async complete(t){let n={model:t.model??"gpt-4o-mini",system:t.system,user:t.user,maxTokens:t.maxTokens??64};t.apiKey!==void 0&&(n.apiKey=t.apiKey);let r=t.baseUrl??this.providerOpts.baseURL;return r!==void 0&&(n.baseURL=r),t.signal&&(n.signal=t.signal),Mx(n)}},VK=new $t});function jr(e,t){if(e.has(t))return!0;let n=t.charAt(0).toUpperCase()+t.slice(1);return n!==t&&e.has(n)}function _n(e){return e.startsWith("mcp__")||e.startsWith("MCP__")?"mcp":jr(YK,e)?"read":jr(XK,e)?"write":jr(ZK,e)?"shell":jr(Hr,e)?"subagent":jr(Ya,e)?"skill":jr(Xa,e)?"dag":jr(QK,e)?"web":eG.has(e)?"browser":jr(tG,e)?"planning":nG.has(e)?"schedule":"other"}function Ch(e){return rG[e]}var YK,XK,ZK,Hr,Ya,Xa,Ye,QK,eG,tG,nG,$x,rG,Za=_(()=>{"use strict";dg();YK=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search"]),XK=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","memory_update","procedure_write","terminal_font_size","config_set"]),ZK=new Set(["Bash","BashOutput","KillBash","bash"]),Hr=new Set(["Agent","Task","agent"]),Ya=new Set(["Skill","skill"]),Xa=new Set(["Compose","compose"]),Ye=new Set([...Hr,...Xa,...Ya]),QK=new Set(["WebFetch","WebSearch","send_telegram","web_scrape"]),eG=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),tG=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),nG=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);$x=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search",...pt];rG={subagent:"subagent",skill:"skill",dag:"dag"}});function Zu(e){let t=oG(e);return t!==void 0?t:sG(e)}function oG(e){let t=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=t.exec(e))!==null;)n=r[1];if(n)return Dx(n.trim())}function sG(e){for(let t=e.length-1;t>=0;t--){if(e[t]!=="}")continue;let n=iG(e,t);if(n===-1)continue;let r=e.slice(n,t+1),o=Dx(r);if(o!==void 0)return o}}function iG(e,t){let n=0,r=!1,o=!1;for(let s=t;s>=0;s--){let i=e[s];if(o){o=!1;continue}if(r){if(i==="\\"){o=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="}")n++;else if(i==="{"&&(n--,n===0))return s}return-1}function Dx(e){try{return JSON.parse(e)}catch{return}}var Ah=_(()=>{"use strict"});import{z as Wr}from"zod";function uG(e){let t=/```(?:json)?\s*([\s\S]*?)```/gi,n;for(;(n=t.exec(e))!==null;){let r=n[1];if(r===void 0)continue;let o=Lx(r.trim());if(Fx(o))return o}for(let r=0;r<e.length;r++){if(e[r]!=="{"||dG(e,r))continue;let o=pG(e,r);if(o===-1)continue;let s=e.slice(r,o+1),i=Lx(s);if(Fx(i))return i;r=o}}function dG(e,t){for(let n=t-1;n>=0;n--){let r=e[n];if(!(r===" "||r===" "||r===`
|
|
@@ -1140,7 +1140,7 @@ ${u}`:u};return Px(p,t.prompt,a)}buildDispatcher(t,n){let r=Uu(t,n.cwd),o=Aa(thi
|
|
|
1140
1140
|
`)}finally{h&&await h.close().catch(()=>{})}}async function d(){let h=await e.readMeta(t);if(!h||!(h.status!=="running"))return!1;try{let y=await nt.stat(r);return i>=y.size}catch{return!0}}if(o)yield*u();else try{i=(await nt.stat(r)).size}catch{}if(await d())return;let p=null,m=null,g=()=>new Promise(h=>{m=h;let b=setTimeout(()=>{m=null,h()},c);p=()=>{clearTimeout(b),m=null,h()}});try{l=ni.watch(s,{persistent:!1},()=>{p?.(),p=null})}catch{}try{for(;await g(),yield*u(),!await d(););}finally{m?.(),l?.close()}}}});import{EventEmitter as fG}from"node:events";import*as Kr from"node:fs/promises";import*as Gx from"node:path";import{createHash as gG}from"node:crypto";function _h(e){Be(e).catch(()=>{})}var hG,Wx,Kx,yG,el,nd,Ih=_(()=>{"use strict";zt();_e();je();td();G();Yn();hG=300*1e3,Wx=4096;Kx=5e3,yG=10,el=class extends Error{constructor(t,n){super(`Background job cap reached (${t}/${n} running). Wait for existing jobs to finish or cancel them before spawning more.`),this.name="BackgroundJobCapError"}},nd=class extends fG{jobs=new Map;counter=Math.floor(Math.random()*65536);traceWriter;maxConcurrentJobs;constructor(t={}){super(),this.traceWriter=t.traceWriter,this.maxConcurrentJobs=t.maxConcurrentJobs??yG,setTimeout(()=>this._sweepOldJobs().catch(r=>process.stderr.write(`[afk] bg sweep error: ${String(r)}
|
|
1141
1141
|
`)),5e3).unref()}register(t){let{job:n,jobId:r,writer:o,metaRecord:s}=this.createJobEntry(t);return t.handle.runInBackground(t.prompt,i=>{this.markTerminal(r,i,o,s)},i=>{o.write(i),i.type==="chunk"&&i.chunk.type==="content"&&this.appendTranscript(r,i.chunk.content)}),this.snapshot(n)}adoptRunning(t){let{job:n,jobId:r,writer:o,metaRecord:s}=this.createJobEntry(t);return t.runPromise.then(i=>{this.markTerminal(r,i,o,s)}).catch(i=>{z("adoptRunning: unexpected rejection from in-flight runPromise",i),this.markTerminal(r,Qu(t.handle.id,"failed",i,Qa()),o,s)}),this.snapshot(n)}createJobEntry(t){let n=[...this.jobs.values()].filter(d=>d.status==="running").length;if(n>=this.maxConcurrentJobs)throw new el(n,this.maxConcurrentJobs);let r=this.nextJobId(),o=t.prompt.trim().slice(0,80),s=Date.now(),i,a=new Promise(d=>{i=d}),l={jobId:r,subagentId:t.handle.id,label:o,model:t.model,startedAt:s,status:"running",handle:t.handle,joiners:[],terminalSettled:a,settle:i,transcriptTail:"",parentSessionId:t.parentSessionId};this.jobs.set(r,l),Ps(this.traceWriter,{transition:"started",jobId:r,subagentId:t.handle.id,label:o,model:t.model}),this.emit("started",this.snapshot(l));let c=new ed(r),u={jobId:r,subagentId:t.handle.id,label:o,promptHash:gG("sha256").update(t.prompt).digest("hex"),model:t.model,startedAt:s,status:"running",...t.parentSessionId!==void 0?{parentSessionId:t.parentSessionId}:{},schemaVersion:1};return c.writeMeta(u),{job:l,jobId:r,writer:c,metaRecord:u}}get(t){let n=this.jobs.get(t);return n?this.snapshot(n):void 0}list(){return[...this.jobs.values()].map(t=>this.snapshot(t))}async join(t){let n=this.jobs.get(t);if(!n)throw new Error(`Background job not found: "${t}". Completed and cancelled jobs are evicted from the registry ~5 minutes after they settle. If the jobId looks correct, the job may have already been evicted.`);let r=await n.terminalSettled;return Ps(this.traceWriter,{transition:"joined",jobId:t,subagentId:n.subagentId,jobStatus:n.status}),this.emit("joined",this.snapshot(n)),r}async cancelJob(t){let n=this.jobs.get(t);return!n||n.status!=="running"?!1:(n.cancelSource="explicit",await n.handle.cancel(),!0)}async cancelAll(){let t=[...this.jobs.values()].filter(n=>n.status==="running");for(let n of t)n.cancelSource="cascade";await Promise.allSettled(t.map(n=>n.handle.cancel())),await Promise.allSettled(t.map(n=>{let r=new Promise(o=>setTimeout(()=>{console.warn(`[BackgroundAgentRegistry] cancelAll: job ${n.jobId} did not settle within ${Kx}ms \u2014 continuing teardown`),o()},Kx).unref());return Promise.race([n.terminalSettled,r])}))}appendTranscript(t,n){let r=this.jobs.get(t);if(!r)return;let o=r.transcriptTail+n;o.length<=Wx?r.transcriptTail=o:r.transcriptTail=o.slice(o.length-Wx)}getTranscript(t){return this.jobs.get(t)?.transcriptTail}nextJobId(){return this.counter+=1,`bg-${Date.now().toString(36)}-${this.counter}`}markTerminal(t,n,r,o){let s=this.jobs.get(t);if(!s||s.status!=="running")return;s.result=n,s.endedAt=Date.now();let i=s.endedAt-s.startedAt;if(s.status=this.statusFromResult(n.status),s.status==="completed"){let l=n.message?.content,c=typeof l=="string"?l:l!==void 0?JSON.stringify(l):"";Ps(this.traceWriter,{transition:"completed",jobId:t,subagentId:s.subagentId,durationMs:i,outputBytes:Buffer.byteLength(c,"utf8")}),_h({event:"subagent.completed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i,content_chars:c.length}),this.emit("settled",this.snapshot(s))}else if(s.status==="failed"){let l=n.error;Ps(this.traceWriter,{transition:"failed",jobId:t,subagentId:s.subagentId,durationMs:i,errorClass:l?.name??"Error",errorMessage:l?.message??"unknown"}),_h({event:"subagent.failed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i,error_message:l?.message}),this.emit("settled",this.snapshot(s))}else Ps(this.traceWriter,{transition:"cancelled",jobId:t,subagentId:s.subagentId,source:s.cancelSource??"explicit"}),_h({event:"subagent.failed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i}),this.emit("settled",this.snapshot(s));if(s.settle(n),r&&o){let l=s.status,c=s.endedAt;r.writeMeta({...o,status:l,...c!==void 0?{endedAt:c}:{}}).then(()=>r.close())}setTimeout(()=>{this.jobs.delete(t)},hG).unref()}async _sweepOldJobs(){let n=ba(),r;try{r=await Kr.readdir(n)}catch{return}for(let o of r){let s=yo(o),i=Gx.join(s,"meta.json");try{if(!(await Kr.lstat(s)).isDirectory()){process.stderr.write(`[afk] bg sweep: skipping non-directory entry ${o}
|
|
1142
1142
|
`);continue}let l=await Kr.readFile(i,"utf8"),c=JSON.parse(l);if(c.status==="running"||c.endedAt===void 0||Date.now()-c.endedAt<6048e5)continue;await Kr.rm(s,{recursive:!0,force:!0})}catch(a){if(a.code==="ENOENT")continue;process.stderr.write(`[afk] bg sweep: error evicting ${o}: ${String(a)}
|
|
1143
|
-
`)}}}statusFromResult(t){return t==="succeeded"?"completed":t==="failed"?"failed":t==="cancelled"?"cancelled":"failed"}snapshot(t){return{jobId:t.jobId,subagentId:t.subagentId,label:t.label,model:t.model,startedAt:t.startedAt,status:t.status,...t.result!==void 0?{result:t.result}:{},...t.endedAt!==void 0?{endedAt:t.endedAt}:{}}}}});function bG(e){return typeof e=="string"&&e.startsWith("sk-ant-")}function tl(e){let{childModel:t,resolved:n,parentApiKey:r}=e;return n!==void 0&&n.length>0||re(t)==="openai-compatible"?n:bG(r)?r:n}var Ph=_(()=>{"use strict";tt()});import{isAbsolute as wG}from"node:path";function SG(e){if(typeof e!="object"||e===null)throw new Error("Agent tool input must be an object");let t=e,n=t.prompt;if(typeof n!="string")throw new Error('Agent tool input must have a "prompt" field of type string');if(n.trim().length===0)throw new Error("Agent tool prompt cannot be empty");let r,o=t.model;if(o!==void 0){if(typeof o!="string")throw new Error("Agent tool model must be a string");r=o}let s=10,i=t.max_turns;if(i!==void 0){if(typeof i!="number")throw new Error("Agent tool max_turns must be a number");s=Math.max(1,Math.min(50,Math.floor(i)))}let a="agent-tool",l=t.id_prefix;if(l!==void 0){if(typeof l!="string")throw new Error("Agent tool id_prefix must be a string");a=l}let c="foreground",u=t.mode;if(u!==void 0){if(u!=="foreground"&&u!=="background")throw new Error(`Agent tool mode must be "foreground" or "background", got: ${JSON.stringify(u)}`);c=u}let d,p=t.cwd;if(p!==void 0){if(typeof p!="string")throw new Error(`Agent tool cwd must be a string, got: ${JSON.stringify(p)}`);if(p.length===0)throw new Error("Agent tool cwd must be a non-empty string");if(!wG(p))throw new Error(`Agent tool cwd must be an absolute path, got: ${JSON.stringify(p)}`);if(p.split(/[/\\]/).includes(".."))throw new Error(`Agent tool cwd must not contain '..' segments, got: ${JSON.stringify(p)}`);d=p}return{prompt:n,model:r,max_turns:s,id_prefix:a,mode:c,...d!==void 0?{cwd:d}:{}}}function rd(e){try{return Be(e).catch(()=>{})}catch{return Promise.resolve()}}function ri(e,t=240){return e.length<=t?e:e.slice(0,t)+"\u2026"}function zx(e){if(e!=null){if(typeof e=="string")return e.length;try{return JSON.stringify(e).length}catch{return}}}function kG(e){if(e==null)return;let t=zx(e);return t!==void 0&&t>vG?{truncated:!0,chars:t}:e}function EG(e){let t={status:e.status,error:ri(e.errorMessage,qx),subagent_id:e.subagentId};e.schemaErrorMessage&&(t.schemaError=ri(e.schemaErrorMessage,qx));let n=kG(e.partialOutput);return n!==void 0&&(t.partialOutput=n),t}var vG,qx,Pn,nl=_(()=>{"use strict";Xe();Ih();tt();Ph();Ks();Gr();Yn();_e();Ao();Br();Gr();vG=4096,qx=1024;Pn=class e{constructor(t){this.ctx=t;this.currentCwd=t.cwd}ctx;currentCwd;setCwd(t){this.currentCwd=t,this.ctx.subagentManager.setCwd(t)}promotionTriggers=new Map;hasPromotableForeground(){return this.ctx.backgroundRegistry!==void 0&&this.promotionTriggers.size>0}async promoteActiveForeground(){let t=[...this.promotionTriggers.values()];return t.forEach(r=>r.fire()),(await Promise.all(t.map(r=>r.ready))).filter(r=>r!==null)}getSubagentsLite(){let t=this.ctx.subagentManager.list().map(r=>({id:r.id,status:r.status})),n=this.ctx.backgroundRegistry?this.ctx.backgroundRegistry.list().map(r=>({jobId:r.jobId,status:r.status,startedAt:new Date(r.startedAt).toISOString(),label:r.label.length>0?r.label:null})):[];return{active:t,backgroundJobs:n}}async execute(t){if(t.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=SG(t.input)}catch(C){return{content:`Agent tool input validation failed: ${C instanceof Error?C.message:String(C)}`,isError:!0}}let r=this.ctx.depth,o=this.ctx.maxDepth??oi,s,i=this.ctx.surface!==void 0?{origin:Nr(this.ctx.surface),actor:An(r)}:{},a=n.model??this.ctx.defaultSubagentModel??"sonnet",l=re(a)==="openai-compatible",c=tl({childModel:a,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(a):or(a),parentApiKey:this.ctx.defaultConfig.apiKey}),u={model:a,apiKey:l?void 0:c,systemPrompt:this.ctx.defaultConfig.systemPrompt,baseUrl:l?void 0:this.ctx.defaultConfig.baseUrl,maxTurns:n.max_turns,depth:r+1,maxDepth:o,...n.cwd!==void 0?{cwd:n.cwd}:{}},d;if(this.ctx.childProviderFactory&&r<o){s=new se({parentAbortSignal:t.signal,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),d=Lo(t.signal);let C=new e({subagentManager:s,parentSession:d,defaultConfig:this.ctx.defaultConfig,...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:r+1,maxDepth:o,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash?{readOnlyBash:!0}:{}}),R=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,t.signal):void 0;u.provider=this.ctx.childProviderFactory({childExecutor:C,...R!==void 0?{childSkillExecutor:R}:{},...u.model!==void 0?{model:u.model}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash?{readOnlyBash:!0}:{}})}let p;try{p=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:t.id,config:u,idPrefix:n.id_prefix,agentType:n.id_prefix&&n.id_prefix!=="agent-tool"?tr(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":tr(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:!0}),d!==void 0&&(d.sessionId=p.id)}catch(C){let R=C instanceof Error?C.message:String(C);return rd({...i,event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:ri(R),depth:r}),{content:`Failed to fork subagent: ${R}`,isError:!0}}if(n.mode==="background"){let C=this.ctx.backgroundRegistry;if(!C)return await p.teardown().catch($=>z("subagent-executor: handle teardown failed: "+($ instanceof Error?$.message:String($)))),{content:'Background mode is not available in this session \u2014 no BackgroundAgentRegistry is wired. Re-issue the call with mode="foreground" or run inside `afk interactive`.',isError:!0};let R;try{R=C.register({handle:p,prompt:n.prompt,model:u.model??"sonnet",parentSessionId:this.ctx.parentSession.sessionId})}catch($){if($ instanceof el)return await p.teardown().catch(A=>z("subagent-executor: handle teardown failed after cap error: "+(A instanceof Error?A.message:String(A)))),{content:$.message,isError:!0};throw $}let k={status:"running",jobId:R.jobId,subagentId:R.subagentId,label:R.label,message:`Background subagent started (jobId=${R.jobId}). It is running detached and its result will NOT auto-inject into this context. Retrieve it later via /bgsub:join ${R.jobId} or ask the user to join.`};return{content:JSON.stringify(k)}}let m=()=>{p.cancel()};t.signal.addEventListener("abort",m,{once:!0});let g=Date.now(),h=this.ctx.parentSession.sessionId,b=!1,y,S=new Promise(C=>{y=C}),w,T=new Promise(C=>{w=C});this.promotionTriggers.set(p.id,{fire:y,ready:T});let x=p.runToResult(n.prompt);try{let C=await Promise.race([x.then(P=>({kind:"result",result:P})),S.then(()=>({kind:"promote"}))]);if(C.kind==="promote"){let P=this.ctx.backgroundRegistry;if(P)try{let F=P.adoptRunning({handle:p,runPromise:x,prompt:n.prompt,model:u.model??"sonnet",parentSessionId:h});return b=!0,t.signal.removeEventListener("abort",m),w({jobId:F.jobId,label:F.label}),{content:JSON.stringify({status:"running",jobId:F.jobId,subagentId:F.subagentId,label:F.label,message:`Subagent backgrounded by user (jobId=${F.jobId}). It keeps running detached and its result will NOT auto-inject into this context. Retrieve it via /bgsub:join ${F.jobId}.`})}}catch(F){z("subagent-executor: promotion failed, staying foreground: "+(F instanceof Error?F.message:String(F))),w(null)}else w(null)}let R=C.kind==="result"?C.result:await x;if(R.status==="succeeded"&&R.message){let P=R.message.content,F=typeof P=="string"?P:JSON.stringify(P),D=R.trace;return rd({...i,event:"subagent.completed",subagent_id:p.id,parent_session_id:h,status:R.status,duration_ms:Date.now()-g,content_chars:F.length,depth:r,tool_call_count:D?.toolCalls.length,thinking_present:D?.thinkingPresent,tool_names:D?.toolCalls.length?JSON.stringify([...new Set(D.toolCalls.map(N=>N.name))]):void 0}),{content:F}}let k=R.error?.message??"Subagent failed with no output",$=R.trace;rd({...i,event:"subagent.failed",subagent_id:p.id,id_prefix:n.id_prefix,parent_session_id:h,status:R.status,duration_ms:Date.now()-g,error_message:ri(k),schema_error:R.schemaError?ri(R.schemaError.message):void 0,partial_output_chars:zx(R.partialOutput),depth:r,tool_call_count:$?.toolCalls.length,thinking_present:$?.thinkingPresent,tool_names:$?.toolCalls.length?JSON.stringify([...new Set($.toolCalls.map(P=>P.name))]):void 0});let A=EG({status:R.status,errorMessage:k,schemaErrorMessage:R.schemaError?.message,partialOutput:R.partialOutput,subagentId:p.id});return{content:JSON.stringify(A),isError:!0}}catch(C){let R=C instanceof Error?C.message:String(C);throw rd({...i,event:"subagent.failed",subagent_id:p.id,id_prefix:n.id_prefix,parent_session_id:h,status:"failed",duration_ms:Date.now()-g,error_message:ri(R),depth:r}),C}finally{this.promotionTriggers.delete(p.id),w(null),b||(t.signal.removeEventListener("abort",m),await s?.teardownAll(),await p.teardown())}}}});function od(e,t){return`Skill tool not available at nesting depth ${e} (max ${t}). ${si}`}var si,Mh=_(()=>{"use strict";si="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});function Vx(e){Jx.add(e)}function Yx(e){return Jx.has(e)}var Jx,Oh=_(()=>{"use strict";Jx=new Set});function Xx(e){$h.add(e)}function Zx(e){$h.delete(e)}function Qx(e){Dh.add(e)}function eR(e){Dh.delete(e)}function tR(e){for(let t of $h)t(e)}function nR(e){for(let t of Dh)t(e)}var $h,Dh,Lh=_(()=>{"use strict";$h=new Set,Dh=new Set});function rR(e){return TG.has(e)}function RG(e,t=xG){return e.length<=t?e:e.slice(0,t)+"\u2026"}function CG(e){if(typeof e!="object"||e===null)return;let t=e.name;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}function AG(e){if(typeof e!="object"||e===null)throw new Error("Skill tool input must be an object");let t=e,n=t.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=t.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var TG,xG,Mn,rl=_(()=>{"use strict";bt();Xe();Ur();Gr();nl();Mh();Ph();Ks();Xn();tn();Yn();Oh();Lh();_e();Br();TG=new Set(["ask-gate","fanout-pace","right-size-delegation","premise-gate","intent-lock","long-bash-gate","exploration-gate","irreversible-action-gate","safe-destruct","plan-probe"]);xG=240;Mn=class{constructor(t){this.ctx=t;this.currentCwd=t.cwd}ctx;pluginBodies=null;currentCwd;setCwd(t){this.currentCwd=t}sessionIdentity(){return this.ctx.surface!==void 0?{origin:Nr(this.ctx.surface),actor:An(this.ctx.depth)}:{}}async execute(t){if(t.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??oi;if(n>=r){let l=CG(t.input);return Be({...this.sessionIdentity(),event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:l}).catch(()=>{}),{content:od(n,r),isError:!0}}let o;try{o=AG(t.input)}catch(l){return{content:`Skill tool input validation failed: ${l instanceof Error?l.message:String(l)}`,isError:!0}}try{let l=Ke(o.name);return await this.executeRegistrySkill(l,o.arguments,t)}catch{}let s=this.getPluginSkillBody(o.name);if(s){if(s.context==="fork"){let c=s.readOnly===!0||Fh.has(o.name);return await this.executePluginSkill(o.name,s.body,s.pluginPath,o.arguments,t,c,s.allowedTools)}let l=s.body.replace(/\$\{?PLUGIN_ROOT\}?/g,()=>s.pluginPath);return this.executeLoadedPluginSkill(o.name,l,o.arguments,t)}let a=cr(this.ctx.pluginConfigs).map(l=>l.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${a||"(none)"}`,isError:!0}}async executeRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(t.context==="fork")return this.executeForkedRegistrySkill(t,n,r);if(t.context==="load")return this.executeLoadedRegistrySkill(t,n,r);let o=Yx(t.name);o&&nR(t.name);let s=this.ctx.depth??0;Be({...this.sessionIdentity(),event:"skill.dispatched",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...rR(t.name)?{is_gate:!0}:{},...t.model!==void 0?{model:t.model}:{}}).catch(()=>{});let i=Date.now(),a,l;try{l=await t.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel,callId:r.id,dispatchSkill:this.createDispatchSkillCallback(r)})}catch(u){a=u}finally{let u=Date.now()-i;o&&tR({skillName:t.name,durationMs:u,...a!==void 0?{isError:!0}:{}});let d=a!==void 0?a instanceof Error?a.message:String(a):void 0,p=a===void 0?typeof l=="string"?l.length:l!=null?JSON.stringify(l).length:0:void 0;Be({...this.sessionIdentity(),event:"skill.completed",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,status:a!==void 0?"failed":"succeeded",duration_ms:u,depth:s,...p!==void 0?{content_chars:p}:{},...d!==void 0?{error_message:RG(d)}:{},...t.model!==void 0?{model:t.model}:{}}).catch(()=>{})}return a!==void 0?{content:`Skill execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}:{content:typeof l=="string"?l:l!=null?JSON.stringify(l):"Skill completed successfully."}}buildForkedChildConfig(t,n,r=!1,o){let s=this.ctx.depth??0,i=this.ctx.maxDepth??oi,a={...t},l=r&&o!==void 0?o.filter(m=>sd.includes(m)):r?[...sd]:o,c=r;if(!this.ctx.childProviderFactory||s>=i)return r?a.provider=oR(a.model):l!==void 0&&(a.provider=sR(l,a.model)),{childConfig:a,childManager:void 0};let u=new se({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),d=new Pn({subagentManager:u,parentSession:Lo(n),defaultConfig:{model:a.model,apiKey:this.ctx.apiKey,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{}},...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:s+1,maxDepth:i,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{},...this.ctx.backgroundRegistry!==void 0?{backgroundRegistry:this.ctx.backgroundRegistry}:{},...l!==void 0?{allowedTools:l}:{},...c?{readOnlyBash:!0}:{}}),p=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(s+1,i,n):void 0;return a.provider=this.ctx.childProviderFactory({childExecutor:d,...p!==void 0?{childSkillExecutor:p}:{},...a.model!==void 0?{model:a.model}:{},...l!==void 0?{allowedTools:l}:{},...c?{readOnlyBash:!0}:{}}),{childConfig:a,childManager:u}}async executeForkedRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o=t.readOnly===!0||Fh.has(t.name),s;try{if(s=He(t.name)["system.md"],!s)return{content:`Skill "${t.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(p){return{content:`Failed to load skill prompts: ${p instanceof Error?p.message:String(p)}`,isError:!0}}let i=t.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",a=tl({childModel:i,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(i):or(i),parentApiKey:this.ctx.apiKey}),l=new se({parentAbortSignal:r.signal,apiKey:a,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:Ht(),...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),{childConfig:c,childManager:u}=this.buildForkedChildConfig({model:i,systemPrompt:s,isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},r.signal,o),d;try{d=await l.forkSubagent({parent:this.ctx.parentSession,config:c,idPrefix:`skill-fork-${t.name}`,parentId:r.id,agentType:t.name});let p=n&&n.length>0?n:`Run the ${t.name} skill now, following the instructions in your system prompt.`,m=await d.runToResult(p);return m.status==="succeeded"&&m.message?{content:m.message.content}:m.status==="cancelled"&&typeof m.partialOutput=="string"&&m.partialOutput.length>0?{content:`[skill cancelled mid-flight \u2014 partial output preserved below]
|
|
1143
|
+
`)}}}statusFromResult(t){return t==="succeeded"?"completed":t==="failed"?"failed":t==="cancelled"?"cancelled":"failed"}snapshot(t){return{jobId:t.jobId,subagentId:t.subagentId,label:t.label,model:t.model,startedAt:t.startedAt,status:t.status,...t.result!==void 0?{result:t.result}:{},...t.endedAt!==void 0?{endedAt:t.endedAt}:{}}}}});function bG(e){return typeof e=="string"&&e.startsWith("sk-ant-")}function tl(e){let{childModel:t,resolved:n,parentApiKey:r}=e;return n!==void 0&&n.length>0||re(t)==="openai-compatible"?n:bG(r)?r:n}var Ph=_(()=>{"use strict";tt()});import{isAbsolute as wG}from"node:path";function SG(e){if(typeof e!="object"||e===null)throw new Error("Agent tool input must be an object");let t=e,n=t.prompt;if(typeof n!="string")throw new Error('Agent tool input must have a "prompt" field of type string');if(n.trim().length===0)throw new Error("Agent tool prompt cannot be empty");let r,o=t.model;if(o!==void 0){if(typeof o!="string")throw new Error("Agent tool model must be a string");r=o}let s=10,i=t.max_turns;if(i!==void 0){if(typeof i!="number")throw new Error("Agent tool max_turns must be a number");s=Math.max(1,Math.min(50,Math.floor(i)))}let a="agent-tool",l=t.id_prefix;if(l!==void 0){if(typeof l!="string")throw new Error("Agent tool id_prefix must be a string");a=l}let c="foreground",u=t.mode;if(u!==void 0){if(u!=="foreground"&&u!=="background")throw new Error(`Agent tool mode must be "foreground" or "background", got: ${JSON.stringify(u)}`);c=u}let d,p=t.cwd;if(p!==void 0){if(typeof p!="string")throw new Error(`Agent tool cwd must be a string, got: ${JSON.stringify(p)}`);if(p.length===0)throw new Error("Agent tool cwd must be a non-empty string");if(!wG(p))throw new Error(`Agent tool cwd must be an absolute path, got: ${JSON.stringify(p)}`);if(p.split(/[/\\]/).includes(".."))throw new Error(`Agent tool cwd must not contain '..' segments, got: ${JSON.stringify(p)}`);d=p}return{prompt:n,model:r,max_turns:s,id_prefix:a,mode:c,...d!==void 0?{cwd:d}:{}}}function rd(e){try{return Be(e).catch(()=>{})}catch{return Promise.resolve()}}function ri(e,t=240){return e.length<=t?e:e.slice(0,t)+"\u2026"}function zx(e){if(e!=null){if(typeof e=="string")return e.length;try{return JSON.stringify(e).length}catch{return}}}function kG(e){if(e==null)return;let t=zx(e);return t!==void 0&&t>vG?{truncated:!0,chars:t}:e}function EG(e){let t={status:e.status,error:ri(e.errorMessage,qx),subagent_id:e.subagentId};e.schemaErrorMessage&&(t.schemaError=ri(e.schemaErrorMessage,qx));let n=kG(e.partialOutput);return n!==void 0&&(t.partialOutput=n),t}var vG,qx,Pn,nl=_(()=>{"use strict";Xe();Ih();tt();Ph();Ks();Gr();Yn();_e();Ao();Br();Gr();vG=4096,qx=1024;Pn=class e{constructor(t){this.ctx=t;this.currentCwd=t.cwd}ctx;currentCwd;setCwd(t){this.currentCwd=t,this.ctx.subagentManager.setCwd(t)}promotionTriggers=new Map;hasPromotableForeground(){return this.ctx.backgroundRegistry!==void 0&&this.promotionTriggers.size>0}async promoteActiveForeground(){let t=[...this.promotionTriggers.values()];return t.forEach(r=>r.fire()),(await Promise.all(t.map(r=>r.ready))).filter(r=>r!==null)}getSubagentsLite(){let t=this.ctx.subagentManager.list().map(r=>({id:r.id,status:r.status})),n=this.ctx.backgroundRegistry?this.ctx.backgroundRegistry.list().map(r=>({jobId:r.jobId,status:r.status,startedAt:new Date(r.startedAt).toISOString(),label:r.label.length>0?r.label:null})):[];return{active:t,backgroundJobs:n}}async execute(t){if(t.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=SG(t.input)}catch(C){return{content:`Agent tool input validation failed: ${C instanceof Error?C.message:String(C)}`,isError:!0}}let r=this.ctx.depth,o=this.ctx.maxDepth??oi,s,i=this.ctx.surface!==void 0?{origin:Nr(this.ctx.surface),actor:An(r)}:{},a=n.model??this.ctx.defaultSubagentModel??"sonnet",l=re(a)==="openai-compatible",c=tl({childModel:a,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(a):or(a),parentApiKey:this.ctx.defaultConfig.apiKey}),u={model:a,apiKey:l?void 0:c,systemPrompt:this.ctx.defaultConfig.systemPrompt,baseUrl:l?void 0:this.ctx.defaultConfig.baseUrl,maxTurns:n.max_turns,depth:r+1,maxDepth:o,...n.cwd!==void 0?{cwd:n.cwd}:{}},d;if(this.ctx.childProviderFactory&&r<o){s=new se({parentAbortSignal:t.signal,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),d=Lo(t.signal);let C=new e({subagentManager:s,parentSession:d,defaultConfig:this.ctx.defaultConfig,...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:r+1,maxDepth:o,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash?{readOnlyBash:!0}:{}}),R=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,t.signal):void 0;u.provider=this.ctx.childProviderFactory({childExecutor:C,...R!==void 0?{childSkillExecutor:R}:{},...u.model!==void 0?{model:u.model}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash?{readOnlyBash:!0}:{}})}let p;try{p=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:t.id,config:u,idPrefix:n.id_prefix,agentType:n.id_prefix&&n.id_prefix!=="agent-tool"?tr(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":tr(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:!0}),d!==void 0&&(d.sessionId=p.id)}catch(C){let R=C instanceof Error?C.message:String(C);return rd({...i,event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:ri(R),depth:r}),{content:`Failed to fork subagent: ${R}`,isError:!0}}if(n.mode==="background"){let C=this.ctx.backgroundRegistry;if(!C)return await p.teardown().catch($=>z("subagent-executor: handle teardown failed: "+($ instanceof Error?$.message:String($)))),{content:'Background mode is not available in this session \u2014 no BackgroundAgentRegistry is wired. Re-issue the call with mode="foreground" or run inside `afk interactive`.',isError:!0};let R;try{R=C.register({handle:p,prompt:n.prompt,model:u.model??"sonnet",parentSessionId:this.ctx.parentSession.sessionId})}catch($){if($ instanceof el)return await p.teardown().catch(A=>z("subagent-executor: handle teardown failed after cap error: "+(A instanceof Error?A.message:String(A)))),{content:$.message,isError:!0};throw $}let k={status:"running",jobId:R.jobId,subagentId:R.subagentId,label:R.label,message:`Background subagent started (jobId=${R.jobId}). It is running detached and its result will NOT auto-inject into this context. Retrieve it later via /bgsub:join ${R.jobId} or ask the user to join.`};return{content:JSON.stringify(k)}}let m=()=>{p.cancel()};t.signal.addEventListener("abort",m,{once:!0});let g=Date.now(),h=this.ctx.parentSession.sessionId,b=!1,y,S=new Promise(C=>{y=C}),w,T=new Promise(C=>{w=C});this.promotionTriggers.set(p.id,{fire:y,ready:T});let x=p.runToResult(n.prompt);try{let C=await Promise.race([x.then(P=>({kind:"result",result:P})),S.then(()=>({kind:"promote"}))]);if(C.kind==="promote"){let P=this.ctx.backgroundRegistry;if(P)try{let F=P.adoptRunning({handle:p,runPromise:x,prompt:n.prompt,model:u.model??"sonnet",parentSessionId:h});return b=!0,t.signal.removeEventListener("abort",m),w({jobId:F.jobId,label:F.label}),{content:JSON.stringify({status:"running",jobId:F.jobId,subagentId:F.subagentId,label:F.label,message:`Subagent backgrounded by user (jobId=${F.jobId}). It keeps running detached and its result will NOT auto-inject into this context. Retrieve it via /bgsub:join ${F.jobId}.`})}}catch(F){z("subagent-executor: promotion failed, staying foreground: "+(F instanceof Error?F.message:String(F))),w(null)}else w(null)}let R=C.kind==="result"?C.result:await x;if(R.status==="succeeded"&&R.message){let P=R.message.content,F=typeof P=="string"?P:JSON.stringify(P),D=R.trace;return rd({...i,event:"subagent.completed",subagent_id:p.id,parent_session_id:h,status:R.status,duration_ms:Date.now()-g,content_chars:F.length,depth:r,tool_call_count:D?.toolCalls.length,thinking_present:D?.thinkingPresent,tool_names:D?.toolCalls.length?JSON.stringify([...new Set(D.toolCalls.map(N=>N.name))]):void 0}),{content:F}}let k=R.error?.message??"Subagent failed with no output",$=R.trace;rd({...i,event:"subagent.failed",subagent_id:p.id,id_prefix:n.id_prefix,parent_session_id:h,status:R.status,duration_ms:Date.now()-g,error_message:ri(k),schema_error:R.schemaError?ri(R.schemaError.message):void 0,partial_output_chars:zx(R.partialOutput),depth:r,tool_call_count:$?.toolCalls.length,thinking_present:$?.thinkingPresent,tool_names:$?.toolCalls.length?JSON.stringify([...new Set($.toolCalls.map(P=>P.name))]):void 0});let A=EG({status:R.status,errorMessage:k,schemaErrorMessage:R.schemaError?.message,partialOutput:R.partialOutput,subagentId:p.id});return{content:JSON.stringify(A),isError:!0}}catch(C){let R=C instanceof Error?C.message:String(C);throw rd({...i,event:"subagent.failed",subagent_id:p.id,id_prefix:n.id_prefix,parent_session_id:h,status:"failed",duration_ms:Date.now()-g,error_message:ri(R),depth:r}),C}finally{this.promotionTriggers.delete(p.id),w(null),b||(t.signal.removeEventListener("abort",m),await s?.teardownAll(),await p.teardown())}}}});function od(e,t){return`Skill tool not available at nesting depth ${e} (max ${t}). ${si}`}var si,Mh=_(()=>{"use strict";si="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});function Vx(e){Jx.add(e)}function Yx(e){return Jx.has(e)}var Jx,Oh=_(()=>{"use strict";Jx=new Set});function Xx(e){$h.add(e)}function Zx(e){$h.delete(e)}function Qx(e){Dh.add(e)}function eR(e){Dh.delete(e)}function tR(e){for(let t of $h)t(e)}function nR(e){for(let t of Dh)t(e)}var $h,Dh,Lh=_(()=>{"use strict";$h=new Set,Dh=new Set});function rR(e){return TG.has(e)}function RG(e,t=xG){return e.length<=t?e:e.slice(0,t)+"\u2026"}function CG(e){if(typeof e!="object"||e===null)return;let t=e.name;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}function AG(e){if(typeof e!="object"||e===null)throw new Error("Skill tool input must be an object");let t=e,n=t.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=t.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var TG,xG,Mn,rl=_(()=>{"use strict";wt();Xe();Ur();Gr();nl();Mh();Ph();Ks();Xn();tn();Yn();Oh();Lh();_e();Br();TG=new Set(["ask-gate","fanout-pace","right-size-delegation","premise-gate","intent-lock","long-bash-gate","exploration-gate","irreversible-action-gate","safe-destruct","plan-probe"]);xG=240;Mn=class{constructor(t){this.ctx=t;this.currentCwd=t.cwd}ctx;pluginBodies=null;currentCwd;setCwd(t){this.currentCwd=t}sessionIdentity(){return this.ctx.surface!==void 0?{origin:Nr(this.ctx.surface),actor:An(this.ctx.depth)}:{}}async execute(t){if(t.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??oi;if(n>=r){let l=CG(t.input);return Be({...this.sessionIdentity(),event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:l}).catch(()=>{}),{content:od(n,r),isError:!0}}let o;try{o=AG(t.input)}catch(l){return{content:`Skill tool input validation failed: ${l instanceof Error?l.message:String(l)}`,isError:!0}}try{let l=Ke(o.name);return await this.executeRegistrySkill(l,o.arguments,t)}catch{}let s=this.getPluginSkillBody(o.name);if(s){if(s.context==="fork"){let c=s.readOnly===!0||Fh.has(o.name);return await this.executePluginSkill(o.name,s.body,s.pluginPath,o.arguments,t,c,s.allowedTools)}let l=s.body.replace(/\$\{?PLUGIN_ROOT\}?/g,()=>s.pluginPath);return this.executeLoadedPluginSkill(o.name,l,o.arguments,t)}let a=cr(this.ctx.pluginConfigs).map(l=>l.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${a||"(none)"}`,isError:!0}}async executeRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(t.context==="fork")return this.executeForkedRegistrySkill(t,n,r);if(t.context==="load")return this.executeLoadedRegistrySkill(t,n,r);let o=Yx(t.name);o&&nR(t.name);let s=this.ctx.depth??0;Be({...this.sessionIdentity(),event:"skill.dispatched",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...rR(t.name)?{is_gate:!0}:{},...t.model!==void 0?{model:t.model}:{}}).catch(()=>{});let i=Date.now(),a,l;try{l=await t.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel,callId:r.id,dispatchSkill:this.createDispatchSkillCallback(r)})}catch(u){a=u}finally{let u=Date.now()-i;o&&tR({skillName:t.name,durationMs:u,...a!==void 0?{isError:!0}:{}});let d=a!==void 0?a instanceof Error?a.message:String(a):void 0,p=a===void 0?typeof l=="string"?l.length:l!=null?JSON.stringify(l).length:0:void 0;Be({...this.sessionIdentity(),event:"skill.completed",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,status:a!==void 0?"failed":"succeeded",duration_ms:u,depth:s,...p!==void 0?{content_chars:p}:{},...d!==void 0?{error_message:RG(d)}:{},...t.model!==void 0?{model:t.model}:{}}).catch(()=>{})}return a!==void 0?{content:`Skill execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}:{content:typeof l=="string"?l:l!=null?JSON.stringify(l):"Skill completed successfully."}}buildForkedChildConfig(t,n,r=!1,o){let s=this.ctx.depth??0,i=this.ctx.maxDepth??oi,a={...t},l=r&&o!==void 0?o.filter(m=>sd.includes(m)):r?[...sd]:o,c=r;if(!this.ctx.childProviderFactory||s>=i)return r?a.provider=oR(a.model):l!==void 0&&(a.provider=sR(l,a.model)),{childConfig:a,childManager:void 0};let u=new se({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),d=new Pn({subagentManager:u,parentSession:Lo(n),defaultConfig:{model:a.model,apiKey:this.ctx.apiKey,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{}},...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:s+1,maxDepth:i,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{},...this.ctx.backgroundRegistry!==void 0?{backgroundRegistry:this.ctx.backgroundRegistry}:{},...l!==void 0?{allowedTools:l}:{},...c?{readOnlyBash:!0}:{}}),p=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(s+1,i,n):void 0;return a.provider=this.ctx.childProviderFactory({childExecutor:d,...p!==void 0?{childSkillExecutor:p}:{},...a.model!==void 0?{model:a.model}:{},...l!==void 0?{allowedTools:l}:{},...c?{readOnlyBash:!0}:{}}),{childConfig:a,childManager:u}}async executeForkedRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o=t.readOnly===!0||Fh.has(t.name),s;try{if(s=He(t.name)["system.md"],!s)return{content:`Skill "${t.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(p){return{content:`Failed to load skill prompts: ${p instanceof Error?p.message:String(p)}`,isError:!0}}let i=t.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",a=tl({childModel:i,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(i):or(i),parentApiKey:this.ctx.apiKey}),l=new se({parentAbortSignal:r.signal,apiKey:a,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:Ht(),...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),{childConfig:c,childManager:u}=this.buildForkedChildConfig({model:i,systemPrompt:s,isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},r.signal,o),d;try{d=await l.forkSubagent({parent:this.ctx.parentSession,config:c,idPrefix:`skill-fork-${t.name}`,parentId:r.id,agentType:t.name});let p=n&&n.length>0?n:`Run the ${t.name} skill now, following the instructions in your system prompt.`,m=await d.runToResult(p);return m.status==="succeeded"&&m.message?{content:m.message.content}:m.status==="cancelled"&&typeof m.partialOutput=="string"&&m.partialOutput.length>0?{content:`[skill cancelled mid-flight \u2014 partial output preserved below]
|
|
1144
1144
|
|
|
1145
1145
|
${m.partialOutput}`}:{content:m.error?.message??"Forked skill failed with no output",isError:!0}}catch(p){return{content:`Forked skill execution error: ${p instanceof Error?p.message:String(p)}`,isError:!0}}finally{d&&await d.teardown().catch(z),await u?.teardownAll(),await l.teardownAll()}}formatLoadedSkillResult(t,n,r){let o=r&&r.trim().length>0?r.trim():"(none)";return{content:`${`[Skill "${t}" loaded into your current context \u2014 act on it now]
|
|
1146
1146
|
The instructions below are your operating procedure for THIS task. Execute them immediately, in this session, using the tools you already have. This is an instruction set, not reference material: follow it directly \u2014 do not merely summarize or describe it. No sub-agent was forked; you are the one carrying it out.
|
|
@@ -1150,7 +1150,7 @@ Arguments: ${o}`}
|
|
|
1150
1150
|
|
|
1151
1151
|
${n}`}}emitLoadTelemetry(t,n,r,o){let s=this.ctx.depth??0,i={...this.sessionIdentity(),requested_name:t,parent_session_id:this.ctx.parentSession.sessionId,depth:s,mode:"load",...o!==void 0?{model:o}:{}};Be({event:"skill.dispatched",...i,...rR(t)?{is_gate:!0}:{}}).catch(()=>{}),Be({event:"skill.completed",status:"succeeded",duration_ms:r,content_chars:n,...i}).catch(()=>{})}executeLoadedRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o=Date.now(),s;if(t.loadBody!==void 0)s=t.loadBody;else try{let l=He(t.name)["system.md"];if(!l)return{content:`Skill "${t.name}" has context: "load" but no prompts/system.md found`,isError:!0};s=l}catch(a){return{content:`Failed to load skill prompts: ${a instanceof Error?a.message:String(a)}`,isError:!0}}let i=this.substituteSkillArgs(s,n);return this.emitLoadTelemetry(t.name,i.length,Date.now()-o,t.model),this.formatLoadedSkillResult(t.name,i,n)}executeLoadedPluginSkill(t,n,r,o){if(o.signal.aborted)return{content:"Skill call aborted",isError:!0};let s=Date.now(),i=this.substituteSkillArgs(n,r);return this.emitLoadTelemetry(t,i.length,Date.now()-s,void 0),this.formatLoadedSkillResult(t,i,r)}substituteSkillArgs(t,n){let r=n??"";return t.replace(/\$ARGUMENTS?\b/g,()=>r)}async executePluginSkill(t,n,r,o,s,i=!1,a){if(s.signal.aborted)return{content:"Skill call aborted",isError:!0};let l=this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",c=tl({childModel:l,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(l):or(l),parentApiKey:this.ctx.apiKey}),u=new se({parentAbortSignal:s.signal,apiKey:c,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:Ht(),...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),d={model:l,systemPrompt:this.substituteSkillArgs(n,o),env:{PLUGIN_ROOT:r},isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},{childConfig:p,childManager:m}=this.buildForkedChildConfig(d,s.signal,i,a),g;try{g=await u.forkSubagent({parent:this.ctx.parentSession,config:p,idPrefix:`skill-${t}`,parentId:s.id,agentType:t});let h=o&&o.length>0?o:`Run the ${t} skill now, following the instructions in your system prompt.`,b=await g.runToResult(h);return b.status==="succeeded"&&b.message?{content:b.message.content}:b.status==="cancelled"&&typeof b.partialOutput=="string"&&b.partialOutput.length>0?{content:`[skill cancelled mid-flight \u2014 partial output preserved below]
|
|
1152
1152
|
|
|
1153
|
-
${b.partialOutput}`}:{content:b.error?.message??"Plugin skill failed with no output",isError:!0}}catch(h){return{content:`Plugin skill execution error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}finally{g&&await g.teardown().catch(z),await m?.teardownAll(),await u.teardownAll()}}getPluginSkillBody(t){return this.pluginBodies||(this.pluginBodies=id(this.ctx.pluginConfigs)),this.pluginBodies.get(t)}createDispatchSkillCallback(t){return async(n,r)=>{let o={id:`${t.id}-dispatch-${n}`,name:"skill",input:{name:n,...r!==void 0?{arguments:r}:{}},signal:t.signal},s=await this.execute(o);if(s.isError)throw new Error(s.content);return s.content}}}});function Lo(e){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:e}}function ii(e={}){return({childExecutor:t,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:s})=>{let i={permissions:{allowedTools:o??_G},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{}};return re(typeof r=="string"?r:void 0)==="openai-compatible"?new $t({...i,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{},readOnlyMemory:!0}):new Ge({...i,readOnlyMemory:!0})}}function oR(e){let t={allowedTools:[...sd]};return re(typeof e=="string"?e:void 0)==="openai-compatible"?new $t({permissions:t,readOnlyBash:!0,readOnlyMemory:!0}):new Ge({permissions:t,readOnlyBash:!0,readOnlyMemory:!0})}function ai(e,t,n,r,o,s,i,a,l){let c=(u,d,p)=>new Mn({parentSession:Lo(p),defaultModel:e,apiKey:t,...r!==void 0?{baseUrl:r}:{},depth:u,maxDepth:d,childProviderFactory:n,childSkillExecutorFactory:c,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{},...i!==void 0?{cwd:i}:{},...a!==void 0?{resolveApiKeyForModel:a}:{},...l!==void 0?{surface:l}:{}});return c}function sR(e,t){let n={allowedTools:[...e]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new $t({permissions:n}):new Ge({permissions:n})}function iR(e,t){let n={allowedTools:[...$x]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new $t({permissions:n}):new Ge({permissions:n})}var oi,_G,sd,Fh,Gr=_(()=>{"use strict";Fo();Va();tt();kn();Tn();Za();rl();oi=3;_G=[...Wt,...pt,"memory_search","agent","skill"],sd=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...pt,"memory_search","agent","skill"],Fh=new Set(["ground-state"])});var ad,aR=_(()=>{"use strict";_e();jc();Xn();Hc();je();zt();ad=class{constructor(t,n,r,o,s,i,a,l,c,u,d,p,m,g,h){this.id=t;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=u;this.agentType=d;this.traceWriter=g;this.onSubagentSucceeded=h;this.progressSink=p,this.parentId=m}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;currentTrace=Qa();lastStreamedContent="";get status(){return this.currentStatus}async run(t,n){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let r=Date.now(),o=Uc(this.streamToFinalMessage(t,n),this.timeoutMs,{controller:this.controller,label:this.id});this.inFlight=o;try{let s=await o;this.lastMessage=s.content,this.lastDurationMs=Date.now()-r,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",So(this.traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:this.lastDurationMs,turnCount:this.currentTrace.turnCount,outputBytes:Buffer.byteLength(this.lastMessage,"utf8")});let i=typeof s.metadata?.totalCostUsd=="number"?s.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this.currentTrace.usage,i),this.onTerminal(),s}catch(s){throw this.lastDurationMs=Date.now()-r,this.currentStatus!=="cancelled"&&(this.controller.signal.aborted?(So(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(So(this.traceWriter,{transition:"failed",subagentId:this.id,errorClass:s instanceof Error?s.constructor.name:"Unknown",errorMessage:s instanceof Error?s.message:String(s),partialOutputBytes:Buffer.byteLength(this.lastStreamedContent,"utf8")}),this.currentStatus="failed",this.latestTerminalStatus="failed")),this.onTerminal(),s}finally{this.inFlight=null}}async streamToFinalMessage(t,n){let r,o;this.lastStreamedContent="",this.currentTrace=Qa();let s=n??this.progressSink??Ht(),i={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}};for await(let a of this.session.sendMessageStream(t)){if(s&&s(a,i),a.type==="chunk"){let l=a.chunk;l.type==="content"?this.lastStreamedContent+=l.content:l.type==="tool_use_detail"?this.currentTrace.toolCalls.push({id:l.toolUseId,name:l.toolName,inputBytes:Buffer.byteLength(l.toolInput,"utf8")}):l.type==="tool_result"?this.currentTrace.toolResults.push({toolUseId:l.toolUseId,isError:l.isError,truncated:l.truncated,sizeBytes:l.sizeBytes}):l.type==="thinking"&&(this.currentTrace.thinkingPresent=!0)}if(a.type==="message")r=a.message,this.currentTrace.turnCount++;else if(a.type==="error"){o=a.error;break}else if(a.type==="done"){if(typeof a.metadata?.usage=="object"&&a.metadata.usage!==null){let l=a.metadata.usage;this.currentTrace.usage={inputTokens:typeof l.input_tokens=="number"?l.input_tokens:void 0,outputTokens:typeof l.output_tokens=="number"?l.output_tokens:void 0,cacheReadTokens:typeof l.cache_read_input_tokens=="number"?l.cache_read_input_tokens:void 0,cacheCreationTokens:typeof l.cache_creation_input_tokens=="number"?l.cache_creation_input_tokens:void 0}}break}}if(o)throw o;if(r)return r;if(this.lastStreamedContent.length>0)return{role:"assistant",content:this.lastStreamedContent,timestamp:new Date};throw new Error(`Subagent ${this.id} produced no terminal message`)}async runToResult(t,n){try{let r=await this.run(t,n);return Ux(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=Qu(this.id,this.currentStatus,r,this.currentTrace);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(t,n,r){let o;if(r){let s=this.progressSink??Ht();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(t,o).then(s=>{n?.(s)}).catch(s=>{z("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let t=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",So(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"});try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(t)}}async teardown(){if(this.stopDispatched)return;let t=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(t)}}async dispatchStopAndRelease(t){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let n=await qv(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:t,lastMessage:this.lastMessage,agentType:this.agentType,durationMs:this.lastDurationMs,trace:this.currentTrace},this.traceWriter?{traceWriter:this.traceWriter}:{});if(n.injectContext&&this.parentInputStreamRef)if(this.parentAbortSignal?.aborted)z(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){z(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}}});var IG,se,Xe=_(()=>{"use strict";Wv();li();jc();Hc();je();Yn();Xn();Gr();aR();IG=async(e,t)=>({action:"decline"}),se=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentCwd;parentTraceWriter;parentSurface;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(t={}){if(this.parentCanUseTool=t.canUseTool,this.hookRegistry=t.hookRegistry,this.progressSink=t.progressSink,this.parentApiKey=t.apiKey,this.parentBaseUrl=t.baseUrl,this.parentCwd=t.cwd,this.parentTraceWriter=t.traceWriter,this.parentSurface=t.surface,this.onSubagentSucceededCb=t.onSubagentSucceeded,this.abortGraph=new Nc(t.traceWriter),this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),t.parentAbortSignal){let n=t.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(t=>({id:t.id,status:t.status}))}get(t){return this.active.get(t)}onChildAborted(t){return this.abortGraph.onChildAborted(this.rootId,t)}setOnSubagentSucceeded(t){this.onSubagentSucceededCb=t}setCwd(t){this.parentCwd=t}abortAll(t,n="user_signal"){this.abortGraph.abort(this.rootId,t,n)}async forkSubagent(t){if(t.phaseRole!==void 0&&t.phaseRole!=="read-write"&&t.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${t.phaseRole}" is mutually exclusive with config.provider. Remove one \u2014 either let the manager construct the phase-restricted provider, or use config.provider with phaseRole: "read-write" (default).`);let n=`${t.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=t.parent.sessionId,o=t.config.hookRegistry??this.hookRegistry??t.parent.hookRegistry;o&&await Gv(o,{event:"SubagentStart",subagentId:n,parentSessionId:t.parent.sessionId},{signal:this.rootController.signal,...t.config.traceWriter?{traceWriter:t.config.traceWriter}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i={...t.config,resume:r,forkSession:r?!0:t.config.forkSession,abortSignal:s.signal,apiKey:t.config.apiKey||this.parentApiKey,baseUrl:t.config.baseUrl??this.parentBaseUrl,isNonInteractive:t.config.isNonInteractive??!0,...t.config.parentSessionId===void 0&&t.parent.sessionId!==void 0?{parentSessionId:t.parent.sessionId}:{},...t.config.phaseRole===void 0&&t.phaseRole!==void 0?{phaseRole:t.phaseRole}:{},...t.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},...t.config.traceWriter===void 0&&this.parentTraceWriter!==void 0?{traceWriter:this.parentTraceWriter}:{},...t.config.surface===void 0&&this.parentSurface!==void 0?{surface:this.parentSurface}:{},hookRegistry:o,permissionBubbler:t.config.permissionBubbler??(this.parentCanUseTool!==void 0&&t.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...t.denyElicitations===!1?{}:{onElicitation:IG},...t.phaseRole==="read-only"?{provider:iR("read-only",t.config.model)}:{}},a;try{a=new wt(i)}catch(h){throw this.abortGraph.dispose(n),h}let l=t.parent.getInputStreamRef?.(),c=t.parent.abortSignal,u=this.progressSink??Ht(),d=t.agentType?.trim()||void 0,p=t.parentId?.trim()||void 0,m=new ad(n,a,s,this.abortGraph,t.outputSchema,t.config.timeoutMs??Bc,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},l,c,d??t.idPrefix,u,p??t.parent.sessionId,t.config.traceWriter,this.onSubagentSucceededCb);this.active.set(n,m);let g=typeof t.config.model=="string"?t.config.model:JSON.stringify(t.config.model);return So(t.config.traceWriter,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:g,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await Be({event:"subagent.dispatched",subagent_id:n,id_prefix:t.idPrefix,model:g,parent_session_id:t.parent.sessionId}),m}async kill(t){let n=this.active.get(t);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(t=>t.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(t=>t.teardown()))}}});async function ld(e,t={}){let{failFast:n=!0,teardown:r=!0}=t;if(e.length===0)return[];let o=new Array(e.length),s=new Set(e.map((a,l)=>l)),i=e.map((a,l)=>a.handle.runToResult(a.prompt).then(c=>{if(o[l]=c,s.delete(l),n&&c.status!=="succeeded")for(let u of s){let d=e[u];d&&d.handle.status==="running"&&d.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(e.map(a=>a.handle.teardown())),o}var Nh=_(()=>{"use strict"});import{fileURLToPath as PG}from"node:url";import{dirname as MG}from"node:path";var OG,Qfe,Jt,Bh=_(()=>{"use strict";OG=PG(import.meta.url),Qfe=MG(OG),Jt={name:"research-agent",systemPrompt:`---
|
|
1153
|
+
${b.partialOutput}`}:{content:b.error?.message??"Plugin skill failed with no output",isError:!0}}catch(h){return{content:`Plugin skill execution error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}finally{g&&await g.teardown().catch(z),await m?.teardownAll(),await u.teardownAll()}}getPluginSkillBody(t){return this.pluginBodies||(this.pluginBodies=id(this.ctx.pluginConfigs)),this.pluginBodies.get(t)}createDispatchSkillCallback(t){return async(n,r)=>{let o={id:`${t.id}-dispatch-${n}`,name:"skill",input:{name:n,...r!==void 0?{arguments:r}:{}},signal:t.signal},s=await this.execute(o);if(s.isError)throw new Error(s.content);return s.content}}}});function Lo(e){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:e}}function ii(e={}){return({childExecutor:t,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:s})=>{let i={permissions:{allowedTools:o??_G},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{}};return re(typeof r=="string"?r:void 0)==="openai-compatible"?new $t({...i,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{},readOnlyMemory:!0}):new Ge({...i,readOnlyMemory:!0})}}function oR(e){let t={allowedTools:[...sd]};return re(typeof e=="string"?e:void 0)==="openai-compatible"?new $t({permissions:t,readOnlyBash:!0,readOnlyMemory:!0}):new Ge({permissions:t,readOnlyBash:!0,readOnlyMemory:!0})}function ai(e,t,n,r,o,s,i,a,l){let c=(u,d,p)=>new Mn({parentSession:Lo(p),defaultModel:e,apiKey:t,...r!==void 0?{baseUrl:r}:{},depth:u,maxDepth:d,childProviderFactory:n,childSkillExecutorFactory:c,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{},...i!==void 0?{cwd:i}:{},...a!==void 0?{resolveApiKeyForModel:a}:{},...l!==void 0?{surface:l}:{}});return c}function sR(e,t){let n={allowedTools:[...e]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new $t({permissions:n}):new Ge({permissions:n})}function iR(e,t){let n={allowedTools:[...$x]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new $t({permissions:n}):new Ge({permissions:n})}var oi,_G,sd,Fh,Gr=_(()=>{"use strict";Fo();Va();tt();kn();Tn();Za();rl();oi=3;_G=[...Wt,...pt,"memory_search","agent","skill"],sd=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...pt,"memory_search","agent","skill"],Fh=new Set(["ground-state"])});var ad,aR=_(()=>{"use strict";_e();jc();Xn();Hc();je();zt();ad=class{constructor(t,n,r,o,s,i,a,l,c,u,d,p,m,g,h){this.id=t;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=u;this.agentType=d;this.traceWriter=g;this.onSubagentSucceeded=h;this.progressSink=p,this.parentId=m}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;currentTrace=Qa();lastStreamedContent="";get status(){return this.currentStatus}async run(t,n){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let r=Date.now(),o=Uc(this.streamToFinalMessage(t,n),this.timeoutMs,{controller:this.controller,label:this.id});this.inFlight=o;try{let s=await o;this.lastMessage=s.content,this.lastDurationMs=Date.now()-r,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",So(this.traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:this.lastDurationMs,turnCount:this.currentTrace.turnCount,outputBytes:Buffer.byteLength(this.lastMessage,"utf8")});let i=typeof s.metadata?.totalCostUsd=="number"?s.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this.currentTrace.usage,i),this.onTerminal(),s}catch(s){throw this.lastDurationMs=Date.now()-r,this.currentStatus!=="cancelled"&&(this.controller.signal.aborted?(So(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(So(this.traceWriter,{transition:"failed",subagentId:this.id,errorClass:s instanceof Error?s.constructor.name:"Unknown",errorMessage:s instanceof Error?s.message:String(s),partialOutputBytes:Buffer.byteLength(this.lastStreamedContent,"utf8")}),this.currentStatus="failed",this.latestTerminalStatus="failed")),this.onTerminal(),s}finally{this.inFlight=null}}async streamToFinalMessage(t,n){let r,o;this.lastStreamedContent="",this.currentTrace=Qa();let s=n??this.progressSink??Ht(),i={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}};for await(let a of this.session.sendMessageStream(t)){if(s&&s(a,i),a.type==="chunk"){let l=a.chunk;l.type==="content"?this.lastStreamedContent+=l.content:l.type==="tool_use_detail"?this.currentTrace.toolCalls.push({id:l.toolUseId,name:l.toolName,inputBytes:Buffer.byteLength(l.toolInput,"utf8")}):l.type==="tool_result"?this.currentTrace.toolResults.push({toolUseId:l.toolUseId,isError:l.isError,truncated:l.truncated,sizeBytes:l.sizeBytes}):l.type==="thinking"&&(this.currentTrace.thinkingPresent=!0)}if(a.type==="message")r=a.message,this.currentTrace.turnCount++;else if(a.type==="error"){o=a.error;break}else if(a.type==="done"){if(typeof a.metadata?.usage=="object"&&a.metadata.usage!==null){let l=a.metadata.usage;this.currentTrace.usage={inputTokens:typeof l.input_tokens=="number"?l.input_tokens:void 0,outputTokens:typeof l.output_tokens=="number"?l.output_tokens:void 0,cacheReadTokens:typeof l.cache_read_input_tokens=="number"?l.cache_read_input_tokens:void 0,cacheCreationTokens:typeof l.cache_creation_input_tokens=="number"?l.cache_creation_input_tokens:void 0}}break}}if(o)throw o;if(r)return r;if(this.lastStreamedContent.length>0)return{role:"assistant",content:this.lastStreamedContent,timestamp:new Date};throw new Error(`Subagent ${this.id} produced no terminal message`)}async runToResult(t,n){try{let r=await this.run(t,n);return Ux(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=Qu(this.id,this.currentStatus,r,this.currentTrace);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(t,n,r){let o;if(r){let s=this.progressSink??Ht();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(t,o).then(s=>{n?.(s)}).catch(s=>{z("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let t=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",So(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"});try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(t)}}async teardown(){if(this.stopDispatched)return;let t=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(t)}}async dispatchStopAndRelease(t){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let n=await qv(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:t,lastMessage:this.lastMessage,agentType:this.agentType,durationMs:this.lastDurationMs,trace:this.currentTrace},this.traceWriter?{traceWriter:this.traceWriter}:{});if(n.injectContext&&this.parentInputStreamRef)if(this.parentAbortSignal?.aborted)z(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){z(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}}});var IG,se,Xe=_(()=>{"use strict";Wv();li();jc();Hc();je();Yn();Xn();Gr();aR();IG=async(e,t)=>({action:"decline"}),se=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentCwd;parentTraceWriter;parentSurface;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(t={}){if(this.parentCanUseTool=t.canUseTool,this.hookRegistry=t.hookRegistry,this.progressSink=t.progressSink,this.parentApiKey=t.apiKey,this.parentBaseUrl=t.baseUrl,this.parentCwd=t.cwd,this.parentTraceWriter=t.traceWriter,this.parentSurface=t.surface,this.onSubagentSucceededCb=t.onSubagentSucceeded,this.abortGraph=new Nc(t.traceWriter),this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),t.parentAbortSignal){let n=t.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(t=>({id:t.id,status:t.status}))}get(t){return this.active.get(t)}onChildAborted(t){return this.abortGraph.onChildAborted(this.rootId,t)}setOnSubagentSucceeded(t){this.onSubagentSucceededCb=t}setCwd(t){this.parentCwd=t}abortAll(t,n="user_signal"){this.abortGraph.abort(this.rootId,t,n)}async forkSubagent(t){if(t.phaseRole!==void 0&&t.phaseRole!=="read-write"&&t.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${t.phaseRole}" is mutually exclusive with config.provider. Remove one \u2014 either let the manager construct the phase-restricted provider, or use config.provider with phaseRole: "read-write" (default).`);let n=`${t.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=t.parent.sessionId,o=t.config.hookRegistry??this.hookRegistry??t.parent.hookRegistry;o&&await Gv(o,{event:"SubagentStart",subagentId:n,parentSessionId:t.parent.sessionId},{signal:this.rootController.signal,...t.config.traceWriter?{traceWriter:t.config.traceWriter}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i={...t.config,resume:r,forkSession:r?!0:t.config.forkSession,abortSignal:s.signal,apiKey:t.config.apiKey||this.parentApiKey,baseUrl:t.config.baseUrl??this.parentBaseUrl,isNonInteractive:t.config.isNonInteractive??!0,...t.config.parentSessionId===void 0&&t.parent.sessionId!==void 0?{parentSessionId:t.parent.sessionId}:{},...t.config.phaseRole===void 0&&t.phaseRole!==void 0?{phaseRole:t.phaseRole}:{},...t.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},...t.config.traceWriter===void 0&&this.parentTraceWriter!==void 0?{traceWriter:this.parentTraceWriter}:{},...t.config.surface===void 0&&this.parentSurface!==void 0?{surface:this.parentSurface}:{},hookRegistry:o,permissionBubbler:t.config.permissionBubbler??(this.parentCanUseTool!==void 0&&t.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...t.denyElicitations===!1?{}:{onElicitation:IG},...t.phaseRole==="read-only"?{provider:iR("read-only",t.config.model)}:{}},a;try{a=new St(i)}catch(h){throw this.abortGraph.dispose(n),h}let l=t.parent.getInputStreamRef?.(),c=t.parent.abortSignal,u=this.progressSink??Ht(),d=t.agentType?.trim()||void 0,p=t.parentId?.trim()||void 0,m=new ad(n,a,s,this.abortGraph,t.outputSchema,t.config.timeoutMs??Bc,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},l,c,d??t.idPrefix,u,p??t.parent.sessionId,t.config.traceWriter,this.onSubagentSucceededCb);this.active.set(n,m);let g=typeof t.config.model=="string"?t.config.model:JSON.stringify(t.config.model);return So(t.config.traceWriter,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:g,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await Be({event:"subagent.dispatched",subagent_id:n,id_prefix:t.idPrefix,model:g,parent_session_id:t.parent.sessionId}),m}async kill(t){let n=this.active.get(t);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(t=>t.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(t=>t.teardown()))}}});async function ld(e,t={}){let{failFast:n=!0,teardown:r=!0}=t;if(e.length===0)return[];let o=new Array(e.length),s=new Set(e.map((a,l)=>l)),i=e.map((a,l)=>a.handle.runToResult(a.prompt).then(c=>{if(o[l]=c,s.delete(l),n&&c.status!=="succeeded")for(let u of s){let d=e[u];d&&d.handle.status==="running"&&d.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(e.map(a=>a.handle.teardown())),o}var Nh=_(()=>{"use strict"});import{fileURLToPath as PG}from"node:url";import{dirname as MG}from"node:path";var OG,Qfe,Jt,Bh=_(()=>{"use strict";OG=PG(import.meta.url),Qfe=MG(OG),Jt={name:"research-agent",systemPrompt:`---
|
|
1154
1154
|
name: research-agent
|
|
1155
1155
|
description: Read-only sub-agent for research, validation, verification, and codebase inspection. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Edit, Write, Bash, commit, or push. Delegates git queries to \`git-investigator\`. Use when the dispatched task is findings-only.
|
|
1156
1156
|
model: sonnet
|
|
@@ -1235,7 +1235,7 @@ ${N.rationale}
|
|
|
1235
1235
|
---
|
|
1236
1236
|
Generated by audit-fit on ${new Date().toISOString().split(".")[0]}Z
|
|
1237
1237
|
`;await kR(H,L),R++}}let k=gn();await vR(k,{recursive:!0});let $=D=>{let N=0;for(let B of Object.values(D))for(let H of Object.values(B))N+=H;return N},A=D=>{let N=x.user[D]??{},B=x.plugin[D]??{},H=L=>Object.values(L).reduce((I,U)=>I+U,0);return H(N)+H(B)},P={timestamp:new Date().toISOString(),surface:"afk",scope:c,total_artifacts:T.length,misfits_count:C.length,briefs_written:R,by_source:{user:$(x.user),plugin:$(x.plugin)},by_type:{skill:A("skill"),command:A("command"),agent:A("agent"),hook:A("hook")}},F=Kh(k,"audit-fit-telemetry.jsonl");return await kR(F,JSON.stringify(P)+`
|
|
1238
|
-
`),{inventory:x,misfits:C,briefs_written:R,total_artifacts:T.length}}var TR,ER,Rge,VG,YG,xR,o2,RR=_(()=>{"use strict";tn();
|
|
1238
|
+
`),{inventory:x,misfits:C,briefs_written:R,total_artifacts:T.length}}var TR,ER,Rge,VG,YG,xR,o2,RR=_(()=>{"use strict";tn();wt();Xe();Nh();Bh();G();SR();TR=Le.object({path:Le.string(),type:Le.enum(["skill","command","agent","hook"]),source:Le.enum(["user","plugin"]),plugin_key:Le.string().optional(),verdict:Le.enum(["correct","misfit","outlier"]),recommended_type:Le.string(),rationale:Le.string(),confidence:Le.enum(["high","med","low"])}),ER=Le.record(Le.string(),Le.record(Le.string(),Le.number())),Rge=Le.object({inventory:Le.object({user:ER,plugin:ER}),misfits:Le.array(TR),briefs_written:Le.number(),total_artifacts:Le.number()}),VG=Le.object({writeBriefs:Le.boolean().optional(),scope:Le.enum(["user","plugin","all"]).optional()}),YG=["skill","command","agent"],xR=["skill","command","agent","hook"];o2={name:"audit-fit",description:"Audit ~/.afk artifacts (skills, commands, agents, hooks) for correct type categorization. Walks user-scope dirs (~/.afk/{skills,commands,agents}/) and every plugin installed under ~/.afk/plugins/ (flat and marketplace-cache layouts), plus ~/.afk/settings.json for hooks. Dispatches per-type inspectors in parallel, applies decision heuristics (progressive-disclosure value, isolation need, deterministic vs. reasoning), flags misfits. Generates migration briefs only for user-scope misfits (plugin misfits are inventory-only \u2014 refactoring vendored plugin code is the maintainer's job). Optional `scope` input filters to `user`, `plugin`, or `all` (default). Use for inventory audits after bulk authoring, imports, or periodic hygiene.",handler:r2,argumentHint:"[--write-briefs]",whenToUse:"When the user wants ~/.afk artifacts (skills, commands, agents, hooks) audited for correct type categorization.",flags:["--write-briefs"],audience:"internal"};Ct(o2)});import{z as ee}from"zod";var dd,CR,pd,AR,_R,IR,s2,PR,md=_(()=>{"use strict";dd=ee.object({id:ee.string(),claim:ee.string(),confidence:ee.number().min(0).max(1),evidence_sources:ee.array(ee.string()),location:ee.string().optional(),proposed_fix:ee.string().optional(),coverage_gaps:ee.array(ee.string()).nullish().transform(e=>e??void 0),boundary_flag:ee.string().nullish().transform(e=>e??void 0)}),CR=ee.object({hypothesis_id:ee.string(),claim:ee.string(),verdict:ee.enum(["VERIFIED","REFUTED","INCONCLUSIVE"]),evidence:ee.string(),gate_reason:ee.string()}),pd=ee.object({hypothesis_id:ee.string(),predicted_pass:ee.boolean(),regressions:ee.array(ee.string()),confidence:ee.number().min(0).max(1),verification_log:ee.string()}),AR=ee.enum(["crash","regression","logic-error","flaky","environment","unknown"]),_R=ee.object({failure_type:AR,error_signature:ee.string(),affected_area:ee.string()}),IR=ee.enum(["clear_winner","multiple_plausible","dissent","all_inconclusive","no_hypotheses"]),s2=ee.object({reproducer:ee.string().optional(),triage:_R.optional(),hypotheses:ee.array(dd),premise_verifications:ee.array(CR).optional(),winner:ee.object({hypothesis_id:ee.string(),verification_log:ee.string(),proposed_fix:ee.string()}).optional(),verification_results:ee.array(pd).optional(),outcome:IR.optional(),recommended_next_skill:ee.enum(["spec"]).optional()}),PR=ee.object({verifications:ee.array(ee.object({claim:ee.string().optional(),verdict:ee.string(),evidence:ee.string().optional()}))})});function Gh(e,t){let n=`${e}
|
|
1239
1239
|
${t}`,r="unknown",o=n.toLowerCase();/flaky|non-?deterministic|intermittent|sometimes fails|race/.test(o)?r="flaky":/regression|used to work|worked before|broke in|ci.*green.*red|was passing/.test(o)?r="regression":/\b(uncaught|unhandled)\b|panic|segfault|exit(ed)? (with )?(code )?[1-9]|sigsegv|stack overflow|fatal|traceback|core dumped|abort(ed)?|\b(type|reference|range|syntax|internal|eval|uri)error\b/.test(o)?r="crash":/platform|node version|python version|dependency|version mismatch|works on .* not |env(ironment)?|config drift/.test(o)?r="environment":/expected .* but|got .* expected|wrong|incorrect|unexpected/.test(o)&&(r="logic-error");let s=/^(why|what|how|when|where|who|is|are|does|did|can|could|should|would)\b/i,i=/\b(error|exception|panic|throws?|traceback|fail(ed|ure|s)?|undefined|null|nan|segfault|sigsegv|stack ?overflow|abort(ed)?)\w*|:\s*\d+|\bat\s+\S|\bcore dumped\b/i,a=e.split(`
|
|
1240
1240
|
`).map(d=>d.trim()).find(d=>d.length>0),l;a?s.test(a)&&!i.test(e)?l="prose-question":a.length>200?l=`${a.slice(0,197)}...`:l=a:l="unknown";let u=n.match(/(?:^|[\s'"`(])((?:\.{1,2}\/)?[\w@./-]+\.(?:ts|tsx|js|jsx|mjs|cjs|py|rb|go|rs|java|kt|cpp|c|h|hpp|md|json|yaml|yml)(?::\d+(?::\d+)?)?)/)?.[1]??"unknown";return{failure_type:r,error_signature:l,affected_area:u}}function qh(e){let n=`${e.proposed_fix??""}
|
|
1241
1241
|
${e.location??""}`.match(/(?:^|[\s'"`(])((?:\.{1,2}\/)?[\w@./-]+\.(?:ts|tsx|js|jsx|mjs|cjs|py|rb|go|rs|java|kt|cpp|c|h|hpp))/g);return n?new Set(n.map(o=>o.trim().replace(/^[\s'"`(]+/,"").split(":")[0])).size>2:!1}function zh(e,t){if(e.length===0)return"no_hypotheses";let n=t.filter(o=>o.predicted_pass&&o.regressions.length===0);return n.length===1?"clear_winner":n.length>=2?"multiple_plausible":e.filter(o=>o.confidence>=.7).length>=2?"dissent":"all_inconclusive"}var Jh=_(()=>{"use strict"});function MR(e){return e.confidence<.5?{verify:!0,reason:`low confidence (${e.confidence.toFixed(2)} < ${.5})`}:e.boundary_flag&&e.boundary_flag.length>0?{verify:!0,reason:`boundary flag set: ${e.boundary_flag}`}:e.coverage_gaps&&e.coverage_gaps.length>0?{verify:!0,reason:`coverage gap${e.coverage_gaps.length===1?"":"s"}: ${e.coverage_gaps.length} unresolved`}:{verify:!1,reason:`confidence ${e.confidence.toFixed(2)} with no gaps or boundary`}}var OR=_(()=>{"use strict"});import{execFile as i2}from"node:child_process";import{promisify as a2}from"node:util";function c2(e){let t=e.trim().toUpperCase();return["VERIFIED","CONFIRMED","CONFIRM","SUPPORTED","TRUE","PASS","PASSED"].includes(t)?"VERIFIED":["REFUTED","REFUTE","DISAGREE","DISAGREED","CONTRADICTED","FALSE","FAIL","FAILED"].includes(t)?"REFUTED":"INCONCLUSIVE"}function u2(e){let t=[],n=0,r=-1,o=!1,s=!1;for(let i=0;i<e.length;i++){let a=e[i];if(o){s?s=!1:a==="\\"?s=!0:a==='"'&&(o=!1);continue}a==='"'?o=!0:a==="{"?(n===0&&(r=i),n++):a==="}"&&n>0&&(n--,n===0&&r!==-1&&(t.push(e.slice(r,i+1)),r=-1))}return t}function Vh(e){let t=u2(e);for(let n of t){let r;try{r=JSON.parse(n)}catch{continue}let o=PR.safeParse(r);if(o.success)return o.data.verifications.map(s=>({claim:s.claim??"",verdict:c2(s.verdict),evidence:s.evidence??""}))}throw new Error(`shadow-verify did not return a parseable {"verifications":[...]} envelope (${t.length} JSON-like span(s) found, none matched the schema); raw output (first 300 chars): ${e.slice(0,300)}`)}function fd(e,t){return e.length<=t?e:`...[truncated]
|
|
@@ -1289,7 +1289,7 @@ Original failure: ${s.failure}`,P;try{P=await $.runToResult(A)}finally{await $.t
|
|
|
1289
1289
|
Hint: model response must include a fenced JSON block with a hypotheses array.`)}throw new Error(`hypothesis synthesis failed: ${ct(P)}`)}let F=P.output.hypotheses.slice(0,s.maxHypotheses);if(F.length===0)return{reproducer:m,triage:g,hypotheses:[],verification_results:[],outcome:"no_hypotheses"};let{premise_verifications:D,hypotheses_to_test:N}=await Zh(F,async X=>{if(!n?.dispatchSkill)throw new Error("shadow-verify dispatch unavailable (no dispatchSkill in ctx)");let W=JSON.stringify({claims:X,context:`Original failure: ${s.failure}
|
|
1290
1290
|
|
|
1291
1291
|
OUTPUT CONTRACT (required): after your verification, end your reply with a single fenced \`\`\`json block of exactly this shape \u2014 one entry per claim, in the SAME order you received them:
|
|
1292
|
-
{"verifications":[{"claim":"<echo of the claim>","verdict":"VERIFIED|REFUTED|INCONCLUSIVE","evidence":"<1-2 sentences; cite file:line or source>"}]}`}),Ee=await n.dispatchSkill("shadow-verify",W);return Vh(Ee)});if(N.length===0)return{reproducer:m,triage:g,hypotheses:F,premise_verifications:D,verification_results:[],outcome:"no_hypotheses"};let B=m||s.failure,H;if(m)try{H=await Yh(m,s.repoPath)}catch(X){H={skipped:!0,reason:`baseline execution error: ${X instanceof Error?X.message:String(X)}`,exitCode:null,stdout:"",stderr:"",timedOut:!1}}else H={skipped:!0,reason:"no reproducer command detected",exitCode:null,stdout:"",stderr:"",timedOut:!1};let L=N.map(X=>v2(X,B,s.repoPath,i,d,p,w,H,o)),I=await Promise.all(L),M=I.filter(X=>X.predicted_pass&&X.regressions.length===0).slice().sort((X,W)=>W.confidence-X.confidence)[0]??I.find(X=>X.predicted_pass),j=zh(F,I),Y=M?F.find(X=>X.id===M.hypothesis_id):void 0,oe=j==="clear_winner"&&Y&&qh(Y)?"spec":void 0;return{reproducer:m,triage:g,hypotheses:F,premise_verifications:D.length>0?D:void 0,winner:M?{hypothesis_id:M.hypothesis_id,verification_log:M.verification_log,proposed_fix:Y?.proposed_fix||""}:void 0,verification_results:I,outcome:j,recommended_next_skill:oe}}var gd,jR,WR=_(()=>{"use strict";tn();Xe();Nh();zt();Bh();DR();FR();md();Jh();Qh();gd=h2(g2);jR=[...Jt.allowedTools,"Agent"]});var k2,KR=_(()=>{"use strict";md();Jh();Qh();WR();
|
|
1292
|
+
{"verifications":[{"claim":"<echo of the claim>","verdict":"VERIFIED|REFUTED|INCONCLUSIVE","evidence":"<1-2 sentences; cite file:line or source>"}]}`}),Ee=await n.dispatchSkill("shadow-verify",W);return Vh(Ee)});if(N.length===0)return{reproducer:m,triage:g,hypotheses:F,premise_verifications:D,verification_results:[],outcome:"no_hypotheses"};let B=m||s.failure,H;if(m)try{H=await Yh(m,s.repoPath)}catch(X){H={skipped:!0,reason:`baseline execution error: ${X instanceof Error?X.message:String(X)}`,exitCode:null,stdout:"",stderr:"",timedOut:!1}}else H={skipped:!0,reason:"no reproducer command detected",exitCode:null,stdout:"",stderr:"",timedOut:!1};let L=N.map(X=>v2(X,B,s.repoPath,i,d,p,w,H,o)),I=await Promise.all(L),M=I.filter(X=>X.predicted_pass&&X.regressions.length===0).slice().sort((X,W)=>W.confidence-X.confidence)[0]??I.find(X=>X.predicted_pass),j=zh(F,I),Y=M?F.find(X=>X.id===M.hypothesis_id):void 0,oe=j==="clear_winner"&&Y&&qh(Y)?"spec":void 0;return{reproducer:m,triage:g,hypotheses:F,premise_verifications:D.length>0?D:void 0,winner:M?{hypothesis_id:M.hypothesis_id,verification_log:M.verification_log,proposed_fix:Y?.proposed_fix||""}:void 0,verification_results:I,outcome:j,recommended_next_skill:oe}}var gd,jR,WR=_(()=>{"use strict";tn();Xe();Nh();zt();Bh();DR();FR();md();Jh();Qh();gd=h2(g2);jR=[...Jt.allowedTools,"Agent"]});var k2,KR=_(()=>{"use strict";md();Jh();Qh();WR();wt();k2={name:"diagnose",description:"Parallel root-cause analysis for bugs and failing tests \u2014 forks research subagents, synthesizes hypotheses, and validates each in isolated worktrees",handler:HR,argumentHint:"<bug-or-failing-test>",whenToUse:"When a test is failing, a bug is reported, or behavior is unexplained \u2014 runs parallel root-cause analysis with hypothesis sub-agents."};Ct(k2)});async function E2(){throw new Error("get-started is a load skill; its handler should never be called directly. Invoke via the `skill` tool or `/get-started` slash command.")}var T2,GR=_(()=>{"use strict";wt();T2={name:"get-started",description:"Guided first-run onboarding for AFK. Runs a preflight check (git repo, model provider, AFK.md, Exa/Telegram/service config), asks the user their name and gives a brief intro, detects importable Claude Code / Codex assets and offers `afk migrate`, walks optional capability setup (Exa Search, Telegram via /telegram-setup, background service via /service-setup), then recommends /init to generate project context and /clear to start fresh \u2014 ending by routing the user to their first task. Runs interactively in the current session.",handler:E2,context:"load",audience:"public",whenToUse:"When someone is setting up AFK for the first time or asks how to get going \u2014 triggers on `/get-started`, 'how do I start', 'set me up', 'onboard me', or a fresh install with no AFK.md and unconfigured capabilities. Best run in the interactive REPL."};Ct(T2)});function x2(){return`# Agent AFK
|
|
1293
1293
|
|
|
1294
1294
|
## What this process is
|
|
1295
1295
|
|
|
@@ -1445,7 +1445,7 @@ The end-of-turn terminal-state protocol is injected by \`assembleSystemPrompt()\
|
|
|
1445
1445
|
|
|
1446
1446
|
${R2}
|
|
1447
1447
|
|
|
1448
|
-
${r}`}function di(){let e=x2(),t=At(),n=t.systemPrompt,r=t.systemPromptSource,o=e!==void 0&&e.trim().length>0,s=n!==void 0&&n.trim().length>0,i;return o&&s?i=`framework+${r??"unknown"}`:o?i="framework":s?i=r??"unknown":i="none",{prompt:C2(e,n),source:i}}function Re(){let e=v.AFK_MODEL??v.CLAUDE_MODEL;return qe(e)}function hd(){return Tg()}function qe(e){return or(e)}function
|
|
1448
|
+
${r}`}function di(){let e=x2(),t=At(),n=t.systemPrompt,r=t.systemPromptSource,o=e!==void 0&&e.trim().length>0,s=n!==void 0&&n.trim().length>0,i;return o&&s?i=`framework+${r??"unknown"}`:o?i="framework":s?i=r??"unknown":i="none",{prompt:C2(e,n),source:i}}function Re(){let e=v.AFK_MODEL??v.CLAUDE_MODEL;return qe(e)}function hd(){return Tg()}function qe(e){return or(e)}function vt(){let e=v.AFK_MODEL??v.CLAUDE_MODEL;return!e||e.length===0?"sonnet":e}function Vt(e){let t=v.AFK_DEFAULT_SUBAGENT_MODEL;return t&&t.length>0?t:typeof e=="string"&&re(e)==="openai-compatible"?e:"sonnet"}function Vr(e){if(e===void 0)return;if(e==="adaptive")return{type:"adaptive"};if(e==="disabled")return{type:"disabled"};if(e==="enabled:max")return{type:"enabled",budgetTokens:Number.POSITIVE_INFINITY};let t=/^enabled:(\d+)$/.exec(e);if(t){let n=parseInt(t[1],10);if(Number.isNaN(n))throw new Error(`Invalid thinking budget: ${e}`);return{type:"enabled",budgetTokens:n}}throw new Error(`Invalid --thinking value: ${e}. Expected 'adaptive' | 'disabled' | 'enabled:<N>' | 'enabled:max'`)}function Yr(e){if(e!==void 0){if(qR.includes(e))return e;throw new Error(`Invalid --effort value: ${e}. Expected one of: ${qR.join(", ")}`)}}function pi(){return Vr(v.AFK_THINKING)}function mi(){return Yr(v.AFK_EFFORT)}function fi(e){if(e===void 0)return;if(e===""||e==="NaN")throw new Error(`Invalid --max-budget-usd value: ${JSON.stringify(e)}. Expected a non-negative number.`);let t=Number(e);if(!Number.isFinite(t))throw new Error(`Invalid --max-budget-usd value: ${JSON.stringify(e)}. Expected a non-negative number.`);if(t<0)throw new Error(`Invalid --max-budget-usd value: ${JSON.stringify(e)}. Must be non-negative.`);return t}function ey(){return fi(v.AFK_MAX_BUDGET_USD)}function ty(){return fi(v.AFK_TASK_BUDGET)}function gi(e){if(e===void 0)return;if(e==="max")return Number.POSITIVE_INFINITY;if(e===""||e==="NaN")throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(e)}. Expected a positive integer or 'max'.`);if(!/^\d+$/.test(e))throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(e)}. Expected a positive integer or 'max'.`);let t=Number(e);if(!Number.isFinite(t)||!Number.isInteger(t)||t<=0)throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(e)}. Must be a positive integer.`);return t}function il(){return gi(v.AFK_MAX_OUTPUT_TOKENS)}function hi(e,t){let n=e;if(n===void 0&&t?.model!==void 0&&re(t.model,{...t.openaiBaseUrl!==void 0?{openaiBaseUrl:t.openaiBaseUrl}:{}})==="openai-compatible"&&(n="openai-compatible"),n===void 0)return;if(!zR.includes(n))throw new Error(`Invalid --provider value: ${n}. Expected one of: ${zR.join(", ")}`);let r=()=>{let o=[...Wt,...Qn,...pt,$o];return t?.subagentExecutor&&o.push("agent"),t?.skillExecutor&&o.push("skill"),t?.composeExecutor&&o.push("compose"),t?.mcpManager&&o.push(...t.mcpManager.getMcpToolWireNames()),o};if(n==="anthropic"||n==="anthropic-direct")return new Ge({permissions:{allowedTools:r()},subagentExecutor:t?.subagentExecutor,skillExecutor:t?.skillExecutor,composeExecutor:t?.composeExecutor,...t?.memoryStore!==void 0?{memoryStore:t.memoryStore}:{},...t?.mcpManager!==void 0?{mcpManager:t.mcpManager}:{}});if(n==="openai"||n==="openai-compatible")return new $t({permissions:{allowedTools:r()},...t?.subagentExecutor!==void 0?{subagentExecutor:t.subagentExecutor}:{},...t?.skillExecutor!==void 0?{skillExecutor:t.skillExecutor}:{},...t?.composeExecutor!==void 0?{composeExecutor:t.composeExecutor}:{},...t?.memoryStore!==void 0?{memoryStore:t.memoryStore}:{},...t?.mcpManager!==void 0?{mcpManager:t.mcpManager}:{},...t?.openaiBaseUrl!==void 0?{baseURL:t.openaiBaseUrl}:{}})}var R2,qR,zR,ze=_(()=>{"use strict";tt();Va();kn();an();Tn();Ku();Mt();Ks();q();R2=`# Operator configuration
|
|
1449
1449
|
|
|
1450
1450
|
The instructions below come from this operator's configuration (AFK.md, afk.config.json, or AFK_SYSTEM_PROMPT). Treat them as refinements layered on top of the operating posture above \u2014 follow them unless they conflict with the Priorities or Constraints already stated.`;qR=["low","medium","high","xhigh","max"];zR=["anthropic","anthropic-direct","openai-codex","openai","openai-compatible"]});async function JR(e,t,n,r,o="sonnet"){let i=He("mint")["spec.md"];if(!i)throw new Error("mint skill missing spec.md prompt");let c=await(await new se(n!==void 0?{cwd:n}:{}).forkSubagent({parent:{sessionId:t},config:{model:o,systemPrompt:i,apiKey:Re()},idPrefix:"mint-spec",phaseRole:"read-only",...r?{parentId:r}:{}})).runToResult(`Create a detailed specification for: ${e}`);if(c.status!=="succeeded"||!c.message)throw new Error(`spec phase failed: ${ct(c)}`);return c.message.content}var VR=_(()=>{"use strict";Xe();zt();ze();tn()});async function YR(e,t,n,r,o="sonnet"){let i=He("mint")["research.md"];if(!i)throw new Error("mint skill missing research.md prompt");let c=await(await new se(n!==void 0?{cwd:n}:{}).forkSubagent({parent:{sessionId:t},config:{model:o,systemPrompt:i,apiKey:Re()},idPrefix:"mint-research",phaseRole:"read-only",...r?{parentId:r}:{}})).runToResult(`Gather context and research for this specification:
|
|
1451
1451
|
|
|
@@ -1455,7 +1455,7 @@ ${e}
|
|
|
1455
1455
|
Research findings:
|
|
1456
1456
|
${t}
|
|
1457
1457
|
|
|
1458
|
-
Create a detailed implementation plan based on the spec and research.`,d=await c.runToResult(u);if(d.status!=="succeeded"||!d.message)throw new Error(`plan phase failed: ${ct(d)}`);return d.message.content}var QR=_(()=>{"use strict";Xe();zt();ze();tn()});function A2(e){let t=/[\w./@-]*\.(?:ts|tsx|js|jsx|mjs|cjs|py|md|json|yaml|yml|toml|sh)\b/gi,n=new Set;for(let r of e.matchAll(t))n.add(r[0].toLowerCase());return n.size}async function eC(e,t,n,r="sonnet"){if(A2(e)<3)return{kind:"skipped",reason:"too-few-files"};let s=!1;try{let i=Ke("parallelize");return s=!0,{kind:"plan",plan:await i.handler({plan:e})}}catch(i){if(s)return{kind:"failed",error:`parallelize skill handler threw: ${i instanceof Error?i.message:String(i)}`}}try{let a=id().get("parallelize");if(!a)return{kind:"skipped",reason:"skill-body-missing"};let l=new se({parentAbortSignal:t.abortSignal,apiKey:Re(),...t.cwd!==void 0?{cwd:t.cwd}:{}});try{let u=await(await l.forkSubagent({parent:{sessionId:t.sessionId},config:{model:r,systemPrompt:a.body,env:{PLUGIN_ROOT:a.pluginPath}},idPrefix:"mint-parallelize",...n?{parentId:n}:{}})).runToResult(JSON.stringify({plan:e}));return u.status==="succeeded"&&u.message?{kind:"plan",plan:u.message.content}:u.status!=="succeeded"?{kind:"failed",error:`parallelize subagent status=${u.status}${u.error?.message?`: ${u.error.message}`:""}`}:{kind:"failed",error:"parallelize subagent returned no message"}}finally{await l.teardownAll()}}catch(i){return{kind:"failed",error:`parallelize dispatch threw: ${i instanceof Error?i.message:String(i)}`}}}var tC=_(()=>{"use strict";
|
|
1458
|
+
Create a detailed implementation plan based on the spec and research.`,d=await c.runToResult(u);if(d.status!=="succeeded"||!d.message)throw new Error(`plan phase failed: ${ct(d)}`);return d.message.content}var QR=_(()=>{"use strict";Xe();zt();ze();tn()});function A2(e){let t=/[\w./@-]*\.(?:ts|tsx|js|jsx|mjs|cjs|py|md|json|yaml|yml|toml|sh)\b/gi,n=new Set;for(let r of e.matchAll(t))n.add(r[0].toLowerCase());return n.size}async function eC(e,t,n,r="sonnet"){if(A2(e)<3)return{kind:"skipped",reason:"too-few-files"};let s=!1;try{let i=Ke("parallelize");return s=!0,{kind:"plan",plan:await i.handler({plan:e})}}catch(i){if(s)return{kind:"failed",error:`parallelize skill handler threw: ${i instanceof Error?i.message:String(i)}`}}try{let a=id().get("parallelize");if(!a)return{kind:"skipped",reason:"skill-body-missing"};let l=new se({parentAbortSignal:t.abortSignal,apiKey:Re(),...t.cwd!==void 0?{cwd:t.cwd}:{}});try{let u=await(await l.forkSubagent({parent:{sessionId:t.sessionId},config:{model:r,systemPrompt:a.body,env:{PLUGIN_ROOT:a.pluginPath}},idPrefix:"mint-parallelize",...n?{parentId:n}:{}})).runToResult(JSON.stringify({plan:e}));return u.status==="succeeded"&&u.message?{kind:"plan",plan:u.message.content}:u.status!=="succeeded"?{kind:"failed",error:`parallelize subagent status=${u.status}${u.error?.message?`: ${u.error.message}`:""}`}:{kind:"failed",error:"parallelize subagent returned no message"}}finally{await l.teardownAll()}}catch(i){return{kind:"failed",error:`parallelize dispatch threw: ${i instanceof Error?i.message:String(i)}`}}}var tC=_(()=>{"use strict";wt();Ur();Xe();ze()});function yi(e){let t=Ht();t&&t({type:"panel",spec:e},{subagentId:"__main__"})}var yd=_(()=>{"use strict";Xn()});import{z as mr}from"zod";async function nC(e,t,n,r,o,s="sonnet"){let a=He("mint")["build.md"];if(!a)throw new Error("mint skill missing build.md prompt");let c=await new se(r!==void 0?{cwd:r}:{}).forkSubagent({parent:{sessionId:n},config:{model:s,systemPrompt:a,apiKey:Re()},idPrefix:"mint-build",outputSchema:_2,...o?{parentId:o}:{}}),u=`Implementation plan:
|
|
1459
1459
|
${e}
|
|
1460
1460
|
|
|
1461
1461
|
`+(t?`Wave orchestration plan:
|
|
@@ -1484,7 +1484,7 @@ ${u}
|
|
|
1484
1484
|
Verification issues:
|
|
1485
1485
|
${h}
|
|
1486
1486
|
|
|
1487
|
-
Apply the fix and update the implementation.`,y=await g.runToResult(b);if(y.status!=="succeeded"||!y.message)throw new Error(`heal phase failed: ${ct(y)}`);let S=/^\s*FIX_APPLIED:\s*(true|false)/im.exec(y.message.content)?.[1]?.toLowerCase()==="true",w=r+1;if(!S)return{healed:!1,newHealIterations:w,newVerifyResults:n};if(!o.sessionId)throw new Error("Parent session ID required for verification");let T=await bd(e,t,o.sessionId,o.cwd,s,i);return{healed:T.testsPassed&&T.lintPassed&&T.designReviewPassed,newHealIterations:w,newVerifyResults:T}}catch{return{healed:!1,newHealIterations:r+1,newVerifyResults:n}}}var sC=_(()=>{"use strict";
|
|
1487
|
+
Apply the fix and update the implementation.`,y=await g.runToResult(b);if(y.status!=="succeeded"||!y.message)throw new Error(`heal phase failed: ${ct(y)}`);let S=/^\s*FIX_APPLIED:\s*(true|false)/im.exec(y.message.content)?.[1]?.toLowerCase()==="true",w=r+1;if(!S)return{healed:!1,newHealIterations:w,newVerifyResults:n};if(!o.sessionId)throw new Error("Parent session ID required for verification");let T=await bd(e,t,o.sessionId,o.cwd,s,i);return{healed:T.testsPassed&&T.lintPassed&&T.designReviewPassed,newHealIterations:w,newVerifyResults:T}}catch{return{healed:!1,newHealIterations:r+1,newVerifyResults:n}}}var sC=_(()=>{"use strict";wt();Xe();zt();ze();tn();ry()});async function iC(e,t,n,r,o="sonnet"){let i=He("mint")["ship.md"];if(!i)throw new Error("mint skill missing ship.md prompt");let l=await new se(n!==void 0?{cwd:n}:{}).forkSubagent({parent:{sessionId:t},config:{model:o,systemPrompt:i,apiKey:Re()},idPrefix:"mint-ship",...r?{parentId:r}:{}}),c=`Idea: ${e.idea}
|
|
1488
1488
|
|
|
1489
1489
|
Specification:
|
|
1490
1490
|
${e.spec}
|
|
@@ -1500,7 +1500,7 @@ ${JSON.stringify(e.verifyResults,null,2)}
|
|
|
1500
1500
|
|
|
1501
1501
|
Heal iterations used: ${e.healIterations}
|
|
1502
1502
|
|
|
1503
|
-
Create a ship-ready summary with next steps.`,u=await l.runToResult(c);if(u.status!=="succeeded"||!u.message)throw new Error(`ship phase failed: ${ct(u)}`);let d=e.buildResults?.filesChanged.length??0,p=e.healIterations;return yi({kind:"checkpoint",title:"ship \u2014 done",body:[`Files changed: ${d}`,`Heal iterations: ${p}`,`Idea: ${e.idea}`]}),u.message.content}var aC=_(()=>{"use strict";Xe();zt();ze();tn();yd()});import{existsSync as lC,mkdirSync as P2,readFileSync as M2,unlinkSync as O2,writeFileSync as $2}from"fs";import{dirname as D2,join as L2}from"path";function oy(e){return L2(Gn(),e,"mint-state.json")}function cC(e,t){let n=oy(e);P2(D2(n),{recursive:!0}),$2(n,JSON.stringify(t,null,2),"utf-8")}function F2(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.currentPhase=="string"&&typeof t.idea=="string"&&typeof t.spec=="string"&&typeof t.healIterations=="number"&&Array.isArray(t.history)}function uC(e){let t=oy(e);if(!lC(t))return null;try{let n=JSON.parse(M2(t,"utf-8"));return F2(n)?n:null}catch{return null}}function sy(e){let t=oy(e);if(lC(t))try{O2(t)}catch{}}var dC=_(()=>{"use strict";G()});function On(e,t,n){e.history.push({phase:t,output:n,timestamp:Date.now()})}function hC(e){if("completed"in e&&"paused"in e)throw new Error("mint: invariant violation \u2014 MintResult carries both completed and paused keys simultaneously")}function U2(e){return e.length<=mC?e:e.slice(0,mC)+"\u2026"}function yC(e){if(typeof e=="string"){if(pC.test(e))return{userApproved:!0};if(e.length>1&&e.trimStart().startsWith("{"))try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null)return yC(t)}catch{}return{idea:e}}if(typeof e=="object"&&e!==null){let t=e,n=typeof t.idea=="string"?t.idea:void 0;if(n!==void 0&&pC.test(n))return{userApproved:!0};if("idea"in t||"resumeFrom"in t||t.userApproved===!0)return t}throw new Error("mint handler requires input.idea (string), input as string, or {userApproved: true} to resume")}async function fC(e,t,n,r="sonnet"){if(!t.sessionId)throw new Error("runPhasesAfterSpec requires parentSession.sessionId");let o=t.sessionId,s=t.cwd;try{e.currentPhase="research",e.research=await YR(e.spec,o,s,n,r),On(e,"research",e.research),e.currentPhase="plan",e.plan=await ZR(e.spec,e.research,o,s,n,r),On(e,"plan",e.plan),e.currentPhase="parallelize";let i=await eC(e.plan,t,n,r);if(i.kind==="plan")e.waveOrchestrationPlan=i.plan,On(e,"parallelize",JSON.stringify(i.plan));else if(i.kind==="skipped")e.waveOrchestrationPlan=void 0,On(e,"parallelize",`skipped: ${i.reason}`);else if(i.kind==="failed"){e.waveOrchestrationPlan=void 0;let c=U2(i.error);On(e,"parallelize",`failed: ${c}`),Be({event:"fallback.inline",parent_session_id:o,reason:"parallelize-dispatch-failed",error_message:c}),console.warn(`[mint] parallelize dispatch failed (single-lane fallback): ${c}`)}else{let c=i}e.currentPhase="build",e.buildResults=await nC(e.plan,e.waveOrchestrationPlan,o,s,n,r),On(e,"build",JSON.stringify(e.buildResults)),e.currentPhase="verify",e.verifyResults=await bd(e.plan,e.buildResults,o,s,n,r),On(e,"verify",JSON.stringify(e.verifyResults)),e.currentPhase="heal";let a=e.verifyResults.testsPassed&&e.verifyResults.lintPassed&&e.verifyResults.designReviewPassed;for(;!a&&e.healIterations<N2;){let c=await oC(e.plan,e.buildResults,e.verifyResults,e.healIterations,t,n,r);e.healIterations=c.newHealIterations,e.verifyResults=c.newVerifyResults,a=c.healed,On(e,"heal",`Iterations: ${e.healIterations}, Success: ${a}`)}if(!a)return{paused:!0,phase:"heal-failed",reason:`Heal capped at ${e.healIterations} iterations; still have failures`,state:e,nextStep:"Heal loop exhausted. Inspect verifyResults, fix manually, then re-invoke /mint with a fresh idea \u2014 resume is not supported from heal-failed."};e.currentPhase="ship";let l=await iC(e,o,s,n,r);return On(e,"ship",l),{completed:!0,artifact:l,state:e}}catch(i){throw new Error(`mint failed at ${e.currentPhase}: ${i}`)}}function gC(e,t){return hC(t),("completed"in t||t.phase==="heal-failed")&&sy(e),t}async function j2(e,t,n){let r=yC(e);if(!t?.sessionId)throw new Error("mint handler requires a parent session to fork subagents");let o=t.sessionId,s=n?.callId,i=n?.defaultSubagentModel??n?.defaultModel??"sonnet";if(r.userApproved){let c=r.resumeFrom??uC(o);if(!c)throw new Error("mint: no paused spec found for this session to continue. Run /mint <idea> first, then /mint --continue approved.");let u=await fC(c,t,s,i);return gC(o,u)}if(!r.idea)throw new Error("mint: no idea provided. Run /mint <idea> to start, or /mint --continue approved to resume a paused spec.");sy(o);let a={currentPhase:"spec",idea:r.idea,healIterations:0,history:[]};try{a.spec=await JR(r.idea,o,t.cwd,s,i),On(a,"spec",a.spec)}catch(c){throw new Error(`mint failed at spec: ${c}`)}if(!r.autoApprove){cC(o,a);let c={paused:!0,phase:"spec",spec:a.spec,state:a,nextStep:B2};return hC(c),c}let l=await fC(a,t,s,i);return gC(o,l)}var N2,pC,B2,mC,H2,bC=_(()=>{"use strict";
|
|
1503
|
+
Create a ship-ready summary with next steps.`,u=await l.runToResult(c);if(u.status!=="succeeded"||!u.message)throw new Error(`ship phase failed: ${ct(u)}`);let d=e.buildResults?.filesChanged.length??0,p=e.healIterations;return yi({kind:"checkpoint",title:"ship \u2014 done",body:[`Files changed: ${d}`,`Heal iterations: ${p}`,`Idea: ${e.idea}`]}),u.message.content}var aC=_(()=>{"use strict";Xe();zt();ze();tn();yd()});import{existsSync as lC,mkdirSync as P2,readFileSync as M2,unlinkSync as O2,writeFileSync as $2}from"fs";import{dirname as D2,join as L2}from"path";function oy(e){return L2(Gn(),e,"mint-state.json")}function cC(e,t){let n=oy(e);P2(D2(n),{recursive:!0}),$2(n,JSON.stringify(t,null,2),"utf-8")}function F2(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.currentPhase=="string"&&typeof t.idea=="string"&&typeof t.spec=="string"&&typeof t.healIterations=="number"&&Array.isArray(t.history)}function uC(e){let t=oy(e);if(!lC(t))return null;try{let n=JSON.parse(M2(t,"utf-8"));return F2(n)?n:null}catch{return null}}function sy(e){let t=oy(e);if(lC(t))try{O2(t)}catch{}}var dC=_(()=>{"use strict";G()});function On(e,t,n){e.history.push({phase:t,output:n,timestamp:Date.now()})}function hC(e){if("completed"in e&&"paused"in e)throw new Error("mint: invariant violation \u2014 MintResult carries both completed and paused keys simultaneously")}function U2(e){return e.length<=mC?e:e.slice(0,mC)+"\u2026"}function yC(e){if(typeof e=="string"){if(pC.test(e))return{userApproved:!0};if(e.length>1&&e.trimStart().startsWith("{"))try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null)return yC(t)}catch{}return{idea:e}}if(typeof e=="object"&&e!==null){let t=e,n=typeof t.idea=="string"?t.idea:void 0;if(n!==void 0&&pC.test(n))return{userApproved:!0};if("idea"in t||"resumeFrom"in t||t.userApproved===!0)return t}throw new Error("mint handler requires input.idea (string), input as string, or {userApproved: true} to resume")}async function fC(e,t,n,r="sonnet"){if(!t.sessionId)throw new Error("runPhasesAfterSpec requires parentSession.sessionId");let o=t.sessionId,s=t.cwd;try{e.currentPhase="research",e.research=await YR(e.spec,o,s,n,r),On(e,"research",e.research),e.currentPhase="plan",e.plan=await ZR(e.spec,e.research,o,s,n,r),On(e,"plan",e.plan),e.currentPhase="parallelize";let i=await eC(e.plan,t,n,r);if(i.kind==="plan")e.waveOrchestrationPlan=i.plan,On(e,"parallelize",JSON.stringify(i.plan));else if(i.kind==="skipped")e.waveOrchestrationPlan=void 0,On(e,"parallelize",`skipped: ${i.reason}`);else if(i.kind==="failed"){e.waveOrchestrationPlan=void 0;let c=U2(i.error);On(e,"parallelize",`failed: ${c}`),Be({event:"fallback.inline",parent_session_id:o,reason:"parallelize-dispatch-failed",error_message:c}),console.warn(`[mint] parallelize dispatch failed (single-lane fallback): ${c}`)}else{let c=i}e.currentPhase="build",e.buildResults=await nC(e.plan,e.waveOrchestrationPlan,o,s,n,r),On(e,"build",JSON.stringify(e.buildResults)),e.currentPhase="verify",e.verifyResults=await bd(e.plan,e.buildResults,o,s,n,r),On(e,"verify",JSON.stringify(e.verifyResults)),e.currentPhase="heal";let a=e.verifyResults.testsPassed&&e.verifyResults.lintPassed&&e.verifyResults.designReviewPassed;for(;!a&&e.healIterations<N2;){let c=await oC(e.plan,e.buildResults,e.verifyResults,e.healIterations,t,n,r);e.healIterations=c.newHealIterations,e.verifyResults=c.newVerifyResults,a=c.healed,On(e,"heal",`Iterations: ${e.healIterations}, Success: ${a}`)}if(!a)return{paused:!0,phase:"heal-failed",reason:`Heal capped at ${e.healIterations} iterations; still have failures`,state:e,nextStep:"Heal loop exhausted. Inspect verifyResults, fix manually, then re-invoke /mint with a fresh idea \u2014 resume is not supported from heal-failed."};e.currentPhase="ship";let l=await iC(e,o,s,n,r);return On(e,"ship",l),{completed:!0,artifact:l,state:e}}catch(i){throw new Error(`mint failed at ${e.currentPhase}: ${i}`)}}function gC(e,t){return hC(t),("completed"in t||t.phase==="heal-failed")&&sy(e),t}async function j2(e,t,n){let r=yC(e);if(!t?.sessionId)throw new Error("mint handler requires a parent session to fork subagents");let o=t.sessionId,s=n?.callId,i=n?.defaultSubagentModel??n?.defaultModel??"sonnet";if(r.userApproved){let c=r.resumeFrom??uC(o);if(!c)throw new Error("mint: no paused spec found for this session to continue. Run /mint <idea> first, then /mint --continue approved.");let u=await fC(c,t,s,i);return gC(o,u)}if(!r.idea)throw new Error("mint: no idea provided. Run /mint <idea> to start, or /mint --continue approved to resume a paused spec.");sy(o);let a={currentPhase:"spec",idea:r.idea,healIterations:0,history:[]};try{a.spec=await JR(r.idea,o,t.cwd,s,i),On(a,"spec",a.spec)}catch(c){throw new Error(`mint failed at spec: ${c}`)}if(!r.autoApprove){cC(o,a);let c={paused:!0,phase:"spec",spec:a.spec,state:a,nextStep:B2};return hC(c),c}let l=await fC(a,t,s,i);return gC(o,l)}var N2,pC,B2,mC,H2,bC=_(()=>{"use strict";wt();VR();XR();QR();tC();Yn();rC();ry();sC();aC();dC();N2=2,pC=/^\s*(?:--continue(?:\s+(?:approved|yes|y))?|approved?|yes|y|lgtm|sure)\s*$/i,B2='To approve and run the rest of the pipeline, say "approve", "yes", "sure", or "lgtm" \u2014 or invoke /mint --continue approved. The handler will reload the spec state from disk.';mC=240;H2={name:"mint",description:"Takes a feature idea or refactor scope and delivers a ship-ready, verified implementation end-to-end",handler:j2,argumentHint:"<idea> | --continue [approved]",whenToUse:'When the user wants a feature or refactor delivered end-to-end (spec \u2192 research \u2192 build \u2192 verify) in one ship-ready pass. After the spec phase pauses for approval, resume by invoking mint again with the literal string `"approved"` (or `"yes"`, `"lgtm"`, `"--continue approved"`) as the arguments. Equivalent JSON forms `{"userApproved": true}` and `{"idea": "approved"}` are also accepted. The handler reloads the spec state from disk and runs phases 2\u20138.',flags:["--continue"]};Ct(H2)});async function W2(){throw new Error("service-setup is a fork skill; its handler should never be called directly. Invoke via the `skill` tool or `/service-setup` slash command.")}var K2,wC=_(()=>{"use strict";wt();K2={name:"service-setup",description:"Install an AFK background process (telegram bot or daemon) as a macOS LaunchAgent so it auto-starts on login and relaunches on crash. Runs pre-flight checks (e.g., refuses to install the telegram service with an invalid token, which would otherwise crash-loop under KeepAlive), invokes `afk service install`, verifies with `afk service status`, and surfaces the management cheatsheet. macOS-only \u2014 gracefully refuses on other platforms.",handler:W2,context:"fork",whenToUse:"When the user wants to make `afk telegram start` or `afk daemon` always-on \u2014 i.e., survive reboot, crash, OOM. Triggers on phrasings like 'install as a service', 'auto-start on login', 'keep the bot running', 'launchd', 'always-on telegram', or right after a successful `/telegram-setup` when the user asks how to make it persistent."};Ct(K2)});async function G2(){throw new Error("telegram-setup is a fork skill; its handler should never be called directly. Invoke via the `skill` tool or `/telegram-setup` slash command.")}var q2,SC=_(()=>{"use strict";wt();q2={name:"telegram-setup",description:"Guide the user through first-time Telegram bot onboarding without leaking the bearer token. Walks the user to run `afk telegram setup` in a terminal for token entry, then uses the sanctioned `afk telegram check-token`/`discover-chat`/`set-allowed-chat` subcommands to validate and finish allowlist setup \u2014 the token never enters the model context. Works in REPL or Telegram. Use when the user wants to set up Telegram push notifications for the first time, or to debug a partially-configured install.",handler:G2,context:"fork",whenToUse:`When the user wants to set up Telegram bot notifications for the first time, or when they say something like "set up telegram", "connect telegram", "enable push", or you detect that TELEGRAM_BOT_TOKEN is unset and they're asking for notifications.`};Ct(q2)});function vC(e){return e.startsWith("--")?e:`--${e}`}function J2(e){let t=new Set;for(let n of e.matchAll(z2))n[1]&&t.add(`--${n[1]}`);return Array.from(t).sort()}function iy(e){if(!e.startsWith(`---
|
|
1504
1504
|
`))return{frontmatter:null,frontmatterFlags:null,body:e};let t=e.indexOf(`
|
|
1505
1505
|
---
|
|
1506
1506
|
`,4);if(t===-1)return{frontmatter:null,frontmatterFlags:null,body:e};let n=e.slice(4,t),r=e.slice(t+5),o={},s=null,i=n.split(`
|
|
@@ -1509,14 +1509,14 @@ ${t.body}`)}var z2,ay=_(()=>{"use strict";z2=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9
|
|
|
1509
1509
|
`),null;if(o.length>EC)return process.stderr.write(`[afk] skipping skill ${t}: description exceeds ${EC} characters (got ${o.length})
|
|
1510
1510
|
`),null;let a=n.frontmatter["argument-hint"]??n.frontmatter.argumentHint,l=wd(e),c={name:r,description:o,body:s,dir:""};a&&a.length>0&&(c.argumentHint=a),l.length>0&&(c.flags=l);let u=n.frontmatter.context;return(u==="inline"||u==="fork"||u==="load")&&(c.context=u),c}function Q2(e){return async(t,n,r)=>{let o=r?.defaultSubagentModel??r?.defaultModel??"sonnet",s=typeof t=="string"&&t.length>0?t:`Run the ${e.name} skill now, following the instructions in your system prompt.`,i=new se({parentAbortSignal:n?.abortSignal}),a=r?.callId;return await(await i.forkSubagent({parent:{sessionId:n?.sessionId,getInputStreamRef:n?.getInputStreamRef?.bind(n),abortSignal:n?.abortSignal},config:{model:o,systemPrompt:e.body,env:{SKILL_ROOT:e.dir},isSkillDispatch:!0},idPrefix:`user-skill-${e.name}`,...a?{parentId:a}:{}})).runToResult(s)}}function eq(e,t){try{return Ke(e).origin===t?e:`${t}:${e}`}catch{return e}}function fr(e,t){let n;try{n=V2(e,{withFileTypes:!0})}catch(o){let s=o;return s.code!=="ENOENT"&&process.stderr.write(`[afk] skipping skills dir ${e}: ${s.message}
|
|
1511
1511
|
`),0}let r=0;for(let o of n){if(!o.isDirectory()||o.name.startsWith("_")||o.name.startsWith("."))continue;let s;try{s=Y2(kC(e,o.name,"SKILL.md"),"utf-8")}catch(c){let u=c;u.code!=="ENOENT"&&process.stderr.write(`[afk] skipping skill ${o.name}: ${u.message}
|
|
1512
|
-
`);continue}let i=Z2(s,o.name);if(!i)continue;i.dir=kC(e,o.name);let l={name:eq(i.name,t),description:i.description,handler:Q2(i),origin:t};i.argumentHint&&(l.argumentHint=i.argumentHint),i.flags&&i.flags.length>0&&(l.flags=i.flags),i.context!=="fork"&&(l.context="load",l.loadBody=i.body.replace(/\$\{?SKILL_ROOT\}?/g,()=>i.dir)),Ct(l),r++}return r}function ly(){return fr(cc(),"user")}var EC,cy=_(()=>{"use strict";G();
|
|
1512
|
+
`);continue}let i=Z2(s,o.name);if(!i)continue;i.dir=kC(e,o.name);let l={name:eq(i.name,t),description:i.description,handler:Q2(i),origin:t};i.argumentHint&&(l.argumentHint=i.argumentHint),i.flags&&i.flags.length>0&&(l.flags=i.flags),i.context!=="fork"&&(l.context="load",l.loadBody=i.body.replace(/\$\{?SKILL_ROOT\}?/g,()=>i.dir)),Ct(l),r++}return r}function ly(){return fr(cc(),"user")}var EC,cy=_(()=>{"use strict";G();wt();ay();Xe();EC=1024});var uy=_(()=>{"use strict";RR();KR();GR();bC();wC();SC();cy()});import{isAbsolute as tq,resolve as nq}from"path";import{pathToFileURL as rq}from"url";async function xC(e,t={}){let n=t.importer??(r=>import(r));for(let r of e){if(r.main===void 0)continue;let o=tq(r.main)?r.main:nq(r.path,r.main);if(!TC.has(o)){TC.add(o);try{await n(rq(o).href)}catch(s){t.onError?.(r,s)}}}}var TC,RC=_(()=>{"use strict";TC=new Set});import{existsSync as oq,readdirSync as sq,readFileSync as iq,statSync as aq}from"fs";import{join as lq}from"path";function uq(e,t){let n=e.trim();if(n.length===0)return;if(t.has(n))return n;let r=cq[n.toLowerCase()];if(r!==void 0&&t.has(r))return r}function Sd(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).trim():t}function dq(e,t){let n=e.trim();if(n.length>0)return n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1).split(",").map(i=>Sd(i)).filter(i=>i.length>0):Sd(n).split(",").map(s=>Sd(s)).filter(s=>s.length>0);let r=[];for(let o of t){let s=o.trim();if(s.startsWith("- "))r.push(Sd(s.slice(2)));else break}return r}function dy(e,t){let n=[];function r(o,s=0){if(s>10||!oq(o))return;let i;try{i=sq(o)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=lq(o,a),c;try{c=aq(l)}catch{continue}if(c.isFile()&&a==="SKILL.md"){let u=pq(l,t);u.name&&n.push(u)}else c.isDirectory()&&r(l,s+1)}}return r(e),n}function pq(e,t){try{let n=iq(e,"utf-8");if(!n.startsWith(`---
|
|
1513
1513
|
`))return{};let r=n.slice(4),o=r.indexOf(`
|
|
1514
1514
|
---`);if(o===-1)return{};let s=r.slice(0,o),i=r.slice(o+4).trim(),a={},l=s.split(`
|
|
1515
1515
|
`);for(let c=0;c<l.length;c++){let u=l[c];if(!u)continue;let d=u.indexOf(":");if(d===-1)continue;let p=u.slice(0,d).trim(),m=u.slice(d+1).trim();if(p==="name")a.name=m.replace(/^["']|["']$/g,"");else if(p==="description")a.description=m.replace(/^["']|["']$/g,"");else if(p==="argumentHint")a.argumentHint=m.replace(/^["']|["']$/g,"");else if(p==="tools"){let g=l.slice(c+1),h=dq(m,g),b=mq(t),y=[];for(let S of h){let w=uq(S,b);w!==void 0?y.includes(w)||y.push(w):process.stderr.write(`[afk] plugin skill at ${e}: unknown tool "${S}" in \`tools:\` frontmatter \u2014 ignored
|
|
1516
1516
|
`)}y.length===0&&h.length>0&&process.stderr.write(`[afk] plugin skill at ${e}: \`tools:\` declared but no valid tools resolved \u2014 subagent will be blocked from all tools
|
|
1517
1517
|
`),a.allowedTools=y}else if(p==="audience"){let g=m.replace(/^["']|["']$/g,"");(g==="public"||g==="internal")&&(a.audience=g)}else p==="context"?a.context=m.replace(/^["']|["']$/g,""):(p==="read-only"||p==="readOnly")&&m.replace(/^["']|["']$/g,"").trim()==="true"&&(a.readOnly=!0)}return i.length>0&&(a.body=i),a}catch{return{}}}function mq(e){return e!==void 0?e:new Set([...Wt,...pt,"memory_search","agent","skill"])}var cq,CC=_(()=>{"use strict";kn();Tn();cq={read:"read_file",edit:"edit_file",write:"write_file",bash:"bash",grep:"grep",glob:"glob",ls:"list_directory",list:"list_directory",webfetch:"web_scrape",websearch:"web_scrape",webbrowse:"web_scrape"}});function AC(e){let t=cr(e);if(t.length===0)return"";let n=[];for(let r of t){let o=r.argumentHint?`${r.argumentHint}`:"",s=o?`- \`${r.name} ${o}\`: ${r.description}`:`- ${r.name}: ${r.description}`;n.push(s),r.whenToUse&&n.push(` When to use: ${r.whenToUse}`)}return["Available skills (invoke via the `skill` tool):","","Each skill either dispatches one or more context-isolated subagents (delegation \u2014 preserves the main session's context) or loads its instructions directly into your current context (`load` mode). Calling `skill` is the entry point for both; the executor picks the mode per skill. Prefer a skill over inline investigation when the task shape matches.","",...n].join(`
|
|
1518
|
-
`)}function cr(e){let t=[],n=new Set,r=v.AFK_INTERNAL==="1",o=rn(Pt());fr(cc(),"user"),fr(uc(),"project");for(let{dir:i,origin:a}of o.skillRoots)fr(i,a);for(let i of Vn()){let a=Ke(i);nn(a,r)&&(t.push({name:i,description:a.description,source:a.origin==="user"?"user":a.origin==="project"?"project":a.origin?.startsWith("imported:")?"imported":"builtin",argumentHint:a.argumentHint,whenToUse:a.whenToUse}),n.add(i))}let s=e??py();for(let i of s){if(i.type!=="local")continue;let a=dy(i.path);for(let l of a)!l.name||n.has(l.name)||nn({audience:l.audience},r)&&(t.push({name:l.name,description:l.description??`Skill from plugin at ${i.path}`,source:"plugin"}),n.add(l.name))}return t}function id(e){let t=new Map,n=e??py();for(let r of n){if(r.type!=="local")continue;let o=dy(r.path);for(let s of o)s.name&&s.body&&s.body.length>0&&!t.has(s.name)&&t.set(s.name,{body:s.body,pluginPath:r.path,...s.allowedTools!==void 0?{allowedTools:s.allowedTools}:{},...s.context!==void 0?{context:s.context}:{},...s.readOnly===!0?{readOnly:!0}:{}})}return t}function py(){return[...dr(dc()),...dr(),...dr(vs()),...rn(Pt()).pluginRoots.flatMap(e=>dr(e,{trustAll:!0}))]}async function _C(){await xC(py())}var Ur=_(()=>{"use strict";uy();
|
|
1519
|
-
`)[0];return" "+(i.length>80?i.slice(0,77)+"\u2026":i)}let s=n.query??n.pattern??n.url??n.description;return typeof s=="string"?" "+s:""}async function*fy(e){let t=e.maxToolUseIterations??Sq,n={stopReason:null},r=0,o=0,s=wq(),i=Date.now(),a=l=>({...l,durationMs:Date.now()-i});De(e.traceWriter,{phase:"loop_start"});try{for(;;){if(e.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}let l=Dc({baseUrl:e.baseUrl})?Nv(e.messages,Lc()):e.messages,c={model:e.model,max_tokens:e.maxTokens,messages:l,stream:!0,...e.system!==null?{system:e.system}:{},...e.tools!==null&&e.tools.length>0?{tools:e.tools.map(vq)}:{},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{output_config:{effort:e.effort}}:{}},u=Date.now(),d;try{d=await Eq(e.client,c,e.headers,e.signal)}catch(w){if(e.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}let T=w instanceof Error?w:new Error(String(w));T.message.includes("thinking")&&xq(e.messages,T),yield{type:"error",error:T};return}let p=null,m=!1,g=!1,h=!1;try{v.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let w of FC(d,e.ctx))if(h||(h=!0,De(e.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-u,resolvedModel:e.model})),v.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",w.kind,w.kind==="event"?w.event.type:""),w.kind==="event"){if(w.event.type==="error"){if(BC(w.event.error)&&o<my&&!e.signal.aborted){g=!0;break}yield w.event,m=!0;break}yield w.event}else{p=w.result;break}v.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",p?"set":"null")}catch(w){if(e.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}let T=w instanceof Error?w:new Error(String(w));if(BC(T)&&o<my&&!e.signal.aborted)g=!0;else{yield{type:"error",error:T};return}}if(g){if(o+=1,yield{type:"stream.retry",sessionId:e.ctx.sessionId},await jC(UC*Math.pow(2,o-1),e.signal),e.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}continue}if(o=0,m){e.signal.aborted&&(yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId});return}if(p===null){yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}let b=DC(p.usage,p.stopReason,e.model);if(n=Wa(n,b),n.contextWindowTokens=(b.inputTokens??0)+(b.outputTokens??0)+(b.cachedInputTokens??0)+(b.cacheCreationTokens??0),e.onUsageProgress?.(n),p.stopReason!=="tool_use"){if(p.stopReason==="refusal"){yield{type:"assistant.message",text:p.text.length>0?p.text:`The model stopped with a content-safety refusal (stop_reason: "refusal") and returned no output. This is Anthropic's safety system declining the request \u2014 not an afk error. Because the flagged context stays in the conversation, follow-up messages will likely be refused the same way; rephrase the request or start a fresh session to continue.`,sessionId:e.ctx.sessionId},yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}p.text.length>0&&(yield{type:"assistant.message",text:p.text,sessionId:e.ctx.sessionId},p.text.length<=200&&(yield{type:"suggestion",suggestion:p.text,sessionId:e.ctx.sessionId}));let w=p.assistantBlocks.filter(T=>T.type!=="tool_use");w.length>0&&e.messages.push({role:"assistant",content:w}),yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}let y=e.messages.length;e.messages.push({role:"assistant",content:p.assistantBlocks});try{let w=[],T=new Map;for(let k of p.toolUseBlocks){w.push({id:k.id,name:k.name,input:k.input,signal:e.signal});let $=Date.now();T.set(k.id,$),Is(e.traceWriter,{phase:"started",toolUseId:k.id,name:k.name,inputBytes:Buffer.byteLength(JSON.stringify(k.input??{}),"utf8")}),yield{type:"tool.use.start",toolUseId:k.id,toolName:k.name,toolInput:Tq(k.name,k.input),toolInputRaw:zu(k.input),sessionId:e.ctx.sessionId}}if(e.signal.aborted){let k=w.map($=>({type:"tool_result",tool_use_id:$.id,content:"Tool call aborted",is_error:!0}));e.messages.push({role:"user",content:k}),yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}let x;if(e.toolDispatcher.executeBatch)try{x=await e.toolDispatcher.executeBatch(w)}catch(k){x=w.map(()=>({content:`Tool batch execution failed: ${k instanceof Error?k.message:String(k)}`,isError:!0}))}else{x=[];for(let k of w){if(e.signal.aborted){x.push({content:"Tool call aborted",isError:!0});continue}try{x.push(await e.toolDispatcher.execute(k))}catch($){let A=$ instanceof Error?$.message:String($);x.push({content:`Tool execution threw: ${A}`,isError:!0})}}}let C=[];for(let k=0;k<w.length;k++){let $=w[k],A=x[k],P=T.get($.id),F=typeof P=="number"?Date.now()-P:0,D=A.truncated===!0||A.content.includes("[output truncated");Is(e.traceWriter,{phase:"completed",toolUseId:$.id,name:$.name,resultBytes:Buffer.byteLength(A.content,"utf8"),isError:A.isError===!0,truncated:D,durationMs:F,...A.circuitBreaker===!0?{circuitBreaker:!0}:{},...A.failureClass?{failureClass:A.failureClass}:{}}),yield{type:"tool.output",toolUseId:$.id,toolName:$.name,content:A.content,...A.isError===!0?{isError:!0}:{},...D?{truncated:!0}:{},sessionId:e.ctx.sessionId},A.render?.diff&&(yield{type:"tool.diff",toolUseId:$.id,diff:A.render.diff,sessionId:e.ctx.sessionId});let{content:N,isError:B,image:H}=A,L=H!==void 0?[{type:"image",source:{type:"base64",media_type:H.mediaType,data:H.data}},...N.length>0?[{type:"text",text:N}]:[]]:N;C.push({type:"tool_result",tool_use_id:$.id,content:L,...B===!0?{is_error:!0}:{}})}let R={role:"user",content:C};e.messages.push(R)}catch(w){throw e.messages.splice(y),w}r+=1;let S=p.toolUseBlocks[p.toolUseBlocks.length-1];if(yield{type:"progress",progress:{taskId:s,description:"Tool-use loop",summary:`Iteration ${r}: used ${S?.name??"unknown"}`,lastToolName:S?.name,totalTokens:n.totalTokens??0,toolUses:r,durationMs:Date.now()-i},sessionId:e.ctx.sessionId},t>0&&r>=t){yield{type:"turn.completed",usage:a({...n,stopReason:"tool_use_loop_capped"}),sessionId:e.ctx.sessionId};return}}}finally{De(e.traceWriter,{phase:"loop_end",durationMs:Date.now()-i})}}function xq(e,t){try{let n=[];for(let r=0;r<e.length;r++){let o=e[r];if(o.role!=="assistant"||typeof o.content=="string")continue;let s=o.content;for(let i=0;i<s.length;i++){let a=s[i];if(a.type==="thinking"){let l=a;(!l.thinking||!l.signature)&&n.push({msgIdx:r,blockIdx:i,thinking:l.thinking?`(${l.thinking.length} chars)`:"(empty)",sigLen:l.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",t.message),console.error(`[afk] messages.length=${e.length}, invalid thinking blocks:`,n.length>0?JSON.stringify(n):"none found (cause may be elsewhere)")}catch{}}var Sq,my,UC,HC=_(()=>{"use strict";LC();Gf();NC();je();yh();q();Sq=0;my=3,UC=5e3});function gy(e){if(!("status"in e))return null;let t=e.status;if(t===429){let n=e.message.split("|");if(n.length>=2){let r=parseInt(n[1].trim(),10);if(!isNaN(r)&&r>0)return{kind:"oauth-limit",resetsAt:new Date(r*1e3)}}return{kind:"oauth-limit-no-ts"}}return t===400&&e.message.includes("invalid_request_error")&&e.message.includes("credit balance")?{kind:"credit-exhausted"}:null}async function WC(e){let{resetsAt:t,signal:n,readToken:r=yt}=e,o=r(),s=t.getTime()+3e4;return new Promise(i=>{let a,l=!1,c=p=>{l||(l=!0,a!==void 0&&clearInterval(a),n.removeEventListener("abort",u),i(p))},u=()=>{c("aborted")},d=()=>n.aborted?(c("aborted"),!0):Date.now()>=s?(c("timer"),!0):r()!==o?(c("hot-swap"),!0):!1;d()||(a=setInterval(()=>{d()},3e4),a.unref(),n.addEventListener("abort",u,{once:!0}))})}async function KC(e){let{signal:t,readToken:n=yt,retryAfterMs:r}=e,o=n(),s=r!==void 0?Date.now()+r:void 0;return new Promise(i=>{let a,l=!1,c=p=>{l||(l=!0,a!==void 0&&clearInterval(a),t.removeEventListener("abort",u),i(p))},u=()=>{c("aborted")},d=()=>t.aborted?(c("aborted"),!0):n()!==o?(c("hot-swap"),!0):s!==void 0&&Date.now()>=s?(c("timer"),!0):!1;d()||(a=setInterval(()=>{d()},3e4),a.unref(),t.addEventListener("abort",u,{once:!0}))})}var GC=_(()=>{"use strict";Fs()});var qC=_(()=>{"use strict";Fs()});import{randomUUID as hy}from"node:crypto";var zC,Rq,kd,JC=_(()=>{"use strict";HC();Ms();GC();qC();zC=7200*1e3,Rq=60*1e3,kd=class{_client;_authMode;initSessionId;tokenRefresher;autoResumeOnUsageLimit;refreshPromise=null;usageLimitWaitPromise=null;constructor(t){this._client=t.client,this._authMode=t.authMode,this.initSessionId=t.initSessionId,this.tokenRefresher=t.tokenRefresher,this.autoResumeOnUsageLimit=t.autoResumeOnUsageLimit}get client(){return this._client}get authMode(){return this._authMode}async forceClientRefresh(){if(!this.tokenRefresher)return null;let t=yt(),n=null;try{if(this.refreshPromise)n=await this.refreshPromise;else{this.refreshPromise=this.tokenRefresher();try{n=await this.refreshPromise??null}finally{this.refreshPromise=null}}}catch{return this.refreshPromise=null,null}if(!n)return null;this._client=n;let r=yt();return{accountId:_r(r??""),swapped:t!==r}}async*turnWithRetries(t,n){yield*this.turnWithUsageLimitRetry(t,n)}async*turnWithUsageLimitRetry(t,n){let r=null,o=null,s=!1;for await(let c of this.turnWithAuthRetry(t,n)){if(c.type==="error"){let u=gy(c.error);if(u&&u.kind==="oauth-limit"){o=u.resetsAt,r=c;break}if(u&&u.kind==="oauth-limit-no-ts"){s=!0,r=c;break}}yield c}if(!r)return;if(s){let c=_r(yt()??"");if(yield{type:"paused",reason:"usage-limit",accountId:c,autoResume:this.autoResumeOnUsageLimit},!this.autoResumeOnUsageLimit){yield r;return}let u=Date.now(),d=!1;for(;;){let p;if(this.usageLimitWaitPromise)p="aborted";else{this.usageLimitWaitPromise=KC({signal:t.signal,retryAfterMs:Rq});try{p=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(p==="aborted")return;let m=c;if(p==="hot-swap"){let h=await this.forceClientRefresh();h&&(t.client=this._client,m=h.accountId)}t.headers=bn(this._authMode,this.initSessionId,hy());let g=null;for await(let h of this.turnWithAuthRetry(t,n)){if(!d&&h.type==="error"){let b=gy(h.error);if(b&&(b.kind==="oauth-limit"||b.kind==="oauth-limit-no-ts")){g=h;break}}d||(yield{type:"resumed",hotSwapped:p==="hot-swap",accountId:m},d=!0),yield h}if(!g)return;if(Date.now()-u>zC){yield g;return}}}if(!o)return;if(o.getTime()-Date.now()>zC){yield r;return}let i=_r(yt()??"");if(yield{type:"paused",reason:"usage-limit",resetsAt:o,accountId:i,autoResume:this.autoResumeOnUsageLimit},!this.autoResumeOnUsageLimit){yield r;return}let a;if(this.usageLimitWaitPromise)a=await this.usageLimitWaitPromise;else{this.usageLimitWaitPromise=WC({resetsAt:o,signal:t.signal});try{a=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(a==="aborted")return;let l=i;if(a==="hot-swap"){let c=await this.forceClientRefresh();c&&(t.client=this._client,l=c.accountId)}t.headers=bn(this._authMode,this.initSessionId,hy()),yield{type:"resumed",hotSwapped:a==="hot-swap",accountId:l},yield*this.turnWithAuthRetry(t,n)}async*turnWithAuthRetry(t,n){let r=null;for await(let s of fy(t)){if(n())return;if(s.type==="error"&&this.isRetryableAuth(s.error)){r=s;break}yield s}if(!r)return;if(!await this.forceClientRefresh()){yield r;return}t.client=this._client,t.headers=bn(this._authMode,this.initSessionId,hy()),yield*fy(t)}isRetryableAuth(t){return this._authMode==="oauth"&&this.tokenRefresher!==void 0&&"status"in t&&t.status===401}}});function Aq(e){if(e.role!=="user")return!1;let t=e.content;if(typeof t=="string")return!0;if(!Array.isArray(t))return!1;for(let n of t)if(n.type==="tool_result")return!1;return!0}function XC(e,t){if(t<=0)return e.length;let n=0;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o&&Aq(o)&&(n+=1,n===t))return r}return-1}function ZC(e,t,n){let r=_q(e);return{model:t,max_tokens:n,system:Cq,messages:[{role:"user",content:`Summarize the following conversation transcript. Follow the system instructions exactly.
|
|
1518
|
+
`)}function cr(e){let t=[],n=new Set,r=v.AFK_INTERNAL==="1",o=rn(Pt());fr(cc(),"user"),fr(uc(),"project");for(let{dir:i,origin:a}of o.skillRoots)fr(i,a);for(let i of Vn()){let a=Ke(i);nn(a,r)&&(t.push({name:i,description:a.description,source:a.origin==="user"?"user":a.origin==="project"?"project":a.origin?.startsWith("imported:")?"imported":"builtin",argumentHint:a.argumentHint,whenToUse:a.whenToUse}),n.add(i))}let s=e??py();for(let i of s){if(i.type!=="local")continue;let a=dy(i.path);for(let l of a)!l.name||n.has(l.name)||nn({audience:l.audience},r)&&(t.push({name:l.name,description:l.description??`Skill from plugin at ${i.path}`,source:"plugin"}),n.add(l.name))}return t}function id(e){let t=new Map,n=e??py();for(let r of n){if(r.type!=="local")continue;let o=dy(r.path);for(let s of o)s.name&&s.body&&s.body.length>0&&!t.has(s.name)&&t.set(s.name,{body:s.body,pluginPath:r.path,...s.allowedTools!==void 0?{allowedTools:s.allowedTools}:{},...s.context!==void 0?{context:s.context}:{},...s.readOnly===!0?{readOnly:!0}:{}})}return t}function py(){return[...dr(dc()),...dr(),...dr(vs()),...rn(Pt()).pluginRoots.flatMap(e=>dr(e,{trustAll:!0}))]}async function _C(){await xC(py())}var Ur=_(()=>{"use strict";uy();wt();cy();zr();RC();CC();G();q();ir()});function IC(e){if(e.length===0)return;let t=e[e.length-1];if(!t||t.role!=="assistant"||typeof t.content=="string")return;let n=t.content,r=[];for(let s of n)s.type==="tool_use"&&typeof s.id=="string"&&r.push(s.id);if(r.length===0)return;let o={role:"user",content:r.map(s=>({type:"tool_result",tool_use_id:s,content:"Tool call interrupted before completing \u2014 no result recorded.",is_error:!0}))};e.push(o)}var PC=_(()=>{"use strict"});function MC(e){return{messages:e.initialMessages?[...e.initialMessages]:[],currentModel:e.model,requestedModel:e.requestedModel??e.model,currentPermissionMode:e.permissionMode,userSystem:e.userSystem,toolDispatcher:e.toolDispatcher,lastUsage:null,closed:!1,autoCompactThreshold:e.autoCompactThreshold}}var OC=_(()=>{"use strict"});var fq,vd,$C=_(()=>{"use strict";fq="__closed__",vd=class{current=null;pendingReason=null;closedPromise;closeResolve=null;constructor(){this.closedPromise=new Promise(t=>{this.closeResolve=()=>t(fq)})}begin(){let t=new AbortController;return this.current=t,this.pendingReason!==null&&!t.signal.aborted&&(t.abort(this.pendingReason),this.pendingReason=null),t}clear(t){this.current===t&&(this.current=null)}requestAbort(t){let n=this.current;if(n&&!n.signal.aborted){n.abort(t);return}this.pendingReason=t}isIdle(){return this.current===null}markClosed(){this.closeResolve?.()}}});function hq(e,t,n,r,o){let s=gq.get(e);if(!s)return;let i=1e6,l=Math.max(0,t-r-o)/i*s.inputPerMTok,c=n/i*s.outputPerMTok,u=s.cacheWritePerMTok??s.inputPerMTok*1.25,d=s.cacheReadPerMTok??s.inputPerMTok*.1,p=o/i*u,m=r/i*d;return l+c+p+m}function DC(e,t,n){if(!e)return{stopReason:t??null};let r={inputTokens:e.input_tokens,outputTokens:e.output_tokens,stopReason:t??null};if(e.cache_read_input_tokens!=null&&(r.cachedInputTokens=e.cache_read_input_tokens),e.cache_creation_input_tokens!=null&&(r.cacheCreationTokens=e.cache_creation_input_tokens),r.totalTokens=(e.input_tokens??0)+(e.output_tokens??0),n){let o=hq(n,e.input_tokens??0,e.output_tokens??0,e.cache_read_input_tokens??0,e.cache_creation_input_tokens??0);o!==void 0&&(r.totalCostUsd=o)}return r}var gq,LC=_(()=>{"use strict";hh();gq=new Map([["claude-sonnet-4-5-20250929",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-opus-4-5-20250929",{inputPerMTok:15,outputPerMTok:75,cacheWritePerMTok:18.75,cacheReadPerMTok:1.5}],["claude-haiku-4-5-20250929",{inputPerMTok:1,outputPerMTok:5,cacheWritePerMTok:1.25,cacheReadPerMTok:.1}],["claude-haiku-4-5-20251001",{inputPerMTok:1,outputPerMTok:5,cacheWritePerMTok:1.25,cacheReadPerMTok:.1}],["claude-3-7-sonnet-20250219",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20241022",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20240620",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-3-5-haiku-20241022",{inputPerMTok:.8,outputPerMTok:4,cacheWritePerMTok:1,cacheReadPerMTok:.08}],["claude-3-opus-20240229",{inputPerMTok:15,outputPerMTok:75,cacheWritePerMTok:18.75,cacheReadPerMTok:1.5}],["claude-3-sonnet-20240229",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["claude-3-haiku-20240307",{inputPerMTok:.25,outputPerMTok:1.25,cacheWritePerMTok:.3,cacheReadPerMTok:.03}]])});function yq(e){let t=e.trim();if(t.length===0)return{};try{return JSON.parse(t)}catch{return{}}}function bq(e,t,n){let r=[],o=[];for(let a of e)a&&(a.kind==="text"?(r.push({type:"text",text:a.text}),o.push(a.text)):a.kind==="thinking"?a.thinking&&a.signature&&r.push({type:"thinking",thinking:a.thinking,signature:a.signature}):a.kind==="redacted_thinking"?r.push({type:"redacted_thinking",data:a.data}):r.push({type:"tool_use",id:a.id,name:a.name,input:yq(a.partialJson)}));let s=a=>a.type==="tool_use",i=r.filter(s);return{stopReason:t,assistantBlocks:r,toolUseBlocks:i,usage:n,text:o.join("")}}async function*FC(e,t){let n=[],r=null,o=null,s=!1,i=!!v.AFK_TELEGRAM_TRACE;try{i&&console.log("[translate] starting SDK event iteration");for await(let a of e){switch(i&&console.log("[translate] SDK evt:",a.type),a.type){case"message_start":{let l=a.message?.usage;l&&(o={...l});break}case"content_block_start":{let l=a.content_block;l.type==="text"?n[a.index]={kind:"text",text:""}:l.type==="thinking"?n[a.index]={kind:"thinking",thinking:"",signature:""}:l.type==="redacted_thinking"?n[a.index]={kind:"redacted_thinking",data:l.data}:l.type==="tool_use"&&(n[a.index]={kind:"tool_use",id:l.id,name:l.name,partialJson:""},yield{kind:"event",event:{type:"tool.use.start",toolUseId:l.id,toolName:l.name,toolInput:" \u2026",sessionId:t.sessionId}});break}case"content_block_delta":{let l=n[a.index],c=a.delta;c.type==="text_delta"?(l&&l.kind==="text"&&(l.text+=c.text),yield{kind:"event",event:{type:"delta.text",text:c.text,sessionId:t.sessionId}}):c.type==="input_json_delta"?l&&l.kind==="tool_use"&&(l.partialJson+=c.partial_json):c.type==="thinking_delta"?(l&&l.kind==="thinking"&&(l.thinking+=c.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:c.thinking,sessionId:t.sessionId}}):c.type==="signature_delta"&&l&&l.kind==="thinking"&&(l.signature=c.signature);break}case"content_block_stop":{let l=n[a.index];l&&l.kind==="tool_use"&&(yield{kind:"event",event:{type:"tool.use",summary:l.name,toolUseIds:[l.id],sessionId:t.sessionId}});break}case"message_delta":{a.delta&&a.delta.stop_reason!==void 0&&(r=a.delta.stop_reason);let l=a.usage;l&&(o!==null?(o.output_tokens=l.output_tokens,l.cache_creation_input_tokens!=null&&(o.cache_creation_input_tokens=l.cache_creation_input_tokens),l.cache_read_input_tokens!=null&&(o.cache_read_input_tokens=l.cache_read_input_tokens),l.input_tokens!=null&&(o.input_tokens=l.input_tokens)):o={cache_creation:null,cache_creation_input_tokens:l.cache_creation_input_tokens??null,cache_read_input_tokens:l.cache_read_input_tokens??null,inference_geo:null,input_tokens:l.input_tokens??0,output_tokens:l.output_tokens,server_tool_use:null,service_tier:null});break}case"message_stop":{s=!0;break}default:break}if(s)break}i&&console.log("[translate] SDK iteration ended naturally, stopped=",s)}catch(a){i&&console.log("[translate] SDK iteration threw:",a.message),yield{kind:"event",event:{type:"error",error:a instanceof Error?a:new Error(String(a))}};return}i&&console.log("[translate] yielding turn-result"),yield{kind:"turn-result",result:bq(n,r,o)}}var NC=_(()=>{"use strict";q()});import{randomUUID as wq}from"node:crypto";function vq(e){let{name:t,description:n,input_schema:r}=e;return{name:t,...n!==void 0?{description:n}:{},input_schema:r}}function kq(e){if(!("status"in e))return!1;let t=e.status;return t===529||t===503}function BC(e){if(e===null||typeof e!="object")return!1;let t=e;if(t.status===529||t.status===503)return!0;let n=t.error;if(n===null||typeof n!="object")return!1;let r=n;return((r.error!==null&&typeof r.error=="object"?r.error.type:void 0)??r.type)==="overloaded_error"}function jC(e,t){return new Promise(n=>{if(t.aborted){n();return}let r=setTimeout(n,e);r.unref(),t.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}async function Eq(e,t,n,r){for(let o=0;;o++){if(o>0){let s=UC*Math.pow(2,o-1);if(await jC(s,r),r.aborted)throw new Error("aborted")}try{return await Promise.resolve(e.messages.create(t,{headers:n,signal:r}))}catch(s){if(r.aborted)throw s;let i=s instanceof Error?s:new Error(String(s));if(kq(i)&&o<my)continue;throw i}}}function Tq(e,t){if(!t||typeof t!="object")return"";let n=t;if(e==="skill"||e==="Skill"){let i=n.name;return typeof i=="string"&&i.length>0?`(${i.length>60?i.slice(0,59)+"\u2026":i})`:""}let r=n.file_path??n.path??n.filePath;if(typeof r=="string")return" "+r;let o=n.command??n.cmd;if(typeof o=="string"){let i=o.split(`
|
|
1519
|
+
`)[0];return" "+(i.length>80?i.slice(0,77)+"\u2026":i)}let s=n.query??n.pattern??n.url??n.description;return typeof s=="string"?" "+s:""}async function*fy(e){let t=e.maxToolUseIterations??Sq,n={stopReason:null},r=0,o=0,s=wq(),i=Date.now(),a=l=>({...l,durationMs:Date.now()-i});De(e.traceWriter,{phase:"loop_start"});try{for(;;){if(e.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}let l=Dc({baseUrl:e.baseUrl})?Nv(e.messages,Lc()):e.messages,c={model:e.model,max_tokens:e.maxTokens,messages:l,stream:!0,...e.system!==null?{system:e.system}:{},...e.tools!==null&&e.tools.length>0?{tools:e.tools.map(vq)}:{},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{output_config:{effort:e.effort}}:{}},u=Date.now(),d;try{d=await Eq(e.client,c,e.headers,e.signal)}catch(w){if(e.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}let T=w instanceof Error?w:new Error(String(w));T.message.includes("thinking")&&xq(e.messages,T),yield{type:"error",error:T};return}let p=null,m=!1,g=!1,h=!1;try{v.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let w of FC(d,e.ctx))if(h||(h=!0,De(e.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-u,resolvedModel:e.model})),v.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",w.kind,w.kind==="event"?w.event.type:""),w.kind==="event"){if(w.event.type==="error"){if(BC(w.event.error)&&o<my&&!e.signal.aborted){g=!0;break}yield w.event,m=!0;break}yield w.event}else{p=w.result;break}v.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",p?"set":"null")}catch(w){if(e.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}let T=w instanceof Error?w:new Error(String(w));if(BC(T)&&o<my&&!e.signal.aborted)g=!0;else{yield{type:"error",error:T};return}}if(g){if(o+=1,yield{type:"stream.retry",sessionId:e.ctx.sessionId},await jC(UC*Math.pow(2,o-1),e.signal),e.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}continue}if(o=0,m){e.signal.aborted&&(yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId});return}if(p===null){yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}let b=DC(p.usage,p.stopReason,e.model);if(n=Wa(n,b),n.contextWindowTokens=(b.inputTokens??0)+(b.outputTokens??0)+(b.cachedInputTokens??0)+(b.cacheCreationTokens??0),e.onUsageProgress?.(n),p.stopReason!=="tool_use"){if(p.stopReason==="refusal"){yield{type:"assistant.message",text:p.text.length>0?p.text:`The model stopped with a content-safety refusal (stop_reason: "refusal") and returned no output. This is Anthropic's safety system declining the request \u2014 not an afk error. Because the flagged context stays in the conversation, follow-up messages will likely be refused the same way; rephrase the request or start a fresh session to continue.`,sessionId:e.ctx.sessionId},yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}p.text.length>0&&(yield{type:"assistant.message",text:p.text,sessionId:e.ctx.sessionId},p.text.length<=200&&(yield{type:"suggestion",suggestion:p.text,sessionId:e.ctx.sessionId}));let w=p.assistantBlocks.filter(T=>T.type!=="tool_use");w.length>0&&e.messages.push({role:"assistant",content:w}),yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}let y=e.messages.length;e.messages.push({role:"assistant",content:p.assistantBlocks});try{let w=[],T=new Map;for(let k of p.toolUseBlocks){w.push({id:k.id,name:k.name,input:k.input,signal:e.signal});let $=Date.now();T.set(k.id,$),Is(e.traceWriter,{phase:"started",toolUseId:k.id,name:k.name,inputBytes:Buffer.byteLength(JSON.stringify(k.input??{}),"utf8")}),yield{type:"tool.use.start",toolUseId:k.id,toolName:k.name,toolInput:Tq(k.name,k.input),toolInputRaw:zu(k.input),sessionId:e.ctx.sessionId}}if(e.signal.aborted){let k=w.map($=>({type:"tool_result",tool_use_id:$.id,content:"Tool call aborted",is_error:!0}));e.messages.push({role:"user",content:k}),yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}let x;if(e.toolDispatcher.executeBatch)try{x=await e.toolDispatcher.executeBatch(w)}catch(k){x=w.map(()=>({content:`Tool batch execution failed: ${k instanceof Error?k.message:String(k)}`,isError:!0}))}else{x=[];for(let k of w){if(e.signal.aborted){x.push({content:"Tool call aborted",isError:!0});continue}try{x.push(await e.toolDispatcher.execute(k))}catch($){let A=$ instanceof Error?$.message:String($);x.push({content:`Tool execution threw: ${A}`,isError:!0})}}}let C=[];for(let k=0;k<w.length;k++){let $=w[k],A=x[k],P=T.get($.id),F=typeof P=="number"?Date.now()-P:0,D=A.truncated===!0||A.content.includes("[output truncated");Is(e.traceWriter,{phase:"completed",toolUseId:$.id,name:$.name,resultBytes:Buffer.byteLength(A.content,"utf8"),isError:A.isError===!0,truncated:D,durationMs:F,...A.circuitBreaker===!0?{circuitBreaker:!0}:{},...A.failureClass?{failureClass:A.failureClass}:{}}),yield{type:"tool.output",toolUseId:$.id,toolName:$.name,content:A.content,...A.isError===!0?{isError:!0}:{},...D?{truncated:!0}:{},sessionId:e.ctx.sessionId},A.render?.diff&&(yield{type:"tool.diff",toolUseId:$.id,diff:A.render.diff,sessionId:e.ctx.sessionId});let{content:N,isError:B,image:H}=A,L=H!==void 0?[{type:"image",source:{type:"base64",media_type:H.mediaType,data:H.data}},...N.length>0?[{type:"text",text:N}]:[]]:N;C.push({type:"tool_result",tool_use_id:$.id,content:L,...B===!0?{is_error:!0}:{}})}let R={role:"user",content:C};e.messages.push(R)}catch(w){throw e.messages.splice(y),w}r+=1;let S=p.toolUseBlocks[p.toolUseBlocks.length-1];if(yield{type:"progress",progress:{taskId:s,description:"Tool-use loop",summary:`Iteration ${r}: used ${S?.name??"unknown"}`,lastToolName:S?.name,totalTokens:n.totalTokens??0,toolUses:r,durationMs:Date.now()-i},sessionId:e.ctx.sessionId},t>0&&r>=t){yield{type:"turn.completed",usage:a({...n,stopReason:"tool_use_loop_capped"}),sessionId:e.ctx.sessionId};return}}}finally{De(e.traceWriter,{phase:"loop_end",durationMs:Date.now()-i})}}function xq(e,t){try{let n=[];for(let r=0;r<e.length;r++){let o=e[r];if(o.role!=="assistant"||typeof o.content=="string")continue;let s=o.content;for(let i=0;i<s.length;i++){let a=s[i];if(a.type==="thinking"){let l=a;(!l.thinking||!l.signature)&&n.push({msgIdx:r,blockIdx:i,thinking:l.thinking?`(${l.thinking.length} chars)`:"(empty)",sigLen:l.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",t.message),console.error(`[afk] messages.length=${e.length}, invalid thinking blocks:`,n.length>0?JSON.stringify(n):"none found (cause may be elsewhere)")}catch{}}var Sq,my,UC,HC=_(()=>{"use strict";LC();Gf();NC();je();yh();q();Sq=0;my=3,UC=5e3});function gy(e){if(!("status"in e))return null;let t=e.status;if(t===429){let n=e.message.split("|");if(n.length>=2){let r=parseInt(n[1].trim(),10);if(!isNaN(r)&&r>0)return{kind:"oauth-limit",resetsAt:new Date(r*1e3)}}return{kind:"oauth-limit-no-ts"}}return t===400&&e.message.includes("invalid_request_error")&&e.message.includes("credit balance")?{kind:"credit-exhausted"}:null}async function WC(e){let{resetsAt:t,signal:n,readToken:r=bt}=e,o=r(),s=t.getTime()+3e4;return new Promise(i=>{let a,l=!1,c=p=>{l||(l=!0,a!==void 0&&clearInterval(a),n.removeEventListener("abort",u),i(p))},u=()=>{c("aborted")},d=()=>n.aborted?(c("aborted"),!0):Date.now()>=s?(c("timer"),!0):r()!==o?(c("hot-swap"),!0):!1;d()||(a=setInterval(()=>{d()},3e4),a.unref(),n.addEventListener("abort",u,{once:!0}))})}async function KC(e){let{signal:t,readToken:n=bt,retryAfterMs:r}=e,o=n(),s=r!==void 0?Date.now()+r:void 0;return new Promise(i=>{let a,l=!1,c=p=>{l||(l=!0,a!==void 0&&clearInterval(a),t.removeEventListener("abort",u),i(p))},u=()=>{c("aborted")},d=()=>t.aborted?(c("aborted"),!0):n()!==o?(c("hot-swap"),!0):s!==void 0&&Date.now()>=s?(c("timer"),!0):!1;d()||(a=setInterval(()=>{d()},3e4),a.unref(),t.addEventListener("abort",u,{once:!0}))})}var GC=_(()=>{"use strict";Fs()});var qC=_(()=>{"use strict";Fs()});import{randomUUID as hy}from"node:crypto";var zC,Rq,kd,JC=_(()=>{"use strict";HC();Ms();GC();qC();zC=7200*1e3,Rq=60*1e3,kd=class{_client;_authMode;initSessionId;tokenRefresher;autoResumeOnUsageLimit;refreshPromise=null;usageLimitWaitPromise=null;constructor(t){this._client=t.client,this._authMode=t.authMode,this.initSessionId=t.initSessionId,this.tokenRefresher=t.tokenRefresher,this.autoResumeOnUsageLimit=t.autoResumeOnUsageLimit}get client(){return this._client}get authMode(){return this._authMode}async forceClientRefresh(){if(!this.tokenRefresher)return null;let t=bt(),n=null;try{if(this.refreshPromise)n=await this.refreshPromise;else{this.refreshPromise=this.tokenRefresher();try{n=await this.refreshPromise??null}finally{this.refreshPromise=null}}}catch{return this.refreshPromise=null,null}if(!n)return null;this._client=n;let r=bt();return{accountId:_r(r??""),swapped:t!==r}}async*turnWithRetries(t,n){yield*this.turnWithUsageLimitRetry(t,n)}async*turnWithUsageLimitRetry(t,n){let r=null,o=null,s=!1;for await(let c of this.turnWithAuthRetry(t,n)){if(c.type==="error"){let u=gy(c.error);if(u&&u.kind==="oauth-limit"){o=u.resetsAt,r=c;break}if(u&&u.kind==="oauth-limit-no-ts"){s=!0,r=c;break}}yield c}if(!r)return;if(s){let c=_r(bt()??"");if(yield{type:"paused",reason:"usage-limit",accountId:c,autoResume:this.autoResumeOnUsageLimit},!this.autoResumeOnUsageLimit){yield r;return}let u=Date.now(),d=!1;for(;;){let p;if(this.usageLimitWaitPromise)p="aborted";else{this.usageLimitWaitPromise=KC({signal:t.signal,retryAfterMs:Rq});try{p=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(p==="aborted")return;let m=c;if(p==="hot-swap"){let h=await this.forceClientRefresh();h&&(t.client=this._client,m=h.accountId)}t.headers=bn(this._authMode,this.initSessionId,hy());let g=null;for await(let h of this.turnWithAuthRetry(t,n)){if(!d&&h.type==="error"){let b=gy(h.error);if(b&&(b.kind==="oauth-limit"||b.kind==="oauth-limit-no-ts")){g=h;break}}d||(yield{type:"resumed",hotSwapped:p==="hot-swap",accountId:m},d=!0),yield h}if(!g)return;if(Date.now()-u>zC){yield g;return}}}if(!o)return;if(o.getTime()-Date.now()>zC){yield r;return}let i=_r(bt()??"");if(yield{type:"paused",reason:"usage-limit",resetsAt:o,accountId:i,autoResume:this.autoResumeOnUsageLimit},!this.autoResumeOnUsageLimit){yield r;return}let a;if(this.usageLimitWaitPromise)a=await this.usageLimitWaitPromise;else{this.usageLimitWaitPromise=WC({resetsAt:o,signal:t.signal});try{a=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(a==="aborted")return;let l=i;if(a==="hot-swap"){let c=await this.forceClientRefresh();c&&(t.client=this._client,l=c.accountId)}t.headers=bn(this._authMode,this.initSessionId,hy()),yield{type:"resumed",hotSwapped:a==="hot-swap",accountId:l},yield*this.turnWithAuthRetry(t,n)}async*turnWithAuthRetry(t,n){let r=null;for await(let s of fy(t)){if(n())return;if(s.type==="error"&&this.isRetryableAuth(s.error)){r=s;break}yield s}if(!r)return;if(!await this.forceClientRefresh()){yield r;return}t.client=this._client,t.headers=bn(this._authMode,this.initSessionId,hy()),yield*fy(t)}isRetryableAuth(t){return this._authMode==="oauth"&&this.tokenRefresher!==void 0&&"status"in t&&t.status===401}}});function Aq(e){if(e.role!=="user")return!1;let t=e.content;if(typeof t=="string")return!0;if(!Array.isArray(t))return!1;for(let n of t)if(n.type==="tool_result")return!1;return!0}function XC(e,t){if(t<=0)return e.length;let n=0;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o&&Aq(o)&&(n+=1,n===t))return r}return-1}function ZC(e,t,n){let r=_q(e);return{model:t,max_tokens:n,system:Cq,messages:[{role:"user",content:`Summarize the following conversation transcript. Follow the system instructions exactly.
|
|
1520
1520
|
|
|
1521
1521
|
<transcript>
|
|
1522
1522
|
`+r+`
|
|
@@ -1524,7 +1524,7 @@ ${t.body}`)}var z2,ay=_(()=>{"use strict";z2=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9
|
|
|
1524
1524
|
|
|
1525
1525
|
`+n},{role:"assistant",content:YC},...e.slice(t)]}function eA(e,t,n){let r=Iq(e.slice(0,t)),o=VC.length+2+n.length+YC.length,s=Math.max(0,r-o);return Math.round(s/4)}function _q(e){let t=[];for(let n of e){let r=n.role==="user"?"User":"Assistant";if(t.push(r+":"),typeof n.content=="string")t.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)t.push(o.text);else if(s==="tool_use"){let i=o.name??"unknown",a=tA(o.input);t.push(`[tool call: ${i} ${a}]`)}else if(s==="tool_result"){let i=o.content;t.push(`[tool result: ${nA(i)}]`)}else s==="image"?t.push("[image]"):s==="document"&&t.push("[document]")}t.push("")}return t.join(`
|
|
1526
1526
|
`).trim()}function tA(e){try{let t=JSON.stringify(e);return t.length>240?t.slice(0,237)+"...":t}catch{return"{}"}}function nA(e){if(typeof e=="string")return e.length>320?e.slice(0,317)+"...":e;if(Array.isArray(e)){let t=[];for(let r of e)r.type==="text"&&"text"in r&&t.push(r.text);let n=t.join(" ");return n.length>320?n.slice(0,317)+"...":n}return""}function Iq(e){let t=0;for(let n of e)if(typeof n.content=="string")t+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content){let o=r.type;o==="text"&&"text"in r?t+=r.text.length:o==="tool_use"?t+=tA(r.input).length:o==="tool_result"&&(t+=nA(r.content).length)}return t}var Cq,VC,YC,rA=_(()=>{"use strict";Cq=["You are a conversation-summarization assistant. The user will paste a","prior conversation between a user and an AI assistant that includes tool","calls and tool results. Produce a concise but complete summary that lets","the AI continue the conversation without losing track.","","Preserve, in this priority order:","1. The user's original intent, explicit asks, constraints, corrections,"," and preferences stated during the conversation.","2. Tool decisions and their outcomes \u2014 file paths read or written, shell"," commands run, search queries, URLs fetched, code edits made, tests"," run, errors observed, and whether each action succeeded or failed.","3. Current state: what has been completed, what remains unresolved, and"," the safest next action.","4. Open questions, pending decisions, blockers, and assumptions.","5. Key facts the assistant discovered (function locations, schemas,"," observed behaviors, important external findings).","","Drop prose narration, conversational filler, and exploratory dead-ends.","Drop verbatim tool output unless an exact snippet, error, path, command,","or result is needed for continuation.","Do not invent details. If something is uncertain, mark it explicitly.","Output plain text, no markdown headers. Aim for ~250 words; use up to","~400 only when needed to preserve tool state or unresolved tasks."].join(`
|
|
1527
|
-
`),VC="[Compacted summary of earlier conversation]",YC="Acknowledged. Continuing from the summary above."});import{randomUUID as Pq}from"node:crypto";async function oA(e){let{state:t,abort:n,retry:r,initSessionId:o,traceWriter:s}=e,i=t.messages.length;if(t.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=Dq(),l=XC(t.messages,a);if(l<0)return{compacted:!1,reason:"history-too-short",messagesBefore:i,messagesAfter:i};if(l===0)return{compacted:!1,reason:"nothing-to-summarize",messagesBefore:i,messagesAfter:i};let c=t.messages.slice(0,l),u=Lq(),d=ZC(c,u,$q),p=n.begin(),m;try{if(p.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let y=bn(r.authMode,o,Pq()),S=r.client,w=await Promise.resolve(S.messages.create(d,{headers:y,signal:p.signal}));m=await Fq(w)}catch(y){return p.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i}:{compacted:!1,reason:"summarization-failed: "+(y instanceof Error?y.message:String(y)),messagesBefore:i,messagesAfter:i}}finally{n.clear(p)}if(m.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:i,messagesAfter:i};let g=eA(t.messages,l,m),h=QC(t.messages,l,m);t.messages.splice(0,t.messages.length,...h);let b=t.messages.length;return xv(s,{trigger:"manual",preCompactionMessages:c,summary:m,keptTailCount:i-l,keepLastNConfig:a,messagesBefore:i,messagesAfter:b,tokensSavedEstimate:g}),{compacted:!0,messagesBefore:i,messagesAfter:b,tokensSavedEstimate:g}}function Dq(){let e=v.AFK_COMPACT_KEEP_LAST_TURNS;if(e!==void 0&&e.length>0){let t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>0)return t}return Mq}function Lq(){let e=v.AFK_COMPACT_MODEL;return e!==void 0&&e.length>0?
|
|
1527
|
+
`),VC="[Compacted summary of earlier conversation]",YC="Acknowledged. Continuing from the summary above."});import{randomUUID as Pq}from"node:crypto";async function oA(e){let{state:t,abort:n,retry:r,initSessionId:o,traceWriter:s}=e,i=t.messages.length;if(t.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=Dq(),l=XC(t.messages,a);if(l<0)return{compacted:!1,reason:"history-too-short",messagesBefore:i,messagesAfter:i};if(l===0)return{compacted:!1,reason:"nothing-to-summarize",messagesBefore:i,messagesAfter:i};let c=t.messages.slice(0,l),u=Lq(),d=ZC(c,u,$q),p=n.begin(),m;try{if(p.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let y=bn(r.authMode,o,Pq()),S=r.client,w=await Promise.resolve(S.messages.create(d,{headers:y,signal:p.signal}));m=await Fq(w)}catch(y){return p.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i}:{compacted:!1,reason:"summarization-failed: "+(y instanceof Error?y.message:String(y)),messagesBefore:i,messagesAfter:i}}finally{n.clear(p)}if(m.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:i,messagesAfter:i};let g=eA(t.messages,l,m),h=QC(t.messages,l,m);t.messages.splice(0,t.messages.length,...h);let b=t.messages.length;return xv(s,{trigger:"manual",preCompactionMessages:c,summary:m,keptTailCount:i-l,keepLastNConfig:a,messagesBefore:i,messagesAfter:b,tokensSavedEstimate:g}),{compacted:!0,messagesBefore:i,messagesAfter:b,tokensSavedEstimate:g}}function Dq(){let e=v.AFK_COMPACT_KEEP_LAST_TURNS;if(e!==void 0&&e.length>0){let t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>0)return t}return Mq}function Lq(){let e=v.AFK_COMPACT_MODEL;return e!==void 0&&e.length>0?yt(e)??e:Oq}async function Fq(e){let t="";for await(let n of e)if(n.type==="content_block_delta"){let r=n.delta;r.type==="text_delta"&&typeof r.text=="string"&&(t+=r.text)}return t}var Mq,Oq,$q,sA=_(()=>{"use strict";Ms();rA();je();Jn();q();Mq=2,Oq="claude-haiku-4-5-20251001",$q=1024});import{randomUUID as iA}from"node:crypto";var Nq,Ed,aA=_(()=>{"use strict";xa();Ms();Gf();zf();Vf();Ur();Ga();Jn();PC();OC();$C();JC();sA();kh();Nq=[{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"}],Ed=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;baseUrl;traceWriter;state;abort;retry;cwdDependentsFactory;onPermissionMode;mcpManager;constructor(t){this.initSessionId=t.sessionId??iA(),this.promptStream=t.promptStream,this.maxTokens=t.maxTokens,this.tools=t.tools,this.systemPrefix=t.systemPrefix,this.thinking=t.thinking,t.effort!==void 0&&(this.effort=t.effort),t.baseUrl!==void 0&&(this.baseUrl=t.baseUrl),this.traceWriter=t.traceWriter,this.cwdDependentsFactory=t.cwdDependentsFactory,this.onPermissionMode=t.onPermissionMode,this.mcpManager=t.mcpManager,this.retry=new kd({client:t.client,authMode:t.authMode,initSessionId:this.initSessionId,...t.tokenRefresher?{tokenRefresher:t.tokenRefresher}:{},autoResumeOnUsageLimit:t.autoResumeOnUsageLimit??!0}),this.state=MC({model:t.model,...t.requestedModel!==void 0?{requestedModel:t.requestedModel}:{},permissionMode:t.permissionMode??"default",userSystem:t.userSystem,toolDispatcher:t.toolDispatcher,...t.initialMessages?{initialMessages:t.initialMessages}:{},...t.autoCompactThreshold!==void 0?{autoCompactThreshold:t.autoCompactThreshold}:{}}),this.abort=new vd}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}IC(this.state.messages),this.state.messages.push({role:"user",content:s.content});let a=this.composeSystem(),l=bn(this.retry.authMode,this.initSessionId,iA(),this.effort!==void 0),c={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:l,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}},u=!1;try{for await(let d of this.retry.turnWithRetries(c,()=>this.state.closed)){if(this.state.closed)return;d.type==="turn.completed"&&(this.state.lastUsage=d.usage,this.abort.clear(i)),(d.type==="turn.completed"||d.type==="error")&&(u=!0),yield d}}catch(d){if(this.state.closed)return;if(i.signal.aborted){this.abort.clear(i),u||(yield this.makeInterruptedTurnEvent());continue}yield{type:"error",error:d instanceof Error?d:new Error(String(d))};return}finally{this.abort.clear(i)}if(this.state.closed)return;if(i.signal.aborted){u||(yield this.makeInterruptedTurnEvent());continue}if(this.state.autoCompactThreshold!==void 0&&!this.state.closed){let d=this.state.lastUsage,p=Ot(this.state.requestedModel);if(d!==null&&p>0){let m=ti(d);wx(m,p,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 t=this.systemPrefix,n=this.state.userSystem,r=[];t&&t.length>0&&r.push(...t),n&&n.length>0&&r.push({type:"text",text:n});let o=Uv(this.state.currentPermissionMode);o!==null&&r.push(o);let s=jv(this.state.currentPermissionMode);return s!==null&&r.push(s),r.length===0?null:Dc({baseUrl:this.baseUrl})?Fv(r,Lc()):r}async interrupt(){this.abort.requestAbort("interrupted")}makeInterruptedTurnEvent(){return{type:"turn.completed",usage:{stopReason:"interrupted",resultSubtype:"interrupted",isError:!1},sessionId:this.initSessionId}}async setModel(t){t!==void 0&&t.length>0&&(this.state.requestedModel=t,this.state.currentModel=yt(t)??t)}async setPermissionMode(t){this.state.currentPermissionMode=t;let n=wn(t);this.state.toolDispatcher.setAllowAll?.(n),this.onPermissionMode?.(t)}setCwd(t){if(this.state.toolDispatcher.setResolveBase?.(t),!this.cwdDependentsFactory)return;let{userSystem:n,dispatcher:r}=this.cwdDependentsFactory(t);this.state.userSystem=n,this.state.toolDispatcher=r}async supportedCommands(){try{return cr().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return Nq.map(t=>({...t}))}async supportedAgents(){return[]}async getContextUsage(){let t=this.state.lastUsage,n=Ot(this.state.requestedModel),r;if(t&&n>0){let i=ti(t);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=Ju(t);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(t=>({name:t.serverName,status:t.status})):[]}async accountInfo(){return{subscriptionType:this.retry.authMode==="oauth"?"claude-subscription":"api-key"}}async reauth(){return this.retry.forceClientRefresh()}async rewindFiles(t,n){return{canRewind:!1,error:"anthropic-direct provider does not support file checkpoint rewind"}}async compact(){return oA({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()}}});function yy(e){if(e===void 0||e===!1)return;if(e===!0)return Uq;let t=e.threshold;if(!(typeof t!="number"||!Number.isFinite(t)||t<=0||t>=1))return t}function by(e,t){let n=Ka(t),r=e.maxOutputTokens;if(typeof r=="number"&&Number.isFinite(r)&&r>0){let o=Math.floor(r);if(o>n){let s=`max:${t}:${o}`;return Td.has(s)||(Td.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${t} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function lA(e){if(!e||e.length===0)return;let t=[];for(let n of e)n.user.length>0&&t.push({role:"user",content:n.user}),n.assistant.length>0&&t.push({role:"assistant",content:n.assistant});return t.length>0?t:void 0}function wy(e,t,n){switch(e.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&Bq(n))return{type:"adaptive",display:"summarized"};let r=Math.floor(t*jq),o=Math.max(1024,t-1-r),s=e.budgetTokens!==void 0&&Number.isFinite(e.budgetTokens)?Math.floor(e.budgetTokens):void 0,i=Math.min(Math.max(s??o,1024),o);if(s!==void 0&&s>o){let a=`think:${n??"default"}:${s}:${t}`;Td.has(a)||(Td.add(a),console.warn(`[afk] thinking budgetTokens ${s} leaves too little of max_tokens ${t} for the reply; clamping to ${o}.`))}return{type:"enabled",budget_tokens:i,display:"summarized"}}}}function Sy(e,t){if(e!==void 0)return e;let n=t.toLowerCase();if(/(claude-)?(opus|sonnet)-4-[678]/.test(n))return"max"}var Bq,Uq,Td,jq,vy=_(()=>{"use strict";Ga();Bq=e=>/opus-4-(7|[89])/.test(e),Uq=.9;Td=new Set,jq=.25});var xd,ky,Ey,hwe,cA,uA,dA=_(()=>{"use strict";xd=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
|
|
1528
1528
|
|
|
1529
1529
|
- Use read_file before editing to verify the exact content you want to change.
|
|
1530
1530
|
- Prefer edit_file over write_file for modifying existing files \u2014 write_file is for new files or complete rewrites.
|
|
@@ -1576,13 +1576,13 @@ On your first turn, decide whether to call memory_search based on the request:
|
|
|
1576
1576
|
- If hot memory (shown in <cross-session-memory> tags above) already covers the relevant context, skip the search.
|
|
1577
1577
|
- Search at most once per session for general context. Search again only if new information surfaces a specific topic worth querying.
|
|
1578
1578
|
|
|
1579
|
-
Use FTS5 syntax: "exact phrase", term1 AND term2, prefix*.`});import{mkdirSync as Hq,appendFileSync as Wq,existsSync as Kq}from"fs";import{resolve as Gq}from"path";import{dirname as qq}from"path";function
|
|
1579
|
+
Use FTS5 syntax: "exact phrase", term1 AND term2, prefix*.`});import{mkdirSync as Hq,appendFileSync as Wq,existsSync as Kq}from"fs";import{resolve as Gq}from"path";import{dirname as qq}from"path";function mt(e){let t=e;for(let[n,r]of Vq)t=t.replace(n,(...o)=>{let s=o.slice(0,o.length-2);return r(s)});return t}function Ty(e){return typeof e=="string"?mt(e):Array.isArray(e)?e.map(Ty):e}function Yq(e){if(e===null||typeof e!="object")return e;let t=e,n={...t},r=t.env;if(r&&typeof r=="object"){let o={};for(let[s,i]of Object.entries(r))Jq.test(s)&&typeof i=="string"?o[s]=`<REDACTED length=${i.length}>`:o[s]=i;n.env=o}return"system"in t&&(n.system=Ty(t.system)),"systemPrompt"in t&&(n.systemPrompt=Ty(t.systemPrompt)),n}function Xq(e){if(e==null)return{kind:"undefined",note:"SDK uses minimal prompt; claude_code preset NOT loaded"};if(typeof e=="string")return{kind:"custom-string",note:"SDK uses this string as full system prompt; claude_code preset NOT loaded"};if(Array.isArray(e))return{kind:"custom-string-array",note:"SDK uses array as full system prompt with cache boundaries; claude_code preset NOT loaded"};if(typeof e=="object"){let t=e;if(t.type==="preset"&&t.preset==="claude_code"){let n={kind:"preset-claude-code",note:"claude_code preset loaded"};return typeof t.append=="string"&&(n.append={length:t.append.length}),t.excludeDynamicSections===!0&&(n.excludeDynamicSections=!0),n}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}function pA(e){let t=v.AFK_DUMP_PROMPT;if(!t||t===""||t==="0"||t.toLowerCase()==="false")return;process.stderr.write(`[--dump-prompt] WARNING: dump may contain secrets from system prompt or messages. Inspect before sharing.
|
|
1580
1580
|
`);let n=e.options,r=typeof n=="object"&&n!==null?n.systemPrompt:void 0,o=Xq(r),s={timestamp:new Date().toISOString(),prompt:e.prompt,options:Yq(e.options),provenance:e.provenance,resolution:o};if(t==="1"||t.toLowerCase()==="true"||t.toLowerCase()==="stderr"){let l=JSON.stringify(s,null,2)+`
|
|
1581
1581
|
`;process.stderr.write(l);return}let i=Gq(t),a=qq(i);try{Hq(a,{recursive:!0});let c=(!Kq(i)?zq:"")+JSON.stringify(s)+`
|
|
1582
1582
|
`;Wq(i,c)}catch(l){let c=`[prompt-dump] Failed to write to ${i}: ${String(l)}
|
|
1583
1583
|
`;process.stderr.write(c)}}var zq,Jq,Vq,wi=_(()=>{"use strict";q();zq=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
|
|
1584
1584
|
`,Jq=/key|token|secret|password|credential|auth/i,Vq=[[/sk-ant-[A-Za-z0-9_\-]{8,200}/g,e=>`<REDACTED sk-ant length=${e[0].length}>`],[/sk-(?!ant-)[A-Za-z0-9_\-]{20,200}/g,e=>`<REDACTED sk- length=${e[0].length}>`],[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,e=>`<REDACTED Bearer length=${e[0].length}>`],[/AKIA[A-Z0-9]{16}/g,e=>`<REDACTED AKIA length=${e[0].length}>`],[/xox[baprs]-[A-Za-z0-9\-]{10,200}/g,e=>`<REDACTED xox token length=${e[0].length}>`],[/\d{8,12}:[A-Za-z0-9_\-]{35}/g,e=>`<REDACTED Telegram token length=${e[0].length}>`],[/([A-Za-z_]{3,}(?:[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]|[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll])[A-Za-z_]*)=([^\s]{16,})/g,e=>`${e[1]}=<REDACTED length=${e[2].length}>`],[/([A-Z_]{3,}(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=([^\s]{16,})/g,e=>`${e[1]}=<REDACTED length=${e[2].length}>`]]});import xy from"path";import{appendFileSync as Zq,mkdirSync as Qq}from"fs";import{dirname as ez}from"path";import mA from"@anthropic-ai/sdk";function tz(e){if(e===void 0)return null;if(typeof e=="string")return e.length>0?e:null;if(typeof e=="object"&&e!==null&&"append"in e){let t=e.append;return t&&t.length>0?t:null}return null}var al,fA,Ry,Ge,nz,Fo=_(()=>{"use strict";Ms();$c();Fs();aA();xa();vy();vy();Oa();mh();Ku();kn();dA();zc();Kc();Jn();Ur();an();wi();G();q();Tn();Br();al="anthropic-direct",fA="claude-sonnet-4-5-20250929",Ry=null,Ge=class{name=al;externalTools;memoryStore;providerFactory;skillExecutor;schemas;hookRegistry;permissions;subagentExecutor;composeExecutor;surface;readOnlyMemory;readOnlyBash;mcpManager;customTools;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_currentCwd;_mcpToolsCache=null;_mcpHandlersCache=null;_presenceSessionId=null;constructor(t={}){let n=[...Zn];t.subagentExecutor&&n.push(To),t.skillExecutor&&n.push(xo),t.composeExecutor&&n.push(Ro),t.readOnlyMemory===!0?n.push(Bs):n.push(...Ir),n.push(En);for(let r of t.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);if(this.memoryStore=t.memoryStore??new at,this.externalTools=t.tools,this.skillExecutor=t.skillExecutor,this.schemas=n,this.hookRegistry=t.hookRegistry,this.permissions=t.permissions,this.subagentExecutor=t.subagentExecutor,this.composeExecutor=t.composeExecutor,this.surface=t.surface??"cli",this.readOnlyMemory=t.readOnlyMemory===!0,this.readOnlyBash=t.readOnlyBash===!0,this.customTools=t.customTools??[],this.mcpManager=t.mcpManager,t.mcpManager){let r=t.mcpManager.onToolsRefreshed;t.mcpManager.onToolsRefreshed=o=>{this._mcpToolsCache=null,this._mcpHandlersCache=null,r?.(o)}}t.clientFactory&&(this.providerFactory=t.clientFactory)}buildDispatcher(t,n){let r=Uu(t,n?.cwd),o=Aa(this.memoryStore,void 0,this.surface);for(let[a,l]of o)this.readOnlyMemory&&a!=="memory_search"||r.set(a,l);n?.runtimeStateSource&&r.set("get_runtime_state",js(n.runtimeStateSource));for(let a of this.customTools)r.has(a.schema.name)||r.set(a.schema.name,a.handler);if(this.mcpManager){this._mcpToolsCache||(this._mcpToolsCache=this.mcpManager.getMcpTools()),this._mcpHandlersCache||(this._mcpHandlersCache=this.mcpManager.getMcpHandlers());for(let[a,l]of this._mcpHandlersCache)r.set(a,l)}let s=this._mcpToolsCache??[],i=t==="plan"?n?.planExitControls:void 0;return i&&r.set($o,Wu(i)),new _t({handlers:r,allowAll:wn(t),schemas:[...this.schemas,...s,...i?[Hu]:[]],hookRegistry:Wc(n?.hookRegistry,this.hookRegistry),permissions:qc(this.mcpManager?Gc(this.permissions,this.mcpManager.getMcpToolWireNames()):this.permissions,this.customTools.map(a=>a.schema.name)),subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,cwd:n?.cwd,readRoots:n?.readRoots,writeRoots:n?.writeRoots,...n?.env!==void 0?{env:n.env}:{},sessionId:n?.sessionId,parentSessionId:n?.parentSessionId,...n?.traceWriter?{traceWriter:n.traceWriter}:{},readOnlyBash:this.readOnlyBash})}close(){this.memoryStore.close()}async complete(t){let n=t.apiKey&&t.apiKey.length>0?t.apiKey:v.ANTHROPIC_API_KEY||v.CLAUDE_CODE_OAUTH_TOKEN||"";if(!n)throw new Error(`${al} complete() requires an API key or OAuth token (config apiKey, ANTHROPIC_API_KEY, or CLAUDE_CODE_OAUTH_TOKEN)`);let r={token:n,model:t.model??fA,system:t.system,user:t.user,maxTokens:t.maxTokens??64};t.signal&&(r.signal=t.signal);let o=this.providerFactory??Ry;return o&&(r.clientFactory=o),Ls(r)}ensureSharedRoots(t){if(!this._sharedReadRoots){let n=t?[t]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),t&&!this._initialResolveBase&&(this._initialResolveBase=t),t&&!this._currentCwd&&(this._currentCwd=t)}}addReadRoot(t,n="slash",r){this.ensureSharedRoots();let o=xy.resolve(t);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this.appendProviderAuditLog({action:"grant-read",path:o,source:n,sessionId:r})}addWriteRoot(t,n="slash",r){this.ensureSharedRoots();let o=xy.resolve(t);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this._sharedWriteRoots.includes(o)||this._sharedWriteRoots.push(o),this.appendProviderAuditLog({action:"grant-write",path:o,source:n,sessionId:r})}revokeRoot(t,n="slash",r){if(!this._sharedReadRoots)return;let o=xy.resolve(t);if(this._initialResolveBase&&o===this._initialResolveBase)return;let s=this._sharedReadRoots.indexOf(o);if(s!==-1&&this._sharedReadRoots.splice(s,1),this._sharedWriteRoots){let i=this._sharedWriteRoots.indexOf(o);i!==-1&&this._sharedWriteRoots.splice(i,1)}this.appendProviderAuditLog({action:"revoke",path:o,source:n,sessionId:r})}getGrants(){return{resolveBase:this._initialResolveBase,readRoots:this._sharedReadRoots?.slice()??[],writeRoots:this._sharedWriteRoots?.slice()??[],allowAll:wn(this._currentPermissionMode)}}appendProviderAuditLog(t){try{let n=Es();Qq(ez(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:t.sessionId??null,action:t.action,path:t.path,source:t.source});Zq(n,r+`
|
|
1585
|
-
`)}catch{}}query(t){let n=t.config,r=typeof n.baseUrl=="string"&&n.baseUrl.length>0,o=r?n.apiKey&&n.apiKey.length>0?n.apiKey:v.AFK_LOCAL_API_KEY||"local":n.apiKey&&n.apiKey.length>0?n.apiKey:v.ANTHROPIC_API_KEY||v.CLAUDE_CODE_OAUTH_TOKEN||"";if(!o||o.length===0)throw new Error(`${al} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=Ic(o),i=Ta(o,s,n.baseUrl),a=this.providerFactory??Ry,l=a?a(i):new mA(i),c=r?null:Av(s),u=tz(n.systemPrompt),d=typeof n.model=="string"&&n.model.length>0?
|
|
1585
|
+
`)}catch{}}query(t){let n=t.config,r=typeof n.baseUrl=="string"&&n.baseUrl.length>0,o=r?n.apiKey&&n.apiKey.length>0?n.apiKey:v.AFK_LOCAL_API_KEY||"local":n.apiKey&&n.apiKey.length>0?n.apiKey:v.ANTHROPIC_API_KEY||v.CLAUDE_CODE_OAUTH_TOKEN||"";if(!o||o.length===0)throw new Error(`${al} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=Ic(o),i=Ta(o,s,n.baseUrl),a=this.providerFactory??Ry,l=a?a(i):new mA(i),c=r?null:Av(s),u=tz(n.systemPrompt),d=typeof n.model=="string"&&n.model.length>0?yt(n.model)??n.model:fA,p=by(n,d),m=n.permissionMode??"default";this._currentPermissionMode=m,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let g,h=_a({surface:this.surface,cwd:n.cwd??process.cwd(),modelName:d,providerName:al,permissionMode:m,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>g instanceof _t?g.toolDefs.map(B=>B.name):[],getMcpTools:()=>this.mcpManager?.getMcpTools()??[],getSubagents:()=>this.subagentExecutor?this.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});if((n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let B=n.sessionId,H=h.getWorkspace();Pa({sessionId:B,surface:this.surface,actor:An(n.depth),cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:al,name:d},workspace:H,pid:process.pid}),process.once("exit",()=>{er(B)}),process.once("SIGINT",()=>{er(B),process.exit(130)}),process.once("SIGTERM",()=>{er(B),process.exit(143)})}g=this.externalTools?Ia(this.externalTools,h):this.buildDispatcher(m,{cwd:n.cwd,readRoots:this._sharedReadRoots,writeRoots:this._sharedWriteRoots,...n.env!==void 0?{env:n.env}:{},sessionId:n.sessionId,parentSessionId:n.parentSessionId,traceWriter:n.traceWriter,runtimeStateSource:h,hookRegistry:n.hookRegistry,planExitControls:n.planExitControls});let y=g instanceof _t?[...g.toolDefs]:[...Zn,En],S=n.isSkillDispatch?y.filter(B=>B.name!=="ask_question"&&B.name!=="terminal_font_size"):n.isNonInteractive?y.filter(B=>B.name!=="ask_question"):y,w=this.skillExecutor?AC():"",T=n.cwd||process.cwd(),x=n.isSkillDispatch?xd:`${xd}
|
|
1586
1586
|
|
|
1587
1587
|
${ky}
|
|
1588
1588
|
|
|
@@ -1601,9 +1601,9 @@ ${Ey}`,C=this.readOnlyMemory?uA:cA,R=[x,C];R.push(Us({cwd:T,...n.sessionId!==voi
|
|
|
1601
1601
|
`),this.errored=!0,this.pendingLines=[],this.readyResolve?.(),this.readyResolve=null}}}_writeLine(t){if(!(!this.stream||this.errored))try{this.stream.write(t,n=>{n&&(process.stderr.write(`[afk] session-ledger: write error for ${this.sessionId}: ${String(n)}
|
|
1602
1602
|
`),this.errored=!0)})}catch(n){process.stderr.write(`[afk] session-ledger: write threw for ${this.sessionId}: ${String(n)}
|
|
1603
1603
|
`),this.errored=!0}}async close(t){if(!this.closed)return this.record({kind:"closed",...t!==void 0?{reason:t}:{}}),this.closed=!0,this.readyPromise&&await this.readyPromise,new Promise(n=>{if(!this.stream){n();return}this.stream.end(()=>n())})}};cz=250});function EA(e,t,n){e&&(e.aborted?t.abort(e.reason):e.addEventListener("abort",()=>{t.signal.aborted||t.abort(e.reason)},{once:!0})),t.signal.addEventListener("abort",n,{once:!0})}function TA(e,t){let n=e.permissionMode??"default",r=e.persistSession??!0,o={sessionId:e.sessionId,configuredSessionId:e.sessionId,resume:e.resume,resumeSessionAt:e.resumeSessionAt,continue:e.continue,forkSession:e.forkSession,persistSession:r},s={sessionId:e.sessionId,model:t,permissionMode:n};return{sessionIdentity:o,metadata:s}}var xA=_(()=>{"use strict"});var Od,RA=_(()=>{"use strict";Od=class{initializationPromise;resolveInitialization;rejectInitialization;initializationSettled=!1;sessionMetadata;sessionIdentity;constructor(t,n){this.sessionIdentity=t,this.sessionMetadata=n,this.initializationPromise=new Promise((r,o)=>{this.resolveInitialization=r,this.rejectInitialization=o})}waitForInitialization(){return this.initializationPromise}getSessionIdentity(){return{...this.sessionIdentity,sessionId:this.getSessionId()}}getSessionMetadata(){return{...this.sessionMetadata,sessionId:this.getSessionId()}}getSessionId(){return this.sessionMetadata.sessionId??this.sessionIdentity.sessionId}updateSessionIdentity(t){t&&(this.sessionIdentity={...this.sessionIdentity,sessionId:t},this.sessionMetadata={...this.sessionMetadata,sessionId:t})}setSessionMetadata(t){this.sessionMetadata=t(this.sessionMetadata)}resolveInitializationIfNeeded(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}resolveInitializationOnce(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}rejectInitializationOnce(t){this.initializationSettled||(this.initializationSettled=!0,this.rejectInitialization(t))}isInitializationSettled(){return this.initializationSettled}}});function CA(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.length;if(n===0)return"no results";let r=0,o=0;for(let a of t)if(a&&typeof a=="object"){let l=a.type;l==="fact"?r++:l==="procedure"&&o++}let s=`${n} result${n===1?"":"s"}`;if(r+o!==n)return s;let i=[];return r>0&&i.push(`${r} fact${r===1?"":"s"}`),o>0&&i.push(`${o} procedure${o===1?"":"s"}`),i.length===0?s:`${s} (${i.join(", ")})`}catch{return null}}function AA(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;if(n.target==="hot"&&n.saved===!0){if(n.truncated===!0)return"hot memory saved (truncated to fit cap)";let r=n.usage;if(r&&typeof r=="object"){let o=r.pct;if(typeof o=="number")return`hot memory saved (${o}% of cap)`}return"hot memory saved"}if(n.target==="fact"){if(n.action==="remove")return n.removed===!0?"fact removed":"fact not found";if(n.action==="set"&&typeof n.id=="number")return`fact #${n.id} set`;if(n.action==="supersede"&&typeof n.id=="number"&&typeof n.supersedes=="number")return`fact #${n.id} supersedes #${n.supersedes}`}return null}catch{return null}}function _A(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return typeof n.name=="string"&&n.written===!0?`wrote procedure '${n.name}'`:null}catch{return null}}var IA=_(()=>{"use strict"});function My(e){let t=e.trim();if(t.length===0)return null;let n=t[0];if(n!=="{"&&n!=="[")return null;let r=t[t.length-1];if(n==="{"&&r!=="}"||n==="["&&r!=="]")return null;let o;try{o=JSON.parse(t)}catch{return null}return Array.isArray(o)?PA(uz(o)):o!==null&&typeof o=="object"?PA(dz(o)):null}function uz(e){return e.length===0?"[empty array]":e.length===1?"[1 item]":`[${e.length} items]`}function dz(e){let t=Object.keys(e);if(t.length===0)return"{empty object}";let n=t.slice(0,4),r=t.length>4?", \u2026":"";return`{${n.join(", ")}${r}}`}function PA(e){return e.length<=80?e:e.slice(0,79)+"\u2026"}var MA=_(()=>{"use strict"});function OA(e,t){if(!e)return null;let n=pz.get(e);if(!n)return null;try{let r=n(t);if(r===null)return null;let o=Co(r);return o.length>0?o:null}catch{return null}}var pz,$A=_(()=>{"use strict";IA();MA();Ao();pz=new Map([["memory_search",CA],["memory_update",AA],["procedure_write",_A],["bash",My],["Bash",My]])});function mz(e){let t=/Output too large \((\d+(?:\.\d+)?)\s*(B|KB|MB|GB)\)\.\s*Full output saved to:\s*(\/[^\n]+)/,n=e.match(t);if(!n||!n[1]||!n[2]||!n[3])return null;let r=n[1],o=n[2],s=n[3],i=parseFloat(r),a=i;o==="KB"?a=i*1024:o==="MB"?a=i*1024*1024:o==="GB"&&(a=i*1024*1024*1024);let l=r;return i%1===0&&(l=String(Math.floor(i))),l+=o,{sizeLabel:l,sizeBytes:Math.round(a),absolutePath:s.trim()}}function fz(e){if(e<1024)return`${e}B`;let t=e/1024;if(t<1024)return t%1===0?`${Math.floor(t)}KB`:`${t.toFixed(1)}KB`;let n=t/1024;if(n<1024)return n%1===0?`${Math.floor(n)}MB`:`${n.toFixed(1)}MB`;let r=n/1024;return r%1===0?`${Math.floor(r)}GB`:`${r.toFixed(1)}GB`}function gz(e){let t=Buffer.byteLength(e,"utf8"),n=fz(t),r=e.split(`
|
|
1604
|
-
`);if(r.length<=1&&e.length<=80)return{content:e,truncated:!1,sizeBytes:t,sizeLabel:n};if(r.length<=1)return e.length<=80?{content:e,truncated:!1,sizeBytes:t,sizeLabel:n}:{content:e.substring(0,80)+"\u2026",truncated:!0,sizeBytes:t,sizeLabel:n};if(e.length<=80)return{content:e,truncated:!1,sizeBytes:t,sizeLabel:n};let o=r[0]??"",s=o;return o.length>80&&(s=o.substring(0,80)+"\u2026"),{content:s+`\u2026+${r.length} lines`,truncated:!0,lineCount:r.length,sizeBytes:t,sizeLabel:n}}function hz(e,t){let n={...e.raw??{}};return e.inputTokens!==void 0&&(n.input_tokens=e.inputTokens),e.outputTokens!==void 0&&(n.output_tokens=e.outputTokens),e.cachedInputTokens!==void 0&&(n.cache_read_input_tokens=e.cachedInputTokens),e.cacheCreationTokens!==void 0&&(n.cache_creation_input_tokens=e.cacheCreationTokens),e.totalTokens!==void 0&&(n.total_tokens=e.totalTokens),e.contextWindowTokens!==void 0&&(n.context_window_tokens=e.contextWindowTokens),{sessionId:t,stopReason:e.stopReason??void 0,resultSubtype:e.resultSubtype,durationMs:e.durationMs,durationApiMs:e.durationApiMs,totalCostUsd:e.totalCostUsd,isError:e.isError,usage:Object.keys(n).length>0?n:void 0,modelUsage:e.modelUsage,permissionDenials:e.permissionDenials,errors:e.errors}}function yz(e){let t=e.isError===!0?null:OA(e.toolName,e.content),n=t!==null?{display:t}:{},r=mz(e.content);if(r)return{type:"chunk",chunk:{type:"tool_result",toolUseId:e.toolUseId,content:`Output persisted (${r.sizeLabel}) \u2192 ${r.absolutePath}`,isError:e.isError===!0,persistedPath:r.absolutePath,sizeBytes:r.sizeBytes,sizeLabel:r.sizeLabel,...n}};let{content:o,lineCount:s,sizeBytes:i,sizeLabel:a}=gz(e.content);return{type:"chunk",chunk:{type:"tool_result",toolUseId:e.toolUseId,content:o,isError:e.isError===!0,sizeBytes:i,sizeLabel:a,...e.truncated===!0&&{truncated:!0},...s!==void 0&&{lineCount:s},...n}}}function Oy(e,t){switch(e.type){case"session.init":{let n=e.info;return t.setSessionMetadata(r=>({...r,sessionId:n.sessionId,model:n.model??r.model,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},...n.cwd!==void 0?{cwd:n.cwd}:{},tools:n.tools?[...n.tools]:r.tools,slashCommands:n.slashCommands?[...n.slashCommands]:r.slashCommands,skills:n.skills?[...n.skills]:r.skills,plugins:n.plugins?n.plugins.map(o=>({...o})):r.plugins,mcpServers:n.mcpServers?n.mcpServers.map(o=>({...o})):r.mcpServers,...n.apiKeySource!==void 0?{apiKeySource:n.apiKeySource}:{},...n.version!==void 0?{claudeCodeVersion:n.version}:{},...n.outputStyle!==void 0?{outputStyle:n.outputStyle}:{}})),t.updateSessionIdentity(n.sessionId),t.resolveInitialization(),null}case"session.status":return t.setSessionMetadata(n=>({...n,sessionId:e.sessionId,...e.permissionMode!==void 0?{permissionMode:e.permissionMode}:{permissionMode:n.permissionMode},...e.status!==void 0?{status:e.status}:{}})),null;case"delta.text":return{type:"chunk",chunk:{type:"content",content:e.text,metadata:{eventType:"delta",deltaType:"text_delta"}}};case"delta.reasoning":return{type:"chunk",chunk:{type:"thinking",content:e.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}};case"assistant.message":if(e.sessionId&&t.updateSessionIdentity(e.sessionId),e.text){let n={role:"assistant",content:e.text,timestamp:new Date};return t.conversationHistory.push(n),{type:"message",message:n}}return null;case"tool.use.start":return{type:"chunk",chunk:{type:"tool_use_detail",toolUseId:e.toolUseId,toolName:e.toolName,toolInput:e.toolInput,toolInputRaw:e.toolInputRaw}};case"tool.use":return{type:"chunk",chunk:{type:"tool_use",content:e.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:e.toolUseIds}}};case"tool.output":return yz(e);case"tool.diff":return{type:"chunk",chunk:{type:"tool_diff",toolUseId:e.toolUseId,diff:e.diff}};case"progress":return{type:"progress",progress:{taskId:e.progress.taskId,description:e.progress.description,...e.progress.summary!==void 0?{summary:e.progress.summary}:{},...e.progress.lastToolName!==void 0?{lastToolName:e.progress.lastToolName}:{},totalTokens:e.progress.totalTokens,toolUses:e.progress.toolUses,durationMs:e.progress.durationMs}};case"suggestion":return{type:"suggestion",suggestion:e.suggestion};case"turn.completed":{let n=hz(e.usage,e.sessionId??t.getSessionMetadata().sessionId);t.setLastResponseMetadata(n);for(let r=t.conversationHistory.length-1;r>=0;r--){let o=t.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}if(t.maxBudgetUsd!==void 0&&t.abortBudget!==void 0&&typeof n.totalCostUsd=="number"&&(t._runningCostUsd=(t._runningCostUsd??0)+n.totalCostUsd,t._runningCostUsd>=t.maxBudgetUsd)){Ev(t.traceWriter,{kind:"monetary",runningCostUsd:t._runningCostUsd,maxBudgetUsd:t.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new xr(t._runningCostUsd,t.maxBudgetUsd);return t.abortBudget(r.message),{type:"error",error:r}}return{type:"done",metadata:n}}case"error":return{type:"error",error:e.error};case"paused":return{type:"paused",reason:e.reason,...e.resetsAt!==void 0?{resetsAt:e.resetsAt}:{},...e.accountId!==void 0?{accountId:e.accountId}:{},...e.autoResume!==void 0?{autoResume:e.autoResume}:{}};case"resumed":return{type:"resumed",hotSwapped:e.hotSwapped,...e.accountId!==void 0?{accountId:e.accountId}:{}};case"stream.retry":return{type:"stream_retry"};default:return null}}var DA=_(()=>{"use strict";Rt();je();$A()});import{z as bz}from"zod";var wt,$y=_(()=>{"use strict";_e();Rt();je();tt();gA();Ks();jc();bA();Rt();SA();Id();Ah();Cy();Py();q();Jn();Br();Ma();en();Ay();xA();RA();DA();wt=class{config;_pendingPlanExitSeed;currentState="idle";providerQuery;providerIterator;conversationHistory=[];turnCount=0;lastResponseMetadata=null;initPromise=null;inputStream;abortController;_hookRegistry;sessionEndDispatched=!1;stateManager;sessionRunningCostUsd=0;sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};lastStopReason;maxTurnsHit=!1;hookBlocked=!1;sawProviderError=!1;sessionStartedAt=Date.now();subagentCompletedCount=0;subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};subagentRunningCostUsd=0;ledger=null;ledgerInitAttempted=!1;constructor(t){this.config=t.parentSessionId===void 0&&t.planExitControls===void 0?{...t,planExitControls:{setPermissionMode:r=>this.setPermissionMode(r),requestImplementSeed:(r,o)=>{this._pendingPlanExitSeed={message:r,mode:o}}}}:t,this.abortController=new AbortController,this._hookRegistry=t.hookRegistry,EA(t.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(t.model);De(t.traceWriter,{phase:"session_init_start",model:n,resolvedModel:ht(t.model)??n,origin:Nr(t.surface),actor:Gu(t.parentSessionId)}),this.initSdkLifecycle()}initSdkLifecycle(){this.config.models&&Oc(this.config.models),Cd(this.config);let t=ht(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=TA(this.config,t);this.stateManager=new Od(n,r),this.inputStream=new Si(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)z(`\u{1F7E2} AgentSession: Creating query session via injected provider=${this.config.provider.name}`),this.providerQuery=this.config.provider.query({prompt:o,config:this.config});else{z("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>Rd(a,void 0,{customTools:this.config.customTools});this.providerQuery=new Ad({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>re(a),resolveApiKey:a=>or(a)})}this.conversationHistory=[],this.turnCount=0,this.lastResponseMetadata=null,this.sessionRunningCostUsd=0,this.sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.lastStopReason=void 0,this.maxTurnsHit=!1,this.hookBlocked=!1,this.sawProviderError=!1,this.sessionEndDispatched=!1,this.currentState="idle",this.subagentCompletedCount=0,this.subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.subagentRunningCostUsd=0;let s=this.providerQuery;this.providerIterator=s[Symbol.asyncIterator](),this.initPromise=this.pullInitialization()}async pullInitialization(){try{for(await hA(this._hookRegistry,{event:"SessionStart",sessionId:this.sessionId},{signal:this.abortController.signal,...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}});;){let t=await this.providerIterator.next();if(t.done){this.stateManager.resolveInitializationIfNeeded();return}let n=t.value,r=Oy(n,this.buildTransformDeps());if(n.type==="session.init"){await De(this.config.traceWriter,{phase:"session_init_done",durationMs:Date.now()-this.sessionStartedAt});return}if(r&&r.type==="error"){this.sawProviderError=!0;return}}}catch(t){let n=t instanceof Error?t:new Error(String(t));n instanceof be&&(this.hookBlocked=!0),this.stateManager.isInitializationSettled()||this.stateManager.rejectInitializationOnce(n),await this.dispatchSessionEndOnce("error").catch(()=>{})}}buildTransformDeps(){return{conversationHistory:this.conversationHistory,getSessionMetadata:()=>this.stateManager.getSessionMetadata(),setSessionMetadata:t=>this.stateManager.setSessionMetadata(t),updateSessionIdentity:t=>this.stateManager.updateSessionIdentity(t),resolveInitialization:()=>this.stateManager.resolveInitializationOnce(),setLastResponseMetadata:t=>{this.lastResponseMetadata=t,typeof t.totalCostUsd=="number"&&Number.isFinite(t.totalCostUsd)&&(this.sessionRunningCostUsd+=t.totalCostUsd);let n=t.usage;if(n&&typeof n=="object"){let r=n,o=(s,i)=>{let a=r[s];typeof a=="number"&&Number.isFinite(a)&&(this.sessionRunningTokens[i]+=a)};o("input_tokens","input"),o("output_tokens","output"),o("cache_read_input_tokens","cacheRead"),o("cache_creation_input_tokens","cacheCreation")}typeof t.stopReason=="string"&&(this.lastStopReason=t.stopReason)},maxBudgetUsd:this.config.maxBudgetUsd,abortBudget:t=>{this.abortController.signal.aborted||this.abortController.abort(t)},...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}}}get state(){return this.currentState}get sessionId(){return this.stateManager.getSessionId()}get cwd(){return this.config.cwd}get abortSignal(){return this.abortController.signal}get hookRegistry(){return this._hookRegistry}abort(t){if(t==="closed"||t.startsWith("Budget ")||t.includes("timed out"))throw new Error(`AgentSession.abort: reserved reason "${t}" (use a caller-specific string like 'sigint')`);this.abortController.signal.aborted||this.abortController.abort(t)}async sendMessage(t,n={}){this.assertCanSend();let r=this.config.timeoutMs??Bc,o=async()=>{let s=null,i="";this.currentState=n.stream?"streaming":"processing";for await(let a of this.sendMessageStreamInternal(t)){if(a.type==="chunk"&&a.chunk.type==="content"&&(i+=a.chunk.content),a.type==="message"&&a.message.role==="assistant"&&(s=a.message),a.type==="error")throw a.error;if(a.type==="done"){if(s)return{...s,metadata:a.metadata};if(i)return{role:"assistant",content:i,metadata:a.metadata,timestamp:new Date}}}if(s)return s;if(i)return{role:"assistant",content:i,timestamp:new Date};throw new Error("No assistant response received")};try{return await Uc(o(),r,{controller:this.abortController,label:this.sessionId??"session"})}finally{this.currentState==="processing"&&(this.currentState="idle")}}async sendMessageStructured(t,n,r={}){let{maxRetries:o=2,injectSchemaPrompt:s=!0,...i}=r,a=s?"\n\nRespond with ONLY a JSON object (optionally in a ```json fence) that conforms to this JSON Schema:\n```json\n"+JSON.stringify(bz.toJSONSchema(n,{target:"openapi-3.0"}))+"\n```":"",l="";for(let c=0;c<=o;c++){let u=c===0?t+a:`Your previous response did not match the required JSON schema.
|
|
1604
|
+
`);if(r.length<=1&&e.length<=80)return{content:e,truncated:!1,sizeBytes:t,sizeLabel:n};if(r.length<=1)return e.length<=80?{content:e,truncated:!1,sizeBytes:t,sizeLabel:n}:{content:e.substring(0,80)+"\u2026",truncated:!0,sizeBytes:t,sizeLabel:n};if(e.length<=80)return{content:e,truncated:!1,sizeBytes:t,sizeLabel:n};let o=r[0]??"",s=o;return o.length>80&&(s=o.substring(0,80)+"\u2026"),{content:s+`\u2026+${r.length} lines`,truncated:!0,lineCount:r.length,sizeBytes:t,sizeLabel:n}}function hz(e,t){let n={...e.raw??{}};return e.inputTokens!==void 0&&(n.input_tokens=e.inputTokens),e.outputTokens!==void 0&&(n.output_tokens=e.outputTokens),e.cachedInputTokens!==void 0&&(n.cache_read_input_tokens=e.cachedInputTokens),e.cacheCreationTokens!==void 0&&(n.cache_creation_input_tokens=e.cacheCreationTokens),e.totalTokens!==void 0&&(n.total_tokens=e.totalTokens),e.contextWindowTokens!==void 0&&(n.context_window_tokens=e.contextWindowTokens),{sessionId:t,stopReason:e.stopReason??void 0,resultSubtype:e.resultSubtype,durationMs:e.durationMs,durationApiMs:e.durationApiMs,totalCostUsd:e.totalCostUsd,isError:e.isError,usage:Object.keys(n).length>0?n:void 0,modelUsage:e.modelUsage,permissionDenials:e.permissionDenials,errors:e.errors}}function yz(e){let t=e.isError===!0?null:OA(e.toolName,e.content),n=t!==null?{display:t}:{},r=mz(e.content);if(r)return{type:"chunk",chunk:{type:"tool_result",toolUseId:e.toolUseId,content:`Output persisted (${r.sizeLabel}) \u2192 ${r.absolutePath}`,isError:e.isError===!0,persistedPath:r.absolutePath,sizeBytes:r.sizeBytes,sizeLabel:r.sizeLabel,...n}};let{content:o,lineCount:s,sizeBytes:i,sizeLabel:a}=gz(e.content);return{type:"chunk",chunk:{type:"tool_result",toolUseId:e.toolUseId,content:o,isError:e.isError===!0,sizeBytes:i,sizeLabel:a,...e.truncated===!0&&{truncated:!0},...s!==void 0&&{lineCount:s},...n}}}function Oy(e,t){switch(e.type){case"session.init":{let n=e.info;return t.setSessionMetadata(r=>({...r,sessionId:n.sessionId,model:n.model??r.model,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},...n.cwd!==void 0?{cwd:n.cwd}:{},tools:n.tools?[...n.tools]:r.tools,slashCommands:n.slashCommands?[...n.slashCommands]:r.slashCommands,skills:n.skills?[...n.skills]:r.skills,plugins:n.plugins?n.plugins.map(o=>({...o})):r.plugins,mcpServers:n.mcpServers?n.mcpServers.map(o=>({...o})):r.mcpServers,...n.apiKeySource!==void 0?{apiKeySource:n.apiKeySource}:{},...n.version!==void 0?{claudeCodeVersion:n.version}:{},...n.outputStyle!==void 0?{outputStyle:n.outputStyle}:{}})),t.updateSessionIdentity(n.sessionId),t.resolveInitialization(),null}case"session.status":return t.setSessionMetadata(n=>({...n,sessionId:e.sessionId,...e.permissionMode!==void 0?{permissionMode:e.permissionMode}:{permissionMode:n.permissionMode},...e.status!==void 0?{status:e.status}:{}})),null;case"delta.text":return{type:"chunk",chunk:{type:"content",content:e.text,metadata:{eventType:"delta",deltaType:"text_delta"}}};case"delta.reasoning":return{type:"chunk",chunk:{type:"thinking",content:e.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}};case"assistant.message":if(e.sessionId&&t.updateSessionIdentity(e.sessionId),e.text){let n={role:"assistant",content:e.text,timestamp:new Date};return t.conversationHistory.push(n),{type:"message",message:n}}return null;case"tool.use.start":return{type:"chunk",chunk:{type:"tool_use_detail",toolUseId:e.toolUseId,toolName:e.toolName,toolInput:e.toolInput,toolInputRaw:e.toolInputRaw}};case"tool.use":return{type:"chunk",chunk:{type:"tool_use",content:e.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:e.toolUseIds}}};case"tool.output":return yz(e);case"tool.diff":return{type:"chunk",chunk:{type:"tool_diff",toolUseId:e.toolUseId,diff:e.diff}};case"progress":return{type:"progress",progress:{taskId:e.progress.taskId,description:e.progress.description,...e.progress.summary!==void 0?{summary:e.progress.summary}:{},...e.progress.lastToolName!==void 0?{lastToolName:e.progress.lastToolName}:{},totalTokens:e.progress.totalTokens,toolUses:e.progress.toolUses,durationMs:e.progress.durationMs}};case"suggestion":return{type:"suggestion",suggestion:e.suggestion};case"turn.completed":{let n=hz(e.usage,e.sessionId??t.getSessionMetadata().sessionId);t.setLastResponseMetadata(n);for(let r=t.conversationHistory.length-1;r>=0;r--){let o=t.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}if(t.maxBudgetUsd!==void 0&&t.abortBudget!==void 0&&typeof n.totalCostUsd=="number"&&(t._runningCostUsd=(t._runningCostUsd??0)+n.totalCostUsd,t._runningCostUsd>=t.maxBudgetUsd)){Ev(t.traceWriter,{kind:"monetary",runningCostUsd:t._runningCostUsd,maxBudgetUsd:t.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new xr(t._runningCostUsd,t.maxBudgetUsd);return t.abortBudget(r.message),{type:"error",error:r}}return{type:"done",metadata:n}}case"error":return{type:"error",error:e.error};case"paused":return{type:"paused",reason:e.reason,...e.resetsAt!==void 0?{resetsAt:e.resetsAt}:{},...e.accountId!==void 0?{accountId:e.accountId}:{},...e.autoResume!==void 0?{autoResume:e.autoResume}:{}};case"resumed":return{type:"resumed",hotSwapped:e.hotSwapped,...e.accountId!==void 0?{accountId:e.accountId}:{}};case"stream.retry":return{type:"stream_retry"};default:return null}}var DA=_(()=>{"use strict";Rt();je();$A()});import{z as bz}from"zod";var St,$y=_(()=>{"use strict";_e();Rt();je();tt();gA();Ks();jc();bA();Rt();SA();Id();Ah();Cy();Py();q();Jn();Br();Ma();en();Ay();xA();RA();DA();St=class{config;_pendingPlanExitSeed;currentState="idle";providerQuery;providerIterator;conversationHistory=[];turnCount=0;lastResponseMetadata=null;initPromise=null;inputStream;abortController;_hookRegistry;sessionEndDispatched=!1;stateManager;sessionRunningCostUsd=0;sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};lastStopReason;maxTurnsHit=!1;hookBlocked=!1;sawProviderError=!1;sessionStartedAt=Date.now();subagentCompletedCount=0;subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};subagentRunningCostUsd=0;ledger=null;ledgerInitAttempted=!1;constructor(t){this.config=t.parentSessionId===void 0&&t.planExitControls===void 0?{...t,planExitControls:{setPermissionMode:r=>this.setPermissionMode(r),requestImplementSeed:(r,o)=>{this._pendingPlanExitSeed={message:r,mode:o}}}}:t,this.abortController=new AbortController,this._hookRegistry=t.hookRegistry,EA(t.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(t.model);De(t.traceWriter,{phase:"session_init_start",model:n,resolvedModel:yt(t.model)??n,origin:Nr(t.surface),actor:Gu(t.parentSessionId)}),this.initSdkLifecycle()}initSdkLifecycle(){this.config.models&&Oc(this.config.models),Cd(this.config);let t=yt(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=TA(this.config,t);this.stateManager=new Od(n,r),this.inputStream=new Si(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)z(`\u{1F7E2} AgentSession: Creating query session via injected provider=${this.config.provider.name}`),this.providerQuery=this.config.provider.query({prompt:o,config:this.config});else{z("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>Rd(a,void 0,{customTools:this.config.customTools});this.providerQuery=new Ad({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>re(a),resolveApiKey:a=>or(a)})}this.conversationHistory=[],this.turnCount=0,this.lastResponseMetadata=null,this.sessionRunningCostUsd=0,this.sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.lastStopReason=void 0,this.maxTurnsHit=!1,this.hookBlocked=!1,this.sawProviderError=!1,this.sessionEndDispatched=!1,this.currentState="idle",this.subagentCompletedCount=0,this.subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.subagentRunningCostUsd=0;let s=this.providerQuery;this.providerIterator=s[Symbol.asyncIterator](),this.initPromise=this.pullInitialization()}async pullInitialization(){try{for(await hA(this._hookRegistry,{event:"SessionStart",sessionId:this.sessionId},{signal:this.abortController.signal,...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}});;){let t=await this.providerIterator.next();if(t.done){this.stateManager.resolveInitializationIfNeeded();return}let n=t.value,r=Oy(n,this.buildTransformDeps());if(n.type==="session.init"){await De(this.config.traceWriter,{phase:"session_init_done",durationMs:Date.now()-this.sessionStartedAt});return}if(r&&r.type==="error"){this.sawProviderError=!0;return}}}catch(t){let n=t instanceof Error?t:new Error(String(t));n instanceof be&&(this.hookBlocked=!0),this.stateManager.isInitializationSettled()||this.stateManager.rejectInitializationOnce(n),await this.dispatchSessionEndOnce("error").catch(()=>{})}}buildTransformDeps(){return{conversationHistory:this.conversationHistory,getSessionMetadata:()=>this.stateManager.getSessionMetadata(),setSessionMetadata:t=>this.stateManager.setSessionMetadata(t),updateSessionIdentity:t=>this.stateManager.updateSessionIdentity(t),resolveInitialization:()=>this.stateManager.resolveInitializationOnce(),setLastResponseMetadata:t=>{this.lastResponseMetadata=t,typeof t.totalCostUsd=="number"&&Number.isFinite(t.totalCostUsd)&&(this.sessionRunningCostUsd+=t.totalCostUsd);let n=t.usage;if(n&&typeof n=="object"){let r=n,o=(s,i)=>{let a=r[s];typeof a=="number"&&Number.isFinite(a)&&(this.sessionRunningTokens[i]+=a)};o("input_tokens","input"),o("output_tokens","output"),o("cache_read_input_tokens","cacheRead"),o("cache_creation_input_tokens","cacheCreation")}typeof t.stopReason=="string"&&(this.lastStopReason=t.stopReason)},maxBudgetUsd:this.config.maxBudgetUsd,abortBudget:t=>{this.abortController.signal.aborted||this.abortController.abort(t)},...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}}}get state(){return this.currentState}get sessionId(){return this.stateManager.getSessionId()}get cwd(){return this.config.cwd}get abortSignal(){return this.abortController.signal}get hookRegistry(){return this._hookRegistry}abort(t){if(t==="closed"||t.startsWith("Budget ")||t.includes("timed out"))throw new Error(`AgentSession.abort: reserved reason "${t}" (use a caller-specific string like 'sigint')`);this.abortController.signal.aborted||this.abortController.abort(t)}async sendMessage(t,n={}){this.assertCanSend();let r=this.config.timeoutMs??Bc,o=async()=>{let s=null,i="";this.currentState=n.stream?"streaming":"processing";for await(let a of this.sendMessageStreamInternal(t)){if(a.type==="chunk"&&a.chunk.type==="content"&&(i+=a.chunk.content),a.type==="message"&&a.message.role==="assistant"&&(s=a.message),a.type==="error")throw a.error;if(a.type==="done"){if(s)return{...s,metadata:a.metadata};if(i)return{role:"assistant",content:i,metadata:a.metadata,timestamp:new Date}}}if(s)return s;if(i)return{role:"assistant",content:i,timestamp:new Date};throw new Error("No assistant response received")};try{return await Uc(o(),r,{controller:this.abortController,label:this.sessionId??"session"})}finally{this.currentState==="processing"&&(this.currentState="idle")}}async sendMessageStructured(t,n,r={}){let{maxRetries:o=2,injectSchemaPrompt:s=!0,...i}=r,a=s?"\n\nRespond with ONLY a JSON object (optionally in a ```json fence) that conforms to this JSON Schema:\n```json\n"+JSON.stringify(bz.toJSONSchema(n,{target:"openapi-3.0"}))+"\n```":"",l="";for(let c=0;c<=o;c++){let u=c===0?t+a:`Your previous response did not match the required JSON schema.
|
|
1605
1605
|
Validation error: ${l}
|
|
1606
|
-
Respond again with ONLY a JSON object (optionally in a \`\`\`json fence) that satisfies the schema.`+a,d=await this.sendMessage(u,i),p=Zu(d.content),m=n.safeParse(p);if(m.success)return m.data;l=m.error.message}throw new Error(`structured output did not match schema after ${o+1} attempt(s): ${l}`)}async*sendMessageStream(t){this.assertCanSend(),this.currentState="streaming";try{yield*this.sendMessageStreamInternal(t)}finally{this.currentState==="streaming"&&(this.currentState="idle")}}async*sendMessageStreamInternal(t){this.initPromise&&await this.initPromise;let n=typeof t=="string"?t:this.summarizeContentBlocks(t),r={role:"user",content:n,timestamp:new Date};this.conversationHistory.push(r),this.inputStream.pushUserMessage(t),this.ensureLedger(),this.ledger?.recordUser(n);let o=this.buildTransformDeps();try{for(;;){let s=await this.providerIterator.next();if(s.done)break;let i=s.value,a=Oy(i,o);if(a&&(a.type==="done"?(this.turnCount++,this.sawProviderError=!1):a.type==="error"&&(this.sawProviderError=!0),this.ledger?.recordEvent(a),yield a,a.type==="done"||a.type==="error"))break}}finally{this.currentState==="streaming"&&(this.currentState="idle")}}ensureLedger(){if(this.ledgerInitAttempted||(this.ledgerInitAttempted=!0,this.config.depth!==void 0||this.config.parentSessionId!==void 0)||v.AFK_SESSION_LEDGER_DISABLED==="1")return;let t=this.sessionId;if(!t)return;let n=new Md(t);if(!n.active)return;this.ledger=n;let r=this.getSessionMetadata();n.record({kind:"meta",sessionId:t,model:r.model??String(this.config.model),...r.cwd!==void 0?{cwd:r.cwd}:{}})}sealLedger(t){let n=this.ledger;return n?(this.ledger=null,this.ledgerInitAttempted=!1,n.close(t)):Promise.resolve()}recordLedgerElicitation(t,n){this.ledger?.record({kind:"elicitation",reqId:t,request:n})}summarizeContentBlocks(t){let n=[],r=0;for(let s of t)s.type==="text"?n.push(s.text):s.type==="image"&&r++;let o=n.join(" ");return r>0&&(o=o?`${o} [+ ${r} image(s)]`:`[+ ${r} image(s)]`),o||"[content block(s)]"}async interrupt(){this.currentState!=="streaming"&&this.currentState!=="processing"||(this.currentState="idle",await this.providerQuery.interrupt())}async reset(){if(this.currentState==="closed")throw new Error("Cannot reset: session is closed");if(this.abortController.signal.aborted)throw new it("Cannot reset: session aborted");if(this.currentState==="processing"||this.currentState==="streaming")try{await this.providerQuery.interrupt()}catch{}await this.dispatchSessionEndOnce("reset"),await this.sealLedger("reset");try{await this.providerQuery.close()}catch{}await this.providerIterator.return?.(),this.initPromise&&await Promise.race([this.initPromise,new Promise(t=>setTimeout(t,Xf))]).catch(()=>{}),this.stateManager.resolveInitializationIfNeeded(),this.config={...this.config},delete this.config.resume,delete this.config.sessionId,delete this.config.resumeHistory,delete this.config.resumeSessionAt,delete this.config.continue,delete this.config.forkSession;try{this.initSdkLifecycle()}catch(t){throw this.currentState="closed",new Error(`Session reset failed during lifecycle rebuild: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async onAbort(){this.sealLedger("abort");try{await this.providerQuery.interrupt()}catch{}}async setModel(t){let n=ht(t);typeof t=="string"&&t.length>0&&await this.providerQuery.setModel(t),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(t){await this.providerQuery.setPermissionMode(t),this.stateManager.setSessionMetadata(n=>({...n,permissionMode:t}))}async takePendingPlanExitSeed(){let t=this._pendingPlanExitSeed;if(this._pendingPlanExitSeed=void 0,t!==void 0){try{await this.setPermissionMode(t.mode)}catch(n){z(`\u26A0\uFE0F AgentSession: deferred plan-exit mode flip to '${t.mode}' rejected; dropping implement-seed (staying in plan mode): ${n instanceof Error?n.message:String(n)}`);return}return t.message}}setCwd(t){this.config={...this.config,cwd:t},this.providerQuery.setCwd?.(t),this.config.sessionId!==void 0&&wk(this.config.sessionId,t)}async reauth(){return await this.providerQuery.reauth?.()??null}waitForInitialization(){return this.stateManager.waitForInitialization()}getSessionIdentity(){return this.stateManager.getSessionIdentity()}getSessionMetadata(){return this.stateManager.getSessionMetadata()}getQuery(){return this.providerQuery}supportedCommands(){return this.providerQuery.supportedCommands()}supportedModels(){return this.providerQuery.supportedModels()}supportedAgents(){return this.providerQuery.supportedAgents()}getContextUsage(){return this.providerQuery.getContextUsage()}mcpServerStatus(){return this.providerQuery.mcpServerStatus()}accountInfo(){return this.providerQuery.accountInfo()}rewindFiles(t,n){return this.providerQuery.rewindFiles(t,n)}async compact(){if(this.currentState==="closed")throw new Error("Cannot compact: session is closed");if(this.currentState!=="idle")return{compacted:!1,reason:"session-busy",messagesBefore:0,messagesAfter:0};let t=this.providerQuery.compact?.bind(this.providerQuery);if(!t)return{compacted:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0};this.currentState="compacting";try{return await t()}finally{this.currentState="idle"}}getLastResponseMetadata(){return this.lastResponseMetadata}getOutputStream(){throw new Error("getOutputStream() is not supported \u2014 use sendMessageStream() instead")}getInputStreamRef(){return{pushUserMessage:t=>this.inputStream.pushUserMessage(t)}}getHistory(){return[...this.conversationHistory]}getTurnCount(){return this.turnCount}async close(){if(this.currentState!=="closed"){this.currentState="closed",await this.sealLedger("close"),this.abortController.signal.aborted||this.abortController.abort("closed"),this.stateManager.resolveInitializationIfNeeded();try{await this.providerQuery.close()}catch{}if(await this.providerIterator.return?.(),this.initPromise)try{await Promise.race([this.initPromise,new Promise(t=>setTimeout(t,Xf))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(t){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await this.emitClosure(t).catch(()=>{}),await this.sealTraceWriter(t).catch(()=>{}),await yA(this._hookRegistry,{event:"SessionEnd",sessionId:this.sessionId,reason:t,parentSessionId:this.config.parentSessionId,...this.config.traceWriter?{tracePath:this.config.traceWriter.getTracePath()}:{}},this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}))}async emitClosure(t){let n=this.config.traceWriter;if(!n)return;let r=this.deriveClosureReason(t),o={};this.sessionRunningTokens.input>0&&(o.input=this.sessionRunningTokens.input),this.sessionRunningTokens.output>0&&(o.output=this.sessionRunningTokens.output),this.sessionRunningTokens.cacheRead>0&&(o.cacheRead=this.sessionRunningTokens.cacheRead),this.sessionRunningTokens.cacheCreation>0&&(o.cacheCreation=this.sessionRunningTokens.cacheCreation);let s=No(r);await Rv(n,{reason:r,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,finalTokens:o,...this.lastStopReason!==void 0?{lastStopReason:this.lastStopReason}:{},...s!==null?{guidance:s}:{}})}deriveClosureReason(t){let n=null,r=this.abortController.signal;if(r.aborted&&r.reason!=="closed"){let o=r.reason;o instanceof xr?n="budget_exceeded":o instanceof Ut?n="timeout":typeof o=="string"&&o.startsWith("Budget ")?n="budget_exceeded":typeof o=="string"&&o.includes("timed out")?n="timeout":n="abort"}return wA({dispatchReason:t,maxTurnsHit:this.maxTurnsHit,hookBlocked:this.hookBlocked,abort:n,lastStopReason:this.lastStopReason,sawProviderError:this.sawProviderError})}async sealTraceWriter(t){let n=this.config.traceWriter;if(!n)return;let r=this.deriveSealStatus(t),o=this.subagentCompletedCount>0?this.subagentCompletedCount:void 0,s=this.subagentRunningTokens,a=s.input>0||s.output>0||s.cacheRead>0||s.cacheCreation>0?{...s.input>0?{input:s.input}:{},...s.output>0?{output:s.output}:{},...s.cacheRead>0?{cacheRead:s.cacheRead}:{},...s.cacheCreation>0?{cacheCreation:s.cacheCreation}:{}}:void 0,l=this.subagentRunningCostUsd>0?this.subagentRunningCostUsd:void 0;await n.seal({status:r,finalCostUsd:this.sessionRunningCostUsd,finalTurnCount:this.turnCount,closedAt:new Date().toISOString(),...o!==void 0?{subagentCount:o}:{},...a!==void 0?{subagentTokens:a}:{},...l!==void 0?{subagentCostUsd:l}:{}})}recordSubagentCompletion(t,n){if(this.subagentCompletedCount++,t){let r=(o,s)=>{typeof o=="number"&&Number.isFinite(o)&&o>0&&(this.subagentRunningTokens[s]+=o)};r(t.inputTokens,"input"),r(t.outputTokens,"output"),r(t.cacheReadTokens,"cacheRead"),r(t.cacheCreationTokens,"cacheCreation")}typeof n=="number"&&Number.isFinite(n)&&n>0&&(this.subagentRunningCostUsd+=n)}deriveSealStatus(t){if(t==="error")return"failed";let n=this.abortController.signal;return n.aborted&&n.reason!=="closed"?"cancelled":this.sawProviderError?"failed":"succeeded"}assertCanSend(){if(this.currentState==="closed")throw new Error("Cannot send message: session is closed");if(this.abortController.signal.aborted)throw new it("Cannot send message: session aborted");if(this.currentState==="processing"||this.currentState==="streaming"||this.currentState==="compacting")throw new Error("Cannot send message: session is busy");if(this.config.maxTurns&&this.turnCount>=this.config.maxTurns)throw this.maxTurnsHit=!0,new Error(`Maximum turns (${this.config.maxTurns}) exceeded`)}}});var li=_(()=>{"use strict";$y()});var rI={};ac(rI,{KeychainOAuthProvider:()=>Pi,clearOauthPending:()=>Wy,readOauthPending:()=>nI});import{existsSync as Vd,mkdirSync as eI,readFileSync as Yd,writeFileSync as Hy}from"node:fs";import{execFileSync as Y_}from"node:child_process";import{randomUUID as jV}from"node:crypto";import{homedir as X_,userInfo as Z_}from"node:os";import{join as Q_,dirname as tI}from"node:path";function WV(){let e=process.platform==="darwin",t=process.platform==="linux";return{read(){if(e)try{return Y_("security",["find-generic-password","-s","Claude Code-credentials","-a",Z_().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()||void 0}catch{return}if(t){let n=Q_(X_(),".claude",".credentials.json");if(!Vd(n))return;try{return Yd(n,"utf-8")}catch{return}}},write(n){if(e)Y_("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",Z_().username,"-w",n],{stdio:["ignore","ignore","ignore"]});else if(t){let r=Q_(X_(),".claude",".credentials.json");eI(tI(r),{recursive:!0}),Hy(r,n,{encoding:"utf-8",mode:384})}}}}function nI(){let e=Sa();if(!Vd(e))return{};let t;try{t=JSON.parse(Yd(e,"utf-8"))}catch{return{}}if(t===null||typeof t!="object")return{};let n={};for(let[r,o]of Object.entries(t)){if(o===null||typeof o!="object")continue;let s=o;s.status==="oauth_pending"&&typeof s.authorizationUrl=="string"&&typeof s.timestamp=="number"&&Date.now()-s.timestamp<=HV&&(n[r]={status:"oauth_pending",authorizationUrl:s.authorizationUrl,timestamp:s.timestamp})}return n}function Wy(e){let t=Sa();if(!Vd(t))return;let n;try{n=JSON.parse(Yd(t,"utf-8"))}catch{return}e in n&&(delete n[e],Hy(t,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}))}function KV(e,t){let n=Sa();eI(tI(n),{recursive:!0});let r={};if(Vd(n))try{r=JSON.parse(Yd(n,"utf-8"))}catch{}let o=new URL(t),s=o.origin+o.pathname;r[e]={status:"oauth_pending",authorizationUrl:s,timestamp:Date.now()},Hy(n,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384})}var HV,Pi,Xd=_(()=>{"use strict";G();HV=600*1e3;Pi=class{serverName;backend;constructor(t,n=WV()){this.serverName=t,this.backend=n}get redirectUrl(){return"http://localhost:3000/oauth/callback"}get clientMetadata(){return{redirect_uris:[this.redirectUrl],client_name:"agent-afk",grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}clientInformation(){return this._readSlot().clientInfo}saveClientInformation(t){this._updateSlot(n=>({...n,clientInfo:t}))}tokens(){return this._readSlot().tokens}saveTokens(t){this._updateSlot(n=>({...n,tokens:t}));try{Wy(this.serverName)}catch{}}saveCodeVerifier(t){this._updateSlot(n=>({...n,codeVerifier:t}))}codeVerifier(){let t=this._readSlot().codeVerifier;if(!t)throw new Error(`[mcp:${this.serverName}] no PKCE code verifier stored`);return t}state(){let t=this._readSlot().state;if(t)return t;let n=jV();return this._updateSlot(r=>({...r,state:n})),n}saveDiscoveryState(t){this._updateSlot(n=>({...n,discoveryState:t}))}discoveryState(){return this._readSlot().discoveryState}invalidateCredentials(t){this._updateSlot(n=>{if(t==="all")return{};let r={...n};return t==="client"&&delete r.clientInfo,t==="tokens"&&delete r.tokens,t==="verifier"&&(delete r.codeVerifier,delete r.state),t==="discovery"&&delete r.discoveryState,r})}async redirectToAuthorization(t){let n=t.toString(),r=`\u{1F510} MCP server "${this.serverName}" requires authorization.
|
|
1606
|
+
Respond again with ONLY a JSON object (optionally in a \`\`\`json fence) that satisfies the schema.`+a,d=await this.sendMessage(u,i),p=Zu(d.content),m=n.safeParse(p);if(m.success)return m.data;l=m.error.message}throw new Error(`structured output did not match schema after ${o+1} attempt(s): ${l}`)}async*sendMessageStream(t){this.assertCanSend(),this.currentState="streaming";try{yield*this.sendMessageStreamInternal(t)}finally{this.currentState==="streaming"&&(this.currentState="idle")}}async*sendMessageStreamInternal(t){this.initPromise&&await this.initPromise;let n=typeof t=="string"?t:this.summarizeContentBlocks(t),r={role:"user",content:n,timestamp:new Date};this.conversationHistory.push(r),this.inputStream.pushUserMessage(t),this.ensureLedger(),this.ledger?.recordUser(n);let o=this.buildTransformDeps();try{for(;;){let s=await this.providerIterator.next();if(s.done)break;let i=s.value,a=Oy(i,o);if(a&&(a.type==="done"?(this.turnCount++,this.sawProviderError=!1):a.type==="error"&&(this.sawProviderError=!0),this.ledger?.recordEvent(a),yield a,a.type==="done"||a.type==="error"))break}}finally{this.currentState==="streaming"&&(this.currentState="idle")}}ensureLedger(){if(this.ledgerInitAttempted||(this.ledgerInitAttempted=!0,this.config.depth!==void 0||this.config.parentSessionId!==void 0)||v.AFK_SESSION_LEDGER_DISABLED==="1")return;let t=this.sessionId;if(!t)return;let n=new Md(t);if(!n.active)return;this.ledger=n;let r=this.getSessionMetadata();n.record({kind:"meta",sessionId:t,model:r.model??String(this.config.model),...r.cwd!==void 0?{cwd:r.cwd}:{}})}sealLedger(t){let n=this.ledger;return n?(this.ledger=null,this.ledgerInitAttempted=!1,n.close(t)):Promise.resolve()}recordLedgerElicitation(t,n){this.ledger?.record({kind:"elicitation",reqId:t,request:n})}summarizeContentBlocks(t){let n=[],r=0;for(let s of t)s.type==="text"?n.push(s.text):s.type==="image"&&r++;let o=n.join(" ");return r>0&&(o=o?`${o} [+ ${r} image(s)]`:`[+ ${r} image(s)]`),o||"[content block(s)]"}async interrupt(){this.currentState!=="streaming"&&this.currentState!=="processing"||(this.currentState="idle",await this.providerQuery.interrupt())}async reset(){if(this.currentState==="closed")throw new Error("Cannot reset: session is closed");if(this.abortController.signal.aborted)throw new it("Cannot reset: session aborted");if(this.currentState==="processing"||this.currentState==="streaming")try{await this.providerQuery.interrupt()}catch{}await this.dispatchSessionEndOnce("reset"),await this.sealLedger("reset");try{await this.providerQuery.close()}catch{}await this.providerIterator.return?.(),this.initPromise&&await Promise.race([this.initPromise,new Promise(t=>setTimeout(t,Xf))]).catch(()=>{}),this.stateManager.resolveInitializationIfNeeded(),this.config={...this.config},delete this.config.resume,delete this.config.sessionId,delete this.config.resumeHistory,delete this.config.resumeSessionAt,delete this.config.continue,delete this.config.forkSession;try{this.initSdkLifecycle()}catch(t){throw this.currentState="closed",new Error(`Session reset failed during lifecycle rebuild: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async onAbort(){this.sealLedger("abort");try{await this.providerQuery.interrupt()}catch{}}async setModel(t){let n=yt(t);typeof t=="string"&&t.length>0&&await this.providerQuery.setModel(t),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(t){await this.providerQuery.setPermissionMode(t),this.stateManager.setSessionMetadata(n=>({...n,permissionMode:t}))}async takePendingPlanExitSeed(){let t=this._pendingPlanExitSeed;if(this._pendingPlanExitSeed=void 0,t!==void 0){try{await this.setPermissionMode(t.mode)}catch(n){z(`\u26A0\uFE0F AgentSession: deferred plan-exit mode flip to '${t.mode}' rejected; dropping implement-seed (staying in plan mode): ${n instanceof Error?n.message:String(n)}`);return}return t.message}}setCwd(t){this.config={...this.config,cwd:t},this.providerQuery.setCwd?.(t),this.config.sessionId!==void 0&&wk(this.config.sessionId,t)}async reauth(){return await this.providerQuery.reauth?.()??null}waitForInitialization(){return this.stateManager.waitForInitialization()}getSessionIdentity(){return this.stateManager.getSessionIdentity()}getSessionMetadata(){return this.stateManager.getSessionMetadata()}getQuery(){return this.providerQuery}supportedCommands(){return this.providerQuery.supportedCommands()}supportedModels(){return this.providerQuery.supportedModels()}supportedAgents(){return this.providerQuery.supportedAgents()}getContextUsage(){return this.providerQuery.getContextUsage()}mcpServerStatus(){return this.providerQuery.mcpServerStatus()}accountInfo(){return this.providerQuery.accountInfo()}rewindFiles(t,n){return this.providerQuery.rewindFiles(t,n)}async compact(){if(this.currentState==="closed")throw new Error("Cannot compact: session is closed");if(this.currentState!=="idle")return{compacted:!1,reason:"session-busy",messagesBefore:0,messagesAfter:0};let t=this.providerQuery.compact?.bind(this.providerQuery);if(!t)return{compacted:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0};this.currentState="compacting";try{return await t()}finally{this.currentState="idle"}}getLastResponseMetadata(){return this.lastResponseMetadata}getOutputStream(){throw new Error("getOutputStream() is not supported \u2014 use sendMessageStream() instead")}getInputStreamRef(){return{pushUserMessage:t=>this.inputStream.pushUserMessage(t)}}getHistory(){return[...this.conversationHistory]}getTurnCount(){return this.turnCount}async close(){if(this.currentState!=="closed"){this.currentState="closed",await this.sealLedger("close"),this.abortController.signal.aborted||this.abortController.abort("closed"),this.stateManager.resolveInitializationIfNeeded();try{await this.providerQuery.close()}catch{}if(await this.providerIterator.return?.(),this.initPromise)try{await Promise.race([this.initPromise,new Promise(t=>setTimeout(t,Xf))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(t){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await this.emitClosure(t).catch(()=>{}),await this.sealTraceWriter(t).catch(()=>{}),await yA(this._hookRegistry,{event:"SessionEnd",sessionId:this.sessionId,reason:t,parentSessionId:this.config.parentSessionId,...this.config.traceWriter?{tracePath:this.config.traceWriter.getTracePath()}:{}},this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}))}async emitClosure(t){let n=this.config.traceWriter;if(!n)return;let r=this.deriveClosureReason(t),o={};this.sessionRunningTokens.input>0&&(o.input=this.sessionRunningTokens.input),this.sessionRunningTokens.output>0&&(o.output=this.sessionRunningTokens.output),this.sessionRunningTokens.cacheRead>0&&(o.cacheRead=this.sessionRunningTokens.cacheRead),this.sessionRunningTokens.cacheCreation>0&&(o.cacheCreation=this.sessionRunningTokens.cacheCreation);let s=No(r);await Rv(n,{reason:r,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,finalTokens:o,...this.lastStopReason!==void 0?{lastStopReason:this.lastStopReason}:{},...s!==null?{guidance:s}:{}})}deriveClosureReason(t){let n=null,r=this.abortController.signal;if(r.aborted&&r.reason!=="closed"){let o=r.reason;o instanceof xr?n="budget_exceeded":o instanceof Ut?n="timeout":typeof o=="string"&&o.startsWith("Budget ")?n="budget_exceeded":typeof o=="string"&&o.includes("timed out")?n="timeout":n="abort"}return wA({dispatchReason:t,maxTurnsHit:this.maxTurnsHit,hookBlocked:this.hookBlocked,abort:n,lastStopReason:this.lastStopReason,sawProviderError:this.sawProviderError})}async sealTraceWriter(t){let n=this.config.traceWriter;if(!n)return;let r=this.deriveSealStatus(t),o=this.subagentCompletedCount>0?this.subagentCompletedCount:void 0,s=this.subagentRunningTokens,a=s.input>0||s.output>0||s.cacheRead>0||s.cacheCreation>0?{...s.input>0?{input:s.input}:{},...s.output>0?{output:s.output}:{},...s.cacheRead>0?{cacheRead:s.cacheRead}:{},...s.cacheCreation>0?{cacheCreation:s.cacheCreation}:{}}:void 0,l=this.subagentRunningCostUsd>0?this.subagentRunningCostUsd:void 0;await n.seal({status:r,finalCostUsd:this.sessionRunningCostUsd,finalTurnCount:this.turnCount,closedAt:new Date().toISOString(),...o!==void 0?{subagentCount:o}:{},...a!==void 0?{subagentTokens:a}:{},...l!==void 0?{subagentCostUsd:l}:{}})}recordSubagentCompletion(t,n){if(this.subagentCompletedCount++,t){let r=(o,s)=>{typeof o=="number"&&Number.isFinite(o)&&o>0&&(this.subagentRunningTokens[s]+=o)};r(t.inputTokens,"input"),r(t.outputTokens,"output"),r(t.cacheReadTokens,"cacheRead"),r(t.cacheCreationTokens,"cacheCreation")}typeof n=="number"&&Number.isFinite(n)&&n>0&&(this.subagentRunningCostUsd+=n)}deriveSealStatus(t){if(t==="error")return"failed";let n=this.abortController.signal;return n.aborted&&n.reason!=="closed"?"cancelled":this.sawProviderError?"failed":"succeeded"}assertCanSend(){if(this.currentState==="closed")throw new Error("Cannot send message: session is closed");if(this.abortController.signal.aborted)throw new it("Cannot send message: session aborted");if(this.currentState==="processing"||this.currentState==="streaming"||this.currentState==="compacting")throw new Error("Cannot send message: session is busy");if(this.config.maxTurns&&this.turnCount>=this.config.maxTurns)throw this.maxTurnsHit=!0,new Error(`Maximum turns (${this.config.maxTurns}) exceeded`)}}});var li=_(()=>{"use strict";$y()});var rI={};ac(rI,{KeychainOAuthProvider:()=>Pi,clearOauthPending:()=>Wy,readOauthPending:()=>nI});import{existsSync as Vd,mkdirSync as eI,readFileSync as Yd,writeFileSync as Hy}from"node:fs";import{execFileSync as Y_}from"node:child_process";import{randomUUID as jV}from"node:crypto";import{homedir as X_,userInfo as Z_}from"node:os";import{join as Q_,dirname as tI}from"node:path";function WV(){let e=process.platform==="darwin",t=process.platform==="linux";return{read(){if(e)try{return Y_("security",["find-generic-password","-s","Claude Code-credentials","-a",Z_().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()||void 0}catch{return}if(t){let n=Q_(X_(),".claude",".credentials.json");if(!Vd(n))return;try{return Yd(n,"utf-8")}catch{return}}},write(n){if(e)Y_("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",Z_().username,"-w",n],{stdio:["ignore","ignore","ignore"]});else if(t){let r=Q_(X_(),".claude",".credentials.json");eI(tI(r),{recursive:!0}),Hy(r,n,{encoding:"utf-8",mode:384})}}}}function nI(){let e=Sa();if(!Vd(e))return{};let t;try{t=JSON.parse(Yd(e,"utf-8"))}catch{return{}}if(t===null||typeof t!="object")return{};let n={};for(let[r,o]of Object.entries(t)){if(o===null||typeof o!="object")continue;let s=o;s.status==="oauth_pending"&&typeof s.authorizationUrl=="string"&&typeof s.timestamp=="number"&&Date.now()-s.timestamp<=HV&&(n[r]={status:"oauth_pending",authorizationUrl:s.authorizationUrl,timestamp:s.timestamp})}return n}function Wy(e){let t=Sa();if(!Vd(t))return;let n;try{n=JSON.parse(Yd(t,"utf-8"))}catch{return}e in n&&(delete n[e],Hy(t,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}))}function KV(e,t){let n=Sa();eI(tI(n),{recursive:!0});let r={};if(Vd(n))try{r=JSON.parse(Yd(n,"utf-8"))}catch{}let o=new URL(t),s=o.origin+o.pathname;r[e]={status:"oauth_pending",authorizationUrl:s,timestamp:Date.now()},Hy(n,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384})}var HV,Pi,Xd=_(()=>{"use strict";G();HV=600*1e3;Pi=class{serverName;backend;constructor(t,n=WV()){this.serverName=t,this.backend=n}get redirectUrl(){return"http://localhost:3000/oauth/callback"}get clientMetadata(){return{redirect_uris:[this.redirectUrl],client_name:"agent-afk",grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}clientInformation(){return this._readSlot().clientInfo}saveClientInformation(t){this._updateSlot(n=>({...n,clientInfo:t}))}tokens(){return this._readSlot().tokens}saveTokens(t){this._updateSlot(n=>({...n,tokens:t}));try{Wy(this.serverName)}catch{}}saveCodeVerifier(t){this._updateSlot(n=>({...n,codeVerifier:t}))}codeVerifier(){let t=this._readSlot().codeVerifier;if(!t)throw new Error(`[mcp:${this.serverName}] no PKCE code verifier stored`);return t}state(){let t=this._readSlot().state;if(t)return t;let n=jV();return this._updateSlot(r=>({...r,state:n})),n}saveDiscoveryState(t){this._updateSlot(n=>({...n,discoveryState:t}))}discoveryState(){return this._readSlot().discoveryState}invalidateCredentials(t){this._updateSlot(n=>{if(t==="all")return{};let r={...n};return t==="client"&&delete r.clientInfo,t==="tokens"&&delete r.tokens,t==="verifier"&&(delete r.codeVerifier,delete r.state),t==="discovery"&&delete r.discoveryState,r})}async redirectToAuthorization(t){let n=t.toString(),r=`\u{1F510} MCP server "${this.serverName}" requires authorization.
|
|
1607
1607
|
|
|
1608
1608
|
Open this URL to authorize:
|
|
1609
1609
|
${n}`;KV(this.serverName,n);let o=!1;try{let{pushIfConfigured:s}=await Promise.resolve().then(()=>(_o(),Ng));o=await s(r)!==null}catch{}o||process.stderr.write(`[mcp:${this.serverName}] OAuth authorization required.
|
|
@@ -1665,7 +1665,7 @@ Single-pass sub-agent reports are prone to confident hallucination \u2014 polish
|
|
|
1665
1665
|
|
|
1666
1666
|
Skip when: the findings are purely exploratory, the sub-agent ran inside an already-verifying orchestrator, the user is about to dismiss the report, or the stakes are low (read-only Q&A).`,Ez=wz.map(e=>new RegExp(`(?:^|-)${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:-|$)`,"i"));function Tz(e){return e?Ez.some(t=>t.test(e)):!1}function xz(e){return vz.some(t=>t.test(e))}function Rz(e){let t=0;for(let n of Sz)n.test(e)&&t++;return t}function LA(e){if(e.event!=="SubagentStop")return{};let t=e.lastMessage??"";return t.length<600?{}:Tz(e.agentType)?{}:xz(t)?{}:Rz(t)<2?{}:{injectContext:kz}}an();Za();ng();function FA(e){return function(n){if(n.event!=="PreToolUse")return{};if(n.parentSessionId)return{};if(e()!=="plan")return{};let{toolName:r}=n;if(_n(r)==="write")return{decision:"block",reason:`plan mode: ${r} is refused. Use /plan off to exit plan mode.`};if(r==="bash"){let o=typeof n.input=="object"&&n.input!==null?String(n.input.command??""):"",s=Vc(o);if(s.mutating)return{decision:"block",reason:`plan mode: bash refused \u2014 command looks state-mutating (${s.reason??"mutation detected"}). Read-only investigation (git status/log/diff, ls, cat, grep, find) is allowed. Use /plan off to act.`}}return{}}}$a();Za();import NA from"path";var Cz=["rm -rf","rm ","sudo","eval ","chmod","chown","git push --force","git push -f","git reset --hard","mkfs","fdisk","diskutil eraseDisk","dd if=","dd of=","| sh","| bash","|sh","|bash"],Az=["git push","git reset","git commit","git stash drop","git stash clear","npm install","pnpm install","yarn","pip install","apt ","apt-get ","brew install","tee "," > "," >> ","mv ","cp ","mkdir","touch","pnpm build","tsc ","eslint --fix"],_z=["pnpm test","vitest","jest","pytest","cargo test","go test","git status","git log","git diff","git show","ls ","cat ","head ","tail ","find ","grep ","echo ","printf "];function Iz(e){return typeof e=="object"&&e!==null&&"command"in e?String(e.command??""):typeof e=="string"?e:""}function Pz(e){if(typeof e!="object"||e===null)return"";let t=e;return typeof t.file_path=="string"?t.file_path:typeof t.path=="string"?t.path:""}function Mz(e){for(let t of Cz)if(e.includes(t))return"high";for(let t of Az)if(e.includes(t))return"medium";for(let t of _z)if(e.includes(t))return"safe";return"medium"}function Oz(e,t){if(!e)return"safe";let n=rr(NA.resolve(t.cwd,e)),r=wg();for(let o of r)if(n===o||n.startsWith(o+"/"))return"high";if(n.includes("/.git/"))return"high";if(t.workspaceRoot!==void 0){let o=rr(t.workspaceRoot);if(NA.relative(o,n).startsWith(".."))return"high"}return n.includes("/node_modules/")?"medium":"safe"}function BA(e,t,n){let r=e.toLowerCase();if(r==="bash"){let o=Iz(t);return Mz(o)}if(r==="write_file"||r==="edit_file"){let o=Pz(t);return Oz(o,n)}return _n(e)==="read"?"safe":r==="send_telegram"?"medium":"safe"}Fr();je();wi();var $z=3e5,UA=300;function jA(e,t,n,r){let o=r?.approvalTimeoutMs??$z,s=r?.promptForApproval??!0,i=r?.traceWriter,a=r?.route??((c,u)=>lt.route(c,u));async function l(c,u,d){let p=Date.now(),m=Dz(c,u),g=new AbortController,h=()=>g.abort();d&&(d.aborted?g.abort():d.addEventListener("abort",h,{once:!0}));let b=Symbol("afk-approval-timeout"),y,S,w=new Promise(R=>{S=()=>{y||(y=setTimeout(()=>{g.abort(),R(b)},o),y.unref?.())}});function T(R,k){let $=Date.now()-p,A=R.decision==="block";return Ar(i,{hookEvent:"PreToolUse",...A?{decision:"block"}:{},...A&&R.reason!==void 0?{reason:R.reason}:{},...A?{blockedTool:c}:{},durationMs:$,approvalOutcome:k}),R}let x;try{x=await Promise.race([a(m,{signal:g.signal,onActive:S}),w])}finally{y&&clearTimeout(y),d&&d.removeEventListener("abort",h)}if(x===b)return T(cl(c,`no approval arrived within ${Math.round(o/1e3)}s`),"timeout");if(x.action!=="accept")return T(cl(c,x.action==="cancel"?"the operator cancelled the approval prompt":"no operator approval was available"),x.action==="cancel"?"cancel":"decline");let C=String(x.content?.choice??"").toLowerCase();return C==="approve"?T({},"approved"):C==="deny"?T(cl(c,"the operator denied it"),"denied"):T(cl(c,"the approval prompt returned an unrecognised choice"),"unrecognised")}return function(u,d){if(u.event!=="PreToolUse")return{};if(e()!=="autonomous")return{};let{toolName:p}=u;if(p==="send_telegram")return{};let m=n?.()??t??process.cwd();return BA(p,u.input,{cwd:m,workspaceRoot:m})!=="high"?{}:u.parentSessionId!==void 0||!s?cl(p,"AFK mode runs autonomously without a human watching"):l(p,u.input,d)}}function Dz(e,t){let n=Lz(t);return{serverName:"agent-afk",message:`AFK: \`${e}\` is high-risk / irreversible and AFK mode runs unattended. Approve this single call?`+(n?`
|
|
1667
1667
|
|
|
1668
|
-
Input: ${n}`:""),mode:"form",title:"AFK high-risk approval",requestedSchema:{type:"object",properties:{choice:{type:"string",title:"Approve this high-risk operation?",enum:["approve","deny"],description:"'approve' runs this single call. 'deny' refuses it (the model gets an error and should push an Asking summary or take a safe path)."}},required:["choice"]}}}function Lz(e){let t;try{t=typeof e=="string"?e:JSON.stringify(e)}catch{t=String(e)}return t?(t=
|
|
1668
|
+
Input: ${n}`:""),mode:"form",title:"AFK high-risk approval",requestedSchema:{type:"object",properties:{choice:{type:"string",title:"Approve this high-risk operation?",enum:["approve","deny"],description:"'approve' runs this single call. 'deny' refuses it (the model gets an error and should push an Asking summary or take a safe path)."}},required:["choice"]}}}function Lz(e){let t;try{t=typeof e=="string"?e:JSON.stringify(e)}catch{t=String(e)}return t?(t=mt(t),t.length>UA?`${t.slice(0,UA)}\u2026 [truncated]`:t):""}function cl(e,t){return{decision:"block",reason:`AFK mode: ${e} is refused \u2014 this op is high-risk or irreversible, and ${t}. Push an Asking summary to Telegram (send_telegram) and stop, or have the operator run /afk off and take over.`}}Xe();import{mkdirSync as Bz,rmSync as Uz,writeFileSync as jz}from"fs";import{join as Dy}from"path";Rt();function Fz(e){let t=new Set;for(let a of e.nodes){if(t.has(a.id))throw new Error(`Duplicate node ID: ${a.id}`);t.add(a.id)}let n=new Set;for(let a of e.edges){if(!t.has(a.from))throw new Error(`Edge references non-existent node: ${a.from}`);if(!t.has(a.to))throw new Error(`Edge references non-existent node: ${a.to}`);let l=`${a.from}->${a.to}`;if(n.has(l))throw new Error(`Duplicate edge: ${a.from} -> ${a.to}`);n.add(l)}let r=HA(e),o=new Map(r.inDegree),s=[];for(let[a,l]of o)l===0&&s.push(a);let i=0;for(;s.length>0;){let a=s.shift();i+=1;for(let l of r.downstream.get(a)??[]){let c=o.get(l)-1;o.set(l,c),c===0&&s.push(l)}}if(i!==t.size)throw new Error("Cycle detected in DAG")}function HA(e){let t=new Map,n=new Map,r=new Map;for(let o of e.nodes)t.set(o.id,new Set),n.set(o.id,new Set),r.set(o.id,0);for(let o of e.edges)t.get(o.from).add(o.to),n.get(o.to).add(o.from),r.set(o.to,r.get(o.to)+1);return{downstream:t,upstream:n,inDegree:r}}function Nz(e,t,n){let r=[e];for(;r.length>0;){let o=r.shift();for(let s of t.get(o)??[])n.has(s)||(n.add(s),r.push(s))}}async function WA(e,t,n={}){if(e.nodes.length===0)return{outputs:{},failed:[],skipped:[]};Fz(e);let{failFast:r=!0,nodeTimeoutMs:o}=n,s=o!==void 0&&Number.isFinite(o)&&o>0,i=HA(e),a=new Map(e.nodes.map(h=>[h.id,h])),l={},c=[],u=new Set,d=new Set,p=new Map(i.inDegree),m=new AbortController,g=()=>{m.signal.aborted||m.abort(t.reason)};t.aborted?m.abort(t.reason):t.addEventListener("abort",g,{once:!0});try{for(;!m.signal.aborted;){let h=[];for(let[y,S]of p)S===0&&!d.has(y)&&!u.has(y)&&h.push(y);if(h.length===0)break;let b=await Promise.allSettled(h.map(async y=>{let S=a.get(y),w=new AbortController,T=()=>{w.signal.aborted||w.abort(m.signal.reason)};m.signal.aborted?w.abort(m.signal.reason):m.signal.addEventListener("abort",T,{once:!0});let x;s&&!w.signal.aborted&&(x=setTimeout(()=>{w.signal.aborted||w.abort(new Ut(`DAG node "${y}" exceeded nodeTimeoutMs of ${o}ms`,o))},o));let C={};for(let R of i.upstream.get(y)??[])C[R]=l[R];try{let R=await S.run(C,w.signal);return{id:y,result:R}}finally{x!==void 0&&clearTimeout(x),m.signal.removeEventListener("abort",T)}}));for(let y=0;y<b.length;y++){let S=b[y];if(S.status==="fulfilled"){let{id:w,result:T}=S.value;l[w]=T,d.add(w),p.delete(w);for(let x of i.downstream.get(w)??[])p.set(x,p.get(x)-1)}else{let w=S.reason instanceof Error?S.reason:new Error(String(S.reason)),T=h[y];c.push({id:T,error:w}),d.add(T),p.delete(T),Nz(T,i.downstream,u),r&&m.abort("fail-fast")}}}}finally{t.removeEventListener("abort",g)}return{outputs:l,failed:c,skipped:Array.from(u)}}zt();Rt();async function $d(e){let{manager:t,parentSession:n,nodes:r,edges:o,failFast:s,nodeTimeoutMs:i}=e,a=n.abortSignal??new AbortController().signal,l=r.map(c=>({id:c.id,async run(u,d){let p=await t.forkSubagent({parent:{sessionId:n.sessionId},config:{model:c.model??"sonnet",systemPrompt:c.systemPrompt,...c.canUseTool!==void 0?{canUseTool:c.canUseTool}:{},...c.cwd!==void 0?{cwd:c.cwd}:{},...c.readRoots!==void 0?{readRoots:c.readRoots}:{},...c.writeRoots!==void 0?{writeRoots:c.writeRoots}:{},...c.apiKey!==void 0?{apiKey:c.apiKey}:{}},idPrefix:c.idPrefix??`dag-${c.id}`,...c.outputSchema!==void 0?{outputSchema:c.outputSchema}:{},...c.agentType!==void 0?{agentType:c.agentType}:{},...c.parentId!==void 0?{parentId:c.parentId}:{}}),m=()=>{p.cancel().catch(()=>{})};d.aborted?p.cancel().catch(()=>{}):d.addEventListener("abort",m,{once:!0});try{if(d.aborted)throw new DOMException("Aborted","AbortError");let g=c.promptBuilder(u),h=await p.runToResult(g);if(h.status!=="succeeded"){let b,y=d.reason;throw y instanceof Ut?b=new Error(`Subagent ${c.id} aborted: ${y.message}`,h.error?{cause:h.error}:{}):b=h.error??new Error(`Subagent ${c.id} ${h.status}`),jx(b,{partialOutput:h.partialOutput,subagentId:h.id})}return h.output??h.message?.content}finally{d.removeEventListener("abort",m),await p.teardown().catch(()=>{})}}}));return WA({nodes:l,edges:o},a,{failFast:s,nodeTimeoutMs:i})}tt();Yn();Br();Xn();G();var KA=1e3,Dd=36e5,GA=1,qA=1e3;function Hz(e){if(typeof e!="object"||e===null)throw new Error("Compose tool input must be an object");let t=e,n=t.nodes;if(!Array.isArray(n)||n.length===0)throw new Error('Compose tool requires a non-empty "nodes" array');let r=20;if(n.length>r)throw new Error(`Compose tool supports at most ${r} nodes (got ${n.length}). Split into multiple compose calls for larger workloads.`);let o=[],s=new Set;for(let d of n){if(typeof d!="object"||d===null)throw new Error("Each node must be an object");let p=d,m=p.id;if(typeof m!="string"||m.trim().length===0)throw new Error('Each node must have a non-empty "id" string');if(!/^[A-Za-z0-9_-]+$/.test(m)){let b=m.replace(/[\x00-\x1f\x7f]/g,"?").slice(0,32);throw new Error(`Node id "${b}" must match /^[A-Za-z0-9_-]+$/ (alphanumeric, underscore, hyphen)`)}if(s.has(m))throw new Error(`Duplicate node ID: ${m}`);s.add(m);let g=p.prompt;if(typeof g!="string"||g.trim().length===0)throw new Error(`Node "${m}" must have a non-empty "prompt" string`);let h;if(p.model!==void 0){if(typeof p.model!="string")throw new Error(`Node "${m}" model must be a string`);h=p.model}o.push({id:m,prompt:g,model:h})}let i;if(t.edges!==void 0){if(!Array.isArray(t.edges))throw new Error('"edges" must be an array');i=[];for(let d of t.edges){if(typeof d!="object"||d===null)throw new Error("Each edge must be an object");let p=d;if(typeof p.from!="string"||typeof p.to!="string")throw new Error('Each edge must have "from" and "to" strings');if(!s.has(p.from))throw new Error(`Edge references non-existent node: ${p.from}`);if(!s.has(p.to))throw new Error(`Edge references non-existent node: ${p.to}`);i.push({from:p.from,to:p.to})}}let a;if(t.fail_fast!==void 0){if(typeof t.fail_fast!="boolean")throw new Error('"fail_fast" must be a boolean');a=t.fail_fast}let l=[],c;if(t.node_timeout_ms!==void 0){let d=t.node_timeout_ms;if(typeof d!="number"||!Number.isFinite(d)||d<=0)throw new Error('"node_timeout_ms" must be a positive finite number (milliseconds)');if(d<KA)throw new Error(`"node_timeout_ms" must be at least ${KA}ms (got ${d}). Sub-second timeouts are almost always a unit mistake.`);c=Math.min(Dd,d),d>Dd&&l.push(`node_timeout_ms clamped: requested ${d}ms exceeds the maximum ${Dd}ms; using ${Dd}ms.`)}let u;if(t.max_tool_calls_per_node!==void 0){let d=t.max_tool_calls_per_node;if(typeof d!="number"||!Number.isFinite(d)||d<=0)throw new Error('"max_tool_calls_per_node" must be a positive finite number');if(!Number.isInteger(d))throw new Error(`"max_tool_calls_per_node" must be an integer (got ${d}). Tool calls are discrete events; fractional budgets are not meaningful.`);if(d<GA)throw new Error(`"max_tool_calls_per_node" must be at least ${GA}`);if(d>qA)throw new Error(`"max_tool_calls_per_node" must be at most ${qA} (got ${d}). A larger budget no longer constrains useful work.`);u=d}return{parsed:{nodes:o,edges:i,fail_fast:a,node_timeout_ms:c,max_tool_calls_per_node:u},warnings:l}}var ul=8e3,zA=500,JA=4e3;function Wz(e){if(e==null)return;let t=typeof e=="string"?e:JSON.stringify(e);if(t.length!==0)return t.length>JA?t.slice(0,JA)+`
|
|
1669
1669
|
\u2026 (truncated)`:t}function Kz(e,t,n,r){try{let o=Dy(Gn(),e,"compose",t);Bz(o,{recursive:!0});let s=Dy(o,`${n}.txt`);return jz(s,r,"utf8"),s}catch{return}}function Gz(e,t){let n=[],r=[];for(let[o,s]of Object.entries(e.outputs)){let i=typeof s=="string"?s:s!=null?JSON.stringify(s):"(no output)",a;if(i.length>ul){let l=Kz(t.sessionId,t.callId,o,i);r.push({nodeId:o,emittedChars:ul,totalChars:i.length,...l!==void 0?{spillPath:l}:{}});let c=l!==void 0?`
|
|
1670
1670
|
\u2026 (truncated at ${ul} / ${i.length} chars \u2014 full output at ${l})`:`
|
|
1671
1671
|
\u2026 (truncated at ${ul} / ${i.length} chars)`;a=i.slice(0,ul)+c}else a=i;n.push(`## ${o}
|
|
@@ -1752,7 +1752,7 @@ ${l}`):s,a=!1;for(let l of i){let c=await n.pushIfConfigured(l);if(c===null){e.w
|
|
|
1752
1752
|
`),this.client=a,this.connected=!0,this.pendingAuthTransport=void 0;let l=await Zd(this.client.listTools(),s,()=>new Error(`MCP server "${this.serverName}" listTools timed out after ${s}ms`),()=>a.close().catch(()=>{})),c=this.client.getServerVersion();return{tools:l.tools,serverInfo:c?{name:c.name,version:c.version}:void 0}}async listTools(){if(!this.client)throw new Error(`McpClient(${this.serverName}): not connected`);let t=this.config.timeout??Ky;return(await Zd(this.client.listTools(),t,()=>new Error(`MCP server "${this.serverName}" listTools timed out after ${t}ms`))).tools}async refreshTools(){return this.listTools()}async callTool(t,n,r){if(!this.client)return{content:`MCP server "${this.serverName}" is not connected`,isError:!0};if(r.aborted)return{content:"Tool call aborted",isError:!0};let o=this.config.timeout??Ky,s;try{s=await this.client.callTool({name:t,arguments:n??{}},GV,{signal:r,timeout:o})}catch(i){let a=i instanceof Error?i.message:String(i);return{content:`MCP tool "${this.serverName}.${t}" failed: ${a}`,isError:!0}}return qV(s)}async finishAuth(t){if(!this.pendingAuthTransport)throw new Error(`McpClient(${this.serverName}): no pending OAuth transport \u2014 server is not in oauth_pending state`);await this.pendingAuthTransport.finishAuth(t)}async disconnect(){if(this.pendingAuthTransport=void 0,!this.client)return;let t=this.client;this.client=void 0,this.connected=!1;try{await t.close()}catch{}}};function qV(e){let t=[];for(let r of e.content??[])if(r.type==="text")t.push(r.text);else if(r.type==="image")t.push(`[image block: mimeType=${r.mimeType}, ${r.data.length} bytes base64]`);else if(r.type==="resource"){let o="resource"in r&&typeof r.resource=="object"?r.resource.uri??"(unknown)":"(unknown)";t.push(`[resource block: ${o}]`)}else t.push(`[unknown block: ${JSON.stringify(r)}]`);let n=t.join(`
|
|
1753
1753
|
`);return{content:n.length===0?"(empty tool result)":n,...e.isError?{isError:!0}:{}}}function zV(e,t,n){let r=t.type??(t.command?"stdio":"streamable-http");return{primary:Jd(e,t,n),fallback:r==="streamable-http"?()=>Jd(e,{...t,type:"sse"},n):null}}function JV(e){return e instanceof aI&&(e.code===404||e.code===405)}function VV(e){return e instanceof aI?e.code:void 0}function Zd(e,t,n,r){let o=null,s=new Promise((i,a)=>{o=setTimeout(()=>{if(r!==void 0)try{let l=r();l&&typeof l.then=="function"&&l.catch(()=>{})}catch{}a(n())},t)});return Promise.race([e,s]).finally(()=>{o!==null&&clearTimeout(o)})}import{createHash as YV}from"node:crypto";var lI="mcp__",cI="__",qy=64,XV=6;function fl(e){if(e.length===0)return"_";let n=e.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_{2,}/g,"_");return n.length===0?"_":n}function ZV(e){return YV("sha256").update(e).digest("hex").slice(0,XV)}function uI(e,t){let n=fl(e),r=fl(t),o=`${lI}${n}${cI}${r}`;if(o.length<=qy)return o;let i=`${`${lI}${ZV(e)}${cI}`}${r}`;return i.length<=qy?i:i.slice(0,qy)}function gl(e){let t=new Map,n=new Map;for(let{serverName:o,toolNames:s}of e)for(let i of s){let a=uI(o,i),l={serverName:o,originalToolName:i},c=t.get(a);if(c===void 0){t.set(a,l);continue}if(c.serverName===o&&c.originalToolName===i)continue;let u=n.get(a)??[c];u.push(l),n.set(a,u)}let r=[];for(let[o,s]of n)r.push({wireName:o,pairs:s});return{tools:t,conflicts:r}}je();var hr=class e{records;nameRegistry;onToolsRefreshed;constructor(t){this.records=t;let n=[];for(let[o,s]of t)s.state.status==="connected"&&n.push({serverName:o,toolNames:s.tools.map(i=>i.name)});let r=gl(n);if(r.conflicts.length>0){let o=r.conflicts.map(s=>{let i=s.pairs.map(a=>`${a.serverName}.${a.originalToolName}`).join(", ");return` ${s.wireName} \u2190 ${i}`});throw new Error(`MCP tool name conflicts (rename one of the servers in mcp.json):
|
|
1754
1754
|
${o.join(`
|
|
1755
|
-
`)}`)}this.nameRegistry=r.tools}static async fromConfig(t,n={}){if(n.warnings&&n.warnings.length>0)for(let c of n.warnings)console.warn(`[mcp] ${c}`);let r=new Map,o=[],s={manager:void 0};for(let[c,u]of Object.entries(t)){let d=fl(c);if(d!==c&&console.warn(`[mcp] server name "${c}" sanitized to "${d}" for wire encoding`),u.disabled){r.set(c,{client:void 0,tools:[],state:{serverName:c,config:u,status:"disabled",toolCount:0}});continue}let m={client:void 0,tools:[],state:{serverName:c,config:u,status:"connecting",toolCount:0}};r.set(c,m);let g=new Mi(c,u);m.client=g,g.onTransportError=b=>{m.state.status="error",m.state.error=Qd(b.message,200),console.warn(`[mcp:${c}] transport error: ${b.message}`)},g.onToolListChanged=()=>{s.manager?.refreshServer(c).catch(b=>{let y=b instanceof Error?b.message:String(b);console.warn(`[mcp:${c}] refreshServer failed: ${y}`)})};let h=(async()=>{let b=Date.now();De(n.traceWriter,{phase:"mcp_server_start",metadata:{server:c}});let y="error",S=0;try{let{tools:w,serverInfo:T}=await g.connect();m.tools=w,m.state.status="connected",m.state.toolCount=w.length,m.state.lastListedAt=Date.now(),y="connected",S=w.length;let x=T?`${T.name}@${T.version}`:"unknown";console.log(`[mcp:${c}] connected (${x}) \u2014 ${w.length} tool(s)`)}catch(w){if(w instanceof Gy){m.state.status="oauth_pending",y="oauth_pending",console.log(`[mcp:${c}] OAuth authorization required \u2014 check Telegram or stderr for the auth URL`);return}let T=w instanceof Error?w.message:String(w);if(m.state.status="error",m.state.error=Qd(T,200),u.alwaysLoad===!0)throw new Error(`MCP server "${c}" is marked alwaysLoad but failed to connect: ${T}`);console.warn(`[mcp:${c}] connect failed: ${T}`)}finally{De(n.traceWriter,{phase:"mcp_server_done",durationMs:Date.now()-b,metadata:{server:c,status:y,toolCount:S}})}})();o.push(h)}let a=(await Promise.allSettled(o)).find(c=>c.status==="rejected");if(a){for(let c of r.values())c.client&&await c.client.disconnect().catch(()=>{});throw a.reason}let l=new e(r);return s.manager=l,l}getMcpTools(){let t=[];for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let s=this.records.get(r);if(!s||s.state.status!=="connected")continue;let i=s.tools.find(a=>a.name===o);i&&t.push(QV(n,i))}return t}getMcpHandlers(){let t=new Map;for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let s=this.records.get(r);!s||s.state.status!=="connected"||t.set(n,async(i,a)=>s.client?s.client.callTool(o,i,a):{content:`MCP server "${r}" is not connected`,isError:!0})}return t}async refreshServer(t){let n=this.records.get(t);if(!n||!n.client||n.state.status!=="connected")throw new Error(`McpManager.refreshServer("${t}"): server is not connected`);let r=await n.client.refreshTools();for(let[s,i]of this.nameRegistry)i.serverName===t&&this.nameRegistry.delete(s);let o=gl([{serverName:t,toolNames:r.map(s=>s.name)}]);if(o.conflicts.length>0)for(let s of o.conflicts){let i=s.pairs.map(a=>`${a.serverName}.${a.originalToolName}`).join(", ");console.warn(`[mcp:${t}] wire-name conflict after refresh \u2014 skipping: ${s.wireName} \u2190 ${i}`)}for(let[s,i]of o.tools)this.nameRegistry.set(s,i);n.tools=r,n.state.toolCount=r.length,n.state.lastListedAt=Date.now(),console.log(`[mcp:${t}] tool list refreshed \u2014 ${r.length} tool(s)`),this.onToolsRefreshed?.(t)}getServerStates(){return[...this.records.values()].map(t=>({...t.state}))}getMcpToolWireNames(){return[...this.nameRegistry.keys()]}async completeAuth(t,n){let r=this.records.get(t);if(!r)throw new Error(`McpManager.completeAuth("${t}"): server not found`);if(r.state.status!=="oauth_pending")throw new Error(`McpManager.completeAuth("${t}"): server is not in oauth_pending state (current status: ${r.state.status})`);if(!r.client)throw new Error(`McpManager.completeAuth("${t}"): no client record \u2014 server was never connected`);await r.client.finishAuth(n),await r.client.disconnect().catch(i=>{let a=i instanceof Error?i.message:String(i);console.warn(`[mcp:${t}] completeAuth disconnect warning: ${a}`)});let o=new Mi(t,r.state.config);o.onTransportError=i=>{r.state.status="error",r.state.error=Qd(i.message,200),console.warn(`[mcp:${t}] transport error: ${i.message}`)},o.onToolListChanged=()=>{this.refreshServer(t).catch(i=>{let a=i instanceof Error?i.message:String(i);console.warn(`[mcp:${t}] refreshServer failed: ${a}`)})},r.state.status="connecting",r.state.error=void 0,r.client=o;try{let{tools:i,serverInfo:a}=await o.connect();r.tools=i,r.state.status="connected",r.state.toolCount=i.length,r.state.lastListedAt=Date.now();let l=a?`${a.name}@${a.version}`:"unknown";console.log(`[mcp:${t}] OAuth complete \u2014 connected (${l}) \u2014 ${i.length} tool(s)`)}catch(i){let a=i instanceof Error?i.message:String(i);throw r.state.status="error",r.state.error=Qd(a,200),new Error(`McpManager.completeAuth("${t}"): reconnect failed: ${a}`)}for(let[i,a]of this.nameRegistry)a.serverName===t&&this.nameRegistry.delete(i);let s=gl([{serverName:t,toolNames:r.tools.map(i=>i.name)}]);for(let[i,a]of s.tools)this.nameRegistry.set(i,a);this.onToolsRefreshed?.(t)}hasAnyConnected(){for(let t of this.records.values())if(t.state.status==="connected")return!0;return!1}size(){return this.records.size}async disconnectAll(){let t=[];for(let[n,r]of this.records)r.client&&t.push(r.client.disconnect().catch(o=>{let s=o instanceof Error?o.message:String(o);console.warn(`[mcp:${n}] disconnect error: ${s}`)}));await Promise.all(t)}};function QV(e,t){let n=t.description??`MCP tool ${t.name}`;return{name:e,description:n,input_schema:t.inputSchema}}function Qd(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}q();G();import{existsSync as yl,lstatSync as eY,readFileSync as tY,readdirSync as nY}from"node:fs";import{join as hl}from"node:path";function Uo(){return hl(Qt(),"mcp.json")}function dI(e=process.cwd()){return hl(e,".mcp.json")}var rY=5;function zy(e=Ve()){if(!yl(e))return[];let t=[];return pI(e,e,0,t,new Set),t}function pI(e,t,n,r,o){if(n>rY||o.has(t))return;o.add(t);let s=hl(t,".claude-plugin","plugin.json");if(yl(s)){let a=hl(t,".claude-plugin","mcp.json");yl(a)&&r.push(a);return}let i;try{i=nY(t)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=hl(t,a),c;try{c=eY(l)}catch{continue}c.isDirectory()&&pI(e,l,n+1,r,o)}}function oY(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return{ok:!1,error:`server "${e}" must be an object`};let n=t,r=n.type;if(r===void 0)if(typeof n.command=="string")r="stdio";else if(typeof n.url=="string")r="streamable-http";else return{ok:!1,error:`server "${e}" has no \`command\` or \`url\`; cannot infer transport`};if(r==="stdio"){if(typeof n.command!="string"||n.command.length===0)return{ok:!1,error:`stdio server "${e}" requires non-empty \`command\``}}else if(r==="streamable-http"||r==="sse"){if(typeof n.url!="string"||n.url.length===0)return{ok:!1,error:`${r} server "${e}" requires non-empty \`url\``}}else return{ok:!1,error:`server "${e}" has unsupported \`type\`: ${String(r)}`};let o={type:r};if(typeof n.command=="string"&&(o.command=n.command),Array.isArray(n.args)&&(o.args=n.args.filter(s=>typeof s=="string")),n.env!==void 0&&typeof n.env=="object"&&n.env!==null){let s={};for(let[i,a]of Object.entries(n.env))typeof a=="string"&&(s[i]=a);o.env=s}if(typeof n.url=="string"&&(o.url=n.url),n.headers!==void 0&&typeof n.headers=="object"&&n.headers!==null){let s={};for(let[i,a]of Object.entries(n.headers))typeof a=="string"&&(s[i]=a);o.headers=s}return typeof n.oauth=="boolean"&&(o.oauth=n.oauth),typeof n.disabled=="boolean"&&(o.disabled=n.disabled),typeof n.alwaysLoad=="boolean"&&(o.alwaysLoad=n.alwaysLoad),typeof n.timeout=="number"&&n.timeout>0&&(o.timeout=n.timeout),{ok:!0,config:o}}function Oi(e){if(!yl(e))return{mcpServers:{},sources:[],warnings:[]};let t=[],n;try{n=JSON.parse(tY(e,"utf-8"))}catch(i){let a=i instanceof Error?i.message:String(i);return t.push(`mcp.json at ${e}: parse error \u2014 ${a}`),{mcpServers:{},sources:[e],warnings:t}}if(n===null||typeof n!="object"||Array.isArray(n))return t.push(`mcp.json at ${e}: top-level must be an object`),{mcpServers:{},sources:[e],warnings:t};let o=n.mcpServers;if(o==null||typeof o!="object")return{mcpServers:{},sources:[e],warnings:t};let s={};for(let[i,a]of Object.entries(o)){let l=oY(i,a);l.ok?s[i]=l.config:t.push(`mcp.json at ${e}: skipping ${l.error}`)}return{mcpServers:s,sources:[e],warnings:t}}function jo(e={}){let t=[],n=[];if(e.importedMcpConfigs&&e.importedMcpConfigs.length>0)for(let a of e.importedMcpConfigs)t.push({path:a,loaded:Oi(a)});if(e.pluginsRoot!==null){let a=e.pluginsRoot,l=a?zy(a):zy();for(let c of l)t.push({path:c,loaded:Oi(c)})}if(!e.skipUserGlobal){let a=Uo();t.push({path:a,loaded:Oi(a)})}if(!e.skipProjectLocal&&v.AFK_ALLOW_PROJECT_MCP!=="0"){let a=dI(e.cwd);yl(a)&&(t.push({path:a,loaded:Oi(a)}),n.push(`mcp: loaded project-local config from ${a} \u2014 set AFK_ALLOW_PROJECT_MCP=0 to disable auto-load`))}e.cliOverride!==void 0&&t.push({path:e.cliOverride,loaded:Oi(e.cliOverride)});let r=new Map,o=[...n],s=[];for(let a of t){for(let l of a.loaded.warnings)o.push(l);if(a.loaded.sources.length>0)for(let l of a.loaded.sources)s.includes(l)||s.push(l);for(let[l,c]of Object.entries(a.loaded.mcpServers)){let u=r.get(l);u&&o.push(`mcp: server "${l}" defined in ${u.source} is overridden by ${a.path}`),r.set(l,{config:c,source:a.path})}}let i={};for(let[a,l]of r)i[a]=l.config;return{mcpServers:i,sources:s,warnings:o}}Xd();ir();je();function aY(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}var fI=10*1024*1024;function gI(){return new Promise((e,t)=>{let n=[],r=0;if(process.stdin.readableEnded){e("");return}let o=s=>{if(r+=s.length,r>fI){process.stdin.destroy(new Error(`stdin exceeds ${fI}-byte limit`));return}n.push(s)};process.stdin.on("data",o),process.stdin.once("end",()=>{process.stdin.removeListener("data",o),e(Buffer.concat(n).toString("utf-8").replace(/\n+$/,""))}),process.stdin.once("error",s=>{process.stdin.removeListener("data",o),t(s)}),process.stdin.resume()})}function hI(e,t){return new Promise((n,r)=>{let o=e.write(t,s=>{s?r(s):o&&n()});if(!o){let s=()=>{e.removeListener("error",i),n()},i=a=>{e.removeListener("drain",s),r(a)};e.once("drain",s),e.once("error",i)}})}function wI(e){e.command("chat").description("Send a message to the agent").argument("[message]","Message to send; use `-` or omit to read from stdin").option("-m, --model <model>","Model to use. Short aliases: opus|opus_1m|sonnet|sonnet_1m|haiku. Any other value (e.g. `auto` for cursor-api-proxy, or a full `claude-*` ID) passes through to the SDK/proxy untouched.",St()).option("-s, --stream","[no-op] reserved; use --format stream-json for headless streaming",!1).option("-f, --format <format>","Output format (text|json|stream-json)","text").option("--max-turns <number>","Maximum conversation turns","10").option("--thinking <mode>","Thinking mode: 'adaptive' | 'disabled' | 'enabled:<N>'","enabled:max").option("--effort <level>","Effort level: low|medium|high|xhigh|max").option("--max-budget-usd <usd>","Hard session cost ceiling in USD. Env: AFK_MAX_BUDGET_USD").option("--task-budget <tokens>","Soft per-task token budget. Env: AFK_TASK_BUDGET").option("--max-output-tokens <n|max>","Per-response output cap ('max' = model ceiling). Env: AFK_MAX_OUTPUT_TOKENS").option("--provider <name>","Provider to use: anthropic|anthropic-direct|openai|openai-compatible. Default: auto-selected by model").option("--dump-prompt [path]",'Dump resolved SDK prompt+options+provenance to file (default: ~/.afk/logs/prompt-dump-<ISO>.json) or "stderr"').option("-w, --worktree [branch]","Create a git worktree for an isolated one-shot. Optional value sets the branch name; otherwise auto-named. On clean exit (no uncommitted changes) the worktree and branch are auto-removed; on dirty exit the worktree is preserved. Mirrors `afk interactive -w`.").option("--worktree-base <ref>","Base git ref for the worktree created by --worktree. Default: the remote's default branch (origin/main), fetched fresh. Pass HEAD to base on your local checkout instead. Also: AFK_WORKTREE_BASE.").option("--mcp-config <path>","Path to an additional MCP config file (highest priority \u2014 merges over ~/.afk/config/mcp.json, project-local .mcp.json, and plugin-contributed configs). File format identical to mcp.json.").option("--resume <id>","Resume a persisted session by id").option("--continue","Continue the most recent persisted session in cwd").option("--session-id <uuid>","Assign a specific UUID to this session (creates new; errors if already exists)").option("--post <targets>","Headless publish of the final assistant message: github, telegram, or github,telegram").option("--post-pr <ref>","PR number, URL, or branch for --post github (defaults to the current-branch PR)").option("--dangerously-skip-permissions","Force bypass mode (already the default for new installs): skip path-approval prompts; read/write ANY path with no confirmation (permissionMode=bypassPermissions). Disable persistently with `afk config set permissionMode default`. Does not affect ask_question.").action(async(t,n)=>{if(n.resume&&n.continue){process.stderr.write(`Error: --resume and --continue are mutually exclusive
|
|
1755
|
+
`)}`)}this.nameRegistry=r.tools}static async fromConfig(t,n={}){if(n.warnings&&n.warnings.length>0)for(let c of n.warnings)console.warn(`[mcp] ${c}`);let r=new Map,o=[],s={manager:void 0};for(let[c,u]of Object.entries(t)){let d=fl(c);if(d!==c&&console.warn(`[mcp] server name "${c}" sanitized to "${d}" for wire encoding`),u.disabled){r.set(c,{client:void 0,tools:[],state:{serverName:c,config:u,status:"disabled",toolCount:0}});continue}let m={client:void 0,tools:[],state:{serverName:c,config:u,status:"connecting",toolCount:0}};r.set(c,m);let g=new Mi(c,u);m.client=g,g.onTransportError=b=>{m.state.status="error",m.state.error=Qd(b.message,200),console.warn(`[mcp:${c}] transport error: ${b.message}`)},g.onToolListChanged=()=>{s.manager?.refreshServer(c).catch(b=>{let y=b instanceof Error?b.message:String(b);console.warn(`[mcp:${c}] refreshServer failed: ${y}`)})};let h=(async()=>{let b=Date.now();De(n.traceWriter,{phase:"mcp_server_start",metadata:{server:c}});let y="error",S=0;try{let{tools:w,serverInfo:T}=await g.connect();m.tools=w,m.state.status="connected",m.state.toolCount=w.length,m.state.lastListedAt=Date.now(),y="connected",S=w.length;let x=T?`${T.name}@${T.version}`:"unknown";console.log(`[mcp:${c}] connected (${x}) \u2014 ${w.length} tool(s)`)}catch(w){if(w instanceof Gy){m.state.status="oauth_pending",y="oauth_pending",console.log(`[mcp:${c}] OAuth authorization required \u2014 check Telegram or stderr for the auth URL`);return}let T=w instanceof Error?w.message:String(w);if(m.state.status="error",m.state.error=Qd(T,200),u.alwaysLoad===!0)throw new Error(`MCP server "${c}" is marked alwaysLoad but failed to connect: ${T}`);console.warn(`[mcp:${c}] connect failed: ${T}`)}finally{De(n.traceWriter,{phase:"mcp_server_done",durationMs:Date.now()-b,metadata:{server:c,status:y,toolCount:S}})}})();o.push(h)}let a=(await Promise.allSettled(o)).find(c=>c.status==="rejected");if(a){for(let c of r.values())c.client&&await c.client.disconnect().catch(()=>{});throw a.reason}let l=new e(r);return s.manager=l,l}getMcpTools(){let t=[];for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let s=this.records.get(r);if(!s||s.state.status!=="connected")continue;let i=s.tools.find(a=>a.name===o);i&&t.push(QV(n,i))}return t}getMcpHandlers(){let t=new Map;for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let s=this.records.get(r);!s||s.state.status!=="connected"||t.set(n,async(i,a)=>s.client?s.client.callTool(o,i,a):{content:`MCP server "${r}" is not connected`,isError:!0})}return t}async refreshServer(t){let n=this.records.get(t);if(!n||!n.client||n.state.status!=="connected")throw new Error(`McpManager.refreshServer("${t}"): server is not connected`);let r=await n.client.refreshTools();for(let[s,i]of this.nameRegistry)i.serverName===t&&this.nameRegistry.delete(s);let o=gl([{serverName:t,toolNames:r.map(s=>s.name)}]);if(o.conflicts.length>0)for(let s of o.conflicts){let i=s.pairs.map(a=>`${a.serverName}.${a.originalToolName}`).join(", ");console.warn(`[mcp:${t}] wire-name conflict after refresh \u2014 skipping: ${s.wireName} \u2190 ${i}`)}for(let[s,i]of o.tools)this.nameRegistry.set(s,i);n.tools=r,n.state.toolCount=r.length,n.state.lastListedAt=Date.now(),console.log(`[mcp:${t}] tool list refreshed \u2014 ${r.length} tool(s)`),this.onToolsRefreshed?.(t)}getServerStates(){return[...this.records.values()].map(t=>({...t.state}))}getMcpToolWireNames(){return[...this.nameRegistry.keys()]}async completeAuth(t,n){let r=this.records.get(t);if(!r)throw new Error(`McpManager.completeAuth("${t}"): server not found`);if(r.state.status!=="oauth_pending")throw new Error(`McpManager.completeAuth("${t}"): server is not in oauth_pending state (current status: ${r.state.status})`);if(!r.client)throw new Error(`McpManager.completeAuth("${t}"): no client record \u2014 server was never connected`);await r.client.finishAuth(n),await r.client.disconnect().catch(i=>{let a=i instanceof Error?i.message:String(i);console.warn(`[mcp:${t}] completeAuth disconnect warning: ${a}`)});let o=new Mi(t,r.state.config);o.onTransportError=i=>{r.state.status="error",r.state.error=Qd(i.message,200),console.warn(`[mcp:${t}] transport error: ${i.message}`)},o.onToolListChanged=()=>{this.refreshServer(t).catch(i=>{let a=i instanceof Error?i.message:String(i);console.warn(`[mcp:${t}] refreshServer failed: ${a}`)})},r.state.status="connecting",r.state.error=void 0,r.client=o;try{let{tools:i,serverInfo:a}=await o.connect();r.tools=i,r.state.status="connected",r.state.toolCount=i.length,r.state.lastListedAt=Date.now();let l=a?`${a.name}@${a.version}`:"unknown";console.log(`[mcp:${t}] OAuth complete \u2014 connected (${l}) \u2014 ${i.length} tool(s)`)}catch(i){let a=i instanceof Error?i.message:String(i);throw r.state.status="error",r.state.error=Qd(a,200),new Error(`McpManager.completeAuth("${t}"): reconnect failed: ${a}`)}for(let[i,a]of this.nameRegistry)a.serverName===t&&this.nameRegistry.delete(i);let s=gl([{serverName:t,toolNames:r.tools.map(i=>i.name)}]);for(let[i,a]of s.tools)this.nameRegistry.set(i,a);this.onToolsRefreshed?.(t)}hasAnyConnected(){for(let t of this.records.values())if(t.state.status==="connected")return!0;return!1}size(){return this.records.size}async disconnectAll(){let t=[];for(let[n,r]of this.records)r.client&&t.push(r.client.disconnect().catch(o=>{let s=o instanceof Error?o.message:String(o);console.warn(`[mcp:${n}] disconnect error: ${s}`)}));await Promise.all(t)}};function QV(e,t){let n=t.description??`MCP tool ${t.name}`;return{name:e,description:n,input_schema:t.inputSchema}}function Qd(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}q();G();import{existsSync as yl,lstatSync as eY,readFileSync as tY,readdirSync as nY}from"node:fs";import{join as hl}from"node:path";function Uo(){return hl(Qt(),"mcp.json")}function dI(e=process.cwd()){return hl(e,".mcp.json")}var rY=5;function zy(e=Ve()){if(!yl(e))return[];let t=[];return pI(e,e,0,t,new Set),t}function pI(e,t,n,r,o){if(n>rY||o.has(t))return;o.add(t);let s=hl(t,".claude-plugin","plugin.json");if(yl(s)){let a=hl(t,".claude-plugin","mcp.json");yl(a)&&r.push(a);return}let i;try{i=nY(t)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=hl(t,a),c;try{c=eY(l)}catch{continue}c.isDirectory()&&pI(e,l,n+1,r,o)}}function oY(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return{ok:!1,error:`server "${e}" must be an object`};let n=t,r=n.type;if(r===void 0)if(typeof n.command=="string")r="stdio";else if(typeof n.url=="string")r="streamable-http";else return{ok:!1,error:`server "${e}" has no \`command\` or \`url\`; cannot infer transport`};if(r==="stdio"){if(typeof n.command!="string"||n.command.length===0)return{ok:!1,error:`stdio server "${e}" requires non-empty \`command\``}}else if(r==="streamable-http"||r==="sse"){if(typeof n.url!="string"||n.url.length===0)return{ok:!1,error:`${r} server "${e}" requires non-empty \`url\``}}else return{ok:!1,error:`server "${e}" has unsupported \`type\`: ${String(r)}`};let o={type:r};if(typeof n.command=="string"&&(o.command=n.command),Array.isArray(n.args)&&(o.args=n.args.filter(s=>typeof s=="string")),n.env!==void 0&&typeof n.env=="object"&&n.env!==null){let s={};for(let[i,a]of Object.entries(n.env))typeof a=="string"&&(s[i]=a);o.env=s}if(typeof n.url=="string"&&(o.url=n.url),n.headers!==void 0&&typeof n.headers=="object"&&n.headers!==null){let s={};for(let[i,a]of Object.entries(n.headers))typeof a=="string"&&(s[i]=a);o.headers=s}return typeof n.oauth=="boolean"&&(o.oauth=n.oauth),typeof n.disabled=="boolean"&&(o.disabled=n.disabled),typeof n.alwaysLoad=="boolean"&&(o.alwaysLoad=n.alwaysLoad),typeof n.timeout=="number"&&n.timeout>0&&(o.timeout=n.timeout),{ok:!0,config:o}}function Oi(e){if(!yl(e))return{mcpServers:{},sources:[],warnings:[]};let t=[],n;try{n=JSON.parse(tY(e,"utf-8"))}catch(i){let a=i instanceof Error?i.message:String(i);return t.push(`mcp.json at ${e}: parse error \u2014 ${a}`),{mcpServers:{},sources:[e],warnings:t}}if(n===null||typeof n!="object"||Array.isArray(n))return t.push(`mcp.json at ${e}: top-level must be an object`),{mcpServers:{},sources:[e],warnings:t};let o=n.mcpServers;if(o==null||typeof o!="object")return{mcpServers:{},sources:[e],warnings:t};let s={};for(let[i,a]of Object.entries(o)){let l=oY(i,a);l.ok?s[i]=l.config:t.push(`mcp.json at ${e}: skipping ${l.error}`)}return{mcpServers:s,sources:[e],warnings:t}}function jo(e={}){let t=[],n=[];if(e.importedMcpConfigs&&e.importedMcpConfigs.length>0)for(let a of e.importedMcpConfigs)t.push({path:a,loaded:Oi(a)});if(e.pluginsRoot!==null){let a=e.pluginsRoot,l=a?zy(a):zy();for(let c of l)t.push({path:c,loaded:Oi(c)})}if(!e.skipUserGlobal){let a=Uo();t.push({path:a,loaded:Oi(a)})}if(!e.skipProjectLocal&&v.AFK_ALLOW_PROJECT_MCP!=="0"){let a=dI(e.cwd);yl(a)&&(t.push({path:a,loaded:Oi(a)}),n.push(`mcp: loaded project-local config from ${a} \u2014 set AFK_ALLOW_PROJECT_MCP=0 to disable auto-load`))}e.cliOverride!==void 0&&t.push({path:e.cliOverride,loaded:Oi(e.cliOverride)});let r=new Map,o=[...n],s=[];for(let a of t){for(let l of a.loaded.warnings)o.push(l);if(a.loaded.sources.length>0)for(let l of a.loaded.sources)s.includes(l)||s.push(l);for(let[l,c]of Object.entries(a.loaded.mcpServers)){let u=r.get(l);u&&o.push(`mcp: server "${l}" defined in ${u.source} is overridden by ${a.path}`),r.set(l,{config:c,source:a.path})}}let i={};for(let[a,l]of r)i[a]=l.config;return{mcpServers:i,sources:s,warnings:o}}Xd();ir();je();function aY(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}var fI=10*1024*1024;function gI(){return new Promise((e,t)=>{let n=[],r=0;if(process.stdin.readableEnded){e("");return}let o=s=>{if(r+=s.length,r>fI){process.stdin.destroy(new Error(`stdin exceeds ${fI}-byte limit`));return}n.push(s)};process.stdin.on("data",o),process.stdin.once("end",()=>{process.stdin.removeListener("data",o),e(Buffer.concat(n).toString("utf-8").replace(/\n+$/,""))}),process.stdin.once("error",s=>{process.stdin.removeListener("data",o),t(s)}),process.stdin.resume()})}function hI(e,t){return new Promise((n,r)=>{let o=e.write(t,s=>{s?r(s):o&&n()});if(!o){let s=()=>{e.removeListener("error",i),n()},i=a=>{e.removeListener("drain",s),r(a)};e.once("drain",s),e.once("error",i)}})}function wI(e){e.command("chat").description("Send a message to the agent").argument("[message]","Message to send; use `-` or omit to read from stdin").option("-m, --model <model>","Model to use. Short aliases: opus|opus_1m|sonnet|sonnet_1m|haiku. Any other value (e.g. `auto` for cursor-api-proxy, or a full `claude-*` ID) passes through to the SDK/proxy untouched.",vt()).option("-s, --stream","[no-op] reserved; use --format stream-json for headless streaming",!1).option("-f, --format <format>","Output format (text|json|stream-json)","text").option("--max-turns <number>","Maximum conversation turns","10").option("--thinking <mode>","Thinking mode: 'adaptive' | 'disabled' | 'enabled:<N>'","enabled:max").option("--effort <level>","Effort level: low|medium|high|xhigh|max").option("--max-budget-usd <usd>","Hard session cost ceiling in USD. Env: AFK_MAX_BUDGET_USD").option("--task-budget <tokens>","Soft per-task token budget. Env: AFK_TASK_BUDGET").option("--max-output-tokens <n|max>","Per-response output cap ('max' = model ceiling). Env: AFK_MAX_OUTPUT_TOKENS").option("--provider <name>","Provider to use: anthropic|anthropic-direct|openai|openai-compatible. Default: auto-selected by model").option("--dump-prompt [path]",'Dump resolved SDK prompt+options+provenance to file (default: ~/.afk/logs/prompt-dump-<ISO>.json) or "stderr"').option("-w, --worktree [branch]","Create a git worktree for an isolated one-shot. Optional value sets the branch name; otherwise auto-named. On clean exit (no uncommitted changes) the worktree and branch are auto-removed; on dirty exit the worktree is preserved. Mirrors `afk interactive -w`.").option("--worktree-base <ref>","Base git ref for the worktree created by --worktree. Default: the remote's default branch (origin/main), fetched fresh. Pass HEAD to base on your local checkout instead. Also: AFK_WORKTREE_BASE.").option("--mcp-config <path>","Path to an additional MCP config file (highest priority \u2014 merges over ~/.afk/config/mcp.json, project-local .mcp.json, and plugin-contributed configs). File format identical to mcp.json.").option("--resume <id>","Resume a persisted session by id").option("--continue","Continue the most recent persisted session in cwd").option("--session-id <uuid>","Assign a specific UUID to this session (creates new; errors if already exists)").option("--post <targets>","Headless publish of the final assistant message: github, telegram, or github,telegram").option("--post-pr <ref>","PR number, URL, or branch for --post github (defaults to the current-branch PR)").option("--dangerously-skip-permissions","Force bypass mode (already the default for new installs): skip path-approval prompts; read/write ANY path with no confirmation (permissionMode=bypassPermissions). Disable persistently with `afk config set permissionMode default`. Does not affect ask_question.").action(async(t,n)=>{if(n.resume&&n.continue){process.stderr.write(`Error: --resume and --continue are mutually exclusive
|
|
1756
1756
|
`),process.exitCode=1;return}if(n.sessionId!==void 0&&(n.resume||n.continue)){process.stderr.write(`Error: --session-id is mutually exclusive with --resume and --continue
|
|
1757
1757
|
`),process.exitCode=1;return}if(n.sessionId!==void 0&&!aY(n.sessionId)){process.stderr.write(`Error: --session-id must be a UUID (got: ${n.sessionId})
|
|
1758
1758
|
`),process.exitCode=1;return}if(n.sessionId!==void 0&&Ci(n.sessionId)!==void 0){process.stderr.write(`Error: session already exists: ${n.sessionId} \u2014 use --resume to continue it
|
|
@@ -1763,7 +1763,7 @@ ${o.join(`
|
|
|
1763
1763
|
`),process.exitCode=1;return}let i=sY("Initializing agent...").start(),a=null,l,c,u,d,p=!1,m,g=Wd(n.model),h=!1,b;try{if(n.worktree!==void 0)try{c=await du(n.worktree,n.worktreeBase!==void 0?{baseRef:n.worktreeBase}:void 0),u=c.path,i.text=`Worktree ready at ${c.path} (branch: ${c.branch})`}catch(ye){i.fail("Failed to create worktree"),J(ye)}let y,S,w,T,x,C;try{y=Vr(n.thinking)??pi(),S=Yr(n.effort)??mi(),w=fi(n.maxBudgetUsd)??ey(),T=fi(n.taskBudget)??ty(),x=gi(n.maxOutputTokens)??il(),C=void 0}catch(ye){i.fail("Invalid options"),J(ye)}if(n.dumpPrompt!==void 0){let ye=n.dumpPrompt===!0?bI.join(yI.homedir(),".afk","logs",`prompt-dump-${new Date().toISOString().replace(/[:.]/g,"-")}.json`):String(n.dumpPrompt);process.env.AFK_DUMP_PROMPT=ye,n.provider!==void 0&&n.provider!=="anthropic"&&n.provider!=="anthropic-direct"&&console.error(`[--dump-prompt] WARNING: active provider (${n.provider}) does not support prompt dumping. No file will be written.`)}let R=Re(),{prompt:k,source:$}=di(),A=At(),P=A.autoRouting?.chat??!1,F=Ld(k,P,"one-shot"),D={},N=Ai({resume:n.resume,continue:n.continue});if(n.resume&&N&&!N.stored){i.fail("Session not found"),process.stderr.write(`Error: session not found: ${JSON.stringify(n.resume)}
|
|
1764
1764
|
Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
1765
1765
|
`),process.exitCode=1;return}N&&(D=_i(N),p=!0,m=N.id),n.sessionId!==void 0&&(D={sessionId:n.sessionId},p=!0,m=n.sessionId);let B=N?.stored?.model??n.model,H=Ds(B);if(H)throw new Error(H);g.model=B,N?.stored&&(g.totalTurns=N.stored.totalTurns,g.totalCostUsd=N.stored.totalCostUsd,g.totalTokens=N.stored.totalTokens,g.totalDurationMs=N.stored.totalDurationMs,g.turns=[...N.stored.turns],g.sessionId=N.stored.sessionId??N.resumeId,g.sessionStartTime=N.stored.startedAt??Date.now()),n.sessionId!==void 0&&(g.sessionId=n.sessionId);let L,I=Qr();b=I?.tracePath;let U=new se({apiKey:R,...A.baseUrl!==void 0?{baseUrl:A.baseUrl}:{},...u!==void 0?{cwd:u}:{}}),M=ii(A.openaiBaseUrl!==void 0?{openaiBaseUrl:A.openaiBaseUrl}:{}),j={get sessionId(){return L?.sessionId},getInputStreamRef(){return L?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return L?.abortSignal??new AbortController().signal},get hookRegistry(){return L?.hookRegistry}},Y=ai(n.model,R,M,A.baseUrl,I?.writer,void 0,u,qe,"cli"),oe=new Pn({subagentManager:U,parentSession:j,surface:"cli",defaultConfig:{apiKey:R,systemPrompt:k,...A.baseUrl!==void 0?{baseUrl:A.baseUrl}:{}},defaultSubagentModel:Vt(n.model),childProviderFactory:M,childSkillExecutorFactory:Y,resolveApiKeyForModel:qe,depth:0,...u!==void 0?{cwd:u}:{}}),X=new Mn({parentSession:j,surface:"cli",defaultModel:n.model,defaultSubagentModel:Vt(n.model),apiKey:R,childProviderFactory:M,childSkillExecutorFactory:Y,...A.baseUrl!==void 0?{baseUrl:A.baseUrl}:{},resolveApiKeyForModel:qe,...I?.writer!==void 0?{traceWriter:I.writer}:{},...u!==void 0?{cwd:u}:{}}),W=new Xr({parentSession:j,defaultModel:n.model,defaultSubagentModel:Vt(n.model),apiKey:R,resolveApiKeyForModel:qe,...A.baseUrl!==void 0?{baseUrl:A.baseUrl}:{},...u!==void 0?{cwd:u}:{},systemPrompt:k??"",surface:"cli",depth:0});l=new at;{let ye=u??process.cwd(),de=rn(Pt()).mcpConfigs.filter(Oe=>Oe.format==="json").map(Oe=>Oe.source),Pe=jo({cwd:ye,...de.length>0?{importedMcpConfigs:de}:{},...n.mcpConfig!==void 0?{cliOverride:n.mcpConfig}:{}}),Ce=Object.values(Pe.mcpServers).filter(Oe=>!Oe.disabled).length;if(Ce>0){let Oe=Date.now();De(I?.writer,{phase:"mcp_connect_start",metadata:{serverCount:Ce}});try{d=await hr.fromConfig(Pe.mcpServers,{warnings:Pe.warnings,...I?.writer!==void 0?{traceWriter:I.writer}:{}})}finally{De(I?.writer,{phase:"mcp_connect_done",durationMs:Date.now()-Oe,metadata:{serverCount:Ce}})}}else if(Pe.warnings.length>0)for(let Oe of Pe.warnings)process.stderr.write(`[mcp] ${Oe}
|
|
1766
|
-
`)}let Ee=d?.getMcpToolWireNames()??[];C=hi(n.provider,{subagentExecutor:oe,skillExecutor:X,composeExecutor:W,memoryStore:l,model:String(n.model),...A.openaiBaseUrl!==void 0?{openaiBaseUrl:A.openaiBaseUrl}:{},...d!==void 0?{mcpManager:d}:{}})??new Ge({permissions:{allowedTools:[...Wt,...Qn,...pt,"agent","skill","compose",...Ee]},subagentExecutor:oe,skillExecutor:X,composeExecutor:W,memoryStore:l,surface:"cli",...d!==void 0?{mcpManager:d}:{}}),a=new
|
|
1766
|
+
`)}let Ee=d?.getMcpToolWireNames()??[];C=hi(n.provider,{subagentExecutor:oe,skillExecutor:X,composeExecutor:W,memoryStore:l,model:String(n.model),...A.openaiBaseUrl!==void 0?{openaiBaseUrl:A.openaiBaseUrl}:{},...d!==void 0?{mcpManager:d}:{}})??new Ge({permissions:{allowedTools:[...Wt,...Qn,...pt,"agent","skill","compose",...Ee]},subagentExecutor:oe,skillExecutor:X,composeExecutor:W,memoryStore:l,surface:"cli",...d!==void 0?{mcpManager:d}:{}}),a=new St(lr({model:B,surface:"cli",apiKey:qe(B),maxTurns:parseInt(n.maxTurns,10),isNonInteractive:!0,...n.dangerouslySkipPermissions?{permissionMode:"bypassPermissions"}:A.permissionMode!==void 0?{permissionMode:A.permissionMode}:{},hookRegistry:Ei(ye=>{console.log(Bd(ye))},"cli",l,void 0,ki({cwd:u}),{cwd:u,...I?.writer!==void 0?{traceWriter:I.writer}:{}}).registry,...F!==void 0?{systemPrompt:F}:{},...$!==void 0?{systemPromptSource:$}:{},...y!==void 0?{thinking:y}:{},...S!==void 0?{effort:S}:{},...w!==void 0?{maxBudgetUsd:w}:{},...T!==void 0?{taskBudget:T}:{},...x!==void 0?{maxOutputTokens:x}:{},...A.baseUrl!==void 0?{baseUrl:A.baseUrl}:{},...I?{traceWriter:I.writer}:{},...A.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:A.autoResumeOnUsageLimit}:{},...u!==void 0?{cwd:u}:{},...D,provider:C})),L=a,i.text="Sending message...";let Je=async(ye,de)=>{if(r.length===0||de)return;let Pe={line:Ce=>{process.stderr.write(`${Ce??""}
|
|
1767
1767
|
`)},raw:Ce=>{process.stderr.write(Ce)},success:Ce=>{process.stderr.write(`\u2714 ${Ce}
|
|
1768
1768
|
`)},info:Ce=>{process.stderr.write(`\u2139 ${Ce}
|
|
1769
1769
|
`)},warn:Ce=>{process.stderr.write(`\u26A0 ${Ce}
|
|
@@ -1784,7 +1784,7 @@ Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
|
1784
1784
|
`)+`
|
|
1785
1785
|
`),c=d.length}return new Promise(d=>{process.stdin.setRawMode(!0),Wo(process.stdin);let p=(g,h)=>{if(h)if(h.name==="up"||h.sequence==="\x1B[A")r>0&&(r--,r<o&&(o=r),u());else if(h.name==="down"||h.sequence==="\x1B[B"){if(r<e.length-1){r++;let{end:b}=i();r>=b&&o++,u()}}else h.name==="space"?(s.has(r)?s.delete(r):s.add(r),u()):h.name==="return"||h.name==="enter"?(m(),d([...s].sort((b,y)=>b-y))):(h.name==="escape"||h.ctrl&&h.name==="c")&&(m(),d(":cancel"))};function m(){process.stdin.removeListener("keypress",p);try{process.stdin.setRawMode(!1)}catch{}}process.stdin.on("keypress",p)})}function np(e=process.env){return e.AFK_DEMO_CLEAN==="1"||typeof e.SCRIPT=="string"&&e.SCRIPT.length>0||e.ASCIINEMA_REC==="1"}function fY(e=process.env){return e.AFK_BELL==="1"}function rp(e=process.env){return e.AFK_REDUCED_MOTION==="1"}function kI(e=process.env){return e.AFK_CARET_BLINK!=="0"}function op(e,t=process.env){fY(t)&&e.isTTY&&e.write("\x07")}var Jy=64,ip=256,sp=20,Vy=new Set(["__proto__","constructor","prototype"]),$i={action:"decline"},te={action:"cancel"},gY={action:"accept"};function hY(e){let t=e.properties,n={},r=0,o=!1;if(typeof t=="object"&&t!==null){let a=0;for(let[l,c]of Object.entries(t))if(!Vy.has(l)){if(r+=1,a>=Jy){o=!0;continue}n[l]=c,a+=1}}let s=e.required,i=new Set(Array.isArray(s)?s.slice(0,Jy*2).filter(a=>typeof a=="string").filter(a=>!Vy.has(a)):[]);return{properties:n,required:i,fieldsTruncated:o,originalFieldCount:r}}function yY(e,t){e.line(),e.line(f.warning("\u26A0 MCP form elicitation")),e.line(f.dim(" server: ")+f.bold(ue(t.serverName,64))),e.line(f.dim(" message: ")+ue(t.message,256)),t.elicitationId&&e.line(f.dim(" id: ")+ue(t.elicitationId,64)),e.line(f.dim(" Type :decline or :cancel at any prompt to exit.")),e.line()}var EI="\u2014 skip (optional) \u2014";async function bY(e,t,n,r,o,s,i){let a,l;if(e.enum!==void 0){let m=e.enum.slice(0,ip);a=m.map(g=>ue(String(g),64)),l=g=>{let h=a.indexOf(g);return h>=0?m[h]:g}}else a=["Yes","No"],l=m=>m==="Yes";let c=t?a:[...a,EI],u=[f.bold(" ? "+n),""],d;try{d=await o({header:u,options:c,multi:!1,signal:i})}catch{return{tag:"cancel"}}if(i.aborted)return{tag:"cancel"};if(d===null)return{tag:"cancel"};let p=d[0];return p===void 0?{tag:"cancel"}:!t&&p===EI?{tag:"value",value:e.default}:(s.line(f.dim(" \u2713 ")+f.brand(`${r}: ${ue(p,128)}`)),{tag:"value",value:l(p)})}async function wY(e,t,n,r,o,s,i){if(s.aborted)return{tag:"cancel"};let a=ue(t.description??t.title??e),l=ue(t.type??"string",32),c=ue(e,64);if(i&&(t.enum!==void 0||l==="boolean"))return bY(t,n,a,c,i,o,s);let u;if(t.enum!==void 0){let p=t.enum.slice(0,sp).map(g=>ue(String(g),32)).join("|"),m=t.enum.length>sp?"|\u2026":"";u=` (enum: ${p}${m})`}else l==="boolean"?u=" (boolean: y/n)":l==="number"||l==="integer"?u=` (${l})`:l==="string"?u=" (string)":(u=` (${l} \u2014 treated as string)`,o.line(f.warning(` \u26A0 Unknown field type '${l}' for '${c}' \u2014 collecting as string.`)));let d=n?"":f.dim(" [optional, enter to skip]");for(o.line(f.dim(` [${c}]`)+f.dim(` ${a}`)+f.dim(u)+d),t.enum!==void 0&&t.enum.length>ip&&o.line(f.warning(` \u26A0 Field '${c}' has ${t.enum.length} enum values; only the first ${ip} are valid for input.`));;){let p;try{p=await r(f.dim(" > "))}catch{return{tag:"cancel"}}if(s.aborted)return{tag:"cancel"};let m=p.trim();if(m===":cancel")return{tag:"cancel"};if(m===":decline")return{tag:"decline"};if(m===""){if(n){o.line(f.warning(" (required \u2014 cannot be skipped)"));continue}return{tag:"value",value:t.default}}let g;if(l==="boolean"){let h=m.toLowerCase();if(h==="y"||h==="yes"||h==="true"||h==="1")g=!0;else if(h==="n"||h==="no"||h==="false"||h==="0")g=!1;else{o.line(f.warning(" Invalid boolean \u2014 enter y/yes/true/1 or n/no/false/0."));continue}}else if(l==="number"){let h=Number(m);if(!isFinite(h)){o.line(f.warning(" Invalid number \u2014 enter a numeric value."));continue}g=h}else if(l==="integer"){let h=parseInt(m,10);if(!isFinite(h)||String(h)!==m.replace(/\.0+$/,"")){o.line(f.warning(" Invalid integer \u2014 enter a whole number."));continue}g=h}else g=m;if(t.enum!==void 0){let h=t.enum.slice(0,ip),b=!1;for(let y of h)if(String(y)===String(g)){b=!0;break}if(!b){let y=ue(String(g),64),S=h.slice(0,sp).map(T=>ue(String(T),32)).join(", "),w=h.length>sp?", \u2026":"";o.line(f.warning(` '${y}' is not a valid choice. Valid: ${S}${w}`));continue}}return{tag:"value",value:g}}}function SY(e,t){e.line(),e.line(f.warning("\u26A0 MCP elicitation")),e.line(f.dim(" server: ")+f.bold(ue(t.serverName,64))),e.line(f.dim(" message: ")+ue(t.message,256)),t.url&&e.line(f.dim(" url: ")+f.brand(ue(t.url,512))),t.elicitationId&&e.line(f.dim(" id: ")+ue(t.elicitationId,64)),e.line()}var Go={action:"skip"};function ap(e){let t=[];return t.push(f.warning(" \u{1F4AC} Agent question")),t.push(f.bold(" ? "+ue(e.message,512))),e.context&&t.push(f.dim(" "+ue(e.context,512))),t.push(""),t}async function vY(e,t,n,r){let o=ap(t),s=t.allowSkip===!0;if(e==="number"){let u=t.min,d=t.max,m=`enter to submit \xB7 esc to cancel${u!==void 0&&d!==void 0?` [${u}\u2013${d}]`:u!==void 0?` [\u2265${u}]`:d!==void 0?` [\u2264${d}]`:""}`,h=await n({header:o,help:m,validate:y=>{let S=y.trim();if(S==="")return s?null:"Please enter a number (or esc to cancel).";let w=Number(S);return Number.isFinite(w)?u!==void 0&&w<u?`Value must be \u2265 ${u}.`:d!==void 0&&w>d?`Value must be \u2264 ${d}.`:null:"Please enter a valid number."},signal:r});if(h===null)return null;let b=h.trim();return b===""&&s?{tag:"skip"}:{tag:"number",value:Number(b)}}let i=t.minLength,a=t.maxLength,c=await n({header:o,validate:u=>u===""?s?null:"Please enter a response (or esc to cancel).":i!==void 0&&u.length<i?`Response must be at least ${i} characters.`:a!==void 0&&u.length>a?`Response must be at most ${a} characters.`:null,signal:r});return c===null?null:c===""&&s?{tag:"skip"}:{tag:"text",value:c}}async function kY(e,t,n){if(n.aborted)return $i;let{readLine:r,writer:o,pendingCount:s,pickFromList:i,readTextOverlay:a}=t,l=e.type??"text",c=s();if(c>1&&o.line(f.dim(` [${c} questions queued]`)),(l==="choice"||l==="multi_choice")&&i&&(e.choices?.length??0)>0){let p=(e.choices??[]).map(h=>ue(h,128));e.allowCustom&&p.push(Ko);let m;try{m=await i({header:ap(e),options:p,multi:l==="multi_choice",signal:n})}catch{return te}if(n.aborted||m===null)return te;if(e.allowCustom&&m.includes(Ko)){if(!a)return te;let h=await a({header:ap(e),help:"Type your custom answer (Esc to cancel)",validate:b=>b.trim()===""?"Please enter a non-empty answer":null,signal:n});return h===null?te:(o.line(f.dim(" \u270E ")+f.brand(ue(h,256))),{action:"accept",content:{value:null,custom_value:h}})}if(m.length===0)return e.allowSkip?Go:te;let g=m.length===1?ue(m[0]??"",128):m.map(h=>ue(h,128)).join(", ");return o.line(f.dim(" \u2713 ")+f.brand(g)),l==="choice"?{action:"accept",content:{value:m[0]}}:{action:"accept",content:{value:[...m]}}}if(l==="confirm"&&i){let m=e.questionDefault!==!1?["Yes","No"]:["No","Yes"],g;try{g=await i({header:ap(e),options:m,multi:!1,signal:n})}catch{return te}if(n.aborted||g===null)return te;let h=g[0];if(h===void 0)return te;let b=h==="Yes";return o.line(f.dim(" \u2713 ")+(b?f.success("Yes"):f.error("No"))),{action:"accept",content:{value:b}}}if((l==="text"||l==="number")&&a){let p=await vY(l,e,a,n);if(p===null)return te;if(p.tag==="skip")return Go;let m=p.tag==="text"?ue(p.value,256):String(p.value);return o.line(f.dim(" \u2713 ")+f.brand(m)),{action:"accept",content:{value:(p.tag==="text",p.value)}}}if(o.line(),o.line(f.warning("\u{1F4AC} Agent question")),e.context&&o.line(f.dim(" context: ")+ue(e.context,512)),o.line(f.bold(" "+ue(e.message,512))),o.line(f.dim(" Type :cancel to skip this question.")),o.line(),l==="confirm"){o.line("\x07");let p=e.questionDefault===!0?"Y/n":"y/N";for(;;){if(n.aborted)return te;let m;try{m=(await r(f.dim(` Continue? [${p}] `))).trim().toLowerCase()}catch{return te}if(n.aborted||m===":cancel")return te;if(m==="")return{action:"accept",content:{value:e.questionDefault===!0}};if(m==="y"||m==="yes")return{action:"accept",content:{value:!0}};if(m==="n"||m==="no")return{action:"accept",content:{value:!1}};o.line(f.warning(" Please enter y or n."))}}if(l==="choice"){o.line("\x07");let p=e.choices??[],m=e.allowCustom?[...p,Ko]:p,g=await SI(m,n);if(g!==null){if(g===":cancel")return te;if(e.allowCustom&&g===p.length){let b;try{b=(await r(f.dim(" Type your answer: "))).trim()}catch{return te}return b===":cancel"||n.aborted?te:{action:"accept",content:{value:null,custom_value:b}}}let h=p[g];return h!==void 0?(o.line(f.dim(` Selected: ${ue(h,128)}`)),{action:"accept",content:{value:h}}):te}for(p.forEach((h,b)=>{o.line(` ${b+1}. ${ue(h,128)}`)}),e.allowCustom&&o.line(` ${p.length+1}. ${Ko}`);;){if(n.aborted)return te;let h;try{h=(await r(f.dim(" Enter number: "))).trim()}catch{return te}if(n.aborted||h===":cancel")return te;if(e.allowCustom&&h===String(p.length+1)){let y;try{y=(await r(f.dim(" Type your answer: "))).trim()}catch{return te}return y===":cancel"?te:{action:"accept",content:{value:null,custom_value:y}}}if(h===""&&e.allowSkip)return Go;let b=parseInt(h,10);if(!isFinite(b)||String(b)!==h||b<1||b>p.length){o.line(f.warning(` Please enter a number between 1 and ${p.length+(e.allowCustom?1:0)}.`));continue}return{action:"accept",content:{value:p[b-1]}}}}if(l==="multi_choice"){let p=e.choices??[],m=e.allowCustom?[...p,Ko]:p,g=await vI(m,n);if(g!==null){if(g===":cancel")return te;if(e.allowCustom&&g.includes(p.length)){let h;try{h=(await r(f.dim(" Type your answer: "))).trim()}catch{return te}return h===":cancel"||n.aborted?te:{action:"accept",content:{value:null,custom_value:h}}}if(g.length===0&&e.allowSkip)return Go;if(g.length>0){let h=g.map(b=>p[b]);return o.line(f.dim(` Selected: ${h.map(b=>ue(b,64)).join(", ")}`)),{action:"accept",content:{value:h}}}}for(p.forEach((h,b)=>{o.line(` ${b+1}. ${ue(h,128)}`)}),e.allowCustom&&o.line(` ${p.length+1}. ${Ko}`);;){if(n.aborted)return te;let h;try{h=(await r(f.dim(" Enter numbers (comma-separated): "))).trim()}catch{return te}if(n.aborted||h===":cancel")return te;if(e.allowCustom&&h===String(p.length+1)){let w;try{w=(await r(f.dim(" Type your answer: "))).trim()}catch{return te}return w===":cancel"?te:{action:"accept",content:{value:null,custom_value:w}}}if(h===""&&e.allowSkip)return Go;if(h===""){o.line(f.warning(" Please enter at least one selection."));continue}let b=h.split(",").map(w=>w.trim()),y=[],S=!0;for(let w of b){let T=parseInt(w,10);if(!isFinite(T)||String(T)!==w||T<1||T>p.length){o.line(f.warning(` Invalid selection "${ue(w,32)}". Enter numbers between 1 and ${p.length}.`)),S=!1;break}y.push(p[T-1])}if(S)return{action:"accept",content:{value:y}}}}if(l==="number"){let p=e.min,m=e.max,g=p!==void 0&&m!==void 0?` [${p}\u2013${m}]`:p!==void 0?` [\u2265${p}]`:m!==void 0?` [\u2264${m}]`:"";for(;;){if(n.aborted)return te;let h;try{h=(await r(f.dim(` Enter a number${g}: `))).trim()}catch{return te}if(n.aborted||h===":cancel")return te;if(h===""&&e.allowSkip)return Go;if(h===""&&!e.allowSkip){o.line(f.warning(" Please enter a number (or :cancel to skip)."));continue}let b=Number(h);if(!isFinite(b)){o.line(f.warning(" Please enter a valid number."));continue}if(p!==void 0&&b<p){o.line(f.warning(` Value must be \u2265 ${p}.`));continue}if(m!==void 0&&b>m){o.line(f.warning(` Value must be \u2264 ${m}.`));continue}return{action:"accept",content:{value:b}}}}let u=e.minLength,d=e.maxLength;for(;;){if(n.aborted)return te;let p;try{p=(await r(f.dim(" > "))).trim()}catch{return te}if(n.aborted||p===":cancel")return te;if(p===""&&e.allowSkip)return Go;if(p===""){o.line(f.warning(" Please enter a response (or type :cancel to skip)."));continue}if(u!==void 0&&p.length<u){o.line(f.warning(` Response must be at least ${u} characters.`));continue}if(d!==void 0&&p.length>d){o.line(f.warning(` Response must be at most ${d} characters.`));continue}return{action:"accept",content:{value:p}}}}function lp(e){return async(t,{signal:n})=>{if(n.aborted)return $i;op(process.stdout),e.suspendInput?.();try{if(t.origin==="agent")return await kY(t,e,n);if(t.mode==="form"){let o=t.requestedSchema,{properties:s,required:i,fieldsTruncated:a,originalFieldCount:l}=typeof o=="object"&&o!==null?hY(o):{properties:{},required:new Set,fieldsTruncated:!1,originalFieldCount:0};yY(e.writer,t),a&&e.writer.line(f.warning(` \u26A0 Schema has ${l} fields; only the first ${Jy} will be prompted (server may be malformed or compromised).`));let c=Object.create(null);if(Object.keys(s).length===0)return e.writer.line(f.warning(" \u26A0 Form schema has no usable fields \u2014 declining.")),$i;for(let u of i)if(!(u in s))return e.writer.line(f.warning(` \u26A0 Required field '${ue(u,64)}' has no schema entry \u2014 declining.`)),$i;for(let[u,d]of Object.entries(s)){if(n.aborted)return te;let p=await wY(u,d,i.has(u),e.readLine,e.writer,n,e.pickFromList);if(p.tag==="cancel")return te;if(p.tag==="decline")return $i;p.value!==void 0&&!Vy.has(u)&&(c[u]=p.value)}return{action:"accept",content:{...c}}}SY(e.writer,t);let r=(await e.readLine(f.dim("Continue? [y/N] "))).trim().toLowerCase();return r===""?te:r==="y"||r==="yes"?gY:$i}finally{e.resumeInput?.()}}}li();en();an();ze();Mt();function TI(e){let t=Math.max(0,Math.min(1,e.ratio)),n=t>.8?f.error:t>.5?f.warning:f.meta,r=20,o=Math.round(t*r),s=r-o,i="["+"\u2588".repeat(o)+"\u2591".repeat(s)+"]",a=Math.round(t*100)+"%",l="";e.used!==void 0&&e.limit!==void 0&&(l=ie(e.used)+"/"+ie(e.limit));let c=l?`${i} ${a} ${l}`:`${i} ${a}`,u=`${i} ${a}`,d=`ctx ${a}`,p=e.sparkline?f.meta(e.sparkline)+" ":"",m=e.sparkline?V(e.sparkline)+1:0,g=Math.max(0,e.width-m);if(V(c)<=g&&g>90)return p+n(c);if(V(u)<=g&&g>32)return p+n(u);if(V(d)<=g)return p+n(d);if(e.width>0){let h=p+n(d);return ne(h,e.width)}return n(a)}var cp=class{stream;force;throttleMs;started=!1;lastRepaint=0;lastFields=null;resizeUnsub=null;resizeImmediateUnsub=null;lastPaintedRow=null;preResizePaintedRow=null;extraRows=0;afterScrollRestore=null;constructor(t={}){this.stream=t.stream??process.stdout,this.force=t.force??!1,this.throttleMs=t.throttleMs??100}get enabled(){return this.force||!!this.stream.isTTY}start(){if(this.started||!this.enabled)return;this.started=!0,this.lastRepaint=0;let t=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.resizeUnsub===null&&(this.resizeUnsub=Ue.subscribe(()=>{this.onResize()}),this.resizeImmediateUnsub=Ue.subscribeImmediate(()=>this.resetGeometry()))}resetGeometry(){this.preResizePaintedRow=this.lastPaintedRow,this.lastPaintedRow=null,this.lastRepaint=0}onResize(){if(!this.started||!this.enabled)return;let t=this.currentRows(),n=this.preResizePaintedRow??this.lastPaintedRow;this.preResizePaintedRow=null,this.stream.write("\x1B[s"),n!==null&&n!==this.paintRow(t)&&(this.stream.write(`\x1B[${n};1H`),this.stream.write("\x1B[2K")),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.flush()}repaint(t){if(!this.enabled||!this.started){this.lastFields=t;return}let n=Date.now();if(n-this.lastRepaint<this.throttleMs){this.lastFields=t;return}this.lastRepaint=n,this.lastFields=t;let r=this.currentRows();this.stream.write("\x1B[s"),this.stream.write(`\x1B[${this.paintRow(r)};1H`),this.stream.write("\x1B[2K"),this.stream.write(this.formatLine(t)),this.stream.write("\x1B[u"),this.lastPaintedRow=this.paintRow(r)}flush(){this.lastRepaint=0,this.lastFields&&this.repaint(this.lastFields)}setExtraRows(t){if(this.extraRows=t,this.started&&this.enabled){let n=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(n),this.stream.write("\x1B[u"),this.flush()}}getExtraRows(){return this.extraRows}setAfterScrollRestore(t){this.afterScrollRestore=t}rearm(){if(!this.started||!this.enabled)return;let t=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.flush()}withFullScrollRegion(t){if(!this.started||!this.enabled)return t();this.stream.write("\x1B[s"),this.stream.write("\x1B[r"),this.stream.write("\x1B[u");try{return t()}finally{let n=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(n),this.stream.write("\x1B[u"),this.flush(),this.afterScrollRestore?.()}}stop(){if(this.resizeUnsub!==null&&(this.resizeUnsub(),this.resizeUnsub=null),this.resizeImmediateUnsub!==null&&(this.resizeImmediateUnsub(),this.resizeImmediateUnsub=null),!this.started||!this.enabled){this.started=!1;return}let t=this.currentRows();this.stream.write("\x1B[s");let n=this.preResizePaintedRow??this.lastPaintedRow??this.paintRow(t);this.stream.write(`\x1B[${n};1H`),this.stream.write("\x1B[2K"),this.stream.write("\x1B[r"),this.stream.write("\x1B[u"),this.started=!1,this.lastRepaint=0,this.lastPaintedRow=null,this.preResizePaintedRow=null}formatLine(t){let n=[],r=Math.max(4,(this.stream.columns??80)-2);if(t.cwd){let a=Math.max(8,Math.floor(r*.4)),l=wl(t.cwd,{maxWidth:a});l&&n.push({text:f.dim(l)})}if(t.branch){let a=ne(t.branch,30),l=`${f.dim("\u2387")} ${f.fileRef(a)}`;t.pr!==void 0&&(l+=` ${f.meta(`#${t.pr}`)}`),n.push({text:l,droppablePriority:1})}if(n.push({text:f.brand(t.model)}),t.permissionMode==="plan"?n.push({text:f.warning("\u25CF plan")}):t.permissionMode==="autonomous"?n.push({text:f.info("\u25D0 AFK")}):t.permissionMode==="bypassPermissions"?n.push({text:f.bypass("\u26A1 bypass")}):t.permissionMode==="default"&&n.push({text:f.success("\u25CB default")}),t.contextPct!==void 0){let a=TI({ratio:t.contextPct,used:t.contextUsedTokens,limit:t.contextLimit,sparkline:t.contextSparkline,width:r});n.push({text:a,droppablePriority:2})}t.cost!==void 0&&n.push({text:f.meta(`$${t.cost.toFixed(2)}`),droppablePriority:3}),t.tokens!==void 0&&n.push({text:f.meta(`${EY(t.tokens)} tok`),droppablePriority:4});let o=f.dim(" \xB7 "),s=n.map(a=>a.text).join(o);if(V(s)<=r)return s;let i=n.filter(a=>a.droppablePriority!==void 0);for(;i.length>0&&V(s)>r;){let a=Math.max(...i.map(l=>l.droppablePriority));n=n.filter(l=>l.droppablePriority===void 0||l.droppablePriority!==a),s=n.map(l=>l.text).join(o),i=n.filter(l=>l.droppablePriority!==void 0)}return ne(s,r)}currentRows(){let t=this.stream.rows;return typeof t=="number"&&t>0?t:24}paintRow(t){return t>1?t:1}writeScrollRegion(t){let n=1+this.extraRows;if(t>n){this.stream.write(`\x1B[1;${t-n}r`);return}this.stream.write("\x1B[r")}};function EY(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}import{execFile as TY}from"node:child_process";import{promisify as xY}from"node:util";var RY=xY(TY);function CY(e){return(t,n,r)=>RY(t,n,{cwd:r,timeout:e,killSignal:"SIGTERM",maxBuffer:64*1024}).then(o=>({stdout:o.stdout,stderr:o.stderr}))}var up=class{cwd;exec;prTtlMs;branchTtlMs;now;onUpdate;branch;pr;prBranch;prFetchedAt=0;branchFetchedAt=0;branchInFlight=null;prInFlight=null;disposed=!1;resetToken=0;constructor(t){this.cwd=t.cwd,this.exec=t.exec??CY(t.timeoutMs??1e4),this.prTtlMs=t.prTtlMs??6e4,this.branchTtlMs=t.branchTtlMs??0,this.now=t.now??Date.now,this.onUpdate=t.onUpdate}setOnUpdate(t){this.onUpdate=t}getBranch(){return this.branch}getPr(){return this.pr}async refresh(t={}){this.disposed||(this.branchInFlight||(this.branchInFlight=this.updateBranch().finally(()=>{this.branchInFlight=null})),await this.branchInFlight,t.blockOnPr&&this.prInFlight&&await this.prInFlight)}reset(){this.resetToken++,this.branch=void 0,this.pr=void 0,this.prBranch=void 0,this.prFetchedAt=0,this.branchFetchedAt=0,this.branchInFlight=null,this.prInFlight=null}dispose(){this.disposed=!0}async updateBranch(){if(this.branchTtlMs>0&&this.branchFetchedAt>0&&this.now()-this.branchFetchedAt<this.branchTtlMs)return;let t=this.resetToken;this.branchFetchedAt=this.now();let n=await this.gitBranch();if(this.disposed||this.resetToken!==t)return;let r=n!==this.branch;if(this.branch=n,n===void 0){let o=this.pr!==void 0;this.pr=void 0,this.prBranch=void 0,(r||o)&&this.notify();return}r&&(this.pr=void 0,this.notify()),this.maybeFetchPr(n)}notify(){try{this.onUpdate?.()}catch{}}async gitBranch(){try{let{stdout:t}=await this.exec("git",["symbolic-ref","--short","HEAD"],this.cwd),n=t.trim();return n.length>0?n:void 0}catch{return}}maybeFetchPr(t){if(this.prInFlight)return this.prInFlight;if(!(this.prBranch!==t||this.now()-this.prFetchedAt>=this.prTtlMs))return Promise.resolve();this.prFetchedAt=this.now();let r=(async()=>{let o=this.resetToken,s=await Gd((l,c)=>this.exec(l,c,this.cwd));if(this.disposed||this.resetToken!==o||this.branch!==t)return;let i=s!==null?Number.parseInt(s,10):NaN,a=this.pr;this.pr=Number.isFinite(i)&&i>0?i:void 0,this.prBranch=t,this.pr!==a&&this.notify()})().finally(()=>{this.prInFlight=null;let o=this.branch;!this.disposed&&o!==void 0&&o!==t&&this.maybeFetchPr(o)});return this.prInFlight=r,r}};var Lt=new Map,qo=new Map;function fe(e){if(Lt.has(e.name))throw new Error(`Slash command already registered: ${e.name}`);Lt.set(e.name,e);for(let t of e.aliases??[]){if(qo.has(t)||Lt.has(t))throw new Error(`Slash alias collides: ${t}`);qo.set(t,e.name)}}function eo(e){if(Lt.has(e.name)){for(let[t,n]of qo.entries())n===e.name&&qo.delete(t);Lt.delete(e.name)}fe(e)}function xI(e){Lt.has(e.name)||fe(e)}function RI(){Lt.clear(),qo.clear()}function ot(){return[...Lt.values()].sort((e,t)=>e.name.localeCompare(t.name))}function Di(){let e=[];for(let[t,n]of qo.entries()){let r=Lt.get(n);r&&e.push({alias:t,canonical:n,summary:r.summary})}return e.sort((t,n)=>t.alias.localeCompare(n.alias))}function AY(e){if(Lt.has(e))return Lt.get(e);let t=qo.get(e);return t?Lt.get(t):void 0}function _Y(e,t){let n=Array.from({length:e.length+1},()=>new Array(t.length+1).fill(0));for(let r=0;r<=e.length;r++)n[r][0]=r;for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=e.length;r++)for(let o=1;o<=t.length;o++){let s=e[r-1]===t[o-1]?0:1;n[r][o]=Math.min(n[r-1][o]+1,n[r][o-1]+1,n[r-1][o-1]+s)}return n[e.length][t.length]}function IY(e,t=3){let n;for(let r of Lt.keys()){let o=_Y(e,r);o<=t&&(n===void 0||o<n.dist)&&(n={name:r,dist:o})}return n?.name}function Yy(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.indexOf(" ");return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}async function CI(e,t,n){let r=Yy(e);if(r===null)return{handled:!1};let o=AY(r.name);if(!o){let a=IY(r.name);return a?t.out.warn(`Unknown command: ${r.name} (did you mean ${a}?)`):t.out.warn(`Unknown command: ${r.name} (type /help for commands)`),{handled:!0,result:"continue"}}let s=n??[];s.length>0&&o.acceptsAttachments!==!0&&t.out.warn(`\u26A0 Image attachments are ignored by ${r.name} (images only reach the model on skill commands like /forge, /mint).`);let i=await o.handler(t,r.args,o.acceptsAttachments===!0?s:void 0);return i==="forward"?{handled:!1}:{handled:!0,result:i}}import $Y from"ora";Ga();function AI(e,t=5){if(e.length===0)return"";let n=e.slice(-t),r=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"];return n.map(o=>{let s=Math.max(0,Math.min(1,o)),i=Math.min(7,Math.floor(s*8));return r[i]}).join("")}function dp(e,t,n){e.totalTurns=t.totalTurns,e.totalCostUsd=t.totalCostUsd,e.totalTokens=t.totalTokens,e.totalDurationMs=t.totalDurationMs,e.turns=[...t.turns],e.sessionId=t.sessionId??n,e.name=t.name,e.model=t.model,e.sessionStartTime=t.startedAt??Date.now()}function pp(e,t){let n=e.turns;if(n.length===0)return;let r=n[n.length-1];if(!r)return;let o=II(_I(r.user),80),s=II(OY(_I(r.assistant)),120);o.length>0&&t.fn(f.dim(` Last: ${o}`)),s.length>0&&t.fn(f.dim(` \u21B3 ${s}`)),t.fn(f.dim(" \u21AA /history for full review"))}function _I(e){return e.replace(MY,"").replace(/\s+/g," ").trim()}var MY=/\u001B\][\s\S]*?(?:\u0007|\u001B\\|\u009C)|\u001B[PX^_][\s\S]*?(?:\u0007|\u001B\\|\u009C)|\u001B[@-OQ-WY-Z\\`6-9=]|[\u001B\u009B][[\]()#;?]*(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]/g;function OY(e){let t=e.match(/^.*?(?<![A-Za-z]\.[A-Za-z])[.!?](?=\s|$)/);return t?t[0]:e}function II(e,t){let n=[...e];return n.length<=t?e:n.slice(0,t-1).join("")+"\u2026"}var Sl={stream:process.stdout,hideCursor:!1,discardStdin:!1};function Xy(e,t){if(t?.getRatio()!==void 0)return t.getRatio();let n=e.turnTokens[e.turnTokens.length-1];return n?(n.footprint??n.input+n.output+n.cache)/Ot(e.model):0}function Fn(e,t,n){let r=Xy(e,t),o=Ot(e.model),s,i=t?.getDetail();if(i!==void 0)s=i.used;else{let u=e.turnTokens[e.turnTokens.length-1];u&&(s=u.footprint??u.input+u.output+u.cache)}let a;if(e.turnTokens.length>=2){let u=e.turnTokens.map(p=>(p.footprint??p.input+p.output+p.cache)/o),d=AI(u,5);d.length>0&&(a=d)}let l=n?.getBranch(),c=n?.getPr();return{model:e.model,cost:e.totalCostUsd,tokens:e.totalTokens,contextPct:r,contextLimit:o,contextUsedTokens:s,contextSparkline:a,permissionMode:e.permissionMode,...e.cwd!==void 0?{cwd:e.cwd}:{},...l!==void 0?{branch:l}:{},...c!==void 0?{pr:c}:{}}}Rt();var DY={name:"/exit",aliases:["/quit"],summary:"Exit the session",hint:"When you want to tear down the REPL \u2014 Ctrl+D on an empty prompt does the same.",async handler(){return"exit"}},LY={name:"/clear",summary:"Clear conversation history",hint:"When the current thread has drifted off-topic or you want a clean slate without restarting the session.",async handler(e){try{await e.session.current.reset(),e.ui.clearScreen(),U_(e.stats),e.ledger?.clear(),e.out.success("Conversation history cleared.")}catch(t){e.out.error(t instanceof Error?t.message:"Unknown error")}return"continue"}},FY={name:"/compact",summary:"Compact history (summarize older messages)",hint:"When context is filling up but you want to keep the thread \u2014 summarizes old turns and keeps the recent ones intact.",async handler(e){let t=$Y({text:f.meta("Summarizing earlier turns..."),...Sl}).start();try{let n=e.session.current,r=n.hookRegistry;r&&await r.dispatch({event:"PreCompact",sessionId:n.sessionId,trigger:"manual"});let o=await n.compact();if(t.stop(),o.compacted){let s=o.tokensSavedEstimate?` (~${o.tokensSavedEstimate} input tokens saved)`:"";e.out.success(`Compacted ${o.messagesBefore} \u2192 ${o.messagesAfter} messages${s}.`)}else{let s=o.reason??"unknown";s==="aborted"?e.out.info("Compaction cancelled."):s.startsWith("summarization-failed")?e.out.error(`Compaction failed: ${s}. History unchanged.`):s==="nothing-to-summarize"?e.out.info("Nothing to compact \u2014 all history is within the keep window."):s==="not-supported"?e.out.warn("Compaction is not supported for this model or provider \u2014 use a Claude model to enable /compact."):e.out.info(`Nothing to compact (${s}).`)}}catch(n){if(t.stop(),n instanceof it)throw n;if(n instanceof be)return e.out.info(`Compaction skipped: ${n.reason??"blocked by hook"}`),"continue";e.out.error(n instanceof Error?n.message:"Unknown error")}return"continue"}},NY={name:"/help",summary:"Show this help",hint:"When you want the full command list with usage strings \u2014 broader than this inline dropdown.",async handler(e){let t=ot(),n=t.reduce((r,o)=>Math.max(r,o.name.length),0)+2;e.out.line(),e.out.line(f.bold(f.brand("Commands"))),e.out.line(pe());for(let r of t){let o=r.usage??r.name,s=" ".repeat(Math.max(0,n-o.length));e.out.line(` ${f.warning(o)}${s} ${f.dim(r.summary)}`)}return e.out.line(),e.out.line(f.dim(" Tip: Ctrl+C interrupts a running turn; a second press exits.")),e.out.line(f.dim(" Hidden: /keys for keybindings \xB7 @ to attach files \xB7 !cmd to run shell \xB7 Shift+Tab to change mode")),e.out.line(),"continue"}},PI=[DY,LY,FY,NY];function Zy(e,t=30){return!e||e.length===0?f.dim("(none)"):e.length<=t?e.join(", "):`${e.slice(0,t).join(", ")}, ${f.dim(`+${e.length-t} more`)}`}function Yt(e,t){return` ${f.label(e.padEnd(16))} ${t}`}function mp(e){let t=[];t.push(" "+pe("Session Debug")),e.sessionId&&t.push(Yt("session",e.sessionId)),e.model&&t.push(Yt("model",e.model)),e.permissionMode&&t.push(Yt("permission",e.permissionMode)),e.cwd&&t.push(Yt("cwd",e.cwd)),e.claudeCodeVersion&&t.push(Yt("sdk",`v${e.claudeCodeVersion}`)),e.apiKeySource&&t.push(Yt("api key",e.apiKeySource)),e.outputStyle&&t.push(Yt("output style",e.outputStyle));let n=e.tools?.length??0;t.push(Yt(`tools (${n})`,Zy(e.tools)));let r=e.mcpServers??[],o=r.length?r.map(c=>`${c.name}[${c.status}]`).join(", "):f.dim("(none)");t.push(Yt(`mcp (${r.length})`,o));let s=e.skills?.length??0;t.push(Yt(`skills (${s})`,Zy(e.skills)));let i=e.plugins?.length??0,a=i?(e.plugins??[]).map(c=>c.name).join(", "):f.dim("(none)");t.push(Yt(`plugins (${i})`,a));let l=e.slashCommands?.length??0;return t.push(Yt(`slash (${l})`,Zy(e.slashCommands))),t.push(" "+pe()),t.join(`
|
|
1786
1786
|
`)}tt();en();var Qy=["local","small","medium","large","opus","opus_1m","sonnet","sonnet_1m","haiku","fable"],BY={name:"/cost",summary:"Show total and per-turn cost",hint:"When you want a dollar breakdown of this session \u2014 total, average per turn, and the recent turn-by-turn series.",async handler(e){let{stats:t,out:n}=e;if(n.line(),n.line(f.bold("Session cost")),n.line(pe()),n.line(` total ${f.success(rt(t.totalCostUsd))}`),n.line(` turns ${f.meta(String(t.totalTurns))}`),t.totalTurns>0){let r=t.totalCostUsd/t.totalTurns;n.line(` avg/turn ${f.meta(rt(r))}`)}if(t.turnCosts.length>0){let r=t.turnCosts.slice(-5).map(rt).join(f.dim(" \xB7 "));n.line(` last 5 ${r}`)}return n.line(),"continue"}};function UY(e,t){let n=t.apiUsage,r=n?.input_tokens??0,o=n?.output_tokens??0,s=n?.cache_read_input_tokens??0,i=n?.cache_creation_input_tokens??0,a=r+o+s+i;e.line(),e.line(f.bold("Token usage")+f.dim(" (SDK breakdown)")),e.line(pe()),e.line(` total ${f.success(ie(t.totalTokens))} of ${f.meta(ie(t.maxTokens))} (${f.meta(`${Math.round(t.percentage*100)/100}%`)})`),t.autoCompactThreshold&&t.isAutoCompactEnabled&&e.line(` compact at ${f.meta(ie(t.autoCompactThreshold))}`),e.line(),e.line(f.dim(" Last turn (API):")),e.line(` input ${f.meta(ie(r))}`),e.line(` output ${f.meta(ie(o))}`),e.line(` cache read ${f.meta(ie(s))}`),e.line(` cache creat ${f.meta(ie(i))}`),e.line(` total ${f.meta(ie(a))}`);let l=t.categories??[];if(l.length>0){let p=[...l].sort((m,g)=>g.tokens-m.tokens).slice(0,5);e.line(),e.line(f.dim(" Top categories:"));for(let m of p)e.line(` ${f.warning(m.name.padEnd(18))} ${f.meta(ie(m.tokens))}`)}let c=t.systemTools??[],u=t.mcpTools??[];if(c.length>0||u.length>0){e.line();let p=c.reduce((g,h)=>g+h.tokens,0),m=u.reduce((g,h)=>g+h.tokens,0);c.length>0&&e.line(f.dim(` system tools ${c.length} tools, ${ie(p)} tokens`)),u.length>0&&e.line(f.dim(` MCP tools ${u.length} tools, ${ie(m)} tokens`))}let d=t.agents??[];if(d.length>0){let p=d.reduce((m,g)=>m+g.tokens,0);e.line(f.dim(` agents ${d.length} loaded, ${ie(p)} tokens`))}if(t.skills){let p=t.skills;e.line(f.dim(` skills ${p.includedSkills}/${p.totalSkills} included, ${ie(p.tokens)} tokens`))}if(t.slashCommands){let p=t.slashCommands;e.line(f.dim(` slash cmds ${p.includedCommands}/${p.totalCommands} included, ${ie(p.tokens)} tokens`))}e.line()}function jY(e,t){let n=t.turnTokens.reduce((u,d)=>u+d.input,0),r=t.turnTokens.reduce((u,d)=>u+d.output,0),o=t.turnTokens.reduce((u,d)=>u+d.cache,0),s=n+r,i=Ot(t.model),a=t.turnTokens[t.turnTokens.length-1],l=a?a.footprint??a.input+a.output+a.cache:0,c=i>0?Math.round(l/i*100):0;e.line(),e.line(f.bold("Token usage")+f.dim(" (local stats \u2014 SDK breakdown unavailable)")),e.line(pe()),e.line(` input ${f.meta(ie(n))}`),e.line(` output ${f.meta(ie(r))}`),e.line(` cache read ${f.meta(ie(o))}`),e.line(` total ${f.success(ie(s))}`),e.line(` context ${f.meta(`${c}% of ${ie(i)} (${t.model})`)}`),e.line()}var HY={name:"/tokens",aliases:["/ctx"],summary:"Show token usage (SDK breakdown with local-stats fallback)",hint:"When you want to know how full the context window is \u2014 input/output/cache breakdown plus % of the model's limit used.",async handler(e){try{let t=await e.session.current.getContextUsage();UY(e.out,t)}catch{jY(e.out,e.stats)}return"continue"}},WY={name:"/history",summary:"Show conversation history",async handler(e){let{stats:t,out:n}=e;return t.turns.length===0?(n.info("No turns yet in this session."),"continue"):(n.line(),n.line(f.bold(`Session history (${t.turns.length} turn${t.turns.length===1?"":"s"})`)),n.line(pe()),t.turns.forEach((r,o)=>{let s=f.meta(`#${o+1}`),i=r.user.length>100?r.user.slice(0,97)+"...":r.user,a=r.assistant.length>100?r.assistant.slice(0,97)+"...":r.assistant;n.line(` ${s} ${f.user("\u25B6")} ${i}`),n.line(` ${f.brand("\u25C6")} ${f.dim(a)}`)}),n.line(),"continue")}},KY={name:"/reset",summary:"Clear screen, history, and session stats",async handler(e){let{stats:t,ui:n,out:r}=e;try{await e.session.current.sendMessage("/clear")}catch{}return t.totalTurns=0,t.totalCostUsd=0,t.totalTokens=0,t.totalDurationMs=0,t.turnCosts.length=0,t.turnTokens.length=0,t.turns.length=0,t.sessionStartTime=Date.now(),n.clearScreen(),r.success("Session reset."),"continue"}},GY={name:"/model",usage:"/model <local|small|medium|large|opus|sonnet|haiku|fable|org/model>",summary:"Switch the active model mid-session",hint:"Switch the capability tier (local/small/medium/large \u2014 or your configured names) or pass a full model id. Upgrade to large for a hard problem, downshift to small for cheap iteration \u2014 context carries over. Also accepts HuggingFace-style ids (e.g. mlx-community/Qwen3-30B-A3B-4bit).",async handler(e,t){let n=t.trim().toLowerCase();if(!n)return e.out.info(`Current model: ${f.brand(e.stats.model)}`),e.out.line(f.dim(` Aliases: ${Qy.join(", ")} (or any org/model HF id)`)),"continue";let r=Qy.includes(n),o=$s(n)!==void 0,s=re(n)==="openai-compatible";if(!r&&!o&&!s)return e.out.warn(`Unknown model: ${n}. Aliases: ${Qy.join(", ")} (or org/model for local/OpenAI-compatible)`),"continue";let i=Ds(n);if(i)return e.out.warn(i),"continue";try{await e.session.current.setModel(n),e.stats.model=n,e.ui.repaintStatusLine(),e.out.success(`Model switched to ${f.brand(n)}`)}catch(a){e.out.error(`Failed to switch model: ${a instanceof Error?a.message:String(a)}`)}return"continue"}},qY={name:"/tools",summary:"List tools available to the session",async handler(e){try{let n=(await e.session.current.waitForInitialization()).tools??[];if(n.length===0)return e.out.info("No tools reported by the session."),"continue";e.out.line(),e.out.line(f.bold(`Tools (${n.length})`)),e.out.line(pe());let r=3,o=Math.ceil(n.length/r),s=Math.max(...n.map(i=>i.length))+2;for(let i=0;i<o;i++){let a=[];for(let l=0;l<r;l++){let c=l*o+i;c<n.length&&a.push(n[c].padEnd(s))}e.out.line(" "+a.join(""))}e.out.line()}catch(t){e.out.error(`Could not read session tools: ${t instanceof Error?t.message:String(t)}`)}return"continue"}},zY={name:"/mcp",summary:'List MCP servers connected to the session ("/mcp auth" to surface pending OAuth URLs)',async handler(e,t){let n=(t??"").trim().toLowerCase();if(n==="auth"){try{let{readOauthPending:r}=await Promise.resolve().then(()=>(Xd(),rI)),o=r();if(Object.keys(o).length===0)return e.out.info("No MCP servers are waiting for OAuth."),"continue";e.out.line(),e.out.line(f.bold(`MCP OAuth pending (${Object.keys(o).length})`)),e.out.line(pe());for(let[s,i]of Object.entries(o)){let a=Date.now()-i.timestamp,l=Math.round(a/6e4);e.out.line(` ${f.warning("\u25CF")} ${s} ${f.dim(`(${l}m ago)`)}`),e.out.line(` ${f.info(i.authorizationUrl)}`)}e.out.line(),e.out.line(f.dim(" Open each URL in a browser. After authorizing, paste the code with:")),e.out.line(f.dim(" /mcp auth complete <serverName> <code>")),e.out.line()}catch(r){e.out.error(`Could not read OAuth state: ${r instanceof Error?r.message:String(r)}`)}return"continue"}if(n.startsWith("auth complete ")){let r=(t??"").trim(),o=r.slice(r.toLowerCase().indexOf("auth complete ")+14).trim(),s=o.indexOf(" ");if(s===-1||o.slice(0,s).length===0||o.slice(s+1).trim().length===0)return e.out.error("Usage: /mcp auth complete <serverName> <code>"),"continue";let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(!e.mcpManager)return e.out.error("No MCP manager available in this session. Make sure an mcp.json config is present and at least one server is enabled."),"continue";try{e.out.info(`Completing OAuth for "${i}"\u2026`),await e.mcpManager.completeAuth(i,a),e.out.success(`OAuth complete for "${i}" \u2014 server is now connected.`)}catch(l){e.out.error(`OAuth completion failed for "${i}": ${l instanceof Error?l.message:String(l)}`)}return"continue"}if(n!==""&&n!=="auth")return e.out.error(`Unknown /mcp subcommand: "${n}". Try: /mcp, /mcp auth, /mcp auth complete <server> <code>.`),"continue";try{let o=(await e.session.current.waitForInitialization()).mcpServers??[];if(o.length===0)return e.out.info("No MCP servers connected."),"continue";e.out.line(),e.out.line(f.bold(`MCP servers (${o.length})`)),e.out.line(pe());let s=0;for(let i of o){let a=typeof i=="string"?i:i.name??JSON.stringify(i),l=typeof i=="object"&&i!==null&&"status"in i?String(i.status):"",c=l==="connected"?f.success("\u25CF"):f.warning("\u25CF");e.out.line(` ${c} ${a}${l?f.dim(` (${l})`):""}`),l==="oauth_pending"&&s++}e.out.line(),s>0&&(e.out.line(f.dim(` ${s} server(s) need OAuth \u2014 run "/mcp auth" to see authorization URLs.`)),e.out.line())}catch(r){e.out.error(`Could not read MCP servers: ${r instanceof Error?r.message:String(r)}`)}return"continue"}},JY={name:"/limits",summary:"Show known per-model context-window limits",async handler(e){e.out.line(),e.out.line(f.bold("Context-window limits")),e.out.line(pe());for(let[t,n]of Object.entries(ei)){let r=t===e.stats.model?f.brand(" \u2190 active"):"";e.out.line(` ${f.warning(t.padEnd(12))} ${f.meta(ie(n))}${r}`)}return e.out.line(),"continue"}},VY={name:"/debug",summary:"Show SDK session metadata (tools, MCP, skills, plugins, etc.)",hint:"When something feels broken and you want to inspect what the session actually loaded \u2014 tools, MCP servers, plugins, system prompt source.",async handler(e){try{let t=await e.session.current.waitForInitialization();e.out.line(),e.out.line(mp(t)),e.out.line()}catch(t){e.out.error(`Could not read session metadata: ${t instanceof Error?t.message:String(t)}`)}return"continue"}},MI=[BY,HY,WY,KY,GY,qY,zY,JY,VY];G();fh();var eb=!1;async function vl(e,t){let n=e.stats.permissionMode==="plan",r=t!==void 0?t:!n;try{if(await e.session.current.setPermissionMode(r?"plan":"default"),e.stats.permissionMode=r?"plan":"default",e.ui.repaintStatusLine(),r){let o=eb?"":f.dim(" /plan off saves the plan + implements; Shift+Tab cycles to the next mode.");eb||(eb=!0),e.out.success(f.warning("\u25CF plan mode ON")+f.dim(" \u2014 writes are refused; read-only bash runs, mutating bash is blocked.")+o)}else e.out.success(f.success("\u25CB plan mode OFF")+f.dim(" \u2014 default permissions restored"))}catch(o){e.out.error(`Could not toggle plan mode: ${o instanceof Error?o.message:String(o)}`)}}async function YY(e){if(await vl(e,!1),e.stats.permissionMode==="plan")return"continue";let t=pc(e.stats.cwd??process.cwd());return e.out.info(f.dim(` \u2192 saving the plan to ${t}/, then implementing it.`)),{kind:"submit",message:ju(t)}}var OI={name:"/plan",usage:"/plan [on|off|<prompt>]",summary:"Toggle plan mode; /plan off saves the plan to a file then implements it",hint:"Think through an approach without changing anything \u2014 write tools and state-mutating bash are refused until you exit; read-only investigation runs. /plan off saves the plan + implements it; Shift+Tab cycles to the next mode without implementing.",async handler(e,t){let n=t.trim(),r=n.toLowerCase();return n!==""&&r!=="on"&&r!=="off"?(e.stats.permissionMode!=="plan"&&await vl(e,!0),{kind:"submit",message:n}):(r==="on"?!0:r==="off"?!1:e.stats.permissionMode!=="plan")===!0?(e.stats.permissionMode==="plan"||await vl(e,!0),"continue"):e.stats.permissionMode!=="plan"?(await vl(e,!1),"continue"):YY(e)}};q();gu();wi();_o();var $I=20,XY={done:"\u2705 Done",blocked:"\u26D4 Blocked",asking:"\u2753 Asking",interrupted:"\u23F8\uFE0F Interrupted"},ZY={done:[["","whatWasDone"],["Evidence","evidence"],["Pending","deferred"]],blocked:[["Blocked by","whatBlocks"],["Unblock","unblockCondition"],["Done so far","alreadyDone"]],asking:[["","question"],["Resolves","assumption"],["Then","followup"]],interrupted:[["","whatWasInProgress"],["State saved","stateLocation"],["Resume needs","resumeRequires"]]},QY=new Set(["write_file","edit_file","bash"]);function DI(e){return e.some(t=>QY.has(t.toolName)&&t.isError!==!0)}function e4(e,t={}){let n=e.kind==="done"&&t.unverified===!0,o=`\u{1F916} AFK \xB7 ${n?"\u26A0\uFE0F Done (unverified)":XY[e.kind]}`,s=[];for(let[a,l]of ZY[e.kind]){let c=e[l];typeof c=="string"&&c.trim().length>0&&s.push(a?`\u2022 ${a}: ${c.trim()}`:`\u2022 ${c.trim()}`)}s.length===0&&e.rawBody.trim().length>0&&s.push(e.rawBody.trim()),n&&s.push("\u2022 \u26A0\uFE0F Unverified: no file write/edit or successful command recorded this turn \u2014 confirm before relying on this.");let i=s.length>0?s.join(`
|
|
1787
|
-
`):"(no detail)";return
|
|
1787
|
+
`):"(no detail)";return mt(`${o}
|
|
1788
1788
|
${i}`)}var tb=0,nb=!1;function LI(){tb=0,nb=!1}async function FI(e,t=$r,n={}){try{if(tb>=$I){nb||(nb=!0,await t(`\u{1F916} AFK \xB7 reached ${$I} updates this session \u2014 further terminal-state pushes muted. Run /afk off then /afk on to resume.`));return}tb+=1,await t(e4(e,n))}catch{}}G();import*as Li from"node:fs";import*as BI from"node:path";import{createHmac as t4,randomBytes as UI,timingSafeEqual as n4}from"node:crypto";var r4=32,jI="\0";function o4(e){return JSON.stringify(rb(e))}function rb(e){if(Array.isArray(e))return e.map(rb);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=rb(t[r]);return n}return e}function HI(e){let t=NI(e);if(t)return t;let n;try{n=Tf(e)}catch{return null}try{Li.mkdirSync(BI.dirname(n),{recursive:!0});let r=UI(r4).toString("hex");return Li.writeFileSync(n,r+`
|
|
1789
1789
|
`,{mode:384}),r}catch{return NI(e)}}function NI(e){let t;try{t=Tf(e)}catch{return null}try{let n=Li.readFileSync(t,"utf8").trim();return n.length>0?n:null}catch{return null}}function WI(e,t){return t4("sha256",e).update(t).digest("hex")}function KI(e,t){if(typeof e!="string"||typeof t!="string"||e.length!==t.length||e.length===0||!/^[0-9a-f]+$/i.test(e)||!/^[0-9a-f]+$/i.test(t))return!1;let n,r;try{n=Buffer.from(e,"hex"),r=Buffer.from(t,"hex")}catch{return!1}return n.length!==r.length||n.length===0?!1:n4(n,r)}function s4(e,t,n){return["elicitation_response",e,t,o4(n)].join(jI)}function i4(e,t,n,r){return WI(e,s4(t,n,r))}function GI(e,t,n,r,o){return KI(o,i4(e,t,n,r))}function a4(e,t){return["abort_request",e,t].join(jI)}function l4(e,t,n){return WI(e,a4(t,n))}function qI(e,t,n,r){return KI(r,l4(e,t,n))}function zI(){return UI(8).toString("hex")}Py();var JI={action:"decline"};function VI(e){let{sessionId:t,key:n,onAbort:r}=e;if(n===null)return{stop:()=>{}};let o=new AbortController;return(async()=>{try{for await(let s of Iy(t,{fromStart:!1,signal:o.signal}))if(s.kind==="abort_request"&&qI(n,t,s.nonce,s.hmac)){r("remote abort via Telegram"),o.abort();return}}catch{}})(),{stop:()=>{o.abort()}}}function YI(e){let{sessionId:t,key:n,emitElicitation:r,fallback:o}=e,s=e.newReqId??zI;return function(a,l){let c=l.signal;if(c.aborted)return Promise.resolve(JI);let u=s(),d,p=new Promise(h=>{d=h}),m=new AbortController,g=()=>{m.abort(),d(JI)};c.addEventListener("abort",g,{once:!0}),n&&(async()=>{try{for await(let h of Iy(t,{fromStart:!1,signal:m.signal}))if(h.kind==="elicitation_response"&&h.reqId===u&&GI(n,t,u,h.result,h.hmac)){d(h.result);return}}catch{}})();try{r({kind:"elicitation",reqId:u,request:a})}catch{}return Promise.resolve(o(a,{signal:m.signal})).then(h=>d(h)).catch(()=>{}),p.finally(()=>{m.abort(),c.removeEventListener("abort",g)})}}Ma();var fp=null;function c4(){return v.TELEGRAM_BOT_TOKEN?Vs().length>0:!1}async function kl(e,t){let n=e.stats.permissionMode==="autonomous",r=t!==void 0?t:!n;try{if(await e.session.current.setPermissionMode(r?"autonomous":"default"),e.stats.permissionMode=r?"autonomous":"default",e.ui.repaintStatusLine(),r){LI();let o=e.session.current,s=o.sessionId,i=e.swapElicitationHandler,a=e.stdinElicitationHandler;if(s&&i&&a){let l=HI(s),c=YI({sessionId:s,key:l,emitElicitation:u=>o.recordLedgerElicitation(u.reqId,u.request),fallback:a});i(c),fp?.stop(),fp=VI({sessionId:s,key:l,onAbort:u=>o.abort(u)}),fg(s,!0)}e.out.success(f.info("\u25D0 AFK mode ON")+f.dim(" \u2014 autonomous on reversible work; high-risk/irreversible ops are refused; terminal states report to Telegram.")),c4()||e.out.error("Telegram is not configured, so AFK updates will not be delivered. Run /telegram-setup to connect a chat. (AFK posture + safety gate still apply.)")}else{e.swapElicitationHandler?.(null),fp?.stop(),fp=null;let o=e.session.current.sessionId;o&&fg(o,!1),e.out.success(f.success("\u25CB AFK mode OFF")+f.dim(" \u2014 default permissions restored"))}}catch(o){e.out.error(`Could not toggle AFK mode: ${o instanceof Error?o.message:String(o)}`)}}var XI={name:"/afk",usage:"/afk [on|off]",summary:"Toggle AFK mode \u2014 autonomous work + Telegram reporting while you are away",hint:"Tell the agent you are away from keyboard: it works autonomously on reversible operations, a safety gate refuses high-risk/irreversible ops, and each turn reports its terminal state to Telegram. /afk off restores default permissions.",async handler(e,t){let n=t.trim().toLowerCase(),r=n==="on"?!0:n==="off"?!1:e.stats.permissionMode!=="autonomous";return r&&e.stats.permissionMode==="autonomous"?"continue":!r&&e.stats.permissionMode!=="autonomous"?(await kl(e,!1),"continue"):(await kl(e,r),"continue")}};G();import{readFileSync as u4,writeFileSync as d4,existsSync as ZI,mkdirSync as p4}from"fs";import{join as m4}from"path";function QI(){return JS(),yf()}function eP(e){return m4(QI(),`${e}.json`)}function gp(e){let t=eP(e);if(!ZI(t))return{sessionId:e,items:[]};try{let n=u4(t,"utf-8"),r=JSON.parse(n);return Array.isArray(r.items)?r:{sessionId:e,items:[]}}catch{return{sessionId:e,items:[]}}}function El(e){let t=QI();ZI(t)||p4(t,{recursive:!0}),d4(eP(e.sessionId),JSON.stringify(e,null,2))}function tP(e,t){let r={id:e.items.reduce((o,s)=>Math.max(o,s.id),0)+1,text:t,done:!1,createdAt:Date.now()};return e.items.push(r),r}function nP(e,t){let n=e.items.find(r=>r.id===t);return n&&(n.done=!0),n}function rP(e,t){let n=e.items.findIndex(r=>r.id===t);return n===-1?!1:(e.items.splice(n,1),!0)}function oP(e){e.items.length=0}function hp(e){if(e.items.length===0)return[];let t=[],n=Math.max(20,Q());{let r=f.dim("\u250C\u2500 todos "),o=Math.max(0,Math.min(n-10,120));t.push(r+f.dim("\u2500".repeat(o)))}for(let r of e.items){let o=r.done?f.success("[x]"):f.dim("[ ]"),s=r.done?f.dim(r.text):Cr(r.text),a=` ${f.meta(`#${r.id}`)} ${o} `,l=Math.max(8,n-V(a)),c=le(s,l).split(`
|
|
1790
1790
|
`);t.push(a+(c[0]??""));let u=" ".repeat(V(a));for(let d of c.slice(1))t.push(u+d)}{let r=Math.max(0,Math.min(n-1,120));t.push(f.dim("\u2514"+"\u2500".repeat(r)))}return t}function sP(e){return e.items.length===0?"":e.items.map(t=>`${t.id}:${t.done?1:0}:${t.text}`).join(`
|
|
@@ -1819,7 +1819,7 @@ ${u}`}function ub(e,t){let n=EP[t.status];e.out.line(` ${n} ${f.bold(t.jobId)}
|
|
|
1819
1819
|
`),s=0;for(let i=0;i<o.length;i++){let a=Ne(o[i]),l=(i===0?t:0)+xl(a);s+=Math.max(1,Math.ceil(l/r))}return Math.max(0,s-1)}function to(e,t,n,r){let o=r||80,s=e.split(`
|
|
1820
1820
|
`),i=0,a=0;for(let l=0;l<s.length;l++){let c=s[l],u=c.length+(l<s.length-1?1:0);if(t<=a+c.length){let p=t-a,m=Ne(c.slice(0,p)),g=(l===0?n:0)+xl(m),h=Math.floor(g/o),b=g%o;return{row:i+h,col:b}}let d=(l===0?n:0)+xl(Ne(c));i+=Math.max(1,Math.ceil(d/o)),a+=u}return{row:i,col:0}}function Jo(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.trunc(e))):0}function Nn(e,t){let n=Jo(t,e.buffer.length);return n===e.cursor?e:{buffer:e.buffer,cursor:n}}function _P(e,t){let n=Jo(t,e.length);for(;n>0&&/\s/.test(e.charAt(n-1));)n--;for(;n>0&&!/\s/.test(e.charAt(n-1));)n--;return n}function IP(e,t){let n=e.length,r=Jo(t,n);for(;r<n&&/\s/.test(e.charAt(r));)r++;for(;r<n&&!/\s/.test(e.charAt(r));)r++;return r}function PP(e,t){let n=Jo(t,e.length),r=n===0?-1:e.lastIndexOf(`
|
|
1821
1821
|
`,n-1);return r<0?0:r+1}function MP(e,t){let n=Jo(t,e.length),r=e.indexOf(`
|
|
1822
|
-
`,n);return r<0?e.length:r}function no(e,t,n){let r=Jo(t.start,e.buffer.length),o=Jo(t.end,e.buffer.length),s=Math.min(r,o),i=Math.max(r,o);if(s===i&&n.length===0)return e;let a=e.buffer.slice(0,s)+n+e.buffer.slice(i),l=s+n.length;return a===e.buffer&&l===e.cursor?e:{buffer:a,cursor:l}}var K={seed(e=""){return{buffer:e,cursor:e.length}},replaceRange:no,insert(e,t){return t.length===0?e:no(e,{start:e.cursor,end:e.cursor},t)},backspace(e){if(e.cursor===0)return e;let t=Af(e.buffer,e.cursor);return no(e,{start:t,end:e.cursor},"")},deleteForward(e){if(e.cursor>=e.buffer.length)return e;let t=bo(e.buffer,e.cursor);return no(e,{start:e.cursor,end:t},"")},deleteWordBackward(e){if(e.cursor===0)return e;let t=_P(e.buffer,e.cursor);return t===e.cursor?e:no(e,{start:t,end:e.cursor},"")},deleteWordForward(e){if(e.cursor>=e.buffer.length)return e;let t=IP(e.buffer,e.cursor);return t===e.cursor?e:no(e,{start:e.cursor,end:t},"")},deleteToLineStart(e){let t=PP(e.buffer,e.cursor);return t===e.cursor?e:no(e,{start:t,end:e.cursor},"")},deleteToLineEnd(e){let t=MP(e.buffer,e.cursor);return t===e.cursor?e:no(e,{start:e.cursor,end:t},"")},moveLeft(e){return Nn(e,Af(e.buffer,e.cursor))},moveRight(e){return Nn(e,bo(e.buffer,e.cursor))},moveHome(e){return Nn(e,0)},moveEnd(e){return Nn(e,e.buffer.length)},moveLineStart(e){return Nn(e,PP(e.buffer,e.cursor))},moveLineEnd(e){return Nn(e,MP(e.buffer,e.cursor))},moveWordBackward(e){return Nn(e,_P(e.buffer,e.cursor))},moveWordForward(e){return Nn(e,IP(e.buffer,e.cursor))},moveUpLine(e,t,n){let r=t||80,{row:o,col:s}=to(e.buffer,e.cursor,n,r);if(o===0)return{moved:!1};let i=o-1,a=s,l=0,c=1/0;for(let d=0;d<=e.buffer.length;d++){let p=to(e.buffer,d,n,r);if(p.row===i){let m=Math.abs(p.col-a);m<c&&(c=m,l=d)}else if(p.row>i)break}let u=Nn(e,l);return u===e?{moved:!1}:{moved:!0,state:u}},moveDownLine(e,t,n){let r=t||80,{row:o,col:s}=to(e.buffer,e.cursor,n,r),i=to(e.buffer,e.buffer.length,n,r);if(o>=i.row)return{moved:!1};let a=o+1,l=s,c=e.buffer.length,u=1/0;for(let p=0;p<e.buffer.length;p++){let m=to(e.buffer,p,n,r);if(m.row===a){let g=Math.abs(m.col-l);g<u&&(u=g,c=p)}else if(m.row>a)break}i.row===a&&Math.abs(i.col-l)<u&&(c=e.buffer.length);let d=Nn(e,c);return d===e?{moved:!1}:{moved:!0,state:d}}};var OP=["Stalking","Shadowing","Tailing","Casing","Sleuthing","Investigating","Deducing","Interrogating","Profiling","Canvassing","Prowling","Lurking","Scanning","Probing","Inspecting","Querying","Invoking","Parsing","Validating","Resolving","Compiling","Executing","Hunting","Sweeping","Tracing","Tracking","Triangulating","Decoding","Decrypting","Intercepting","Hacking","Bugging","Wiretapping","Dispatching","Deploying","Patching","Hooking","Unmasking","Cornering","Striking","Surveilling","Scouting"];function fb(){return OP[Math.floor(Math.random()*OP.length)]}
|
|
1822
|
+
`,n);return r<0?e.length:r}function no(e,t,n){let r=Jo(t.start,e.buffer.length),o=Jo(t.end,e.buffer.length),s=Math.min(r,o),i=Math.max(r,o);if(s===i&&n.length===0)return e;let a=e.buffer.slice(0,s)+n+e.buffer.slice(i),l=s+n.length;return a===e.buffer&&l===e.cursor?e:{buffer:a,cursor:l}}var K={seed(e=""){return{buffer:e,cursor:e.length}},replaceRange:no,insert(e,t){return t.length===0?e:no(e,{start:e.cursor,end:e.cursor},t)},backspace(e){if(e.cursor===0)return e;let t=Af(e.buffer,e.cursor);return no(e,{start:t,end:e.cursor},"")},deleteForward(e){if(e.cursor>=e.buffer.length)return e;let t=bo(e.buffer,e.cursor);return no(e,{start:e.cursor,end:t},"")},deleteWordBackward(e){if(e.cursor===0)return e;let t=_P(e.buffer,e.cursor);return t===e.cursor?e:no(e,{start:t,end:e.cursor},"")},deleteWordForward(e){if(e.cursor>=e.buffer.length)return e;let t=IP(e.buffer,e.cursor);return t===e.cursor?e:no(e,{start:e.cursor,end:t},"")},deleteToLineStart(e){let t=PP(e.buffer,e.cursor);return t===e.cursor?e:no(e,{start:t,end:e.cursor},"")},deleteToLineEnd(e){let t=MP(e.buffer,e.cursor);return t===e.cursor?e:no(e,{start:e.cursor,end:t},"")},moveLeft(e){return Nn(e,Af(e.buffer,e.cursor))},moveRight(e){return Nn(e,bo(e.buffer,e.cursor))},moveHome(e){return Nn(e,0)},moveEnd(e){return Nn(e,e.buffer.length)},moveLineStart(e){return Nn(e,PP(e.buffer,e.cursor))},moveLineEnd(e){return Nn(e,MP(e.buffer,e.cursor))},moveWordBackward(e){return Nn(e,_P(e.buffer,e.cursor))},moveWordForward(e){return Nn(e,IP(e.buffer,e.cursor))},moveUpLine(e,t,n){let r=t||80,{row:o,col:s}=to(e.buffer,e.cursor,n,r);if(o===0)return{moved:!1};let i=o-1,a=s,l=0,c=1/0;for(let d=0;d<=e.buffer.length;d++){let p=to(e.buffer,d,n,r);if(p.row===i){let m=Math.abs(p.col-a);m<c&&(c=m,l=d)}else if(p.row>i)break}let u=Nn(e,l);return u===e?{moved:!1}:{moved:!0,state:u}},moveDownLine(e,t,n){let r=t||80,{row:o,col:s}=to(e.buffer,e.cursor,n,r),i=to(e.buffer,e.buffer.length,n,r);if(o>=i.row)return{moved:!1};let a=o+1,l=s,c=e.buffer.length,u=1/0;for(let p=0;p<e.buffer.length;p++){let m=to(e.buffer,p,n,r);if(m.row===a){let g=Math.abs(m.col-l);g<u&&(u=g,c=p)}else if(m.row>a)break}i.row===a&&Math.abs(i.col-l)<u&&(c=e.buffer.length);let d=Nn(e,c);return d===e?{moved:!1}:{moved:!0,state:d}}};var OP=["Stalking","Shadowing","Tailing","Casing","Sleuthing","Investigating","Deducing","Interrogating","Profiling","Canvassing","Prowling","Lurking","Scanning","Probing","Inspecting","Querying","Invoking","Parsing","Validating","Resolving","Compiling","Executing","Hunting","Sweeping","Tracing","Tracking","Triangulating","Decoding","Decrypting","Intercepting","Hacking","Bugging","Wiretapping","Dispatching","Deploying","Patching","Hooking","Unmasking","Cornering","Striking","Surveilling","Scouting"];function fb(){return OP[Math.floor(Math.random()*OP.length)]}wt();q();var z4=[{id:"kbd:ctrl-b",text:"Ctrl+B during a turn detaches it to the background so you can keep typing \u2014 find it later with /bgsub.",source:"static"},{id:"kbd:shift-tab",text:"Shift+Tab cycles permission modes: default \u2192 plan \u2192 bypass (AFK stays on /afk).",source:"static"},{id:"kbd:ctrl-c",text:"Ctrl+C interrupts the current turn; press it twice in a row to exit the REPL.",source:"static"},{id:"kbd:at-path",text:"Type @ in the prompt to autocomplete a file path and attach its contents to your turn.",source:"static"},{id:"kbd:cmd-v",text:"Paste an image with Cmd+V (macOS) or Ctrl+V \u2014 clipboard images attach automatically.",source:"static"},{id:"env:tips-opt-out",text:"Set AFK_SPINNER_TIPS=0 to silence these loading-screen tips.",source:"static"}];function J4(){let e=[];for(let t of ot())t.hint&&(t.name.includes(":")||e.push({id:`cmd:${t.name}`,text:`${t.name} \u2014 ${t.hint}`,source:"command"}));return e}function V4(e){let t=[];for(let n of Vn()){let r=`cmd:/${n}`;if(e.has(r))continue;let o;try{o=Ke(n)}catch{continue}nn(o,v.AFK_INTERNAL==="1")&&o.whenToUse&&t.push({id:`skill:${n}`,text:`/${n} \u2014 ${o.whenToUse}`,source:"skill"})}return t}function LP(){if(v.AFK_SPINNER_TIPS==="0")return[];let e=J4(),t=new Set(e.map(r=>r.id)),n=V4(t);return[...z4,...e,...n]}var $P=new Set,DP=new Map;function FP(e,t){if(e.length===0)return null;let n=t.now??Date.now(),r=t.warmupMs??1500;if(n-t.startedAt<r)return null;let o=t.rotateMs??7e3,s=Math.floor((n-t.startedAt)/o),i=`${t.startedAt}:${s}`,a=DP.get(i);if(a)return a;let l=null,c=e.filter(u=>!$P.has(u.id));if(c.length>0){let u=(s%c.length+c.length)%c.length;l=c[u]??null}else{let u=(s%e.length+e.length)%e.length;l=e[u]??null}return l&&($P.add(l.id),DP.set(i,l)),l}var gb=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Y4=2e3;function NP(e){let t=Date.now()-e;if(t<Y4)return"";let n=Math.floor(t/1e3);if(n<60)return f.dim(` ${n}s`);let r=Math.floor(n/60),o=n%60;return f.dim(` ${r}m${o.toString().padStart(2,"0")}s`)}function kt(e,t){return`\x1B[${e};1H\x1B[2K${t??""}`}function BP(e,t){let n=" \u{1F4A1} Tip: ",r=Math.max(8,t-V(n)-1),o=V(e)>r?ne(e,Math.max(0,r-1),"")+"\u2026":e;return f.dim(n+o)}var Ep=class{state=null;interval=null;captureMode;onTick;constructor(t){this.captureMode=t.captureMode,this.onTick=t.onTick}set(t){if(!t.enabled){this.interval&&(clearInterval(this.interval),this.interval=null),this.state&&(this.state=null,this.onTick());return}if(this.captureMode||this.state)return;let n=t.rotateVerbEveryMs??3500,r=Date.now();this.state={frameIndex:0,verb:fb(),nextVerbRotateAt:r+n,startedAt:r,tipPool:LP(),currentTip:null},this.interval=setInterval(()=>this.tick(n),80),this.onTick()}dispose(){this.interval&&(clearInterval(this.interval),this.interval=null),this.state=null}renderSpinnerRow(){return this.state?f.meta(`${gb[this.state.frameIndex]} ${this.state.verb}...`)+NP(this.state.startedAt):null}renderTipRow(t){return this.state?.currentTip?BP(this.state.currentTip.text,t):null}tick(t){if(!this.state)return;this.state.frameIndex=(this.state.frameIndex+1)%gb.length;let n=Date.now();n>=this.state.nextVerbRotateAt&&(this.state.verb=fb(),this.state.nextVerbRotateAt=n+t),this.state.currentTip=FP(this.state.tipPool,{startedAt:this.state.startedAt,now:n}),this.onTick()}};var Tp=class{interval=null;visiblePhase=!0;enabled;captureMode;intervalMs;onTick;constructor(t){this.enabled=t.enabled,this.captureMode=t.captureMode,this.intervalMs=t.intervalMs,this.onTick=t.onTick}get visible(){return this.enabled?this.visiblePhase:!0}start(){!this.enabled||this.captureMode||this.interval||(this.visiblePhase=!0,this.schedule())}resetVisible(){if(!this.enabled||this.captureMode||!this.interval)return!1;let t=!this.visiblePhase;return this.visiblePhase=!0,clearInterval(this.interval),this.schedule(),t}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.visiblePhase=!0}schedule(){let t=setInterval(()=>{this.visiblePhase=!this.visiblePhase,this.onTick()},this.intervalMs);t.unref?.(),this.interval=t}};import{randomBytes as X4}from"node:crypto";var Z4=5,Q4=1e3,e8=/\[Pasted text #([0-9a-f]+) \+\d+ (?:lines|chars)\]/g;function t8(e,t){let n=t.match(/\n/g),r=n?n.length:0;return r>0?`[Pasted text #${e} +${r+1} lines]`:`[Pasted text #${e} +${t.length} chars]`}function xp(e,t){return e.pasteRegistry.size===0?t:t.replace(e8,(n,r)=>e.pasteRegistry.get(r)??n)}function UP(e){return{text:xp(e,e.input.buffer),queued:e.queued}}function jP(e){let t=e.pasteStartCursor,n=e.input.cursor;if(n<=t)return;let o=e.input.buffer.slice(t,n).replace(/\x1b\[200~/g,"").replace(/\x1b\[201~/g,""),s=o.match(/\n/g),i=s?s.length:0,a=o.length;if(i<Z4&&a<Q4)return;let l=X4(4).toString("hex");e.pasteRegistry.set(l,o);let c=t8(l,o);e.input=K.replaceRange(e.input,{start:t,end:n},c)}function hb(e,t){if(e.pasteRegistry.size===0)return null;let n=e.input.buffer,r=e.input.cursor;if(t==="backward"){let l=/\[Pasted text #([0-9a-f]+) \+\d+ (?:lines|chars)\]$/.exec(n.slice(0,r));if(!l)return null;let c=r-l[0].length,u=l[1],d=K.replaceRange(e.input,{start:c,end:r},"");return e.pasteRegistry.delete(u),d}let o=/^\[Pasted text #([0-9a-f]+) \+\d+ (?:lines|chars)\]/.exec(n.slice(r));if(!o)return null;let s=r+o[0].length,i=o[1],a=K.replaceRange(e.input,{start:r,end:s},"");return e.pasteRegistry.delete(i),a}import{readdirSync as r8,statSync as o8}from"fs";import{join as s8}from"path";import{join as WP}from"path";import{homedir as n8}from"os";var KP=50;function Rp(e,t,n=n8()){if(e==="~"||e.startsWith("~/")){let l=e==="~"?"":e.slice(2),c=l.lastIndexOf("/"),u=c===-1?"":l.slice(0,c),d=c===-1?l:l.slice(c+1),p=u?WP(n,u):n,m=u?`~/${u}/`:"~/";return{scanDir:p,leafPrefix:d,displayPrefix:m}}if(e.startsWith("/")){let l=e.lastIndexOf("/"),c=e.slice(0,l+1)||"/",u=e.slice(l+1);return{scanDir:c,leafPrefix:u,displayPrefix:c}}let r=e.lastIndexOf("/"),o=r===-1?"":e.slice(0,r),s=r===-1?e:e.slice(r+1),i=o?WP(t,o):t,a=o?`${o}/`:"";return{scanDir:i,leafPrefix:s,displayPrefix:a}}async function GP(e){let t="",n=e.promptFn(),r=e.continuationPrompt??" \u203A ";for(;;){e.rl.setPrompt(n),e.rl.prompt();let o=await new Promise(s=>{e.rl.once("line",i=>s(i))});if(o.endsWith("\\")){t+=o.slice(0,-1)+`
|
|
1823
1823
|
`,n=r;continue}return t+=o,t}}function Rl(e,t){let n=e.slice(0,t);if(/^\/[A-Za-z_-]*$/.test(n))return{kind:"slash",query:n.slice(1)};let r=n.split(/\s+/),o=r[r.length-1]??"";if(o.startsWith("@")&&/^@[^\s]*$/.test(o))return{kind:"file",query:o.slice(1)};let s=/^\/([A-Za-z][A-Za-z0-9_:-]*)\s+(?:.*\s)?--([a-z0-9-]*)$/.exec(n);if(s){let i=s[1],a=s[2],l=ot().find(c=>c.name===`/${i}`);if(l?.flags&&l.flags.length>0)return{kind:"flag",command:i,query:a}}return null}function Cp(e){let t=ot(),n=t.filter(s=>s.name.slice(1).startsWith(e)).map(s=>({value:s.name,summary:s.summary,...s.hint?{hint:s.hint}:{}})),r=Di().filter(s=>s.alias.slice(1).startsWith(e)).map(s=>{let i=t.find(a=>a.name===s.canonical);return{value:s.alias,summary:s.summary,...i?.hint?{hint:i.hint}:{}}});return[...n,...r].sort((s,i)=>s.value.localeCompare(i.value)).slice(0,20)}function Ap(e,t=process.cwd(),n){let{scanDir:r,leafPrefix:o,displayPrefix:s}=Rp(e,t,n);try{return r8(r).filter(a=>a.startsWith(o)).filter(a=>!(a.startsWith(".")&&!o.startsWith("."))).sort().slice(0,KP).map(a=>{let l=s+a;try{o8(s8(r,a)).isDirectory()&&(l+="/")}catch{}return{value:"@"+l}})}catch{return[]}}function Cl(e,t){let n=ot().find(s=>s.name===`/${e}`);if(!n?.flags||n.flags.length===0)return[];let r=t.startsWith("--")?t.slice(2):t;return n.flags.filter(s=>(s.startsWith("--")?s.slice(2):s).startsWith(r)).map(s=>({value:s})).sort((s,i)=>s.value.localeCompare(i.value)).slice(0,20)}tt();q();var i8=3,a8=250,l8=1500,c8=500;function qP(){return"Predict the single most likely completion of the user's in-progress REPL input. Return ONLY the completed line \u2014 no explanation, no preamble, no trailing newline."}function zP(e,t){let n=t.cwd.split("/").filter(Boolean).pop()??t.cwd,r=t.getRecentCommands().slice(0,5),o=t.getTranscriptTail(),s=[];return s.push(`cwd: ${n}`),r.length>0&&s.push(`recent: ${r.join(" | ")}`),o.length>0&&s.push(`context: ${o.slice(0,200)}`),s.push(`input: ${e}`),s.join(`
|
|
1824
1824
|
`)}function Ni(e){return e.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\u001b\][\s\S]*?(?:\u0007|\u001b\\)/g,"").replace(/\u001b[@-_]/g,"").replace(/[\u0000-\u001f\u007f-\u009f]/g,"")}function JP(e,t){let n=t.trim();return n.startsWith(e)&&n.length>e.length}function YP(e={}){let t=e.debounceMs??a8,n=e.timeoutMs??l8,r=null,o=null,s=null,i=new Map,a=e.resolveProviderFn??Rd,l=new Map;function c(h,b){let y=re(h,b),S=l.get(y);return S===void 0&&(S=a(h,b),l.set(y,S)),S}function u(h,b){if(i.size>=c8&&!i.has(h)){let y=i.keys().next().value;y!==void 0&&i.delete(y)}i.set(h,b)}function d(h,b){if(h.length===0)return null;let y=b.getDropdownTopCandidate(h);if(y!==null&&y.startsWith(h)&&y.length>h.length)return y;let S=b.getHistory();for(let T of S)if(T.startsWith(h)&&T.length>h.length)return T;let w=/\s+\/([A-Za-z][A-Za-z0-9_:-]*)$/.exec(h);if(w){let x="/"+w[1],C=ot().map(A=>A.name),R=Di().map(A=>A.alias),$=[...C,...R].filter(A=>A.startsWith(x)).sort((A,P)=>A.localeCompare(P))[0];if($){let A=h.length-x.length;return h.slice(0,A)+$}}return null}async function p(h,b){let y=d(h,b);if(y!==null)return y;if(!b.llmEnabled()||h.length<i8)return null;if(i.has(h))return i.get(h)??null;if(s!==null&&(s.abort(),s=null),r!==null&&(clearTimeout(r),r=null,o!==null)){let S=o;o=null,S(null)}return new Promise(S=>{o=S,r=setTimeout(()=>{r=null,o=null,m(h,b,S)},t)})}async function m(h,b,y){let S=new AbortController;s=S;let w=setTimeout(()=>S.abort(),n),T=new Promise(x=>{S.signal.aborted?x(null):S.signal.addEventListener("abort",()=>x(null),{once:!0})});try{let x=null,C=!1;if(e.completeFn){let R=await Promise.race([e.completeFn({system:qP(),user:zP(h,b),model:VP(b),maxTokens:24,signal:S.signal,apiKey:b.apiKey,baseUrl:b.baseUrl}).then(k=>({ok:!0,raw:k})),T.then(()=>({ok:!1}))]);if(R.ok){C=!0;let k=Ni(R.raw).trim();x=JP(h,k)?k:null}}else{let R=VP(b),k=b.baseUrl?{openaiBaseUrl:b.baseUrl}:void 0,$=c(R,k);if(typeof $.complete!="function"){u(h,null),y(null);return}let A=await Promise.race([$.complete({system:qP(),user:zP(h,b),model:R,maxTokens:24,signal:S.signal,apiKey:b.apiKey,baseUrl:b.baseUrl}).then(P=>({ok:!0,raw:P})),T.then(()=>({ok:!1}))]);if(A.ok){C=!0;let P=Ni(A.raw).trim();x=JP(h,P)?P:null}}C&&u(h,x),y(x)}catch(x){e.onError?.(x),y(null)}finally{clearTimeout(w),s===S&&(s=null)}}function g(){if(r!==null&&(clearTimeout(r),r=null,o!==null)){let h=o;o=null,h(null)}s!==null&&(s.abort(),s=null);for(let h of l.values())try{h.close?.()}catch{}l.clear()}return{getDeterministicGhost:d,getGhost:p,dispose:g}}function VP(e){let t=v.AFK_SUGGEST_MODEL;if(t)return t;let n=re(e.model);return n==="anthropic-direct"||n==="anthropic"?v.AFK_COMPACT_MODEL??"haiku":e.model}var Vo=6;function _p(e){let t=e.autocompleteState;if(!t)return;t.trigger=Rl(e.input.buffer,e.input.cursor);let n=`${e.input.cursor}:${e.input.buffer}`;t.suppressedSignature!==null&&t.suppressedSignature!==n&&(t.suppressedSignature=null),t.trigger&&t.suppressedSignature===null?(t.trigger.kind==="slash"?t.candidates=Cp(t.trigger.query).slice(0,12):t.trigger.kind==="file"?t.candidates=Ap(t.trigger.query):t.candidates=Cl(t.trigger.command,t.trigger.query),t.dropdownOpen=t.candidates.length>0):(t.dropdownOpen=!1,t.candidates=[]),t.selectedIndex>=t.candidates.length&&(t.selectedIndex=Math.max(0,t.candidates.length-1)),t.viewportStart>t.selectedIndex&&(t.viewportStart=t.selectedIndex),t.selectedIndex>=t.viewportStart+Vo&&(t.viewportStart=t.selectedIndex-Vo+1)}function XP(e){if(!e.ghostEngine||!e.ghostGetContext)return;let t=e.input.buffer;e.activeGhost!==null&&!e.activeGhost.startsWith(t)&&(e.activeGhost=null);let n=e.ghostGetContext(),r=e.ghostEngine.getDeterministicGhost(t,n);if(r!==null){e.activeGhost=r;return}if(e.activeGhost=null,e.autocompleteState?.dropdownOpen)return;let s=t;e.ghostEngine.getGhost(t,n).then(i=>{i!==null&&e.input.buffer===s&&i.startsWith(s)&&i.length>s.length&&(e.activeGhost=i,e.repaint())}).catch(()=>{})}function ZP(e){let t=e.autocompleteState;if(!t?.dropdownOpen||t.candidates.length===0)return!1;let n=t.candidates[t.selectedIndex];if(!n)return!1;let r=e.input.buffer.slice(0,e.input.cursor),o=e.input.buffer.slice(e.input.cursor),s,i;if(t.trigger?.kind==="slash"){let l=/\/[A-Za-z_-]*$/.exec(r);s=l?r.length-l[0].length:e.input.cursor,i=n.value+(o.startsWith(" ")?"":" ")}else if(t.trigger?.kind==="flag"){let l=/--[a-z0-9-]*$/.exec(r);s=l?r.length-l[0].length:e.input.cursor,i=n.value+(o.startsWith(" ")?"":" ")}else{let l=r.search(/[^\s]*$/);s=l>=0?l:e.input.cursor,i=n.value}let a=K.replaceRange(e.input,{start:s,end:e.input.cursor},i);return a===e.input?!1:(e.input=a,t.dropdownOpen=!1,t.candidates=[],t.viewportStart=0,t.selectedIndex=0,_p(e),e.repaint(),!0)}function QP(e){let t=e.activeGhost;if(t===null||e.autocompleteState?.dropdownOpen||e.input.cursor!==e.input.buffer.length||!t.startsWith(e.input.buffer)||t.length<=e.input.buffer.length)return!1;let r=e.input.buffer+Ni(t.slice(e.input.buffer.length)),o=K.seed(r);return e.input=o,e.activeGhost=null,_p(e),e.repaint(),!0}import d8 from"chalk";import p8 from"string-width";function eM(e,t){if(t<=0)return"";let n=0;for(let r=0;r<e.length;r++)if(n+=p8(e[r]),n>t)return e.slice(0,r)+f.dim("\u2026");return e}function Ip(e,t,n,r){let o=t?">":" ",s=e.value,i=e.summary?` ${e.summary}`:"",a=`${s}${i}`,l=eM(a,n-4),c=` ${o} ${l}`;return t?d8.inverse(f.user(c)):f.meta(c)}function Pp(e,t){if(!e)return null;let n=e.trim();if(n.length===0)return null;let r=eM(n,Math.max(0,t-7));return r.length===0?null:f.dim(` \u21B3 ${r}`)}function tM(e){let t=e.pendingSubmissions.length,n=t>0?" "+f.dim(t===1?"[queued]":`[${t} queued]`):"",r=e.input.buffer.slice(0,e.input.cursor),o=bo(e.input.buffer,e.input.cursor),s=e.input.cursor>=e.input.buffer.length,i=s?"\u258F":e.input.buffer.slice(e.input.cursor,o),a=e.input.cursor<e.input.buffer.length?e.input.buffer.slice(o):"",l=e.formatInputBuffer?.(r)??r,c=e.formatInputBuffer?.(a)??a,u=e.caretVisible!==!1,d;u?d=s?f.caret(i):f.caret.inverse(i):s?d=" ":d=e.formatInputBuffer?.(i)??i;let p=e.autocompleteState,m="",g=e.activeGhost;if(g!==null&&!n&&e.input.buffer.length>0&&e.input.cursor===e.input.buffer.length&&g.startsWith(e.input.buffer)&&g.length>e.input.buffer.length&&!p?.dropdownOpen){let h=Ni(g.slice(e.input.buffer.length)),b=e.stdout.columns??80,y=V(Ne(e.promptTextFn())),S=V(Ne(r))+1,w=Math.max(0,b-y-S-1),T=ne(h,w,"");T.length>0&&(m=f.dim(T))}return e.promptTextFn()+l+d+c+m+n}function nM(e){let t=e.autocompleteState;if(!t?.dropdownOpen)return[];let n=e.stdout.columns||80;if(n<=40)return[];let r=Math.min(n-4,60),o=Math.min(t.candidates.length-t.viewportStart,Vo),s=[];for(let i=0;i<o;i++){let a=t.viewportStart+i,l=t.candidates[a];if(!l)continue;let c=Ip(l,a===t.selectedIndex,r,t.trigger?.kind),u=V(Ne(c)),d=Math.max(0,Math.ceil(u/n)-1);s.push(c);for(let p=0;p<d;p++)s.push("")}return s.reverse()}function rM(e){let t=e.autocompleteState;if(!t?.dropdownOpen)return null;let n=e.stdout.columns||80;if(n<=40)return null;let r=t.candidates[t.selectedIndex];if(!r)return null;let o=Math.min(n-4,80);return Pp(r.hint,o)??""}function oM(e){let{prevTopRow:t,frameTop:n,anchorFloor:r,anchorRow:o,lineCount:s,textLines:i,rows:a,extraRows:l,committedBand:c,committedBandBottomRow:u,committedBandPaintedRows:d}=e,p=t>1&&s<=n-r,m=Math.max(0,n-r),g=Math.max(1,a-1-l),h=Math.max(0,g-r),b=c.length>0&&o<=1&&u===n-1,y=b?[...c,...i]:i,S=b&&c.length>d,w=S||!p&&(y.length<=h||i.length<=h);return{fitsAboveFrame:p,room:m,overflowTargetBottom:g,maxBandModel:h,overflowPriorContiguous:b,overflowRun:y,overflowHasPending:S,useBandHold:w}}function yb(e,t){return e.length>t?e.slice(e.length-t):e}function sM(e,t){e.debugLog("commitAbove:enter",{textLen:t.length,anchorRow:e.anchorRow??null,committing:e.committing,topRow:e.logUpdate?.topRow??null});let n=P=>{e.scrollRegion?e.scrollRegion.withFullScrollRegion(P):P()};if(!e.armed||!e.logUpdate){n(()=>{e.stdout.write(t+`
|
|
1825
1825
|
`)});return}let r=Math.max(1,e.stdout.rows??24),o=t.endsWith(`
|
|
@@ -1856,7 +1856,7 @@ ${u}`}function ub(e,t){let n=EP[t.status];e.out.line(` ${n} ${f.bold(t.jobId)}
|
|
|
1856
1856
|
`,s=F8(r,n,{trim:!1,hard:!0,wordWrap:!1}).split(`
|
|
1857
1857
|
`);for(;s.length>0&&s[s.length-1]==="";)s.pop();return s}measure(t,n){let r=this.stream.columns??80,o=Math.max(1,e.wrapToPhysicalLines(t,r).length),s=Math.max(1,n);return{topRow:Math.max(1,s-o+1),lineCount:o}}render(t,n,r){let o=Math.max(1,n),s=Math.max(1,r??1),i=this.stream.columns??80,a=this.stream.isTTY===!0,l=e.wrapToPhysicalLines(t,i),c=Math.max(1,l.length),u=this.previousRawLineCount>c?this.previousRawLineCount-c:0,d=Math.max(0,o-c+1-s),p=Math.min(u,d),m=p>0?[...Array(p).fill(""),...l]:l,g=m.length,h=Math.max(1,o-g+1),b="";if(a&&(b+=xM),this.previousLineCount>0)for(let y=0;y<this.previousLineCount;y++){let S=this.previousTopRow+y;b+=Il(S,1)+vb}for(let y=0;y<g;y++){let S=h+y;b+=Il(S,1)+vb+(m[y]??"")}if(b+=Il(h+g-1,1),a&&(b+=RM),this.stream.isTTY)try{this.stream.write(N8)}catch{}try{this.stream.write(b)}catch{try{this.stream.isTTY&&this.stream.write(CM)}catch{}}if(v.NODE_ENV!=="production"&&g<c)throw new Error(`CupFrameRenderer invariant violation: lineCount (${g}) < rawLineCount (${c}). previousLineCount must cover at least previousRawLineCount \u2014 padded footprint must be \u2265 raw content size; see PR #557.`);this.previousTopRow=h,this.previousLineCount=g,this.previousRawLineCount=c}resetGeometry(){this.previousTopRow=0,this.previousLineCount=0,this.previousRawLineCount=0}clear(t=0){if(this.previousLineCount===0)return;let n="",r=this.stream.isTTY===!0;r&&(n+=xM);for(let o=0;o<this.previousLineCount;o++){let s=this.previousTopRow+o;n+=Il(s,1)+vb}n+=Il(Math.max(1,(this.stream.rows??24)-1-t),1),r&&(n+=RM);try{this.stream.write(n)}catch{}this.previousTopRow=0,this.previousLineCount=0,this.previousRawLineCount=0}done(){if(this.previousTopRow=0,this.previousLineCount=0,this.previousRawLineCount=0,this.stream.isTTY)try{this.stream.write(CM)}catch{}}};var Pl=null;function Ml(e){if(Pl!==null)throw new Error(`stdin claim conflict: '${Pl.name}' already holds the claim, '${e}' cannot acquire it concurrently.`);let t=!1,n={release(){t||(t=!0,Pl?.handle===n&&(Pl=null))}};return Pl={name:e,handle:n},n}async function AM(e,t){let n=Ml(e);try{return await t()}finally{n.release()}}function _M(e){if(!(!e.armed||e.suspended)){if(e.logUpdate)try{e.logUpdate.clear(e.scrollRegion?.getExtraRows()??0),e.logUpdate.done()}catch{}e.handleKeypress&&e.stdin.removeListener("keypress",e.handleKeypress);try{e.stdin.setRawMode(!1)}catch{}e.caretBlinkController.stop(),e.suspended=!0}}function IM(e){if(!(!e.armed||!e.suspended)){try{e.stdin.setRawMode(!0)}catch{}e.handleKeypress&&e.stdin.on("keypress",e.handleKeypress),e.suspended=!1,e.repaint(),e.caretBlinkController.start()}}async function PM(e){if(e.armed)throw new Error("TerminalCompositor: arm() called while already armed");if(!(!e.stdout.isTTY||!e.stdin.isTTY)){e.anchorRow=e.declaredAnchorRow,e.logUpdate||(e.logUpdate=new Mp(e.stdout)),e.stdinClaim=Ml("TerminalCompositor.arm"),e.wasRaw=e.stdin.isRaw??!1;try{e.stdin.setRawMode(!0)}catch{e.stdinClaim?.release(),e.stdinClaim=null,e.logUpdate=null,e.wasRaw=!1;return}try{e.stdout.write("\x1B[?2004h")}catch{}e.stdin.resume(),Wo(e.stdin),e.handleKeypress=(t,n)=>{let r=e.pasting?!1:e.caretBlinkController.resetVisible(),o=e.repaintCount;EM(e,t,n),r&&e.repaintCount===o&&e.repaint()},e.stdin.on("keypress",e.handleKeypress),e.armed=!0,e.canceled=!1,e.resizeUnsub=Ue.subscribe(()=>{e.armed&&e.repaint()}),e.resizeImmediateUnsub=Ue.subscribeImmediate(()=>{if(!e.armed)return;let t=e.stdout.rows??24;if(e.lastKnownRows>0&&t>e.lastKnownRows){let n=e.scrollRegion?.getExtraRows()??0,r=e.logUpdate?.topRow??0,o=e.committedBand.length>0?e.committedBandTopRow:0,s=[r,o].filter(l=>l>0),i=s.length>0?Math.min(...s):0,a=Math.max(1,e.lastKnownRows-1-n);i>0&&i<=a&&(e.pendingResizeErase={top:i,bottom:a})}else e.pendingResizeErase=null;e.logUpdate?.resetGeometry?.()}),e.repaint(),e.caretBlinkController.start()}}function MM(e){if(e.spinnerController.dispose(),e.caretBlinkController.stop(),!e.armed){e.resetState();return}if(e.handleKeypress&&(e.stdin.removeListener("keypress",e.handleKeypress),e.handleKeypress=null),e.resizeUnsub&&(e.resizeUnsub(),e.resizeUnsub=null),e.resizeImmediateUnsub&&(e.resizeImmediateUnsub(),e.resizeImmediateUnsub=null),B8(e),e.logUpdate)try{e.logUpdate.clear(e.scrollRegion?.getExtraRows()??0),e.logUpdate.done()}catch{}if(e.stdout.isTTY&&e.stdin.isTTY){try{e.stdout.write("\x1B[?2004l")}catch{}try{e.stdin.setRawMode(e.wasRaw)}catch{}}e.stdinClaim&&(e.stdinClaim.release(),e.stdinClaim=null),e.armed=!1,e.resetState(),e.ghostEngine?.dispose()}function B8(e){let t=e.committedBand.length-e.committedBandPaintedRows;if(t<=0)return;let n=e.committedBand.slice(0,t),r=Math.max(1,e.stdout.rows??24),o=Math.max(e.anchorRow??1,1),s=()=>{let i=Math.max(1,r-o+1);for(let a=0;a<n.length;a+=i){let l=n.slice(a,Math.min(a+i,n.length)),c=l.map((u,d)=>kt(o+d,u)).join("");e.stdout.write(`${c}\x1B[${r};1H${`
|
|
1858
1858
|
`.repeat(l.length)}`)}};try{e.scrollRegion?e.scrollRegion.withFullScrollRegion(s):s()}catch{}}function OM(e){e.overlay="",e.input=K.seed(""),e.queued=!1,e.pendingSubmissions=[],e.canceled=!1,e.backgrounded=!1,e.softStopped=!1,e.paused=!1,e.activeGhost=null,e.anchorRow=void 0,e.hasCommitted=!1,e.clearCommittedBand(),e.commitInFlight=!1,e.pendingResizeErase=null,e.lastKnownRows=0,e.pickerController=null,e.inputMode="streaming",e.attachments=[],e.pasting=!1,e.pasteStartBufferLen=0,e.pasteStartCursor=0,e.pasteRegistry.clear(),e.clipboardFailureMsg=null,e.autocompleteState?.reset(),e.resizeUnsub&&(e.resizeUnsub(),e.resizeUnsub=null),e.resizeImmediateUnsub&&(e.resizeImmediateUnsub(),e.resizeImmediateUnsub=null)}var Ui=class{stdout;stdin;onCancel;onSoftStop;softStopped=!1;onBackground;onPauseInterrupt;onShiftTab;promptTextFn;history;autocompleteState;formatInputBuffer;scrollRegion;anchorRow;declaredAnchorRow;onSubmit;attachments=[];pasting=!1;pasteStartBufferLen=0;pasteStartCursor=0;pasteRegistry=new Map;clipboardInFlight=!1;clipboardFailureMsg=null;inputMode="streaming";pickerController=null;pickerSavedMode="streaming";armed=!1;suspended=!1;canceled=!1;backgrounded=!1;paused=!1;wasRaw=!1;stdinClaim=null;logUpdate=null;overlay="";input=K.seed("");queued=!1;pendingSubmissions=[];handleKeypress=null;resizeUnsub=null;resizeImmediateUnsub=null;spinnerController;caretBlinkController;repaintCount=0;committing=!1;hasCommitted=!1;committedBand=[];committedBandTopRow=0;committedBandBottomRow=0;committedBandPaintedRows=0;lastKnownRows=0;pendingResizeErase=null;commitInFlight=!1;debugCompositor=!!v.AFK_DEBUG_COMPOSITOR;ghostEngine;ghostGetContext;activeGhost=null;debugLog(t,n={}){if(!this.debugCompositor)return;let r=process.hrtime.bigint(),o=Object.entries(n).map(([s,i])=>{let a=typeof i=="string"?JSON.stringify(i.length>60?i.slice(0,57)+"...":i):String(i);return`${s}=${a}`}).join(" ");process.stderr.write(`[compositor] t=${r} ${t}${o?" "+o:""}
|
|
1859
|
-
`)}constructor(t){this.stdout=t.stdout,this.stdin=t.stdin,this.onCancel=t.onCancel,this.onSoftStop=t.onSoftStop,this.onBackground=t.onBackground,this.onPauseInterrupt=t.onPauseInterrupt,this.onShiftTab=t.onShiftTab;let n=t.promptText;if(typeof n=="function")this.promptTextFn=n;else if(typeof n=="string")this.promptTextFn=()=>n;else{let r=" "+f.dim("\u23AF")+" ";this.promptTextFn=()=>r}this.history=t.history,this.autocompleteState=t.autocompleteState,this.formatInputBuffer=t.formatInputBuffer,this.scrollRegion=t.scrollRegion,this.spinnerController=new Ep({captureMode:t.captureMode??!1,onTick:()=>this.repaint()}),this.caretBlinkController=new Tp({enabled:t.caretBlink??!1,captureMode:t.captureMode??!1,intervalMs:t.caretBlinkIntervalMs??530,onTick:()=>this.repaint()}),this.onSubmit=t.onSubmit,this.anchorRow=t.anchorRow,this.declaredAnchorRow=t.anchorRow,this.ghostEngine=t.suggest?.engine,this.ghostGetContext=t.suggest?.getContext}isArmed(){return this.armed}setAnchorRow(t){this.anchorRow=t,this.declaredAnchorRow=t}suspendInput(){_M(this)}resumeInput(){IM(this)}setOnSubmit(t){this.onSubmit=t??void 0}setOnCancel(t){this.onCancel=t??void 0}getOnCancel(){return this.onCancel}setOnSoftStop(t){this.onSoftStop=t??void 0}setOnBackground(t){this.onBackground=t??void 0}setOnShiftTab(t){this.onShiftTab=t??void 0}enterPickerMode(t){pM(this,t)}exitPickerMode(){mM(this)}repaintPicker(){fM(this)}setInputMode(t){gM(this,t)}getInputMode(){return hM(this)}async arm(){return PM(this)}disarm(){MM(this)}setOverlay(t){t!==this.overlay&&(this.debugLog("setOverlay",{framesLen:t.length,anchorRow:this.anchorRow??null}),this.overlay=t,this.repaint())}setSpinner(t){this.stdout.isTTY&&this.spinnerController.set(t)}commitAbove(t){sM(this,t)}clearCommittedBand(){Al(this)}flushResizeGhostErase(){aM(this)}resetCommittedBand(){iM(this)}repositionCommittedBand(t,n,r){lM(this,t,n,r)}getBuffer(){return UP(this)}getPendingCount(){return this.pendingSubmissions.length}getAttachments(){return[...this.attachments]}get caretVisible(){return this.caretBlinkController.visible}renderInputLine(){return tM(this)}updateAutocomplete(){_p(this)}updateGhost(){XP(this)}renderDropdownRows(){return nM(this)}renderHintRow(){return rM(this)}repaint(){this.repaintCount++,dM(this)}clearScreen(){this.logUpdate?.resetGeometry?.(),this.stdout.write("\x1B[H\x1B[2J"),this.repaint()}resetState(){OM(this)}applyEdit(t){return kM(this,t)}applyDropdownSelection(){return ZP(this)}applyGhostAccept(){return QP(this)}};import W8 from"chalk";var K8=/(?<=\s|^)(\/[A-Za-z][\w:-]*)(?=\s|$)/g,G8=/(?<=\s|^)(@[~\w./-]*)(?=\s|$)/g,q8=/\[Pasted text #[0-9a-f]+ \+\d+ (?:lines|chars)\]/g,$M={mint:f.mint};function z8(e){let t=$M[e];if(t)return t;let n=e.lastIndexOf(":");if(n>=0){let r=e.slice(n+1),o=$M[r];if(o)return o}return null}function ro(e,t){return W8.level===0?e:e.replace(K8,o=>{let s=o.slice(1);return t.has(s)?(z8(s)??f.brand)(o):f.meta(o)}).replace(G8,o=>f.fileRef(o)).replace(q8,o=>f.meta(o))}q();import{pathToFileURL as J8}from"node:url";var V8="\x1B]8;;\x1B\\",Y8=new Set(["iterm2","wezterm","kitty","vscode","ghostty","windows-terminal","konsole","gnome-terminal","alacritty"]),X8=5e3;function Z8(e=process.env,t=process.stdout.isTTY===!0){let n=e.FORCE_HYPERLINK;if(n!==void 0&&n.length>0)return n!=="0"&&n.toLowerCase()!=="false";if(!t||e.CI!==void 0&&e.CI.length>0)return!1;let r=Tl(e);if(!Y8.has(r))return!1;if(r==="gnome-terminal"&&e.VTE_VERSION!==void 0){let o=Number.parseInt(e.VTE_VERSION,10);if(!Number.isFinite(o)||o<X8)return!1}return!0}var kb;function Op(){return kb===void 0&&(kb=Z8()),kb}function Q8(e,t){return`\x1B]8;;${t}\x1B\\${e}${V8}`}function $p(e,t){try{return Q8(e,J8(t).href)}catch{return e}}var DM=/[\x00-\x1F\x7F-\x9F]/g;function ut(e){return Ne(e).replace(DM," ").replace(/ {2,}/g," ").trim()}function Eb(e){return Ne(e).replace(DM," ")}function Ol(e){let t=/[a-z][a-z0-9+.-]*:\/\/[^\s<>\"`]+/gi,n="",r=0;for(let o of e.matchAll(t)){let s=o[0]??"",i=o.index??r;n+=LM(e.slice(r,i)),n+=s,r=i+s.length}return n+=LM(e.slice(r)),n}function LM(e){let t=Op();return e.replace(/\/(?:[^/\s,)]+\/){2,}([^/\s,)]+)/g,(n,r)=>t?$p(r,n):r)}function e5(e){let t=/^(\s*[("]?\s*)cd\s+\S+\s+&&\s+(?!cd\s)(.+)$/.exec(e);return t?(t[1]??"")+(t[2]??""):e}var FM=60;function Tb(e,t){let n=e.trim().replace(/^\((.*)\)$/s,"$1"),r;try{r=JSON.parse(n)}catch{return e}if(!r||typeof r!="object")return e;let o=r;for(let s of t){let i=o[s];if(typeof i=="string"&&i.length>0){let a=ut(i);if(a.length===0)continue;return`(${a.length>FM?ne(a,FM,"\u2026"):a})`}}return e}function NM(e,t){if(e==="bash"||e==="Bash")return e5(t);if(e==="compose"||e==="Compose"){let n=t.trim().replace(/^\((.*)\)$/s,"$1");try{let r=JSON.parse(n);if(r&&typeof r=="object"){let o=Array.isArray(r.nodes)?r.nodes.length:void 0,s=Array.isArray(r.edges)?r.edges.length:0;if(o!==void 0){let i=`${o} node${o===1?"":"s"}`,a=s>0?`, ${s} edge${s===1?"":"s"}`:"";return`(${i}${a})`}}}catch{}}return e==="agent"||e==="Agent"?Tb(t,["id_prefix","prompt"]):e==="Task"?Tb(t,["description","prompt"]):e==="skill"||e==="Skill"?Tb(t,["name","arguments"]):e==="ask_question"?t5(t):t}function t5(e){let t=e.trim().replace(/^\((.*)\)$/s,"$1");try{let n=JSON.parse(t);if(!n||typeof n!="object")return e;let r=n,o=typeof r.type=="string"?r.type:"text";if(o==="choice"||o==="multi_choice"){let s=r.choices,i=Array.isArray(s)?s.length:0;return i>0?`(${o}: ${i} option${i===1?"":"s"})`:`(${o})`}return`(${o})`}catch{return e}}function n5(e){return e.replace(/[\r\n]+/g," ")}var r5={"(":")","{":"}","[":"]"};function BM(e,t,n="\u2026"){let r=e.charAt(0),o=r5[r];return!(o&&e.endsWith(o)&&e.length>=2)||V(e)<=t?ne(e,t,n):t<3?t>=2?r+o:ne(e,t,n):ne(e,t-1,n)+o}function yr(e,t){let n=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/s.exec(e);if(n){let r=n[1],o=Ol(NM(r,n[2]??"")),s=_n(r),{color:i,glyph:a}=Ti(r),l=Ch(s),c=l?` [${l}]`:"";if(t!==void 0){let d=(a+" ").length+r.length+c.length,p=Math.max(1,t-d);o=BM(o,p)}o=n5(o);let u=i(a+" ")+i.bold(r)+f.toolArg(o);return l?u+f.dim(c):u}return f.chrome("\u25CF ")+f.toolArg(e)}q();var UM=8,Dp=30;function o5(){let e=v.AFK_DIFF_LINES;if(e===void 0)return Dp;let t=e.trim();if(!/^\d+$/.test(t))return Dp;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:Dp}function s5(){let e=v.AFK_SHOW_DIFFS;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"}function i5(e){let t=f.diffAdd(`+${e.addedLines}`),n=f.diffRemove(`-${e.removedLines}`),r=e.hunks.length,o=f.dim(`across ${r} hunk${r===1?"":"s"}`);return`${t} ${n} ${o}`}var a5=/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;function l5(e){let t=Ne(e.text).replace(a5,"");return e.kind==="+"?f.diffAdd("+ "+t):e.kind==="-"?f.diffRemove("- "+t):f.dim(" "+t)}var Rb=new WeakMap;function br(e,t,n){if(s5())return[];if(e.hunks.length===0)return[];let r=t==="overlay"?UM:o5(),o=t+"|"+n+"|"+r,s=Rb.get(e);if(s!==void 0){let m=s.get(o);if(m!==void 0)return m}let i=[];i.push(n+i5(e));let a=[];for(let m of e.hunks){let g=`@@ -${m.oldStart},${m.oldLines} +${m.newStart},${m.newLines} @@`;a.push({kind:"header",text:f.diffHunk(g)});for(let h of m.lines)a.push({kind:"body",text:l5(h)})}if(r===0){for(let m of a)i.push(n+m.text);return xb(e,o,i),i}let l=0;for(let m of a)m.kind==="body"&&l++;if(l<=r){for(let m of a)i.push(n+m.text);return xb(e,o,i),i}let c=0;for(let m of a)m.kind==="header"?i.push(n+m.text):c<r&&(i.push(n+m.text),c++);let u=l-r,d=`line${u===1?"":"s"}`,p=t==="flush"?" (set AFK_DIFF_LINES=0 to expand)":"";return i.push(n+f.dim(`\u2026 +${u} more diff ${d}${p}`)),xb(e,o,i),i}function xb(e,t,n){let r=Rb.get(e);r===void 0&&(r=new Map,Rb.set(e,r)),r.set(t,n)}var c5=f.success("\u2713"),u5=f.error("\u2717");function oo(e){return e?u5:c5}var $l=3,jM=2,HM=3;function WM(e){switch(_n(e)){case"read":return"Reading\u2026";case"write":return"Writing\u2026";case"web":return"Fetching\u2026";case"shell":return"Running\u2026";default:return"Running\u2026"}}function d5(e,t){return e?e==="grep"||e==="Grep"?t===1?"match":"matches":e==="glob"||e==="Glob"?t===1?"path":"paths":t===1?"line":"lines":t===1?"line":"lines"}function wr(e,t,n=60,r){let o=e.isError?f.error:f.dim,s=t??v.HOME??"___NOHOME___";if(e.display!==void 0&&!e.isError)return o(e.display);if(e.persistedPath){let a=e.persistedPath.startsWith(s)?"~"+e.persistedPath.slice(s.length):e.persistedPath,l=Op()?$p(a,e.persistedPath):a;return o(`saved \u2192 ${l}`)}if(e.lineCount!==void 0&&e.lineCount>1)return o(`${e.lineCount} ${d5(r,e.lineCount)}`);let i=e.content.length>n?e.content.slice(0,n-3)+"\u2026":e.content;return o(ut(i))}q();function Dl(e,t){if(e.length<=t)return e;let n=e.slice(0,t),r=e.slice(t),o=GM(r);return[...n,{kind:"overflow",count:r.length,text:o}]}function p5(e,t){return t<=1||e.endsWith("s")||/(sh|ch|x|z)$/i.test(e)?e:e+"s"}var m5=5,KM=60;function GM(e){let t=new Map,n=0;for(let s of e)s.kind==="group"?(t.set(s.toolName,(t.get(s.toolName)??0)+s.entries.length),n+=s.entries.length):(t.set(s.toolName,(t.get(s.toolName)??0)+1),n+=1);if(n===0)return"";if(e.length>0&&e.every(s=>Ye.has(s.toolName))&&new Set(e.map(s=>s.toolName)).size===1){let s=[],i=!1;for(let a of e){let c=(a.kind==="group"?a.label:a.toolInput).trim();if(!c.startsWith("(")||!c.endsWith(")")){i=!0;break}let u=c.slice(1,-1),d=ut(u);if(!d){i=!0;break}let p=d.length>KM?d.slice(0,KM-1)+"\u2026":d,m=a.kind==="group"?a.entries.length:1;s.push({display:p,entries:m})}if(!i&&s.length>0){let a=s.slice(0,m5),l=a.map(({display:p,entries:m})=>m>1?`${p} \xD7${m}`:p),c=a.reduce((p,m)=>p+m.entries,0),u=n-c,d=l.join(", ")+(u>0?` (+${u})`:"");return`\u2026 +${n} more: ${d}`}}let o=[];for(let[s,i]of t)o.push(`${i} ${p5(s,i)}`);return`\u2026 +${n} (${o.join(", ")})`}function Lp(e,t=ln()){return e.map((n,r)=>({sibling:n,connector:r===e.length-1?t.lastConnector:t.midConnector}))}function Cb(e,t){return t?[...e,{kind:"resultSummary",summary:t}]:e}function Ab(e){if(e.length===0)return[];let t=new Map;for(let o of e){let s=qM(o),i=t.get(s);i||(i=[],t.set(s,i)),i.push(o)}let n=[],r=new Set;for(let o of e){let s=qM(o),i=t.get(s);i.length>=f5(o.toolName)?r.has(s)||(n.push({kind:"group",toolName:o.toolName,label:Ye.has(o.toolName)?o.toolInput:"",entries:i}),r.add(s)):n.push(o)}return n}function _b(e){let t=e.entries.length,n=e.entries.filter(a=>a.result),r=n.filter(a=>a.result.isError),o=n.length,s;if(r.length>0){let a=o-r.length,l=[];a>0&&l.push(`${a} ok`),l.push(`${r.length} error${r.length===1?"":"s"}`),s=l.join(", ")}else o===t?s=`${t} done`:o===0?s=`${t} running`:s=`${o}/${t} done`;return yr(e.toolName+e.label)+f.dim(` \xD7${t} \u2014 ${s}`)}function qM(e){return Ye.has(e.toolName)?e.toolName+"::"+e.toolInput:e.toolName}function f5(e){return Ye.has(e)?jM:HM}function zM(e,t,n,r){return e>0||t?ji([...n,!0],r):ji(n,r)}function JM(e,t){return!Ye.has(e.toolName)||e.headerEmitted!==!0?!1:(t.get(e.toolUseId)??[]).every(r=>r.kind==="tool"&&JM(r,t))}function Fp(e,t,n,r=Q(),o=[],s=ln(),i){let a=ji(o,s),l=Ll(a,s),c=e.filter(h=>h.kind==="text"),u=e.filter(h=>h.kind==="tool").filter(h=>!JM(h,t)),d=Ab(u),p=Dl(d,$l),m=Lp(p,s);for(let{sibling:h,connector:b}of m){let y=f.dim(b),S=b===s.lastConnector;if(h.kind==="overflow")n.push(Ie(l+y+f.dim(h.text),r));else if(h.kind==="group")n.push(Ie(l+y+_b(h),r));else if(h.kind==="resultSummary")n.push(Ie(l+y+f.dim(h.summary),r));else{let w=h,T=t.get(w.toolUseId);if(Ye.has(w.toolName)&&T&&T.length>0){w.headerEmitted?n.push(Ie(l+y,r)):n.push(Ie(l+y+w.prefix,r));let x=i??S;if(Fp(T,t,n,r,[...o,x],s,S),w.thinkingTail){let C=Ll(ji([...o,x],s),s);n.push(Ie(C+f.thinking("\u2307 "+ut(w.thinkingTail)),r))}}else if(!(Ye.has(w.toolName)&&w.headerEmitted))if(w.result){if(n.push(Ie(l+y+w.prefix+f.dim(" \u2014 ")+oo(w.result.isError)+" "+wr(w.result,void 0,60,w.toolName),r)),w.diff&&!w.result.isError){let x=l+(S?s.spineClosed:f.dim(s.spine))+" ";for(let C of br(w.diff,"overlay",x))n.push(Ie(C,r))}}else{n.push(Ie(l+y+w.prefix,r));let x=l+(S?s.spineClosed:f.dim(s.spine))+" ";w.thinkingTail?n.push(Ie(x+f.thinking("\u2307 "+ut(w.thinkingTail)),r)):n.push(Ie(x+f.dim(WM(w.toolName)),r))}}}let g=zM(u.length,!1,o,s);for(let h of c)for(let b of Ib(h.text,g,s))n.push(Ie(b,r))}function Fl(e,t,n,r,o=Q(),s=[],i=ln(),a){let l=ji(s,i),c=Ll(l,i),u=[],d=e.filter(S=>S.kind==="text"),p=e.filter(S=>S.kind==="tool"),m=Ab(p),g=Dl(m,$l),h=Cb(g,r),b=Lp(h,i);for(let{sibling:S,connector:w}of b){let T=f.dim(w),x=w===i.lastConnector;if(S.kind==="overflow")u.push(Ie(c+T+f.dim(S.text),o));else if(S.kind==="resultSummary")u.push(Ie(c+T+f.dim(S.summary),o));else if(S.kind==="group")u.push(Ie(c+T+_b(S),o));else{let C=S,R=t.get(C.toolUseId);if(Ye.has(C.toolName)&&R&&R.length>0){if(C.headerEmitted){let $=C.toolInput?`${C.toolName} ${ut(C.toolInput)}`:C.toolName;u.push(Ie(c+T+f.dim("\u21B3 "+$),o))}else u.push(Ie(c+T+C.prefix,o));let k=a??x;u.push(...Fl(R,t,n,void 0,o,[...s,k],i,x))}else if(C.result){if(u.push(Ie(c+T+C.prefix+f.dim(" \u2014 ")+oo(C.result.isError)+" "+wr(C.result,n,60,C.toolName),o)),C.diff&&!C.result.isError){let k=c+(x?i.spineClosed:f.dim(i.spine))+" ";for(let $ of br(C.diff,"flush",k))u.push(Ie($,o))}}else u.push(Ie(c+T+C.prefix,o))}}let y=zM(p.length,r!=null,s,i);for(let S of d)for(let w of Ib(S.text,y,i))u.push(Ie(w,o));return u}function Nl(e,t,n,r,o=[]){let s=ln(),i=t.filter(h=>h.kind==="tool"),l=i.filter(h=>h.result).reduce((h,b)=>h+(b.result.lineCount??0),0),c=[];i.length>$l&&(c.push(`${i.length} tools`),l>0&&c.push(`${l} lines`));let u=f.dim(s.spine.repeat(o.length)),d=o,p=f.dim(s.turnRoot),m=c.length>0?u+p+e.prefix+f.dim(" \u2014 "+c.join(" \xB7 ")):u+p+e.prefix,g=Fl(t,n,r,e.agentResultSummary,Q(),d,s);return[m,...g].join(`
|
|
1859
|
+
`)}constructor(t){this.stdout=t.stdout,this.stdin=t.stdin,this.onCancel=t.onCancel,this.onSoftStop=t.onSoftStop,this.onBackground=t.onBackground,this.onPauseInterrupt=t.onPauseInterrupt,this.onShiftTab=t.onShiftTab;let n=t.promptText;if(typeof n=="function")this.promptTextFn=n;else if(typeof n=="string")this.promptTextFn=()=>n;else{let r=" "+f.dim("\u23AF")+" ";this.promptTextFn=()=>r}this.history=t.history,this.autocompleteState=t.autocompleteState,this.formatInputBuffer=t.formatInputBuffer,this.scrollRegion=t.scrollRegion,this.spinnerController=new Ep({captureMode:t.captureMode??!1,onTick:()=>this.repaint()}),this.caretBlinkController=new Tp({enabled:t.caretBlink??!1,captureMode:t.captureMode??!1,intervalMs:t.caretBlinkIntervalMs??530,onTick:()=>this.repaint()}),this.onSubmit=t.onSubmit,this.anchorRow=t.anchorRow,this.declaredAnchorRow=t.anchorRow,this.ghostEngine=t.suggest?.engine,this.ghostGetContext=t.suggest?.getContext}isArmed(){return this.armed}setAnchorRow(t){this.anchorRow=t,this.declaredAnchorRow=t}suspendInput(){_M(this)}resumeInput(){IM(this)}setOnSubmit(t){this.onSubmit=t??void 0}setOnCancel(t){this.onCancel=t??void 0}getOnCancel(){return this.onCancel}setOnSoftStop(t){this.onSoftStop=t??void 0}setOnBackground(t){this.onBackground=t??void 0}setOnShiftTab(t){this.onShiftTab=t??void 0}enterPickerMode(t){pM(this,t)}exitPickerMode(){mM(this)}repaintPicker(){fM(this)}setInputMode(t){gM(this,t)}getInputMode(){return hM(this)}async arm(){return PM(this)}disarm(){MM(this)}setOverlay(t){t!==this.overlay&&(this.debugLog("setOverlay",{framesLen:t.length,anchorRow:this.anchorRow??null}),this.overlay=t,this.repaint())}setSpinner(t){this.stdout.isTTY&&this.spinnerController.set(t)}commitAbove(t){sM(this,t)}clearCommittedBand(){Al(this)}flushResizeGhostErase(){aM(this)}resetCommittedBand(){iM(this)}repositionCommittedBand(t,n,r){lM(this,t,n,r)}getBuffer(){return UP(this)}getPendingCount(){return this.pendingSubmissions.length}getAttachments(){return[...this.attachments]}get caretVisible(){return this.caretBlinkController.visible}renderInputLine(){return tM(this)}updateAutocomplete(){_p(this)}updateGhost(){XP(this)}renderDropdownRows(){return nM(this)}renderHintRow(){return rM(this)}repaint(){this.repaintCount++,dM(this)}clearScreen(){this.logUpdate?.resetGeometry?.(),this.stdout.write("\x1B[H\x1B[2J"),this.repaint()}resetState(){OM(this)}applyEdit(t){return kM(this,t)}applyDropdownSelection(){return ZP(this)}applyGhostAccept(){return QP(this)}};import W8 from"chalk";var K8=/(?<=\s|^)(\/[A-Za-z][\w:-]*)(?=\s|$)/g,G8=/(?<=\s|^)(@[~\w./-]*)(?=\s|$)/g,q8=/\[Pasted text #[0-9a-f]+ \+\d+ (?:lines|chars)\]/g,$M={mint:f.mint};function z8(e){let t=$M[e];if(t)return t;let n=e.lastIndexOf(":");if(n>=0){let r=e.slice(n+1),o=$M[r];if(o)return o}return null}function ro(e,t){return W8.level===0?e:e.replace(K8,o=>{let s=o.slice(1);return t.has(s)?(z8(s)??f.brand)(o):f.meta(o)}).replace(G8,o=>f.fileRef(o)).replace(q8,o=>f.meta(o))}q();import{pathToFileURL as J8}from"node:url";var V8="\x1B]8;;\x1B\\",Y8=new Set(["iterm2","wezterm","kitty","vscode","ghostty","windows-terminal","konsole","gnome-terminal","alacritty"]),X8=5e3;function Z8(e=process.env,t=process.stdout.isTTY===!0){let n=e.FORCE_HYPERLINK;if(n!==void 0&&n.length>0)return n!=="0"&&n.toLowerCase()!=="false";if(!t||e.CI!==void 0&&e.CI.length>0)return!1;let r=Tl(e);if(!Y8.has(r))return!1;if(r==="gnome-terminal"&&e.VTE_VERSION!==void 0){let o=Number.parseInt(e.VTE_VERSION,10);if(!Number.isFinite(o)||o<X8)return!1}return!0}var kb;function Op(){return kb===void 0&&(kb=Z8()),kb}function Q8(e,t){return`\x1B]8;;${t}\x1B\\${e}${V8}`}function $p(e,t){try{return Q8(e,J8(t).href)}catch{return e}}var DM=/[\x00-\x1F\x7F-\x9F]/g;function ut(e){return Ne(e).replace(DM," ").replace(/ {2,}/g," ").trim()}function Eb(e){return Ne(e).replace(DM," ")}function Ol(e){let t=/[a-z][a-z0-9+.-]*:\/\/[^\s<>\"`]+/gi,n="",r=0;for(let o of e.matchAll(t)){let s=o[0]??"",i=o.index??r;n+=LM(e.slice(r,i)),n+=s,r=i+s.length}return n+=LM(e.slice(r)),n}function LM(e){let t=Op();return e.replace(/\/(?:[^/\s,)]+\/){2,}([^/\s,)]+)/g,(n,r)=>t?$p(r,n):r)}function e5(e){let t=/^(\s*[("]?\s*)cd\s+\S+\s+&&\s+(?!cd\s)(.+)$/.exec(e);return t?(t[1]??"")+(t[2]??""):e}var FM=60;function Tb(e,t){let n=e.trim().replace(/^\((.*)\)$/s,"$1"),r;try{r=JSON.parse(n)}catch{return e}if(!r||typeof r!="object")return e;let o=r;for(let s of t){let i=o[s];if(typeof i=="string"&&i.length>0){let a=ut(i);if(a.length===0)continue;return`(${a.length>FM?ne(a,FM,"\u2026"):a})`}}return e}function NM(e,t){if(e==="bash"||e==="Bash")return e5(t);if(e==="compose"||e==="Compose"){let n=t.trim().replace(/^\((.*)\)$/s,"$1");try{let r=JSON.parse(n);if(r&&typeof r=="object"){let o=Array.isArray(r.nodes)?r.nodes.length:void 0,s=Array.isArray(r.edges)?r.edges.length:0;if(o!==void 0){let i=`${o} node${o===1?"":"s"}`,a=s>0?`, ${s} edge${s===1?"":"s"}`:"";return`(${i}${a})`}}}catch{}}return e==="agent"||e==="Agent"?Tb(t,["id_prefix","prompt"]):e==="Task"?Tb(t,["description","prompt"]):e==="skill"||e==="Skill"?Tb(t,["name","arguments"]):e==="ask_question"?t5(t):t}function t5(e){let t=e.trim().replace(/^\((.*)\)$/s,"$1");try{let n=JSON.parse(t);if(!n||typeof n!="object")return e;let r=n,o=typeof r.type=="string"?r.type:"text";if(o==="choice"||o==="multi_choice"){let s=r.choices,i=Array.isArray(s)?s.length:0;return i>0?`(${o}: ${i} option${i===1?"":"s"})`:`(${o})`}return`(${o})`}catch{return e}}function n5(e){return e.replace(/[\r\n]+/g," ")}var r5={"(":")","{":"}","[":"]"};function BM(e,t,n="\u2026"){let r=e.charAt(0),o=r5[r];return!(o&&e.endsWith(o)&&e.length>=2)||V(e)<=t?ne(e,t,n):t<3?t>=2?r+o:ne(e,t,n):ne(e,t-1,n)+o}function yr(e,t){let n=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/s.exec(e);if(n){let r=n[1],o=Ol(NM(r,n[2]??"")),s=_n(r),{color:i,glyph:a}=Ti(r),l=Ch(s),c=l?` [${l}]`:"";if(t!==void 0){let d=(a+" ").length+r.length+c.length,p=Math.max(1,t-d);o=BM(o,p)}o=n5(o);let u=i(a+" ")+i.bold(r)+f.toolArg(o);return l?u+f.dim(c):u}return f.chrome("\u25CF ")+f.toolArg(e)}q();var UM=8,Dp=30;function o5(){let e=v.AFK_DIFF_LINES;if(e===void 0)return Dp;let t=e.trim();if(!/^\d+$/.test(t))return Dp;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:Dp}function s5(){let e=v.AFK_SHOW_DIFFS;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"}function i5(e){let t=f.diffAdd(`+${e.addedLines}`),n=f.diffRemove(`-${e.removedLines}`),r=e.hunks.length,o=f.dim(`across ${r} hunk${r===1?"":"s"}`);return`${t} ${n} ${o}`}var a5=/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;function l5(e){let t=Ne(e.text).replace(a5,"");return e.kind==="+"?f.diffAdd("+ "+t):e.kind==="-"?f.diffRemove("- "+t):f.dim(" "+t)}var Rb=new WeakMap;function br(e,t,n){if(s5())return[];if(e.hunks.length===0)return[];let r=t==="overlay"?UM:o5(),o=t+"|"+n+"|"+r,s=Rb.get(e);if(s!==void 0){let m=s.get(o);if(m!==void 0)return m}let i=[];i.push(n+i5(e));let a=[];for(let m of e.hunks){let g=`@@ -${m.oldStart},${m.oldLines} +${m.newStart},${m.newLines} @@`;a.push({kind:"header",text:f.diffHunk(g)});for(let h of m.lines)a.push({kind:"body",text:l5(h)})}if(r===0){for(let m of a)i.push(n+m.text);return xb(e,o,i),i}let l=0;for(let m of a)m.kind==="body"&&l++;if(l<=r){for(let m of a)i.push(n+m.text);return xb(e,o,i),i}let c=0;for(let m of a)m.kind==="header"?i.push(n+m.text):c<r&&(i.push(n+m.text),c++);let u=l-r,d=`line${u===1?"":"s"}`,p=t==="flush"?" (set AFK_DIFF_LINES=0 to expand)":"";return i.push(n+f.dim(`\u2026 +${u} more diff ${d}${p}`)),xb(e,o,i),i}function xb(e,t,n){let r=Rb.get(e);r===void 0&&(r=new Map,Rb.set(e,r)),r.set(t,n)}var c5=f.success("\u2713"),u5=f.error("\u2717");function oo(e){return e?u5:c5}var $l=3,jM=2,HM=3;function WM(e){switch(_n(e)){case"read":return"Reading\u2026";case"write":return"Writing\u2026";case"web":return"Fetching\u2026";case"shell":return"Running\u2026";default:return"Running\u2026"}}function d5(e,t){return e?e==="grep"||e==="Grep"?t===1?"match":"matches":e==="glob"||e==="Glob"?t===1?"path":"paths":t===1?"line":"lines":t===1?"line":"lines"}function wr(e,t,n=60,r){let o=e.isError?f.error:f.dim,s=t??v.HOME??"___NOHOME___";if(e.display!==void 0&&!e.isError)return o(e.display);if(e.persistedPath){let a=e.persistedPath.startsWith(s)?"~"+e.persistedPath.slice(s.length):e.persistedPath,l=Op()?$p(a,e.persistedPath):a;return o(`saved \u2192 ${l}`)}if(e.lineCount!==void 0&&e.lineCount>1)return o(`${e.lineCount} ${d5(r,e.lineCount)}`);let i=e.content.length>n?e.content.slice(0,n-3)+"\u2026":e.content;return o(ut(i))}q();function Dl(e,t){if(e.length<=t)return e;let n=e.length-t,r=e.slice(0,n),o=e.slice(n),s=GM(r);return[{kind:"overflow",count:r.length,text:s},...o]}function p5(e,t){return t<=1||e.endsWith("s")||/(sh|ch|x|z)$/i.test(e)?e:e+"s"}var m5=5,KM=60;function GM(e){let t=new Map,n=0;for(let s of e)s.kind==="group"?(t.set(s.toolName,(t.get(s.toolName)??0)+s.entries.length),n+=s.entries.length):(t.set(s.toolName,(t.get(s.toolName)??0)+1),n+=1);if(n===0)return"";if(e.length>0&&e.every(s=>Ye.has(s.toolName))&&new Set(e.map(s=>s.toolName)).size===1){let s=[],i=!1;for(let a of e){let c=(a.kind==="group"?a.label:a.toolInput).trim();if(!c.startsWith("(")||!c.endsWith(")")){i=!0;break}let u=c.slice(1,-1),d=ut(u);if(!d){i=!0;break}let p=d.length>KM?d.slice(0,KM-1)+"\u2026":d,m=a.kind==="group"?a.entries.length:1;s.push({display:p,entries:m})}if(!i&&s.length>0){let a=s.slice(0,m5),l=a.map(({display:p,entries:m})=>m>1?`${p} \xD7${m}`:p),c=a.reduce((p,m)=>p+m.entries,0),u=n-c,d=l.join(", ")+(u>0?` (+${u})`:"");return`\u2026 +${n} more: ${d}`}}let o=[];for(let[s,i]of t)o.push(`${i} ${p5(s,i)}`);return`\u2026 +${n} (${o.join(", ")})`}function Lp(e,t=ln()){return e.map((n,r)=>({sibling:n,connector:r===e.length-1?t.lastConnector:t.midConnector}))}function Cb(e,t){return t?[...e,{kind:"resultSummary",summary:t}]:e}function Ab(e){if(e.length===0)return[];let t=new Map;for(let o of e){let s=qM(o),i=t.get(s);i||(i=[],t.set(s,i)),i.push(o)}let n=[],r=new Set;for(let o of e){let s=qM(o),i=t.get(s);i.length>=f5(o.toolName)?r.has(s)||(n.push({kind:"group",toolName:o.toolName,label:Ye.has(o.toolName)?o.toolInput:"",entries:i}),r.add(s)):n.push(o)}return n}function _b(e){let t=e.entries.length,n=e.entries.filter(a=>a.result),r=n.filter(a=>a.result.isError),o=n.length,s;if(r.length>0){let a=o-r.length,l=[];a>0&&l.push(`${a} ok`),l.push(`${r.length} error${r.length===1?"":"s"}`),s=l.join(", ")}else o===t?s=`${t} done`:o===0?s=`${t} running`:s=`${o}/${t} done`;return yr(e.toolName+e.label)+f.dim(` \xD7${t} \u2014 ${s}`)}function qM(e){return Ye.has(e.toolName)?e.toolName+"::"+e.toolInput:e.toolName}function f5(e){return Ye.has(e)?jM:HM}function zM(e,t,n,r){return e>0||t?ji([...n,!0],r):ji(n,r)}function JM(e,t){return!Ye.has(e.toolName)||e.headerEmitted!==!0?!1:(t.get(e.toolUseId)??[]).every(r=>r.kind==="tool"&&JM(r,t))}function Fp(e,t,n,r=Q(),o=[],s=ln(),i){let a=ji(o,s),l=Ll(a,s),c=e.filter(h=>h.kind==="text"),u=e.filter(h=>h.kind==="tool").filter(h=>!JM(h,t)),d=Ab(u),p=Dl(d,$l),m=Lp(p,s);for(let{sibling:h,connector:b}of m){let y=f.dim(b),S=b===s.lastConnector;if(h.kind==="overflow")n.push(Ie(l+y+f.dim(h.text),r));else if(h.kind==="group")n.push(Ie(l+y+_b(h),r));else if(h.kind==="resultSummary")n.push(Ie(l+y+f.dim(h.summary),r));else{let w=h,T=t.get(w.toolUseId);if(Ye.has(w.toolName)&&T&&T.length>0){w.headerEmitted?n.push(Ie(l+y,r)):n.push(Ie(l+y+w.prefix,r));let x=i??S;if(Fp(T,t,n,r,[...o,x],s,S),w.thinkingTail){let C=Ll(ji([...o,x],s),s);n.push(Ie(C+f.thinking("\u2307 "+ut(w.thinkingTail)),r))}}else if(!(Ye.has(w.toolName)&&w.headerEmitted))if(w.result){if(n.push(Ie(l+y+w.prefix+f.dim(" \u2014 ")+oo(w.result.isError)+" "+wr(w.result,void 0,60,w.toolName),r)),w.diff&&!w.result.isError){let x=l+(S?s.spineClosed:f.dim(s.spine))+" ";for(let C of br(w.diff,"overlay",x))n.push(Ie(C,r))}}else{n.push(Ie(l+y+w.prefix,r));let x=l+(S?s.spineClosed:f.dim(s.spine))+" ";w.thinkingTail?n.push(Ie(x+f.thinking("\u2307 "+ut(w.thinkingTail)),r)):n.push(Ie(x+f.dim(WM(w.toolName)),r))}}}let g=zM(u.length,!1,o,s);for(let h of c)for(let b of Ib(h.text,g,s))n.push(Ie(b,r))}function Fl(e,t,n,r,o=Q(),s=[],i=ln(),a){let l=ji(s,i),c=Ll(l,i),u=[],d=e.filter(S=>S.kind==="text"),p=e.filter(S=>S.kind==="tool"),m=Ab(p),g=Dl(m,$l),h=Cb(g,r),b=Lp(h,i);for(let{sibling:S,connector:w}of b){let T=f.dim(w),x=w===i.lastConnector;if(S.kind==="overflow")u.push(Ie(c+T+f.dim(S.text),o));else if(S.kind==="resultSummary")u.push(Ie(c+T+f.dim(S.summary),o));else if(S.kind==="group")u.push(Ie(c+T+_b(S),o));else{let C=S,R=t.get(C.toolUseId);if(Ye.has(C.toolName)&&R&&R.length>0){if(C.headerEmitted){let $=C.toolInput?`${C.toolName} ${ut(C.toolInput)}`:C.toolName;u.push(Ie(c+T+f.dim("\u21B3 "+$),o))}else u.push(Ie(c+T+C.prefix,o));let k=a??x;u.push(...Fl(R,t,n,void 0,o,[...s,k],i,x))}else if(C.result){if(u.push(Ie(c+T+C.prefix+f.dim(" \u2014 ")+oo(C.result.isError)+" "+wr(C.result,n,60,C.toolName),o)),C.diff&&!C.result.isError){let k=c+(x?i.spineClosed:f.dim(i.spine))+" ";for(let $ of br(C.diff,"flush",k))u.push(Ie($,o))}}else u.push(Ie(c+T+C.prefix,o))}}let y=zM(p.length,r!=null,s,i);for(let S of d)for(let w of Ib(S.text,y,i))u.push(Ie(w,o));return u}function Nl(e,t,n,r,o=[]){let s=ln(),i=t.filter(h=>h.kind==="tool"),l=i.filter(h=>h.result).reduce((h,b)=>h+(b.result.lineCount??0),0),c=[];i.length>$l&&(c.push(`${i.length} tools`),l>0&&c.push(`${l} lines`));let u=f.dim(s.spine.repeat(o.length)),d=o,p=f.dim(s.turnRoot),m=c.length>0?u+p+e.prefix+f.dim(" \u2014 "+c.join(" \xB7 ")):u+p+e.prefix,g=Fl(t,n,r,e.agentResultSummary,Q(),d,s);return[m,...g].join(`
|
|
1860
1860
|
`)}function Pb(e,t=[]){let n=ln(),r=f.dim(n.spine.repeat(t.length)),o=f.dim(n.turnRoot);return r+o+e.prefix}function Bl(e,t,n,r,o=[]){let s=ln(),i=o;return Fl(t,n,r,e.agentResultSummary,Q(),i,s)}function Hi(e,t,n){let r=[],o=Q();for(let s of t){let i=e.get(s);if(i.length===1){let a=i[0];if(a.result){if(r.push(" "+a.prefix+f.dim(" \u2014 ")+oo(a.result.isError)+" "+wr(a.result,n,60,a.toolName)),a.diff&&!a.result.isError)for(let l of br(a.diff,"flush"," "))r.push(Ie(l,o))}else r.push(" "+a.prefix)}else{r.push(VM(s,i,n));let a=i.filter(c=>c.diff&&c.result&&!c.result.isError),l=a.length>1;for(let c of a){if(l){let u=ut(c.toolInput),d=Ol(u).trim()||u.trim();r.push(" "+f.dim(`\u2500\u2500 ${d} \u2500\u2500`))}for(let u of br(c.diff,"flush"," "))r.push(Ie(u,o))}}}return r}function VM(e,t,n){let{color:r,glyph:o}=Ti(e),s=t.map(u=>Ol(ut(u.toolInput)).trim()),i=r(o+" ")+r.bold(e)+f.dim(` \xD7${t.length}`)+" "+f.toolArg(s.join(", ")),a=t.filter(u=>u.result),l=a.filter(u=>u.result.isError);if(l.length>0){let u=a.length-l.length,p=a.filter(g=>!g.result.isError).map(g=>g.result.lineCount).filter(g=>g!==void 0).reduce((g,h)=>g+h,0),m=[];return p>0&&m.push(`${p} lines`),u>0&&m.push(`${u} ok`),m.push(f.error(`${l.length} error${l.length>1?"s":""}`))," "+i+f.dim(" \u2014 ")+m.join(f.dim(", "))}let c=a.map(u=>u.result?.lineCount).filter(u=>u!==void 0);if(c.length===a.length&&c.length>0){if(c.every(p=>p===c[0]))return" "+i+f.dim(` \u2014 ${c[0]} lines each`);let d=c.reduce((p,m)=>p+m,0);return" "+i+f.dim(` \u2014 ${d} lines total`)}if(a.length>0){let u=a.map(d=>wr(d.result,n,60,d.toolName));return" "+i+f.dim(" \u2014 ")+u.join(f.dim(", "))}return" "+i}function Ie(e,t){return ne(e,t)}var Mb=Object.freeze({spine:"\u2502 ",spineClosed:" ",lead:" ",turnRoot:"\u25C9 ",midConnector:"\u251C\u2500 ",lastConnector:"\u2570\u2500 ",textPrefix:"\u2502 "}),g5=Object.freeze({spine:"| ",spineClosed:" ",lead:" ",turnRoot:"o ",midConnector:"+- ",lastConnector:"\\- ",textPrefix:"| "}),rIe=Mb.midConnector,oIe=Mb.lastConnector;function ln(){let e=v.AGENT_AFK_ASCII;return e&&/^(1|true|yes)$/i.test(e)?g5:Mb}function ji(e,t){let n="";for(let r of e)n+=r?t.spineClosed:t.spine;return n+=t.spine,n}function Ll(e,t){let n="";for(let r=0;r<e.length;r+=2){let o=e.slice(r,r+2);n+=o===t.spine?f.dim(o):o}return n}function Ib(e,t,n){if(!e||!e.trim())return[];let r=f.dim(n.textPrefix),o=Math.max(1,Q()-t.length-2-2),s=Ll(t,n),i=[];for(let a of e.split(`
|
|
1861
1861
|
`)){let l=Eb(a),c=le(l,o);for(let u of c.split(`
|
|
1862
1862
|
`))i.push(s+r+u)}return i}var YM=6,Ul=class{entries=new Map;order=[];agentIdStack=[];addStart(t,n,r){let o=Ne(r),s=yr(n+o),i=this.agentIdStack.at(-1)??void 0,a={kind:"tool",toolUseId:t,toolName:n,toolInput:o,prefix:s,...i!==void 0?{agentContext:i}:{}};this.entries.set(t,a),this.order.push(t),Hr.has(n)&&this.agentIdStack.push(t)}addStartWithAgentContext(t,n,r,o,s){let i=Ne(r),a=this.entries.get(t);if(a?.kind==="tool"){a.toolInput=i,a.prefix=yr(n+i,s),o!==void 0&&(a.agentContext=o);return}let l=yr(n+i,s),c={kind:"tool",toolUseId:t,toolName:n,toolInput:i,prefix:l,...o!==void 0?{agentContext:o}:{}};this.entries.set(t,c),this.order.push(t)}mergeAgentLabel(t,n,r){let o=this.entries.get(t);if(o?.kind!=="tool"||!Hr.has(o.toolName)||o.toolName==="Agent")return!1;let i=`(${Ne(n)})`;return o.toolName="Agent",o.toolInput=i,o.prefix=yr("Agent"+i,r),!0}setAgentContext(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(n===void 0?delete r.agentContext:r.agentContext=n)}setAgentResultSummary(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(r.agentResultSummary=n)}setThinkingTail(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(n===void 0?delete r.thinkingTail:r.thinkingTail=n)}addResult(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(r.result=n),this.agentIdStack.at(-1)===t&&this.agentIdStack.pop()}addDiff(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(r.diff=n)}upsertTextChild(t,n,r){let o=this.entries.get(t);if(o?.kind==="text"){o.text=r,o.agentContext=n;return}let s={kind:"text",toolUseId:t,text:r,agentContext:n};this.entries.set(t,s),this.order.push(t)}removeTextChildrenUnder(t){let n=[];for(let[r,o]of this.entries)o.kind==="text"&&o.agentContext===t&&n.push(r);for(let r of n)this.entries.delete(r);if(n.length>0){let r=new Set(n);this.order=this.order.filter(o=>!r.has(o))}}hasPending(){return this.entries.size>0}hasEntry(t){return this.entries.get(t)?.kind==="tool"}findLastSkillEntryId(){for(let t=this.order.length-1;t>=0;t--){let n=this.order[t],r=this.entries.get(n);if(r?.kind==="tool"&&Ya.has(r.toolName))return n}}getOverlay(){let t=this.buildChildMap(),n=[],r=ln(),o=Q(),s=d=>ne(d,o),i=[];for(let d of this.order){let p=this.entries.get(d);!p||p.kind!=="tool"||p.agentContext||i.push(p)}let a=i,l=0;if(i.length>YM){let d=i.filter(h=>!h.result),p=i.filter(h=>h.result),m=Math.max(0,YM-d.length),g=new Set(p.slice(-m));l=p.length-g.size,a=i.filter(h=>!h.result||g.has(h))}let u=a.some(d=>Ye.has(d.toolName))?f.dim(r.turnRoot):" ";for(let d of a){let p=t.get(d.toolUseId);if(Ye.has(d.toolName)&&p&&p.length>0)d.headerEmitted?n.push(s(f.dim(r.turnRoot))):n.push(s(f.dim(r.turnRoot)+d.prefix)),Fp(p,t,n,o,void 0,r),d.thinkingTail&&n.push(s(f.dim(r.spine)+f.thinking("\u2307 "+ut(d.thinkingTail))));else if(!(Ye.has(d.toolName)&&d.headerEmitted))if(Ye.has(d.toolName))d.result?n.push(s(f.dim(r.turnRoot)+d.prefix+f.dim(" \u2014 ")+oo(d.result.isError)+" "+wr(d.result,void 0,60,d.toolName))):n.push(s(f.dim(r.turnRoot)+d.prefix+f.dim(" \u2026"))),d.thinkingTail&&n.push(s(f.dim(r.spine)+f.thinking("\u2307 "+ut(d.thinkingTail))));else if(d.result){if(n.push(s(u+d.prefix+f.dim(" \u2014 ")+oo(d.result.isError)+" "+wr(d.result,void 0,60,d.toolName))),d.diff&&!d.result.isError)for(let m of br(d.diff,"overlay"," "))n.push(s(m))}else n.push(s(u+d.prefix+f.dim(" \u2026"))),d.thinkingTail&&n.push(s(f.dim(r.spine)+f.thinking("\u2307 "+ut(d.thinkingTail))))}return l>0&&n.push(s(" "+f.dim(`\u2026 +${l} done`))),n.join(`
|
|
@@ -1907,7 +1907,7 @@ These existing agent-instruction sources were found: ${c}. Read each and incorpo
|
|
|
1907
1907
|
${c}`)}o.push({type:"text",text:s});let l=zp(e,{skillName:"init",out:zi(),onCancel:()=>{e.session.current.interrupt().catch(()=>{})}});try{await l.arm(),await Ns(l.sink,async()=>{for await(let c of e.session.current.sendMessageStream(o))l.sink(c)})}catch(c){e.out.line(),e.out.error(`init failed: ${c instanceof Error?c.message:String(c)}`)}finally{await l.dispose()}return"continue"}};import w0 from"chalk";Oh();var Jb=new Map;function S0(e,t){let n=Jb.get(e);if(n){if(n.glyph===t.glyph&&n.color===t.color&&n.inFlightVerb===t.inFlightVerb)return;throw new Error(`Trusted skill "${e}" already registered with different config`)}Jb.set(e,t),Vx(e)}function Jp(e){return Jb.get(e)}function $5(e){return(e/1e3).toFixed(1)+"s"}function v0(e,t){let n=Jp(e.skillName),r=$5(e.durationMs);if(!n){let s=`[${e.skillName} \xB7 ${r}]`;return Ji(s,t?.columns)}if(t?.isTTY!==!1){let s;if(e.claimsTotal!==void 0){let a=e.claimsTotal===e.claimsConfirmed&&e.claimsRefuted===void 0&&e.claimsInconclusive===void 0,l;if(a)l=`${e.claimsTotal} claims \xB7 all confirmed`;else{let c=`${e.claimsTotal} claims`;e.claimsConfirmed!==void 0&&(c+=` \xB7 ${e.claimsConfirmed} confirmed`),e.claimsRefuted!==void 0&&(c+=` \xB7 ${e.claimsRefuted} refuted`),e.claimsInconclusive!==void 0&&(c+=` \xB7 ${e.claimsInconclusive} inconclusive`),l=c}s=`${n.glyph} ${e.skillName} \xB7 ${l} \xB7 ${r}`}else s=`${n.glyph} ${e.skillName} \xB7 ${r}`;let i=w0.hex(n.color)(s);return Ji(i,t?.columns)}else{let s;if(e.claimsTotal!==void 0){let i=e.claimsConfirmed??0;s=`[${e.skillName} \xB7 ${i}/${e.claimsTotal} confirmed \xB7 ${r}]`}else s=`[${e.skillName} \xB7 ${r}]`;return Ji(s,t?.columns)}}function Ji(e,t){return t!==void 0&&V(e)>t?ne(e,t):e}function k0(e,t){let n=Jp(e);if(!n){let s=`[${e} \xB7 running\u2026]`;return Ji(s,t?.columns)}if(t?.isTTY!==!1){let s=`${n.glyph} ${e} \xB7 ${n.inFlightVerb}`,i=w0.hex(n.color)(s);return Ji(i,t?.columns)}let o=`[${e} \xB7 ${n.inFlightVerb}]`;return Ji(o,t?.columns)}var E0={name:"/stats",summary:"Show session statistics including skill runs",hint:"When you want a summary of skill invocations, token usage, and cost for the current session.",async handler(e){let t=e.ledger;if(!t)return e.out.info("No skill stats available."),"continue";let n=t.summary();if(!n)return e.out.info("No skill runs recorded this session."),"continue";e.out.line(),e.out.line(f.bold("Skill runs"));for(let[r,o]of n){let s=Jp(r)?.glyph??"",i=s?`${s} `:"",a=`${(o.totalDurationMs/1e3).toFixed(1)}s total`,l=`${o.runs} run${o.runs!==1?"s":""}`,c="";o.totalClaims!==void 0&&(c=` \xB7 ${o.totalClaims} claims`,o.totalConfirmed!==void 0&&(c+=` \xB7 ${o.totalConfirmed} confirmed`),o.totalRefuted!==void 0&&(c+=` \xB7 ${o.totalRefuted} refuted`),o.totalInconclusive!==void 0&&(c+=` \xB7 ${o.totalInconclusive} inconclusive`)),e.out.line(` ${i}${r} ${l}${c} \xB7 ${a}`)}return e.out.line(),"continue"}};nh();function D5(e=th){return{name:"/font-size",summary:"Get or set the terminal font size in Cursor / VS Code",usage:"/font-size [size] [editor]",hint:"Direct shortcut to the terminal_font_size tool \u2014 bypasses the LLM and the first-write permission prompt. Examples: `/font-size` (read all), `/font-size 18` (set all), `/font-size 14 cursor` (set Cursor only).",async handler(t,n){let r=n.split(/\s+/).filter(Boolean),o=new AbortController;if(r.length===0){let u=await e({action:"get"},o.signal);return u.isError?t.out.error(u.content):t.out.line(u.content),"continue"}let s=r[0],i=Number(s);if(!Number.isFinite(i))return t.out.error(`Invalid size: "${s}". Usage: /font-size [size] [editor]`),"continue";let a=r[1],l={action:"set",size:i};a!==void 0&&(l.editor=a);let c=await e(l,o.signal);return c.isError?t.out.error(c.content):t.out.success(c.content),"continue"}}}var T0=D5();import L5 from"path";import{statSync as F5}from"fs";var Qo;function x0(e){Qo=e}var R0={name:"/allow-dir",summary:"Manage per-session directory access grants for tool handlers",usage:"/allow-dir [--rw | --revoke] [<path>]",hint:"When the model needs read or write access to a directory outside the session root \u2014 grant it here without restarting.",flags:["--rw","--revoke"],async handler(e,t){if(!Qo)return e.out.error("Directory grants not available in this session."),"continue";let n=t.trim();if(!n){let a=Qo.getGrants();return e.out.line(" Session directory grants:"),e.out.line(` resolveBase : ${a.resolveBase??"(none)"}`),e.out.line(` readRoots : ${a.readRoots.length>0?a.readRoots.join(", "):"(none)"}`),e.out.line(` writeRoots : ${a.writeRoots.length>0?a.writeRoots.join(", "):"(none)"}`),"continue"}let r="read",o=n;if(o.startsWith("--rw ")||o==="--rw"?(r="write",o=o.slice(5).trim()):(o.startsWith("--revoke ")||o==="--revoke")&&(r="revoke",o=o.slice(9).trim()),!o)return e.out.error("Usage: /allow-dir [--rw | --revoke] <path>"),"continue";let s=L5.resolve(process.cwd(),o);if(r!=="revoke")try{F5(s)}catch{return e.out.error(`Path does not exist: ${s}`),"continue"}let i=e.stats.sessionId;if(r==="revoke"){let a=Qo.getGrants();Qo.revokeRoot(s,"slash",i),a.resolveBase&&s===a.resolveBase?e.out.warn(`Cannot revoke the session's initial resolveBase: ${s}`):e.out.line(`\u2713 Revoked: ${s}`)}else r==="write"?(Qo.addWriteRoot(s,"slash",i),e.out.line(`\u2713 Read+write grant: ${s}`)):(Qo.addReadRoot(s,"slash",i),e.out.line(`\u2713 Read-only grant: ${s}`));return"continue"}};var C0=[{group:"Navigation",rows:[["ctrl+a","Move to start of current line"],["ctrl+e","Move to end of current line"],["ctrl+b","Move one character backward (input mode) / Run turn in background (streaming mode)"],["ctrl+f","Move one character forward"],["alt+b","Move one word backward"],["alt+f","Move one word forward"],["\u2190 / \u2192","Character left / right"],["home / end","Buffer start / end"]]},{group:"Editing",rows:[["ctrl+u","Delete to start of current line"],["ctrl+k","Delete to end of current line"],["ctrl+w","Delete previous word"],["backspace","Delete previous character"],["delete","Delete next character"],["alt+backspace","Delete previous word (Option+Delete on macOS)"],["alt+delete","Delete next word (Option+Fn-Delete on macOS)"]]},{group:"History",rows:[["ctrl+p / \u2191","Previous history entry (or move up in multi-line draft)"],["ctrl+n / \u2193","Next history entry (or move down in multi-line draft)"]]},{group:"Multi-line",rows:[["shift+enter","Insert newline (no submit)"],["alt+enter","Insert newline (no submit)"],["<text>\\","Trailing \\ + Enter inserts newline (backwards-compat)"]]},{group:"Attach",rows:[["@<path>","Autocomplete and attach a file \u2014 type @ then start the path"],["ctrl+v","Paste image from clipboard (macOS: Cmd+V also works)"],["ctrl+x","Remove the last attached image from the prompt"]]},{group:"Misc",rows:[["ctrl+l","Clear screen and repaint"],["ctrl+c","Interrupt running turn / exit (second press)"],["ctrl+d","EOF / exit (when buffer is empty)"],["tab","Accept autocomplete suggestion"],["enter","Submit prompt"]]}],A0={name:"/keys",summary:"Show keybinding reference",hint:"When you want the full list of keyboard shortcuts available in the interactive REPL.",async handler(e){e.out.line(),e.out.line(f.bold(f.brand("Keybindings"))),e.out.line(pe());let n=C0.flatMap(r=>r.rows).reduce((r,[o])=>Math.max(r,o.length),0);for(let{group:r,rows:o}of C0){e.out.line(),e.out.line(f.bold(r));for(let[s,i]of o){let a=" ".repeat(Math.max(0,n-s.length));e.out.line(` ${f.warning(s)}${a} ${f.dim(i)}`)}}return e.out.line(),"continue"}};import{execFile as Y5}from"node:child_process";import{promises as X5}from"node:fs";import{dirname as Z5,isAbsolute as Q5,join as e3,resolve as t3}from"node:path";import{promisify as n3}from"node:util";G();Ma();import{promises as un,existsSync as P0,createReadStream as N5,realpathSync as B5}from"node:fs";import{join as Vp,relative as U5,isAbsolute as j5}from"node:path";import{createInterface as H5}from"node:readline";var W5=36e5,K5=30*864e5;function _0(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function I0(e){try{return B5(e)}catch{return e}}function G5(e,t){let n=U5(I0(t),I0(e));return n===""||!n.startsWith("..")&&!j5(n)}function q5(e){let t=e.trim().split(/\n\n+/),n=[];for(let r of t){let o=r.split(`
|
|
1908
1908
|
`),s="",i="",a="",l=!1,c=!1,u=!1;for(let d of o)d.startsWith("worktree ")?s=d.slice(9).trim():d.startsWith("HEAD ")?i=d.slice(5).trim():d.startsWith("branch ")?a=d.slice(7).trim():d.trim()==="locked"?l=!0:d.trim()==="prunable"?c=!0:d.trim()==="bare"&&(u=!0);s&&n.push({path:s,head:i,branch:a,locked:l,prunable:c,isBare:u})}return n}function z5(e,t,n){if(e.locked)return"locked";let r=864e5,o=t*r,s=n*r;return e.ownerLiveness==="dead"&&!e.isDirty&&e.commitsAhead===0?"dead-owner":e.commitsAhead===0&&!e.isDirty&&e.ageMs>=W5?"empty":e.isDirty&&e.ageMs>s?"stale-dirty":!e.isDirty&&e.ageMs>o?"stale-clean":"active"}async function J5(e){if(!P0(e))return 0;let t=0;try{let n=H5({input:N5(e),crlfDelay:1/0});for await(let r of n){let o=r.trim();if(o)try{let s=JSON.parse(o);s.taskId==="worktree-prune"&&(s.status==="success"||s.status==="error")&&t++}catch{}}}catch{}return t}var Yp=class extends Error{constructor(t){super(`Worktree sweep lock contested: ${t} \u2014 another sweep may be running.`),this.name="LockContestedError"}};async function V5(e){let t=Vp(e,"..");await un.mkdir(t,{recursive:!0}).catch(()=>{});let r=await(async()=>{try{return await un.open(e,"wx")}catch(o){if(o.code!=="EEXIST")throw o;let i=null;try{let a=await un.readFile(e,"utf-8");i=parseInt(a.trim(),10)}catch{}if(i!==null&&!Number.isNaN(i)){let a=!1;try{process.kill(i,0),a=!0}catch{}if(!a)return await un.unlink(e).catch(()=>{}),await un.open(e,"wx")}throw new Yp(e)}})();return await r.writeFile(String(process.pid),"utf-8"),await r.close(),async()=>{await un.unlink(e).catch(()=>{})}}async function Bn(e){let{execFile:t,repoRoot:n,maxAgeDaysClean:r=14,maxAgeDaysDirty:o=30,scope:s="all",telemetryPath:i}=e,a=i??Tr(),l=e.lockPath??WS(),c={removed:[],warnings:[],dryRun:e.dryRun??!1,candidates:[]},u=e.bypassSoftLaunch?Number.POSITIVE_INFINITY:await J5(a),d=e.dryRun===!0||u<3;c.dryRun=d;let p=null;try{p=await V5(l)}catch(m){if(m instanceof Yp)return c.warnings.push(`[WARN] ${m.message}`),c;throw m}try{let m=await t("git",["-C",n,"worktree","list","--porcelain"]),g=q5(m.stdout),h=Vp(n,".afk-worktrees"),b=new Set(g.map(R=>R.path)),y=[];try{y=(await un.readdir(h,{withFileTypes:!0})).filter(k=>k.isDirectory()).map(k=>Vp(h,k.name))}catch{}let S=y.filter(R=>!b.has(R));if(s==="all"||s==="interactive")for(let R of S){let k=0;try{let $=await un.stat(R);k=Date.now()-$.birthtimeMs}catch{}if(c.candidates.push({path:R,verdict:"orphaned-dir",owner:"interactive",ageMs:k}),!d)try{await un.rm(R,{recursive:!0,force:!0}),c.removed.push(R)}catch($){c.warnings.push(`[ERROR] Failed to remove orphaned dir ${R}: ${$ instanceof Error?$.message:String($)}`)}}let w=e.readPresence??gg,T=[];try{T=(await w()).filter(k=>typeof k.pid=="number"&&k.pid>0&&_0(k.pid)).map(k=>k.cwd).filter(k=>typeof k=="string"&&k.length>0)}catch{}let x=!1,C=g[0]?.path;for(let R of g){if(R.path===C||R.isBare||!R.path.startsWith(h))continue;let k;try{let L=await un.readFile(Vp(R.path,".afk-worktree-meta.json"),"utf-8");k=JSON.parse(L)}catch{}if(s!=="all"&&k?.owner!==s)continue;let $=k?.owner==="interactive"||k?.owner==="diagnose"?k.owner:"unknown";if(!P0(R.path)){c.candidates.push({path:R.path,verdict:"orphaned-registration",owner:$,ageMs:0}),d||(x=!0);continue}let A=0,P=k?.createdAt;if(P)A=Date.now()-new Date(P).getTime();else try{let L=await un.stat(R.path);A=Date.now()-L.birthtimeMs}catch{}let F=!1,D=0;try{F=(await t("git",["-C",R.path,"status","--porcelain"])).stdout.trim().length>0}catch{F=!0}if(!F&&R.head){let L=k?.baseSha??R.head;try{let I=await t("git",["-C",n,"rev-list",`${L}..${R.head}`,"--count"]);D=parseInt(I.stdout.trim(),10)||0}catch{D=0}}let N="unknown";typeof k?.pid=="number"&&Number.isInteger(k.pid)&&k.pid>0&&A<=K5&&(N=_0(k.pid)?"alive":"dead"),N!=="alive"&&T.some(L=>G5(L,R.path))&&(N="alive");let B={path:R.path,head:R.head,branch:R.branch,locked:R.locked,prunable:R.prunable,meta:k,ageMs:A,isDirty:F,commitsAhead:D,ownerLiveness:N},H=z5(B,r,o);if(c.candidates.push({path:R.path,verdict:H,owner:$,ageMs:A}),!d)try{H==="empty"?(await t("git",["-C",n,"worktree","remove","--force",R.path]),R.branch&&await t("git",["-C",n,"branch","-d",R.branch]).catch(()=>{}),c.removed.push(R.path)):H==="dead-owner"?(await t("git",["-C",n,"worktree","remove","--force",R.path]),R.branch&&await t("git",["-C",n,"branch","-d",R.branch]).catch(()=>{}),c.removed.push(R.path)):H==="stale-clean"?(await t("git",["-C",n,"worktree","remove","--force",R.path]),c.removed.push(R.path)):H==="stale-dirty"&&c.warnings.push(`[WARN] stale-dirty worktree preserved (uncommitted changes): ${R.path}`)}catch(L){c.warnings.push(`[ERROR] Failed to process ${R.path} (${H}): ${L instanceof Error?L.message:String(L)}`)}}if(x&&!d)try{await t("git",["-C",n,"worktree","prune"])}catch(R){c.warnings.push(`[ERROR] git worktree prune failed: ${R instanceof Error?R.message:String(R)}`)}}finally{p&&await p()}return c}var Vb=n3(Y5),M0=["interactive","diagnose","all"],Xp=new Set(["empty","stale-clean","orphaned-dir","orphaned-registration","dead-owner"]);async function O0(){let t=(await Vb("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=Q5(t)?t:t3(process.cwd(),t);return Z5(n)}function r3(e){if(e<=0)return"-";let t=e/864e5;return t<1?`${Math.max(1,Math.round(e/36e5))}h`:`${Math.round(t)}d`}function o3(e,t){return Xp.has(e)?f.error(t):e==="stale-dirty"?f.warning(t):e==="locked"?f.dim(t):f.dim(t)}function $0(e,t){let n=e.split(/\s+/).map(o=>o.trim()).filter(o=>o.length>0),r={scope:t,apply:!1,unknown:[]};for(let o=0;o<n.length;o++){let s=n[o];if(s==="--apply")r.apply=!0;else if(s==="--scope"&&o+1<n.length){let i=n[o+1];o++,M0.includes(i)?r.scope=i:r.unknown.push(`--scope=${i}`)}else if(s.startsWith("--scope=")){let i=s.slice(8);M0.includes(i)?r.scope=i:r.unknown.push(s)}else r.unknown.push(s)}return r}async function s3(e){try{let t=await X5.readFile(e3(e,".afk-worktree-meta.json"),"utf-8"),n=JSON.parse(t);if(typeof n.pid=="number"&&Number.isInteger(n.pid)&&n.pid>0)return n.pid}catch{}}async function i3(e,t,n){if(t.length===0){e.info("No afk-managed worktrees found.");return}let r=process.pid;e.line(),e.line(f.bold("Worktrees")),e.line(f.dim(" "+"PATH".padEnd(45)+" "+"OWNER".padEnd(12)+" "+"AGE".padEnd(5)+" "+"VERDICT".padEnd(22)+" PRUNE?"));for(let o of t){let a=n.get(o.path)===r?f.brand("\u2192 "):" ",l=o.path.slice(-44).padEnd(45),c=o.owner.padEnd(12),u=r3(o.ageMs).padEnd(5),d=o.verdict.padEnd(22),p=Xp.has(o.verdict)?f.error("yes"):o.verdict==="stale-dirty"?f.warning("warn"):f.dim("no"),m=o3(o.verdict,d);e.line(`${a}${l} ${c} ${u} ${m} ${p}`)}e.line(),e.line(f.dim(" \u2192 this session")),e.line()}async function a3(e){let t=new Map;for(let n of e)t.set(n.path,await s3(n.path));return t}async function l3(e,t){let n=$0(t,"interactive");n.unknown.length>0&&e.out.warn(`Unknown args ignored: ${n.unknown.join(" ")}`);let r;try{r=await O0()}catch(i){return e.out.error(`Not in a git repository: ${i.message}`),"continue"}let o;try{let i={execFile:Vb,repoRoot:r,dryRun:!0,scope:n.scope};o=await Bn(i)}catch(i){return e.out.error(`Sweep failed: ${i.message}`),"continue"}let s=await a3(o.candidates);await i3(e.out,o.candidates,s);for(let i of o.warnings)e.out.warn(i);return"continue"}async function c3(e,t){let n=$0(t,"interactive");n.unknown.length>0&&e.out.warn(`Unknown args ignored: ${n.unknown.join(" ")}`);let r;try{r=await O0()}catch(a){return e.out.error(`Not in a git repository: ${a.message}`),"continue"}let o;try{let a={execFile:Vb,repoRoot:r,dryRun:!n.apply,scope:n.scope};o=await Bn(a)}catch(a){return e.out.error(`Sweep failed: ${a.message}`),"continue"}let s={};for(let a of o.candidates)s[a.verdict]=(s[a.verdict]??0)+1;let i=Object.entries(s).sort(([a],[l])=>a.localeCompare(l)).map(([a,l])=>`${a}=${l}`);if(o.dryRun){let a=o.candidates.filter(l=>Xp.has(l.verdict)).length;e.out.line(),e.out.line(f.warning("\u{1F50D} Dry-run \u2014 pass --apply to actually remove.")+` Would prune ${a} worktree(s).`+(i.length>0?` [${i.join(" ")}]`:""))}else{let a=o.warnings.filter(c=>c.startsWith("[WARN]")).length,l=o.warnings.filter(c=>c.startsWith("[ERROR]")).length;e.out.line(),e.out.success(`Removed ${o.removed.length}, warned ${a}, errors ${l}`+(i.length>0?` [${i.join(" ")}]`:""))}for(let a of o.candidates){let c=o.removed.includes(a.path)?f.error("\u2717"):Xp.has(a.verdict)?f.warning("\u2022"):f.dim("\xB7");e.out.line(` ${c} [${a.verdict.padEnd(22)}] ${a.path}`)}for(let a of o.warnings)a.startsWith("[ERROR]")?e.out.error(a):e.out.warn(a);return e.out.line(),"continue"}var D0={name:"/worktree",summary:"List or prune afk-managed git worktrees",usage:"/worktree list | /worktree prune [--apply] [--scope <interactive|diagnose|all>]",hint:"When you want to audit or clean up stale afk-managed git worktrees from past sessions.",async handler(e,t){let n=t.trim();return n.length===0||n.startsWith("list")?l3(e,n.replace(/^list\s*/,"")):n.startsWith("prune")?c3(e,n.replace(/^prune\s*/,"")):(e.out.error(`Unknown /worktree subcommand. Usage:
|
|
1909
1909
|
/worktree list
|
|
1910
|
-
/worktree prune [--apply] [--scope <interactive|diagnose|all>]`),"continue")}};Fs();var L0={name:"/reauth",summary:"Re-read keychain credentials and swap the running session's client",usage:"/reauth [--check]",hint:"Force the running session to pick up a new keychain token (e.g. after `claude /login` in another terminal)",async handler(e,t){if(t.trim()==="--check"){let s=
|
|
1910
|
+
/worktree prune [--apply] [--scope <interactive|diagnose|all>]`),"continue")}};Fs();var L0={name:"/reauth",summary:"Re-read keychain credentials and swap the running session's client",usage:"/reauth [--check]",hint:"Force the running session to pick up a new keychain token (e.g. after `claude /login` in another terminal)",async handler(e,t){if(t.trim()==="--check"){let s=bt();if(!s)return e.out.warn("No OAuth token found. Run `claude login` in a terminal to authenticate."),"continue";let i=_r(s);return e.out.success(`Active keychain account: ${i}`),e.out.info("Note: --check only inspects the keychain. The running SDK client may still hold an older token \u2014 run `/reauth` (no args) to actually swap."),"continue"}let r=bt();if(r){let s=_r(r);e.out.info(`Current keychain account: ${s}`)}e.out.info("Rebuilding session client from keychain credentials\u2026");let o;try{o=await e.session.current.reauth()}catch(s){return e.out.error(`Client refresh failed: ${s instanceof Error?s.message:String(s)}`),e.out.warn("Run `claude login` in a terminal to re-authenticate."),"continue"}return o?(o.swapped?(e.out.success(`\u2713 Client swapped. Session now authenticated as: ${o.accountId}`),e.out.info("Next turn will use the new credential. If a usage-limit pause is active, it will resume automatically within ~30s (or send a message to retry immediately).")):e.out.success(`\u2713 Client refreshed. Authenticated as: ${o.accountId} (token unchanged)`),"continue"):(bt()?e.out.warn("This session is not using OAuth (probably api-key mode) \u2014 nothing to refresh. The active credential is whatever ANTHROPIC_API_KEY held at session start."):e.out.warn("No OAuth credentials found in the keychain. Run `claude login` in a terminal to authenticate."),"continue")}};q();import{spawn as u3}from"node:child_process";import{promises as Yb}from"node:fs";import*as F0 from"node:os";import*as N0 from"node:path";function d3(e){return new Date(e).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}function p3(e,t){let n=[f.meta(`#${t+1}`),f.dim(d3(e.timestamp))];if(e.durationMs!==void 0&&e.durationMs>0&&n.push(f.dim(me(e.durationMs))),e.costUsd!==void 0&&e.costUsd>0&&n.push(f.dim(rt(e.costUsd))),e.inputTokens!==void 0||e.outputTokens!==void 0){let r=e.inputTokens??0,o=e.outputTokens??0;n.push(f.dim(`${Math.round((r+o)/1e3)}k tok`))}return n.join(" ")}function m3(e){if(!e.toolEvents||e.toolEvents.length===0)return"";let t=[];for(let n of e.toolEvents){let r=n.isError?f.error("\u2717"):f.dim("\u25CF"),o=f.chrome(n.toolName),s="";if(n.result){let i=n.result.trim().split(`
|
|
1911
1911
|
`)[0]??"";s=i.length>80?i.slice(0,77)+"...":i}t.push(` ${r} ${o}${s?f.dim(` ${s}`):""}`)}return t.join(`
|
|
1912
1912
|
`)+`
|
|
1913
1913
|
`}function f3(e,t,n,r){let o=[];o.push(pe("Session Transcript"));let s=[f.dim(`Started ${new Date(n).toLocaleString()}`),f.dim(`model: ${t}`),f.dim(`${e.length} turn${e.length===1?"":"s"}`)];r>0&&s.push(f.dim(rt(r))),o.push(s.join(" \xB7 ")),o.push("");for(let i=0;i<e.length;i++){let a=e[i];o.push(p3(a,i)),o.push(""),o.push(` ${f.user("\u25B6")} ${f.user("User")}`),o.push("");let l=a.user.split(`
|
|
@@ -1916,7 +1916,7 @@ ${c}`)}o.push({type:"text",text:s});let l=zp(e,{skillName:"init",out:zi(),onCanc
|
|
|
1916
1916
|
`).map(p=>` ${p}`);o.push(d.join(`
|
|
1917
1917
|
`)),o.push(""),i<e.length-1&&(o.push(pe()),o.push(""))}return o.push(pe()),o.join(`
|
|
1918
1918
|
`)+`
|
|
1919
|
-
`}function g3(){let e=v.PAGER;if(e){let t=e.split(/\s+/);return{cmd:t[0],args:t.slice(1)}}return{cmd:"less",args:["-R"]}}var B0={name:"/transcript",aliases:["/t"],summary:"View full session transcript in $PAGER",hint:"When you want to read the full conversation \u2014 all turns, tool calls, costs \u2014 in a scrollable pager.",async handler(e){let{stats:t,out:n}=e;if(t.turns.length===0)return n.info("No turns yet in this session."),"continue";let r=f3(t.turns,String(t.model),t.sessionStartTime,t.totalCostUsd);if(!process.stdout.isTTY)return n.raw(r),"continue";let o=g3();if(!o)return n.raw(r),"continue";let s=N0.join(F0.tmpdir(),`afk-transcript-${Date.now()}.txt`);return await Yb.writeFile(s,r,{mode:384}),new Promise(i=>{let a=u3(o.cmd,[...o.args,s],{stdio:"inherit"});a.on("error",()=>{n.raw(r),Yb.unlink(s).catch(()=>{}),i("continue")}),a.on("exit",()=>{Yb.unlink(s).catch(()=>{}),i("continue")})})}};q();tt();Mt();q();ze();G();ir();import{access as h3,constants as y3,mkdir as b3,readFile as w3}from"fs/promises";import{execSync as S3}from"child_process";async function v3(){return Re()?{name:"Anthropic API Key",state:"pass",detail:"ANTHROPIC_API_KEY set"}:{name:"Anthropic API Key",state:"fail",fix:"Set ANTHROPIC_API_KEY or run `afk login`"}}async function k3(){return hd()?{name:"Codex/OpenAI API Key",state:"pass",detail:"OPENAI_API_KEY or CODEX_API_KEY set"}:{name:"Codex/OpenAI API Key",state:"warn",fix:"Set OPENAI_API_KEY or CODEX_API_KEY to use Codex models"}}async function E3(){try{let t=`${S3("npm config get prefix",{timeout:2e3,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().replace(/\/$/,"")}/bin`;return(v.PATH??"").split(":").map(r=>r.replace(/\/$/,"")).includes(t)?{name:"npm bin on PATH",state:"pass",detail:t}:{name:"npm bin on PATH",state:"fail",detail:t,fix:`Add ${t} to PATH: echo 'export PATH="${t}:$PATH"' >> ~/.zshrc`}}catch{return{name:"npm bin on PATH",state:"warn",detail:"could not query npm prefix"}}}async function Xb(e,t){let n=t();try{return await h3(n,y3.W_OK),{name:e,state:"pass",detail:n}}catch{try{return await b3(n,{recursive:!0}),{name:e,state:"pass",detail:`${n} (created)`}}catch{return{name:e,state:"fail",detail:n,fix:`Unable to create or write to ${n}`}}}}async function T3(){let e=Bt();try{let t=await w3(e,"utf-8");return JSON.parse(t),{name:"Config File",state:"pass",detail:`${e} (valid JSON)`}}catch(t){return t.code==="ENOENT"?{name:"Config File",state:"pass",detail:"no config file (using defaults)"}:{name:"Config File",state:"fail",detail:e,fix:`Unable to parse config file: ${t instanceof Error?t.message:"unknown error"}`}}}async function x3(){let e=LS();return e.length===0?null:{name:"Required env vars",state:"fail",detail:`Missing: ${e.map(t=>t.name).join(", ")}`,fix:"Set these env vars before running. See docs/env-registry.md for descriptions."}}async function R3(){let e=v.AFK_TELEGRAM_BOT_TOKEN;if(!e)return null;try{let t=new AbortController,n=setTimeout(()=>t.abort(),5e3),r=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:t.signal});if(clearTimeout(n),r.ok){let s=(await r.json()).result?.username;return{name:"Telegram Bot",state:"pass",detail:s?`@${s}`:"connected"}}return{name:"Telegram Bot",state:"fail",fix:`Telegram API returned ${r.status}. Check AFK_TELEGRAM_BOT_TOKEN.`}}catch(t){return t.name==="AbortError"?{name:"Telegram Bot",state:"warn",detail:"connection timeout"}:{name:"Telegram Bot",state:"warn",detail:`network error: ${t instanceof Error?t.message:"unknown"}`}}}async function C3(e={}){let t;if(e.detected!==void 0)t=e.detected;else try{t=mu()}catch{return null}let n=e.trusted??Pt()??{},r=t.filter(s=>s.present&&(s.plugins.length>0||s.skills.length>0)&&n[s.binary]===void 0);return r.length===0?null:{name:"Cross-tool import available",state:"warn",detail:r.map(s=>`${s.label} (${s.plugins.length} plugins, ${s.skills.length} skills)`).join("; "),fix:"Run `afk migrate` to import them"}}async function Zp(){let e=[];e.push(await v3()),e.push(await k3()),e.push(await E3()),e.push(await Xb("Config Directory",Qt)),e.push(await Xb("State Directory",Te)),e.push(await Xb("Logs Directory",ks)),e.push(await T3());let t=await x3();t!==null&&e.push(t);let n=await R3();n!==null&&e.push(n);let r=await C3();return r!==null&&e.push(r),e}var A3={name:"/config",summary:"View resolved configuration (model, provider, API keys, env vars)",hint:"When you want to confirm which model and API key the session is using, or check what env vars are active \u2014 same as `afk config` but available mid-session.",async handler(e){let{out:t}=e,n=v.AFK_MODEL??v.CLAUDE_MODEL,r=n??"sonnet",o=re(n),s=v.ANTHROPIC_API_KEY||v.CLAUDE_CODE_OAUTH_TOKEN,i=v.OPENAI_API_KEY||v.CODEX_API_KEY,a=o==="anthropic"?s:i;if(t.line(),t.line(f.bold("Configuration")),t.line(pe()),t.line(` model ${f.info(n?r:`${r} (default)`)}`),t.line(` provider ${f.plan(o)}`),o==="anthropic"){let d=a?f.success("\u2713 set (ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN)"):f.warning("\u26A0 not set \u2014 subprocess falls back to OAuth / keychain");t.line(` api key ${d}`)}else{let d=v.OPENAI_API_KEY?"OPENAI_API_KEY":"CODEX_API_KEY",p=a?f.success(`\u2713 set (${d})`):f.warning("\u26A0 not set \u2014 falling back to `codex login` state");t.line(` api key ${p}`)}t.line(` thinking ${v.AFK_THINKING?f.info(v.AFK_THINKING):f.dim("(unset \u2014 SDK default)")}`),t.line(` effort ${v.AFK_EFFORT?f.info(v.AFK_EFFORT):f.dim("(unset \u2014 SDK default)")}`);let l=Js();t.line(` perm mode ${l==="bypassPermissions"?f.warning(`${l} (bypass \u2014 containment off)`):f.info(`${l} (containment on)`)}`),t.line(),t.line(f.bold("Environment variables")),t.line(pe());let c=[["AFK_MODEL",v.AFK_MODEL??f.dim("unset")],["CLAUDE_MODEL",v.CLAUDE_MODEL??f.dim("unset")],["ANTHROPIC_API_KEY",v.ANTHROPIC_API_KEY?f.success("set"):f.dim("unset")],["CLAUDE_CODE_OAUTH_TOKEN",v.CLAUDE_CODE_OAUTH_TOKEN?f.success("set"):f.dim("unset")],["OPENAI_API_KEY",v.OPENAI_API_KEY?f.success("set"):f.dim("unset")],["CODEX_API_KEY",v.CODEX_API_KEY?f.success("set"):f.dim("unset")],["AFK_THINKING",v.AFK_THINKING??f.dim("unset")],["AFK_EFFORT",v.AFK_EFFORT??f.dim("unset")]],u=Math.max(...c.map(([d])=>d.length))+2;for(let[d,p]of c)t.line(` ${f.meta(d.padEnd(u))} ${p}`);return t.line(),"continue"}},_3={name:"/doctor",summary:"Run system health checks (API keys, directories, config file, Telegram)",hint:"When something feels broken \u2014 API key missing, config file unreadable, Telegram bot unreachable. Same checks as `afk doctor` but surfaced mid-session without exiting.",async handler(e){let{out:t}=e;t.line(),t.line(f.bold("System health checks")),t.line(pe());let n;try{n=await Zp()}catch(a){return t.error(`Health check failed: ${a instanceof Error?a.message:String(a)}`),"continue"}for(let a of n){let l;a.state==="pass"?l=f.success("\u2713"):a.state==="warn"?l=f.warning("\u26A0"):l=f.error("\u2717");let c=` ${l} ${a.name}`;a.detail&&(c+=` \u2014 ${f.dim(a.detail)}`),t.line(c),a.state!=="pass"&&a.fix&&t.line(f.dim(` Fix: ${a.fix}`))}let r=n.filter(a=>a.state==="pass").length,o=n.filter(a=>a.state==="warn").length,s=n.filter(a=>a.state==="fail").length;t.line();let i=[f.success(`${r} passed`),o>0?f.warning(`${o} warned`):f.dim(`${o} warned`),s>0?f.error(`${s} failed`):f.dim(`${s} failed`)];return t.line(` Summary: ${i.join(f.dim(" \xB7 "))}`),t.line(),"continue"}},U0=[A3,_3];zr();Ur();import{readdirSync as n6,readFileSync as r6,statSync as Q0}from"fs";import{join as o6}from"path";G();zr();Dt();import{basename as O3}from"path";import{existsSync as I3,readFileSync as P3}from"fs";import{join as M3}from"path";function es(e){let t=M3(e,".claude-plugin","plugin.json");if(!I3(t))return{name:null,version:null};try{let n=JSON.parse(P3(t,"utf8"));return{name:typeof n.name=="string"&&n.name.trim()?n.name.trim():null,version:typeof n.version=="string"&&n.version.trim()?n.version.trim():null}}catch{return{name:null,version:null}}}function $3(e,t,n){let r=new Set([e]);t&&r.add(t);for(let[o,s]of Object.entries(n)){if(r.has(o))return s;let i=o.includes(":")?o.split(":").pop():o;if(r.has(i)||s.manifestName&&r.has(s.manifestName))return s}return null}function j0(e={}){let t=e.roots??[dc(),Ve(),vs()],n=xe(e.indexPath??ce()),r=[],o=new Set;for(let s of t)for(let i of dr(s)){if(i.type!=="local")continue;let a=i.path,l=O3(a),{name:c,version:u}=es(a),d=c??l;if(o.has(d))continue;o.add(d);let p=$3(l,c,n.plugins);r.push({name:d,version:u,ref:p?.ref??null,commit:p?.commit??null,source:p?.source??null,sourceType:p?.sourceType??null,dir:a})}return r.sort((s,i)=>s.name.localeCompare(i.name)),r}function H0(e){let t;return e.version?t=/^v/i.test(e.version)?e.version:`v${e.version}`:e.ref?t=e.ref:t="(local)",e.commit&&e.commit!==e.ref&&(t+=` @ ${e.commit.slice(0,7)}`),t}G();bt();var Zb=[],D3={name:"/agents",summary:"List plugin-provided subagents (loads after session init)",async handler(e){return e.out.line(),e.out.line(f.dim(" Plugin agents are still loading \u2014 try again after the session is ready.")),e.out.line(),"continue"}};function L3(e){return{name:"/agents",summary:"List Task-tool subagents loaded by the SDK (plugin + user + project)",async handler(t){if(t.out.line(),e.length===0)return t.out.line(f.dim(" No plugin agents loaded. Agents come from `agents:` entries in plugin.json or from ~/.afk/agents/.")),t.out.line(),"continue";t.out.line(f.bold("Plugin agents")+f.dim(` (${e.length} loaded)`)),t.out.line(f.dim("\u2500".repeat(60)));let n=e.reduce((r,o)=>Math.max(r,o.name.length),0)+2;for(let r of e){let o=f.warning(r.name.padEnd(n)),s=r.model?f.dim(`[${r.model}]`):"",i=r.description?f.dim(` ${r.description}`):"";t.out.line(` ${o} ${s}${i}`)}return t.out.line(),t.out.line(f.dim(" Agents are dispatched by the model via the Task tool \u2014 not user-invoked.")),t.out.line(),"continue"}}}async function Qb(e){let t;try{t=await e.supportedAgents()}catch(n){return console.error(f.dim(" \u26A0 Plugin-agent discovery failed: ")+(n instanceof Error?n.message:String(n))),null}return Zb=t.map(n=>{let r={name:n.name,description:n.description};return n.model&&(r.model=n.model),r}),eo(L3(Zb)),Zb.length}function W0(){fe(D3)}ay();Xn();function Qp(e,t){for(let n of t??[])e.push({type:"image",source:{type:"base64",media_type:n.mediaType,data:n.bytes.toString("base64")}})}function K0(e,t,n,r){let o=kp(e.name,t),s=e.context==="fork"?" This skill runs with context: 'fork' \u2014 the executor will fork a subagent.":"",i=`Use the \`skill\` tool with {"name": "${e.name}", "arguments": "${t}"} to dispatch this skill.${s}`,a=[];return n&&n.trim().length>0&&a.push({type:"text",text:n}),a.push({type:"text",text:o}),a.push({type:"text",text:i}),Qp(a,r),a}var F3=15e3;async function em(e,t){let n=zp(e,{skillName:t.skillName,onCancel:()=>{e.session.current.interrupt().catch(()=>{})}}),r=!1,o=`/${t.skillName}${t.args?" "+t.args:""}`;await e.transcript?.appendUser?.(o).catch(()=>{});let s="",i=!1,a,l=0,c=[],u=new Map;try{await n.arm(),e.setSoftStopHandler?.(()=>{r=!0,e.session.current.interrupt().catch(()=>{})});let d;if(t.preflight)try{d=await t.preflight()}catch{d=void 0}let p=K0(t.skillMeta,t.args,d,t.attachments);await Ns(n.sink,async()=>{for await(let m of e.session.current.sendMessageStream(p)){if(r)break;if(m.type==="message"&&m.message.role==="assistant"&&(s=m.message.content),m.type==="chunk"&&m.chunk.type==="tool_use_detail"){let g=m.chunk,h={toolName:g.toolName,toolUseId:g.toolUseId,input:g.toolInput};u.set(g.toolUseId,h),c.push(h)}else if(m.type==="chunk"&&m.chunk.type==="tool_result"){let g=m.chunk,h=u.get(g.toolUseId);if(h&&(h.result=g.content,h.isError=g.isError,u.delete(g.toolUseId)),e.onContextProgress){let b=Date.now();if(b-l>=F3){l=b;try{let y=e.onContextProgress();y instanceof Promise&&await y}catch{}}}}else m.type==="done"&&(i=!0,a=m.metadata);n.sink(m)}})}finally{e.setSoftStopHandler?.(null),await n.dispose();try{e.onStageChange?.("observing")}catch{}}if(i&&!r){Bo(e.stats,o,s,a,c);try{e.ui.repaintStatusLine()}catch{}await e.transcript?.appendTurn(o,s).catch(()=>{})}return s}q();import{execFile as N3}from"child_process";import{promisify as B3}from"util";import{writeFileSync as U3}from"fs";import{join as j3}from"path";var H3=B3(N3),W3=4*1024*1024,ew=!1;function tw(e){let t=e.trim();if(!t)return null;if(/^#?\d+$/.test(t)){let r=t.replace(/^#/,""),o=parseInt(r,10);if(!(o>0&&o<1e6))throw new Error(`[afk preflight] Invalid PR number: ${r}. Must be 1\u2013999999.`);return r}let n=t.match(/github\.com\/[^/]+\/[^/]+\/pull\/(\d+)/);if(n&&n[1]){let r=n[1],o=parseInt(r,10);if(!(o>0&&o<1e6))throw new Error(`[afk preflight] Invalid PR number in URL: ${r}. Must be 1\u2013999999.`);return r}return null}async function K3(e,t,n){try{let{stdout:r}=await H3(e,t,{encoding:"utf-8",...n?.cwd?{cwd:n.cwd}:{},maxBuffer:n?.maxBuffer??W3,timeout:8e3});return r}catch(r){if(v.AFK_DEBUG==="1"&&r instanceof Error&&"stderr"in r){let s=String(r.stderr??"").replace(/\x1b\[[0-9;]*m/g,"").slice(0,200).trim();s&&process.stderr.write(`[afk preflight] ${e} stderr: ${s}
|
|
1919
|
+
`}function g3(){let e=v.PAGER;if(e){let t=e.split(/\s+/);return{cmd:t[0],args:t.slice(1)}}return{cmd:"less",args:["-R"]}}var B0={name:"/transcript",aliases:["/t"],summary:"View full session transcript in $PAGER",hint:"When you want to read the full conversation \u2014 all turns, tool calls, costs \u2014 in a scrollable pager.",async handler(e){let{stats:t,out:n}=e;if(t.turns.length===0)return n.info("No turns yet in this session."),"continue";let r=f3(t.turns,String(t.model),t.sessionStartTime,t.totalCostUsd);if(!process.stdout.isTTY)return n.raw(r),"continue";let o=g3();if(!o)return n.raw(r),"continue";let s=N0.join(F0.tmpdir(),`afk-transcript-${Date.now()}.txt`);return await Yb.writeFile(s,r,{mode:384}),new Promise(i=>{let a=u3(o.cmd,[...o.args,s],{stdio:"inherit"});a.on("error",()=>{n.raw(r),Yb.unlink(s).catch(()=>{}),i("continue")}),a.on("exit",()=>{Yb.unlink(s).catch(()=>{}),i("continue")})})}};q();tt();Mt();q();ze();G();ir();import{access as h3,constants as y3,mkdir as b3,readFile as w3}from"fs/promises";import{execSync as S3}from"child_process";async function v3(){return Re()?{name:"Anthropic API Key",state:"pass",detail:"ANTHROPIC_API_KEY set"}:{name:"Anthropic API Key",state:"fail",fix:"Set ANTHROPIC_API_KEY or run `afk login`"}}async function k3(){return hd()?{name:"Codex/OpenAI API Key",state:"pass",detail:"OPENAI_API_KEY or CODEX_API_KEY set"}:{name:"Codex/OpenAI API Key",state:"warn",fix:"Set OPENAI_API_KEY or CODEX_API_KEY to use Codex models"}}async function E3(){try{let t=`${S3("npm config get prefix",{timeout:2e3,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().replace(/\/$/,"")}/bin`;return(v.PATH??"").split(":").map(r=>r.replace(/\/$/,"")).includes(t)?{name:"npm bin on PATH",state:"pass",detail:t}:{name:"npm bin on PATH",state:"fail",detail:t,fix:`Add ${t} to PATH: echo 'export PATH="${t}:$PATH"' >> ~/.zshrc`}}catch{return{name:"npm bin on PATH",state:"warn",detail:"could not query npm prefix"}}}async function Xb(e,t){let n=t();try{return await h3(n,y3.W_OK),{name:e,state:"pass",detail:n}}catch{try{return await b3(n,{recursive:!0}),{name:e,state:"pass",detail:`${n} (created)`}}catch{return{name:e,state:"fail",detail:n,fix:`Unable to create or write to ${n}`}}}}async function T3(){let e=Bt();try{let t=await w3(e,"utf-8");return JSON.parse(t),{name:"Config File",state:"pass",detail:`${e} (valid JSON)`}}catch(t){return t.code==="ENOENT"?{name:"Config File",state:"pass",detail:"no config file (using defaults)"}:{name:"Config File",state:"fail",detail:e,fix:`Unable to parse config file: ${t instanceof Error?t.message:"unknown error"}`}}}async function x3(){let e=LS();return e.length===0?null:{name:"Required env vars",state:"fail",detail:`Missing: ${e.map(t=>t.name).join(", ")}`,fix:"Set these env vars before running. See docs/env-registry.md for descriptions."}}async function R3(){let e=v.AFK_TELEGRAM_BOT_TOKEN;if(!e)return null;try{let t=new AbortController,n=setTimeout(()=>t.abort(),5e3),r=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:t.signal});if(clearTimeout(n),r.ok){let s=(await r.json()).result?.username;return{name:"Telegram Bot",state:"pass",detail:s?`@${s}`:"connected"}}return{name:"Telegram Bot",state:"fail",fix:`Telegram API returned ${r.status}. Check AFK_TELEGRAM_BOT_TOKEN.`}}catch(t){return t.name==="AbortError"?{name:"Telegram Bot",state:"warn",detail:"connection timeout"}:{name:"Telegram Bot",state:"warn",detail:`network error: ${t instanceof Error?t.message:"unknown"}`}}}async function C3(e={}){let t;if(e.detected!==void 0)t=e.detected;else try{t=mu()}catch{return null}let n=e.trusted??Pt()??{},r=t.filter(s=>s.present&&(s.plugins.length>0||s.skills.length>0)&&n[s.binary]===void 0);return r.length===0?null:{name:"Cross-tool import available",state:"warn",detail:r.map(s=>`${s.label} (${s.plugins.length} plugins, ${s.skills.length} skills)`).join("; "),fix:"Run `afk migrate` to import them"}}async function Zp(){let e=[];e.push(await v3()),e.push(await k3()),e.push(await E3()),e.push(await Xb("Config Directory",Qt)),e.push(await Xb("State Directory",Te)),e.push(await Xb("Logs Directory",ks)),e.push(await T3());let t=await x3();t!==null&&e.push(t);let n=await R3();n!==null&&e.push(n);let r=await C3();return r!==null&&e.push(r),e}var A3={name:"/config",summary:"View resolved configuration (model, provider, API keys, env vars)",hint:"When you want to confirm which model and API key the session is using, or check what env vars are active \u2014 same as `afk config` but available mid-session.",async handler(e){let{out:t}=e,n=v.AFK_MODEL??v.CLAUDE_MODEL,r=n??"sonnet",o=re(n),s=v.ANTHROPIC_API_KEY||v.CLAUDE_CODE_OAUTH_TOKEN,i=v.OPENAI_API_KEY||v.CODEX_API_KEY,a=o==="anthropic"?s:i;if(t.line(),t.line(f.bold("Configuration")),t.line(pe()),t.line(` model ${f.info(n?r:`${r} (default)`)}`),t.line(` provider ${f.plan(o)}`),o==="anthropic"){let d=a?f.success("\u2713 set (ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN)"):f.warning("\u26A0 not set \u2014 subprocess falls back to OAuth / keychain");t.line(` api key ${d}`)}else{let d=v.OPENAI_API_KEY?"OPENAI_API_KEY":"CODEX_API_KEY",p=a?f.success(`\u2713 set (${d})`):f.warning("\u26A0 not set \u2014 falling back to `codex login` state");t.line(` api key ${p}`)}t.line(` thinking ${v.AFK_THINKING?f.info(v.AFK_THINKING):f.dim("(unset \u2014 SDK default)")}`),t.line(` effort ${v.AFK_EFFORT?f.info(v.AFK_EFFORT):f.dim("(unset \u2014 SDK default)")}`);let l=Js();t.line(` perm mode ${l==="bypassPermissions"?f.warning(`${l} (bypass \u2014 containment off)`):f.info(`${l} (containment on)`)}`),t.line(),t.line(f.bold("Environment variables")),t.line(pe());let c=[["AFK_MODEL",v.AFK_MODEL??f.dim("unset")],["CLAUDE_MODEL",v.CLAUDE_MODEL??f.dim("unset")],["ANTHROPIC_API_KEY",v.ANTHROPIC_API_KEY?f.success("set"):f.dim("unset")],["CLAUDE_CODE_OAUTH_TOKEN",v.CLAUDE_CODE_OAUTH_TOKEN?f.success("set"):f.dim("unset")],["OPENAI_API_KEY",v.OPENAI_API_KEY?f.success("set"):f.dim("unset")],["CODEX_API_KEY",v.CODEX_API_KEY?f.success("set"):f.dim("unset")],["AFK_THINKING",v.AFK_THINKING??f.dim("unset")],["AFK_EFFORT",v.AFK_EFFORT??f.dim("unset")]],u=Math.max(...c.map(([d])=>d.length))+2;for(let[d,p]of c)t.line(` ${f.meta(d.padEnd(u))} ${p}`);return t.line(),"continue"}},_3={name:"/doctor",summary:"Run system health checks (API keys, directories, config file, Telegram)",hint:"When something feels broken \u2014 API key missing, config file unreadable, Telegram bot unreachable. Same checks as `afk doctor` but surfaced mid-session without exiting.",async handler(e){let{out:t}=e;t.line(),t.line(f.bold("System health checks")),t.line(pe());let n;try{n=await Zp()}catch(a){return t.error(`Health check failed: ${a instanceof Error?a.message:String(a)}`),"continue"}for(let a of n){let l;a.state==="pass"?l=f.success("\u2713"):a.state==="warn"?l=f.warning("\u26A0"):l=f.error("\u2717");let c=` ${l} ${a.name}`;a.detail&&(c+=` \u2014 ${f.dim(a.detail)}`),t.line(c),a.state!=="pass"&&a.fix&&t.line(f.dim(` Fix: ${a.fix}`))}let r=n.filter(a=>a.state==="pass").length,o=n.filter(a=>a.state==="warn").length,s=n.filter(a=>a.state==="fail").length;t.line();let i=[f.success(`${r} passed`),o>0?f.warning(`${o} warned`):f.dim(`${o} warned`),s>0?f.error(`${s} failed`):f.dim(`${s} failed`)];return t.line(` Summary: ${i.join(f.dim(" \xB7 "))}`),t.line(),"continue"}},U0=[A3,_3];zr();Ur();import{readdirSync as n6,readFileSync as r6,statSync as Q0}from"fs";import{join as o6}from"path";G();zr();Dt();import{basename as O3}from"path";import{existsSync as I3,readFileSync as P3}from"fs";import{join as M3}from"path";function es(e){let t=M3(e,".claude-plugin","plugin.json");if(!I3(t))return{name:null,version:null};try{let n=JSON.parse(P3(t,"utf8"));return{name:typeof n.name=="string"&&n.name.trim()?n.name.trim():null,version:typeof n.version=="string"&&n.version.trim()?n.version.trim():null}}catch{return{name:null,version:null}}}function $3(e,t,n){let r=new Set([e]);t&&r.add(t);for(let[o,s]of Object.entries(n)){if(r.has(o))return s;let i=o.includes(":")?o.split(":").pop():o;if(r.has(i)||s.manifestName&&r.has(s.manifestName))return s}return null}function j0(e={}){let t=e.roots??[dc(),Ve(),vs()],n=xe(e.indexPath??ce()),r=[],o=new Set;for(let s of t)for(let i of dr(s)){if(i.type!=="local")continue;let a=i.path,l=O3(a),{name:c,version:u}=es(a),d=c??l;if(o.has(d))continue;o.add(d);let p=$3(l,c,n.plugins);r.push({name:d,version:u,ref:p?.ref??null,commit:p?.commit??null,source:p?.source??null,sourceType:p?.sourceType??null,dir:a})}return r.sort((s,i)=>s.name.localeCompare(i.name)),r}function H0(e){let t;return e.version?t=/^v/i.test(e.version)?e.version:`v${e.version}`:e.ref?t=e.ref:t="(local)",e.commit&&e.commit!==e.ref&&(t+=` @ ${e.commit.slice(0,7)}`),t}G();wt();var Zb=[],D3={name:"/agents",summary:"List plugin-provided subagents (loads after session init)",async handler(e){return e.out.line(),e.out.line(f.dim(" Plugin agents are still loading \u2014 try again after the session is ready.")),e.out.line(),"continue"}};function L3(e){return{name:"/agents",summary:"List Task-tool subagents loaded by the SDK (plugin + user + project)",async handler(t){if(t.out.line(),e.length===0)return t.out.line(f.dim(" No plugin agents loaded. Agents come from `agents:` entries in plugin.json or from ~/.afk/agents/.")),t.out.line(),"continue";t.out.line(f.bold("Plugin agents")+f.dim(` (${e.length} loaded)`)),t.out.line(f.dim("\u2500".repeat(60)));let n=e.reduce((r,o)=>Math.max(r,o.name.length),0)+2;for(let r of e){let o=f.warning(r.name.padEnd(n)),s=r.model?f.dim(`[${r.model}]`):"",i=r.description?f.dim(` ${r.description}`):"";t.out.line(` ${o} ${s}${i}`)}return t.out.line(),t.out.line(f.dim(" Agents are dispatched by the model via the Task tool \u2014 not user-invoked.")),t.out.line(),"continue"}}}async function Qb(e){let t;try{t=await e.supportedAgents()}catch(n){return console.error(f.dim(" \u26A0 Plugin-agent discovery failed: ")+(n instanceof Error?n.message:String(n))),null}return Zb=t.map(n=>{let r={name:n.name,description:n.description};return n.model&&(r.model=n.model),r}),eo(L3(Zb)),Zb.length}function W0(){fe(D3)}ay();Xn();function Qp(e,t){for(let n of t??[])e.push({type:"image",source:{type:"base64",media_type:n.mediaType,data:n.bytes.toString("base64")}})}function K0(e,t,n,r){let o=kp(e.name,t),s=e.context==="fork"?" This skill runs with context: 'fork' \u2014 the executor will fork a subagent.":"",i=`Use the \`skill\` tool with {"name": "${e.name}", "arguments": "${t}"} to dispatch this skill.${s}`,a=[];return n&&n.trim().length>0&&a.push({type:"text",text:n}),a.push({type:"text",text:o}),a.push({type:"text",text:i}),Qp(a,r),a}var F3=15e3;async function em(e,t){let n=zp(e,{skillName:t.skillName,onCancel:()=>{e.session.current.interrupt().catch(()=>{})}}),r=!1,o=`/${t.skillName}${t.args?" "+t.args:""}`;await e.transcript?.appendUser?.(o).catch(()=>{});let s="",i=!1,a,l=0,c=[],u=new Map;try{await n.arm(),e.setSoftStopHandler?.(()=>{r=!0,e.session.current.interrupt().catch(()=>{})});let d;if(t.preflight)try{d=await t.preflight()}catch{d=void 0}let p=K0(t.skillMeta,t.args,d,t.attachments);await Ns(n.sink,async()=>{for await(let m of e.session.current.sendMessageStream(p)){if(r)break;if(m.type==="message"&&m.message.role==="assistant"&&(s=m.message.content),m.type==="chunk"&&m.chunk.type==="tool_use_detail"){let g=m.chunk,h={toolName:g.toolName,toolUseId:g.toolUseId,input:g.toolInput};u.set(g.toolUseId,h),c.push(h)}else if(m.type==="chunk"&&m.chunk.type==="tool_result"){let g=m.chunk,h=u.get(g.toolUseId);if(h&&(h.result=g.content,h.isError=g.isError,u.delete(g.toolUseId)),e.onContextProgress){let b=Date.now();if(b-l>=F3){l=b;try{let y=e.onContextProgress();y instanceof Promise&&await y}catch{}}}}else m.type==="done"&&(i=!0,a=m.metadata);n.sink(m)}})}finally{e.setSoftStopHandler?.(null),await n.dispose();try{e.onStageChange?.("observing")}catch{}}if(i&&!r){Bo(e.stats,o,s,a,c);try{e.ui.repaintStatusLine()}catch{}await e.transcript?.appendTurn(o,s).catch(()=>{})}return s}q();import{execFile as N3}from"child_process";import{promisify as B3}from"util";import{writeFileSync as U3}from"fs";import{join as j3}from"path";var H3=B3(N3),W3=4*1024*1024,ew=!1;function tw(e){let t=e.trim();if(!t)return null;if(/^#?\d+$/.test(t)){let r=t.replace(/^#/,""),o=parseInt(r,10);if(!(o>0&&o<1e6))throw new Error(`[afk preflight] Invalid PR number: ${r}. Must be 1\u2013999999.`);return r}let n=t.match(/github\.com\/[^/]+\/[^/]+\/pull\/(\d+)/);if(n&&n[1]){let r=n[1],o=parseInt(r,10);if(!(o>0&&o<1e6))throw new Error(`[afk preflight] Invalid PR number in URL: ${r}. Must be 1\u2013999999.`);return r}return null}async function K3(e,t,n){try{let{stdout:r}=await H3(e,t,{encoding:"utf-8",...n?.cwd?{cwd:n.cwd}:{},maxBuffer:n?.maxBuffer??W3,timeout:8e3});return r}catch(r){if(v.AFK_DEBUG==="1"&&r instanceof Error&&"stderr"in r){let s=String(r.stderr??"").replace(/\x1b\[[0-9;]*m/g,"").slice(0,200).trim();s&&process.stderr.write(`[afk preflight] ${e} stderr: ${s}
|
|
1920
1920
|
`)}return null}}async function G3(e,t,n={}){let r=n.exec??K3,o=n.writeFile??((m,g)=>U3(m,g,"utf-8")),[s,i,a]=await Promise.all([r("gh",["pr","view",e,"--json","title,baseRefName,headRefName,additions,deletions,changedFiles,files"],{cwd:t.cwd}),r("gh",["pr","diff",e],{cwd:t.cwd}),r("git",["status","--porcelain"],{cwd:t.cwd})]),l=null;if(s)try{l=JSON.parse(s)}catch{l=null}let c=null,u=null;if(i!==null){let m=j3(t.artifactDir,`pr-${e}.diff`);try{o(m,i),c=m,u=i.trimEnd().split(`
|
|
1921
1921
|
`).length}catch{}}let d=a?a.split(`
|
|
1922
1922
|
`).filter(m=>m.trim().length>0).length:0,p=d>0;return{pr:e,metadata:l,diffPath:c,diffLineCount:u,dirty:p,dirtyFiles:d}}function tm(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/[\r\n]/g,"")}function q3(e){let t=[];if(t.push(`<preflight-context skill="review" pr="${e.pr}">`),e.metadata){let n=e.metadata;n.title&&t.push(`Title: ${tm(n.title)}`),n.baseRefName&&n.headRefName&&t.push(`Branch: ${tm(n.headRefName)} \u2192 ${tm(n.baseRefName)}`);let r=[];if(n.additions!==void 0&&r.push(`+${n.additions}`),n.deletions!==void 0&&r.push(`-${n.deletions}`),n.changedFiles!==void 0&&r.push(`${n.changedFiles} file${n.changedFiles===1?"":"s"}`),r.length>0&&t.push(`Stats: ${r.join(" / ")}`),n.files&&n.files.length>0){let s=n.files.filter(i=>!!i.path);t.push("Files changed:");for(let i of s.slice(0,40)){let a=i.additions!==void 0?`+${i.additions}`:"",l=i.deletions!==void 0?`-${i.deletions}`:"",c=a||l?` (${[a,l].filter(Boolean).join("/")})`:"";t.push(` - ${tm(i.path)}${c}`)}s.length>40&&t.push(` \u2026and ${s.length-40} more (see diff artifact)`)}}else t.push("PR metadata: UNAVAILABLE (gh pr view failed \u2014 check `gh auth status`)");return e.diffPath&&e.diffLineCount!==null?t.push(`Diff artifact: ${e.diffPath} (${e.diffLineCount} lines)`):t.push("Diff artifact: UNAVAILABLE (gh pr diff failed)"),e.dirty?(t.push(`Working tree: DIRTY (${e.dirtyFiles} uncommitted change${e.dirtyFiles===1?"":"s"})`),t.push(" \u2192 DO NOT stash, commit, reset, or otherwise mutate the working tree."),t.push(" \u2192 Review is read-only. The user is mid-work; preserve their state.")):(t.push("Working tree: clean"),t.push(" \u2192 Review is read-only. Do not stash, commit, or modify files.")),t.push("Capabilities: compose available, subagents available."),t.push("Use the diff artifact path above instead of re-running `gh pr diff`."),t.push("</preflight-context>"),t.join(`
|
|
@@ -1929,7 +1929,7 @@ ${t}`}var X0=!1;function Z0(){X0||(X0=!0,nw("review",G0),z0())}q();var s6=new Se
|
|
|
1929
1929
|
`);if(V(o.display)>n-1){e.out.line(" "+f.warning(o.display));for(let a of i)e.out.line(" "+" ".repeat(n)+f.dim(a))}else{let a=Qe(f.warning(o.display),n);e.out.line(" "+a+f.dim(i[0]??""));for(let l of i.slice(1))e.out.line(" "+" ".repeat(n)+f.dim(l))}if(s.length>0){let a=s.map(l=>l.slashName).join(", ");for(let l of le(`\u21B3 also: ${a}`,r).split(`
|
|
1930
1930
|
`))e.out.line(" "+" ".repeat(n)+f.dim(l))}}function iO(e,t,n){let r=i6(t,n);if(e.out.line(),r.size===0){e.out.line(f.dim(" No skills available. Built-in skills should always load \u2014 check your install.")),e.out.line();return}let o=Array.from(r.values()),s=o.reduce((g,h)=>g+h.alts.length,0),i=o.filter(g=>g.main.source==="builtin").sort(nO),a=o.filter(g=>g.main.source!=="builtin").sort(nO),l=Math.max(20,Q()),c=o.reduce((g,h)=>Math.max(g,V(h.main.display)),0),u=Math.min(c+2,Math.max(10,Math.floor((l-2)*.45))),d=Math.max(12,l-2-u);e.out.line(f.bold("Skills")+f.dim(` (${o.length})`));let p=new Set(o.map(g=>g.main.source)),m=["builtin","user","project","plugin"].filter(g=>p.has(g)).map(iw).join(" \xB7 ");if(e.out.line(f.dim(` ${m} \u2014 /skills <name> for details`)),i.length>0){e.out.line(),e.out.line(pe("Built-in"));for(let g of i)rO(e,g,u,d)}if(a.length>0){e.out.line(),e.out.line(i.length>0?pe("Plugins & user skills"):pe());for(let g of a)rO(e,g,u,d)}e.out.line(),e.out.line(f.dim(s>0?" Tip: \u21B3 also lines show alternative (shadowed) forms \xB7 /skills <name> for full details":" Tip: /skills <name> for full details on a skill")),e.out.line()}function a6(e,t){try{let n=Ke(e);return nn(n,t)?n:void 0}catch{return}}function l6(e,t){let n=[];for(let r of Yf(t))if(r.includes(":")&&Un(r)===e){let o=aw(Ke(r).origin);n.push({slash:`/${r}`,source:o})}for(let r of rs.collisions)r.bare===e&&n.push({slash:r.altSlash,source:"plugin"});return n}function aO(e,t,n,r){let o=t.replace(/^\//,"").trim(),s=a6(o,r),i=n.find(y=>Un(y.name)===o||y.name===o);if(!s&&!i){e.out.line(),e.out.line(f.dim(` No skill found matching "${o}".`)),e.out.line(f.dim(" Run /skills to see everything available.")),e.out.line();return}let a=s?.name??Un(i.name),l=s?.description??i.description,c=s?.argumentHint??i?.argumentHint,u=c?`/${a} ${c}`:`/${a}`,d=s?aw(s.origin):"plugin",p=Math.max(20,Q()),m=Math.max(20,Math.min(p-2,100));e.out.line(),e.out.line(` ${f.warning(u)}`),e.out.line();for(let y of le(l,m).split(`
|
|
1931
1931
|
`))e.out.line(` ${y}`);let g=s?.whenToUse??sO(l);if(g&&g!==l.trim()){e.out.line(),e.out.line(` ${f.bold("When to use")}`);for(let y of le(g,m).split(`
|
|
1932
|
-
`))e.out.line(` ${f.dim(y)}`)}let h=s?.flags??oO().get(o);h&&h.length>0&&(e.out.line(),e.out.line(` ${f.bold("Flags")} ${f.dim(h.join(", "))}`)),e.out.line(),e.out.line(` ${f.bold("Source")} ${f.dim(iw(d))}`);let b=l6(a,r);if(b.length>0){e.out.line(),e.out.line(` ${f.bold("Alternatives")}`);for(let y of b)e.out.line(` ${f.dim("\u21B3")} ${f.warning(y.slash)} ${f.dim(`(${iw(y.source)} \u2014 shadowed by /${a})`)}`)}e.out.line()}var c6={name:"/skills",aliases:["/builtin-skills"],summary:"List all skills available in this session \u2014 vendored, user, and plugin",usage:"/skills [name]",hint:"When you want to browse every skill the session can dispatch \u2014 pass a name for full details on one.",async handler(e,t){let n=v.AFK_INTERNAL==="1",r=t.trim();return r&&!r.startsWith("-")?aO(e,r,[],n):iO(e,[],n),"continue"}};function u6(e){return{name:"/skills",aliases:["/builtin-skills"],summary:"List all skills available in this session \u2014 vendored, user, and plugin",usage:"/skills [name]",hint:"When you want to browse every skill the session can dispatch \u2014 pass a name for full details on one.",async handler(t,n){let r=v.AFK_INTERNAL==="1",o=n.trim();return o&&!o.startsWith("-")?aO(t,o,e,r):iO(t,e,r),"continue"}}}async function lO(e){let t;try{t=await e.supportedCommands()}catch(l){return console.error(f.dim(" \u26A0 Plugin-skill discovery failed: ")+(l instanceof Error?l.message:String(l))),null}let n=t.map(l=>({name:l.name,description:l.description,...l.argumentHint?{argumentHint:l.argumentHint}:{}})),r=oO(),o=v.AFK_INTERNAL==="1",s=new Set(Vn().filter(l=>nn(Ke(l),o)).map(Un)),i=[],a=new Set;for(let l of n){let c=`/${l.name}`;if(s6.has(c))continue;let u=Un(l.name),d=r.get(u);if(s.has(u)){let p=l.name.includes(":")?l.name:`plugin:${l.name}`,m={...l,name:p};eo(tO(m,d)),i.push({bare:u,altSlash:`/${p}`,altDescription:l.description}),a.add(u);continue}eo(tO(l,d))}return rs={discovered:n,collisions:i,shadowedBareNames:a},eo(u6(n)),n.length}function cO(){return rs.collisions.length===0?[]:rs.collisions.map(e=>f.dim(` /${e.bare}: vendored or user skill wins; plugin form ${e.altSlash} stays reachable.`))}async function rm(e){let[t,n]=await Promise.all([lO(e),Qb(e)]);return{skillCount:t,agentCount:n}}function d6(e){let t={builtin:0,plugin:0,user:0,project:0,imported:0};for(let r of e)t[r.source]++;return[["builtin","built-in"],["plugin","plugin"],["user","user"],["project","project"],["imported","imported"]].filter(([r])=>t[r]>0).map(([r,o])=>`${t[r]} ${o}`).join(" \xB7 ")}function p6(e,t){return e.size===0?null:{added:[...t].filter(n=>!e.has(n)).sort(),removed:[...e].filter(n=>!t.has(n)).sort()}}function m6(e){let{added:t,removed:n}=e;if(t.length===0&&n.length===0)return"";let r=[];t.length&&r.push(`+${t.length}`),n.length&&r.push(`\u2212${n.length}`);let o=`${r.join(" ")} since last reload`,s=[];return t.length>0&&t.length<=3&&s.push(`new: ${t.map(i=>`/${i}`).join(", ")}`),n.length>0&&n.length<=3&&s.push(`gone: ${n.map(i=>`/${i}`).join(", ")}`),s.length>0&&(o+=` (${s.join("; ")})`),o}function f6(e){if(e.length===0)return[];let t=8,n=e.slice(0,t),r=Math.min(24,n.reduce((s,i)=>Math.max(s,i.name.length),0)),o=n.map(s=>f.dim(` ${s.name.padEnd(r)} ${H0(s)}`));return e.length>t&&o.push(f.dim(` \u2026and ${e.length-t} more`)),o}var g6={name:"/reload-plugins",summary:"Reload plugin skills from disk and refresh the slash registry",async handler(e){e.out.line(),e.out.info("Reloading plugins\u2026");let t=new Set(rs.discovered.map(a=>a.name));ur();try{let a=e.session.current.getQuery();typeof a.reloadPlugins=="function"&&await a.reloadPlugins()}catch(a){e.out.warn(`Plugin reload failed: ${a instanceof Error?a.message:String(a)}`)}let[n,r]=await Promise.all([lO(e.session.current),Qb(e.session.current)]);if(n===null&&r===null)return e.out.error("Could not refresh plugin skills or agents."),e.out.line(),"continue";let o=j0(),s=[];n!==null&&s.push(`${n} skill${n===1?"":"s"}`),r!==null&&s.push(`${r} agent${r===1?"":"s"}`);let i=o.length>0?` from ${o.length} plugin${o.length===1?"":"s"}`:"";if(e.out.success(`Reloaded ${s.join(" + ")}${i}.`),n!==null){let a=d6(cr()),l=p6(t,new Set(rs.discovered.map(d=>d.name))),c=l?m6(l):"",u=[a,c].filter(d=>d.length>0);u.length>0&&e.out.line(f.dim(` ${u.join(" \xB7 ")}`))}for(let a of f6(o))e.out.line(a);return e.out.line(),"continue"}};function uO(){fe(c6),fe(g6)}
|
|
1932
|
+
`))e.out.line(` ${f.dim(y)}`)}let h=s?.flags??oO().get(o);h&&h.length>0&&(e.out.line(),e.out.line(` ${f.bold("Flags")} ${f.dim(h.join(", "))}`)),e.out.line(),e.out.line(` ${f.bold("Source")} ${f.dim(iw(d))}`);let b=l6(a,r);if(b.length>0){e.out.line(),e.out.line(` ${f.bold("Alternatives")}`);for(let y of b)e.out.line(` ${f.dim("\u21B3")} ${f.warning(y.slash)} ${f.dim(`(${iw(y.source)} \u2014 shadowed by /${a})`)}`)}e.out.line()}var c6={name:"/skills",aliases:["/builtin-skills"],summary:"List all skills available in this session \u2014 vendored, user, and plugin",usage:"/skills [name]",hint:"When you want to browse every skill the session can dispatch \u2014 pass a name for full details on one.",async handler(e,t){let n=v.AFK_INTERNAL==="1",r=t.trim();return r&&!r.startsWith("-")?aO(e,r,[],n):iO(e,[],n),"continue"}};function u6(e){return{name:"/skills",aliases:["/builtin-skills"],summary:"List all skills available in this session \u2014 vendored, user, and plugin",usage:"/skills [name]",hint:"When you want to browse every skill the session can dispatch \u2014 pass a name for full details on one.",async handler(t,n){let r=v.AFK_INTERNAL==="1",o=n.trim();return o&&!o.startsWith("-")?aO(t,o,e,r):iO(t,e,r),"continue"}}}async function lO(e){let t;try{t=await e.supportedCommands()}catch(l){return console.error(f.dim(" \u26A0 Plugin-skill discovery failed: ")+(l instanceof Error?l.message:String(l))),null}let n=t.map(l=>({name:l.name,description:l.description,...l.argumentHint?{argumentHint:l.argumentHint}:{}})),r=oO(),o=v.AFK_INTERNAL==="1",s=new Set(Vn().filter(l=>nn(Ke(l),o)).map(Un)),i=[],a=new Set;for(let l of n){let c=`/${l.name}`;if(s6.has(c))continue;let u=Un(l.name),d=r.get(u);if(s.has(u)){let p=l.name.includes(":")?l.name:`plugin:${l.name}`,m={...l,name:p};eo(tO(m,d)),i.push({bare:u,altSlash:`/${p}`,altDescription:l.description}),a.add(u);continue}eo(tO(l,d))}return rs={discovered:n,collisions:i,shadowedBareNames:a},eo(u6(n)),n.length}function cO(){return rs.collisions.length===0?[]:rs.collisions.map(e=>f.dim(` /${e.bare}: vendored or user skill wins; plugin form ${e.altSlash} stays reachable.`))}async function rm(e){let[t,n]=await Promise.all([lO(e),Qb(e)]);return{skillCount:t,agentCount:n}}function d6(e){let t={builtin:0,plugin:0,user:0,project:0,imported:0};for(let r of e)t[r.source]++;return[["builtin","built-in"],["plugin","plugin"],["user","user"],["project","project"],["imported","imported"]].filter(([r])=>t[r]>0).map(([r,o])=>`${t[r]} ${o}`).join(" \xB7 ")}function p6(e,t){return e.size===0?null:{added:[...t].filter(n=>!e.has(n)).sort(),removed:[...e].filter(n=>!t.has(n)).sort()}}function m6(e){let{added:t,removed:n}=e;if(t.length===0&&n.length===0)return"";let r=[];t.length&&r.push(`+${t.length}`),n.length&&r.push(`\u2212${n.length}`);let o=`${r.join(" ")} since last reload`,s=[];return t.length>0&&t.length<=3&&s.push(`new: ${t.map(i=>`/${i}`).join(", ")}`),n.length>0&&n.length<=3&&s.push(`gone: ${n.map(i=>`/${i}`).join(", ")}`),s.length>0&&(o+=` (${s.join("; ")})`),o}function f6(e){if(e.length===0)return[];let t=8,n=e.slice(0,t),r=Math.min(24,n.reduce((s,i)=>Math.max(s,i.name.length),0)),o=n.map(s=>f.dim(` ${s.name.padEnd(r)} ${H0(s)}`));return e.length>t&&o.push(f.dim(` \u2026and ${e.length-t} more`)),o}var g6={name:"/reload-plugins",summary:"Reload plugin skills from disk and refresh the slash registry",async handler(e){e.out.line(),e.out.info("Reloading plugins\u2026");let t=new Set(rs.discovered.map(a=>a.name));ur();try{let a=e.session.current.getQuery();typeof a.reloadPlugins=="function"&&await a.reloadPlugins()}catch(a){e.out.warn(`Plugin reload failed: ${a instanceof Error?a.message:String(a)}`)}let[n,r]=await Promise.all([lO(e.session.current),Qb(e.session.current)]);if(n===null&&r===null)return e.out.error("Could not refresh plugin skills or agents."),e.out.line(),"continue";let o=j0(),s=[];n!==null&&s.push(`${n} skill${n===1?"":"s"}`),r!==null&&s.push(`${r} agent${r===1?"":"s"}`);let i=o.length>0?` from ${o.length} plugin${o.length===1?"":"s"}`:"";if(e.out.success(`Reloaded ${s.join(" + ")}${i}.`),n!==null){let a=d6(cr()),l=p6(t,new Set(rs.discovered.map(d=>d.name))),c=l?m6(l):"",u=[a,c].filter(d=>d.length>0);u.length>0&&e.out.line(f.dim(` ${u.join(" \xB7 ")}`))}for(let a of f6(o))e.out.line(a);return e.out.line(),"continue"}};function uO(){fe(c6),fe(g6)}wt();uy();ir();G();q();function h6(e){let t=e??"builtin";return t==="builtin"||t==="user"||t==="project"?t:t.startsWith("imported:")?"imported":"user"}function y6(e){let t=`/${e.name}`,n=e.argumentHint?`${t} ${e.argumentHint}`:void 0;return{name:t,summary:e.description,acceptsAttachments:!0,...n!==void 0?{usage:n}:{},...e.whenToUse?{hint:e.whenToUse}:{},...e.flags&&e.flags.length>0?{flags:e.flags}:{},async handler(r,o,s){try{await em(r,{skillName:e.name,skillMeta:e,args:o,attachments:s,preflight:async()=>{let i={skillName:e.name,rawArgs:o,source:h6(e.origin),capabilities:{compose:!0,subagents:!0}},a=r.session.current.sessionId,l=ns(a);return(await ts(i,{cwd:r.stats.cwd??process.cwd(),artifactDir:l},u=>{v.AFK_SKILL_STREAM_VERBOSE==="1"&&r.out.warn(`preflight(${e.name}) failed: ${u instanceof Error?u.message:String(u)}`)}))?.manifestBlock}})}catch(i){r.out.line(),r.out.error(`${e.name} failed: ${i instanceof Error?i.message:String(i)}`)}return"continue"}}}function dO(){Z0(),ly(),fr(uc(),"project");for(let{dir:t,origin:n}of rn(Pt()).skillRoots)fr(t,n);let e=v.AFK_INTERNAL==="1";for(let t of Vn()){let n=Ke(t);nn(n,e)&&eo(y6(n))}}G();import{existsSync as Hl,mkdirSync as Z6,renameSync as Q6,rmSync as eX,symlinkSync as tX,lstatSync as nX,unlinkSync as rX}from"fs";import{basename as oX,join as mw}from"path";G();import{existsSync as lo,mkdirSync as O6,readFileSync as $6,realpathSync as hO,renameSync as D6,rmSync as L6,symlinkSync as F6,lstatSync as N6,unlinkSync as B6}from"fs";import{basename as yO,dirname as U6,join as ss,resolve as cw,relative as j6}from"path";import{existsSync as pO}from"fs";import{isAbsolute as b6,resolve as gO}from"path";import{homedir as mO}from"os";var w6=/^(?:https?:\/\/|git:\/\/|ssh:\/\/|git\+ssh:\/\/|file:\/\/|git@[^:]+:)/,S6=/^([a-zA-Z0-9][a-zA-Z0-9_.-]*)\/([a-zA-Z0-9][a-zA-Z0-9._-]*?)(?:\.git)?$/,v6=/^([a-zA-Z0-9][a-zA-Z0-9_.-]*):([a-zA-Z0-9][a-zA-Z0-9_.-]*)$/;function k6(e){return e==="~"?mO():e.startsWith("~/")?gO(mO(),e.slice(2)):e}function om(e){if(!e.startsWith("https://"))throw new Error(`Plugin source must use https:// (got: ${e}). git://, http://, ssh://, file://, and git@ are rejected to avoid downgrade attacks and unauthenticated clones.`)}function Vi(e){let t=e.trim();if(!t)throw new Error('plugin source is required (examples: "owner/repo", "https://github.com/owner/repo.git", "./my-plugin")');if(E6(t)){let o=fO(t);if(!pO(o))throw new Error(`could not resolve plugin source: "${t}" looks like a local path but does not exist on disk`);return{type:"local",path:o}}if(w6.test(t))return{type:"git",url:t};let n=v6.exec(t);if(n&&n[1]&&n[2])return{type:"marketplace-ref",marketplace:n[1],plugin:n[2]};let r=S6.exec(t);if(r&&r[1]&&r[2]){let o=r[1],s=r[2];return{type:"github",owner:o,repo:s,url:`https://github.com/${o}/${s}.git`}}if(pO(t))return{type:"local",path:fO(t)};throw new Error(`could not resolve plugin source: "${t}". Use a git URL (https://\u2026/repo.git), GitHub shorthand (owner/repo), or a local path to a directory that exists on disk.`)}function E6(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("~")||e.startsWith("/")}function fO(e){let t=k6(e);return b6(t)?t:gO(process.cwd(),t)}import{execFile as T6}from"child_process";import{promisify as x6}from"util";var R6=x6(T6),os=async(e,t,n)=>{try{let{stdout:r,stderr:o}=await R6("git",Array.from(e),{cwd:t,env:n,maxBuffer:20971520});return{stdout:r,stderr:o}}catch(r){throw C6(r)&&r.code==="ENOENT"?new Error("git not found on PATH \u2014 install git first"):r}};function C6(e){return typeof e=="object"&&e!==null&&"code"in e}var A6=Object.freeze(["-c","core.hooksPath=/dev/null","-c","filter.process=","-c","filter.smudge=","-c","filter.clean="]);function lw(e){return[...A6,...e]}async function sm(e,t,n={}){await(n.runner??os)(lw(["clone","--",e,t]),void 0,n.env)}async function im(e,t={}){await(t.runner??os)(lw(["fetch","--tags","--prune"]),e,t.env)}async function so(e,t={}){let n=t.runner??os,{stdout:r}=await n(["tag","--list","--sort=-v:refname"],e,t.env);return r.split(`
|
|
1933
1933
|
`).map(o=>o.trim()).filter(Boolean)}async function io(e,t,n={}){let r=n.runner??os,o=["checkout","--detach"];n.force&&o.push("--force"),o.push(t),await r(lw(o),e,n.env)}async function jn(e,t={}){let n=t.runner??os,{stdout:r}=await n(["rev-parse","HEAD"],e,t.env);return r.trim()}async function am(e,t,n={}){let r=n.runner??os;try{let{stdout:o}=await r(["rev-parse","--verify","--quiet",t],e,n.env);return o.trim()||null}catch{return null}}async function Hn(e,t={}){let n=t.runner??os;try{let{stdout:r}=await n(["symbolic-ref","refs/remotes/origin/HEAD","--short"],e,t.env);return r.trim().replace(/^origin\//,"")||"main"}catch{return"main"}}Dt();var _6=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function I6(e){let t=_6.exec(e);if(!t)return null;let[,n,r,o,s]=t;return{raw:e,major:Number(n),minor:Number(r),patch:Number(o),prerelease:s??null}}function P6(e,t){if(e===null&&t===null)return 0;if(e===null)return 1;if(t===null)return-1;let n=e.split("."),r=t.split("."),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){let i=n[s],a=r[s];if(i===void 0)return-1;if(a===void 0)return 1;let l=/^\d+$/.test(i),c=/^\d+$/.test(a);if(l&&c){let u=Number(i)-Number(a);if(u!==0)return u}else{if(l)return-1;if(c)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function M6(e,t){return e.major!==t.major?e.major-t.major:e.minor!==t.minor?e.minor-t.minor:e.patch!==t.patch?e.patch-t.patch:P6(e.prerelease,t.prerelease)}function ao(e){let t=e.map(n=>I6(n.trim())).filter(n=>n!==null);return t.length===0?null:(t.sort((n,r)=>M6(r,n)),t[0]?.raw??null)}zr();async function um(e,t={},n={}){let r=n.pluginsDir??Ve(),o=n.indexPath??ce(),s=n.now??(()=>new Date),i=n.gitRunner?{runner:n.gitRunner}:{},a=n.confirm??!0,l=n.confirmDelayMs??3e3,c=Vi(e);if(O6(r,{recursive:!0}),c.type==="local")return H6(c,t,r,o,s);if(c.type==="marketplace-ref")throw new Error(`marketplace-ref source "${c.marketplace}:${c.plugin}" must be installed via the marketplace resolver, not installPlugin directly`);return om(c.url),W6(c,t,r,o,s,i,{confirm:a,confirmDelayMs:l})}function H6(e,t,n,r,o){bO(e.path);let s=wO(e.path),i=t.name??s??yO(e.path);Sr(i);let a=ss(n,i);is(a,n),uw(a,t.force??!1),(lo(a)||dw(a))&&cm(a),F6(e.path,a,"dir");let l=o().toISOString(),c={source:e.path,sourceType:"local",ref:null,commit:null,enabled:!0,installedAt:l,updatedAt:l,...s&&s!==i?{manifestName:s}:{}};return qr(i,c,r),ur(),{name:i,dir:a,entry:c}}async function W6(e,t,n,r,o,s,i){let a=t.name??G6(e);Sr(a);let l=ss(n,a);is(l,n),uw(l,t.force??!1),lo(l)&&cm(l);let c=e.type==="github"?`${e.owner}/${e.repo}`:e.url;i.confirm&&await q6(e.url,i.confirmDelayMs),await sm(e.url,l,s);try{let u;if(t.ref)u=t.ref;else{let y=await so(l,s);u=ao(y)??await Hn(l,s)}(t.ref||await K6(l,u,s))&&await io(l,u,s);let d=await jn(l,s);bO(l);let p=wO(l),m=a,g=l;if(!t.name&&p&&p!==a){Sr(p);let y=ss(n,p);is(y,n),uw(y,t.force??!1),lo(y)&&cm(y),D6(l,y),m=p,g=y}let h=o().toISOString(),b={source:c,sourceType:e.type,ref:u,commit:d,enabled:!0,installedAt:h,updatedAt:h,...p&&p!==m?{manifestName:p}:{}};return qr(m,b,r),ur(),{name:m,dir:g,entry:b}}catch(u){try{lo(l)&&cm(l)}catch{}throw u}}async function K6(e,t,n){let r=await Hn(e,n);return t!==r}function G6(e){if(e.type==="github")return e.repo;let t=e.url.replace(/\.git$/,""),n=t.lastIndexOf("/"),r=t.lastIndexOf(":"),o=Math.max(n,r);return o>=0?t.slice(o+1):t}async function q6(e,t){let n="\u2550".repeat(70),r=o=>process.stderr.write(o+`
|
|
1934
1934
|
`);if(r(""),r(n),r(" \u26A0\uFE0F PLUGIN INSTALL WARNING \u2014 READ BEFORE CONTINUING"),r(n),r(""),r(` Source : ${e}`),r(""),r(" Installing a plugin grants ARBITRARY CODE EXECUTION to whoever controls"),r(" that git ref. The plugin's SKILL.md becomes a system prompt that runs"),r(" inside a subagent with full tool access (bash, write_file, web_scrape,"),r(" and any other tool enabled in your session)."),r(""),r(" \u25BA Audit the repository source code before proceeding."),r(" \u25BA Only install plugins from authors you trust."),r(" \u25BA Run `afk plugin install --yes <source>` to suppress this warning."),r(""),t>0){let o=Math.ceil(t/1e3);r(` Proceeding in ${o} second(s)\u2026 Press Ctrl-C to abort.`),r(""),await new Promise(s=>setTimeout(s,t))}r(n),r("")}function bO(e){let t=ss(e,".claude-plugin","plugin.json");if(lo(t))return;let n=ss(e,".claude-plugin","marketplace.json");if(lo(n))throw new Error(`${e} contains .claude-plugin/marketplace.json instead of plugin.json. Use \`afk marketplace install <source>\` to install a marketplace, then \`afk plugin install <marketplace>:<plugin>\` to install a plugin from it.`)}function wO(e){let t=ss(e,".claude-plugin","plugin.json");if(!lo(t))return null;try{let n=JSON.parse($6(t,"utf8"));return typeof n.name=="string"&&n.name.trim()?n.name.trim():null}catch{return null}}var z6=/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;function Sr(e){if(!e||e.length>100||!z6.test(e))throw new Error(`Invalid plugin name "${e}": must be 1\u2013100 chars, starting with alphanumeric, containing only letters, digits, hyphens, or underscores.`)}function is(e,t){let n;try{n=hO(cw(t))}catch{n=cw(t)}let r=cw(e),o;try{o=ss(hO(U6(r)),yO(r))}catch{o=r}let s=j6(n,o);if(s.startsWith("..")||s==="")throw new Error(`Path traversal detected: resolved path "${e}" escapes plugin dir "${t}"`);if(s.startsWith("/"))throw new Error(`Path traversal detected: resolved path "${e}" escapes plugin dir "${t}"`)}function uw(e,t){if(!(!lo(e)&&!dw(e))&&!t)throw new Error(`plugin directory already exists: ${e} (re-run with --force to replace)`)}function dw(e){try{return N6(e).isSymbolicLink()}catch{return!1}}function cm(e){if(dw(e)){B6(e);return}L6(e,{recursive:!0,force:!0})}Dt();import{existsSync as vO,readFileSync as J6}from"fs";import{join as V6}from"path";var Y6=".claude-plugin/marketplace.json";function kO(e){return V6(e,Y6)}function pw(e){return vO(kO(e))}function vr(e){let t=kO(e);if(!vO(t))throw new Error(`marketplace manifest not found: ${t}`);let n;try{n=J6(t,"utf8")}catch(o){throw new Error(`could not read marketplace manifest at ${t}: ${SO(o)}`)}let r;try{r=JSON.parse(n)}catch(o){throw new Error(`marketplace manifest at ${t} is not valid JSON: ${SO(o)}`)}return X6(r,t)}function EO(e){try{return vr(e)}catch{return null}}function X6(e,t){if(!e||typeof e!="object")throw new Error(`marketplace manifest at ${t} must be a JSON object`);let n=e,r=n.name;if(typeof r!="string"||!r.trim())throw new Error(`marketplace manifest at ${t} is missing required "name" field`);let o=n.plugins;if(!Array.isArray(o))throw new Error(`marketplace manifest at ${t} is missing required "plugins" array`);let s=new Set,i=o.map((u,d)=>{if(!u||typeof u!="object")throw new Error(`marketplace manifest at ${t}: plugins[${d}] must be an object`);let p=u,m=p.name,g=p.source;if(typeof m!="string"||!m.trim())throw new Error(`marketplace manifest at ${t}: plugins[${d}] missing required "name"`);if(typeof g!="string"||!g.trim())throw new Error(`marketplace manifest at ${t}: plugins[${d}] missing required "source"`);let h=m.trim();if(s.has(h))throw new Error(`marketplace manifest at ${t}: duplicate plugin name "${h}"`);s.add(h);let b={name:h,source:g.trim()},y=p.description;return typeof y=="string"&&(b.description=y),b}),a={name:r.trim(),plugins:i},l=n.metadata;if(l&&typeof l=="object"){let u=l,d={};typeof u.description=="string"&&(d.description=u.description),Object.keys(d).length>0&&(a.metadata=d)}let c=n.owner;if(c&&typeof c=="object"){let u=c,d={};typeof u.name=="string"&&(d.name=u.name),typeof u.email=="string"&&(d.email=u.email),Object.keys(d).length>0&&(a.owner=d)}return a}function SO(e){return e instanceof Error?e.message:String(e)}async function pm(e,t={},n={}){let r=n.cacheDir??Kn(),o=n.indexPath??ce(),s=n.now??(()=>new Date),i=n.gitRunner?{runner:n.gitRunner}:{},a=Vi(e);if(a.type==="marketplace-ref")throw new Error(`marketplace source cannot itself be a marketplace reference ("${e}")`);return Z6(r,{recursive:!0}),a.type==="local"?sX(a,t,r,o,s):iX(a,t,r,o,s,i)}function sX(e,t,n,r,o){let s=vr(e.path),i=t.name??s.name;Sr(i);let a=mw(n,i);is(a,n),fw(a,t.force??!1),(Hl(a)||gw(a))&&dm(a),tX(e.path,a,"dir");let l=o().toISOString(),c={source:e.path,sourceType:"local",ref:null,commit:null,installedAt:l,updatedAt:l};return sl(i,c,r),{name:i,dir:a,entry:c,plugins:s.plugins.map(TO)}}async function iX(e,t,n,r,o,s){om(e.url);let i=t.name??lX(e);Sr(i);let a=mw(n,i);is(a,n),fw(a,t.force??!1),Hl(a)&&dm(a);let l=e.type==="github"?`${e.owner}/${e.repo}`:e.url;await sm(e.url,a,s);try{let c;if(t.ref)c=t.ref;else{let b=await so(a,s);c=ao(b)??await Hn(a,s)}(t.ref||await aX(a,c,s))&&await io(a,c,s);let u=await jn(a,s),d=vr(a),p=i,m=a;if(!t.name&&d.name!==i){Sr(d.name);let b=mw(n,d.name);is(b,n),fw(b,t.force??!1),Hl(b)&&dm(b),Q6(a,b),p=d.name,m=b}let g=o().toISOString(),h={source:l,sourceType:e.type,ref:c,commit:u,installedAt:g,updatedAt:g};return sl(p,h,r),{name:p,dir:m,entry:h,plugins:d.plugins.map(TO)}}catch(c){try{Hl(a)&&dm(a)}catch{}throw c}}async function aX(e,t,n){let r=await Hn(e,n);return t!==r}function lX(e){if(e.type==="github")return e.repo;let t=e.url.replace(/\.git$/,""),n=t.lastIndexOf("/"),r=t.lastIndexOf(":"),o=Math.max(n,r);return o>=0?t.slice(o+1):oX(t)}function fw(e,t){if(!(!Hl(e)&&!gw(e))&&!t)throw new Error(`marketplace directory already exists: ${e} (re-run with --force to replace)`)}function gw(e){try{return nX(e).isSymbolicLink()}catch{return!1}}function dm(e){if(gw(e)){rX(e);return}eX(e,{recursive:!0,force:!0})}function TO(e){return e.description?{name:e.name,description:e.description}:{name:e.name}}G();Dt();import{existsSync as cX,lstatSync as uX,rmSync as dX,unlinkSync as pX}from"fs";import{join as mX}from"path";function mm(e,t={}){let n=t.cacheDir??Kn(),r=t.indexPath??ce(),o=mX(n,e),s=!1;fX(o)?(pX(o),s=!0):cX(o)&&(dX(o,{recursive:!0,force:!0}),s=!0);let i=xe(r),a=Object.prototype.hasOwnProperty.call(i.marketplaces,e),l=Object.entries(i.plugins).filter(([,c])=>c.marketplace===e).map(([c])=>c);return(a||l.length>0)&&dR(e,r),{name:e,removedDir:s,removedIndexEntry:a,removedPluginEntries:l}}function fX(e){try{return uX(e).isSymbolicLink()}catch{return!1}}G();import{existsSync as vX}from"fs";import{join as kX}from"path";Dt();q();G();Dt();import{existsSync as fm,statSync as gX}from"fs";import{isAbsolute as xO,join as hX,resolve as RO}from"path";async function Yi(e,t,n={},r={}){let o=r.marketplaceDirFor??ga,s=r.indexPath??ce(),i=r.now??(()=>new Date),a=o(e);if(!fm(a)||!pw(a))throw new Error(`marketplace "${e}" is not installed (looked for manifest under ${a})`);let l=vr(a),c=l.plugins.find(u=>u.name===t);if(!c){let u=l.plugins.map(d=>d.name).join(", ")||"(none)";throw new Error(`marketplace "${e}" does not list a plugin named "${t}". Available: ${u}`)}return yX(c.source)?bX(e,c,a,s,i,n):wX(e,c,n,r)}function gm(e,t={}){let n=t.marketplaceDirFor??ga,r=t.indexPath??ce(),o=n(e);if(!fm(o)||!pw(o))throw new Error(`marketplace "${e}" is not installed`);let s=vr(o),i=xe(r);return s.plugins.map(a=>{let l=`${e}:${a.name}`,c=l in i.plugins||a.name in i.plugins&&i.plugins[a.name]?.marketplace===e,u={name:a.name,installed:c,key:l};return a.description&&(u.description=a.description),u})}function yX(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.startsWith("~")}function CO(e){return e.startsWith(".")||xO(e)||e.startsWith("~")}function hw(e,t){return xO(t)||t.startsWith("~")?SX(t):RO(e,t)}function bX(e,t,n,r,o,s){let i=t.source,a=hw(n,i);if(!fm(a))throw new Error(`marketplace "${e}" lists plugin "${t.name}" at ${a}, but that path does not exist on disk`);if(!gX(a).isDirectory())throw new Error(`marketplace "${e}" lists plugin "${t.name}" at ${a}, but that path is not a directory`);let c=hX(a,".claude-plugin","plugin.json");if(!fm(c))throw new Error(`marketplace "${e}" lists plugin "${t.name}" at ${a}, but no .claude-plugin/plugin.json was found`);let u=`${e}:${t.name}`,d=xe(r);if(!s.force&&u in d.plugins&&d.plugins[u]?.enabled)throw new Error(`plugin "${u}" is already installed (re-run with --force to overwrite)`);let p=o().toISOString(),m={source:`${e}:${t.name}`,sourceType:"marketplace",ref:null,commit:null,enabled:!0,installedAt:p,updatedAt:p,marketplace:e};return qr(u,m,r),{key:u,name:t.name,dir:a,entry:m}}async function wX(e,t,n,r){let o={name:t.name,...n.ref?{ref:n.ref}:{},...n.force?{force:!0}:{}},s=await um(t.source,o,r),i=r.indexPath??ce(),a={...s.entry,marketplace:e};return qr(s.name,a,i),{key:s.name,name:s.name,dir:s.dir,entry:a}}function SX(e){if(e.startsWith("~")){let t=v.HOME??"";if(e==="~")return t;if(e.startsWith("~/"))return RO(t,e.slice(2))}return e}async function Wl(e,t={},n={}){let r=n.indexPath??ce(),o=n.now??(()=>new Date),s=n.gitRunner?{runner:n.gitRunner}:{},a=xe(r).marketplaces[e];if(!a)throw new Error(`marketplace "${e}" is not installed`);let l=n.cacheDir?kX(n.cacheDir,e):ga(e);if(!vX(l))return{name:e,status:"missing-dir",dir:l};if(a.sourceType==="local")return{name:e,status:"skipped-local"};let c=new Set((EO(l)?.plugins??[]).map(k=>k.name));await im(l,s);let u,d=!1;if(t.ref)u=t.ref;else{let k=await so(l,s),$=ao(k);$!==null?(u=$,d=!0):u=a.ref??await Hn(l,s)}let p=`refs/remotes/origin/${u}`,m=d?null:await am(l,p,s),g=m!==null,h=await jn(l,s);if(g?m===h:u===a.ref)return{name:e,status:"up-to-date",ref:u,commit:h};await io(l,g?p:d?`refs/tags/${u}`:u,{...s,force:!0});let y=await jn(l,s),S=o().toISOString(),w={...a,ref:u,commit:y,updatedAt:S};sl(e,w,r);let T=vr(l),x=new Set(T.plugins.map(k=>k.name)),C=[...x].filter(k=>!c.has(k)),R=[...c].filter(k=>!x.has(k));return{name:e,status:"updated",fromRef:a.ref,toRef:u,commit:y,addedPlugins:C,removedPlugins:R,pluginVersions:EX(l,T)}}function EX(e,t){return t.plugins.map(n=>{let r=CO(n.source)?es(hw(e,n.source)).version:null;return{name:n.name,version:r}})}async function AO(e={}){let t=e.indexPath??ce(),n=xe(t),r=[];for(let o of Object.keys(n.marketplaces))try{r.push(await Wl(o,{},e))}catch(s){let i=s instanceof Error?s.message:String(s);r.push({name:o,status:"missing-dir",dir:i})}return r}Dt();var TX=["install","install-plugin","plugins","remove","update","list","add"],xX={name:"/marketplaces",summary:"List installed plugin marketplaces",async handler(e){return PO(e),"continue"}},RX={name:"/marketplace",summary:"Manage plugin marketplaces (install | install-plugin | plugins | remove | update)",usage:"/marketplace <install|install-plugin|plugins|remove|update|list> [args]",async handler(e,t){let n=t.trim();if(!n)return CX(e),"continue";let[r,...o]=n.split(/\s+/);if(!r||!TX.includes(r))return e.out.error(`Unknown subcommand "${r??""}". Try one of: install, install-plugin, plugins, remove, update.`),"continue";switch(r){case"install":return AX(e,o);case"install-plugin":return IX(e,o);case"plugins":return MX(e,o);case"remove":return OX(e,o);case"update":return $X(e,o);case"list":return PO(e),"continue";case"add":return PX(e,o);default:return"continue"}}};function IO(){fe(xX),fe(RX)}function PO(e){let t=xe(),n=Object.entries(t.marketplaces).sort(([r],[o])=>r.localeCompare(o));if(e.out.line(),n.length===0){e.out.line(f.dim(" No marketplaces installed.")),e.out.line(f.dim(" Try: /marketplace install anthropics/claude-plugins-official")),e.out.line();return}e.out.line(f.bold("Installed marketplaces:"));for(let[r,o]of n){let s=o.ref?f.brand(o.ref):f.dim("(local)");e.out.line(` ${f.bold(r.padEnd(28))} ${s.padEnd(12)} ${f.dim(o.source)}`)}e.out.line()}function CX(e){e.out.line(),e.out.line(f.bold("/marketplace usage:")),e.out.line(` ${f.brand("/marketplace install")} <git-url|owner/repo|local-path> [name]`),e.out.line(` ${f.brand("/marketplace install-plugin")} <marketplace> <plugin>`),e.out.line(` ${f.brand("/marketplace plugins")} <marketplace>`),e.out.line(` ${f.brand("/marketplace remove")} <marketplace>`),e.out.line(` ${f.brand("/marketplace update")} [<marketplace>]`),e.out.line(` ${f.brand("/marketplace list")}`),e.out.line()}async function MO(e,t){if(t.length===0)return e.out.error("Usage: /marketplace install <source> [name]"),"continue";let[n,r,...o]=t;if(!n)return e.out.error("Usage: /marketplace install <source> [name]"),"continue";let s=DX(o);e.out.info(`Installing marketplace ${n}\u2026`);try{let i=await pm(n,{...r&&!r.startsWith("-")?{name:r}:{},...s.ref?{ref:s.ref}:{},...s.force?{force:!0}:{}});e.out.success(`Installed marketplace ${i.name} (${i.plugins.length} plugin(s) available).`),e.out.line(f.dim(` Next: /marketplace plugins ${i.name}`))}catch(i){e.out.error(`Install failed: ${hm(i)}`)}return"continue"}async function AX(e,t){return t.length===1&&_X(t[0])||t.length>=2?_O(e,t):MO(e,t)}function _X(e){return!e||!e.includes(":")?!1:!/^[a-zA-Z][a-zA-Z0-9+\-.]*:\/\//.test(e)}async function _O(e,t){return e.out.warn("Deprecated: use `/marketplace install-plugin <marketplace> <plugin>` instead."),OO(e,t)}async function IX(e,t){return OO(e,t)}async function OO(e,t){let n,r;if(t.length===1&&t[0]?.includes(":")){let o=t[0].split(":");o.length===2&&([n,r]=o)}else[n,r]=t;if(!n||!r)return e.out.error("Usage: /marketplace install-plugin <marketplace> <plugin>"),"continue";e.out.info(`Installing ${n}:${r}\u2026`);try{let o=await Yi(n,r);e.out.success(`Installed ${o.key}.`),e.out.line(f.dim(" Run /reload-plugins to refresh this session's slash commands."))}catch(o){e.out.error(`Install failed: ${hm(o)}`)}return"continue"}async function PX(e,t){return e.out.warn("Deprecated: use `/marketplace install <source>` instead."),MO(e,t)}function MX(e,t){let n=t[0];if(!n)return e.out.error("Usage: /marketplace plugins <marketplace>"),"continue";try{let r=gm(n);if(e.out.line(),r.length===0)return e.out.line(f.dim(` Marketplace "${n}" lists no plugins.`)),e.out.line(),"continue";e.out.line(f.bold(`Plugins in ${n}:`)),r.forEach((o,s)=>{let i=o.installed?f.brand("[\u2713]"):f.dim("[ ]"),a=o.description?f.dim(` \u2014 ${o.description}`):"";e.out.line(` ${i} ${f.bold(String(s+1).padStart(2))}. ${f.bold(o.name)}${a}`)}),e.out.line(),e.out.line(f.dim(` Install one: /marketplace install-plugin ${n} <plugin>`)),e.out.line()}catch(r){e.out.error(`List failed: ${hm(r)}`)}return"continue"}function OX(e,t){let n=t[0];if(!n)return e.out.error("Usage: /marketplace remove <marketplace>"),"continue";let r=mm(n);if(!r.removedDir&&!r.removedIndexEntry&&r.removedPluginEntries.length===0)return e.out.line(f.dim(` No marketplace named "${n}" to remove.`)),"continue";let o=r.removedPluginEntries.length>0?` + ${r.removedPluginEntries.length} plugin(s)`:"";return e.out.success(`Removed marketplace ${n}${o}.`),"continue"}async function $X(e,t){let n=t[0];if(!n)return e.out.error("Usage: /marketplace update <marketplace>"),"continue";e.out.info(`Updating ${n}\u2026`);try{let r=await Wl(n);switch(r.status){case"updated":{let o=r.addedPlugins.length>0?` +${r.addedPlugins.join(", ")}`:"",s=r.removedPlugins.length>0?` -${r.removedPlugins.join(", ")}`:"";e.out.success(`Updated ${n}: ${r.fromRef??"(none)"} \u2192 ${r.toRef}${o}${s}`);break}case"up-to-date":e.out.info(`${n} is up-to-date (${r.ref}).`);break;case"skipped-local":e.out.info(`${n} skipped (local source).`);break;case"missing-dir":e.out.warn(`${n}: marketplace dir missing (${r.dir}).`);break}}catch(r){e.out.error(`Update failed: ${hm(r)}`)}return"continue"}function DX(e){let t={};for(let n=0;n<e.length;n+=1){let r=e[n];r==="-f"||r==="--force"?t.force=!0:(r==="-r"||r==="--ref")&&e[n+1]&&(t.ref=e[n+1],n+=1)}return t}function hm(e){return e instanceof Error?e.message:String(e)}S0("shadow-verify",{glyph:"\u25C8",color:"#7B5EA7",inFlightVerb:"verifying\u2026"});function $O(){RI();for(let e of PI)fe(e);for(let e of MI)fe(e);fe(OI),fe(XI),fe(aP),fe(lP),fe(cP),fe(uP),fe(fP),fe(SP);for(let e of TP)fe(e);fe(CP),fe(b0),fe(E0),fe(T0),fe(R0),fe(D0),fe(L0),fe(B0);for(let e of U0)fe(e);dO(),xI(A0),uO(),W0(),IO()}function DO(e,t={}){if(!e.isTTY)return{writeLine:o=>{e.write(o+`
|
|
1935
1935
|
`)},setCompositor:()=>{}};let n=null,r=t.statusLine;return{writeLine(o){if(n?.isArmed()){n.commitAbove(o);return}r?r.withFullScrollRegion(()=>{e.write(o+`
|
|
@@ -1937,7 +1937,7 @@ ${t}`}var X0=!1;function Z0(){X0||(X0=!0,nw("review",G0),z0())}q();var s6=new Se
|
|
|
1937
1937
|
`)},setCompositor(o){n=o}}}var ym=class{entries=new Map;record(t){let n=this.entries.get(t.skillName);n?(n.runs+=1,n.totalDurationMs+=t.durationMs,t.claimsTotal!==void 0&&(n.totalClaims=(n.totalClaims??0)+t.claimsTotal),t.claimsConfirmed!==void 0&&(n.totalConfirmed=(n.totalConfirmed??0)+t.claimsConfirmed),t.claimsRefuted!==void 0&&(n.totalRefuted=(n.totalRefuted??0)+t.claimsRefuted),t.claimsInconclusive!==void 0&&(n.totalInconclusive=(n.totalInconclusive??0)+t.claimsInconclusive)):this.entries.set(t.skillName,{skillName:t.skillName,runs:1,totalDurationMs:t.durationMs,...t.claimsTotal!==void 0?{totalClaims:t.claimsTotal}:{},...t.claimsConfirmed!==void 0?{totalConfirmed:t.claimsConfirmed}:{},...t.claimsRefuted!==void 0?{totalRefuted:t.claimsRefuted}:{},...t.claimsInconclusive!==void 0?{totalInconclusive:t.claimsInconclusive}:{}})}summary(){return this.entries.size===0?null:new Map(this.entries)}clear(){this.entries=new Map}};Lh();var bm=class{source;sampleEveryNTurns;cachedRatio;cachedDetail;inFlight=null;disposed=!1;generation=0;constructor(t,n={}){this.source=t,this.sampleEveryNTurns=n.sampleEveryNTurns??3}attach(t){return this.source=t,this.generation+=1,this.reset(),this}getRatio(){return this.cachedRatio}getDetail(){return this.cachedDetail}async refresh(){if(this.disposed)return;if(this.inFlight)return this.inFlight;let t=this.doFetch().finally(()=>{this.inFlight=null});return this.inFlight=t,t}async onTurn(t){this.disposed||t%this.sampleEveryNTurns===1&&await this.refresh()}reset(){this.cachedRatio=void 0,this.cachedDetail=void 0,this.inFlight=null}dispose(){this.disposed=!0}async doFetch(){let t=this.generation;try{let n=await this.source.getContextUsage();if(this.generation!==t)return;let r=LX(n.apiUsage),o=n.maxTokens??0,s=n.percentage;typeof s=="number"&&(this.cachedRatio=Math.min(1,Math.max(0,s/100)),this.cachedDetail={used:r,limit:o,percentage:s})}catch{}}};function LX(e){return e?e.input_tokens+e.output_tokens+e.cache_creation_input_tokens+e.cache_read_input_tokens:0}Xe();nl();Ih();_e();$c();var FX="claude-haiku-4-5",NX=15e3,BX=1e3,UX=80,jX=200,HX=3e3,WX='Summarize what this background subagent is currently doing in \u226480 tokens. Be concrete: name specific tools used, files examined, decisions made. Avoid filler ("appears to be working on\u2026").';function KX(e){return e.replace(/\bauthorization:\s*bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]").replace(/\bsk-ant-[A-Za-z0-9_-]{20,}/g,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,"[REDACTED]").replace(/\b(?:AKIA|ASIA|AROA|AIDA|AGPA|AIPA|ANPA|ANVA|APKA|ABIA|ACCA)[A-Z0-9]{16}\b/g,"[REDACTED]").replace(/(?<![/.\w])[A-Za-z0-9+/=_-]{32,}(?![/.\w])/g,"[REDACTED]")}var wm=class{registry;apiKey;model;intervalMs;maxInputTokens;maxOutputTokens;maxCallsPerSession;callLLM;getTranscriptFn;summaries=new Map;jobIndexMap=new Map;jobIndexCounter=0;callsThisSession=0;lastRefreshedAt=new Map;abortController=new AbortController;tickTimer;tickIntervalMs;constructor(t){this.registry=t.registry,this.apiKey=t.apiKey,this.model=t.model??FX,this.intervalMs=t.intervalMs??NX,this.maxInputTokens=t.maxInputTokens??BX,this.maxOutputTokens=t.maxOutputTokens??UX,this.maxCallsPerSession=t.maxCallsPerSession??jX,this.tickIntervalMs=Math.max(1e3,Math.floor(this.intervalMs/10)),t.callLLM!==void 0?this.callLLM=t.callLLM:this.callLLM=(n,r)=>Ls({token:this.apiKey,model:this.model,system:WX,user:n,maxTokens:this.maxOutputTokens,signal:r}),this.getTranscriptFn=t.getTranscript??(n=>this.registry.getTranscript(n)),this.registry.on("started",n=>{this.jobIndexMap.set(n.jobId,this.jobIndexCounter++)}),this.registry.on("settled",n=>{this.summaries.delete(n.jobId),this.jobIndexMap.delete(n.jobId),this.lastRefreshedAt.delete(n.jobId)})}start(){this.tickTimer===void 0&&(this.abortController=new AbortController,this.tickTimer=setInterval(()=>{this.tick()},this.tickIntervalMs))}stop(){this.tickTimer!==void 0&&(clearInterval(this.tickTimer),this.tickTimer=void 0),this.abortController.abort()}getSummary(t){return this.summaries.get(t)}async tick(){let t=Date.now(),n=this.registry.list().filter(o=>o.status==="running"),r=[];for(let o of n){let i=(this.jobIndexMap.get(o.jobId)??0)*HX%this.intervalMs,a=this.intervalMs-1e3-i,l=this.lastRefreshedAt.get(o.jobId)??0;if(!(t-l<a)){if(this.callsThisSession>=this.maxCallsPerSession){z(`[BackgroundSummarizer] budget cap (${this.callsThisSession}/${this.maxCallsPerSession}) \u2014 skipping ${o.jobId}`);continue}this.callsThisSession++,r.push(o.jobId)}}await Promise.allSettled(r.map(o=>this.refreshJob(o,t)))}async refreshJob(t,n){let r=!1;try{let o=this.getTranscriptFn(t);if(o===void 0||o.trim().length===0)return;let s=this.maxInputTokens*4,i=o.length>s?o.slice(-s):o,l=`Transcript tail:
|
|
1938
1938
|
<transcript>
|
|
1939
1939
|
${KX(i)}
|
|
1940
|
-
</transcript>`;this.lastRefreshedAt.set(t,n);let c=await this.callLLM(l,this.abortController.signal);this.summaries.set(t,{text:c.trim(),refreshedAt:n,stale:!1}),r=!0}catch(o){if(z(`[BackgroundSummarizer] Haiku call failed for ${t}:`,o),!this.abortController.signal.aborted){let s=this.summaries.get(t);s!==void 0&&this.summaries.set(t,{...s,stale:!0})}}finally{r||this.callsThisSession--}}};rl();Gr();Fo();tt();function LO(e,t){let n=new Map;return r=>{let o=t(r),s=n.get(o);if(s!==void 0)return s;let i=e(r);return n.set(o,i),i}}kn();Ur();Tn();ir();je();function yw(e){return e.replace(/\bsk-ant-[A-Za-z0-9_-]{10,}/g,"sk-ant-[REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{10,}/g,"sk-[REDACTED]").replace(/Bearer\s+[A-Za-z0-9._-]{10,}/gi,"Bearer [REDACTED]").replace(/Authorization:\s*\S+/gi,"Authorization: [REDACTED]")}function Kl(e,t,n){let r=n instanceof Error?n.message:String(n);e.fn(f.warning(`\u26A0 [resume-swap] ${t}: ${yw(r)}`))}async function FO(e,t){if(t.isInFlight()===!0)return{ok:!1,reason:"A turn is in flight \u2014 wait for it to finish before resuming."};let n;try{n=t.buildSession(e)}catch(i){let a=i instanceof Error?i.message:String(i);return{ok:!1,reason:`buildSession failed: ${yw(a)}`}}let r;if(!await n.waitForInitialization().then(()=>!0,i=>(r=yw(i instanceof Error?i.message:String(i)),!1))){await n.close().catch(a=>{Kl(t.completionWriter,"new session close after init failure",a)});let i=`Session initialization failed: ${r??"unknown error"}`;return t.completionWriter.fn(f.warning(`\u26A0 ${i}`)),{ok:!1,reason:i}}await t.backgroundRegistry.cancelAll().catch(i=>{Kl(t.completionWriter,"cancelAll failed",i)}),await t.sessionRef.current.close().catch(i=>{Kl(t.completionWriter,"session close failed",i)}),t.sessionRef.current=n,e.stored?(dp(t.stats,e.stored,e.resumeId),t.stats.turnCosts=[],t.stats.turnTokens=[]):(t.stats.totalTurns=0,t.stats.totalCostUsd=0,t.stats.totalTokens=0,t.stats.totalDurationMs=0,t.stats.turns=[],t.stats.sessionId=e.resumeId,t.stats.sessionStartTime=Date.now(),t.stats.turnCosts=[],t.stats.turnTokens=[]),t.stats.permissionMode="default";try{t.onSwapped(e)}catch(i){Kl(t.completionWriter,"onSwapped callback threw",i)}t.contextSampler.attach(n),await rm(n).catch(i=>{Kl(t.completionWriter,"autoRegisterPluginPassthroughs failed",i)});let s=[`\u21AA Resumed ${e.id}`];return t.stats.totalTurns>0&&s.push(`${t.stats.totalTurns} prior turn${t.stats.totalTurns===1?"":"s"}`),t.stats.totalCostUsd>0&&s.push(rt(t.stats.totalCostUsd)),t.stats.totalTokens>0&&s.push(ie(t.stats.totalTokens)+" tokens"),t.completionWriter.fn(f.brand(s.join(" \xB7 "))),pp(t.stats,t.completionWriter),t.statusLine.repaint(Fn(t.stats,t.contextSampler,t.gitStatusSampler)),{ok:!0,sessionId:n.sessionId??t.stats.sessionId??e.resumeId}}function NO(e){return new
|
|
1940
|
+
</transcript>`;this.lastRefreshedAt.set(t,n);let c=await this.callLLM(l,this.abortController.signal);this.summaries.set(t,{text:c.trim(),refreshedAt:n,stale:!1}),r=!0}catch(o){if(z(`[BackgroundSummarizer] Haiku call failed for ${t}:`,o),!this.abortController.signal.aborted){let s=this.summaries.get(t);s!==void 0&&this.summaries.set(t,{...s,stale:!0})}}finally{r||this.callsThisSession--}}};rl();Gr();Fo();tt();function LO(e,t){let n=new Map;return r=>{let o=t(r),s=n.get(o);if(s!==void 0)return s;let i=e(r);return n.set(o,i),i}}kn();Ur();Tn();ir();je();function yw(e){return e.replace(/\bsk-ant-[A-Za-z0-9_-]{10,}/g,"sk-ant-[REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{10,}/g,"sk-[REDACTED]").replace(/Bearer\s+[A-Za-z0-9._-]{10,}/gi,"Bearer [REDACTED]").replace(/Authorization:\s*\S+/gi,"Authorization: [REDACTED]")}function Kl(e,t,n){let r=n instanceof Error?n.message:String(n);e.fn(f.warning(`\u26A0 [resume-swap] ${t}: ${yw(r)}`))}async function FO(e,t){if(t.isInFlight()===!0)return{ok:!1,reason:"A turn is in flight \u2014 wait for it to finish before resuming."};let n;try{n=t.buildSession(e)}catch(i){let a=i instanceof Error?i.message:String(i);return{ok:!1,reason:`buildSession failed: ${yw(a)}`}}let r;if(!await n.waitForInitialization().then(()=>!0,i=>(r=yw(i instanceof Error?i.message:String(i)),!1))){await n.close().catch(a=>{Kl(t.completionWriter,"new session close after init failure",a)});let i=`Session initialization failed: ${r??"unknown error"}`;return t.completionWriter.fn(f.warning(`\u26A0 ${i}`)),{ok:!1,reason:i}}await t.backgroundRegistry.cancelAll().catch(i=>{Kl(t.completionWriter,"cancelAll failed",i)}),await t.sessionRef.current.close().catch(i=>{Kl(t.completionWriter,"session close failed",i)}),t.sessionRef.current=n,e.stored?(dp(t.stats,e.stored,e.resumeId),t.stats.turnCosts=[],t.stats.turnTokens=[]):(t.stats.totalTurns=0,t.stats.totalCostUsd=0,t.stats.totalTokens=0,t.stats.totalDurationMs=0,t.stats.turns=[],t.stats.sessionId=e.resumeId,t.stats.sessionStartTime=Date.now(),t.stats.turnCosts=[],t.stats.turnTokens=[]),t.stats.permissionMode="default";try{t.onSwapped(e)}catch(i){Kl(t.completionWriter,"onSwapped callback threw",i)}t.contextSampler.attach(n),await rm(n).catch(i=>{Kl(t.completionWriter,"autoRegisterPluginPassthroughs failed",i)});let s=[`\u21AA Resumed ${e.id}`];return t.stats.totalTurns>0&&s.push(`${t.stats.totalTurns} prior turn${t.stats.totalTurns===1?"":"s"}`),t.stats.totalCostUsd>0&&s.push(rt(t.stats.totalCostUsd)),t.stats.totalTokens>0&&s.push(ie(t.stats.totalTokens)+" tokens"),t.completionWriter.fn(f.brand(s.join(" \xB7 "))),pp(t.stats,t.completionWriter),t.statusLine.repaint(Fn(t.stats,t.contextSampler,t.gitStatusSampler)),{ok:!0,sessionId:n.sessionId??t.stats.sessionId??e.resumeId}}function NO(e){return new St(lr({model:e.model,surface:"cli",apiKey:qe(e.model),maxTurns:e.maxTurns,hookRegistry:e.hookRegistry,...e.permissionMode!==void 0?{permissionMode:e.permissionMode}:{},...e.systemPrompt!==void 0?{systemPrompt:e.systemPrompt}:{},...e.systemPromptSource!==void 0?{systemPromptSource:e.systemPromptSource}:{},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.maxOutputTokens!==void 0?{maxOutputTokens:e.maxOutputTokens}:{},...e.resumeConfig,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.traceWriter!==void 0?{traceWriter:e.traceWriter}:{},...e.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:e.autoResumeOnUsageLimit}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},providerFactory:e.providerFactory}))}async function UO(e,t){let n=Date.now(),r=Ai(e),o=_i(r),s=r?.stored?.model??e.model,i=Ds(s);if(i)throw new Error(i);let a,l,c;a=Vr(e.thinking)??pi(),l=Yr(e.effort)??mi(),c=gi(e.maxOutputTokens)??il();let{prompt:u,source:d}=di(),p=At(),m=p.autoRouting?.interactive??!0,g=Ld(u,m,"repl",h_()),h={current:null},b=Re(),y=new se({apiKey:b,...p.baseUrl!==void 0?{baseUrl:p.baseUrl}:{},...t?.cwd!==void 0?{cwd:t.cwd}:{}}),S=r?.stored?.sessionId,w=Qr(S?{sessionLabel:S}:{});De(w?.writer,{phase:"bootstrap_start"});let T=new nd(w?{traceWriter:w.writer}:{});vP(T);let C=p.bgSummaries===!0&&b?new wm({registry:T,apiKey:b,maxCallsPerSession:p.maxSummaryCallsPerSession??200}):void 0;C?.start(),kP(C);let R=ii(p.openaiBaseUrl!==void 0?{openaiBaseUrl:p.openaiBaseUrl}:{}),k={get sessionId(){return h.current?.sessionId},getInputStreamRef(){return h.current?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return h.current?.abortSignal??new AbortController().signal},get hookRegistry(){return h.current?.hookRegistry}},$=ai(s,b,R,p.baseUrl,w?.writer,T,t?.cwd,qe,"cli"),A=new Pn({subagentManager:y,parentSession:k,surface:"cli",defaultConfig:{apiKey:b,systemPrompt:u,...p.baseUrl!==void 0?{baseUrl:p.baseUrl}:{}},defaultSubagentModel:Vt(s),childProviderFactory:R,childSkillExecutorFactory:$,backgroundRegistry:T,resolveApiKeyForModel:qe,depth:0,...t?.cwd!==void 0?{cwd:t.cwd}:{}}),P=new Mn({parentSession:k,surface:"cli",defaultModel:s,defaultSubagentModel:Vt(s),apiKey:b,childProviderFactory:R,childSkillExecutorFactory:$,backgroundRegistry:T,...p.baseUrl!==void 0?{baseUrl:p.baseUrl}:{},resolveApiKeyForModel:qe,...w?.writer!==void 0?{traceWriter:w.writer}:{},...t?.cwd!==void 0?{cwd:t.cwd}:{}}),F=new Xr({parentSession:k,defaultModel:s,defaultSubagentModel:Vt(s),apiKey:b,resolveApiKeyForModel:qe,...p.baseUrl!==void 0?{baseUrl:p.baseUrl}:{},...t?.cwd!==void 0?{cwd:t.cwd}:{},systemPrompt:u??"",surface:"cli",depth:0}),D=new at,N;{let ve=t?.cwd??process.cwd(),Zt=rn(Pt()).mcpConfigs.filter(Wn=>Wn.format==="json").map(Wn=>Wn.source),fn=jo({cwd:ve,...Zt.length>0?{importedMcpConfigs:Zt}:{},...e.mcpConfig!==void 0?{cliOverride:e.mcpConfig}:{}}),ic=Object.values(fn.mcpServers).filter(Wn=>!Wn.disabled).length;if(ic>0){let Wn=fn.sources.length===1?fn.sources[0]:`${fn.sources.length} source(s)`;console.log(f.dim(` mcp: ${ic} server(s) from ${Wn??Uo()}`));let GF=Date.now();De(w?.writer,{phase:"mcp_connect_start",metadata:{serverCount:ic}});try{N=await hr.fromConfig(fn.mcpServers,{warnings:fn.warnings,...w?.writer!==void 0?{traceWriter:w.writer}:{}})}finally{De(w?.writer,{phase:"mcp_connect_done",durationMs:Date.now()-GF,metadata:{serverCount:ic}})}}else if(fn.warnings.length>0)for(let Wn of fn.warnings)console.warn(`[mcp] ${Wn}`)}let B=N?.getMcpToolWireNames()??[],L=LO(ve=>hi(e.provider,{subagentExecutor:A,skillExecutor:P,composeExecutor:F,memoryStore:D,model:ve!==void 0?ve:String(s),...p.openaiBaseUrl!==void 0?{openaiBaseUrl:p.openaiBaseUrl}:{},...N!==void 0?{mcpManager:N}:{}})??new Ge({permissions:{allowedTools:[...Wt,...Qn,...pt,"agent","skill","compose",...B]},subagentExecutor:A,skillExecutor:P,composeExecutor:F,memoryStore:D,surface:"cli",...N!==void 0?{mcpManager:N}:{}}),ve=>e.provider??re(ve!==void 0?ve:String(s),p.openaiBaseUrl!==void 0?{openaiBaseUrl:p.openaiBaseUrl}:void 0)),I=L(String(s)),U=Wd(s);r?.stored&&dp(U,r.stored,r.resumeId);let M=e.dangerouslySkipPermissions?"bypassPermissions":p.permissionMode;M!==void 0&&(U.permissionMode=M),U.cwd=t?.cwd??process.cwd(),w&&console.log(f.dim(` trace: ${w.tracePath}`));let j={fn:ve=>console.log(ve),idleFn:ve=>console.log(ve)},Y=new cp,oe=DO(process.stdout,{statusLine:Y}),X=Ei(ve=>{j.fn(Bd(ve))},"cli",D,()=>U.permissionMode,ki({cwd:t?.cwd}),{cwd:t?.cwd,...w?.writer!==void 0?{traceWriter:w.writer}:{}},()=>t?.cwd??process.cwd()),W=X.registry,Ee=X.pathApprovalGrantRef,Je={model:s,resumeConfig:o,systemPrompt:g,systemPromptSource:d,thinking:a,effort:l,maxOutputTokens:c,...p.baseUrl!==void 0?{baseUrl:p.baseUrl}:{},providerFactory:L,hookRegistry:W,traceWriter:w?.writer,cwd:t?.cwd,maxTurns:parseInt(e.maxTurns,10),autoResumeOnUsageLimit:p.autoResumeOnUsageLimit,...M!==void 0?{permissionMode:M}:{}};await _C();let st=NO(Je);h.current=st,y.setOnSubagentSucceeded((ve,Zt)=>{h.current?.recordSubagentCompletion(ve,Zt)});let Se=new ym,ye=zi(j),de=new bm(st),Pe=new up({cwd:U.cwd??process.cwd(),branchTtlMs:1e3}),Ce={session:h,stats:U,out:ye,ui:{clearScreen:()=>{let ve=Ce.getCompositor?.();ve?.setOverlay(""),ve?.resetCommittedBand(),Y.stop(),de.reset(),process.stdout.write("\x1B[3J\x1B[2J\x1B[H"),Y.start(),Y.repaint(Fn(U,de,Pe))},repaintStatusLine:()=>Y.repaint(Fn(U,de,Pe))},ledger:Se,...N!==void 0?{mcpManager:N}:{}},Oe=ve=>(Se.clear(),FO(ve,{sessionRef:h,stats:U,contextSampler:de,gitStatusSampler:Pe,statusLine:Y,backgroundRegistry:T,completionWriter:j,isInFlight:()=>xt.getInFlight?.()??!1,onSwapped:Zt=>{xt.resumeTarget=Zt,xt.clearVerdictLedger?.()},buildSession:Zt=>NO({...Je,model:Zt.stored?.model??Je.model,resumeConfig:_i(Zt),permissionMode:U.permissionMode})})),xt={session:h,memoryStore:D,stats:U,statusLine:Y,contextSampler:de,gitStatusSampler:Pe,completionWriter:j,replRenderer:oe,slashCtx:Ce,rl:null,options:e,...r!==void 0?{resumeTarget:r}:{},teardownTrustedSkillEvents:void 0,backgroundRegistry:T,subagentControl:A,...C!==void 0?{bgSummarizer:C}:{},requestResume:Oe,getInFlight:()=>!1,...N!==void 0?{mcpManager:N}:{},suggestApiKey:b,...p.openaiBaseUrl!==void 0?{suggestBaseUrl:p.openaiBaseUrl}:{},...p.interactive?.suggestGhost!==void 0?{suggestGhostConfig:p.interactive.suggestGhost}:{},hookRegistry:X.registry},$S=ve=>{j.fn(k0(ve,{isTTY:process.stdout.isTTY,columns:process.stdout.columns}))},DS=ve=>{j.fn(v0(ve,{isTTY:process.stdout.isTTY,columns:process.stdout.columns})),Se.record(ve)};Qx($S),Xx(DS),xt.teardownTrustedSkillEvents=()=>{eR($S),Zx(DS)},$O(),I instanceof Ge&&(x0(I),Ee.current=I,r_(I));let pf=BO.createInterface({input:process.stdin,output:process.stdout,terminal:!1});xt.rl=pf;let mf={current:null};return xt.inputSurfaceRef=mf,lt.install(lp({readLine:ve=>new Promise((Zt,fn)=>{pf.question(ve,Zt),pf.once("close",()=>fn(new Error("readline closed")))}),writer:{line:(ve="")=>process.stdout.write(ve+`
|
|
1941
1941
|
`)},pendingCount:()=>lt.pendingCount(),suspendInput:()=>mf.current?.suspendForElicitation(),resumeInput:()=>mf.current?.resumeAfterElicitation()})),Ce.requestResume=Oe,De(w?.writer,{phase:"bootstrap_done",durationMs:Date.now()-n}),xt}Fr();G();import{promises as bw}from"node:fs";import*as HO from"node:path";async function jO(e,t,n=!1){await bw.mkdir(e,{recursive:!0});let r=new Date().toISOString().replace(/[:.]/g,"-"),o=HO.join(e,`${r}.md`),s=n?" (continued)":"";return await bw.writeFile(o,`# Session \u2014 ${new Date().toISOString()}${s}
|
|
1942
1942
|
|
|
1943
1943
|
- model: ${t}
|
|
@@ -2013,7 +2013,7 @@ _ended: ${new Date().toISOString()}_
|
|
|
2013
2013
|
${T}${S}
|
|
2014
2014
|
${w}
|
|
2015
2015
|
${T}`})}return{fileBlocks:a,warnings:l}}async function f$(e,t,n,r,o="summary",s,i){let a=cM(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0);let l="",c=0,u=!1,d=!1,p=!1,m=!1,g,h=!1,b=!1,y={abort:null},S=0,w=3e3,T=[],x=new Map,C=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,R=()=>{let D=r.subagentControl;D?.hasPromotableForeground()&&D.promoteActiveForeground().then(N=>{for(let B of N)(s??{fn:console.log}).fn(f.dim(` \u2192 subagent backgrounded as ${B.jobId}: ${B.label}`))}).catch(()=>{})},k=r.getCompositor?r.getCompositor():null,$=()=>new qi({out:zi(s),thinkingMode:o,...C?{activeSkillName:C}:{},onCancel:()=>{t.interrupt().catch(D=>{We()&&console.error(" "+f.error("session.interrupt() failed:"),D)})},...r.subagentControl?{onBackground:R}:{},...i?.history?{history:i.history}:{},...i?.autocompleteState?{autocompleteState:i.autocompleteState}:{},...i?.promptText!==void 0?{promptText:i.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...k?{compositor:k}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),A=$(),P=async()=>{if(!p){p=!0;try{await A.dispose()}catch{}}},F=async()=>{await A.arm();let D=A.getCompositor();if(s&&D){let N=D;s.fn=B=>N.commitAbove(B)}r.setActiveCompositor?.(D),r.setInterruptNotifier?.(N=>A.setInterrupting(N)),r.rearmStatus?.()};try{k?k.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{h=!0,t.interrupt().catch(I=>{We()&&console.error(" "+f.error("soft-stop session.interrupt() failed:"),I)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{b=!0,t.interrupt().catch(I=>{We()&&console.error(" "+f.error("pause-interrupt session.interrupt() failed:"),I)})}),await F(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(R);let{fileBlocks:D,warnings:N}=m$(e.text,{rootDir:process.cwd()});for(let I of N)(s??{fn:console.log}).fn(f.dim(` @-file: ${I}`));let B=D.length>0||e.attachments.length>0?d$(e.text,e.attachments,void 0,D):e.text,H=t.sendMessageStream(B);if(await Ns((I,U)=>{A.process(I,U)},async()=>{for await(let I of H){if(h||b)break;if(I.type==="chunk"&&I.chunk.type==="content"?(l+=I.chunk.content,u=!0):I.type==="message"&&!u&&(l=I.message.content),I.type==="stream_retry"&&(l=l.slice(0,c)),I.type==="chunk"&&I.chunk.type==="tool_use_detail"){let U=I.chunk,M={toolName:U.toolName,toolUseId:U.toolUseId,input:U.toolInput,...U.toolInputRaw!==void 0&&{inputRaw:U.toolInputRaw}};x.set(U.toolUseId,M),T.push(M)}else if(I.type==="chunk"&&I.chunk.type==="tool_result"){let U=I.chunk;c=l.length;let M=x.get(U.toolUseId);if(M&&(M.result=U.content,M.isError=U.isError,x.delete(U.toolUseId)),r.onContextProgress){let j=Date.now();if(j-S>=w){S=j;try{let Y=r.onContextProgress();Y instanceof Promise&&await Y}catch(Y){We()&&console.error(" "+f.error("onContextProgress (status refresh) failed:"),Y)}}}}if(I.type==="paused"){if(r.setPausedState?.(!0),await P(),k&&I.autoResume===!0){let U=new AbortController;y.abort=U;let M=I.resetsAt?I.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,j=M?`Keep waiting \u2014 auto-resumes at ${M}`:"Keep waiting \u2014 auto-resume in progress",Y="Switch model / provider (type /model after)",oe="Stop waiting",X=[f.warning(" \u23F3 Usage limit reached.")+(M?f.dim(` Auto-resumes at ${M}.`):""),f.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];Em(k,{header:X,options:[j,Y,oe],signal:U.signal,initialIndex:0}).then(W=>{if(y.abort=null,!W)return;let Ee=W[0];Ee===void 0||Ee===j||(b=!0,Ee===Y&&(s??{fn:console.log}).fn(f.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(Je=>{We()&&console.error(" "+f.error("picker pause-interrupt session.interrupt() failed:"),Je)}))}).catch(W=>{We()&&console.error(" "+f.error("picker promise rejected:"),W)})}else(s??{fn:console.log}).fn(hv({reason:I.reason,...I.resetsAt!==void 0?{resetsAt:I.resetsAt}:{},...I.accountId!==void 0?{accountId:I.accountId}:{},...I.autoResume!==void 0?{autoResume:I.autoResume}:{}}));continue}if(I.type==="resumed"){r.setPausedState?.(!1),y.abort?.abort(),y.abort=null;let U=I.hotSwapped&&I.accountId?`\u25B6 Resumed on ${I.accountId}`:"\u25B6 Resumed";l="",c=0,u=!1,T.length=0,x.clear(),m=!1,g=void 0,d=!1,A=$(),p=!1,await F(),(s??{fn:console.log}).fn(f.success(U));continue}if(I.type==="error"){await P(),_s(xs(I.error)),d=!0;continue}A.process(I),I.type==="done"&&(m=!0,g=I.metadata)}}),await P(),h){let I=s?s.fn:console.log;I(f.warning("\u23F8 Stopped \u2014 work so far kept.")+f.dim(" Send a message to continue.")),I("")}if(b){let I=s?s.fn:console.log;I(f.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),I("")}if(m&&!h&&!b){Bo(n,a,l,g,T),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),op(process.stdout);let I=M=>{s?s.fn(M):console.log(M)},U=c$(l);if(U){if(I(u$(U)),I(""),r.onTerminalState)try{r.onTerminalState(U)}catch{}if(n.permissionMode==="autonomous"){let M=U.kind==="done"&&fu().verifyDone===!0&&!DI(T);FI(U,void 0,{unverified:M})}}if(U9(g,n,I),r.onAfterTurn){let M=r.onAfterTurn();M instanceof Promise&&await M.catch(()=>{})}}}catch(D){await P(),d||_s(xs(D))}finally{await P(),s&&(s.fn=s.idleFn),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setPausedState?.(!1),r.setPauseInterruptHandler?.(null),y.abort?.abort(),y.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}function U9(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(me(e.durationMs)),e.totalCostUsd!==void 0&&r.push(rt(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),s=Number(e.usage?.output_tokens??0);o+s>0&&r.push(ie(o+s)+" tok"),r.length>0&&n(f.dim(" \u25E6 "+r.join(" \xB7 ")));let i=Xy(t),a=Ot(t.model);if(i>=1){let l=Math.round((i-1)*a),c=Math.round(a/1e3);n(f.error(` context OVER ${c}k tok by ~${ie(l)} tok \u2014 model output may be silently truncated`))}else if(i>.5){let l=i>.8?f.error:f.warning;n(l(` context ${Math.round(i*100)}% used of ${ie(a)}`))}n("")}var j9=5e3;async function H9(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(f.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function g$(e,t,n,r,o,s,i,a){let{contextPane:l,loopStageBar:c,verdictLedger:u,shellPassthrough:d}=i,p=null,m=[];e.session.current.waitForInitialization().then(async y=>{We()&&(p=mp(y)),await rm(e.session.current),We()&&(m=cO())}).catch(()=>{});let g,h=!1,b=!1;for(;;){if(p&&(e.replRenderer.writeLine(p),e.replRenderer.writeLine(""),p=null),m.length>0){for(let k of m)e.replRenderer.writeLine(k);e.replRenderer.writeLine(""),m=[]}let y=d.drainNotifications();for(let{job:k,result:$}of y){let A=$.errorReason===void 0?"\u2713":"\u2717",P=$.errorReason==="abort"?"killed":$.errorReason==="timeout"?"timed out":$.errorReason==="signal-killed"?"killed by signal":`exit ${$.exitCode??0}`,F=Math.max(0,Math.round($.durationMs/100)/10);e.replRenderer.writeLine(f.dim(` ${A} [${k.id}] ${P} \xB7 ${F}s \xB7 `)+k.command)}let S=l.renderIfChanged(e.stats.sessionId);if(S.length>0){for(let k of S)e.replRenderer.writeLine(k);e.replRenderer.writeLine("")}let w,T;if(g===void 0){let k=await e.session.current.takePendingPlanExitSeed();k!==void 0&&(g={text:k,attachments:[]})}if(g!==void 0){let k=g;g=void 0;let $=Xi(e.stats.permissionMode),A=zo({buffer:k.text,promptText:$,isTTY:!!process.stdout.isTTY,attachmentSummary:Bi([...k.attachments])});e.replRenderer.writeLine(A),w=k.text.trim(),T=k.attachments}else{let k=await o.readLine({promptFn:()=>Xi(e.stats.permissionMode),onSigint:r,onShiftTab:()=>{Tm(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});w=k.text.trim(),T=k.attachments}if(!w&&T.length===0)continue;if(w.startsWith("!")){let k=/^(0|false|off|no)$/i.test(v.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!k&&(h||(h=!0,e.replRenderer.writeLine(f.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await d.dispatch(w))){e.statusLine.rearm();continue}}let x=!1;if(w.startsWith("/")){let k=await CI(w,e.slashCtx,T);if(k.handled){if(k.result==="exit"){e.rl.close();return}if((w==="/clear"||w.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(f.dim(` transcript: ${t.path()}`)),u.reset()),k.result!==null&&typeof k.result=="object"&&"kind"in k.result&&k.result.kind==="submit"){g={text:k.result.message,attachments:T??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}x=!0}a.push(w),await H9(e,w);let C=w;if(x){let k=Yy(w);if(k){let $=k.name.replace(/^\//,"").split(":").pop()??"";if($&&rw($)){let A={skillName:$,rawArgs:k.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},P=e.session.current.sessionId,F=ns(P),D=Date.now();z(`[afk trace] preflight.start commandName=${$}`);let N=!1,B=await ts(A,{cwd:e.stats.cwd??process.cwd(),artifactDir:F},H=>{We()&&e.replRenderer.writeLine(f.warning(`\u26A0 preflight(${$}) failed: `)+(H instanceof Error?H.message:String(H)))});N=B!==null,z(`[afk trace] preflight.end commandName=${$} durationMs=${Date.now()-D} success=${N}`),C=sw(B?.manifestBlock,w)}}}let R=d.drainInjections();if(R.length>0&&(C=R+C),e.hookRegistry)try{let k={event:"UserPromptSubmit",prompt:C,sessionId:e.stats.sessionId},$=await e.hookRegistry.dispatch(k);$.injectContext&&(C=$.injectContext+C)}catch(k){if(k instanceof be){e.replRenderer.writeLine(f.warning("\u2298 Turn blocked by hook")+(k.reason?f.dim(`: ${Co(k.reason)}`):"")),e.statusLine.rearm();continue}if(k instanceof Sn){e.replRenderer.writeLine(f.warning("\u2298 Turn blocked by hook")+f.dim(`: handler timed out after ${k.timeoutMs}ms`)),e.statusLine.rearm();continue}throw k}if(await f$({text:C,attachments:T},e.session.current,e.stats,{setInFlight(k){n.turnInFlight=k},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(k){await t.appendUser(k)},async onTurnComplete(k,$){if(await t.appendTurn(k,$),e.stats.sessionId)try{$n(e.stats)}catch(A){b||(b=!0,e.replRenderer.writeLine(f.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(A instanceof Error?A.message:String(A))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:k=>u?.push(k),setActiveCompositor:k=>{n.activeCompositor=k},setInterruptNotifier:k=>{n.notifyInterrupting=k},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:k=>o.setBackgroundHandler(k),setSoftStopHandler:s,setPausedState:k=>o.setPausedState(k),setPauseInterruptHandler:k=>o.setPauseInterruptHandler(k),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(Fn(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:k=>c.repaint(k)}:{}},e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(Xi(e.stats.permissionMode))),e.hookRegistry)try{await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId},void 0,j9)}catch(k){if(k instanceof it)throw k;k instanceof Sn?(z("[stop hook] handler timed out"),e.completionWriter.fn(f.dim(" [stop hook] timed out"))):k instanceof be?e.completionWriter.fn(f.dim(` [stop hook] blocked: ${Co(k.reason??"no reason given")}`)):z("[stop hook] unexpected error: "+String(k))}}}function W9(e,t){if(e!==void 0){let n=e.toLowerCase();return!(n==="0"||n==="false"||n==="off"||n==="no")}return typeof t=="boolean"?t:!0}async function h$(e,t,n,r){let o=await zO(),s=new km({rl:e.rl,history:o,statusLine:e.statusLine}),i=W9(v.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await QO(e,s,n,t,r,i,{getLoopStageBar:()=>a?.loopStageBar});a=l$(e,n),await g$(e,t,n,r,s,l,a,o)}finally{n.tryAbortShellForeground=null,a?.shellPassthrough.drainOnExit(),a?.loopStageBar.stop(),a?.bgStatusBar.stop(),a?.verdictLedger.stop(),a?.contextPane.dispose();let l=c=>console.log(c);e.completionWriter.fn=l,e.completionWriter.idleFn=l,await s.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}Da();import{execFile as K9}from"node:child_process";import{dirname as G9,isAbsolute as q9,resolve as z9}from"node:path";import{promisify as J9}from"node:util";var y$=J9(K9),V9=3e3,Y9=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function X9(){let t=(await y$("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=q9(t)?t:z9(process.cwd(),t);return G9(n)}async function b$(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await X9()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),V9)});try{let o=Bn({execFile:y$,repoRoot:t,dryRun:!1,scope:"interactive",bypassSoftLaunch:!0}),s=await Promise.race([o,r]);if(s==="timeout")return{ran:!1,removedCount:0,skippedReason:"timeout"};let i=s;return i.warnings.some(c=>c.toLowerCase().includes("contested"))?{ran:!1,removedCount:0,skippedReason:"lock-contested"}:{ran:!0,removedCount:i.candidates.filter(c=>Y9.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}$c();Da();import{promises as Z9}from"node:fs";import{dirname as Q9,join as v$}from"node:path";import{randomBytes as e7}from"node:crypto";var t7=["Generate a 2-4 word kebab-case slug describing this work request.","Rules:","- ASCII lowercase letters and digits only, separated by single hyphens","- 2 to 4 hyphen-separated words","- Maximum 30 characters total","- No prefix, no quotes, no punctuation other than hyphens","- Output ONLY the slug \u2014 no explanation, no preamble","Examples: fix-cleanup-race, add-telegram-allowlist, refactor-prompt-loader, debug-flaky-test"].join(`
|
|
2016
|
-
`),w$=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Cw=30,n7=1024,r7=8e3,o7="haiku";async function s7(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=c7(n,n7),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??r7),i=t.signal?u7([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await Ls({token:t.token,model:t.model??o7,system:t7,user:r,maxTokens:32,signal:i})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(s)}let l=i7(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=Q9(t.worktreePath);return await a7(l,c)}function i7(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(w$.test(t)&&t.length<=Cw)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(s=>s.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let s=1;s<r.length;s++){let i=`${o}-${r[s]}`;if(i.length>Cw)break;o=i}return w$.test(o)?o:null}async function a7(e,t){if(!await l7(v$(t,e)))return e;let n=e7(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Cw-5)}-${n}`}async function l7(e){try{return await Z9.access(e),!0}catch{return!1}}function c7(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function u7(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function k$(e){let t,n,r=v$(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await s7(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),s=t??"unknown",i=n;if(o!==null){let l=`${uu(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return S$(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){s="create-failed",i=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return S$(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:s,...i!==void 0?{detail:i}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function S$(e,t){e&&e.setCwd(t),d7(t)}function d7(e){try{process.chdir(e)}catch{}}ze();Mt();G();import{spawn as T$}from"child_process";import{existsSync as x$,mkdirSync as h7,readFileSync as R$,unlinkSync as E$,writeFileSync as y7}from"fs";import{get as b7}from"https";import{join as C$}from"path";import{readFileSync as p7}from"fs";import{dirname as m7,join as f7}from"path";import{fileURLToPath as g7}from"url";function kr(){try{return"5.3.
|
|
2016
|
+
`),w$=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Cw=30,n7=1024,r7=8e3,o7="haiku";async function s7(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=c7(n,n7),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??r7),i=t.signal?u7([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await Ls({token:t.token,model:t.model??o7,system:t7,user:r,maxTokens:32,signal:i})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(s)}let l=i7(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=Q9(t.worktreePath);return await a7(l,c)}function i7(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(w$.test(t)&&t.length<=Cw)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(s=>s.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let s=1;s<r.length;s++){let i=`${o}-${r[s]}`;if(i.length>Cw)break;o=i}return w$.test(o)?o:null}async function a7(e,t){if(!await l7(v$(t,e)))return e;let n=e7(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Cw-5)}-${n}`}async function l7(e){try{return await Z9.access(e),!0}catch{return!1}}function c7(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function u7(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function k$(e){let t,n,r=v$(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await s7(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),s=t??"unknown",i=n;if(o!==null){let l=`${uu(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return S$(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){s="create-failed",i=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return S$(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:s,...i!==void 0?{detail:i}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function S$(e,t){e&&e.setCwd(t),d7(t)}function d7(e){try{process.chdir(e)}catch{}}ze();Mt();G();import{spawn as T$}from"child_process";import{existsSync as x$,mkdirSync as h7,readFileSync as R$,unlinkSync as E$,writeFileSync as y7}from"fs";import{get as b7}from"https";import{join as C$}from"path";import{readFileSync as p7}from"fs";import{dirname as m7,join as f7}from"path";import{fileURLToPath as g7}from"url";function kr(){try{return"5.3.2"}catch{}try{let e=m7(g7(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(p7(f7(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}q();var w7=64*1024,S7=1440*60*1e3,v7=3600*1e3,k7="update-check.json",E7="pending-update.json";function A$(){return C$(mc(),k7)}function zl(){return C$(mc(),E7)}function _$(){let e=mc();x$(e)||h7(e,{recursive:!0})}function T7(e,t){let n=a=>a.split(/[-+]/,1)[0]??a,r=a=>a.includes("-"),o=n(e).split(".").map(Number),s=n(t).split(".").map(Number),i=Math.max(o.length,s.length);for(let a=0;a<i;a++){let l=o[a]??0,c=s[a]??0;if(c>l)return!0;if(c<l)return!1}return r(e)&&!r(t)}function x7(){try{let e=R$(A$(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function R7(){try{_$();let e=`
|
|
2017
2017
|
const https = require('https');
|
|
2018
2018
|
const fs = require('fs');
|
|
2019
2019
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|
|
@@ -2036,14 +2036,14 @@ ${T}`})}return{fileBlocks:a,warnings:l}}async function f$(e,t,n,r,o="summary",s,
|
|
|
2036
2036
|
${t}${n}Update available:${o} ${r}${e.currentVersion}${o} \u2192 ${n}${e.latestVersion}${o}
|
|
2037
2037
|
${r}Run \`npm install -g agent-afk\` to update${o}
|
|
2038
2038
|
`)}var Aw=/^\d+\.\d+\.\d+(-[\da-z.]+)?$/i;function _w(e){if(Aw.test(e))try{_$(),y7(zl(),JSON.stringify({targetVersion:e,triggeredAt:Date.now()}))}catch{}}function Iw(e=5e3,t="https://registry.npmjs.org/agent-afk/latest"){return new Promise(n=>{let r=!1,o=i=>{r||(r=!0,n(i))},s=(i,a)=>{try{let l=b7(i,{headers:{Accept:"application/json"}},c=>{if((c.statusCode===301||c.statusCode===302)&&typeof c.headers.location=="string"&&a>0){c.resume(),s(c.headers.location,a-1);return}if(c.statusCode!==200){c.resume(),o(void 0);return}let u="",d=0,p=!1;c.on("data",m=>{if(!p){if(d+=m.byteLength,d>w7){p=!0,l.destroy(),o(void 0);return}u+=m.toString("utf-8")}}),c.on("end",()=>{if(!p){try{let m=JSON.parse(u);if(typeof m.version=="string"&&Aw.test(m.version)){o(m.version);return}}catch{}o(void 0)}})});l.on("error",()=>o(void 0)),l.setTimeout(e,()=>{l.destroy(),o(void 0)})}catch{o(void 0)}};s(t,3)})}function Pw(e){if(Aw.test(e)&&!x$(zl()))try{_w(e),T$("npm",["install","-g",`agent-afk@${e}`],{detached:!0,stdio:"ignore"}).unref()}catch{}}function P$(){try{let e=R$(zl(),"utf-8"),t=JSON.parse(e);if(typeof t.targetVersion!="string")return;let n=kr();if(n===t.targetVersion){E$(zl()),process.stderr.write(`\x1B[32m\x1B[1mUpdated to agent-afk v${n}\x1B[0m
|
|
2039
|
-
`);return}let r=typeof t.triggeredAt=="number"?t.triggeredAt:0;Date.now()-r>v7&&E$(zl())}catch{}}var Am=null;function $$(e,t){Am={updateInfo:e,pendingMessage:t}}function A7(e){if(e==="summary"||e==="live"||e==="off")return e;throw new Error(`Invalid --thinking-ui value: ${e}. Expected summary|live|off`)}function _7(e,t){switch(e){case"empty-message":case"slash-command":return;case"slug-generator-error":return t?`slug generation failed: ${t}`:"slug generation failed";case"invalid-slug-output":return t?`model returned invalid slug: ${JSON.stringify(t)}`:"model returned invalid slug";case"create-failed":return t?`named worktree create failed: ${t}`:"named worktree create failed";default:return"unknown reason"}}function I7(e,t){if(e.worktreeAutoname===!1)return!1;let n=v.AFK_WORKTREE_AUTONAME;if(n!==void 0){let r=n.toLowerCase();return!(r==="0"||r==="false"||r==="off"||r==="no")}return typeof t.interactive?.worktreeAutoname=="boolean"?t.interactive.worktreeAutoname:!0}function P7(){return"/help \xB7 /model \xB7 @ for files \xB7 Shift+Tab mode \xB7 Esc to interrupt \xB7 /exit to quit"}function D$(e){e.command("interactive",{isDefault:!0}).description("Start interactive chat session").option("-m, --model <model>","Model to use. Short aliases: opus|opus_1m|sonnet|sonnet_1m|haiku. Any other value (e.g. `auto` for cursor-api-proxy, or a full `claude-*` ID) passes through to the SDK/proxy untouched.",
|
|
2039
|
+
`);return}let r=typeof t.triggeredAt=="number"?t.triggeredAt:0;Date.now()-r>v7&&E$(zl())}catch{}}var Am=null;function $$(e,t){Am={updateInfo:e,pendingMessage:t}}function A7(e){if(e==="summary"||e==="live"||e==="off")return e;throw new Error(`Invalid --thinking-ui value: ${e}. Expected summary|live|off`)}function _7(e,t){switch(e){case"empty-message":case"slash-command":return;case"slug-generator-error":return t?`slug generation failed: ${t}`:"slug generation failed";case"invalid-slug-output":return t?`model returned invalid slug: ${JSON.stringify(t)}`:"model returned invalid slug";case"create-failed":return t?`named worktree create failed: ${t}`:"named worktree create failed";default:return"unknown reason"}}function I7(e,t){if(e.worktreeAutoname===!1)return!1;let n=v.AFK_WORKTREE_AUTONAME;if(n!==void 0){let r=n.toLowerCase();return!(r==="0"||r==="false"||r==="off"||r==="no")}return typeof t.interactive?.worktreeAutoname=="boolean"?t.interactive.worktreeAutoname:!0}function P7(){return"/help \xB7 /model \xB7 @ for files \xB7 Shift+Tab mode \xB7 Esc to interrupt \xB7 /exit to quit"}function D$(e){e.command("interactive",{isDefault:!0}).description("Start interactive chat session").option("-m, --model <model>","Model to use. Short aliases: opus|opus_1m|sonnet|sonnet_1m|haiku. Any other value (e.g. `auto` for cursor-api-proxy, or a full `claude-*` ID) passes through to the SDK/proxy untouched.",vt()).option("--max-turns <number>","Maximum conversation turns","100").option("--thinking <mode>","Thinking mode: 'adaptive' | 'disabled' | 'enabled:<N>'","enabled:max").option("--thinking-ui <mode>","Thinking display mode: summary|live|off",A7,"live").option("--effort <level>","Effort level: low|medium|high|xhigh|max").option("--max-output-tokens <n|max>","Per-response output cap ('max' = model ceiling). Env: AFK_MAX_OUTPUT_TOKENS").option("--resume <id>","Resume a persisted SDK session by id").option("--continue","Continue the most recent persisted session in cwd").option("--debug","Show SDK init metadata on startup; enables /debug command",!1).option("-w, --worktree [branch]","Create a git worktree for an isolated session. Optional value sets the branch name; otherwise auto-named. On clean exit (no uncommitted changes) the worktree and branch are auto-removed; on dirty exit the worktree is preserved.").option("--no-worktree-autoname","Disable mid-session rename of auto-named worktrees from the first user message via haiku. Default on. Also: AFK_WORKTREE_AUTONAME=0, or interactive.worktreeAutoname:false in afk.config.json.").option("--worktree-base <ref>","Base git ref for the worktree created by --worktree. Default: the remote's default branch (origin/main), fetched fresh. Pass HEAD to base on your local checkout instead. Also: AFK_WORKTREE_BASE, or interactive.worktreeBase in afk.config.json.").option("--no-shell-passthrough","Disable the ! shell-passthrough feature. When set, inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Also: AFK_SHELL_PASSTHROUGH set to 0, false, off, or no.").option("--provider <name>","Provider to use: anthropic|anthropic-direct|openai|openai-compatible. Default: auto-selected by model").option("--dump-prompt [path]",'Dump resolved SDK prompt+options+provenance to file (default: ~/.afk/logs/prompt-dump-<ISO>.json) or "stderr"').option("--dangerously-skip-permissions","Force bypass mode (already the default for new installs): skip path-approval prompts; read/write ANY path with no confirmation. Toggle live with Shift+Tab (permission-mode cycle); disable persistently with `afk config set permissionMode default`. Does not affect ask_question.").option("--mcp-config <path>","Path to an additional MCP config file (highest priority \u2014 merges over ~/.afk/config/mcp.json, project-local .mcp.json, and plugin-contributed configs). File format identical to mcp.json.").action(async t=>{if(t.debug&&(process.env.AFK_DEBUG="1"),t.dumpPrompt!==void 0){let L=t.dumpPrompt===!0?ls.join(O$.homedir(),".afk","logs",`prompt-dump-${new Date().toISOString().replace(/[:.]/g,"-")}.json`):String(t.dumpPrompt);process.env.AFK_DUMP_PROMPT=L,t.provider!==void 0&&t.provider!=="anthropic"&&t.provider!=="anthropic-direct"&&console.error(`[--dump-prompt] WARNING: active provider (${t.provider}) does not support prompt dumping. No file will be written.`)}let n=M$({text:"Initializing interactive session...",...Sl}).start();if(t.resume||t.continue)try{let L=Ai({resume:t.resume,continue:t.continue});if(L&&!L.stored){n.fail("Session not found"),process.stderr.write(`Error: session not found: ${JSON.stringify(t.resume)}
|
|
2040
2040
|
Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
2041
2041
|
`),process.exitCode=1;return}}catch(L){n.fail("Session not found");let I=L instanceof Error?L.message:String(L);process.stderr.write(`Error: ${I}
|
|
2042
2042
|
Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
2043
2043
|
`),process.exitCode=1;return}let r=At(),o=v.AFK_WORKTREE_BRANCH_PREFIX??r.interactive?.worktreeBranchPrefix,s=t.worktreeBase??v.AFK_WORKTREE_BASE??r.interactive?.worktreeBase,i={};o!==void 0&&(i.branchPrefix=o),s!==void 0&&(i.baseRef=s);let a=Object.keys(i).length>0?i:void 0,l=v.AFK_WORKTREE_BOOT_PRUNE==="0",c=await b$({disabled:l}),u=I7(t,r),d=Re(),p=t.worktree===!0&&u&&d!==void 0,m,g,h;if(t.worktree!==void 0)try{p?(h=await Yk(a),n.text="Worktree will be named from your first message"):(g=await du(t.worktree,a),m=g.path,n.text=`Worktree ready at ${g.path} (branch: ${g.branch})`)}catch(L){n.fail("Worktree setup failed"),J(L)}let b=c.ran&&c.removedCount>0?`Pruned ${c.removedCount} stale worktree(s). Run /worktree list for details.`:void 0,y;try{y=await UO(t,m!==void 0?{cwd:m}:void 0)}catch(L){n.fail("Invalid options"),J(L)}if(h!==void 0&&d!==void 0){let L=h,I=d;y.firstTurnHook=async U=>{let M=M$({text:"Naming & creating worktree\u2026",...Sl}).start(),j=await k$({deferred:L,message:U,token:I,session:y.session.current,...o!==void 0?{branchPrefix:o}:{}}).finally(()=>M.stop());if(j.status==="created"||j.status==="created-fallback"){g=L.handle(),y.stats.cwd=j.path;let Y=ls.relative(process.cwd(),j.path)||j.path;if(j.status==="created")console.log(f.dim(" \u21AA worktree: ")+`${Y} `+f.dim(`(branch: ${j.branch})`));else{let oe=_7(j.reason,j.detail),X=oe!==void 0?f.dim(` \u2014 ${oe}`):"";console.log(f.dim(" \u21AA worktree: ")+`${Y} `+f.dim(`(branch: ${j.branch})`)+X)}}else console.warn(f.warning("\u26A0 ")+`Worktree creation failed: ${j.reason}. `+f.dim(`Continuing in ${wl(process.cwd(),{maxWidth:60})} (no isolation).`))}}Ho(async()=>{y.teardownTrustedSkillEvents?.(),lt.uninstall(),y.bgSummarizer?.stop(),await y.backgroundRegistry.cancelAll().catch(()=>{}),await y.session.current.close(),y.mcpManager&&await y.mcpManager.disconnectAll(),y.memoryStore.close(),g!==void 0&&await g.cleanup({force:y.stats.totalTurns===0})}),n.succeed("Session ready"),g!==void 0?console.log(f.dim(" \u21AA worktree: ")+f.dim(wl(g.path,{maxWidth:60}))+f.dim(` (branch: ${g.branch})`)):h!==void 0&&console.log(f.dim(" \u21AA worktree: named & created from your first message"));let S=await WO(()=>y.stats.model);console.log(f.dim(` transcript: ${S.path()}`)),Ho(async()=>{await S.appendEnded()});let w=!1,T=()=>{if(y.stats.totalTurns===0)return;let L=$n(y.stats);return w=!0,L};Ho(async()=>{if(!w)try{T()}catch{}});let x={turnInFlight:!1,lastSigintAt:0};y.getInFlight=()=>x.turnInFlight;let C=1500,R=()=>{let L=Date.now();if(x.tryAbortShellForeground&&x.tryAbortShellForeground()){x.lastSigintAt=L;return}if(x.turnInFlight){x.requestSoftStop?x.requestSoftStop():y.session.current.interrupt().catch(()=>{}),x.lastSigintAt=L,x.notifyInterrupting?.(!0);let I=`
|
|
2044
2044
|
`+f.info("\u2139 ")+"Press Ctrl+C again to exit.",U=x.activeCompositor;if(U&&U.isArmed())try{U.commitAbove(I)}catch{console.log(I)}else console.log(I);return}if(L-x.lastSigintAt<C){y.session.current?.abort("sigint"),y.rl.close();return}x.lastSigintAt=L,console.log(`
|
|
2045
2045
|
`+f.info("\u2139 ")+"Press Ctrl+C again (or /exit) to quit.")};process.on("SIGINT",R),Ho(async()=>{process.removeListener("SIGINT",R)});let k=!1,$=()=>{if(k)return;k=!0,y.session.current?.abort("sigterm");try{y.rl.close()}catch{}setTimeout(()=>{tp().finally(()=>process.exit(0))},2e3).unref()};process.on("SIGTERM",$),Ho(async()=>{process.removeListener("SIGTERM",$)});let A=!1,P=()=>{if(A)return;A=!0,y.session.current?.abort("sighup");try{y.rl.close()}catch{}setTimeout(()=>{tp().finally(()=>process.exit(0))},2e3).unref()};process.on("SIGHUP",P),Ho(async()=>{process.removeListener("SIGHUP",P)}),process.stdout.write("\x1B[3J\x1B[2J\x1B[H");let F=1,D=process.stdout.write.bind(process.stdout),N=process.stderr.write.bind(process.stderr),B=L=>(typeof L=="string"?L:L instanceof Uint8Array?Buffer.from(L).toString("utf8"):String(L)).match(/\n/g)?.length??0,H=L=>((I,...U)=>(F+=B(I),L(I,...U)));process.stdout.write=H(D),process.stderr.write=H(N);try{if(Am!==null){let{updateInfo:I,pendingMessage:U}=Am;Am=null,U!==null&&process.stderr.write(U),I!==null&&Cm(I)}let L=y.resumeTarget?`Resuming ${y.resumeTarget.id} \xB7 ${y.stats.totalTurns} prior turn${y.stats.totalTurns===1?"":"s"}`:void 0;console.log(`
|
|
2046
|
-
`+mv({mode:"Interactive Mode",model:y.stats.model,version:kr(),...g!==void 0?{worktree:g.branch}:{},cwd:m??process.cwd(),...L!==void 0?{metaLine:L}:{},hintLine:P7()})),b!==void 0&&console.log(f.dim(` ${b}`)),y.resumeTarget&&pp(y.stats,y.completionWriter),console.log()}finally{process.stdout.write=D,process.stderr.write=N}y.preArmAnchorRow=F,y.statusLine.start(),y.slashCtx.ui.repaintStatusLine(),y.rl.on("close",async()=>{y.statusLine.stop(),M7(y,g,T),console.log(f.info("\u2139 ")+"Goodbye!"),await tp(),process.exit(0)}),await h$(y,S,x,R)})}function M7(e,t,n){if(e.stats.totalTurns===0)return;console.log(pe("Session Summary"));let r=[`${e.stats.totalTurns} turn${e.stats.totalTurns===1?"":"s"}`,me(Date.now()-e.stats.sessionStartTime)];e.stats.totalCostUsd>0&&r.push(rt(e.stats.totalCostUsd)),e.stats.totalTokens>0&&r.push(ie(e.stats.totalTokens)+" tokens"),console.log(f.dim(" "+r.join(" \xB7 ")));let o=t?ls.basename(t.path):"none";console.log(f.dim(` model: ${e.stats.model} \xB7 worktree: ${o}`));try{let i=e.stats.cwd??process.cwd(),l=C7("git",["diff","--shortstat","HEAD"],{cwd:i,encoding:"utf8",timeout:2e3}).trim();console.log(f.dim(` edits: ${l||"no files changed"}`))}catch{}let s=e.stats.sessionId;try{let i=n();!s&&i&&(s=ls.basename(i,".json"))}catch{}s&&console.log(f.dim(" Continue with: ")+f.brand(Dn(s,e.stats.model))),console.log()}q();import O7 from"ora";li();tt();ze();Mt();function L$(e){e.command("status").description("Check agent connection status").option("-f, --format <format>","Output format (text|json)","text").action(async t=>{let n=O7("Checking status...").start();try{let r=
|
|
2046
|
+
`+mv({mode:"Interactive Mode",model:y.stats.model,version:kr(),...g!==void 0?{worktree:g.branch}:{},cwd:m??process.cwd(),...L!==void 0?{metaLine:L}:{},hintLine:P7()})),b!==void 0&&console.log(f.dim(` ${b}`)),y.resumeTarget&&pp(y.stats,y.completionWriter),console.log()}finally{process.stdout.write=D,process.stderr.write=N}y.preArmAnchorRow=F,y.statusLine.start(),y.slashCtx.ui.repaintStatusLine(),y.rl.on("close",async()=>{y.statusLine.stop(),M7(y,g,T),console.log(f.info("\u2139 ")+"Goodbye!"),await tp(),process.exit(0)}),await h$(y,S,x,R)})}function M7(e,t,n){if(e.stats.totalTurns===0)return;console.log(pe("Session Summary"));let r=[`${e.stats.totalTurns} turn${e.stats.totalTurns===1?"":"s"}`,me(Date.now()-e.stats.sessionStartTime)];e.stats.totalCostUsd>0&&r.push(rt(e.stats.totalCostUsd)),e.stats.totalTokens>0&&r.push(ie(e.stats.totalTokens)+" tokens"),console.log(f.dim(" "+r.join(" \xB7 ")));let o=t?ls.basename(t.path):"none";console.log(f.dim(` model: ${e.stats.model} \xB7 worktree: ${o}`));try{let i=e.stats.cwd??process.cwd(),l=C7("git",["diff","--shortstat","HEAD"],{cwd:i,encoding:"utf8",timeout:2e3}).trim();console.log(f.dim(` edits: ${l||"no files changed"}`))}catch{}let s=e.stats.sessionId;try{let i=n();!s&&i&&(s=ls.basename(i,".json"))}catch{}s&&console.log(f.dim(" Continue with: ")+f.brand(Dn(s,e.stats.model))),console.log()}q();import O7 from"ora";li();tt();ze();Mt();function L$(e){e.command("status").description("Check agent connection status").option("-f, --format <format>","Output format (text|json)","text").action(async t=>{let n=O7("Checking status...").start();try{let r=vt(),o=re(r),s=qe(r),i=o==="openai-compatible"||o==="openai-codex";await new St({model:i?"gpt-4o-mini":"haiku",...s!==void 0?{apiKey:s}:{},maxTurns:1}).close(),n.succeed(`${o} provider reachable`);let l=Js();if(t.format==="json"){let c=Re(),u=hd(),d=c?v.ANTHROPIC_API_KEY?"ANTHROPIC_API_KEY":"CLAUDE_CODE_OAUTH_TOKEN":null,p=u?v.OPENAI_API_KEY?"OPENAI_API_KEY":"CODEX_API_KEY":null;console.log(JSON.stringify({providers:{anthropic:{ok:!!c,source:d},codex:{ok:!!u,source:p}},model:String(r),permissionMode:l,bypass:l==="bypassPermissions"},null,2))}else{let c=l==="bypassPermissions"?{label:"Permissions",value:"Bypass \u2014 path containment off (read/write anywhere)",kind:"warn"}:{label:"Permissions",value:`Contained \u2014 mode: ${l}`,kind:"info"};console.log(`
|
|
2047
2047
|
`+lv("Agent AFK \xB7 Status",[{label:"Provider",value:o,kind:"info"},{label:"Auth",value:i?s?"Found (OPENAI_API_KEY / CODEX_API_KEY)":"Reading ~/.codex/auth.json (run `afk provider auth diagnose`)":s?"Found (ANTHROPIC_API_KEY)":"Falling back to Claude OAuth",kind:s?"ok":"warn"},{label:"Model",value:String(r),kind:"info"},c])+`
|
|
2048
2048
|
`)}}catch(r){n.fail("Connection failed"),J(r)}})}q();import{readFileSync as $7}from"fs";tt();Mt();import F$ from"chalk";function _m(e){return process.stdin.isTTY||(console.error(F$.red(`Cannot securely prompt for secret on a non-TTY stdin: "${e.trim()}"`)),console.error(F$.gray(" Supply the token via environment variable or ~/.afk/config/afk.env instead.")),process.exit(1)),new Promise(t=>{process.stdout.write(e);let n=[];process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf-8");let r=o=>{o==="\r"||o===`
|
|
2049
2049
|
`||o===""?(process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",r),process.stdout.write(`
|
|
@@ -2052,12 +2052,12 @@ Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
|
2052
2052
|
`)),console.log(` Model: ${f.info(o?s:s+" (default)")}`),console.log(` Provider: ${f.plan(i)}`),console.log(i==="anthropic"?` API Key: ${c?f.success("\u2713 Set (ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN)"):f.warning("\u26A0 Not set \u2014 subprocess will fall back to OAuth / keychain")}`:` API Key: ${c?f.success("\u2713 Set (OPENAI_API_KEY / CODEX_API_KEY)"):f.warning("\u26A0 Not set \u2014 falling back to `codex login` state")}`);let g=v.AFK_THINKING||"(unset \u2014 SDK default)";console.log(` Thinking: ${f.info(g)}`);let h=v.AFK_EFFORT||"(unset \u2014 SDK default)";console.log(` Effort: ${f.info(h)}`),console.log(` Permission Mode: ${m?f.warning(`${p} (bypass \u2014 path containment off)`):f.info(`${p} (path containment on)`)}`),console.log(f.meta(`
|
|
2053
2053
|
Edit config:`)),console.log(f.meta(" afk config set permissionMode default # re-enable path containment")),console.log(f.meta(" afk config set <key> <value> e.g. afk config set model opus")),console.log(f.meta(" afk config env set <KEY> [value] e.g. afk config env set AFK_EFFORT high")),console.log(f.meta(" afk config get [key] / afk config env get [key]")),console.log("")}});t.command("get [key]").description("Read afk.config.json \u2014 a dotted key (e.g. telegram.notify.mode) or the whole file").option("--json","Output JSON").action((r,o)=>{try{if(r){let s=Fu(r);o.json?console.log(JSON.stringify(s)):console.log(s.value===void 0?f.meta("(unset)"):String(JSON.stringify(s.value)))}else{let s=Nu();console.log(JSON.stringify(s,null,2))}}catch(s){cs(s.message)}}),t.command("set <key> <value>").description("Set an afk.config.json key (dotted path; agent + human-tier keys)").option("--json","Output JSON").action((r,o,s)=>{try{let i=Du(r,o,{allowHumanOnly:!0});s.json?console.log(JSON.stringify({ok:!0,...i})):console.log(f.success(`\u2713 ${i.path} = ${JSON.stringify(i.value)} \u2192 ${i.persistedTo}
|
|
2054
2054
|
${Lr}.`))}catch(i){cs(i.message)}}),t.command("unset <key>").description("Remove an afk.config.json key").option("--json","Output JSON").action((r,o)=>{try{let s=Lu(r,{allowHumanOnly:!0});o.json?console.log(JSON.stringify({ok:!0,...s})):console.log(s.removed?f.success(`\u2713 removed ${s.path} \u2192 ${s.persistedTo}`):f.meta(`(${s.path} was not set)`))}catch(s){cs(s.message)}});let n=t.command("env").description("View or edit afk.env environment variables");n.command("get [key]").description("Read afk.env \u2014 one var or all present (secrets masked)").option("--all","Include every known var, not just those set").option("--json","Output JSON").action((r,o)=>{try{if(r){let s=Pu(r);o.json?console.log(JSON.stringify(s)):console.log(`${s.key} [${s.class}]: ${s.persisted??f.meta("(unset)")}`)}else{let s=Mu({all:o.all});if(o.json)console.log(JSON.stringify(s,null,2));else for(let i of s)console.log(`${i.key} [${i.class}]: ${i.persisted??f.meta("(unset)")}`)}}catch(s){cs(s.message)}}),n.command("set <key> [value]").description("Set an afk.env var. Secret vars are prompted (masked) unless --stdin is given.").option("--stdin","Read the value from stdin (for scripted secret entry)").option("--json","Output JSON").action(async(r,o,s)=>{try{let i=Xs(r),a=o;if(i==="secret")s.stdin?a=N$():a=await _m(`${r} (input hidden): `),o!==void 0&&console.error(f.warning(" note: positional value ignored for a secret var \u2014 use the prompt or --stdin"));else if(a===void 0)if(s.stdin)a=N$();else{cs(`${r} requires a value`);return}let l=_u(r,a??"",{allowSecret:!0,allowProtected:!0});s.json?console.log(JSON.stringify({ok:!0,...l})):console.log(f.success(`\u2713 ${l.key} = ${l.display} \u2192 ${l.persistedTo}
|
|
2055
|
-
${Lr}.`))}catch(i){cs(i.message)}}),n.command("unset <key>").description("Remove an afk.env var").option("--json","Output JSON").action((r,o)=>{try{let s=Iu(r,{allowSecret:!0,allowProtected:!0});o.json?console.log(JSON.stringify({ok:!0,...s})):console.log(s.removed?f.success(`\u2713 removed ${s.key} \u2192 ${s.persistedTo}`):f.meta(`(${s.key} was not set)`))}catch(s){cs(s.message)}})}q();import uZ from"path";import dZ from"os";import{createServer as J7}from"node:http";import{writeFileSync as V7,unlinkSync as Y7,mkdirSync as X7,readFileSync as Z7}from"node:fs";import{dirname as Q7,join as eZ}from"node:path";q();import{mkdirSync as j7,appendFileSync as H7}from"node:fs";import{dirname as W7}from"node:path";import{execFile as K7}from"node:child_process";import{promisify as G7}from"node:util";import{randomUUID as q7}from"node:crypto";import*as Z$ from"node-cron";var Im=class{_count=0;increment(){this._count++}decrement(){this._count>0&&this._count--}isIdle(){return this._count===0}count(){return this._count}};G();wi();import{mkdirSync as $w,readdirSync as H$,readFileSync as D7,renameSync as Mw,unlinkSync as Dw,writeFileSync as L7}from"node:fs";import{randomBytes as Ow}from"node:crypto";import{join as us}from"node:path";function W$(e,t={},n=hn()){$w(n,{recursive:!0});let o=H$(n).filter(m=>m.endsWith(".json")).length+1,s=`q-${Date.now()}-${Ow(3).toString("hex")}`,i=new Date().toISOString(),a={id:s,command:e,enqueuedAt:i,sequence:o,...t.notifyOn!==void 0?{notifyOn:t.notifyOn}:{}},c=`${String(o).padStart(4,"0")}-${s}.json`,u=us(n,c),d=Ow(4).toString("hex"),p=us(n,`.tmp-${d}.json`);try{L7(p,JSON.stringify(a),"utf-8"),Mw(p,u)}catch(m){try{Dw(p)}catch{}throw m}return a}var U$="poison";function K$(e=hn()){$w(e,{recursive:!0});let t=H$(e).filter(n=>n.endsWith(".json")&&!n.startsWith(".tmp-")).sort();for(let n of t){let r=us(e,n),o;try{o=D7(r,"utf-8")}catch(i){j$(e,n,i);continue}let s;try{s=JSON.parse(o)}catch(i){j$(e,n,i);continue}return Dw(r),s}return null}function j$(e,t,n){let r=
|
|
2056
|
-
`);for(let o=r.length-1;o>=0;o-=1){let s=r[o];if(s)try{let i=JSON.parse(s);if(i.taskId!==e||typeof i.triggeredAt!="string")continue;let a=Date.parse(i.triggeredAt);if(Number.isNaN(a))continue;return a}catch{continue}}return null}function U7(e){if(!q$(e))return 0;try{return N7(e,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(".md")).length}catch{return 0}}function V$(e){let t=B7(e.taskId,e.telemetryPath);if(t!==null&&e.cooldownMs>0){let r=e.nowMs-t;if(r<e.cooldownMs)return{fire:!1,skipReason:"cooldown",lastFiredAtMs:t,cooldownRemainingMs:e.cooldownMs-r}}let n=U7(e.briefsDir);return n>0?{fire:!1,skipReason:"briefs_pending",pendingBriefCount:n,...t!==null?{lastFiredAtMs:t}:{}}:{fire:!0,...t!==null?{lastFiredAtMs:t}:{}}}var Y$=G7(K7);async function z7(e,t,n){if(n!==void 0&&n.length>0)return n;try{let o=(await e("git",["rev-parse","--show-toplevel"],{cwd:t})).stdout.trim();return o.length>0?o:null}catch{return null}}function X$(e){return`${e.replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"task"}-${q7()}`}var Pm=class{registry=new Map;options;defaultCooldownMs;briefsDir;now;idleDetector=new Im;pullPollTimer;isDequeuing=!1;queueDir;constructor(t={}){this.options=t,this.defaultCooldownMs=t.cooldownMs??z$,this.briefsDir=t.briefsDir??J$(),this.now=t.now??Date.now,this.queueDir=t.queueDir??hn(),this.ensureTelemetrySink()}register(t){if(G$(t),this.registry.has(t.taskId))throw new Error(`task ${t.taskId} is already registered`);let n;(t.trigger==="cron"||t.trigger==="both")&&(n=Z$.schedule(t.cronExpression,()=>{this.runOnce(t,"cron").catch(()=>{})},{name:t.taskId})),this.registry.set(t.taskId,{task:t,cronTask:n})}unregister(t){let n=this.registry.get(t);n&&(n.cronTask&&(Promise.resolve(n.cronTask.stop()).catch(()=>{}),Promise.resolve(n.cronTask.destroy()).catch(()=>{})),this.registry.delete(t))}list(){return Array.from(this.registry.values()).map(t=>t.task)}async tick(t){let n=this.registry.get(t);if(!n)throw new Error(`task ${t} is not registered`);return this.runOnce(n.task,"cron")}async fireOnStart(){let t=Array.from(this.registry.values()).map(r=>r.task).filter(r=>r.trigger==="sessionstart"||r.trigger==="both"),n=[];for(let r of t){let o=r.debounceMs??this.defaultCooldownMs,s=V$({taskId:r.taskId,cooldownMs:o,nowMs:this.now(),telemetryPath:this.telemetryPath(),briefsDir:this.briefsDir});s.fire?n.push(await this.runOnce(r,"sessionstart")):n.push(this.recordSkip(r,s))}return n}async stop(){this.pullPollTimer!==void 0&&(clearInterval(this.pullPollTimer),this.pullPollTimer=void 0);for(let t of Array.from(this.registry.keys()))this.unregister(t)}startPullLoop(){if(this.pullPollTimer!==void 0)return;let t=this.options.pullPollIntervalMs;!t||t<=0||(this.pullPollTimer=setInterval(()=>{this.pullTick()},t).unref())}async pullTick(){if(this.idleDetector.isIdle()&&!this.isDequeuing){this.isDequeuing=!0;try{let t=K$(this.queueDir);if(t===null)return;let n={taskId:t.id,command:t.command,trigger:"pull",...t.notifyOn!==void 0?{notifyOn:t.notifyOn}:{}};await this.runOnce(n,"pull")}catch(t){let n=
|
|
2057
|
-
`,"utf-8"),this.fireOnTaskComplete(t,n,r)}catch(o){let s=o instanceof Error?o.message:String(o);console.error(`[daemon] telemetry write failed: ${s}`)}}fireOnTaskComplete(t,n,r){let o=this.options.onTaskComplete;if(o&&!(n!==void 0&&(n.notifyOn==="never"||n.notifyOn==="failure"&&t.status!=="error")))try{let s=o(t,r);s instanceof Promise&&s.catch(i=>{let a=i instanceof Error?i.message:String(i);console.error(`[daemon] onTaskComplete callback failed: ${a}`)})}catch(s){let i=s instanceof Error?s.message:String(s);console.error(`[daemon] onTaskComplete callback failed: ${i}`)}}};G();var tZ=7777,nZ="127.0.0.1";async function Q$(e={}){let t=new Pm({...e.sessionConfig!==void 0?{sessionConfig:e.sessionConfig}:{},...e.telemetryPath!==void 0?{telemetryPath:e.telemetryPath}:{},...e.sessionFactory!==void 0?{sessionFactory:e.sessionFactory}:{},...e.cooldownMs!==void 0?{cooldownMs:e.cooldownMs}:{},...e.briefsDir!==void 0?{briefsDir:e.briefsDir}:{},...e.now!==void 0?{now:e.now}:{},...e.onTaskComplete!==void 0?{onTaskComplete:e.onTaskComplete}:{},...e.pullPollIntervalMs!==void 0?{pullPollIntervalMs:e.pullPollIntervalMs}:{},...e.queueDir!==void 0?{queueDir:e.queueDir}:{}});e.pullPollIntervalMs!==void 0&&e.pullPollIntervalMs>0&&t.startPullLoop();for(let a of e.tasks??[])t.register(a);let n=e.writePortFile!==!1,r=eZ(hc("default"),"port"),o=J7((a,l)=>oZ(a,l,t)),{port:s,address:i}=await iZ(o,e.port??tZ,e.host??nZ);if(n)try{X7(Q7(r),{recursive:!0}),V7(r,String(s),"utf-8")}catch{}return{port:s,host:i,scheduler:t,registerTask(a){t.register(a)},unregisterTask(a){t.unregister(a)},tickOnce(a){return t.tick(a)},fireOnStart(){return t.fireOnStart()},async stop(){if(await t.stop(),n)try{Z7(r,"utf-8").trim()===String(s)&&Y7(r)}catch{}await aZ(o)}}}function rZ(e){return new Promise((t,n)=>{let r=[];e.on("data",o=>r.push(o)),e.on("end",()=>t(Buffer.concat(r).toString("utf-8"))),e.on("error",n)})}function oZ(e,t,n){sZ(e,t,n).catch(r=>{let o=r instanceof Error?r.message:String(r);t.headersSent||t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:o}))})}async function sZ(e,t,n){let r=e.url??"/";if(e.method==="GET"&&r==="/health"){let o=JSON.stringify({status:"ok",tasks:n.list().length});t.writeHead(200,{"Content-Type":"application/json"}),t.end(o);return}if(e.method==="GET"&&r==="/tasks"){t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(n.list()));return}if(e.method==="POST"&&r==="/tasks"){let o=await rZ(e),s;try{s=JSON.parse(o)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid JSON body"}));return}if(!s||typeof s!="object"){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"body must be an object"}));return}let i=s,a=i.cron??i.cronExpression;if(typeof i.taskId!="string"||typeof i.command!="string"||typeof a!="string"){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"taskId, command, and cron (or cronExpression) are required strings"}));return}let l={taskId:i.taskId,command:i.command,trigger:i.trigger??"cron",cronExpression:a,...i.notifyOn!==void 0?{notifyOn:i.notifyOn}:{}};try{n.register(l)}catch(c){let u=c instanceof Error?c.message:String(c),d=u.includes("already registered")?409:400;t.writeHead(d,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:u}));return}t.writeHead(201,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0}));return}if(e.method==="DELETE"&&r.startsWith("/tasks/")){let o=r.slice(7);if(!o){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"taskId required in URL"}));return}if(!n.list().some(i=>i.taskId===o)){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}n.unregister(o),t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0}));return}t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"not found"}))}function iZ(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen(t,n,()=>{e.removeListener("error",o);let s=e.address();r(typeof s=="object"&&s?{port:s.port,address:s.address}:{port:t,address:n})})})}function aZ(e){return new Promise((t,n)=>{e.close(r=>{r?n(r):t()})})}G();_o();function eD(e,t){let n=e??t;if(n===void 0||n==="")return;let r=Number(n);if(!Number.isFinite(r)||!Number.isInteger(r)||r<=0)throw new Error(`Invalid timeout-ms: '${n}' \u2014 must be a positive integer (milliseconds).`);return r}function tD(e,t){let n=e??t;if(n===void 0||n==="")return;let r=Number(n);if(!Number.isFinite(r)||!Number.isInteger(r)||r<0)throw new Error(`Invalid sessionstart-cooldown-ms: '${n}' \u2014 must be a non-negative integer (milliseconds).`);return r}function nD(e,t){if(e!==void 0&&e!==""){if(e==="cron"||e==="sessionstart"||e==="both"||e==="pull")return e;throw new Error(`Invalid trigger: '${e}' \u2014 must be one of cron | sessionstart | both | pull.`)}return t!==void 0&&t!==""?"cron":"sessionstart"}var lZ="",Lw="default";function co(e){if(e!==void 0&&e.trim()!=="")return e}function rD(e,t,n){return co(e)??co(t)??co(n)??lZ}function oD(e,t,n){return co(e)??co(t)??co(n)??Lw}var cZ="127.0.0.1";function sD(e,t){return co(e)??co(t)??cZ}function iD(e){let t=e.trim().toLowerCase();return t==="127.0.0.1"||t==="localhost"||t==="::1"}Mt();ze();vu();li();an();Xe();nl();rl();Gr();Fo();kn();an();Tn();function pZ(e){let t;return n=>{let r=new AbortController,o=Lo(r.signal),s=new se({...e.apiKey!==void 0?{apiKey:e.apiKey}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.cwd!==void 0?{cwd:e.cwd}:{}}),i=ii(e.openaiBaseUrl!==void 0?{openaiBaseUrl:e.openaiBaseUrl}:{}),a=ai(e.model,e.apiKey,i,e.baseUrl,void 0,void 0,e.cwd,qe,"daemon"),l=new Pn({subagentManager:s,parentSession:o,surface:"daemon",defaultConfig:{...e.apiKey!==void 0?{apiKey:e.apiKey}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}},defaultSubagentModel:Vt(e.model),childProviderFactory:i,childSkillExecutorFactory:a,resolveApiKeyForModel:qe,depth:0,...e.cwd!==void 0?{cwd:e.cwd}:{}}),c=new Mn({parentSession:o,surface:"daemon",defaultModel:e.model,defaultSubagentModel:Vt(e.model),...e.apiKey!==void 0?{apiKey:e.apiKey}:{},childProviderFactory:i,childSkillExecutorFactory:a,resolveApiKeyForModel:qe,...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.cwd!==void 0?{cwd:e.cwd}:{}}),u=new Xr({parentSession:o,defaultModel:e.model,defaultSubagentModel:Vt(e.model),...e.apiKey!==void 0?{apiKey:e.apiKey}:{},resolveApiKeyForModel:qe,...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.cwd!==void 0?{cwd:e.cwd}:{},systemPrompt:"",surface:"daemon",depth:0});t??=new at;let d=n.mcpManager,p=d?.getMcpToolWireNames()??[],m=hi(void 0,{subagentExecutor:l,skillExecutor:c,composeExecutor:u,memoryStore:t,model:String(e.model),...e.openaiBaseUrl!==void 0?{openaiBaseUrl:e.openaiBaseUrl}:{},...d!==void 0?{mcpManager:d}:{}})??new Ge({permissions:{allowedTools:[...Wt,...Qn,...pt,"agent","skill","compose",...p]},subagentExecutor:l,skillExecutor:c,composeExecutor:u,memoryStore:t,surface:"daemon",...d!==void 0?{mcpManager:d}:{}});return new
|
|
2055
|
+
${Lr}.`))}catch(i){cs(i.message)}}),n.command("unset <key>").description("Remove an afk.env var").option("--json","Output JSON").action((r,o)=>{try{let s=Iu(r,{allowSecret:!0,allowProtected:!0});o.json?console.log(JSON.stringify({ok:!0,...s})):console.log(s.removed?f.success(`\u2713 removed ${s.key} \u2192 ${s.persistedTo}`):f.meta(`(${s.key} was not set)`))}catch(s){cs(s.message)}})}q();import uZ from"path";import dZ from"os";import{createServer as J7}from"node:http";import{writeFileSync as V7,unlinkSync as Y7,mkdirSync as X7,readFileSync as Z7}from"node:fs";import{dirname as Q7,join as eZ}from"node:path";q();import{mkdirSync as j7,appendFileSync as H7}from"node:fs";import{dirname as W7}from"node:path";import{execFile as K7}from"node:child_process";import{promisify as G7}from"node:util";import{randomUUID as q7}from"node:crypto";import*as Z$ from"node-cron";var Im=class{_count=0;increment(){this._count++}decrement(){this._count>0&&this._count--}isIdle(){return this._count===0}count(){return this._count}};G();wi();import{mkdirSync as $w,readdirSync as H$,readFileSync as D7,renameSync as Mw,unlinkSync as Dw,writeFileSync as L7}from"node:fs";import{randomBytes as Ow}from"node:crypto";import{join as us}from"node:path";function W$(e,t={},n=hn()){$w(n,{recursive:!0});let o=H$(n).filter(m=>m.endsWith(".json")).length+1,s=`q-${Date.now()}-${Ow(3).toString("hex")}`,i=new Date().toISOString(),a={id:s,command:e,enqueuedAt:i,sequence:o,...t.notifyOn!==void 0?{notifyOn:t.notifyOn}:{}},c=`${String(o).padStart(4,"0")}-${s}.json`,u=us(n,c),d=Ow(4).toString("hex"),p=us(n,`.tmp-${d}.json`);try{L7(p,JSON.stringify(a),"utf-8"),Mw(p,u)}catch(m){try{Dw(p)}catch{}throw m}return a}var U$="poison";function K$(e=hn()){$w(e,{recursive:!0});let t=H$(e).filter(n=>n.endsWith(".json")&&!n.startsWith(".tmp-")).sort();for(let n of t){let r=us(e,n),o;try{o=D7(r,"utf-8")}catch(i){j$(e,n,i);continue}let s;try{s=JSON.parse(o)}catch(i){j$(e,n,i);continue}return Dw(r),s}return null}function j$(e,t,n){let r=mt(t),o=mt(n instanceof Error?n.message:String(n)),s=us(e,U$),i=us(e,t);try{$w(s,{recursive:!0});let a=us(s,t);try{Mw(i,a)}catch{a=us(s,`${Date.now()}-${Ow(3).toString("hex")}-${t}`),Mw(i,a)}console.error(`[daemon] pull-queue: quarantined malformed entry ${r} \u2192 ${U$}/ (${o})`)}catch(a){let l=mt(a instanceof Error?a.message:String(a));console.error(`[daemon] pull-queue: failed to quarantine malformed entry ${r}; removing to unblock queue (${l})`);try{Dw(i)}catch(c){let u=mt(c instanceof Error?c.message:String(c));console.error(`[daemon] pull-queue: could not remove unquarantinable entry ${r}; will retry next tick (${u})`)}}}G();$y();an();ir();G();wi();function G$(e){if(!e.taskId)throw new Error("ScheduledTask.taskId is required");if(!e.command)throw new Error(`task ${e.taskId}: command is required`);if((e.trigger==="cron"||e.trigger==="both")&&!e.cronExpression)throw new Error(`task ${e.taskId}: cronExpression required for trigger=${e.trigger}`);if(e.trigger==="pull"&&e.cronExpression!==void 0)throw new Error(`task ${e.taskId}: cronExpression must not be set when trigger='pull' \u2014 pull tasks are dequeued from the queue directory, not scheduled via cron`)}G();import{existsSync as q$,readFileSync as F7,readdirSync as N7}from"node:fs";var z$=360*60*1e3;function J$(){return Ss()}function B7(e,t){if(!q$(t))return null;let n;try{n=F7(t,"utf-8")}catch{return null}let r=n.split(`
|
|
2056
|
+
`);for(let o=r.length-1;o>=0;o-=1){let s=r[o];if(s)try{let i=JSON.parse(s);if(i.taskId!==e||typeof i.triggeredAt!="string")continue;let a=Date.parse(i.triggeredAt);if(Number.isNaN(a))continue;return a}catch{continue}}return null}function U7(e){if(!q$(e))return 0;try{return N7(e,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(".md")).length}catch{return 0}}function V$(e){let t=B7(e.taskId,e.telemetryPath);if(t!==null&&e.cooldownMs>0){let r=e.nowMs-t;if(r<e.cooldownMs)return{fire:!1,skipReason:"cooldown",lastFiredAtMs:t,cooldownRemainingMs:e.cooldownMs-r}}let n=U7(e.briefsDir);return n>0?{fire:!1,skipReason:"briefs_pending",pendingBriefCount:n,...t!==null?{lastFiredAtMs:t}:{}}:{fire:!0,...t!==null?{lastFiredAtMs:t}:{}}}var Y$=G7(K7);async function z7(e,t,n){if(n!==void 0&&n.length>0)return n;try{let o=(await e("git",["rev-parse","--show-toplevel"],{cwd:t})).stdout.trim();return o.length>0?o:null}catch{return null}}function X$(e){return`${e.replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"task"}-${q7()}`}var Pm=class{registry=new Map;options;defaultCooldownMs;briefsDir;now;idleDetector=new Im;pullPollTimer;isDequeuing=!1;queueDir;constructor(t={}){this.options=t,this.defaultCooldownMs=t.cooldownMs??z$,this.briefsDir=t.briefsDir??J$(),this.now=t.now??Date.now,this.queueDir=t.queueDir??hn(),this.ensureTelemetrySink()}register(t){if(G$(t),this.registry.has(t.taskId))throw new Error(`task ${t.taskId} is already registered`);let n;(t.trigger==="cron"||t.trigger==="both")&&(n=Z$.schedule(t.cronExpression,()=>{this.runOnce(t,"cron").catch(()=>{})},{name:t.taskId})),this.registry.set(t.taskId,{task:t,cronTask:n})}unregister(t){let n=this.registry.get(t);n&&(n.cronTask&&(Promise.resolve(n.cronTask.stop()).catch(()=>{}),Promise.resolve(n.cronTask.destroy()).catch(()=>{})),this.registry.delete(t))}list(){return Array.from(this.registry.values()).map(t=>t.task)}async tick(t){let n=this.registry.get(t);if(!n)throw new Error(`task ${t} is not registered`);return this.runOnce(n.task,"cron")}async fireOnStart(){let t=Array.from(this.registry.values()).map(r=>r.task).filter(r=>r.trigger==="sessionstart"||r.trigger==="both"),n=[];for(let r of t){let o=r.debounceMs??this.defaultCooldownMs,s=V$({taskId:r.taskId,cooldownMs:o,nowMs:this.now(),telemetryPath:this.telemetryPath(),briefsDir:this.briefsDir});s.fire?n.push(await this.runOnce(r,"sessionstart")):n.push(this.recordSkip(r,s))}return n}async stop(){this.pullPollTimer!==void 0&&(clearInterval(this.pullPollTimer),this.pullPollTimer=void 0);for(let t of Array.from(this.registry.keys()))this.unregister(t)}startPullLoop(){if(this.pullPollTimer!==void 0)return;let t=this.options.pullPollIntervalMs;!t||t<=0||(this.pullPollTimer=setInterval(()=>{this.pullTick()},t).unref())}async pullTick(){if(this.idleDetector.isIdle()&&!this.isDequeuing){this.isDequeuing=!0;try{let t=K$(this.queueDir);if(t===null)return;let n={taskId:t.id,command:t.command,trigger:"pull",...t.notifyOn!==void 0?{notifyOn:t.notifyOn}:{}};await this.runOnce(n,"pull")}catch(t){let n=mt(t instanceof Error?t.message:String(t));console.error(`[daemon] pull tick failed: ${n}`)}finally{this.isDequeuing=!1}}}async runOnce(t,n){if(t.command==="__BUILTIN_WORKTREE_PRUNE__")return this.runBuiltinWorktreePrune(t,n);let r=new Date(this.now()),o=this.now(),s={taskId:t.taskId,command:mt(t.command),trigger:n,...t.cronExpression!==void 0?{cronExpression:t.cronExpression}:{},triggeredAt:r.toISOString()},i=null,a=null,l=null;this.idleDetector.increment();try{let c=await this.spawnSession(t.taskId);i=c.session,a=c.memoryStore,l=c.mcpManager??null;let u=await i.sendMessage(t.command),d=mt(u.content),p={...s,durationMs:this.now()-o,status:"success",responseExcerpt:d.slice(0,280)};return this.writeTelemetry(p,t,{responseText:d}),p}catch(c){let u={...s,durationMs:this.now()-o,status:"error",errorMessage:mt(c instanceof Error?c.message:String(c))};return this.writeTelemetry(u,t),u}finally{if(this.idleDetector.decrement(),i)try{await i.close()}catch{}if(l)try{await l.disconnectAll()}catch{}a?.close()}}recordSkip(t,n){let r=new Date(this.now()),o={taskId:t.taskId,command:t.command,trigger:"sessionstart",...t.cronExpression!==void 0?{cronExpression:t.cronExpression}:{},triggeredAt:r.toISOString(),durationMs:0,status:"skipped",...n.skipReason!==void 0?{skipReason:n.skipReason}:{}};return this.writeTelemetry(o,t),o}async runBuiltinWorktreePrune(t,n){let r=new Date(this.now()),o=this.now(),s={taskId:t.taskId,command:t.command,trigger:n,...t.cronExpression!==void 0?{cronExpression:t.cronExpression}:{},triggeredAt:r.toISOString()};try{let i=await z7(Y$,process.cwd(),v.AFK_WORKTREE_SWEEP_ROOT);if(i===null){let m={...s,durationMs:this.now()-o,status:"skipped",responseExcerpt:"worktree-prune skipped: daemon cwd is not inside a git repository (set AFK_WORKTREE_SWEEP_ROOT to target a repo)"};return this.writeTelemetry(m,t),m}let a=parseInt(v.AFK_WORKTREE_MAX_AGE_CLEAN??"",10)||14,l=parseInt(v.AFK_WORKTREE_MAX_AGE_DIRTY??"",10)||30,c=await Bn({execFile:Y$,repoRoot:i,dryRun:!1,maxAgeDaysClean:a,maxAgeDaysDirty:l,scope:"all",telemetryPath:this.telemetryPath()}),u=new Set(["empty","stale-clean","orphaned-dir","orphaned-registration","dead-owner"]),d=c.dryRun?`\u{1F50D} worktree-prune (dry-run): would remove ${c.candidates.filter(m=>u.has(m.verdict)).length} worktree(s)`:`\u2702\uFE0F worktree-prune: removed ${c.removed.length}, warned ${c.warnings.length}`,p={...s,durationMs:this.now()-o,status:"success",responseExcerpt:d};return this.writeTelemetry(p,t),p}catch(i){let a={...s,durationMs:this.now()-o,status:"error",errorMessage:mt(i instanceof Error?i.message:String(i))};return this.writeTelemetry(a,t),a}}async spawnSession(t){let n=X$(t),r=this.options.sessionConfig?.cwd??process.cwd(),o=Qr({sessionLabel:X$(t)}),{registry:s,memoryStore:i}=Ei(void 0,"daemon",void 0,void 0,ki({cwd:r}),{cwd:r,sessionId:n,...o?.writer!==void 0?{traceWriter:o.writer}:{}}),a,l=rn(Pt()).mcpConfigs.filter(p=>p.format==="json").map(p=>p.source),c=jo({cwd:r,...l.length>0?{importedMcpConfigs:l}:{}}),u=Object.values(c.mcpServers).filter(p=>!p.disabled).length;try{if(u>0)a=await hr.fromConfig(c.mcpServers,{warnings:c.warnings,...o?.writer!==void 0?{traceWriter:o.writer}:{}});else if(c.warnings.length>0)for(let p of c.warnings)console.warn(`[mcp] ${p}`)}catch(p){throw i.close(),p}let d={model:"sonnet",permissionMode:"bypassPermissions",hookRegistry:s,isNonInteractive:!0,surface:"daemon",...o?{traceWriter:o.writer}:{},...a!==void 0?{mcpManager:a}:{},...this.options.sessionConfig};try{return{session:this.options.sessionFactory?this.options.sessionFactory(d):new St(lr(d)),memoryStore:i,...a!==void 0?{mcpManager:a}:{}}}catch(p){throw a&&await a.disconnectAll().catch(()=>{}),i.close(),p}}telemetryPath(){return this.options.telemetryPath??Tr()}ensureTelemetrySink(){try{j7(W7(this.telemetryPath()),{recursive:!0})}catch{}}writeTelemetry(t,n,r){try{H7(this.telemetryPath(),`${JSON.stringify(t)}
|
|
2057
|
+
`,"utf-8"),this.fireOnTaskComplete(t,n,r)}catch(o){let s=o instanceof Error?o.message:String(o);console.error(`[daemon] telemetry write failed: ${s}`)}}fireOnTaskComplete(t,n,r){let o=this.options.onTaskComplete;if(o&&!(n!==void 0&&(n.notifyOn==="never"||n.notifyOn==="failure"&&t.status!=="error")))try{let s=o(t,r);s instanceof Promise&&s.catch(i=>{let a=i instanceof Error?i.message:String(i);console.error(`[daemon] onTaskComplete callback failed: ${a}`)})}catch(s){let i=s instanceof Error?s.message:String(s);console.error(`[daemon] onTaskComplete callback failed: ${i}`)}}};G();var tZ=7777,nZ="127.0.0.1";async function Q$(e={}){let t=new Pm({...e.sessionConfig!==void 0?{sessionConfig:e.sessionConfig}:{},...e.telemetryPath!==void 0?{telemetryPath:e.telemetryPath}:{},...e.sessionFactory!==void 0?{sessionFactory:e.sessionFactory}:{},...e.cooldownMs!==void 0?{cooldownMs:e.cooldownMs}:{},...e.briefsDir!==void 0?{briefsDir:e.briefsDir}:{},...e.now!==void 0?{now:e.now}:{},...e.onTaskComplete!==void 0?{onTaskComplete:e.onTaskComplete}:{},...e.pullPollIntervalMs!==void 0?{pullPollIntervalMs:e.pullPollIntervalMs}:{},...e.queueDir!==void 0?{queueDir:e.queueDir}:{}});e.pullPollIntervalMs!==void 0&&e.pullPollIntervalMs>0&&t.startPullLoop();for(let a of e.tasks??[])t.register(a);let n=e.writePortFile!==!1,r=eZ(hc("default"),"port"),o=J7((a,l)=>oZ(a,l,t)),{port:s,address:i}=await iZ(o,e.port??tZ,e.host??nZ);if(n)try{X7(Q7(r),{recursive:!0}),V7(r,String(s),"utf-8")}catch{}return{port:s,host:i,scheduler:t,registerTask(a){t.register(a)},unregisterTask(a){t.unregister(a)},tickOnce(a){return t.tick(a)},fireOnStart(){return t.fireOnStart()},async stop(){if(await t.stop(),n)try{Z7(r,"utf-8").trim()===String(s)&&Y7(r)}catch{}await aZ(o)}}}function rZ(e){return new Promise((t,n)=>{let r=[];e.on("data",o=>r.push(o)),e.on("end",()=>t(Buffer.concat(r).toString("utf-8"))),e.on("error",n)})}function oZ(e,t,n){sZ(e,t,n).catch(r=>{let o=r instanceof Error?r.message:String(r);t.headersSent||t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:o}))})}async function sZ(e,t,n){let r=e.url??"/";if(e.method==="GET"&&r==="/health"){let o=JSON.stringify({status:"ok",tasks:n.list().length});t.writeHead(200,{"Content-Type":"application/json"}),t.end(o);return}if(e.method==="GET"&&r==="/tasks"){t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(n.list()));return}if(e.method==="POST"&&r==="/tasks"){let o=await rZ(e),s;try{s=JSON.parse(o)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid JSON body"}));return}if(!s||typeof s!="object"){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"body must be an object"}));return}let i=s,a=i.cron??i.cronExpression;if(typeof i.taskId!="string"||typeof i.command!="string"||typeof a!="string"){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"taskId, command, and cron (or cronExpression) are required strings"}));return}let l={taskId:i.taskId,command:i.command,trigger:i.trigger??"cron",cronExpression:a,...i.notifyOn!==void 0?{notifyOn:i.notifyOn}:{}};try{n.register(l)}catch(c){let u=c instanceof Error?c.message:String(c),d=u.includes("already registered")?409:400;t.writeHead(d,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:u}));return}t.writeHead(201,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0}));return}if(e.method==="DELETE"&&r.startsWith("/tasks/")){let o=r.slice(7);if(!o){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"taskId required in URL"}));return}if(!n.list().some(i=>i.taskId===o)){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}n.unregister(o),t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0}));return}t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"not found"}))}function iZ(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen(t,n,()=>{e.removeListener("error",o);let s=e.address();r(typeof s=="object"&&s?{port:s.port,address:s.address}:{port:t,address:n})})})}function aZ(e){return new Promise((t,n)=>{e.close(r=>{r?n(r):t()})})}G();_o();function eD(e,t){let n=e??t;if(n===void 0||n==="")return;let r=Number(n);if(!Number.isFinite(r)||!Number.isInteger(r)||r<=0)throw new Error(`Invalid timeout-ms: '${n}' \u2014 must be a positive integer (milliseconds).`);return r}function tD(e,t){let n=e??t;if(n===void 0||n==="")return;let r=Number(n);if(!Number.isFinite(r)||!Number.isInteger(r)||r<0)throw new Error(`Invalid sessionstart-cooldown-ms: '${n}' \u2014 must be a non-negative integer (milliseconds).`);return r}function nD(e,t){if(e!==void 0&&e!==""){if(e==="cron"||e==="sessionstart"||e==="both"||e==="pull")return e;throw new Error(`Invalid trigger: '${e}' \u2014 must be one of cron | sessionstart | both | pull.`)}return t!==void 0&&t!==""?"cron":"sessionstart"}var lZ="",Lw="default";function co(e){if(e!==void 0&&e.trim()!=="")return e}function rD(e,t,n){return co(e)??co(t)??co(n)??lZ}function oD(e,t,n){return co(e)??co(t)??co(n)??Lw}var cZ="127.0.0.1";function sD(e,t){return co(e)??co(t)??cZ}function iD(e){let t=e.trim().toLowerCase();return t==="127.0.0.1"||t==="localhost"||t==="::1"}Mt();ze();vu();li();an();Xe();nl();rl();Gr();Fo();kn();an();Tn();function pZ(e){let t;return n=>{let r=new AbortController,o=Lo(r.signal),s=new se({...e.apiKey!==void 0?{apiKey:e.apiKey}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.cwd!==void 0?{cwd:e.cwd}:{}}),i=ii(e.openaiBaseUrl!==void 0?{openaiBaseUrl:e.openaiBaseUrl}:{}),a=ai(e.model,e.apiKey,i,e.baseUrl,void 0,void 0,e.cwd,qe,"daemon"),l=new Pn({subagentManager:s,parentSession:o,surface:"daemon",defaultConfig:{...e.apiKey!==void 0?{apiKey:e.apiKey}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}},defaultSubagentModel:Vt(e.model),childProviderFactory:i,childSkillExecutorFactory:a,resolveApiKeyForModel:qe,depth:0,...e.cwd!==void 0?{cwd:e.cwd}:{}}),c=new Mn({parentSession:o,surface:"daemon",defaultModel:e.model,defaultSubagentModel:Vt(e.model),...e.apiKey!==void 0?{apiKey:e.apiKey}:{},childProviderFactory:i,childSkillExecutorFactory:a,resolveApiKeyForModel:qe,...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.cwd!==void 0?{cwd:e.cwd}:{}}),u=new Xr({parentSession:o,defaultModel:e.model,defaultSubagentModel:Vt(e.model),...e.apiKey!==void 0?{apiKey:e.apiKey}:{},resolveApiKeyForModel:qe,...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.cwd!==void 0?{cwd:e.cwd}:{},systemPrompt:"",surface:"daemon",depth:0});t??=new at;let d=n.mcpManager,p=d?.getMcpToolWireNames()??[],m=hi(void 0,{subagentExecutor:l,skillExecutor:c,composeExecutor:u,memoryStore:t,model:String(e.model),...e.openaiBaseUrl!==void 0?{openaiBaseUrl:e.openaiBaseUrl}:{},...d!==void 0?{mcpManager:d}:{}})??new Ge({permissions:{allowedTools:[...Wt,...Qn,...pt,"agent","skill","compose",...p]},subagentExecutor:l,skillExecutor:c,composeExecutor:u,memoryStore:t,surface:"daemon",...d!==void 0?{mcpManager:d}:{}});return new St(lr({...n,provider:m,isNonInteractive:!0,surface:"daemon"}))}}function mZ(e,t={}){let n=e.status==="success"?"\u2705":e.status==="skipped"?"\u23ED\uFE0F":"\u274C",r=(e.durationMs/1e3).toFixed(1),o=[`${n} daemon task: ${e.taskId} (${e.status})`,`trigger=${e.trigger} duration=${r}s`];e.skipReason&&o.push(`skipReason=${e.skipReason}`),e.errorMessage&&o.push(`error: ${e.errorMessage.slice(0,400)}`);let s=t.responseText??e.responseExcerpt;return s&&o.push("",s),o.join(`
|
|
2058
2058
|
`)}function aD(e){e.command("daemon").description("Run agent-afk as a daemon that fires scheduled tasks (e.g. /forge-friction --auto)").option("-p, --port <number>","Control HTTP port","7777").option("--host <address>","Bind address for the control HTTP surface. Overrides AFK_DAEMON_HOST. Defaults to 127.0.0.1 (loopback only). The control surface is UNAUTHENTICATED \u2014 bind a non-loopback address (e.g. 0.0.0.0) only on a trusted or firewalled network.").option("-t, --task <command>","Command to fire on each tick. Required for the cron and both triggers; optional otherwise.").option("-c, --cron <expression>",'Cron expression (e.g. "0 */6 * * *"). Required when --trigger includes cron.').option("-i, --task-id <id>",`Task identifier (default: ${Lw})`).option("--once","Fire one tick and exit (for testing)",!1).option("--timeout-ms <ms>","Per-tick session timeout in ms. Overrides AFK_TIMEOUT_MS. Defaults to the session default (120000).").option("--thinking <mode>","Thinking mode: 'adaptive' | 'disabled' | 'enabled:<N>'").option("--effort <level>","Effort level: low|medium|high|xhigh|max").option("--trigger <mode>","Trigger mode: cron | sessionstart | both | pull. Defaults to 'cron' when --cron is set, else 'sessionstart'.").option("--sessionstart-cooldown-ms <ms>","Cooldown between Phase 6 sessionstart fires. Overrides AFK_SESSIONSTART_COOLDOWN_MS. Defaults to 6h.").option("--briefs-dir <path>","Override directory scanned for pending briefs (defaults to ~/.afk/agent-framework/briefs).").option("--dump-prompt [path]",'Dump resolved SDK prompt+options+provenance to file (default: ~/.afk/logs/prompt-dump-<ISO>.json) or "stderr"').action(async t=>{let n=parseInt(t.port,10);(Number.isNaN(n)||n<=0)&&J(new Error(`Invalid port: ${t.port}`));let r=At(),o=rD(t.task,v.AFK_DAEMON_TASK,r.daemon?.task),s=oD(t.taskId,v.AFK_DAEMON_TASK_ID,r.daemon?.taskId),i=sD(t.host,v.AFK_DAEMON_HOST),a,l,c;try{a=eD(t.timeoutMs,v.AFK_TIMEOUT_MS),l=tD(t.sessionstartCooldownMs,v.AFK_SESSIONSTART_COOLDOWN_MS),c=nD(t.trigger,t.cron)}catch(A){J(A)}(c==="cron"||c==="both")&&!t.cron&&J(new Error(`--cron is required when --trigger is '${c}'.`)),(c==="cron"||c==="both")&&o.trim()===""&&J(new Error("A daemon task is required for the cron and both triggers. Provide one via --task, the AFK_DAEMON_TASK env var, or daemon.task in afk.config.json."));let u,d;try{u=Vr(t.thinking)??pi(),d=Yr(t.effort)??mi()}catch(A){J(A)}let p=r.daemon?.worktreePrune,m=v.AFK_WORKTREE_PRUNE_DISABLE==="1",g=p?.cron??"0 4 * * *",h={taskId:"worktree-prune",command:"__BUILTIN_WORKTREE_PRUNE__",trigger:"cron",cronExpression:g},b=c==="pull"||o.trim()===""?[]:[{taskId:s,command:o,trigger:c,...t.cron!==void 0?{cronExpression:t.cron}:{}}];!m&&p?.enabled!==!1&&b.push(h);let y=qt();for(let A of y)A.enabled&&b.push(QE(A));if(t.dumpPrompt!==void 0&&t.dumpPrompt!==!1){let A=t.dumpPrompt===!0?uZ.join(dZ.homedir(),".afk","logs",`prompt-dump-${new Date().toISOString().replace(/[:.]/g,"-")}.json`):t.dumpPrompt;process.env.AFK_DUMP_PROMPT=A}let S=0,w=6e4,T=(A,P)=>{let F=Date.now();if(F-S<w)return;S=F;let D=P instanceof Error?`${P.name}: ${P.message}`:String(P);$r(`\u{1F6D1} agent-afk daemon ${A}
|
|
2059
|
-
${D.slice(0,500)}`).catch(N=>{console.error("[daemon] crash notification push failed:",N instanceof Error?N.message:String(N))})};process.on("uncaughtException",A=>{T("uncaughtException",A),process.exit(1)}),process.on("unhandledRejection",A=>{T("unhandledRejection",A),process.exit(1)});let x=v.AFK_DAEMON_CWD,C=
|
|
2060
|
-
\xB7 Shutting down daemon...`)),await A.stop(),process.exit(0)};process.on("SIGINT",P),process.on("SIGTERM",P)}catch(A){J(A)}})}import{mkdirSync as fZ}from"node:fs";import{join as gZ}from"node:path";G();function lD(e){e.command("queue").description("Manage the pull-trigger task queue (used with `afk daemon --trigger pull`)").command("add <command>").description("Enqueue a command for the pull-trigger daemon to execute").option("--notify-on <mode>","When to send a notification: failure | always | never").action((n,r)=>{try{let o=hn();fZ(o,{recursive:!0});let s=r.notifyOn,i=W$(n,{notifyOn:s},o),a=String(i.sequence).padStart(4,"0"),l=gZ(o,`${a}-${i.id}.json`);console.log(f.success(`\u2714 Queued task #${a} (id: ${i.id})`)),console.log(f.dim(` command: ${n}`)),console.log(f.dim(` file: ${l}`))}catch(o){J(o)}})}tt();ze();import Zi from"chalk";import cD from"chalk";G();xu();function uD(){return _m("Anthropic API key or OAuth token: ")}async function Mm(e){let t=e??await uD();t||(console.error(cD.red("No token provided. Nothing saved.")),process.exit(1));let n=
|
|
2059
|
+
${D.slice(0,500)}`).catch(N=>{console.error("[daemon] crash notification push failed:",N instanceof Error?N.message:String(N))})};process.on("uncaughtException",A=>{T("uncaughtException",A),process.exit(1)}),process.on("unhandledRejection",A=>{T("unhandledRejection",A),process.exit(1)});let x=v.AFK_DAEMON_CWD,C=vt(),R=Re(),k=x!==void 0&&x.length>0?x:void 0,$=pZ({model:C,...R!==void 0?{apiKey:R}:{},...r.baseUrl!==void 0?{baseUrl:r.baseUrl}:{},...r.openaiBaseUrl!==void 0?{openaiBaseUrl:r.openaiBaseUrl}:{},...k!==void 0?{cwd:k}:{}});try{let A=await Q$({port:n,host:i,...t.once?{writePortFile:!1}:{},sessionConfig:{model:C,...R!==void 0?{apiKey:R}:{},...r.baseUrl!==void 0?{baseUrl:r.baseUrl}:{},...a!==void 0?{timeoutMs:a}:{},...u!==void 0?{thinking:u}:{},...d!==void 0?{effort:d}:{},...k!==void 0?{cwd:k}:{}},sessionFactory:$,...l!==void 0?{cooldownMs:l}:{},...t.briefsDir!==void 0?{briefsDir:t.briefsDir}:{},...c==="pull"?{pullPollIntervalMs:3e4,queueDir:hn()}:{},tasks:b,onTaskComplete:(F,D)=>{$r(mZ(F,D),{markdown:!0}).catch(()=>{})}});if(t.once){console.log(f.info(`\u25B6 Firing task '${s}' once...`));let F=await A.tickOnce(s);console.log(JSON.stringify(F,null,2)),await A.stop(),process.exit(F.status==="success"?0:1)}if(c==="sessionstart"||c==="both"){let F=await A.fireOnStart();for(let D of F){let N=D.status==="success"?"\u2714":D.status==="skipped"?"\u23ED":"\u2717";console.log(f.info(`${N} sessionstart: ${JSON.stringify(D)}`))}}console.log(f.success(`\u2714 Daemon listening on http://${A.host}:${A.port}`)),iD(A.host)||console.log(f.warning(`\u26A0 Control surface bound to ${A.host} (non-loopback) and is UNAUTHENTICATED \u2014 anyone who can reach this port can schedule commands the daemon will run. Ensure the port is firewalled / on a trusted network.`)),c==="pull"?(console.log(f.success("\u2714 Daemon in pull mode")),console.log(f.dim(` polling queue: ${hn()} every 30s`))):console.log(f.dim(` task='${s}' command='${o}' trigger='${c}'${t.cron?` cron='${t.cron}'`:""}`)),b.length>1&&console.log(f.meta(` + built-in: worktree-prune (cron: ${g})`)),console.log(f.dim(" Press Ctrl+C to stop."));let P=async()=>{console.log(f.dim(`
|
|
2060
|
+
\xB7 Shutting down daemon...`)),await A.stop(),process.exit(0)};process.on("SIGINT",P),process.on("SIGTERM",P)}catch(A){J(A)}})}import{mkdirSync as fZ}from"node:fs";import{join as gZ}from"node:path";G();function lD(e){e.command("queue").description("Manage the pull-trigger task queue (used with `afk daemon --trigger pull`)").command("add <command>").description("Enqueue a command for the pull-trigger daemon to execute").option("--notify-on <mode>","When to send a notification: failure | always | never").action((n,r)=>{try{let o=hn();fZ(o,{recursive:!0});let s=r.notifyOn,i=W$(n,{notifyOn:s},o),a=String(i.sequence).padStart(4,"0"),l=gZ(o,`${a}-${i.id}.json`);console.log(f.success(`\u2714 Queued task #${a} (id: ${i.id})`)),console.log(f.dim(` command: ${n}`)),console.log(f.dim(` file: ${l}`))}catch(o){J(o)}})}tt();ze();import Zi from"chalk";import cD from"chalk";G();xu();function uD(){return _m("Anthropic API key or OAuth token: ")}async function Mm(e){let t=e??await uD();t||(console.error(cD.red("No token provided. Nothing saved.")),process.exit(1));let n=ht(),r,o;t.startsWith("sk-ant-oat")?(r="CLAUDE_CODE_OAUTH_TOKEN",o=["ANTHROPIC_API_KEY"]):(r="ANTHROPIC_API_KEY",o=["CLAUDE_CODE_OAUTH_TOKEN"]),sn(n,r,t,o),console.log(cD.green(`\u2713 Saved ${r} to ${n}`)),console.log(f.meta("Restart any running afk daemon to pick up the new token."))}function dD(e){e.command("login [token]").description("Save an Anthropic API key or OAuth token for afk to use").action(async t=>{let n=re(vt());if(n==="openai-compatible"||n==="openai-codex"){console.log(Zi.yellow("`afk login` is Anthropic-only.")),console.log(""),console.log("For OpenAI-backed models (gpt-*, o1*, o3*, o4*, codex-*), authenticate with one of:"),console.log(Zi.cyan(" export OPENAI_API_KEY=sk-proj-...")),console.log(Zi.cyan(" # or: export CODEX_API_KEY=...")),console.log(Zi.cyan(" codex login --api-key sk-proj-...")),console.log(""),console.log(Zi.gray("Run `afk provider auth diagnose` to see which auth source AFK will use.")),console.log(Zi.gray("To save an Anthropic key for Claude models instead, re-run with AFK_MODEL=sonnet (or similar) first."));return}await Mm(t)})}import ge from"chalk";import Om from"ora";G();import{existsSync as hZ}from"fs";import{join as yZ}from"path";Dt();zr();async function Fw(e,t={},n={}){let r=n.pluginsDir??Ve(),o=n.indexPath??ce(),s=n.now??(()=>new Date),i=n.gitRunner?{runner:n.gitRunner}:{},l=xe(o).plugins[e];if(!l)throw new Error(`plugin "${e}" is not installed`);let c=yZ(r,e);if(!hZ(c))return{name:e,status:"missing-dir",dir:c};if(ur(),l.sourceType==="local")return{name:e,status:"skipped-local"};await im(c,i);let u,d=!1;if(t.ref)u=t.ref;else{let x=await so(c,i),C=ao(x);C!==null?(u=C,d=!0):u=l.ref??await Hn(c,i)}let p=`refs/remotes/origin/${u}`,m=d?null:await am(c,p,i),g=m!==null,h=await jn(c,i);if(g?m===h:u===l.ref)return{name:e,status:"up-to-date",ref:u,commit:h,version:es(c).version};await io(c,g?p:d?`refs/tags/${u}`:u,{...i,force:!0});let y=await jn(c,i),S=es(c).version,w=s().toISOString(),T={...l,ref:u,commit:y,updatedAt:w};return qr(e,T,o),{name:e,status:"updated",fromRef:l.ref,toRef:u,commit:y,version:S}}async function pD(e={}){let t=e.indexPath??ce(),n=xe(t),r=[];for(let o of Object.keys(n.plugins))try{r.push(await Fw(o,{},e))}catch(s){let i=s instanceof Error?s.message:String(s);r.push({name:o,status:"missing-dir",dir:i})}return r}G();Dt();import{existsSync as bZ,lstatSync as wZ,rmSync as SZ,unlinkSync as vZ}from"fs";import{join as kZ}from"path";zr();function mD(e,t={}){Sr(e);let n=t.pluginsDir??Ve(),r=t.indexPath??ce(),o=kZ(n,e),s=!1;EZ(o)?(vZ(o),s=!0):bZ(o)&&(SZ(o,{recursive:!0,force:!0}),s=!0);let i=xe(r),a=Object.prototype.hasOwnProperty.call(i.plugins,e);return a&&uR(e,r),ur(),{name:e,removedDir:s,removedIndexEntry:a}}function EZ(e){try{return wZ(e).isSymbolicLink()}catch{return!1}}Dt();G();function fD(e,t={}){let n=t.logger??console,r=t.pluginsDir??Ve(),o=t.indexPath??ce(),s={...t,pluginsDir:r,indexPath:o},i=e.command("plugin").description("Manage AFK plugins (install / update / list / remove / enable / disable)");i.command("install <source> [name]").description("Install a plugin from a git URL, owner/repo shorthand, local path, or <marketplace>:<plugin>").option("-r, --ref <ref>","Install a specific tag, branch, or SHA").option("-f, --force","Replace an existing plugin with the same name").option("-y, --yes","Skip the install warning and countdown (non-interactive / CI)").action(async(a,l,c)=>{let u;try{u=Vi(a)}catch(m){Om(`Installing ${a}\u2026`).start().fail("Failed"),J(m)}let d=process.stderr.isTTY===!0&&!c.yes;if(u.type==="marketplace-ref"){let m=Om(`Installing ${u.marketplace}:${u.plugin}\u2026`).start();try{let g=await Yi(u.marketplace,u.plugin,{...c.ref?{ref:c.ref}:{},...c.force?{force:!0}:{}},{...s,confirm:d});m.succeed(ge.green(`Installed ${ge.bold(g.key)}`)+ge.gray(` at ${g.dir}`))}catch(g){m.fail("Failed"),J(g)}return}let p=Om(`Installing ${a}\u2026`).start();try{let m={...l?{name:l}:{},...c.ref?{ref:c.ref}:{},...c.force?{force:!0}:{}},g=await um(a,m,{...s,confirm:d});p.succeed(ge.green(`Installed ${ge.bold(g.name)}`)+ge.gray(` at ${g.dir}${g.entry.ref?` (ref: ${g.entry.ref})`:""}`))}catch(m){p.fail("Failed"),J(m)}}),i.command("update [name]").description("Update one plugin, or all if no name is given").option("-r, --ref <ref>","Pin to a specific ref instead of the latest tag").action(async(a,l)=>{try{if(a){let c=Om(`Updating ${a}\u2026`).start(),u=await Fw(a,l.ref?{ref:l.ref}:{},s);xZ(u,c)}else{n.log(ge.cyan("Updating all plugins\u2026"));let c=await pD(s);if(c.length===0){n.log(ge.gray(" (nothing installed)"));return}for(let u of c)n.log(" "+gD(u))}}catch(c){J(c)}}),i.command("list").description("List installed plugins with their source, version, and enabled state").option("-f, --format <format>","Output format (text|json)","text").action(a=>{let l=xe(o);if(a.format==="json"){let c=Object.entries(l.plugins).map(([u,d])=>({name:u,enabled:d.enabled,...d.ref?{ref:d.ref}:{},source:d.source}));n.log(JSON.stringify({plugins:c},null,2))}else TZ(l,n)}),i.command("remove <name>").description("Remove a plugin (directory + index entry)").action(a=>{let l=mD(a,{pluginsDir:r,indexPath:o});if(!l.removedDir&&!l.removedIndexEntry){n.log(ge.gray(`No plugin named "${a}" to remove.`));return}let c=[l.removedDir?"directory":null,l.removedIndexEntry?"index entry":null].filter(Boolean);n.log(ge.green(`Removed ${a}: ${c.join(" + ")}`))}),i.command("enable <name>").description("Re-enable a previously disabled plugin").action(a=>{try{Uh(a,!0,o),n.log(ge.green(`Enabled ${a}`))}catch(l){J(l)}}),i.command("disable <name>").description("Keep the plugin on disk but skip it from SDK init").action(a=>{try{Uh(a,!1,o),n.log(ge.yellow(`Disabled ${a} (dir preserved at ${r}/${a})`))}catch(l){J(l)}})}function TZ(e,t){let n=Object.keys(e.plugins).sort();if(n.length===0){t.log(ge.gray("No plugins installed.")),t.log(ge.gray(" Try: afk plugin install anthropics/claude-plugins-official"));return}t.log(ge.cyan.bold(`
|
|
2061
2061
|
Installed plugins:`));for(let r of n){let o=e.plugins[r];if(!o)continue;let s=o.enabled?ge.green("enabled "):ge.yellow("disabled"),i=o.ref?ge.blue(o.ref):ge.gray("(local)"),a=ge.gray(o.source);t.log(` ${ge.bold(r.padEnd(30))} ${s} ${i.padEnd(12)} ${a}`)}t.log("")}function gD(e){switch(e.status){case"updated":{let t=e.fromRef===e.toRef?`${e.toRef} @ ${e.commit.slice(0,7)}`:`${e.fromRef??"(none)"} \u2192 ${e.toRef}`,n=e.version?ge.gray(` [v${e.version.replace(/^v/i,"")}]`):"";return`${ge.green("\u2713")} ${ge.bold(e.name)}: ${t}${n}`}case"up-to-date":{let t=e.version?ge.gray(` [v${e.version.replace(/^v/i,"")}]`):"";return`${ge.gray("\xB7")} ${ge.bold(e.name)}: up-to-date (${e.ref})${t}`}case"skipped-local":return`${ge.gray("\xB7")} ${ge.bold(e.name)}: skipped (local source)`;case"missing-dir":return`${ge.yellow("!")} ${ge.bold(e.name)}: plugin dir missing (${e.dir})`}}function xZ(e,t){let n=gD(e);e.status==="updated"?t.succeed(n):e.status==="up-to-date"||e.status==="skipped-local"?t.info(n):t.warn(n)}import ae from"chalk";import Nw from"ora";Dt();G();function hD(e,t={}){let n=t.logger??console,r=t.cacheDir??Kn(),o=t.indexPath??ce(),s={...t,cacheDir:r,indexPath:o},i=e.command("marketplace").description("Manage AFK plugin marketplaces (install / list / plugins / install-plugin / remove / update)");i.command("install <source> [name]").description("Clone or symlink a marketplace into the local plugin cache").option("-r, --ref <ref>","Install a specific tag, branch, or SHA").option("-f, --force","Replace an existing marketplace with the same name").action(async(a,l,c)=>{let u=Nw(`Installing marketplace ${a}\u2026`).start();try{let d={...l?{name:l}:{},...c.ref?{ref:c.ref}:{},...c.force?{force:!0}:{}},p=await pm(a,d,s),m=p.entry.ref?` (ref: ${p.entry.ref})`:"";u.succeed(ae.green(`Installed marketplace ${ae.bold(p.name)}`)+ae.gray(`${m} at ${p.dir}`)),n.log(ae.gray(` ${p.plugins.length} plugin(s) available \u2014 run \`afk marketplace plugins ${p.name}\` to list.`))}catch(d){u.fail("Failed"),J(d)}}),i.command("list").description("List installed marketplaces with their source and ref").option("-f, --format <format>","Output format (text|json)","text").action(a=>{let l=xe(o),c=Object.entries(l.marketplaces);if(a.format==="json"){n.log(JSON.stringify({marketplaces:c.map(([u,d])=>({name:u,source:d.source,sourceType:d.sourceType,...d.ref?{ref:d.ref}:{}}))},null,2));return}if(c.length===0){n.log(ae.gray("No marketplaces installed.")),n.log(ae.gray(" Try: afk marketplace install <org>/<marketplace>"));return}n.log(ae.cyan.bold(`
|
|
2062
2062
|
Installed marketplaces:`));for(let[u,d]of c.sort()){let p=d.ref?ae.blue(d.ref):ae.gray("(local)"),m=ae.gray(d.source);n.log(` ${ae.bold(u.padEnd(30))} ${p.padEnd(12)} ${m}`)}n.log("")}),i.command("plugins <name>").description("List plugins inside a marketplace, with [installed] / [available] markers").option("-f, --format <format>","Output format (text|json)","text").action((a,l)=>{try{let c=gm(a,s);if(l.format==="json"){n.log(JSON.stringify({marketplace:a,plugins:c},null,2));return}if(c.length===0){n.log(ae.gray(`Marketplace "${a}" lists no plugins.`));return}n.log(ae.cyan.bold(`
|
|
2063
2063
|
Plugins in ${a}:`)),c.forEach((u,d)=>{let p=u.installed?ae.green("[\u2713]"):ae.gray("[ ]"),m=u.description?ae.gray(` \u2014 ${u.description}`):"";n.log(` ${p} ${ae.bold((d+1).toString().padStart(2))}. ${ae.bold(u.name)}${m}`)}),n.log(ae.gray(`
|
|
@@ -2166,11 +2166,11 @@ complete -c afk -l trigger -x -a '${n}' -d 'Trigger type'`}function vD(e){e.comm
|
|
|
2166
2166
|
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1||o.slice(0,s).trim()!==t)continue;let a=o.slice(s+1).trim();return(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),a}}async function CD(e){let t=RD(e,"TELEGRAM_BOT_TOKEN");if(!t)return{set:!1,valid:!1,reason:"unset"};let n=await Vw(t);return n?{set:!0,valid:!0,botId:n.id,...n.username!==void 0?{username:n.username}:{}}:{set:!0,valid:!1,reason:"unauthorized"}}async function AD(e,t={}){let n=RD(e,"TELEGRAM_BOT_TOKEN");if(!n)return{found:!1,chats:[],reason:"unset"};let r=t.timeoutSec??60,o=2e3,s=Math.max(1,Math.ceil(r*1e3/o)),i=await _D(n,{maxAttempts:s,intervalMs:o});return i.length===0?{found:!1,chats:[],reason:"timeout"}:{found:!0,chats:i}}async function Vw(e){try{let t=await fetch(`${xD}/bot${e}/getMe`);if(!t.ok)return null;let n=await t.json();return!n.ok||!n.result?.id||!n.result?.first_name?null:{id:n.result.id,...n.result.username!==void 0?{username:n.result.username}:{},firstName:n.result.first_name}}catch{return null}}function nQ(e){let t=new Map;for(let n of e){let o=(n.message??n.edited_message)?.chat;!o||typeof o.id!="number"||t.set(o.id,{chatId:o.id,type:o.type??"unknown",...o.username!==void 0?{username:o.username}:{},...o.first_name!==void 0?{firstName:o.first_name}:{}})}return[...t.values()].reverse()}async function rQ(e){try{let t=await fetch(`${xD}/bot${e}/getUpdates`);if(!t.ok)return[];let n=await t.json();return!n.ok||!Array.isArray(n.result)?[]:n.result}catch{return[]}}async function _D(e,t={}){let n=t.maxAttempts??30,r=t.intervalMs??2e3;for(let o=0;o<n;o++){let s=await rQ(e),i=nQ(s);if(i.length>0)return i;o<n-1&&await new Promise(a=>setTimeout(a,r))}return[]}function TD(e){let t=tQ({input:process.stdin,output:process.stdout});return AM("telegram.setup-wizard",()=>new Promise(n=>{t.question(e,r=>{t.close(),n(r.trim())})}))}function oQ(e){return process.stdin.isTTY||(console.error(Fe.red(`Cannot securely prompt for secret on a non-TTY stdin: "${e.trim()}"`)),console.error(Fe.gray(" Supply TELEGRAM_BOT_TOKEN via environment variable or ~/.afk/config/afk.env instead.")),process.exit(1)),new Promise(t=>{process.stdout.write(e);let n=[];process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf-8");let r=o=>{o==="\r"||o===`
|
|
2167
2167
|
`||o===""?(process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",r),process.stdout.write(`
|
|
2168
2168
|
`),t(n.join("").trim())):o===""?(process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write(`
|
|
2169
|
-
`),process.exit(1)):o==="\x7F"?n.pop():n.push(o)};process.stdin.on("data",r)})}async function ID(){let e=
|
|
2170
|
-
Multiple chats found:`)),o.forEach((l,c)=>{let u=l.username?`@${l.username}`:l.firstName??l.type;console.log(` [${c+1}] ${u} (id ${l.chatId}, ${l.type})`)});let i=await TD("Which chat should be allowed? [1]: "),a=Number.parseInt(i||"1",10)-1;Number.isFinite(a)&&a>=0&&a<o.length&&(s=o[a])}else{let i=s.username?`@${s.username}`:s.firstName??s.type;console.log(Fe.green(`\u2713 Found chat with ${i} (id ${s.chatId})`))}return sn(e,"AFK_TELEGRAM_ALLOWED_CHAT_IDS",String(s.chatId)),console.log(Fe.green(`\u2713 Saved AFK_TELEGRAM_ALLOWED_CHAT_IDS=${s.chatId} \u2192 ${e}`)),console.log(""),console.log(Fe.bold("Setup complete. Start the bot with:")),console.log(Fe.cyan(" afk telegram start")),console.log(""),{envPath:e,bot:n,chatId:s.chatId}}G();function PD(e){let t=e.command("telegram").description("Manage the Agent AFK Telegram bot (setup, start, stop, status)");t.command("setup").description("Interactive setup: validate bot token, discover chat ID, persist to ~/.afk/config/afk.env").action(async()=>{try{await ID()}catch(n){console.error(Me.red(`Setup failed: ${n.message}`)),process.exit(1)}}),t.command("check-token").description("Validate TELEGRAM_BOT_TOKEN via getMe; emit JSON {set, valid, username?, botId?, reason?}").action(async()=>{let n=await CD(
|
|
2171
|
-
`)}),t.command("discover-chat").description("Poll getUpdates for chats that have DM'd the bot; emit JSON {found, chats, reason?}").option("--timeout-sec <n>","How long to poll before giving up","60").action(async n=>{let r=Number.parseInt(n.timeoutSec??"60",10);(!Number.isFinite(r)||r<1)&&(console.error(Me.red("--timeout-sec must be a positive integer")),process.exit(2));let o=await AD(
|
|
2169
|
+
`),process.exit(1)):o==="\x7F"?n.pop():n.push(o)};process.stdin.on("data",r)})}async function ID(){let e=ht();console.log(""),console.log(Fe.bold("\u{1F916} Telegram bot setup")),console.log(""),console.log(Fe.gray(`Config will be written to ${e}`)),console.log("");let t=v.TELEGRAM_BOT_TOKEN?.trim()??"",n=null;for(t&&(console.log(Fe.gray("Validating existing TELEGRAM_BOT_TOKEN...")),n=await Vw(t),n?console.log(Fe.green(`\u2713 Token valid for @${n.username??n.firstName} (id ${n.id})`)):(console.log(Fe.yellow("\u26A0 Existing TELEGRAM_BOT_TOKEN is invalid; prompting for a new one")),t=""));!n;)t=await oQ("Paste your bot token (from @BotFather): "),t||(console.error(Fe.red("No token provided. Aborting.")),process.exit(1)),n=await Vw(t),n||console.log(Fe.red("\u2717 Token rejected by getMe. Try again or Ctrl-C to abort."));sn(e,"TELEGRAM_BOT_TOKEN",t),console.log(Fe.green(`\u2713 Saved TELEGRAM_BOT_TOKEN \u2192 ${e}`)),console.log(""),console.log(Fe.bold("Now DM your bot to authorize your account."));let r=n.username?`@${n.username}`:`"${n.firstName}"`;console.log(` 1. Open Telegram and find ${Fe.cyan(r)}`),console.log(' 2. Send any message (e.g. "hi")'),console.log(""),console.log(Fe.gray("Polling for your chat ID (up to 60s)..."));let o=await _D(t);if(o.length===0){console.error(Fe.red("\u2717 No chats found after 60s.")),console.error(Fe.gray(" Send a message to the bot and run `afk telegram setup` again,")),console.error(Fe.gray(" or paste your chat ID manually:"));let i=await TD("Chat ID: "),a=Number.parseInt(i,10);return Number.isFinite(a)||(console.error(Fe.red("Invalid chat ID. Aborting.")),process.exit(1)),sn(e,"AFK_TELEGRAM_ALLOWED_CHAT_IDS",String(a)),console.log(Fe.green(`\u2713 Saved AFK_TELEGRAM_ALLOWED_CHAT_IDS=${a}`)),{envPath:e,bot:n,chatId:a}}let s=o[0];if(o.length>1){console.log(Fe.bold(`
|
|
2170
|
+
Multiple chats found:`)),o.forEach((l,c)=>{let u=l.username?`@${l.username}`:l.firstName??l.type;console.log(` [${c+1}] ${u} (id ${l.chatId}, ${l.type})`)});let i=await TD("Which chat should be allowed? [1]: "),a=Number.parseInt(i||"1",10)-1;Number.isFinite(a)&&a>=0&&a<o.length&&(s=o[a])}else{let i=s.username?`@${s.username}`:s.firstName??s.type;console.log(Fe.green(`\u2713 Found chat with ${i} (id ${s.chatId})`))}return sn(e,"AFK_TELEGRAM_ALLOWED_CHAT_IDS",String(s.chatId)),console.log(Fe.green(`\u2713 Saved AFK_TELEGRAM_ALLOWED_CHAT_IDS=${s.chatId} \u2192 ${e}`)),console.log(""),console.log(Fe.bold("Setup complete. Start the bot with:")),console.log(Fe.cyan(" afk telegram start")),console.log(""),{envPath:e,bot:n,chatId:s.chatId}}G();function PD(e){let t=e.command("telegram").description("Manage the Agent AFK Telegram bot (setup, start, stop, status)");t.command("setup").description("Interactive setup: validate bot token, discover chat ID, persist to ~/.afk/config/afk.env").action(async()=>{try{await ID()}catch(n){console.error(Me.red(`Setup failed: ${n.message}`)),process.exit(1)}}),t.command("check-token").description("Validate TELEGRAM_BOT_TOKEN via getMe; emit JSON {set, valid, username?, botId?, reason?}").action(async()=>{let n=await CD(ht());process.stdout.write(JSON.stringify(n)+`
|
|
2171
|
+
`)}),t.command("discover-chat").description("Poll getUpdates for chats that have DM'd the bot; emit JSON {found, chats, reason?}").option("--timeout-sec <n>","How long to poll before giving up","60").action(async n=>{let r=Number.parseInt(n.timeoutSec??"60",10);(!Number.isFinite(r)||r<1)&&(console.error(Me.red("--timeout-sec must be a positive integer")),process.exit(2));let o=await AD(ht(),{timeoutSec:r});process.stdout.write(JSON.stringify(o)+`
|
|
2172
2172
|
`)}),t.command("set-allowed-chat <chatId>").description("Persist AFK_TELEGRAM_ALLOWED_CHAT_IDS=<chatId> to ~/.afk/config/afk.env; emit JSON {ok, path}").action(n=>{let r=Number.parseInt(n,10);Number.isFinite(r)||(process.stdout.write(JSON.stringify({ok:!1,reason:"invalid-chat-id"})+`
|
|
2173
|
-
`),process.exit(2));let o=
|
|
2173
|
+
`),process.exit(2));let o=ht();sn(o,"AFK_TELEGRAM_ALLOWED_CHAT_IDS",String(r)),process.stdout.write(JSON.stringify({ok:!0,path:o})+`
|
|
2174
2174
|
`)}),t.command("start").description("Start the bot as a background daemon").action(async()=>{let n=await qw();if(n.kind==="started"){console.log(Me.green(`\u2713 Bot started (PID ${n.pid})`)),console.log(Me.gray(` Logs: ${n.logFile}`)),console.log(Me.gray(" Tail with: afk telegram logs --follow"));return}if(n.kind==="already-running"&&(console.log(Me.yellow(`\u26A0 ${n.message}`)),process.exit(1)),n.kind==="exited-immediately"){if(console.error(Me.red(`\u2717 ${n.message}`)),n.logTail&&n.logTail.length>0){console.error(""),console.error(Me.bold("Last log entries:"));for(let r of n.logTail)console.error(Me.gray(` ${r}`))}process.exit(1)}console.error(Me.red(`\u2717 ${n.message}`)),process.exit(1)}),t.command("stop").description("Stop the bot (SIGTERM, then SIGKILL after 5s)").action(async()=>{let n=await zw();if(n.kind==="not-running"){console.log(Me.yellow("\u26A0 Bot is not running"));return}if(n.kind==="stopped"){console.log(Me.green(`\u2713 Bot stopped (PID ${n.pid})`));return}console.log(Me.yellow(`\u26A0 Bot force-killed (PID ${n.pid}); graceful shutdown timed out`))}),t.command("restart").description("Stop and restart the bot").action(async()=>{let n=await zw();(n.kind==="stopped"||n.kind==="force-killed")&&console.log(Me.gray(`Stopped (PID ${n.pid})`));let r=await qw();if(r.kind==="started"){console.log(Me.green(`\u2713 Bot restarted (PID ${r.pid})`));return}console.error(Me.red(`\u2717 Restart failed: ${r.message}`)),process.exit(1)}),t.command("status").description("Show running state, uptime, memory, and recent log entries").action(()=>{let n=Jw();lQ(n)}),t.command("logs").description("Show or follow the bot log").option("-f, --follow","Stream new log entries (like tail -f)",!1).option("-n, --lines <count>","Number of trailing lines to show","50").action(n=>{let{logFile:r}=Jw();if(!iQ(r)){console.log(Me.yellow(`No log file at ${r}`)),console.log(Me.gray("Start the bot first: afk telegram start"));return}let o=Number.parseInt(n.lines??"50",10);if(n.follow){sQ("tail",["-n",String(o),"-f",r],{stdio:"inherit"}).on("error",a=>{console.error(Me.red(`Failed to spawn tail: ${a.message}`))});return}let s=aQ(r,"utf-8").split(`
|
|
2175
2175
|
`).slice(-o-1);console.log(s.join(`
|
|
2176
2176
|
`))})}function lQ(e){if(console.log(Me.bold("\u{1F4CA} Telegram Bot Status")),console.log(""),e.running?(console.log(` ${Me.green("\u25CF")} Running (PID ${e.pid})`),e.uptimeSec!==void 0&&console.log(` Uptime: ${cQ(e.uptimeSec)}`),e.memoryMb!==void 0&&console.log(` Memory: ${e.memoryMb} MB`)):console.log(` ${Me.red("\u25CF")} Stopped`),console.log(` PID: ${e.pidFile}`),console.log(` Logs: ${e.logFile}`),e.logTail&&e.logTail.length>0){console.log(""),console.log(Me.bold("Recent log entries:"));for(let t of e.logTail)console.log(Me.gray(` ${t}`))}}function cQ(e){if(e<60)return`${e}s`;let t=Math.floor(e/60);if(t<60)return`${t}m ${e%60}s`;let n=Math.floor(t/60);return n<24?`${n}h ${t%60}m`:`${Math.floor(n/24)}d ${n%24}h`}import{execFile as NQ}from"node:child_process";import{promisify as BQ}from"node:util";import ke from"chalk";G();import{execFile as uQ}from"node:child_process";import{randomBytes as dQ}from"node:crypto";import{promises as ta}from"node:fs";import{join as Lm}from"node:path";import{promisify as pQ}from"node:util";var mQ=pQ(uQ),MD=16;var Tt=class extends Error{cause;code;constructor(t,n,r){super(t),this.name="WorktreeError",this.cause=n,this.code=r}};function Yw(e,t=40){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||"task"}function fQ(){return dQ(4).toString("hex").slice(0,4)}function gQ(e){let t=n=>String(n).padStart(2,"0");return`${e.getUTCFullYear()}${t(e.getUTCMonth()+1)}${t(e.getUTCDate())}T${t(e.getUTCHours())}${t(e.getUTCMinutes())}${t(e.getUTCSeconds())}`}function hQ(e,t={}){let n=(t.now??(()=>new Date))(),r=(t.randomSuffix??fQ)();return`${gQ(n)}-${Yw(e,32)}-${r}`}async function ds(e,t){try{let n=await mQ("git",t,{cwd:e,maxBuffer:4194304});return{stdout:n.stdout.trim(),stderr:n.stderr.trim()}}catch(n){let r=n,o=(r.stderr??r.stdout??r.message??"").toString().trim();throw new Tt(`git ${t.join(" ")} failed: ${o}`,n)}}async function yQ(e){let{stdout:t}=await ds(e,["rev-parse","--show-toplevel"]);if(!t)throw new Tt(`not a git repository: ${e}`);return t}async function bQ(e,t){if(t){let{stdout:o}=await ds(e,["rev-parse",t]);return{sha:o}}let{stdout:n}=await ds(e,["rev-parse","HEAD"]),r;try{let{stdout:o}=await ds(e,["symbolic-ref","--quiet","HEAD"]);o&&(r=o)}catch{}return{sha:n,branch:r}}function wQ(e,t,n){let r=n?Yw(n,32):`branch-${t}`;return`afk/farm/${e}/${t}-${r}`}function SQ(e,t){return Lm(e,`branch-${t}`)}async function vQ(e,t){try{await ds(e,["worktree","remove","--force",t])}catch{}}async function kQ(e,t){try{await ds(e,["branch","-D",t])}catch{}}async function OD(e){if(e.count<1||e.count>MD)throw new Tt(`count must be between 1 and ${MD}, got ${e.count}`);if(e.labels&&e.labels.length!==e.count)throw new Tt(`labels.length (${e.labels.length}) must equal count (${e.count})`);let t=e.cwd??process.cwd(),n=await yQ(t),{sha:r,branch:o}=await bQ(n,e.baseRef),s=(e.now??(()=>new Date))(),i=e.taskSlug??hQ(e.taskName,{now:()=>s,randomSuffix:e.randomSuffix}),a=e.taskSlug??i,l=bf(i);try{throw await ta.access(l),new Tt(`farm directory already exists: ${l}`)}catch(d){if(d.code!=="ENOENT")throw d instanceof Tt?d:new Tt(`failed to check farm dir ${l}`,d)}await ta.mkdir(l,{recursive:!0});let c=[];try{for(let d=1;d<=e.count;d++){let p=e.labels?.[d-1],m=wQ(i,d,p),g=SQ(l,d);await ds(n,["worktree","add","-b",m,g,r]),c.push({index:d,label:p?Yw(p,32):void 0,path:g,branch:m})}}catch(d){for(let p of c.slice().reverse())await vQ(n,p.path),await kQ(n,p.branch);throw await ta.rm(l,{recursive:!0,force:!0}).catch(()=>{}),d instanceof Tt?d:new Tt("farm creation failed",d)}let u={schemaVersion:3,taskId:a,taskSlug:i,taskName:e.taskName,repoRoot:n,baseRef:r,baseBranch:o,farmDir:l,createdAt:s.toISOString(),branches:c};return await ta.writeFile(Lm(l,"farm.json"),JSON.stringify(u,null,2)+`
|
|
@@ -2180,9 +2180,9 @@ Multiple chats found:`)),o.forEach((l,c)=>{let u=l.username?`@${l.username}`:l.f
|
|
|
2180
2180
|
`)}async function KD(e,t){let n=FQ(e),r=WD(e.taskSlug),o=t?._push??await Promise.resolve().then(()=>(_o(),Ng)).then(s=>s.pushIfConfigured);try{let s=await o(n,{replyMarkup:r});return s===null?{sent:!1,reason:"telegram unconfigured"}:{sent:!0,chatCount:s.length}}catch(s){return{sent:!1,reason:s instanceof Error?s.message:String(s)}}}var GD=BQ(NQ);async function UQ(e,t){try{let{stdout:n}=await GD("git",["-C",e,"rev-list",`${t}..HEAD`,"--count"],{maxBuffer:4194304});return parseInt(n.trim(),10)||0}catch{return 0}}async function jQ(e){try{let{stdout:t}=await GD("git",["-C",e,"status","--porcelain"],{maxBuffer:4194304});return t.trim()?t.trim().split(`
|
|
2181
2181
|
`).filter(Boolean):[]}catch{return[]}}var Xw=class extends Error{dirtyFiles;constructor(t){super(`Source repository has uncommitted changes after farm run. Dirty files:
|
|
2182
2182
|
${t.map(n=>` ${n}`).join(`
|
|
2183
|
-
`)}`),this.name="FarmIsolationViolation",this.dirtyFiles=t}};function HQ(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function WQ(e){if(e===void 0)return ke.dim("\u2014");if(e===null)return ke.dim("skipped");let t=e.fail===0&&e.pass>0?ke.green("tests\u2713"):ke.red("tests\u2717"),n=e.lint_ok===!0?ke.green("lint\u2713"):e.lint_ok===!1?ke.red("lint\u2717"):ke.dim("lint?"),r=e.loc_delta>0?"+":"",o=ke.dim(`${r}${e.loc_delta} LoC`);return`${t} ${n} ${o}`}function KQ(e,t,n,r){let o="\u2500".repeat(45);console.log(ke.dim(o)),console.log(`farm: ${e}`),console.log(`slug: ${t}`),console.log("");let s=r.some(u=>u.score!=null),i=s?Yl(r.map(u=>({index:u.index,score:u.score??null}))).map(u=>r.find(d=>d.index===u)):r;for(let u=0;u<i.length;u++){let d=i[u],p=n.find(S=>S.index===d.index),m=d.ok?ke.green("\u2713"):ke.red("\u2717"),g=HQ(p.branch,40),h=d.ok?ke.dim(`(${d.commitCount} commit${d.commitCount===1?"":"s"})`):ke.red(`[error: ${d.error}]`),b=s?ke.cyan(`#${u+1} `):"",y=s?` ${WQ(d.score)}`:"";console.log(`${b}branch-${d.index} ${m} ${g} ${h}${y}`),console.log(ke.dim(` worktree: ${p.path}`))}console.log(ke.dim(o));let a=r.filter(u=>u.ok).length,l=r.length;console.log(`${a}/${l} branches completed.`);let c=r.some(u=>u.score!=null&&u.score.pass>0);s&&!c&&console.log(ke.yellow("\u26A0 no branch passed tests \u2014 ranking falls back to lint + LoC"))}function GQ(e,t,n){let r=t.map(a=>{let l=e.branches.find(u=>u.index===a.index),c={index:a.index,branch:l?.branch??`(unknown-${a.index})`,ok:a.ok,commitCount:a.commitCount};return l?.label!==void 0&&(c.label=l.label),a.error!==void 0&&(c.error=a.error),a.score!==void 0&&(c.score=a.score),c}),o=Yl(t.map(a=>({index:a.index,score:a.score??null}))),s;for(let a of o){let l=t.find(c=>c.index===a);if(!(!l||!l.ok||!l.score)&&l.score.pass>0&&l.score.fail===0){s=a;break}}if(s===void 0)for(let a of o){let l=t.find(c=>c.index===a);if(l?.ok&&l.score){s=a;break}}let i={taskName:e.taskName,taskSlug:e.taskSlug,baseSha:e.baseRef,startedAt:n,completedAt:new Date().toISOString(),branches:r};return s!==void 0&&(i.winner=s),e.human_decision!==void 0&&(i.human_decision=e.human_decision),i}async function qQ(e){let{task:t,branches:n,labels:r,model:o,baseRef:s,cwd:i=process.cwd(),failFast:a,taskSlug:l,score:c=!0,scoreTimeoutMs:u=Nm,memoryWrite:d=!0,digest:p=!0,_createFarm:m=OD,_runSubagentDAG:g=$d,_getCommitCount:h=UQ,_getSourceRepoDirtyFiles:b=jQ,_scoreBranch:y=ND,_writeScore:S=BD,_writeFarmFact:w=HD,_sendFarmDigest:T=KD,_setFarmMemoryFactId:x=$D,_createTraceWriter:C=Qr}=e,R=new Date().toISOString();(!Number.isInteger(n)||n<1||n>16)&&(console.error(ke.red(`--branches must be between 1 and 16 (got ${n})`)),process.exit(1)),r!==void 0&&r.length!==n&&(console.error(ke.red(`--labels count (${r.length}) must equal --branches (${n})`)),process.exit(1));let k;try{k=await m({taskName:t,count:n,labels:r,cwd:i,baseRef:s,taskSlug:l})}catch(j){console.error(ke.red(`Farm creation failed: ${j instanceof Error?j.message:String(j)}`)),process.exit(1)}let $=k.baseRef,A=o??
|
|
2183
|
+
`)}`),this.name="FarmIsolationViolation",this.dirtyFiles=t}};function HQ(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function WQ(e){if(e===void 0)return ke.dim("\u2014");if(e===null)return ke.dim("skipped");let t=e.fail===0&&e.pass>0?ke.green("tests\u2713"):ke.red("tests\u2717"),n=e.lint_ok===!0?ke.green("lint\u2713"):e.lint_ok===!1?ke.red("lint\u2717"):ke.dim("lint?"),r=e.loc_delta>0?"+":"",o=ke.dim(`${r}${e.loc_delta} LoC`);return`${t} ${n} ${o}`}function KQ(e,t,n,r){let o="\u2500".repeat(45);console.log(ke.dim(o)),console.log(`farm: ${e}`),console.log(`slug: ${t}`),console.log("");let s=r.some(u=>u.score!=null),i=s?Yl(r.map(u=>({index:u.index,score:u.score??null}))).map(u=>r.find(d=>d.index===u)):r;for(let u=0;u<i.length;u++){let d=i[u],p=n.find(S=>S.index===d.index),m=d.ok?ke.green("\u2713"):ke.red("\u2717"),g=HQ(p.branch,40),h=d.ok?ke.dim(`(${d.commitCount} commit${d.commitCount===1?"":"s"})`):ke.red(`[error: ${d.error}]`),b=s?ke.cyan(`#${u+1} `):"",y=s?` ${WQ(d.score)}`:"";console.log(`${b}branch-${d.index} ${m} ${g} ${h}${y}`),console.log(ke.dim(` worktree: ${p.path}`))}console.log(ke.dim(o));let a=r.filter(u=>u.ok).length,l=r.length;console.log(`${a}/${l} branches completed.`);let c=r.some(u=>u.score!=null&&u.score.pass>0);s&&!c&&console.log(ke.yellow("\u26A0 no branch passed tests \u2014 ranking falls back to lint + LoC"))}function GQ(e,t,n){let r=t.map(a=>{let l=e.branches.find(u=>u.index===a.index),c={index:a.index,branch:l?.branch??`(unknown-${a.index})`,ok:a.ok,commitCount:a.commitCount};return l?.label!==void 0&&(c.label=l.label),a.error!==void 0&&(c.error=a.error),a.score!==void 0&&(c.score=a.score),c}),o=Yl(t.map(a=>({index:a.index,score:a.score??null}))),s;for(let a of o){let l=t.find(c=>c.index===a);if(!(!l||!l.ok||!l.score)&&l.score.pass>0&&l.score.fail===0){s=a;break}}if(s===void 0)for(let a of o){let l=t.find(c=>c.index===a);if(l?.ok&&l.score){s=a;break}}let i={taskName:e.taskName,taskSlug:e.taskSlug,baseSha:e.baseRef,startedAt:n,completedAt:new Date().toISOString(),branches:r};return s!==void 0&&(i.winner=s),e.human_decision!==void 0&&(i.human_decision=e.human_decision),i}async function qQ(e){let{task:t,branches:n,labels:r,model:o,baseRef:s,cwd:i=process.cwd(),failFast:a,taskSlug:l,score:c=!0,scoreTimeoutMs:u=Nm,memoryWrite:d=!0,digest:p=!0,_createFarm:m=OD,_runSubagentDAG:g=$d,_getCommitCount:h=UQ,_getSourceRepoDirtyFiles:b=jQ,_scoreBranch:y=ND,_writeScore:S=BD,_writeFarmFact:w=HD,_sendFarmDigest:T=KD,_setFarmMemoryFactId:x=$D,_createTraceWriter:C=Qr}=e,R=new Date().toISOString();(!Number.isInteger(n)||n<1||n>16)&&(console.error(ke.red(`--branches must be between 1 and 16 (got ${n})`)),process.exit(1)),r!==void 0&&r.length!==n&&(console.error(ke.red(`--labels count (${r.length}) must equal --branches (${n})`)),process.exit(1));let k;try{k=await m({taskName:t,count:n,labels:r,cwd:i,baseRef:s,taskSlug:l})}catch(j){console.error(ke.red(`Farm creation failed: ${j instanceof Error?j.message:String(j)}`)),process.exit(1)}let $=k.baseRef,A=o??vt(),P=di().prompt??"",F=k.branches.map(j=>({id:`branch-${j.index}`,agentType:`branch-${j.index}${j.label?` (${j.label})`:""}`,systemPrompt:P,promptBuilder:Y=>(console.log(`[branch-${j.index}] started`),[`Task: ${t}`,"",`You are working in a dedicated git worktree. Your working directory has been set to: ${j.path}`,`Your branch is: ${j.branch}`,"","Complete the task. All file operations are restricted to this worktree by the runtime."].join(`
|
|
2184
2184
|
`)),model:A,idPrefix:`farm-${k.taskSlug}-branch-${j.index}`,cwd:j.path,readRoots:[j.path],writeRoots:[j.path]})),D=C(),N=new AbortController,B=new se({parentAbortSignal:N.signal,...D!==null?{traceWriter:D.writer}:{},surface:"cli"}),H={sessionId:`farm-${k.taskSlug}`,abortSignal:N.signal,surface:"cli"},L;try{L=await g({manager:B,parentSession:H,nodes:F,edges:[],failFast:a})}catch(j){throw console.error(ke.red(`Farm dispatch failed: ${j instanceof Error?j.message:String(j)}`)),j}finally{N.abort()}let I=[];for(let j of k.branches){let Y=L.failed.find(W=>W.id===`branch-${j.index}`),oe=L.skipped.includes(`branch-${j.index}`);if(Y||oe){let W=Y?Y.error.message:"skipped";console.log(`[branch-${j.index}] \u2717 failed: ${W}`),I.push({index:j.index,ok:!1,commitCount:0,error:W});continue}let X=await h(j.path,$);if(X===0){let W="no commits made";console.log(`[branch-${j.index}] \u2717 failed: ${W}`),I.push({index:j.index,ok:!1,commitCount:0,error:W})}else console.log(`[branch-${j.index}] \u2713 done`),I.push({index:j.index,ok:!0,commitCount:X})}let U=await b(i);if(c)for(let j of I){if(!j.ok){j.score=null;continue}let Y=k.branches.find(X=>X.index===j.index);console.log(`[branch-${j.index}] scoring\u2026`);let oe=await y({branchPath:Y.path,baseSha:$,timeoutMs:u});j.score=oe;try{await S(k.farmDir,j.index,oe)}catch(X){console.error(ke.yellow(`[branch-${j.index}] score.json write failed: ${X instanceof Error?X.message:String(X)}`))}}if(KQ(t,k.taskSlug,k.branches,I),d||p){let j=GQ(k,I,R);if(d){let Y=w(j);if("skipped"in Y)console.error(ke.yellow(`[memory] write skipped: ${Y.reason}`));else{let{factId:oe}=Y;try{await x(k.taskSlug,oe)}catch(X){console.error(ke.yellow(`[memory] setFarmMemoryFactId failed: ${X.message}`))}}}if(p){let Y=await T(j);Y.sent?console.log(ke.dim(`[telegram] digest sent (${Y.chatCount} chat${Y.chatCount===1?"":"s"})`)):Y.reason&&Y.reason!=="telegram unconfigured"&&console.error(ke.yellow(`[telegram] digest failed: ${Y.reason}`))}}if(U.length>0){let j=new Xw(U);console.error(ke.red(`
|
|
2185
|
-
\u26A0 ISOLATION VIOLATION`)),console.error(ke.red(j.message)),process.exit(1)}let M=I.every(j=>j.ok);process.exit(M?0:1)}function qD(e){e.command("farm").description("Run a task across N speculative git worktree branches in parallel").argument("<task>","Task description to run on each branch").option("-n, --branches <number>","Number of branches to spawn (1-16)","3").option("--labels <labels>","Comma-separated branch labels (count must equal --branches)").option("-m, --model <model>","Model to use",
|
|
2185
|
+
\u26A0 ISOLATION VIOLATION`)),console.error(ke.red(j.message)),process.exit(1)}let M=I.every(j=>j.ok);process.exit(M?0:1)}function qD(e){e.command("farm").description("Run a task across N speculative git worktree branches in parallel").argument("<task>","Task description to run on each branch").option("-n, --branches <number>","Number of branches to spawn (1-16)","3").option("--labels <labels>","Comma-separated branch labels (count must equal --branches)").option("-m, --model <model>","Model to use",vt()).option("--base-ref <ref>","Base git ref (default: HEAD)").option("--cwd <path>","Source repo root (default: process.cwd())").option("--fail-fast","Abort remaining branches on first failure",!1).option("--task-slug <slug>","Deterministic task slug override (for tests)").option("--no-score","Skip the post-run scorer (tests + lint + LoC)").option("--score-timeout <ms>",`Per-branch test timeout in ms (default ${Nm})`).option("--no-memory","Skip writing the farm-run fact to cross-session memory").option("--no-digest","Skip pushing the Telegram digest on completion").action(async(t,n)=>{let r=parseInt(n.branches,10),o=n.labels?n.labels.split(",").map(i=>i.trim()).filter(Boolean):void 0,s=n.scoreTimeout?parseInt(n.scoreTimeout,10):void 0;s!==void 0&&(!Number.isFinite(s)||s<1)&&(console.error(ke.red(`--score-timeout must be a positive integer (got "${n.scoreTimeout}")`)),process.exit(1));try{await qQ({task:t,branches:r,labels:o,model:n.model,baseRef:n.baseRef,cwd:n.cwd,failFast:n.failFast,taskSlug:n.taskSlug,score:n.score,memoryWrite:n.memory,digest:n.digest,...s!==void 0?{scoreTimeoutMs:s}:{}})}catch(i){console.error(i),process.exitCode=1}})}q();import pn from"chalk";import{execFile as zQ}from"node:child_process";import{promisify as JQ}from"node:util";Mt();var Zw=JQ(zQ);async function zD(){try{return(await Zw("git",["rev-parse","--show-toplevel"])).stdout.trim()}catch{throw new Error("Not in a git repository.")}}function VQ(e){return["empty","stale-clean","orphaned-dir","orphaned-registration","dead-owner"].includes(e)?pn.red("yes"):e==="stale-dirty"?pn.yellow("warn"):pn.green("no")}var JD=["interactive","diagnose","all"];function YQ(e){if(JD.includes(e))return e;throw new Error(`Invalid --scope value: '${e}'. Allowed: ${JD.join(" | ")}.`)}function XQ(e){if(e<=0)return"-";let t=e/864e5;return t<1?`${Math.max(1,Math.round(e/36e5))}h`:`${Math.round(t)}d`}function VD(e){let t=e.command("worktree").description("Manage git worktrees created by afk");t.command("list").description("List all afk-managed worktrees and show prune candidates (dry-run only)").action(async()=>{let n;try{n=await zD()}catch(s){J(s)}let r;try{r=await Bn({execFile:Zw,repoRoot:n,dryRun:!0})}catch(s){J(new Error(`Sweep failed: ${s.message}`))}let o=["PATH".padEnd(45),"OWNER".padEnd(12),"AGE".padEnd(6),"STATUS".padEnd(22),"PRUNE?"].join(" | ");console.log(pn.bold(o)),console.log("-".repeat(o.length));for(let s of r.candidates){let i=[s.path.slice(-44).padEnd(45),s.owner.padEnd(12),XQ(s.ageMs).padEnd(6),s.verdict.padEnd(22),VQ(s.verdict)].join(" | ");console.log(i)}if(r.candidates.length===0&&console.log(pn.dim(" (no afk-managed worktrees found)")),r.warnings.length>0){console.log("");for(let s of r.warnings)console.log(pn.yellow(s))}}),t.command("prune").description("Remove stale, empty, and orphaned worktrees").option("--apply","Execute removals (default is dry-run)",!1).option("--max-age-days-clean <n>","Max age (days) for clean worktrees before removal").option("--max-age-days-dirty <n>","Max age (days) for dirty worktrees before warning").option("--scope <scope>","Scope: interactive | diagnose | all","all").action(async n=>{let r;try{r=await zD()}catch(S){J(S)}let s=At().daemon?.worktreePrune,i=parseInt(v.AFK_WORKTREE_MAX_AGE_CLEAN??"",10),a=parseInt(v.AFK_WORKTREE_MAX_AGE_DIRTY??"",10),l=n.maxAgeDaysClean!==void 0?parseInt(n.maxAgeDaysClean,10):s?.maxAgeDaysClean??(Number.isNaN(i)?14:i),c=n.maxAgeDaysDirty!==void 0?parseInt(n.maxAgeDaysDirty,10):s?.maxAgeDaysDirty??(Number.isNaN(a)?30:a),u;try{u=YQ(n.scope)}catch(S){J(S)}let d={execFile:Zw,repoRoot:r,dryRun:!n.apply,maxAgeDaysClean:l,maxAgeDaysDirty:c,scope:u},p;try{p=await Bn(d)}catch(S){J(new Error(`Sweep failed: ${S.message}`))}p.dryRun&&console.log(pn.yellow("\u{1F50D} Dry-run mode \u2014 no changes made."));let m={};for(let S of p.candidates)m[S.verdict]=(m[S.verdict]??0)+1;let g=p.warnings.filter(S=>S.startsWith("[WARN]")).length,h=p.warnings.filter(S=>S.startsWith("[ERROR]")).length,b=Object.entries(m).sort(([S],[w])=>S.localeCompare(w)).map(([S,w])=>`${S}=${w}`);console.log(`Removed: ${p.removed.length}, Warned: ${g}, Errors: ${h}`+(b.length>0?` [${b.join(" ")}]`:""));for(let S of p.candidates){let T=p.removed.includes(S.path)?pn.red("\u2717"):pn.green("\u2713");console.log(` ${T} [${S.verdict.padEnd(22)}] ${S.path}`)}if(p.warnings.length>0){console.log("");for(let S of p.warnings)S.startsWith("[ERROR]")?console.error(pn.red(S)):console.log(pn.yellow(S))}p.warnings.some(S=>S.startsWith("[ERROR]"))&&process.exit(1)})}import{spawn as ZQ}from"child_process";var QQ=/^\d+\.\d+\.\d+(-[\da-z.]+)?$/i;function eee(e,t){let n=e.split(".").map(Number),r=t.split(".").map(Number),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){let i=n[s]??0,a=r[s]??0;if(a>i)return!0;if(a<i)return!1}return!1}function YD(e){e.command("update").alias("upgrade").description("Update agent-afk to the latest published version").option("--check","Only check whether an update is available; do not install").option("--pin <version>","Install a specific version instead of latest (must be valid semver)").action(async t=>{let n=kr();if(t.check===!0){process.stderr.write(`Checking for updates\u2026
|
|
2186
2186
|
`);let i=await Iw();if(i===void 0){console.log(f.warning("Could not reach the npm registry to check for updates.")),console.log(f.dim(` Current: ${n}`)),process.exitCode=1;return}if(eee(n,i)){console.log(`${f.bold("Update available:")} ${f.dim(n)} \u2192 ${f.bold(i)}`),console.log(f.dim(" Run `afk update` to install."));return}console.log(`agent-afk ${f.bold(n)} is up to date.`);return}if(t.pin!==void 0&&!QQ.test(t.pin)){console.error(f.warning(`Invalid version: ${JSON.stringify(t.pin)}. Must be valid semver (e.g. 1.2.3 or 1.2.3-beta.1).`)),process.exitCode=1;return}let r=t.pin;if(r===void 0){if(process.stderr.write(`Fetching latest version\u2026
|
|
2187
2187
|
`),r=await Iw(),r===void 0){console.error(f.warning("Could not reach the npm registry. Aborting.")),process.exitCode=1;return}if(r===n){console.log(`agent-afk ${f.bold(n)} is up to date.`);return}}console.log(`Updating agent-afk: ${f.dim(n)} \u2192 ${f.bold(r)}`),console.log(f.dim(` npm install -g agent-afk@${r}`));let{code:o,signal:s}=await tee(r);o===0?(_w(r),console.log(f.success(`\u2713 agent-afk@${r} installed.`))):s!==null?(console.error(f.warning(`npm install was killed by signal ${s}.`)),process.exitCode=1):(console.error(f.warning(`npm install exited with code ${o??1}.`)),process.exitCode=o??1)})}function tee(e){return new Promise(t=>{let n=ZQ("npm",["install","-g",`agent-afk@${e}`],{stdio:"inherit"});n.on("error",()=>t({code:1,signal:null})),n.on("exit",(r,o)=>t({code:r,signal:o}))})}import{existsSync as nee,readFileSync as ree}from"node:fs";vu();G();Yg();function XD(e){let t=e.command("schedule").description("Manage scheduled daemon tasks");t.command("add").description("Add a new scheduled task").requiredOption("--name <name>","Human-readable label").requiredOption("--command <cmd>","Command to run").requiredOption("--cron <expr>","Cron expression (5-field)").option("--trigger <mode>","cron | sessionstart | both","cron").option("--notify <when>","failure | always | never","failure").option("--disabled","Add in disabled state",!1).action(async n=>{try{let r=wu({name:n.name,command:n.command,cron:n.cron,trigger:n.trigger,notifyOn:n.notify,enabled:!n.disabled});(r.enabled?await on("POST","/tasks",{taskId:r.id,command:r.command,cron:r.cron,trigger:r.trigger,notifyOn:r.notifyOn}):await on("DELETE",`/tasks/${r.id}`)).synced||console.error(`\u26A0\uFE0F ${Dr}`),console.log(`\u2705 Added: ${r.id} \u2014 ${r.name}`)}catch(r){J(r)}}),t.command("list").description("List all scheduled tasks").action(()=>{try{let n=qt();if(n.length===0){console.log("No scheduled tasks.");return}let r="ID | NAME | CRON | ENABLED",o="-".repeat(r.length);console.log(r),console.log(o);for(let s of n)console.log([s.id.padEnd(20),s.name.padEnd(30),s.cron.padEnd(15),String(s.enabled)].join(" | "))}catch(n){J(n)}}),t.command("remove <id>").description("Permanently remove a scheduled task").action(async n=>{try{Su(n)||(console.error(`Task not found: ${n}`),process.exit(1)),(await on("DELETE",`/tasks/${n}`)).synced||console.error(`\u26A0\uFE0F ${Dr}`),console.log(`\u2705 Removed: ${n}`)}catch(r){J(r)}}),t.command("enable <id>").description("Enable a scheduled task").action(async n=>{try{let r=Ua(n);r||(console.error(`Task not found: ${n}`),process.exit(1));let o=qt();Oo(o.map(i=>i.id===n?{...i,enabled:!0,updatedAt:new Date().toISOString()}:i)),(await on("POST","/tasks",{taskId:r.id,command:r.command,cron:r.cron,trigger:r.trigger,notifyOn:r.notifyOn})).synced||console.error(`\u26A0\uFE0F ${Dr}`),console.log(`\u2705 Enabled: ${n}`)}catch(r){J(r)}}),t.command("disable <id>").description("Disable a scheduled task").action(async n=>{try{Ua(n)||(console.error(`Task not found: ${n}`),process.exit(1));let o=qt();Oo(o.map(i=>i.id===n?{...i,enabled:!1,updatedAt:new Date().toISOString()}:i)),(await on("DELETE",`/tasks/${n}`)).synced||console.error(`\u26A0\uFE0F ${Dr}`),console.log(`\u2705 Disabled: ${n}`)}catch(r){J(r)}}),t.command("logs <id>").description("Show recent execution history for a task").option("-n, --limit <n>","Number of records to show","10").action((n,r)=>{try{let o=Math.min(Math.max(1,parseInt(r.limit,10)||10),50),s=Tr();if(!nee(s)){console.log(`No telemetry found for task: ${n}`);return}let i=ree(s),c=(i.length>1048576?i.subarray(i.length-1048576):i).toString("utf-8").split(`
|
|
2188
2188
|
`),u=[];for(let p=c.length-1;p>=0;p-=1){let m=c[p];if(m)try{let g=JSON.parse(m);if(g.taskId!==n)continue;if(u.push(g),u.length>=o)break}catch{continue}}let d=u.reverse();if(d.length===0){console.log(`No history found for task: ${n}`);return}console.log(JSON.stringify(d,null,2))}catch(o){J(o)}})}td();function ZD(e){return new Date(e).toISOString().replace("T"," ").slice(0,19)}function na(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}var QD=9,Bm=50,eL=22;function oee(e){let t=na(e.jobId,eL),n=na(e.status,QD),r=e.label.length>Bm?`${e.label.slice(0,Bm-1)}\u2026`:na(e.label,Bm),o=ZD(e.startedAt),s=e.endedAt!==void 0?ZD(e.endedAt):"\u2014";return`${t} ${n} ${r} ${o} ${s}`}function see(e){return e.type==="done"||e.type==="error"}function tL(e){let t=e.command("bg").description(`Inspect persisted background subagent job logs.
|
|
@@ -2207,10 +2207,10 @@ or "latest" (the default) \u2014 the most recently written trace.`).option("--al
|
|
|
2207
2207
|
`)?l:l+`
|
|
2208
2208
|
`);return}let s=await nL(o),i;if(r.limit!==void 0){let a=parseInt(r.limit,10);!Number.isNaN(a)&&a>=0&&(i=a)}process.stdout.write(gee(s.sessionId,s.tracePath,s,{showAll:r.all,...i!==void 0?{limit:i}:{}}))}catch(o){J(o)}}),t.command("list").description("List sessions that have a trace, most recent first").option("-n, --max <number>","Maximum sessions to show","20").action(async n=>{try{let r=Math.min(200,Math.max(1,parseInt(n.max,10)||20)),o=await oL();if(o.length===0){process.stdout.write(`No traces found under ${tS()}
|
|
2209
2209
|
`);return}for(let s of o.slice(0,r)){let i=new Date(s.mtimeMs).toISOString().replace("T"," ").slice(0,19);process.stdout.write(`${i} ${s.sessionId}
|
|
2210
|
-
`)}}catch(r){J(r)}})}import
|
|
2210
|
+
`)}}catch(r){J(r)}})}import gt from"chalk";import{execFileSync as Oee}from"child_process";import{existsSync as yL}from"fs";G();import{homedir as iL}from"os";import{join as nS}from"path";var oa=["telegram","daemon"];function ft(e){return`com.afk.${e}`}function rS(e=iL()){return nS(e,"Library","LaunchAgents")}function po(e,t=iL()){return nS(rS(t),`${ft(e)}.plist`)}function sa(e){return nS(ks(),`service-${e}.log`)}function Zl(){return`gui/${process.getuid?.()??501}`}var ps=8e3;import{execFileSync as hee}from"child_process";import{existsSync as aL,realpathSync as lL}from"fs";import{homedir as yee}from"os";import{delimiter as bee,dirname as wee,resolve as See}from"path";function mo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function cL(e){let t=[];t.push('<?xml version="1.0" encoding="UTF-8"?>'),t.push('<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">'),t.push('<plist version="1.0">'),t.push("<dict>"),t.push(" <key>Label</key>"),t.push(` <string>${mo(e.label)}</string>`),t.push(" <key>ProgramArguments</key>"),t.push(" <array>");for(let n of e.programArguments)t.push(` <string>${mo(n)}</string>`);if(t.push(" </array>"),t.push(" <key>WorkingDirectory</key>"),t.push(` <string>${mo(e.workingDirectory)}</string>`),t.push(" <key>StandardOutPath</key>"),t.push(` <string>${mo(e.standardOutPath)}</string>`),t.push(" <key>StandardErrorPath</key>"),t.push(` <string>${mo(e.standardErrorPath)}</string>`),t.push(" <key>RunAtLoad</key>"),t.push(" <true/>"),t.push(" <key>KeepAlive</key>"),t.push(" <true/>"),t.push(" <key>ProcessType</key>"),t.push(" <string>Interactive</string>"),e.watchPaths&&e.watchPaths.length>0){t.push(" <key>WatchPaths</key>"),t.push(" <array>");for(let n of e.watchPaths)t.push(` <string>${mo(n)}</string>`);t.push(" </array>")}if(e.environmentVariables&&Object.keys(e.environmentVariables).length>0){t.push(" <key>EnvironmentVariables</key>"),t.push(" <dict>");let n=Object.keys(e.environmentVariables).sort();for(let r of n){let o=e.environmentVariables[r]??"";t.push(` <key>${mo(r)}</key>`),t.push(` <string>${mo(o)}</string>`)}t.push(" </dict>")}return t.push("</dict>"),t.push("</plist>"),t.join(`
|
|
2211
2211
|
`)+`
|
|
2212
2212
|
`}var vee=["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin","/usr/sbin","/sbin"];function uL(e=process.execPath){let t=wee(e),n=new Set,r=[];for(let o of[t,...vee])o.length>0&&!n.has(o)&&(n.add(o),r.push(o));return r.join(bee)}function kee(e=["/usr/local/bin/afk","/opt/homebrew/bin/afk"],t=aL,n=Eee,r=lL){let o=process.argv[1];if(o)try{let i=r(o);if(dL.some(a=>i.startsWith(a))&&t(i))return i}catch{}let s=n();if(s&&t(s))return s;for(let i of e)if(t(i))return i;throw new Error(`Could not locate the 'afk' binary. Searched: ${e.join(", ")}. Install it globally first (e.g. 'pnpm install -g agent-afk' or via Homebrew).`)}var dL=["/usr/local/bin/","/opt/homebrew/bin/","/usr/bin/","/opt/local/bin/"];function Eee(){try{let e=hee("which",["afk"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(!e)return;let t;try{t=lL(e)}catch{return}return dL.some(n=>t.startsWith(n))?t:void 0}catch{return}}function oS(e,t=aL){if(e==="telegram"){let r=Gw();if(r.endsWith(".ts"))throw new Error(`Refusing to install telegram service pointing at TypeScript source (${r}). Run 'pnpm build' first so the compiled entrypoint exists, or install agent-afk globally (e.g. 'pnpm install -g agent-afk').`);if(!t(r))throw new Error(`Telegram entrypoint does not exist on disk: ${r}. Run 'pnpm build' to compile it, or install agent-afk globally.`);return[process.execPath,r]}return[kee(),"daemon"]}function pL(e,t){let n=oS(e,t),r=e==="telegram"?n[1]:void 0;if(!r)return;let o=See(r),s=yee();if(o.startsWith(s)&&!(o.includes("/node_modules/")||o.includes("/homebrew/")))return[o]}import{execFileSync as Tee}from"child_process";import{existsSync as xee}from"fs";function Ree(e,t){let n=e.trim();if(n.startsWith("[")||n.startsWith("{")){try{let r=JSON.parse(n),o=Array.isArray(r)?r:[r];for(let s of o){if(typeof s!="object"||s===null)continue;let i=s;if(i.Label!==t)continue;let a={};return typeof i.PID=="number"&&Number.isFinite(i.PID)&&(a.pid=i.PID),typeof i.LastExitStatus=="number"&&Number.isFinite(i.LastExitStatus)&&(a.lastExitStatus=i.LastExitStatus),a}}catch{}return}for(let r of n.split(`
|
|
2213
|
-
`)){let o=r.split(" "),s=o.length>=3?o:r.trim().split(/\s+/);if(s.length<3||s[2]?.trim()!==t)continue;let i=s[0]?.trim()??"-",a=s[1]?.trim()??"0",l={};if(i!=="-"&&i!==""){let u=Number.parseInt(i,10);Number.isFinite(u)&&(l.pid=u)}let c=Number.parseInt(a,10);return Number.isFinite(c)&&(l.lastExitStatus=c),l}}function sS(e){let t=po(e),n={name:e,label:
|
|
2213
|
+
`)){let o=r.split(" "),s=o.length>=3?o:r.trim().split(/\s+/);if(s.length<3||s[2]?.trim()!==t)continue;let i=s[0]?.trim()??"-",a=s[1]?.trim()??"0",l={};if(i!=="-"&&i!==""){let u=Number.parseInt(i,10);Number.isFinite(u)&&(l.pid=u)}let c=Number.parseInt(a,10);return Number.isFinite(c)&&(l.lastExitStatus=c),l}}function sS(e){let t=po(e),n={name:e,label:ft(e),installed:xee(t),plistPath:t,logFile:sa(e)};if(!n.installed)return n;try{let r=Tee("launchctl",["list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:ps}),o=Ree(r,n.label);o&&(o.pid!==void 0&&(n.pid=o.pid),o.lastExitStatus!==void 0&&(n.lastExitStatus=o.lastExitStatus))}catch{}return n}import{execFileSync as jm}from"child_process";import{existsSync as fL,mkdirSync as mL,readFileSync as _We,renameSync as Cee,rmSync as Aee,unlinkSync as _ee,writeFileSync as Iee}from"fs";import{homedir as Pee}from"os";import{dirname as Mee}from"path";function gL(e,t={}){let n=po(e);if(fL(n))return{kind:"already-installed",plistPath:n,label:ft(e)};let r;try{r=oS(e,t._entrypointExistsCheck)}catch(u){return{kind:"failed",reason:u.message}}let o=t.noWatch?void 0:pL(e,t._entrypointExistsCheck),s=sa(e);mL(rS(),{recursive:!0}),mL(Mee(s),{recursive:!0});let i={PATH:uL(),...t.environment??{}},a={label:ft(e),programArguments:r,workingDirectory:Pee(),standardOutPath:s,standardErrorPath:s,...o?{watchPaths:o}:{},environmentVariables:i},l=cL(a),c=`${n}.tmp`;try{Iee(c,l,{encoding:"utf-8",flag:"wx",mode:384})}catch(u){return{kind:"failed",reason:`Failed to write plist (tmp ${c}): ${u.message}`}}try{Cee(c,n)}catch(u){try{_ee(c)}catch{}return{kind:"failed",reason:`Failed to install plist (rename ${c} \u2192 ${n}): ${u.message}`}}if(t.skipBootstrap)return{kind:"installed",plistPath:n,label:ft(e),watchPathsActive:!!o};try{jm("launchctl",["bootstrap",Zl(),n],{stdio:["ignore","pipe","pipe"],timeout:ps})}catch(u){let d=u.message;if(u.code==="EALREADY"||/\b37\b/.test(d))return{kind:"failed",reason:`Service already loaded \u2014 run 'afk service restart ${e}' to reload with the new plist.`};if(/already bootstrapped|already loaded/i.test(d)){let p="";try{jm("launchctl",["bootout",`${Zl()}/${ft(e)}`],{stdio:["ignore","pipe","pipe"],timeout:ps})}catch(m){p=m.message}try{jm("launchctl",["bootstrap",Zl(),n],{stdio:["ignore","pipe","pipe"],timeout:ps})}catch(m){let g=m.message;return{kind:"failed",reason:`Bootstrap failed: ${p?`${g} (prior bootout: ${p})`:g}`}}}else return{kind:"failed",reason:`Bootstrap failed: ${d}`}}return{kind:"installed",plistPath:n,label:ft(e),watchPathsActive:!!o}}function hL(e,t={}){let n=po(e);if(!fL(n))return{kind:"not-installed",plistPath:n};if(!t.skipBootout)try{jm("launchctl",["bootout",`${Zl()}/${ft(e)}`],{stdio:"ignore",timeout:ps})}catch{}try{Aee(n,{force:!0})}catch(r){return{kind:"failed",reason:`Failed to remove plist: ${r.message}`}}return{kind:"uninstalled",plistPath:n}}function Ql(){if(process.platform!=="darwin")throw new Error(`'afk service' uses macOS launchd and is only supported on darwin. Detected: ${process.platform}.`)}function Hm(e){let t=e.toLowerCase();if(oa.includes(t))return t;throw new Error(`Unknown service '${e}'. Supported: ${oa.join(", ")}.`)}function wL(e){let t=e.command("service").description("Manage AFK background services via macOS launchd (always-on, auto-restart)");t.command("install <name>").description(`Install <${oa.join("|")}> as a LaunchAgent that starts on login and relaunches on crash`).option("--no-watch","Disable WatchPaths (no auto-restart on rebuild)").option("--dry-run","Write the plist but do not call launchctl",!1).action((n,r)=>{try{Ql();let o=Hm(n),s=gL(o,{noWatch:r.watch===!1,skipBootstrap:!!r.dryRun});if(s.kind==="already-installed"&&(console.log(gt.yellow(`\u26A0 ${s.label} already installed at ${s.plistPath}`)),console.log(f.meta(` Run 'afk service uninstall ${o}' first to reinstall.`)),process.exit(1)),s.kind==="failed"&&(console.error(gt.red(`\u2717 Install failed: ${s.reason}`)),process.exit(1)),console.log(gt.green(`\u2713 Installed ${s.label}`)),console.log(f.meta(` Plist: ${s.plistPath}`)),console.log(f.meta(` Log: ${sa(o)}`)),s.watchPathsActive?console.log(f.meta(" WatchPaths: active \u2014 service auto-restarts on rebuild.")):console.log(f.meta(" WatchPaths: off \u2014 manual 'afk service restart' needed after updates.")),r.dryRun){let i=process.getuid?.()??501;console.log(f.info(" (dry-run) launchctl bootstrap was skipped; service is NOT yet running.")),console.log(f.meta(` Load manually: launchctl bootstrap gui/${i} ${s.plistPath}`))}else console.log(f.meta(` Status: afk service status ${o}`))}catch(o){J(o)}}),t.command("uninstall <name>").description("Stop the service and remove its LaunchAgent plist").action(n=>{try{Ql();let r=Hm(n),o=hL(r);if(o.kind==="not-installed"){console.log(gt.yellow(`\u26A0 ${ft(r)} is not installed (no plist at ${o.plistPath})`));return}o.kind==="failed"&&(console.error(gt.red(`\u2717 Uninstall failed: ${o.reason}`)),process.exit(1)),console.log(gt.green(`\u2713 Uninstalled ${ft(r)}`)),console.log(f.meta(` Removed: ${o.plistPath}`))}catch(r){J(r)}}),t.command("status [name]").description("Show running PID, last exit status, and log file for one or all services").action(n=>{try{if(Ql(),n){let r=sS(Hm(n));bL(r);return}for(let r of oa)bL(sS(r)),console.log("")}catch(r){J(r)}}),t.command("list").description("List recognised service names and whether each is installed").action(()=>{try{Ql(),console.log(gt.bold("AFK services:"));for(let n of oa){let r=po(n),o=yL(r),s=o?gt.green("\u25CF"):gt.dim("\u25CB"),i=o?f.meta("installed"):f.meta("not installed");console.log(` ${s} ${n.padEnd(10)} ${i} ${f.meta(r)}`)}}catch(n){J(n)}}),t.command("restart <name>").description("Restart the service (launchctl kickstart -k)").action(n=>{try{Ql();let r=Hm(n),o=po(r);if(yL(o)||(console.error(gt.red(`\u2717 ${ft(r)} is not installed. Run 'afk service install ${r}' first.`)),process.exit(1)),typeof process.getuid!="function")throw new Error("process.getuid is unavailable \u2014 afk service restart requires a POSIX system.");let s=process.getuid();try{Oee("launchctl",["kickstart","-k",`gui/${s}/${ft(r)}`],{stdio:["ignore","pipe","pipe"],timeout:8e3}),console.log(gt.green(`\u2713 Restarted ${ft(r)}`))}catch(i){console.error(gt.red(`\u2717 Restart failed: ${i.message}`)),process.exit(1)}}catch(r){J(r)}})}function bL(e){if(console.log(gt.bold(`${e.label}`)),!e.installed){console.log(` ${gt.dim("\u25CB")} Not installed`),console.log(f.meta(` Plist: ${e.plistPath}`)),console.log(f.meta(` Install: afk service install ${e.name}`));return}e.pid!==void 0?console.log(` ${gt.green("\u25CF")} Running (PID ${e.pid})`):(console.log(` ${gt.yellow("\u25CF")} Installed but not running`),e.lastExitStatus!==void 0&&e.lastExitStatus!==0&&console.log(f.meta(` Last exit status: ${e.lastExitStatus}`))),console.log(f.meta(` Plist: ${e.plistPath}`)),console.log(f.meta(` Log: ${e.logFile}`))}import ms from"chalk";import{execFileSync as $ee}from"child_process";import{existsSync as EL,mkdirSync as Dee,readFileSync as Lee,renameSync as Fee,writeFileSync as Nee}from"fs";import{dirname as SL,join as Bee}from"path";import{randomBytes as Uee}from"crypto";var fo="chrome-devtools",iS=["stable","beta","canary","dev"];function jee(e="stable"){let t=["chrome-devtools-mcp@latest","--autoConnect"];return e!=="stable"&&t.push("--channel",e),{command:"npx",args:t}}function vL(e){if(!EL(e))return{mcpServers:{}};let t;try{t=Lee(e,"utf-8")}catch(o){throw new Error(`Failed to read MCP config at ${e}: ${o.message}`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`MCP config at ${e} is not valid JSON. Fix or remove it, then retry.`)}if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`MCP config at ${e} must be a JSON object.`);let r=n;if(Array.isArray(r.mcpServers))throw new Error(`MCP config at ${e} has an invalid "mcpServers" (must be a JSON object, not an array).`);return(r.mcpServers===void 0||typeof r.mcpServers!="object"||r.mcpServers===null)&&(r.mcpServers={}),r}function kL(e,t){Dee(SL(e),{recursive:!0});let n=Bee(SL(e),`.mcp.json.${process.pid}.${Uee(4).toString("hex")}.tmp`);Nee(n,`${JSON.stringify(t,null,2)}
|
|
2214
2214
|
`,"utf-8"),Fee(n,e)}function Hee(){let e=process.platform==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary"]:["google-chrome","google-chrome-stable","chromium","chromium-browser"];for(let t of e)try{let r=$ee(t,["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).match(/(\d+)\.\d+\.\d+/);if(r!==null&&r[1]!==void 0)return parseInt(r[1],10)}catch{}return null}function Wee(){let e=Hee();console.log(""),console.log(ms.bold("Drive your real Chrome \u2014 one-time setup:")),e===null?console.log(f.meta(" \u2022 Chrome not detected. autoConnect requires Chrome \u2265 144.")):e<144?console.log(ms.yellow(` \u2022 Detected Chrome ${e} \u2014 autoConnect requires \u2265 144. Please update Chrome.`)):console.log(f.meta(` \u2022 Detected Chrome ${e} \u2713 (autoConnect needs \u2265 144)`)),console.log(f.meta(" 1. In Chrome, open chrome://inspect/#remote-debugging and enable it (one time).")),console.log(f.meta(' 2. The first time the agent drives Chrome, click "Allow" on the prompt.')),console.log(f.meta(' 3. Chrome shows a "being controlled by automated test software" banner while active.')),console.log(""),console.log(f.meta("The agent gains mcp__chrome-devtools__* tools (navigate, click, fill, take_snapshot, \u2026)")),console.log(f.meta("driving your REAL, logged-in profile. Run `/mcp` in the REPL to confirm it connected.")),console.log(f.meta("Undo anytime with `afk browser disconnect`."))}function TL(e){let t=e.command("browser").description("Connect the agent to your real Chrome browser (via Chrome DevTools MCP)");t.command("connect").description("Wire chrome-devtools-mcp (--autoConnect) so the agent can drive your real, logged-in Chrome").option("--channel <channel>",`Chrome channel autoConnect targets (${iS.join("|")})`,"stable").action(n=>{try{let r=(n.channel??"stable").toLowerCase();if(!iS.includes(r))throw new Error(`--channel must be one of ${iS.join(", ")} (got "${n.channel}")`);let o=Uo(),s=vL(o);s.mcpServers===void 0&&(s.mcpServers={});let i=jee(r),a=s.mcpServers[fo];if(a!==void 0&&JSON.stringify(a)===JSON.stringify(i))console.log(ms.green(`\u2713 "${fo}" already configured`)),console.log(f.meta(` Config: ${o}`));else{s.mcpServers[fo]=i,kL(o,s);let l=a===void 0?"Added":"Updated";console.log(ms.green(`\u2713 ${l} "${fo}" MCP server`)),console.log(f.meta(` Config: ${o}`)),console.log(f.meta(` Runs: npx ${i.args?.join(" ")??""}`))}Wee()}catch(r){J(r)}}),t.command("disconnect").description("Remove the chrome-devtools server from your MCP config").action(()=>{try{let n=Uo();if(!EL(n)){console.log(ms.yellow(`\u26A0 No MCP config at ${n} \u2014 nothing to remove.`));return}let r=vL(n);if(r.mcpServers===void 0||r.mcpServers[fo]===void 0){console.log(ms.yellow(`\u26A0 "${fo}" is not configured \u2014 nothing to remove.`));return}delete r.mcpServers[fo],kL(n,r),console.log(ms.green(`\u2713 Removed "${fo}" from ${n}`))}catch(n){J(n)}})}import{readFileSync as Kee,readdirSync as Gee,statSync as qee}from"fs";import{join as uS}from"path";G();import{join as Ze}from"path";function Wm(){return Ze(gn(),"improve")}function go(){return Ze(Wm(),"failure-cards")}function xL(){return Ze(go(),".index.jsonl")}function ec(e){return Ze(go(),`${e}.json`)}function Km(e){return Ze(go(),`${e}.md`)}function RL(){return Ze(Te(),"witness")}function fs(){return Ze(Wm(),"proposals")}function CL(){return Ze(fs(),".index.jsonl")}function aS(e){return Ze(fs(),`${e}.json`)}function AL(e){return Ze(fs(),`${e}.md`)}function ho(){return Ze(Wm(),"eval-cases")}function _L(){return Ze(ho(),".index.jsonl")}function lS(e){return Ze(ho(),`${e}.json`)}function cS(e){return Ze(ho(),`${e}.fixture.jsonl`)}function IL(e){return Ze(ho(),`${e}.md`)}function ia(){return Ze(Wm(),"eval-runs")}function PL(){return Ze(ia(),".index.jsonl")}function ML(e){return Ze(ia(),`${e}.json`)}function OL(e){return Ze(ia(),`${e}.md`)}q();function $L(e){let t=e.trim(),n=/^(\d+)\s*([smhd])$/i.exec(t);if(!n)return;let r=Number.parseInt(n[1]??"0",10),o=(n[2]??"").toLowerCase();if(!(!Number.isFinite(r)||r<=0))switch(o){case"s":return r*1e3;case"m":return r*60*1e3;case"h":return r*60*60*1e3;case"d":return r*24*60*60*1e3;default:return}}function DL(e={}){let t=e.witnessRoot??RL(),n=e.afkHome??v.AFK_HOME??zee(),r=e.sinceMs,o={sessionsScanned:0,sessionsSkippedOld:0,sessionsSkippedEmpty:0,invalidLineCount:0,sessions:[]},s;try{s=Gee(t)}catch{return o}for(let i of s){if(i.startsWith("."))continue;let a=uS(t,i),l;try{l=qee(a)}catch{continue}if(!l.isDirectory())continue;if(r!==void 0&&l.mtimeMs<r){o.sessionsSkippedOld+=1;continue}let c=uS(a,"trace.jsonl"),u;try{u=Kee(c,"utf-8")}catch{o.sessionsSkippedEmpty+=1;continue}let d=Jee(c,n),p=aa({sessionId:i,tracePath:c,relativeTracePath:d,content:u,sessionMtimeMs:l.mtimeMs});o.sessions.push(p),o.sessionsScanned+=1,o.invalidLineCount+=p.invalidLineCount}return o}function aa(e){let{sessionId:t,tracePath:n,relativeTracePath:r,content:o,sessionMtimeMs:s}=e,i=[],a=0,l=o.split(`
|
|
2215
2215
|
`);for(let c=0;c<l.length;c+=1){let u=l[c]??"";if(u.trim()==="")continue;let d;try{d=JSON.parse(u)}catch{a+=1;continue}let p=I_.safeParse(d);if(!p.success){a+=1;continue}i.push({sessionId:t,tracePath:n,relativeTracePath:r,lineNumber:c+1,rawLine:u,event:p.data})}return{sessionId:t,tracePath:n,relativeTracePath:r,sessionMtimeMs:s,events:i,invalidLineCount:a}}function zee(){let e=v.AFK_HOME;return e&&e.length>0?e:uS(v.HOME??"",".afk")}function Jee(e,t){if(!t)return e;if(e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")&&(n=n.slice(1)),n}return e}import{createHash as Vee}from"crypto";var Er=4,Yee=8,Xee="v1-bytes-tuple";function Gm(e,t={}){let n=t.minRepeats??Er;if(n<2)throw new Error(`minRepeats must be >= 2 (got ${n})`);let r=[];for(let o of e){let s=Zee(o,n);r.push(...s)}return r}function Zee(e,t){let n=Qee(e.events),r=ete(n),o=[];for(let[s,i]of r.entries()){let a=tte(i,t);for(let l of a)o.push(rte(e,l,s))}return o}function Qee(e){let t=new Map,n=[];for(let r of e){let o=r.event;if(o.kind!=="tool_call")continue;if(o.payload.phase==="started"){t.set(o.payload.toolUseId,{seq:o.seq,name:o.payload.name,inputBytes:o.payload.inputBytes,subagentId:o.payload.subagentId});continue}let s=t.get(o.payload.toolUseId);if(!s)continue;t.delete(o.payload.toolUseId);let i=nte({name:o.payload.name,inputBytes:s.inputBytes,resultBytes:o.payload.resultBytes,isError:o.payload.isError,subagentId:s.subagentId});n.push({toolUseId:o.payload.toolUseId,startedSeq:s.seq,completedSeq:o.seq,completedLineNumber:r.lineNumber,name:o.payload.name,inputBytes:s.inputBytes,resultBytes:o.payload.resultBytes,isError:o.payload.isError,subagentId:s.subagentId,rawLine:r.rawLine,fingerprint:i})}return n}function ete(e){let t=new Map;for(let n of e){let r=n.subagentId??"root",o=t.get(r);o?o.push(n):t.set(r,[n])}return t}function tte(e,t){let n=[],r=0;for(;r<e.length;){let o=e[r];if(!o){r+=1;continue}let s=r+1;for(;s<e.length;){let a=e[s];if(!a||a.fingerprint!==o.fingerprint)break;s+=1}s-r>=t&&n.push(e.slice(r,s)),r=s>r?s:r+1}return n}function nte(e){let t=[e.name,String(e.inputBytes),String(e.resultBytes),e.isError?"1":"0",e.subagentId??""].join("|");return Vee("sha256").update(t).digest("hex")}function rte(e,t,n){let r=t[0];if(!r)throw new Error("repeated-tool-use: empty run");let o=lte(r.name,r.fingerprint),s=new Date().toISOString(),i=t.slice(0,Yee),a=[{sessionId:e.sessionId,tracePath:e.relativeTracePath,eventIndices:i.map(l=>l.completedSeq),excerpt:ote(i),annotation:ste(t,n)}];return{slug:o,title:ite(r.name,t.length),pattern:"repeated-tool-use",severity:ate(t.length),observedAt:s,evidence:a,detail:{detector:"repeated-tool-use@v1",fingerprintAlgorithm:Xee,fingerprint:r.fingerprint,toolName:r.name,runLength:t.length,agentContext:n,inputBytes:r.inputBytes,resultBytes:r.resultBytes,isError:r.isError,toolUseIds:t.map(l=>l.toolUseId),completedSeqs:t.map(l=>l.completedSeq)}}}function ote(e){let t=e.map(n=>n.rawLine).join(`
|
|
2216
2216
|
`);return t.length<=2e3?t:t.slice(0,1997)+"..."}function ste(e,t){let n=e[0],r=e[e.length-1];return!n||!r?"":[`${e.length}\xD7 consecutive '${n.name}' calls in ${t} context`,`(seq ${n.completedSeq}\u2026${r.completedSeq},`,`inputBytes=${n.inputBytes}, resultBytes=${n.resultBytes},`,`isError=${n.isError})`].join(" ")}function ite(e,t){return`'${e}' tool repeated ${t}\xD7 with identical fingerprint`}function ate(e){return e>=10?"high":e>=4?"medium":"low"}function lte(e,t){let n=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),r=t.slice(0,12);return`repeated-tool-${n.length>0?n:"tool"}-${r}`}var cte=new Set(["budget_exceeded","timeout","hook_blocked","abort","iteration_cap","max_turns_exceeded"]);function qm(e,t={}){let n=t.minOccurrences??1;if(n<1)throw new Error(`minOccurrences must be >= 1 (got ${n})`);let r=new Map;for(let s of e)for(let i of s.events){let a=i.event;if(a.kind!=="closure")continue;let l=a.payload.reason;if(!cte.has(l))continue;let c={sessionId:s.sessionId,relativeTracePath:s.relativeTracePath,seq:a.seq,rawLine:i.rawLine,reason:l,finalCostUsd:a.payload.finalCostUsd,finalTurnCount:a.payload.finalTurnCount},u=r.get(l);u?u.push(c):r.set(l,[c])}let o=[];for(let[s,i]of r.entries())i.length<n||o.push(dte(s,i));return o}var ute=8;function dte(e,t){let n=mte(e),r=new Date().toISOString(),s=t.slice(0,ute).map(l=>({sessionId:l.sessionId,tracePath:l.relativeTracePath,eventIndices:[l.seq],excerpt:fte(l.rawLine),annotation:`closure.reason='${l.reason}' \xB7 cost=${gte(l.finalCostUsd)} \xB7 turns=${l.finalTurnCount}`})),i=t.reduce((l,c)=>l+c.finalCostUsd,0),a=t.reduce((l,c)=>l+c.finalTurnCount,0)/t.length;return{slug:n,title:`Session closure reason '${e}' across ${t.length} session${t.length===1?"":"s"}`,pattern:"closure-anomaly",severity:pte(e,t.length),observedAt:r,evidence:s,detail:{detector:"closure-anomaly@v1",closureReason:e,affectedSessions:t.length,totalCostUsd:LL(i),avgTurnCount:hte(a),maxCostUsd:LL(Math.max(...t.map(l=>l.finalCostUsd))),sessionIds:t.map(l=>l.sessionId),seqs:t.map(l=>l.seq)}}}function pte(e,t){switch(e){case"budget_exceeded":case"timeout":return"high";case"hook_blocked":case"iteration_cap":case"max_turns_exceeded":return t>=3?"high":"medium";case"abort":return t>=3?"medium":"low";default:return"low"}}function mte(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`closure-anomaly-${t.length>0?t:"unknown"}`}function fte(e){return e.length<=2e3?e:e.slice(0,1997)+"..."}function gte(e){return`$${e.toFixed(4)}`}function LL(e){return Math.round(e*1e4)/1e4}function hte(e){return Math.round(e*100)/100}import{createHash as yte}from"crypto";var gs=2,bte="v1-hook-reason-tuple",wte=8;function FL(e,t={}){let n=t.minOccurrences??gs;if(n<1)throw new Error(`minOccurrences must be >= 1 (got ${n})`);let r=new Map;for(let s of e)for(let i of s.events){let a=i.event;if(a.kind!=="hook_decision"||a.payload.hookEvent!=="SubagentStart"||a.payload.decision!=="block")continue;let l=a.payload.reason??"",c=a.payload.blockedTool,u=Ste({hookEvent:a.payload.hookEvent,reason:l,blockedTool:c}),d={sessionId:s.sessionId,relativeTracePath:s.relativeTracePath,seq:a.seq,rawLine:i.rawLine,reason:l,blockedTool:c,injectedContextBytes:a.payload.injectedContextBytes},p=r.get(u);p?p.push(d):r.set(u,[d])}let o=[];for(let[s,i]of r.entries())i.length<n||o.push(kte(s,i));return o}function Ste(e){let t=[e.hookEvent,e.reason,e.blockedTool??""].join("|");return yte("sha256").update(t).digest("hex")}function vte(e){return`subagent-block-${e.slice(0,12)}`}function kte(e,t){let n=t[0];if(!n)throw new Error("subagent-block: empty sighting bucket");let r=vte(e),o=new Date().toISOString(),i=t.slice(0,wte).map(l=>({sessionId:l.sessionId,tracePath:l.relativeTracePath,eventIndices:[l.seq],excerpt:Rte(l.rawLine),annotation:xte(l)})),a=new Set(t.map(l=>l.sessionId)).size;return{slug:r,title:Tte(n.reason,t.length,a),pattern:"subagent-block",severity:Ete(t.length,a),observedAt:o,evidence:i,detail:{detector:"subagent-block@v1",fingerprintAlgorithm:bte,fingerprint:e,hookEvent:"SubagentStart",reason:n.reason,blockedTool:n.blockedTool??null,blockCount:t.length,distinctSessions:a,sessionIds:t.map(l=>l.sessionId),seqs:t.map(l=>l.seq)}}}function Ete(e,t){return e>=6||t>=3?"high":e>=3?"medium":"low"}function Tte(e,t,n){let r=e.length>80?e.slice(0,77)+"...":e,o=r.length>0?`: "${r}"`:"";return`SubagentStart hook blocked ${t}\xD7 across ${n} session${n===1?"":"s"}${o}`}function xte(e){let t=[`seq ${e.seq}`];return e.reason&&t.push(`reason="${e.reason.slice(0,200)}"`),e.blockedTool&&t.push(`blockedTool=${e.blockedTool}`),typeof e.injectedContextBytes=="number"&&t.push(`injectedContextBytes=${e.injectedContextBytes}`),t.join(" \xB7 ")}function Rte(e){return e.length<=2e3?e:e.slice(0,1997)+"..."}var Cte=new Set(["policy-refusal","permission-denied","hook-block","abort","elicitation-declined"]),hs=3,ys=.25,Ate=8;function la(e,t={}){let n=t.minFailures??hs,r=t.minFailureRate??ys;if(n<1)throw new Error(`minFailures must be >= 1 (got ${n})`);if(r<=0||r>1)throw new Error(`minFailureRate must be in (0, 1] (got ${r})`);let o=new Map;for(let i of e)for(let a of i.events){let l=a.event;if(l.kind!=="tool_call"||l.payload.phase!=="completed"||l.payload.circuitBreaker===!0)continue;let c=_te(o,l.payload.name),u=l.payload.failureClass;if(u!==void 0&&Cte.has(u)){c.excludedByClass.set(u,(c.excludedByClass.get(u)??0)+1);continue}c.totalCalls+=1,l.payload.isError&&(c.failures.push({sessionId:i.sessionId,relativeTracePath:i.relativeTracePath,seq:l.seq,rawLine:a.rawLine,resultBytes:l.payload.resultBytes,durationMs:l.payload.durationMs,truncated:l.payload.truncated,...u!==void 0?{failureClass:u}:{}}),c.affectedSessions.add(i.sessionId),l.payload.truncated&&(c.truncatedFailureCount+=1))}let s=[];for(let i of o.values()){if(i.failures.length<n)continue;let a=i.failures.length/i.totalCalls;a<r||s.push(Ite(i,a))}return s.sort((i,a)=>i.slug.localeCompare(a.slug)),s}function _te(e,t){let n=e.get(t);return n||(n={toolName:t,totalCalls:0,failures:[],affectedSessions:new Set,truncatedFailureCount:0,excludedByClass:new Map},e.set(t,n)),n}function Ite(e,t){let n=Ote(e.toolName),r=new Date().toISOString(),s=e.failures.slice(0,Ate).map(u=>({sessionId:u.sessionId,tracePath:u.relativeTracePath,eventIndices:[u.seq],excerpt:$te(u.rawLine),annotation:`isError=true${u.failureClass?` \xB7 class=${u.failureClass}`:""} \xB7 resultBytes=${u.resultBytes} \xB7 durationMs=${u.durationMs}${u.truncated?" \xB7 truncated":""}`})),a=e.failures.reduce((u,d)=>u+d.durationMs,0)/e.failures.length,l={};for(let u of e.failures){let d=u.failureClass??"unclassified";l[d]=(l[d]??0)+1}let c={};for(let[u,d]of e.excludedByClass)c[u]=d;return{slug:n,title:Mte(e.toolName,e.failures.length,e.totalCalls,t),pattern:"tool-failure-density",severity:Pte(e.failures.length,t),observedAt:r,evidence:s,detail:{detector:"tool-failure-density@v2",toolName:e.toolName,totalCalls:e.totalCalls,failureCount:e.failures.length,failureRate:Dte(t),affectedSessionCount:e.affectedSessions.size,truncatedFailureCount:e.truncatedFailureCount,avgFailureDurationMs:Lte(a),failureClassBreakdown:l,excludedByClass:c,sessionIds:Array.from(e.affectedSessions),seqs:e.failures.map(u=>u.seq)}}}function Pte(e,t){return t>=1||t>=.5?"high":t>=.25?e>=10?"high":"medium":e>=10?"medium":"low"}function Mte(e,t,n,r){let o=(r*100).toFixed(1);return`'${e}' tool failed ${t}/${n} calls (${o}%)`}function Ote(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`tool-failure-${t.length>0?t:"unknown"}`}function $te(e){return e.length<=2e3?e:e.slice(0,1997)+"..."}function Dte(e){return Math.round(e*1e4)/1e4}function Lte(e){return Math.round(e*100)/100}var zm=Object.freeze([{name:"repeated-tool-use",description:`Tool fired \u2265N consecutive times with identical fingerprint (default ${Er})`,run:(e,t)=>Gm(e,{minRepeats:t.minRepeats??Er})},{name:"closure-anomaly",description:`Session closure reason \u2208 {budget_exceeded,timeout,hook_blocked,abort,iteration_cap,max_turns_exceeded} (default \u2265${1})`,enabledByDefault:!1,run:(e,t)=>qm(e,{minOccurrences:t.closureAnomalyMinOccurrences??1})},{name:"subagent-block",description:`Same SubagentStart hook block reason recurring across \u2265N events (default ${gs})`,enabledByDefault:!1,run:(e,t)=>FL(e,{minOccurrences:t.subagentBlockMinOccurrences??gs})},{name:"tool-failure-density",description:`Tool with \u2265N failures (isError: true) AND failure rate \u2265R (defaults: ${hs} failures, ${ys} rate)`,enabledByDefault:!0,run:(e,t)=>la(e,{minFailures:t.toolFailureMinFailures??hs,minFailureRate:t.toolFailureMinRate??ys})}]);function NL(e,t,n,r){let o=[];for(let s of zm){if(n!==void 0){if(!n.has(s.name))continue}else if(r!==!0&&s.enabledByDefault===!1)continue;let i=s.run(e,t);o.push(...i)}return o}function Jm(){return zm.map(e=>e.name)}function BL(){return zm.filter(e=>e.enabledByDefault!==!1).map(e=>e.name)}function ca(){return zm.filter(e=>e.enabledByDefault===!1).map(e=>e.name)}import{existsSync as rc,mkdirSync as JL,readFileSync as ene,readdirSync as VL,renameSync as YL,writeFileSync as mS}from"fs";import{join as XL}from"path";import{z as O}from"zod";var ua=O.enum(["repeated-tool-use","subagent-block","closure-anomaly","tool-failure-density"]),Vm=O.enum(["low","medium","high"]),Fte=O.enum(["open","deferred","resolved"]),UL=O.object({sessionId:O.string().min(1),tracePath:O.string().min(1),eventIndices:O.array(O.number().int().nonnegative()).min(1),excerpt:O.string().max(2e3),annotation:O.string().optional()}),Ym=O.object({at:O.string().datetime(),text:O.string()}),nc=O.object({schemaVersion:O.literal(1),slug:O.string().regex(/^[a-z0-9][a-z0-9-]*$/,"slug must be lowercase alphanumeric with hyphens"),title:O.string().min(1).max(200),pattern:ua,severity:Vm,status:Fte,firstSeen:O.string().datetime(),lastSeen:O.string().datetime(),occurrenceCount:O.number().int().nonnegative(),evidence:O.array(UL).min(1),detail:O.record(O.string(),O.unknown()),notes:O.array(Ym).default([])}),EKe=O.object({slug:O.string().regex(/^[a-z0-9][a-z0-9-]*$/),title:O.string().min(1).max(200),pattern:ua,severity:Vm,observedAt:O.string().datetime(),evidence:O.array(UL).min(1),detail:O.record(O.string(),O.unknown())}),jL=O.object({timestamp:O.string().datetime(),event:O.enum(["created","updated","merged-noop"]),slug:O.string(),pattern:ua,occurrenceCount:O.number().int().nonnegative(),evidenceAdded:O.number().int().nonnegative()}),Nte=O.enum(["prompt-defect","schema-too-strict","schema-too-loose","tool-output-shape","hook-overreach","retry-policy","timeout-too-low","cost-control","dispatcher-bug","detector-needs-tuning","unknown"]),Bte=O.enum(["safe","moderate","high","forbidden"]),Ute=O.enum(["low","medium","high"]),jte=O.object({cardSlug:O.string(),eventIndices:O.array(O.number().int().nonnegative()).min(1),annotation:O.string().optional()}),Hte=O.object({path:O.string().min(1),rationale:O.string(),riskTier:Bte,confidence:Ute}),Wte=O.object({unitTests:O.array(O.string()),evalCases:O.array(O.string()),smokeChecks:O.array(O.string()),manualChecks:O.array(O.string())}),Kte=O.object({forbiddenPaths:O.array(O.string()),requiresExplicitApproval:O.boolean()}),Gte=O.enum(["draft","approved","rejected","superseded"]),dS=O.object({schemaVersion:O.literal(1),proposalId:O.string().regex(/^[a-z0-9][a-z0-9-]*$/),cardSlug:O.string().regex(/^[a-z0-9][a-z0-9-]*$/),title:O.string().min(1).max(200),hypothesis:O.string().min(1),rootCauseClass:Nte,evidenceRefs:O.array(jte).min(1),fixSketch:O.string().min(1),likelyFiles:O.array(Hte),riskLevel:Vm,validationPlan:Wte,scopeFreeze:Kte,generatedBy:O.enum(["template","llm"]),createdAt:O.string().datetime(),status:Gte,notes:O.array(Ym).default([])}),HL=O.object({timestamp:O.string().datetime(),event:O.enum(["created","triaged","superseded"]),proposalId:O.string(),cardSlug:O.string(),generatedBy:O.enum(["template","llm"]),riskLevel:Vm}),qte=O.object({sourceSessionId:O.string().min(1),sourceTracePath:O.string().min(1),fixturePath:O.string().min(1),evidenceRowIndex:O.number().int().nonnegative(),evidenceEventIndices:O.array(O.number().int().nonnegative()).min(1),sliceLineRange:O.object({startLine:O.number().int().positive(),endLine:O.number().int().positive()}),sliceLineCount:O.number().int().positive(),sliceSha256:O.string().regex(/^[0-9a-f]{64}$/,"sliceSha256 must be 64 lowercase hex chars")}),zte=O.object({kind:O.literal("pattern-absent"),patternId:ua,detectorVersion:O.string().min(1),rationale:O.string().min(1)}),Jte=O.object({detectorAtGeneration:O.string().min(1),fingerprintAtGeneration:O.string().nullable(),cardOccurrenceCountAtGeneration:O.number().int().nonnegative(),cardLastSeenAtGeneration:O.string().datetime(),generatedBy:O.literal("replay-fixture")}),Vte=O.enum(["draft","approved","rejected","superseded"]),Xm=O.object({schemaVersion:O.literal(1),evalCaseId:O.string().regex(/^[a-z0-9][a-z0-9-]*$/,"evalCaseId must be lowercase alphanumeric with hyphens"),cardSlug:O.string().regex(/^[a-z0-9][a-z0-9-]*$/),proposalId:O.string().regex(/^[a-z0-9][a-z0-9-]*$/).nullable(),title:O.string().min(1).max(200),createdAt:O.string().datetime(),kind:O.literal("replay"),replay:qte,assertion:zte,provenance:Jte,status:Vte,notes:O.array(Ym).default([])}),WL=O.object({timestamp:O.string().datetime(),event:O.enum(["created","triaged","superseded"]),evalCaseId:O.string(),cardSlug:O.string(),proposalId:O.string().nullable(),kind:O.literal("replay")}),Yte=O.enum(["pass","fail","skipped"]),Xte=O.object({name:O.string().min(1),description:O.string().min(1),status:Yte,expected:O.string(),actual:O.string()}),Zte=O.enum(["config-value","observed-behavior","source-symbol","fixture"]),Qte=O.object({kind:Zte,ref:O.string().min(1),detail:O.string()}),KL=O.enum(["pass","fail","unsupported","error"]),pS=O.object({schemaVersion:O.literal(1),evalRunId:O.string().regex(/^[a-z0-9][a-z0-9-]*$/,"evalRunId must be lowercase alphanumeric with hyphens"),evalCaseId:O.string().min(1),cardSlug:O.string().min(1),patternId:ua,contract:O.string().min(1).nullable(),status:KL,createdAt:O.string().datetime(),durationMs:O.number().int().nonnegative(),checks:O.array(Xte),evidence:O.array(Qte),runner:O.object({version:O.string().min(1),mode:O.literal("deterministic")}),notes:O.array(Ym).default([])}),GL=O.object({timestamp:O.string().datetime(),event:O.literal("created"),evalRunId:O.string(),evalCaseId:O.string(),cardSlug:O.string(),patternId:ua,contract:O.string().nullable(),status:KL}),qL=Object.freeze(["**/auth/**","**/billing/**","**/secrets/**","**/credentials*",".env",".env.*","pnpm-lock.yaml","package-lock.json","yarn.lock",".github/workflows/**","dist/**","build/**","node_modules/**",".git/**","**/.afk/config/**","**/.afk/state/**"]);function ZL(e){let t=go();rc(t)||JL(t,{recursive:!0});let n=ec(e.slug),r=Km(e.slug),o=da(n),s=tne(o,e),i=o===void 0,a=s.evidence.length-(o?.evidence.length??0),l=i?"created":a>0?"updated":"merged-noop",c=nc.parse(s);return one(n,c),sne(r,oc(c)),rne({timestamp:ine(),event:l,slug:c.slug,pattern:c.pattern,occurrenceCount:c.occurrenceCount,evidenceAdded:Math.max(0,a)}),{slug:c.slug,event:l,occurrenceCount:c.occurrenceCount,evidenceAdded:Math.max(0,a),jsonPath:n,markdownPath:r}}function da(e){if(rc(e))try{let t=ene(e,"utf-8"),n=JSON.parse(t),r=nc.safeParse(n);return r.success?r.data:void 0}catch{return}}function tne(e,t){if(!e)return{schemaVersion:1,slug:t.slug,title:t.title,pattern:t.pattern,severity:t.severity,status:"open",firstSeen:t.observedAt,lastSeen:t.observedAt,occurrenceCount:t.evidence.length,evidence:t.evidence,detail:t.detail,notes:[]};if(e.slug!==t.slug)throw new Error(`card-writer: slug mismatch on merge (existing='${e.slug}', detection='${t.slug}')`);let n=nne(e.evidence,t.evidence),r=ane(e.firstSeen,t.observedAt),o=lne(e.lastSeen,t.observedAt),s=cne(e.severity,t.severity);return{schemaVersion:1,slug:e.slug,title:t.title,pattern:e.pattern,severity:s,status:e.status,firstSeen:r,lastSeen:o,occurrenceCount:n.length,evidence:n,detail:t.detail,notes:e.notes}}function nne(e,t){let n=s=>`${s.sessionId}::${s.eventIndices[0]??"NA"}`,r=new Set(e.map(n)),o=[...e];for(let s of t){let i=n(s);r.has(i)||(r.add(i),o.push(s))}return o}function oc(e){let t=[];t.push(`# ${e.slug} \u2014 \`${e.severity}\` \u2014 \`${e.status}\``),t.push(""),t.push(e.title),t.push(""),t.push(`**Pattern:** \`${e.pattern}\` \xB7 **Occurrences:** ${e.occurrenceCount} \xB7 **First seen:** ${e.firstSeen} \xB7 **Last seen:** ${e.lastSeen}`),t.push(""),t.push("## Evidence"),t.push("");for(let n of e.evidence)t.push(`### Session \`${n.sessionId}\``),t.push(""),t.push(`- Trace: \`${n.tracePath}\``),t.push(`- Event seqs: ${n.eventIndices.join(", ")}`),n.annotation&&t.push(`- Note: ${n.annotation}`),t.push(""),t.push("```jsonl"),t.push(n.excerpt),t.push("```"),t.push("");if(t.push("## Detail"),t.push(""),t.push("```json"),t.push(JSON.stringify(e.detail,null,2)),t.push("```"),t.push(""),t.push("## Triage notes"),t.push(""),e.notes.length>0){for(let n of e.notes)t.push(`- _${n.at}_ \u2014 ${n.text}`);t.push("")}else t.push('_(none \u2014 add one with `afk improve cards triage <slug> --note "\u2026"`)_'),t.push("");return t.join(`
|
|
@@ -2267,9 +2267,9 @@ Safe to run repeatedly \u2014 replaces the index atomically.`).action(async()=>{
|
|
|
2267
2267
|
${i.snippet}
|
|
2268
2268
|
|
|
2269
2269
|
`)}process.stdout.write(`${s.results.length} result${s.results.length===1?"":"s"} (use FTS5 syntax for advanced queries: "exact phrase", term*, AND, OR)
|
|
2270
|
-
`)}catch(o){J(o)}})}Mt();tt();ze();ze();import{realpathSync as Vre}from"fs";OS();OS({path:
|
|
2270
|
+
`)}catch(o){J(o)}})}Mt();tt();ze();ze();import{realpathSync as Vre}from"fs";OS();OS({path:ht(),override:!1});process.argv.includes("shell-init")||XS();process.env.AFK_FRAMEWORK_DIR??=gn();process.env.AGENT_SURFACE??="afk";ev();var he=new Gre;he.name("afk").description("AI agent CLI. Starts interactive REPL by default; use `afk chat` for one-shot.").version(kr()).option("--no-update-check","Skip update version check");wI(he);B$(he);aD(he);lD(he);D$(he);dD(he);fD(he);hD(he);L$(he);bD(he);wD(he);SD(he);vD(he);PD(he);qD(he);VD(he);YD(he);XD(he);tL(he);sL(he);wL(he);TL(he);UF(he);Gk(he);WF(he);he.commands.find(e=>e.name()==="chat")?.alias("c");he.commands.find(e=>e.name()==="interactive")?.alias("i");he.commands.find(e=>e.name()==="status")?.alias("s");he.addHelpText("after",`
|
|
2271
2271
|
Examples:
|
|
2272
2272
|
$ afk # start interactive REPL
|
|
2273
2273
|
$ afk --model opus # REPL with specific model
|
|
2274
2274
|
$ afk chat "What is 2+2?" # one-shot message
|
|
2275
|
-
$ afk status --format json`);var qre=new Set(["chat","c","interactive","i","daemon","farm"]);function zre(e){let t=e.slice(2);if(t.some(o=>o==="--version"||o==="-V"||o==="--help"||o==="-h"))return!1;let n=t[0],r=n&&!n.startsWith("-")?n:void 0;return r===void 0?!0:qre.has(r)}async function Jre(e=process.argv){if(!zre(e))return;let t=Dg(),n=re(
|
|
2275
|
+
$ afk status --format json`);var qre=new Set(["chat","c","interactive","i","daemon","farm"]);function zre(e){let t=e.slice(2);if(t.some(o=>o==="--version"||o==="-V"||o==="--help"||o==="-h"))return!1;let n=t[0],r=n&&!n.startsWith("-")?n:void 0;return r===void 0?!0:qre.has(r)}async function Jre(e=process.argv){if(!zre(e))return;let t=Dg(),n=re(vt());if(!t&&n==="anthropic-direct"){if(!process.stdin.isTTY){process.stderr.write("agent-afk: No Anthropic credential found. Run `afk login` to authenticate.\n"),process.exit(1);return}try{await Mm(),OS({path:ht(),override:!0})}catch{}}}var KF=process.argv[1]??"",Yre=import.meta.url===`file://${KF}`||import.meta.url===`file://${Vre(KF)}`;Yre&&(async()=>{await Jre();let e=At(),n=process.argv.slice(2).some(a=>a==="--no-update-check")?"off":e.updatePolicy,r=I$(n),o=null,s=process.stderr.write.bind(process.stderr);process.stderr.write=(a,...l)=>typeof a=="string"&&a.includes("Updated to agent-afk")?(o=(o??"")+a,!0):s(a,...l),P$(),process.stderr.write=s,$$(r,o),process.argv.length<=2||process.argv[2]==="interactive"||process.argv[2]==="i"?r&&n==="auto"&&Pw(r.latestVersion):(o!==null&&process.stderr.write(o),r&&(Cm(r),n==="auto"&&Pw(r.latestVersion))),he.parseAsync(process.argv).catch(a=>{console.error(a),process.exitCode=1})})();export{ey as getMaxBudgetUsd,il as getMaxOutputTokens,ty as getTaskBudget,zre as needsCredentialGate,fi as parseBudget,Yr as parseEffort,gi as parseMaxOutputTokens,Vr as parseThinking,Jre as runFirstRunDetector};
|