agent-afk 5.8.1 → 5.9.0
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/agent/providers/anthropic-direct/query.d.ts +3 -0
- package/dist/cli.mjs +88 -88
- package/dist/index.mjs +72 -72
- package/dist/telegram.mjs +37 -37
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
var QF=Object.defineProperty;var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var mc=(e,t)=>{for(var n in t)QF(e,n,{get:t[n],enumerable:!0})};function fc(e){return ba.find(t=>t.name===e)}function KS(e){return ba.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function vf(e){return process.env[e]!==void 0}var ba,v,q=_(()=>{"use strict";ba=[{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 ba){if(!t.secret)continue;let n=Object.getOwnPropertyDescriptor(v,t.name);n&&Object.defineProperty(v,t.name,{...n,enumerable:!1})}})()});import{existsSync as GS,mkdirSync as eN,renameSync as tN,cpSync as nN,rmSync as rN}from"fs";import{join as Z,dirname as zS,isAbsolute as JS}from"path";import{homedir as kf}from"os";import{fileURLToPath as oN}from"url";function De(){let e=v.AFK_HOME;if(e!==void 0&&e!==""){if(!JS(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return Z(kf(),".afk")}function yn(){return Z(De(),"agent-framework")}function Cr(){return Z(yn(),"forge-telemetry.jsonl")}function Ss(){return Z(yn(),"briefs")}function gc(){return Z(De(),"skills")}function Xe(){return Z(De(),"plugins")}function VS(){return Z(process.cwd(),".afk")}function hc(){return Z(VS(),"skills")}function yc(){return Z(VS(),"plugins")}function bc(e=process.cwd()){return Z(e,".afk","plans")}function ce(){return Z(Xe(),".index.json")}function Ef(){return Z(en(),"schedules.json")}function zn(){return Z(Xe(),"cache")}function wa(e){return Z(zn(),e)}function vs(){let e=oN(import.meta.url),t=zS(e);return Z(t,"bundled-plugins")}function en(){return Z(De(),"config")}function xe(){let e=v.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!JS(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return Z(De(),"state")}function wc(){return Z(De(),"cache")}function ks(){return Z(De(),"logs")}function Jn(){return Z(xe(),"sessions")}function Sc(){return Z(xe(),"presence")}function Tf(){return Z(xe(),"todos")}function Sa(){return Z(xe(),"transcripts")}function vc(){return Z(xe(),"memory")}function mt(){return Z(xe(),"queue")}function Es(){return Z(xe(),"session-grants.jsonl")}function va(){return Z(en(),"permissions.json")}function YS(){return Z(De(),"farms")}function xf(e){return Z(YS(),e)}function iN(e){if(!sN.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function Ts(e){return iN(e),Z(xe(),"witness",e)}function Rf(){return Z(xe(),"receipts")}function kc(e="default"){return Z(xe(),"daemon",`agent-afk@${e}`)}function XS(){return Z(xe(),"worktree-sweep.lock")}function yt(){return Z(en(),"afk.env")}function Ut(){return Z(en(),"afk.config.json")}function ZS(){return Z(en(),"settings.json")}function QS(e=process.cwd()){return Z(e,".afk","settings.json")}function ev(){return Z(kf(),".afk.env")}function Ec(){return Z(kf(),".afk.config.json")}function aN(){return Z(De(),"sessions")}function lN(){return Z(De(),"todos")}function cN(){return Z(De(),"transcripts")}function Cf(e,t){if(e!==t&&GS(e)&&!GS(t))try{eN(zS(t),{recursive:!0});try{tN(e,t)}catch(n){if(n.code==="EXDEV")try{nN(e,t,{recursive:!0}),rN(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
|
|
3
|
-
`)}}}catch{}}function tv(){Cf(aN(),Jn())}function nv(){Cf(lN(),Tf())}function rv(){Cf(cN(),Sa())}function Af(){return Z(xe(),"repl-history.jsonl")}function dN(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(e.length>qS)throw new Error(`Invalid jobId: exceeds ${qS} chars`);if(!uN.test(e))throw new Error(`Invalid jobId: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function ka(){return Z(xe(),"bg")}function bo(e){return dN(e),Z(ka(),e)}function Tc(e){return Z(bo(e),"events.jsonl")}function _f(e){return Z(bo(e),"meta.json")}function xc(e){return typeof e=="string"&&e.length>0&&e.length<=mN&&pN.test(e)}function Ea(e){if(!xc(e))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(e)}`);return Z(Jn(),e)}function If(e){return Z(Ea(e),"events.jsonl")}function Pf(e){return Z(Ea(e),"session.key")}function Ta(){return Z(xe(),"mcp","server-status.json")}var sN,uN,qS,pN,mN,K=_(()=>{"use strict";q();sN=/^[a-zA-Z0-9_-]+$/;uN=/^[A-Za-z0-9_-]+$/,qS=128;pN=/^[A-Za-z0-9_-]+$/,mN=128});import{randomBytes as fN}from"node:crypto";import{mkdirSync as gN,renameSync as hN,rmSync as ov,writeFileSync as yN}from"node:fs";import{dirname as bN,isAbsolute as wN,join as SN}from"node:path";function Rc(){return SN(xe(),"last-cwd")}function sv(){try{ov(Rc(),{force:!0})}catch{}}function iv(e){if(!wN(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=Rc();gN(bN(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${fN(6).toString("hex")}`;try{yN(n,e,{encoding:"utf8",mode:384}),hN(n,t)}catch(r){try{ov(n,{force:!0})}catch{}throw r}}catch{}}function av(){let e=v.AFK_SHELL_WRAPPER;return e==="1"||e==="true"}var Cc=_(()=>{"use strict";q();K()});var at,jt,
|
|
3
|
+
`)}}}catch{}}function tv(){Cf(aN(),Jn())}function nv(){Cf(lN(),Tf())}function rv(){Cf(cN(),Sa())}function Af(){return Z(xe(),"repl-history.jsonl")}function dN(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(e.length>qS)throw new Error(`Invalid jobId: exceeds ${qS} chars`);if(!uN.test(e))throw new Error(`Invalid jobId: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function ka(){return Z(xe(),"bg")}function bo(e){return dN(e),Z(ka(),e)}function Tc(e){return Z(bo(e),"events.jsonl")}function _f(e){return Z(bo(e),"meta.json")}function xc(e){return typeof e=="string"&&e.length>0&&e.length<=mN&&pN.test(e)}function Ea(e){if(!xc(e))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(e)}`);return Z(Jn(),e)}function If(e){return Z(Ea(e),"events.jsonl")}function Pf(e){return Z(Ea(e),"session.key")}function Ta(){return Z(xe(),"mcp","server-status.json")}var sN,uN,qS,pN,mN,K=_(()=>{"use strict";q();sN=/^[a-zA-Z0-9_-]+$/;uN=/^[A-Za-z0-9_-]+$/,qS=128;pN=/^[A-Za-z0-9_-]+$/,mN=128});import{randomBytes as fN}from"node:crypto";import{mkdirSync as gN,renameSync as hN,rmSync as ov,writeFileSync as yN}from"node:fs";import{dirname as bN,isAbsolute as wN,join as SN}from"node:path";function Rc(){return SN(xe(),"last-cwd")}function sv(){try{ov(Rc(),{force:!0})}catch{}}function iv(e){if(!wN(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=Rc();gN(bN(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${fN(6).toString("hex")}`;try{yN(n,e,{encoding:"utf8",mode:384}),hN(n,t)}catch(r){try{ov(n,{force:!0})}catch{}throw r}}catch{}}function av(){let e=v.AFK_SHELL_WRAPPER;return e==="1"||e==="true"}var Cc=_(()=>{"use strict";q();K()});var at,jt,pe,Ar,Ac,bt=_(()=>{"use strict";at=class extends Error{constructor(t){super(t),this.name="AbortError"}},jt=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},pe=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},Ar=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},Ac=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 Ke(){return v.AFK_DEBUG==="1"||v.DEBUG==="1"}function z(...e){Ke()&&console.log(...e)}var Me=_(()=>{"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: ${bn(n)}`)}}async function tn(e,t){if(e)try{await e.write({kind:"hook_decision",payload:t})}catch(n){z(`trace.emit hook_decision failed: ${bn(n)}`)}}async function vo(e,t){if(e)try{await e.write({kind:"subagent_lifecycle",payload:t})}catch(n){z(`trace.emit subagent_lifecycle failed: ${bn(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: ${bn(n)}`)}}async function Pv(e,t){if(e)try{await e.write({kind:"budget",payload:t})}catch(n){z(`trace.emit budget failed: ${bn(n)}`)}}async function Mv(e,t){if(e)try{await e.write({kind:"abort",payload:t})}catch(n){z(`trace.emit abort failed: ${bn(n)}`)}}async function Ov(e,t){if(e)try{await e.write({kind:"compaction",payload:t})}catch(n){z(`trace.emit compaction failed: ${bn(n)}`)}}async function $v(e,t){if(e)try{await e.write({kind:"closure",payload:t})}catch(n){z(`trace.emit closure failed: ${bn(n)}`)}}async function nt(e,t){if(e)try{await e.write({kind:"browser_event",payload:t})}catch(n){z(`trace.emit browser_event failed: ${bn(n)}`)}}async function Le(e,t){if(e)try{await e.write({kind:"session_phase",payload:t})}catch(n){z(`trace.emit session_phase failed: ${bn(n)}`)}}function bn(e){return e instanceof Error?e.message:String(e)}var Ue=_(()=>{"use strict";Me()});function Lc(e){return e.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Aa(e,t,n){let r=t==="oauth"?{authToken:e}:{apiKey:e};return typeof n=="string"&&n.length>0?{...r,baseURL:n}:r}function wn(e,t,n,r){return e!=="oauth"?{}:{"anthropic-beta":r?`${Dv},${nB}`:Dv,"x-app":"cli","User-Agent":rB,"X-Claude-Code-Session-Id":t,"x-client-request-id":n}}function Lv(e){return e!=="oauth"?null:[{type:"text",text:oB}]}var Dv,nB,rB,oB,Ms=_(()=>{"use strict";Dv="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",nB="effort-2025-11-24",rB="claude-cli/1.0.0 (external, cli)",oB="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;"});function Bc(e){Kf=e}function Wf(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}function Fc(e,t,n){let r={},o=Wf(e);o&&(r.id=o);let s=Wf(t);s&&(r.baseUrl=s);let i=Wf(n);return i&&(r.apiKey=i),r}function lB(){return{local:Fc(v.AFK_MODEL_LOCAL,v.AFK_MODEL_LOCAL_BASE_URL,v.AFK_MODEL_LOCAL_API_KEY),small:Fc(v.AFK_MODEL_SMALL,v.AFK_MODEL_SMALL_BASE_URL,v.AFK_MODEL_SMALL_API_KEY),medium:Fc(v.AFK_MODEL_MEDIUM,v.AFK_MODEL_MEDIUM_BASE_URL,v.AFK_MODEL_MEDIUM_API_KEY),large:Fc(v.AFK_MODEL_LARGE,v.AFK_MODEL_LARGE_BASE_URL,v.AFK_MODEL_LARGE_API_KEY)}}function zf(e){let t=lB(),n={};for(let r of Gf){let o=ko[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||Kf||zf()}function $s(e,t=Os()){let n=e.trim().toLowerCase();if(!n||n===iB)return;for(let o of Gf){let s=t[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:sB[n]}function Jf(e,t=Os()){if(e===void 0)return{id:""};let n=$s(e,t);if(n)return t[n];let r=aB[e.trim().toLowerCase()];return r?{id:r}:{id:e}}function Eo(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 Fv(e){let t={};if(!e||typeof e!="object")return t;let n=e;for(let r of Gf){let o=uB(n[r]);o&&(t[r]=o)}return t}function cB(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 Nc(e){return typeof e=="string"?e.trim():""}function uB(e){if(typeof e=="string"){let t=e.trim();return t?{id:t}:void 0}if(e&&typeof e=="object"){let t=e,n=Nc(t.id);if(!n)return;let r={id:n},o=Nc(t.name);o&&(r.name=o);let s=cB(t.provider);s&&(r.provider=s);let i=Nc(t.baseUrl);i&&(r.baseUrl=i);let a=Nc(t.apiKey);return a&&(r.apiKey=a),r}}var Gf,ko,sB,iB,qf,aB,Kf,nn=_(()=>{"use strict";q();Gf=["local","small","medium","large"],ko={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-4-6"},large:{id:"claude-opus-4-8"}},sB={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},iB="auto",qf="claude-fable-5",aB={fable:qf}});function Yf(e){return e in Vf}function wt(e){return Eo(e)}var Vf,Xn=_(()=>{"use strict";nn();Vf={opus:ko.large.id,opus_1m:ko.large.id,sonnet:ko.medium.id,sonnet_1m:ko.medium.id,haiku:ko.small.id,fable:qf}});import dB from"@anthropic-ai/sdk";import{randomUUID as Nv}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=Lc(t),c=Aa(t,l),u=a?a(c):new dB(c),d=Nv(),p=Nv(),m=wn(l,d,p),g=wt(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 Uc=_(()=>{"use strict";Ms();Xn()});import{execFileSync as Bv}from"child_process";import{existsSync as pB,readFileSync as mB,writeFileSync as fB}from"fs";import{homedir as Uv,userInfo as jv}from"os";import{join as Hv}from"path";function St(){let e=Wv();if(e===void 0)return;let t=Kv(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 Xf(){let e=Wv();if(e===void 0)return;let t=Kv(e);if(t===void 0)return;if(t.expiresAt!==void 0&&t.expiresAt>Date.now()+yB)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 bB(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}:{}},wB(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 Wv(){if(process.platform==="darwin")try{return Bv("security",["find-generic-password","-s","Claude Code-credentials","-a",jv().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let e=Hv(Uv(),".claude",".credentials.json");if(!pB(e))return;try{return mB(e,"utf-8")}catch{return}}}function Kv(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 bB(e){try{let t=await fetch(hB,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:gB})});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 Pr(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 wB(e){if(process.platform==="darwin")Bv("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",jv().username,"-w",e],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let t=Hv(Uv(),".claude",".credentials.json");SB(t,e)}}function SB(e,t){fB(e,t,{encoding:"utf-8",mode:384})}var gB,hB,yB,Fs=_(()=>{"use strict";gB="9d1c250a-e61b-44d9-88ed-5944d1962f5e",hB="https://platform.claude.com/v1/oauth/token",yB=300*1e3});function Sn(e){return e==="bypassPermissions"||e==="autonomous"}var _a=_(()=>{"use strict"});function jc(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 Hc(){let e=v.AFK_PROMPT_CACHE_TTL;return e==="5m"?"5m":e==="1h"?"1h":vB}function Gv(e,t){if(e.length===0)return e;let n=e[e.length-1],r=zv(n,t);return r===n?e:[...e.slice(0,-1),r]}function qv(e,t){if(e.length===0)return e;let n=e[e.length-1],r=kB(n,t);return r===n?e:[...e.slice(0,-1),r]}function kB(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=zv(r,t);return o===r?e:{...e,content:[...n.slice(0,-1),o]}}function zv(e,t){return e.type==="thinking"||e.type==="redacted_thinking"?e:{...e,cache_control:{type:"ephemeral",ttl:t}}}var vB,Zf=_(()=>{"use strict";q();vB="1h"});function Jv(e){return e!=="plan"?null:{type:"text",text:Qf}}var Qf,eg=_(()=>{"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 Vv(e){return e!=="autonomous"?null:{type:"text",text:tg}}var tg,ng=_(()=>{"use strict";tg=["## 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 We(e){let t=Yv[e];if(!t){let n=Object.keys(Yv).sort(),r=n.length>0?"Available: "+n.join(", "):"";throw new Error("Unknown skill: "+e+". "+r)}return t}var Yv,rn=_(()=>{"use strict";Yv={"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 on(e,t){return t?!0:(e.audience??"public")==="public"}function At(e){Wc.set(e.name,e)}function Ge(e){let t=Wc.get(e);if(t)return t;let n=Array.from(Wc.keys()).sort(),r=n.length>0?`
|
|
858
|
-
Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${e}${r}`)}function Zn(){return Array.from(Wc.keys()).sort()}function rg(e){return Zn().filter(t=>on(Ge(t),e))}var Wc,
|
|
858
|
+
Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${e}${r}`)}function Zn(){return Array.from(Wc.keys()).sort()}function rg(e){return Zn().filter(t=>on(Ge(t),e))}var Wc,vt=_(()=>{"use strict";Wc=new Map});function EB(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}var Kc,Xv=_(()=>{"use strict";Ue();Kc=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)}}Mv(this.traceWriter,{origin:r,cascadedTo:s,...n!==void 0?{reason:EB(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 qc(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 jt(`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 Gc,og,zc=_(()=>{"use strict";bt();Gc=0,og=5e3});function TB(e,t,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new vn(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 xB(e){return e.continue===!1||e.decision==="block"}function sg(e,t){if(e?.aborted){let n=e.reason,r=`aborted during ${t}${n?`: ${String(n)}`:""}`;throw new at(r)}}function Zv(){return new ig}var To,vn,ig,Ia=_(()=>{"use strict";bt();To=3e4;vn=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"},ig=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=To){sg(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){sg(n,t.event);let l;try{let c=a.handler(t,n);l=!a.options.longRunning&&r>0&&Number.isFinite(r)?await TB(c,r,t.event):await c}catch(c){throw c instanceof vn?c:new pe(`hook handler threw during ${t.event}`,t.event,c instanceof Error?c.message:String(c),{cause:c})}if(sg(n,t.event),xB(l))throw new pe(`hook handler blocked ${t.event}${l.reason?`: ${l.reason}`:""}`,t.event,l.reason);i=l}return i}}});async function kn(e,t,n,r){if(!e)return;if(r.kind==="blocked"){await tn(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 tn(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 Qv(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await kn(n.traceWriter,"SubagentStart",{},{kind:"decision",decision:r})}catch(r){throw r instanceof pe&&await kn(n.traceWriter,"SubagentStart",{},{kind:"blocked",err:r}),r}}function RB(e,t,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new vn(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 ek(e,t,n={}){if(!e)return{};try{let r=await RB(e.dispatch(t,n.signal,To),To,"SubagentStop");return await kn(n.traceWriter,"SubagentStop",{},{kind:"decision",decision:r}),r}catch(r){return r instanceof vn?(console.warn(`[afk] SubagentStop hook timed out after ${To}ms (subagentId=${t.subagentId}): ${r.message}`),n.onError?.(r),{}):(r instanceof pe&&await kn(n.traceWriter,"SubagentStop",{},{kind:"blocked",err:r}),r instanceof pe||r instanceof at?(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 ag(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await kn(n.traceWriter,"PreToolUse",{toolName:t.toolName},{kind:"decision",decision:r})}catch(r){throw r instanceof pe&&await kn(n.traceWriter,"PreToolUse",{toolName:t.toolName},{kind:"blocked",err:r}),r}}async function tk(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await kn(n.traceWriter,"PostToolUse",{toolName:t.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof pe&&await kn(n.traceWriter,"PostToolUse",{toolName:t.toolName},{kind:"blocked",err:r}),r instanceof pe||r instanceof at){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 nk(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await kn(n.traceWriter,"PostToolUseFailure",{toolName:t.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof pe&&await kn(n.traceWriter,"PostToolUseFailure",{toolName:t.toolName},{kind:"blocked",err:r}),r instanceof pe||r instanceof at){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 Jc=_(()=>{"use strict";Me();bt();Ia();Ue()});import{mkdir as CB,writeFile as AB}from"fs/promises";import{dirname as _B,join as IB}from"path";function PB(){return IB(yn(),"routing-decisions.jsonl")}function MB(e){let t={surface:"afk"};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}async function je(e){if(!(v.VITEST||v.NODE_ENV==="test"))try{let t=PB();await CB(_B(t),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,...MB(e)})+`
|
|
859
859
|
`;await AB(t,r,{flag:"a"})}catch{}}var Qn=_(()=>{"use strict";q();K()});import{AsyncLocalStorage as OB}from"node:async_hooks";function Ns(e,t){return rk.run(e,t)}function Wt(){return rk.getStore()}var rk,er=_(()=>{"use strict";rk=new OB});function ok(){return Zv()}function Vc(e,t){return e??t}var Yc=_(()=>{"use strict";Ia()});function lg(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 Xc(e,t){return sk(e,t)}function Zc(e,t){return sk(e,t)}function sk(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 Qc=_(()=>{"use strict"});function hU(e){return e.replace(/'[^']*'/g," ").replace(/"(?:[^"\\]|\\.)*"/g,t=>/\$\(|`/.test(t)?t:" ")}function tu(e){if(typeof e!="string"||e.trim().length===0)return{mutating:!1};let t=e.replace(UB," ");for(let s of fU)if(s.re.test(t))return{mutating:!0,reason:s.reason};let n=e.match(sU)?.[1];if(n&&iU.test(n))return{mutating:!0,reason:"interpreter one-liner file write (`-c`/`-e`)"};let r=hU(e);for(let s of gU)if(s.re.test(r))return{mutating:!0,reason:s.reason};let o=r.replace(pU," ").replace(dU," ").replace(/&(>>?)/g,"$1");return mU.test(o)?{mutating:!0,reason:"output redirection to a file (`>`/`>>`)"}:{mutating:!1}}var $B,DB,LB,FB,NB,BB,UB,jB,HB,WB,KB,GB,qB,zB,JB,VB,YB,eu,XB,ZB,QB,eU,tU,nU,rU,oU,sU,iU,aU,lU,cU,uU,dU,pU,mU,fU,gU,cg=_(()=>{"use strict";$B=/\bgit\b[^|;&]*\s(commit|push|pull|merge|rebase|reset|checkout|switch|restore|cherry-pick|revert|am|apply|clean|add|rm|mv|init)\b/i,DB=/\bgit\b[^|;&]*\s+tag\s+-/i,LB=/\bgit\b[^|;&]*\s+branch\s+-[dDmM]\b/i,FB=/\bgit\b[^|;&]*\s+remote\s+(add|remove|rm|set-url|rename)\b/i,NB=/\bgit\b[^|;&]*\s+worktree\s+(remove|prune|move|lock|unlock)\b/i,BB=/\bgit\b[^|;&]*\s+stash\b(?!\s+(list|show)\b)/i,UB=/\bstash@\{[^}]*\}/gi,jB=/\bgit\s+config\b[^|;&]*\s(--add|--unset|--unset-all|--replace-all|--rename-section|--remove-section|--edit|-e)\b/i,HB=/\bgit\s+config\s+(?:--(?:global|system|local|worktree)\s+|(?:--file|-f)\s+\S+\s+)*[\w][\w.-]*\s+\S/i,WB=/\bgh\s+\w[\w-]*\s+(create|merge|close|edit|delete|comment|review|reopen|sync|fork|clone|ready)\b/i,KB=/\bgh\s+api\b.*(-X|--method)\s+(POST|PUT|PATCH|DELETE)\b/i,GB=/\bgh\s+api\b.*(\s-f\b|\s-F\b|--field\b)/i,qB=/\bgh\s+(secret|variable|workflow|release|run|cache|ssh-key|gpg-key)\s+(set|run|rerun|cancel|upload|delete|enable|disable)\b/i,zB=/\|\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,VB=/\bfind\b[^|;&]*\s-delete\b/i,YB=/\bfind\b[^|;&]*\s-exec\s+['"]?\s*(rm|rmdir|unlink|mv|cp|dd|truncate|shred|tee|chmod|chown|chgrp|install|patch)\b/i,eu=String.raw`(?:^|[\n;|&(]|\$\()\s*`,XB=new RegExp(eu+String.raw`patch\b`,"i"),ZB=new RegExp(eu+String.raw`install\b`,"i"),QB=new RegExp(eu+String.raw`(?:source\b|\.\s+\S)`,"i"),eU=/\btar\s+-?[a-zA-Z]*[cxruA][a-zA-Z]*\b/i,tU=new RegExp(eu+String.raw`unzip\b`,"i"),nU=/\bcpio\b[^|;&]*\s-[a-zA-Z]*i\b/i,rU=/\bsed\b[^|;&]*\s-[a-zA-Z]*i\b/i,oU=/\bperl\b[^|;&]*\s-[a-zA-Z]*i\b/i,sU=/\b(?:python3?|nodejs|node|bun|ruby|perl|php)\b[^|;&]*?\s-(?:c|e)\b\s*("(?:[^"\\]|\\.)*"|'[^']*'|`[^`]*`)/i,iU=/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,aU=/\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,lU=/\b(curl|wget)\b[^|;&]*\s(-o\b|-O\b|--output\b)/i,cU=/\bcurl\b[^|;&]*\s-X\s+(POST|PUT|PATCH|DELETE)\b/i,uU=/\bcurl\b[^|;&]*\s(-d\b|--data\b|-F\b|--form\b)/i,dU=/(\d*&?>>?\s*\/dev\/null|\d*>&\d+|&>\s*\/dev\/null|&>>\s*\/dev\/null)/gi,pU=/\$\(\(.*?\)\)/g,mU=/(?<![=<>-])>>?(?!&)/,fU=[{re:$B,reason:"git repository mutation"},{re:DB,reason:"git tag create/delete"},{re:LB,reason:"git branch delete/rename"},{re:FB,reason:"git remote mutation"},{re:BB,reason:"git stash mutation (only `stash list`/`stash show` allowed)"},{re:jB,reason:"git config write flag (only reads allowed)"},{re:HB,reason:"git config set (`<key> <value>`; only reads allowed)"},{re:WB,reason:"gh write operation"},{re:KB,reason:"gh api write method (POST/PUT/PATCH/DELETE)"},{re:GB,reason:"gh api field payload (-f/-F/--field)"},{re:qB,reason:"gh extended write operation (secret/variable/workflow/run/cache)"},{re:NB,reason:"git worktree mutation (remove/prune/move)"},{re:rU,reason:"sed in-place edit (-i)"},{re:oU,reason:"perl in-place edit (-i)"},{re:aU,reason:"package install/modify"},{re:lU,reason:"curl/wget output-to-file"},{re:cU,reason:"curl write method (POST/PUT/PATCH/DELETE)"},{re:uU,reason:"curl data/form payload"},{re:YB,reason:"find -exec with mutating verb"}],gU=[{re:zB,reason:"pipe-to-shell (RCE via piped interpreter)"},{re:JB,reason:"filesystem mutation"},{re:VB,reason:"find -delete (file removal)"},{re:XB,reason:"patch (applies a diff to files)"},{re:ZB,reason:"install (writes files)"},{re:QB,reason:"source/dot-source executes a script"},{re:eU,reason:"tar create/extract/append/update (writes files/archive)"},{re:tU,reason:"unzip (writes files)"},{re:nU,reason:"cpio extract (-i mode writes files)"}]});var yU,bU,wU,SU,vU,kU,EU,TU,xU,xo,Ro,Co,RU,CU,AU,_U,IU,PU,MU,OU,$U,DU,LU,FU,NU,tr,Kt,fae,En=_(()=>{"use strict";yU={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"]}},bU={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"]}},wU={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"]}},SU={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"]}},vU={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"]}},kU={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"]}},EU={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"]}},TU={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"]}},xU={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:[]}},xo={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.
|
|
@@ -994,8 +994,8 @@ ${ug}
|
|
|
994
994
|
`,"utf-8")}catch(r){z("WAL append failed (non-fatal):",String(r))}}};ZU=/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;QU=new Set(["fact","session_start","session_end","supersede"]),ej=new Set(["preference","convention","decision","learning"])});function bk(e){return nj.has(e)}function lu(){return v.AFK_MEMORY_EVIDENCE_GATE==="1"}function dg(e){return bk(e)}function cu(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function wk(e,t){return bk(e)?cu(t)?"verified":"unverified":"not-applicable"}function Sk(e,t){return t!=="unverified"||e.startsWith(yk)?e:`${yk} ${e}`}var nj,yk,vk=_(()=>{"use strict";q();nj=new Set(["convention"]),yk="[unverified]"});function oj(e,t){return t?e.map(n=>{if(n.type!=="fact"||!n.category)return{...n,verification:"not-applicable"};let r=wk(n.category,n.evidence);return{...n,verification:r,content:Sk(n.content,r)}}):e.map(n=>{let r={...n};return delete r.evidence,delete r.verification,r})}function Ma(e,t,n){let r=async i=>{try{let a=sj(i),l=e.search(a.query,{category:a.category,since:a.since,limit:a.limit??10});return{content:JSON.stringify(oj(l,lu()))}}catch(a){return{content:`memory_search error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},o=async i=>{try{let a=ij(i);if(a.target==="hot"){if(a.action!=="set")return{content:'Hot memory only supports action: "set". Use supersede/remove only for facts.',isError:!0};if(!a.content)return{content:'content is required for action: "set"',isError:!0};let l=e.saveHot(a.content),c={saved:!0,target:"hot",usage:{tokens:l.tokens,maxTokens:l.maxTokens,pct:l.pct}};return l.truncated?(c.truncated=!0,c.note='Hot memory exceeded the ~1,500-token cap and was truncated from the end (lowest-priority lines dropped; a sentinel marks the cut). Keep hot memory to a few durable essentials \u2014 move detail to the fact archive with target:"fact".'):l.pct>=gk*100&&(c.warning=`Hot memory is at ${l.pct}% of the ~1,500-token cap. Move non-essential lines to the fact archive (target:"fact") before it truncates.`),{content:JSON.stringify(c)}}if(a.action==="set"){if(!a.category)return{content:"category is required for fact storage",isError:!0};if(!a.content)return{content:'content is required for action: "set"',isError:!0};let l=a.category,c=cu(a.evidence),d={id:e.storeFact({session_id:t,category:l,content:a.content,source_surface:n??"cli",evidence:c}),action:"set",target:"fact"};return lu()&&dg(l)&&!c&&(d.warning=kk),{content:JSON.stringify(d)}}if(a.action==="supersede"){if(!a.supersedes)return{content:'supersedes (fact ID) is required for action: "supersede"',isError:!0};if(!a.content)return{content:'content is required for action: "supersede"',isError:!0};let l=e.getFact(a.supersedes),c=a.evidence===void 0?void 0:cu(a.evidence),d={id:e.supersedeFact(a.supersedes,a.content,a.category??void 0,c),action:"supersede",target:"fact",supersedes:a.supersedes};if(lu()){let p=a.category??l?.category;p&&dg(p)&&((c===void 0?l?.evidence??null:c)?c===void 0&&(d.warning=rj):d.warning=kk)}return{content:JSON.stringify(d)}}if(a.action==="remove"){if(!a.id)return{content:'id (fact ID) is required for action: "remove"',isError:!0};let l=e.removeFact(a.id);return{content:JSON.stringify({removed:l,action:"remove",target:"fact"})}}return{content:`Unknown action: ${a.action}`,isError:!0}}catch(a){return{content:`memory_update error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},s=async i=>{try{let a=aj(i);return e.writeProcedure(a.name,a.content,t),{content:JSON.stringify({name:a.name,written:!0})}}catch(a){return{content:`procedure_write error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}};return new Map([["memory_search",r],["memory_update",o],["procedure_write",s]])}function sj(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e;if(typeof t.query!="string")throw new Error("query (string) is required");let n={query:t.query};if(t.category!==void 0){if(typeof t.category!="string")throw new Error("category must be a string");let r=["preference","convention","decision","learning"];if(!r.includes(t.category))throw new Error(`category must be one of: ${r.join(", ")}`);n.category=t.category}if(t.since!==void 0){if(typeof t.since!="string")throw new Error("since must be a string (ISO date)");n.since=t.since}if(t.limit!==void 0){if(typeof t.limit!="number"||t.limit<=0)throw new Error("limit must be a positive number");n.limit=t.limit}return n}function ij(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e,n=["hot","fact"];if(typeof t.target!="string"||!n.includes(t.target))throw new Error(`target must be one of: ${n.join(", ")}`);let r=["set","supersede","remove"];if(typeof t.action!="string"||!r.includes(t.action))throw new Error(`action must be one of: ${r.join(", ")}`);let o={target:t.target,action:t.action};if(t.content!==void 0){if(typeof t.content!="string")throw new Error("content must be a string");o.content=t.content}if(t.category!==void 0){if(typeof t.category!="string")throw new Error("category must be a string");let s=["preference","convention","decision","learning"];if(!s.includes(t.category))throw new Error(`category must be one of: ${s.join(", ")}`);o.category=t.category}if(t.evidence!==void 0){if(typeof t.evidence!="string")throw new Error("evidence must be a string");o.evidence=t.evidence}if(t.supersedes!==void 0){if(typeof t.supersedes!="number"||t.supersedes<=0)throw new Error("supersedes must be a positive fact ID");o.supersedes=t.supersedes}if(t.id!==void 0){if(typeof t.id!="number"||t.id<=0)throw new Error("id must be a positive fact ID");o.id=t.id}return o}function aj(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e;if(typeof t.name!="string")throw new Error("name (string) is required");if(typeof t.content!="string")throw new Error("content (string) is required");return{name:t.name,content:t.content}}var Bs,Ek,Tk,Mr,nr,kk,rj,pg=_(()=>{"use strict";au();vk();Bs={name:"memory_search",category:"read",concurrencySafe:!0,description:'Search cross-session memory for facts and procedures. Returns results ranked by relevance. Use this to recall information from prior sessions. Supports FTS5 match syntax: AND, OR, NOT, "exact phrase", prefix*',input_schema:{type:"object",properties:{query:{type:"string",description:'Search query (supports FTS5 match syntax: AND, OR, NOT, "exact phrase", prefix*)'},category:{type:"string",enum:["preference","convention","decision","learning"],description:"Optional: filter by fact category"},since:{type:"string",description:"Optional: ISO date \u2014 only return facts created after this date"},limit:{type:"number",description:"Max results (default 10)"}},required:["query"]}},Ek={name:"memory_update",category:"write",concurrencySafe:!1,description:'Store a fact in cross-session memory or update hot memory. Hot memory (target: "hot") persists in the system prompt across all future sessions. Facts (target: "fact") are stored in the searchable archive.',input_schema:{type:"object",properties:{target:{type:"string",enum:["hot","fact"],description:'"hot" writes to HOT.md (system prompt), "fact" writes to the searchable archive'},action:{type:"string",enum:["set","supersede","remove"],description:"Operation: set (create/overwrite), supersede (replace while keeping history), remove (delete)"},content:{type:"string",description:"The content to store (for set/supersede)"},category:{type:"string",enum:["preference","convention","decision","learning"],description:"Required for fact target"},evidence:{type:"string",description:'Optional provenance citation backing a codebase fact \u2014 a file:line, commit SHA, or trace-event id. When the evidence gate is enabled, a "convention" fact stored without it is recalled as [unverified]; preferences and reflections never need it.'},supersedes:{type:"number",description:"Fact ID being superseded (for supersede action)"},id:{type:"number",description:"Fact ID to remove (for remove action)"}},required:["target","action"]}},Tk={name:"procedure_write",category:"write",concurrencySafe:!1,description:"Write a reusable procedure to memory. Procedures are markdown files describing how to perform recurring tasks. They persist across sessions and are searchable via memory_search.",input_schema:{type:"object",properties:{name:{type:"string",description:"Procedure name (kebab-case, becomes the filename)"},content:{type:"string",description:"Procedure content (markdown)"}},required:["name","content"]}},Mr=[Bs,Ek,Tk],nr=Mr.map(e=>e.name),kk='Stored without evidence \u2014 this codebase fact (category "convention") will be recalled as [unverified]. Supply `evidence` (a file:line, commit SHA, or trace-event id) so future sessions can trust it as ground truth rather than an unverified agent claim.',rj='Superseded without fresh evidence \u2014 the prior citation is carried forward and this codebase fact (category "convention") is still recalled as verified against the OLD evidence, which may not back the changed content. Re-supply `evidence` if the claim changed (or pass an empty string to clear it and recall as [unverified]).'});function mg(e,t="all"){switch(t){case"self":return{self:e.getSelf()};case"tools":return{tools:e.getTools()};case"subagents":return{subagents:e.getSubagents()};case"workspace":return{workspace:e.getWorkspace()};default:return{self:e.getSelf(),tools:e.getTools(),subagents:e.getSubagents(),workspace:e.getWorkspace()}}}function fg(e){return e==="self"||e==="tools"||e==="subagents"||e==="workspace"||e==="all"?e:"all"}function Us(e){let n=[`- Working directory: ${e.cwd.replace(/[\r\n]/g," ")}`];n.push(`- Date: ${lj(e.now??new Date,e.timeZone)}`);let r=typeof e.sessionId=="string"&&e.sessionId.length>0?e.sessionId.slice(0,8):null,o=e.surface&&e.surface!=="unknown"?e.surface:null,s=typeof e.depth=="number"?typeof e.maxDepth=="number"?`depth ${e.depth}/${e.maxDepth}`:`depth ${e.depth}`:null,i=[o,s].filter(a=>typeof a=="string");if(r!==null||i.length>0){let a=["- Session:"];r!==null&&a.push(r),i.length>0&&a.push(`(${i.join(", ")})`),n.push(a.join(" "))}if(e.workspace!==void 0&&e.workspace!==null){let a=e.workspace;if(a.branch!==null||a.headSha!==null){let l=a.branch??"(detached)",c=a.headSha!==null?` @ ${a.headSha}`:"",u;a.dirty===null?u="":a.dirty?u=` (${a.dirtyCount!==null?a.dirtyCount:"?"} dirty)`:u=" (clean)",n.push(`- Workspace: ${l}${c}${u}`)}}return`# Environment
|
|
995
995
|
${n.join(`
|
|
996
996
|
`)}`}function lj(e,t){try{let n=t??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",r=new Intl.DateTimeFormat("en-CA",{timeZone:n,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),o=i=>r.find(a=>a.type===i)?.value??"";return`${new Intl.DateTimeFormat("en-US",{timeZone:n,weekday:"long"}).format(e)}, ${o("year")}-${o("month")}-${o("day")} (${n})`}catch{return e.toISOString().slice(0,10)}}var gg=_(()=>{"use strict"});import{spawnSync as cj}from"child_process";function uu(e,t){try{let n=cj("git",t,{cwd:e,encoding:"utf8",maxBuffer:4096,shell:!1});if(n.status!==0||n.signal!==null||n.error!==void 0)return null;let r=typeof n.stdout=="string"?n.stdout.trim():null;return r!==null&&r.length>0?r:null}catch{return null}}function hg(e){let t=uu(e,["rev-parse","--short","HEAD"]);if(t===null)return{...uj};let n=uu(e,["symbolic-ref","--short","HEAD"]),r=uu(e,["status","--porcelain"]),o=!1,s=0;if(r!==null){let a=r.split(`
|
|
997
|
-
`).filter(l=>l.trim().length>0);o=a.length>0,s=a.length}r===null&&(o=null,s=null);let i=uu(e,["remote","get-url","origin"]);return{branch:n,headSha:t,dirty:o,dirtyCount:s,remoteUrl:i}}var uj,yg=_(()=>{"use strict";uj={branch:null,headSha:null,dirty:null,dirtyCount:null,remoteUrl:null}});function Oa(e){return{getSelf(){return{sessionId:e.sessionId??null,surface:pj(e.surface),parentSessionId:e.parentSessionId??null,depth:e.depth??null,maxDepth:e.maxDepth??null,phaseRole:e.phaseRole??null,cwd:e.cwd,model:{provider:e.providerName,name:e.modelName},permissionMode:dj(e.permissionMode)}},getTools(){return{enabled:e.getEnabledToolNames(),mcpServers:mj(e.getMcpTools())}},getSubagents(){return e.getSubagents()},getWorkspace(){return hg(e.cwd)}}}function dj(e){switch(e){case"bypassPermissions":case"acceptEdits":case"dontAsk":case"auto":return"elevated";default:return"default"}}function pj(e){switch(e){case"cli":case"repl":case"daemon":case"telegram":case"subagent":return e;default:return"unknown"}}function mj(e){let t=new Map;for(let n of e){if(!n.name.startsWith("mcp__"))continue;let r=n.name.split("__");if(r.length<3)continue;let o=r[1];typeof o!="string"||o.length===0||t.set(o,(t.get(o)??0)+1)}return[...t.entries()].map(([n,r])=>({name:n,toolCount:r})).sort((n,r)=>n.name.localeCompare(r.name))}var xk=_(()=>{"use strict";yg()});function js(e){return async(t,n)=>{let r=t&&typeof t=="object"?fg(t.view):"all",o=mg(e,r);return{content:JSON.stringify(o)}}}function $a(e,t){let n=js(t),r=e,o=Array.isArray(r.toolDefs)?r.toolDefs:null,s={async execute(i){return i.name==="get_runtime_state"?n(i.input,i.signal):e.execute(i)}};if(o!==null){let i=o.some(a=>a.name==="get_runtime_state");s.toolDefs=i?o:[...o,Tn]}return s}var Tn,ft,bg=_(()=>{"use strict";gg();Tn={name:"get_runtime_state",category:"other",concurrencySafe:!0,description:"Inspect what the runtime knows about this session: identity (sessionId, surface, depth, parent), tool affordances (currently-enabled tool names and MCP server summary), delegation state (active subagent handles, background jobs), and git workspace state (branch, HEAD SHA, dirty count, remote URL). Returns a compact JSON snapshot.\n\nUse when uncertain about: your current nesting depth, whether a tool you want is actually available right now, what MCP servers are wired, whether earlier subagents you dispatched are still running, or what git branch / commit the session started on.\n\nViews:\n- `self` \u2014 identity + model + permissions + cwd only\n- `tools` \u2014 enabled tool names + MCP server summary only\n- `subagents` \u2014 active subagent handles + background jobs only\n- `workspace` \u2014 git state (branch, headSha, dirty, dirtyCount, remoteUrl)\n- `all` \u2014 union of the four above (default)\n\nThis is a read-only, in-memory inspection. It does not probe the file system or network. Fields the runtime does not know (e.g. depth for a top-level session) come back as `null` rather than synthesised defaults.",input_schema:{type:"object",properties:{view:{type:"string",enum:["self","tools","subagents","workspace","all"],description:'Which slice of state to return. Defaults to "all". Use a narrower view when only one slice is needed to keep the response compact.'}},required:[]}},ft=[Tn.name]});import{mkdir as fj,writeFile as wg,unlink as Lae,readdir as gj,readFile as Sg}from"fs/promises";import{unlinkSync as hj,existsSync as yj}from"fs";import{join as Rk}from"path";function du(e){return Rk(Sc(),`${e}.json`)}async function bj(){try{return await fj(Sc(),{recursive:!0}),!0}catch{return!1}}async function Da(e){try{if(!await bj())return;let n=du(e.sessionId);await wg(n,JSON.stringify(e,null,2),"utf8")}catch{}}async function vg(e,t){try{let n=du(e),r=await Sg(n,"utf8"),o=JSON.parse(r);o.afk=t,await wg(n,JSON.stringify(o,null,2),"utf8")}catch{}}async function Ck(e,t){try{let n=du(e),r=await Sg(n,"utf8"),o=JSON.parse(r);o.cwd=t,await wg(n,JSON.stringify(o,null,2),"utf8")}catch{}}function rr(e){try{let t=du(e);yj(t)&&hj(t)}catch{}}async function kg(){let e=Sc(),t;try{t=await gj(e)}catch{return[]}let n=[];for(let r of t){if(!r.endsWith(".json"))continue;let o=Rk(e,r);try{let s=await Sg(o,"utf8"),i=JSON.parse(s);i!==null&&typeof i=="object"&&"sessionId"in i&&typeof i.sessionId=="string"&&n.push({...i,path:o})}catch{}}return n}var La=_(()=>{"use strict";K()});var xn=_(()=>{"use strict";gg();xk();bg();yg();La()});import Eg from"path";import{appendFileSync as wj,mkdirSync as Sj}from"fs";import{dirname as vj}from"path";import{createHash as kj}from"node:crypto";function Tj(e){return Ej.has(e)}function Rj(e){let t;try{t=JSON.stringify(e.input)??"null"}catch{t=String(e.input)}return kj("sha256").update(e.name).update("\0").update(t).digest("hex")}function Cj(e,t){return e.reduce((n,r,o)=>{let s=t(r.name,r.input),i=n[n.length-1];return i&&s&&i.isConcurrencySafe?i.indices.push(o):n.push({isConcurrencySafe:s,indices:[o]}),n},[])}var Ej,Hs,xj,It,Fa=_(()=>{"use strict";Me();
|
|
998
|
-
`)}catch{}}get toolDefs(){let t=this.permissions?.allowedTools;if(!t)return this.schemas;let n=new Set(t);return this.schemas.filter(r=>n.has(r.name))}checkReadOnlyBash(t){if(!this.readOnlyBash||t.name!=="bash")return null;let n=t.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=tu(r);return o.mutating?{content:`Bash command blocked: read-only skill may not run mutating commands (${o.reason??"mutation detected"}). Allowed: read-only recon (git status/log/diff, ls, cat, find, grep).`,isError:!0,failureClass:"permission-denied"}:null}checkRepeatCircuitBreaker(t){if(xj.has(t.name))return null;let n=Rj(t);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<Hs?null:{content:`Loop circuit breaker: "${t.name}" has been called ${this.repeatBreaker.count} times in a row with byte-identical input. The result will not change. Stop repeating this call \u2014 reuse the previous result, change the input, try a different tool, or end the turn.`,isError:!0,circuitBreaker:!0}}async runCanUseTool(t){if(!this.canUseTool)return null;let n;try{n=await this.canUseTool(t.name,t.input??{},{signal:t.signal,toolUseID:t.id})}catch(r){return await tn(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:t.name,reason:`Tool "${t.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`}),{content:`Tool "${t.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`,isError:!0,failureClass:"permission-denied"}}return n.behavior==="deny"?(await tn(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:t.name,reason:n.message||`Tool "${t.name}" denied by permission policy`}),{content:n.message||`Tool "${t.name}" denied by permission policy`,isError:!0,failureClass:"permission-denied"}):(n.updatedInput!==void 0&&(t.input=n.updatedInput),null)}async execute(t){if(t.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:"abort"};if(this.hookRegistry){let u={event:"PreToolUse",toolName:t.name,input:t.input,...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};try{await ag(this.hookRegistry,u,{signal:t.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(d){if(d instanceof we)return{content:`Tool "${t.name}" blocked by PreToolUse hook: ${d.message}`,isError:!0,failureClass:"hook-block"};throw d}}let n=lg(t.name,this.permissions);if(!n.allowed)return{content:n.reason??`Tool "${t.name}" is not permitted`,isError:!0,failureClass:"permission-denied"};let r=await this.runCanUseTool(t);if(r)return r;let o=this.checkReadOnlyBash(t);if(o)return o;let s=this.checkRepeatCircuitBreaker(t);if(s)return s;if(t.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let u,d=!1,p="";try{u=await this.subagentExecutor.execute(t)}catch(m){d=!0,p=m instanceof Error?m.message:String(m),u={content:`Agent tool error: ${p}`,isError:!0}}return d?this.firePostToolUseFailure(t.name,p,t.signal,t.input):this.firePostToolUse(t.name,u.content,t.signal,t.input),u}if(t.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let u,d=!1,p="";try{u=await this.skillExecutor.execute(t)}catch(m){d=!0,p=m instanceof Error?m.message:String(m),u={content:`Skill tool error: ${p}`,isError:!0}}return d?this.firePostToolUseFailure(t.name,p,t.signal,t.input):this.firePostToolUse(t.name,u.content,t.signal,t.input),u}if(t.name==="compose"){let u=await this.executeCompose(t);return this.firePostToolUse(t.name,u.content,t.signal,t.input),u}let i=this.handlers.get(t.name);if(!i)return{content:`Unknown tool "${t.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let a,l=!1,c="";try{a=await i(t.input,t.signal,this.callHandlerContext(t))}catch(u){l=!0,c=u instanceof Error?u.message:String(u),a={content:`Tool execution error: ${c}`,isError:!0}}return l?this.firePostToolUseFailure(t.name,c,t.signal,t.input):this.firePostToolUse(t.name,a.content,t.signal,t.input),a}async executeBatch(t){if(t.length===0)return[];if(t.length===1)return[await this.execute(t[0])];let n=new Array(t.length),r=new Set;for(let i=0;i<t.length;i++){let a=t[i];if(a.signal.aborted){n[i]={content:"Tool call aborted",isError:!0,failureClass:"abort"},r.add(i);continue}if(this.hookRegistry){let p={event:"PreToolUse",toolName:a.name,input:a.input,...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};try{await ag(this.hookRegistry,p,{signal:a.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(m){if(m instanceof we){n[i]={content:`Tool "${a.name}" blocked by PreToolUse hook: ${m.message}`,isError:!0,failureClass:"hook-block"},r.add(i);continue}throw m}}let l=lg(a.name,this.permissions);if(!l.allowed){n[i]={content:l.reason??`Tool "${a.name}" is not permitted`,isError:!0,failureClass:"permission-denied"},r.add(i);continue}let c=await this.runCanUseTool(a);if(c){n[i]=c,r.add(i);continue}let u=this.checkReadOnlyBash(a);if(u){n[i]=u,r.add(i);continue}let d=this.checkRepeatCircuitBreaker(a);if(d){n[i]=d,r.add(i);continue}}let o=t.map((i,a)=>({call:i,originalIndex:a})).filter((i,a)=>!r.has(a));if(o.length===0)return n;let s=Cj(o.map(i=>i.call),this.classifier);for(let i of s)if(i.isConcurrencySafe){let a=await Promise.allSettled(i.indices.map(async l=>{let{call:c,originalIndex:u}=o[l];return c.signal.aborted?{result:{content:"Tool call aborted",isError:!0,failureClass:"abort"},originalIndex:u}:{result:await this.executeCore(c),originalIndex:u}}));for(let l of a)if(l.status==="fulfilled")n[l.value.originalIndex]=l.value.result;else{let c=l.reason instanceof Error?l.reason.message:String(l.reason),u=i.indices[a.indexOf(l)];n[o[u].originalIndex]={content:`Tool execution error: ${c}`,isError:!0}}}else for(let a of i.indices){let{call:l,originalIndex:c}=o[a];if(l.signal.aborted){n[c]={content:"Tool call aborted",isError:!0,failureClass:"abort"};continue}n[c]=await this.executeCore(l)}return n}async executeCore(t){if(t.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let i,a=!1,l="";try{i=await this.subagentExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),i={content:`Agent tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,i.content,t.signal,t.input),i}if(t.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let i,a=!1,l="";try{i=await this.skillExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),i={content:`Skill tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,i.content,t.signal,t.input),i}if(t.name==="compose"){let i=await this.executeCompose(t);return this.firePostToolUse(t.name,i.content,t.signal,t.input),i}let n=this.handlers.get(t.name);if(!n)return{content:`Unknown tool "${t.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let r,o=!1,s="";try{r=await n(t.input,t.signal,this.callHandlerContext(t))}catch(i){o=!0,s=i instanceof Error?i.message:String(i),r={content:`Tool execution error: ${s}`,isError:!0}}return o?this.firePostToolUseFailure(t.name,s,t.signal,t.input):this.firePostToolUse(t.name,r.content,t.signal,t.input),r}async executeCompose(t){if(!this.composeExecutor)return{content:"Compose tool is not available in this session configuration",isError:!0};try{return await this.composeExecutor.execute(t)}catch(n){return{content:`Compose tool error: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}firePostToolUse(t,n,r,o){if(!this.hookRegistry)return;let s={event:"PostToolUse",toolName:t,output:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};tk(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(()=>{})}firePostToolUseFailure(t,n,r,o){if(!this.hookRegistry)return;let s={event:"PostToolUseFailure",toolName:t,error:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};nk(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(i=>{z(`firePostToolUseFailure outer catch (tool=${t}): ${String(i)}`)})}}});function Nj(e){let t=e.match(Aj);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"vitest",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function Bj(e){let t=e.match(_j);if(!t)return null;let n=parseInt(t[1]??"0",10);return{runner:"jest",passed:parseInt(t[2]??"0",10),failed:n}}function Uj(e){let t=e.match(Ij);if(!t)return null;if(t[2]!==void 0){let n=parseInt(t[2],10),r=parseInt(t[1]??"0",10);return{runner:"pytest",passed:n,failed:r}}return t[4]!==void 0?{runner:"pytest",passed:parseInt(t[4],10),failed:0}:null}function jj(e){let t=e.match(Pj);if(!t)return null;let n=parseInt(t[1]??"0",10),r=e.match(Mj),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function Hj(e){let t=[...e.matchAll(Oj)];if(t.length===0)return null;let n=0,r=0;for(let o of t)o[1]==="ok"?n++:o[1]==="FAIL"&&r++;return{runner:"go-test",passed:n,failed:r}}function Wj(e){let t=e.match($j);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"cargo",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function Kj(e){let t=e.match(Dj);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10);return{runner:"rspec",passed:n-r,failed:r}}function Gj(e){let t=e.match(Lj);if(t)return{runner:"phpunit",passed:parseInt(t[1]??"0",10),failed:0};let n=e.match(Fj);if(n){let r=parseInt(n[1]??"0",10),o=parseInt(n[2]??"0",10);return{runner:"phpunit",passed:r-o,failed:o}}return null}function Tg(e){return Nj(e)??Bj(e)??Uj(e)??jj(e)??Hj(e)??Wj(e)??Kj(e)??Gj(e)??null}var Aj,_j,Ij,Pj,Mj,Oj,$j,Dj,Lj,Fj,Ak=_(()=>{"use strict";Aj=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,_j=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,Ij=/={3,}\s*(?:(\d+)\s+failed,\s*)?(\d+)\s+passed(?:,\s*(\d+)\s+warning)?.*in\s+[\d.]+s\s*={3,}|={3,}\s*(\d+)\s+passed.*in\s+[\d.]+s\s*={3,}/,Pj=/(\d+)\s+passing/,Mj=/(\d+)\s+failing/,Oj=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,$j=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,Dj=/(\d+) examples?, (\d+) failures?/,Lj=/OK \((\d+) tests?/,Fj=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/});function Ao(e){return e.replace(_k,"").replace(qj," ").trim()}function or(e){return e.replace(_k,"")}var _k,qj,_o=_(()=>{"use strict";_k=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,qj=/[\x00-\x1F\x7F-\x9F]/g});import{spawn as zj}from"child_process";function Jj(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e;if(typeof t.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(t.timeout_ms<0||t.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=t.timeout_ms}return{command:t.command,timeout_ms:n}}function pu(e,t){let n=!1;function r(){n||e==="bypassPermissions"&&(n=!0,console.warn("[security] bash handler: shell=true with bypassPermissions \u2014 all shell metacharacters are interpreted without confirmation. Migrate to execFile to eliminate this risk (tracked: C4)."))}return async(o,s,i)=>{let{command:a,timeout_ms:l}=Jj(o);return s.aborted?{content:"Command aborted",isError:!0}:(r(),new Promise(c=>{let u=!1;function d(x){u||(u=!0,clearTimeout(m),s.removeEventListener("abort",T),c(x))}let p=zj(a,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...(i?.resolveBase??i?.cwd??t)!==void 0?{cwd:i?.resolveBase??i?.cwd??t}:{},...i?.env!==void 0?{env:{...process.env,...i.env}}:{}});p.unref();let m=setTimeout(()=>{p.pid!==void 0&&process.kill(-p.pid,"SIGKILL"),d({content:`Command timed out after ${l}ms`,isError:!0})},l),g="",h="",b=1e5,y=0,S=!1;function w(x){if(S||u||y<b)return;S=!0,console.warn(`[bash] overflow kill: stream=${x} totalBytes=${y} command="${a}"`),je({event:"tool.overflow_kill",tool:"bash",total_bytes:y,stream:x}),p.kill("SIGKILL");let C=(g+h).trimEnd();C=or(C);let R=Tg(C)??void 0;C.length>b&&(C=C.slice(0,b)),C+=`
|
|
997
|
+
`).filter(l=>l.trim().length>0);o=a.length>0,s=a.length}r===null&&(o=null,s=null);let i=uu(e,["remote","get-url","origin"]);return{branch:n,headSha:t,dirty:o,dirtyCount:s,remoteUrl:i}}var uj,yg=_(()=>{"use strict";uj={branch:null,headSha:null,dirty:null,dirtyCount:null,remoteUrl:null}});function Oa(e){return{getSelf(){return{sessionId:e.sessionId??null,surface:pj(e.surface),parentSessionId:e.parentSessionId??null,depth:e.depth??null,maxDepth:e.maxDepth??null,phaseRole:e.phaseRole??null,cwd:e.cwd,model:{provider:e.providerName,name:e.modelName},permissionMode:dj(e.permissionMode)}},getTools(){return{enabled:e.getEnabledToolNames(),mcpServers:mj(e.getMcpTools())}},getSubagents(){return e.getSubagents()},getWorkspace(){return hg(e.cwd)}}}function dj(e){switch(e){case"bypassPermissions":case"acceptEdits":case"dontAsk":case"auto":return"elevated";default:return"default"}}function pj(e){switch(e){case"cli":case"repl":case"daemon":case"telegram":case"subagent":return e;default:return"unknown"}}function mj(e){let t=new Map;for(let n of e){if(!n.name.startsWith("mcp__"))continue;let r=n.name.split("__");if(r.length<3)continue;let o=r[1];typeof o!="string"||o.length===0||t.set(o,(t.get(o)??0)+1)}return[...t.entries()].map(([n,r])=>({name:n,toolCount:r})).sort((n,r)=>n.name.localeCompare(r.name))}var xk=_(()=>{"use strict";yg()});function js(e){return async(t,n)=>{let r=t&&typeof t=="object"?fg(t.view):"all",o=mg(e,r);return{content:JSON.stringify(o)}}}function $a(e,t){let n=js(t),r=e,o=Array.isArray(r.toolDefs)?r.toolDefs:null,s={async execute(i){return i.name==="get_runtime_state"?n(i.input,i.signal):e.execute(i)}};if(o!==null){let i=o.some(a=>a.name==="get_runtime_state");s.toolDefs=i?o:[...o,Tn]}return s}var Tn,ft,bg=_(()=>{"use strict";gg();Tn={name:"get_runtime_state",category:"other",concurrencySafe:!0,description:"Inspect what the runtime knows about this session: identity (sessionId, surface, depth, parent), tool affordances (currently-enabled tool names and MCP server summary), delegation state (active subagent handles, background jobs), and git workspace state (branch, HEAD SHA, dirty count, remote URL). Returns a compact JSON snapshot.\n\nUse when uncertain about: your current nesting depth, whether a tool you want is actually available right now, what MCP servers are wired, whether earlier subagents you dispatched are still running, or what git branch / commit the session started on.\n\nViews:\n- `self` \u2014 identity + model + permissions + cwd only\n- `tools` \u2014 enabled tool names + MCP server summary only\n- `subagents` \u2014 active subagent handles + background jobs only\n- `workspace` \u2014 git state (branch, headSha, dirty, dirtyCount, remoteUrl)\n- `all` \u2014 union of the four above (default)\n\nThis is a read-only, in-memory inspection. It does not probe the file system or network. Fields the runtime does not know (e.g. depth for a top-level session) come back as `null` rather than synthesised defaults.",input_schema:{type:"object",properties:{view:{type:"string",enum:["self","tools","subagents","workspace","all"],description:'Which slice of state to return. Defaults to "all". Use a narrower view when only one slice is needed to keep the response compact.'}},required:[]}},ft=[Tn.name]});import{mkdir as fj,writeFile as wg,unlink as Lae,readdir as gj,readFile as Sg}from"fs/promises";import{unlinkSync as hj,existsSync as yj}from"fs";import{join as Rk}from"path";function du(e){return Rk(Sc(),`${e}.json`)}async function bj(){try{return await fj(Sc(),{recursive:!0}),!0}catch{return!1}}async function Da(e){try{if(!await bj())return;let n=du(e.sessionId);await wg(n,JSON.stringify(e,null,2),"utf8")}catch{}}async function vg(e,t){try{let n=du(e),r=await Sg(n,"utf8"),o=JSON.parse(r);o.afk=t,await wg(n,JSON.stringify(o,null,2),"utf8")}catch{}}async function Ck(e,t){try{let n=du(e),r=await Sg(n,"utf8"),o=JSON.parse(r);o.cwd=t,await wg(n,JSON.stringify(o,null,2),"utf8")}catch{}}function rr(e){try{let t=du(e);yj(t)&&hj(t)}catch{}}async function kg(){let e=Sc(),t;try{t=await gj(e)}catch{return[]}let n=[];for(let r of t){if(!r.endsWith(".json"))continue;let o=Rk(e,r);try{let s=await Sg(o,"utf8"),i=JSON.parse(s);i!==null&&typeof i=="object"&&"sessionId"in i&&typeof i.sessionId=="string"&&n.push({...i,path:o})}catch{}}return n}var La=_(()=>{"use strict";K()});var xn=_(()=>{"use strict";gg();xk();bg();yg();La()});import Eg from"path";import{appendFileSync as wj,mkdirSync as Sj}from"fs";import{dirname as vj}from"path";import{createHash as kj}from"node:crypto";function Tj(e){return Ej.has(e)}function Rj(e){let t;try{t=JSON.stringify(e.input)??"null"}catch{t=String(e.input)}return kj("sha256").update(e.name).update("\0").update(t).digest("hex")}function Cj(e,t){return e.reduce((n,r,o)=>{let s=t(r.name,r.input),i=n[n.length-1];return i&&s&&i.isConcurrencySafe?i.indices.push(o):n.push({isConcurrencySafe:s,indices:[o]}),n},[])}var Ej,Hs,xj,It,Fa=_(()=>{"use strict";Me();bt();Jc();Qc();cg();K();Ue();En();pg();xn();Ej=new Set([...tr,xo,Ro,Co,...Mr,Tn].filter(e=>e.concurrencySafe===!0).map(e=>e.name));Hs=8,xj=new Set;It=class{handlers;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;skillExecutor;composeExecutor;classifier;resolveBase;_readRoots;_writeRoots;_allowAll;_env;sessionId;parentSessionId;traceWriter;readOnlyBash;repeatBreaker=null;constructor(t){this.handlers=t.handlers,this.schemas=t.schemas,this.hookRegistry=t.hookRegistry,this.permissions=t.permissions,this.canUseTool=t.canUseTool,this.subagentExecutor=t.subagentExecutor,this.skillExecutor=t.skillExecutor,this.composeExecutor=t.composeExecutor,this.classifier=t.concurrencyClassifier??Tj,this.resolveBase=t.cwd,this._env=t.env,this.sessionId=t.sessionId,this.parentSessionId=t.parentSessionId,this.traceWriter=t.traceWriter,this.readOnlyBash=t.readOnlyBash===!0,this._allowAll=t.allowAll===!0;let n=t.cwd?[t.cwd]:[];this._readRoots=t.readRoots??n.slice(),this._writeRoots=t.writeRoots??n.slice()}get handlerContext(){return{cwd:this.resolveBase,resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),...this._allowAll?{allowAll:!0}:{},...this._env!==void 0?{env:this._env}:{}}}callHandlerContext(t){return{...this.handlerContext,toolUseId:t.id,...this.traceWriter!==void 0?{traceWriter:this.traceWriter}:{}}}addReadRoot(t,n="slash"){let r=Eg.resolve(t);this._readRoots.includes(r)||this._readRoots.push(r),this.appendAuditLog({action:"grant-read",path:r,source:n})}addWriteRoot(t,n="slash"){let r=Eg.resolve(t);this._readRoots.includes(r)||this._readRoots.push(r),this._writeRoots.includes(r)||this._writeRoots.push(r),this.appendAuditLog({action:"grant-write",path:r,source:n})}revokeRoot(t,n="slash"){let r=Eg.resolve(t);if(r===this.resolveBase)return;let o=this._readRoots.indexOf(r);o!==-1&&this._readRoots.splice(o,1);let s=this._writeRoots.indexOf(r);s!==-1&&this._writeRoots.splice(s,1),this.appendAuditLog({action:"revoke",path:r,source:n})}getGrants(){return{resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),allowAll:this._allowAll}}setAllowAll(t){this._allowAll=t}setResolveBase(t){let n=this.resolveBase;if(n!==t){if(this.resolveBase=t,n!==void 0){let r=this._readRoots.indexOf(n);r!==-1?this._readRoots[r]=t:this._readRoots.includes(t)||this._readRoots.push(t);let o=this._writeRoots.indexOf(n);o!==-1?this._writeRoots[o]=t:this._writeRoots.includes(t)||this._writeRoots.push(t)}else this._readRoots.includes(t)||this._readRoots.push(t),this._writeRoots.includes(t)||this._writeRoots.push(t);this.subagentExecutor?.setCwd(t),this.skillExecutor?.setCwd(t),this.composeExecutor?.setCwd(t)}}appendAuditLog(t){try{let n=Es();Sj(vj(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:this.sessionId??null,action:t.action,path:t.path,source:t.source});wj(n,r+`
|
|
998
|
+
`)}catch{}}get toolDefs(){let t=this.permissions?.allowedTools;if(!t)return this.schemas;let n=new Set(t);return this.schemas.filter(r=>n.has(r.name))}checkReadOnlyBash(t){if(!this.readOnlyBash||t.name!=="bash")return null;let n=t.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=tu(r);return o.mutating?{content:`Bash command blocked: read-only skill may not run mutating commands (${o.reason??"mutation detected"}). Allowed: read-only recon (git status/log/diff, ls, cat, find, grep).`,isError:!0,failureClass:"permission-denied"}:null}checkRepeatCircuitBreaker(t){if(xj.has(t.name))return null;let n=Rj(t);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<Hs?null:{content:`Loop circuit breaker: "${t.name}" has been called ${this.repeatBreaker.count} times in a row with byte-identical input. The result will not change. Stop repeating this call \u2014 reuse the previous result, change the input, try a different tool, or end the turn.`,isError:!0,circuitBreaker:!0}}async runCanUseTool(t){if(!this.canUseTool)return null;let n;try{n=await this.canUseTool(t.name,t.input??{},{signal:t.signal,toolUseID:t.id})}catch(r){return await tn(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:t.name,reason:`Tool "${t.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`}),{content:`Tool "${t.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`,isError:!0,failureClass:"permission-denied"}}return n.behavior==="deny"?(await tn(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:t.name,reason:n.message||`Tool "${t.name}" denied by permission policy`}),{content:n.message||`Tool "${t.name}" denied by permission policy`,isError:!0,failureClass:"permission-denied"}):(n.updatedInput!==void 0&&(t.input=n.updatedInput),null)}async execute(t){if(t.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:"abort"};if(this.hookRegistry){let u={event:"PreToolUse",toolName:t.name,input:t.input,...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};try{await ag(this.hookRegistry,u,{signal:t.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(d){if(d instanceof pe)return{content:`Tool "${t.name}" blocked by PreToolUse hook: ${d.message}`,isError:!0,failureClass:"hook-block"};throw d}}let n=lg(t.name,this.permissions);if(!n.allowed)return{content:n.reason??`Tool "${t.name}" is not permitted`,isError:!0,failureClass:"permission-denied"};let r=await this.runCanUseTool(t);if(r)return r;let o=this.checkReadOnlyBash(t);if(o)return o;let s=this.checkRepeatCircuitBreaker(t);if(s)return s;if(t.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let u,d=!1,p="";try{u=await this.subagentExecutor.execute(t)}catch(m){d=!0,p=m instanceof Error?m.message:String(m),u={content:`Agent tool error: ${p}`,isError:!0}}return d?this.firePostToolUseFailure(t.name,p,t.signal,t.input):this.firePostToolUse(t.name,u.content,t.signal,t.input),u}if(t.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let u,d=!1,p="";try{u=await this.skillExecutor.execute(t)}catch(m){d=!0,p=m instanceof Error?m.message:String(m),u={content:`Skill tool error: ${p}`,isError:!0}}return d?this.firePostToolUseFailure(t.name,p,t.signal,t.input):this.firePostToolUse(t.name,u.content,t.signal,t.input),u}if(t.name==="compose"){let u=await this.executeCompose(t);return this.firePostToolUse(t.name,u.content,t.signal,t.input),u}let i=this.handlers.get(t.name);if(!i)return{content:`Unknown tool "${t.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let a,l=!1,c="";try{a=await i(t.input,t.signal,this.callHandlerContext(t))}catch(u){l=!0,c=u instanceof Error?u.message:String(u),a={content:`Tool execution error: ${c}`,isError:!0}}return l?this.firePostToolUseFailure(t.name,c,t.signal,t.input):this.firePostToolUse(t.name,a.content,t.signal,t.input),a}async executeBatch(t){if(t.length===0)return[];if(t.length===1)return[await this.execute(t[0])];let n=new Array(t.length),r=new Set;for(let i=0;i<t.length;i++){let a=t[i];if(a.signal.aborted){n[i]={content:"Tool call aborted",isError:!0,failureClass:"abort"},r.add(i);continue}if(this.hookRegistry){let p={event:"PreToolUse",toolName:a.name,input:a.input,...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};try{await ag(this.hookRegistry,p,{signal:a.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(m){if(m instanceof pe){n[i]={content:`Tool "${a.name}" blocked by PreToolUse hook: ${m.message}`,isError:!0,failureClass:"hook-block"},r.add(i);continue}throw m}}let l=lg(a.name,this.permissions);if(!l.allowed){n[i]={content:l.reason??`Tool "${a.name}" is not permitted`,isError:!0,failureClass:"permission-denied"},r.add(i);continue}let c=await this.runCanUseTool(a);if(c){n[i]=c,r.add(i);continue}let u=this.checkReadOnlyBash(a);if(u){n[i]=u,r.add(i);continue}let d=this.checkRepeatCircuitBreaker(a);if(d){n[i]=d,r.add(i);continue}}let o=t.map((i,a)=>({call:i,originalIndex:a})).filter((i,a)=>!r.has(a));if(o.length===0)return n;let s=Cj(o.map(i=>i.call),this.classifier);for(let i of s)if(i.isConcurrencySafe){let a=await Promise.allSettled(i.indices.map(async l=>{let{call:c,originalIndex:u}=o[l];return c.signal.aborted?{result:{content:"Tool call aborted",isError:!0,failureClass:"abort"},originalIndex:u}:{result:await this.executeCore(c),originalIndex:u}}));for(let l of a)if(l.status==="fulfilled")n[l.value.originalIndex]=l.value.result;else{let c=l.reason instanceof Error?l.reason.message:String(l.reason),u=i.indices[a.indexOf(l)];n[o[u].originalIndex]={content:`Tool execution error: ${c}`,isError:!0}}}else for(let a of i.indices){let{call:l,originalIndex:c}=o[a];if(l.signal.aborted){n[c]={content:"Tool call aborted",isError:!0,failureClass:"abort"};continue}n[c]=await this.executeCore(l)}return n}async executeCore(t){if(t.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let i,a=!1,l="";try{i=await this.subagentExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),i={content:`Agent tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,i.content,t.signal,t.input),i}if(t.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let i,a=!1,l="";try{i=await this.skillExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),i={content:`Skill tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,i.content,t.signal,t.input),i}if(t.name==="compose"){let i=await this.executeCompose(t);return this.firePostToolUse(t.name,i.content,t.signal,t.input),i}let n=this.handlers.get(t.name);if(!n)return{content:`Unknown tool "${t.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let r,o=!1,s="";try{r=await n(t.input,t.signal,this.callHandlerContext(t))}catch(i){o=!0,s=i instanceof Error?i.message:String(i),r={content:`Tool execution error: ${s}`,isError:!0}}return o?this.firePostToolUseFailure(t.name,s,t.signal,t.input):this.firePostToolUse(t.name,r.content,t.signal,t.input),r}async executeCompose(t){if(!this.composeExecutor)return{content:"Compose tool is not available in this session configuration",isError:!0};try{return await this.composeExecutor.execute(t)}catch(n){return{content:`Compose tool error: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}firePostToolUse(t,n,r,o){if(!this.hookRegistry)return;let s={event:"PostToolUse",toolName:t,output:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};tk(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(()=>{})}firePostToolUseFailure(t,n,r,o){if(!this.hookRegistry)return;let s={event:"PostToolUseFailure",toolName:t,error:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};nk(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(i=>{z(`firePostToolUseFailure outer catch (tool=${t}): ${String(i)}`)})}}});function Nj(e){let t=e.match(Aj);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"vitest",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function Bj(e){let t=e.match(_j);if(!t)return null;let n=parseInt(t[1]??"0",10);return{runner:"jest",passed:parseInt(t[2]??"0",10),failed:n}}function Uj(e){let t=e.match(Ij);if(!t)return null;if(t[2]!==void 0){let n=parseInt(t[2],10),r=parseInt(t[1]??"0",10);return{runner:"pytest",passed:n,failed:r}}return t[4]!==void 0?{runner:"pytest",passed:parseInt(t[4],10),failed:0}:null}function jj(e){let t=e.match(Pj);if(!t)return null;let n=parseInt(t[1]??"0",10),r=e.match(Mj),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function Hj(e){let t=[...e.matchAll(Oj)];if(t.length===0)return null;let n=0,r=0;for(let o of t)o[1]==="ok"?n++:o[1]==="FAIL"&&r++;return{runner:"go-test",passed:n,failed:r}}function Wj(e){let t=e.match($j);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"cargo",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function Kj(e){let t=e.match(Dj);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10);return{runner:"rspec",passed:n-r,failed:r}}function Gj(e){let t=e.match(Lj);if(t)return{runner:"phpunit",passed:parseInt(t[1]??"0",10),failed:0};let n=e.match(Fj);if(n){let r=parseInt(n[1]??"0",10),o=parseInt(n[2]??"0",10);return{runner:"phpunit",passed:r-o,failed:o}}return null}function Tg(e){return Nj(e)??Bj(e)??Uj(e)??jj(e)??Hj(e)??Wj(e)??Kj(e)??Gj(e)??null}var Aj,_j,Ij,Pj,Mj,Oj,$j,Dj,Lj,Fj,Ak=_(()=>{"use strict";Aj=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,_j=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,Ij=/={3,}\s*(?:(\d+)\s+failed,\s*)?(\d+)\s+passed(?:,\s*(\d+)\s+warning)?.*in\s+[\d.]+s\s*={3,}|={3,}\s*(\d+)\s+passed.*in\s+[\d.]+s\s*={3,}/,Pj=/(\d+)\s+passing/,Mj=/(\d+)\s+failing/,Oj=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,$j=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,Dj=/(\d+) examples?, (\d+) failures?/,Lj=/OK \((\d+) tests?/,Fj=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/});function Ao(e){return e.replace(_k,"").replace(qj," ").trim()}function or(e){return e.replace(_k,"")}var _k,qj,_o=_(()=>{"use strict";_k=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,qj=/[\x00-\x1F\x7F-\x9F]/g});import{spawn as zj}from"child_process";function Jj(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e;if(typeof t.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(t.timeout_ms<0||t.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=t.timeout_ms}return{command:t.command,timeout_ms:n}}function pu(e,t){let n=!1;function r(){n||e==="bypassPermissions"&&(n=!0,console.warn("[security] bash handler: shell=true with bypassPermissions \u2014 all shell metacharacters are interpreted without confirmation. Migrate to execFile to eliminate this risk (tracked: C4)."))}return async(o,s,i)=>{let{command:a,timeout_ms:l}=Jj(o);return s.aborted?{content:"Command aborted",isError:!0}:(r(),new Promise(c=>{let u=!1;function d(x){u||(u=!0,clearTimeout(m),s.removeEventListener("abort",T),c(x))}let p=zj(a,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...(i?.resolveBase??i?.cwd??t)!==void 0?{cwd:i?.resolveBase??i?.cwd??t}:{},...i?.env!==void 0?{env:{...process.env,...i.env}}:{}});p.unref();let m=setTimeout(()=>{p.pid!==void 0&&process.kill(-p.pid,"SIGKILL"),d({content:`Command timed out after ${l}ms`,isError:!0})},l),g="",h="",b=1e5,y=0,S=!1;function w(x){if(S||u||y<b)return;S=!0,console.warn(`[bash] overflow kill: stream=${x} totalBytes=${y} command="${a}"`),je({event:"tool.overflow_kill",tool:"bash",total_bytes:y,stream:x}),p.kill("SIGKILL");let C=(g+h).trimEnd();C=or(C);let R=Tg(C)??void 0;C.length>b&&(C=C.slice(0,b)),C+=`
|
|
999
999
|
[output truncated \u2014 exceeded 100KB]`,d({content:C,truncated:!0,...R!==void 0?{testResult:R}:{}})}p.stdout.on("data",x=>{let C=b-y,R=x.length<=C?x:x.subarray(0,Math.max(0,C));y+=R.length,g+=R.toString("utf8"),w("stdout")}),p.stderr.on("data",x=>{let C=b-y,R=x.length<=C?x:x.subarray(0,Math.max(0,C));y+=R.length,h+=R.toString("utf8"),w("stderr")});let T=()=>{p.pid!==void 0&&process.kill(-p.pid,"SIGKILL"),d({content:"Command aborted",isError:!0})};s.addEventListener("abort",T),p.on("close",x=>{if(s.aborted){d({content:"Command aborted",isError:!0});return}if(x!==null&&x!==0){let $=h.trimEnd()||g.trimEnd();d({content:`Command exited with code ${x}${$?`
|
|
1000
1000
|
`+$:""}`,isError:!0});return}if(S)return;let C=(g+h).trimEnd();C=or(C);let R=Tg(C)??void 0,k=!1;C.length>b&&(C=C.slice(0,b)+`
|
|
1001
1001
|
[output truncated \u2014 exceeded 100KB]`,k=!0),d({content:C,...k?{truncated:!0}:{},...R!==void 0?{testResult:R}:{}})}),p.on("error",x=>{d({content:`Failed to execute: ${x.message}`,isError:!0})})}))}}var Ik,Pk=_(()=>{"use strict";Qn();Ak();_o();Ik=pu("default")});import sr from"path";import{realpathSync as Vj}from"fs";function Ws(e){try{return Vj.native(e)}catch{let t=sr.dirname(e),n=sr.basename(e);return t===e?e:sr.join(Ws(t),n)}}function Ok(e){let t=Mk.get(e);if(t!==void 0)return t;let n=Ws(e);return Mk.set(e,n),n}function qt(e,t,n="read"){let r=t?.resolveBase??t?.cwd,o=sr.isAbsolute(e)?e:sr.resolve(r??process.cwd(),e);if(t?.allowAll===!0||r===void 0)return o;let s=Ws(o),i=n==="read"?t?.readRoots??[r]:t?.writeRoots??[r];for(let c of i){let u=Ok(c);if(!sr.relative(u,s).startsWith(".."))return o}let a=i.map(c=>`\`${c}\``).join(", "),l=n==="read"?"read roots":"write roots";throw new Error(`Path \`${e}\` is outside the allowed ${l} [${a}].`)}function xg(e,t,n="read"){let r=t?.resolveBase??t?.cwd,o=sr.isAbsolute(e)?e:sr.resolve(r??process.cwd(),e);if(t?.allowAll===!0)return{restricted:!1,resolved:o,roots:[]};if(r===void 0)return{restricted:!1,resolved:o,roots:[]};let s=Ws(o),i=n==="read"?t?.readRoots??[r]:t?.writeRoots??[r];for(let a of i){let l=Ok(a);if(!sr.relative(l,s).startsWith(".."))return{restricted:!1,resolved:o,roots:i}}return{restricted:!0,resolved:o,roots:i}}var Mk,Or=_(()=>{"use strict";Mk=new Map});import{promises as Yj}from"fs";var $k,Dk=_(()=>{"use strict";Or();$k=async(e,t,n)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let r=e,o=r.file_path,s=r.offset??1,i=r.limit??2e3;if(typeof o!="string")return{content:"Invalid input: file_path must be a string",isError:!0};if(typeof s!="number"||s<1)return{content:"Invalid input: offset must be a positive number",isError:!0};if(typeof i!="number"||i<1)return{content:"Invalid input: limit must be a positive number",isError:!0};let a;try{a=qt(o,n,"read")}catch(l){return{content:l instanceof Error?l.message:String(l),isError:!0}}try{let l=await Yj.readFile(a),c=Math.min(8192,l.length);for(let S=0;S<c;S++)if(l[S]===0)return{content:`File appears to be binary: ${a}`,isError:!0};let u=l.toString("utf-8");if(u.length===0)return{content:""};let d=u.split(`
|
|
@@ -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=or(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 qk,zk=_(()=>{"use strict";Qn();Or();_o();qk=_g()});import{promises as b1}from"fs";var Jk,Vk=_(()=>{"use strict";Or();Jk=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=qt(o,n,"read")}catch(i){return{content:i instanceof Error?i.message:String(i),isError:!0}}try{let i=await b1.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 Yk(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 Xk=_(()=>{"use strict"});function Ig(){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 Yk(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 Xk=_(()=>{"use strict"});function Ig(){return v.ANTHROPIC_API_KEY||v.CLAUDE_CODE_OAUTH_TOKEN||St()}function Pg(){return v.OPENAI_API_KEY||v.CODEX_API_KEY||void 0}function ar(e){let t=re(e);return t==="openai-compatible"||t==="openai-codex"?Pg():Ig()}var Ks=_(()=>{"use strict";rt();Fs();q()});import{basename as Zk}from"node:path";function w1(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\`.
|
|
@@ -1078,7 +1078,7 @@ ${o}`;return s.includes("already checked out")||s.includes("is already used by w
|
|
|
1078
1078
|
Effective base URL: ${r}`)),r}return t}function Z1(){if(Ug!==void 0)return Ug;if(!fE){let o=[Ha(process.cwd(),".env"),yt(),ev()];for(let s of o)jg(s)&&Y1({path:s,override:!1});fE=!0}let e={},t=v.AFK_MODEL??v.CLAUDE_MODEL;if(t){let o=t.toLowerCase();e.model=Yf(o)?o:t}if(re(t)==="anthropic-direct"){let o=Hg();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=X1(v.AFK_OPENAI_BASE_URL)),Ug=e,e}function Wg(){if(qs!==void 0)return qs;let e=[Ha(process.cwd(),"afk.config.json"),Ut(),Ec()];for(let t of e)if(jg(t))try{let n=hE(t,"utf-8"),r=JSON.parse(n),o={},s=Fv(r.models);if(typeof r.model=="string"&&r.model.length>0){let i=r.model.toLowerCase();o.model=Yf(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!==Ha(process.cwd(),"afk.config.json")){let i=Ua(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=Lg(r.interactive.worktreeBranchPrefix,`${t}#/interactive/worktreeBranchPrefix`)),typeof r.interactive.worktreeBase=="string"&&r.interactive.worktreeBase.trim().length>0&&(Fg(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=[Ha(process.cwd(),"AFK.md"),Ha(De(),"AFK.md")];for(let t of e)if(jg(t))try{let n=hE(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 Su(){return Wg().config.telegram??{}}function Js(){return Wg().config.permissionMode??yE}function _t(e){let t=Z1(),{config:n,sourcePath:r,modelsPartial:o}=Wg(),s={...ja,...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??ja.model,maxTokens:s.maxTokens??ja.maxTokens,temperature:s.temperature??ja.temperature,updatePolicy:s.updatePolicy??ja.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??yE,...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??zf(o);if(Bc(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 ja,yE,fE,Ug,gE,qs,zs,Ot=_(()=>{"use strict";Xn();nn();rt();K();Ks();Ba();q();cr();ja={model:"sonnet",maxTokens:4096,temperature:1,updatePolicy:"notify"},yE="bypassPermissions",fE=!1;gE=new Set});function eH(e,t){return t!==void 0&&Number.isFinite(t)&&t!==0?t:e.find(r=>r>0)??e[0]}function tH(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=eH(n,t.primaryChatId);return o!==void 0?[o]:[]}function nH(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 rH(e){if(!e)return;let t=e.trim().toLowerCase();return t==="primary"||t==="broadcast"||t==="custom"?t:void 0}function oH(){let e=Su().notify??{},t=e.mode??rH(v.AFK_TELEGRAM_NOTIFY_MODE),n=e.primaryChatId??nH(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=Yk(v.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return tH(e,oH())}var vu=_(()=>{"use strict";Xk();Ot();q()});function Kg(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 bE(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),sH(t)||(t=t.replace(/<\/?[bis]>/g,"")),t}function sH(e){let t=[],n=/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>/g,r;for(;(r=n.exec(e))!==null;){let o=(r[2]??"").toLowerCase();if(r[1]==="/"){if(t.pop()!==o)return!1}else t.push(o)}return t.length===0}var wE=_(()=>{"use strict"});var Gg={};mc(Gg,{push:()=>Ys,pushIfConfigured:()=>Lr,pushMarkdown:()=>SE});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??iH}/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 SE(e){let t=bE(e.text),n=Kg(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 Lr(e,t={}){let n=v.TELEGRAM_BOT_TOKEN;if(!n)return null;let r=Vs();if(r.length===0)return null;let o=Kg(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 SE(l):await Ys({...l,...t.parseMode!==void 0?{parseMode:t.parseMode}:{}}))}return s}var iH,Io=_(()=>{"use strict";vu();wE();q();iH="https://api.telegram.org"});function aH(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>vE)return{content:`Invalid input: message exceeds Telegram's ${vE}-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 vE,kE,EE=_(()=>{"use strict";q();Io();vu();vE=4096;kE=aH()});import{JSDOM as lH}from"jsdom";import{Readability as cH}from"@mozilla/readability";import uH from"turndown";function TE(e){return e.replace(/\n{3,}/g,`
|
|
1080
1080
|
|
|
1081
|
-
`).trim()}function dH(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function RE(e,t){let r=new lH(e,{url:t}).window.document,o=(r.title??"").trim(),s=null;try{let c=r.cloneNode(!0);s=new cH(c).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let c=TE(qg.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=TE(qg.turndown(a));return{title:o,markdown:l,textLength:dH(i),usedFallback:!0}}var xE,qg,CE=_(()=>{"use strict";xE=200,qg=new uH({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});qg.remove(["script","style","noscript","iframe"])});import{readFileSync as pH}from"node:fs";import{join as mH}from"path";function fH(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function AE(e,t){return fH(t).test(e)}function yH(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(gH.has(t))return!0;if(hH.has(t))return!1}return!1}function _E(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function bH(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 wH(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function SH(e){try{return pH(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function vH(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 IE(e){let t=e?.env??v,n=e?.readFileSync??SH,r=e?.surface??t.AGENT_SURFACE,o=yH(t.AFK_BROWSER_HEADLESS,r),s=_E(t.AFK_BROWSER_ALLOWED_DOMAINS),i=_E(t.AFK_BROWSER_BLOCKED_DOMAINS),a=wH(t.AFK_BROWSER_DOM_SNAPSHOTS),l=bH(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():mH(en(),"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=vH(c,m);return g.configPath=d,g}function zg(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(AE(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>AE(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var gH,hH,Jg=_(()=>{"use strict";q();K();gH=new Set(["daemon","subagent","telegram","afk"]),hH=new Set(["repl","interactive","cli"])});import kH from"node:fs";import EH from"node:path";import{chromium as TH}from"playwright";function xH(){try{return"5.8.1"}catch{}try{let e=EH.resolve(import.meta.dirname,"../../../package.json"),t=kH.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var RH,ku,PE=_(()=>{"use strict";RH=xH(),ku=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=TH.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/${RH}`}}}});import{createHash as CH}from"crypto";function Vg(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of AH)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function ME(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&_H.test(e.label))}function OE(e){return CH("sha256").update(e,"utf8").digest("hex").slice(0,8)}function $E(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var AH,_H,Wa=_(()=>{"use strict";AH=[{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}];_H=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as IH}from"node:crypto";function PH(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function MH(e,t,n){return`el_${IH("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function OH(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function DE(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function FE(e,t){let n=e.role??"",r=e.name??"";LE.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let s of e.children??[])FE(s,t)}async function $H(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},NE).catch(()=>[])}async function DH(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},NE).catch(()=>[])}function LH(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Eu(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],s=LH(e),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=$H(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=[],FE(d,b)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,b=(await DH(e)).filter(F=>LE.has(F.role??"")));let S=new Map;for(let P of p){let F=DE(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(DE(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=MH(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)),ME({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:PH(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=OH(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 LE,NE,BE=_(()=>{"use strict";Wa();LE=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);NE="a[href], button, input, select, textarea, [role], [tabindex], label"});async function UE(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 Yg(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,s)=>UE(e,s)))).filter(o=>o!==null)}async function FH(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 Xg(e,t,n){switch(t.kind){case"element_id":return NH(e,t,n);case"selector":return BH(e,t);case"semantic":return UH(e,t)}}async function NH(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 Yg(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function BH(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 Yg(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function UH(e,t){return t.role!==void 0?jH(e,t.text,t.role):HH(e,t.text,t)}async function jH(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 Yg(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:s}}async function HH(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 FH(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 UE(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 jE=_(()=>{"use strict"});import{randomBytes as WH}from"crypto";import{mkdir as KH,stat as GH,writeFile as qH}from"fs/promises";import{join as Zg}from"path";import{gzip as zH}from"zlib";import{promisify as JH}from"util";function VH(e){return Zg(Ts(e),"browser")}function YH(e){return Zg(VH(e),"screenshots")}function XH(){return new Date().toISOString().replace(/[:.]/g,"-")}function ZH(){return WH(3).toString("hex")}async function Qg(e,t,n){if(t.length>HE)throw new Error(`writeScreenshotSidecar: buffer exceeds ${HE} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=YH(e);await KH(r,{recursive:!0});let o=`${XH()}-${ZH()}-${n}.png`,s=Zg(r,o);await qH(s,t);let{size:i}=await GH(s);return{path:s,bytes:i}}var Sue,HE,WE=_(()=>{"use strict";K();Wa();Sue=JH(zH);HE=5*1024*1024});var GE={};mc(GE,{PlaywrightProvider:()=>eh});function KE(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 eh,qE=_(()=>{"use strict";PE();BE();jE();Jg();Wa();WE();eh=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new ku(t)}async open(t){let n=zg(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 Eu(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 Eu(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 Xg(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${KE(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=Vg(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=zg(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 Eu(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 Xg(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${KE(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 Mo={};mc(Mo,{__resetBrowserRegistryForTests:()=>rW,browserProviderActive:()=>tW,closeBrowserProvider:()=>th,getBrowserProvider:()=>eW,peekBrowserProvider:()=>nW});function zE(){Promise.resolve(th()).then(()=>{process.exit(130)})}function JE(){Promise.resolve(th()).then(()=>{process.exit(143)})}function VE(){Rn=null}function QH(){Tu||(process.on("SIGINT",zE),process.on("SIGTERM",JE),process.on("exit",VE),Tu=!0)}function YE(){Tu&&(process.removeListener("SIGINT",zE),process.removeListener("SIGTERM",JE),process.removeListener("exit",VE),Tu=!1)}async function eW(e){return Rn!==null?Rn:(Po!==null||(Po=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(qE(),GE)),n=IE(e),r=new t(n);return QH(),Rn=r,Po=null,r})()),Po)}async function th(){if(Rn===null)return;let e=Rn;Rn=null,Po=null,YE(),await e.shutdown()}function tW(){return Rn!==null}function nW(){return Rn}function rW(){Rn=null,Po=null,YE()}var Rn,Po,Tu,Oo=_(()=>{"use strict";Jg();Rn=null,Po=null,Tu=!1});function XE(e,t){try{return RE(e,t)}catch(n){return z("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function lW(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Oo(),Mo));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function ZE(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??lW,o=null,s=e,i=null,a=null;try{let c=await n(e,{headers:aW,redirect:"follow",signal:t.signal});i=c.status,s=c.url||e;let u=c.headers.get("content-type")??"";if(c.ok){if(iW.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(sW.test(u)&&!oW.test(u))return{title:"",markdown:d.trim(),finalUrl:s,usedRender:!1};o=XE(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<xE)&&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=XE(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 oW,sW,iW,aW,QE=_(()=>{"use strict";CE();Me();oW=/(text\/html|application\/xhtml\+xml)/i,sW=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,iW=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,aW={"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 dW(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await t(cW,{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),uW),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let u=await s.text(),d=Ao(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 eT(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?dW({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 tT(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
1081
|
+
`).trim()}function dH(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function RE(e,t){let r=new lH(e,{url:t}).window.document,o=(r.title??"").trim(),s=null;try{let c=r.cloneNode(!0);s=new cH(c).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let c=TE(qg.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=TE(qg.turndown(a));return{title:o,markdown:l,textLength:dH(i),usedFallback:!0}}var xE,qg,CE=_(()=>{"use strict";xE=200,qg=new uH({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});qg.remove(["script","style","noscript","iframe"])});import{readFileSync as pH}from"node:fs";import{join as mH}from"path";function fH(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function AE(e,t){return fH(t).test(e)}function yH(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(gH.has(t))return!0;if(hH.has(t))return!1}return!1}function _E(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function bH(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 wH(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function SH(e){try{return pH(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function vH(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 IE(e){let t=e?.env??v,n=e?.readFileSync??SH,r=e?.surface??t.AGENT_SURFACE,o=yH(t.AFK_BROWSER_HEADLESS,r),s=_E(t.AFK_BROWSER_ALLOWED_DOMAINS),i=_E(t.AFK_BROWSER_BLOCKED_DOMAINS),a=wH(t.AFK_BROWSER_DOM_SNAPSHOTS),l=bH(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():mH(en(),"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=vH(c,m);return g.configPath=d,g}function zg(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(AE(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>AE(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var gH,hH,Jg=_(()=>{"use strict";q();K();gH=new Set(["daemon","subagent","telegram","afk"]),hH=new Set(["repl","interactive","cli"])});import kH from"node:fs";import EH from"node:path";import{chromium as TH}from"playwright";function xH(){try{return"5.9.0"}catch{}try{let e=EH.resolve(import.meta.dirname,"../../../package.json"),t=kH.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var RH,ku,PE=_(()=>{"use strict";RH=xH(),ku=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=TH.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/${RH}`}}}});import{createHash as CH}from"crypto";function Vg(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of AH)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function ME(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&_H.test(e.label))}function OE(e){return CH("sha256").update(e,"utf8").digest("hex").slice(0,8)}function $E(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var AH,_H,Wa=_(()=>{"use strict";AH=[{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}];_H=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as IH}from"node:crypto";function PH(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function MH(e,t,n){return`el_${IH("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function OH(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function DE(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function FE(e,t){let n=e.role??"",r=e.name??"";LE.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let s of e.children??[])FE(s,t)}async function $H(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},NE).catch(()=>[])}async function DH(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},NE).catch(()=>[])}function LH(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Eu(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],s=LH(e),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=$H(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=[],FE(d,b)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,b=(await DH(e)).filter(F=>LE.has(F.role??"")));let S=new Map;for(let P of p){let F=DE(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(DE(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=MH(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)),ME({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:PH(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=OH(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 LE,NE,BE=_(()=>{"use strict";Wa();LE=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);NE="a[href], button, input, select, textarea, [role], [tabindex], label"});async function UE(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 Yg(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,s)=>UE(e,s)))).filter(o=>o!==null)}async function FH(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 Xg(e,t,n){switch(t.kind){case"element_id":return NH(e,t,n);case"selector":return BH(e,t);case"semantic":return UH(e,t)}}async function NH(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 Yg(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function BH(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 Yg(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function UH(e,t){return t.role!==void 0?jH(e,t.text,t.role):HH(e,t.text,t)}async function jH(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 Yg(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:s}}async function HH(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 FH(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 UE(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 jE=_(()=>{"use strict"});import{randomBytes as WH}from"crypto";import{mkdir as KH,stat as GH,writeFile as qH}from"fs/promises";import{join as Zg}from"path";import{gzip as zH}from"zlib";import{promisify as JH}from"util";function VH(e){return Zg(Ts(e),"browser")}function YH(e){return Zg(VH(e),"screenshots")}function XH(){return new Date().toISOString().replace(/[:.]/g,"-")}function ZH(){return WH(3).toString("hex")}async function Qg(e,t,n){if(t.length>HE)throw new Error(`writeScreenshotSidecar: buffer exceeds ${HE} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=YH(e);await KH(r,{recursive:!0});let o=`${XH()}-${ZH()}-${n}.png`,s=Zg(r,o);await qH(s,t);let{size:i}=await GH(s);return{path:s,bytes:i}}var Sue,HE,WE=_(()=>{"use strict";K();Wa();Sue=JH(zH);HE=5*1024*1024});var GE={};mc(GE,{PlaywrightProvider:()=>eh});function KE(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 eh,qE=_(()=>{"use strict";PE();BE();jE();Jg();Wa();WE();eh=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new ku(t)}async open(t){let n=zg(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 Eu(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 Eu(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 Xg(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${KE(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=Vg(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=zg(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 Eu(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 Xg(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${KE(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 Mo={};mc(Mo,{__resetBrowserRegistryForTests:()=>rW,browserProviderActive:()=>tW,closeBrowserProvider:()=>th,getBrowserProvider:()=>eW,peekBrowserProvider:()=>nW});function zE(){Promise.resolve(th()).then(()=>{process.exit(130)})}function JE(){Promise.resolve(th()).then(()=>{process.exit(143)})}function VE(){Rn=null}function QH(){Tu||(process.on("SIGINT",zE),process.on("SIGTERM",JE),process.on("exit",VE),Tu=!0)}function YE(){Tu&&(process.removeListener("SIGINT",zE),process.removeListener("SIGTERM",JE),process.removeListener("exit",VE),Tu=!1)}async function eW(e){return Rn!==null?Rn:(Po!==null||(Po=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(qE(),GE)),n=IE(e),r=new t(n);return QH(),Rn=r,Po=null,r})()),Po)}async function th(){if(Rn===null)return;let e=Rn;Rn=null,Po=null,YE(),await e.shutdown()}function tW(){return Rn!==null}function nW(){return Rn}function rW(){Rn=null,Po=null,YE()}var Rn,Po,Tu,Oo=_(()=>{"use strict";Jg();Rn=null,Po=null,Tu=!1});function XE(e,t){try{return RE(e,t)}catch(n){return z("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function lW(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Oo(),Mo));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function ZE(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??lW,o=null,s=e,i=null,a=null;try{let c=await n(e,{headers:aW,redirect:"follow",signal:t.signal});i=c.status,s=c.url||e;let u=c.headers.get("content-type")??"";if(c.ok){if(iW.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(sW.test(u)&&!oW.test(u))return{title:"",markdown:d.trim(),finalUrl:s,usedRender:!1};o=XE(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<xE)&&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=XE(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 oW,sW,iW,aW,QE=_(()=>{"use strict";CE();Me();oW=/(text\/html|application\/xhtml\+xml)/i,sW=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,iW=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,aW={"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 dW(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await t(cW,{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),uW),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let u=await s.text(),d=Ao(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 eT(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?dW({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 tT(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 cW,uW,nT=_(()=>{"use strict";_o();cW="https://api.exa.ai/search",uW=10});function wW(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=pW;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,mW)}let a=fW;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,gW)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function nh(e,t){let n=Buffer.from(e,"utf8");return n.byteLength<=t?e:n.subarray(0,t).toString("utf8")+hW}function SW(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 bW.some(o=>r.includes(o))}function vW(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=wW(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:nh(p,s.maxBytes)}}if(s.mode==="markdown")try{let d=await ZE(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:nh(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=SW(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=eT({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:yW,timeoutMs:s.timeoutMs,signal:i.signal});return{content:nh(tT(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 pW,mW,fW,gW,hW,yW,bW,rT,oT=_(()=>{"use strict";QE();nT();pW=3e4,mW=12e4,fW=1e6,gW=1e7,hW=`
|
|
@@ -1119,11 +1119,11 @@ ${s}`:s}function nx(e,t){if(typeof e=="string")return e;if(!t.vision)return tx(e
|
|
|
1119
1119
|
${o}`:o}function LK(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 rx(e){let t=[],n=LK(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:DK(r.content)}:r):t}var ox=_(()=>{"use strict"});function BK(){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 sx(e,t){return e===t||e.includes(t)}function ix(e){if(!e)return!1;let t=(Eo(e)??e).trim();if(!t)return!1;let n=t.toLowerCase(),{enable:r,disable:o}=BK();return o.some(s=>sx(n,s))?!1:r.some(s=>sx(n,s))||FK.has(n)?!0:NK.some(s=>s.test(t))}var FK,NK,ax=_(()=>{"use strict";q();nn();FK=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"]),NK=[/^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 Rh(){return{assistantText:"",reasoningText:"",toolCallsByIndex:new Map,finishReason:null,usage:null,model:null,id:null}}function*lx(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 cx(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 Ch(e){return[...e.toolCallsByIndex.values()].sort((t,n)=>t.index-n.index)}function Ah(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 ux=_(()=>{"use strict"});function dx(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 px(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 mx(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 fx(e){return e.map(({call:t,result:n})=>({role:"tool",tool_call_id:t.id,content:n.isError?`[error] ${n.content}`:n.content}))}function gx(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 hx=_(()=>{"use strict"});function*yx(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":{_h(t,e),t.finishReason=t.toolCallsByIndex.size>0?"tool_calls":"stop";return}case"response.incomplete":{_h(t,e),t.finishReason=e.response?.incomplete_details?.reason??"incomplete";return}case"response.failed":{_h(t,e),t.finishReason="failed";return}default:return}}function _h(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 bx=_(()=>{"use strict"});function wx(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:UK(i.content)})}let o={input:r};n.length>0&&(o.instructions=n.join(`
|
|
1120
1120
|
|
|
1121
1121
|
`));let s=jK(t);return s.length>0&&(o.tools=s),o}function UK(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 jK(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 Sx=_(()=>{"use strict"});function kx(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 Ex(e){if(!e)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function WK(e){let t={"OpenAI-Beta":"responses=experimental",originator:"agent-afk"};return e&&(t["chatgpt-account-id"]=e),t}function Tx(e,t=!1){return e.source==="chatgpt-oauth"?{mode:"responses",baseURL:HK,headers:WK(e.accountId)}:t?{mode:"responses"}:{mode:"chat-completions"}}var HK,vx,xx=_(()=>{"use strict";HK="https://chatgpt.com/backend-api/codex",vx="You are a helpful assistant."});function KK(e){return(e.inputTokens??0)+(e.outputTokens??0)}function ti(e){return e.contextWindowTokens??KK(e)}function ed(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 Rx(e,t,n){return t<=0||e<=0||n<=0||n>=1?!1:e/t>=n}var Ih=_(()=>{"use strict"});import GK from"openai";import{randomUUID as Cx}from"node:crypto";function Dx(e){if(e===null||typeof e!="object")return;let t=e;return typeof t.status=="number"?t.status:void 0}function Ix(e){let t=Dx(e);return t===void 0?!1:$x.has(t)}function Px(e){let t=Dx(e);return t===void 0?!1:$x.has(t)}function nd(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 Lx(e,t){let n=Ja(e);return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):n}function JK(e,t){let n=Lx(e,t);return Fx(e)?{max_completion_tokens:n}:{max_tokens:n}}function Mx(e){return e??"default"}function Fx(e){let t=e.includes("/")?e.slice(e.lastIndexOf("/")+1):e;return/^o[0-9]/.test(t)}function VK(e){switch(e){case"low":return"low";case"medium":return"medium";case"high":case"xhigh":case"max":return"high"}}function Ox(e,t){if(e!==void 0&&Fx(t))return VK(e)}function YK(e){let t={apiKey:e.apiKey};return e.baseURL!==void 0&&(t.baseURL=e.baseURL),e.defaultHeaders!==void 0&&(t.defaultHeaders=e.defaultHeaders),new GK(t)}function XK(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 Nx(e,t,n={}){let r=Lo(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 Nx(e,t,n={}){let r=Lo(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=wt(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 rd(a)}var Ph,qK,$x,Ax,_x,td,zK,rd,Mh=_(()=>{"use strict";Ue();_a();Th();Va();Xn();In();xh();Me();Za();ox();ax();ux();hx();bx();Sx();xx();q();Ih();eg();ng();Ph="openai-compatible",qK=50,$x=new Set([429,500,502,503,529]),Ax=3,_x=3,td=2e3;zK=null;rd=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=Mx(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=dx(o.toolDefs))}let n=(t.useResponsesApi??!1)||Ex(v.AFK_OPENAI_USE_RESPONSES),r=Tx(t.auth,n);if(this.wireMode=r.mode,t.auth.apiKey===null)this.client=null;else{let o=zK??YK,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:Ph}},this.opts.auth.apiKey===null){yield{type:"error",error:new Error(Xa(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=Cx();Le(this.traceWriter,{phase:"loop_start"});try{yield*this._runTurnInner(t,n,r,o)}finally{Le(this.traceWriter,{phase:"loop_end",durationMs:Date.now()-r})}}async*_runTurnInner(t,n,r,o){let s=ix(this.currentModel);this.priorTurns.push({role:"user",content:nx(t,{vision:s,model:this.currentModel})});let i={stopReason:null,resultSubtype:"success",isError:!1},a="",l="";for(let c=0;c<qK;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=cx(u.state);if(i=za(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=Ch(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=rx({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"?tg: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&&kx(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=wx(r,this.openAITools),i={model:this.currentModel,input:s.input,stream:!0};o||(i.max_output_tokens=Lx(this.currentModel,this.opts.config.maxOutputTokens));let a=s.instructions??(o?vx:void 0);a!==void 0&&(i.instructions=a),o&&(i.store=!1),s.tools&&s.tools.length>0&&(i.tools=s.tools);let l=Ox(this.opts.config.effort,this.currentModel);l!==void 0&&(i.reasoning={effort:l});let c=0;for(;;){let u=Rh(),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(Ix(y)&&b<Ax){let S=td*Math.pow(2,b);if(await nd(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 yx(b,u,this.initSessionId))h||(h=!0,Le(this.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-d,resolvedModel:this.currentModel})),yield y}}catch(b){if(t.signal.aborted)return null;if(Px(b)&&c<_x){if(c++,yield{type:"stream.retry",sessionId:this.initSessionId},await nd(td*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:Ah(u)&&u.toolCallsByIndex.size>0}}}else{let o={model:this.currentModel,messages:r,stream:!0,stream_options:{include_usage:!0}};Object.assign(o,JK(this.currentModel,this.opts.config.maxOutputTokens)),this.openAITools&&this.openAITools.length>0&&(o.tools=this.openAITools);let s=Ox(this.opts.config.effort,this.currentModel);s!==void 0&&(o.reasoning_effort=s);let i=0;for(;;){let a=Rh(),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(Ix(g)&&m<Ax){let h=td*Math.pow(2,m);if(await nd(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 lx(m,a,this.initSessionId))p||(p=!0,Le(this.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-l,resolvedModel:this.currentModel})),yield g}}catch(m){if(t.signal.aborted)return null;if(Px(m)&&i<_x){if(i++,yield{type:"stream.retry",sessionId:this.initSessionId},await nd(td*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:Ah(a)&&a.toolCallsByIndex.size>0}}}}async*dispatchAndAppend(t,n,r){if(!this.toolDispatcher)return;let o=Ch(t);for(let u of o)u.id.length===0&&(u.id=Cx());let{calls:s,parseErrors:i}=px(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:XK(u.name,u.input),toolInputRaw:Qu(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(mx(t.assistantText,o,t.reasoningText));for(let u of fx(l))this.priorTurns.push(u);let c=gx(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(mx(t.assistantText,o,t.reasoningText));for(let u of fx(l))this.priorTurns.push(u);let c=gx(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=wt(t)??t)}async setPermissionMode(t){this.currentPermissionMode=Mx(t);let n=Sn(this.currentPermissionMode);this.toolDispatcher?.setAllowAll?.(n),this.onPermissionMode?.(this.currentPermissionMode)}setCwd(t){this.toolDispatcher?.setResolveBase?.(t)}async supportedCommands(){try{return pr().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=$t(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}=ed(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:`${Ph} 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} ${Ph}: closed`)}}});import ZK from"openai";async function Bx(e){let{apiKey:t,baseURL:n,model:r,system:o,user:s,maxTokens:i=64,signal:a,clientFactory:l}=e,c=Lo(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??QK,p=d?d(u):new ZK(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 QK,Ux=_(()=>{"use strict";Za();QK=null});import Oh from"path";import{appendFileSync as eG,mkdirSync as tG}from"fs";import{dirname as nG}from"path";var $h,Dt,rG,Qa=_(()=>{"use strict";K();Yc();Qc();Fa();_a();Sh();Yu();En();cn();Mh();Ux();xn();jr();Za();Mh();$h="openai-compatible",Dt=class{name=$h;providerOpts;memoryStore;schemas;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_presenceSessionId=null;constructor(t={}){this.providerOpts=t,this.memoryStore=t.memoryStore??new lt;let n=[...tr];t.subagentExecutor&&n.push(xo),t.skillExecutor&&n.push(Ro),t.composeExecutor&&n.push(Co),t.readOnlyMemory===!0?n.push(Bs):n.push(...Mr),n.push(Tn);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=Oa({surface:this.providerOpts.surface??"cli",cwd:n.cwd??process.cwd(),modelName:s,providerName:$h,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 It?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?$a(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();Da({sessionId:m,surface:this.providerOpts.surface??"cli",actor:_n(n.depth),cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:$h,name:s},workspace:g,pid:process.pid}),process.once("exit",()=>{rr(m)}),process.once("SIGINT",()=>{rr(m),process.exit(130)}),process.once("SIGTERM",()=>{rr(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 Nx(p,t.prompt,a)}buildDispatcher(t,n){let r=qu(t,n.cwd),o=Ma(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(Do,Vu(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?[Ju]:[]],hookRegistry:Vc(n.hookRegistry,this.providerOpts.hookRegistry)},c=Zc(this.providerOpts.mcpManager?Xc(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),this.providerOpts.canUseTool!==void 0&&(l.canUseTool=this.providerOpts.canUseTool),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=Sn(t),new It(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=Oh.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=Oh.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=Oh.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:Sn(this._currentPermissionMode)}}appendProviderAuditLog(t){try{let n=Es();tG(nG(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:t.sessionId??null,action:t.action,path:t.path,source:t.source});eG(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),Bx(n)}},rG=new Dt});function Hr(e,t){if(e.has(t))return!0;let n=t.charAt(0).toUpperCase()+t.slice(1);return n!==t&&e.has(n)}function Pn(e){return e.startsWith("mcp__")||e.startsWith("MCP__")?"mcp":Hr(oG,e)?"read":Hr(sG,e)?"write":Hr(iG,e)?"shell":Hr(Wr,e)?"subagent":Hr(el,e)?"skill":Hr(tl,e)?"dag":Hr(aG,e)?"web":lG.has(e)?"browser":Hr(cG,e)?"planning":uG.has(e)?"schedule":"other"}function Dh(e){return dG[e]}var oG,sG,iG,Wr,el,tl,Ze,aG,lG,cG,uG,jx,dG,nl=_(()=>{"use strict";bg();oG=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search"]),sG=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","memory_update","procedure_write","terminal_font_size","config_set"]),iG=new Set(["Bash","BashOutput","KillBash","bash"]),Wr=new Set(["Agent","Task","agent"]),el=new Set(["Skill","skill"]),tl=new Set(["Compose","compose"]),Ze=new Set([...Wr,...tl,...el]),aG=new Set(["WebFetch","WebSearch","send_telegram","web_scrape"]),lG=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),cG=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),uG=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);jx=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search",...ft];dG={subagent:"subagent",skill:"skill",dag:"dag"}});function od(e){let t=pG(e);return t!==void 0?t:mG(e)}function pG(e){let t=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=t.exec(e))!==null;)n=r[1];if(n)return Hx(n.trim())}function mG(e){for(let t=e.length-1;t>=0;t--){if(e[t]!=="}")continue;let n=fG(e,t);if(n===-1)continue;let r=e.slice(n,t+1),o=Hx(r);if(o!==void 0)return o}}function fG(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 Hx(e){try{return JSON.parse(e)}catch{return}}var Lh=_(()=>{"use strict"});import{z as Kr}from"zod";function bG(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=Wx(r.trim());if(Kx(o))return o}for(let r=0;r<e.length;r++){if(e[r]!=="{"||wG(e,r))continue;let o=SG(e,r);if(o===-1)continue;let s=e.slice(r,o+1),i=Wx(s);if(Kx(i))return i;r=o}}function wG(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 Nx(p,t.prompt,a)}buildDispatcher(t,n){let r=qu(t,n.cwd),o=Ma(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 ot.stat(r);return i>=y.size}catch{return!0}}if(o)yield*u();else try{i=(await ot.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 kG}from"node:events";import*as Gr from"node:fs/promises";import*as Zx from"node:path";import{createHash as EG}from"node:crypto";function Fh(e){je(e).catch(()=>{})}var TG,Yx,Xx,xG,ol,ld,Nh=_(()=>{"use strict";Jt();Me();Ue();ad();K();Qn();TG=300*1e3,Yx=4096;Xx=5e3,xG=10,ol=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"}},ld=class extends kG{jobs=new Map;counter=Math.floor(Math.random()*65536);traceWriter;maxConcurrentJobs;constructor(t={}){super(),this.traceWriter=t.traceWriter,this.maxConcurrentJobs=t.maxConcurrentJobs??xG,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,sd(t.handle.id,"failed",i,rl()),o,s)}),this.snapshot(n)}createJobEntry(t){let n=[...this.jobs.values()].filter(d=>d.status==="running").length;if(n>=this.maxConcurrentJobs)throw new ol(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 id(r),u={jobId:r,subagentId:t.handle.id,label:o,promptHash:EG("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 ${Xx}ms \u2014 continuing teardown`),o()},Xx).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<=Yx?r.transcriptTail=o:r.transcriptTail=o.slice(o.length-Yx)}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")}),Fh({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"}),Fh({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"}),Fh({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)},TG).unref()}async _sweepOldJobs(){let n=ka(),r;try{r=await Gr.readdir(n)}catch{return}for(let o of r){let s=bo(o),i=Zx.join(s,"meta.json");try{if(!(await Gr.lstat(s)).isDirectory()){process.stderr.write(`[afk] bg sweep: skipping non-directory entry ${o}
|
|
1142
1142
|
`);continue}let l=await Gr.readFile(i,"utf8"),c=JSON.parse(l);if(c.status==="running"||c.endedAt===void 0||Date.now()-c.endedAt<6048e5)continue;await Gr.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 RG(e){return typeof e=="string"&&e.startsWith("sk-ant-")}function sl(e){let{childModel:t,resolved:n,parentApiKey:r}=e;return n!==void 0&&n.length>0||re(t)==="openai-compatible"?n:RG(r)?r:n}var Bh=_(()=>{"use strict";rt()});import{isAbsolute as CG}from"node:path";function AG(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(!CG(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 cd(e){try{return je(e).catch(()=>{})}catch{return Promise.resolve()}}function ri(e,t=240){return e.length<=t?e:e.slice(0,t)+"\u2026"}function eR(e){if(e!=null){if(typeof e=="string")return e.length;try{return JSON.stringify(e).length}catch{return}}}function IG(e){if(e==null)return;let t=eR(e);return t!==void 0&&t>_G?{truncated:!0,chars:t}:e}function PG(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=IG(e.partialOutput);return n!==void 0&&(t.partialOutput=n),t}var _G,Qx,On,il=_(()=>{"use strict";Qe();Nh();rt();Bh();Ks();qr();Qn();Me();_o();jr();qr();_G=4096,Qx=1024;On=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=AG(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:Ur(this.ctx.surface),actor:_n(r)}:{},a=n.model??this.ctx.defaultSubagentModel??"sonnet",l=re(a)==="openai-compatible",c=sl({childModel:a,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(a):ar(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=Fo(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"?or(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":or(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 cd({...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 ol)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 cd({...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;cd({...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:eR(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=PG({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 cd({...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 ud(e,t){return`Skill tool not available at nesting depth ${e} (max ${t}). ${si}`}var si,Uh=_(()=>{"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 nR(e){tR.add(e)}function rR(e){return tR.has(e)}var tR,jh=_(()=>{"use strict";tR=new Set});function oR(e){Hh.add(e)}function sR(e){Hh.delete(e)}function iR(e){Wh.add(e)}function aR(e){Wh.delete(e)}function lR(e){for(let t of Hh)t(e)}function cR(e){for(let t of Wh)t(e)}var Hh,Wh,Kh=_(()=>{"use strict";Hh=new Set,Wh=new Set});function uR(e){return MG.has(e)}function $G(e,t=OG){return e.length<=t?e:e.slice(0,t)+"\u2026"}function DG(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 LG(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 MG,OG,$n,al=_(()=>{"use strict";St();Qe();In();qr();il();Uh();Bh();Ks();er();rn();Qn();jh();Kh();Me();jr();MG=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"]);OG=240;$n=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:Ur(this.ctx.surface),actor:_n(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=DG(t.input);return je({...this.sessionIdentity(),event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:l}).catch(()=>{}),{content:ud(n,r),isError:!0}}let o;try{o=LG(t.input)}catch(l){return{content:`Skill tool input validation failed: ${l instanceof Error?l.message:String(l)}`,isError:!0}}try{let l=Ge(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||Gh.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=pr(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=rR(t.name);o&&cR(t.name);let s=this.ctx.depth??0;je({...this.sessionIdentity(),event:"skill.dispatched",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...uR(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&&lR({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;je({...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:$G(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=>dd.includes(m)):r?[...dd]:o,c=r;if(!this.ctx.childProviderFactory||s>=i)return r?a.provider=dR(a.model):l!==void 0&&(a.provider=pR(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 On({subagentManager:u,parentSession:Fo(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||Gh.has(t.name),s;try{if(s=We(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=sl({childModel:i,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(i):ar(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:Wt(),...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 RG(e){return typeof e=="string"&&e.startsWith("sk-ant-")}function sl(e){let{childModel:t,resolved:n,parentApiKey:r}=e;return n!==void 0&&n.length>0||re(t)==="openai-compatible"?n:RG(r)?r:n}var Bh=_(()=>{"use strict";rt()});import{isAbsolute as CG}from"node:path";function AG(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(!CG(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 cd(e){try{return je(e).catch(()=>{})}catch{return Promise.resolve()}}function ri(e,t=240){return e.length<=t?e:e.slice(0,t)+"\u2026"}function eR(e){if(e!=null){if(typeof e=="string")return e.length;try{return JSON.stringify(e).length}catch{return}}}function IG(e){if(e==null)return;let t=eR(e);return t!==void 0&&t>_G?{truncated:!0,chars:t}:e}function PG(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=IG(e.partialOutput);return n!==void 0&&(t.partialOutput=n),t}var _G,Qx,On,il=_(()=>{"use strict";Qe();Nh();rt();Bh();Ks();qr();Qn();Me();_o();jr();qr();_G=4096,Qx=1024;On=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=AG(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:Ur(this.ctx.surface),actor:_n(r)}:{},a=n.model??this.ctx.defaultSubagentModel??"sonnet",l=re(a)==="openai-compatible",c=sl({childModel:a,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(a):ar(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=Fo(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"?or(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":or(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 cd({...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 ol)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 cd({...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;cd({...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:eR(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=PG({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 cd({...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 ud(e,t){return`Skill tool not available at nesting depth ${e} (max ${t}). ${si}`}var si,Uh=_(()=>{"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 nR(e){tR.add(e)}function rR(e){return tR.has(e)}var tR,jh=_(()=>{"use strict";tR=new Set});function oR(e){Hh.add(e)}function sR(e){Hh.delete(e)}function iR(e){Wh.add(e)}function aR(e){Wh.delete(e)}function lR(e){for(let t of Hh)t(e)}function cR(e){for(let t of Wh)t(e)}var Hh,Wh,Kh=_(()=>{"use strict";Hh=new Set,Wh=new Set});function uR(e){return MG.has(e)}function $G(e,t=OG){return e.length<=t?e:e.slice(0,t)+"\u2026"}function DG(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 LG(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 MG,OG,$n,al=_(()=>{"use strict";vt();Qe();In();qr();il();Uh();Bh();Ks();er();rn();Qn();jh();Kh();Me();jr();MG=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"]);OG=240;$n=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:Ur(this.ctx.surface),actor:_n(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=DG(t.input);return je({...this.sessionIdentity(),event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:l}).catch(()=>{}),{content:ud(n,r),isError:!0}}let o;try{o=LG(t.input)}catch(l){return{content:`Skill tool input validation failed: ${l instanceof Error?l.message:String(l)}`,isError:!0}}try{let l=Ge(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||Gh.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=pr(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=rR(t.name);o&&cR(t.name);let s=this.ctx.depth??0;je({...this.sessionIdentity(),event:"skill.dispatched",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...uR(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&&lR({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;je({...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:$G(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=>dd.includes(m)):r?[...dd]:o,c=r;if(!this.ctx.childProviderFactory||s>=i)return r?a.provider=dR(a.model):l!==void 0&&(a.provider=pR(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 On({subagentManager:u,parentSession:Fo(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||Gh.has(t.name),s;try{if(s=We(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=sl({childModel:i,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(i):ar(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:Wt(),...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}:{}};je({event:"skill.dispatched",...i,...uR(t)?{is_gate:!0}:{}}).catch(()=>{}),je({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=We(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=sl({childModel:l,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(l):ar(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:Wt(),...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=pd(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 Fo(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??FG},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{}};return re(typeof r=="string"?r:void 0)==="openai-compatible"?new Dt({...i,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{},readOnlyMemory:!0}):new qe({...i,readOnlyMemory:!0})}}function dR(e){let t={allowedTools:[...dd]};return re(typeof e=="string"?e:void 0)==="openai-compatible"?new Dt({permissions:t,readOnlyBash:!0,readOnlyMemory:!0}):new qe({permissions:t,readOnlyBash:!0,readOnlyMemory:!0})}function ai(e,t,n,r,o,s,i,a,l){let c=(u,d,p)=>new $n({parentSession:Fo(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 pR(e,t){let n={allowedTools:[...e]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new Dt({permissions:n}):new qe({permissions:n})}function mR(e,t){let n={allowedTools:[...jx]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new Dt({permissions:n}):new qe({permissions:n})}var oi,FG,dd,Gh,qr=_(()=>{"use strict";No();Qa();rt();En();xn();nl();al();oi=3;FG=[...Kt,...ft,"memory_search","agent","skill"],dd=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...ft,"memory_search","agent","skill"],Gh=new Set(["ground-state"])});var md,fR=_(()=>{"use strict";Me();zc();er();Jc();Ue();Jt();md=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=rl();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=qc(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",vo(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?(vo(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(vo(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=rl();let s=n??this.progressSink??Wt(),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 zx(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=sd(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??Wt();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",vo(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 ek(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 NG,se,Qe=_(()=>{"use strict";Xv();li();zc();Jc();Ue();Qn();er();qr();fR();NG=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 Kc(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 Qv(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:NG},...t.phaseRole==="read-only"?{provider:mR("read-only",t.config.model)}:{}},a;try{a=new vt(i)}catch(h){throw this.abortGraph.dispose(n),h}let l=t.parent.getInputStreamRef?.(),c=t.parent.abortSignal,u=this.progressSink??Wt(),d=t.agentType?.trim()||void 0,p=t.parentId?.trim()||void 0,m=new md(n,a,s,this.abortGraph,t.outputSchema,t.config.timeoutMs??Gc,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 vo(t.config.traceWriter,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:g,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await je({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 fd(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 qh=_(()=>{"use strict"});import{fileURLToPath as BG}from"node:url";import{dirname as UG}from"node:path";var jG,cge,Vt,zh=_(()=>{"use strict";jG=BG(import.meta.url),cge=UG(jG),Vt={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=pd(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 Fo(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??FG},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{}};return re(typeof r=="string"?r:void 0)==="openai-compatible"?new Dt({...i,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{},readOnlyMemory:!0}):new qe({...i,readOnlyMemory:!0})}}function dR(e){let t={allowedTools:[...dd]};return re(typeof e=="string"?e:void 0)==="openai-compatible"?new Dt({permissions:t,readOnlyBash:!0,readOnlyMemory:!0}):new qe({permissions:t,readOnlyBash:!0,readOnlyMemory:!0})}function ai(e,t,n,r,o,s,i,a,l){let c=(u,d,p)=>new $n({parentSession:Fo(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 pR(e,t){let n={allowedTools:[...e]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new Dt({permissions:n}):new qe({permissions:n})}function mR(e,t){let n={allowedTools:[...jx]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new Dt({permissions:n}):new qe({permissions:n})}var oi,FG,dd,Gh,qr=_(()=>{"use strict";No();Qa();rt();En();xn();nl();al();oi=3;FG=[...Kt,...ft,"memory_search","agent","skill"],dd=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...ft,"memory_search","agent","skill"],Gh=new Set(["ground-state"])});var md,fR=_(()=>{"use strict";Me();zc();er();Jc();Ue();Jt();md=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=rl();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=qc(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",vo(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?(vo(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(vo(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=rl();let s=n??this.progressSink??Wt(),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 zx(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=sd(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??Wt();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",vo(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 ek(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 NG,se,Qe=_(()=>{"use strict";Xv();li();zc();Jc();Ue();Qn();er();qr();fR();NG=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 Kc(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 Qv(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:NG},...t.phaseRole==="read-only"?{provider:mR("read-only",t.config.model)}:{}},a;try{a=new kt(i)}catch(h){throw this.abortGraph.dispose(n),h}let l=t.parent.getInputStreamRef?.(),c=t.parent.abortSignal,u=this.progressSink??Wt(),d=t.agentType?.trim()||void 0,p=t.parentId?.trim()||void 0,m=new md(n,a,s,this.abortGraph,t.outputSchema,t.config.timeoutMs??Gc,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 vo(t.config.traceWriter,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:g,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await je({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 fd(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 qh=_(()=>{"use strict"});import{fileURLToPath as BG}from"node:url";import{dirname as UG}from"node:path";var jG,cge,Vt,zh=_(()=>{"use strict";jG=BG(import.meta.url),cge=UG(jG),Vt={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 _R(H,L),R++}}let k=yn();await AR(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=Zh(k,"audit-fit-telemetry.jsonl");return await _R(F,JSON.stringify(P)+`
|
|
1238
|
-
`),{inventory:x,misfits:C,briefs_written:R,total_artifacts:T.length}}var PR,IR,Lge,r2,o2,MR,p2,OR=_(()=>{"use strict";rn();
|
|
1238
|
+
`),{inventory:x,misfits:C,briefs_written:R,total_artifacts:T.length}}var PR,IR,Lge,r2,o2,MR,p2,OR=_(()=>{"use strict";rn();vt();Qe();qh();zh();K();CR();PR=Fe.object({path:Fe.string(),type:Fe.enum(["skill","command","agent","hook"]),source:Fe.enum(["user","plugin"]),plugin_key:Fe.string().optional(),verdict:Fe.enum(["correct","misfit","outlier"]),recommended_type:Fe.string(),rationale:Fe.string(),confidence:Fe.enum(["high","med","low"])}),IR=Fe.record(Fe.string(),Fe.record(Fe.string(),Fe.number())),Lge=Fe.object({inventory:Fe.object({user:IR,plugin:IR}),misfits:Fe.array(PR),briefs_written:Fe.number(),total_artifacts:Fe.number()}),r2=Fe.object({writeBriefs:Fe.boolean().optional(),scope:Fe.enum(["user","plugin","all"]).optional()}),o2=["skill","command","agent"],MR=["skill","command","agent","hook"];p2={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:d2,argumentHint:"[--write-briefs]",whenToUse:"When the user wants ~/.afk artifacts (skills, commands, agents, hooks) audited for correct type categorization.",flags:["--write-briefs"],audience:"internal"};At(p2)});import{z as ee}from"zod";var yd,$R,bd,DR,LR,FR,m2,NR,wd=_(()=>{"use strict";yd=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)}),$R=ee.object({hypothesis_id:ee.string(),claim:ee.string(),verdict:ee.enum(["VERIFIED","REFUTED","INCONCLUSIVE"]),evidence:ee.string(),gate_reason:ee.string()}),bd=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()}),DR=ee.enum(["crash","regression","logic-error","flaky","environment","unknown"]),LR=ee.object({failure_type:DR,error_signature:ee.string(),affected_area:ee.string()}),FR=ee.enum(["clear_winner","multiple_plausible","dissent","all_inconclusive","no_hypotheses"]),m2=ee.object({reproducer:ee.string().optional(),triage:LR.optional(),hypotheses:ee.array(yd),premise_verifications:ee.array($R).optional(),winner:ee.object({hypothesis_id:ee.string(),verification_log:ee.string(),proposed_fix:ee.string()}).optional(),verification_results:ee.array(bd).optional(),outcome:FR.optional(),recommended_next_skill:ee.enum(["spec"]).optional()}),NR=ee.object({verifications:ee.array(ee.object({claim:ee.string().optional(),verdict:ee.string(),evidence:ee.string().optional()}))})});function Qh(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 ey(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 ty(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 ny=_(()=>{"use strict"});function BR(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 UR=_(()=>{"use strict"});import{execFile as f2}from"node:child_process";import{promisify as g2}from"node:util";function y2(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 b2(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 ry(e){let t=b2(e);for(let n of t){let r;try{r=JSON.parse(n)}catch{continue}let o=NR.safeParse(r);if(o.success)return o.data.verifications.map(s=>({claim:s.claim??"",verdict:y2(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 Sd(e,t){return e.length<=t?e:`...[truncated]
|
|
@@ -1286,10 +1286,10 @@ ${JSON.stringify(k.git,null,2)}
|
|
|
1286
1286
|
|
|
1287
1287
|
Original failure: ${s.failure}`,P;try{P=await $.runToResult(A)}finally{await $.teardown().catch(()=>{})}if(P.status!=="succeeded"||!P.output){if(P.schemaError){let X=P.message?.content||"(no response)";throw new Error(`hypothesis synthesis schema mismatch: ${P.schemaError.message}
|
|
1288
1288
|
Raw response (first 500 chars): ${X.slice(0,500)}
|
|
1289
|
-
Hint: model response must include a fenced JSON block with a hypotheses array.`)}throw new Error(`hypothesis synthesis failed: ${ut(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 iy(F,async X=>{if(!n?.dispatchSkill)throw new Error("shadow-verify dispatch unavailable (no dispatchSkill in ctx)");let
|
|
1289
|
+
Hint: model response must include a fenced JSON block with a hypotheses array.`)}throw new Error(`hypothesis synthesis failed: ${ut(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 iy(F,async X=>{if(!n?.dispatchSkill)throw new Error("shadow-verify dispatch unavailable (no dispatchSkill in ctx)");let me=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>"}]}`}),J=await n.dispatchSkill("shadow-verify",
|
|
1292
|
+
{"verifications":[{"claim":"<echo of the claim>","verdict":"VERIFIED|REFUTED|INCONCLUSIVE","evidence":"<1-2 sentences; cite file:line or source>"}]}`}),J=await n.dispatchSkill("shadow-verify",me);return ry(J)});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 oy(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=>_2(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,me)=>me.confidence-X.confidence)[0]??I.find(X=>X.predicted_pass),j=ty(F,I),Y=M?F.find(X=>X.id===M.hypothesis_id):void 0,oe=j==="clear_winner"&&Y&&ey(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 vd,JR,YR=_(()=>{"use strict";rn();Qe();qh();Jt();zh();HR();KR();wd();ny();ay();vd=T2(E2);JR=[...Vt.allowedTools,"Agent"]});var I2,XR=_(()=>{"use strict";wd();ny();ay();YR();vt();I2={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:VR,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."};At(I2)});async function P2(){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 M2,ZR=_(()=>{"use strict";vt();M2={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:P2,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."};At(M2)});function O2(){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
|
${$2}
|
|
1447
1447
|
|
|
1448
|
-
${r}`}function di(){let e=O2(),t=_t(),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:D2(e,n),source:i}}function Ce(){let e=v.AFK_MODEL??v.CLAUDE_MODEL;return ze(e)}function kd(){return Pg()}function ze(e){return ar(e)}function
|
|
1448
|
+
${r}`}function di(){let e=O2(),t=_t(),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:D2(e,n),source:i}}function Ce(){let e=v.AFK_MODEL??v.CLAUDE_MODEL;return ze(e)}function kd(){return Pg()}function ze(e){return ar(e)}function Et(){let e=v.AFK_MODEL??v.CLAUDE_MODEL;return!e||e.length===0?"sonnet":e}function Yt(e){let t=v.AFK_DEFAULT_SUBAGENT_MODEL;return t&&t.length>0?t:typeof e=="string"&&re(e)==="openai-compatible"?e:"sonnet"}function Yr(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 Xr(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 Yr(v.AFK_THINKING)}function mi(){return Xr(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 ly(){return fi(v.AFK_MAX_BUDGET_USD)}function cy(){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 ul(){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(!eC.includes(n))throw new Error(`Invalid --provider value: ${n}. Expected one of: ${eC.join(", ")}`);let r=()=>{let o=[...Kt,...nr,...ft,Do];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 qe({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 Dt({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 $2,QR,eC,Je=_(()=>{"use strict";rt();Qa();En();cn();xn();Yu();Ot();Ks();q();$2=`# 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"];eC=["anthropic","anthropic-direct","openai-codex","openai","openai-compatible"]});async function tC(e,t,n,r,o="sonnet"){let i=We("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:Ce()},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: ${ut(c)}`);return c.message.content}var nC=_(()=>{"use strict";Qe();Jt();Je();rn()});async function rC(e,t,n,r,o="sonnet"){let i=We("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:Ce()},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: ${ut(d)}`);return d.message.content}var iC=_(()=>{"use strict";Qe();Jt();Je();rn()});function L2(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 aC(e,t,n,r="sonnet"){if(L2(e)<3)return{kind:"skipped",reason:"too-few-files"};let s=!1;try{let i=Ge("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=pd().get("parallelize");if(!a)return{kind:"skipped",reason:"skill-body-missing"};let l=new se({parentAbortSignal:t.abortSignal,apiKey:Ce(),...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 lC=_(()=>{"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: ${ut(d)}`);return d.message.content}var iC=_(()=>{"use strict";Qe();Jt();Je();rn()});function L2(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 aC(e,t,n,r="sonnet"){if(L2(e)<3)return{kind:"skipped",reason:"too-few-files"};let s=!1;try{let i=Ge("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=pd().get("parallelize");if(!a)return{kind:"skipped",reason:"skill-body-missing"};let l=new se({parentAbortSignal:t.abortSignal,apiKey:Ce(),...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 lC=_(()=>{"use strict";vt();In();Qe();Je()});function yi(e){let t=Wt();t&&t({type:"panel",spec:e},{subagentId:"__main__"})}var Ed=_(()=>{"use strict";er()});import{z as hr}from"zod";async function cC(e,t,n,r,o,s="sonnet"){let a=We("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:Ce()},idPrefix:"mint-build",outputSchema:F2,...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: ${ut(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 Td(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 pC=_(()=>{"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: ${ut(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 Td(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 pC=_(()=>{"use strict";vt();Qe();Jt();Je();rn();dy()});async function mC(e,t,n,r,o="sonnet"){let i=We("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:Ce()},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: ${ut(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 fC=_(()=>{"use strict";Qe();Jt();Je();rn();Ed()});import{existsSync as gC,mkdirSync as B2,readFileSync as U2,unlinkSync as j2,writeFileSync as H2}from"fs";import{dirname as W2,join as K2}from"path";function py(e){return K2(Jn(),e,"mint-state.json")}function hC(e,t){let n=py(e);B2(W2(n),{recursive:!0}),H2(n,JSON.stringify(t,null,2),"utf-8")}function G2(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 yC(e){let t=py(e);if(!gC(t))return null;try{let n=JSON.parse(U2(t,"utf-8"));return G2(n)?n:null}catch{return null}}function my(e){let t=py(e);if(gC(t))try{j2(t)}catch{}}var bC=_(()=>{"use strict";K()});function Dn(e,t,n){e.history.push({phase:t,output:n,timestamp:Date.now()})}function EC(e){if("completed"in e&&"paused"in e)throw new Error("mint: invariant violation \u2014 MintResult carries both completed and paused keys simultaneously")}function J2(e){return e.length<=SC?e:e.slice(0,SC)+"\u2026"}function TC(e){if(typeof e=="string"){if(wC.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 TC(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&&wC.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 vC(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 rC(e.spec,o,s,n,r),Dn(e,"research",e.research),e.currentPhase="plan",e.plan=await sC(e.spec,e.research,o,s,n,r),Dn(e,"plan",e.plan),e.currentPhase="parallelize";let i=await aC(e.plan,t,n,r);if(i.kind==="plan")e.waveOrchestrationPlan=i.plan,Dn(e,"parallelize",JSON.stringify(i.plan));else if(i.kind==="skipped")e.waveOrchestrationPlan=void 0,Dn(e,"parallelize",`skipped: ${i.reason}`);else if(i.kind==="failed"){e.waveOrchestrationPlan=void 0;let c=J2(i.error);Dn(e,"parallelize",`failed: ${c}`),je({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 cC(e.plan,e.waveOrchestrationPlan,o,s,n,r),Dn(e,"build",JSON.stringify(e.buildResults)),e.currentPhase="verify",e.verifyResults=await Td(e.plan,e.buildResults,o,s,n,r),Dn(e,"verify",JSON.stringify(e.verifyResults)),e.currentPhase="heal";let a=e.verifyResults.testsPassed&&e.verifyResults.lintPassed&&e.verifyResults.designReviewPassed;for(;!a&&e.healIterations<q2;){let c=await dC(e.plan,e.buildResults,e.verifyResults,e.healIterations,t,n,r);e.healIterations=c.newHealIterations,e.verifyResults=c.newVerifyResults,a=c.healed,Dn(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 mC(e,o,s,n,r);return Dn(e,"ship",l),{completed:!0,artifact:l,state:e}}catch(i){throw new Error(`mint failed at ${e.currentPhase}: ${i}`)}}function kC(e,t){return EC(t),("completed"in t||t.phase==="heal-failed")&&my(e),t}async function V2(e,t,n){let r=TC(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??yC(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 vC(c,t,s,i);return kC(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.");my(o);let a={currentPhase:"spec",idea:r.idea,healIterations:0,history:[]};try{a.spec=await tC(r.idea,o,t.cwd,s,i),Dn(a,"spec",a.spec)}catch(c){throw new Error(`mint failed at spec: ${c}`)}if(!r.autoApprove){hC(o,a);let c={paused:!0,phase:"spec",spec:a.spec,state:a,nextStep:z2};return EC(c),c}let l=await vC(a,t,s,i);return kC(o,l)}var q2,wC,z2,SC,Y2,xC=_(()=>{"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: ${ut(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 fC=_(()=>{"use strict";Qe();Jt();Je();rn();Ed()});import{existsSync as gC,mkdirSync as B2,readFileSync as U2,unlinkSync as j2,writeFileSync as H2}from"fs";import{dirname as W2,join as K2}from"path";function py(e){return K2(Jn(),e,"mint-state.json")}function hC(e,t){let n=py(e);B2(W2(n),{recursive:!0}),H2(n,JSON.stringify(t,null,2),"utf-8")}function G2(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 yC(e){let t=py(e);if(!gC(t))return null;try{let n=JSON.parse(U2(t,"utf-8"));return G2(n)?n:null}catch{return null}}function my(e){let t=py(e);if(gC(t))try{j2(t)}catch{}}var bC=_(()=>{"use strict";K()});function Dn(e,t,n){e.history.push({phase:t,output:n,timestamp:Date.now()})}function EC(e){if("completed"in e&&"paused"in e)throw new Error("mint: invariant violation \u2014 MintResult carries both completed and paused keys simultaneously")}function J2(e){return e.length<=SC?e:e.slice(0,SC)+"\u2026"}function TC(e){if(typeof e=="string"){if(wC.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 TC(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&&wC.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 vC(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 rC(e.spec,o,s,n,r),Dn(e,"research",e.research),e.currentPhase="plan",e.plan=await sC(e.spec,e.research,o,s,n,r),Dn(e,"plan",e.plan),e.currentPhase="parallelize";let i=await aC(e.plan,t,n,r);if(i.kind==="plan")e.waveOrchestrationPlan=i.plan,Dn(e,"parallelize",JSON.stringify(i.plan));else if(i.kind==="skipped")e.waveOrchestrationPlan=void 0,Dn(e,"parallelize",`skipped: ${i.reason}`);else if(i.kind==="failed"){e.waveOrchestrationPlan=void 0;let c=J2(i.error);Dn(e,"parallelize",`failed: ${c}`),je({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 cC(e.plan,e.waveOrchestrationPlan,o,s,n,r),Dn(e,"build",JSON.stringify(e.buildResults)),e.currentPhase="verify",e.verifyResults=await Td(e.plan,e.buildResults,o,s,n,r),Dn(e,"verify",JSON.stringify(e.verifyResults)),e.currentPhase="heal";let a=e.verifyResults.testsPassed&&e.verifyResults.lintPassed&&e.verifyResults.designReviewPassed;for(;!a&&e.healIterations<q2;){let c=await dC(e.plan,e.buildResults,e.verifyResults,e.healIterations,t,n,r);e.healIterations=c.newHealIterations,e.verifyResults=c.newVerifyResults,a=c.healed,Dn(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 mC(e,o,s,n,r);return Dn(e,"ship",l),{completed:!0,artifact:l,state:e}}catch(i){throw new Error(`mint failed at ${e.currentPhase}: ${i}`)}}function kC(e,t){return EC(t),("completed"in t||t.phase==="heal-failed")&&my(e),t}async function V2(e,t,n){let r=TC(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??yC(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 vC(c,t,s,i);return kC(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.");my(o);let a={currentPhase:"spec",idea:r.idea,healIterations:0,history:[]};try{a.spec=await tC(r.idea,o,t.cwd,s,i),Dn(a,"spec",a.spec)}catch(c){throw new Error(`mint failed at spec: ${c}`)}if(!r.autoApprove){hC(o,a);let c={paused:!0,phase:"spec",spec:a.spec,state:a,nextStep:z2};return EC(c),c}let l=await vC(a,t,s,i);return kC(o,l)}var q2,wC,z2,SC,Y2,xC=_(()=>{"use strict";vt();nC();oC();iC();lC();Qn();uC();dy();pC();fC();bC();q2=2,wC=/^\s*(?:--continue(?:\s+(?:approved|yes|y))?|approved?|yes|y|lgtm|sure)\s*$/i,z2='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.';SC=240;Y2={name:"mint",description:"Takes a feature idea or refactor scope and delivers a ship-ready, verified implementation end-to-end",handler:V2,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"]};At(Y2)});async function X2(){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 Z2,RC=_(()=>{"use strict";vt();Z2={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:X2,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."};At(Z2)});async function Q2(){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 eq,CC=_(()=>{"use strict";vt();eq={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:Q2,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.`};At(eq)});function AC(e){return e.startsWith("--")?e:`--${e}`}function nq(e){let t=new Set;for(let n of e.matchAll(tq))n[1]&&t.add(`--${n[1]}`);return Array.from(t).sort()}function fy(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 tq,gy=_(()=>{"use strict";tq=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9
|
|
|
1509
1509
|
`),null;if(o.length>IC)return process.stderr.write(`[afk] skipping skill ${t}: description exceeds ${IC} characters (got ${o.length})
|
|
1510
1510
|
`),null;let a=n.frontmatter["argument-hint"]??n.frontmatter.argumentHint,l=xd(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 aq(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 lq(e,t){try{return Ge(e).origin===t?e:`${t}:${e}`}catch{return e}}function yr(e,t){let n;try{n=rq(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=oq(_C(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=iq(s,o.name);if(!i)continue;i.dir=_C(e,o.name);let l={name:lq(i.name,t),description:i.description,handler:aq(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)),At(l),r++}return r}function hy(){return yr(gc(),"user")}var IC,yy=_(()=>{"use strict";K();
|
|
1512
|
+
`);continue}let i=iq(s,o.name);if(!i)continue;i.dir=_C(e,o.name);let l={name:lq(i.name,t),description:i.description,handler:aq(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)),At(l),r++}return r}function hy(){return yr(gc(),"user")}var IC,yy=_(()=>{"use strict";K();vt();gy();Qe();IC=1024});var by=_(()=>{"use strict";OR();XR();ZR();xC();RC();CC();yy()});import{isAbsolute as cq,resolve as uq}from"path";import{pathToFileURL as dq}from"url";async function MC(e,t={}){let n=t.importer??(r=>import(r));for(let r of e){if(r.main===void 0)continue;let o=cq(r.main)?r.main:uq(r.path,r.main);if(!PC.has(o)){PC.add(o);try{await n(dq(o).href)}catch(s){t.onError?.(r,s)}}}}var PC,OC=_(()=>{"use strict";PC=new Set});import{existsSync as pq,readdirSync as mq,readFileSync as fq,statSync as gq}from"fs";import{join as hq}from"path";function bq(e,t){let n=e.trim();if(n.length===0)return;if(t.has(n))return n;let r=yq[n.toLowerCase()];if(r!==void 0&&t.has(r))return r}function Rd(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).trim():t}function wq(e,t){let n=e.trim();if(n.length>0)return n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1).split(",").map(i=>Rd(i)).filter(i=>i.length>0):Rd(n).split(",").map(s=>Rd(s)).filter(s=>s.length>0);let r=[];for(let o of t){let s=o.trim();if(s.startsWith("- "))r.push(Rd(s.slice(2)));else break}return r}function wy(e,t){let n=[];function r(o,s=0){if(s>10||!pq(o))return;let i;try{i=mq(o)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=hq(o,a),c;try{c=gq(l)}catch{continue}if(c.isFile()&&a==="SKILL.md"){let u=Sq(l,t);u.name&&n.push(u)}else c.isDirectory()&&r(l,s+1)}}return r(e),n}function Sq(e,t){try{let n=fq(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=wq(m,g),b=vq(t),y=[];for(let S of h){let w=bq(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 vq(e){return e!==void 0?e:new Set([...Kt,...ft,"memory_search","agent","skill"])}var yq,$C=_(()=>{"use strict";En();xn();yq={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 DC(e){let t=pr(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 pr(e){let t=[],n=new Set,r=v.AFK_INTERNAL==="1",o=sn(Mt());yr(gc(),"user"),yr(hc(),"project");for(let{dir:i,origin:a}of o.skillRoots)yr(i,a);for(let i of Zn()){let a=Ge(i);on(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??Sy();for(let i of s){if(i.type!=="local")continue;let a=wy(i.path);for(let l of a)!l.name||n.has(l.name)||on({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 pd(e){let t=new Map,n=e??Sy();for(let r of n){if(r.type!=="local")continue;let o=wy(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 Sy(){return[...fr(yc()),...fr(),...fr(vs()),...sn(Mt()).pluginRoots.flatMap(e=>fr(e,{trustAll:!0}))]}async function wi(){await MC(Sy())}var In=_(()=>{"use strict";by();
|
|
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*ky(e){let t=e.maxToolUseIterations??Aq,n={stopReason:null},r=0,o=0,s=Cq(),i=Date.now(),a=l=>({...l,durationMs:Date.now()-i});Le(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=jc({baseUrl:e.baseUrl})?qv(e.messages,Hc()):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(_q)}:{},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{output_config:{effort:e.effort}}:{}},u=Date.now(),d;try{d=await Pq(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")&&Oq(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 WC(d,e.ctx))if(h||(h=!0,Le(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(GC(w.event.error)&&o<vy&&!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(GC(T)&&o<vy&&!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 zC(qC*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=jC(p.usage,p.stopReason,e.model);if(n=za(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:Mq(k.name,k.input),toolInputRaw:Qu(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{Le(e.traceWriter,{phase:"loop_end",durationMs:Date.now()-i})}}function Oq(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 Aq,vy,qC,JC=_(()=>{"use strict";HC();Zf();KC();Ue();xh();q();Aq=0;vy=3,qC=5e3});function Ey(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 VC(e){let{resetsAt:t,signal:n,readToken:r=wt}=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 YC(e){let{signal:t,readToken:n=wt,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 XC=_(()=>{"use strict";Fs()});var ZC=_(()=>{"use strict";Fs()});import{randomUUID as Ty}from"node:crypto";var QC,$q,Ad,eA=_(()=>{"use strict";JC();Ms();XC();ZC();QC=7200*1e3,$q=60*1e3,Ad=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=wt(),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=wt();return{accountId:Pr(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=Ey(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=Pr(wt()??"");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=YC({signal:t.signal,retryAfterMs:$q});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=wn(this._authMode,this.initSessionId,Ty());let g=null;for await(let h of this.turnWithAuthRetry(t,n)){if(!d&&h.type==="error"){let b=Ey(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>QC){yield g;return}}}if(!o)return;if(o.getTime()-Date.now()>QC){yield r;return}let i=Pr(wt()??"");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=VC({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=wn(this._authMode,this.initSessionId,Ty()),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 ky(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=wn(this._authMode,this.initSessionId,Ty()),yield*ky(t)}isRetryableAuth(t){return this._authMode==="oauth"&&this.tokenRefresher!==void 0&&"status"in t&&t.status===401}}});function Lq(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 rA(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&&Lq(o)&&(n+=1,n===t))return r}return-1}function oA(e,t,n){let r=Fq(e);return{model:t,max_tokens:n,system:Dq,messages:[{role:"user",content:`Summarize the following conversation transcript. Follow the system instructions exactly.
|
|
1518
|
+
`)}function pr(e){let t=[],n=new Set,r=v.AFK_INTERNAL==="1",o=sn(Mt());yr(gc(),"user"),yr(hc(),"project");for(let{dir:i,origin:a}of o.skillRoots)yr(i,a);for(let i of Zn()){let a=Ge(i);on(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??Sy();for(let i of s){if(i.type!=="local")continue;let a=wy(i.path);for(let l of a)!l.name||n.has(l.name)||on({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 pd(e){let t=new Map,n=e??Sy();for(let r of n){if(r.type!=="local")continue;let o=wy(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 Sy(){return[...fr(yc()),...fr(),...fr(vs()),...sn(Mt()).pluginRoots.flatMap(e=>fr(e,{trustAll:!0}))]}async function wi(){await MC(Sy())}var In=_(()=>{"use strict";by();vt();yy();Jr();OC();$C();K();q();cr()});function LC(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 FC=_(()=>{"use strict"});function NC(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 BC=_(()=>{"use strict"});var kq,Cd,UC=_(()=>{"use strict";kq="__closed__",Cd=class{current=null;pendingReason=null;closedPromise;closeResolve=null;constructor(){this.closedPromise=new Promise(t=>{this.closeResolve=()=>t(kq)})}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 Tq(e,t,n,r,o){let s=Eq.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 jC(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=Tq(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 Eq,HC=_(()=>{"use strict";Th();Eq=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 xq(e){let t=e.trim();if(t.length===0)return{};try{return JSON.parse(t)}catch{return{}}}function Rq(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:xq(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*WC(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:Rq(n,r,o)}}var KC=_(()=>{"use strict";q()});import{randomUUID as Cq}from"node:crypto";function _q(e){let{name:t,description:n,input_schema:r}=e;return{name:t,...n!==void 0?{description:n}:{},input_schema:r}}function Iq(e){if(!("status"in e))return!1;let t=e.status;return t===529||t===503}function GC(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 zC(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 Pq(e,t,n,r){for(let o=0;;o++){if(o>0){let s=qC*Math.pow(2,o-1);if(await zC(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(Iq(i)&&o<vy)continue;throw i}}}function Mq(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*ky(e){let t=e.maxToolUseIterations??Aq,n={stopReason:null},r=0,o=0,s=Cq(),i=Date.now(),a=l=>({...l,durationMs:Date.now()-i});Le(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=jc({baseUrl:e.baseUrl})?qv(e.messages,Hc()):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(_q)}:{},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{output_config:{effort:e.effort}}:{}},u=Date.now(),d;try{d=await Pq(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")&&Oq(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 WC(d,e.ctx))if(h||(h=!0,Le(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(GC(w.event.error)&&o<vy&&!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(GC(T)&&o<vy&&!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 zC(qC*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=jC(p.usage,p.stopReason,e.model);if(n=za(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:Mq(k.name,k.input),toolInputRaw:Qu(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{Le(e.traceWriter,{phase:"loop_end",durationMs:Date.now()-i})}}function Oq(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 Aq,vy,qC,JC=_(()=>{"use strict";HC();Zf();KC();Ue();xh();q();Aq=0;vy=3,qC=5e3});function Ey(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 VC(e){let{resetsAt:t,signal:n,readToken:r=St}=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 YC(e){let{signal:t,readToken:n=St,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 XC=_(()=>{"use strict";Fs()});var ZC=_(()=>{"use strict";Fs()});import{randomUUID as Ty}from"node:crypto";var QC,$q,Ad,eA=_(()=>{"use strict";JC();Ms();XC();ZC();QC=7200*1e3,$q=60*1e3,Ad=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=St(),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=St();return{accountId:Pr(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=Ey(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=Pr(St()??"");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=YC({signal:t.signal,retryAfterMs:$q});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=wn(this._authMode,this.initSessionId,Ty());let g=null;for await(let h of this.turnWithAuthRetry(t,n)){if(!d&&h.type==="error"){let b=Ey(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>QC){yield g;return}}}if(!o)return;if(o.getTime()-Date.now()>QC){yield r;return}let i=Pr(St()??"");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=VC({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=wn(this._authMode,this.initSessionId,Ty()),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 ky(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=wn(this._authMode,this.initSessionId,Ty()),yield*ky(t)}isRetryableAuth(t){return this._authMode==="oauth"&&this.tokenRefresher!==void 0&&"status"in t&&t.status===401}}});function Lq(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 rA(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&&Lq(o)&&(n+=1,n===t))return r}return-1}function oA(e,t,n){let r=Fq(e);return{model:t,max_tokens:n,system:Dq,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 tq,gy=_(()=>{"use strict";tq=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9
|
|
|
1524
1524
|
|
|
1525
1525
|
`+n},{role:"assistant",content:nA},...e.slice(t)]}function iA(e,t,n){let r=Nq(e.slice(0,t)),o=tA.length+2+n.length+nA.length,s=Math.max(0,r-o);return Math.round(s/4)}function Fq(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=aA(o.input);t.push(`[tool call: ${i} ${a}]`)}else if(s==="tool_result"){let i=o.content;t.push(`[tool result: ${lA(i)}]`)}else s==="image"?t.push("[image]"):s==="document"&&t.push("[document]")}t.push("")}return t.join(`
|
|
1526
1526
|
`).trim()}function aA(e){try{let t=JSON.stringify(e);return t.length>240?t.slice(0,237)+"...":t}catch{return"{}"}}function lA(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 Nq(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+=aA(r.input).length:o==="tool_result"&&(t+=lA(r.content).length)}return t}var Dq,tA,nA,cA=_(()=>{"use strict";Dq=["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
|
-
`),tA="[Compacted summary of earlier conversation]",nA="Acknowledged. Continuing from the summary above."});import{randomUUID as Bq}from"node:crypto";async function uA(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=Wq(),l=rA(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=Kq(),d=oA(c,u,Hq),p=n.begin(),m;try{if(p.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let y=wn(r.authMode,o,Bq()),S=r.client,w=await Promise.resolve(S.messages.create(d,{headers:y,signal:p.signal}));m=await Gq(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=iA(t.messages,l,m),h=sA(t.messages,l,m);t.messages.splice(0,t.messages.length,...h);let b=t.messages.length;return Ov(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 Wq(){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 Uq}function Kq(){let e=v.AFK_COMPACT_MODEL;return e!==void 0&&e.length>0?bt(e)??e:jq}async function Gq(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 Uq,jq,Hq,dA=_(()=>{"use strict";Ms();cA();Ue();Xn();q();Uq=2,jq="claude-haiku-4-5-20251001",Hq=1024});import{randomUUID as pA}from"node:crypto";var qq,_d,mA=_(()=>{"use strict";_a();Ms();Zf();eg();ng();In();Va();Xn();FC();BC();UC();eA();dA();Ih();qq=[{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"}],_d=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;baseUrl;traceWriter;state;abort;retry;cwdDependentsFactory;onPermissionMode;mcpManager;constructor(t){this.initSessionId=t.sessionId??pA(),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 Ad({client:t.client,authMode:t.authMode,initSessionId:this.initSessionId,...t.tokenRefresher?{tokenRefresher:t.tokenRefresher}:{},autoResumeOnUsageLimit:t.autoResumeOnUsageLimit??!0}),this.state=NC({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 Cd}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}LC(this.state.messages),this.state.messages.push({role:"user",content:s.content});let a=this.composeSystem(),l=wn(this.retry.authMode,this.initSessionId,pA(),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=$t(this.state.requestedModel);if(d!==null&&p>0){let m=ti(d);Rx(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=Jv(this.state.currentPermissionMode);o!==null&&r.push(o);let s=Vv(this.state.currentPermissionMode);return s!==null&&r.push(s),r.length===0?null:jc({baseUrl:this.baseUrl})?Gv(r,Hc()):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=bt(t)??t)}async setPermissionMode(t){this.state.currentPermissionMode=t;let n=Sn(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 pr().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return qq.map(t=>({...t}))}async supportedAgents(){return[]}async getContextUsage(){let t=this.state.lastUsage,n=$t(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}=ed(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 uA({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 xy(e){if(e===void 0||e===!1)return;if(e===!0)return Jq;let t=e.threshold;if(!(typeof t!="number"||!Number.isFinite(t)||t<=0||t>=1))return t}function Ry(e,t){let n=Ja(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 Id.has(s)||(Id.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${t} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function fA(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 Cy(e,t,n){switch(e.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&zq(n))return{type:"adaptive",display:"summarized"};let r=Math.floor(t*Vq),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}`;Id.has(a)||(Id.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 Ay(e,t){if(e!==void 0)return e;let n=t.toLowerCase();if(/(claude-)?(opus|sonnet)-4-[678]/.test(n))return"max"}var zq,Jq,Id,Vq,_y=_(()=>{"use strict";Va();zq=e=>/opus-4-(7|[89])/.test(e),Jq=.9;Id=new Set,Vq=.25});var Pd,Iy,Py,Rwe,gA,hA,yA=_(()=>{"use strict";Pd=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
|
|
1527
|
+
`),tA="[Compacted summary of earlier conversation]",nA="Acknowledged. Continuing from the summary above."});import{randomUUID as Bq}from"node:crypto";async function uA(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=Wq(),l=rA(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=Kq(),d=oA(c,u,Hq),p=n.begin(),m;try{if(p.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let y=wn(r.authMode,o,Bq()),S=r.client,w=await Promise.resolve(S.messages.create(d,{headers:y,signal:p.signal}));m=await Gq(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=iA(t.messages,l,m),h=sA(t.messages,l,m);t.messages.splice(0,t.messages.length,...h);let b=t.messages.length;return Ov(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 Wq(){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 Uq}function Kq(){let e=v.AFK_COMPACT_MODEL;return e!==void 0&&e.length>0?wt(e)??e:jq}async function Gq(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 Uq,jq,Hq,dA=_(()=>{"use strict";Ms();cA();Ue();Xn();q();Uq=2,jq="claude-haiku-4-5-20251001",Hq=1024});import{randomUUID as pA}from"node:crypto";var qq,_d,mA=_(()=>{"use strict";_a();Ms();Zf();eg();ng();In();Va();Xn();FC();BC();UC();eA();dA();Ih();bt();qq=[{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"}],_d=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;baseUrl;traceWriter;state;abort;retry;cwdDependentsFactory;onPermissionMode;mcpManager;hookRegistry;constructor(t){this.initSessionId=t.sessionId??pA(),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,t.hookRegistry!==void 0&&(this.hookRegistry=t.hookRegistry),this.retry=new Ad({client:t.client,authMode:t.authMode,initSessionId:this.initSessionId,...t.tokenRefresher?{tokenRefresher:t.tokenRefresher}:{},autoResumeOnUsageLimit:t.autoResumeOnUsageLimit??!0}),this.state=NC({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 Cd}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}LC(this.state.messages),this.state.messages.push({role:"user",content:s.content});let a=this.composeSystem(),l=wn(this.retry.authMode,this.initSessionId,pA(),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=$t(this.state.requestedModel);if(d!==null&&p>0){let m=ti(d);if(Rx(m,p,this.state.autoCompactThreshold))try{this.hookRegistry&&await this.hookRegistry.dispatch({event:"PreCompact",sessionId:this.initSessionId,trigger:"auto"}),await this.compact()}catch(g){if(!(g instanceof pe))throw g}}}}}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=Jv(this.state.currentPermissionMode);o!==null&&r.push(o);let s=Vv(this.state.currentPermissionMode);return s!==null&&r.push(s),r.length===0?null:jc({baseUrl:this.baseUrl})?Gv(r,Hc()):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=wt(t)??t)}async setPermissionMode(t){this.state.currentPermissionMode=t;let n=Sn(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 pr().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return qq.map(t=>({...t}))}async supportedAgents(){return[]}async getContextUsage(){let t=this.state.lastUsage,n=$t(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}=ed(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 uA({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 xy(e){if(e===void 0||e===!1)return;if(e===!0)return Jq;let t=e.threshold;if(!(typeof t!="number"||!Number.isFinite(t)||t<=0||t>=1))return t}function Ry(e,t){let n=Ja(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 Id.has(s)||(Id.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${t} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function fA(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 Cy(e,t,n){switch(e.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&zq(n))return{type:"adaptive",display:"summarized"};let r=Math.floor(t*Vq),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}`;Id.has(a)||(Id.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 Ay(e,t){if(e!==void 0)return e;let n=t.toLowerCase();if(/(claude-)?(opus|sonnet)-4-[678]/.test(n))return"max"}var zq,Jq,Id,Vq,_y=_(()=>{"use strict";Va();zq=e=>/opus-4-(7|[89])/.test(e),Jq=.9;Id=new Set,Vq=.25});var Pd,Iy,Py,Cwe,gA,hA,yA=_(()=>{"use strict";Pd=`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.
|
|
@@ -1533,7 +1533,7 @@ ${t.body}`)}var tq,gy=_(()=>{"use strict";tq=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9
|
|
|
1533
1533
|
- Use glob and grep to discover files before reading individual files.
|
|
1534
1534
|
- When bash output is very long, it may be truncated. If you need the full output, redirect to a file and read it.
|
|
1535
1535
|
- Use absolute paths for file operations.
|
|
1536
|
-
- Prefer \`agent\` (and \`skill\`) for multi-file investigation, verification, parallel hypotheses, and any work that would otherwise consume large amounts of inline context. The main session is the coordinator; subagents are the investigators.`,Iy="When you see a `<command-name>` tag in the current conversation turn, the skill has ALREADY been loaded by the user typing a slash command. Do NOT re-invoke the skill tool to dispatch that same skill again. Instead, treat the `<command-message>` as the skill name and `<command-args>` as its arguments, then follow the instructions in the body block immediately following the tag. You MAY still invoke the skill tool to dispatch OTHER skills that are not the one already loaded.",Py='When a user message contains a `<bash-passthrough>` block, it represents a shell command the **user ran directly** in the REPL using the `!` prefix (e.g. `!ls` or `!&pnpm test`). This is distinct from the `bash` tool you invoke yourself:\n\n- `<bash-passthrough>` = human-initiated shell run, output injected into your context automatically\n- `bash` tool result = model-initiated command you explicitly called\n\nAttributes on the opening tag:\n- `mode="foreground"` \u2014 user waited for the command to finish before the next prompt\n- `mode="background"` \u2014 command ran detached (`!&` prefix); output arrives after it completes\n- `exit="N"` \u2014 shell exit code (0 = success)\n- `reason="..."` \u2014 error category when nonzero: `nonzero-exit`, `abort` (Ctrl+C), `timeout`, `overflow`, `spawn-failed`, `signal-killed`\n- `duration="1.3s"` \u2014 wall-clock runtime\n- `truncated="true"` \u2014 output was capped; full output not available\n\nThe `<command>` child contains the literal command the user typed (XML-escaped). The `<output>` child contains ANSI-stripped, XML-escaped captured stdout/stderr.',
|
|
1536
|
+
- Prefer \`agent\` (and \`skill\`) for multi-file investigation, verification, parallel hypotheses, and any work that would otherwise consume large amounts of inline context. The main session is the coordinator; subagents are the investigators.`,Iy="When you see a `<command-name>` tag in the current conversation turn, the skill has ALREADY been loaded by the user typing a slash command. Do NOT re-invoke the skill tool to dispatch that same skill again. Instead, treat the `<command-message>` as the skill name and `<command-args>` as its arguments, then follow the instructions in the body block immediately following the tag. You MAY still invoke the skill tool to dispatch OTHER skills that are not the one already loaded.",Py='When a user message contains a `<bash-passthrough>` block, it represents a shell command the **user ran directly** in the REPL using the `!` prefix (e.g. `!ls` or `!&pnpm test`). This is distinct from the `bash` tool you invoke yourself:\n\n- `<bash-passthrough>` = human-initiated shell run, output injected into your context automatically\n- `bash` tool result = model-initiated command you explicitly called\n\nAttributes on the opening tag:\n- `mode="foreground"` \u2014 user waited for the command to finish before the next prompt\n- `mode="background"` \u2014 command ran detached (`!&` prefix); output arrives after it completes\n- `exit="N"` \u2014 shell exit code (0 = success)\n- `reason="..."` \u2014 error category when nonzero: `nonzero-exit`, `abort` (Ctrl+C), `timeout`, `overflow`, `spawn-failed`, `signal-killed`\n- `duration="1.3s"` \u2014 wall-clock runtime\n- `truncated="true"` \u2014 output was capped; full output not available\n\nThe `<command>` child contains the literal command the user typed (XML-escaped). The `<output>` child contains ANSI-stripped, XML-escaped captured stdout/stderr.',Cwe=`${Pd}
|
|
1537
1537
|
|
|
1538
1538
|
${Iy}
|
|
1539
1539
|
|
|
@@ -1582,7 +1582,7 @@ Use FTS5 syntax: "exact phrase", term1 AND term2, prefix*.`});import{mkdirSync a
|
|
|
1582
1582
|
`;Xq(i,c)}catch(l){let c=`[prompt-dump] Failed to write to ${i}: ${String(l)}
|
|
1583
1583
|
`;process.stderr.write(c)}}var tz,nz,rz,Si=_(()=>{"use strict";q();tz=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
|
|
1584
1584
|
`,nz=/key|token|secret|password|credential|auth/i,rz=[[/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 Oy from"path";import{appendFileSync as iz,mkdirSync as az}from"fs";import{dirname as lz}from"path";import wA from"@anthropic-ai/sdk";function cz(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 dl,SA,$y,qe,uz,No=_(()=>{"use strict";Ms();Uc();Fs();mA();_a();_y();_y();Fa();Sh();Yu();En();yA();Qc();Yc();Xn();In();cn();Si();K();q();xn();jr();dl="anthropic-direct",SA="claude-sonnet-4-5-20250929",$y=null,qe=class{name=dl;externalTools;memoryStore;providerFactory;skillExecutor;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;composeExecutor;surface;readOnlyMemory;readOnlyBash;mcpManager;customTools;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_currentCwd;_mcpToolsCache=null;_mcpHandlersCache=null;_presenceSessionId=null;constructor(t={}){let n=[...tr];t.subagentExecutor&&n.push(xo),t.skillExecutor&&n.push(Ro),t.composeExecutor&&n.push(Co),t.readOnlyMemory===!0?n.push(Bs):n.push(...Mr),n.push(Tn);for(let r of t.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);if(this.memoryStore=t.memoryStore??new lt,this.externalTools=t.tools,this.skillExecutor=t.skillExecutor,this.schemas=n,this.hookRegistry=t.hookRegistry,this.permissions=t.permissions,this.canUseTool=t.canUseTool,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=qu(t,n?.cwd),o=Ma(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(Do,Vu(i)),new It({handlers:r,allowAll:Sn(t),schemas:[...this.schemas,...s,...i?[Ju]:[]],hookRegistry:Vc(n?.hookRegistry,this.hookRegistry),permissions:Zc(this.mcpManager?Xc(this.permissions,this.mcpManager.getMcpToolWireNames()):this.permissions,this.customTools.map(a=>a.schema.name)),subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,...this.canUseTool!==void 0?{canUseTool:this.canUseTool}:{},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(`${dl} 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??SA,system:t.system,user:t.user,maxTokens:t.maxTokens??64};t.signal&&(r.signal=t.signal);let o=this.providerFactory??$y;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=Oy.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=Oy.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=Oy.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:Sn(this._currentPermissionMode)}}appendProviderAuditLog(t){try{let n=Es();az(lz(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:t.sessionId??null,action:t.action,path:t.path,source:t.source});iz(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(`${dl} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=Lc(o),i=Aa(o,s,n.baseUrl),a=this.providerFactory??$y,l=a?a(i):new wA(i),c=r?null:Lv(s),u=cz(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(`${dl} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=Lc(o),i=Aa(o,s,n.baseUrl),a=this.providerFactory??$y,l=a?a(i):new wA(i),c=r?null:Lv(s),u=cz(n.systemPrompt),d=typeof n.model=="string"&&n.model.length>0?wt(n.model)??n.model:SA,p=Ry(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=Oa({surface:this.surface,cwd:n.cwd??process.cwd(),modelName:d,providerName:dl,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 It?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();Da({sessionId:B,surface:this.surface,actor:_n(n.depth),cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:dl,name:d},workspace:H,pid:process.pid}),process.once("exit",()=>{rr(B)}),process.once("SIGINT",()=>{rr(B),process.exit(130)}),process.once("SIGTERM",()=>{rr(B),process.exit(143)})}g=this.externalTools?$a(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 It?[...g.toolDefs]:[...tr,Tn],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?DC():"",T=n.cwd||process.cwd(),x=n.isSkillDispatch?Pd:`${Pd}
|
|
1586
1586
|
|
|
1587
1587
|
${Iy}
|
|
1588
1588
|
|
|
@@ -1590,9 +1590,9 @@ ${Py}`,C=this.readOnlyMemory?hA:gA,R=[x,C];R.push(Us({cwd:T,...n.sessionId!==voi
|
|
|
1590
1590
|
|
|
1591
1591
|
`),$=[x,C];w.length>0&&$.push(w),u&&$.push(u),bA({prompt:t.prompt,options:{model:d,maxTokens:p,system:k},provenance:{systemPrompt:{source:n.systemPromptSource??"none",shape:typeof n.systemPrompt=="string"?"string":Array.isArray(n.systemPrompt)?"string[]":n.systemPrompt!=null?"preset":"undefined",...typeof n.systemPrompt=="string"?{length:n.systemPrompt.length}:{}},...n.apiKey?{apiKey:{source:"config"}}:{}}});let A;if(s==="oauth"&&!r){let B=this.providerFactory??$y;A=async()=>{let H=await Xf();if(!H)return null;let L=Aa(H,"oauth",n.baseUrl);return B?B(L):new wA(L)}}let P=n.sessionId??n.resume,F=fA(n.resumeHistory),D=this.externalTools?void 0:B=>{let H=this._currentCwd;if(this._sharedReadRoots&&H!==void 0&&H!==B){let M=this._sharedReadRoots.indexOf(H);M!==-1?this._sharedReadRoots[M]=B:this._sharedReadRoots.includes(B)||this._sharedReadRoots.push(B)}if(this._sharedWriteRoots&&H!==void 0&&H!==B){let M=this._sharedWriteRoots.indexOf(H);M!==-1?this._sharedWriteRoots[M]=B:this._sharedWriteRoots.includes(B)||this._sharedWriteRoots.push(B)}this._currentCwd=B,this.subagentExecutor?.setCwd(B),this.skillExecutor?.setCwd(B),this.composeExecutor?.setCwd(B);let I=[$[0],$[1],Us({cwd:B,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.surface,...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:h.getWorkspace()}),...$.slice(2)].join(`
|
|
1592
1592
|
|
|
1593
|
-
`),U=this.buildDispatcher(this._currentPermissionMode,{cwd:B,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});return{userSystem:I,dispatcher:U}},N=Ay(n.effort,d);return new _d({client:l,authMode:r?"api-key":s,promptStream:t.prompt,toolDispatcher:g,...P!==void 0?{sessionId:P}:{},...F!==void 0?{initialMessages:F}:{},model:d,requestedModel:typeof n.model=="string"&&n.model.length>0?n.model:d,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:p,tools:S,userSystem:k,systemPrefix:c,tokenRefresher:A,...n.thinking!==void 0?{thinking:Cy(n.thinking,p,d)}:{},...N!==void 0?{effort:N}:{},...r?{baseUrl:n.baseUrl}:{},...n.traceWriter?{traceWriter:n.traceWriter}:{},...n.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:n.autoResumeOnUsageLimit}:{},...D!==void 0?{cwdDependentsFactory:D}:{},onPermissionMode:B=>{this._currentPermissionMode=B},...this.mcpManager!==void 0?{mcpManager:this.mcpManager}:{},...xy(n.autoCompact)!==void 0?{autoCompactThreshold:xy(n.autoCompact)}:{}})}};uz=new qe});function pz(e){if(!e)return;let t=e.trim().toLowerCase();if(t){if(t==="anthropic"||t==="anthropic-direct")return"anthropic-direct";if(t==="openai"||t==="openai-compatible"||t==="openai-codex")return"openai-compatible"}}function re(e,t){let n=t?.explicit??v.AFK_PROVIDER,r=t?.openaiBaseUrl??v.AFK_OPENAI_BASE_URL,o=pz(n);if(o)return o;let s=Jf(e,t?.slots);if(s.provider==="anthropic")return"anthropic-direct";if(s.provider==="openai")return"openai-compatible";let i=s.id.trim().toLowerCase();return i&&(dz.has(i)||i.startsWith("claude-")||i.startsWith("claude_")||i.startsWith("local-")||i.startsWith("local_"))?"anthropic-direct":i&&(i.startsWith("gpt-")||i.startsWith("gpt_")||i.startsWith("o1")||i.startsWith("o3")||i.startsWith("o4")||i.startsWith("codex-")||i.startsWith("codex_")||i==="codex"||i.startsWith("deepseek-")||i.startsWith("deepseek_")||i.startsWith("mistral-")||i.startsWith("mistral_")||i.startsWith("mixtral-")||i.startsWith("mixtral_")||i.startsWith("llama-")||i.startsWith("llama_")||i.startsWith("qwen-")||i.startsWith("qwen_")||i.includes("/"))||s.baseUrl&&s.baseUrl.trim()||r&&r.trim()?"openai-compatible":"anthropic-direct"}function Md(e,t,n){let r=re(e,t),o=n?.customTools,s=n?.canUseTool,i={...o!==void 0&&o.length>0?{customTools:o}:{},...s!==void 0?{canUseTool:s}:{}};switch(r){case"openai-compatible":case"openai-codex":return new Dt(i);default:return new qe(i)}}var dz,rt=_(()=>{"use strict";No();Qa();Xn();nn();q();No();Qa();dz=new Set([...Object.keys(Vf),"auto"])});var vi,Dy=_(()=>{"use strict";vi=class{pendingResolve=null;bufferedMessages=[];getSessionId;constructor(t){this.getSessionId=t}pushUserMessage(t){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:t,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessages.push(t)}createIterable(){let t=this;return{[Symbol.asyncIterator](){return{next(){if(t.bufferedMessages.length>0){let n=t.bufferedMessages.shift(),r=t.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{t.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}}});function Od(e,t){let n=t??Os(),r=$s(e.model,n);if(!r)return;let o=n[r],s=o.provider==="anthropic"?"anthropic-direct":o.provider==="openai"?"openai-compatible":re(e.model,t?{slots:t}:void 0);o.apiKey!==void 0?e.apiKey=o.apiKey:(s==="openai-compatible"||o.baseUrl!==void 0)&&(e.apiKey=void 0),o.baseUrl!==void 0&&(s==="openai-compatible"?e.openaiBaseUrl=o.baseUrl:e.baseUrl=o.baseUrl)}var Ly=_(()=>{"use strict";rt();nn()});function mz(e){return typeof e=="string"?e:e.map(t=>{let n=t;return n.type==="text"&&typeof n.text=="string"?n.text:""}).filter(t=>t.length>0).join(`
|
|
1593
|
+
`),U=this.buildDispatcher(this._currentPermissionMode,{cwd:B,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});return{userSystem:I,dispatcher:U}},N=Ay(n.effort,d);return new _d({client:l,authMode:r?"api-key":s,promptStream:t.prompt,toolDispatcher:g,...P!==void 0?{sessionId:P}:{},...F!==void 0?{initialMessages:F}:{},model:d,requestedModel:typeof n.model=="string"&&n.model.length>0?n.model:d,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:p,tools:S,userSystem:k,systemPrefix:c,tokenRefresher:A,...n.thinking!==void 0?{thinking:Cy(n.thinking,p,d)}:{},...N!==void 0?{effort:N}:{},...r?{baseUrl:n.baseUrl}:{},...n.traceWriter?{traceWriter:n.traceWriter}:{},...n.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:n.autoResumeOnUsageLimit}:{},...D!==void 0?{cwdDependentsFactory:D}:{},onPermissionMode:B=>{this._currentPermissionMode=B},...this.mcpManager!==void 0?{mcpManager:this.mcpManager}:{},...xy(n.autoCompact)!==void 0?{autoCompactThreshold:xy(n.autoCompact)}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{}})}};uz=new qe});function pz(e){if(!e)return;let t=e.trim().toLowerCase();if(t){if(t==="anthropic"||t==="anthropic-direct")return"anthropic-direct";if(t==="openai"||t==="openai-compatible"||t==="openai-codex")return"openai-compatible"}}function re(e,t){let n=t?.explicit??v.AFK_PROVIDER,r=t?.openaiBaseUrl??v.AFK_OPENAI_BASE_URL,o=pz(n);if(o)return o;let s=Jf(e,t?.slots);if(s.provider==="anthropic")return"anthropic-direct";if(s.provider==="openai")return"openai-compatible";let i=s.id.trim().toLowerCase();return i&&(dz.has(i)||i.startsWith("claude-")||i.startsWith("claude_")||i.startsWith("local-")||i.startsWith("local_"))?"anthropic-direct":i&&(i.startsWith("gpt-")||i.startsWith("gpt_")||i.startsWith("o1")||i.startsWith("o3")||i.startsWith("o4")||i.startsWith("codex-")||i.startsWith("codex_")||i==="codex"||i.startsWith("deepseek-")||i.startsWith("deepseek_")||i.startsWith("mistral-")||i.startsWith("mistral_")||i.startsWith("mixtral-")||i.startsWith("mixtral_")||i.startsWith("llama-")||i.startsWith("llama_")||i.startsWith("qwen-")||i.startsWith("qwen_")||i.includes("/"))||s.baseUrl&&s.baseUrl.trim()||r&&r.trim()?"openai-compatible":"anthropic-direct"}function Md(e,t,n){let r=re(e,t),o=n?.customTools,s=n?.canUseTool,i={...o!==void 0&&o.length>0?{customTools:o}:{},...s!==void 0?{canUseTool:s}:{}};switch(r){case"openai-compatible":case"openai-codex":return new Dt(i);default:return new qe(i)}}var dz,rt=_(()=>{"use strict";No();Qa();Xn();nn();q();No();Qa();dz=new Set([...Object.keys(Vf),"auto"])});var vi,Dy=_(()=>{"use strict";vi=class{pendingResolve=null;bufferedMessages=[];getSessionId;constructor(t){this.getSessionId=t}pushUserMessage(t){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:t,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessages.push(t)}createIterable(){let t=this;return{[Symbol.asyncIterator](){return{next(){if(t.bufferedMessages.length>0){let n=t.bufferedMessages.shift(),r=t.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{t.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}}});function Od(e,t){let n=t??Os(),r=$s(e.model,n);if(!r)return;let o=n[r],s=o.provider==="anthropic"?"anthropic-direct":o.provider==="openai"?"openai-compatible":re(e.model,t?{slots:t}:void 0);o.apiKey!==void 0?e.apiKey=o.apiKey:(s==="openai-compatible"||o.baseUrl!==void 0)&&(e.apiKey=void 0),o.baseUrl!==void 0&&(s==="openai-compatible"?e.openaiBaseUrl=o.baseUrl:e.baseUrl=o.baseUrl)}var Ly=_(()=>{"use strict";rt();nn()});function mz(e){return typeof e=="string"?e:e.map(t=>{let n=t;return n.type==="text"&&typeof n.text=="string"?n.text:""}).filter(t=>t.length>0).join(`
|
|
1594
1594
|
`)}var $d,vA=_(()=>{"use strict";Dy();Ly();Me();$d=class{outerIterator;baseConfig;deps;currentModel;currentPermissionMode;currentCwd;startupFamily;active;activeModel;closed=!1;shadowHistory;pendingUserText;pendingAssistantText="";lastSessionId;constructor(t,n){this.outerIterator=t.prompt[Symbol.asyncIterator](),this.baseConfig=t.config,this.deps=n,this.currentModel=typeof t.config.model=="string"?t.config.model:void 0,this.currentPermissionMode=t.config.permissionMode,this.currentCwd=t.config.cwd,this.startupFamily=n.providerNameForModel(this.currentModel),this.shadowHistory=[...t.config.resumeHistory??[]]}resolveInner(t){let n=this.deps.resolveProvider(t),r={...this.baseConfig};r.model=t??this.baseConfig.model;let o=n.name===this.startupFamily&&this.baseConfig.apiKey!==void 0?this.baseConfig.apiKey:this.deps.resolveApiKey(t);o!==void 0?r.apiKey=o:delete r.apiKey,Od(r);let s=[n.name,r.baseUrl??"",r.openaiBaseUrl??"",r.apiKey??""].join("\0");return{provider:n,innerConfig:r,signature:s}}buildInner(t,n){let{provider:r,innerConfig:o,signature:s}=this.resolveInner(t),i=new vi(()=>this.lastSessionId);this.currentPermissionMode!==void 0&&(o.permissionMode=this.currentPermissionMode),this.currentCwd!==void 0&&(o.cwd=this.currentCwd),n&&(o.resumeHistory=[...this.shadowHistory]);let a=r.query({prompt:i.createIterable(),config:o});return{family:r.name,signature:s,query:a,iterator:a[Symbol.asyncIterator](),input:i}}async closeActive(){let t=this.active;if(t){this.active=void 0;try{await t.iterator.return?.(void 0)}catch{}try{await t.query.close()}catch{}}}observeEvent(t){t.type==="assistant.message"&&(this.pendingAssistantText+=(this.pendingAssistantText?`
|
|
1595
|
-
`:"")+t.text)}commitShadowTurn(){this.pendingUserText!==void 0&&(this.shadowHistory.push({user:this.pendingUserText,assistant:this.pendingAssistantText}),this.pendingUserText=void 0,this.pendingAssistantText="")}async*[Symbol.asyncIterator](){try{for(this.active=this.buildInner(this.currentModel,!1),this.activeModel=this.currentModel,yield*this.driveUntilInit(!1);!this.closed;){let t=await this.outerIterator.next();if(t.done)break;let n=t.value;this.lastSessionId=n.sessionId;let r=this.currentModel!==this.activeModel,o=!this.active||r&&this.resolveInner(this.currentModel).signature!==this.active.signature;if(this.activeModel=this.currentModel,o&&(await this.closeActive(),this.active=this.buildInner(this.currentModel,!0),z(`\u{1F500} ProviderRouter: switched inner provider \u2192 ${this.active.family} (model=${this.currentModel})`),yield*this.driveUntilInit(!0)))break;for(this.pendingUserText=mz(n.content),this.pendingAssistantText="",this.active.input.pushUserMessage(n.content);;){let s=await this.active.iterator.next();if(s.done){this.closed=!0;break}let i=s.value;if(this.observeEvent(i),yield i,i.type==="turn.completed"){this.commitShadowTurn();break}if(i.type==="error"){this.commitShadowTurn();break}}}}finally{await this.closeActive()}}async*driveUntilInit(t){for(;;){let n=await this.active.iterator.next();if(n.done)return yield{type:"error",error:new Error("provider ended before initialization")},this.closed=!0,!0;let r=n.value;if(r.type==="session.init")return t||(yield r),!1;if(r.type==="error")return yield r,this.closed=!0,!0;yield r}}async interrupt(){await this.active?.query.interrupt()}async setModel(t){typeof t=="string"&&t.length>0&&(this.currentModel=t,this.active&&this.resolveInner(t).signature===this.active.signature&&await this.active.query.setModel(t))}async setPermissionMode(t){this.currentPermissionMode=t,await this.active?.query.setPermissionMode(t)}setCwd(t){this.currentCwd=t,this.active?.query.setCwd?.(t)}async reauth(){return await this.active?.query.reauth?.()??null}async supportedCommands(){return await this.active?.query.supportedCommands()??[]}async supportedModels(){return await this.active?.query.supportedModels()??[]}async supportedAgents(){return await this.active?.query.supportedAgents()??[]}async getContextUsage(){return await this.active?.query.getContextUsage()??{}}async mcpServerStatus(){return await this.active?.query.mcpServerStatus()??[]}async accountInfo(){return await this.active?.query.accountInfo()??{}}async rewindFiles(t,n){let r=this.active;return r?r.query.rewindFiles(t,n):{canRewind:!1,error:"no active provider"}}async compact(){let t=this.active;return t?.query.compact?t.query.compact():{compacted:!1,reason:"provider does not support compaction",messagesBefore:0,messagesAfter:0}}async reloadPlugins(...t){let n=this.active?.query;if(n&&typeof n.reloadPlugins=="function")return n.reloadPlugins(...t)}async close(){this.closed=!0,await this.closeActive()}}});async function Dd(e,t,n){if(!e)return;if(n.kind==="blocked"){await tn(e,{hookEvent:t,decision:"block",...n.err.reason!==void 0?{reason:n.err.reason}:{}});return}let r=n.decision;await tn(e,{hookEvent:t,decision:r.decision,...r.reason!==void 0?{reason:r.reason}:{},...r.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(r.injectContext,"utf8")}:{}})}async function kA(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await Dd(n.traceWriter,"SessionStart",{kind:"decision",decision:r})}catch(r){throw r instanceof
|
|
1595
|
+
`:"")+t.text)}commitShadowTurn(){this.pendingUserText!==void 0&&(this.shadowHistory.push({user:this.pendingUserText,assistant:this.pendingAssistantText}),this.pendingUserText=void 0,this.pendingAssistantText="")}async*[Symbol.asyncIterator](){try{for(this.active=this.buildInner(this.currentModel,!1),this.activeModel=this.currentModel,yield*this.driveUntilInit(!1);!this.closed;){let t=await this.outerIterator.next();if(t.done)break;let n=t.value;this.lastSessionId=n.sessionId;let r=this.currentModel!==this.activeModel,o=!this.active||r&&this.resolveInner(this.currentModel).signature!==this.active.signature;if(this.activeModel=this.currentModel,o&&(await this.closeActive(),this.active=this.buildInner(this.currentModel,!0),z(`\u{1F500} ProviderRouter: switched inner provider \u2192 ${this.active.family} (model=${this.currentModel})`),yield*this.driveUntilInit(!0)))break;for(this.pendingUserText=mz(n.content),this.pendingAssistantText="",this.active.input.pushUserMessage(n.content);;){let s=await this.active.iterator.next();if(s.done){this.closed=!0;break}let i=s.value;if(this.observeEvent(i),yield i,i.type==="turn.completed"){this.commitShadowTurn();break}if(i.type==="error"){this.commitShadowTurn();break}}}}finally{await this.closeActive()}}async*driveUntilInit(t){for(;;){let n=await this.active.iterator.next();if(n.done)return yield{type:"error",error:new Error("provider ended before initialization")},this.closed=!0,!0;let r=n.value;if(r.type==="session.init")return t||(yield r),!1;if(r.type==="error")return yield r,this.closed=!0,!0;yield r}}async interrupt(){await this.active?.query.interrupt()}async setModel(t){typeof t=="string"&&t.length>0&&(this.currentModel=t,this.active&&this.resolveInner(t).signature===this.active.signature&&await this.active.query.setModel(t))}async setPermissionMode(t){this.currentPermissionMode=t,await this.active?.query.setPermissionMode(t)}setCwd(t){this.currentCwd=t,this.active?.query.setCwd?.(t)}async reauth(){return await this.active?.query.reauth?.()??null}async supportedCommands(){return await this.active?.query.supportedCommands()??[]}async supportedModels(){return await this.active?.query.supportedModels()??[]}async supportedAgents(){return await this.active?.query.supportedAgents()??[]}async getContextUsage(){return await this.active?.query.getContextUsage()??{}}async mcpServerStatus(){return await this.active?.query.mcpServerStatus()??[]}async accountInfo(){return await this.active?.query.accountInfo()??{}}async rewindFiles(t,n){let r=this.active;return r?r.query.rewindFiles(t,n):{canRewind:!1,error:"no active provider"}}async compact(){let t=this.active;return t?.query.compact?t.query.compact():{compacted:!1,reason:"provider does not support compaction",messagesBefore:0,messagesAfter:0}}async reloadPlugins(...t){let n=this.active?.query;if(n&&typeof n.reloadPlugins=="function")return n.reloadPlugins(...t)}async close(){this.closed=!0,await this.closeActive()}}});async function Dd(e,t,n){if(!e)return;if(n.kind==="blocked"){await tn(e,{hookEvent:t,decision:"block",...n.err.reason!==void 0?{reason:n.err.reason}:{}});return}let r=n.decision;await tn(e,{hookEvent:t,decision:r.decision,...r.reason!==void 0?{reason:r.reason}:{},...r.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(r.injectContext,"utf8")}:{}})}async function kA(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await Dd(n.traceWriter,"SessionStart",{kind:"decision",decision:r})}catch(r){throw r instanceof pe&&await Dd(n.traceWriter,"SessionStart",{kind:"blocked",err:r}),r}}async function EA(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await Dd(n.traceWriter,"SessionEnd",{kind:"decision",decision:r})}catch(r){if(r instanceof pe&&await Dd(n.traceWriter,"SessionEnd",{kind:"blocked",err:r}),r instanceof pe||r instanceof at){z(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}z(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var TA=_(()=>{"use strict";Me();bt();Ue()});function fz(e){return e==="max_tokens"||e==="length"}function xA(e){return e.maxTurnsHit?"max_turns_exceeded":e.hookBlocked?"hook_blocked":e.dispatchReason==="error"?"abort":e.abort!==null?e.abort:e.sawProviderError?"abort":fz(e.lastStopReason)?"truncated":"model_end_turn"}var RA=_(()=>{"use strict"});function Bo(e){return e==="abort"?Fy:null}var Fy,Ld=_(()=>{"use strict";Fy="Session ended via abort before reaching a terminal state. The transcript and witness trace are preserved \u2014 resume with `afk --resume <sessionId>` to continue from saved state, or re-run the task if the interruption was intentional."});import*as ki from"node:fs";import*as pl from"node:fs/promises";function Fd(e,t){return e.length>t?`${e.slice(0,t)}\u2026 [truncated]`:e}function gz(e){switch(e.type){case"message":return e.message.role!=="assistant"||!e.message.content?null:{kind:"assistant",text:Fd(e.message.content,AA)};case"chunk":{let t=e.chunk;return t.type==="tool_use_detail"?{kind:"tool",toolName:t.toolName,input:Fd(t.toolInput,CA)}:t.type==="tool_result"&&t.isError===!0?{kind:"tool_error",content:Fd(t.content,CA)}:null}case"done":{let t=e.metadata?.totalCostUsd,n=e.metadata?.durationMs;return{kind:"done",...typeof t=="number"?{costUsd:t}:{},...typeof n=="number"?{durationMs:n}:{}}}case"error":return{kind:"error",message:e.error.message};case"paused":return{kind:"paused",...e.resetsAt?{resetsAt:e.resetsAt.toISOString()}:{}};case"resumed":return{kind:"resumed"};default:return null}}function hz(e){let t=e.trim();if(!t)return null;try{let n=JSON.parse(t);return n.v!==1||typeof n.ts!="number"||typeof n.kind!="string"?null:n}catch{return null}}async function*Ny(e,t){if(!xc(e))return;let n=If(e),r=Ea(e),{fromStart:o=!1,signal:s}=t??{},i=0,a="",l=!1;async function*c(){let m=null;try{m=await pl.open(n,"r");let g=await m.stat();if(g.size<=i)return;let h=g.size-i,b=Buffer.allocUnsafe(h),{bytesRead:y}=await m.read(b,0,h,i);if(y===0)return;i+=y,a+=b.toString("utf8",0,y);let S=a.split(`
|
|
1596
1596
|
`);a=S.pop()??"";for(let w of S){let T=hz(w);if(T&&(T.kind==="closed"&&(l=!0),yield T,l))return}}catch(g){g.code!=="ENOENT"&&process.stderr.write(`[afk] session-ledger: tail read error for ${e}: ${String(g)}
|
|
1597
1597
|
`)}finally{m&&await m.close().catch(()=>{})}}if(o){if(yield*c(),l)return}else try{i=(await pl.stat(n)).size}catch{}let u=null,d=null,p=()=>new Promise(m=>{let g=setTimeout(()=>{d=null,m()},yz);d=()=>{clearTimeout(g),d=null,m()},s?.addEventListener("abort",()=>{clearTimeout(g),d=null,m()},{once:!0})});try{u=ki.watch(r,{persistent:!1},()=>{d?.()})}catch{}try{for(;!s?.aborted&&!l&&(await p(),!s?.aborted);)yield*c()}finally{u?.close()}}var AA,CA,Nd,yz,By=_(()=>{"use strict";K();AA=8e3,CA=400;Nd=class{sessionId;ledgerPath;stream=null;errored=!1;closed=!1;streamReady=!1;pendingLines=[];readyPromise=null;readyResolve=null;constructor(t){if(this.sessionId=t,!xc(t)){this.errored=!0,this.ledgerPath="";return}this.ledgerPath=If(t);try{ki.mkdirSync(Ea(t),{recursive:!0})}catch(n){process.stderr.write(`[afk] session-ledger: mkdir failed for ${t}: ${String(n)}
|
|
1598
1598
|
`),this.errored=!0}}get active(){return!this.errored&&!this.closed}record(t){if(this.errored||this.closed)return;let n={v:1,ts:Date.now(),...t},r=JSON.stringify(n)+`
|
|
@@ -1601,16 +1601,16 @@ ${Py}`,C=this.readOnlyMemory?hA:gA,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())})}};yz=250});function _A(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 IA(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 PA=_(()=>{"use strict"});var Bd,MA=_(()=>{"use strict";Bd=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 OA(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 $A(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 DA(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 LA=_(()=>{"use strict"});function Uy(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)?FA(bz(o)):o!==null&&typeof o=="object"?FA(wz(o)):null}function bz(e){return e.length===0?"[empty array]":e.length===1?"[1 item]":`[${e.length} items]`}function wz(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 FA(e){return e.length<=80?e:e.slice(0,79)+"\u2026"}var NA=_(()=>{"use strict"});function BA(e,t){if(!e)return null;let n=Sz.get(e);if(!n)return null;try{let r=n(t);if(r===null)return null;let o=Ao(r);return o.length>0?o:null}catch{return null}}var Sz,UA=_(()=>{"use strict";LA();NA();_o();Sz=new Map([["memory_search",OA],["memory_update",$A],["procedure_write",DA],["bash",Uy],["Bash",Uy]])});function vz(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 kz(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 Ez(e){let t=Buffer.byteLength(e,"utf8"),n=kz(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 Tz(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 xz(e){let t=e.isError===!0?null:BA(e.toolName,e.content),n=t!==null?{display:t}:{},r=vz(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}=Ez(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 jy(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 xz(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=Tz(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)){Pv(t.traceWriter,{kind:"monetary",runningCostUsd:t._runningCostUsd,maxBudgetUsd:t.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new Ar(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 jA=_(()=>{"use strict";Ct();Ue();UA()});import{z as Rz}from"zod";var vt,Hy=_(()=>{"use strict";Me();Ct();Ue();rt();vA();Ks();zc();TA();Ct();RA();Ld();Lh();Dy();By();q();Xn();jr();La();nn();Ly();PA();MA();jA();vt=class{config;_pendingPlanExitSeed;_prePlanPermissionMode;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}},getPrePlanMode:()=>this._prePlanPermissionMode}}:t,this.abortController=new AbortController,this._hookRegistry=t.hookRegistry,_A(t.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(t.model);Le(t.traceWriter,{phase:"session_init_start",model:n,resolvedModel:bt(t.model)??n,origin:Ur(t.surface),actor:Xu(t.parentSessionId)}),this.initSdkLifecycle()}initSdkLifecycle(){this.config.models&&Bc(this.config.models),Od(this.config);let t=bt(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=IA(this.config,t);this.stateManager=new Bd(n,r),this.inputStream=new vi(()=>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=>Md(a,void 0,{customTools:this.config.customTools,canUseTool:this.config.canUseTool});this.providerQuery=new $d({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>re(a),resolveApiKey:a=>ar(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 kA(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=jy(n,this.buildTransformDeps());if(n.type==="session.init"){await Le(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 we&&(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??Gc,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 qc(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(Rz.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 Tz(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 xz(e){let t=e.isError===!0?null:BA(e.toolName,e.content),n=t!==null?{display:t}:{},r=vz(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}=Ez(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 jy(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 xz(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=Tz(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)){Pv(t.traceWriter,{kind:"monetary",runningCostUsd:t._runningCostUsd,maxBudgetUsd:t.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new Ar(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 jA=_(()=>{"use strict";bt();Ue();UA()});import{z as Rz}from"zod";var kt,Hy=_(()=>{"use strict";Me();bt();Ue();rt();vA();Ks();zc();TA();bt();RA();Ld();Lh();Dy();By();q();Xn();jr();La();nn();Ly();PA();MA();jA();kt=class{config;_pendingPlanExitSeed;_prePlanPermissionMode;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}},getPrePlanMode:()=>this._prePlanPermissionMode}}:t,this.abortController=new AbortController,this._hookRegistry=t.hookRegistry,_A(t.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(t.model);Le(t.traceWriter,{phase:"session_init_start",model:n,resolvedModel:wt(t.model)??n,origin:Ur(t.surface),actor:Xu(t.parentSessionId)}),this.initSdkLifecycle()}initSdkLifecycle(){this.config.models&&Bc(this.config.models),Od(this.config);let t=wt(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=IA(this.config,t);this.stateManager=new Bd(n,r),this.inputStream=new vi(()=>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=>Md(a,void 0,{customTools:this.config.customTools,canUseTool:this.config.canUseTool});this.providerQuery=new $d({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>re(a),resolveApiKey:a=>ar(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 kA(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=jy(n,this.buildTransformDeps());if(n.type==="session.init"){await Le(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 pe&&(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??Gc,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 qc(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(Rz.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=od(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=jy(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 Nd(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 at("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,og))]).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=bt(t);typeof t=="string"&&t.length>0&&await this.providerQuery.setModel(t),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(t){if(t==="plan"){let n=this.stateManager.getSessionMetadata().permissionMode;n!=="plan"&&(this._prePlanPermissionMode=n==="autonomous"?void 0:n)}await this.providerQuery.setPermissionMode(t),this.stateManager.setSessionMetadata(n=>({...n,permissionMode:t}))}getPrePlanMode(){return this._prePlanPermissionMode}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&&Ck(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,og))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(t){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await this.emitClosure(t).catch(()=>{}),await this.sealTraceWriter(t).catch(()=>{}),await EA(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=Bo(r);await $v(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 Ar?n="budget_exceeded":o instanceof jt?n="timeout":typeof o=="string"&&o.startsWith("Budget ")?n="budget_exceeded":typeof o=="string"&&o.includes("timed out")?n="timeout":n="abort"}return xA({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 at("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";Hy()});var cI={};mc(cI,{KeychainOAuthProvider:()=>Mi,clearOauthPending:()=>Xy,readOauthPending:()=>lI});import{existsSync as tp,mkdirSync as iI,readFileSync as np,writeFileSync as Yy}from"node:fs";import{execFileSync as nI}from"node:child_process";import{randomUUID as VV}from"node:crypto";import{homedir as rI,userInfo as oI}from"node:os";import{join as sI,dirname as aI}from"node:path";function XV(){let e=process.platform==="darwin",t=process.platform==="linux";return{read(){if(e)try{return nI("security",["find-generic-password","-s","Claude Code-credentials","-a",oI().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()||void 0}catch{return}if(t){let n=sI(rI(),".claude",".credentials.json");if(!tp(n))return;try{return np(n,"utf-8")}catch{return}}},write(n){if(e)nI("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",oI().username,"-w",n],{stdio:["ignore","ignore","ignore"]});else if(t){let r=sI(rI(),".claude",".credentials.json");iI(aI(r),{recursive:!0}),Yy(r,n,{encoding:"utf-8",mode:384})}}}}function lI(){let e=Ta();if(!tp(e))return{};let t;try{t=JSON.parse(np(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<=YV&&(n[r]={status:"oauth_pending",authorizationUrl:s.authorizationUrl,timestamp:s.timestamp})}return n}function Xy(e){let t=Ta();if(!tp(t))return;let n;try{n=JSON.parse(np(t,"utf-8"))}catch{return}e in n&&(delete n[e],Yy(t,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}))}function ZV(e,t){let n=Ta();iI(aI(n),{recursive:!0});let r={};if(tp(n))try{r=JSON.parse(np(n,"utf-8"))}catch{}let o=new URL(t),s=o.origin+o.pathname;r[e]={status:"oauth_pending",authorizationUrl:s,timestamp:Date.now()},Yy(n,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384})}var YV,Mi,rp=_(()=>{"use strict";K();YV=600*1e3;Mi=class{serverName;backend;constructor(t,n=XV()){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{Xy(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=VV();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=od(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=jy(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 Nd(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 at("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,og))]).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=wt(t);typeof t=="string"&&t.length>0&&await this.providerQuery.setModel(t),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(t){if(t==="plan"){let n=this.stateManager.getSessionMetadata().permissionMode;n!=="plan"&&(this._prePlanPermissionMode=n==="autonomous"?void 0:n)}await this.providerQuery.setPermissionMode(t),this.stateManager.setSessionMetadata(n=>({...n,permissionMode:t}))}getPrePlanMode(){return this._prePlanPermissionMode}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&&Ck(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,og))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(t){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await this.emitClosure(t).catch(()=>{}),await this.sealTraceWriter(t).catch(()=>{}),await EA(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=Bo(r);await $v(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 Ar?n="budget_exceeded":o instanceof jt?n="timeout":typeof o=="string"&&o.startsWith("Budget ")?n="budget_exceeded":typeof o=="string"&&o.includes("timed out")?n="timeout":n="abort"}return xA({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 at("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";Hy()});var cI={};mc(cI,{KeychainOAuthProvider:()=>Mi,clearOauthPending:()=>Xy,readOauthPending:()=>lI});import{existsSync as tp,mkdirSync as iI,readFileSync as np,writeFileSync as Yy}from"node:fs";import{execFileSync as nI}from"node:child_process";import{randomUUID as VV}from"node:crypto";import{homedir as rI,userInfo as oI}from"node:os";import{join as sI,dirname as aI}from"node:path";function XV(){let e=process.platform==="darwin",t=process.platform==="linux";return{read(){if(e)try{return nI("security",["find-generic-password","-s","Claude Code-credentials","-a",oI().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()||void 0}catch{return}if(t){let n=sI(rI(),".claude",".credentials.json");if(!tp(n))return;try{return np(n,"utf-8")}catch{return}}},write(n){if(e)nI("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",oI().username,"-w",n],{stdio:["ignore","ignore","ignore"]});else if(t){let r=sI(rI(),".claude",".credentials.json");iI(aI(r),{recursive:!0}),Yy(r,n,{encoding:"utf-8",mode:384})}}}}function lI(){let e=Ta();if(!tp(e))return{};let t;try{t=JSON.parse(np(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<=YV&&(n[r]={status:"oauth_pending",authorizationUrl:s.authorizationUrl,timestamp:s.timestamp})}return n}function Xy(e){let t=Ta();if(!tp(t))return;let n;try{n=JSON.parse(np(t,"utf-8"))}catch{return}e in n&&(delete n[e],Yy(t,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}))}function ZV(e,t){let n=Ta();iI(aI(n),{recursive:!0});let r={};if(tp(n))try{r=JSON.parse(np(n,"utf-8"))}catch{}let o=new URL(t),s=o.origin+o.pathname;r[e]={status:"oauth_pending",authorizationUrl:s,timestamp:Date.now()},Yy(n,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384})}var YV,Mi,rp=_(()=>{"use strict";K();YV=600*1e3;Mi=class{serverName;backend;constructor(t,n=XV()){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{Xy(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=VV();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}`;ZV(this.serverName,n);let o=!1;try{let{pushIfConfigured:s}=await Promise.resolve().then(()=>(Io(),Gg));o=await s(r)!==null}catch{}o||process.stderr.write(`[mcp:${this.serverName}] OAuth authorization required.
|
|
1610
1610
|
Open this URL to authorize:
|
|
1611
1611
|
${n}
|
|
1612
1612
|
Status written to: ${Ta()}
|
|
1613
|
-
`)}_readSlot(){let t=this.backend.read();if(!t)return{};try{return JSON.parse(t).mcpOAuth?.[this.serverName]??{}}catch{return{}}}_updateSlot(t){let n=this.backend.read(),r={};if(n)try{r=JSON.parse(n)}catch{}let o=r.mcpOAuth??{},s=o[this.serverName]??{};o[this.serverName]=t(s),r.mcpOAuth=o,this.backend.write(JSON.stringify(r))}}});K();Cc();import{config as jS}from"dotenv";import{Command as eoe}from"commander";q();import Mf from"chalk";function lv(){let e=v.FORCE_COLOR;if(e&&e.length>0)return;let t=v.NO_COLOR;if(t&&t.length>0){Mf.level=0;return}let n=v.CI;if(n&&n.length>0){Mf.level=0;return}process.stdout.isTTY||(Mf.level=0)}import wI from"chalk";import mY from"ora";
|
|
1613
|
+
`)}_readSlot(){let t=this.backend.read();if(!t)return{};try{return JSON.parse(t).mcpOAuth?.[this.serverName]??{}}catch{return{}}}_updateSlot(t){let n=this.backend.read(),r={};if(n)try{r=JSON.parse(n)}catch{}let o=r.mcpOAuth??{},s=o[this.serverName]??{};o[this.serverName]=t(s),r.mcpOAuth=o,this.backend.write(JSON.stringify(r))}}});K();Cc();import{config as jS}from"dotenv";import{Command as eoe}from"commander";q();import Mf from"chalk";function lv(){let e=v.FORCE_COLOR;if(e&&e.length>0)return;let t=v.NO_COLOR;if(t&&t.length>0){Mf.level=0;return}let n=v.CI;if(n&&n.length>0){Mf.level=0;return}process.stdout.isTTY||(Mf.level=0)}import wI from"chalk";import mY from"ora";bt();function cv(e){let t=e instanceof Error?e.message:String(e);return t.toLowerCase().includes("rate limit")||t.toLowerCase().includes("too many requests")}function uv(e){let t=e instanceof Error?e.message:String(e);return t.toLowerCase().includes("network")||t.toLowerCase().includes("connect")||t.toLowerCase().includes("timeout")}function xs(e){if(e instanceof Ar)return{kind:"budget_exceeded",userMessage:`Session stopped: cost ceiling reached ($${e.runningCostUsd.toFixed(4)} of $${e.maxBudgetUsd.toFixed(4)} limit).`,exitCode:1,raw:e};if(e instanceof Ac)return{kind:"unsupported_config",userMessage:`The "${e.provider}" provider does not support this configuration option.`,hint:`Option "${e.field}" is not available for provider "${e.provider}". Switch to a compatible provider or remove the option.`,exitCode:1,raw:e};if(e instanceof pe)return{kind:"hook_blocked",userMessage:`A hook blocked the operation (event: ${e.event}).`,...e.reason!==void 0?{hint:e.reason}:{},exitCode:1,raw:e};if(e instanceof jt){let s=Math.round(e.timeoutMs/1e3);return{kind:"timeout",userMessage:`The operation timed out after ${s} second${s!==1?"s":""}.`,hint:`Timeout: ${e.timeoutMs}ms (${s}s). Increase the timeout or retry.`,exitCode:124,raw:e}}let t=e,n=e instanceof Error?e.message:String(e),r=n.toLowerCase();return t.status===401||e instanceof Error&&e.name==="AuthenticationError"?{kind:"auth",userMessage:"Authentication failed. Check that your API key is valid and has not expired.",hint:"Verify the ANTHROPIC_API_KEY environment variable or run `afk login`.",exitCode:1,raw:e}:t.status===429||cv(e)?{kind:"rate_limit",userMessage:"Anthropic rate limit reached. The request was rejected (HTTP 429).",hint:"Wait a moment and retry, or reduce the request frequency.",exitCode:1,raw:e}:t.status===529||t.status===503?{kind:"overloaded",userMessage:`Anthropic API is temporarily overloaded (HTTP ${t.status}). All retry attempts were exhausted.`,hint:"Wait a minute and try again, or switch to a less loaded model (e.g. sonnet).",exitCode:1,raw:e}:n==="Not in a git repository."||r.includes("not in a git repository")?{kind:"not_git_repo",userMessage:"This command must be run from inside a git repository.",hint:"Run `git init` to initialise a repository, or change to a directory that is already a git repo.",exitCode:1,raw:e}:uv(e)||r.includes("econnrefused")||r.includes("etimedout")?{kind:"network",userMessage:"Network error: unable to reach the API endpoint.",hint:"Check your internet connection and try again.",exitCode:1,raw:e}:{kind:"unknown",userMessage:(e instanceof Error?e.message:String(e))||"An unexpected error occurred.",exitCode:1,raw:e}}import vN from"string-width";var Of=/\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P^_X][^\x1B]*\x1B\\|[@-OQ-WYZ\\\-])/g,dv=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;function Be(e){return e.replace(Of,"")}function V(e){return vN(e)}function _c(e){return e.length===0?[]:dv?Array.from(dv.segment(e),t=>t.segment):Array.from(e)}function kN(e){let t=[],n=0,r;for(Of.lastIndex=0;(r=Of.exec(e))!==null;){if(r.index>n)for(let o of _c(e.slice(n,r.index)))t.push({type:"text",value:o});t.push({type:"ansi",value:r[0]}),n=r.index+r[0].length}if(n<e.length)for(let o of _c(e.slice(n)))t.push({type:"text",value:o});return t}function tt(e,t){let n=Math.max(0,t-V(e));return e+" ".repeat(n)}function EN(e,t){let n=Math.max(0,t-V(e));return" ".repeat(n)+e}function $f(e,t,n="left"){let r=Math.max(0,t-V(e));if(r===0)return e;if(n==="right")return EN(e,t);if(n==="center"){let o=Math.floor(r/2);return" ".repeat(o)+e+" ".repeat(r-o)}return tt(e,t)}var TN=/^\x1b\]8;[^;\x07\x1b]*;(.*?)(?:\x07|\x1b\\)$/s,xN="\x1B]8;;\x1B\\";function ne(e,t,n="\u2026"){if(t<=0)return"";if(V(e)<=t)return e;let r=V(n),o=Math.max(0,t-r),s=0,i="",a=!1,l=!1;for(let c of kN(e)){if(c.type==="ansi"){i+=c.value,a=!0;let d=TN.exec(c.value);d&&(l=(d[1]??"").length>0);continue}let u=s+V(c.value);if(u>o)break;i+=c.value,s=u}return i+n+(l?xN:"")+(a?"\x1B[0m":"")}function pv(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.trunc(e))):0}function Df(e,t){let n=pv(t,e.length);if(n===0||e.length===0)return 0;let r=0;for(let o of _c(e)){let s=r+o.length;if(s>=n)return r;r=s}return r}function wo(e,t){let n=pv(t,e.length);if(n>=e.length||e.length===0)return e.length;let r=0;for(let o of _c(e)){let s=r+o.length;if(r>=n||n>r&&n<s)return s;r=s}return e.length}function Q(){let e=process.stdout.columns;return typeof e=="number"&&e>0?e:80}var Ic=new Set,Pc=new Set,Rs=!1,So=null;function RN(){for(let e of Ic)try{e()}catch{}}function CN(){for(let e of Pc)try{e()}catch{}}function AN(){So!==null&&clearTimeout(So),So=setTimeout(()=>{So=null,RN()},150)}function Lf(){CN(),AN()}function _N(e){return Ic.add(e),Rs||(process.stdout.on("resize",Lf),Rs=!0),()=>{Ic.delete(e),mv()}}function IN(e){return Pc.add(e),Rs||(process.stdout.on("resize",Lf),Rs=!0),()=>{Pc.delete(e),mv()}}function mv(){Ic.size===0&&Pc.size===0&&(Rs&&(process.stdout.off("resize",Lf),Rs=!1),So!==null&&(clearTimeout(So),So=null))}var He={subscribe:_N,subscribeImmediate:IN};import fv from"wrap-ansi";function le(e,t,n={}){if(!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY)return e;let r=Math.floor(t);return fv(e,r,{hard:n.breakLongWords??!1,trim:!1,wordWrap:!0})}function gv(e,t){return!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY?e:fv(e,Math.floor(t),{hard:!0,trim:!1,wordWrap:!1})}import Ie from"chalk";var f={brand:Ie.hex("#E67E4C"),mint:Ie.hex("#5FE3A1"),goblin:Ie.hex("#9CB04A"),user:Ie.cyan,caret:Ie.hex("#7AA2F7"),tool:Ie.hex("#DCDCAA"),chrome:Ie.hex("#B0B8C2"),syntaxString:Ie.italic.hex("#8AB07A"),toolArg:Ie.dim.white,thinking:Ie.italic.hex("#9B8FB5"),success:Ie.green,error:Ie.red,warning:Ie.yellow,plan:Ie.hex("#9F7CE0"),bypass:Ie.bold.hex("#FF6AC1"),meta:Ie.blackBright,info:Ie.hex("#5BA8FF"),fileRef:Ie.hex("#56B5A8"),heading:Ie.bold.white,label:Ie.dim,dim:Ie.dim,bold:Ie.bold,italic:Ie.italic,diffAdd:Ie.green,diffRemove:Ie.red,diffHunk:Ie.blackBright};function Ht(){return Math.max(22,Q()-6)}function xa(e,t){return ne(e,t)}var PN={ok:f.success("\u25CF"),warn:f.warning("\u25CF"),error:f.error("\u25CF"),info:f.info("\u25C6")};function hv(e,t){let o=t.reduce((w,T)=>Math.max(w,V(T.label)),0),s=t.reduce((w,T)=>Math.max(w,V(T.value)),0),i=o+4+2+s,a=Math.min(Q()-4,100),l=Math.max(44,V(e),i,a);l=Math.min(l,Ht());let c=l+4,u=f.dim,d=u("\u256D"+"\u2500".repeat(c)+"\u256E"),p=u("\u251C"+"\u2500".repeat(c)+"\u2524"),m=u("\u2570"+"\u2500".repeat(c)+"\u256F"),g=u("\u2502"),b=le(e,l).split(`
|
|
1614
1614
|
`).map(w=>g+" "+tt(w,l)+" "+g),y=Math.max(1,l-o-4-2),S=t.map(w=>{let T=w.kind?PN[w.kind]+" ":" ",x=f.dim(tt(xa(w.label,o),o)),C=" ".repeat(4),R=xa(w.value,y),k=tt(R,y),$=x+C+T+k;return g+" "+$+" "+g});return[d,...b,p,...S,m].join(`
|
|
1615
1615
|
`)}import{sep as Bf}from"node:path";q();q();import Ff from"chalk";var yv={".":null,D:[74,92,36],M:[139,166,63],L:[178,197,88],Y:[245,213,71],K:[13,18,9],W:[238,238,222],X:[42,42,26]},Mc=[".......KKKKK.......","......WKKLKKW......",".....KKWMLMWKK.....","..DDKKWLMMMLWKKDD..","DDD..KMMMMMMMK..DDD","..DDKMMMMMMMMMKDD..","...KKMMKKKKKMMKK...","...KMMKKKKKKKMMK...","...KMMMYMDMYMMMK...","...KMMMMMMMMMMMK...","...KKMMXXXXXMMKK...","....KKMMWXXMMKK....",".....KKMWMMMKK.....",".....KKMMMMMKK.....","......KKMMMKK......",".......KKKKK......."],Nf=19,Ra=8;function MN(e,t){if(e.length!==t.length)throw new Error(`pixel row width mismatch: top=${e.length}, bot=${t.length}`);let n="";for(let r=0;r<e.length;r++){let o=yv[e[r]??"."]??null,s=yv[t[r]??"."]??null;!o&&!s?n+=" ":o&&!s?n+=Ff.rgb(o[0],o[1],o[2])("\u2580"):!o&&s?n+=Ff.rgb(s[0],s[1],s[2])("\u2584"):o&&s&&(n+=Ff.bgRgb(s[0],s[1],s[2]).rgb(o[0],o[1],o[2])("\u2580"))}return n}function ON(){if(Mc.length!==Ra*2)throw new Error(`GOBLIN_GRID has ${Mc.length} pixel rows but MASCOT_HEIGHT*2 = ${Ra*2}`);let e=[];for(let t=0;t<Ra;t++){let n=Mc[t*2]??"",r=Mc[t*2+1]??"";e.push(MN(n,r))}return e}function bv(e="idle"){return v.AFK_BANNER_PLAIN==="1"?[]:ON()}function wv(){return v.AFK_BANNER_PLAIN==="1"}function vv(e){let t=e.model!==void 0||e.worktree!==void 0||e.cwd!==void 0||e.version!==void 0;return t&&!wv()?DN(e):Sv(t?$N(e):e)}function $N(e){let t=e.mode;e.model!==void 0&&e.model.length>0&&(t=`${e.model} \xB7 ${t}`),e.version!==void 0&&e.version.length>0&&(t=`${t} \xB7 ${kv(e.version)}`);let n=[];e.worktree!==void 0&&e.worktree.length>0&&n.push(`branch ${e.worktree}`),e.cwd!==void 0&&e.cwd.length>0&&n.push(Ev(e.cwd));let r=n.join(" \xB7 "),o=e.metaLine!==void 0?e.metaLine:r.length>0?r:void 0,s={mode:t};return o!==void 0&&(s.metaLine=o),e.hintLine!==void 0&&(s.hintLine=e.hintLine),s}function Sv(e){let t="Agent AFK",n=" \xB7 ",r=f.bold(t)+f.dim(n)+e.mode,o=t+n+e.mode,s=Math.min(Q()-4,120),i=Math.max(54,V(o)+4,s);i=Math.min(i,Ht());let a=i+4,l=f.dim,c=l("\u256D"+"\u2500".repeat(a)+"\u256E"),d=le(r,i).split(`
|
|
1616
1616
|
`).map(g=>l("\u2502")+" "+tt(g,i)+" "+l("\u2502")),p=l("\u2570"+"\u2500".repeat(a)+"\u256F"),m=[c,...d,p];return e.metaLine!==void 0&&m.push(...le(f.dim(" "+e.metaLine),Q()).split(`
|
|
@@ -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).`,Pz=Cz.map(e=>new RegExp(`(?:^|-)${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:-|$)`,"i"));function Mz(e){return e?Pz.some(t=>t.test(e)):!1}function Oz(e){return _z.some(t=>t.test(e))}function $z(e){let t=0;for(let n of Az)n.test(e)&&t++;return t}function HA(e){if(e.event!=="SubagentStop")return{};let t=e.lastMessage??"";return t.length<600?{}:Mz(e.agentType)?{}:Oz(t)?{}:$z(t)<2?{}:{injectContext:Iz}}cn();nl();cg();function WA(e){return function(n){if(n.event!=="PreToolUse")return{};if(n.parentSessionId)return{};if(e()!=="plan")return{};let{toolName:r}=n;if(Pn(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=tu(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{}}}Na();nl();import KA from"path";var Dz=["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"],Lz=["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"],Fz=["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 Nz(e){return typeof e=="object"&&e!==null&&"command"in e?String(e.command??""):typeof e=="string"?e:""}function Bz(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 Uz(e){for(let t of Dz)if(e.includes(t))return"high";for(let t of Lz)if(e.includes(t))return"medium";for(let t of Fz)if(e.includes(t))return"safe";return"medium"}function jz(e,t){if(!e)return"safe";let n=ir(KA.resolve(t.cwd,e)),r=Rg();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=ir(t.workspaceRoot);if(KA.relative(o,n).startsWith(".."))return"high"}return n.includes("/node_modules/")?"medium":"safe"}function GA(e,t,n){let r=e.toLowerCase();if(r==="bash"){let o=Nz(t);return Uz(o)}if(r==="write_file"||r==="edit_file"){let o=Bz(t);return jz(o,n)}return Pn(e)==="read"?"safe":r==="send_telegram"?"medium":"safe"}Br();Ue();Si();var Hz=3e5,qA=300;function zA(e,t,n,r){let o=r?.approvalTimeoutMs??Hz,s=r?.promptForApproval??!0,i=r?.traceWriter,a=r?.route??((c,u)=>ct.route(c,u));async function l(c,u,d){let p=Date.now(),m=Wz(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 tn(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(ml(c,`no approval arrived within ${Math.round(o/1e3)}s`),"timeout");if(x.action!=="accept")return T(ml(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(ml(c,"the operator denied it"),"denied"):T(ml(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 GA(p,u.input,{cwd:m,workspaceRoot:m})!=="high"?{}:u.parentSessionId!==void 0||!s?ml(p,"AFK mode runs autonomously without a human watching"):l(p,u.input,d)}}function Wz(e,t){let n=Kz(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 Kz(e){let t;try{t=typeof e=="string"?e:JSON.stringify(e)}catch{t=String(e)}return t?(t=Ve(t),t.length>qA?`${t.slice(0,qA)}\u2026 [truncated]`:t):""}function ml(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.`}}Qe();import{mkdirSync as zz,rmSync as Jz,writeFileSync as Vz}from"fs";import{join as Wy}from"path";
|
|
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 Kz(e){let t;try{t=typeof e=="string"?e:JSON.stringify(e)}catch{t=String(e)}return t?(t=Ve(t),t.length>qA?`${t.slice(0,qA)}\u2026 [truncated]`:t):""}function ml(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.`}}Qe();import{mkdirSync as zz,rmSync as Jz,writeFileSync as Vz}from"fs";import{join as Wy}from"path";bt();function Gz(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=JA(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 JA(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 qz(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 VA(e,t,n={}){if(e.nodes.length===0)return{outputs:{},failed:[],skipped:[]};Gz(e);let{failFast:r=!0,nodeTimeoutMs:o}=n,s=o!==void 0&&Number.isFinite(o)&&o>0,i=JA(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 jt(`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),qz(T,i.downstream,u),r&&m.abort("fail-fast")}}}}finally{t.removeEventListener("abort",g)}return{outputs:l,failed:c,skipped:Array.from(u)}}Jt();bt();async function Ud(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 jt?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 VA({nodes:l,edges:o},a,{failFast:s,nodeTimeoutMs:i})}rt();Qn();jr();er();K();var YA=1e3,jd=36e5,XA=1,ZA=1e3;function Yz(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<YA)throw new Error(`"node_timeout_ms" must be at least ${YA}ms (got ${d}). Sub-second timeouts are almost always a unit mistake.`);c=Math.min(jd,d),d>jd&&l.push(`node_timeout_ms clamped: requested ${d}ms exceeds the maximum ${jd}ms; using ${jd}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<XA)throw new Error(`"max_tool_calls_per_node" must be at least ${XA}`);if(d>ZA)throw new Error(`"max_tool_calls_per_node" must be at most ${ZA} (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 fl=8e3,QA=500,e_=4e3;function Xz(e){if(e==null)return;let t=typeof e=="string"?e:JSON.stringify(e);if(t.length!==0)return t.length>e_?t.slice(0,e_)+`
|
|
1669
1669
|
\u2026 (truncated)`:t}function Zz(e,t,n,r){try{let o=Wy(Jn(),e,"compose",t);zz(o,{recursive:!0});let s=Wy(o,`${n}.txt`);return Vz(s,r,"utf8"),s}catch{return}}function Qz(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>fl){let l=Zz(t.sessionId,t.callId,o,i);r.push({nodeId:o,emittedChars:fl,totalChars:i.length,...l!==void 0?{spillPath:l}:{}});let c=l!==void 0?`
|
|
1670
1670
|
\u2026 (truncated at ${fl} / ${i.length} chars \u2014 full output at ${l})`:`
|
|
1671
1671
|
\u2026 (truncated at ${fl} / ${i.length} chars)`;a=i.slice(0,fl)+c}else a=i;n.push(`## ${o}
|
|
@@ -1703,7 +1703,7 @@ Choose how to handle this and future requests for this path.`,p=await ct.route({
|
|
|
1703
1703
|
${S.trim()}`:""}`),g({decision:{}})}}),h.on("error",k=>{m||(clearTimeout(R),console.warn(`[hooks] command error: ${s} \u2014 ${k.message}`),g({decision:{}}))})})}function FJ(e){let t=e.trim();if(!t)return{};let n;try{n=JSON.parse(t)}catch{return{}}if(n===null||typeof n!="object"||Array.isArray(n))return{};let r=n,o={};r.continue===!1&&(o.continue=!1),r.decision==="block"?o.decision="block":r.decision==="approve"&&(o.decision="approve"),typeof r.reason=="string"&&(o.reason=r.reason);let s=r.hookSpecificOutput;if(s!==null&&typeof s=="object"&&!Array.isArray(s)){let i=s;typeof i.additionalContext=="string"&&(o.injectContext=i.additionalContext)}return o}function S_(e,t,n){if(!t.userGlobalEnabled){let i=[];for(let a of Object.keys(t.hooks)){let l=t.hooks[a];if(l!==void 0)for(let c of l)for(let u of c.hooks)i.push(`${a}: ${u.command}`)}i.length>0&&console.warn(`[hooks] shell hooks are disabled (enableShellHooks not set in user-global config).
|
|
1704
1704
|
Skipped ${i.length} hook(s):
|
|
1705
1705
|
`+i.map(a=>` - ${a}`).join(`
|
|
1706
|
-
`));return}let r=n.cwd??process.cwd(),o=n.sessionId,s=["SessionStart","SessionEnd","SubagentStart","SubagentStop","PreToolUse","PostToolUse","PreCompact","PostToolUseFailure","Stop","UserPromptSubmit"];for(let i of s){let a=t.hooks[i];if(!(a===void 0||a.length===0))for(let l of a){let c=y_(l.matcher);for(let u of l.hooks){let d=u.command,p=u.timeoutMs,m=async g=>(g.event==="PreToolUse"||g.event==="PostToolUse"||g.event==="PostToolUseFailure")&&!c(g.toolName)?{}:(await w_({command:d,context:g,agentCwd:r,sessionId:o,timeoutMs:p})).decision;e.register(i,m)}}}}var v_=!1;function Ti(e,t,n,r,o,s,i){let a=ok();a.register("SubagentStop",HA);let l=n??new lt;r!==void 0&&(a.register("PreToolUse",WA(r)),a.register("PreToolUse",zA(r,s?.cwd,i,{...s?.traceWriter!==void 0?{traceWriter:s.traceWriter}:{}}),{longRunning:!0}));let c={current:void 0},u=v.AFK_DISABLE_PATH_APPROVAL==="1";if(u&&!v_&&(v_=!0,console.warn("[path-approval] disabled via AFK_DISABLE_PATH_APPROVAL=1 \u2014 typed-file path-access prompts and bash restrictions are OFF for this process.")),!u){let d=p_({getGrantManager:()=>c.current,getCwd:i??(()=>s?.cwd),surface:NJ(t)});a.register("PreToolUse",d.preToolUse,{longRunning:!0}),a.register("PostToolUse",d.postToolUse),a.register("SessionEnd",d.sessionEnd),a.register("PreToolUse",g_({getGrantManager:()=>c.current,disableInterpreterGuard:v.AFK_DISABLE_BASH_INTERPRETER_GUARD==="1",forceInterpreterGuard:v.AFK_FORCE_BASH_INTERPRETER_GUARD==="1"}))}return a.register("SessionEnd",Eh(l,t)),a.register("SessionEnd",d=>d.event!=="SessionEnd"?{}:(d.sessionId&&t_(d.sessionId),{})),a.register("SessionEnd",o_),e&&a.register("SubagentStop",d=>d.event!=="SubagentStop"?{}:d.status==="idle"||d.status==="running"?{}:(e({subagentId:d.subagentId,status:d.status,durationMs:d.durationMs,agentType:d.agentType}),{})),o!==void 0&&S_(a,o,{cwd:s?.cwd,sessionId:s?.sessionId}),{registry:a,memoryStore:l,pathApprovalGrantRef:c}}function NJ(e){return e==="telegram"?"telegram":e==="cli"||e==="repl"?"repl":"unknown"}cn();nn();function
|
|
1706
|
+
`));return}let r=n.cwd??process.cwd(),o=n.sessionId,s=["SessionStart","SessionEnd","SubagentStart","SubagentStop","PreToolUse","PostToolUse","PreCompact","PostToolUseFailure","Stop","UserPromptSubmit"];for(let i of s){let a=t.hooks[i];if(!(a===void 0||a.length===0))for(let l of a){let c=y_(l.matcher);for(let u of l.hooks){let d=u.command,p=u.timeoutMs,m=async g=>(g.event==="PreToolUse"||g.event==="PostToolUse"||g.event==="PostToolUseFailure")&&!c(g.toolName)?{}:(await w_({command:d,context:g,agentCwd:r,sessionId:o,timeoutMs:p})).decision;e.register(i,m)}}}}var v_=!1;function Ti(e,t,n,r,o,s,i){let a=ok();a.register("SubagentStop",HA);let l=n??new lt;r!==void 0&&(a.register("PreToolUse",WA(r)),a.register("PreToolUse",zA(r,s?.cwd,i,{...s?.traceWriter!==void 0?{traceWriter:s.traceWriter}:{}}),{longRunning:!0}));let c={current:void 0},u=v.AFK_DISABLE_PATH_APPROVAL==="1";if(u&&!v_&&(v_=!0,console.warn("[path-approval] disabled via AFK_DISABLE_PATH_APPROVAL=1 \u2014 typed-file path-access prompts and bash restrictions are OFF for this process.")),!u){let d=p_({getGrantManager:()=>c.current,getCwd:i??(()=>s?.cwd),surface:NJ(t)});a.register("PreToolUse",d.preToolUse,{longRunning:!0}),a.register("PostToolUse",d.postToolUse),a.register("SessionEnd",d.sessionEnd),a.register("PreToolUse",g_({getGrantManager:()=>c.current,disableInterpreterGuard:v.AFK_DISABLE_BASH_INTERPRETER_GUARD==="1",forceInterpreterGuard:v.AFK_FORCE_BASH_INTERPRETER_GUARD==="1"}))}return a.register("SessionEnd",Eh(l,t)),a.register("SessionEnd",d=>d.event!=="SessionEnd"?{}:(d.sessionId&&t_(d.sessionId),{})),a.register("SessionEnd",o_),e&&a.register("SubagentStop",d=>d.event!=="SubagentStop"?{}:d.status==="idle"||d.status==="running"?{}:(e({subagentId:d.subagentId,status:d.status,durationMs:d.durationMs,agentType:d.agentType}),{})),o!==void 0&&S_(a,o,{cwd:s?.cwd,sessionId:s?.sessionId}),{registry:a,memoryStore:l,pathApprovalGrantRef:c}}function NJ(e){return e==="telegram"?"telegram":e==="cli"||e==="repl"?"repl":"unknown"}cn();nn();function ge(e){let t=Math.round(e/1e3);if(t<=0)return"0s";let n=Math.floor(t/86400),r=Math.floor(t%86400/3600),o=Math.floor(t%3600/60),s=t%60;return n>0?`${n}d ${r}h`:r>0?`${r}h ${o}m`:o>0?`${o}m ${s}s`:`${s}s`}function st(e){return e===0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function ie(e){if(!Number.isFinite(e))return"0";if(e<1e3)return String(e);if(e<1e6){let n=e/1e3;return n%1===0?`${n}k`:`${n.toFixed(1).replace(/\.0$/,"")}k`}let t=e/1e6;return t%1===0?`${t}m`:`${t.toFixed(1).replace(/\.0$/,"")}m`}Je();Ot();K();import{existsSync as BJ,readdirSync as UJ}from"node:fs";var jJ='[skill-routing: active]\n\nRoute recurring work through registered skills instead of rolling ad-hoc solutions:\n\n- Before non-trivial implementation (multi-file edits, new features, config/build changes \u2014 anything that writes) \u2192 `/ground-state` first. Do NOT substitute inline `git status`/`get_runtime_state` \u2014 the skill triangulates git + infra + prior-session memory in parallel, which the inline checks miss. If `/ground-state` dispatch fails (depth limit, unavailable), fall back to inline checks AND note the coverage gap.\n- Bugs, failing tests, or regressions \u2192 `/diagnose`\n- High-stakes sub-agent output that will drive edits or commits \u2192 `/shadow-verify` before acting\n- Refactor needing parallel waves \u2192 `/parallelize`\n- Parallel or dependent multi-task work \u2192 `compose` tool (DAG of subagent nodes)\n- Greenfield feature where a written spec would genuinely help (novel scope, multi-day work, or external stakeholders involved) \u2192 `/mint`\n\nDo NOT reach for `/mint` for: bug fixes (use `/diagnose`), refactors with known shape, single-feature edits, work already spec\'d in chat, or anything where the spec/approve pause would feel like ceremony. Implement directly in those cases.\n\nCommon composed sequences \u2014 reach for these when the task shape matches:\n\n- Bug with failing test and non-trivial fix \u2192 `/diagnose` \u2192 `/shadow-verify` on the proposed fix\n- Refactor needing parallel waves \u2192 plan \u2192 `/parallelize` \u2192 build waves\n- Diagnose + fix in parallel \u2192 `compose` with two independent nodes\n- Research \u2192 implement \u2192 verify pipeline \u2192 `compose` with edges: research\u2192implement\u2192verify\n- Multiple independent investigations \u2192 `compose` with N nodes, no edges\n\nReach for context-isolated investigators when the task is exploratory:\n\n- Map an unfamiliar module before editing \u2192 `/gather` or `/research`\n- Re-derive a load-bearing claim independently \u2192 `/shadow-verify`\n- Audit a diff before merge \u2192 `/review`\n- Generate alternatives before committing to a plan \u2192 `/devils-advocate`\n\nOr dispatch a raw `agent` call when no skill matches but the work is parallelizable, verification-heavy, or would otherwise consume substantial inline context.\n\nSkip orchestration for: single-line edits, trivial Q&A, and direct tool calls the user explicitly requested. The goal is leverage, not ceremony. If a skill would add overhead without adding value, don\'t invoke it.\n\nDefault to acting autonomously. `ask_question` is a last resort, not a first move \u2014 every question blocks on the operator, who is often away from keyboard.\n\nBefore you ask, you MUST exhaust the tools you have: read the files, check git, search the codebase and docs, inspect runtime state. If any tool can get you the answer, use the tool \u2014 never ask the operator for something you can discover yourself. When a wrong guess would be cheap or reversible, make a reasonable assumption, proceed, and state the assumption instead of asking.\n\n**Answerability \u2014 a question only helps if a human will actually answer it:**\n\n`surface` (from `get_runtime_state`, view `"self"`) is a partial signal, not a guarantee:\n- `daemon`, or any session started by a scheduler, cron job, or another agent, has no human watching \u2014 never block on `ask_question` here.\n- `cli` is ambiguous: the interactive REPL and the Telegram bot can reach a human, but one-shot `chat` runs and sub-agent forks report the same `cli` and have no elicitation handler \u2014 there `ask_question` returns `{ action: \'decline\' }` instantly.\n- Even when a handler exists, the operator is usually away, so a blocking question can stall until the turn aborts.\n\nSo treat `ask_question` as best-effort: a `decline` or `cancel` result means "no answer is coming," not a failure to abort the task on. When you cannot be sure a human will answer, instead of asking:\n1. **Proceed on a stated assumption** \u2014 pick the most reasonable interpretation, act on it, and record the assumption in your Done/Blocked terminal state for async review.\n2. **Emit a Blocked artifact** \u2014 if no safe assumption exists and proceeding would be irreversible, end the turn with a **Blocked** terminal state naming exactly what the operator must supply before the next run.\n\nReserve `ask_question` for the narrow set of things no tool can resolve: a genuinely ambiguous requirement whose readings lead to materially different work, a decision with significant or irreversible consequences, or context that lives only in the operator\'s head (a preference, a secret, an external constraint):\n\n- Question types: `text` (open-ended), `confirm` (yes/no), `choice` (single pick from list), `multi_choice` (multi-pick), `number` (numeric with optional bounds). When `allow_custom: true`, the result may include `custom_value` instead of `value` \u2014 check `content.custom_value !== undefined` to detect a free-form answer.\n- Ask one focused question at a time. Do NOT ask multiple questions in a single call, and do NOT stack several ask_question calls across a turn \u2014 fold the genuine unknowns into the single most decision-relevant question.\n- Do NOT use when the user has already provided sufficient context \u2014 infer and proceed instead.\n- The result `action` will be `accept` (answered), `cancel` (user interrupted), `decline` (no handler), or `skip` (optional question skipped).\n- `allow_custom` (choice/multi_choice only): opt-in to a free-form entry affordance. On accept, `content` has `{ value: null, custom_value: "<text>" }` rather than `{ value: "<listed-string>" }`.\n- After a `cancel` or `decline`, stop and tell the user what information you need \u2014 do not loop and re-ask.',HJ=`[end-of-turn protocol]
|
|
1707
1707
|
|
|
1708
1708
|
Every turn must end in one externally identifiable terminal state. AFK users need inspectable artifacts, not ceremony. Write each bullet as a single sentence.
|
|
1709
1709
|
|
|
@@ -1735,7 +1735,7 @@ ${r} skill ${o} from \`/forge-friction\` awaiting generation in \`${t}/\`: ${s}
|
|
|
1735
1735
|
|
|
1736
1736
|
Run \`/forge\` to process (it will pick up the pending briefs automatically). Ignore if the user is mid-task on something else.`}function Hd(e,t,n="one-shot",r){if(!e)return e;let o=[e];return t&&o.push(jJ),WJ.has(n)&&(r!==void 0&&o.push(r),o.push(HJ)),o.join(`
|
|
1737
1737
|
|
|
1738
|
-
`)}import br from"chalk";nl();var KJ={read:br.hex("#C9B584"),write:br.hex("#E8A33D"),shell:br.hex("#A8E060"),subagent:f.plan,skill:br.hex("#F08AC4"),dag:br.hex("#4EC9B0"),mcp:br.hex("#5FE0C0"),web:br.hex("#A0C4C0"),browser:br.hex("#FF8A65"),planning:f.meta,schedule:br.hex("#D4A84B"),other:f.meta},GJ={read:"\u25CF",write:"\u270E",shell:"$",subagent:"\u2192",skill:"\u25C6",dag:"\u2B21",mcp:"\u22A1",web:"\u2316",browser:"\u25C9",planning:"\u25B1",schedule:"\u23F2",other:"\u25CF"};function zy(e){return{color:KJ[e],glyph:GJ[e]}}function xi(e){return zy(Pn(e))}function Wd(e,t){let n=t??process.stdout.columns??80;return!Number.isFinite(n)||n<=0?e:ne(e,n)}function Kd(e,t){let{description:n,summary:r,lastToolName:o,totalTokens:s,toolUses:i,durationMs:a}=e,l=[];if(o){let{color:u,glyph:d}=xi(o);l.push(`via ${u(`${d} ${o}`)}`)}i&&l.push(`${i} tool${i===1?"":"s"}`),s&&l.push(`${ie(s)} tok`),a&&l.push(fe(a)),l.push("esc to interrupt \xB7 ctrl+b background");let c=l.length>0?` (${l.join(" \xB7 ")})`:"";return r?[Wd(f.dim(` \u25E6 ${n}`),t),Wd(f.dim(` ${r}${c}`),t)]:[Wd(f.dim(` \u25E6 ${n}${c}`),t)]}function Gd(e,t){let n=e.status==="succeeded"?"\u2713":e.status==="failed"?"\u2717":"\u2298",r=e.agentType??e.subagentId,o=[n,r];return e.durationMs!==void 0&&o.push(`\xB7 ${fe(e.durationMs)}`),Wd(f.dim(` ${o.join(" ")}`),t)}Qe();il();al();In();qr();No();En();cn();xn();q();K();import{randomUUID as vV}from"node:crypto";import{createHash as gV}from"crypto";import{appendFileSync as hV}from"fs";import{mkdir as yV,open as bV,writeFile as wV}from"fs/promises";import{join as F_}from"path";import{z as E}from"zod";var E_=["policy-refusal","timeout","permission-denied","hook-block","abort","elicitation-declined"];var qJ=E.object({phase:E.literal("started"),toolUseId:E.string(),name:E.string(),inputBytes:E.number().int().nonnegative(),subagentId:E.string().optional()}),zJ=E.enum(E_),JJ=E.object({phase:E.literal("completed"),toolUseId:E.string(),name:E.string(),resultBytes:E.number().int().nonnegative(),isError:E.boolean(),truncated:E.boolean(),durationMs:E.number().nonnegative(),circuitBreaker:E.boolean().optional(),failureClass:zJ.optional(),subagentId:E.string().optional()}),T_=E.discriminatedUnion("phase",[qJ,JJ]),VJ=E.enum(["PreToolUse","PostToolUse","PostToolUseFailure","SessionStart","SessionEnd","SubagentStart","SubagentStop"]),x_=E.object({hookEvent:VJ,decision:E.union([E.literal("block"),E.literal("approve")]).optional(),reason:E.string().optional(),blockedTool:E.string().optional(),injectedContextBytes:E.number().int().nonnegative().optional(),durationMs:E.number().nonnegative().optional(),approvalOutcome:E.enum(["approved","denied","unrecognised","timeout","decline","cancel"]).optional()}),YJ=E.object({transition:E.literal("started"),subagentId:E.string(),parentId:E.string(),model:E.string(),allowedTools:E.array(E.string()).readonly().optional(),systemPromptHash:E.string().optional()}),XJ=E.object({transition:E.literal("succeeded"),subagentId:E.string(),durationMs:E.number().nonnegative(),turnCount:E.number().int().nonnegative(),totalCostUsd:E.number().nonnegative().optional(),outputBytes:E.number().int().nonnegative()}),ZJ=E.object({transition:E.literal("failed"),subagentId:E.string(),errorClass:E.string(),errorMessage:E.string(),partialOutputBytes:E.number().int().nonnegative()}),QJ=E.object({transition:E.literal("cancelled"),subagentId:E.string(),source:E.enum(["cascade","explicit"])}),R_=E.discriminatedUnion("transition",[YJ,XJ,ZJ,QJ]),eV=E.object({transition:E.literal("started"),jobId:E.string(),subagentId:E.string(),label:E.string(),model:E.string()}),tV=E.object({transition:E.literal("completed"),jobId:E.string(),subagentId:E.string(),durationMs:E.number().nonnegative(),outputBytes:E.number().int().nonnegative()}),nV=E.object({transition:E.literal("failed"),jobId:E.string(),subagentId:E.string(),durationMs:E.number().nonnegative(),errorClass:E.string(),errorMessage:E.string()}),rV=E.object({transition:E.literal("cancelled"),jobId:E.string(),subagentId:E.string(),source:E.enum(["explicit","cascade"])}),oV=E.object({transition:E.literal("joined"),jobId:E.string(),subagentId:E.string(),jobStatus:E.enum(["completed","failed","cancelled"])}),C_=E.discriminatedUnion("transition",[eV,tV,nV,rV,oV]),A_=E.object({kind:E.literal("monetary"),runningCostUsd:E.number().nonnegative(),maxBudgetUsd:E.number().nonnegative(),lastTurnCostUsd:E.number().nonnegative()}),sV=E.enum(["user_signal","cascade","timeout","budget","hook_block"]),__=E.object({origin:sV,cascadedTo:E.array(E.string()).readonly(),reason:E.string().optional()}),I_=E.enum(["manual","token_threshold","turn_count"]),iV=E.object({path:E.string(),sizeBytes:E.number().int().nonnegative(),sha256:E.string().regex(/^[0-9a-f]{64}$/)}),aV=E.object({trigger:I_,preCompactionMessages:E.array(E.unknown()),summary:E.string(),keptTailCount:E.number().int().nonnegative(),keepLastNConfig:E.number().int().nonnegative(),messagesBefore:E.number().int().nonnegative(),messagesAfter:E.number().int().nonnegative(),tokensSavedEstimate:E.number().nonnegative().optional(),summarizationTokens:E.object({input:E.number().int().nonnegative(),output:E.number().int().nonnegative()}).optional()}),lV=E.object({trigger:I_,preCompactionMessagesRef:iV,summary:E.string(),keptTailCount:E.number().int().nonnegative(),keepLastNConfig:E.number().int().nonnegative(),messagesBefore:E.number().int().nonnegative(),messagesAfter:E.number().int().nonnegative(),tokensSavedEstimate:E.number().nonnegative().optional(),summarizationTokens:E.object({input:E.number().int().nonnegative(),output:E.number().int().nonnegative()}).optional()}),cV=E.enum(["model_end_turn","truncated","iteration_cap","abort","timeout","budget_exceeded","hook_blocked","max_turns_exceeded"]),P_=E.object({reason:cV,finalTurnCount:E.number().int().nonnegative(),finalCostUsd:E.number().nonnegative(),finalTokens:E.object({input:E.number().int().nonnegative().optional(),output:E.number().int().nonnegative().optional(),cacheRead:E.number().int().nonnegative().optional(),cacheCreation:E.number().int().nonnegative().optional()}),lastStopReason:E.string().optional(),guidance:E.string().optional()}),M_=E.object({source:E.string(),assertion:E.string(),evidence:E.array(E.string()).readonly(),confidence:E.number().min(0).max(1),dissent:E.string().optional()}),uV=E.enum(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),dV=E.enum(["click","fill","press","select","hover","scroll_to","wait_for"]),pV=E.object({kind:E.enum(["semantic","element_id","selector"]),text:E.string().max(80).optional(),role:E.string().optional(),elementId:E.string().optional(),selectorHash:E.string().regex(/^[0-9a-f]{8}$/).optional()}),O_=E.object({tool:uV,action:dV.optional(),toolUseId:E.string(),target:pV.optional(),urlBefore:E.string().nullable(),urlAfter:E.string().nullable(),status:E.enum(["ok","error","ambiguous_target","blocked_by_policy"]),screenshotPath:E.string().optional(),observationSummary:E.string().max(500).optional(),error:E.object({reason:E.string(),recoverable:E.boolean()}).optional(),durationMs:E.number().nonnegative()}),mV=E.enum(["bootstrap_start","bootstrap_done","session_init_start","session_init_done","mcp_connect_start","mcp_connect_done","mcp_server_start","mcp_server_done","loop_start","loop_end","model_ttfb"]),$_=E.object({phase:mV,durationMs:E.number().nonnegative().optional(),metadata:E.record(E.string(),E.union([E.string(),E.number(),E.boolean()])).optional(),model:E.string().optional(),resolvedModel:E.string().optional(),origin:E.enum(["cli","telegram","daemon","unknown"]).optional(),actor:E.enum(["main","subagent"]).optional()}),fV=E.object({status:E.enum(["succeeded","failed","cancelled"]),finalCostUsd:E.number().nonnegative(),finalTurnCount:E.number().int().nonnegative(),closedAt:E.string().datetime(),incomplete:E.boolean().optional(),subagentCount:E.number().int().nonnegative().optional(),subagentTokens:E.object({input:E.number().int().nonnegative().optional(),output:E.number().int().nonnegative().optional(),cacheRead:E.number().int().nonnegative().optional(),cacheCreation:E.number().int().nonnegative().optional()}).optional(),subagentCostUsd:E.number().nonnegative().optional()}),D_=E.discriminatedUnion("kind",[E.object({kind:E.literal("tool_call"),payload:T_}),E.object({kind:E.literal("hook_decision"),payload:x_}),E.object({kind:E.literal("subagent_lifecycle"),payload:R_}),E.object({kind:E.literal("background_agent"),payload:C_}),E.object({kind:E.literal("budget"),payload:A_}),E.object({kind:E.literal("abort"),payload:__}),E.object({kind:E.literal("compaction"),payload:aV}),E.object({kind:E.literal("closure"),payload:P_}),E.object({kind:E.literal("claim"),payload:M_}),E.object({kind:E.literal("browser_event"),payload:O_}),E.object({kind:E.literal("session_phase"),payload:$_})]),L_=E.discriminatedUnion("kind",[E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("tool_call"),payload:T_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("hook_decision"),payload:x_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("subagent_lifecycle"),payload:R_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("background_agent"),payload:C_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("budget"),payload:A_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("abort"),payload:__}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("compaction"),payload:lV}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("closure"),payload:P_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("claim"),payload:M_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("browser_event"),payload:O_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("session_phase"),payload:$_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("session_sealed"),payload:fV})]);var qd=new Set,N_=!1;function SV(){N_||(N_=!0,process.on("exit",()=>{for(let e of qd)e.sealOnProcessExit()}))}var zd=class{traceDir;tracePath;seq=0;sealed=!1;fh=null;writeQueue=Promise.resolve();constructor(t){this.traceDir=t.traceDir,this.tracePath=F_(this.traceDir,"trace.jsonl")}getTracePath(){return this.tracePath}async write(t){if(this.sealed)throw new Error("NdjsonTraceWriter: trace is sealed; write() rejected");return D_.parse(t),this.enqueue(async()=>{await this.ensureOpen();let n=await this.materializePersistedEvent(t);await this.appendLine(n)})}async seal(t){this.sealed||(this.sealed=!0,await this.enqueue(async()=>{await this.ensureOpen();let n={ts:new Date().toISOString(),seq:this.seq++,kind:"session_sealed",payload:t};await this.appendLine(n),this.fh&&await this.fh.sync()}),await this.closeHandle())}async close(){await this.enqueue(async()=>{}),await this.closeHandle()}enqueue(t){let n=this.writeQueue.then(t,t);return this.writeQueue=n.then(()=>{},()=>{}),n}async ensureOpen(){this.fh||(await yV(this.traceDir,{recursive:!0}),this.fh=await bV(this.tracePath,"a"),qd.add(this),SV())}async closeHandle(){if(qd.delete(this),!this.fh)return;let t=this.fh;this.fh=null,await t.close()}sealOnProcessExit(){if(this.sealed||this.seq===0)return;this.sealed=!0,qd.delete(this);try{let n={ts:new Date().toISOString(),seq:this.seq++,kind:"session_sealed",payload:{status:"failed",finalCostUsd:0,finalTurnCount:0,closedAt:new Date().toISOString(),incomplete:!0}};hV(this.tracePath,`${JSON.stringify(n)}
|
|
1738
|
+
`)}import br from"chalk";nl();var KJ={read:br.hex("#C9B584"),write:br.hex("#E8A33D"),shell:br.hex("#A8E060"),subagent:f.plan,skill:br.hex("#F08AC4"),dag:br.hex("#4EC9B0"),mcp:br.hex("#5FE0C0"),web:br.hex("#A0C4C0"),browser:br.hex("#FF8A65"),planning:f.meta,schedule:br.hex("#D4A84B"),other:f.meta},GJ={read:"\u25CF",write:"\u270E",shell:"$",subagent:"\u2192",skill:"\u25C6",dag:"\u2B21",mcp:"\u22A1",web:"\u2316",browser:"\u25C9",planning:"\u25B1",schedule:"\u23F2",other:"\u25CF"};function zy(e){return{color:KJ[e],glyph:GJ[e]}}function xi(e){return zy(Pn(e))}function Wd(e,t){let n=t??process.stdout.columns??80;return!Number.isFinite(n)||n<=0?e:ne(e,n)}function Kd(e,t){let{description:n,summary:r,lastToolName:o,totalTokens:s,toolUses:i,durationMs:a}=e,l=[];if(o){let{color:u,glyph:d}=xi(o);l.push(`via ${u(`${d} ${o}`)}`)}i&&l.push(`${i} tool${i===1?"":"s"}`),s&&l.push(`${ie(s)} tok`),a&&l.push(ge(a)),l.push("esc to interrupt \xB7 ctrl+b background");let c=l.length>0?` (${l.join(" \xB7 ")})`:"";return r?[Wd(f.dim(` \u25E6 ${n}`),t),Wd(f.dim(` ${r}${c}`),t)]:[Wd(f.dim(` \u25E6 ${n}${c}`),t)]}function Gd(e,t){let n=e.status==="succeeded"?"\u2713":e.status==="failed"?"\u2717":"\u2298",r=e.agentType??e.subagentId,o=[n,r];return e.durationMs!==void 0&&o.push(`\xB7 ${ge(e.durationMs)}`),Wd(f.dim(` ${o.join(" ")}`),t)}Qe();il();al();In();qr();No();En();cn();xn();q();K();import{randomUUID as vV}from"node:crypto";import{createHash as gV}from"crypto";import{appendFileSync as hV}from"fs";import{mkdir as yV,open as bV,writeFile as wV}from"fs/promises";import{join as F_}from"path";import{z as E}from"zod";var E_=["policy-refusal","timeout","permission-denied","hook-block","abort","elicitation-declined"];var qJ=E.object({phase:E.literal("started"),toolUseId:E.string(),name:E.string(),inputBytes:E.number().int().nonnegative(),subagentId:E.string().optional()}),zJ=E.enum(E_),JJ=E.object({phase:E.literal("completed"),toolUseId:E.string(),name:E.string(),resultBytes:E.number().int().nonnegative(),isError:E.boolean(),truncated:E.boolean(),durationMs:E.number().nonnegative(),circuitBreaker:E.boolean().optional(),failureClass:zJ.optional(),subagentId:E.string().optional()}),T_=E.discriminatedUnion("phase",[qJ,JJ]),VJ=E.enum(["PreToolUse","PostToolUse","PostToolUseFailure","SessionStart","SessionEnd","SubagentStart","SubagentStop"]),x_=E.object({hookEvent:VJ,decision:E.union([E.literal("block"),E.literal("approve")]).optional(),reason:E.string().optional(),blockedTool:E.string().optional(),injectedContextBytes:E.number().int().nonnegative().optional(),durationMs:E.number().nonnegative().optional(),approvalOutcome:E.enum(["approved","denied","unrecognised","timeout","decline","cancel"]).optional()}),YJ=E.object({transition:E.literal("started"),subagentId:E.string(),parentId:E.string(),model:E.string(),allowedTools:E.array(E.string()).readonly().optional(),systemPromptHash:E.string().optional()}),XJ=E.object({transition:E.literal("succeeded"),subagentId:E.string(),durationMs:E.number().nonnegative(),turnCount:E.number().int().nonnegative(),totalCostUsd:E.number().nonnegative().optional(),outputBytes:E.number().int().nonnegative()}),ZJ=E.object({transition:E.literal("failed"),subagentId:E.string(),errorClass:E.string(),errorMessage:E.string(),partialOutputBytes:E.number().int().nonnegative()}),QJ=E.object({transition:E.literal("cancelled"),subagentId:E.string(),source:E.enum(["cascade","explicit"])}),R_=E.discriminatedUnion("transition",[YJ,XJ,ZJ,QJ]),eV=E.object({transition:E.literal("started"),jobId:E.string(),subagentId:E.string(),label:E.string(),model:E.string()}),tV=E.object({transition:E.literal("completed"),jobId:E.string(),subagentId:E.string(),durationMs:E.number().nonnegative(),outputBytes:E.number().int().nonnegative()}),nV=E.object({transition:E.literal("failed"),jobId:E.string(),subagentId:E.string(),durationMs:E.number().nonnegative(),errorClass:E.string(),errorMessage:E.string()}),rV=E.object({transition:E.literal("cancelled"),jobId:E.string(),subagentId:E.string(),source:E.enum(["explicit","cascade"])}),oV=E.object({transition:E.literal("joined"),jobId:E.string(),subagentId:E.string(),jobStatus:E.enum(["completed","failed","cancelled"])}),C_=E.discriminatedUnion("transition",[eV,tV,nV,rV,oV]),A_=E.object({kind:E.literal("monetary"),runningCostUsd:E.number().nonnegative(),maxBudgetUsd:E.number().nonnegative(),lastTurnCostUsd:E.number().nonnegative()}),sV=E.enum(["user_signal","cascade","timeout","budget","hook_block"]),__=E.object({origin:sV,cascadedTo:E.array(E.string()).readonly(),reason:E.string().optional()}),I_=E.enum(["manual","token_threshold","turn_count"]),iV=E.object({path:E.string(),sizeBytes:E.number().int().nonnegative(),sha256:E.string().regex(/^[0-9a-f]{64}$/)}),aV=E.object({trigger:I_,preCompactionMessages:E.array(E.unknown()),summary:E.string(),keptTailCount:E.number().int().nonnegative(),keepLastNConfig:E.number().int().nonnegative(),messagesBefore:E.number().int().nonnegative(),messagesAfter:E.number().int().nonnegative(),tokensSavedEstimate:E.number().nonnegative().optional(),summarizationTokens:E.object({input:E.number().int().nonnegative(),output:E.number().int().nonnegative()}).optional()}),lV=E.object({trigger:I_,preCompactionMessagesRef:iV,summary:E.string(),keptTailCount:E.number().int().nonnegative(),keepLastNConfig:E.number().int().nonnegative(),messagesBefore:E.number().int().nonnegative(),messagesAfter:E.number().int().nonnegative(),tokensSavedEstimate:E.number().nonnegative().optional(),summarizationTokens:E.object({input:E.number().int().nonnegative(),output:E.number().int().nonnegative()}).optional()}),cV=E.enum(["model_end_turn","truncated","iteration_cap","abort","timeout","budget_exceeded","hook_blocked","max_turns_exceeded"]),P_=E.object({reason:cV,finalTurnCount:E.number().int().nonnegative(),finalCostUsd:E.number().nonnegative(),finalTokens:E.object({input:E.number().int().nonnegative().optional(),output:E.number().int().nonnegative().optional(),cacheRead:E.number().int().nonnegative().optional(),cacheCreation:E.number().int().nonnegative().optional()}),lastStopReason:E.string().optional(),guidance:E.string().optional()}),M_=E.object({source:E.string(),assertion:E.string(),evidence:E.array(E.string()).readonly(),confidence:E.number().min(0).max(1),dissent:E.string().optional()}),uV=E.enum(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),dV=E.enum(["click","fill","press","select","hover","scroll_to","wait_for"]),pV=E.object({kind:E.enum(["semantic","element_id","selector"]),text:E.string().max(80).optional(),role:E.string().optional(),elementId:E.string().optional(),selectorHash:E.string().regex(/^[0-9a-f]{8}$/).optional()}),O_=E.object({tool:uV,action:dV.optional(),toolUseId:E.string(),target:pV.optional(),urlBefore:E.string().nullable(),urlAfter:E.string().nullable(),status:E.enum(["ok","error","ambiguous_target","blocked_by_policy"]),screenshotPath:E.string().optional(),observationSummary:E.string().max(500).optional(),error:E.object({reason:E.string(),recoverable:E.boolean()}).optional(),durationMs:E.number().nonnegative()}),mV=E.enum(["bootstrap_start","bootstrap_done","session_init_start","session_init_done","mcp_connect_start","mcp_connect_done","mcp_server_start","mcp_server_done","loop_start","loop_end","model_ttfb"]),$_=E.object({phase:mV,durationMs:E.number().nonnegative().optional(),metadata:E.record(E.string(),E.union([E.string(),E.number(),E.boolean()])).optional(),model:E.string().optional(),resolvedModel:E.string().optional(),origin:E.enum(["cli","telegram","daemon","unknown"]).optional(),actor:E.enum(["main","subagent"]).optional()}),fV=E.object({status:E.enum(["succeeded","failed","cancelled"]),finalCostUsd:E.number().nonnegative(),finalTurnCount:E.number().int().nonnegative(),closedAt:E.string().datetime(),incomplete:E.boolean().optional(),subagentCount:E.number().int().nonnegative().optional(),subagentTokens:E.object({input:E.number().int().nonnegative().optional(),output:E.number().int().nonnegative().optional(),cacheRead:E.number().int().nonnegative().optional(),cacheCreation:E.number().int().nonnegative().optional()}).optional(),subagentCostUsd:E.number().nonnegative().optional()}),D_=E.discriminatedUnion("kind",[E.object({kind:E.literal("tool_call"),payload:T_}),E.object({kind:E.literal("hook_decision"),payload:x_}),E.object({kind:E.literal("subagent_lifecycle"),payload:R_}),E.object({kind:E.literal("background_agent"),payload:C_}),E.object({kind:E.literal("budget"),payload:A_}),E.object({kind:E.literal("abort"),payload:__}),E.object({kind:E.literal("compaction"),payload:aV}),E.object({kind:E.literal("closure"),payload:P_}),E.object({kind:E.literal("claim"),payload:M_}),E.object({kind:E.literal("browser_event"),payload:O_}),E.object({kind:E.literal("session_phase"),payload:$_})]),L_=E.discriminatedUnion("kind",[E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("tool_call"),payload:T_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("hook_decision"),payload:x_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("subagent_lifecycle"),payload:R_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("background_agent"),payload:C_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("budget"),payload:A_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("abort"),payload:__}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("compaction"),payload:lV}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("closure"),payload:P_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("claim"),payload:M_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("browser_event"),payload:O_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("session_phase"),payload:$_}),E.object({ts:E.string().datetime(),seq:E.number().int().nonnegative(),kind:E.literal("session_sealed"),payload:fV})]);var qd=new Set,N_=!1;function SV(){N_||(N_=!0,process.on("exit",()=>{for(let e of qd)e.sealOnProcessExit()}))}var zd=class{traceDir;tracePath;seq=0;sealed=!1;fh=null;writeQueue=Promise.resolve();constructor(t){this.traceDir=t.traceDir,this.tracePath=F_(this.traceDir,"trace.jsonl")}getTracePath(){return this.tracePath}async write(t){if(this.sealed)throw new Error("NdjsonTraceWriter: trace is sealed; write() rejected");return D_.parse(t),this.enqueue(async()=>{await this.ensureOpen();let n=await this.materializePersistedEvent(t);await this.appendLine(n)})}async seal(t){this.sealed||(this.sealed=!0,await this.enqueue(async()=>{await this.ensureOpen();let n={ts:new Date().toISOString(),seq:this.seq++,kind:"session_sealed",payload:t};await this.appendLine(n),this.fh&&await this.fh.sync()}),await this.closeHandle())}async close(){await this.enqueue(async()=>{}),await this.closeHandle()}enqueue(t){let n=this.writeQueue.then(t,t);return this.writeQueue=n.then(()=>{},()=>{}),n}async ensureOpen(){this.fh||(await yV(this.traceDir,{recursive:!0}),this.fh=await bV(this.tracePath,"a"),qd.add(this),SV())}async closeHandle(){if(qd.delete(this),!this.fh)return;let t=this.fh;this.fh=null,await t.close()}sealOnProcessExit(){if(this.sealed||this.seq===0)return;this.sealed=!0,qd.delete(this);try{let n={ts:new Date().toISOString(),seq:this.seq++,kind:"session_sealed",payload:{status:"failed",finalCostUsd:0,finalTurnCount:0,closedAt:new Date().toISOString(),incomplete:!0}};hV(this.tracePath,`${JSON.stringify(n)}
|
|
1739
1739
|
`)}catch{}let t=this.fh;this.fh=null,t&&t.close().catch(()=>{})}async appendLine(t){if(!this.fh)throw new Error("NdjsonTraceWriter: file handle missing");await this.fh.appendFile(`${JSON.stringify(t)}
|
|
1740
1740
|
`)}async materializePersistedEvent(t){let n=new Date().toISOString(),r=this.seq++;if(t.kind==="compaction"){let o=await this.persistCompactionSidecar(t.payload,r,n);return{ts:n,seq:r,kind:"compaction",payload:o}}return{ts:n,seq:r,kind:t.kind,payload:t.payload}}async persistCompactionSidecar(t,n,r){let o=r.replace(/[:.]/g,"-"),s=F_(this.traceDir,`${String(n).padStart(6,"0")}-${o}-pre-compaction.json`),i=JSON.stringify(t.preCompactionMessages),a=Buffer.byteLength(i,"utf8"),l=gV("sha256").update(i).digest("hex");await wV(s,i,{encoding:"utf8",flag:"w"});let c={path:s,sizeBytes:a,sha256:l};return{trigger:t.trigger,preCompactionMessagesRef:c,summary:t.summary,keptTailCount:t.keptTailCount,keepLastNConfig:t.keepLastNConfig,messagesBefore:t.messagesBefore,messagesAfter:t.messagesAfter,...t.tokensSavedEstimate!==void 0?{tokensSavedEstimate:t.tokensSavedEstimate}:{},...t.summarizationTokens!==void 0?{summarizationTokens:t.summarizationTokens}:{}}}};function eo(e={}){if(v.AFK_TRACE_DISABLED==="1")return null;let t=e.sessionLabel??vV(),n=Ts(t),r=new zd({traceDir:n});return{writer:r,tracePath:r.getTracePath(),sessionLabel:t}}Ba();K();import{readFileSync as kV,writeFileSync as j_,existsSync as gl,mkdirSync as H_,readdirSync as EV,statSync as TV,realpathSync as B_}from"fs";import{join as W_,basename as K_,resolve as U_,sep as xV}from"path";import{randomUUID as RV}from"node:crypto";function Ci(){return tv(),Jn()}function CV(e){return W_(Ci(),`${e}.json`)}function Jd(e,{write:t=!1}={}){let n=e.includes("/")?e:CV(e),r,o;if(!t&&gl(n)?(r=B_(n),o=B_(Ci())):(r=U_(n),o=U_(Ci())),!r.startsWith(o+xV)&&r!==o)throw new Error(`Session path escapes sessions directory: ${e}`);return r}function Ln(e,t){let n=Ci();gl(n)||H_(n,{recursive:!0});let r=t??e.sessionId??`session-${Date.now()}`,o={sessionId:e.sessionId,...e.name?{name:e.name}:{},...e.source?{source:e.source}:{},...e.actor?{actor:e.actor}:{},...e.telegramChatId!==void 0?{telegramChatId:e.telegramChatId}:{},...e.cwd?{cwd:e.cwd}:{},model:e.model,startedAt:e.sessionStartTime,savedAt:Date.now(),totalTurns:e.totalTurns,totalCostUsd:e.totalCostUsd,totalTokens:e.totalTokens,totalDurationMs:e.totalDurationMs,turns:e.turns},s=Jd(r,{write:!0});return j_(s,JSON.stringify(o,null,2)),s}function G_(e,t={}){let n=Ci();gl(n)||H_(n,{recursive:!0});let r=t.newId??RV(),o={sessionId:r,model:e.model,startedAt:e.sessionStartTime,savedAt:Date.now(),totalTurns:e.totalTurns,totalCostUsd:e.totalCostUsd,totalTokens:e.totalTokens,totalDurationMs:e.totalDurationMs,turns:[...e.turns],...e.sessionId?{forkedFrom:e.sessionId}:{},forkedAt:Date.now()},s=Jd(r,{write:!0});return j_(s,JSON.stringify(o,null,2)),{id:r,path:s}}function Ri(e){let t;try{t=Jd(e)}catch{return}if(gl(t))try{let n=kV(t,"utf-8");return JSON.parse(n)}catch{return}}function Ai(e){let t;try{t=Jd(e)}catch{return}let n=Ri(t);if(n)return{path:t,id:K_(t,".json"),data:n};let r=hl();for(let s of r){if(s.id!==e&&s.sessionId!==e&&s.name!==e)continue;let i=Ri(s.path);if(i)return{path:s.path,id:s.id,data:i}}if(e.length>=3){let s=r.filter(i=>i.name!==void 0&&i.name.startsWith(e));if(s.length===1){let i=s[0];if(i){let a=Ri(i.path);if(a)return{path:i.path,id:i.id,data:a}}}}}function hl(){let e=Ci();if(!gl(e))return[];let t=[];for(let n of EV(e)){if(!n.endsWith(".json"))continue;let r=W_(e,n);try{if(!TV(r).isFile())continue;let s=Ri(r);if(!s||typeof s.savedAt!="number"||typeof s.model!="string")continue;t.push({path:r,id:K_(n,".json"),sessionId:s.sessionId,name:s.name,source:s.source,actor:s.actor,model:s.model,startedAt:s.startedAt,savedAt:s.savedAt,totalTurns:s.totalTurns,totalCostUsd:s.totalCostUsd,cwd:s.cwd})}catch{}}return t.sort((n,r)=>r.savedAt-n.savedAt),t}function _i(e){if(e.resume&&e.continue)throw new Error("Use either --resume <id> or --continue, not both.");if(e.resume){let t=Ai(e.resume);return t?{id:t.id,resumeId:t.data.sessionId??t.id,stored:t.data}:{id:e.resume,resumeId:e.resume}}if(e.continue){let t=hl()[0];if(!t)throw new Error("No saved sessions found for --continue. Run a session first or use /save.");let n=Ri(t.path);if(!n)throw new Error(`Could not load latest saved session: ${t.id}`);return{id:t.id,resumeId:n.sessionId??t.id,stored:n}}}function Ii(e){return e?{resume:e.resumeId,sessionId:e.resumeId,...e.stored?{resumeHistory:e.stored.turns.map(t=>({user:t.user,assistant:t.assistant}))}:{}}:{}}function Pi(e){let t=e.toLowerCase().replace(/[`*_~]/g," ").replace(/[^\w\s-]/g," ").replace(/[\s_]+/g," ").trim();return t?t.split(" ").filter(Boolean).slice(0,6).join("-").slice(0,48).replace(/-+$/g,""):""}function Vd(e){return{totalTurns:0,totalCostUsd:0,totalTokens:0,totalDurationMs:0,sessionStartTime:Date.now(),turnCosts:[],turnTokens:[],turns:[],model:e,permissionMode:"default"}}function q_(e){e.totalTurns=0,e.totalCostUsd=0,e.totalTokens=0,e.totalDurationMs=0,e.sessionStartTime=Date.now(),e.turnCosts.length=0,e.turnTokens.length=0,e.turns.length=0,delete e.sessionId,delete e.name}function Uo(e,t,n,r,o){let s=r?.totalCostUsd??0,i=r?.durationMs??0,a=Number(r?.usage?.input_tokens??0),l=Number(r?.usage?.output_tokens??0),c=a,u=l,d=Number(r?.usage?.cache_read_input_tokens??0)+Number(r?.usage?.cache_creation_input_tokens??0),p=r?.usage?.iterations;if(Array.isArray(p)&&p.length>0){let y=p[p.length-1];if(y&&typeof y=="object"){let S=y;c=Number(S.input_tokens??0),u=Number(S.output_tokens??0),d=Number(S.cache_read_input_tokens??0)+Number(S.cache_creation_input_tokens??0)}}e.totalTurns+=1,e.totalCostUsd+=s,e.totalDurationMs+=i,e.totalTokens+=a+l,e.turnCosts.push(s);let m=Number(r?.usage?.context_window_tokens??NaN),g=Array.isArray(p)&&p.length>0,h=Number.isFinite(m)?m:g?c+u+d:void 0;if(e.turnTokens.push({input:c,output:u,cache:d,...h!==void 0?{footprint:h}:{}}),r?.sessionId&&!e.sessionId&&(e.sessionId=String(r.sessionId)),!e.name){let y=Pi(t);y&&(e.name=y)}let b={user:t,assistant:n,timestamp:Date.now(),costUsd:s,durationMs:i,inputTokens:a,outputTokens:l,...o&&o.length>0?{toolEvents:o}:{}};return e.turns.push(b),b}import{execFile as AV,spawn as _V}from"node:child_process";import{promisify as IV}from"node:util";var PV=IV(AV),z_=2e4,Jy=class extends Error{kind;exitCode;stderr;constructor(t,n,r,o){super(t),this.name="GhError",this.kind=n,this.exitCode=r,this.stderr=o}},Yd=null,yl=null;function MV(e,t,n){return n===!0?"timeout":t==="ENOENT"?"not-found":/already exists/i.test(e)?"already-exists":/authentication|please log in|HTTP 40[13]|bad credentials|token|scope/i.test(e)?"unauthed":/ETIMEDOUT|ECONNRESET|ECONNREFUSED/i.test(e+(t??""))?"network":"unknown"}function J_(e,t){return PV(e,t,{timeout:z_,killSignal:"SIGTERM"}).then(n=>({stdout:n.stdout,stderr:n.stderr}))}async function V_(e={}){let t=(e._now??(()=>Date.now()))(),n=e.ttlMs??6e4,r=e.execFn??J_,o=e.log??(()=>{});return Yd&&Yd.expiresAt>t?(o("[gh] checkGhReady cache hit"),Yd.result):(o("[gh] checkGhReady cache miss \u2014 probing"),yl||(yl=(async()=>{try{await r("gh",["--version"])}catch(a){let l=a;return l.killed?{ok:!1,hint:"`gh` timed out \u2014 check connectivity"}:l.code==="ENOENT"?{ok:!1,hint:"`gh` CLI not found \u2014 install with: brew install gh"}:{ok:!1,hint:"`gh --version` failed unexpectedly \u2014 check gh installation"}}try{await r("gh",["auth","status"])}catch(a){let l=a;return l.killed||/ETIMEDOUT|ECONNRESET|ENOTFOUND/i.test(String(l.code??""))?{ok:!1,hint:"check network \u2014 cannot reach GitHub"}:{ok:!1,hint:"`gh` is not authenticated \u2014 run: gh auth login"}}let i={ok:!0};return n>0&&(Yd={result:i,expiresAt:t+n}),i})().finally(()=>{yl=null}),yl))}function OV(e,t,n){return new Promise((r,o)=>{let s=_V(e,t,{stdio:["pipe","pipe","pipe"]}),i="",a="",l=!1,c=setTimeout(()=>{l=!0,s.kill("SIGTERM")},z_);s.stdout?.on("data",u=>{i+=u.toString()}),s.stderr?.on("data",u=>{a+=u.toString()}),s.on("error",u=>{clearTimeout(c),o(Object.assign(new Error(u.message),{...u.code!==void 0?{code:u.code}:{},stderr:a}))}),s.on("close",u=>{if(clearTimeout(c),l){o(Object.assign(new Error(`${e} timed out`),{killed:!0,stderr:a}));return}if(u===0){r({stdout:i,stderr:a});return}o(Object.assign(new Error(`${e} exited ${u??"null"}`),{exitCode:u??1,stderr:a}))}),s.stdin?.on("error",()=>{}),s.stdin?.end(n)})}async function Y_(e,t){let n=t??OV,r=["pr","comment"],o=e.pr.trim();o&&r.push(o),r.push("--body-file","-");try{let{stdout:s}=await n("gh",r,e.body);return s.trim()}catch(s){let i=s,a=i.stderr??"",l=MV(a,i.code,i.killed);throw new Jy(`gh pr comment failed (${l}): ${a.trim()}`,l,i.exitCode??1,a)}}async function Xd(e){let t=e??J_;try{let{stdout:n}=await t("gh",["pr","view","--json","number","--jq",".number"]),r=n.trim();return/^\d+$/.test(r)?r:null}catch{return null}}Io();var $V=4096,DV="<!-- agent-afk-review -->",LV=new Set(["github","telegram"]),X_=/--post(?:=|\s+)([^\s]+)/g;function Z_(e){if(!/--post\b/.test(e))return{targets:[],cleanedArgs:e,unknown:[]};let t=[],n=[];for(let o of e.matchAll(X_))Q_(o[1]??"",t,n);let r=e.replace(X_," ").replace(/(^|\s)--post(?=\s|$)/g," ").replace(/\s+/g," ").trim();return{targets:t,cleanedArgs:r,unknown:n}}function Q_(e,t,n){for(let r of e.split(",").map(o=>o.trim()).filter(Boolean))if(LV.has(r)){let o=r;t.includes(o)||t.push(o)}else n.push(r)}function eI(e){let t=[],n=[];return Q_(e,t,n),{targets:t,unknown:n}}function FV(e,t){if(t<=0||e.length<=t)return[e];let n=[],r="";for(let o of e.split(`
|
|
1741
1741
|
`)){if(o.length>t){r&&(n.push(r),r="");for(let s=0;s<o.length;s+=t)n.push(o.slice(s,s+t));continue}r.length+o.length+1>t?(r&&n.push(r),r=o):r=r?`${r}
|
|
@@ -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 op(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??Zy;return(await op(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??Zy,s;try{s=await this.client.callTool({name:t,arguments:n??{}},QV,{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 eY(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 eY(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 tY(e,t,n){let r=t.type??(t.command?"stdio":"streamable-http");return{primary:ep(e,t,n),fallback:r==="streamable-http"?()=>ep(e,{...t,type:"sse"},n):null}}function nY(e){return e instanceof mI&&(e.code===404||e.code===405)}function rY(e){return e instanceof mI?e.code:void 0}function op(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 oY}from"node:crypto";var fI="mcp__",gI="__",eb=64,sY=6;function bl(e){if(e.length===0)return"_";let n=e.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_{2,}/g,"_");return n.length===0?"_":n}function iY(e){return oY("sha256").update(e).digest("hex").slice(0,sY)}function hI(e,t){let n=bl(e),r=bl(t),o=`${fI}${n}${gI}${r}`;if(o.length<=eb)return o;let i=`${`${fI}${iY(e)}${gI}`}${r}`;return i.length<=eb?i:i.slice(0,eb)}function wl(e){let t=new Map,n=new Map;for(let{serverName:o,toolNames:s}of e)for(let i of s){let a=hI(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}}Ue();var wr=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=wl(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=bl(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 Oi(c,u);m.client=g,g.onTransportError=b=>{m.state.status="error",m.state.error=sp(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();Le(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 Qy){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=sp(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{Le(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(aY(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=wl([{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 Oi(t,r.state.config);o.onTransportError=i=>{r.state.status="error",r.state.error=sp(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=sp(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=wl([{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 aY(e,t){let n=t.description??`MCP tool ${t.name}`;return{name:e,description:n,input_schema:t.inputSchema}}function sp(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}q();K();import{existsSync as vl,lstatSync as lY,readFileSync as cY,readdirSync as uY}from"node:fs";import{join as Sl}from"node:path";function jo(){return Sl(en(),"mcp.json")}function yI(e=process.cwd()){return Sl(e,".mcp.json")}var dY=5;function tb(e=Xe()){if(!vl(e))return[];let t=[];return bI(e,e,0,t,new Set),t}function bI(e,t,n,r,o){if(n>dY||o.has(t))return;o.add(t);let s=Sl(t,".claude-plugin","plugin.json");if(vl(s)){let a=Sl(t,".claude-plugin","mcp.json");vl(a)&&r.push(a);return}let i;try{i=uY(t)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=Sl(t,a),c;try{c=lY(l)}catch{continue}c.isDirectory()&&bI(e,l,n+1,r,o)}}function pY(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 $i(e){if(!vl(e))return{mcpServers:{},sources:[],warnings:[]};let t=[],n;try{n=JSON.parse(cY(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=pY(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 Ho(e={}){let t=[],n=[];if(e.importedMcpConfigs&&e.importedMcpConfigs.length>0)for(let a of e.importedMcpConfigs)t.push({path:a,loaded:$i(a)});if(e.pluginsRoot!==null){let a=e.pluginsRoot,l=a?tb(a):tb();for(let c of l)t.push({path:c,loaded:$i(c)})}if(!e.skipUserGlobal){let a=jo();t.push({path:a,loaded:$i(a)})}if(!e.skipProjectLocal&&v.AFK_ALLOW_PROJECT_MCP!=="0"){let a=yI(e.cwd);vl(a)&&(t.push({path:a,loaded:$i(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:$i(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}}rp();cr();Ue();function gY(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 SI=10*1024*1024;function vI(){return new Promise((e,t)=>{let n=[],r=0;if(process.stdin.readableEnded){e("");return}let o=s=>{if(r+=s.length,r>SI){process.stdin.destroy(new Error(`stdin exceeds ${SI}-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 kI(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 xI(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.",kt()).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=bl(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 Oi(c,u);m.client=g,g.onTransportError=b=>{m.state.status="error",m.state.error=sp(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();Le(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 Qy){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=sp(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{Le(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(aY(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=wl([{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 Oi(t,r.state.config);o.onTransportError=i=>{r.state.status="error",r.state.error=sp(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=sp(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=wl([{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 aY(e,t){let n=t.description??`MCP tool ${t.name}`;return{name:e,description:n,input_schema:t.inputSchema}}function sp(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}q();K();import{existsSync as vl,lstatSync as lY,readFileSync as cY,readdirSync as uY}from"node:fs";import{join as Sl}from"node:path";function jo(){return Sl(en(),"mcp.json")}function yI(e=process.cwd()){return Sl(e,".mcp.json")}var dY=5;function tb(e=Xe()){if(!vl(e))return[];let t=[];return bI(e,e,0,t,new Set),t}function bI(e,t,n,r,o){if(n>dY||o.has(t))return;o.add(t);let s=Sl(t,".claude-plugin","plugin.json");if(vl(s)){let a=Sl(t,".claude-plugin","mcp.json");vl(a)&&r.push(a);return}let i;try{i=uY(t)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=Sl(t,a),c;try{c=lY(l)}catch{continue}c.isDirectory()&&bI(e,l,n+1,r,o)}}function pY(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 $i(e){if(!vl(e))return{mcpServers:{},sources:[],warnings:[]};let t=[],n;try{n=JSON.parse(cY(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=pY(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 Ho(e={}){let t=[],n=[];if(e.importedMcpConfigs&&e.importedMcpConfigs.length>0)for(let a of e.importedMcpConfigs)t.push({path:a,loaded:$i(a)});if(e.pluginsRoot!==null){let a=e.pluginsRoot,l=a?tb(a):tb();for(let c of l)t.push({path:c,loaded:$i(c)})}if(!e.skipUserGlobal){let a=jo();t.push({path:a,loaded:$i(a)})}if(!e.skipProjectLocal&&v.AFK_ALLOW_PROJECT_MCP!=="0"){let a=yI(e.cwd);vl(a)&&(t.push({path:a,loaded:$i(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:$i(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}}rp();cr();Ue();function gY(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 SI=10*1024*1024;function vI(){return new Promise((e,t)=>{let n=[],r=0;if(process.stdin.readableEnded){e("");return}let o=s=>{if(r+=s.length,r>SI){process.stdin.destroy(new Error(`stdin exceeds ${SI}-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 kI(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 xI(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.",Et()).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&&!gY(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&&Ai(n.sessionId)!==void 0){process.stderr.write(`Error: session already exists: ${n.sessionId} \u2014 use --resume to continue it
|
|
@@ -1762,16 +1762,16 @@ ${o.join(`
|
|
|
1762
1762
|
`),process.exitCode=1;return}if(o.trim()===""){process.stderr.write(`Error: message is empty \u2014 stdin contained only whitespace
|
|
1763
1763
|
`),process.exitCode=1;return}let i=mY("Initializing agent...").start(),a=null,l,c,u,d,p=!1,m,g=Vd(n.model),h=!1,b;try{if(n.worktree!==void 0)try{c=await yu(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(Te){i.fail("Failed to create worktree"),G(Te)}let y,S,w,T,x,C;try{y=Yr(n.thinking)??pi(),S=Xr(n.effort)??mi(),w=fi(n.maxBudgetUsd)??ly(),T=fi(n.taskBudget)??cy(),x=gi(n.maxOutputTokens)??ul(),C=void 0}catch(Te){i.fail("Invalid options"),G(Te)}if(n.dumpPrompt!==void 0){let Te=n.dumpPrompt===!0?TI.join(EI.homedir(),".afk","logs",`prompt-dump-${new Date().toISOString().replace(/[:.]/g,"-")}.json`):String(n.dumpPrompt);process.env.AFK_DUMP_PROMPT=Te,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=Ce(),{prompt:k,source:$}=di(),A=_t(),P=A.autoRouting?.chat??!1,F=Hd(k,P,"one-shot"),D={},N=_i({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
|
-
`),process.exitCode=1;return}N&&(D=Ii(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=eo();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,ze,"cli"),oe=new On({subagentManager:U,parentSession:j,surface:"cli",defaultConfig:{apiKey:R,systemPrompt:k,...A.baseUrl!==void 0?{baseUrl:A.baseUrl}:{}},defaultSubagentModel:Yt(n.model),childProviderFactory:M,childSkillExecutorFactory:Y,resolveApiKeyForModel:ze,depth:0,...u!==void 0?{cwd:u}:{}}),X=new $n({parentSession:j,surface:"cli",defaultModel:n.model,defaultSubagentModel:Yt(n.model),apiKey:R,childProviderFactory:M,childSkillExecutorFactory:Y,...A.baseUrl!==void 0?{baseUrl:A.baseUrl}:{},resolveApiKeyForModel:ze,...I?.writer!==void 0?{traceWriter:I.writer}:{},...u!==void 0?{cwd:u}:{}}),
|
|
1766
|
-
`)}let J=d?.getMcpToolWireNames()??[];C=hi(n.provider,{subagentExecutor:oe,skillExecutor:X,composeExecutor:
|
|
1765
|
+
`),process.exitCode=1;return}N&&(D=Ii(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=eo();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,ze,"cli"),oe=new On({subagentManager:U,parentSession:j,surface:"cli",defaultConfig:{apiKey:R,systemPrompt:k,...A.baseUrl!==void 0?{baseUrl:A.baseUrl}:{}},defaultSubagentModel:Yt(n.model),childProviderFactory:M,childSkillExecutorFactory:Y,resolveApiKeyForModel:ze,depth:0,...u!==void 0?{cwd:u}:{}}),X=new $n({parentSession:j,surface:"cli",defaultModel:n.model,defaultSubagentModel:Yt(n.model),apiKey:R,childProviderFactory:M,childSkillExecutorFactory:Y,...A.baseUrl!==void 0?{baseUrl:A.baseUrl}:{},resolveApiKeyForModel:ze,...I?.writer!==void 0?{traceWriter:I.writer}:{},...u!==void 0?{cwd:u}:{}}),me=new Zr({parentSession:j,defaultModel:n.model,defaultSubagentModel:Yt(n.model),apiKey:R,resolveApiKeyForModel:ze,...A.baseUrl!==void 0?{baseUrl:A.baseUrl}:{},...u!==void 0?{cwd:u}:{},systemPrompt:k??"",surface:"cli",depth:0});l=new lt;{let Te=u??process.cwd(),_e=sn(Mt()).mcpConfigs.filter(Pe=>Pe.format==="json").map(Pe=>Pe.source),we=Ho({cwd:Te,..._e.length>0?{importedMcpConfigs:_e}:{},...n.mcpConfig!==void 0?{cliOverride:n.mcpConfig}:{}}),ve=Object.values(we.mcpServers).filter(Pe=>!Pe.disabled).length;if(ve>0){let Pe=Date.now();Le(I?.writer,{phase:"mcp_connect_start",metadata:{serverCount:ve}});try{d=await wr.fromConfig(we.mcpServers,{warnings:we.warnings,...I?.writer!==void 0?{traceWriter:I.writer}:{}})}finally{Le(I?.writer,{phase:"mcp_connect_done",durationMs:Date.now()-Pe,metadata:{serverCount:ve}})}}else if(we.warnings.length>0)for(let Pe of we.warnings)process.stderr.write(`[mcp] ${Pe}
|
|
1766
|
+
`)}let J=d?.getMcpToolWireNames()??[];C=hi(n.provider,{subagentExecutor:oe,skillExecutor:X,composeExecutor:me,memoryStore:l,model:String(n.model),...A.openaiBaseUrl!==void 0?{openaiBaseUrl:A.openaiBaseUrl}:{},...d!==void 0?{mcpManager:d}:{}})??new qe({permissions:{allowedTools:[...Kt,...nr,...ft,"agent","skill","compose",...J]},subagentExecutor:oe,skillExecutor:X,composeExecutor:me,memoryStore:l,surface:"cli",...d!==void 0?{mcpManager:d}:{}}),await wi(),a=new kt(dr({model:B,surface:"cli",apiKey:ze(B),maxTurns:parseInt(n.maxTurns,10),isNonInteractive:!0,...n.dangerouslySkipPermissions?{permissionMode:"bypassPermissions"}:A.permissionMode!==void 0?{permissionMode:A.permissionMode}:{},hookRegistry:Ti(Te=>{console.log(Gd(Te))},"cli",l,void 0,Ei({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 Ae=async(Te,_e)=>{if(r.length===0||_e)return;let we={line:ve=>{process.stderr.write(`${ve??""}
|
|
1767
1767
|
`)},raw:ve=>{process.stderr.write(ve)},success:ve=>{process.stderr.write(`\u2714 ${ve}
|
|
1768
1768
|
`)},info:ve=>{process.stderr.write(`\u2139 ${ve}
|
|
1769
1769
|
`)},warn:ve=>{process.stderr.write(`\u26A0 ${ve}
|
|
1770
1770
|
`)},error:ve=>{process.stderr.write(`\u2716 ${ve}
|
|
1771
|
-
`)}};try{await Zd(
|
|
1772
|
-
`)}};if(n.format==="stream-json"){let Te=(Pe,
|
|
1773
|
-
`),Pe.type==="chunk"&&Pe.chunk.type==="content"&&(_e+=Pe.chunk.content),Pe.type==="done"&&(Uo(g,o,_e,Pe.metadata),Pe.metadata?.sessionId&&!g.sessionId&&(g.sessionId=String(Pe.metadata.sessionId))),Pe.type==="error"){process.exitCode=1,
|
|
1774
|
-
\u{1F916} Claude:`)),console.log(Yn(Ye.content)),
|
|
1771
|
+
`)}};try{await Zd(we,{targets:r,reviewText:Te,prRefFromArgs:n.postPr??null})}catch(ve){process.stderr.write(`[--post] publish failed: ${ve instanceof Error?ve.message:String(ve)}
|
|
1772
|
+
`)}};if(n.format==="stream-json"){let Te=(Pe,Ct)=>Ct instanceof Date?Ct.toISOString():Ct instanceof Error?{message:Ct.message,name:Ct.name}:Ct;i.stop();let _e="",we=!1,ve=a.sendMessageStream(o);for await(let Pe of ve)if(await kI(process.stdout,JSON.stringify(Pe,Te)+`
|
|
1773
|
+
`),Pe.type==="chunk"&&Pe.chunk.type==="content"&&(_e+=Pe.chunk.content),Pe.type==="done"&&(Uo(g,o,_e,Pe.metadata),Pe.metadata?.sessionId&&!g.sessionId&&(g.sessionId=String(Pe.metadata.sessionId))),Pe.type==="error"){process.exitCode=1,we=!0;break}await Ae(_e,we);return}let Ye=await a.sendMessage(o,{stream:n.stream});i.succeed("Response received");let fe=a.getLastResponseMetadata();if(Uo(g,o,Ye.content,fe??void 0),fe?.sessionId&&!g.sessionId&&(g.sessionId=String(fe.sessionId)),n.format==="json"){let Te=fe?Number(fe.usage?.input_tokens??0):0,_e=fe?Number(fe.usage?.output_tokens??0):0;console.log(JSON.stringify({success:!0,model:B,message:Ye.content,timestamp:Ye.timestamp,...fe?.totalCostUsd!==void 0?{costUsd:fe.totalCostUsd}:{},...fe?.durationMs!==void 0?{durationMs:fe.durationMs}:{},...Te>0?{inputTokens:Te}:{},..._e>0?{outputTokens:_e}:{}},null,2))}else{if(console.log(wI.cyan(`
|
|
1774
|
+
\u{1F916} Claude:`)),console.log(Yn(Ye.content)),fe){let Te=[];fe.durationMs&&Te.push(ge(fe.durationMs)),fe.totalCostUsd!==void 0&&Te.push(st(fe.totalCostUsd));let _e=Number(fe.usage?.input_tokens??0),we=Number(fe.usage?.output_tokens??0);_e+we>0&&Te.push(ie(_e+we)+" tokens"),Te.length>0&&console.log(wI.dim(" \xB7 "+Te.join(" \xB7 ")))}console.log("")}await Ae(Ye.content,!1)}catch(y){if(h=!0,n.format==="stream-json"){let S=y instanceof Error?y:new Error(String(y));try{await kI(process.stdout,JSON.stringify({type:"error",error:{message:S.message,name:S.name}})+`
|
|
1775
1775
|
`)}catch{}process.exitCode=1}i.fail("Failed to send message"),G(y)}finally{if(p&&g.totalTurns>0&&!h)try{let S=Ln(g,m).replace(/\.json$/,"").split("/").pop()??m??g.sessionId??"unknown";process.stderr.write(`Continue with: afk chat <msg> --resume ${S}
|
|
1776
1776
|
`)}catch{}if(a&&(await a.close(),b!==void 0))try{let{mdPath:y}=Ky(b);fY(y)&&process.stderr.write(`Receipt: ${y}
|
|
1777
1777
|
`)}catch{}d&&await d.disconnectAll(),l?.close(),c!==void 0&&await c.cleanup()}})}q();import F$ from"ora";import*as N$ from"node:os";import*as cs from"node:path";import{execFileSync as L7}from"node:child_process";var ip=new Set;function Wo(e){return ip.add(e),()=>{ip.delete(e)}}async function ap(){await Promise.all([...ip].map(e=>e())),ip.clear()}Je();var hY=/^[A-Za-z0-9_@%+=:,./-]+$/;function kl(e){return hY.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Fn(e,t){let n=["afk","interactive"];return typeof t=="string"&&t.length>0&&n.push("--model",kl(t)),n.push("--resume",kl(e)),n.join(" ")}import{homedir as yY}from"node:os";import{sep as Nn}from"node:path";function El(e,t={}){if(!e)return"";let n=t.homedir??yY(),r=bY(e,n),o=t.maxWidth;if(o===void 0||o<=0||V(r)<=o)return r;let s=r.split(Nn).filter(d=>d.length>0);if(s.length<=1)return ne(r,o);let a=r.startsWith("~")?"~":s[0],l=1,c=s[s.length-1],u=[];for(let d=s.length-2;d>=l;d--){let p=s.slice(l,d+1),m=p.length>0?p.join(Nn)+Nn:"";u.push(`${a}${Nn}${m}\u2026${Nn}${c}`)}u.push(`${a}${Nn}\u2026${Nn}${c}`);for(let d of u)if(V(d)<=o)return d;return ne(u[u.length-1],o)}function bY(e,t){if(!t)return e;if(e===t)return"~";let n=t.endsWith(Nn)?t:t+Nn;return e.startsWith(n)?"~"+Nn+e.slice(n.length):e}Br();import*as KO from"node:readline";var wY=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])|\x9B[0-?]*[ -/]*[@-~]|[\x80-\x9F]/g;function ue(e,t=128){let n=e.replace(wY,"");return n.length>t?n.slice(0,t)+"\u2026":n}import{emitKeypressEvents as SY}from"readline";var vY=50;function Ko(e){SY(e,{escapeCodeTimeout:vY})}var Go="\u270E Type your own answer";async function RI(e,t){if(!process.stdout.isTTY||!process.stdin.isTTY||e.length===0)return null;let n=10,r=0,o=0;function s(){let u=o,d=Math.min(u+n,e.length);return{start:u,end:d}}function i(){let{start:u,end:d}=s(),p=[];for(let m=u;m<d;m++){let g=ue(e[m],80);m===r?p.push(` ${f.bold("\u25B6 "+g)}`):p.push(` ${f.dim(g)}`)}if(e.length>n){let{end:m}=s();p.push(f.dim(` (${o+1}\u2013${m} of ${e.length} \u2191/\u2193 to scroll)`))}else p.push(f.dim(" \u2191/\u2193 navigate Enter select Esc cancel"));return p}let a=i();process.stdout.write(a.join(`
|
|
@@ -1782,7 +1782,7 @@ Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
|
1782
1782
|
`)+`
|
|
1783
1783
|
`);let c=l.length;function u(){let d=a();process.stdout.write(`\x1B[${c}A\x1B[0J`+d.join(`
|
|
1784
1784
|
`)+`
|
|
1785
|
-
`),c=d.length}return new Promise(d=>{process.stdin.setRawMode(!0),Ko(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 lp(e=process.env){return e.AFK_DEMO_CLEAN==="1"||typeof e.SCRIPT=="string"&&e.SCRIPT.length>0||e.ASCIINEMA_REC==="1"}function kY(e=process.env){return e.AFK_BELL==="1"}function cp(e=process.env){return e.AFK_REDUCED_MOTION==="1"}function AI(e=process.env){return e.AFK_CARET_BLINK!=="0"}function up(e,t=process.env){kY(t)&&e.isTTY&&e.write("\x07")}var nb=64,pp=256,dp=20,rb=new Set(["__proto__","constructor","prototype"]),Di={action:"decline"},te={action:"cancel"},EY={action:"accept"};function TY(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(!rb.has(l)){if(r+=1,a>=nb){o=!0;continue}n[l]=c,a+=1}}let s=e.required,i=new Set(Array.isArray(s)?s.slice(0,nb*2).filter(a=>typeof a=="string").filter(a=>!rb.has(a)):[]);return{properties:n,required:i,fieldsTruncated:o,originalFieldCount:r}}function xY(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 _I="\u2014 skip (optional) \u2014";async function RY(e,t,n,r,o,s,i){let a,l;if(e.enum!==void 0){let m=e.enum.slice(0,pp);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,_I],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===_I?{tag:"value",value:e.default}:(s.line(f.dim(" \u2713 ")+f.brand(`${r}: ${ue(p,128)}`)),{tag:"value",value:l(p)})}async function CY(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 RY(t,n,a,c,i,o,s);let u;if(t.enum!==void 0){let p=t.enum.slice(0,dp).map(g=>ue(String(g),32)).join("|"),m=t.enum.length>dp?"|\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>pp&&o.line(f.warning(` \u26A0 Field '${c}' has ${t.enum.length} enum values; only the first ${pp} 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,pp),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,dp).map(T=>ue(String(T),32)).join(", "),w=h.length>dp?", \u2026":"";o.line(f.warning(` '${y}' is not a valid choice. Valid: ${S}${w}`));continue}}return{tag:"value",value:g}}}function AY(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 qo={action:"skip"};function mp(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 _Y(e,t,n,r){let o=mp(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 IY(e,t,n){if(n.aborted)return Di;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(Go);let m;try{m=await i({header:mp(e),options:p,multi:l==="multi_choice",signal:n})}catch{return te}if(n.aborted||m===null)return te;if(e.allowCustom&&m.includes(Go)){if(!a)return te;let h=await a({header:mp(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?qo: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:mp(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 _Y(l,e,a,n);if(p===null)return te;if(p.tag==="skip")return qo;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,Go]:p,g=await RI(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}. ${Go}`);;){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 qo;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,Go]:p,g=await CI(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 qo;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}. ${Go}`);;){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 qo;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 qo;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 qo;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 fp(e){return async(t,{signal:n})=>{if(n.aborted)return Di;up(process.stdout),e.suspendInput?.();try{if(t.origin==="agent")return await IY(t,e,n);if(t.mode==="form"){let o=t.requestedSchema,{properties:s,required:i,fieldsTruncated:a,originalFieldCount:l}=typeof o=="object"&&o!==null?TY(o):{properties:{},required:new Set,fieldsTruncated:!1,originalFieldCount:0};xY(e.writer,t),a&&e.writer.line(f.warning(` \u26A0 Schema has ${l} fields; only the first ${nb} 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.")),Di;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.`)),Di;for(let[u,d]of Object.entries(s)){if(n.aborted)return te;let p=await CY(u,d,i.has(u),e.readLine,e.writer,n,e.pickFromList);if(p.tag==="cancel")return te;if(p.tag==="decline")return Di;p.value!==void 0&&!rb.has(u)&&(c[u]=p.value)}return{action:"accept",content:{...c}}}AY(e.writer,t);let r=(await e.readLine(f.dim("Continue? [y/N] "))).trim().toLowerCase();return r===""?te:r==="y"||r==="yes"?EY:Di}finally{e.resumeInput?.()}}}li();nn();cn();Je();Ot();function II(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 gp=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=He.subscribe(()=>{this.onResize()}),this.resizeImmediateUnsub=He.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=El(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=II({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(`${PY(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 PY(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}import{execFile as MY}from"node:child_process";import{promisify as OY}from"node:util";var $Y=OY(MY);function DY(e){return(t,n,r)=>$Y(t,n,{cwd:r,timeout:e,killSignal:"SIGTERM",maxBuffer:64*1024}).then(o=>({stdout:o.stdout,stderr:o.stderr}))}var hp=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??DY(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 Xd((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 Ft=new Map,zo=new Map;function ge(e){if(Ft.has(e.name))throw new Error(`Slash command already registered: ${e.name}`);Ft.set(e.name,e);for(let t of e.aliases??[]){if(zo.has(t)||Ft.has(t))throw new Error(`Slash alias collides: ${t}`);zo.set(t,e.name)}}function to(e){if(Ft.has(e.name)){for(let[t,n]of zo.entries())n===e.name&&zo.delete(t);Ft.delete(e.name)}ge(e)}function PI(e){Ft.has(e.name)||ge(e)}function MI(){Ft.clear(),zo.clear()}function it(){return[...Ft.values()].sort((e,t)=>e.name.localeCompare(t.name))}function Li(){let e=[];for(let[t,n]of zo.entries()){let r=Ft.get(n);r&&e.push({alias:t,canonical:n,summary:r.summary})}return e.sort((t,n)=>t.alias.localeCompare(n.alias))}function LY(e){if(Ft.has(e))return Ft.get(e);let t=zo.get(e);return t?Ft.get(t):void 0}function FY(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 NY(e,t=3){let n;for(let r of Ft.keys()){let o=FY(e,r);o<=t&&(n===void 0||o<n.dist)&&(n={name:r,dist:o})}return n?.name}function ob(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 OI(e,t,n){let r=ob(e);if(r===null)return{handled:!1};let o=LY(r.name);if(!o){let a=NY(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 HY from"ora";Va();function $I(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 yp(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 bp(e,t){let n=e.turns;if(n.length===0)return;let r=n[n.length-1];if(!r)return;let o=LI(DI(r.user),80),s=LI(jY(DI(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 DI(e){return e.replace(UY,"").replace(/\s+/g," ").trim()}var UY=/\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 jY(e){let t=e.match(/^.*?(?<![A-Za-z]\.[A-Za-z])[.!?](?=\s|$)/);return t?t[0]:e}function LI(e,t){let n=[...e];return n.length<=t?e:n.slice(0,t-1).join("")+"\u2026"}var Tl={stream:process.stdout,hideCursor:!1,discardStdin:!1};function sb(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)/$t(e.model):0}function Bn(e,t,n){let r=sb(e,t),o=$t(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=$I(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}:{}}}Ct();var WY={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"}},KY={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(),q_(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"}},GY={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=HY({text:f.meta("Summarizing earlier turns..."),...Tl}).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 at)throw n;if(n instanceof we)return e.out.info(`Compaction skipped: ${n.reason??"blocked by hook"}`),"continue";e.out.error(n instanceof Error?n.message:"Unknown error")}return"continue"}},qY={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=it(),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(de());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"}},FI=[WY,KY,GY,qY];function ib(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 Xt(e,t){return` ${f.label(e.padEnd(16))} ${t}`}function wp(e){let t=[];t.push(" "+de("Session Debug")),e.sessionId&&t.push(Xt("session",e.sessionId)),e.model&&t.push(Xt("model",e.model)),e.permissionMode&&t.push(Xt("permission",e.permissionMode)),e.cwd&&t.push(Xt("cwd",e.cwd)),e.claudeCodeVersion&&t.push(Xt("sdk",`v${e.claudeCodeVersion}`)),e.apiKeySource&&t.push(Xt("api key",e.apiKeySource)),e.outputStyle&&t.push(Xt("output style",e.outputStyle));let n=e.tools?.length??0;t.push(Xt(`tools (${n})`,ib(e.tools)));let r=e.mcpServers??[],o=r.length?r.map(c=>`${c.name}[${c.status}]`).join(", "):f.dim("(none)");t.push(Xt(`mcp (${r.length})`,o));let s=e.skills?.length??0;t.push(Xt(`skills (${s})`,ib(e.skills)));let i=e.plugins?.length??0,a=i?(e.plugins??[]).map(c=>c.name).join(", "):f.dim("(none)");t.push(Xt(`plugins (${i})`,a));let l=e.slashCommands?.length??0;return t.push(Xt(`slash (${l})`,ib(e.slashCommands))),t.push(" "+de()),t.join(`
|
|
1785
|
+
`),c=d.length}return new Promise(d=>{process.stdin.setRawMode(!0),Ko(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 lp(e=process.env){return e.AFK_DEMO_CLEAN==="1"||typeof e.SCRIPT=="string"&&e.SCRIPT.length>0||e.ASCIINEMA_REC==="1"}function kY(e=process.env){return e.AFK_BELL==="1"}function cp(e=process.env){return e.AFK_REDUCED_MOTION==="1"}function AI(e=process.env){return e.AFK_CARET_BLINK!=="0"}function up(e,t=process.env){kY(t)&&e.isTTY&&e.write("\x07")}var nb=64,pp=256,dp=20,rb=new Set(["__proto__","constructor","prototype"]),Di={action:"decline"},te={action:"cancel"},EY={action:"accept"};function TY(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(!rb.has(l)){if(r+=1,a>=nb){o=!0;continue}n[l]=c,a+=1}}let s=e.required,i=new Set(Array.isArray(s)?s.slice(0,nb*2).filter(a=>typeof a=="string").filter(a=>!rb.has(a)):[]);return{properties:n,required:i,fieldsTruncated:o,originalFieldCount:r}}function xY(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 _I="\u2014 skip (optional) \u2014";async function RY(e,t,n,r,o,s,i){let a,l;if(e.enum!==void 0){let m=e.enum.slice(0,pp);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,_I],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===_I?{tag:"value",value:e.default}:(s.line(f.dim(" \u2713 ")+f.brand(`${r}: ${ue(p,128)}`)),{tag:"value",value:l(p)})}async function CY(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 RY(t,n,a,c,i,o,s);let u;if(t.enum!==void 0){let p=t.enum.slice(0,dp).map(g=>ue(String(g),32)).join("|"),m=t.enum.length>dp?"|\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>pp&&o.line(f.warning(` \u26A0 Field '${c}' has ${t.enum.length} enum values; only the first ${pp} 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,pp),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,dp).map(T=>ue(String(T),32)).join(", "),w=h.length>dp?", \u2026":"";o.line(f.warning(` '${y}' is not a valid choice. Valid: ${S}${w}`));continue}}return{tag:"value",value:g}}}function AY(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 qo={action:"skip"};function mp(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 _Y(e,t,n,r){let o=mp(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 IY(e,t,n){if(n.aborted)return Di;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(Go);let m;try{m=await i({header:mp(e),options:p,multi:l==="multi_choice",signal:n})}catch{return te}if(n.aborted||m===null)return te;if(e.allowCustom&&m.includes(Go)){if(!a)return te;let h=await a({header:mp(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?qo: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:mp(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 _Y(l,e,a,n);if(p===null)return te;if(p.tag==="skip")return qo;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,Go]:p,g=await RI(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}. ${Go}`);;){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 qo;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,Go]:p,g=await CI(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 qo;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}. ${Go}`);;){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 qo;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 qo;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 qo;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 fp(e){return async(t,{signal:n})=>{if(n.aborted)return Di;up(process.stdout),e.suspendInput?.();try{if(t.origin==="agent")return await IY(t,e,n);if(t.mode==="form"){let o=t.requestedSchema,{properties:s,required:i,fieldsTruncated:a,originalFieldCount:l}=typeof o=="object"&&o!==null?TY(o):{properties:{},required:new Set,fieldsTruncated:!1,originalFieldCount:0};xY(e.writer,t),a&&e.writer.line(f.warning(` \u26A0 Schema has ${l} fields; only the first ${nb} 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.")),Di;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.`)),Di;for(let[u,d]of Object.entries(s)){if(n.aborted)return te;let p=await CY(u,d,i.has(u),e.readLine,e.writer,n,e.pickFromList);if(p.tag==="cancel")return te;if(p.tag==="decline")return Di;p.value!==void 0&&!rb.has(u)&&(c[u]=p.value)}return{action:"accept",content:{...c}}}AY(e.writer,t);let r=(await e.readLine(f.dim("Continue? [y/N] "))).trim().toLowerCase();return r===""?te:r==="y"||r==="yes"?EY:Di}finally{e.resumeInput?.()}}}li();nn();cn();Je();Ot();function II(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 gp=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=He.subscribe(()=>{this.onResize()}),this.resizeImmediateUnsub=He.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=El(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=II({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(`${PY(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 PY(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}import{execFile as MY}from"node:child_process";import{promisify as OY}from"node:util";var $Y=OY(MY);function DY(e){return(t,n,r)=>$Y(t,n,{cwd:r,timeout:e,killSignal:"SIGTERM",maxBuffer:64*1024}).then(o=>({stdout:o.stdout,stderr:o.stderr}))}var hp=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??DY(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 Xd((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 Ft=new Map,zo=new Map;function he(e){if(Ft.has(e.name))throw new Error(`Slash command already registered: ${e.name}`);Ft.set(e.name,e);for(let t of e.aliases??[]){if(zo.has(t)||Ft.has(t))throw new Error(`Slash alias collides: ${t}`);zo.set(t,e.name)}}function to(e){if(Ft.has(e.name)){for(let[t,n]of zo.entries())n===e.name&&zo.delete(t);Ft.delete(e.name)}he(e)}function PI(e){Ft.has(e.name)||he(e)}function MI(){Ft.clear(),zo.clear()}function it(){return[...Ft.values()].sort((e,t)=>e.name.localeCompare(t.name))}function Li(){let e=[];for(let[t,n]of zo.entries()){let r=Ft.get(n);r&&e.push({alias:t,canonical:n,summary:r.summary})}return e.sort((t,n)=>t.alias.localeCompare(n.alias))}function LY(e){if(Ft.has(e))return Ft.get(e);let t=zo.get(e);return t?Ft.get(t):void 0}function FY(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 NY(e,t=3){let n;for(let r of Ft.keys()){let o=FY(e,r);o<=t&&(n===void 0||o<n.dist)&&(n={name:r,dist:o})}return n?.name}function ob(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 OI(e,t,n){let r=ob(e);if(r===null)return{handled:!1};let o=LY(r.name);if(!o){let a=NY(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 HY from"ora";Va();function $I(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 yp(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 bp(e,t){let n=e.turns;if(n.length===0)return;let r=n[n.length-1];if(!r)return;let o=LI(DI(r.user),80),s=LI(jY(DI(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 DI(e){return e.replace(UY,"").replace(/\s+/g," ").trim()}var UY=/\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 jY(e){let t=e.match(/^.*?(?<![A-Za-z]\.[A-Za-z])[.!?](?=\s|$)/);return t?t[0]:e}function LI(e,t){let n=[...e];return n.length<=t?e:n.slice(0,t-1).join("")+"\u2026"}var Tl={stream:process.stdout,hideCursor:!1,discardStdin:!1};function sb(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)/$t(e.model):0}function Bn(e,t,n){let r=sb(e,t),o=$t(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=$I(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}:{}}}bt();var WY={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"}},KY={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(),q_(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"}},GY={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=HY({text:f.meta("Summarizing earlier turns..."),...Tl}).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 at)throw n;if(n instanceof pe)return e.out.info(`Compaction skipped: ${n.reason??"blocked by hook"}`),"continue";e.out.error(n instanceof Error?n.message:"Unknown error")}return"continue"}},qY={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=it(),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(de());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"}},FI=[WY,KY,GY,qY];function ib(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 Xt(e,t){return` ${f.label(e.padEnd(16))} ${t}`}function wp(e){let t=[];t.push(" "+de("Session Debug")),e.sessionId&&t.push(Xt("session",e.sessionId)),e.model&&t.push(Xt("model",e.model)),e.permissionMode&&t.push(Xt("permission",e.permissionMode)),e.cwd&&t.push(Xt("cwd",e.cwd)),e.claudeCodeVersion&&t.push(Xt("sdk",`v${e.claudeCodeVersion}`)),e.apiKeySource&&t.push(Xt("api key",e.apiKeySource)),e.outputStyle&&t.push(Xt("output style",e.outputStyle));let n=e.tools?.length??0;t.push(Xt(`tools (${n})`,ib(e.tools)));let r=e.mcpServers??[],o=r.length?r.map(c=>`${c.name}[${c.status}]`).join(", "):f.dim("(none)");t.push(Xt(`mcp (${r.length})`,o));let s=e.skills?.length??0;t.push(Xt(`skills (${s})`,ib(e.skills)));let i=e.plugins?.length??0,a=i?(e.plugins??[]).map(c=>c.name).join(", "):f.dim("(none)");t.push(Xt(`plugins (${i})`,a));let l=e.slashCommands?.length??0;return t.push(Xt(`slash (${l})`,ib(e.slashCommands))),t.push(" "+de()),t.join(`
|
|
1786
1786
|
`)}rt();nn();var ab=["local","small","medium","large","opus","opus_1m","sonnet","sonnet_1m","haiku","fable"],zY={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(de()),n.line(` total ${f.success(st(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(st(r))}`)}if(t.turnCosts.length>0){let r=t.turnCosts.slice(-5).map(st).join(f.dim(" \xB7 "));n.line(` last 5 ${r}`)}return n.line(),"continue"}};function JY(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(de()),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 VY(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=$t(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(de()),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 YY={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();JY(e.out,t)}catch{VY(e.out,e.stats)}return"continue"}},XY={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(de()),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")}},ZY={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"}},QY={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: ${ab.join(", ")} (or any org/model HF id)`)),"continue";let r=ab.includes(n),o=$s(n)!==void 0,s=re(n)==="openai-compatible";if(!r&&!o&&!s)return e.out.warn(`Unknown model: ${n}. Aliases: ${ab.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"}},e4={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(de());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"}},t4={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(()=>(rp(),cI)),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(de());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(de());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"}},n4={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(de());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"}},r4={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(wp(t)),e.out.line()}catch(t){e.out.error(`Could not read session metadata: ${t instanceof Error?t.message:String(t)}`)}return"continue"}},NI=[zY,YY,XY,ZY,QY,e4,t4,n4,r4];K();vh();var lb=!1;function o4(e){switch(e){case"bypassPermissions":return"bypass restored \u2014 no prompts, read/write any path";case"acceptEdits":return"accept-edits restored \u2014 edits auto-approved";case"dontAsk":case"auto":return"previous mode restored \u2014 no approval prompts";default:return"default permissions restored"}}async function xl(e,t){let n=e.stats.permissionMode==="plan",r=t!==void 0?t:!n,o=r?"plan":e.session.current.getPrePlanMode?.()??"default";try{if(await e.session.current.setPermissionMode(o),e.stats.permissionMode=o,e.ui.repaintStatusLine(),r){let s=lb?"":f.dim(" /plan off saves the plan + implements; Shift+Tab cycles to the next mode.");lb||(lb=!0),e.out.success(f.warning("\u25CF plan mode ON")+f.dim(" \u2014 writes are refused; read-only bash runs, mutating bash is blocked.")+s)}else e.out.success(f.success("\u25CB plan mode OFF")+f.dim(` \u2014 ${o4(o)}`))}catch(s){e.out.error(`Could not toggle plan mode: ${s instanceof Error?s.message:String(s)}`)}}async function s4(e){if(await xl(e,!1),e.stats.permissionMode==="plan")return"continue";let t=bc(e.stats.cwd??process.cwd());return e.out.info(f.dim(` \u2192 saving the plan to ${t}/, then implementing it.`)),{kind:"submit",message:zu(t)}}var BI={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 xl(e,!0),{kind:"submit",message:n}):(r==="on"?!0:r==="off"?!1:e.stats.permissionMode!=="plan")===!0?(e.stats.permissionMode==="plan"||await xl(e,!0),"continue"):e.stats.permissionMode!=="plan"?(await xl(e,!1),"continue"):s4(e)}};q();vu();Si();Io();var UI=20,i4={done:"\u2705 Done",blocked:"\u26D4 Blocked",asking:"\u2753 Asking",interrupted:"\u23F8\uFE0F Interrupted"},a4={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"]]},l4=new Set(["write_file","edit_file","bash"]);function jI(e){return e.some(t=>l4.has(t.toolName)&&t.isError!==!0)}function c4(e,t={}){let n=e.kind==="done"&&t.unverified===!0,o=`\u{1F916} AFK \xB7 ${n?"\u26A0\uFE0F Done (unverified)":i4[e.kind]}`,s=[];for(let[a,l]of a4[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
1787
|
`):"(no detail)";return Ve(`${o}
|
|
1788
1788
|
${i}`)}var cb=0,ub=!1;function HI(){cb=0,ub=!1}async function WI(e,t=Lr,n={}){try{if(cb>=UI){ub||(ub=!0,await t(`\u{1F916} AFK \xB7 reached ${UI} updates this session \u2014 further terminal-state pushes muted. Run /afk off then /afk on to resume.`));return}cb+=1,await t(c4(e,n))}catch{}}K();import*as Fi from"node:fs";import*as GI from"node:path";import{createHmac as u4,randomBytes as qI,timingSafeEqual as d4}from"node:crypto";var p4=32,zI="\0";function m4(e){return JSON.stringify(db(e))}function db(e){if(Array.isArray(e))return e.map(db);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=db(t[r]);return n}return e}function JI(e){let t=KI(e);if(t)return t;let n;try{n=Pf(e)}catch{return null}try{Fi.mkdirSync(GI.dirname(n),{recursive:!0});let r=qI(p4).toString("hex");return Fi.writeFileSync(n,r+`
|
|
@@ -1802,12 +1802,12 @@ ${i}`)}var cb=0,ub=!1;function HI(){cb=0,ub=!1}async function WI(e,t=Lr,n={}){tr
|
|
|
1802
1802
|
|
|
1803
1803
|
${a}
|
|
1804
1804
|
`);if(l===r)throw new Error("No ## [Unreleased] section found");N4(n,l)}var RP={name:"/changelog",usage:"/changelog [--dry-run]",summary:"Generate CHANGELOG entries from commits since last tag",hint:"When you are preparing a release and want to auto-generate changelog entries from conventional commits.",async handler(e,t){let n=t.split(/\s+/).includes("--dry-run"),r=process.cwd(),o;try{o=kP(r)}catch(a){return e.out.error(`Failed to read git log: ${a instanceof Error?a.message:String(a)}`),"continue"}if(o.length===0)return e.out.warn("No commits found since the last tag."),"continue";let s=EP(o),i=(()=>{try{let a=K4(xP(r,"CHANGELOG.md"),"utf8");return fb(a)}catch{return""}})();e.out.line(),e.out.info(`${o.length} commits since last tag`),e.out.line(),i&&(e.out.warn("Existing [Unreleased] entries will be preserved above new entries."),e.out.line()),e.out.line(f.heading("Preview:")),e.out.line(f.dim("\u2500".repeat(60)));for(let a of s.split(`
|
|
1805
|
-
`))a.startsWith("### ")?e.out.line(f.bold(a)):a.startsWith("- ")?e.out.line(f.dim(" ")+a):e.out.line(a);if(e.out.line(f.dim("\u2500".repeat(60))),n)return e.out.info("Dry run \u2014 CHANGELOG.md not modified."),"continue";try{if(!W4(xP(r,"CHANGELOG.md")))return e.out.error("CHANGELOG.md not found. Create one with a ## [Unreleased] section first."),"continue";TP(r,s),e.out.success("Wrote entries to CHANGELOG.md [Unreleased] section."),e.out.line(f.dim(" Review with: git diff CHANGELOG.md"))}catch(a){e.out.error(`Failed to update CHANGELOG.md: ${a instanceof Error?a.message:String(a)}`)}return"continue"}};ad();var gb,hb;function CP(e){gb=e}function AP(e){hb=e}var _P={running:"\u25D0",completed:"\u2713",failed:"\u2717",cancelled:"\u2298"};function Tp(e){return gb||(e.out.error("Background subagent jobs are not available in this session."),null)}var yb=/\x1b\[[0-9;]*[a-zA-Z]/g;function G4(e,t=120){let n=e.replace(yb,"").replace(/[\r\n]+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function q4(e){let t=_P[e.status],n=e.endedAt!==void 0?
|
|
1806
|
-
${u}`}function bb(e,t){let n=_P[t.status];e.out.line(` ${n} ${f.bold(t.jobId)} ${t.label}`);let r=t.endedAt!==void 0?
|
|
1805
|
+
`))a.startsWith("### ")?e.out.line(f.bold(a)):a.startsWith("- ")?e.out.line(f.dim(" ")+a):e.out.line(a);if(e.out.line(f.dim("\u2500".repeat(60))),n)return e.out.info("Dry run \u2014 CHANGELOG.md not modified."),"continue";try{if(!W4(xP(r,"CHANGELOG.md")))return e.out.error("CHANGELOG.md not found. Create one with a ## [Unreleased] section first."),"continue";TP(r,s),e.out.success("Wrote entries to CHANGELOG.md [Unreleased] section."),e.out.line(f.dim(" Review with: git diff CHANGELOG.md"))}catch(a){e.out.error(`Failed to update CHANGELOG.md: ${a instanceof Error?a.message:String(a)}`)}return"continue"}};ad();var gb,hb;function CP(e){gb=e}function AP(e){hb=e}var _P={running:"\u25D0",completed:"\u2713",failed:"\u2717",cancelled:"\u2298"};function Tp(e){return gb||(e.out.error("Background subagent jobs are not available in this session."),null)}var yb=/\x1b\[[0-9;]*[a-zA-Z]/g;function G4(e,t=120){let n=e.replace(yb,"").replace(/[\r\n]+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function q4(e){let t=_P[e.status],n=e.endedAt!==void 0?ge(e.endedAt-e.startedAt):ge(Date.now()-e.startedAt),r=e.label.length>60?`${e.label.slice(0,60)}\u2026`:e.label,o=` ${t} ${f.bold(e.jobId)} ${r} ${f.dim(`(${e.status} \xB7 ${n} \xB7 ${e.model})`)}`;if(!hb||e.status!=="running")return o;let s=hb.getSummary(e.jobId);if(!s)return o;let i=process.stdout.columns??120,a=G4(s.text,Math.max(40,i-10)),l=Math.round((Date.now()-s.refreshedAt)/1e3),c=s.stale?" [stale]":"",u=f.dim(` \u21B3 ${a} (${l}s ago)${c}`);return`${o}
|
|
1806
|
+
${u}`}function bb(e,t){let n=_P[t.status];e.out.line(` ${n} ${f.bold(t.jobId)} ${t.label}`);let r=t.endedAt!==void 0?ge(t.endedAt-t.startedAt):ge(Date.now()-t.startedAt);e.out.line(` Status: ${t.status} \xB7 ${r}`),e.out.line(` Subagent: ${t.subagentId}`),e.out.line(` Model: ${t.model}`);let o=t.result;if(o?.message?.content){e.out.line("");let s=typeof o.message.content=="string"?o.message.content:JSON.stringify(o.message.content),i=s.split(`
|
|
1807
1807
|
`).slice(0,40);for(let a of i)e.out.line(` ${a}`);s.split(`
|
|
1808
|
-
`).length>40&&e.out.line(f.dim(" \u2026 (truncated; full result available via /bgsub:join again)"))}o?.error&&e.out.error(` Error: ${o.error.message}`)}var z4={name:"/bgsub",summary:"List background subagent jobs",usage:"/bgsub [id]",hint:'When you want to check on background subagent jobs spawned with mode="background" during this session.',async handler(e,t){let n=Tp(e);if(!n)return"continue";let r=t.trim();if(r){let s=n.get(r);return s?(bb(e,s),"continue"):(e.out.error(`No background job with ID "${r}".`),"continue")}let o=n.list();if(o.length===0)return e.out.info('No background subagent jobs. Spawn one by calling the agent tool with mode="background".'),"continue";for(let s of o)e.out.line(q4(s));return"continue"}},J4={name:"/bgsub:status",summary:"Show one background job",usage:"/bgsub:status <id>",hint:"When you need the full detail view for one specific background job by its ID.",async handler(e,t){let n=Tp(e);if(!n)return"continue";let r=t.trim();if(!r)return e.out.info("Usage: /bgsub:status <id>"),"continue";let o=n.get(r);return o?(bb(e,o),"continue"):(e.out.error(`No background job with ID "${r}".`),"continue")}},V4={name:"/bgsub:join",summary:"Wait for a background subagent job and print its result",usage:"/bgsub:join <id>",hint:"When a background subagent has finished and you want to surface its result into the conversation.",async handler(e,t){let n=Tp(e);if(!n)return"continue";let r=t.trim();if(!r)return e.out.info("Usage: /bgsub:join <id>"),"continue";if(n.get(r)){try{await n.join(r)}catch(i){let a=i instanceof Error?i.message:String(i);e.out.error(`/bgsub:join failed: ${a}`)}let s=n.get(r);return s&&bb(e,s),"continue"}let o=await Mn.readMeta(r);if(o){e.out.info("Job evicted from memory \u2014 replaying from log.");let s=0;for await(let i of Mn.readEvents(r)){let a=Y4(i);a!==null&&(e.out.line(a),s++)}return s===0&&e.out.info(` (no events recorded for job ${r})`),e.out.line(""),e.out.line(` Status: ${o.status}`+(o.endedAt!==void 0?` \xB7 ended ${new Date(o.endedAt).toISOString()}`:"")),"continue"}return e.out.error(`No background job with ID "${r}".`),"continue"}};function Y4(e){if(e.type==="chunk"){let t=e.chunk;return t.type==="content"?t.content.replace(yb,""):t.type==="tool_use_detail"?f.dim(` [tool: ${t.toolName}]`):null}if(e.type==="error")return f.dim(` [error: ${e.error.message}]`);if(e.type==="message"){let t=e.message.content;return(typeof t=="string"?t:JSON.stringify(t)).replace(yb,"")}return null}var X4={name:"/bgsub:cancel",summary:"Cancel a running background subagent job",usage:"/bgsub:cancel <id>",hint:"When you want to abort a background subagent job that is still in progress.",async handler(e,t){let n=Tp(e);if(!n)return"continue";let r=t.trim();if(!r)return e.out.info("Usage: /bgsub:cancel <id>"),"continue";let o=n.get(r);return o?o.status!=="running"?(e.out.info(`Job ${r} is already ${o.status}; nothing to cancel.`),"continue"):(await n.cancelJob(r)?e.out.line(f.dim(` \u2192 cancellation requested for ${r}`)):e.out.info(`Job ${r} could not be cancelled (already terminal).`),"continue"):(e.out.error(`No background job with ID "${r}".`),"continue")}},IP=[z4,J4,V4,X4];var Ni;function MP(e){Ni=e}function PP(e){let t=e.trim();return t.startsWith("sh-")?t:/^\d+$/.test(t)?`sh-${t}`:t}function Z4(e){switch(e){case"running":return"\u25B6";case"completed":return"\u2713";case"failed":return"\u2717";case"killed":return"\u2298";default:return"?"}}var OP={name:"/sh",summary:"Inspect or kill user-typed `!cmd` shell jobs",usage:"/sh [list | show <id> | kill <id>]",hint:"Manages shell processes started with `!cmd` (foreground) or `!&cmd` (background). No args \u2192 list. `show <id>` prints captured output, `kill <id>` terminates a running job.",async handler(e,t){if(!Ni)return e.out.error("Shell passthrough not available in this session."),"continue";let n=t.trim(),[r,...o]=n===""?["list"]:n.split(/\s+/),s=o.join(" ");switch(r){case"list":{let i=Ni.registry.list();if(i.length===0)return e.out.line(f.dim(" no shell jobs in this session yet \u2014 type !<cmd> to start one")),"continue";e.out.line(f.dim(" id status duration mode command"));for(let a of i){let l=Z4(a.status),c=a.status.padEnd(10),u=a.result?
|
|
1808
|
+
`).length>40&&e.out.line(f.dim(" \u2026 (truncated; full result available via /bgsub:join again)"))}o?.error&&e.out.error(` Error: ${o.error.message}`)}var z4={name:"/bgsub",summary:"List background subagent jobs",usage:"/bgsub [id]",hint:'When you want to check on background subagent jobs spawned with mode="background" during this session.',async handler(e,t){let n=Tp(e);if(!n)return"continue";let r=t.trim();if(r){let s=n.get(r);return s?(bb(e,s),"continue"):(e.out.error(`No background job with ID "${r}".`),"continue")}let o=n.list();if(o.length===0)return e.out.info('No background subagent jobs. Spawn one by calling the agent tool with mode="background".'),"continue";for(let s of o)e.out.line(q4(s));return"continue"}},J4={name:"/bgsub:status",summary:"Show one background job",usage:"/bgsub:status <id>",hint:"When you need the full detail view for one specific background job by its ID.",async handler(e,t){let n=Tp(e);if(!n)return"continue";let r=t.trim();if(!r)return e.out.info("Usage: /bgsub:status <id>"),"continue";let o=n.get(r);return o?(bb(e,o),"continue"):(e.out.error(`No background job with ID "${r}".`),"continue")}},V4={name:"/bgsub:join",summary:"Wait for a background subagent job and print its result",usage:"/bgsub:join <id>",hint:"When a background subagent has finished and you want to surface its result into the conversation.",async handler(e,t){let n=Tp(e);if(!n)return"continue";let r=t.trim();if(!r)return e.out.info("Usage: /bgsub:join <id>"),"continue";if(n.get(r)){try{await n.join(r)}catch(i){let a=i instanceof Error?i.message:String(i);e.out.error(`/bgsub:join failed: ${a}`)}let s=n.get(r);return s&&bb(e,s),"continue"}let o=await Mn.readMeta(r);if(o){e.out.info("Job evicted from memory \u2014 replaying from log.");let s=0;for await(let i of Mn.readEvents(r)){let a=Y4(i);a!==null&&(e.out.line(a),s++)}return s===0&&e.out.info(` (no events recorded for job ${r})`),e.out.line(""),e.out.line(` Status: ${o.status}`+(o.endedAt!==void 0?` \xB7 ended ${new Date(o.endedAt).toISOString()}`:"")),"continue"}return e.out.error(`No background job with ID "${r}".`),"continue"}};function Y4(e){if(e.type==="chunk"){let t=e.chunk;return t.type==="content"?t.content.replace(yb,""):t.type==="tool_use_detail"?f.dim(` [tool: ${t.toolName}]`):null}if(e.type==="error")return f.dim(` [error: ${e.error.message}]`);if(e.type==="message"){let t=e.message.content;return(typeof t=="string"?t:JSON.stringify(t)).replace(yb,"")}return null}var X4={name:"/bgsub:cancel",summary:"Cancel a running background subagent job",usage:"/bgsub:cancel <id>",hint:"When you want to abort a background subagent job that is still in progress.",async handler(e,t){let n=Tp(e);if(!n)return"continue";let r=t.trim();if(!r)return e.out.info("Usage: /bgsub:cancel <id>"),"continue";let o=n.get(r);return o?o.status!=="running"?(e.out.info(`Job ${r} is already ${o.status}; nothing to cancel.`),"continue"):(await n.cancelJob(r)?e.out.line(f.dim(` \u2192 cancellation requested for ${r}`)):e.out.info(`Job ${r} could not be cancelled (already terminal).`),"continue"):(e.out.error(`No background job with ID "${r}".`),"continue")}},IP=[z4,J4,V4,X4];var Ni;function MP(e){Ni=e}function PP(e){let t=e.trim();return t.startsWith("sh-")?t:/^\d+$/.test(t)?`sh-${t}`:t}function Z4(e){switch(e){case"running":return"\u25B6";case"completed":return"\u2713";case"failed":return"\u2717";case"killed":return"\u2298";default:return"?"}}var OP={name:"/sh",summary:"Inspect or kill user-typed `!cmd` shell jobs",usage:"/sh [list | show <id> | kill <id>]",hint:"Manages shell processes started with `!cmd` (foreground) or `!&cmd` (background). No args \u2192 list. `show <id>` prints captured output, `kill <id>` terminates a running job.",async handler(e,t){if(!Ni)return e.out.error("Shell passthrough not available in this session."),"continue";let n=t.trim(),[r,...o]=n===""?["list"]:n.split(/\s+/),s=o.join(" ");switch(r){case"list":{let i=Ni.registry.list();if(i.length===0)return e.out.line(f.dim(" no shell jobs in this session yet \u2014 type !<cmd> to start one")),"continue";e.out.line(f.dim(" id status duration mode command"));for(let a of i){let l=Z4(a.status),c=a.status.padEnd(10),u=a.result?ge(a.result.durationMs).padEnd(12):ge(Date.now()-a.startedAt).padEnd(12),d=a.mode==="background"?"bg":"fg",p=a.command.length>60?a.command.slice(0,57)+"...":a.command;e.out.line(` ${l} ${a.id.padEnd(5)} ${c} ${u} ${d.padEnd(4)} ${p}`)}return"continue"}case"show":{if(!s)return e.out.info("Usage: /sh show <id>"),"continue";let i=PP(s),a=Ni.registry.get(i);if(!a)return e.out.error(`Job ${i} not found.`),"continue";if(e.out.line(f.dim(`$ ${a.command}`)),!a.result)return e.out.line(f.dim(" (still running \u2014 output captured so far is not yet flushed)")),"continue";let l=a.result.displayCaptured;l.length===0?e.out.line(f.dim(" (no output)")):e.out.raw(l.endsWith(`
|
|
1809
1809
|
`)?l:l+`
|
|
1810
|
-
`);let c=a.result.errorReason==="abort"?"killed":a.result.errorReason==="timeout"?"timed out":`exit ${a.result.exitCode??0}`;return e.out.line(f.dim(` [${a.id} \xB7 ${c} \xB7 ${
|
|
1810
|
+
`);let c=a.result.errorReason==="abort"?"killed":a.result.errorReason==="timeout"?"timed out":`exit ${a.result.exitCode??0}`;return e.out.line(f.dim(` [${a.id} \xB7 ${c} \xB7 ${ge(a.result.durationMs)}]`)),a.result.truncated&&e.out.line(f.warning(" \u26A0 output was truncated \u2014 re-run with smaller scope if you need the tail")),"continue"}case"kill":{if(!s)return e.out.info("Usage: /sh kill <id>"),"continue";let i=PP(s);if(Ni.registry.kill(i))e.out.success(`Killed ${i}.`);else{let l=Ni.registry.get(i);l?e.out.warn(`${i} is not running (status: ${l.status}).`):e.out.error(`Job ${i} not found.`)}return"continue"}default:return e.out.warn(`Unknown subcommand: ${r}. Try /sh list, /sh show <id>, or /sh kill <id>.`),"continue"}}};import{existsSync as ew}from"node:fs";import{resolve as tw}from"node:path";var xp="command-name",Rp="command-message",Cp="command-args";function Ap(e,t){return`<${xp}>/${e}</${xp}>
|
|
1811
1811
|
<${Rp}>${e}</${Rp}>
|
|
1812
1812
|
<${Cp}>${t}</${Cp}>`}var $P=`<(?:${xp}|${Rp}|${Cp})[\\s\\S]*?</(?:${xp}|${Rp}|${Cp})>`,Q4=new RegExp(`(\\n|^)[ \\t]*${$P}[ \\t]*\\n?`,"gm"),e8=new RegExp($P,"g");function wb(e){let t=!1,n=e.replace(Q4,(r,o)=>(t=!0,o));return n=n.replace(e8,()=>(t=!0,"")),n=n.replace(/^[ \t]+$/gm,""),n=n.replace(/\n{3,}/g,`
|
|
1813
1813
|
|
|
@@ -1819,17 +1819,17 @@ ${u}`}function bb(e,t){let n=_P[t.status];e.out.line(` ${n} ${f.bold(t.jobId)}
|
|
|
1819
1819
|
`),s=0;for(let i=0;i<o.length;i++){let a=Be(o[i]),l=(i===0?t:0)+_l(a);s+=Math.max(1,Math.ceil(l/r))}return Math.max(0,s-1)}function no(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=Be(c.slice(0,p)),g=(l===0?n:0)+_l(m),h=Math.floor(g/o),b=g%o;return{row:i+h,col:b}}let d=(l===0?n:0)+_l(Be(c));i+=Math.max(1,Math.ceil(d/o)),a+=u}return{row:i,col:0}}function Vo(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.trunc(e))):0}function Un(e,t){let n=Vo(t,e.buffer.length);return n===e.cursor?e:{buffer:e.buffer,cursor:n}}function DP(e,t){let n=Vo(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 LP(e,t){let n=e.length,r=Vo(t,n);for(;r<n&&/\s/.test(e.charAt(r));)r++;for(;r<n&&!/\s/.test(e.charAt(r));)r++;return r}function FP(e,t){let n=Vo(t,e.length),r=n===0?-1:e.lastIndexOf(`
|
|
1821
1821
|
`,n-1);return r<0?0:r+1}function NP(e,t){let n=Vo(t,e.length),r=e.indexOf(`
|
|
1822
|
-
`,n);return r<0?e.length:r}function ro(e,t,n){let r=Vo(t.start,e.buffer.length),o=Vo(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 W={seed(e=""){return{buffer:e,cursor:e.length}},replaceRange:ro,insert(e,t){return t.length===0?e:ro(e,{start:e.cursor,end:e.cursor},t)},backspace(e){if(e.cursor===0)return e;let t=Df(e.buffer,e.cursor);return ro(e,{start:t,end:e.cursor},"")},deleteForward(e){if(e.cursor>=e.buffer.length)return e;let t=wo(e.buffer,e.cursor);return ro(e,{start:e.cursor,end:t},"")},deleteWordBackward(e){if(e.cursor===0)return e;let t=DP(e.buffer,e.cursor);return t===e.cursor?e:ro(e,{start:t,end:e.cursor},"")},deleteWordForward(e){if(e.cursor>=e.buffer.length)return e;let t=LP(e.buffer,e.cursor);return t===e.cursor?e:ro(e,{start:e.cursor,end:t},"")},deleteToLineStart(e){let t=FP(e.buffer,e.cursor);return t===e.cursor?e:ro(e,{start:t,end:e.cursor},"")},deleteToLineEnd(e){let t=NP(e.buffer,e.cursor);return t===e.cursor?e:ro(e,{start:e.cursor,end:t},"")},moveLeft(e){return Un(e,Df(e.buffer,e.cursor))},moveRight(e){return Un(e,wo(e.buffer,e.cursor))},moveHome(e){return Un(e,0)},moveEnd(e){return Un(e,e.buffer.length)},moveLineStart(e){return Un(e,FP(e.buffer,e.cursor))},moveLineEnd(e){return Un(e,NP(e.buffer,e.cursor))},moveWordBackward(e){return Un(e,DP(e.buffer,e.cursor))},moveWordForward(e){return Un(e,LP(e.buffer,e.cursor))},moveUpLine(e,t,n){let r=t||80,{row:o,col:s}=no(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=no(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=Un(e,l);return u===e?{moved:!1}:{moved:!0,state:u}},moveDownLine(e,t,n){let r=t||80,{row:o,col:s}=no(e.buffer,e.cursor,n,r),i=no(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=no(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=Un(e,c);return d===e?{moved:!1}:{moved:!0,state:d}}};var BP=["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 kb(){return BP[Math.floor(Math.random()*BP.length)]}
|
|
1822
|
+
`,n);return r<0?e.length:r}function ro(e,t,n){let r=Vo(t.start,e.buffer.length),o=Vo(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 W={seed(e=""){return{buffer:e,cursor:e.length}},replaceRange:ro,insert(e,t){return t.length===0?e:ro(e,{start:e.cursor,end:e.cursor},t)},backspace(e){if(e.cursor===0)return e;let t=Df(e.buffer,e.cursor);return ro(e,{start:t,end:e.cursor},"")},deleteForward(e){if(e.cursor>=e.buffer.length)return e;let t=wo(e.buffer,e.cursor);return ro(e,{start:e.cursor,end:t},"")},deleteWordBackward(e){if(e.cursor===0)return e;let t=DP(e.buffer,e.cursor);return t===e.cursor?e:ro(e,{start:t,end:e.cursor},"")},deleteWordForward(e){if(e.cursor>=e.buffer.length)return e;let t=LP(e.buffer,e.cursor);return t===e.cursor?e:ro(e,{start:e.cursor,end:t},"")},deleteToLineStart(e){let t=FP(e.buffer,e.cursor);return t===e.cursor?e:ro(e,{start:t,end:e.cursor},"")},deleteToLineEnd(e){let t=NP(e.buffer,e.cursor);return t===e.cursor?e:ro(e,{start:e.cursor,end:t},"")},moveLeft(e){return Un(e,Df(e.buffer,e.cursor))},moveRight(e){return Un(e,wo(e.buffer,e.cursor))},moveHome(e){return Un(e,0)},moveEnd(e){return Un(e,e.buffer.length)},moveLineStart(e){return Un(e,FP(e.buffer,e.cursor))},moveLineEnd(e){return Un(e,NP(e.buffer,e.cursor))},moveWordBackward(e){return Un(e,DP(e.buffer,e.cursor))},moveWordForward(e){return Un(e,LP(e.buffer,e.cursor))},moveUpLine(e,t,n){let r=t||80,{row:o,col:s}=no(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=no(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=Un(e,l);return u===e?{moved:!1}:{moved:!0,state:u}},moveDownLine(e,t,n){let r=t||80,{row:o,col:s}=no(e.buffer,e.cursor,n,r),i=no(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=no(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=Un(e,c);return d===e?{moved:!1}:{moved:!0,state:d}}};var BP=["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 kb(){return BP[Math.floor(Math.random()*BP.length)]}vt();q();var n8=[{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 r8(){let e=[];for(let t of it())t.hint&&(t.name.includes(":")||e.push({id:`cmd:${t.name}`,text:`${t.name} \u2014 ${t.hint}`,source:"command"}));return e}function o8(e){let t=[];for(let n of Zn()){let r=`cmd:/${n}`;if(e.has(r))continue;let o;try{o=Ge(n)}catch{continue}on(o,v.AFK_INTERNAL==="1")&&o.whenToUse&&t.push({id:`skill:${n}`,text:`/${n} \u2014 ${o.whenToUse}`,source:"skill"})}return t}function HP(){if(v.AFK_SPINNER_TIPS==="0")return[];let e=r8(),t=new Set(e.map(r=>r.id)),n=o8(t);return[...n8,...e,...n]}var UP=new Set,jP=new Map;function WP(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=jP.get(i);if(a)return a;let l=null,c=e.filter(u=>!UP.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&&(UP.add(l.id),jP.set(i,l)),l}var Eb=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],s8=2e3;function KP(e){let t=Date.now()-e;if(t<s8)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 Tt(e,t){return`\x1B[${e};1H\x1B[2K${t??""}`}function GP(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 _p=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:kb(),nextVerbRotateAt:r+n,startedAt:r,tipPool:HP(),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(`${Eb[this.state.frameIndex]} ${this.state.verb}...`)+KP(this.state.startedAt):null}renderTipRow(t){return this.state?.currentTip?GP(this.state.currentTip.text,t):null}tick(t){if(!this.state)return;this.state.frameIndex=(this.state.frameIndex+1)%Eb.length;let n=Date.now();n>=this.state.nextVerbRotateAt&&(this.state.verb=kb(),this.state.nextVerbRotateAt=n+t),this.state.currentTip=WP(this.state.tipPool,{startedAt:this.state.startedAt,now:n}),this.onTick()}};var Ip=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 i8}from"node:crypto";var a8=5,l8=1e3,c8=/\[Pasted text #([0-9a-f]+) \+\d+ (?:lines|chars)\]/g;function u8(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 Pp(e,t){return e.pasteRegistry.size===0?t:t.replace(c8,(n,r)=>e.pasteRegistry.get(r)??n)}function qP(e){return{text:Pp(e,e.input.buffer),queued:e.queued}}function zP(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<a8&&a<l8)return;let l=i8(4).toString("hex");e.pasteRegistry.set(l,o);let c=u8(l,o);e.input=W.replaceRange(e.input,{start:t,end:n},c)}function Tb(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=W.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=W.replaceRange(e.input,{start:r,end:s},"");return e.pasteRegistry.delete(i),a}import{readdirSync as p8,statSync as m8}from"fs";import{join as f8}from"path";import{join as VP}from"path";import{homedir as d8}from"os";function Mp(e,t){let n=e?.shift===!0||t==="\x1B[13;2u",r=e?.meta===!0;return n||r}function Bi(e){return e.endsWith("\\")}var YP=50;function Op(e,t,n=d8()){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?VP(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?VP(t,o):t,a=o?`${o}/`:"";return{scanDir:i,leafPrefix:s,displayPrefix:a}}async function XP(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(Bi(o)){t+=o.slice(0,-1)+`
|
|
1823
1823
|
`,n=r;continue}return t+=o,t}}function Il(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=it().find(c=>c.name===`/${i}`);if(l?.flags&&l.flags.length>0)return{kind:"flag",command:i,query:a}}return null}function $p(e){let t=it(),n=t.filter(s=>s.name.slice(1).startsWith(e)).map(s=>({value:s.name,summary:s.summary,...s.hint?{hint:s.hint}:{}})),r=Li().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 Dp(e,t=process.cwd(),n){let{scanDir:r,leafPrefix:o,displayPrefix:s}=Op(e,t,n);try{return p8(r).filter(a=>a.startsWith(o)).filter(a=>!(a.startsWith(".")&&!o.startsWith("."))).sort().slice(0,YP).map(a=>{let l=s+a;try{m8(f8(r,a)).isDirectory()&&(l+="/")}catch{}return{value:"@"+l}})}catch{return[]}}function Pl(e,t){let n=it().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)}rt();q();var g8=3,h8=250,y8=1500,b8=500;function ZP(){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 QP(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 Ui(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 eM(e,t){let n=t.trim();return n.startsWith(e)&&n.length>e.length}function nM(e={}){let t=e.debounceMs??h8,n=e.timeoutMs??y8,r=null,o=null,s=null,i=new Map,a=e.resolveProviderFn??Md,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>=b8&&!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=it().map(A=>A.name),R=Li().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<g8)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:ZP(),user:QP(h,b),model:tM(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=Ui(R.raw).trim();x=eM(h,k)?k:null}}else{let R=tM(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:ZP(),user:QP(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=Ui(A.raw).trim();x=eM(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 tM(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 Yo=6;function Lp(e){let t=e.autocompleteState;if(!t)return;t.trigger=Il(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=$p(t.trigger.query).slice(0,12):t.trigger.kind==="file"?t.candidates=Dp(t.trigger.query):t.candidates=Pl(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+Yo&&(t.viewportStart=t.selectedIndex-Yo+1)}function rM(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 oM(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=W.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,Lp(e),e.repaint(),!0)}function sM(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+Ui(t.slice(e.input.buffer.length)),o=W.seed(r);return e.input=o,e.activeGhost=null,Lp(e),e.repaint(),!0}import S8 from"chalk";import v8 from"string-width";function iM(e,t){if(t<=0)return"";let n=0;for(let r=0;r<e.length;r++)if(n+=v8(e[r]),n>t)return e.slice(0,r)+f.dim("\u2026");return e}function Fp(e,t,n,r){let o=t?">":" ",s=e.value,i=e.summary?` ${e.summary}`:"",a=`${s}${i}`,l=iM(a,n-4),c=` ${o} ${l}`;return t?S8.inverse(f.user(c)):f.meta(c)}function Np(e,t){if(!e)return null;let n=e.trim();if(n.length===0)return null;let r=iM(n,Math.max(0,t-7));return r.length===0?null:f.dim(` \u21B3 ${r}`)}function aM(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=wo(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=Ui(g.slice(e.input.buffer.length)),b=e.stdout.columns??80,y=V(Be(e.promptTextFn())),S=V(Be(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 lM(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,Yo),s=[];for(let i=0;i<o;i++){let a=t.viewportStart+i,l=t.candidates[a];if(!l)continue;let c=Fp(l,a===t.selectedIndex,r,t.trigger?.kind),u=V(Be(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 cM(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 Np(r.hint,o)??""}function uM(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 xb(e,t){return e.length>t?e.slice(e.length-t):e}function dM(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(`
|
|
1826
1826
|
`)?t.slice(0,-1):t,s=Math.max(1,e.stdout.columns??80),i=o.split(`
|
|
1827
1827
|
`),a=!1;for(;i.length>1&&i[i.length-1]==="";)i.pop(),a=!0;let l=i.flatMap(P=>gv(P,s).split(`
|
|
1828
|
-
`)),c=Math.max(1,l.length),u=e.scrollRegion?.getExtraRows()??0,d=e.logUpdate.topRow??0,p=d>1?d:Math.max(1,r-1-u),m=Math.max(e.anchorRow??1,1),g=d>1&&c<=p-m,h=g&&e.committedBand.length>0&&e.committedBandBottomRow>0?Math.max(p,e.committedBandBottomRow+1):p,b=Math.max(0,h-m),y=a&&g&&c<b,S=y?[...l,""]:l,w=c+(y?1:0),T=a?[...l,""]:l,x=T.length,{useBandHold:C,overflowRun:R,maxBandModel:k}=uM({prevTopRow:d,frameTop:p,anchorFloor:m,anchorRow:e.anchorRow??1,lineCount:x,textLines:T,rows:r,extraRows:u,committedBand:e.committedBand,committedBandBottomRow:e.committedBandBottomRow,committedBandPaintedRows:e.committedBandPaintedRows});e.commitInFlight=!0,e.committing=!0;let $=0;try{e.logUpdate.clear(u),n(()=>{let P=g,F=P&&e.committedBand.length>0&&e.committedBandBottomRow>0?Math.max(p,e.committedBandBottomRow+1):p,D=Math.max(0,F-m),N=P?Math.max(0,e.committedBand.length+w-D):w;if($=g?N:0,e.debugLog("commitAbove:phase1",{lineCount:w,fitsAboveFrame:g,bandOverflow:N}),C){let B=Math.max(0,R.length-k);if(B>0){let H=Math.max(1,r-m+1);for(let L=0;L<B;L+=H){let I=R.slice(L,Math.min(L+H,B)),U=I.map((M,j)=>
|
|
1828
|
+
`)),c=Math.max(1,l.length),u=e.scrollRegion?.getExtraRows()??0,d=e.logUpdate.topRow??0,p=d>1?d:Math.max(1,r-1-u),m=Math.max(e.anchorRow??1,1),g=d>1&&c<=p-m,h=g&&e.committedBand.length>0&&e.committedBandBottomRow>0?Math.max(p,e.committedBandBottomRow+1):p,b=Math.max(0,h-m),y=a&&g&&c<b,S=y?[...l,""]:l,w=c+(y?1:0),T=a?[...l,""]:l,x=T.length,{useBandHold:C,overflowRun:R,maxBandModel:k}=uM({prevTopRow:d,frameTop:p,anchorFloor:m,anchorRow:e.anchorRow??1,lineCount:x,textLines:T,rows:r,extraRows:u,committedBand:e.committedBand,committedBandBottomRow:e.committedBandBottomRow,committedBandPaintedRows:e.committedBandPaintedRows});e.commitInFlight=!0,e.committing=!0;let $=0;try{e.logUpdate.clear(u),n(()=>{let P=g,F=P&&e.committedBand.length>0&&e.committedBandBottomRow>0?Math.max(p,e.committedBandBottomRow+1):p,D=Math.max(0,F-m),N=P?Math.max(0,e.committedBand.length+w-D):w;if($=g?N:0,e.debugLog("commitAbove:phase1",{lineCount:w,fitsAboveFrame:g,bandOverflow:N}),C){let B=Math.max(0,R.length-k);if(B>0){let H=Math.max(1,r-m+1);for(let L=0;L<B;L+=H){let I=R.slice(L,Math.min(L+H,B)),U=I.map((M,j)=>Tt(m+j,M)).join("");e.stdout.write(`${U}\x1B[${r};1H${`
|
|
1829
1829
|
`.repeat(I.length)}`)}}}else if(g)N>0&&e.stdout.write(`\x1B[${r};1H${`
|
|
1830
1830
|
`.repeat(N)}`);else{let B=S.map(H=>`\x1B[2K${H??""}`).join(`
|
|
1831
1831
|
`);e.stdout.write(`\x1B[${m};1H${B}\x1B[${r};1H${`
|
|
1832
|
-
`.repeat(w)}`)}})}finally{e.committing=!1,e.debugLog("commitAbove:finally")}$>0&&e.anchorRow!==void 0&&e.anchorRow>1&&(e.anchorRow=Math.max(1,e.anchorRow-$)),e.hasCommitted=!0,e.debugLog("commitAbove:phase2:repaint"),e.repaint(),e.debugLog("commitAbove:phase2:done",{newTopRow:e.logUpdate.topRow??null});let A=e.logUpdate.topRow??0;if(A>1){let P=Math.max(e.anchorRow??1,1),F=Math.max(0,A-P);if(C){let D=xb(R,k),N=Math.min(D.length,F),B=A-N,H="";for(let L=0;L<N;L++){let I=B+L;if(I>=A)break;H+=
|
|
1832
|
+
`.repeat(w)}`)}})}finally{e.committing=!1,e.debugLog("commitAbove:finally")}$>0&&e.anchorRow!==void 0&&e.anchorRow>1&&(e.anchorRow=Math.max(1,e.anchorRow-$)),e.hasCommitted=!0,e.debugLog("commitAbove:phase2:repaint"),e.repaint(),e.debugLog("commitAbove:phase2:done",{newTopRow:e.logUpdate.topRow??null});let A=e.logUpdate.topRow??0;if(A>1){let P=Math.max(e.anchorRow??1,1),F=Math.max(0,A-P);if(C){let D=xb(R,k),N=Math.min(D.length,F),B=A-N,H="";for(let L=0;L<N;L++){let I=B+L;if(I>=A)break;H+=Tt(I,D[D.length-N+L])}H.length>0&&n(()=>{e.stdout.write(H)}),e.committedBand=D,e.committedBandBottomRow=A-1,e.committedBandTopRow=B,e.committedBandPaintedRows=N}else{let D=Math.min(S.length,F);if(D>0){let N=S.slice(S.length-D),B=D===S.length,L=g&&B&&e.committedBand.length>0&&(e.committedBandBottomRow===A-1||e.committedBandBottomRow===h-1)?[...e.committedBand,...N]:N,I=L.length>F?L.slice(L.length-F):L,U=A-I.length,M=e.committedBandTopRow,j="";if(g){if(M>0&&M<U){let Y=Math.max(P,M);for(let oe=Y;oe<U;oe++)j+=Tt(oe)}for(let Y=0;Y<I.length;Y++){let oe=U+Y;if(oe>=A)break;j+=Tt(oe,I[Y])}}else{let Y=Math.max(0,A-m),oe=Math.max(0,S.length-Y);for(let X=oe;X<S.length;X++){let me=m+(X-oe);if(me>=A)break;j+=Tt(me,S[X])}}j.length>0&&n(()=>{e.stdout.write(j)}),e.committedBand=I,e.committedBandBottomRow=A-1,e.committedBandTopRow=U,e.committedBandPaintedRows=I.length}else Ml(e)}}else if(C){let P=xb(R,k),F=Math.max(1,r-1-u);e.committedBand=P,e.committedBandBottomRow=Math.max(0,F-1),e.committedBandTopRow=Math.max(m,F-P.length),e.committedBandPaintedRows=0}else Ml(e);e.commitInFlight=!1,e.debugLog("commitAbove:phase3:done")}function Ml(e){e.committedBand=[],e.committedBandTopRow=0,e.committedBandBottomRow=0,e.committedBandPaintedRows=0}function pM(e){e.hasCommitted=!1,Ml(e),e.commitInFlight=!1}function mM(e){let t=e.pendingResizeErase;if(!t)return;e.pendingResizeErase=null;let n=Math.max(1,e.stdout.rows??24),r=Math.max(1,t.top),o=Math.min(t.bottom,n);if(r>o)return;let s="";for(let i=r;i<=o;i++)s+=Tt(i);try{e.stdout.write(s)}catch{}}function fM(e,t,n,r){if(e.commitInFlight||!e.logUpdate)return;let o=Math.max(e.anchorRow??1,1),s=t-1;if(e.committedBand.length===0||s<o)return;let i=s-o+1,a=Math.min(e.committedBand.length,i);if(a<=0)return;let l=s-a+1,c=l!==e.committedBandTopRow||s!==e.committedBandBottomRow,u=n>0&&n<=e.committedBandBottomRow;if(!c&&!u)return;let d=e.committedBand.slice(e.committedBand.length-a),p="\x1B[?25l";for(let m=Math.max(o,e.committedBandTopRow);m<l;m++)p+=Tt(m);for(let m=0;m<d.length;m++)p+=Tt(l+m,d[m]);p+=`\x1B[${Math.max(1,r)};1H`;try{e.stdout.write(p)}catch{}e.committedBandTopRow=l,e.committedBandBottomRow=s,e.committedBandPaintedRows=a}var T8={"image/png":"PNG","image/jpeg":"JPEG","image/gif":"GIF","image/webp":"WEBP"};function x8(e){if(e<1024)return`${e} B`;let t=e/1024;return t<1024?`${t.toFixed(1)} KiB`:`${(t/1024).toFixed(1)} MiB`}function Ol(e){if(e.length===0)return"";let t=e.reduce((a,l)=>a+l.sizeBytes,0),n=x8(t),r=e.length===1?"image":"images",o=new Set,s=[];for(let a of e){let l=T8[a.mediaType];o.has(l)||(o.add(l),s.push(l))}let i=s.join(", ");return`[${e.length} ${r} attached \xB7 ${n} \xB7 ${i} \xB7 Ctrl+X to discard]`}function gM(e,t){if(t.length===0)return e;if(e){let n=t.length===1?"image":"images";return`${e} [+ ${t.length} ${n}]`}return t.length===1?"[image attached]":`[${t.length} images attached]`}function ji(e){return e.length===0?"":e.length===1?"[image attached]":`[${e.length} images attached]`}function Rb(e,t){let n=e.logUpdate?.topRow??0;if(!(e.anchorRow!==void 0&&e.anchorRow>1)){let a=e.hasCommitted&&n>1&&t<n,l=e.committedBand.length;if(!a||l===0)return;let c=Math.max(0,t-1),u=l-c;if(u<=0)return;let d="";for(let p=Math.max(1,e.committedBandTopRow);p<=e.committedBandBottomRow;p++)d+=Tt(p);for(let p=0;p<l;p++)d+=Tt(1+p,e.committedBand[p]);try{e.stdout.write(d)}catch{}hM(e,u),e.committedBand=e.committedBand.slice(u),e.committedBandTopRow=1,e.committedBandBottomRow=c,e.committedBandPaintedRows=e.committedBand.length;return}let o=e.hasCommitted&&n>1?Math.max(0,n-t):0,s=t<e.anchorRow?e.anchorRow-t:0,i=Math.max(o,s);if(i>0&&(hM(e,i),e.anchorRow!==void 0&&e.anchorRow>1&&(e.anchorRow=Math.max(1,e.anchorRow-i)),e.committedBand.length>0)){e.committedBandTopRow-=i,e.committedBandBottomRow-=i;let a=Math.max(e.anchorRow??1,1);if(e.committedBandTopRow<a){let l=a-e.committedBandTopRow;e.committedBand=e.committedBand.slice(l),e.committedBandTopRow=a}e.committedBand.length===0||e.committedBandBottomRow<a?e.clearCommittedBand():e.committedBandPaintedRows=e.committedBand.length}}function hM(e,t){if(t<=0)return;e.debugLog("evict:enter",{rows:t,anchorRow:e.anchorRow??null});let r=`\x1B[${Math.max(1,e.stdout.rows??24)};1H${`
|
|
1833
1833
|
`.repeat(t)}`,o=()=>{try{e.stdout.write(r)}catch(s){e.debugLog("evict:error",{msg:s?.message??String(s)})}};e.scrollRegion!==void 0?e.scrollRegion.withFullScrollRegion(o):o()}function yM(e){if(!e.armed||!e.logUpdate||e.committing||e.suspended)return;if(e.flushResizeGhostErase(),e.lastKnownRows=e.stdout.rows??24,e.inputMode==="picker"&&e.pickerController){R8(e);return}let t=e.renderInputLine(),n=e.overlay?e.overlay.split(`
|
|
1834
1834
|
`):[],r=e.spinnerController.renderSpinnerRow(),o=e.spinnerController.renderTipRow(e.stdout.columns??80),s=null;e.attachments.length>0?s=Ol(e.attachments):e.clipboardFailureMsg!==null&&(s=f.dim(e.clipboardFailureMsg),e.clipboardFailureMsg=null);let i=e.renderDropdownRows(),a=e.renderHintRow(),l=!!r||!!o||!!s,c=l||n.length>0,u=e.scrollRegion?.getExtraRows()??0,d=Math.max(1,(e.stdout.rows??24)-1-u),p=c?1:0,m=(r?1:0)+(o?1:0)+(s?1:0)+p+i.length+(a!==null?1:0)+1,g=Math.max(0,d-m),h=n.length>g?n.slice(-g):n,b=l||h.length>0,y=[];y.push(...h),r&&y.push(r),o&&y.push(o),s&&y.push(s),b&&y.push(""),y.push(...i),a!==null&&y.push(a),y.push(t);let S=Math.max(1,(e.stdout.rows??24)-1-u),w=y.join(`
|
|
1835
1835
|
`),T=S,x=e.logUpdate.measure?e.logUpdate.measure(w,T).topRow:Math.max(1,T-y.length+1);Rb(e,x);let C=e.logUpdate.topRow??0;e.logUpdate.render(w,T,e.anchorRow),e.repositionCommittedBand(x,C,T)}function R8(e){if(!e.logUpdate||!e.pickerController)return;let t=[...e.pickerController.renderRows()],n=e.overlay?e.overlay.split(`
|
|
@@ -1855,14 +1855,14 @@ ${u}`}function bb(e,t){let n=_P[t.status];e.out.line(` ${n} ${f.bold(t.jobId)}
|
|
|
1855
1855
|
`)),!0;if(e.input.buffer.length===0&&e.attachments.length===0)return!0;if(e.inputMode==="idle"&&e.onSubmit){let a=e.input.buffer,l=Pp(e,a),c=[...e.attachments],u=e.onSubmit;return e.queued=e.pendingSubmissions.length>0,e.input=W.seed(""),e.attachments=[],e.pasteRegistry.clear(),e.autocompleteState?.reset(),e.repaint(),u(l===a?{text:l,attachments:c}:{text:l,displayText:a,attachments:c}),!0}let o=e.input.buffer,s=Pp(e,o),i=[...e.attachments];return e.pendingSubmissions.push(s===o?{text:s,attachments:i}:{text:s,displayText:o,attachments:i}),e.queued=!0,e.input=W.seed(""),e.attachments=[],e.pasteRegistry.clear(),e.history?.resetRecall(),e.autocompleteState?.reset(),e.repaint(),e.paused&&e.onPauseInterrupt&&e.onPauseInterrupt(),!0}function j8(e,t){if(t?.name!=="backspace")return!1;if(t?.meta){let o=W.deleteWordBackward(e.input);return o!==e.input&&(e.history?.resetRecall(),e.applyEdit(o)),!0}let n=Tb(e,"backward");if(n)return e.history?.resetRecall(),e.applyEdit(n),!0;let r=W.backspace(e.input);return r!==e.input?(e.history?.resetRecall(),e.applyEdit(r)):e.attachments.length>0&&(e.attachments.pop(),e.repaint()),!0}function H8(e,t){if(t?.ctrl&&t?.name==="a")return e.applyEdit(W.moveLineStart(e.input)),!0;if(t?.ctrl&&t?.name==="e")return e.applyEdit(W.moveLineEnd(e.input)),!0;if((t?.meta||t?.ctrl)&&t?.name==="left")return e.applyEdit(W.moveWordBackward(e.input)),!0;if((t?.meta||t?.ctrl)&&t?.name==="right")return e.applyEdit(W.moveWordForward(e.input)),!0;if(t?.meta&&t?.name==="b")return e.applyEdit(W.moveWordBackward(e.input)),!0;if(t?.meta&&t?.name==="f")return e.applyEdit(W.moveWordForward(e.input)),!0;if(t?.ctrl&&t?.name==="w"){let n=W.deleteWordBackward(e.input);return n!==e.input&&(e.history?.resetRecall(),e.applyEdit(n)),!0}if(t?.ctrl&&t?.name==="u"){let n=W.deleteToLineStart(e.input);return n!==e.input&&(e.history?.resetRecall(),e.applyEdit(n)),!0}if(t?.ctrl&&t?.name==="k"){let n=W.deleteToLineEnd(e.input);return n!==e.input&&(e.history?.resetRecall(),e.applyEdit(n)),!0}if(t?.ctrl&&t?.name==="l")return e.clearScreen(),!0;if(t?.ctrl&&t?.name==="d")return e.input.buffer.length===0?e.onCancel&&e.onCancel():(e.history?.resetRecall(),e.applyEdit(W.deleteForward(e.input))),!0;if(t?.name==="left")return e.applyEdit(W.moveLeft(e.input)),!0;if(t?.name==="right")return e.input.cursor===e.input.buffer.length&&e.activeGhost!==null&&!e.autocompleteState?.dropdownOpen?e.applyGhostAccept():e.applyEdit(W.moveRight(e.input)),!0;if(t?.name==="home")return e.applyEdit(W.moveLineStart(e.input)),!0;if(t?.name==="end")return e.applyEdit(W.moveLineEnd(e.input)),!0;if(t?.name==="delete"){if(t?.meta){let r=W.deleteWordForward(e.input);return r!==e.input&&(e.history?.resetRecall(),e.applyEdit(r)),!0}let n=Tb(e,"forward");return n?(e.history?.resetRecall(),e.applyEdit(n),!0):(e.history?.resetRecall(),e.applyEdit(W.deleteForward(e.input)),!0)}return!1}function W8(e,t){return t?.ctrl&&t?.name==="b"?(e.inputMode==="idle"||e.backgrounded||(e.backgrounded=!0,e.onBackground&&e.onBackground()),!0):!1}function K8(e,t){return t?.name==="tab"&&t?.shift?(e.onShiftTab&&e.onShiftTab(),!0):t?.name==="tab"?(e.applyDropdownSelection()||e.applyGhostAccept(),!0):!1}function G8(e,t,n){let r=["tab","pageup","pagedown"];if(n?.name&&r.includes(n.name)||n?.ctrl||n?.meta)return;let o=typeof t=="string"&&Hi(t)?t:typeof n?.sequence=="string"&&Hi(n.sequence)?n.sequence:null;o!==null&&(e.history?.resetRecall(),e.applyEdit(W.insert(e.input,o)))}q();import q8 from"wrap-ansi";var IM="\x1B[?2026h",PM="\x1B[?2026l",$l=(e,t)=>`\x1B[${e};${t}H`,_b="\x1B[2K",z8="\x1B[?25l",MM="\x1B[?25h",Bp=class e{stream;previousTopRow=0;previousLineCount=0;previousRawLineCount=0;constructor(t){this.stream=t}get topRow(){return this.previousTopRow}static wrapToPhysicalLines(t,n){let r=t.endsWith(`
|
|
1856
1856
|
`)?t:`${t}
|
|
1857
1857
|
`,s=q8(r,n,{trim:!1,hard:!0,wordWrap:!1}).split(`
|
|
1858
|
-
`);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+=IM),this.previousLineCount>0)for(let y=0;y<this.previousLineCount;y++){let S=this.previousTopRow+y;b+=$l(S,1)+_b}for(let y=0;y<g;y++){let S=h+y;b+=$l(S,1)+_b+(m[y]??"")}if(b+=$l(h+g-1,1),a&&(b+=PM),this.stream.isTTY)try{this.stream.write(z8)}catch{}try{this.stream.write(b)}catch{try{this.stream.isTTY&&this.stream.write(MM)}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+=IM);for(let o=0;o<this.previousLineCount;o++){let s=this.previousTopRow+o;n+=$l(s,1)+_b}n+=$l(Math.max(1,(this.stream.rows??24)-1-t),1),r&&(n+=PM);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(MM)}catch{}}};var Dl=null;function Ll(e){if(Dl!==null)throw new Error(`stdin claim conflict: '${Dl.name}' already holds the claim, '${e}' cannot acquire it concurrently.`);let t=!1,n={release(){t||(t=!0,Dl?.handle===n&&(Dl=null))}};return Dl={name:e,handle:n},n}async function OM(e,t){let n=Ll(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 DM(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 LM(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 Bp(e.stdout)),e.stdinClaim=Ll("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(),Ko(e.stdin),e.handleKeypress=(t,n)=>{let r=e.pasting?!1:e.caretBlinkController.resetVisible(),o=e.repaintCount;AM(e,t,n),r&&e.repaintCount===o&&e.repaint()},e.stdin.on("keypress",e.handleKeypress),e.armed=!0,e.canceled=!1,e.resizeUnsub=He.subscribe(()=>{e.armed&&e.repaint()}),e.resizeImmediateUnsub=He.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 FM(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),J8(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 J8(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)=>
|
|
1858
|
+
`);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+=IM),this.previousLineCount>0)for(let y=0;y<this.previousLineCount;y++){let S=this.previousTopRow+y;b+=$l(S,1)+_b}for(let y=0;y<g;y++){let S=h+y;b+=$l(S,1)+_b+(m[y]??"")}if(b+=$l(h+g-1,1),a&&(b+=PM),this.stream.isTTY)try{this.stream.write(z8)}catch{}try{this.stream.write(b)}catch{try{this.stream.isTTY&&this.stream.write(MM)}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+=IM);for(let o=0;o<this.previousLineCount;o++){let s=this.previousTopRow+o;n+=$l(s,1)+_b}n+=$l(Math.max(1,(this.stream.rows??24)-1-t),1),r&&(n+=PM);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(MM)}catch{}}};var Dl=null;function Ll(e){if(Dl!==null)throw new Error(`stdin claim conflict: '${Dl.name}' already holds the claim, '${e}' cannot acquire it concurrently.`);let t=!1,n={release(){t||(t=!0,Dl?.handle===n&&(Dl=null))}};return Dl={name:e,handle:n},n}async function OM(e,t){let n=Ll(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 DM(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 LM(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 Bp(e.stdout)),e.stdinClaim=Ll("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(),Ko(e.stdin),e.handleKeypress=(t,n)=>{let r=e.pasting?!1:e.caretBlinkController.resetVisible(),o=e.repaintCount;AM(e,t,n),r&&e.repaintCount===o&&e.repaint()},e.stdin.on("keypress",e.handleKeypress),e.armed=!0,e.canceled=!1,e.resizeUnsub=He.subscribe(()=>{e.armed&&e.repaint()}),e.resizeImmediateUnsub=He.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 FM(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),J8(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 J8(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)=>Tt(o+d,u)).join("");e.stdout.write(`${c}\x1B[${r};1H${`
|
|
1859
1859
|
`.repeat(l.length)}`)}};try{e.scrollRegion?e.scrollRegion.withFullScrollRegion(s):s()}catch{}}function NM(e){e.overlay="",e.input=W.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 Wi=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=W.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:""}
|
|
1860
1860
|
`)}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 _p({captureMode:t.captureMode??!1,onTick:()=>this.repaint()}),this.caretBlinkController=new Ip({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(){DM(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){bM(this,t)}exitPickerMode(){wM(this)}repaintPicker(){SM(this)}setInputMode(t){vM(this,t)}getInputMode(){return kM(this)}async arm(){return LM(this)}disarm(){FM(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){dM(this,t)}clearCommittedBand(){Ml(this)}flushResizeGhostErase(){mM(this)}resetCommittedBand(){pM(this)}repositionCommittedBand(t,n,r){fM(this,t,n,r)}getBuffer(){return qP(this)}getPendingCount(){return this.pendingSubmissions.length}getAttachments(){return[...this.attachments]}get caretVisible(){return this.caretBlinkController.visible}renderInputLine(){return aM(this)}updateAutocomplete(){Lp(this)}updateGhost(){rM(this)}renderDropdownRows(){return lM(this)}renderHintRow(){return cM(this)}repaint(){this.repaintCount++,yM(this)}clearScreen(){this.logUpdate?.resetGeometry?.(),this.stdout.write("\x1B[H\x1B[2J"),this.repaint()}resetState(){NM(this)}applyEdit(t){return CM(this,t)}applyDropdownSelection(){return oM(this)}applyGhostAccept(){return sM(this)}};import Z8 from"chalk";var Q8=/(?<=\s|^)(\/[A-Za-z][\w:-]*)(?=\s|$)/g,e5=/(?<=\s|^)(@[~\w./-]*)(?=\s|$)/g,t5=/\[Pasted text #[0-9a-f]+ \+\d+ (?:lines|chars)\]/g,BM={mint:f.mint};function n5(e){let t=BM[e];if(t)return t;let n=e.lastIndexOf(":");if(n>=0){let r=e.slice(n+1),o=BM[r];if(o)return o}return null}function oo(e,t){return Z8.level===0?e:e.replace(Q8,o=>{let s=o.slice(1);return t.has(s)?(n5(s)??f.brand)(o):f.meta(o)}).replace(e5,o=>f.fileRef(o)).replace(t5,o=>f.meta(o))}q();import{pathToFileURL as r5}from"node:url";var o5="\x1B]8;;\x1B\\",s5=new Set(["iterm2","wezterm","kitty","vscode","ghostty","windows-terminal","konsole","gnome-terminal","alacritty"]),i5=5e3;function a5(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=Al(e);if(!s5.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<i5)return!1}return!0}var Ib;function Up(){return Ib===void 0&&(Ib=a5()),Ib}function l5(e,t){return`\x1B]8;;${t}\x1B\\${e}${o5}`}function jp(e,t){try{return l5(e,r5(t).href)}catch{return e}}var UM=/[\x00-\x1F\x7F-\x9F]/g;function dt(e){return Be(e).replace(UM," ").replace(/ {2,}/g," ").trim()}function Pb(e){return Be(e).replace(UM," ")}function Fl(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+=jM(e.slice(r,i)),n+=s,r=i+s.length}return n+=jM(e.slice(r)),n}function jM(e){let t=Up();return e.replace(/\/(?:[^/\s,)]+\/){2,}([^/\s,)]+)/g,(n,r)=>t?jp(r,n):r)}function c5(e){let t=/^(\s*[("]?\s*)cd\s+\S+\s+&&\s+(?!cd\s)(.+)$/.exec(e);return t?(t[1]??"")+(t[2]??""):e}var HM=60;function Mb(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=dt(i);if(a.length===0)continue;return`(${a.length>HM?ne(a,HM,"\u2026"):a})`}}return e}function WM(e,t){if(e==="bash"||e==="Bash")return c5(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"?Mb(t,["id_prefix","prompt"]):e==="Task"?Mb(t,["description","prompt"]):e==="skill"||e==="Skill"?Mb(t,["name","arguments"]):e==="ask_question"?u5(t):t}function u5(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 d5(e){return e.replace(/[\r\n]+/g," ")}var p5={"(":")","{":"}","[":"]"};function KM(e,t,n="\u2026"){let r=e.charAt(0),o=p5[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 Sr(e,t){let n=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/s.exec(e);if(n){let r=n[1],o=Fl(WM(r,n[2]??"")),s=Pn(r),{color:i,glyph:a}=xi(r),l=Dh(s),c=l?` [${l}]`:"";if(t!==void 0){let d=(a+" ").length+r.length+c.length,p=Math.max(1,t-d);o=KM(o,p)}o=d5(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 GM=8,Hp=30;function m5(){let e=v.AFK_DIFF_LINES;if(e===void 0)return Hp;let t=e.trim();if(!/^\d+$/.test(t))return Hp;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:Hp}function f5(){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 g5(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 h5=/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;function y5(e){let t=Be(e.text).replace(h5,"");return e.kind==="+"?f.diffAdd("+ "+t):e.kind==="-"?f.diffRemove("- "+t):f.dim(" "+t)}var $b=new WeakMap;function vr(e,t,n){if(f5())return[];if(e.hunks.length===0)return[];let r=t==="overlay"?GM:m5(),o=t+"|"+n+"|"+r,s=$b.get(e);if(s!==void 0){let m=s.get(o);if(m!==void 0)return m}let i=[];i.push(n+g5(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:y5(h)})}if(r===0){for(let m of a)i.push(n+m.text);return Ob(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 Ob(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}`)),Ob(e,o,i),i}function Ob(e,t,n){let r=$b.get(e);r===void 0&&(r=new Map,$b.set(e,r)),r.set(t,n)}var b5=f.success("\u2713"),w5=f.error("\u2717");function so(e){return e?w5:b5}var Nl=3,qM=2,zM=3;function JM(e){switch(Pn(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 S5(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 kr(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=Up()?jp(a,e.persistedPath):a;return o(`saved \u2192 ${l}`)}if(e.lineCount!==void 0&&e.lineCount>1)return o(`${e.lineCount} ${S5(r,e.lineCount)}`);let i=e.content.length>n?e.content.slice(0,n-3)+"\u2026":e.content;return o(dt(i))}q();function Bl(e,t){if(e.length<=t)return e;let n=e.length-t,r=e.slice(0,n),o=e.slice(n),s=YM(r);return[{kind:"overflow",count:r.length,text:s},...o]}function v5(e,t){return t<=1||e.endsWith("s")||/(sh|ch|x|z)$/i.test(e)?e:e+"s"}var k5=5,VM=60;function YM(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=>Ze.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=dt(u);if(!d){i=!0;break}let p=d.length>VM?d.slice(0,VM-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,k5),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} ${v5(s,i)}`);return`\u2026 +${n} (${o.join(", ")})`}function Wp(e,t=un()){return e.map((n,r)=>({sibling:n,connector:r===e.length-1?t.lastConnector:t.midConnector}))}function Db(e,t){return t?[...e,{kind:"resultSummary",summary:t}]:e}function Lb(e){if(e.length===0)return[];let t=new Map;for(let o of e){let s=XM(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=XM(o),i=t.get(s);i.length>=E5(o.toolName)?r.has(s)||(n.push({kind:"group",toolName:o.toolName,label:Ze.has(o.toolName)?o.toolInput:"",entries:i}),r.add(s)):n.push(o)}return n}function Fb(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 Sr(e.toolName+e.label)+f.dim(` \xD7${t} \u2014 ${s}`)}function XM(e){return Ze.has(e.toolName)?e.toolName+"::"+e.toolInput:e.toolName}function E5(e){return Ze.has(e)?qM:zM}function ZM(e,t,n,r){return e>0||t?Ki([...n,!0],r):Ki(n,r)}function QM(e,t){return!Ze.has(e.toolName)||e.headerEmitted!==!0?!1:(t.get(e.toolUseId)??[]).every(r=>r.kind==="tool"&&QM(r,t))}function Kp(e,t,n,r=Q(),o=[],s=un(),i){let a=Ki(o,s),l=Ul(a,s),c=e.filter(h=>h.kind==="text"),u=e.filter(h=>h.kind==="tool").filter(h=>!QM(h,t)),d=Lb(u),p=Bl(d,Nl),m=Wp(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(Oe(l+y+f.dim(h.text),r));else if(h.kind==="group")n.push(Oe(l+y+Fb(h),r));else if(h.kind==="resultSummary")n.push(Oe(l+y+f.dim(h.summary),r));else{let w=h,T=t.get(w.toolUseId);if(Ze.has(w.toolName)&&T&&T.length>0){w.headerEmitted?n.push(Oe(l+y,r)):n.push(Oe(l+y+w.prefix,r));let x=i??S;if(Kp(T,t,n,r,[...o,x],s,S),w.thinkingTail){let C=Ul(Ki([...o,x],s),s);n.push(Oe(C+f.thinking("\u2307 "+dt(w.thinkingTail)),r))}}else if(!(Ze.has(w.toolName)&&w.headerEmitted))if(w.result){if(n.push(Oe(l+y+w.prefix+f.dim(" \u2014 ")+so(w.result.isError)+" "+kr(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 vr(w.diff,"overlay",x))n.push(Oe(C,r))}}else{n.push(Oe(l+y+w.prefix,r));let x=l+(S?s.spineClosed:f.dim(s.spine))+" ";w.thinkingTail?n.push(Oe(x+f.thinking("\u2307 "+dt(w.thinkingTail)),r)):n.push(Oe(x+f.dim(JM(w.toolName)),r))}}}let g=ZM(u.length,!1,o,s);for(let h of c)for(let b of Nb(h.text,g,s))n.push(Oe(b,r))}function jl(e,t,n,r,o=Q(),s=[],i=un(),a){let l=Ki(s,i),c=Ul(l,i),u=[],d=e.filter(S=>S.kind==="text"),p=e.filter(S=>S.kind==="tool"),m=Lb(p),g=Bl(m,Nl),h=Db(g,r),b=Wp(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(Oe(c+T+f.dim(S.text),o));else if(S.kind==="resultSummary")u.push(Oe(c+T+f.dim(S.summary),o));else if(S.kind==="group")u.push(Oe(c+T+Fb(S),o));else{let C=S,R=t.get(C.toolUseId);if(Ze.has(C.toolName)&&R&&R.length>0){if(C.headerEmitted){let $=C.toolInput?`${C.toolName} ${dt(C.toolInput)}`:C.toolName;u.push(Oe(c+T+f.dim("\u21B3 "+$),o))}else u.push(Oe(c+T+C.prefix,o));let k=a??x;u.push(...jl(R,t,n,void 0,o,[...s,k],i,x))}else if(C.result){if(u.push(Oe(c+T+C.prefix+f.dim(" \u2014 ")+so(C.result.isError)+" "+kr(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 vr(C.diff,"flush",k))u.push(Oe($,o))}}else u.push(Oe(c+T+C.prefix,o))}}let y=ZM(p.length,r!=null,s,i);for(let S of d)for(let w of Nb(S.text,y,i))u.push(Oe(w,o));return u}function Hl(e,t,n,r,o=[]){let s=un(),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>Nl&&(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=jl(t,n,r,e.agentResultSummary,Q(),d,s);return[m,...g].join(`
|
|
1861
|
-
`)}function Bb(e,t=[]){let n=un(),r=f.dim(n.spine.repeat(t.length)),o=f.dim(n.turnRoot);return r+o+e.prefix}function Wl(e,t,n,r,o=[]){let s=un(),i=o;return jl(t,n,r,e.agentResultSummary,Q(),i,s)}function Gi(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 ")+so(a.result.isError)+" "+kr(a.result,n,60,a.toolName)),a.diff&&!a.result.isError)for(let l of vr(a.diff,"flush"," "))r.push(Oe(l,o))}else r.push(" "+a.prefix)}else{r.push(e0(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=dt(c.toolInput),d=Fl(u).trim()||u.trim();r.push(" "+f.dim(`\u2500\u2500 ${d} \u2500\u2500`))}for(let u of vr(c.diff,"flush"," "))r.push(Oe(u,o))}}}return r}function e0(e,t,n){let{color:r,glyph:o}=xi(e),s=t.map(u=>Fl(dt(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=>kr(d.result,n,60,d.toolName));return" "+i+f.dim(" \u2014 ")+u.join(f.dim(", "))}return" "+i}function Oe(e,t){return ne(e,t)}var Ub=Object.freeze({spine:"\u2502 ",spineClosed:" ",lead:" ",turnRoot:"\u25C9 ",midConnector:"\u251C\u2500 ",lastConnector:"\u2570\u2500 ",textPrefix:"\u2502 "}),T5=Object.freeze({spine:"| ",spineClosed:" ",lead:" ",turnRoot:"o ",midConnector:"+- ",lastConnector:"\\- ",textPrefix:"| "}),
|
|
1861
|
+
`)}function Bb(e,t=[]){let n=un(),r=f.dim(n.spine.repeat(t.length)),o=f.dim(n.turnRoot);return r+o+e.prefix}function Wl(e,t,n,r,o=[]){let s=un(),i=o;return jl(t,n,r,e.agentResultSummary,Q(),i,s)}function Gi(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 ")+so(a.result.isError)+" "+kr(a.result,n,60,a.toolName)),a.diff&&!a.result.isError)for(let l of vr(a.diff,"flush"," "))r.push(Oe(l,o))}else r.push(" "+a.prefix)}else{r.push(e0(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=dt(c.toolInput),d=Fl(u).trim()||u.trim();r.push(" "+f.dim(`\u2500\u2500 ${d} \u2500\u2500`))}for(let u of vr(c.diff,"flush"," "))r.push(Oe(u,o))}}}return r}function e0(e,t,n){let{color:r,glyph:o}=xi(e),s=t.map(u=>Fl(dt(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=>kr(d.result,n,60,d.toolName));return" "+i+f.dim(" \u2014 ")+u.join(f.dim(", "))}return" "+i}function Oe(e,t){return ne(e,t)}var Ub=Object.freeze({spine:"\u2502 ",spineClosed:" ",lead:" ",turnRoot:"\u25C9 ",midConnector:"\u251C\u2500 ",lastConnector:"\u2570\u2500 ",textPrefix:"\u2502 "}),T5=Object.freeze({spine:"| ",spineClosed:" ",lead:" ",turnRoot:"o ",midConnector:"+- ",lastConnector:"\\- ",textPrefix:"| "}),SIe=Ub.midConnector,vIe=Ub.lastConnector;function un(){let e=v.AGENT_AFK_ASCII;return e&&/^(1|true|yes)$/i.test(e)?T5:Ub}function Ki(e,t){let n="";for(let r of e)n+=r?t.spineClosed:t.spine;return n+=t.spine,n}function Ul(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 Nb(e,t,n){if(!e||!e.trim())return[];let r=f.dim(n.textPrefix),o=Math.max(1,Q()-t.length-2-2),s=Ul(t,n),i=[];for(let a of e.split(`
|
|
1862
1862
|
`)){let l=Pb(a),c=le(l,o);for(let u of c.split(`
|
|
1863
1863
|
`))i.push(s+r+u)}return i}var t0=6,Kl=class{entries=new Map;order=[];agentIdStack=[];addStart(t,n,r){let o=Be(r),s=Sr(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),Wr.has(n)&&this.agentIdStack.push(t)}addStartWithAgentContext(t,n,r,o,s){let i=Be(r),a=this.entries.get(t);if(a?.kind==="tool"){a.toolInput=i,a.prefix=Sr(n+i,s),o!==void 0&&(a.agentContext=o);return}let l=Sr(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"||!Wr.has(o.toolName)||o.toolName==="Agent")return!1;let i=`(${Be(n)})`;return o.toolName="Agent",o.toolInput=i,o.prefix=Sr("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"&&el.has(r.toolName))return n}}getOverlay(){let t=this.buildChildMap(),n=[],r=un(),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>t0){let d=i.filter(h=>!h.result),p=i.filter(h=>h.result),m=Math.max(0,t0-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=>Ze.has(d.toolName))?f.dim(r.turnRoot):" ";for(let d of a){let p=t.get(d.toolUseId);if(Ze.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)),Kp(p,t,n,o,void 0,r),d.thinkingTail&&n.push(s(f.dim(r.spine)+f.thinking("\u2307 "+dt(d.thinkingTail))));else if(!(Ze.has(d.toolName)&&d.headerEmitted))if(Ze.has(d.toolName))d.result?n.push(s(f.dim(r.turnRoot)+d.prefix+f.dim(" \u2014 ")+so(d.result.isError)+" "+kr(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 "+dt(d.thinkingTail))));else if(d.result){if(n.push(s(u+d.prefix+f.dim(" \u2014 ")+so(d.result.isError)+" "+kr(d.result,void 0,60,d.toolName))),d.diff&&!d.result.isError)for(let m of vr(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 "+dt(d.thinkingTail))))}return l>0&&n.push(s(" "+f.dim(`\u2026 +${l} done`))),n.join(`
|
|
1864
1864
|
`)}ancestorDepthOf(t){let n=new Set([t]),r=0,o=t,s=32;for(;o!==void 0&&r<s;){let i=this.entries.get(o);if(!i||i.kind!=="tool")break;let a=i.agentContext;if(a===void 0||n.has(a))break;n.add(a);let l=this.entries.get(a);if(!l||l.kind!=="tool")break;r+=1,o=a}return r}flushSource(t,n){let r=this.entries.get(t);if(!r||r.kind!=="tool")return[];let o=Array.from({length:this.ancestorDepthOf(t)},()=>!1),s=[];{let p=[],m=new Set([t]),g=r.agentContext;for(;g!==void 0&&!m.has(g);){m.add(g);let h=this.entries.get(g);if(!h||h.kind!=="tool")break;p.push({entry:h,depth:this.ancestorDepthOf(h.toolUseId)}),g=h.agentContext}p.reverse();for(let{entry:h,depth:b}of p)h.headerEmitted||(s.push(Bb(h,Array.from({length:b},()=>!1))),h.headerEmitted=!0)}let i=new Set([t]),a=[t];for(;a.length>0;){let p=a.shift();for(let[m,g]of this.entries){if(i.has(m))continue;(g.kind==="tool",g.agentContext)===p&&(i.add(m),g.kind==="tool"&&a.push(m))}}let l=new Map;for(let p of this.order){if(!i.has(p))continue;let m=this.entries.get(p);if(!m)continue;let g=(m.kind==="tool",m.agentContext);if(!g)continue;let h=l.get(g);h||(h=[],l.set(g,h)),h.push(m)}let c=l.get(r.toolUseId)??[],u=r.headerEmitted?Wl(r,c,l,n,o).join(`
|
|
1865
|
-
`):Hl(r,c,l,n,o);for(let p of i)this.entries.delete(p);this.order=this.order.filter(p=>!i.has(p));let d=u===""?[]:[u];return[...s,...d]}flushCompletedRoots(t){if(this.entries.size===0)return[];let n=this.buildChildMap(),r=[];for(let c of this.order){let u=this.entries.get(c);!u||u.kind!=="tool"||u.agentContext||u.result!==void 0&&r.push(c)}if(r.length===0)return[];let o=[],s=new Map,i=[];for(let c of r){let u=this.entries.get(c);if(!u||u.kind!=="tool")continue;let d=n.get(u.toolUseId);if(Ze.has(u.toolName))if(o.push(...Gi(s,i,t)),s.clear(),i.length=0,u.headerEmitted){let p=Wl(u,d??[],n,t,[]);o.push(...p)}else o.push(Hl(u,d??[],n,t));else s.has(u.toolName)||(s.set(u.toolName,[]),i.push(u.toolName)),s.get(u.toolName).push(u)}o.push(...Gi(s,i,t));let a=new Set(r),l=[...r];for(;l.length>0;){let c=l.shift();for(let[u,d]of this.entries){if(a.has(u))continue;(d.kind==="tool",d.agentContext)===c&&(a.add(u),d.kind==="tool"&&l.push(u))}}for(let c of a)this.entries.delete(c);return this.order=this.order.filter(c=>!a.has(c)),o}flush(t){if(this.entries.size===0)return[];let n=this.buildChildMap(),r=[];for(let a of this.order){let l=this.entries.get(a);!l||l.kind!=="tool"||l.agentContext||r.push(a)}let o=[],s=new Map,i=[];for(let a of r){let l=this.entries.get(a);if(!l||l.kind!=="tool")continue;let c=n.get(l.toolUseId);if(Ze.has(l.toolName))if(o.push(...Gi(s,i,t)),s.clear(),i.length=0,l.headerEmitted){let u=Wl(l,c??[],n,t,[]);o.push(...u)}else o.push(Hl(l,c??[],n,t));else s.has(l.toolName)||(s.set(l.toolName,[]),i.push(l.toolName)),s.get(l.toolName).push(l)}return o.push(...Gi(s,i,t)),this.entries.clear(),this.order=[],this.agentIdStack=[],o}buildChildMap(){let t=new Map;for(let n of this.order){let r=this.entries.get(n);if(!r)continue;let o=(r.kind==="tool",r.agentContext);if(!o)continue;let s=t.get(o);s||(s=[],t.set(o,s)),s.push(r)}return t}};Me();function jb(e,t){let n=Math.max(0,e),r=n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`,o=Math.ceil(t/4);return` ${f.thinking("\u25C6 thought for "+r+" \xB7 "+o+" tok")}`}var qi=class{buffer="";startedAt=null;endedAt=null;hasEmitted=!1;committedUpTo=0;push(t){this.hasEmitted||(this.buffer+=t,this.startedAt||(this.startedAt=Date.now()))}markEnded(){this.endedAt===null&&this.startedAt!==null&&(this.endedAt=Date.now())}isActive(){return!this.hasEmitted}hasBufferedContent(){return this.buffer.trim().length>0}peek(){return this.buffer}consume(){return this.hasEmitted=!0,this.buffer}peekPhase(){return this.buffer.slice(this.committedUpTo)}drainPhase(){let t=this.buffer.slice(this.committedUpTo);return this.committedUpTo=this.buffer.length,t}collapse(){if(this.hasEmitted||!this.startedAt)return!this.startedAt&&!this.hasEmitted&&Ke()&&console.error("[afk:thinking] collapse() short-circuited: no thinking chunks received this turn. Model may not support extended thinking, or API ignored the thinking parameter."),null;this.hasEmitted=!0;let t=this.endedAt??Date.now();return jb(t-this.startedAt,this.buffer.length)}inlineSummary(){if(!this.startedAt||!this.hasBufferedContent())return null;let t=this.endedAt??Date.now(),n=Math.max(0,t-this.startedAt),r=n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`,o=Math.ceil(this.buffer.length/4);return`thought ${r} \xB7 ${o} tok`}};var Hb="__main__";function r0(e){let t={startedAt:Date.now(),lastEventAt:Date.now(),stats:{tokens:0,toolUses:0},contentBuffer:"",done:!1,errored:!1,stalledTicks:0};return e!==void 0&&(t.agentType=e),t}function Gl(e,t){return{type:"tool_result",toolUseId:"synthetic",content:e,isError:t}}function o0(e){let t=["Done"],n=[];e.stats.toolUses&&n.push(`${e.stats.toolUses} tool${e.stats.toolUses===1?"":"s"}`),e.stats.tokens&&n.push(`${ie(e.stats.tokens)} tok`);let r=e.responseMetadata?.durationMs,o=Date.now()-e.startedAt;typeof r=="number"&&(n.push(
|
|
1865
|
+
`):Hl(r,c,l,n,o);for(let p of i)this.entries.delete(p);this.order=this.order.filter(p=>!i.has(p));let d=u===""?[]:[u];return[...s,...d]}flushCompletedRoots(t){if(this.entries.size===0)return[];let n=this.buildChildMap(),r=[];for(let c of this.order){let u=this.entries.get(c);!u||u.kind!=="tool"||u.agentContext||u.result!==void 0&&r.push(c)}if(r.length===0)return[];let o=[],s=new Map,i=[];for(let c of r){let u=this.entries.get(c);if(!u||u.kind!=="tool")continue;let d=n.get(u.toolUseId);if(Ze.has(u.toolName))if(o.push(...Gi(s,i,t)),s.clear(),i.length=0,u.headerEmitted){let p=Wl(u,d??[],n,t,[]);o.push(...p)}else o.push(Hl(u,d??[],n,t));else s.has(u.toolName)||(s.set(u.toolName,[]),i.push(u.toolName)),s.get(u.toolName).push(u)}o.push(...Gi(s,i,t));let a=new Set(r),l=[...r];for(;l.length>0;){let c=l.shift();for(let[u,d]of this.entries){if(a.has(u))continue;(d.kind==="tool",d.agentContext)===c&&(a.add(u),d.kind==="tool"&&l.push(u))}}for(let c of a)this.entries.delete(c);return this.order=this.order.filter(c=>!a.has(c)),o}flush(t){if(this.entries.size===0)return[];let n=this.buildChildMap(),r=[];for(let a of this.order){let l=this.entries.get(a);!l||l.kind!=="tool"||l.agentContext||r.push(a)}let o=[],s=new Map,i=[];for(let a of r){let l=this.entries.get(a);if(!l||l.kind!=="tool")continue;let c=n.get(l.toolUseId);if(Ze.has(l.toolName))if(o.push(...Gi(s,i,t)),s.clear(),i.length=0,l.headerEmitted){let u=Wl(l,c??[],n,t,[]);o.push(...u)}else o.push(Hl(l,c??[],n,t));else s.has(l.toolName)||(s.set(l.toolName,[]),i.push(l.toolName)),s.get(l.toolName).push(l)}return o.push(...Gi(s,i,t)),this.entries.clear(),this.order=[],this.agentIdStack=[],o}buildChildMap(){let t=new Map;for(let n of this.order){let r=this.entries.get(n);if(!r)continue;let o=(r.kind==="tool",r.agentContext);if(!o)continue;let s=t.get(o);s||(s=[],t.set(o,s)),s.push(r)}return t}};Me();function jb(e,t){let n=Math.max(0,e),r=n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`,o=Math.ceil(t/4);return` ${f.thinking("\u25C6 thought for "+r+" \xB7 "+o+" tok")}`}var qi=class{buffer="";startedAt=null;endedAt=null;hasEmitted=!1;committedUpTo=0;push(t){this.hasEmitted||(this.buffer+=t,this.startedAt||(this.startedAt=Date.now()))}markEnded(){this.endedAt===null&&this.startedAt!==null&&(this.endedAt=Date.now())}isActive(){return!this.hasEmitted}hasBufferedContent(){return this.buffer.trim().length>0}peek(){return this.buffer}consume(){return this.hasEmitted=!0,this.buffer}peekPhase(){return this.buffer.slice(this.committedUpTo)}drainPhase(){let t=this.buffer.slice(this.committedUpTo);return this.committedUpTo=this.buffer.length,t}collapse(){if(this.hasEmitted||!this.startedAt)return!this.startedAt&&!this.hasEmitted&&Ke()&&console.error("[afk:thinking] collapse() short-circuited: no thinking chunks received this turn. Model may not support extended thinking, or API ignored the thinking parameter."),null;this.hasEmitted=!0;let t=this.endedAt??Date.now();return jb(t-this.startedAt,this.buffer.length)}inlineSummary(){if(!this.startedAt||!this.hasBufferedContent())return null;let t=this.endedAt??Date.now(),n=Math.max(0,t-this.startedAt),r=n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`,o=Math.ceil(this.buffer.length/4);return`thought ${r} \xB7 ${o} tok`}};var Hb="__main__";function r0(e){let t={startedAt:Date.now(),lastEventAt:Date.now(),stats:{tokens:0,toolUses:0},contentBuffer:"",done:!1,errored:!1,stalledTicks:0};return e!==void 0&&(t.agentType=e),t}function Gl(e,t){return{type:"tool_result",toolUseId:"synthetic",content:e,isError:t}}function o0(e){let t=["Done"],n=[];e.stats.toolUses&&n.push(`${e.stats.toolUses} tool${e.stats.toolUses===1?"":"s"}`),e.stats.tokens&&n.push(`${ie(e.stats.tokens)} tok`);let r=e.responseMetadata?.durationMs,o=Date.now()-e.startedAt;typeof r=="number"&&(n.push(ge(r)),o>r*1.5&&o-r>=1e3&&n.push(`${ge(o)} wall`)),n.length===0&&o>0&&n.push(ge(o));let s=e.thinkingLane?.inlineSummary();return s&&n.push(s),n.length>0&&t.push(`(${n.join(" \xB7 ")})`),t.join(" ")}function Kb(e){let t=Math.max(1,Q()-2);return Math.max(1,t-e)}function s0(e,t){return x5(e)?Yn(e,{maxWidth:t}):le(e,t)}function i0(e,t,n){if(!n||!e.trim())return"";let r;return Wb(e)?r=`
|
|
1866
1866
|
\u258D streaming code\u2026
|
|
1867
1867
|
`:R5(e)?r=`
|
|
1868
1868
|
\u258D streaming table\u2026
|
|
@@ -1883,17 +1883,17 @@ ${u}`}function bb(e,t){let n=_P[t.status];e.out.line(` ${n} ${f.bold(t.jobId)}
|
|
|
1883
1883
|
`))}function zb(e,t,n){n.streamingMarkdown.current?n.streamingMarkdown.current.commitPending():t.contentBuffer.trim()&&(Vb(t.contentBuffer,n.out),t.contentBuffer=""),zi(n);let o=As(e).split(`
|
|
1884
1884
|
`);if(n.isTTY&&n.compositor)dn(n.compositor,o);else for(let s of o)n.out.line(s)}function f0(e,t){let n=e.thinkingPhaseStartedAt;if(n==null)return null;e.thinkingPhaseStartedAt=void 0;let r=t.thinkingLane.drainPhase();return r.trim()?jb(Date.now()-n,r.length):null}function Vp(e,t){let n=f0(e,t);n!=null&&(t.isTTY&&t.compositor?t.compositor.commitAbove(n):t.out.line(n))}function Jb(e,t){if(!t.streamingMarkdown.current&&e.contentBuffer.trim()&&Vb(e.contentBuffer,t.out),e.contentBuffer="",t.coordinator){if(!t.isTTY&&t.thinkingMode!=="off"){let n=t.thinkingLane.collapse();if(n){let r=n,o=t.out;t.coordinator.schedule({anchor:"before-content",commits:[()=>{o.line(r)}]})}}if(t.toolLane.hasPending()){let n=t.toolLane.flushCompletedRoots();if(n.length>0){let r=t.compositor,o=t.overlayComposer,s=t.toolLane,i=t.isTTY,a=t.out;t.coordinator.schedule({anchor:"before-content",commits:[()=>{if(i&&r)dn(r,n),r.commitAbove(""),o?(o.markDirty("tool-lane"),o.flush()):r.setOverlay(s.getOverlay());else{for(let l of n)a.line(l);a.line("")}}]})}}if(t.isTTY&&t.thinkingMode!=="off"){let n=f0(e,t);if(n!=null){let r=t.compositor,o=t.out,s=t.isTTY;t.coordinator.schedule({anchor:"before-content",commits:[()=>{s&&r?r.commitAbove(n):o.line(n)}]})}}}else{if(!t.isTTY&&t.thinkingMode!=="off"){let n=t.thinkingLane.collapse();n&&t.out.line(n)}zi(t),t.isTTY&&t.thinkingMode!=="off"&&Vp(e,t)}}function Vb(e,t){let n=process.stdout.isTTY?Math.max(1,Q()-2):Number.POSITIVE_INFINITY,r=Yn(e,{maxWidth:n}),o=le(r,n,{breakLongWords:!0});for(let s of o.split(`
|
|
1885
1885
|
`))t.line(s)}function Yb(e,t){let n=Oc(e.message,e.stack);for(let r of n.split(`
|
|
1886
|
-
`))t.line(r)}function zi(e){if(!e.toolLane.hasPending())return;let t=e.toolLane.flushCompletedRoots();if(e.isTTY&&e.compositor)t.length>0&&(dn(e.compositor,t),e.compositor.commitAbove("")),e.overlayComposer?(e.overlayComposer.markDirty("tool-lane"),e.overlayComposer.flush()):e.compositor.setOverlay(e.toolLane.getOverlay());else if(t.length>0){for(let n of t)e.out.line(n);e.out.line("")}}function g0(e,t,n){switch(n.stageTracker&&m0(n.stageTracker,e),e.type){case"progress":n.lastProgressByTask.clear(),n.lastProgressByTask.set(e.progress.taskId,e.progress),n.isTTY&&
|
|
1886
|
+
`))t.line(r)}function zi(e){if(!e.toolLane.hasPending())return;let t=e.toolLane.flushCompletedRoots();if(e.isTTY&&e.compositor)t.length>0&&(dn(e.compositor,t),e.compositor.commitAbove("")),e.overlayComposer?(e.overlayComposer.markDirty("tool-lane"),e.overlayComposer.flush()):e.compositor.setOverlay(e.toolLane.getOverlay());else if(t.length>0){for(let n of t)e.out.line(n);e.out.line("")}}function g0(e,t,n){switch(n.stageTracker&&m0(n.stageTracker,e),e.type){case"progress":n.lastProgressByTask.clear(),n.lastProgressByTask.set(e.progress.taskId,e.progress),n.isTTY&&xt(n);return;case"chunk":{let r=e.chunk;if(r.type==="tool_use_detail"){n.thinkingLane.markEnded(),n.streamingMarkdown.current?.commitPending(),n.isTTY&&(zi(n),Vp(t,n));let o=Wr.has(r.toolName)||tl.has(r.toolName),s=n.activeSkillName&&o?n.toolLane.findLastSkillEntryId():void 0;n.toolLane.addStartWithAgentContext(r.toolUseId,r.toolName,r.toolInput,s),t.stats.toolUses+=1,n.isTTY&&n.compositor&&n.compositor.setSpinner({enabled:!0,rotateVerbEveryMs:3500}),n.isTTY&&xt(n)}else if(r.type==="tool_result")n.streamingMarkdown.current?.commitPending(),n.toolLane.addResult(r.toolUseId,r),n.isTTY&&xt(n);else if(r.type==="tool_diff")n.toolLane.addDiff(r.toolUseId,r.diff),n.isTTY&&xt(n);else if(r.type==="content"){n.thinkingLane.markEnded();let o=wb(r.content);if(n.activeSkillName&&!n.skillBadgeEmitted){let s=Sb(o,n.activeSkillName);if(o=s.text,s.found){n.skillBadgeEmitted=!0;let{color:i,glyph:a}=zy("skill"),l=" "+i(a+" ")+i.bold(n.activeSkillName);n.isTTY&&n.compositor?n.compositor.commitAbove(l):n.out.line(l)}}else n.activeSkillName&&(o=Sb(o,n.activeSkillName).text);if(!o)return;t.contentBuffer+=o,n.isTTY&&(n.compositor&&n.compositor.setSpinner({enabled:!1}),zi(n),Vp(t,n),n.streamingMarkdown.current||(n.streamingMarkdown.current=new Gp({...n.compositor?{compositor:n.compositor}:{},...n.overlayComposer?{overlayComposer:n.overlayComposer}:{}})),n.streamingMarkdown.current.push(o))}else if(r.type==="thinking"){if(n.thinkingMode==="off")return;t.thinkingPhaseStartedAt==null&&(t.thinkingPhaseStartedAt=Date.now()),n.thinkingLane.push(r.content),n.isTTY&&n.thinkingMode==="live"&&xt(n)}return}case"message":t.contentBuffer||(t.contentBuffer=wb(e.message.content));return;case"error":t.errored=!0,Yb(e.error,n.out);return;case"done":t.done=!0,e.metadata&&(t.responseMetadata=e.metadata),Jb(t,n);return;case"suggestion":return;case"stream_retry":t.contentBuffer="",n.streamingMarkdown.current?.discardPending();return;case"panel":zb(e.spec,t,n);return}}function xt(e){if(!e.compositor)return;if(e.overlayComposer){e.overlayComposer.invalidate(),e.overlayComposer.flush();return}let t=[];if(e.thinkingMode==="live"&&e.thinkingLane.hasBufferedContent()){let r=Jp(e.thinkingLane.peek(),{cols:Q()});r&&t.push(r)}e.toolLane.hasPending()&&t.push(e.toolLane.getOverlay());let n=[];for(let r of e.lastProgressByTask.values())n.push(...Kd(r));n.length>0&&t.push(n.join(`
|
|
1887
1887
|
`)),e.compositor.setOverlay(t.join(`
|
|
1888
1888
|
`))}var Yp=class{beforeContent=[];afterSubagent=new Map;afterContent=[];schedule(t){let{anchor:n}=t;if(n==="before-content")this.beforeContent.push(t);else if(n==="after-content")this.afterContent.push(t);else{let r=n.slice(15),o=this.afterSubagent.get(r);o||(o=[],this.afterSubagent.set(r,o)),o.push(t)}}drainSubagent(t){for(let r of this.beforeContent.splice(0))for(let o of r.commits)o();let n=this.afterSubagent.get(t);if(n){this.afterSubagent.delete(t);for(let r of n)for(let o of r.commits)o()}}async flushAll(t){for(let n of this.beforeContent.splice(0))for(let r of n.commits)r();if(t)try{await t()}catch{}for(let[n,r]of Array.from(this.afterSubagent)){this.afterSubagent.delete(n);for(let o of r)for(let s of o.commits)s()}for(let n of this.afterContent.splice(0))for(let r of n.commits)r()}};function Xb(e,t){let n=e.trimEnd();if(!n.trim())return"";let r=Math.max(t*4,400),o=n.length>r?n.slice(-r):n,s=/[.!?](?=\s)|\n+/g,i=-1,a;for(;(a=s.exec(o))!==null;)i=a.index+a[0].length;let l=i>=0?o.slice(i):o;return l=l.replace(/\s+/g," ").trim(),l?(l.length>t&&(l=l.slice(0,Math.max(1,t-1))+"\u2026"),l):""}function Xp(e,t){if(!(!e||!e.trim())&&!t.isTTY)for(let n of D5(e))t.out.line(n)}function D5(e){if(!e)return[];let t=f.dim("\u2502 "),n=" ",r=Math.max(1,Q()-n.length-2-2),o=[];for(let s of e.split(`
|
|
1889
1889
|
`)){let i=le(s,r);for(let a of i.split(`
|
|
1890
|
-
`))o.push(n+t+a)}return o}function Zb(e,t,n,r){if(t.syntheticAgentToolUseId)return;let o=t.agentType?.trim()||"agent",s=process.stdout.columns??100,i=Math.max(20,s-14);if(r!==void 0&&n.toolLane.mergeAgentLabel(r,o,i)){t.syntheticAgentToolUseId=r;return}let a=`__synth_agent_${e}`;n.toolLane.addStartWithAgentContext(a,"Agent",`(${o})`,r,i),t.syntheticAgentToolUseId=a}var Zp=new Map,Ji=new Map;function h0(e,t,n,r){let o=n.syntheticAgentToolUseId;if(o)switch(e.type){case"progress":e.progress.totalTokens&&(n.stats.tokens=e.progress.totalTokens),e.progress.toolUses!==void 0&&(n.stats.progressReportedToolUses=e.progress.toolUses);return;case"chunk":{let s=e.chunk;if(s.type==="tool_use_detail"){n.thinkingLane?.markEnded(),n.currentTextEntryId=void 0;let i=r.streamingMarkdown.get(t);i&&i.commitPending(),r.toolLane.setThinkingTail(o,void 0);let a=process.stdout.columns??100,l=Math.max(20,a-14);r.toolLane.addStartWithAgentContext(s.toolUseId,s.toolName,s.toolInput,o,l),n.stats.toolUses+=1,r.isTTY&&r.orchestratorCtx&&
|
|
1891
|
-
`);if(i!==-1){let a=n.contentBuffer.slice(0,i);n.contentBuffer=n.contentBuffer.slice(i+1),Xp(a,r)}}else if(s.type==="thinking"){if(r.thinkingMode==="off")return;if(n.thinkingLane||(n.thinkingLane=new qi),n.thinkingLane.push(s.content),r.thinkingMode==="live"&&r.isTTY&&r.orchestratorCtx){let i=process.stdout.columns??100,a=Math.max(20,i-14),l=Xb(n.thinkingLane.peek(),a);l&&r.toolLane.setThinkingTail(o,l);{let c=Date.now(),u=Ji.get(o)??0;c-u>=1500&&(Ji.set(o,c),
|
|
1892
|
-
`);if(r.isTTY&&r.compositor)dn(r.compositor,s);else for(let i of s)r.out.line(i);r.isTTY&&r.compositor?r.compositor.commitAbove(""):r.out.line("")}function F5(e,t,n){let r=t.syntheticAgentToolUseId;if(!r||t.errored)return;if(!n.isTTY&&t.contentBuffer&&Xp(t.contentBuffer,n),t.contentBuffer="",!n.isTTY&&t.thinkingLane?.hasBufferedContent()){let s=t.thinkingLane.collapse();s&&(n.out.line(s),n.out.line(""))}n.toolLane.setThinkingTail(r,void 0),Zp.delete(r),Ji.delete(r);let o=o0(t);n.toolLane.setAgentResultSummary(r,o),n.toolLane.addResult(r,Gl(o,!1)),n.isTTY&&n.orchestratorCtx&&
|
|
1890
|
+
`))o.push(n+t+a)}return o}function Zb(e,t,n,r){if(t.syntheticAgentToolUseId)return;let o=t.agentType?.trim()||"agent",s=process.stdout.columns??100,i=Math.max(20,s-14);if(r!==void 0&&n.toolLane.mergeAgentLabel(r,o,i)){t.syntheticAgentToolUseId=r;return}let a=`__synth_agent_${e}`;n.toolLane.addStartWithAgentContext(a,"Agent",`(${o})`,r,i),t.syntheticAgentToolUseId=a}var Zp=new Map,Ji=new Map;function h0(e,t,n,r){let o=n.syntheticAgentToolUseId;if(o)switch(e.type){case"progress":e.progress.totalTokens&&(n.stats.tokens=e.progress.totalTokens),e.progress.toolUses!==void 0&&(n.stats.progressReportedToolUses=e.progress.toolUses);return;case"chunk":{let s=e.chunk;if(s.type==="tool_use_detail"){n.thinkingLane?.markEnded(),n.currentTextEntryId=void 0;let i=r.streamingMarkdown.get(t);i&&i.commitPending(),r.toolLane.setThinkingTail(o,void 0);let a=process.stdout.columns??100,l=Math.max(20,a-14);r.toolLane.addStartWithAgentContext(s.toolUseId,s.toolName,s.toolInput,o,l),n.stats.toolUses+=1,r.isTTY&&r.orchestratorCtx&&xt(r.orchestratorCtx)}else if(s.type==="tool_result"){let i=r.streamingMarkdown.get(t);i&&i.commitPending(),r.toolLane.addResult(s.toolUseId,s),r.isTTY&&r.orchestratorCtx&&xt(r.orchestratorCtx)}else if(s.type==="tool_diff")r.toolLane.addDiff(s.toolUseId,s.diff),r.isTTY&&r.orchestratorCtx&&xt(r.orchestratorCtx);else if(s.type==="content")if(n.thinkingLane?.markEnded(),n.currentTextEntryId||(n.currentTextEntryId="__in_text_block__"),n.contentBuffer+=s.content,r.isTTY&&r.compositor){if(s.content.trim()){let i=process.stdout.columns??100,a=Math.max(20,i-14),l=Xb(n.contentBuffer,a),c=Date.now(),u=Zp.get(o)??0,d=l?/[.!?…]$/.test(l):!1;l&&(c-u>=1500||d)&&(Zp.set(o,c),r.toolLane.setThinkingTail(o,l))}if(r.orchestratorCtx){let i=Date.now(),a=Ji.get(o)??0;i-a>=1500&&(Ji.set(o,i),xt(r.orchestratorCtx))}}else{let i=n.contentBuffer.lastIndexOf(`
|
|
1891
|
+
`);if(i!==-1){let a=n.contentBuffer.slice(0,i);n.contentBuffer=n.contentBuffer.slice(i+1),Xp(a,r)}}else if(s.type==="thinking"){if(r.thinkingMode==="off")return;if(n.thinkingLane||(n.thinkingLane=new qi),n.thinkingLane.push(s.content),r.thinkingMode==="live"&&r.isTTY&&r.orchestratorCtx){let i=process.stdout.columns??100,a=Math.max(20,i-14),l=Xb(n.thinkingLane.peek(),a);l&&r.toolLane.setThinkingTail(o,l);{let c=Date.now(),u=Ji.get(o)??0;c-u>=1500&&(Ji.set(o,c),xt(r.orchestratorCtx))}}}return}case"message":return;case"error":n.errored=!0,r.toolLane.setThinkingTail(o,void 0),Zp.delete(o),Ji.delete(o);{let s=`error \u2014 ${e.error.message}`;r.toolLane.setAgentResultSummary(o,s),r.toolLane.addResult(o,Gl(s,!0))}r.isTTY&&r.orchestratorCtx&&xt(r.orchestratorCtx);return;case"done":n.done=!0,e.metadata&&(n.responseMetadata=e.metadata),F5(t,n,r);return;case"suggestion":return;case"panel":L5(e.spec,t,n,r);return}}function L5(e,t,n,r){if(r.isTTY){let i=n.syntheticAgentToolUseId;i&&r.toolLane.setThinkingTail(i,void 0),n.contentBuffer=""}else n.contentBuffer.trim()&&(Xp(n.contentBuffer,r),n.contentBuffer="");let s=As(e).split(`
|
|
1892
|
+
`);if(r.isTTY&&r.compositor)dn(r.compositor,s);else for(let i of s)r.out.line(i);r.isTTY&&r.compositor?r.compositor.commitAbove(""):r.out.line("")}function F5(e,t,n){let r=t.syntheticAgentToolUseId;if(!r||t.errored)return;if(!n.isTTY&&t.contentBuffer&&Xp(t.contentBuffer,n),t.contentBuffer="",!n.isTTY&&t.thinkingLane?.hasBufferedContent()){let s=t.thinkingLane.collapse();s&&(n.out.line(s),n.out.line(""))}n.toolLane.setThinkingTail(r,void 0),Zp.delete(r),Ji.delete(r);let o=o0(t);n.toolLane.setAgentResultSummary(r,o),n.toolLane.addResult(r,Gl(o,!1)),n.isTTY&&n.orchestratorCtx&&xt(n.orchestratorCtx)}var Qp=class{sink;order;slots=new Map;dirty=!1;constructor(t,n){this.sink=t,this.order=[...n]}register(t){this.slots.set(t.key,t),this.dirty=!0}markDirty(t){this.slots.has(t)&&(this.dirty=!0)}flush(){if(!this.dirty)return;this.dirty=!1;let t=[];for(let n of this.order){let r=this.slots.get(n);if(r===void 0)continue;let o=r.render();o.length>0&&t.push(o)}this.sink.setOverlay(t.join(`
|
|
1893
1893
|
`))}invalidate(){this.dirty=!0}};function y0(e,t=2){if(t<1||!Number.isInteger(t))throw new RangeError(`makeDedupingLineWriter: maxRepeat must be a positive integer, got ${t}`);let n=null,r=0,o=()=>{if(n!==null&&r>t){let s=r-t;e.line(` \u2026 (line repeated ${s} more time${s===1?"":"s"})`)}};return{line(s){let i=s??"";i===n?(r++,r<=t&&e.line(i)):(o(),n=i,r=1,e.line(i))},raw(s){o(),n=null,r=0,e.raw(s)},success(s){o(),n=null,r=0,e.success(s)},info(s){o(),n=null,r=0,e.info(s)},warn(s){o(),n=null,r=0,e.warn(s)},error(s){o(),n=null,r=0,e.error(s)},flush(){o(),n=null,r=0}}}Me();var N5=3e4,B5=" \xB7 waiting ",U5=375;function b0(e,t){e.register({key:"thinking-live",render:()=>t.thinkingMode!=="live"||!t.thinkingLane.isActive()||!t.thinkingLane.hasBufferedContent()?"":Jp(t.thinkingLane.peekPhase(),{cols:Q()})??""}),e.register({key:"markdown-pending",render:()=>{let n=t.streamingMarkdownRef.current;return n?n.renderPending():""}}),e.register({key:"tool-lane",render:()=>t.toolLane.hasPending()?t.toolLane.getOverlay():""}),e.register({key:"progress-banner",render:()=>{let n=[];for(let r of t.lastProgressByTask.values())n.push(...Kd(r));return n.length>0?n.join(`
|
|
1894
1894
|
`):""}}),e.register({key:"interrupt",render:()=>j5(t.getInterrupting())})}function j5(e){return e?" "+f.warning("\u26A0 interrupting\u2026 (Ctrl+C again to exit)"):""}function w0(e,t){return He.subscribe(()=>{t||!e||(e.invalidate(),e.flush())})}function S0(e){if(e.disposed)return!1;let t=!1,n=Date.now();for(let[r,o]of e.sources){if(o.done||o.errored||!o.syntheticAgentToolUseId)continue;let s=n-o.lastEventAt;if(s>N5)if(o.stalledTicks+=1,o.stalledTicks>=U5*2)Ke()&&process.stderr.write(`[stream-renderer] auto_settle_timeout ${JSON.stringify({sourceId:r,elapsedMs:s,syntheticAgentToolUseId:o.syntheticAgentToolUseId})}
|
|
1895
|
-
`),e.toolLane.addResult(o.syntheticAgentToolUseId,Gl("[no-result \u2014 timed out]",!1)),o.done=!0,t=!0;else{let i=o.agentType??r,a=B5+
|
|
1896
|
-
`)}var Vi=class{out;thinkingMode;isTTY;captureMode;reducedMotion;onCancel;onBackground;activeSkillName;history;autocompleteState;promptText;scrollRegion;onStageChange;ownsCompositor=!0;borrowedCompositor=null;priorOnCancel=void 0;interrupting=!1;coordinator=new Yp;compositor=null;overlayComposer=null;streamingMarkdownRef={current:null};toolLane=new Kl;thinkingLane=new qi;stageTracker=p0();sources=new Map;subagentMarkdown=new Map;lastProgressByTask=new Map;disposed=!1;pauseTickInterval=null;resizeUnsub=null;sink;constructor(t){this.captureMode=t.captureMode??lp(),this.reducedMotion=t.reducedMotion??cp(),this.out=this.captureMode?y0(t.out,2):t.out;let n=t.thinkingMode??(t.verbose===!0?"live":"summary");this.thinkingMode=this.captureMode&&n==="live"?"summary":n,this.onCancel=t.onCancel,this.onBackground=t.onBackground,this.isTTY=!(t.forceNonTty??!1)&&!!process.stdout.isTTY&&!!process.stdin.isTTY,this.activeSkillName=t.activeSkillName,this.history=t.history,this.autocompleteState=t.autocompleteState,this.promptText=t.promptText,this.scrollRegion=t.scrollRegion,this.onStageChange=t.onStageChange,t.compositor&&(this.borrowedCompositor=t.compositor,this.ownsCompositor=!1),this.sink=(r,o)=>this.process(r,o)}async arm(){if(this.disposed||!this.isTTY||this.compositor)return;let t;if(this.borrowedCompositor)t=this.borrowedCompositor,t.setInputMode("streaming"),this.priorOnCancel=t.getOnCancel(),this.onCancel&&t.setOnCancel(this.onCancel);else{let n={has:r=>it().some(o=>o.name===`/${r}`)};t=new Wi({stdout:process.stdout,stdin:process.stdin,...this.onCancel?{onCancel:this.onCancel}:{},...this.onBackground?{onBackground:this.onBackground}:{},...this.history?{history:this.history}:{},...this.autocompleteState?{autocompleteState:this.autocompleteState}:{},...this.promptText!==void 0?{promptText:this.promptText}:{},formatInputBuffer:r=>oo(r,n),...this.scrollRegion?{scrollRegion:this.scrollRegion}:{},captureMode:this.captureMode}),await t.arm()}this.compositor=t,this.overlayComposer=new Qp(t,["thinking-live","markdown-pending","tool-lane","progress-banner","interrupt"]),b0(this.overlayComposer,{stageTracker:this.stageTracker,thinkingMode:this.thinkingMode,thinkingLane:this.thinkingLane,streamingMarkdownRef:this.streamingMarkdownRef,toolLane:this.toolLane,lastProgressByTask:this.lastProgressByTask,getInterrupting:()=>this.interrupting}),t.setSpinner({enabled:!this.reducedMotion,rotateVerbEveryMs:3500}),this.pauseTickInterval=setInterval(()=>this.checkPauseAnnotations(),80),this.resizeUnsub=w0(this.overlayComposer,!1)}getCompositor(){return this.compositor}setInterrupting(t){this.disposed||(this.interrupting=t,this.overlayComposer&&(this.overlayComposer.markDirty("interrupt"),this.overlayComposer.flush()))}buildOrchestratorCtx(){return v0({out:this.out,isTTY:this.isTTY,compositor:this.compositor,overlayComposer:this.overlayComposer,toolLane:this.toolLane,thinkingLane:this.thinkingLane,thinkingMode:this.thinkingMode,streamingMarkdown:this.streamingMarkdownRef,coordinator:this.coordinator,lastProgressByTask:this.lastProgressByTask,...this.isTTY?{stageTracker:this.stageTracker}:{},...this.activeSkillName?{activeSkillName:this.activeSkillName}:{}})}process(t,n){if(this.disposed)return;let r=n?.subagentId??Hb,o=r===Hb,s=this.sources.get(r);if(!s&&(s=r0(n?.agentType),this.sources.set(r,s),!o)){let i=k0({parentId:n?.parentId,sources:this.sources,toolLane:this.toolLane,sourceId:r});Zb(r,s,Qb({isTTY:this.isTTY,compositor:this.compositor,toolLane:this.toolLane,out:this.out,streamingMarkdown:this.subagentMarkdown,thinkingMode:this.thinkingMode,orchestratorCtx:this.buildOrchestratorCtx()}),i)}if(o){let i=this.stageTracker.stage;if(g0(t,s,this.buildOrchestratorCtx()),this.onStageChange&&this.stageTracker.stage!==i)try{this.onStageChange(this.stageTracker.stage)}catch{}}else{if(h0(t,r,s,Qb({isTTY:this.isTTY,compositor:this.compositor,toolLane:this.toolLane,out:this.out,streamingMarkdown:this.subagentMarkdown,thinkingMode:this.thinkingMode,orchestratorCtx:this.buildOrchestratorCtx()})),s.lastEventAt=Date.now(),s.pauseAnnotation!==void 0&&s.syntheticAgentToolUseId){s.pauseAnnotation=void 0,s.stalledTicks=0;let a=s.agentType??r;this.toolLane.addStartWithAgentContext(s.syntheticAgentToolUseId,"Agent",`(${a})`,void 0)}if((t.type==="done"||t.type==="error")&&this.isTTY){let a=s.syntheticAgentToolUseId;if(a&&this.toolLane.hasEntry(a)){let l=this.toolLane.flushSource(a),c=this.compositor,u=this.overlayComposer,d=this.toolLane,p=this.out;this.coordinator.schedule({anchor:`after-subagent:${r}`,commits:[()=>{if(c)dn(c,l),c.commitAbove(""),u?(u.markDirty("tool-lane"),u.flush()):c.setOverlay(d.getOverlay());else{for(let m of l)p.line(m);p.line("")}}]});try{this.streamingMarkdownRef.current&&this.streamingMarkdownRef.current.commitPending()}finally{this.coordinator.drainSubagent(r)}}
|
|
1895
|
+
`),e.toolLane.addResult(o.syntheticAgentToolUseId,Gl("[no-result \u2014 timed out]",!1)),o.done=!0,t=!0;else{let i=o.agentType??r,a=B5+ge(s);o.pauseAnnotation!==a&&(o.pauseAnnotation=a,e.toolLane.addStartWithAgentContext(o.syntheticAgentToolUseId,"Agent",`(${i})${a}`,void 0),t=!0)}}return t&&e.isTTY&&e.overlayComposer&&(e.overlayComposer.markDirty("tool-lane"),e.overlayComposer.flush()),t}Me();function v0(e){return{out:e.out,isTTY:e.isTTY,compositor:e.compositor,overlayComposer:e.overlayComposer,toolLane:e.toolLane,thinkingLane:e.thinkingLane,thinkingMode:e.thinkingMode,streamingMarkdown:e.streamingMarkdown,coordinator:e.coordinator,lastProgressByTask:e.lastProgressByTask,...e.isTTY&&e.stageTracker?{stageTracker:e.stageTracker}:{},...e.activeSkillName?{activeSkillName:e.activeSkillName}:{}}}function Qb(e){return{isTTY:e.isTTY,compositor:e.compositor,toolLane:e.toolLane,out:e.out,streamingMarkdown:e.streamingMarkdown,thinkingMode:e.thinkingMode,orchestratorCtx:e.orchestratorCtx}}function k0(e){if(e.parentId===void 0)return;let t=e.sources.get(e.parentId);if(t!==void 0)return t.syntheticAgentToolUseId;if(e.toolLane.hasEntry(e.parentId))return e.parentId;Ke()&&process.stderr.write(`[stream-renderer] parentId_fallback_unresolved ${JSON.stringify({parentId:e.parentId,sourceId:e.sourceId})}
|
|
1896
|
+
`)}var Vi=class{out;thinkingMode;isTTY;captureMode;reducedMotion;onCancel;onBackground;activeSkillName;history;autocompleteState;promptText;scrollRegion;onStageChange;ownsCompositor=!0;borrowedCompositor=null;priorOnCancel=void 0;interrupting=!1;coordinator=new Yp;compositor=null;overlayComposer=null;streamingMarkdownRef={current:null};toolLane=new Kl;thinkingLane=new qi;stageTracker=p0();sources=new Map;subagentMarkdown=new Map;lastProgressByTask=new Map;disposed=!1;pauseTickInterval=null;resizeUnsub=null;sink;constructor(t){this.captureMode=t.captureMode??lp(),this.reducedMotion=t.reducedMotion??cp(),this.out=this.captureMode?y0(t.out,2):t.out;let n=t.thinkingMode??(t.verbose===!0?"live":"summary");this.thinkingMode=this.captureMode&&n==="live"?"summary":n,this.onCancel=t.onCancel,this.onBackground=t.onBackground,this.isTTY=!(t.forceNonTty??!1)&&!!process.stdout.isTTY&&!!process.stdin.isTTY,this.activeSkillName=t.activeSkillName,this.history=t.history,this.autocompleteState=t.autocompleteState,this.promptText=t.promptText,this.scrollRegion=t.scrollRegion,this.onStageChange=t.onStageChange,t.compositor&&(this.borrowedCompositor=t.compositor,this.ownsCompositor=!1),this.sink=(r,o)=>this.process(r,o)}async arm(){if(this.disposed||!this.isTTY||this.compositor)return;let t;if(this.borrowedCompositor)t=this.borrowedCompositor,t.setInputMode("streaming"),this.priorOnCancel=t.getOnCancel(),this.onCancel&&t.setOnCancel(this.onCancel);else{let n={has:r=>it().some(o=>o.name===`/${r}`)};t=new Wi({stdout:process.stdout,stdin:process.stdin,...this.onCancel?{onCancel:this.onCancel}:{},...this.onBackground?{onBackground:this.onBackground}:{},...this.history?{history:this.history}:{},...this.autocompleteState?{autocompleteState:this.autocompleteState}:{},...this.promptText!==void 0?{promptText:this.promptText}:{},formatInputBuffer:r=>oo(r,n),...this.scrollRegion?{scrollRegion:this.scrollRegion}:{},captureMode:this.captureMode}),await t.arm()}this.compositor=t,this.overlayComposer=new Qp(t,["thinking-live","markdown-pending","tool-lane","progress-banner","interrupt"]),b0(this.overlayComposer,{stageTracker:this.stageTracker,thinkingMode:this.thinkingMode,thinkingLane:this.thinkingLane,streamingMarkdownRef:this.streamingMarkdownRef,toolLane:this.toolLane,lastProgressByTask:this.lastProgressByTask,getInterrupting:()=>this.interrupting}),t.setSpinner({enabled:!this.reducedMotion,rotateVerbEveryMs:3500}),this.pauseTickInterval=setInterval(()=>this.checkPauseAnnotations(),80),this.resizeUnsub=w0(this.overlayComposer,!1)}getCompositor(){return this.compositor}setInterrupting(t){this.disposed||(this.interrupting=t,this.overlayComposer&&(this.overlayComposer.markDirty("interrupt"),this.overlayComposer.flush()))}buildOrchestratorCtx(){return v0({out:this.out,isTTY:this.isTTY,compositor:this.compositor,overlayComposer:this.overlayComposer,toolLane:this.toolLane,thinkingLane:this.thinkingLane,thinkingMode:this.thinkingMode,streamingMarkdown:this.streamingMarkdownRef,coordinator:this.coordinator,lastProgressByTask:this.lastProgressByTask,...this.isTTY?{stageTracker:this.stageTracker}:{},...this.activeSkillName?{activeSkillName:this.activeSkillName}:{}})}process(t,n){if(this.disposed)return;let r=n?.subagentId??Hb,o=r===Hb,s=this.sources.get(r);if(!s&&(s=r0(n?.agentType),this.sources.set(r,s),!o)){let i=k0({parentId:n?.parentId,sources:this.sources,toolLane:this.toolLane,sourceId:r});Zb(r,s,Qb({isTTY:this.isTTY,compositor:this.compositor,toolLane:this.toolLane,out:this.out,streamingMarkdown:this.subagentMarkdown,thinkingMode:this.thinkingMode,orchestratorCtx:this.buildOrchestratorCtx()}),i)}if(o){let i=this.stageTracker.stage;if(g0(t,s,this.buildOrchestratorCtx()),this.onStageChange&&this.stageTracker.stage!==i)try{this.onStageChange(this.stageTracker.stage)}catch{}}else{if(h0(t,r,s,Qb({isTTY:this.isTTY,compositor:this.compositor,toolLane:this.toolLane,out:this.out,streamingMarkdown:this.subagentMarkdown,thinkingMode:this.thinkingMode,orchestratorCtx:this.buildOrchestratorCtx()})),s.lastEventAt=Date.now(),s.pauseAnnotation!==void 0&&s.syntheticAgentToolUseId){s.pauseAnnotation=void 0,s.stalledTicks=0;let a=s.agentType??r;this.toolLane.addStartWithAgentContext(s.syntheticAgentToolUseId,"Agent",`(${a})`,void 0)}if((t.type==="done"||t.type==="error")&&this.isTTY){let a=s.syntheticAgentToolUseId;if(a&&this.toolLane.hasEntry(a)){let l=this.toolLane.flushSource(a),c=this.compositor,u=this.overlayComposer,d=this.toolLane,p=this.out;this.coordinator.schedule({anchor:`after-subagent:${r}`,commits:[()=>{if(c)dn(c,l),c.commitAbove(""),u?(u.markDirty("tool-lane"),u.flush()):c.setOverlay(d.getOverlay());else{for(let m of l)p.line(m);p.line("")}}]});try{this.streamingMarkdownRef.current&&this.streamingMarkdownRef.current.commitPending()}finally{this.coordinator.drainSubagent(r)}}xt(this.buildOrchestratorCtx())}}}async dispose(){if(this.disposed)return;this.disposed=!0,this.resizeUnsub&&(this.resizeUnsub(),this.resizeUnsub=null);let t=this.streamingMarkdownRef.current?()=>this.streamingMarkdownRef.current.flush():void 0;await this.coordinator.flushAll(t),this.streamingMarkdownRef.current&&(this.streamingMarkdownRef.current.dispose(),this.streamingMarkdownRef.current=null);for(let r of this.subagentMarkdown.values()){try{await r.flush()}catch{}r.dispose()}if(this.subagentMarkdown.clear(),this.toolLane.hasPending()){let r=this.toolLane.flush();if(this.isTTY&&this.compositor)dn(this.compositor,r),this.compositor.commitAbove(""),this.overlayComposer?(this.overlayComposer.markDirty("tool-lane"),this.overlayComposer.flush()):this.compositor.setOverlay(this.toolLane.getOverlay());else{for(let o of r)this.out.line(o);this.out.line("")}}if(this.pauseTickInterval&&(clearInterval(this.pauseTickInterval),this.pauseTickInterval=null),this.compositor){if(this.ownsCompositor)try{this.compositor.disarm()}catch{}else{try{this.compositor.setSpinner({enabled:!1})}catch(r){z("[stream-renderer] borrow-dispose setSpinner: "+String(r))}try{this.overlayComposer?(this.overlayComposer.invalidate(),this.overlayComposer.flush()):this.compositor.setOverlay("")}catch(r){z("[stream-renderer] borrow-dispose setOverlay: "+String(r))}try{this.compositor.setInputMode("idle")}catch(r){z("[stream-renderer] borrow-dispose setInputMode: "+String(r))}try{this.compositor.setOnCancel(this.priorOnCancel??null)}catch(r){z("[stream-renderer] borrow-dispose setOnCancel: "+String(r))}this.priorOnCancel=void 0}this.compositor=null,this.borrowedCompositor=null}let n=this.out;if(typeof n.flush=="function")try{n.flush()}catch{}}checkPauseAnnotations(){S0({compositor:this.compositor,disposed:this.disposed,sources:this.sources,toolLane:this.toolLane,isTTY:this.isTTY,overlayComposer:this.overlayComposer,stageTracker:this.stageTracker,thinkingMode:this.thinkingMode,thinkingLane:this.thinkingLane,streamingMarkdownRef:this.streamingMarkdownRef,lastProgressByTask:this.lastProgressByTask,out:this.out,pauseTickInterval:this.pauseTickInterval,resizeUnsub:this.resizeUnsub})}};function em(e,t){let n=t.verbose??v.AFK_SKILL_STREAM_VERBOSE==="1",r=t.out??e.out,o=e.getCompositor?.()??null;return new Vi({out:r,verbose:n,activeSkillName:t.skillName,onCancel:t.onCancel??(()=>{}),...o?{compositor:o}:{},...e.onStageChange?{onStageChange:e.onStageChange}:{}})}function Yi(e){let t=e!==void 0?r=>{e.fn(r)}:r=>{console.log(r)},n=e!==void 0&&e.rawFn!==void 0?r=>{e.rawFn(r)}:r=>{process.stdout.write(r)};return{line(r=""){t(r)},raw(r){n(r)},success(r){t(f.success("\u2713 ")+r)},info(r){t(f.info("\u2139 ")+r)},warn(r){t(f.warning("\u26A0 ")+r)},error(r){t(f.error("\u2717 ")+r)}}}er();var H5="You are initializing this project for use with AFK (an AI agent CLI).\n\nYour job: scan this project and generate an `AFK.md` file in the project root. AFK.md is a plain markdown file (no YAML frontmatter) that serves as the system prompt for all AFK sessions in this project.\n\n## Steps\n\n1. **Discover project metadata** \u2014 read these files if they exist:\n - `package.json`, `tsconfig.json`, `pyproject.toml`, `Cargo.toml`, `go.mod`, `Makefile`, `CMakeLists.txt`\n - `.github/workflows/` (CI config)\n - `docker-compose.yml`, `Dockerfile`\n - `README.md` or `README`\n - Any existing `CLAUDE.md` or `AGENTS.md` (borrow relevant context)\n\n2. **Scan directory structure** \u2014 list top-level directories and key subdirectories to understand the project layout.\n\n3. **Generate AFK.md** with these sections:\n - **What This Is** \u2014 one-paragraph description of the project (language, framework, purpose)\n - **Commands** \u2014 build, test, lint, dev commands (extracted from package.json scripts, Makefile targets, etc.)\n - **Architecture** \u2014 key directories and their purpose, entry points, major subsystems\n - **Conventions** \u2014 coding style, naming patterns, anything notable from config files (strictness levels, linting rules)\n - Only include sections where you found real content. Skip empty sections.\n\n4. **Write the file** \u2014 write AFK.md to the project root. Keep it concise \u2014 under 150 lines. This file is loaded into every session, so brevity matters.\n\n## Format rules\n- Plain markdown, no YAML frontmatter\n- Use code blocks for commands\n- Use tables for directory layouts\n- Don't include boilerplate or filler \u2014 every line should earn its place",E0={name:"/init",summary:"Scan project and generate AFK.md",hint:"When you're in a fresh repo and want the model to bootstrap an AFK.md system prompt that captures conventions, commands, and architecture.",async handler(e,t){let n=tw(process.cwd(),"AFK.md"),r=tw(process.cwd(),"CLAUDE.md"),o=[];o.push({type:"text",text:Ap("init",t)});let s=H5;ew(n)&&!t.includes("--force")&&(s+=`
|
|
1897
1897
|
|
|
1898
1898
|
## Existing AFK.md detected
|
|
1899
1899
|
An AFK.md already exists at \`${n}\`. Read it first \u2014 then update it with any new information from the project scan. Preserve user-written content and only add/refresh sections derived from project metadata. If the existing file is already good, say so and make minimal changes.`),ew(r)&&(s+=`
|
|
@@ -1908,7 +1908,7 @@ These existing agent-instruction sources were found: ${c}. Read each and incorpo
|
|
|
1908
1908
|
${c}`)}o.push({type:"text",text:s});let l=em(e,{skillName:"init",out:Yi(),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 T0 from"chalk";jh();var nw=new Map;function x0(e,t){let n=nw.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`)}nw.set(e,t),nR(e)}function tm(e){return nw.get(e)}function W5(e){return(e/1e3).toFixed(1)+"s"}function R0(e,t){let n=tm(e.skillName),r=W5(e.durationMs);if(!n){let s=`[${e.skillName} \xB7 ${r}]`;return Xi(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=T0.hex(n.color)(s);return Xi(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 Xi(s,t?.columns)}}function Xi(e,t){return t!==void 0&&V(e)>t?ne(e,t):e}function C0(e,t){let n=tm(e);if(!n){let s=`[${e} \xB7 running\u2026]`;return Xi(s,t?.columns)}if(t?.isTTY!==!1){let s=`${n.glyph} ${e} \xB7 ${n.inFlightVerb}`,i=T0.hex(n.color)(s);return Xi(i,t?.columns)}let o=`[${e} \xB7 ${n.inFlightVerb}]`;return Xi(o,t?.columns)}var A0={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=tm(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"}};ch();function K5(e=lh){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 _0=K5();import G5 from"path";import{statSync as q5}from"fs";var es;function I0(e){es=e}var P0={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(!es)return e.out.error("Directory grants not available in this session."),"continue";let n=t.trim();if(!n){let a=es.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=G5.resolve(process.cwd(),o);if(r!=="revoke")try{q5(s)}catch{return e.out.error(`Path does not exist: ${s}`),"continue"}let i=e.stats.sessionId;if(r==="revoke"){let a=es.getGrants();es.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"?(es.addWriteRoot(s,"slash",i),e.out.line(`\u2713 Read+write grant: ${s}`)):(es.addReadRoot(s,"slash",i),e.out.line(`\u2713 Read-only grant: ${s}`));return"continue"}};var M0=[{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"]]}],O0={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(de());let n=M0.flatMap(r=>r.rows).reduce((r,[o])=>Math.max(r,o.length),0);for(let{group:r,rows:o}of M0){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 s3}from"node:child_process";import{promises as i3}from"node:fs";import{dirname as a3,isAbsolute as l3,join as c3,resolve as u3}from"node:path";import{promisify as d3}from"node:util";K();La();import{promises as pn,existsSync as L0,createReadStream as z5,realpathSync as J5}from"node:fs";import{join as nm,relative as V5,isAbsolute as Y5}from"node:path";import{createInterface as X5}from"node:readline";var Z5=36e5,Q5=30*864e5;function $0(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function D0(e){try{return J5(e)}catch{return e}}function e3(e,t){let n=V5(D0(t),D0(e));return n===""||!n.startsWith("..")&&!Y5(n)}function t3(e){let t=e.trim().split(/\n\n+/),n=[];for(let r of t){let o=r.split(`
|
|
1909
1909
|
`),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 n3(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>=Z5?"empty":e.isDirty&&e.ageMs>s?"stale-dirty":!e.isDirty&&e.ageMs>o?"stale-clean":"active"}async function r3(e){if(!L0(e))return 0;let t=0;try{let n=X5({input:z5(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 rm=class extends Error{constructor(t){super(`Worktree sweep lock contested: ${t} \u2014 another sweep may be running.`),this.name="LockContestedError"}};async function o3(e){let t=nm(e,"..");await pn.mkdir(t,{recursive:!0}).catch(()=>{});let r=await(async()=>{try{return await pn.open(e,"wx")}catch(o){if(o.code!=="EEXIST")throw o;let i=null;try{let a=await pn.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 pn.unlink(e).catch(()=>{}),await pn.open(e,"wx")}throw new rm(e)}})();return await r.writeFile(String(process.pid),"utf-8"),await r.close(),async()=>{await pn.unlink(e).catch(()=>{})}}async function jn(e){let{execFile:t,repoRoot:n,maxAgeDaysClean:r=14,maxAgeDaysDirty:o=30,scope:s="all",telemetryPath:i}=e,a=i??Cr(),l=e.lockPath??XS(),c={removed:[],warnings:[],dryRun:e.dryRun??!1,candidates:[]},u=e.bypassSoftLaunch?Number.POSITIVE_INFINITY:await r3(a),d=e.dryRun===!0||u<3;c.dryRun=d;let p=null;try{p=await o3(l)}catch(m){if(m instanceof rm)return c.warnings.push(`[WARN] ${m.message}`),c;throw m}try{let m=await t("git",["-C",n,"worktree","list","--porcelain"]),g=t3(m.stdout),h=nm(n,".afk-worktrees"),b=new Set(g.map(R=>R.path)),y=[];try{y=(await pn.readdir(h,{withFileTypes:!0})).filter(k=>k.isDirectory()).map(k=>nm(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 pn.stat(R);k=Date.now()-$.birthtimeMs}catch{}if(c.candidates.push({path:R,verdict:"orphaned-dir",owner:"interactive",ageMs:k}),!d)try{await pn.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??kg,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 pn.readFile(nm(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(!L0(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 pn.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<=Q5&&(N=$0(k.pid)?"alive":"dead"),N!=="alive"&&T.some(L=>e3(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=n3(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 rw=d3(s3),F0=["interactive","diagnose","all"],om=new Set(["empty","stale-clean","orphaned-dir","orphaned-registration","dead-owner"]);async function N0(){let t=(await rw("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=l3(t)?t:u3(process.cwd(),t);return a3(n)}function p3(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 m3(e,t){return om.has(e)?f.error(t):e==="stale-dirty"?f.warning(t):e==="locked"?f.dim(t):f.dim(t)}function B0(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++,F0.includes(i)?r.scope=i:r.unknown.push(`--scope=${i}`)}else if(s.startsWith("--scope=")){let i=s.slice(8);F0.includes(i)?r.scope=i:r.unknown.push(s)}else r.unknown.push(s)}return r}async function f3(e){try{let t=await i3.readFile(c3(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 g3(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=p3(o.ageMs).padEnd(5),d=o.verdict.padEnd(22),p=om.has(o.verdict)?f.error("yes"):o.verdict==="stale-dirty"?f.warning("warn"):f.dim("no"),m=m3(o.verdict,d);e.line(`${a}${l} ${c} ${u} ${m} ${p}`)}e.line(),e.line(f.dim(" \u2192 this session")),e.line()}async function h3(e){let t=new Map;for(let n of e)t.set(n.path,await f3(n.path));return t}async function y3(e,t){let n=B0(t,"interactive");n.unknown.length>0&&e.out.warn(`Unknown args ignored: ${n.unknown.join(" ")}`);let r;try{r=await N0()}catch(i){return e.out.error(`Not in a git repository: ${i.message}`),"continue"}let o;try{let i={execFile:rw,repoRoot:r,dryRun:!0,scope:n.scope};o=await jn(i)}catch(i){return e.out.error(`Sweep failed: ${i.message}`),"continue"}let s=await h3(o.candidates);await g3(e.out,o.candidates,s);for(let i of o.warnings)e.out.warn(i);return"continue"}async function b3(e,t){let n=B0(t,"interactive");n.unknown.length>0&&e.out.warn(`Unknown args ignored: ${n.unknown.join(" ")}`);let r;try{r=await N0()}catch(a){return e.out.error(`Not in a git repository: ${a.message}`),"continue"}let o;try{let a={execFile:rw,repoRoot:r,dryRun:!n.apply,scope:n.scope};o=await jn(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=>om.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"):om.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 U0={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")?y3(e,n.replace(/^list\s*/,"")):n.startsWith("prune")?b3(e,n.replace(/^prune\s*/,"")):(e.out.error(`Unknown /worktree subcommand. Usage:
|
|
1910
1910
|
/worktree list
|
|
1911
|
-
/worktree prune [--apply] [--scope <interactive|diagnose|all>]`),"continue")}};Fs();var j0={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=
|
|
1911
|
+
/worktree prune [--apply] [--scope <interactive|diagnose|all>]`),"continue")}};Fs();var j0={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=St();if(!s)return e.out.warn("No OAuth token found. Run `claude login` in a terminal to authenticate."),"continue";let i=Pr(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=St();if(r){let s=Pr(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"):(St()?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 w3}from"node:child_process";import{promises as ow}from"node:fs";import*as H0 from"node:os";import*as W0 from"node:path";function S3(e){return new Date(e).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}function v3(e,t){let n=[f.meta(`#${t+1}`),f.dim(S3(e.timestamp))];if(e.durationMs!==void 0&&e.durationMs>0&&n.push(f.dim(ge(e.durationMs))),e.costUsd!==void 0&&e.costUsd>0&&n.push(f.dim(st(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 k3(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(`
|
|
1912
1912
|
`)[0]??"";s=i.length>80?i.slice(0,77)+"...":i}t.push(` ${r} ${o}${s?f.dim(` ${s}`):""}`)}return t.join(`
|
|
1913
1913
|
`)+`
|
|
1914
1914
|
`}function E3(e,t,n,r){let o=[];o.push(de("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(st(r))),o.push(s.join(" \xB7 ")),o.push("");for(let i=0;i<e.length;i++){let a=e[i];o.push(v3(a,i)),o.push(""),o.push(` ${f.user("\u25B6")} ${f.user("User")}`),o.push("");let l=a.user.split(`
|
|
@@ -1917,7 +1917,7 @@ ${c}`)}o.push({type:"text",text:s});let l=em(e,{skillName:"init",out:Yi(),onCanc
|
|
|
1917
1917
|
`).map(p=>` ${p}`);o.push(d.join(`
|
|
1918
1918
|
`)),o.push(""),i<e.length-1&&(o.push(de()),o.push(""))}return o.push(de()),o.join(`
|
|
1919
1919
|
`)+`
|
|
1920
|
-
`}function T3(){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 K0={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=E3(t.turns,String(t.model),t.sessionStartTime,t.totalCostUsd);if(!process.stdout.isTTY)return n.raw(r),"continue";let o=T3();if(!o)return n.raw(r),"continue";let s=W0.join(H0.tmpdir(),`afk-transcript-${Date.now()}.txt`);return await ow.writeFile(s,r,{mode:384}),new Promise(i=>{let a=w3(o.cmd,[...o.args,s],{stdio:"inherit"});a.on("error",()=>{n.raw(r),ow.unlink(s).catch(()=>{}),i("continue")}),a.on("exit",()=>{ow.unlink(s).catch(()=>{}),i("continue")})})}};q();rt();Ot();q();Je();K();cr();import{access as x3,constants as R3,mkdir as C3,readFile as A3}from"fs/promises";import{execSync as _3}from"child_process";async function I3(){return Ce()?{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 P3(){return kd()?{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 M3(){try{let t=`${_3("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 sw(e,t){let n=t();try{return await x3(n,R3.W_OK),{name:e,state:"pass",detail:n}}catch{try{return await C3(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 O3(){let e=Ut();try{let t=await A3(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 $3(){let e=KS();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 D3(){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 L3(e={}){let t;if(e.detected!==void 0)t=e.detected;else try{t=wu()}catch{return null}let n=e.trusted??Mt()??{},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 sm(){let e=[];e.push(await I3()),e.push(await P3()),e.push(await M3()),e.push(await sw("Config Directory",en)),e.push(await sw("State Directory",xe)),e.push(await sw("Logs Directory",ks)),e.push(await O3());let t=await $3();t!==null&&e.push(t);let n=await D3();n!==null&&e.push(n);let r=await L3();return r!==null&&e.push(r),e}var F3={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(de()),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(de());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"}},N3={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(de());let n;try{n=await sm()}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"}},G0=[F3,N3];Jr();In();import{readdirSync as d6,readFileSync as p6,statSync as oO}from"fs";import{join as m6}from"path";K();Jr();Lt();import{basename as H3}from"path";import{existsSync as B3,readFileSync as U3}from"fs";import{join as j3}from"path";function ts(e){let t=j3(e,".claude-plugin","plugin.json");if(!B3(t))return{name:null,version:null};try{let n=JSON.parse(U3(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 W3(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 q0(e={}){let t=e.roots??[yc(),Xe(),vs()],n=Re(e.indexPath??ce()),r=[],o=new Set;for(let s of t)for(let i of fr(s)){if(i.type!=="local")continue;let a=i.path,l=H3(a),{name:c,version:u}=ts(a),d=c??l;if(o.has(d))continue;o.add(d);let p=W3(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 z0(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}K();St();var iw=[],K3={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 G3(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 aw(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 iw=t.map(n=>{let r={name:n.name,description:n.description};return n.model&&(r.model=n.model),r}),to(G3(iw)),iw.length}function J0(){ge(K3)}gy();er();function im(e,t){for(let n of t??[])e.push({type:"image",source:{type:"base64",media_type:n.mediaType,data:n.bytes.toString("base64")}})}function V0(e,t,n,r){let o=Ap(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}),im(a,r),a}var q3=15e3;async function am(e,t){let n=em(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=V0(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>=q3){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){Uo(e.stats,o,s,a,c);try{e.ui.repaintStatusLine()}catch{}await e.transcript?.appendTurn(o,s).catch(()=>{})}return s}q();import{execFile as z3}from"child_process";import{promisify as J3}from"util";import{writeFileSync as V3}from"fs";import{join as Y3}from"path";var X3=J3(z3),Z3=4*1024*1024,lw=!1;function cw(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 Q3(e,t,n){try{let{stdout:r}=await X3(e,t,{encoding:"utf-8",...n?.cwd?{cwd:n.cwd}:{},maxBuffer:n?.maxBuffer??Z3,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
|
+
`}function T3(){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 K0={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=E3(t.turns,String(t.model),t.sessionStartTime,t.totalCostUsd);if(!process.stdout.isTTY)return n.raw(r),"continue";let o=T3();if(!o)return n.raw(r),"continue";let s=W0.join(H0.tmpdir(),`afk-transcript-${Date.now()}.txt`);return await ow.writeFile(s,r,{mode:384}),new Promise(i=>{let a=w3(o.cmd,[...o.args,s],{stdio:"inherit"});a.on("error",()=>{n.raw(r),ow.unlink(s).catch(()=>{}),i("continue")}),a.on("exit",()=>{ow.unlink(s).catch(()=>{}),i("continue")})})}};q();rt();Ot();q();Je();K();cr();import{access as x3,constants as R3,mkdir as C3,readFile as A3}from"fs/promises";import{execSync as _3}from"child_process";async function I3(){return Ce()?{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 P3(){return kd()?{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 M3(){try{let t=`${_3("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 sw(e,t){let n=t();try{return await x3(n,R3.W_OK),{name:e,state:"pass",detail:n}}catch{try{return await C3(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 O3(){let e=Ut();try{let t=await A3(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 $3(){let e=KS();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 D3(){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 L3(e={}){let t;if(e.detected!==void 0)t=e.detected;else try{t=wu()}catch{return null}let n=e.trusted??Mt()??{},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 sm(){let e=[];e.push(await I3()),e.push(await P3()),e.push(await M3()),e.push(await sw("Config Directory",en)),e.push(await sw("State Directory",xe)),e.push(await sw("Logs Directory",ks)),e.push(await O3());let t=await $3();t!==null&&e.push(t);let n=await D3();n!==null&&e.push(n);let r=await L3();return r!==null&&e.push(r),e}var F3={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(de()),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(de());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"}},N3={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(de());let n;try{n=await sm()}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"}},G0=[F3,N3];Jr();In();import{readdirSync as d6,readFileSync as p6,statSync as oO}from"fs";import{join as m6}from"path";K();Jr();Lt();import{basename as H3}from"path";import{existsSync as B3,readFileSync as U3}from"fs";import{join as j3}from"path";function ts(e){let t=j3(e,".claude-plugin","plugin.json");if(!B3(t))return{name:null,version:null};try{let n=JSON.parse(U3(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 W3(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 q0(e={}){let t=e.roots??[yc(),Xe(),vs()],n=Re(e.indexPath??ce()),r=[],o=new Set;for(let s of t)for(let i of fr(s)){if(i.type!=="local")continue;let a=i.path,l=H3(a),{name:c,version:u}=ts(a),d=c??l;if(o.has(d))continue;o.add(d);let p=W3(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 z0(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}K();vt();var iw=[],K3={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 G3(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 aw(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 iw=t.map(n=>{let r={name:n.name,description:n.description};return n.model&&(r.model=n.model),r}),to(G3(iw)),iw.length}function J0(){he(K3)}gy();er();function im(e,t){for(let n of t??[])e.push({type:"image",source:{type:"base64",media_type:n.mediaType,data:n.bytes.toString("base64")}})}function V0(e,t,n,r){let o=Ap(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}),im(a,r),a}var q3=15e3;async function am(e,t){let n=em(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=V0(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>=q3){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){Uo(e.stats,o,s,a,c);try{e.ui.repaintStatusLine()}catch{}await e.transcript?.appendTurn(o,s).catch(()=>{})}return s}q();import{execFile as z3}from"child_process";import{promisify as J3}from"util";import{writeFileSync as V3}from"fs";import{join as Y3}from"path";var X3=J3(z3),Z3=4*1024*1024,lw=!1;function cw(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 Q3(e,t,n){try{let{stdout:r}=await X3(e,t,{encoding:"utf-8",...n?.cwd?{cwd:n.cwd}:{},maxBuffer:n?.maxBuffer??Z3,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}
|
|
1921
1921
|
`)}return null}}async function e6(e,t,n={}){let r=n.exec??Q3,o=n.writeFile??((m,g)=>V3(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=Y3(t.artifactDir,`pr-${e}.diff`);try{o(m,i),c=m,u=i.trimEnd().split(`
|
|
1922
1922
|
`).length}catch{}}let d=a?a.split(`
|
|
1923
1923
|
`).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 lm(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/[\r\n]/g,"")}function t6(e){let t=[];if(t.push(`<preflight-context skill="review" pr="${e.pr}">`),e.metadata){let n=e.metadata;n.title&&t.push(`Title: ${lm(n.title)}`),n.baseRefName&&n.headRefName&&t.push(`Branch: ${lm(n.headRefName)} \u2192 ${lm(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(` - ${lm(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(`
|
|
@@ -1930,16 +1930,16 @@ ${t}`}var nO=!1;function rO(){nO||(nO=!0,uw("review",Y0),Z0())}q();var f6=new Se
|
|
|
1930
1930
|
`);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=tt(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(`
|
|
1931
1931
|
`))e.out.line(" "+" ".repeat(n)+f.dim(l))}}function dO(e,t,n){let r=g6(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(aO),a=o.filter(g=>g.main.source!=="builtin").sort(aO),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(fw).join(" \xB7 ");if(e.out.line(f.dim(` ${m} \u2014 /skills <name> for details`)),i.length>0){e.out.line(),e.out.line(de("Built-in"));for(let g of i)lO(e,g,u,d)}if(a.length>0){e.out.line(),e.out.line(i.length>0?de("Plugins & user skills"):de());for(let g of a)lO(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 h6(e,t){try{let n=Ge(e);return on(n,t)?n:void 0}catch{return}}function y6(e,t){let n=[];for(let r of rg(t))if(r.includes(":")&&Hn(r)===e){let o=gw(Ge(r).origin);n.push({slash:`/${r}`,source:o})}for(let r of os.collisions)r.bare===e&&n.push({slash:r.altSlash,source:"plugin"});return n}function pO(e,t,n,r){let o=t.replace(/^\//,"").trim(),s=h6(o,r),i=n.find(y=>Hn(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??Hn(i.name),l=s?.description??i.description,c=s?.argumentHint??i?.argumentHint,u=c?`/${a} ${c}`:`/${a}`,d=s?gw(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(`
|
|
1932
1932
|
`))e.out.line(` ${y}`);let g=s?.whenToUse??uO(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(`
|
|
1933
|
-
`))e.out.line(` ${f.dim(y)}`)}let h=s?.flags??cO().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(fw(d))}`);let b=y6(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(`(${fw(y.source)} \u2014 shadowed by /${a})`)}`)}e.out.line()}var b6={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("-")?pO(e,r,[],n):dO(e,[],n),"continue"}};function w6(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("-")?pO(t,o,e,r):dO(t,e,r),"continue"}}}async function mO(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=cO(),o=v.AFK_INTERNAL==="1",s=new Set(Zn().filter(l=>on(Ge(l),o)).map(Hn)),i=[],a=new Set;for(let l of n){let c=`/${l.name}`;if(f6.has(c))continue;let u=Hn(l.name),d=r.get(u);if(s.has(u)){let p=l.name.includes(":")?l.name:`plugin:${l.name}`,m={...l,name:p};to(iO(m,d)),i.push({bare:u,altSlash:`/${p}`,altDescription:l.description}),a.add(u);continue}to(iO(l,d))}return os={discovered:n,collisions:i,shadowedBareNames:a},to(w6(n)),n.length}function fO(){return os.collisions.length===0?[]:os.collisions.map(e=>f.dim(` /${e.bare}: vendored or user skill wins; plugin form ${e.altSlash} stays reachable.`))}async function um(e){let[t,n]=await Promise.all([mO(e),aw(e)]);return{skillCount:t,agentCount:n}}function S6(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 v6(e,t){return e.size===0?null:{added:[...t].filter(n=>!e.has(n)).sort(),removed:[...e].filter(n=>!t.has(n)).sort()}}function k6(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 E6(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)} ${z0(s)}`));return e.length>t&&o.push(f.dim(` \u2026and ${e.length-t} more`)),o}var T6={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(os.discovered.map(a=>a.name));mr();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([mO(e.session.current),aw(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=q0(),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=S6(pr()),l=v6(t,new Set(os.discovered.map(d=>d.name))),c=l?k6(l):"",u=[a,c].filter(d=>d.length>0);u.length>0&&e.out.line(f.dim(` ${u.join(" \xB7 ")}`))}for(let a of E6(o))e.out.line(a);return e.out.line(),"continue"}};function gO(){
|
|
1933
|
+
`))e.out.line(` ${f.dim(y)}`)}let h=s?.flags??cO().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(fw(d))}`);let b=y6(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(`(${fw(y.source)} \u2014 shadowed by /${a})`)}`)}e.out.line()}var b6={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("-")?pO(e,r,[],n):dO(e,[],n),"continue"}};function w6(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("-")?pO(t,o,e,r):dO(t,e,r),"continue"}}}async function mO(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=cO(),o=v.AFK_INTERNAL==="1",s=new Set(Zn().filter(l=>on(Ge(l),o)).map(Hn)),i=[],a=new Set;for(let l of n){let c=`/${l.name}`;if(f6.has(c))continue;let u=Hn(l.name),d=r.get(u);if(s.has(u)){let p=l.name.includes(":")?l.name:`plugin:${l.name}`,m={...l,name:p};to(iO(m,d)),i.push({bare:u,altSlash:`/${p}`,altDescription:l.description}),a.add(u);continue}to(iO(l,d))}return os={discovered:n,collisions:i,shadowedBareNames:a},to(w6(n)),n.length}function fO(){return os.collisions.length===0?[]:os.collisions.map(e=>f.dim(` /${e.bare}: vendored or user skill wins; plugin form ${e.altSlash} stays reachable.`))}async function um(e){let[t,n]=await Promise.all([mO(e),aw(e)]);return{skillCount:t,agentCount:n}}function S6(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 v6(e,t){return e.size===0?null:{added:[...t].filter(n=>!e.has(n)).sort(),removed:[...e].filter(n=>!t.has(n)).sort()}}function k6(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 E6(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)} ${z0(s)}`));return e.length>t&&o.push(f.dim(` \u2026and ${e.length-t} more`)),o}var T6={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(os.discovered.map(a=>a.name));mr();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([mO(e.session.current),aw(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=q0(),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=S6(pr()),l=v6(t,new Set(os.discovered.map(d=>d.name))),c=l?k6(l):"",u=[a,c].filter(d=>d.length>0);u.length>0&&e.out.line(f.dim(` ${u.join(" \xB7 ")}`))}for(let a of E6(o))e.out.line(a);return e.out.line(),"continue"}};function gO(){he(b6),he(T6)}vt();by();cr();K();q();function x6(e){let t=e??"builtin";return t==="builtin"||t==="user"||t==="project"?t:t.startsWith("imported:")?"imported":"user"}function R6(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 am(r,{skillName:e.name,skillMeta:e,args:o,attachments:s,preflight:async()=>{let i={skillName:e.name,rawArgs:o,source:x6(e.origin),capabilities:{compose:!0,subagents:!0}},a=r.session.current.sessionId,l=rs(a);return(await ns(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 hO(){rO(),hy(),yr(hc(),"project");for(let{dir:t,origin:n}of sn(Mt()).skillRoots)yr(t,n);let e=v.AFK_INTERNAL==="1";for(let t of Zn()){let n=Ge(t);on(n,e)&&to(R6(n))}}K();import{existsSync as ql,mkdirSync as aX,renameSync as lX,rmSync as cX,symlinkSync as uX,lstatSync as dX,unlinkSync as pX}from"fs";import{basename as mX,join as vw}from"path";K();import{existsSync as co,mkdirSync as H6,readFileSync as W6,realpathSync as vO,renameSync as K6,rmSync as G6,symlinkSync as q6,lstatSync as z6,unlinkSync as J6}from"fs";import{basename as kO,dirname as V6,join as is,resolve as yw,relative as Y6}from"path";import{existsSync as yO}from"fs";import{isAbsolute as C6,resolve as SO}from"path";import{homedir as bO}from"os";var A6=/^(?:https?:\/\/|git:\/\/|ssh:\/\/|git\+ssh:\/\/|file:\/\/|git@[^:]+:)/,_6=/^([a-zA-Z0-9][a-zA-Z0-9_.-]*)\/([a-zA-Z0-9][a-zA-Z0-9._-]*?)(?:\.git)?$/,I6=/^([a-zA-Z0-9][a-zA-Z0-9_.-]*):([a-zA-Z0-9][a-zA-Z0-9_.-]*)$/;function P6(e){return e==="~"?bO():e.startsWith("~/")?SO(bO(),e.slice(2)):e}function dm(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 Zi(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(M6(t)){let o=wO(t);if(!yO(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(A6.test(t))return{type:"git",url:t};let n=I6.exec(t);if(n&&n[1]&&n[2])return{type:"marketplace-ref",marketplace:n[1],plugin:n[2]};let r=_6.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(yO(t))return{type:"local",path:wO(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 M6(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("~")||e.startsWith("/")}function wO(e){let t=P6(e);return C6(t)?t:SO(process.cwd(),t)}import{execFile as O6}from"child_process";import{promisify as $6}from"util";var D6=$6(O6),ss=async(e,t,n)=>{try{let{stdout:r,stderr:o}=await D6("git",Array.from(e),{cwd:t,env:n,maxBuffer:20971520});return{stdout:r,stderr:o}}catch(r){throw L6(r)&&r.code==="ENOENT"?new Error("git not found on PATH \u2014 install git first"):r}};function L6(e){return typeof e=="object"&&e!==null&&"code"in e}var F6=Object.freeze(["-c","core.hooksPath=/dev/null","-c","filter.process=","-c","filter.smudge=","-c","filter.clean="]);function hw(e){return[...F6,...e]}async function pm(e,t,n={}){await(n.runner??ss)(hw(["clone","--",e,t]),void 0,n.env)}async function mm(e,t={}){await(t.runner??ss)(hw(["fetch","--tags","--prune"]),e,t.env)}async function io(e,t={}){let n=t.runner??ss,{stdout:r}=await n(["tag","--list","--sort=-v:refname"],e,t.env);return r.split(`
|
|
1934
1934
|
`).map(o=>o.trim()).filter(Boolean)}async function ao(e,t,n={}){let r=n.runner??ss,o=["checkout","--detach"];n.force&&o.push("--force"),o.push(t),await r(hw(o),e,n.env)}async function Wn(e,t={}){let n=t.runner??ss,{stdout:r}=await n(["rev-parse","HEAD"],e,t.env);return r.trim()}async function fm(e,t,n={}){let r=n.runner??ss;try{let{stdout:o}=await r(["rev-parse","--verify","--quiet",t],e,n.env);return o.trim()||null}catch{return null}}async function Kn(e,t={}){let n=t.runner??ss;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"}}Lt();var N6=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function B6(e){let t=N6.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 U6(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 j6(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:U6(e.prerelease,t.prerelease)}function lo(e){let t=e.map(n=>B6(n.trim())).filter(n=>n!==null);return t.length===0?null:(t.sort((n,r)=>j6(r,n)),t[0]?.raw??null)}Jr();async function ym(e,t={},n={}){let r=n.pluginsDir??Xe(),o=n.indexPath??ce(),s=n.now??(()=>new Date),i=n.gitRunner?{runner:n.gitRunner}:{},a=n.confirm??!0,l=n.confirmDelayMs??3e3,c=Zi(e);if(H6(r,{recursive:!0}),c.type==="local")return X6(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 dm(c.url),Z6(c,t,r,o,s,i,{confirm:a,confirmDelayMs:l})}function X6(e,t,n,r,o){EO(e.path);let s=TO(e.path),i=t.name??s??kO(e.path);Er(i);let a=is(n,i);as(a,n),bw(a,t.force??!1),(co(a)||ww(a))&&hm(a),q6(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 zr(i,c,r),mr(),{name:i,dir:a,entry:c}}async function Z6(e,t,n,r,o,s,i){let a=t.name??eX(e);Er(a);let l=is(n,a);as(l,n),bw(l,t.force??!1),co(l)&&hm(l);let c=e.type==="github"?`${e.owner}/${e.repo}`:e.url;i.confirm&&await tX(e.url,i.confirmDelayMs),await pm(e.url,l,s);try{let u;if(t.ref)u=t.ref;else{let y=await io(l,s);u=lo(y)??await Kn(l,s)}(t.ref||await Q6(l,u,s))&&await ao(l,u,s);let d=await Wn(l,s);EO(l);let p=TO(l),m=a,g=l;if(!t.name&&p&&p!==a){Er(p);let y=is(n,p);as(y,n),bw(y,t.force??!1),co(y)&&hm(y),K6(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 zr(m,b,r),mr(),{name:m,dir:g,entry:b}}catch(u){try{co(l)&&hm(l)}catch{}throw u}}async function Q6(e,t,n){let r=await Kn(e,n);return t!==r}function eX(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 tX(e,t){let n="\u2550".repeat(70),r=o=>process.stderr.write(o+`
|
|
1935
|
-
`);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 EO(e){let t=is(e,".claude-plugin","plugin.json");if(co(t))return;let n=is(e,".claude-plugin","marketplace.json");if(co(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 TO(e){let t=is(e,".claude-plugin","plugin.json");if(!co(t))return null;try{let n=JSON.parse(W6(t,"utf8"));return typeof n.name=="string"&&n.name.trim()?n.name.trim():null}catch{return null}}var nX=/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;function Er(e){if(!e||e.length>100||!nX.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 as(e,t){let n;try{n=vO(yw(t))}catch{n=yw(t)}let r=yw(e),o;try{o=is(vO(V6(r)),kO(r))}catch{o=r}let s=Y6(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 bw(e,t){if(!(!co(e)&&!ww(e))&&!t)throw new Error(`plugin directory already exists: ${e} (re-run with --force to replace)`)}function ww(e){try{return z6(e).isSymbolicLink()}catch{return!1}}function hm(e){if(ww(e)){J6(e);return}G6(e,{recursive:!0,force:!0})}Lt();import{existsSync as RO,readFileSync as rX}from"fs";import{join as oX}from"path";var sX=".claude-plugin/marketplace.json";function CO(e){return oX(e,sX)}function Sw(e){return RO(CO(e))}function Tr(e){let t=CO(e);if(!RO(t))throw new Error(`marketplace manifest not found: ${t}`);let n;try{n=rX(t,"utf8")}catch(o){throw new Error(`could not read marketplace manifest at ${t}: ${xO(o)}`)}let r;try{r=JSON.parse(n)}catch(o){throw new Error(`marketplace manifest at ${t} is not valid JSON: ${xO(o)}`)}return iX(r,t)}function AO(e){try{return Tr(e)}catch{return null}}function iX(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 xO(e){return e instanceof Error?e.message:String(e)}async function wm(e,t={},n={}){let r=n.cacheDir??zn(),o=n.indexPath??ce(),s=n.now??(()=>new Date),i=n.gitRunner?{runner:n.gitRunner}:{},a=Zi(e);if(a.type==="marketplace-ref")throw new Error(`marketplace source cannot itself be a marketplace reference ("${e}")`);return aX(r,{recursive:!0}),a.type==="local"?fX(a,t,r,o,s):gX(a,t,r,o,s,i)}function fX(e,t,n,r,o){let s=Tr(e.path),i=t.name??s.name;Er(i);let a=vw(n,i);as(a,n),kw(a,t.force??!1),(ql(a)||Ew(a))&&bm(a),uX(e.path,a,"dir");let l=o().toISOString(),c={source:e.path,sourceType:"local",ref:null,commit:null,installedAt:l,updatedAt:l};return cl(i,c,r),{name:i,dir:a,entry:c,plugins:s.plugins.map(_O)}}async function gX(e,t,n,r,o,s){dm(e.url);let i=t.name??yX(e);Er(i);let a=vw(n,i);as(a,n),kw(a,t.force??!1),ql(a)&&bm(a);let l=e.type==="github"?`${e.owner}/${e.repo}`:e.url;await pm(e.url,a,s);try{let c;if(t.ref)c=t.ref;else{let b=await io(a,s);c=lo(b)??await Kn(a,s)}(t.ref||await hX(a,c,s))&&await ao(a,c,s);let u=await Wn(a,s),d=Tr(a),p=i,m=a;if(!t.name&&d.name!==i){Er(d.name);let b=vw(n,d.name);as(b,n),kw(b,t.force??!1),ql(b)&&bm(b),lX(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 cl(p,h,r),{name:p,dir:m,entry:h,plugins:d.plugins.map(_O)}}catch(c){try{ql(a)&&bm(a)}catch{}throw c}}async function hX(e,t,n){let r=await Kn(e,n);return t!==r}function yX(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):mX(t)}function kw(e,t){if(!(!ql(e)&&!Ew(e))&&!t)throw new Error(`marketplace directory already exists: ${e} (re-run with --force to replace)`)}function Ew(e){try{return dX(e).isSymbolicLink()}catch{return!1}}function bm(e){if(Ew(e)){pX(e);return}cX(e,{recursive:!0,force:!0})}function _O(e){return e.description?{name:e.name,description:e.description}:{name:e.name}}K();Lt();import{existsSync as bX,lstatSync as wX,rmSync as SX,unlinkSync as vX}from"fs";import{join as kX}from"path";function Sm(e,t={}){let n=t.cacheDir??zn(),r=t.indexPath??ce(),o=kX(n,e),s=!1;EX(o)?(vX(o),s=!0):bX(o)&&(SX(o,{recursive:!0,force:!0}),s=!0);let i=Re(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)&&bR(e,r),{name:e,removedDir:s,removedIndexEntry:a,removedPluginEntries:l}}function EX(e){try{return wX(e).isSymbolicLink()}catch{return!1}}K();import{existsSync as IX}from"fs";import{join as PX}from"path";Lt();q();K();Lt();import{existsSync as vm,statSync as TX}from"fs";import{isAbsolute as IO,join as xX,resolve as PO}from"path";async function Qi(e,t,n={},r={}){let o=r.marketplaceDirFor??wa,s=r.indexPath??ce(),i=r.now??(()=>new Date),a=o(e);if(!vm(a)||!Sw(a))throw new Error(`marketplace "${e}" is not installed (looked for manifest under ${a})`);let l=Tr(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 RX(c.source)?CX(e,c,a,s,i,n):AX(e,c,n,r)}function km(e,t={}){let n=t.marketplaceDirFor??wa,r=t.indexPath??ce(),o=n(e);if(!vm(o)||!Sw(o))throw new Error(`marketplace "${e}" is not installed`);let s=Tr(o),i=Re(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 RX(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.startsWith("~")}function MO(e){return e.startsWith(".")||IO(e)||e.startsWith("~")}function Tw(e,t){return IO(t)||t.startsWith("~")?_X(t):PO(e,t)}function CX(e,t,n,r,o,s){let i=t.source,a=Tw(n,i);if(!vm(a))throw new Error(`marketplace "${e}" lists plugin "${t.name}" at ${a}, but that path does not exist on disk`);if(!TX(a).isDirectory())throw new Error(`marketplace "${e}" lists plugin "${t.name}" at ${a}, but that path is not a directory`);let c=xX(a,".claude-plugin","plugin.json");if(!vm(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=Re(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 zr(u,m,r),{key:u,name:t.name,dir:a,entry:m}}async function AX(e,t,n,r){let o={name:t.name,...n.ref?{ref:n.ref}:{},...n.force?{force:!0}:{}},s=await ym(t.source,o,r),i=r.indexPath??ce(),a={...s.entry,marketplace:e};return zr(s.name,a,i),{key:s.name,name:s.name,dir:s.dir,entry:a}}function _X(e){if(e.startsWith("~")){let t=v.HOME??"";if(e==="~")return t;if(e.startsWith("~/"))return PO(t,e.slice(2))}return e}async function zl(e,t={},n={}){let r=n.indexPath??ce(),o=n.now??(()=>new Date),s=n.gitRunner?{runner:n.gitRunner}:{},a=Re(r).marketplaces[e];if(!a)throw new Error(`marketplace "${e}" is not installed`);let l=n.cacheDir?PX(n.cacheDir,e):wa(e);if(!IX(l))return{name:e,status:"missing-dir",dir:l};if(a.sourceType==="local")return{name:e,status:"skipped-local"};let c=new Set((AO(l)?.plugins??[]).map(k=>k.name));await mm(l,s);let u,d=!1;if(t.ref)u=t.ref;else{let k=await io(l,s),$=lo(k);$!==null?(u=$,d=!0):u=a.ref??await Kn(l,s)}let p=`refs/remotes/origin/${u}`,m=d?null:await fm(l,p,s),g=m!==null,h=await Wn(l,s);if(g?m===h:u===a.ref)return{name:e,status:"up-to-date",ref:u,commit:h};await ao(l,g?p:d?`refs/tags/${u}`:u,{...s,force:!0});let y=await Wn(l,s),S=o().toISOString(),w={...a,ref:u,commit:y,updatedAt:S};cl(e,w,r);let T=Tr(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:MX(l,T)}}function MX(e,t){return t.plugins.map(n=>{let r=MO(n.source)?ts(Tw(e,n.source)).version:null;return{name:n.name,version:r}})}async function OO(e={}){let t=e.indexPath??ce(),n=Re(t),r=[];for(let o of Object.keys(n.marketplaces))try{r.push(await zl(o,{},e))}catch(s){let i=s instanceof Error?s.message:String(s);r.push({name:o,status:"missing-dir",dir:i})}return r}Lt();var OX=["install","install-plugin","plugins","remove","update","list","add"],$X={name:"/marketplaces",summary:"List installed plugin marketplaces",async handler(e){return LO(e),"continue"}},DX={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 LX(e),"continue";let[r,...o]=n.split(/\s+/);if(!r||!OX.includes(r))return e.out.error(`Unknown subcommand "${r??""}". Try one of: install, install-plugin, plugins, remove, update.`),"continue";switch(r){case"install":return FX(e,o);case"install-plugin":return BX(e,o);case"plugins":return jX(e,o);case"remove":return HX(e,o);case"update":return WX(e,o);case"list":return LO(e),"continue";case"add":return UX(e,o);default:return"continue"}}};function DO(){ge($X),ge(DX)}function LO(e){let t=Re(),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 LX(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 FO(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=KX(o);e.out.info(`Installing marketplace ${n}\u2026`);try{let i=await wm(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: ${Em(i)}`)}return"continue"}async function FX(e,t){return t.length===1&&NX(t[0])||t.length>=2?$O(e,t):FO(e,t)}function NX(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."),NO(e,t)}async function BX(e,t){return NO(e,t)}async function NO(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 Qi(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: ${Em(o)}`)}return"continue"}async function UX(e,t){return e.out.warn("Deprecated: use `/marketplace install <source>` instead."),FO(e,t)}function jX(e,t){let n=t[0];if(!n)return e.out.error("Usage: /marketplace plugins <marketplace>"),"continue";try{let r=km(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: ${Em(r)}`)}return"continue"}function HX(e,t){let n=t[0];if(!n)return e.out.error("Usage: /marketplace remove <marketplace>"),"continue";let r=Sm(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 WX(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 zl(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: ${Em(r)}`)}return"continue"}function KX(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 Em(e){return e instanceof Error?e.message:String(e)}x0("shadow-verify",{glyph:"\u25C8",color:"#7B5EA7",inFlightVerb:"verifying\u2026"});function BO(){MI();for(let e of FI)ge(e);for(let e of NI)ge(e);ge(BI),ge(rP),ge(mP),ge(fP),ge(gP),ge(hP),ge(SP),ge(RP);for(let e of IP)ge(e);ge(OP),ge(E0),ge(A0),ge(_0),ge(P0),ge(U0),ge(j0),ge(K0);for(let e of G0)ge(e);hO(),PI(O0),gO(),J0(),DO()}function UO(e,t={}){if(!e.isTTY)return{writeLine:o=>{e.write(o+`
|
|
1935
|
+
`);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 EO(e){let t=is(e,".claude-plugin","plugin.json");if(co(t))return;let n=is(e,".claude-plugin","marketplace.json");if(co(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 TO(e){let t=is(e,".claude-plugin","plugin.json");if(!co(t))return null;try{let n=JSON.parse(W6(t,"utf8"));return typeof n.name=="string"&&n.name.trim()?n.name.trim():null}catch{return null}}var nX=/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;function Er(e){if(!e||e.length>100||!nX.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 as(e,t){let n;try{n=vO(yw(t))}catch{n=yw(t)}let r=yw(e),o;try{o=is(vO(V6(r)),kO(r))}catch{o=r}let s=Y6(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 bw(e,t){if(!(!co(e)&&!ww(e))&&!t)throw new Error(`plugin directory already exists: ${e} (re-run with --force to replace)`)}function ww(e){try{return z6(e).isSymbolicLink()}catch{return!1}}function hm(e){if(ww(e)){J6(e);return}G6(e,{recursive:!0,force:!0})}Lt();import{existsSync as RO,readFileSync as rX}from"fs";import{join as oX}from"path";var sX=".claude-plugin/marketplace.json";function CO(e){return oX(e,sX)}function Sw(e){return RO(CO(e))}function Tr(e){let t=CO(e);if(!RO(t))throw new Error(`marketplace manifest not found: ${t}`);let n;try{n=rX(t,"utf8")}catch(o){throw new Error(`could not read marketplace manifest at ${t}: ${xO(o)}`)}let r;try{r=JSON.parse(n)}catch(o){throw new Error(`marketplace manifest at ${t} is not valid JSON: ${xO(o)}`)}return iX(r,t)}function AO(e){try{return Tr(e)}catch{return null}}function iX(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 xO(e){return e instanceof Error?e.message:String(e)}async function wm(e,t={},n={}){let r=n.cacheDir??zn(),o=n.indexPath??ce(),s=n.now??(()=>new Date),i=n.gitRunner?{runner:n.gitRunner}:{},a=Zi(e);if(a.type==="marketplace-ref")throw new Error(`marketplace source cannot itself be a marketplace reference ("${e}")`);return aX(r,{recursive:!0}),a.type==="local"?fX(a,t,r,o,s):gX(a,t,r,o,s,i)}function fX(e,t,n,r,o){let s=Tr(e.path),i=t.name??s.name;Er(i);let a=vw(n,i);as(a,n),kw(a,t.force??!1),(ql(a)||Ew(a))&&bm(a),uX(e.path,a,"dir");let l=o().toISOString(),c={source:e.path,sourceType:"local",ref:null,commit:null,installedAt:l,updatedAt:l};return cl(i,c,r),{name:i,dir:a,entry:c,plugins:s.plugins.map(_O)}}async function gX(e,t,n,r,o,s){dm(e.url);let i=t.name??yX(e);Er(i);let a=vw(n,i);as(a,n),kw(a,t.force??!1),ql(a)&&bm(a);let l=e.type==="github"?`${e.owner}/${e.repo}`:e.url;await pm(e.url,a,s);try{let c;if(t.ref)c=t.ref;else{let b=await io(a,s);c=lo(b)??await Kn(a,s)}(t.ref||await hX(a,c,s))&&await ao(a,c,s);let u=await Wn(a,s),d=Tr(a),p=i,m=a;if(!t.name&&d.name!==i){Er(d.name);let b=vw(n,d.name);as(b,n),kw(b,t.force??!1),ql(b)&&bm(b),lX(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 cl(p,h,r),{name:p,dir:m,entry:h,plugins:d.plugins.map(_O)}}catch(c){try{ql(a)&&bm(a)}catch{}throw c}}async function hX(e,t,n){let r=await Kn(e,n);return t!==r}function yX(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):mX(t)}function kw(e,t){if(!(!ql(e)&&!Ew(e))&&!t)throw new Error(`marketplace directory already exists: ${e} (re-run with --force to replace)`)}function Ew(e){try{return dX(e).isSymbolicLink()}catch{return!1}}function bm(e){if(Ew(e)){pX(e);return}cX(e,{recursive:!0,force:!0})}function _O(e){return e.description?{name:e.name,description:e.description}:{name:e.name}}K();Lt();import{existsSync as bX,lstatSync as wX,rmSync as SX,unlinkSync as vX}from"fs";import{join as kX}from"path";function Sm(e,t={}){let n=t.cacheDir??zn(),r=t.indexPath??ce(),o=kX(n,e),s=!1;EX(o)?(vX(o),s=!0):bX(o)&&(SX(o,{recursive:!0,force:!0}),s=!0);let i=Re(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)&&bR(e,r),{name:e,removedDir:s,removedIndexEntry:a,removedPluginEntries:l}}function EX(e){try{return wX(e).isSymbolicLink()}catch{return!1}}K();import{existsSync as IX}from"fs";import{join as PX}from"path";Lt();q();K();Lt();import{existsSync as vm,statSync as TX}from"fs";import{isAbsolute as IO,join as xX,resolve as PO}from"path";async function Qi(e,t,n={},r={}){let o=r.marketplaceDirFor??wa,s=r.indexPath??ce(),i=r.now??(()=>new Date),a=o(e);if(!vm(a)||!Sw(a))throw new Error(`marketplace "${e}" is not installed (looked for manifest under ${a})`);let l=Tr(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 RX(c.source)?CX(e,c,a,s,i,n):AX(e,c,n,r)}function km(e,t={}){let n=t.marketplaceDirFor??wa,r=t.indexPath??ce(),o=n(e);if(!vm(o)||!Sw(o))throw new Error(`marketplace "${e}" is not installed`);let s=Tr(o),i=Re(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 RX(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.startsWith("~")}function MO(e){return e.startsWith(".")||IO(e)||e.startsWith("~")}function Tw(e,t){return IO(t)||t.startsWith("~")?_X(t):PO(e,t)}function CX(e,t,n,r,o,s){let i=t.source,a=Tw(n,i);if(!vm(a))throw new Error(`marketplace "${e}" lists plugin "${t.name}" at ${a}, but that path does not exist on disk`);if(!TX(a).isDirectory())throw new Error(`marketplace "${e}" lists plugin "${t.name}" at ${a}, but that path is not a directory`);let c=xX(a,".claude-plugin","plugin.json");if(!vm(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=Re(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 zr(u,m,r),{key:u,name:t.name,dir:a,entry:m}}async function AX(e,t,n,r){let o={name:t.name,...n.ref?{ref:n.ref}:{},...n.force?{force:!0}:{}},s=await ym(t.source,o,r),i=r.indexPath??ce(),a={...s.entry,marketplace:e};return zr(s.name,a,i),{key:s.name,name:s.name,dir:s.dir,entry:a}}function _X(e){if(e.startsWith("~")){let t=v.HOME??"";if(e==="~")return t;if(e.startsWith("~/"))return PO(t,e.slice(2))}return e}async function zl(e,t={},n={}){let r=n.indexPath??ce(),o=n.now??(()=>new Date),s=n.gitRunner?{runner:n.gitRunner}:{},a=Re(r).marketplaces[e];if(!a)throw new Error(`marketplace "${e}" is not installed`);let l=n.cacheDir?PX(n.cacheDir,e):wa(e);if(!IX(l))return{name:e,status:"missing-dir",dir:l};if(a.sourceType==="local")return{name:e,status:"skipped-local"};let c=new Set((AO(l)?.plugins??[]).map(k=>k.name));await mm(l,s);let u,d=!1;if(t.ref)u=t.ref;else{let k=await io(l,s),$=lo(k);$!==null?(u=$,d=!0):u=a.ref??await Kn(l,s)}let p=`refs/remotes/origin/${u}`,m=d?null:await fm(l,p,s),g=m!==null,h=await Wn(l,s);if(g?m===h:u===a.ref)return{name:e,status:"up-to-date",ref:u,commit:h};await ao(l,g?p:d?`refs/tags/${u}`:u,{...s,force:!0});let y=await Wn(l,s),S=o().toISOString(),w={...a,ref:u,commit:y,updatedAt:S};cl(e,w,r);let T=Tr(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:MX(l,T)}}function MX(e,t){return t.plugins.map(n=>{let r=MO(n.source)?ts(Tw(e,n.source)).version:null;return{name:n.name,version:r}})}async function OO(e={}){let t=e.indexPath??ce(),n=Re(t),r=[];for(let o of Object.keys(n.marketplaces))try{r.push(await zl(o,{},e))}catch(s){let i=s instanceof Error?s.message:String(s);r.push({name:o,status:"missing-dir",dir:i})}return r}Lt();var OX=["install","install-plugin","plugins","remove","update","list","add"],$X={name:"/marketplaces",summary:"List installed plugin marketplaces",async handler(e){return LO(e),"continue"}},DX={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 LX(e),"continue";let[r,...o]=n.split(/\s+/);if(!r||!OX.includes(r))return e.out.error(`Unknown subcommand "${r??""}". Try one of: install, install-plugin, plugins, remove, update.`),"continue";switch(r){case"install":return FX(e,o);case"install-plugin":return BX(e,o);case"plugins":return jX(e,o);case"remove":return HX(e,o);case"update":return WX(e,o);case"list":return LO(e),"continue";case"add":return UX(e,o);default:return"continue"}}};function DO(){he($X),he(DX)}function LO(e){let t=Re(),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 LX(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 FO(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=KX(o);e.out.info(`Installing marketplace ${n}\u2026`);try{let i=await wm(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: ${Em(i)}`)}return"continue"}async function FX(e,t){return t.length===1&&NX(t[0])||t.length>=2?$O(e,t):FO(e,t)}function NX(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."),NO(e,t)}async function BX(e,t){return NO(e,t)}async function NO(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 Qi(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: ${Em(o)}`)}return"continue"}async function UX(e,t){return e.out.warn("Deprecated: use `/marketplace install <source>` instead."),FO(e,t)}function jX(e,t){let n=t[0];if(!n)return e.out.error("Usage: /marketplace plugins <marketplace>"),"continue";try{let r=km(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: ${Em(r)}`)}return"continue"}function HX(e,t){let n=t[0];if(!n)return e.out.error("Usage: /marketplace remove <marketplace>"),"continue";let r=Sm(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 WX(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 zl(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: ${Em(r)}`)}return"continue"}function KX(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 Em(e){return e instanceof Error?e.message:String(e)}x0("shadow-verify",{glyph:"\u25C8",color:"#7B5EA7",inFlightVerb:"verifying\u2026"});function BO(){MI();for(let e of FI)he(e);for(let e of NI)he(e);he(BI),he(rP),he(mP),he(fP),he(gP),he(hP),he(SP),he(RP);for(let e of IP)he(e);he(OP),he(E0),he(A0),he(_0),he(P0),he(U0),he(j0),he(K0);for(let e of G0)he(e);hO(),PI(O0),gO(),J0(),DO()}function UO(e,t={}){if(!e.isTTY)return{writeLine:o=>{e.write(o+`
|
|
1936
1936
|
`)},setCompositor:()=>{}};let n=null,r=t.statusLine;return{writeLine(o){if(n?.isArmed()){n.commitAbove(o);return}r?r.withFullScrollRegion(()=>{e.write(o+`
|
|
1937
1937
|
`)}):e.write(o+`
|
|
1938
1938
|
`)},setCompositor(o){n=o}}}var Tm=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}};Kh();var xm=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=GX(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 GX(e){return e?e.input_tokens+e.output_tokens+e.cache_creation_input_tokens+e.cache_read_input_tokens:0}Qe();il();Nh();Me();Uc();var qX="claude-haiku-4-5",zX=15e3,JX=1e3,VX=80,YX=200,XX=3e3,ZX='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 QX(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 Rm=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??qX,this.intervalMs=t.intervalMs??zX,this.maxInputTokens=t.maxInputTokens??JX,this.maxOutputTokens=t.maxOutputTokens??VX,this.maxCallsPerSession=t.maxCallsPerSession??YX,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:ZX,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)*XX%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:
|
|
1939
1939
|
<transcript>
|
|
1940
1940
|
${QX(i)}
|
|
1941
|
-
</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--}}};al();qr();No();rt();function jO(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}}En();In();xn();cr();Ue();function xw(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 Jl(e,t,n){let r=n instanceof Error?n.message:String(n);e.fn(f.warning(`\u26A0 [resume-swap] ${t}: ${xw(r)}`))}async function HO(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: ${xw(a)}`}}let r;if(!await n.waitForInitialization().then(()=>!0,i=>(r=xw(i instanceof Error?i.message:String(i)),!1))){await n.close().catch(a=>{Jl(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=>{Jl(t.completionWriter,"cancelAll failed",i)}),await t.sessionRef.current.close().catch(i=>{Jl(t.completionWriter,"session close failed",i)}),t.sessionRef.current=n,e.stored?(yp(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){Jl(t.completionWriter,"onSwapped callback threw",i)}t.contextSampler.attach(n),await um(n).catch(i=>{Jl(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(st(t.stats.totalCostUsd)),t.stats.totalTokens>0&&s.push(ie(t.stats.totalTokens)+" tokens"),t.completionWriter.fn(f.brand(s.join(" \xB7 "))),bp(t.stats,t.completionWriter),t.statusLine.repaint(Bn(t.stats,t.contextSampler,t.gitStatusSampler)),{ok:!0,sessionId:n.sessionId??t.stats.sessionId??e.resumeId}}function WO(e){return new
|
|
1942
|
-
`)},pendingCount:()=>ct.pendingCount(),suspendInput:()=>Sf.current?.suspendForElicitation(),resumeInput:()=>Sf.current?.resumeAfterElicitation()})),ve.requestResume=Pe,Le(w?.writer,{phase:"bootstrap_done",durationMs:Date.now()-n}),
|
|
1941
|
+
</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--}}};al();qr();No();rt();function jO(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}}En();In();xn();cr();Ue();function xw(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 Jl(e,t,n){let r=n instanceof Error?n.message:String(n);e.fn(f.warning(`\u26A0 [resume-swap] ${t}: ${xw(r)}`))}async function HO(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: ${xw(a)}`}}let r;if(!await n.waitForInitialization().then(()=>!0,i=>(r=xw(i instanceof Error?i.message:String(i)),!1))){await n.close().catch(a=>{Jl(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=>{Jl(t.completionWriter,"cancelAll failed",i)}),await t.sessionRef.current.close().catch(i=>{Jl(t.completionWriter,"session close failed",i)}),t.sessionRef.current=n,e.stored?(yp(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){Jl(t.completionWriter,"onSwapped callback threw",i)}t.contextSampler.attach(n),await um(n).catch(i=>{Jl(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(st(t.stats.totalCostUsd)),t.stats.totalTokens>0&&s.push(ie(t.stats.totalTokens)+" tokens"),t.completionWriter.fn(f.brand(s.join(" \xB7 "))),bp(t.stats,t.completionWriter),t.statusLine.repaint(Bn(t.stats,t.contextSampler,t.gitStatusSampler)),{ok:!0,sessionId:n.sessionId??t.stats.sessionId??e.resumeId}}function WO(e){return new kt(dr({model:e.model,surface:"cli",apiKey:ze(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 GO(e,t){let n=Date.now(),r=_i(e),o=Ii(r),s=r?.stored?.model??e.model,i=Ds(s);if(i)throw new Error(i);let a,l,c;a=Yr(e.thinking)??pi(),l=Xr(e.effort)??mi(),c=gi(e.maxOutputTokens)??ul();let{prompt:u,source:d}=di(),p=_t(),m=p.autoRouting?.interactive??!0,g=Hd(u,m,"repl",k_()),h={current:null},b=Ce(),y=new se({apiKey:b,...p.baseUrl!==void 0?{baseUrl:p.baseUrl}:{},...t?.cwd!==void 0?{cwd:t.cwd}:{}}),S=r?.stored?.sessionId,w=eo(S?{sessionLabel:S}:{});Le(w?.writer,{phase:"bootstrap_start"});let T=new ld(w?{traceWriter:w.writer}:{});CP(T);let C=p.bgSummaries===!0&&b?new Rm({registry:T,apiKey:b,maxCallsPerSession:p.maxSummaryCallsPerSession??200}):void 0;C?.start(),AP(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,ze,"cli"),A=new On({subagentManager:y,parentSession:k,surface:"cli",defaultConfig:{apiKey:b,systemPrompt:u,...p.baseUrl!==void 0?{baseUrl:p.baseUrl}:{}},defaultSubagentModel:Yt(s),childProviderFactory:R,childSkillExecutorFactory:$,backgroundRegistry:T,resolveApiKeyForModel:ze,depth:0,...t?.cwd!==void 0?{cwd:t.cwd}:{}}),P=new $n({parentSession:k,surface:"cli",defaultModel:s,defaultSubagentModel:Yt(s),apiKey:b,childProviderFactory:R,childSkillExecutorFactory:$,backgroundRegistry:T,...p.baseUrl!==void 0?{baseUrl:p.baseUrl}:{},resolveApiKeyForModel:ze,...w?.writer!==void 0?{traceWriter:w.writer}:{},...t?.cwd!==void 0?{cwd:t.cwd}:{}}),F=new Zr({parentSession:k,defaultModel:s,defaultSubagentModel:Yt(s),apiKey:b,resolveApiKeyForModel:ze,...p.baseUrl!==void 0?{baseUrl:p.baseUrl}:{},...t?.cwd!==void 0?{cwd:t.cwd}:{},systemPrompt:u??"",surface:"cli",depth:0}),D=new lt,N;{let ke=t?.cwd??process.cwd(),Qt=sn(Mt()).mcpConfigs.filter(qn=>qn.format==="json").map(qn=>qn.source),hn=Ho({cwd:ke,...Qt.length>0?{importedMcpConfigs:Qt}:{},...e.mcpConfig!==void 0?{cliOverride:e.mcpConfig}:{}}),pc=Object.values(hn.mcpServers).filter(qn=>!qn.disabled).length;if(pc>0){let qn=hn.sources.length===1?hn.sources[0]:`${hn.sources.length} source(s)`;console.log(f.dim(` mcp: ${pc} server(s) from ${qn??jo()}`));let ZF=Date.now();Le(w?.writer,{phase:"mcp_connect_start",metadata:{serverCount:pc}});try{N=await wr.fromConfig(hn.mcpServers,{warnings:hn.warnings,...w?.writer!==void 0?{traceWriter:w.writer}:{}})}finally{Le(w?.writer,{phase:"mcp_connect_done",durationMs:Date.now()-ZF,metadata:{serverCount:pc}})}}else if(hn.warnings.length>0)for(let qn of hn.warnings)console.warn(`[mcp] ${qn}`)}let B=N?.getMcpToolWireNames()??[],L=jO(ke=>hi(e.provider,{subagentExecutor:A,skillExecutor:P,composeExecutor:F,memoryStore:D,model:ke!==void 0?ke:String(s),...p.openaiBaseUrl!==void 0?{openaiBaseUrl:p.openaiBaseUrl}:{},...N!==void 0?{mcpManager:N}:{}})??new qe({permissions:{allowedTools:[...Kt,...nr,...ft,"agent","skill","compose",...B]},subagentExecutor:A,skillExecutor:P,composeExecutor:F,memoryStore:D,surface:"cli",...N!==void 0?{mcpManager:N}:{}}),ke=>e.provider??re(ke!==void 0?ke:String(s),p.openaiBaseUrl!==void 0?{openaiBaseUrl:p.openaiBaseUrl}:void 0)),I=L(String(s)),U=Vd(s);r?.stored&&yp(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:ke=>console.log(ke),idleFn:ke=>console.log(ke)},Y=new gp,oe=UO(process.stdout,{statusLine:Y}),X=Ti(ke=>{j.fn(Gd(ke))},"cli",D,()=>U.permissionMode,Ei({cwd:t?.cwd}),{cwd:t?.cwd,...w?.writer!==void 0?{traceWriter:w.writer}:{}},()=>t?.cwd??process.cwd()),me=X.registry,J=X.pathApprovalGrantRef,Ae={model:s,resumeConfig:o,systemPrompt:g,systemPromptSource:d,thinking:a,effort:l,maxOutputTokens:c,...p.baseUrl!==void 0?{baseUrl:p.baseUrl}:{},providerFactory:L,hookRegistry:me,traceWriter:w?.writer,cwd:t?.cwd,maxTurns:parseInt(e.maxTurns,10),autoResumeOnUsageLimit:p.autoResumeOnUsageLimit,...M!==void 0?{permissionMode:M}:{}};await wi();let Ye=WO(Ae);h.current=Ye,y.setOnSubagentSucceeded((ke,Qt)=>{h.current?.recordSubagentCompletion(ke,Qt)});let fe=new Tm,Te=Yi(j),_e=new xm(Ye),we=new hp({cwd:U.cwd??process.cwd(),branchTtlMs:1e3}),ve={session:h,stats:U,out:Te,ui:{clearScreen:()=>{let ke=ve.getCompositor?.();ke?.setOverlay(""),ke?.resetCommittedBand(),Y.stop(),_e.reset(),process.stdout.write("\x1B[3J\x1B[2J\x1B[H"),Y.start(),Y.repaint(Bn(U,_e,we))},repaintStatusLine:()=>Y.repaint(Bn(U,_e,we))},ledger:fe,...N!==void 0?{mcpManager:N}:{}},Pe=ke=>(fe.clear(),HO(ke,{sessionRef:h,stats:U,contextSampler:_e,gitStatusSampler:we,statusLine:Y,backgroundRegistry:T,completionWriter:j,isInFlight:()=>Ct.getInFlight?.()??!1,onSwapped:Qt=>{Ct.resumeTarget=Qt,Ct.clearVerdictLedger?.()},buildSession:Qt=>WO({...Ae,model:Qt.stored?.model??Ae.model,resumeConfig:Ii(Qt),permissionMode:U.permissionMode})})),Ct={session:h,memoryStore:D,stats:U,statusLine:Y,contextSampler:_e,gitStatusSampler:we,completionWriter:j,replRenderer:oe,slashCtx:ve,rl:null,options:e,...r!==void 0?{resumeTarget:r}:{},teardownTrustedSkillEvents:void 0,backgroundRegistry:T,subagentControl:A,...C!==void 0?{bgSummarizer:C}:{},requestResume:Pe,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},HS=ke=>{j.fn(C0(ke,{isTTY:process.stdout.isTTY,columns:process.stdout.columns}))},WS=ke=>{j.fn(R0(ke,{isTTY:process.stdout.isTTY,columns:process.stdout.columns})),fe.record(ke)};iR(HS),oR(WS),Ct.teardownTrustedSkillEvents=()=>{aR(HS),sR(WS)},BO(),I instanceof qe&&(I0(I),J.current=I,c_(I));let wf=KO.createInterface({input:process.stdin,output:process.stdout,terminal:!1});Ct.rl=wf;let Sf={current:null};return Ct.inputSurfaceRef=Sf,ct.install(fp({readLine:ke=>new Promise((Qt,hn)=>{wf.question(ke,Qt),wf.once("close",()=>hn(new Error("readline closed")))}),writer:{line:(ke="")=>process.stdout.write(ke+`
|
|
1942
|
+
`)},pendingCount:()=>ct.pendingCount(),suspendInput:()=>Sf.current?.suspendForElicitation(),resumeInput:()=>Sf.current?.resumeAfterElicitation()})),ve.requestResume=Pe,Le(w?.writer,{phase:"bootstrap_done",durationMs:Date.now()-n}),Ct}Br();K();import{promises as Rw}from"node:fs";import*as zO from"node:path";async function qO(e,t,n=!1){await Rw.mkdir(e,{recursive:!0});let r=new Date().toISOString().replace(/[:.]/g,"-"),o=zO.join(e,`${r}.md`),s=n?" (continued)":"";return await Rw.writeFile(o,`# Session \u2014 ${new Date().toISOString()}${s}
|
|
1943
1943
|
|
|
1944
1944
|
- model: ${t}
|
|
1945
1945
|
|
|
@@ -1988,23 +1988,23 @@ _ended: ${new Date().toISOString()}_
|
|
|
1988
1988
|
`)){let l=a.trim();if(l)try{let c=JSON.parse(l);c!==null&&typeof c=="object"&&"text"in c&&typeof c.text=="string"&&s.push(c)}catch{}}}catch{}if(ls=s.length,s.length<Vl-1){let i=await Cw(t,Aw|_w|VO|Iw,384);try{await i.writeFile(r)}finally{await i.close()}ls++}else{let i=s.slice(-(Vl-1));i.push(n);let a=i.map(c=>JSON.stringify(c)).join(`
|
|
1989
1989
|
`)+`
|
|
1990
1990
|
`,l=await Cw(t,Aw|_w|r9|Iw,384);try{await l.writeFile(a)}finally{await l.close()}ls=Vl}})}async function QO(e){if(e.initialBuffer!==void 0&&e.initialBuffer.length>0)return{text:e.initialBuffer,attachments:[]};let t=null;if(e.onSigint){let n=e.onSigint;t=()=>n(),process.on("SIGINT",t)}try{return{text:await XP({rl:e.rl,promptFn:e.promptFn}),attachments:[]}}finally{t&&process.removeListener("SIGINT",t)}}import*as Nt from"ansi-escapes";import Pw from"string-width";var l9="\x1B[?2004h",c9="\x1B[?2004l";function e$(e,t){let n=e.isRaw;e.setRawMode(!0),e.resume(),t.write(l9);let r=!1;return{restore(){if(!r){r=!0;try{t.write(c9)}catch{}try{e.setRawMode(n)}catch{}}}}}function Am(){let e={dropdownOpen:!1,candidates:[],selectedIndex:0,viewportStart:0,suppressedSignature:null,trigger:null,reset(){e.dropdownOpen=!1,e.candidates=[],e.selectedIndex=0,e.viewportStart=0,e.suppressedSignature=null,e.trigger=null}};return e}async function t$(e){let t=process.stdin,n=process.stdout,r=e.compositor?.isArmed()??!1,o=r?{restore:()=>{}}:e$(t,n),s=r?null:Ll("reader.readWithAutocomplete"),i=e.statusLine?.getExtraRows()??0;Ko(t);let a=e.promptFn(),l=Pw(Be(a)),c=null,u=null;try{return e.statusLine?.setExtraRows(i+1),await new Promise((d,p)=>{let m=W.seed(e.initialBuffer??""),g=e.autocompleteState??Am();g.reset();let h=0,b=!1,y=!1,S=0,w=0,T=0,x=null,C=[],R=6,k=0,$=!1,A=8,P={has:U=>it().some(M=>M.name===`/${U}`)},F=()=>{if((T>0||w>0)&&n.write(Nt.cursorUp(T+w)),n.write("\r"),n.write(Nt.eraseDown),C.length>0)n.write(Ol(C)+`
|
|
1991
|
-
`),T=1;else if(x!==null){let
|
|
1992
|
-
`),T=1}else T=0;n.write(a+oo(m.buffer,P)),g.trigger=Il(m.buffer,m.cursor);let U=`${m.cursor}:${m.buffer}`;g.suppressedSignature!==null&&g.suppressedSignature!==U&&(g.suppressedSignature=null),g.trigger&&g.suppressedSignature===null?(g.trigger.kind==="slash"?g.candidates=$p(g.trigger.query).slice(0,12):g.trigger.kind==="file"?g.candidates=Dp(g.trigger.query):g.candidates=Pl(g.trigger.command,g.trigger.query),g.dropdownOpen=g.candidates.length>0):(g.dropdownOpen=!1,g.candidates=[]),g.selectedIndex>=g.candidates.length&&(g.selectedIndex=Math.max(0,g.candidates.length-1)),g.viewportStart>g.selectedIndex&&(g.viewportStart=g.selectedIndex),g.selectedIndex>=g.viewportStart+R&&(g.viewportStart=g.selectedIndex-R+1);let M=n.columns||80;if(h=0,g.dropdownOpen&&M>40){let
|
|
1993
|
-
`+_e);let
|
|
1994
|
-
`+Ye);let
|
|
1991
|
+
`),T=1;else if(x!==null){let me=x;x=null,n.write(me+`
|
|
1992
|
+
`),T=1}else T=0;n.write(a+oo(m.buffer,P)),g.trigger=Il(m.buffer,m.cursor);let U=`${m.cursor}:${m.buffer}`;g.suppressedSignature!==null&&g.suppressedSignature!==U&&(g.suppressedSignature=null),g.trigger&&g.suppressedSignature===null?(g.trigger.kind==="slash"?g.candidates=$p(g.trigger.query).slice(0,12):g.trigger.kind==="file"?g.candidates=Dp(g.trigger.query):g.candidates=Pl(g.trigger.command,g.trigger.query),g.dropdownOpen=g.candidates.length>0):(g.dropdownOpen=!1,g.candidates=[]),g.selectedIndex>=g.candidates.length&&(g.selectedIndex=Math.max(0,g.candidates.length-1)),g.viewportStart>g.selectedIndex&&(g.viewportStart=g.selectedIndex),g.selectedIndex>=g.viewportStart+R&&(g.viewportStart=g.selectedIndex-R+1);let M=n.columns||80;if(h=0,g.dropdownOpen&&M>40){let me=Math.min(M-4,60),J=Math.min(g.candidates.length-g.viewportStart,R);for(let fe=0;fe<J;fe++){let Te=g.viewportStart+fe,_e=Fp(g.candidates[Te],Te===g.selectedIndex,me,g.trigger?.kind);n.write(`
|
|
1993
|
+
`+_e);let we=Pw(Be(_e));h+=Math.max(1,Math.ceil(we/M))}let Ae=Math.min(M-4,80),Ye=Np(g.candidates[g.selectedIndex]?.hint,Ae);if(Ye!==null){n.write(`
|
|
1994
|
+
`+Ye);let fe=Pw(Be(Ye));h+=Math.max(1,Math.ceil(fe/M))}}let j=vb(m.buffer,l,M),{row:Y,col:oe}=no(m.buffer,m.cursor,l,M),X=Math.max(0,j-Y+h);X>0&&n.write(Nt.cursorUp(X)),n.write("\r"),oe>0&&n.write(Nt.cursorForward(oe)),w=j},D=!1,N=()=>{$||($=!0,setImmediate(()=>{$&&!D&&($=!1,F())}))};F();let B=()=>{let U=g.candidates[g.selectedIndex];if(!U)return!1;let M=m.buffer.slice(0,m.cursor),j=m.buffer.slice(m.cursor),Y,oe;if(g.trigger?.kind==="slash"){let X=/\/[A-Za-z_-]*$/.exec(M);Y=X?M.length-X[0].length:m.cursor,oe=U.value+(j.startsWith(" ")?"":" ")}else if(g.trigger?.kind==="flag"){let X=/--[a-z0-9-]*$/.exec(M);Y=X?M.length-X[0].length:m.cursor,oe=U.value+(j.startsWith(" ")?"":" ")}else{let X=M.search(/[^\s]*$/);Y=X>=0?X:m.cursor,oe=U.value}return m=W.replaceRange(m,{start:Y,end:m.cursor},oe),g.dropdownOpen=!1,g.viewportStart=0,g.selectedIndex=0,F(),!0},H=()=>{(T>0||w>0)&&n.write(Nt.cursorUp(T+w)),n.write("\r"),n.write(Nt.eraseDown),h=0;let U=Jo({buffer:oo(m.buffer,P),promptText:a,isTTY:!!n.isTTY,attachmentSummary:ji(C)}),M=()=>n.write(U+`
|
|
1995
1995
|
`);e.statusLine?.withFullScrollRegion?e.statusLine.withFullScrollRegion(M):M(),I(),d({text:m.buffer,attachments:[...C]}),w=0},L=U=>{w>0&&n.write(Nt.cursorUp(w)),h>0&&(n.write(Nt.eraseDown),h=0),n.write(`
|
|
1996
1996
|
`),I(),p(U),w=0},I=()=>{D=!0,c&&t.removeListener("keypress",c),u&&u(),c=null,u=null};c=(U,M)=>{let j=Date.now(),Y=j-k<A;k=j;let oe=M?.sequence||"";if(oe==="\x1B[200~"){b=!0,S=m.buffer.length;return}if(oe==="\x1B[201~"){b=!1,m.buffer.length===S?y||(y=!0,Qo().then(J=>{J?(x=null,C.push(J)):x="[clipboard: no image found]",N()}).catch(()=>{}).finally(()=>{y=!1})):(F(),y||(y=!0,Qo().then(J=>{J&&(x=null,C.push(J),N())}).catch(()=>{}).finally(()=>{y=!1})));return}if(M?.ctrl&&M?.name==="c"){e.onSigint?e.onSigint():L(new Error("SIGINT"));return}if(M?.ctrl&&M?.name==="d"){m.buffer.length===0&&((T>0||w>0)&&n.write(Nt.cursorUp(T+w)),h>0&&(n.write(Nt.eraseDown),h=0),n.write(`
|
|
1997
1997
|
`),I(),d({text:"",attachments:[...C]}),w=0);return}if(M?.ctrl&&M?.name==="v"){y||(y=!0,Qo().then(J=>{J?(x=null,C.push(J)):x="[clipboard: no image found]",N()}).catch(()=>{}).finally(()=>{y=!1}));return}if(M?.name==="escape"){g.dropdownOpen&&(g.suppressedSignature=`${m.cursor}:${m.buffer}`,g.dropdownOpen=!1,g.candidates=[],F());return}if(M?.ctrl&&M?.name==="a"){let J=W.moveLineStart(m);J!==m&&(m=J,F());return}if(M?.ctrl&&M?.name==="e"){let J=W.moveLineEnd(m);J!==m&&(m=J,F());return}if(M?.ctrl&&M?.name==="b"){let J=W.moveLeft(m);J!==m&&(m=J,F());return}if(M?.ctrl&&M?.name==="f"){let J=W.moveRight(m);J!==m&&(m=J,F());return}if(M?.meta&&M?.name==="b"){let J=W.moveWordBackward(m);J!==m&&(m=J,F());return}if(M?.meta&&M?.name==="f"){let J=W.moveWordForward(m);J!==m&&(m=J,F());return}if(M?.ctrl&&M?.name==="w"){let J=W.deleteWordBackward(m);J!==m&&(m=J,e.history?.resetRecall(),F());return}if(M?.ctrl&&M?.name==="l"){w=0,T=0,n.write("\x1B[H\x1B[2J"),F();return}if(M?.ctrl&&M?.name==="p"||M?.name==="up"){if(g.dropdownOpen){g.selectedIndex>0&&(g.selectedIndex--,g.selectedIndex<g.viewportStart&&(g.viewportStart=g.selectedIndex),F());return}let J=n.columns||80,Ae=W.moveUpLine(m,J,l);if(Ae.moved)m=Ae.state,e.history?.resetRecall(),F();else if(e.history){let Ye=e.history.back(m.buffer);Ye!==null&&(m=W.seed(Ye),F())}return}if(M?.ctrl&&M?.name==="n"||M?.name==="down"){if(g.dropdownOpen){g.selectedIndex<g.candidates.length-1&&(g.selectedIndex++,g.selectedIndex>=g.viewportStart+R&&(g.viewportStart=g.selectedIndex-R+1),F());return}let J=n.columns||80,Ae=W.moveDownLine(m,J,l);if(Ae.moved)m=Ae.state,e.history?.resetRecall(),F();else if(e.history){let Ye=e.history.forward();Ye!==null&&(m=W.seed(Ye),F())}return}if(M?.name==="left"){let J=W.moveLeft(m);J!==m&&(m=J,F());return}if(M?.name==="right"){let J=W.moveRight(m);J!==m&&(m=J,F());return}if(M?.name==="home"){let J=W.moveHome(m);J!==m&&(m=J,F());return}if(M?.name==="end"){let J=W.moveEnd(m);J!==m&&(m=J,F());return}if(M?.ctrl&&M?.name==="u"){let J=W.deleteToLineStart(m);J!==m&&(m=J,e.history?.resetRecall(),F());return}if(M?.ctrl&&M?.name==="k"){let J=W.deleteToLineEnd(m);J!==m&&(m=J,e.history?.resetRecall(),F());return}if(M?.ctrl&&M?.name==="x"){C.length>0&&(C.pop(),F());return}if(M?.name==="backspace"){if(M?.meta){let Ae=W.deleteWordBackward(m);Ae!==m&&(m=Ae,e.history?.resetRecall(),F());return}let J=W.backspace(m);J!==m?(m=J,e.history?.resetRecall(),F()):C.length>0&&(C.pop(),F());return}if(M?.name==="delete"){if(M?.meta){let Ae=W.deleteWordForward(m);Ae!==m&&(m=Ae,e.history?.resetRecall(),F());return}let J=W.deleteForward(m);J!==m&&(m=J,e.history?.resetRecall(),F());return}if(M?.name==="return"){if(Mp(M,oe)){m=W.insert(m,`
|
|
1998
1998
|
`),e.history?.resetRecall(),F();return}if(b){m=W.insert(m,`
|
|
1999
1999
|
`);return}if(Y){m=W.insert(m,`
|
|
2000
2000
|
`),N();return}if(g.dropdownOpen){let J=g.trigger?.kind,Ae=B();J==="slash"&&Ae&&H()}else Bi(m.buffer)?(m=W.replaceRange(m,{start:m.buffer.length-1,end:m.buffer.length},`
|
|
2001
|
-
`),F()):H();return}if(M?.shift&&M?.name==="tab"||M?.sequence==="\x1B[Z"){e.onShiftTab?.();return}if(M?.name==="tab"){if(g.dropdownOpen)B();else{let J=m.buffer.slice(0,m.cursor),Ae=/\s+\/([A-Za-z][A-Za-z0-9_:-]*)$/.exec(J);if(Ae){let
|
|
2001
|
+
`),F()):H();return}if(M?.shift&&M?.name==="tab"||M?.sequence==="\x1B[Z"){e.onShiftTab?.();return}if(M?.name==="tab"){if(g.dropdownOpen)B();else{let J=m.buffer.slice(0,m.cursor),Ae=/\s+\/([A-Za-z][A-Za-z0-9_:-]*)$/.exec(J);if(Ae){let fe="/"+Ae[1],_e=[...it().map(we=>we.name),...Li().map(we=>we.alias)].filter(we=>we.startsWith(fe)).sort((we,ve)=>we.localeCompare(ve))[0];if(_e){let we=m.buffer.slice(m.cursor),ve=m.cursor-fe.length,Pe=_e+(we.startsWith(" ")?"":" ");m=W.replaceRange(m,{start:ve,end:m.cursor},Pe),F()}}}return}let X=!M?.ctrl&&!M?.meta,me=X&&typeof U=="string"&&Hi(U)?U:X&&typeof M?.sequence=="string"&&Hi(M.sequence)?M.sequence:null;me!==null&&(m=W.insert(m,me),e.history?.resetRecall(),b||(Y?N():F()))},u=He.subscribe(()=>{w=0,T=0,h=0,F()}),t.on("keypress",c)})}finally{e.statusLine?.setExtraRows(i),o.restore(),s?.release()}}async function n$(e){return!process.stdout.isTTY||!process.stdin.isTTY?QO(e):t$(e)}var _m=class{history;autocompleteState;rl;statusLine;compositor=null;armedStdout=null;backgroundHandler=null;softStopHandler=null;pauseInterruptHandler=null;pendingReadReject=null;slashRegistryView={has:t=>it().some(n=>n.name===`/${t}`)};constructor(t){this.rl=t.rl,this.history=t.history,this.statusLine=t.statusLine,this.autocompleteState=Am()}async armCompositor(t){if(this.compositor)return;let n=t.stdout??process.stdout,r=t.stdin??process.stdin;if(!n.isTTY||!r.isTTY)return;let o=new Wi({stdout:n,stdin:r,promptText:t.promptFn,onCancel:t.onCancel,onSoftStop:()=>{this.softStopHandler?.()},onBackground:()=>{this.backgroundHandler?.()},onPauseInterrupt:()=>{this.pauseInterruptHandler?.()},...t.onShiftTab?{onShiftTab:t.onShiftTab}:{},history:this.history,autocompleteState:this.autocompleteState,formatInputBuffer:s=>oo(s,this.slashRegistryView),caretBlink:AI()&&!cp(),captureMode:lp(),...t.scrollRegion?{scrollRegion:t.scrollRegion}:{},...t.anchorRow!==void 0?{anchorRow:t.anchorRow}:{},...t.suggest?{suggest:t.suggest}:{}});await o.arm(),o.setInputMode("idle"),this.compositor=o,this.armedStdout=n}async dispose(){if(this.compositor){if(this.pendingReadReject){this.compositor.setOnSubmit(null);let t=this.pendingReadReject;this.pendingReadReject=null,t(new Error("InputSurface disposed while readLine was in progress"))}try{this.compositor.disarm()}catch{}this.compositor=null,this.armedStdout=null,this.backgroundHandler=null,this.softStopHandler=null,this.pauseInterruptHandler=null}}getCompositor(){return this.compositor}setBackgroundHandler(t){this.backgroundHandler=t}setSoftStopHandler(t){this.softStopHandler=t}setPauseInterruptHandler(t){this.pauseInterruptHandler=t}setPausedState(t){this.compositor&&(this.compositor.paused=t)}suspendForElicitation(){this.compositor?.suspendInput()}resumeAfterElicitation(){this.compositor?.resumeInput()}async readLine(t){if(this.compositor&&this.compositor.isArmed()){let n=this.compositor;return new Promise((r,o)=>{this.pendingReadReject=o;let s=i=>{n.setOnSubmit(null),this.pendingReadReject=null;let a=this.armedStdout??process.stdout,l=i.displayText??i.text,c=Jo({buffer:oo(l,this.slashRegistryView),promptText:t.promptFn(),isTTY:!!a.isTTY,attachmentSummary:ji([...i.attachments])});dn(n,c.split(`
|
|
2002
2002
|
`)),r({text:i.text,attachments:[...i.attachments]})};n.setOnSubmit(s),n.setInputMode("idle"),n.repaint()})}return n$({rl:this.rl,promptFn:t.promptFn,...t.onSigint?{onSigint:t.onSigint}:{},...t.onShiftTab?{onShiftTab:t.onShiftTab}:{},...t.compositor?{compositor:t.compositor}:{},history:this.history,autocompleteState:this.autocompleteState,...this.statusLine?{statusLine:this.statusLine}:{}})}toRunTurnRefs(t){return{history:this.history,autocompleteState:this.autocompleteState,promptText:t}}};q();Br();var u9="\u25B8",d9=" ",p9="\u25C9",m9="\u25EF",f9="\u2191/\u2193 navigate \xB7 enter select \xB7 esc cancel",g9="\u2191/\u2193 navigate \xB7 space toggle \xB7 enter confirm \xB7 esc cancel";function Im(e,t){return new Promise(n=>{let{header:r,options:o,multi:s=!1,signal:i,initialIndex:a=0}=t;if(o.length===0){n(null);return}if(i?.aborted){n(null);return}let l=h9(a,0,o.length-1),c=new Set(t.initialSelected??[]),u=!1,d=b=>{u||(u=!0,i&&i.removeEventListener("abort",p),e.exitPickerMode(),n(b))},p=()=>d(null);i&&i.addEventListener("abort",p,{once:!0});let h={renderRows:()=>{let b=[];for(let y of r)b.push(y);for(let y=0;y<o.length;y++){let S=o[y]??"",w=y===l,T=w?f.brand(u9):d9,x;if(s){let C=c.has(y),R=C?f.success(p9):f.dim(m9),k=w&&!C?f.bold(S):S;x=` ${T} ${R} ${k}`}else{let C=w?f.bold(S):f.dim(S);x=` ${T} ${C}`}b.push(x)}return b.push(f.dim(" "+(s?g9:f9))),b},onKey:(b,y)=>{if(!u){if(y.name==="escape"||y.ctrl&&y.name==="c"){d(null);return}if(y.name==="up"||y.ctrl&&y.name==="p"){l=l===0?o.length-1:l-1,e.repaintPicker();return}if(y.name==="down"||y.ctrl&&y.name==="n"){l=l===o.length-1?0:l+1,e.repaintPicker();return}if(y.name==="return"){if(s){let S=[];for(let w=0;w<o.length;w++)if(c.has(w)){let T=o[w];T!==void 0&&S.push(T)}d(S)}else{let S=o[l];d(S!==void 0?[S]:[])}return}if(s&&(y.name==="space"||b===" ")){c.has(l)?c.delete(l):c.add(l),e.repaintPicker();return}if(y.name==="home"){l=0,e.repaintPicker();return}if(y.name==="end"){l=o.length-1,e.repaintPicker();return}}}};e.enterPickerMode(h)})}function h9(e,t,n){return n<t||e<t?t:e>n?n:e}var y9="enter to submit \xB7 esc to cancel",b9=">";function r$(e,t){return new Promise(n=>{let{header:r,initial:o="",help:s=y9,validate:i,signal:a}=t;if(a?.aborted){n(null);return}let l=W.seed(o),c=null,u=!1,d=b=>{u||(u=!0,a&&a.removeEventListener("abort",p),e.exitPickerMode(),n(b))},p=()=>d(null);a&&a.addEventListener("abort",p,{once:!0});let h={renderRows:()=>{let b=[];for(let y of r)b.push(y);return b.push(w9(l)),c!==null&&b.push(f.warning(" "+c)),b.push(f.dim(" "+s)),b},onKey:(b,y)=>{if(u)return;if(y.name==="escape"||y.ctrl&&y.name==="c"){d(null);return}if(y.name==="return"){if(i){let w=i(l.buffer);if(w!==null){c=w,e.repaintPicker();return}}d(l.buffer);return}let S=c!==null;if(y.name==="left"||y.ctrl&&y.name==="b"){l=W.moveLeft(l),c=null,e.repaintPicker();return}if(y.name==="right"||y.ctrl&&y.name==="f"){l=W.moveRight(l),c=null,e.repaintPicker();return}if(y.name==="home"||y.ctrl&&y.name==="a"){l=W.moveHome(l),c=null,e.repaintPicker();return}if(y.name==="end"||y.ctrl&&y.name==="e"){l=W.moveEnd(l),c=null,e.repaintPicker();return}if(y.name==="backspace"){l=W.backspace(l),c=null,e.repaintPicker();return}if(y.name==="delete"){l=W.deleteForward(l),c=null,e.repaintPicker();return}if(y.ctrl&&y.name==="w"){l=W.deleteWordBackward(l),c=null,e.repaintPicker();return}if(y.ctrl&&y.name==="u"){l=W.deleteToLineStart(l),c=null,e.repaintPicker();return}if(y.ctrl&&y.name==="k"){l=W.deleteToLineEnd(l),c=null,e.repaintPicker();return}if(b!==void 0&&b.length>0&&!S9(b)){l=W.insert(l,b),c=null,e.repaintPicker();return}S&&(c=null,e.repaintPicker())}};e.enterPickerMode(h)})}function w9(e){let{buffer:t,cursor:n}=e,r=t.slice(0,n),o=n>=t.length,s=o?"\u258F":t.charAt(n),i=n<t.length?t.slice(n+1):"",a=o?f.caret(s):f.caret.inverse(s);return` ${f.dim(b9)} ${r}${a}${i}`}function S9(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t<32||t===127}Me();q();var Mw=["default","plan","bypassPermissions"];function v9(e,t){switch(t){case"plan":e.out.success(f.warning("\u25CF plan mode ON")+f.dim(" \u2014 writes refused; read-only bash runs, mutating bash blocked."));return;case"bypassPermissions":e.out.line(f.bypass("\u26A1 bypass ON")+f.dim(" \u2014 path-approval prompts + containment OFF; read/write any path. (Does not affect ask_question.)"));return;case"default":e.out.success(f.success("\u25CB default")+f.dim(" \u2014 path containment + approval prompts restored."));return}}async function Pm(e){let t=e.stats.permissionMode;if(t==="autonomous"){await Rl(e,!1);return}let n=Mw.indexOf(t),r=Mw[(n+1)%Mw.length]??"default";try{await e.session.current.setPermissionMode(r),e.stats.permissionMode=r,e.ui.repaintStatusLine(),v9(e,r)}catch(o){e.out.error(`Could not switch permission mode: ${o instanceof Error?o.message:String(o)}`)}}function ea(e){let t=f.brand("afk"),n=e==="plan"?f.warning(" \u25CF plan"):e==="autonomous"?f.info(" \u25D0 AFK"):e==="bypassPermissions"?f.bypass(" \u26A1 bypass"):"";return t+n+f.dim(" \u203A ")}async function o$(e,t,n,r,o,s,i){let a=nM({onError:p=>z("[afk suggest] Tier-2 completion failed:",p)});await t.armCompositor({promptFn:()=>ea(e.stats.permissionMode),onCancel:o,onShiftTab:()=>{Pm(e.slashCtx).catch(()=>{}),e.statusLine.rearm()},scrollRegion:e.statusLine,...e.preArmAnchorRow!==void 0?{anchorRow:e.preArmAnchorRow}:{},...s?{suggest:{engine:a,getContext:()=>({model:e.stats.model,apiKey:e.suggestApiKey,baseUrl:e.suggestBaseUrl,cwd:e.stats.cwd??process.cwd(),getHistory:()=>{let p=t.history;return p.getEntries?[...p.getEntries()]:[]},getDropdownTopCandidate:p=>{let g=t.autocompleteState.candidates[0];return g&&g.value.startsWith(p)&&g.value.length>p.length?g.value:null},getTranscriptTail:()=>"",getRecentCommands:()=>[],llmEnabled:()=>/^(1|true|yes|on)$/i.test(v.AFK_SUGGEST_ENABLED??"")})}}:{}});let l=t.getCompositor(),c=fp({readLine:p=>t.readLine({promptFn:()=>p}).then(m=>m.text),writer:{line:(p="")=>{let m=t.getCompositor();m?m.commitAbove(p):process.stdout.write(p+`
|
|
2003
|
-
`)}},pendingCount:()=>ct.pendingCount(),...l?{pickFromList:p=>Im(l,p),readTextOverlay:p=>r$(l,p)}:{}});ct.install(c),e.replRenderer.setCompositor(t.getCompositor()),e.slashCtx.getCompositor=()=>t.getCompositor();let u=t.getCompositor();if(u){let p=m=>u.commitAbove(m);e.completionWriter.fn=p,e.completionWriter.idleFn=p}let d=p=>{t.setSoftStopHandler(p),n.requestSoftStop=p};return e.slashCtx.setSoftStopHandler=d,e.slashCtx.onStageChange=p=>i.getLoopStageBar()?.repaint(p),e.slashCtx.onContextProgress=async()=>{await e.contextSampler.refresh(),await e.gitStatusSampler.refresh(),e.statusLine.repaint(Bn(e.stats,e.contextSampler,e.gitStatusSampler))},e.slashCtx.transcript=r,e.slashCtx.stdinElicitationHandler=c,e.slashCtx.swapElicitationHandler=p=>ct.install(p??c),e.inputSurfaceRef&&(e.inputSurfaceRef.current=t),e.gitStatusSampler.setOnUpdate(()=>{e.statusLine.repaint(Bn(e.stats,e.contextSampler,e.gitStatusSampler))}),e.gitStatusSampler.refresh(),{installSoftStop:d}}function s$(e={}){let t=e.load??vp,n=e.onResize??(i=>He.subscribe(i)),r="",o,s=n(()=>{r=""});return{renderIfChanged(i){let a=i??"unbound",l=t(a),c=dP(l);return a===o&&c===r?[]:(o=a,r=c,c===""?[]:kp(l))},invalidate(){r=""},dispose(){try{s()}catch{}}}}var Ow={done:{glyph:"\u2713",color:f.success,label:"done"},blocked:{glyph:"\u2298",color:f.error,label:"blocked"},asking:{glyph:"?",color:f.warning,label:"asking"},interrupted:{glyph:"\u23F8",color:f.meta,label:"interrupted"}};function i$(e={}){let t=Math.max(2,e.capacity??8),n=[],r=null,o=()=>0,s=!1,i=0,a,l=null;function c(){let g=r?.rows;return typeof g=="number"&&g>0?g:24}function u(g){let h=o();return Math.max(1,g-1-h)}function d(){if(!s||!r?.isTTY)return;let g=m(),h=c(),b=g!==null&&h>1?1:0;if(b!==i&&(i>0&&p(),i=b,a?.(i)),b===0)return;let y=u(h);r.write("\x1B[s"),r.write(`\x1B[${y};1H`),r.write("\x1B[2K"),r.write(g),r.write("\x1B[u")}function p(){if(!r?.isTTY)return;let g=c(),h=u(g);r.write("\x1B[s"),r.write(`\x1B[${h};1H`),r.write("\x1B[2K"),r.write("\x1B[u")}function m(){if(n.length===0)return null;let g=f.dim(" ledger "),h=f.dim(" \xB7 "),b=n.map(x=>{let C=Ow[x];return C.color(`${C.glyph} ${C.label}`)}),y=f.dim(` (${n.length} turn${n.length===1?"":"s"})`),S=g+b.join(h)+y,w=Math.max(20,Q()-2);if(V(S)<=w)return S;let T=g+n.map(x=>Ow[x].color(Ow[x].glyph)).join(f.dim(" "))+y;return ne(T,w)}return{push(g){n.push(g.kind),n.length>t&&(n=n.slice(n.length-t)),d()},reset(){n=[],s&&i>0&&(p(),i=0,a?.(0))},entries(){return n},render(){return m()},setRowCountChangeHandler(g){a=g},start(g){s||(s=!0,r=g.stream??process.stdout,o=g.getAdjacentRows??(()=>0),i=0,l=He.subscribe(()=>d()),d())},stop(){s&&(s=!1,l!==null&&(l(),l=null),i>0&&(p(),i=0,a?.(0)),r=null)},repaint(){d()}}}var a$=["\u25D0","\u25D1","\u25D2","\u25D3"],Mm=class{stream;registry;throttleMs;started=!1;lastRepaint=0;spinnerIndex=0;spinnerInterval=null;resizeUnsub=null;resizeImmediateUnsub=null;registryStartedHandler=null;registrySettledHandler=null;rowCount=0;lastPaintStartRow=0;preResizeStartRow=null;preResizeRowCount=null;onRowCountChange;getAdjacentRows;constructor(t,n={}){this.registry=t,this.stream=n.stream??process.stdout,this.throttleMs=n.throttleMs??200,this.getAdjacentRows=n.getAdjacentRows??(()=>0)}setRowCountChangeHandler(t){this.onRowCountChange=t}start(){this.started||(this.started=!0,this.registry&&(this.registryStartedHandler=t=>{this.scheduleRepaint()},this.registrySettledHandler=t=>{this.scheduleRepaint()},this.registry.on("started",this.registryStartedHandler),this.registry.on("settled",this.registrySettledHandler)),this.resizeUnsub=He.subscribe(()=>this.repaint()),this.resizeImmediateUnsub=He.subscribeImmediate(()=>this.resetGeometry()),this.spinnerInterval=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%a$.length,this.rowCount>0&&this.repaint()},Math.max(this.throttleMs,50)))}stop(){this.started&&(this.started=!1,this.registry&&(this.registryStartedHandler&&(this.registry.off("started",this.registryStartedHandler),this.registryStartedHandler=null),this.registrySettledHandler&&(this.registry.off("settled",this.registrySettledHandler),this.registrySettledHandler=null)),this.resizeUnsub&&(this.resizeUnsub(),this.resizeUnsub=null),this.resizeImmediateUnsub&&(this.resizeImmediateUnsub(),this.resizeImmediateUnsub=null),this.spinnerInterval&&(clearInterval(this.spinnerInterval),this.spinnerInterval=null),this.rowCount>0&&(this.clearRows(),this.rowCount=0,this.onRowCountChange?.(0)))}resetGeometry(){this.rowCount>0&&(this.preResizeStartRow=this.lastPaintStartRow,this.preResizeRowCount=this.rowCount),this.rowCount=0,this.lastRepaint=0}scheduleRepaint(){Date.now()-this.lastRepaint<this.throttleMs||this.repaint()}redraw(){this.repaint()}repaint(){if(!this.started||!this.stream.isTTY)return;this.lastRepaint=Date.now();let t=(this.registry?.list()??[]).filter(i=>i.status==="running").map(i=>({kind:"subagent",job:i})),n=this.stream.rows??24,r=this.getAdjacentRows(),o=Math.max(0,Math.min(t.length,n-1-r));if(this.clearPreResizeRows(),o!==this.rowCount&&(this.rowCount>0&&this.clearRows(),this.rowCount=o,this.onRowCountChange?.(o)),o===0)return;let s=Math.max(1,n-o-r);this.lastPaintStartRow=s,this.stream.write("\x1B[s");for(let i=0;i<o;i++){let a=t[i],l=s+i;this.stream.write(`\x1B[${l};1H`),this.stream.write("\x1B[2K"),this.stream.write(this.formatItemLine(a))}this.stream.write("\x1B[u")}clearRows(){if(!this.stream.isTTY)return;let t=this.stream.rows??24,n=this.getAdjacentRows(),r=Math.min(this.rowCount,t-1-n),o=Math.max(1,t-r-n);this.stream.write("\x1B[s");for(let s=0;s<r;s++)this.stream.write(`\x1B[${o+s};1H`),this.stream.write("\x1B[2K");this.stream.write("\x1B[u")}clearPreResizeRows(){let t=this.preResizeStartRow,n=this.preResizeRowCount;if(this.preResizeStartRow=null,this.preResizeRowCount=null,t===null||n===null||!this.stream.isTTY)return;let r=this.stream.rows??24,o=[];for(let s=0;s<n;s++){let i=t+s;i<=r&&o.push(i)}if(o.length!==0){this.stream.write("\x1B[s");for(let s of o)this.stream.write(`\x1B[${s};1H`),this.stream.write("\x1B[2K");this.stream.write("\x1B[u")}}formatItemLine(t){return this.formatJobLine(t.job)}formatJobLine(t){let n=Math.max(4,(this.stream.columns??80)-2),r=f.brand(a$[this.spinnerIndex]),o=f.dim(t.jobId),s=f.bold(t.label||t.jobId),i=[r,o,s],a=Date.now()-t.startedAt;return i.push(f.dim(fe(a))),ne(" "+i.join(" "),n)}};import{spawn as k9}from"node:child_process";var E9=/\x1b(?:\[[0-9;]*[a-zA-Z]|[\]P^_X][^\x07\x1b]*(?:\x07|\x1b\\)|[@-OQ-WYZ\\])/g;function T9(){let e="";return{strip(t){let r=(e+t).replace(E9,""),o=r.match(/\x1b(?:[\]P^_X][^\x07\x1b]*|\[[0-9;]*)?$/);return o?(e=o[0],r.slice(0,r.length-e.length)):(e="",r)},flush(){return e="",""}}}function l$(e,t){if(e.length<=t)return e;let n=t;for(;n>0&&(e[n]&192)===128;)n--;return e.subarray(0,n)}var c$=12e4,u$=1e5;function $w(e){let t=Date.now(),n=e.timeoutMs??c$,r=e.maxBytes??u$,o=T9(),s;try{s=k9(e.command,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...e.cwd!==void 0?{cwd:e.cwd}:{},...e.env!==void 0?{env:{...process.env,...e.env}}:{}})}catch(x){let C=x instanceof Error?x.message:String(x);return{pid:void 0,kill:()=>{},promise:Promise.resolve({exitCode:null,durationMs:Date.now()-t,displayCaptured:"",modelCaptured:"",truncated:!1,errorReason:"spawn-failed",errorMessage:`Failed to spawn shell: ${C}`})}}s.unref();let i,a=!1,l=new Promise(x=>{i=C=>{a||(a=!0,x(C))}}),c="",u="",d=0,p=0,m=!1,g=!1,h=!1;function b(x){let C=r-d;if(C>0){let R=x.length<=C?x:l$(x,C);d+=R.length,c+=R.toString("utf8"),x.length>C&&(m=!0)}else x.length>0&&(m=!0);if(p<r){let R=o.strip(x.toString("utf8")),k=Buffer.byteLength(R,"utf8"),$=r-p;if(k<=$)u+=R,p+=k;else{let A=Buffer.from(R,"utf8");u+=l$(A,$).toString("utf8"),p=r,m=!0}}}function y(){if(s.pid!==void 0&&s.pid!==0&&!s.killed)try{process.kill(-s.pid,"SIGKILL")}catch{}}let S=setTimeout(()=>{y(),e.abort.removeEventListener("abort",w),i({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m,errorReason:"timeout",errorMessage:`Command timed out after ${n}ms`})},n),w=()=>{y(),clearTimeout(S),i({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m,errorReason:"abort",errorMessage:h?"Command killed":"Command aborted"})};e.abort.addEventListener("abort",w);function T(){g||a||d<r&&p<r||(g=!0,y(),clearTimeout(S),e.abort.removeEventListener("abort",w),i({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:!0,errorReason:"overflow",errorMessage:`Output exceeded ${r} bytes`}))}return s.stdout?.on("data",x=>{b(x);try{e.onChunk?.(x,"stdout")}catch{}T()}),s.stderr?.on("data",x=>{b(x);try{e.onChunk?.(x,"stderr")}catch{}T()}),s.on("error",x=>{clearTimeout(S),e.abort.removeEventListener("abort",w),i({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m,errorReason:"spawn-failed",errorMessage:`Shell process error: ${x.message}`})}),s.on("close",(x,C)=>{if(clearTimeout(S),e.abort.removeEventListener("abort",w),!(g||a)){if(o.flush(),h){i({exitCode:x,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m,errorReason:"abort",errorMessage:"Command killed"});return}if(x!==null&&x!==0){i({exitCode:x,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m,errorReason:"nonzero-exit",errorMessage:`Command exited with code ${x}`});return}if(x===null){i({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m,errorReason:"signal-killed",errorMessage:C?`Command killed by signal ${C}`:"Command killed by signal"});return}i({exitCode:x,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m})}}),{pid:s.pid,promise:l,kill:(x="SIGKILL")=>{if(!(s.pid===void 0||s.pid===0||s.killed)){h=!0;try{process.kill(-s.pid,x)}catch{}}}}}import{EventEmitter as x9}from"node:events";var d$=200,Yl=class extends x9{jobs=new Map;handles=new Map;aborts=new Map;counter=0;start(t){let n=`sh-${++this.counter}`,r=new AbortController,o=$w({command:t.command,...t.cwd!==void 0?{cwd:t.cwd}:{},abort:r.signal,...t.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{},...t.maxBytes!==void 0?{maxBytes:t.maxBytes}:{},...t.env!==void 0?{env:t.env}:{},...t.onChunk!==void 0?{onChunk:t.onChunk}:{}}),s={id:n,command:t.command,pid:o.pid,startedAt:Date.now(),mode:t.mode,status:"running"};return this.jobs.set(n,s),this.handles.set(n,o),this.aborts.set(n,r),o.promise.then(i=>{s.result=i,s.status=R9(i),this.aborts.delete(n),this.handles.delete(n);try{this.emit("complete",s)}catch(a){console.warn(`[shell-jobs] listener for 'complete' threw on ${n}: ${a instanceof Error?a.message:String(a)}`)}this.pruneHistory()}),{job:s,handle:o}}get(t){return this.jobs.get(t)}list(){return[...this.jobs.values()].sort((t,n)=>t.startedAt-n.startedAt)}running(){return this.list().filter(t=>t.status==="running")}kill(t){let n=this.jobs.get(t);if(!n||n.status!=="running")return!1;let r=this.aborts.get(t);if(r)return r.abort(),!0;let o=this.handles.get(t);return o?(o.kill(),!0):!1}killAll(){let t=this.running();for(let n of t)this.kill(n.id);return t}runningCount(){let t=0;for(let n of this.jobs.values())n.status==="running"&&t++;return t}pruneHistory(){if(!(this.jobs.size<=d$))for(let[t,n]of this.jobs){if(this.jobs.size<=d$)break;n.status!=="running"&&this.jobs.delete(t)}}};function R9(e){return e.errorReason===void 0?"completed":e.errorReason==="abort"?"killed":"failed"}function C9(e){if(!e.startsWith("!"))return null;if(e.startsWith("!&")){let n=e.slice(2).trim();return n.length===0?null:{mode:"background",command:n}}let t=e.slice(1).trim();return t.length===0?null:{mode:"foreground",command:t}}function A9(e,t){let n=fe(t.durationMs);return t.errorReason==="abort"?f.dim(` [${e.id} \xB7 killed \xB7 ${n}]`):t.errorReason==="timeout"?f.dim(` [${e.id} \xB7 timed out \xB7 ${n}]`):t.errorReason==="overflow"?f.dim(` [${e.id} \xB7 output overflow \xB7 ${n}]`):t.errorReason==="spawn-failed"?f.warning(` [${e.id} \xB7 spawn failed \xB7 ${n}]`):t.errorReason==="nonzero-exit"?f.warning(` [${e.id} \xB7 exit ${t.exitCode} \xB7 ${n}]`):t.errorReason==="signal-killed"?f.warning(` [${e.id} \xB7 killed by signal \xB7 ${n}]`):f.dim(` [${e.id} \xB7 exit ${t.exitCode??0} \xB7 ${n}]`)}function p$(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function _9(e,t,n){let r=[],o=[`mode="${t}"`];return n.exitCode!==null&&o.push(`exit="${n.exitCode}"`),n.errorReason!==void 0&&o.push(`reason="${n.errorReason}"`),o.push(`duration="${fe(n.durationMs)}"`),n.truncated&&o.push('truncated="true"'),r.push(`<bash-passthrough ${o.join(" ")}>`),r.push(`<command>${p$(e)}</command>`),r.push("<output>"),r.push(p$(n.modelCaptured)),r.push("</output>"),r.push("</bash-passthrough>"),r.join(`
|
|
2003
|
+
`)}},pendingCount:()=>ct.pendingCount(),...l?{pickFromList:p=>Im(l,p),readTextOverlay:p=>r$(l,p)}:{}});ct.install(c),e.replRenderer.setCompositor(t.getCompositor()),e.slashCtx.getCompositor=()=>t.getCompositor();let u=t.getCompositor();if(u){let p=m=>u.commitAbove(m);e.completionWriter.fn=p,e.completionWriter.idleFn=p}let d=p=>{t.setSoftStopHandler(p),n.requestSoftStop=p};return e.slashCtx.setSoftStopHandler=d,e.slashCtx.onStageChange=p=>i.getLoopStageBar()?.repaint(p),e.slashCtx.onContextProgress=async()=>{await e.contextSampler.refresh(),await e.gitStatusSampler.refresh(),e.statusLine.repaint(Bn(e.stats,e.contextSampler,e.gitStatusSampler))},e.slashCtx.transcript=r,e.slashCtx.stdinElicitationHandler=c,e.slashCtx.swapElicitationHandler=p=>ct.install(p??c),e.inputSurfaceRef&&(e.inputSurfaceRef.current=t),e.gitStatusSampler.setOnUpdate(()=>{e.statusLine.repaint(Bn(e.stats,e.contextSampler,e.gitStatusSampler))}),e.gitStatusSampler.refresh(),{installSoftStop:d}}function s$(e={}){let t=e.load??vp,n=e.onResize??(i=>He.subscribe(i)),r="",o,s=n(()=>{r=""});return{renderIfChanged(i){let a=i??"unbound",l=t(a),c=dP(l);return a===o&&c===r?[]:(o=a,r=c,c===""?[]:kp(l))},invalidate(){r=""},dispose(){try{s()}catch{}}}}var Ow={done:{glyph:"\u2713",color:f.success,label:"done"},blocked:{glyph:"\u2298",color:f.error,label:"blocked"},asking:{glyph:"?",color:f.warning,label:"asking"},interrupted:{glyph:"\u23F8",color:f.meta,label:"interrupted"}};function i$(e={}){let t=Math.max(2,e.capacity??8),n=[],r=null,o=()=>0,s=!1,i=0,a,l=null;function c(){let g=r?.rows;return typeof g=="number"&&g>0?g:24}function u(g){let h=o();return Math.max(1,g-1-h)}function d(){if(!s||!r?.isTTY)return;let g=m(),h=c(),b=g!==null&&h>1?1:0;if(b!==i&&(i>0&&p(),i=b,a?.(i)),b===0)return;let y=u(h);r.write("\x1B[s"),r.write(`\x1B[${y};1H`),r.write("\x1B[2K"),r.write(g),r.write("\x1B[u")}function p(){if(!r?.isTTY)return;let g=c(),h=u(g);r.write("\x1B[s"),r.write(`\x1B[${h};1H`),r.write("\x1B[2K"),r.write("\x1B[u")}function m(){if(n.length===0)return null;let g=f.dim(" ledger "),h=f.dim(" \xB7 "),b=n.map(x=>{let C=Ow[x];return C.color(`${C.glyph} ${C.label}`)}),y=f.dim(` (${n.length} turn${n.length===1?"":"s"})`),S=g+b.join(h)+y,w=Math.max(20,Q()-2);if(V(S)<=w)return S;let T=g+n.map(x=>Ow[x].color(Ow[x].glyph)).join(f.dim(" "))+y;return ne(T,w)}return{push(g){n.push(g.kind),n.length>t&&(n=n.slice(n.length-t)),d()},reset(){n=[],s&&i>0&&(p(),i=0,a?.(0))},entries(){return n},render(){return m()},setRowCountChangeHandler(g){a=g},start(g){s||(s=!0,r=g.stream??process.stdout,o=g.getAdjacentRows??(()=>0),i=0,l=He.subscribe(()=>d()),d())},stop(){s&&(s=!1,l!==null&&(l(),l=null),i>0&&(p(),i=0,a?.(0)),r=null)},repaint(){d()}}}var a$=["\u25D0","\u25D1","\u25D2","\u25D3"],Mm=class{stream;registry;throttleMs;started=!1;lastRepaint=0;spinnerIndex=0;spinnerInterval=null;resizeUnsub=null;resizeImmediateUnsub=null;registryStartedHandler=null;registrySettledHandler=null;rowCount=0;lastPaintStartRow=0;preResizeStartRow=null;preResizeRowCount=null;onRowCountChange;getAdjacentRows;constructor(t,n={}){this.registry=t,this.stream=n.stream??process.stdout,this.throttleMs=n.throttleMs??200,this.getAdjacentRows=n.getAdjacentRows??(()=>0)}setRowCountChangeHandler(t){this.onRowCountChange=t}start(){this.started||(this.started=!0,this.registry&&(this.registryStartedHandler=t=>{this.scheduleRepaint()},this.registrySettledHandler=t=>{this.scheduleRepaint()},this.registry.on("started",this.registryStartedHandler),this.registry.on("settled",this.registrySettledHandler)),this.resizeUnsub=He.subscribe(()=>this.repaint()),this.resizeImmediateUnsub=He.subscribeImmediate(()=>this.resetGeometry()),this.spinnerInterval=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%a$.length,this.rowCount>0&&this.repaint()},Math.max(this.throttleMs,50)))}stop(){this.started&&(this.started=!1,this.registry&&(this.registryStartedHandler&&(this.registry.off("started",this.registryStartedHandler),this.registryStartedHandler=null),this.registrySettledHandler&&(this.registry.off("settled",this.registrySettledHandler),this.registrySettledHandler=null)),this.resizeUnsub&&(this.resizeUnsub(),this.resizeUnsub=null),this.resizeImmediateUnsub&&(this.resizeImmediateUnsub(),this.resizeImmediateUnsub=null),this.spinnerInterval&&(clearInterval(this.spinnerInterval),this.spinnerInterval=null),this.rowCount>0&&(this.clearRows(),this.rowCount=0,this.onRowCountChange?.(0)))}resetGeometry(){this.rowCount>0&&(this.preResizeStartRow=this.lastPaintStartRow,this.preResizeRowCount=this.rowCount),this.rowCount=0,this.lastRepaint=0}scheduleRepaint(){Date.now()-this.lastRepaint<this.throttleMs||this.repaint()}redraw(){this.repaint()}repaint(){if(!this.started||!this.stream.isTTY)return;this.lastRepaint=Date.now();let t=(this.registry?.list()??[]).filter(i=>i.status==="running").map(i=>({kind:"subagent",job:i})),n=this.stream.rows??24,r=this.getAdjacentRows(),o=Math.max(0,Math.min(t.length,n-1-r));if(this.clearPreResizeRows(),o!==this.rowCount&&(this.rowCount>0&&this.clearRows(),this.rowCount=o,this.onRowCountChange?.(o)),o===0)return;let s=Math.max(1,n-o-r);this.lastPaintStartRow=s,this.stream.write("\x1B[s");for(let i=0;i<o;i++){let a=t[i],l=s+i;this.stream.write(`\x1B[${l};1H`),this.stream.write("\x1B[2K"),this.stream.write(this.formatItemLine(a))}this.stream.write("\x1B[u")}clearRows(){if(!this.stream.isTTY)return;let t=this.stream.rows??24,n=this.getAdjacentRows(),r=Math.min(this.rowCount,t-1-n),o=Math.max(1,t-r-n);this.stream.write("\x1B[s");for(let s=0;s<r;s++)this.stream.write(`\x1B[${o+s};1H`),this.stream.write("\x1B[2K");this.stream.write("\x1B[u")}clearPreResizeRows(){let t=this.preResizeStartRow,n=this.preResizeRowCount;if(this.preResizeStartRow=null,this.preResizeRowCount=null,t===null||n===null||!this.stream.isTTY)return;let r=this.stream.rows??24,o=[];for(let s=0;s<n;s++){let i=t+s;i<=r&&o.push(i)}if(o.length!==0){this.stream.write("\x1B[s");for(let s of o)this.stream.write(`\x1B[${s};1H`),this.stream.write("\x1B[2K");this.stream.write("\x1B[u")}}formatItemLine(t){return this.formatJobLine(t.job)}formatJobLine(t){let n=Math.max(4,(this.stream.columns??80)-2),r=f.brand(a$[this.spinnerIndex]),o=f.dim(t.jobId),s=f.bold(t.label||t.jobId),i=[r,o,s],a=Date.now()-t.startedAt;return i.push(f.dim(ge(a))),ne(" "+i.join(" "),n)}};import{spawn as k9}from"node:child_process";var E9=/\x1b(?:\[[0-9;]*[a-zA-Z]|[\]P^_X][^\x07\x1b]*(?:\x07|\x1b\\)|[@-OQ-WYZ\\])/g;function T9(){let e="";return{strip(t){let r=(e+t).replace(E9,""),o=r.match(/\x1b(?:[\]P^_X][^\x07\x1b]*|\[[0-9;]*)?$/);return o?(e=o[0],r.slice(0,r.length-e.length)):(e="",r)},flush(){return e="",""}}}function l$(e,t){if(e.length<=t)return e;let n=t;for(;n>0&&(e[n]&192)===128;)n--;return e.subarray(0,n)}var c$=12e4,u$=1e5;function $w(e){let t=Date.now(),n=e.timeoutMs??c$,r=e.maxBytes??u$,o=T9(),s;try{s=k9(e.command,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...e.cwd!==void 0?{cwd:e.cwd}:{},...e.env!==void 0?{env:{...process.env,...e.env}}:{}})}catch(x){let C=x instanceof Error?x.message:String(x);return{pid:void 0,kill:()=>{},promise:Promise.resolve({exitCode:null,durationMs:Date.now()-t,displayCaptured:"",modelCaptured:"",truncated:!1,errorReason:"spawn-failed",errorMessage:`Failed to spawn shell: ${C}`})}}s.unref();let i,a=!1,l=new Promise(x=>{i=C=>{a||(a=!0,x(C))}}),c="",u="",d=0,p=0,m=!1,g=!1,h=!1;function b(x){let C=r-d;if(C>0){let R=x.length<=C?x:l$(x,C);d+=R.length,c+=R.toString("utf8"),x.length>C&&(m=!0)}else x.length>0&&(m=!0);if(p<r){let R=o.strip(x.toString("utf8")),k=Buffer.byteLength(R,"utf8"),$=r-p;if(k<=$)u+=R,p+=k;else{let A=Buffer.from(R,"utf8");u+=l$(A,$).toString("utf8"),p=r,m=!0}}}function y(){if(s.pid!==void 0&&s.pid!==0&&!s.killed)try{process.kill(-s.pid,"SIGKILL")}catch{}}let S=setTimeout(()=>{y(),e.abort.removeEventListener("abort",w),i({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m,errorReason:"timeout",errorMessage:`Command timed out after ${n}ms`})},n),w=()=>{y(),clearTimeout(S),i({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m,errorReason:"abort",errorMessage:h?"Command killed":"Command aborted"})};e.abort.addEventListener("abort",w);function T(){g||a||d<r&&p<r||(g=!0,y(),clearTimeout(S),e.abort.removeEventListener("abort",w),i({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:!0,errorReason:"overflow",errorMessage:`Output exceeded ${r} bytes`}))}return s.stdout?.on("data",x=>{b(x);try{e.onChunk?.(x,"stdout")}catch{}T()}),s.stderr?.on("data",x=>{b(x);try{e.onChunk?.(x,"stderr")}catch{}T()}),s.on("error",x=>{clearTimeout(S),e.abort.removeEventListener("abort",w),i({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m,errorReason:"spawn-failed",errorMessage:`Shell process error: ${x.message}`})}),s.on("close",(x,C)=>{if(clearTimeout(S),e.abort.removeEventListener("abort",w),!(g||a)){if(o.flush(),h){i({exitCode:x,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m,errorReason:"abort",errorMessage:"Command killed"});return}if(x!==null&&x!==0){i({exitCode:x,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m,errorReason:"nonzero-exit",errorMessage:`Command exited with code ${x}`});return}if(x===null){i({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m,errorReason:"signal-killed",errorMessage:C?`Command killed by signal ${C}`:"Command killed by signal"});return}i({exitCode:x,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m})}}),{pid:s.pid,promise:l,kill:(x="SIGKILL")=>{if(!(s.pid===void 0||s.pid===0||s.killed)){h=!0;try{process.kill(-s.pid,x)}catch{}}}}}import{EventEmitter as x9}from"node:events";var d$=200,Yl=class extends x9{jobs=new Map;handles=new Map;aborts=new Map;counter=0;start(t){let n=`sh-${++this.counter}`,r=new AbortController,o=$w({command:t.command,...t.cwd!==void 0?{cwd:t.cwd}:{},abort:r.signal,...t.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{},...t.maxBytes!==void 0?{maxBytes:t.maxBytes}:{},...t.env!==void 0?{env:t.env}:{},...t.onChunk!==void 0?{onChunk:t.onChunk}:{}}),s={id:n,command:t.command,pid:o.pid,startedAt:Date.now(),mode:t.mode,status:"running"};return this.jobs.set(n,s),this.handles.set(n,o),this.aborts.set(n,r),o.promise.then(i=>{s.result=i,s.status=R9(i),this.aborts.delete(n),this.handles.delete(n);try{this.emit("complete",s)}catch(a){console.warn(`[shell-jobs] listener for 'complete' threw on ${n}: ${a instanceof Error?a.message:String(a)}`)}this.pruneHistory()}),{job:s,handle:o}}get(t){return this.jobs.get(t)}list(){return[...this.jobs.values()].sort((t,n)=>t.startedAt-n.startedAt)}running(){return this.list().filter(t=>t.status==="running")}kill(t){let n=this.jobs.get(t);if(!n||n.status!=="running")return!1;let r=this.aborts.get(t);if(r)return r.abort(),!0;let o=this.handles.get(t);return o?(o.kill(),!0):!1}killAll(){let t=this.running();for(let n of t)this.kill(n.id);return t}runningCount(){let t=0;for(let n of this.jobs.values())n.status==="running"&&t++;return t}pruneHistory(){if(!(this.jobs.size<=d$))for(let[t,n]of this.jobs){if(this.jobs.size<=d$)break;n.status!=="running"&&this.jobs.delete(t)}}};function R9(e){return e.errorReason===void 0?"completed":e.errorReason==="abort"?"killed":"failed"}function C9(e){if(!e.startsWith("!"))return null;if(e.startsWith("!&")){let n=e.slice(2).trim();return n.length===0?null:{mode:"background",command:n}}let t=e.slice(1).trim();return t.length===0?null:{mode:"foreground",command:t}}function A9(e,t){let n=ge(t.durationMs);return t.errorReason==="abort"?f.dim(` [${e.id} \xB7 killed \xB7 ${n}]`):t.errorReason==="timeout"?f.dim(` [${e.id} \xB7 timed out \xB7 ${n}]`):t.errorReason==="overflow"?f.dim(` [${e.id} \xB7 output overflow \xB7 ${n}]`):t.errorReason==="spawn-failed"?f.warning(` [${e.id} \xB7 spawn failed \xB7 ${n}]`):t.errorReason==="nonzero-exit"?f.warning(` [${e.id} \xB7 exit ${t.exitCode} \xB7 ${n}]`):t.errorReason==="signal-killed"?f.warning(` [${e.id} \xB7 killed by signal \xB7 ${n}]`):f.dim(` [${e.id} \xB7 exit ${t.exitCode??0} \xB7 ${n}]`)}function p$(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function _9(e,t,n){let r=[],o=[`mode="${t}"`];return n.exitCode!==null&&o.push(`exit="${n.exitCode}"`),n.errorReason!==void 0&&o.push(`reason="${n.errorReason}"`),o.push(`duration="${ge(n.durationMs)}"`),n.truncated&&o.push('truncated="true"'),r.push(`<bash-passthrough ${o.join(" ")}>`),r.push(`<command>${p$(e)}</command>`),r.push("<output>"),r.push(p$(n.modelCaptured)),r.push("</output>"),r.push("</bash-passthrough>"),r.join(`
|
|
2004
2004
|
`)}var Om=class e{constructor(t){this.opts=t;this.registry.on("complete",n=>{if(n.mode!=="background")return;let r=n.result;r&&(this.queueInjection({command:n.command,mode:"background",result:r}),this.pendingNotifications.push({job:n,result:r}),this.pendingNotifications.length>e.MAX_PENDING_NOTIFICATIONS&&this.pendingNotifications.shift())})}opts;registry=new Yl;pendingInjections=[];pendingNotifications=[];activeFgJobId=null;static MAX_PENDING_INJECTIONS=25;static MAX_PENDING_NOTIFICATIONS=50;async dispatch(t){let n=C9(t);return n===null?t==="!"||t==="!&"||t.startsWith("! ")||t.startsWith("!& ")?(this.opts.writeLine(f.dim(" usage: !<cmd> (foreground) !&<cmd> (background)")),!0):!1:(n.mode==="foreground"?await this.runForeground(n.command):this.startBackground(n.command),!0)}drainInjections(){if(this.pendingInjections.length===0)return"";let t=this.pendingInjections.map(n=>_9(n.command,n.mode,n.result));return this.pendingInjections=[],t.join(`
|
|
2005
2005
|
`)+`
|
|
2006
2006
|
`}drainNotifications(){if(this.pendingNotifications.length===0)return[];let t=this.pendingNotifications;return this.pendingNotifications=[],t}abortActiveForeground(){return this.activeFgJobId===null?!1:(this.registry.kill(this.activeFgJobId),!0)}hasActiveForeground(){return this.activeFgJobId!==null}drainOnExit(){let t=this.registry.killAll();t.length>0&&this.opts.writeLine(f.dim(` Killing ${t.length} background shell job${t.length===1?"":"s"} on exit.`))}async runForeground(t){this.opts.writeLine(f.dim(`$ ${t}`));let n="",r=!1,o=()=>{let c;for(;(c=n.indexOf(`
|
|
2007
|
-
`))!==-1;){let u=n.slice(0,c);n=n.slice(c+1),this.opts.writeLine(u)}},s={command:t,mode:"foreground",onChunk:c=>{r||(n+=c.toString("utf8"),o())}},i=this.opts.getCwd();i!==void 0&&(s.cwd=i);let{job:a,handle:l}=this.registry.start(s);this.activeFgJobId=a.id;try{let c=await l.promise;r=!0,n.length>0&&(this.opts.writeLine(n),n=""),this.opts.writeLine(A9(a,c)),this.queueInjection({command:t,mode:"foreground",result:c})}finally{this.activeFgJobId=null}}startBackground(t){let n={command:t,mode:"background"},r=this.opts.getCwd();r!==void 0&&(n.cwd=r);let{job:o}=this.registry.start(n);this.opts.writeLine(f.dim(` [${o.id}] background: `)+t)}queueInjection(t){this.pendingInjections.push(t),this.pendingInjections.length>e.MAX_PENDING_INJECTIONS&&this.pendingInjections.shift()}};function m$(e,t){let n=s$(),r=i$();e.clearVerdictLedger=()=>r.reset();let o=0,s=0,i=1,a=()=>e.statusLine.setExtraRows(i+o+s),l,c;r.setRowCountChangeHandler(d=>{s=d,a(),l?.redraw(),c?.redraw()}),l=new Mm(e.backgroundRegistry,{getAdjacentRows:()=>s}),l.setRowCountChangeHandler(d=>{o=d,a()}),c=new qp({getExtraRows:()=>e.statusLine.getExtraRows()}),c.setRowCountChangeHandler(d=>{a()}),e.statusLine.setAfterScrollRestore(()=>{r.repaint(),l?.redraw(),c?.redraw()}),l.start(),c.start(),r.start({stream:process.stdout});let u=new Om({writeLine:d=>e.replRenderer.writeLine(d),getCwd:()=>e.stats.cwd});return MP(u),t.tryAbortShellForeground=()=>u.abortActiveForeground(),{contextPane:n,bgStatusBar:l,loopStageBar:c,verdictLedger:r,shellPassthrough:u}}Me();_o();q();
|
|
2007
|
+
`))!==-1;){let u=n.slice(0,c);n=n.slice(c+1),this.opts.writeLine(u)}},s={command:t,mode:"foreground",onChunk:c=>{r||(n+=c.toString("utf8"),o())}},i=this.opts.getCwd();i!==void 0&&(s.cwd=i);let{job:a,handle:l}=this.registry.start(s);this.activeFgJobId=a.id;try{let c=await l.promise;r=!0,n.length>0&&(this.opts.writeLine(n),n=""),this.opts.writeLine(A9(a,c)),this.queueInjection({command:t,mode:"foreground",result:c})}finally{this.activeFgJobId=null}}startBackground(t){let n={command:t,mode:"background"},r=this.opts.getCwd();r!==void 0&&(n.cwd=r);let{job:o}=this.registry.start(n);this.opts.writeLine(f.dim(` [${o.id}] background: `)+t)}queueInjection(t){this.pendingInjections.push(t),this.pendingInjections.length>e.MAX_PENDING_INJECTIONS&&this.pendingInjections.shift()}};function m$(e,t){let n=s$(),r=i$();e.clearVerdictLedger=()=>r.reset();let o=0,s=0,i=1,a=()=>e.statusLine.setExtraRows(i+o+s),l,c;r.setRowCountChangeHandler(d=>{s=d,a(),l?.redraw(),c?.redraw()}),l=new Mm(e.backgroundRegistry,{getAdjacentRows:()=>s}),l.setRowCountChangeHandler(d=>{o=d,a()}),c=new qp({getExtraRows:()=>e.statusLine.getExtraRows()}),c.setRowCountChangeHandler(d=>{a()}),e.statusLine.setAfterScrollRestore(()=>{r.repaint(),l?.redraw(),c?.redraw()}),l.start(),c.start(),r.start({stream:process.stdout});let u=new Om({writeLine:d=>e.replRenderer.writeLine(d),getCwd:()=>e.stats.cwd});return MP(u),t.tryAbortShellForeground=()=>u.abortActiveForeground(),{contextPane:n,bgStatusBar:l,loopStageBar:c,verdictLedger:r,shellPassthrough:u}}Me();_o();q();bt();Ia();Me();er();function f$(e){if(!e)return null;let t=e.split(`
|
|
2008
2008
|
`),n=t.slice(Math.max(0,t.length-40)),r=-1,o=null;for(let l=n.length-1;l>=0;l--){let c=n[l]??"",u=I9(c);if(u){r=l,o=u;break}}if(o===null||r<0)return null;let s=n.slice(r+1).map(l=>l.trim());for(;s.length>0&&s[0]==="";)s.shift();for(;s.length>0&&s[s.length-1]==="";)s.pop();let i=P9(s),a=s.join(`
|
|
2009
2009
|
`).trim();return{kind:o,rawBody:a,...M9(o,i)}}function I9(e){let t=e.trim().replace(/^#{1,6}\s+/,"").replace(/^[-•▶▸]\s+/,"").replace(/^\*\s+/,"").replace(/^\*\*(.+?)\*\*$/,"$1").replace(/^__(.+?)__$/,"$1").replace(/^\*(.+?)\*$/,"$1").replace(/^_(.+?)_$/,"$1").replace(/[.:!?\s]+$/,"").trim();if(t.length===0||t.length>24)return null;let n=t.toLowerCase();return n==="done"?"done":n==="blocked"?"blocked":n==="asking"?"asking":n==="interrupted"?"interrupted":null}function P9(e){let t=[];for(let n of e){let r=n.trim();if(r==="")continue;let o=/^(?:[-*•▶▸]|\d+[.)])\s+(.*)$/.exec(r),s=o?(o[1]??"").trim():r;if(!o&&t.length>0&&r.length>0){let a=t[t.length-1];a.value=`${a.value} ${r}`.trim();continue}let i=s.indexOf(":");if(i>0&&i<60){let a=s.slice(0,i).trim().replace(/^\*\*(.+?)\*\*$/,"$1").replace(/^__(.+?)__$/,"$1").replace(/^(?:\*\*|__)\s*/,"").toLowerCase(),l=s.slice(i+1).trim().replace(/^(?:\*\*|__)\s/,"");t.push({label:a,value:l})}else t.push({label:"",value:s})}return t}function M9(e,t){let n=(...r)=>{for(let o of t)if(o.label!==""){for(let s of r)if(o.label.includes(s))return o.value}};switch(e){case"done":{let r={},o=n("what was done","what i did","completed","done");o!==void 0&&(r.whatWasDone=o);let s=n("evidence","what changed","change","artifact","output");s!==void 0&&(r.evidence=s);let i=n("pending","deferred","follow-up","followup","next");return i!==void 0&&(r.deferred=i),r}case"blocked":{let r={},o=n("what blocks","blocker","blocked by");o!==void 0&&(r.whatBlocks=o);let s=n("unblock","must change","to unblock","condition");s!==void 0&&(r.unblockCondition=s);let i=n("has already","been done","already done","what has been done","progress");return i!==void 0&&(r.alreadyDone=i),r}case"asking":{let r={},o=n("question","asking");o!==void 0&&(r.question=o);let s=n("assumption","resolves");s!==void 0&&(r.assumption=s);let i=n("once answered","follow-up","next","will do","after");return i!==void 0&&(r.followup=i),r}case"interrupted":{let r={},o=n("what you were doing","in progress","doing","task");o!==void 0&&(r.whatWasInProgress=o);let s=n("state was saved","state","saved","where");s!==void 0&&(r.stateLocation=s);let i=n("resumption","resume","requires");return i!==void 0&&(r.resumeRequires=i),r}}}var O9={done:{color:f.success,chip:"\u2713 Done",affordance:"Objective satisfied - review evidence and close."},blocked:{color:f.error,chip:"\u2298 Blocked",affordance:"External dependency - unblock above to resume."},asking:{color:f.warning,chip:"? Asking",affordance:"Waiting on you - answer above to continue."},interrupted:{color:f.meta,chip:"\u23F8 Interrupted",affordance:"Halted with state preserved - resume when ready."}};function g$(e){let t=O9[e.kind],n=Math.max(34,Math.min(Q()-6,100)),r=n+4,o=t.color("\u256D\u2500")+t.color.call(null,` ${t.chip} `)+t.color("\u2500".repeat(Math.max(0,r-1-V(` ${t.chip} `)))+"\u256E"),s=t.color("\u2570"+"\u2500".repeat(r)+"\u256F"),i=t.color("\u2502"),a=i+" ".repeat(n+4)+i,l=$9(e),c=l.reduce((m,g)=>Math.max(m,V(g.label)),0),u=Math.max(8,n-c-2),d=[o,a];if(l.length===0){let m=e.rawBody.split(`
|
|
2010
2010
|
`).find(b=>b.trim().length>0)?.trim()??"",g=m.length>0?m:`${e.kind} (no structured fields)`,h=le(Ir(g),n).split(`
|
|
@@ -2013,8 +2013,8 @@ _ended: ${new Date().toISOString()}_
|
|
|
2013
2013
|
`)}function $9(e){let t=[],n=(r,o)=>{o&&o.trim().length>0&&t.push({label:r,value:o.trim()})};switch(e.kind){case"done":n("done",e.whatWasDone),n("evidence",e.evidence),e.deferred?.trim()!==e.whatWasDone?.trim()&&n("deferred",e.deferred);break;case"blocked":n("blocks",e.whatBlocks),n("unblock",e.unblockCondition),n("progress",e.alreadyDone);break;case"asking":n("question",e.question),n("resolves",e.assumption),n("after",e.followup);break;case"interrupted":n("was doing",e.whatWasInProgress),n("saved at",e.stateLocation),n("resume",e.resumeRequires);break}return t}Ot();function h$(e,t,n,r){let o=[];return n&&n.trim().length>0&&o.push({type:"text",text:n}),r&&r.length>0&&o.push(...r),e&&o.push({type:"text",text:e}),im(o,t),o}import{readFileSync as D9,statSync as L9}from"fs";import{extname as F9,join as y$}from"path";import{homedir as N9}from"os";Na();var B9=100*1024,U9=400*1024,j9=/(?<=\s|^)@([~\w./-]+)(?=\s|$)/g,H9=/(^|\/)\.(ssh|aws|gnupg|kube|docker)(\/|$)|(^|\/)[^/]*\.env(\.[^/]+)?$|(^|\/)\.(netrc|npmrc|pypirc)$|(^|\/)id_(rsa|ed25519|ecdsa|dsa)(\.pub)?$|\.(pem|key|p12|pfx)$|(^|\/)credentials$|(^|\/)\.git\/config$|(^|\/)\.git-credentials$|(^|\/)\.(bash|zsh|fish|sh)_history$/i,W9=[".afk/config",".afk/state",".config/gcloud",".config/gh"];function K9(e){let t=0,n=e.match(/`+/g);if(n)for(let r of n)r.length>t&&(t=r.length);return"`".repeat(Math.max(3,t+1))}function G9(e,t){if(H9.test(e))return!0;for(let n of t)if(e===n||e.startsWith(n+"/"))return!0;return!1}var q9={".ts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"jsx",".mjs":"javascript",".cjs":"javascript",".json":"json",".md":"markdown",".py":"python",".sh":"bash",".bash":"bash",".zsh":"bash",".yaml":"yaml",".yml":"yaml",".toml":"toml",".rs":"rust",".go":"go",".rb":"ruby",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cs":"csharp",".html":"html",".css":"css",".scss":"scss",".sql":"sql",".xml":"xml",".txt":""};function z9(e){return q9[e.toLowerCase()]??""}function J9(e=process.env){return e.AFK_AT_FILE_INJECT!=="0"}function b$(e,t={}){let n={fileBlocks:[],warnings:[]};if(!J9(t.env))return n;let r=[];for(let d of e.matchAll(j9)){let p=d[1];p&&r.push(p)}if(r.length===0)return n;let o=t.rootDir??process.cwd(),s=t.homeDir??N9(),i=W9.map(d=>ir(y$(s,d))),a=[],l=[],c=new Set,u=0;for(let d of r){let{scanDir:p,leafPrefix:m}=Op(d,o,s),g=m?y$(p,m):p,h=ir(g);if(c.has(h))continue;if(c.add(h),G9(h,i)){l.push(`@${d}: sensitive path, not injected`);continue}let b;try{b=L9(h)}catch{l.push(`@${d}: not found, left as text`);continue}if(b.isDirectory()){l.push(`@${d}: is a directory, skipped`);continue}if(!b.isFile()){l.push(`@${d}: not a regular file, skipped`);continue}if(b.size>B9){l.push(`@${d}: too large (${Math.round(b.size/1024)} KB > 100 KB), skipped`);continue}if(u+b.size>U9){l.push(`@${d}: 400 KB total injection budget exceeded, skipped`);continue}let y;try{y=D9(h)}catch{l.push(`@${d}: could not read, skipped`);continue}if(y.includes(0)){l.push(`@${d}: binary file, skipped`);continue}u+=b.size;let S=z9(F9(h)),w=y.toString("utf8"),T=K9(w);a.push({type:"text",text:`Contents of ${d}:
|
|
2014
2014
|
${T}${S}
|
|
2015
2015
|
${w}
|
|
2016
|
-
${T}`})}return{fileBlocks:a,warnings:l}}async function w$(e,t,n,r,o="summary",s,i){let a=gM(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 Vi({out:Yi(s),thinkingMode:o,...C?{activeSkillName:C}:{},onCancel:()=>{t.interrupt().catch(D=>{Ke()&&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=>{Ke()&&console.error(" "+f.error("soft-stop session.interrupt() failed:"),I)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{b=!0,t.interrupt().catch(I=>{Ke()&&console.error(" "+f.error("pause-interrupt session.interrupt() failed:"),I)})}),await F(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(R);let{fileBlocks:D,warnings:N}=b$(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?h$(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){Ke()&&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."),""];Im(k,{header:X,options:[j,Y,oe],signal:U.signal,initialIndex:0}).then(pe=>{if(y.abort=null,!pe)return;let J=pe[0];J===void 0||J===j||(b=!0,J===Y&&(s??{fn:console.log}).fn(f.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(Ae=>{Ke()&&console.error(" "+f.error("picker pause-interrupt session.interrupt() failed:"),Ae)}))}).catch(pe=>{Ke()&&console.error(" "+f.error("picker promise rejected:"),pe)})}else(s??{fn:console.log}).fn(Tv({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){Uo(n,a,l,g,T),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),up(process.stdout);let I=M=>{s?s.fn(M):console.log(M)},U=f$(l);if(U){if(I(g$(U)),I(""),r.onTerminalState)try{r.onTerminalState(U)}catch{}if(n.permissionMode==="autonomous"){let M=U.kind==="done"&&Su().verifyDone===!0&&!jI(T);WI(U,void 0,{unverified:M})}}if(V9(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 V9(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(fe(e.durationMs)),e.totalCostUsd!==void 0&&r.push(st(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=sb(t),a=$t(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 Y9=5e3;async function X9(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 S$(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=>{Ke()&&(p=wp(y)),await um(e.session.current),Ke()&&(m=fO())}).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 $=ea(e.stats.permissionMode),A=Jo({buffer:k.text,promptText:$,isTTY:!!process.stdout.isTTY,attachmentSummary:ji([...k.attachments])});e.replRenderer.writeLine(A),w=k.text.trim(),T=k.attachments}else{let k=await o.readLine({promptFn:()=>ea(e.stats.permissionMode),onSigint:r,onShiftTab:()=>{Pm(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 OI(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 X9(e,w);let C=w;if(x){let k=ob(w);if(k){let $=k.name.replace(/^\//,"").split(":").pop()??"";if($&&dw($)){let A={skillName:$,rawArgs:k.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},P=e.session.current.sessionId,F=rs(P),D=Date.now();z(`[afk trace] preflight.start commandName=${$}`);let N=!1,B=await ns(A,{cwd:e.stats.cwd??process.cwd(),artifactDir:F},H=>{Ke()&&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=mw(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 we){e.replRenderer.writeLine(f.warning("\u2298 Turn blocked by hook")+(k.reason?f.dim(`: ${Ao(k.reason)}`):"")),e.statusLine.rearm();continue}if(k instanceof vn){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 w$({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{Ln(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(Bn(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:k=>c.repaint(k)}:{}},e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(ea(e.stats.permissionMode))),e.hookRegistry)try{await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId},void 0,Y9)}catch(k){if(k instanceof at)throw k;k instanceof vn?(z("[stop hook] handler timed out"),e.completionWriter.fn(f.dim(" [stop hook] timed out"))):k instanceof we?e.completionWriter.fn(f.dim(` [stop hook] blocked: ${Ao(k.reason??"no reason given")}`)):z("[stop hook] unexpected error: "+String(k))}}}function Z9(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 v$(e,t,n,r){let o=await ZO(),s=new _m({rl:e.rl,history:o,statusLine:e.statusLine}),i=Z9(v.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await o$(e,s,n,t,r,i,{getLoopStageBar:()=>a?.loopStageBar});a=m$(e,n),await S$(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)}}Ba();import{execFile as Q9}from"node:child_process";import{dirname as e7,isAbsolute as t7,resolve as n7}from"node:path";import{promisify as r7}from"node:util";var k$=r7(Q9),o7=3e3,s7=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function i7(){let t=(await k$("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=t7(t)?t:n7(process.cwd(),t);return e7(n)}async function E$(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await i7()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),o7)});try{let o=jn({execFile:k$,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=>s7.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}Uc();Ba();import{promises as a7}from"node:fs";import{dirname as l7,join as R$}from"node:path";import{randomBytes as c7}from"node:crypto";var u7=["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(`
|
|
2017
|
-
`),T$=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Dw=30,d7=1024,p7=8e3,m7="haiku";async function f7(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=b7(n,d7),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??p7),i=t.signal?w7([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??m7,system:u7,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=g7(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=l7(t.worktreePath);return await h7(l,c)}function g7(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(T$.test(t)&&t.length<=Dw)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>Dw)break;o=i}return T$.test(o)?o:null}async function h7(e,t){if(!await y7(R$(t,e)))return e;let n=c7(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Dw-5)}-${n}`}async function y7(e){try{return await a7.access(e),!0}catch{return!1}}function b7(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 w7(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 C$(e){let t,n,r=R$(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await f7(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=`${hu(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return x$(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 x$(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 x$(e,t){e&&e.setCwd(t),S7(t)}function S7(e){try{process.chdir(e)}catch{}}Je();Ot();K();import{spawn as _$}from"child_process";import{existsSync as I$,mkdirSync as x7,readFileSync as P$,unlinkSync as A$,writeFileSync as R7}from"fs";import{get as C7}from"https";import{join as M$}from"path";import{readFileSync as v7}from"fs";import{dirname as k7,join as E7}from"path";import{fileURLToPath as T7}from"url";function xr(){try{return"5.
|
|
2016
|
+
${T}`})}return{fileBlocks:a,warnings:l}}async function w$(e,t,n,r,o="summary",s,i){let a=gM(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 Vi({out:Yi(s),thinkingMode:o,...C?{activeSkillName:C}:{},onCancel:()=>{t.interrupt().catch(D=>{Ke()&&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=>{Ke()&&console.error(" "+f.error("soft-stop session.interrupt() failed:"),I)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{b=!0,t.interrupt().catch(I=>{Ke()&&console.error(" "+f.error("pause-interrupt session.interrupt() failed:"),I)})}),await F(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(R);let{fileBlocks:D,warnings:N}=b$(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?h$(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){Ke()&&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."),""];Im(k,{header:X,options:[j,Y,oe],signal:U.signal,initialIndex:0}).then(me=>{if(y.abort=null,!me)return;let J=me[0];J===void 0||J===j||(b=!0,J===Y&&(s??{fn:console.log}).fn(f.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(Ae=>{Ke()&&console.error(" "+f.error("picker pause-interrupt session.interrupt() failed:"),Ae)}))}).catch(me=>{Ke()&&console.error(" "+f.error("picker promise rejected:"),me)})}else(s??{fn:console.log}).fn(Tv({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){Uo(n,a,l,g,T),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),up(process.stdout);let I=M=>{s?s.fn(M):console.log(M)},U=f$(l);if(U){if(I(g$(U)),I(""),r.onTerminalState)try{r.onTerminalState(U)}catch{}if(n.permissionMode==="autonomous"){let M=U.kind==="done"&&Su().verifyDone===!0&&!jI(T);WI(U,void 0,{unverified:M})}}if(V9(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 V9(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(ge(e.durationMs)),e.totalCostUsd!==void 0&&r.push(st(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=sb(t),a=$t(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 Y9=5e3;async function X9(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 S$(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=>{Ke()&&(p=wp(y)),await um(e.session.current),Ke()&&(m=fO())}).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 $=ea(e.stats.permissionMode),A=Jo({buffer:k.text,promptText:$,isTTY:!!process.stdout.isTTY,attachmentSummary:ji([...k.attachments])});e.replRenderer.writeLine(A),w=k.text.trim(),T=k.attachments}else{let k=await o.readLine({promptFn:()=>ea(e.stats.permissionMode),onSigint:r,onShiftTab:()=>{Pm(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 OI(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 X9(e,w);let C=w;if(x){let k=ob(w);if(k){let $=k.name.replace(/^\//,"").split(":").pop()??"";if($&&dw($)){let A={skillName:$,rawArgs:k.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},P=e.session.current.sessionId,F=rs(P),D=Date.now();z(`[afk trace] preflight.start commandName=${$}`);let N=!1,B=await ns(A,{cwd:e.stats.cwd??process.cwd(),artifactDir:F},H=>{Ke()&&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=mw(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 pe){e.replRenderer.writeLine(f.warning("\u2298 Turn blocked by hook")+(k.reason?f.dim(`: ${Ao(k.reason)}`):"")),e.statusLine.rearm();continue}if(k instanceof vn){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 w$({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{Ln(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(Bn(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:k=>c.repaint(k)}:{}},e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(ea(e.stats.permissionMode))),e.hookRegistry)try{await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId},void 0,Y9)}catch(k){if(k instanceof at)throw k;k instanceof vn?(z("[stop hook] handler timed out"),e.completionWriter.fn(f.dim(" [stop hook] timed out"))):k instanceof pe?e.completionWriter.fn(f.dim(` [stop hook] blocked: ${Ao(k.reason??"no reason given")}`)):z("[stop hook] unexpected error: "+String(k))}}}function Z9(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 v$(e,t,n,r){let o=await ZO(),s=new _m({rl:e.rl,history:o,statusLine:e.statusLine}),i=Z9(v.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await o$(e,s,n,t,r,i,{getLoopStageBar:()=>a?.loopStageBar});a=m$(e,n),await S$(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)}}Ba();import{execFile as Q9}from"node:child_process";import{dirname as e7,isAbsolute as t7,resolve as n7}from"node:path";import{promisify as r7}from"node:util";var k$=r7(Q9),o7=3e3,s7=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function i7(){let t=(await k$("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=t7(t)?t:n7(process.cwd(),t);return e7(n)}async function E$(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await i7()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),o7)});try{let o=jn({execFile:k$,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=>s7.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}Uc();Ba();import{promises as a7}from"node:fs";import{dirname as l7,join as R$}from"node:path";import{randomBytes as c7}from"node:crypto";var u7=["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(`
|
|
2017
|
+
`),T$=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Dw=30,d7=1024,p7=8e3,m7="haiku";async function f7(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=b7(n,d7),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??p7),i=t.signal?w7([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??m7,system:u7,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=g7(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=l7(t.worktreePath);return await h7(l,c)}function g7(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(T$.test(t)&&t.length<=Dw)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>Dw)break;o=i}return T$.test(o)?o:null}async function h7(e,t){if(!await y7(R$(t,e)))return e;let n=c7(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Dw-5)}-${n}`}async function y7(e){try{return await a7.access(e),!0}catch{return!1}}function b7(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 w7(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 C$(e){let t,n,r=R$(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await f7(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=`${hu(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return x$(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 x$(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 x$(e,t){e&&e.setCwd(t),S7(t)}function S7(e){try{process.chdir(e)}catch{}}Je();Ot();K();import{spawn as _$}from"child_process";import{existsSync as I$,mkdirSync as x7,readFileSync as P$,unlinkSync as A$,writeFileSync as R7}from"fs";import{get as C7}from"https";import{join as M$}from"path";import{readFileSync as v7}from"fs";import{dirname as k7,join as E7}from"path";import{fileURLToPath as T7}from"url";function xr(){try{return"5.9.0"}catch{}try{let e=k7(T7(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(v7(E7(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}q();var A7=64*1024,_7=1440*60*1e3,I7=3600*1e3,P7="update-check.json",M7="pending-update.json";function O$(){return M$(wc(),P7)}function Xl(){return M$(wc(),M7)}function $$(){let e=wc();I$(e)||x7(e,{recursive:!0})}function O7(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 $7(){try{let e=P$(O$(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function D7(){try{$$();let e=`
|
|
2018
2018
|
const https = require('https');
|
|
2019
2019
|
const fs = require('fs');
|
|
2020
2020
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|
|
@@ -2037,14 +2037,14 @@ ${T}`})}return{fileBlocks:a,warnings:l}}async function w$(e,t,n,r,o="summary",s,
|
|
|
2037
2037
|
${t}${n}Update available:${o} ${r}${e.currentVersion}${o} \u2192 ${n}${e.latestVersion}${o}
|
|
2038
2038
|
${r}Run \`npm install -g agent-afk\` to update${o}
|
|
2039
2039
|
`)}var Lw=/^\d+\.\d+\.\d+(-[\da-z.]+)?$/i;function Fw(e){if(Lw.test(e))try{$$(),R7(Xl(),JSON.stringify({targetVersion:e,triggeredAt:Date.now()}))}catch{}}function Nw(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=C7(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>A7){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"&&Lw.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 Bw(e){if(Lw.test(e)&&!I$(Xl()))try{Fw(e),_$("npm",["install","-g",`agent-afk@${e}`],{detached:!0,stdio:"ignore"}).unref()}catch{}}function L$(){try{let e=P$(Xl(),"utf-8"),t=JSON.parse(e);if(typeof t.targetVersion!="string")return;let n=xr();if(n===t.targetVersion){A$(Xl()),process.stderr.write(`\x1B[32m\x1B[1mUpdated to agent-afk v${n}\x1B[0m
|
|
2040
|
-
`);return}let r=typeof t.triggeredAt=="number"?t.triggeredAt:0;Date.now()-r>I7&&A$(Xl())}catch{}}var Dm=null;function B$(e,t){Dm={updateInfo:e,pendingMessage:t}}function F7(e){if(e==="summary"||e==="live"||e==="off")return e;throw new Error(`Invalid --thinking-ui value: ${e}. Expected summary|live|off`)}function N7(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 B7(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 U7(){return"/help \xB7 /model \xB7 @ for files \xB7 Shift+Tab mode \xB7 Esc to interrupt \xB7 /exit to quit"}function U$(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.",
|
|
2040
|
+
`);return}let r=typeof t.triggeredAt=="number"?t.triggeredAt:0;Date.now()-r>I7&&A$(Xl())}catch{}}var Dm=null;function B$(e,t){Dm={updateInfo:e,pendingMessage:t}}function F7(e){if(e==="summary"||e==="live"||e==="off")return e;throw new Error(`Invalid --thinking-ui value: ${e}. Expected summary|live|off`)}function N7(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 B7(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 U7(){return"/help \xB7 /model \xB7 @ for files \xB7 Shift+Tab mode \xB7 Esc to interrupt \xB7 /exit to quit"}function U$(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.",Et()).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",F7,"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?cs.join(N$.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=F$({text:"Initializing interactive session...",...Tl}).start();if(t.resume||t.continue)try{let L=_i({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)}
|
|
2041
2041
|
Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
2042
2042
|
`),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}
|
|
2043
2043
|
Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
2044
2044
|
`),process.exitCode=1;return}let r=_t(),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 E$({disabled:l}),u=B7(t,r),d=Ce(),p=t.worktree===!0&&u&&d!==void 0,m,g,h;if(t.worktree!==void 0)try{p?(h=await oE(a),n.text="Worktree will be named from your first message"):(g=await yu(t.worktree,a),m=g.path,n.text=`Worktree ready at ${g.path} (branch: ${g.branch})`)}catch(L){n.fail("Worktree setup failed"),G(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 GO(t,m!==void 0?{cwd:m}:void 0)}catch(L){n.fail("Invalid options"),G(L)}if(h!==void 0&&d!==void 0){let L=h,I=d;y.firstTurnHook=async U=>{let M=F$({text:"Naming & creating worktree\u2026",...Tl}).start(),j=await C$({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=cs.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=N7(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 ${El(process.cwd(),{maxWidth:60})} (no isolation).`))}}Wo(async()=>{y.teardownTrustedSkillEvents?.(),ct.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(El(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 JO(()=>y.stats.model);console.log(f.dim(` transcript: ${S.path()}`)),Wo(async()=>{await S.appendEnded()});let w=!1,T=()=>{if(y.stats.totalTurns===0)return;let L=Ln(y.stats);return w=!0,L};Wo(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=`
|
|
2045
2045
|
`+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(`
|
|
2046
2046
|
`+f.info("\u2139 ")+"Press Ctrl+C again (or /exit) to quit.")};process.on("SIGINT",R),Wo(async()=>{process.removeListener("SIGINT",R)});let k=!1,$=()=>{if(k)return;k=!0,y.session.current?.abort("sigterm");try{y.rl.close()}catch{}setTimeout(()=>{ap().finally(()=>process.exit(0))},2e3).unref()};process.on("SIGTERM",$),Wo(async()=>{process.removeListener("SIGTERM",$)});let A=!1,P=()=>{if(A)return;A=!0,y.session.current?.abort("sighup");try{y.rl.close()}catch{}setTimeout(()=>{ap().finally(()=>process.exit(0))},2e3).unref()};process.on("SIGHUP",P),Wo(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(Dm!==null){let{updateInfo:I,pendingMessage:U}=Dm;Dm=null,U!==null&&process.stderr.write(U),I!==null&&$m(I)}let L=y.resumeTarget?`Resuming ${y.resumeTarget.id} \xB7 ${y.stats.totalTurns} prior turn${y.stats.totalTurns===1?"":"s"}`:void 0;console.log(`
|
|
2047
|
-
`+vv({mode:"Interactive Mode",model:y.stats.model,version:xr(),...g!==void 0?{worktree:g.branch}:{},cwd:m??process.cwd(),...L!==void 0?{metaLine:L}:{},hintLine:U7()})),b!==void 0&&console.log(f.dim(` ${b}`)),y.resumeTarget&&bp(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(),j7(y,g,T),console.log(f.info("\u2139 ")+"Goodbye!"),await ap(),process.exit(0)}),await v$(y,S,x,R)})}function j7(e,t,n){if(e.stats.totalTurns===0)return;console.log(de("Session Summary"));let r=[`${e.stats.totalTurns} turn${e.stats.totalTurns===1?"":"s"}`,
|
|
2047
|
+
`+vv({mode:"Interactive Mode",model:y.stats.model,version:xr(),...g!==void 0?{worktree:g.branch}:{},cwd:m??process.cwd(),...L!==void 0?{metaLine:L}:{},hintLine:U7()})),b!==void 0&&console.log(f.dim(` ${b}`)),y.resumeTarget&&bp(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(),j7(y,g,T),console.log(f.info("\u2139 ")+"Goodbye!"),await ap(),process.exit(0)}),await v$(y,S,x,R)})}function j7(e,t,n){if(e.stats.totalTurns===0)return;console.log(de("Session Summary"));let r=[`${e.stats.totalTurns} turn${e.stats.totalTurns===1?"":"s"}`,ge(Date.now()-e.stats.sessionStartTime)];e.stats.totalCostUsd>0&&r.push(st(e.stats.totalCostUsd)),e.stats.totalTokens>0&&r.push(ie(e.stats.totalTokens)+" tokens"),console.log(f.dim(" "+r.join(" \xB7 ")));let o=t?cs.basename(t.path):"none";console.log(f.dim(` model: ${e.stats.model} \xB7 worktree: ${o}`));try{let i=e.stats.cwd??process.cwd(),l=L7("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=cs.basename(i,".json"))}catch{}s&&console.log(f.dim(" Continue with: ")+f.brand(Fn(s,e.stats.model))),console.log()}q();import H7 from"ora";li();rt();Je();Ot();function j$(e){e.command("status").description("Check agent connection status").option("-f, --format <format>","Output format (text|json)","text").action(async t=>{let n=H7("Checking status...").start();try{let r=Et(),o=re(r),s=ze(r),i=o==="openai-compatible"||o==="openai-codex";await new kt({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=Ce(),u=kd(),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(`
|
|
2048
2048
|
`+hv("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])+`
|
|
2049
2049
|
`)}}catch(r){n.fail("Connection failed"),G(r)}})}q();import{readFileSync as W7}from"fs";rt();Ot();import H$ from"chalk";function Lm(e){return process.stdin.isTTY||(console.error(H$.red(`Cannot securely prompt for secret on a non-TTY stdin: "${e.trim()}"`)),console.error(H$.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===`
|
|
2050
2050
|
`||o===""?(process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",r),process.stdout.write(`
|
|
@@ -2054,14 +2054,14 @@ Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
|
2054
2054
|
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=Wu(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=Ku();console.log(JSON.stringify(s,null,2))}}catch(s){us(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=ju(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}
|
|
2055
2055
|
${Nr}.`))}catch(i){us(i.message)}}),t.command("unset <key>").description("Remove an afk.config.json key").option("--json","Output JSON").action((r,o)=>{try{let s=Hu(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){us(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=Fu(r);o.json?console.log(JSON.stringify(s)):console.log(`${s.key} [${s.class}]: ${s.persisted??f.meta("(unset)")}`)}else{let s=Nu({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){us(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=W$():a=await Lm(`${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=W$();else{us(`${r} requires a value`);return}let l=Du(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}
|
|
2056
2056
|
${Nr}.`))}catch(i){us(i.message)}}),n.command("unset <key>").description("Remove an afk.env var").option("--json","Output JSON").action((r,o)=>{try{let s=Lu(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){us(s.message)}})}q();import bZ from"path";import wZ from"os";import{createServer as nZ}from"node:http";import{writeFileSync as rZ,unlinkSync as oZ,mkdirSync as sZ,readFileSync as iZ}from"node:fs";import{dirname as aZ,join as lZ}from"node:path";q();import{mkdirSync as V7,appendFileSync as Y7}from"node:fs";import{dirname as X7}from"node:path";import{execFile as Z7}from"node:child_process";import{promisify as Q7}from"node:util";import{randomUUID as eZ}from"node:crypto";import*as sD from"node-cron";var Fm=class{_count=0;increment(){this._count++}decrement(){this._count>0&&this._count--}isIdle(){return this._count===0}count(){return this._count}};K();Si();import{mkdirSync as ta,readdirSync as Zl,readFileSync as Hw,renameSync as Uw,statSync as z$,unlinkSync as Ql,writeFileSync as K7}from"node:fs";import{randomBytes as jw}from"node:crypto";import{join as Gn}from"node:path";function J$(e,t={},n=mt()){ta(n,{recursive:!0});let o=Zl(n).filter(m=>m.endsWith(".json")).length+1,s=`q-${Date.now()}-${jw(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=Gn(n,c),d=jw(4).toString("hex"),p=Gn(n,`.tmp-${d}.json`);try{K7(p,JSON.stringify(a),"utf-8"),Uw(p,u)}catch(m){try{Ql(p)}catch{}throw m}return a}var G$="poison";function V$(e=mt()){ta(e,{recursive:!0});let t=Zl(e).filter(n=>n.endsWith(".json")&&!n.startsWith(".tmp-")).sort();for(let n of t){let r=Gn(e,n),o;try{o=Hw(r,"utf-8")}catch(i){q$(e,n,i);continue}let s;try{s=JSON.parse(o)}catch(i){q$(e,n,i);continue}return Ql(r),s}return null}function q$(e,t,n){let r=Ve(t),o=Ve(n instanceof Error?n.message:String(n)),s=Gn(e,G$),i=Gn(e,t);try{ta(s,{recursive:!0});let a=Gn(s,t);try{Uw(i,a)}catch{a=Gn(s,`${Date.now()}-${jw(3).toString("hex")}-${t}`),Uw(i,a)}console.error(`[daemon] pull-queue: quarantined malformed entry ${r} \u2192 ${G$}/ (${o})`)}catch(a){let l=Ve(a instanceof Error?a.message:String(a));console.error(`[daemon] pull-queue: failed to quarantine malformed entry ${r}; removing to unblock queue (${l})`);try{Ql(i)}catch(c){let u=Ve(c instanceof Error?c.message:String(c));console.error(`[daemon] pull-queue: could not remove unquarantinable entry ${r}; will retry next tick (${u})`)}}}function Ww(e=mt()){try{ta(e,{recursive:!0})}catch{return[]}let t=Zl(e).filter(r=>r.endsWith(".json")&&!r.startsWith(".tmp-")).sort(),n=[];for(let r of t){let o=Gn(e,r);try{n.push(JSON.parse(Hw(o,"utf-8")))}catch(s){let i=Ve(r),a=Ve(s instanceof Error?s.message:String(s));console.error(`[daemon] pull-queue: skipping unreadable entry ${i} in listPending (${a})`)}}return n}function Y$(e=mt(),t){try{ta(e,{recursive:!0})}catch{return!1}let n=Zl(e).filter(r=>r.endsWith(".json")&&!r.startsWith(".tmp-")).sort();for(let r of n){let o=Gn(e,r);try{if(z$(o).isDirectory())continue}catch{continue}let s;try{s=JSON.parse(Hw(o,"utf-8"))}catch{continue}if(s.id===t)return Ql(o),!0}return!1}function X$(e=mt()){try{ta(e,{recursive:!0})}catch{return 0}let t=Zl(e).filter(r=>r.endsWith(".json")&&!r.startsWith(".tmp-")).sort(),n=0;for(let r of t){let o=Gn(e,r);try{if(z$(o).isDirectory())continue}catch{continue}try{Ql(o),n+=1}catch(s){let i=Ve(r),a=Ve(s instanceof Error?s.message:String(s));console.error(`[daemon] pull-queue: failed to remove entry ${i} in clearPending (${a})`)}}return n}K();Hy();cn();cr();K();Si();function Z$(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`)}K();import{existsSync as Q$,readFileSync as G7,readdirSync as q7}from"node:fs";var eD=360*60*1e3;function tD(){return Ss()}function z7(e,t){if(!Q$(t))return null;let n;try{n=G7(t,"utf-8")}catch{return null}let r=n.split(`
|
|
2057
|
-
`);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 J7(e){if(!Q$(e))return 0;try{return q7(e,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(".md")).length}catch{return 0}}function nD(e){let t=z7(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=J7(e.briefsDir);return n>0?{fire:!1,skipReason:"briefs_pending",pendingBriefCount:n,...t!==null?{lastFiredAtMs:t}:{}}:{fire:!0,...t!==null?{lastFiredAtMs:t}:{}}}var rD=Q7(Z7);async function tZ(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 oD(e){return`${e.replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"task"}-${eZ()}`}var Nm=class{registry=new Map;options;defaultCooldownMs;briefsDir;now;idleDetector=new Fm;pullPollTimer;isDequeuing=!1;queueDir;constructor(t={}){this.options=t,this.defaultCooldownMs=t.cooldownMs??eD,this.briefsDir=t.briefsDir??tD(),this.now=t.now??Date.now,this.queueDir=t.queueDir??mt(),this.ensureTelemetrySink()}register(t){if(Z$(t),this.registry.has(t.taskId))throw new Error(`task ${t.taskId} is already registered`);let n;(t.trigger==="cron"||t.trigger==="both")&&(n=sD.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=nD({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=V$(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=Ve(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:Ve(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=Ve(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:Ve(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 tZ(rD,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 jn({execFile:rD,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:Ve(i instanceof Error?i.message:String(i))};return this.writeTelemetry(a,t),a}}async spawnSession(t){let n=oD(t),r=this.options.sessionConfig?.cwd??process.cwd(),o=eo({sessionLabel:oD(t)}),{registry:s,memoryStore:i}=Ti(void 0,"daemon",void 0,void 0,Ei({cwd:r}),{cwd:r,sessionId:n,...o?.writer!==void 0?{traceWriter:o.writer}:{}}),a,l=sn(Mt()).mcpConfigs.filter(p=>p.format==="json").map(p=>p.source),c=Ho({cwd:r,...l.length>0?{importedMcpConfigs:l}:{}}),u=Object.values(c.mcpServers).filter(p=>!p.disabled).length;try{if(u>0)a=await wr.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
|
|
2058
|
-
`,"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}`)}}};K();var cZ=7777,uZ="127.0.0.1";async function iD(e={}){let t=new Nm({...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=lZ(kc("default"),"port"),o=nZ((a,l)=>pZ(a,l,t)),{port:s,address:i}=await fZ(o,e.port??cZ,e.host??uZ);if(n)try{sZ(aZ(r),{recursive:!0}),rZ(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{iZ(r,"utf-8").trim()===String(s)&&oZ(r)}catch{}await gZ(o)}}}function dZ(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 pZ(e,t,n){mZ(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 mZ(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 dZ(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 fZ(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 gZ(e){return new Promise((t,n)=>{e.close(r=>{r?n(r):t()})})}K();Io();function aD(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 lD(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 cD(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 hZ="",Kw="default";function uo(e){if(e!==void 0&&e.trim()!=="")return e}function uD(e,t,n){return uo(e)??uo(t)??uo(n)??hZ}function dD(e,t,n){return uo(e)??uo(t)??uo(n)??Kw}var yZ="127.0.0.1";function pD(e,t){return uo(e)??uo(t)??yZ}function mD(e){let t=e.trim().toLowerCase();return t==="127.0.0.1"||t==="localhost"||t==="::1"}Ot();Je();Cu();li();cn();Qe();il();al();In();qr();No();En();cn();xn();function SZ(e){let t;return n=>{let r=new AbortController,o=Fo(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,ze,"daemon"),l=new On({subagentManager:s,parentSession:o,surface:"daemon",defaultConfig:{...e.apiKey!==void 0?{apiKey:e.apiKey}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}},defaultSubagentModel:Yt(e.model),childProviderFactory:i,childSkillExecutorFactory:a,resolveApiKeyForModel:ze,depth:0,...e.cwd!==void 0?{cwd:e.cwd}:{}}),c=new $n({parentSession:o,surface:"daemon",defaultModel:e.model,defaultSubagentModel:Yt(e.model),...e.apiKey!==void 0?{apiKey:e.apiKey}:{},childProviderFactory:i,childSkillExecutorFactory:a,resolveApiKeyForModel:ze,...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.cwd!==void 0?{cwd:e.cwd}:{}}),u=new Zr({parentSession:o,defaultModel:e.model,defaultSubagentModel:Yt(e.model),...e.apiKey!==void 0?{apiKey:e.apiKey}:{},resolveApiKeyForModel:ze,...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.cwd!==void 0?{cwd:e.cwd}:{},systemPrompt:"",surface:"daemon",depth:0});t??=new lt;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 qe({permissions:{allowedTools:[...Kt,...nr,...ft,"agent","skill","compose",...p]},subagentExecutor:l,skillExecutor:c,composeExecutor:u,memoryStore:t,surface:"daemon",...d!==void 0?{mcpManager:d}:{}});return new
|
|
2057
|
+
`);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 J7(e){if(!Q$(e))return 0;try{return q7(e,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(".md")).length}catch{return 0}}function nD(e){let t=z7(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=J7(e.briefsDir);return n>0?{fire:!1,skipReason:"briefs_pending",pendingBriefCount:n,...t!==null?{lastFiredAtMs:t}:{}}:{fire:!0,...t!==null?{lastFiredAtMs:t}:{}}}var rD=Q7(Z7);async function tZ(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 oD(e){return`${e.replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"task"}-${eZ()}`}var Nm=class{registry=new Map;options;defaultCooldownMs;briefsDir;now;idleDetector=new Fm;pullPollTimer;isDequeuing=!1;queueDir;constructor(t={}){this.options=t,this.defaultCooldownMs=t.cooldownMs??eD,this.briefsDir=t.briefsDir??tD(),this.now=t.now??Date.now,this.queueDir=t.queueDir??mt(),this.ensureTelemetrySink()}register(t){if(Z$(t),this.registry.has(t.taskId))throw new Error(`task ${t.taskId} is already registered`);let n;(t.trigger==="cron"||t.trigger==="both")&&(n=sD.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=nD({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=V$(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=Ve(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:Ve(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=Ve(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:Ve(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 tZ(rD,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 jn({execFile:rD,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:Ve(i instanceof Error?i.message:String(i))};return this.writeTelemetry(a,t),a}}async spawnSession(t){let n=oD(t),r=this.options.sessionConfig?.cwd??process.cwd(),o=eo({sessionLabel:oD(t)}),{registry:s,memoryStore:i}=Ti(void 0,"daemon",void 0,void 0,Ei({cwd:r}),{cwd:r,sessionId:n,...o?.writer!==void 0?{traceWriter:o.writer}:{}}),a,l=sn(Mt()).mcpConfigs.filter(p=>p.format==="json").map(p=>p.source),c=Ho({cwd:r,...l.length>0?{importedMcpConfigs:l}:{}}),u=Object.values(c.mcpServers).filter(p=>!p.disabled).length;try{if(u>0)a=await wr.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 kt(dr(d)),memoryStore:i,...a!==void 0?{mcpManager:a}:{}}}catch(p){throw a&&await a.disconnectAll().catch(()=>{}),i.close(),p}}telemetryPath(){return this.options.telemetryPath??Cr()}ensureTelemetrySink(){try{V7(X7(this.telemetryPath()),{recursive:!0})}catch{}}writeTelemetry(t,n,r){try{Y7(this.telemetryPath(),`${JSON.stringify(t)}
|
|
2058
|
+
`,"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}`)}}};K();var cZ=7777,uZ="127.0.0.1";async function iD(e={}){let t=new Nm({...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=lZ(kc("default"),"port"),o=nZ((a,l)=>pZ(a,l,t)),{port:s,address:i}=await fZ(o,e.port??cZ,e.host??uZ);if(n)try{sZ(aZ(r),{recursive:!0}),rZ(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{iZ(r,"utf-8").trim()===String(s)&&oZ(r)}catch{}await gZ(o)}}}function dZ(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 pZ(e,t,n){mZ(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 mZ(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 dZ(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 fZ(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 gZ(e){return new Promise((t,n)=>{e.close(r=>{r?n(r):t()})})}K();Io();function aD(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 lD(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 cD(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 hZ="",Kw="default";function uo(e){if(e!==void 0&&e.trim()!=="")return e}function uD(e,t,n){return uo(e)??uo(t)??uo(n)??hZ}function dD(e,t,n){return uo(e)??uo(t)??uo(n)??Kw}var yZ="127.0.0.1";function pD(e,t){return uo(e)??uo(t)??yZ}function mD(e){let t=e.trim().toLowerCase();return t==="127.0.0.1"||t==="localhost"||t==="::1"}Ot();Je();Cu();li();cn();Qe();il();al();In();qr();No();En();cn();xn();function SZ(e){let t;return n=>{let r=new AbortController,o=Fo(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,ze,"daemon"),l=new On({subagentManager:s,parentSession:o,surface:"daemon",defaultConfig:{...e.apiKey!==void 0?{apiKey:e.apiKey}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}},defaultSubagentModel:Yt(e.model),childProviderFactory:i,childSkillExecutorFactory:a,resolveApiKeyForModel:ze,depth:0,...e.cwd!==void 0?{cwd:e.cwd}:{}}),c=new $n({parentSession:o,surface:"daemon",defaultModel:e.model,defaultSubagentModel:Yt(e.model),...e.apiKey!==void 0?{apiKey:e.apiKey}:{},childProviderFactory:i,childSkillExecutorFactory:a,resolveApiKeyForModel:ze,...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.cwd!==void 0?{cwd:e.cwd}:{}}),u=new Zr({parentSession:o,defaultModel:e.model,defaultSubagentModel:Yt(e.model),...e.apiKey!==void 0?{apiKey:e.apiKey}:{},resolveApiKeyForModel:ze,...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.cwd!==void 0?{cwd:e.cwd}:{},systemPrompt:"",surface:"daemon",depth:0});t??=new lt;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 qe({permissions:{allowedTools:[...Kt,...nr,...ft,"agent","skill","compose",...p]},subagentExecutor:l,skillExecutor:c,composeExecutor:u,memoryStore:t,surface:"daemon",...d!==void 0?{mcpManager:d}:{}});return new kt(dr({...n,provider:m,isNonInteractive:!0,surface:"daemon"}))}}function vZ(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(`
|
|
2059
2059
|
`)}function fD(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: ${Kw})`).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)&&G(new Error(`Invalid port: ${t.port}`));let r=_t(),o=uD(t.task,v.AFK_DAEMON_TASK,r.daemon?.task),s=dD(t.taskId,v.AFK_DAEMON_TASK_ID,r.daemon?.taskId),i=pD(t.host,v.AFK_DAEMON_HOST),a,l,c;try{a=aD(t.timeoutMs,v.AFK_TIMEOUT_MS),l=lD(t.sessionstartCooldownMs,v.AFK_SESSIONSTART_COOLDOWN_MS),c=cD(t.trigger,t.cron)}catch(A){G(A)}(c==="cron"||c==="both")&&!t.cron&&G(new Error(`--cron is required when --trigger is '${c}'.`)),(c==="cron"||c==="both")&&o.trim()===""&&G(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=Yr(t.thinking)??pi(),d=Xr(t.effort)??mi()}catch(A){G(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=zt();for(let A of y)A.enabled&&b.push(aT(A));if(t.dumpPrompt!==void 0&&t.dumpPrompt!==!1){let A=t.dumpPrompt===!0?bZ.join(wZ.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);Lr(`\u{1F6D1} agent-afk daemon ${A}
|
|
2060
|
-
${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
|
+
${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=Et(),R=Ce(),k=x!==void 0&&x.length>0?x:void 0;await wi();let $=SZ({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 iD({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:mt()}:{},tasks:b,onTaskComplete:(F,D)=>{Lr(vZ(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}`)),mD(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: ${mt()} 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(`
|
|
2061
2061
|
\xB7 Shutting down daemon...`)),await A.stop(),process.exit(0)};process.on("SIGINT",P),process.on("SIGTERM",P)}catch(A){G(A)}})}import{createInterface as kZ}from"node:readline/promises";import{mkdirSync as EZ}from"node:fs";import{join as TZ}from"node:path";K();function gD(e){let t=e.command("queue").description("Manage the pull-trigger task queue (used with `afk daemon --trigger pull`)");t.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=mt();EZ(o,{recursive:!0});let s=r.notifyOn,i=J$(n,{notifyOn:s},o),a=String(i.sequence).padStart(4,"0"),l=TZ(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){G(o)}}),t.command("list").description("List all pending queued tasks in FIFO order").action(()=>{try{let n=mt(),r=Ww(n);if(r.length===0){console.log(f.dim("No pending tasks in queue."));return}let o=`${"SEQ".padEnd(4)} ${"ID".padEnd(26)} ${"ENQUEUED".padEnd(24)} COMMAND`,s="\u2500".repeat(o.length);console.log(f.heading(o)),console.log(f.dim(s));for(let a of r){let l=String(a.sequence).padStart(4,"0"),c=a.id.padEnd(26).slice(0,26),u=a.enqueuedAt.padEnd(24).slice(0,24);console.log(`${l} ${c} ${u} ${a.command}`)}let i=r.length===1?"task":"tasks";console.log(f.dim(`
|
|
2062
2062
|
${r.length} pending ${i}.`))}catch(n){G(n)}}),t.command("remove <id>").description("Remove a pending task by id").action(n=>{try{let r=mt();Y$(r,n)||(console.error(f.error(`Task not found: ${n}`)),console.error(f.dim(" (already executed, already removed, or id is wrong)")),process.exit(1)),console.log(f.success(`\u2714 Removed task ${n}`))}catch(r){G(r)}}),t.command("clear").description("Remove all pending tasks from the queue").option("-y, --yes","Skip the confirmation prompt (non-interactive / CI)").action(async n=>{try{let r=mt(),o=Ww(r);if(o.length===0){console.log(f.dim("Queue is already empty \u2014 nothing to clear."));return}if(n.yes!==!0){process.stdin.isTTY||(console.log(f.warning(`Non-interactive shell: re-run with --yes to clear ${o.length} pending task(s).`)),process.exit(0));let a=kZ({input:process.stdin,output:process.stdout});try{let l=(await a.question(f.bold(`
|
|
2063
|
-
Remove all ${o.length} pending task(s) from the queue? [y/N] `))).trim().toLowerCase();l!=="y"&&l!=="yes"&&(console.log(f.dim("Aborted \u2014 queue unchanged.")),process.exit(0))}finally{a.close()}}let s=X$(r),i=s===1?"task":"tasks";console.log(f.success(`\u2714 Cleared ${s} pending ${i}.`))}catch(r){G(r)}})}rt();Je();import na from"chalk";import hD from"chalk";K();Pu();function yD(){return Lm("Anthropic API key or OAuth token: ")}async function Bm(e){let t=e??await yD();t||(console.error(hD.red("No token provided. Nothing saved.")),process.exit(1));let n=yt(),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"]),ln(n,r,t,o),console.log(hD.green(`\u2713 Saved ${r} to ${n}`)),console.log(f.meta("Restart any running afk daemon to pick up the new token."))}function bD(e){e.command("login [token]").description("Save an Anthropic API key or OAuth token for afk to use").action(async t=>{let n=re(
|
|
2064
|
-
Installed plugins:`));for(let r of n){let o=e.plugins[r];if(!o)continue;let s=o.enabled?
|
|
2063
|
+
Remove all ${o.length} pending task(s) from the queue? [y/N] `))).trim().toLowerCase();l!=="y"&&l!=="yes"&&(console.log(f.dim("Aborted \u2014 queue unchanged.")),process.exit(0))}finally{a.close()}}let s=X$(r),i=s===1?"task":"tasks";console.log(f.success(`\u2714 Cleared ${s} pending ${i}.`))}catch(r){G(r)}})}rt();Je();import na from"chalk";import hD from"chalk";K();Pu();function yD(){return Lm("Anthropic API key or OAuth token: ")}async function Bm(e){let t=e??await yD();t||(console.error(hD.red("No token provided. Nothing saved.")),process.exit(1));let n=yt(),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"]),ln(n,r,t,o),console.log(hD.green(`\u2713 Saved ${r} to ${n}`)),console.log(f.meta("Restart any running afk daemon to pick up the new token."))}function bD(e){e.command("login [token]").description("Save an Anthropic API key or OAuth token for afk to use").action(async t=>{let n=re(Et());if(n==="openai-compatible"||n==="openai-codex"){console.log(na.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(na.cyan(" export OPENAI_API_KEY=sk-proj-...")),console.log(na.cyan(" # or: export CODEX_API_KEY=...")),console.log(na.cyan(" codex login --api-key sk-proj-...")),console.log(""),console.log(na.gray("Run `afk provider auth diagnose` to see which auth source AFK will use.")),console.log(na.gray("To save an Anthropic key for Claude models instead, re-run with AFK_MODEL=sonnet (or similar) first."));return}await Bm(t)})}import ye from"chalk";import Um from"ora";K();import{existsSync as xZ}from"fs";import{join as RZ}from"path";Lt();Jr();async function Gw(e,t={},n={}){let r=n.pluginsDir??Xe(),o=n.indexPath??ce(),s=n.now??(()=>new Date),i=n.gitRunner?{runner:n.gitRunner}:{},l=Re(o).plugins[e];if(!l)throw new Error(`plugin "${e}" is not installed`);let c=RZ(r,e);if(!xZ(c))return{name:e,status:"missing-dir",dir:c};if(mr(),l.sourceType==="local")return{name:e,status:"skipped-local"};await mm(c,i);let u,d=!1;if(t.ref)u=t.ref;else{let x=await io(c,i),C=lo(x);C!==null?(u=C,d=!0):u=l.ref??await Kn(c,i)}let p=`refs/remotes/origin/${u}`,m=d?null:await fm(c,p,i),g=m!==null,h=await Wn(c,i);if(g?m===h:u===l.ref)return{name:e,status:"up-to-date",ref:u,commit:h,version:ts(c).version};await ao(c,g?p:d?`refs/tags/${u}`:u,{...i,force:!0});let y=await Wn(c,i),S=ts(c).version,w=s().toISOString(),T={...l,ref:u,commit:y,updatedAt:w};return zr(e,T,o),{name:e,status:"updated",fromRef:l.ref,toRef:u,commit:y,version:S}}async function wD(e={}){let t=e.indexPath??ce(),n=Re(t),r=[];for(let o of Object.keys(n.plugins))try{r.push(await Gw(o,{},e))}catch(s){let i=s instanceof Error?s.message:String(s);r.push({name:o,status:"missing-dir",dir:i})}return r}K();Lt();import{existsSync as CZ,lstatSync as AZ,rmSync as _Z,unlinkSync as IZ}from"fs";import{join as PZ}from"path";Jr();function SD(e,t={}){Er(e);let n=t.pluginsDir??Xe(),r=t.indexPath??ce(),o=PZ(n,e),s=!1;MZ(o)?(IZ(o),s=!0):CZ(o)&&(_Z(o,{recursive:!0,force:!0}),s=!0);let i=Re(r),a=Object.prototype.hasOwnProperty.call(i.plugins,e);return a&&yR(e,r),mr(),{name:e,removedDir:s,removedIndexEntry:a}}function MZ(e){try{return AZ(e).isSymbolicLink()}catch{return!1}}Lt();K();function vD(e,t={}){let n=t.logger??console,r=t.pluginsDir??Xe(),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=Zi(a)}catch(m){Um(`Installing ${a}\u2026`).start().fail("Failed"),G(m)}let d=process.stderr.isTTY===!0&&!c.yes;if(u.type==="marketplace-ref"){let m=Um(`Installing ${u.marketplace}:${u.plugin}\u2026`).start();try{let g=await Qi(u.marketplace,u.plugin,{...c.ref?{ref:c.ref}:{},...c.force?{force:!0}:{}},{...s,confirm:d});m.succeed(ye.green(`Installed ${ye.bold(g.key)}`)+ye.gray(` at ${g.dir}`))}catch(g){m.fail("Failed"),G(g)}return}let p=Um(`Installing ${a}\u2026`).start();try{let m={...l?{name:l}:{},...c.ref?{ref:c.ref}:{},...c.force?{force:!0}:{}},g=await ym(a,m,{...s,confirm:d});p.succeed(ye.green(`Installed ${ye.bold(g.name)}`)+ye.gray(` at ${g.dir}${g.entry.ref?` (ref: ${g.entry.ref})`:""}`))}catch(m){p.fail("Failed"),G(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=Um(`Updating ${a}\u2026`).start(),u=await Gw(a,l.ref?{ref:l.ref}:{},s);$Z(u,c)}else{n.log(ye.cyan("Updating all plugins\u2026"));let c=await wD(s);if(c.length===0){n.log(ye.gray(" (nothing installed)"));return}for(let u of c)n.log(" "+kD(u))}}catch(c){G(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=Re(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 OZ(l,n)}),i.command("remove <name>").description("Remove a plugin (directory + index entry)").action(a=>{let l=SD(a,{pluginsDir:r,indexPath:o});if(!l.removedDir&&!l.removedIndexEntry){n.log(ye.gray(`No plugin named "${a}" to remove.`));return}let c=[l.removedDir?"directory":null,l.removedIndexEntry?"index entry":null].filter(Boolean);n.log(ye.green(`Removed ${a}: ${c.join(" + ")}`))}),i.command("enable <name>").description("Re-enable a previously disabled plugin").action(a=>{try{Jh(a,!0,o),n.log(ye.green(`Enabled ${a}`))}catch(l){G(l)}}),i.command("disable <name>").description("Keep the plugin on disk but skip it from SDK init").action(a=>{try{Jh(a,!1,o),n.log(ye.yellow(`Disabled ${a} (dir preserved at ${r}/${a})`))}catch(l){G(l)}})}function OZ(e,t){let n=Object.keys(e.plugins).sort();if(n.length===0){t.log(ye.gray("No plugins installed.")),t.log(ye.gray(" Try: afk plugin install anthropics/claude-plugins-official"));return}t.log(ye.cyan.bold(`
|
|
2064
|
+
Installed plugins:`));for(let r of n){let o=e.plugins[r];if(!o)continue;let s=o.enabled?ye.green("enabled "):ye.yellow("disabled"),i=o.ref?ye.blue(o.ref):ye.gray("(local)"),a=ye.gray(o.source);t.log(` ${ye.bold(r.padEnd(30))} ${s} ${i.padEnd(12)} ${a}`)}t.log("")}function kD(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?ye.gray(` [v${e.version.replace(/^v/i,"")}]`):"";return`${ye.green("\u2713")} ${ye.bold(e.name)}: ${t}${n}`}case"up-to-date":{let t=e.version?ye.gray(` [v${e.version.replace(/^v/i,"")}]`):"";return`${ye.gray("\xB7")} ${ye.bold(e.name)}: up-to-date (${e.ref})${t}`}case"skipped-local":return`${ye.gray("\xB7")} ${ye.bold(e.name)}: skipped (local source)`;case"missing-dir":return`${ye.yellow("!")} ${ye.bold(e.name)}: plugin dir missing (${e.dir})`}}function $Z(e,t){let n=kD(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 qw from"ora";Lt();K();function ED(e,t={}){let n=t.logger??console,r=t.cacheDir??zn(),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=qw(`Installing marketplace ${a}\u2026`).start();try{let d={...l?{name:l}:{},...c.ref?{ref:c.ref}:{},...c.force?{force:!0}:{}},p=await wm(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"),G(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=Re(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(`
|
|
2065
2065
|
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=km(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(`
|
|
2066
2066
|
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(`
|
|
2067
2067
|
Install one: afk plugin install ${a}:<plugin>`))}catch(c){G(c)}}),i.command("install-plugin <marketplace> <plugin>").description("Install a single plugin from a marketplace").option("-r, --ref <ref>","For git-sourced plugins, pin to a specific tag/branch/SHA").option("-f, --force","Replace an existing plugin with the same key").option("-y, --yes","Skip the install warning and countdown (non-interactive / CI)").action(async(a,l,c)=>{let u=process.stderr.isTTY===!0&&!c.yes,d=qw(`Installing ${a}:${l}\u2026`).start();try{let p=await Qi(a,l,{...c.ref?{ref:c.ref}:{},...c.force?{force:!0}:{}},{...s,confirm:u});d.succeed(ae.green(`Installed ${ae.bold(p.key)}`)+ae.gray(` at ${p.dir}`))}catch(p){d.fail("Failed"),G(p)}}),i.command("remove <name>").description("Remove a marketplace and cascade-delete its installed plugins").action(a=>{let l=Sm(a,{cacheDir:r,indexPath:o});if(!l.removedDir&&!l.removedIndexEntry&&l.removedPluginEntries.length===0){n.log(ae.gray(`No marketplace named "${a}" to remove.`));return}let c=[l.removedDir?"directory":null,l.removedIndexEntry?"index entry":null,l.removedPluginEntries.length>0?`${l.removedPluginEntries.length} plugin entry`:null].filter(Boolean);if(n.log(ae.green(`Removed ${a}: ${c.join(" + ")}`)),l.removedPluginEntries.length>0)for(let u of l.removedPluginEntries)n.log(ae.gray(` - ${u}`))}),i.command("update [name]").description("Update one marketplace, 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=qw(`Updating ${a}\u2026`).start(),u=await zl(a,l.ref?{ref:l.ref}:{},s);DZ(u,c)}else{n.log(ae.cyan("Updating all marketplaces\u2026"));let c=await OO(s);if(c.length===0){n.log(ae.gray(" (no marketplaces installed)"));return}for(let u of c)n.log(" "+TD(u))}}catch(c){G(c)}})}function TD(e){switch(e.status){case"updated":{let t=e.addedPlugins.length>0?` +${e.addedPlugins.join(", ")}`:"",n=e.removedPlugins.length>0?` -${e.removedPlugins.join(", ")}`:"",r=e.fromRef===e.toRef?`${e.toRef} @ ${e.commit.slice(0,7)}`:`${e.fromRef??"(none)"} \u2192 ${e.toRef}`,o=e.pluginVersions.filter(i=>i.version!==null).map(i=>`${i.name} ${i.version}`).join(", "),s=o?ae.gray(` [${o}]`):"";return`${ae.green("\u2713")} ${ae.bold(e.name)}: ${r}${ae.gray(t+n)}${s}`}case"up-to-date":return`${ae.gray("\xB7")} ${ae.bold(e.name)}: up-to-date (${e.ref})`;case"skipped-local":return`${ae.gray("\xB7")} ${ae.bold(e.name)}: skipped (local source)`;case"missing-dir":return`${ae.yellow("!")} ${ae.bold(e.name)}: marketplace dir missing (${e.dir})`}}function DZ(e,t){let n=TD(e);e.status==="updated"?t.succeed(n):e.status==="up-to-date"||e.status==="skipped-local"?t.info(n):t.warn(n)}function xD(e){e.command("doctor").description("Check system health and configuration").option("-f, --format <format>","Output format (text|json)","text").action(async t=>{let n=await sm(),r={passed:n.filter(o=>o.state==="pass").length,warned:n.filter(o=>o.state==="warn").length,failed:n.filter(o=>o.state==="fail").length};t.format==="json"?console.log(JSON.stringify({checks:n,summary:r},null,2)):(n.forEach(o=>{let s;o.state==="pass"?s=f.success("\u2713"):o.state==="warn"?s=f.warning("\u26A0"):s=f.error("\u2717");let i=`${s} ${o.name}`;o.detail&&(i+=` \u2014 ${o.detail}`),console.log(i),o.state==="fail"&&o.fix&&console.log(` Fix: ${o.fix}`)}),console.log(`
|
|
@@ -2176,16 +2176,16 @@ Multiple chats found:`)),o.forEach((l,c)=>{let u=l.username?`@${l.username}`:l.f
|
|
|
2176
2176
|
`),process.exit(2));let o=yt();ln(o,"AFK_TELEGRAM_ALLOWED_CHAT_IDS",String(r)),process.stdout.write(JSON.stringify({ok:!0,path:o})+`
|
|
2177
2177
|
`)}),t.command("start").description("Start the bot as a background daemon").action(async()=>{let n=await eS();if(n.kind==="started"){console.log($e.green(`\u2713 Bot started (PID ${n.pid})`)),console.log($e.gray(` Logs: ${n.logFile}`)),console.log($e.gray(" Tail with: afk telegram logs --follow"));return}if(n.kind==="already-running"&&(console.log($e.yellow(`\u26A0 ${n.message}`)),process.exit(1)),n.kind==="exited-immediately"){if(console.error($e.red(`\u2717 ${n.message}`)),n.logTail&&n.logTail.length>0){console.error(""),console.error($e.bold("Last log entries:"));for(let r of n.logTail)console.error($e.gray(` ${r}`))}process.exit(1)}console.error($e.red(`\u2717 ${n.message}`)),process.exit(1)}),t.command("stop").description("Stop the bot (SIGTERM, then SIGKILL after 5s)").action(async()=>{let n=await tS();if(n.kind==="not-running"){console.log($e.yellow("\u26A0 Bot is not running"));return}if(n.kind==="stopped"){console.log($e.green(`\u2713 Bot stopped (PID ${n.pid})`));return}console.log($e.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 tS();(n.kind==="stopped"||n.kind==="force-killed")&&console.log($e.gray(`Stopped (PID ${n.pid})`));let r=await eS();if(r.kind==="started"){console.log($e.green(`\u2713 Bot restarted (PID ${r.pid})`));return}console.error($e.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=nS();yQ(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}=nS();if(!gQ(r)){console.log($e.yellow(`No log file at ${r}`)),console.log($e.gray("Start the bot first: afk telegram start"));return}let o=Number.parseInt(n.lines??"50",10);if(n.follow){fQ("tail",["-n",String(o),"-f",r],{stdio:"inherit"}).on("error",a=>{console.error($e.red(`Failed to spawn tail: ${a.message}`))});return}let s=hQ(r,"utf-8").split(`
|
|
2178
2178
|
`).slice(-o-1);console.log(s.join(`
|
|
2179
|
-
`))})}function yQ(e){if(console.log($e.bold("\u{1F4CA} Telegram Bot Status")),console.log(""),e.running?(console.log(` ${$e.green("\u25CF")} Running (PID ${e.pid})`),e.uptimeSec!==void 0&&console.log(` Uptime: ${bQ(e.uptimeSec)}`),e.memoryMb!==void 0&&console.log(` Memory: ${e.memoryMb} MB`)):console.log(` ${$e.red("\u25CF")} Stopped`),console.log(` PID: ${e.pidFile}`),console.log(` Logs: ${e.logFile}`),e.logTail&&e.logTail.length>0){console.log(""),console.log($e.bold("Recent log entries:"));for(let t of e.logTail)console.log($e.gray(` ${t}`))}}function bQ(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 zQ}from"node:child_process";import{promisify as JQ}from"node:util";import Ee from"chalk";K();import{execFile as wQ}from"node:child_process";import{randomBytes as SQ}from"node:crypto";import{promises as sa}from"node:fs";import{join as Wm}from"node:path";import{promisify as vQ}from"node:util";var kQ=vQ(wQ),BD=16;var
|
|
2180
|
-
`,"utf8"),u}function MQ(e){let t=e;return t.respawnedAt===void 0&&(t.respawnedAt=void 0),t.respawnedAs===void 0&&(t.respawnedAs=void 0),t.prUrl===void 0&&(t.prUrl=void 0),t.prCreatedAt===void 0&&(t.prCreatedAt=void 0),t}async function OQ(e){let t=Wm(xf(e),"farm.json");try{let n=await sa.readFile(t,"utf8"),r=JSON.parse(n);if(r.schemaVersion!==1&&r.schemaVersion!==2&&r.schemaVersion!==3)throw new
|
|
2181
|
-
`,"utf8"),n}Qe();Je();import{spawn as $Q}from"child_process";import{promises as Km}from"fs";import{join as tc,dirname as
|
|
2179
|
+
`))})}function yQ(e){if(console.log($e.bold("\u{1F4CA} Telegram Bot Status")),console.log(""),e.running?(console.log(` ${$e.green("\u25CF")} Running (PID ${e.pid})`),e.uptimeSec!==void 0&&console.log(` Uptime: ${bQ(e.uptimeSec)}`),e.memoryMb!==void 0&&console.log(` Memory: ${e.memoryMb} MB`)):console.log(` ${$e.red("\u25CF")} Stopped`),console.log(` PID: ${e.pidFile}`),console.log(` Logs: ${e.logFile}`),e.logTail&&e.logTail.length>0){console.log(""),console.log($e.bold("Recent log entries:"));for(let t of e.logTail)console.log($e.gray(` ${t}`))}}function bQ(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 zQ}from"node:child_process";import{promisify as JQ}from"node:util";import Ee from"chalk";K();import{execFile as wQ}from"node:child_process";import{randomBytes as SQ}from"node:crypto";import{promises as sa}from"node:fs";import{join as Wm}from"node:path";import{promisify as vQ}from"node:util";var kQ=vQ(wQ),BD=16;var Rt=class extends Error{cause;code;constructor(t,n,r){super(t),this.name="WorktreeError",this.cause=n,this.code=r}};function oS(e,t=40){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||"task"}function EQ(){return SQ(4).toString("hex").slice(0,4)}function TQ(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 xQ(e,t={}){let n=(t.now??(()=>new Date))(),r=(t.randomSuffix??EQ)();return`${TQ(n)}-${oS(e,32)}-${r}`}async function ds(e,t){try{let n=await kQ("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 Rt(`git ${t.join(" ")} failed: ${o}`,n)}}async function RQ(e){let{stdout:t}=await ds(e,["rev-parse","--show-toplevel"]);if(!t)throw new Rt(`not a git repository: ${e}`);return t}async function CQ(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 AQ(e,t,n){let r=n?oS(n,32):`branch-${t}`;return`afk/farm/${e}/${t}-${r}`}function _Q(e,t){return Wm(e,`branch-${t}`)}async function IQ(e,t){try{await ds(e,["worktree","remove","--force",t])}catch{}}async function PQ(e,t){try{await ds(e,["branch","-D",t])}catch{}}async function UD(e){if(e.count<1||e.count>BD)throw new Rt(`count must be between 1 and ${BD}, got ${e.count}`);if(e.labels&&e.labels.length!==e.count)throw new Rt(`labels.length (${e.labels.length}) must equal count (${e.count})`);let t=e.cwd??process.cwd(),n=await RQ(t),{sha:r,branch:o}=await CQ(n,e.baseRef),s=(e.now??(()=>new Date))(),i=e.taskSlug??xQ(e.taskName,{now:()=>s,randomSuffix:e.randomSuffix}),a=e.taskSlug??i,l=xf(i);try{throw await sa.access(l),new Rt(`farm directory already exists: ${l}`)}catch(d){if(d.code!=="ENOENT")throw d instanceof Rt?d:new Rt(`failed to check farm dir ${l}`,d)}await sa.mkdir(l,{recursive:!0});let c=[];try{for(let d=1;d<=e.count;d++){let p=e.labels?.[d-1],m=AQ(i,d,p),g=_Q(l,d);await ds(n,["worktree","add","-b",m,g,r]),c.push({index:d,label:p?oS(p,32):void 0,path:g,branch:m})}}catch(d){for(let p of c.slice().reverse())await IQ(n,p.path),await PQ(n,p.branch);throw await sa.rm(l,{recursive:!0,force:!0}).catch(()=>{}),d instanceof Rt?d:new Rt("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 sa.writeFile(Wm(l,"farm.json"),JSON.stringify(u,null,2)+`
|
|
2180
|
+
`,"utf8"),u}function MQ(e){let t=e;return t.respawnedAt===void 0&&(t.respawnedAt=void 0),t.respawnedAs===void 0&&(t.respawnedAs=void 0),t.prUrl===void 0&&(t.prUrl=void 0),t.prCreatedAt===void 0&&(t.prCreatedAt=void 0),t}async function OQ(e){let t=Wm(xf(e),"farm.json");try{let n=await sa.readFile(t,"utf8"),r=JSON.parse(n);if(r.schemaVersion!==1&&r.schemaVersion!==2&&r.schemaVersion!==3)throw new Rt(`unsupported farm manifest schema: ${r.schemaVersion} (expected 1, 2, or 3)`,void 0,"unsupported-schema");return MQ(r)}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Rt?n:new Rt(`failed to load farm manifest ${t}`,n,"invalid")}}async function jD(e,t){let n=await OQ(e);if(!n)throw new Rt(`farm not found: ${e}`);return n.memoryFactId=t,n.schemaVersion=3,await sa.writeFile(Wm(n.farmDir,"farm.json"),JSON.stringify(n,null,2)+`
|
|
2181
|
+
`,"utf8"),n}Qe();Je();import{spawn as $Q}from"child_process";import{promises as Km}from"fs";import{join as tc,dirname as BHe}from"path";var DQ=1,Gm=12e4;async function GD(e){let{branchPath:t,baseSha:n,testCmd:r,timeoutMs:o=Gm,_spawn:s=$Q,_readPackageJson:i=LQ,_now:a=Date.now,_nowIso:l=()=>new Date().toISOString()}=e,c=r??await FQ(t,i),u=0,d=0,p=0,m;if(c){let y=await zD(c,t,o,s,a);p=y.durationMs,y.timedOut?(d=1,m=`tests timed out after ${o}ms`):y.crashed?(d=1,m=`test runner crashed: ${UQ(y.stderr,200)}`):y.exitCode===0?u=1:d=1}else m="no test command found (no package.json scripts.test)";let g=await NQ(t,o,s,a),h=await BQ(t,n,s),b={schemaVersion:DQ,pass:u,fail:d,loc_delta:h,lint_ok:g,duration_ms:p,branchPath:t,baseSha:n,scoredAt:l()};return m!==void 0&&(b.error=m),c!==void 0&&(b.testCmd=c),b}async function qD(e,t,n){let r=tc(e,"scores");await Km.mkdir(r,{recursive:!0});let o=tc(r,`branch-${t}.json`);return await Km.writeFile(o,JSON.stringify(n,null,2)+`
|
|
2182
2182
|
`,"utf8"),o}function nc(e){let t=e.filter(r=>r.score!==null),n=e.filter(r=>r.score===null).map(r=>r.index).sort((r,o)=>r-o);return t.sort((r,o)=>{let s=r.score,i=o.score,a=HD(s),l=HD(i);if(a!==l)return l-a;let c=WD(s.lint_ok),u=WD(i.lint_ok);return c!==u?u-c:s.loc_delta!==i.loc_delta?s.loc_delta-i.loc_delta:r.index-o.index}),[...t.map(r=>r.index),...n]}async function LQ(e){try{let t=await Km.readFile(e,"utf8");return JSON.parse(t)}catch{return null}}async function FQ(e,t){let n=await t(tc(e,"package.json"));if(!KD(n))return;let r=n.scripts;return!KD(r)||typeof r.test!="string"?void 0:await JD(tc(e,"pnpm-lock.yaml"))?"pnpm test":"npm test"}async function zD(e,t,n,r,o){let s=o();return new Promise(i=>{let a;try{a=r(e,{cwd:t,shell:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CI:"1"}})}catch(p){i({exitCode:null,durationMs:o()-s,stderr:p instanceof Error?p.message:String(p),timedOut:!1,crashed:!0});return}let l="",c=!1,u=!1,d=setTimeout(()=>{c=!0,a.kill("SIGKILL")},n);a.stderr?.on("data",p=>{l+=String(p),l.length>64e3&&(l=l.slice(-32e3))}),a.on("error",p=>{u||(u=!0,clearTimeout(d),i({exitCode:null,durationMs:o()-s,stderr:p.message,timedOut:!1,crashed:!0}))}),a.on("close",p=>{u||(u=!0,clearTimeout(d),i({exitCode:p,durationMs:o()-s,stderr:l,timedOut:c,crashed:!1}))})})}async function NQ(e,t,n,r){if(!await JD(tc(e,"tsconfig.json")))return null;let o=await zD("npx --no-install tsc --noEmit",e,t,n,r);return o.crashed||o.timedOut?null:o.exitCode===0}async function BQ(e,t,n){return new Promise(r=>{let o;try{o=n("git",["diff","--shortstat",`${t}..HEAD`],{cwd:e,stdio:["ignore","pipe","pipe"]})}catch{r(0);return}let s="";o.stdout?.on("data",i=>{s+=String(i)}),o.on("error",()=>r(0)),o.on("close",()=>{let i=/(\d+) insertions?\(\+\)/.exec(s),a=/(\d+) deletions?\(-\)/.exec(s),l=i?Number(i[1]):0,c=a?Number(a[1]):0;r(l-c)})})}function HD(e){let t=e.pass+e.fail;return t===0?0:e.pass/t}function WD(e){return e===!0?2:e===!1?1:0}function UQ(e,t){return e.length<=t?e:e.slice(0,t)+"\u2026"}function KD(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function JD(e){try{return await Km.access(e),!0}catch{return!1}}au();function VD(e,t){let n;try{n=t?._store??new lt}catch(r){return{skipped:!0,reason:r instanceof Error?r.message:String(r)}}try{let r=jQ(e);return{factId:n.storeFact({category:"learning",content:JSON.stringify(r),source_surface:"afk"})}}catch(r){return{skipped:!0,reason:r instanceof Error?r.message:String(r)}}}function jQ(e){let t=HQ(e.branches),n=e.winner??null,r=WQ(e,t);return{type:"farm-run",task:e.taskName,taskSlug:e.taskSlug,winner:n,why:r,scores:t,human_decision:e.human_decision??null,baseSha:e.baseSha,completedAt:e.completedAt}}function HQ(e){return e.map(t=>{let n=t.score??null;return{index:t.index,branch:t.branch,pass:n?.pass??0,fail:n?.fail??0,loc_delta:n?.loc_delta??0,lint_ok:n?.lint_ok??null,duration_ms:n?.duration_ms??0}})}function WQ(e,t){let{winner:n,branches:r}=e;if(n==null)return r.some(p=>p.score!=null)?`no winner: all ${r.length} branches failed tests`:"no winner: scoring data unavailable";let o=t.find(d=>d.index===n);if(!o)return`branch-${n} wins`;let s=o.pass>0?"\u2713":"\u2717",i=o.lint_ok===!0?"\u2713":o.lint_ok===!1?"\u2717":"?",a=o.loc_delta>=0?`+${o.loc_delta}`:String(o.loc_delta),c=t.filter(d=>d.index!==n).map(d=>d.loc_delta>=0?`+${d.loc_delta}`:String(d.loc_delta)),u=c.length>0?` (vs ${c.join(", ")} LoC)`:"";return`branch-${n} wins: tests${s}, lint${i}, ${a} LoC${u}`}var KQ="afk:f:";var GQ=/^[a-z0-9T][a-z0-9T-]{0,62}$/;function rc(e,t){if(!GQ.test(t))throw new Error(`buildFarmCallback: invalid taskSlug ${JSON.stringify(t)}`);let n=`${KQ}${e}:${t}`,r=Buffer.byteLength(n,"utf8");if(r>64)throw new Error(`buildFarmCallback: payload ${r} bytes exceeds Telegram's 64-byte limit (slug=${t})`);return n}function YD(e){return{inline_keyboard:[[{text:"\u2705 Open PR",callback_data:rc("p",e)},{text:"\u{1F501} Respawn from winner",callback_data:rc("r",e)}],[{text:"\u{1F50D} Full diff",callback_data:rc("d",e)},{text:"\u274C Discard all",callback_data:rc("x",e)}]]}}function qQ(e){let{taskName:t,taskSlug:n,baseSha:r,branches:o,winner:s}=e,i=o.filter(y=>y.ok),a=o.filter(y=>!y.ok),l=o.length,c=i.length,u=i.map(y=>({index:y.index,score:y.score??null})),d=nc(u),p=new Map(o.map(y=>[y.index,y])),m=[];m.push(`\u{1F331} Farm complete: ${c}/${l} branches \u2014 ${t}`),m.push("");let g=1;for(let y of d){let S=p.get(y);if(!S)continue;let w=s!==void 0&&s===S.index,T=S.label?` (${S.label})`:"",x=S.score??null,C=x===null?"\u2014":x.pass>0?"\u2713":"\u2717",R=x===null?"\u2014":x.lint_ok===!0?"\u2713":x.lint_ok===!1?"\u2717":"?",k=x===null?"?":x.loc_delta>0?`+${x.loc_delta}`:x.loc_delta<0?`${x.loc_delta}`:"0",$=w?" \u2190 winner":"";m.push(`#${g} ${S.branch}${T} tests${C} lint${R} ${k} LoC${$}`),g++}let h=[...a].sort((y,S)=>y.index-S.index);for(let y of h){let S=y.label?` (${y.label})`:"",w=y.error??"unknown error";m.push(`#${g} ${y.branch}${S} failed: ${w}`),g++}m.push(""),s===void 0&&(m.push("\u26A0 no branch won (no successful + scored branches)"),m.push(""));let b=r.slice(0,7);return m.push(`base: ${b}`),m.push(`farm: ~/.afk/farms/${n}/`),m.join(`
|
|
2183
2183
|
`)}async function XD(e,t){let n=qQ(e),r=YD(e.taskSlug),o=t?._push??await Promise.resolve().then(()=>(Io(),Gg)).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 ZD=JQ(zQ);async function VQ(e,t){try{let{stdout:n}=await ZD("git",["-C",e,"rev-list",`${t}..HEAD`,"--count"],{maxBuffer:4194304});return parseInt(n.trim(),10)||0}catch{return 0}}async function YQ(e){try{let{stdout:t}=await ZD("git",["-C",e,"status","--porcelain"],{maxBuffer:4194304});return t.trim()?t.trim().split(`
|
|
2184
2184
|
`).filter(Boolean):[]}catch{return[]}}var sS=class extends Error{dirtyFiles;constructor(t){super(`Source repository has uncommitted changes after farm run. Dirty files:
|
|
2185
2185
|
${t.map(n=>` ${n}`).join(`
|
|
2186
|
-
`)}`),this.name="FarmIsolationViolation",this.dirtyFiles=t}};function XQ(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function ZQ(e){if(e===void 0)return Ee.dim("\u2014");if(e===null)return Ee.dim("skipped");let t=e.fail===0&&e.pass>0?Ee.green("tests\u2713"):Ee.red("tests\u2717"),n=e.lint_ok===!0?Ee.green("lint\u2713"):e.lint_ok===!1?Ee.red("lint\u2717"):Ee.dim("lint?"),r=e.loc_delta>0?"+":"",o=Ee.dim(`${r}${e.loc_delta} LoC`);return`${t} ${n} ${o}`}function QQ(e,t,n,r){let o="\u2500".repeat(45);console.log(Ee.dim(o)),console.log(`farm: ${e}`),console.log(`slug: ${t}`),console.log("");let s=r.some(u=>u.score!=null),i=s?nc(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?Ee.green("\u2713"):Ee.red("\u2717"),g=XQ(p.branch,40),h=d.ok?Ee.dim(`(${d.commitCount} commit${d.commitCount===1?"":"s"})`):Ee.red(`[error: ${d.error}]`),b=s?Ee.cyan(`#${u+1} `):"",y=s?` ${ZQ(d.score)}`:"";console.log(`${b}branch-${d.index} ${m} ${g} ${h}${y}`),console.log(Ee.dim(` worktree: ${p.path}`))}console.log(Ee.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(Ee.yellow("\u26A0 no branch passed tests \u2014 ranking falls back to lint + LoC"))}function eee(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=nc(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 tee(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=Gm,memoryWrite:d=!0,digest:p=!0,_createFarm:m=UD,_runSubagentDAG:g=Ud,_getCommitCount:h=VQ,_getSourceRepoDirtyFiles:b=YQ,_scoreBranch:y=GD,_writeScore:S=qD,_writeFarmFact:w=VD,_sendFarmDigest:T=XD,_setFarmMemoryFactId:x=jD,_createTraceWriter:C=eo}=e,R=new Date().toISOString();(!Number.isInteger(n)||n<1||n>16)&&(console.error(Ee.red(`--branches must be between 1 and 16 (got ${n})`)),process.exit(1)),r!==void 0&&r.length!==n&&(console.error(Ee.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(Ee.red(`Farm creation failed: ${j instanceof Error?j.message:String(j)}`)),process.exit(1)}let $=k.baseRef,A=o??
|
|
2187
|
-
`)),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(Ee.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(
|
|
2188
|
-
\u26A0 ISOLATION VIOLATION`)),console.error(Ee.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",
|
|
2186
|
+
`)}`),this.name="FarmIsolationViolation",this.dirtyFiles=t}};function XQ(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function ZQ(e){if(e===void 0)return Ee.dim("\u2014");if(e===null)return Ee.dim("skipped");let t=e.fail===0&&e.pass>0?Ee.green("tests\u2713"):Ee.red("tests\u2717"),n=e.lint_ok===!0?Ee.green("lint\u2713"):e.lint_ok===!1?Ee.red("lint\u2717"):Ee.dim("lint?"),r=e.loc_delta>0?"+":"",o=Ee.dim(`${r}${e.loc_delta} LoC`);return`${t} ${n} ${o}`}function QQ(e,t,n,r){let o="\u2500".repeat(45);console.log(Ee.dim(o)),console.log(`farm: ${e}`),console.log(`slug: ${t}`),console.log("");let s=r.some(u=>u.score!=null),i=s?nc(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?Ee.green("\u2713"):Ee.red("\u2717"),g=XQ(p.branch,40),h=d.ok?Ee.dim(`(${d.commitCount} commit${d.commitCount===1?"":"s"})`):Ee.red(`[error: ${d.error}]`),b=s?Ee.cyan(`#${u+1} `):"",y=s?` ${ZQ(d.score)}`:"";console.log(`${b}branch-${d.index} ${m} ${g} ${h}${y}`),console.log(Ee.dim(` worktree: ${p.path}`))}console.log(Ee.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(Ee.yellow("\u26A0 no branch passed tests \u2014 ranking falls back to lint + LoC"))}function eee(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=nc(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 tee(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=Gm,memoryWrite:d=!0,digest:p=!0,_createFarm:m=UD,_runSubagentDAG:g=Ud,_getCommitCount:h=VQ,_getSourceRepoDirtyFiles:b=YQ,_scoreBranch:y=GD,_writeScore:S=qD,_writeFarmFact:w=VD,_sendFarmDigest:T=XD,_setFarmMemoryFactId:x=jD,_createTraceWriter:C=eo}=e,R=new Date().toISOString();(!Number.isInteger(n)||n<1||n>16)&&(console.error(Ee.red(`--branches must be between 1 and 16 (got ${n})`)),process.exit(1)),r!==void 0&&r.length!==n&&(console.error(Ee.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(Ee.red(`Farm creation failed: ${j instanceof Error?j.message:String(j)}`)),process.exit(1)}let $=k.baseRef,A=o??Et(),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(`
|
|
2187
|
+
`)),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(Ee.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(me=>me.id===`branch-${j.index}`),oe=L.skipped.includes(`branch-${j.index}`);if(Y||oe){let me=Y?Y.error.message:"skipped";console.log(`[branch-${j.index}] \u2717 failed: ${me}`),I.push({index:j.index,ok:!1,commitCount:0,error:me});continue}let X=await h(j.path,$);if(X===0){let me="no commits made";console.log(`[branch-${j.index}] \u2717 failed: ${me}`),I.push({index:j.index,ok:!1,commitCount:0,error:me})}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(Ee.yellow(`[branch-${j.index}] score.json write failed: ${X instanceof Error?X.message:String(X)}`))}}if(QQ(t,k.taskSlug,k.branches,I),d||p){let j=eee(k,I,R);if(d){let Y=w(j);if("skipped"in Y)console.error(Ee.yellow(`[memory] write skipped: ${Y.reason}`));else{let{factId:oe}=Y;try{await x(k.taskSlug,oe)}catch(X){console.error(Ee.yellow(`[memory] setFarmMemoryFactId failed: ${X.message}`))}}}if(p){let Y=await T(j);Y.sent?console.log(Ee.dim(`[telegram] digest sent (${Y.chatCount} chat${Y.chatCount===1?"":"s"})`)):Y.reason&&Y.reason!=="telegram unconfigured"&&console.error(Ee.yellow(`[telegram] digest failed: ${Y.reason}`))}}if(U.length>0){let j=new sS(U);console.error(Ee.red(`
|
|
2188
|
+
\u26A0 ISOLATION VIOLATION`)),console.error(Ee.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",Et()).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 ${Gm})`).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(Ee.red(`--score-timeout must be a positive integer (got "${n.scoreTimeout}")`)),process.exit(1));try{await tee({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 fn from"chalk";import{execFile as nee}from"node:child_process";import{promisify as ree}from"node:util";Ot();var iS=ree(nee);async function eL(){try{return(await iS("git",["rev-parse","--show-toplevel"])).stdout.trim()}catch{throw new Error("Not in a git repository.")}}function oee(e){return["empty","stale-clean","orphaned-dir","orphaned-registration","dead-owner"].includes(e)?fn.red("yes"):e==="stale-dirty"?fn.yellow("warn"):fn.green("no")}var tL=["interactive","diagnose","all"];function see(e){if(tL.includes(e))return e;throw new Error(`Invalid --scope value: '${e}'. Allowed: ${tL.join(" | ")}.`)}function iee(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 nL(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 eL()}catch(s){G(s)}let r;try{r=await jn({execFile:iS,repoRoot:n,dryRun:!0})}catch(s){G(new Error(`Sweep failed: ${s.message}`))}let o=["PATH".padEnd(45),"OWNER".padEnd(12),"AGE".padEnd(6),"STATUS".padEnd(22),"PRUNE?"].join(" | ");console.log(fn.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),iee(s.ageMs).padEnd(6),s.verdict.padEnd(22),oee(s.verdict)].join(" | ");console.log(i)}if(r.candidates.length===0&&console.log(fn.dim(" (no afk-managed worktrees found)")),r.warnings.length>0){console.log("");for(let s of r.warnings)console.log(fn.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 eL()}catch(S){G(S)}let s=_t().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=see(n.scope)}catch(S){G(S)}let d={execFile:iS,repoRoot:r,dryRun:!n.apply,maxAgeDaysClean:l,maxAgeDaysDirty:c,scope:u},p;try{p=await jn(d)}catch(S){G(new Error(`Sweep failed: ${S.message}`))}p.dryRun&&console.log(fn.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)?fn.red("\u2717"):fn.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(fn.red(S)):console.log(fn.yellow(S))}p.warnings.some(S=>S.startsWith("[ERROR]"))&&process.exit(1)})}import{spawn as aee}from"child_process";var lee=/^\d+\.\d+\.\d+(-[\da-z.]+)?$/i;function cee(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 rL(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=xr();if(t.check===!0){process.stderr.write(`Checking for updates\u2026
|
|
2189
2189
|
`);let i=await Nw();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(cee(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&&!lee.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
|
|
2190
2190
|
`),r=await Nw(),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 uee(r);o===0?(Fw(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 uee(e){return new Promise(t=>{let n=aee("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 dee,readFileSync as pee}from"node:fs";Cu();K();rh();function oL(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=xu({name:n.name,command:n.command,cron:n.cron,trigger:n.trigger,notifyOn:n.notify,enabled:!n.disabled});(r.enabled?await an("POST","/tasks",{taskId:r.id,command:r.command,cron:r.cron,trigger:r.trigger,notifyOn:r.notifyOn}):await an("DELETE",`/tasks/${r.id}`)).synced||console.error(`\u26A0\uFE0F ${Fr}`),console.log(`\u2705 Added: ${r.id} \u2014 ${r.name}`)}catch(r){G(r)}}),t.command("list").description("List all scheduled tasks").action(()=>{try{let n=zt();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){G(n)}}),t.command("remove <id>").description("Permanently remove a scheduled task").action(async n=>{try{Ru(n)||(console.error(`Task not found: ${n}`),process.exit(1)),(await an("DELETE",`/tasks/${n}`)).synced||console.error(`\u26A0\uFE0F ${Fr}`),console.log(`\u2705 Removed: ${n}`)}catch(r){G(r)}}),t.command("enable <id>").description("Enable a scheduled task").action(async n=>{try{let r=Ka(n);r||(console.error(`Task not found: ${n}`),process.exit(1));let o=zt();$o(o.map(i=>i.id===n?{...i,enabled:!0,updatedAt:new Date().toISOString()}:i)),(await an("POST","/tasks",{taskId:r.id,command:r.command,cron:r.cron,trigger:r.trigger,notifyOn:r.notifyOn})).synced||console.error(`\u26A0\uFE0F ${Fr}`),console.log(`\u2705 Enabled: ${n}`)}catch(r){G(r)}}),t.command("disable <id>").description("Disable a scheduled task").action(async n=>{try{Ka(n)||(console.error(`Task not found: ${n}`),process.exit(1));let o=zt();$o(o.map(i=>i.id===n?{...i,enabled:!1,updatedAt:new Date().toISOString()}:i)),(await an("DELETE",`/tasks/${n}`)).synced||console.error(`\u26A0\uFE0F ${Fr}`),console.log(`\u2705 Disabled: ${n}`)}catch(r){G(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=Cr();if(!dee(s)){console.log(`No telemetry found for task: ${n}`);return}let i=pee(s),c=(i.length>1048576?i.subarray(i.length-1048576):i).toString("utf-8").split(`
|
|
2191
2191
|
`),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){G(o)}})}ad();function sL(e){return new Date(e).toISOString().replace("T"," ").slice(0,19)}function ia(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}var iL=9,qm=50,aL=22;function mee(e){let t=ia(e.jobId,aL),n=ia(e.status,iL),r=e.label.length>qm?`${e.label.slice(0,qm-1)}\u2026`:ia(e.label,qm),o=sL(e.startedAt),s=e.endedAt!==void 0?sL(e.endedAt):"\u2014";return`${t} ${n} ${r} ${o} ${s}`}function fee(e){return e.type==="done"||e.type==="error"}function lL(e){let t=e.command("bg").description(`Inspect persisted background subagent job logs.
|
|
@@ -2213,10 +2213,10 @@ or "latest" (the default) \u2014 the most recently written trace.`).option("--al
|
|
|
2213
2213
|
`)}}catch(r){G(r)}})}import ht from"chalk";import{execFileSync as Hee}from"child_process";import{existsSync as TL}from"fs";K();import{homedir as mL}from"os";import{join as uS}from"path";var la=["telegram","daemon"];function gt(e){return`com.afk.${e}`}function dS(e=mL()){return uS(e,"Library","LaunchAgents")}function mo(e,t=mL()){return uS(dS(t),`${gt(e)}.plist`)}function ca(e){return uS(ks(),`service-${e}.log`)}function oc(){return`gui/${process.getuid?.()??501}`}var ps=8e3;import{execFileSync as xee}from"child_process";import{existsSync as fL,realpathSync as gL}from"fs";import{homedir as Ree}from"os";import{delimiter as Cee,dirname as Aee,resolve as _ee}from"path";function fo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function hL(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>${fo(e.label)}</string>`),t.push(" <key>ProgramArguments</key>"),t.push(" <array>");for(let n of e.programArguments)t.push(` <string>${fo(n)}</string>`);if(t.push(" </array>"),t.push(" <key>WorkingDirectory</key>"),t.push(` <string>${fo(e.workingDirectory)}</string>`),t.push(" <key>StandardOutPath</key>"),t.push(` <string>${fo(e.standardOutPath)}</string>`),t.push(" <key>StandardErrorPath</key>"),t.push(` <string>${fo(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>${fo(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>${fo(r)}</key>`),t.push(` <string>${fo(o)}</string>`)}t.push(" </dict>")}return t.push("</dict>"),t.push("</plist>"),t.join(`
|
|
2214
2214
|
`)+`
|
|
2215
2215
|
`}var Iee=["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin","/usr/sbin","/sbin"];function yL(e=process.execPath){let t=Aee(e),n=new Set,r=[];for(let o of[t,...Iee])o.length>0&&!n.has(o)&&(n.add(o),r.push(o));return r.join(Cee)}function Pee(e=["/usr/local/bin/afk","/opt/homebrew/bin/afk"],t=fL,n=Mee,r=gL){let o=process.argv[1];if(o)try{let i=r(o);if(bL.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 bL=["/usr/local/bin/","/opt/homebrew/bin/","/usr/bin/","/opt/local/bin/"];function Mee(){try{let e=xee("which",["afk"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(!e)return;let t;try{t=gL(e)}catch{return}return bL.some(n=>t.startsWith(n))?t:void 0}catch{return}}function pS(e,t=fL){if(e==="telegram"){let r=Qw();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[Pee(),"daemon"]}function wL(e,t){let n=pS(e,t),r=e==="telegram"?n[1]:void 0;if(!r)return;let o=_ee(r),s=Ree();if(o.startsWith(s)&&!(o.includes("/node_modules/")||o.includes("/homebrew/")))return[o]}import{execFileSync as Oee}from"child_process";import{existsSync as $ee}from"fs";function Dee(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(`
|
|
2216
|
-
`)){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 mS(e){let t=mo(e),n={name:e,label:gt(e),installed:$ee(t),plistPath:t,logFile:ca(e)};if(!n.installed)return n;try{let r=Oee("launchctl",["list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:ps}),o=Dee(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 vL,mkdirSync as SL,readFileSync as
|
|
2216
|
+
`)){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 mS(e){let t=mo(e),n={name:e,label:gt(e),installed:$ee(t),plistPath:t,logFile:ca(e)};if(!n.installed)return n;try{let r=Oee("launchctl",["list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:ps}),o=Dee(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 vL,mkdirSync as SL,readFileSync as YWe,renameSync as Lee,rmSync as Fee,unlinkSync as Nee,writeFileSync as Bee}from"fs";import{homedir as Uee}from"os";import{dirname as jee}from"path";function kL(e,t={}){let n=mo(e);if(vL(n))return{kind:"already-installed",plistPath:n,label:gt(e)};let r;try{r=pS(e,t._entrypointExistsCheck)}catch(u){return{kind:"failed",reason:u.message}}let o=t.noWatch?void 0:wL(e,t._entrypointExistsCheck),s=ca(e);SL(dS(),{recursive:!0}),SL(jee(s),{recursive:!0});let i={PATH:yL(),...t.environment??{}},a={label:gt(e),programArguments:r,workingDirectory:Uee(),standardOutPath:s,standardErrorPath:s,...o?{watchPaths:o}:{},environmentVariables:i},l=hL(a),c=`${n}.tmp`;try{Bee(c,l,{encoding:"utf-8",flag:"wx",mode:384})}catch(u){return{kind:"failed",reason:`Failed to write plist (tmp ${c}): ${u.message}`}}try{Lee(c,n)}catch(u){try{Nee(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:gt(e),watchPathsActive:!!o};try{Jm("launchctl",["bootstrap",oc(),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",`${oc()}/${gt(e)}`],{stdio:["ignore","pipe","pipe"],timeout:ps})}catch(m){p=m.message}try{Jm("launchctl",["bootstrap",oc(),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:gt(e),watchPathsActive:!!o}}function EL(e,t={}){let n=mo(e);if(!vL(n))return{kind:"not-installed",plistPath:n};if(!t.skipBootout)try{Jm("launchctl",["bootout",`${oc()}/${gt(e)}`],{stdio:"ignore",timeout:ps})}catch{}try{Fee(n,{force:!0})}catch(r){return{kind:"failed",reason:`Failed to remove plist: ${r.message}`}}return{kind:"uninstalled",plistPath:n}}function sc(){if(process.platform!=="darwin")throw new Error(`'afk service' uses macOS launchd and is only supported on darwin. Detected: ${process.platform}.`)}function Vm(e){let t=e.toLowerCase();if(la.includes(t))return t;throw new Error(`Unknown service '${e}'. Supported: ${la.join(", ")}.`)}function RL(e){let t=e.command("service").description("Manage AFK background services via macOS launchd (always-on, auto-restart)");t.command("install <name>").description(`Install <${la.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{sc();let o=Vm(n),s=kL(o,{noWatch:r.watch===!1,skipBootstrap:!!r.dryRun});if(s.kind==="already-installed"&&(console.log(ht.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(ht.red(`\u2717 Install failed: ${s.reason}`)),process.exit(1)),console.log(ht.green(`\u2713 Installed ${s.label}`)),console.log(f.meta(` Plist: ${s.plistPath}`)),console.log(f.meta(` Log: ${ca(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){G(o)}}),t.command("uninstall <name>").description("Stop the service and remove its LaunchAgent plist").action(n=>{try{sc();let r=Vm(n),o=EL(r);if(o.kind==="not-installed"){console.log(ht.yellow(`\u26A0 ${gt(r)} is not installed (no plist at ${o.plistPath})`));return}o.kind==="failed"&&(console.error(ht.red(`\u2717 Uninstall failed: ${o.reason}`)),process.exit(1)),console.log(ht.green(`\u2713 Uninstalled ${gt(r)}`)),console.log(f.meta(` Removed: ${o.plistPath}`))}catch(r){G(r)}}),t.command("status [name]").description("Show running PID, last exit status, and log file for one or all services").action(n=>{try{if(sc(),n){let r=mS(Vm(n));xL(r);return}for(let r of la)xL(mS(r)),console.log("")}catch(r){G(r)}}),t.command("list").description("List recognised service names and whether each is installed").action(()=>{try{sc(),console.log(ht.bold("AFK services:"));for(let n of la){let r=mo(n),o=TL(r),s=o?ht.green("\u25CF"):ht.dim("\u25CB"),i=o?f.meta("installed"):f.meta("not installed");console.log(` ${s} ${n.padEnd(10)} ${i} ${f.meta(r)}`)}}catch(n){G(n)}}),t.command("restart <name>").description("Restart the service (launchctl kickstart -k)").action(n=>{try{sc();let r=Vm(n),o=mo(r);if(TL(o)||(console.error(ht.red(`\u2717 ${gt(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{Hee("launchctl",["kickstart","-k",`gui/${s}/${gt(r)}`],{stdio:["ignore","pipe","pipe"],timeout:8e3}),console.log(ht.green(`\u2713 Restarted ${gt(r)}`))}catch(i){console.error(ht.red(`\u2717 Restart failed: ${i.message}`)),process.exit(1)}}catch(r){G(r)}})}function xL(e){if(console.log(ht.bold(`${e.label}`)),!e.installed){console.log(` ${ht.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(` ${ht.green("\u25CF")} Running (PID ${e.pid})`):(console.log(` ${ht.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 Wee}from"child_process";import{existsSync as IL,mkdirSync as Kee,readFileSync as Gee,renameSync as qee,writeFileSync as zee}from"fs";import{dirname as CL,join as Jee}from"path";import{randomBytes as Vee}from"crypto";var go="chrome-devtools",fS=["stable","beta","canary","dev"];function Yee(e="stable"){let t=["chrome-devtools-mcp@latest","--autoConnect"];return e!=="stable"&&t.push("--channel",e),{command:"npx",args:t}}function AL(e){if(!IL(e))return{mcpServers:{}};let t;try{t=Gee(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 _L(e,t){Kee(CL(e),{recursive:!0});let n=Jee(CL(e),`.mcp.json.${process.pid}.${Vee(4).toString("hex")}.tmp`);zee(n,`${JSON.stringify(t,null,2)}
|
|
2217
2217
|
`,"utf-8"),qee(n,e)}function Xee(){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=Wee(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 Zee(){let e=Xee();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 PL(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 (${fS.join("|")})`,"stable").action(n=>{try{let r=(n.channel??"stable").toLowerCase();if(!fS.includes(r))throw new Error(`--channel must be one of ${fS.join(", ")} (got "${n.channel}")`);let o=jo(),s=AL(o);s.mcpServers===void 0&&(s.mcpServers={});let i=Yee(r),a=s.mcpServers[go];if(a!==void 0&&JSON.stringify(a)===JSON.stringify(i))console.log(ms.green(`\u2713 "${go}" already configured`)),console.log(f.meta(` Config: ${o}`));else{s.mcpServers[go]=i,_L(o,s);let l=a===void 0?"Added":"Updated";console.log(ms.green(`\u2713 ${l} "${go}" MCP server`)),console.log(f.meta(` Config: ${o}`)),console.log(f.meta(` Runs: npx ${i.args?.join(" ")??""}`))}Zee()}catch(r){G(r)}}),t.command("disconnect").description("Remove the chrome-devtools server from your MCP config").action(()=>{try{let n=jo();if(!IL(n)){console.log(ms.yellow(`\u26A0 No MCP config at ${n} \u2014 nothing to remove.`));return}let r=AL(n);if(r.mcpServers===void 0||r.mcpServers[go]===void 0){console.log(ms.yellow(`\u26A0 "${go}" is not configured \u2014 nothing to remove.`));return}delete r.mcpServers[go],_L(n,r),console.log(ms.green(`\u2713 Removed "${go}" from ${n}`))}catch(n){G(n)}})}import{readFileSync as Qee,readdirSync as ete,statSync as tte}from"fs";import{join as bS}from"path";K();import{join as et}from"path";function Ym(){return et(yn(),"improve")}function ho(){return et(Ym(),"failure-cards")}function ML(){return et(ho(),".index.jsonl")}function ic(e){return et(ho(),`${e}.json`)}function Xm(e){return et(ho(),`${e}.md`)}function OL(){return et(xe(),"witness")}function fs(){return et(Ym(),"proposals")}function $L(){return et(fs(),".index.jsonl")}function gS(e){return et(fs(),`${e}.json`)}function DL(e){return et(fs(),`${e}.md`)}function yo(){return et(Ym(),"eval-cases")}function LL(){return et(yo(),".index.jsonl")}function hS(e){return et(yo(),`${e}.json`)}function yS(e){return et(yo(),`${e}.fixture.jsonl`)}function FL(e){return et(yo(),`${e}.md`)}function ua(){return et(Ym(),"eval-runs")}function NL(){return et(ua(),".index.jsonl")}function BL(e){return et(ua(),`${e}.json`)}function UL(e){return et(ua(),`${e}.md`)}q();function jL(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 HL(e={}){let t=e.witnessRoot??OL(),n=e.afkHome??v.AFK_HOME??nte(),r=e.sinceMs,o={sessionsScanned:0,sessionsSkippedOld:0,sessionsSkippedEmpty:0,invalidLineCount:0,sessions:[]},s;try{s=ete(t)}catch{return o}for(let i of s){if(i.startsWith("."))continue;let a=bS(t,i),l;try{l=tte(a)}catch{continue}if(!l.isDirectory())continue;if(r!==void 0&&l.mtimeMs<r){o.sessionsSkippedOld+=1;continue}let c=bS(a,"trace.jsonl"),u;try{u=Qee(c,"utf-8")}catch{o.sessionsSkippedEmpty+=1;continue}let d=rte(c,n),p=da({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 da(e){let{sessionId:t,tracePath:n,relativeTracePath:r,content:o,sessionMtimeMs:s}=e,i=[],a=0,l=o.split(`
|
|
2218
2218
|
`);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=L_.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 nte(){let e=v.AFK_HOME;return e&&e.length>0?e:bS(v.HOME??"",".afk")}function rte(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 ote}from"crypto";var Rr=4,ste=8,ite="v1-bytes-tuple";function Zm(e,t={}){let n=t.minRepeats??Rr;if(n<2)throw new Error(`minRepeats must be >= 2 (got ${n})`);let r=[];for(let o of e){let s=ate(o,n);r.push(...s)}return r}function ate(e,t){let n=lte(e.events),r=cte(n),o=[];for(let[s,i]of r.entries()){let a=ute(i,t);for(let l of a)o.push(pte(e,l,s))}return o}function lte(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=dte({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 cte(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 ute(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 dte(e){let t=[e.name,String(e.inputBytes),String(e.resultBytes),e.isError?"1":"0",e.subagentId??""].join("|");return ote("sha256").update(t).digest("hex")}function pte(e,t,n){let r=t[0];if(!r)throw new Error("repeated-tool-use: empty run");let o=yte(r.name,r.fingerprint),s=new Date().toISOString(),i=t.slice(0,ste),a=[{sessionId:e.sessionId,tracePath:e.relativeTracePath,eventIndices:i.map(l=>l.completedSeq),excerpt:mte(i),annotation:fte(t,n)}];return{slug:o,title:gte(r.name,t.length),pattern:"repeated-tool-use",severity:hte(t.length),observedAt:s,evidence:a,detail:{detector:"repeated-tool-use@v1",fingerprintAlgorithm:ite,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 mte(e){let t=e.map(n=>n.rawLine).join(`
|
|
2219
|
-
`);return t.length<=2e3?t:t.slice(0,1997)+"..."}function fte(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 gte(e,t){return`'${e}' tool repeated ${t}\xD7 with identical fingerprint`}function hte(e){return e>=10?"high":e>=4?"medium":"low"}function yte(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 bte=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(!bte.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(Ste(s,i));return o}var wte=8;function Ste(e,t){let n=kte(e),r=new Date().toISOString(),s=t.slice(0,wte).map(l=>({sessionId:l.sessionId,tracePath:l.relativeTracePath,eventIndices:[l.seq],excerpt:Ete(l.rawLine),annotation:`closure.reason='${l.reason}' \xB7 cost=${Tte(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:vte(e,t.length),observedAt:r,evidence:s,detail:{detector:"closure-anomaly@v1",closureReason:e,affectedSessions:t.length,totalCostUsd:WL(i),avgTurnCount:xte(a),maxCostUsd:WL(Math.max(...t.map(l=>l.finalCostUsd))),sessionIds:t.map(l=>l.sessionId),seqs:t.map(l=>l.seq)}}}function vte(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 kte(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`closure-anomaly-${t.length>0?t:"unknown"}`}function Ete(e){return e.length<=2e3?e:e.slice(0,1997)+"..."}function Tte(e){return`$${e.toFixed(4)}`}function WL(e){return Math.round(e*1e4)/1e4}function xte(e){return Math.round(e*100)/100}import{createHash as Rte}from"crypto";var gs=2,Cte="v1-hook-reason-tuple",Ate=8;function KL(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=_te({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(Pte(s,i));return o}function _te(e){let t=[e.hookEvent,e.reason,e.blockedTool??""].join("|");return Rte("sha256").update(t).digest("hex")}function Ite(e){return`subagent-block-${e.slice(0,12)}`}function Pte(e,t){let n=t[0];if(!n)throw new Error("subagent-block: empty sighting bucket");let r=Ite(e),o=new Date().toISOString(),i=t.slice(0,Ate).map(l=>({sessionId:l.sessionId,tracePath:l.relativeTracePath,eventIndices:[l.seq],excerpt:Dte(l.rawLine),annotation:$te(l)})),a=new Set(t.map(l=>l.sessionId)).size;return{slug:r,title:Ote(n.reason,t.length,a),pattern:"subagent-block",severity:Mte(t.length,a),observedAt:o,evidence:i,detail:{detector:"subagent-block@v1",fingerprintAlgorithm:Cte,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 Mte(e,t){return e>=6||t>=3?"high":e>=3?"medium":"low"}function Ote(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 $te(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 Dte(e){return e.length<=2e3?e:e.slice(0,1997)+"..."}var Lte=new Set(["policy-refusal","permission-denied","hook-block","abort","elicitation-declined"]),hs=3,ys=.25,Fte=8;function pa(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=Nte(o,l.payload.name),u=l.payload.failureClass;if(u!==void 0&&Lte.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(Bte(i,a))}return s.sort((i,a)=>i.slug.localeCompare(a.slug)),s}function Nte(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 Bte(e,t){let n=Hte(e.toolName),r=new Date().toISOString(),s=e.failures.slice(0,Fte).map(u=>({sessionId:u.sessionId,tracePath:u.relativeTracePath,eventIndices:[u.seq],excerpt:Wte(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:jte(e.toolName,e.failures.length,e.totalCalls,t),pattern:"tool-failure-density",severity:Ute(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:Kte(t),affectedSessionCount:e.affectedSessions.size,truncatedFailureCount:e.truncatedFailureCount,avgFailureDurationMs:Gte(a),failureClassBreakdown:l,excludedByClass:c,sessionIds:Array.from(e.affectedSessions),seqs:e.failures.map(u=>u.seq)}}}function Ute(e,t){return t>=1||t>=.5?"high":t>=.25?e>=10?"high":"medium":e>=10?"medium":"low"}function jte(e,t,n,r){let o=(r*100).toFixed(1);return`'${e}' tool failed ${t}/${n} calls (${o}%)`}function Hte(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`tool-failure-${t.length>0?t:"unknown"}`}function Wte(e){return e.length<=2e3?e:e.slice(0,1997)+"..."}function Kte(e){return Math.round(e*1e4)/1e4}function Gte(e){return Math.round(e*100)/100}var ef=Object.freeze([{name:"repeated-tool-use",description:`Tool fired \u2265N consecutive times with identical fingerprint (default ${Rr})`,run:(e,t)=>Zm(e,{minRepeats:t.minRepeats??Rr})},{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)=>KL(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)=>pa(e,{minFailures:t.toolFailureMinFailures??hs,minFailureRate:t.toolFailureMinRate??ys})}]);function GL(e,t,n,r){let o=[];for(let s of ef){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 tf(){return ef.map(e=>e.name)}function qL(){return ef.filter(e=>e.enabledByDefault!==!1).map(e=>e.name)}function ma(){return ef.filter(e=>e.enabledByDefault===!1).map(e=>e.name)}import{existsSync as cc,mkdirSync as tF,readFileSync as cne,readdirSync as nF,renameSync as rF,writeFileSync as vS}from"fs";import{join as oF}from"path";import{z as O}from"zod";var fa=O.enum(["repeated-tool-use","subagent-block","closure-anomaly","tool-failure-density"]),nf=O.enum(["low","medium","high"]),qte=O.enum(["open","deferred","resolved"]),zL=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()}),rf=O.object({at:O.string().datetime(),text:O.string()}),lc=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:fa,severity:nf,status:qte,firstSeen:O.string().datetime(),lastSeen:O.string().datetime(),occurrenceCount:O.number().int().nonnegative(),evidence:O.array(zL).min(1),detail:O.record(O.string(),O.unknown()),notes:O.array(rf).default([])}),WKe=O.object({slug:O.string().regex(/^[a-z0-9][a-z0-9-]*$/),title:O.string().min(1).max(200),pattern:fa,severity:nf,observedAt:O.string().datetime(),evidence:O.array(zL).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:fa,occurrenceCount:O.number().int().nonnegative(),evidenceAdded:O.number().int().nonnegative()}),zte=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"]),Jte=O.enum(["safe","moderate","high","forbidden"]),Vte=O.enum(["low","medium","high"]),Yte=O.object({cardSlug:O.string(),eventIndices:O.array(O.number().int().nonnegative()).min(1),annotation:O.string().optional()}),Xte=O.object({path:O.string().min(1),rationale:O.string(),riskTier:Jte,confidence:Vte}),Zte=O.object({unitTests:O.array(O.string()),evalCases:O.array(O.string()),smokeChecks:O.array(O.string()),manualChecks:O.array(O.string())}),Qte=O.object({forbiddenPaths:O.array(O.string()),requiresExplicitApproval:O.boolean()}),ene=O.enum(["draft","approved","rejected","superseded"]),wS=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:zte,evidenceRefs:O.array(Yte).min(1),fixSketch:O.string().min(1),likelyFiles:O.array(Xte),riskLevel:nf,validationPlan:Zte,scopeFreeze:Qte,generatedBy:O.enum(["template","llm"]),createdAt:O.string().datetime(),status:ene,notes:O.array(rf).default([])}),VL=O.object({timestamp:O.string().datetime(),event:O.enum(["created","triaged","superseded"]),proposalId:O.string(),cardSlug:O.string(),generatedBy:O.enum(["template","llm"]),riskLevel:nf}),tne=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")}),nne=O.object({kind:O.literal("pattern-absent"),patternId:fa,detectorVersion:O.string().min(1),rationale:O.string().min(1)}),rne=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")}),one=O.enum(["draft","approved","rejected","superseded"]),of=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:tne,assertion:nne,provenance:rne,status:one,notes:O.array(rf).default([])}),YL=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")}),sne=O.enum(["pass","fail","skipped"]),ine=O.object({name:O.string().min(1),description:O.string().min(1),status:sne,expected:O.string(),actual:O.string()}),ane=O.enum(["config-value","observed-behavior","source-symbol","fixture"]),lne=O.object({kind:ane,ref:O.string().min(1),detail:O.string()}),XL=O.enum(["pass","fail","unsupported","error"]),SS=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:fa,contract:O.string().min(1).nullable(),status:XL,createdAt:O.string().datetime(),durationMs:O.number().int().nonnegative(),checks:O.array(ine),evidence:O.array(lne),runner:O.object({version:O.string().min(1),mode:O.literal("deterministic")}),notes:O.array(rf).default([])}),ZL=O.object({timestamp:O.string().datetime(),event:O.literal("created"),evalRunId:O.string(),evalCaseId:O.string(),cardSlug:O.string(),patternId:fa,contract:O.string().nullable(),status:XL}),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 sF(e){let t=ho();cc(t)||tF(t,{recursive:!0});let n=ic(e.slug),r=Xm(e.slug),o=ga(n),s=une(o,e),i=o===void 0,a=s.evidence.length-(o?.evidence.length??0),l=i?"created":a>0?"updated":"merged-noop",c=lc.parse(s);return mne(n,c),fne(r,uc(c)),pne({timestamp:gne(),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 ga(e){if(cc(e))try{let t=cne(e,"utf-8"),n=JSON.parse(t),r=lc.safeParse(n);return r.success?r.data:void 0}catch{return}}function une(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=dne(e.evidence,t.evidence),r=hne(e.firstSeen,t.observedAt),o=yne(e.lastSeen,t.observedAt),s=bne(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 dne(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 uc(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(`
|
|
2219
|
+
`);return t.length<=2e3?t:t.slice(0,1997)+"..."}function fte(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 gte(e,t){return`'${e}' tool repeated ${t}\xD7 with identical fingerprint`}function hte(e){return e>=10?"high":e>=4?"medium":"low"}function yte(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 bte=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(!bte.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(Ste(s,i));return o}var wte=8;function Ste(e,t){let n=kte(e),r=new Date().toISOString(),s=t.slice(0,wte).map(l=>({sessionId:l.sessionId,tracePath:l.relativeTracePath,eventIndices:[l.seq],excerpt:Ete(l.rawLine),annotation:`closure.reason='${l.reason}' \xB7 cost=${Tte(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:vte(e,t.length),observedAt:r,evidence:s,detail:{detector:"closure-anomaly@v1",closureReason:e,affectedSessions:t.length,totalCostUsd:WL(i),avgTurnCount:xte(a),maxCostUsd:WL(Math.max(...t.map(l=>l.finalCostUsd))),sessionIds:t.map(l=>l.sessionId),seqs:t.map(l=>l.seq)}}}function vte(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 kte(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`closure-anomaly-${t.length>0?t:"unknown"}`}function Ete(e){return e.length<=2e3?e:e.slice(0,1997)+"..."}function Tte(e){return`$${e.toFixed(4)}`}function WL(e){return Math.round(e*1e4)/1e4}function xte(e){return Math.round(e*100)/100}import{createHash as Rte}from"crypto";var gs=2,Cte="v1-hook-reason-tuple",Ate=8;function KL(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=_te({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(Pte(s,i));return o}function _te(e){let t=[e.hookEvent,e.reason,e.blockedTool??""].join("|");return Rte("sha256").update(t).digest("hex")}function Ite(e){return`subagent-block-${e.slice(0,12)}`}function Pte(e,t){let n=t[0];if(!n)throw new Error("subagent-block: empty sighting bucket");let r=Ite(e),o=new Date().toISOString(),i=t.slice(0,Ate).map(l=>({sessionId:l.sessionId,tracePath:l.relativeTracePath,eventIndices:[l.seq],excerpt:Dte(l.rawLine),annotation:$te(l)})),a=new Set(t.map(l=>l.sessionId)).size;return{slug:r,title:Ote(n.reason,t.length,a),pattern:"subagent-block",severity:Mte(t.length,a),observedAt:o,evidence:i,detail:{detector:"subagent-block@v1",fingerprintAlgorithm:Cte,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 Mte(e,t){return e>=6||t>=3?"high":e>=3?"medium":"low"}function Ote(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 $te(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 Dte(e){return e.length<=2e3?e:e.slice(0,1997)+"..."}var Lte=new Set(["policy-refusal","permission-denied","hook-block","abort","elicitation-declined"]),hs=3,ys=.25,Fte=8;function pa(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=Nte(o,l.payload.name),u=l.payload.failureClass;if(u!==void 0&&Lte.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(Bte(i,a))}return s.sort((i,a)=>i.slug.localeCompare(a.slug)),s}function Nte(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 Bte(e,t){let n=Hte(e.toolName),r=new Date().toISOString(),s=e.failures.slice(0,Fte).map(u=>({sessionId:u.sessionId,tracePath:u.relativeTracePath,eventIndices:[u.seq],excerpt:Wte(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:jte(e.toolName,e.failures.length,e.totalCalls,t),pattern:"tool-failure-density",severity:Ute(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:Kte(t),affectedSessionCount:e.affectedSessions.size,truncatedFailureCount:e.truncatedFailureCount,avgFailureDurationMs:Gte(a),failureClassBreakdown:l,excludedByClass:c,sessionIds:Array.from(e.affectedSessions),seqs:e.failures.map(u=>u.seq)}}}function Ute(e,t){return t>=1||t>=.5?"high":t>=.25?e>=10?"high":"medium":e>=10?"medium":"low"}function jte(e,t,n,r){let o=(r*100).toFixed(1);return`'${e}' tool failed ${t}/${n} calls (${o}%)`}function Hte(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`tool-failure-${t.length>0?t:"unknown"}`}function Wte(e){return e.length<=2e3?e:e.slice(0,1997)+"..."}function Kte(e){return Math.round(e*1e4)/1e4}function Gte(e){return Math.round(e*100)/100}var ef=Object.freeze([{name:"repeated-tool-use",description:`Tool fired \u2265N consecutive times with identical fingerprint (default ${Rr})`,run:(e,t)=>Zm(e,{minRepeats:t.minRepeats??Rr})},{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)=>KL(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)=>pa(e,{minFailures:t.toolFailureMinFailures??hs,minFailureRate:t.toolFailureMinRate??ys})}]);function GL(e,t,n,r){let o=[];for(let s of ef){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 tf(){return ef.map(e=>e.name)}function qL(){return ef.filter(e=>e.enabledByDefault!==!1).map(e=>e.name)}function ma(){return ef.filter(e=>e.enabledByDefault===!1).map(e=>e.name)}import{existsSync as cc,mkdirSync as tF,readFileSync as cne,readdirSync as nF,renameSync as rF,writeFileSync as vS}from"fs";import{join as oF}from"path";import{z as O}from"zod";var fa=O.enum(["repeated-tool-use","subagent-block","closure-anomaly","tool-failure-density"]),nf=O.enum(["low","medium","high"]),qte=O.enum(["open","deferred","resolved"]),zL=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()}),rf=O.object({at:O.string().datetime(),text:O.string()}),lc=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:fa,severity:nf,status:qte,firstSeen:O.string().datetime(),lastSeen:O.string().datetime(),occurrenceCount:O.number().int().nonnegative(),evidence:O.array(zL).min(1),detail:O.record(O.string(),O.unknown()),notes:O.array(rf).default([])}),KKe=O.object({slug:O.string().regex(/^[a-z0-9][a-z0-9-]*$/),title:O.string().min(1).max(200),pattern:fa,severity:nf,observedAt:O.string().datetime(),evidence:O.array(zL).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:fa,occurrenceCount:O.number().int().nonnegative(),evidenceAdded:O.number().int().nonnegative()}),zte=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"]),Jte=O.enum(["safe","moderate","high","forbidden"]),Vte=O.enum(["low","medium","high"]),Yte=O.object({cardSlug:O.string(),eventIndices:O.array(O.number().int().nonnegative()).min(1),annotation:O.string().optional()}),Xte=O.object({path:O.string().min(1),rationale:O.string(),riskTier:Jte,confidence:Vte}),Zte=O.object({unitTests:O.array(O.string()),evalCases:O.array(O.string()),smokeChecks:O.array(O.string()),manualChecks:O.array(O.string())}),Qte=O.object({forbiddenPaths:O.array(O.string()),requiresExplicitApproval:O.boolean()}),ene=O.enum(["draft","approved","rejected","superseded"]),wS=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:zte,evidenceRefs:O.array(Yte).min(1),fixSketch:O.string().min(1),likelyFiles:O.array(Xte),riskLevel:nf,validationPlan:Zte,scopeFreeze:Qte,generatedBy:O.enum(["template","llm"]),createdAt:O.string().datetime(),status:ene,notes:O.array(rf).default([])}),VL=O.object({timestamp:O.string().datetime(),event:O.enum(["created","triaged","superseded"]),proposalId:O.string(),cardSlug:O.string(),generatedBy:O.enum(["template","llm"]),riskLevel:nf}),tne=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")}),nne=O.object({kind:O.literal("pattern-absent"),patternId:fa,detectorVersion:O.string().min(1),rationale:O.string().min(1)}),rne=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")}),one=O.enum(["draft","approved","rejected","superseded"]),of=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:tne,assertion:nne,provenance:rne,status:one,notes:O.array(rf).default([])}),YL=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")}),sne=O.enum(["pass","fail","skipped"]),ine=O.object({name:O.string().min(1),description:O.string().min(1),status:sne,expected:O.string(),actual:O.string()}),ane=O.enum(["config-value","observed-behavior","source-symbol","fixture"]),lne=O.object({kind:ane,ref:O.string().min(1),detail:O.string()}),XL=O.enum(["pass","fail","unsupported","error"]),SS=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:fa,contract:O.string().min(1).nullable(),status:XL,createdAt:O.string().datetime(),durationMs:O.number().int().nonnegative(),checks:O.array(ine),evidence:O.array(lne),runner:O.object({version:O.string().min(1),mode:O.literal("deterministic")}),notes:O.array(rf).default([])}),ZL=O.object({timestamp:O.string().datetime(),event:O.literal("created"),evalRunId:O.string(),evalCaseId:O.string(),cardSlug:O.string(),patternId:fa,contract:O.string().nullable(),status:XL}),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 sF(e){let t=ho();cc(t)||tF(t,{recursive:!0});let n=ic(e.slug),r=Xm(e.slug),o=ga(n),s=une(o,e),i=o===void 0,a=s.evidence.length-(o?.evidence.length??0),l=i?"created":a>0?"updated":"merged-noop",c=lc.parse(s);return mne(n,c),fne(r,uc(c)),pne({timestamp:gne(),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 ga(e){if(cc(e))try{let t=cne(e,"utf-8"),n=JSON.parse(t),r=lc.safeParse(n);return r.success?r.data:void 0}catch{return}}function une(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=dne(e.evidence,t.evidence),r=hne(e.firstSeen,t.observedAt),o=yne(e.lastSeen,t.observedAt),s=bne(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 dne(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 uc(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(`
|
|
2220
2220
|
`)}function pne(e){let t=JL.parse(e),n=ML(),r=ho();cc(r)||tF(r,{recursive:!0});try{vS(n,JSON.stringify(t)+`
|
|
2221
2221
|
`,{flag:"a"})}catch{}}function mne(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;vS(n,JSON.stringify(t,null,2)),rF(n,e)}function fne(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;vS(n,t),rF(n,e)}function gne(){return new Date().toISOString()}function hne(e,t){return e<=t?e:t}function yne(e,t){return e>=t?e:t}var eF={low:0,medium:1,high:2};function bne(e,t){return eF[e]>=eF[t]?e:t}function iF(){let e=ho();if(!cc(e))return[];let t=[];for(let n of nF(e)){if(!n.endsWith(".json")||n.startsWith("."))continue;let r=ga(oF(e,n));r&&t.push({slug:r.slug,title:r.title,pattern:r.pattern,severity:r.severity,status:r.status,occurrenceCount:r.occurrenceCount,firstSeen:r.firstSeen,lastSeen:r.lastSeen})}return t.sort((n,r)=>n.lastSeen!==r.lastSeen?n.lastSeen<r.lastSeen?1:-1:n.slug<r.slug?-1:1),t}function sf(e){return ga(ic(e))}function aF(e){let t;for(let n of e.notes)(t===void 0||Date.parse(n.at)>Date.parse(t))&&(t=n.at);return t}function wne(e){if(e.status!=="resolved"&&e.status!=="deferred")return!1;let t=aF(e);if(t===void 0)return!1;let n=Date.parse(e.lastSeen),r=Date.parse(t);return Number.isNaN(n)||Number.isNaN(r)?!1:n>r}function Sne(e){let t=[];for(let n of e){if(!wne(n))continue;let r=aF(n);r!==void 0&&t.push({slug:n.slug,pattern:n.pattern,severity:n.severity,status:n.status,occurrenceCount:n.occurrenceCount,lastSeen:n.lastSeen,latestNoteAt:r})}return t.sort((n,r)=>n.lastSeen!==r.lastSeen?n.lastSeen<r.lastSeen?1:-1:n.slug<r.slug?-1:1),t}function lF(){let e=ho();if(!cc(e))return[];let t=[];for(let n of nF(e)){if(!n.endsWith(".json")||n.startsWith("."))continue;let r=ga(oF(e,n));r&&t.push(r)}return Sne(t)}import{existsSync as vne,mkdirSync as kne,renameSync as cF,writeFileSync as uF}from"fs";import{dirname as Ene}from"path";var bs=class extends Error{constructor(n,r){super(r);this.code=n;this.name="TriageError"}code};function dF(e,t){let n=ic(e),r=Xm(e),o=ga(n);if(!o)throw new bs("card-not-found",`No failure card found for slug '${e}'`);if(t.note!==void 0&&t.note.trim().length===0)throw new bs("invalid-note","triage note must be non-empty after trim");let s=t.note?.trim(),i=s!==void 0&&s.length>0,a=t.status!==void 0&&t.status!==o.status;if(!i&&!a)throw new bs("no-change","triage requires at least --note or --status to differ from current");let l=(t.now??(()=>new Date))().toISOString(),c=i?[...o.notes,{at:l,text:s}]:o.notes,u=a?t.status:o.status,d={...o,status:u,notes:c},p=lc.parse(d);return Tne(n),xne(n,p),Rne(r,uc(p)),{slug:e,card:p,noteAdded:i,statusChanged:a?{from:o.status,to:u}:void 0,jsonPath:n,markdownPath:r}}function Tne(e){let t=Ene(e);vne(t)||kne(t,{recursive:!0})}function xne(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;uF(n,JSON.stringify(t,null,2)),cF(n,e)}function Rne(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;uF(n,t),cF(n,e)}var Cne={"repeated-tool-use":{rootCauseClass:"dispatcher-bug",hypothesis:e=>{let t=typeof e.detail.toolName=="string"?e.detail.toolName:"<unknown>",n=typeof e.detail.runLength=="number"?e.detail.runLength:"?";return`The '${t}' tool was dispatched ${n} times in a row with an identical input/output byte fingerprint. This is either (a) the model is stuck retrying the same call without responding to its result, (b) the tool's result shape is too uninformative for the model to make progress, or (c) a productive recursion that happens to share byte counts (rare; the fingerprint caveat is documented on the detector).`},fixSketch:e=>["## Candidate fixes (human picks)","",`**Option A \u2014 make the loop visible.** Surface a clear "no-progress" signal to the model when '${typeof e.detail.toolName=="string"?e.detail.toolName:"<the tool>"}' returns the same result N times in a row. Today the dispatcher just executes the call.`,"",`**Option B \u2014 improve the tool's result shape.** If the model can't distinguish "no results" from "same results," its result is information-poor. Inspect the tool's response and verify it carries enough signal for the model to change its query.`,"","**Option C \u2014 confirm productive recursion.** Open the source trace at the seq values listed in the evidence and inspect the model's reasoning between repeats. If each call's args genuinely differ (and the byte-count collision is the issue), no code change is needed; tune the detector instead.","","_Option C first \u2014 the byte-fingerprint detector has a documented collision caveat. Confirm there is a real loop before changing dispatcher behavior._"].join(`
|
|
2222
2222
|
`),likelyFiles:[{path:"src/agent/providers/anthropic-direct/loop.ts",rationale:"Main tool dispatch loop. If a no-progress detector is added at the dispatch boundary, it lives here.",riskTier:"moderate",confidence:"medium"},{path:"src/agent/tools/",rationale:"Tool implementations. If the result shape is information-poor, the specific tool implementation needs the change.",riskTier:"safe",confidence:"low"},{path:"src/improve/scan/detectors/repeated-tool-use.ts",rationale:"If this turns out to be detector noise rather than a real bug, tune here.",riskTier:"safe",confidence:"medium"}],riskFloor:"medium",validationPlan:{unitTests:["pnpm test -- src/improve/scan/detectors/repeated-tool-use","pnpm test -- src/agent/providers/anthropic-direct"],evalCases:[],smokeChecks:["pnpm lint","afk improve scan --since 7d # after fix lands, this pattern should NOT recur"],manualChecks:["Open the trace at the evidence seqs and confirm the calls are truly identical (not just byte-coincident)."]}},"subagent-block":{rootCauseClass:"hook-overreach",hypothesis:e=>{let t=typeof e.detail.reason=="string"?e.detail.reason:"",n=typeof e.detail.blockCount=="number"?e.detail.blockCount:"?",r=typeof e.detail.distinctSessions=="number"?e.detail.distinctSessions:"?",o=t?` with reason "${t.slice(0,200)}"`:" (no reason field on the block events)";return`A SubagentStart hook returned decision:'block' ${n} times across ${r} session(s)${o}. Recurring blocks suggest either (a) the guard is over-broad and trips on legitimate dispatches, (b) the legitimate use case actually needs a refactor to satisfy the guard, or (c) the user has no signal explaining the block and keeps retrying.`},fixSketch:e=>{let t=typeof e.detail.reason=="string"?e.detail.reason:"<not in payload>";return["## Candidate fixes (human picks)","",`**Identify the hook owner first.** The trace's hook_decision event carries the \`reason\` field ("${t}"). Grep the codebase for that literal string \u2014 that locates the hook handler.`,"","```sh","# Replace the quoted string below with the actual reason text from the evidence.",`grep -rn -- "${t.slice(0,60).replace(/"/g,'\\"')}" src/`,"```","","**Option A \u2014 tighten the guard.** If the block fires on dispatches it should not, narrow the predicate. Confirm by adding a unit test that exercises the false-positive case.","","**Option B \u2014 make the refusal legible.** Instead of `decision: 'block'`, return a hook decision that injects a context message via `injectContext`. The parent session then sees a clear no-op message instead of a silent block.","",'**Option C \u2014 accept the block as correct.** If the guard is doing its job, mark the card resolved via `afk improve cards triage <slug> --status resolved --note "..."`. No code change.'].join(`
|
|
@@ -2226,7 +2226,7 @@ or "latest" (the default) \u2014 the most recently written trace.`).option("--al
|
|
|
2226
2226
|
`)}function bF(){let e=fs();if(!af(e))return[];let t=[];for(let n of Lne(e)){if(!n.endsWith(".json")||n.startsWith("."))continue;let r=wF(Fne(e,n));r&&t.push({proposalId:r.proposalId,cardSlug:r.cardSlug,title:r.title,riskLevel:r.riskLevel,status:r.status,rootCauseClass:r.rootCauseClass,generatedBy:r.generatedBy,createdAt:r.createdAt})}return t.sort((n,r)=>n.createdAt!==r.createdAt?n.createdAt<r.createdAt?1:-1:n.proposalId<r.proposalId?-1:1),t}function ES(e){return wF(gS(e))}function wF(e){if(af(e))try{let t=Dne(e,"utf-8"),n=JSON.parse(t),r=wS.safeParse(n);return r.success?r.data:void 0}catch{return}}function Bne(e){let t=VL.parse(e),n=$L(),r=fs();af(r)||fF(r,{recursive:!0});try{kS(n,JSON.stringify(t)+`
|
|
2227
2227
|
`,{flag:"a"})}catch{}}function Une(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;kS(n,JSON.stringify(t,null,2)),gF(n,e)}function jne(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;kS(n,t),gF(n,e)}import{createHash as SF}from"crypto";import{existsSync as Hne,readFileSync as Wne}from"fs";var Zt=class extends Error{code;constructor(t,n){super(t),this.name="EvalGenError",this.code=n}};function vF(e,t){if(!Hne(e))throw new Zt(`replay-fixture: source trace not found: ${e}`,"source-not-found");let n=t.startLine??1;if(n!==1)throw new Zt(`replay-fixture: only startLine=1 (prefix slice) is supported in Sprint 3 (got ${n})`,"unsupported-window");let r=Wne(e);if(r.length===0)throw new Zt(`replay-fixture: source trace is empty: ${e}`,"source-empty");let o=Kne(r),s=o.length,i=-1;for(let d=0;d<o.length;d++){let p=o[d];if(p.contentEnd===p.start)continue;let m=r.subarray(p.start,p.contentEnd).toString("utf8"),g;try{g=JSON.parse(m)}catch{continue}if(g!==null&&typeof g=="object"&&"seq"in g&&typeof g.seq=="number"&&g.seq===t.endSeq){i=d+1;break}}if(i===-1)throw new Zt(`replay-fixture: seq ${t.endSeq} not found in ${e} (scanned ${s} lines)`,"seq-not-found");let l=o[i-1].byteEnd,c=Buffer.from(r.subarray(0,l)),u=SF("sha256").update(c).digest("hex");return{bytes:c,startLine:1,endLine:i,sliceLineCount:i,sliceSha256:u,sourceLineCount:s}}function cf(e){return SF("sha256").update(e).digest("hex")}function Kne(e){let t=[],n=0;for(let r=0;r<e.length;r++)e[r]===10&&(t.push({start:n,contentEnd:r,byteEnd:r+1}),n=r+1);return n<e.length&&t.push({start:n,contentEnd:e.length,byteEnd:e.length}),t}import{randomBytes as Gne}from"crypto";import{existsSync as uf,mkdirSync as kF,readFileSync as EF,readdirSync as qne,renameSync as TS,writeFileSync as df}from"fs";import{join as TF,relative as zne}from"path";K();function xF(e,t={}){let n=(t.now??(()=>new Date))(),r=Jne(n),o=t.randomSuffix!==void 0?t.randomSuffix():Gne(3).toString("hex");if(!/^[0-9a-f]{6}$/.test(o))throw new Error(`generateEvalCaseId: randomSuffix must be 6 lowercase hex chars (got '${o}')`);return`${e}-eval-${r}-${o}`}function Jne(e){let t=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0"),r=String(e.getUTCDate()).padStart(2,"0");return`${t}${n}${r}`}function RF(e,t){if(t.evidenceRowIndex<0||t.evidenceRowIndex>=e.evidence.length)throw new Zt(`buildEvalCase: evidence row ${t.evidenceRowIndex} out of range (card has ${e.evidence.length} row(s))`,"evidence-row-out-of-range");let n=e.evidence[t.evidenceRowIndex];if(n.eventIndices.length===0)throw new Zt(`buildEvalCase: evidence row ${t.evidenceRowIndex} has no eventIndices`,"seq-not-found");let r=Math.max(...n.eventIndices),s=(t.resolveTraceAbsPath??Vne)(n.tracePath),i=vF(s,{endSeq:r}),a=(t.now??(()=>new Date))().toISOString(),l=yS(t.evalCaseId),c=zne(De(),l),u=typeof e.detail.detector=="string"?e.detail.detector:e.pattern,d=typeof e.detail.fingerprint=="string"?e.detail.fingerprint:null,p=t.proposalId??null,m={schemaVersion:1,evalCaseId:t.evalCaseId,cardSlug:e.slug,proposalId:p,title:Yne(e,r),createdAt:a,kind:"replay",replay:{sourceSessionId:n.sessionId,sourceTracePath:n.tracePath,fixturePath:c,evidenceRowIndex:t.evidenceRowIndex,evidenceEventIndices:[...n.eventIndices],sliceLineRange:{startLine:i.startLine,endLine:i.endLine},sliceLineCount:i.sliceLineCount,sliceSha256:i.sliceSha256},assertion:{kind:"pattern-absent",patternId:e.pattern,detectorVersion:u,rationale:Xne({patternId:e.pattern,detectorVersion:u,endSeq:r,sliceLineCount:i.sliceLineCount,sessionId:n.sessionId})},provenance:{detectorAtGeneration:u,fingerprintAtGeneration:d,cardOccurrenceCountAtGeneration:e.occurrenceCount,cardLastSeenAtGeneration:e.lastSeen,generatedBy:"replay-fixture"},status:"draft",notes:[]};return of.parse(m),{evalCase:m,sliceBytes:i.bytes}}function Vne(e){return TF(De(),e)}function Yne(e,t){let n="Replay [pattern-absent]: ",r=` (through seq ${t})`,o=200-n.length-r.length,s=e.title.length>o?e.title.slice(0,o-1)+"\u2026":e.title;return`${n}${s}${r}`.slice(0,200)}function Xne(e){let t=e.sessionId.slice(0,8);return`After the proposed fix lands, replaying the prefix [seq 0..${e.endSeq}] (${e.sliceLineCount} lines, session ${t}\u2026) through ${e.detectorVersion} must produce zero findings for '${e.patternId}' with the fingerprint at generation time. **Sprint 3 ships eval-case-as-contract; the runner that enforces this lands in a later sprint.**`}function CF(e,t){let n=of.parse(e),r=yo();uf(r)||kF(r,{recursive:!0});let o=hS(n.evalCaseId),s=yS(n.evalCaseId),i=FL(n.evalCaseId);tre(s,t);let a=cf(EF(s));if(a!==n.replay.sliceSha256)throw new Zt(`writeEvalCase: fixture sha256 mismatch after write (expected ${n.replay.sliceSha256}, got ${a}, path ${s})`,"fixture-mismatch");return Qne(o,n),ere(i,pf(n)),Zne({timestamp:new Date().toISOString(),event:"created",evalCaseId:n.evalCaseId,cardSlug:n.cardSlug,proposalId:n.proposalId,kind:n.kind}),{evalCaseId:n.evalCaseId,jsonPath:o,fixturePath:s,markdownPath:i}}function pf(e){let t=[];if(t.push(`# ${e.evalCaseId} \u2014 \`${e.kind}\` \u2014 \`${e.status}\``),t.push(""),t.push(e.title),t.push(""),t.push(`**Card:** \`${e.cardSlug}\` \xB7 **Proposal:** ${e.proposalId?`\`${e.proposalId}\``:"_(none)_"} \xB7 **Created:** ${e.createdAt}`),t.push(""),t.push("> **Sprint 3 disclaimer.** This file is a CONTRACT, not an"),t.push("> executable. No runner consumes it yet. A future sprint will"),t.push("> replay the fixture through the detector and assert the"),t.push("> pattern is absent. Until then this artifact captures intent."),t.push(""),t.push("## Replay fixture"),t.push(""),t.push(`- **Source session:** \`${e.replay.sourceSessionId}\``),t.push(`- **Source trace:** \`${e.replay.sourceTracePath}\``),t.push(`- **Fixture:** \`${e.replay.fixturePath}\``),t.push(`- **Evidence row:** index ${e.replay.evidenceRowIndex} (seqs ${e.replay.evidenceEventIndices.join(", ")})`),t.push(`- **Slice:** lines ${e.replay.sliceLineRange.startLine}\u2013${e.replay.sliceLineRange.endLine} (${e.replay.sliceLineCount} lines)`),t.push(`- **SHA-256:** \`${e.replay.sliceSha256}\``),t.push(""),t.push("## Assertion"),t.push(""),t.push(`- **Kind:** \`${e.assertion.kind}\``),t.push(`- **Pattern:** \`${e.assertion.patternId}\``),t.push(`- **Detector:** \`${e.assertion.detectorVersion}\``),t.push(""),t.push(e.assertion.rationale),t.push(""),t.push("## Provenance"),t.push(""),t.push(`- **Detector at generation:** \`${e.provenance.detectorAtGeneration}\``),t.push(`- **Fingerprint at generation:** ${e.provenance.fingerprintAtGeneration?`\`${e.provenance.fingerprintAtGeneration}\``:"_(none \u2014 detector has no fingerprint)_"}`),t.push(`- **Card occurrence count at generation:** ${e.provenance.cardOccurrenceCountAtGeneration}`),t.push(`- **Card lastSeen at generation:** ${e.provenance.cardLastSeenAtGeneration}`),t.push(`- **Generated by:** \`${e.provenance.generatedBy}\``),t.push(""),t.push("## Triage notes"),t.push(""),e.notes.length===0)t.push("_(none)_");else for(let n of e.notes)t.push(`- _${n.at}_ \u2014 ${n.text}`);return t.push(""),t.join(`
|
|
2228
2228
|
`)}function xS(){let e=yo();if(!uf(e))return[];let t=[];for(let n of qne(e)){if(!n.endsWith(".json")||n.startsWith(".")||n.endsWith(".fixture.jsonl"))continue;let r=_F(TF(e,n));r&&t.push({evalCaseId:r.evalCaseId,cardSlug:r.cardSlug,proposalId:r.proposalId,title:r.title,kind:r.kind,status:r.status,patternId:r.assertion.patternId,createdAt:r.createdAt,sliceSha256:r.replay.sliceSha256})}return t.sort((n,r)=>n.createdAt!==r.createdAt?n.createdAt<r.createdAt?1:-1:n.evalCaseId<r.evalCaseId?-1:1),t}function mf(e){return _F(hS(e))}function AF(e){return xS().filter(t=>t.cardSlug===e).map(t=>mf(t.evalCaseId)).filter(t=>t!==void 0)}function _F(e){if(uf(e))try{let t=EF(e,"utf-8"),n=JSON.parse(t),r=of.safeParse(n);return r.success?r.data:void 0}catch{return}}function Zne(e){let t=YL.parse(e),n=LL(),r=yo();uf(r)||kF(r,{recursive:!0});try{df(n,JSON.stringify(t)+`
|
|
2229
|
-
`,{flag:"a"})}catch{}}function Qne(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;df(n,JSON.stringify(t,null,2)),TS(n,e)}function ere(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;df(n,t),TS(n,e)}function tre(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;df(n,t),TS(n,e)}import{randomBytes as Sre}from"crypto";import{existsSync as PS,mkdirSync as HF,readFileSync as vre,readdirSync as
|
|
2229
|
+
`,{flag:"a"})}catch{}}function Qne(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;df(n,JSON.stringify(t,null,2)),TS(n,e)}function ere(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;df(n,t),TS(n,e)}function tre(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;df(n,t),TS(n,e)}import{randomBytes as Sre}from"crypto";import{existsSync as PS,mkdirSync as HF,readFileSync as vre,readdirSync as NGe,renameSync as WF,writeFileSync as MS}from"fs";import{join as kre}from"path";K();Fa();Uh();Ld();var IF=400;function Bt(e){let n=(typeof e=="string"?e:String(e)).replace(/\s+/g," ").trim();return n.length>IF?n.slice(0,IF-1)+"\u2026":n}function Se(e){return{name:e.name,description:e.description,status:e.status??(e.pass?"pass":"fail"),expected:Bt(e.expected),actual:Bt(e.actual)}}var dc="eval_run_probe_tool";async function nre(){let e=Hs,t=0,n=async()=>(t+=1,{content:"probe-ok"}),r=new It({handlers:new Map([[dc,n]]),schemas:[],hookRegistry:void 0,permissions:{allowedTools:[dc]}}),o=new AbortController().signal,s=h=>({id:"eval-run-probe",name:dc,input:h,signal:o}),i={probe:"byte-identical-input"},a=[];for(let h=0;h<e-1;h++)a.push(await r.execute(s(i)));let l=t,c=await r.execute(s(i)),u=t,d=await r.execute(s({probe:"a-different-input"})),p=a.every(h=>h.isError!==!0&&h.circuitBreaker!==!0),m=[Se({name:"executes-below-threshold",description:`First ${e-1} byte-identical calls execute without tripping`,pass:p&&l===e-1,expected:`${e-1} clean executions; handler runs ${e-1}\xD7`,actual:`${a.filter(h=>h.isError!==!0).length} clean; handler ran ${l}\xD7`}),Se({name:"trips-at-threshold",description:`Call #${e} is short-circuited with isError + circuitBreaker, handler skipped`,pass:c.isError===!0&&c.circuitBreaker===!0&&u===l,expected:"isError=true, circuitBreaker=true, handler not re-run",actual:`isError=${c.isError??!1}, circuitBreaker=${c.circuitBreaker??!1}, handler ran ${u}\xD7`}),Se({name:"breaker-message-is-actionable",description:"The synthetic block names the looping tool and reads as a stop nudge",pass:/circuit breaker/i.test(c.content)&&c.content.includes(dc),expected:`mentions "circuit breaker" and the tool name "${dc}"`,actual:c.content}),Se({name:"resets-on-different-input",description:"A different-input call after a trip resets the consecutive counter and executes",pass:d.isError!==!0&&d.circuitBreaker!==!0&&t===u+1,expected:"executes (no breaker), handler runs once more",actual:`isError=${d.isError??!1}, circuitBreaker=${d.circuitBreaker??!1}, handler ran ${t}\xD7`})],g=[{kind:"config-value",ref:"src/agent/tools/dispatcher.ts#REPEAT_CIRCUIT_BREAKER_THRESHOLD",detail:String(e)},{kind:"observed-behavior",ref:"SessionToolDispatcher.execute",detail:`handler ran ${u}\xD7 across ${e} byte-identical calls; call #${e} short-circuited (circuitBreaker=${c.circuitBreaker??!1})`}];return{checks:m,evidence:g}}async function rre(){let n=ud(3,3);return{checks:[Se({name:"refusal-states-depth",description:"Refusal reports the depth that was hit and the max",pass:n.includes("nesting depth 3 (max 3)"),expected:'mentions "nesting depth 3 (max 3)"',actual:n}),Se({name:"recovery-hint-present",description:"Refusal carries the recovery hint clause",pass:n.includes(si),expected:"contains SKILL_MAX_DEPTH_RECOVERY_HINT",actual:n}),Se({name:"hint-directs-inline-work",description:"Hint tells the model to work inline instead of delegating further",pass:/perform the work inline/i.test(si)&&/skill\/agent\/compose/i.test(si),expected:'hint mentions "perform the work inline" and "skill/agent/compose"',actual:si})],evidence:[{kind:"source-symbol",ref:"src/agent/tools/skill-depth-message.ts#buildSkillMaxDepthRefusal",detail:n},{kind:"source-symbol",ref:"src/agent/tools/skill-executor.ts (execute: depth >= maxDepth branch)",detail:"returns buildSkillMaxDepthRefusal(depth, maxDepth)"}]}}var ws="tool-failure-density",gn="flaky_tool",ha="refusal_only_tool",ya="tool-failure-flaky-tool",ore="tool-failure-refusal-only-tool";async function sre(){let e=qL(),t=ma(),n=[Se({name:"in-default-enabled-set",description:`${ws} runs in a default scan`,pass:e.includes(ws),expected:`defaultEnabledDetectorNames() includes "${ws}"`,actual:`[${e.join(", ")}]`}),Se({name:"not-opt-in",description:`${ws} is not in the disabled-by-default set`,pass:!t.includes(ws),expected:`disabledByDefaultDetectorNames() excludes "${ws}"`,actual:`[${t.join(", ")}]`})],r=[{kind:"config-value",ref:"DETECTOR_REGISTRY['tool-failure-density'].enabledByDefault",detail:String(e.includes(ws))}];return{checks:n,evidence:r}}function pt(e,t,n){let r={phase:"completed",toolUseId:`tu-${e}`,name:t,resultBytes:128,isError:n.isError,truncated:!1,durationMs:10};return n.circuitBreaker===!0&&(r.circuitBreaker=!0),n.failureClass!==void 0&&(r.failureClass=n.failureClass),JSON.stringify({ts:"2026-06-20T10:00:00.000Z",seq:e,kind:"tool_call",payload:r})}function RS(e,t){let n=`state/witness/${e}/trace.jsonl`;return da({sessionId:e,tracePath:n,relativeTracePath:n,content:t.join(`
|
|
2230
2230
|
`)+`
|
|
2231
2231
|
`,sessionMtimeMs:0})}function ire(){let e=RS("tfd-sess-a",[pt(0,gn,{isError:!1}),pt(1,gn,{isError:!0,failureClass:"timeout"}),pt(2,gn,{isError:!0}),pt(3,gn,{isError:!0,failureClass:"policy-refusal"}),pt(4,gn,{isError:!0,circuitBreaker:!0})]),t=RS("tfd-sess-b",[pt(0,gn,{isError:!0}),pt(1,gn,{isError:!1}),pt(2,gn,{isError:!0,failureClass:"permission-denied"}),pt(3,gn,{isError:!0,failureClass:"abort"}),pt(4,gn,{isError:!0,failureClass:"hook-block"}),pt(5,gn,{isError:!0,failureClass:"elicitation-declined"})]),n=RS("tfd-sess-c",[pt(0,ha,{isError:!1}),pt(1,ha,{isError:!0,failureClass:"policy-refusal"}),pt(2,ha,{isError:!0,failureClass:"policy-refusal"}),pt(3,ha,{isError:!0,failureClass:"permission-denied"}),pt(4,ha,{isError:!0,failureClass:"hook-block"}),pt(5,ha,{isError:!0,failureClass:"abort"})]);return[e,t,n]}function ff(e,t){let n=e[t];return typeof n=="number"?n:void 0}function CS(e){let t={};if(e===null||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="number"&&(t[n]=r);return t}function PF(e,t){let n=CS(e),r=Object.keys(n),o=Object.keys(t);if(r.length!==o.length)return!1;for(let s of o)if(n[s]!==t[s])return!1;return!0}function are(e){return Array.isArray(e)?e.filter(t=>typeof t=="number"):[]}function lre(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function cre(){let e=ire(),t=pa(e,{}),n=t.find(x=>x.slug===ya),r=t.find(x=>x.slug===ore),o=n?.detail??{},s=ff(o,"failureCount"),i=ff(o,"totalCalls"),a=ff(o,"failureRate"),l=ff(o,"affectedSessionCount"),c=CS(o.failureClassBreakdown),u=CS(o.excludedByClass),d=lre(o.sessionIds).slice().sort(),p=are(o.seqs),m=pa(e,{minFailures:4}),g=pa(e,{minFailureRate:.7}),h=!m.some(x=>x.slug===ya),b=!g.some(x=>x.slug===ya),y={"policy-refusal":1,"permission-denied":1,abort:1,"hook-block":1,"elicitation-declined":1},S={timeout:1,unclassified:2},w=[Se({name:"classification-fires-on-dual-threshold",description:"A tool clearing BOTH the failure-count and failure-rate floors yields exactly one card at the recorded magnitude",pass:t.length===1&&n!==void 0&&s===3&&i===5&&a===.6,expected:`1 card '${ya}' with failureCount=3, totalCalls=5, failureRate=0.6`,actual:n===void 0?`no '${ya}' card; ${t.length} card(s): [${t.map(x=>x.slug).join(", ")}]`:`${t.length} card(s); failureCount=${s}, totalCalls=${i}, failureRate=${a}`}),Se({name:"classification-excludes-system-said-no-classes",description:"policy-refusal / permission-denied / hook-block / abort / elicitation-declined are excluded from BOTH numerator and denominator and never manufacture a card alone",pass:PF(u,y)&&s===3&&i===5&&r===void 0,expected:"excludedByClass={policy-refusal:1,permission-denied:1,abort:1,hook-block:1,elicitation-declined:1}; counts not inflated; refusal-only tool yields NO card",actual:`excludedByClass=${JSON.stringify(u)}; failureCount=${s}, totalCalls=${i}; refusal_only_tool card ${r===void 0?"absent":"PRESENT"}`}),Se({name:"classification-excludes-circuit-breaker",description:"A circuitBreaker-synthesised completion is skipped before classification \u2014 it inflates neither totalCalls nor the unclassified count, and never lands in excludedByClass",pass:i===5&&c.unclassified===2&&u.circuitBreaker===void 0,expected:"totalCalls=5 (breaker not counted); unclassified=2 (breaker not folded in); no circuitBreaker key in excludedByClass",actual:`totalCalls=${i}; unclassified=${c.unclassified??0}; excludedByClass keys=[${Object.keys(u).join(", ")}]`}),Se({name:"classification-counts-timeout-and-unclassified",description:"timeout and unclassified (no failureClass) failures DO count toward the failure stats",pass:PF(c,S),expected:"failureClassBreakdown={timeout:1,unclassified:2}",actual:`failureClassBreakdown=${JSON.stringify(c)}`}),Se({name:"classification-respects-thresholds",description:"The card drops out when EITHER the count floor or the rate floor is raised above the recorded magnitude (dual AND threshold)",pass:h&&b,expected:"minFailures=4 \u2192 no card (count gate); minFailureRate=0.7 \u2192 no card (rate gate)",actual:`count gate ${h?"held":"LEAKED"}; rate gate ${b?"held":"LEAKED"}`}),Se({name:"classification-reports-affected-sessions-and-seqs",description:"The card reports the distinct affected sessions and per-failure seqs in deterministic order",pass:l===2&&JSON.stringify(d)===JSON.stringify(["tfd-sess-a","tfd-sess-b"])&&JSON.stringify(p)===JSON.stringify([1,2,0]),expected:"affectedSessionCount=2; sessionIds=[tfd-sess-a,tfd-sess-b]; seqs=[1,2,0]",actual:`affectedSessionCount=${l}; sessionIds=[${d.join(",")}]; seqs=[${p.join(",")}]`})],T=[{kind:"source-symbol",ref:"src/improve/scan/detectors/tool-failure-density.ts#detectToolFailureDensity",detail:n===void 0?`synthetic corpus \u2192 ${t.length} card(s); '${ya}' absent`:`synthetic corpus \u2192 flaky_tool ${s}/${i} (rate ${a}); breakdown ${JSON.stringify(c)}`},{kind:"observed-behavior",ref:"detectToolFailureDensity (EXCLUDED_FAILURE_CLASSES + circuitBreaker exclusion)",detail:`excludedByClass=${JSON.stringify(u)}; refusal_only_tool card ${r===void 0?"absent":"PRESENT"}`}];return{checks:w,evidence:T}}async function ure(){let e=await sre(),t=cre();return{checks:[...e.checks,...t.checks],evidence:[...e.evidence,...t.evidence]}}async function dre(){let e=Bo("abort"),t=Bo("model_end_turn"),n=[Se({name:"abort-closure-has-guidance",description:"An abort closure maps to a non-empty recovery hint",pass:typeof e=="string"&&e.trim().length>0,expected:"non-empty guidance string for reason=abort",actual:e===null?"null (no guidance)":Bt(e)}),Se({name:"guidance-names-a-recovery-action",description:"The abort hint names a concrete next action (resume / re-run)",pass:e!==null&&/\b(resume|re-run|rerun|retry)\b/i.test(e),expected:"hint mentions resume / re-run",actual:e===null?"null":Bt(e)}),Se({name:"guidance-is-the-canonical-constant",description:"The wired hint is the exported CLOSURE_ABORT_RECOVERY_HINT (no drift)",pass:e===Fy,expected:'buildClosureGuidance("abort") === CLOSURE_ABORT_RECOVERY_HINT',actual:e===null?"null":Bt(e)}),Se({name:"benign-closure-has-no-guidance",description:"A clean model_end_turn close carries no false-positive guidance",pass:t===null,expected:"null for reason=model_end_turn",actual:t===null?"null":Bt(t)})],r=[{kind:"source-symbol",ref:"src/agent/session/closure-guidance.ts#buildClosureGuidance",detail:e===null?"null":Bt(e)},{kind:"source-symbol",ref:"src/agent/session/agent-session.ts (emitClosure: attaches guidance to closure event)",detail:"buildClosureGuidance(reason) \u2192 closure payload .guidance"}];return{checks:n,evidence:r}}var AS=Object.freeze([{id:"repeat-loop-circuit-breaker",patternId:"repeated-tool-use",title:"Repeat-loop circuit breaker trips at the consecutive-identical threshold",run:nre},{id:"skill-max-depth-recovery-hint",patternId:"subagent-block",title:"Skill max-depth refusal carries an actionable recovery hint",run:rre},{id:"tool-failure-density-enabled",patternId:"tool-failure-density",title:"tool-failure-density detector is enabled by default and classifies a known failure mix correctly",run:ure},{id:"closure-abort-recovery-hint",patternId:"closure-anomaly",title:"Anomalous abort closure carries an actionable recovery hint",run:dre}]);function MF(e){return AS.find(t=>t.patternId===e)}function OF(){return AS.map(e=>e.patternId)}function $F(){return AS.map(e=>e.id)}Fa();Ld();var hf="replay:",DF=`${hf}fixture-reproduces-pattern`,BF=`${hf}guardrail-neutralizes-recorded-loop`,LF=`${hf}fixture-reproduces-closure-anomaly`,UF=`${hf}guardrail-guides-recorded-closure`,FF="The committed fixture still reproduces the recorded repeated-tool-use loop when re-scanned by the detector",pre=Object.freeze({replay:"byte-identical-input"}),mre=async(e,t)=>{let n=async()=>({content:"replay-probe-ok"}),r=new It({handlers:new Map([[e,n]]),schemas:[],hookRegistry:void 0,permissions:{allowedTools:[e]}}),o=new AbortController().signal,s=null,i=0;for(let a=1;a<=t;a++){let l={id:`replay-${a}`,name:e,input:pre,signal:o},c=await r.execute(l);if(i=a,c.circuitBreaker===!0){s=a;break}}return{trippedAtCall:s,callsDriven:i}};function gf(e){let t=e.detail.runLength;return typeof t=="number"?t:0}async function fre(e,t,n){let r=[],o=[],s=t.toString("utf8"),i=da({sessionId:e.replay.sourceSessionId,tracePath:e.replay.sourceTracePath,relativeTracePath:e.replay.sourceTracePath,content:s,sessionMtimeMs:0}),a=Zm([i],{minRepeats:Rr}),l=e.provenance.fingerprintAtGeneration,c=l?a.find(S=>S.detail.fingerprint===l):void 0,u=[...a].sort((S,w)=>gf(w)-gf(S))[0],d=c??u;if(d===void 0)return r.push(Se({name:DF,description:FF,pass:!1,status:"skipped",expected:l?`detector finds a run with fingerprint ${l.slice(0,12)}\u2026`:"detector finds \u22651 repeated-tool-use run in the fixture",actual:`detector found ${a.length} run(s); none matched \u2014 replay skipped (eval-case may be stale or misgenerated)`})),o.push({kind:"fixture",ref:e.replay.fixturePath,detail:"fixture did not reproduce the repeated-tool-use pattern; replay skipped (no loop to re-drive)"}),{checks:r,evidence:o};r.push(Se({name:DF,description:FF,pass:!0,expected:l?`detector finds a run with fingerprint ${l.slice(0,12)}\u2026`:"detector finds \u22651 repeated-tool-use run in the fixture",actual:`found '${String(d.detail.toolName)}' \xD7${gf(d)}`}));let p=String(d.detail.toolName),m=gf(d),g=n.driveLoop??mre,h=Math.min(m,Hs),b=await g(p,h),y=b.trippedAtCall!==null&&b.trippedAtCall<=m;return r.push(Se({name:BF,description:"Re-driving the recorded loop through the live guardrail trips the circuit breaker at or before the recorded length",pass:y,expected:`circuit breaker trips at call \u2264 ${m} (recorded run length)`,actual:b.trippedAtCall===null?`no trip within ${b.callsDriven} call(s) \u2014 recorded loop of ${m} would still complete`:`tripped at call ${b.trippedAtCall}`})),o.push({kind:"observed-behavior",ref:"SessionToolDispatcher.execute (repeat-loop circuit breaker)",detail:`'${p}' recorded \xD7${m}; live breaker ${b.trippedAtCall===null?"did NOT trip":`tripped at call ${b.trippedAtCall}`} (threshold ${Hs})`},{kind:"fixture",ref:e.replay.fixturePath,detail:`replayed recorded loop on '${p}' (run length ${m})`}),{checks:r,evidence:o}}function gre(e){let t=e.detail.closureReason;return typeof t=="string"?t:null}function hre(e){let t=e.detail.seqs;return Array.isArray(t)?t.filter(n=>typeof n=="number"):[]}var NF="The committed fixture still reproduces the recorded anomalous closure when re-scanned by the detector";async function yre(e,t,n){let r=[],o=[],s=t.toString("utf8"),i=da({sessionId:e.replay.sourceSessionId,tracePath:e.replay.sourceTracePath,relativeTracePath:e.replay.sourceTracePath,content:s,sessionMtimeMs:0}),a=Qm([i],{minOccurrences:1}),l=Math.max(...e.replay.evidenceEventIndices),u=a.find(h=>hre(h).includes(l))??a[0];if(u===void 0)return r.push(Se({name:LF,description:NF,pass:!1,status:"skipped",expected:"detector finds \u22651 anomalous closure in the fixture",actual:`detector found ${a.length} closure-anomaly finding(s); none matched \u2014 replay skipped (eval-case may be stale or misgenerated)`})),o.push({kind:"fixture",ref:e.replay.fixturePath,detail:"fixture did not reproduce an anomalous closure; replay skipped (no closure to re-drive)"}),{checks:r,evidence:o};let d=gre(u)??"";r.push(Se({name:LF,description:NF,pass:!0,expected:"detector finds \u22651 anomalous closure in the fixture",actual:`found closure.reason='${d}' (seq ${l})`}));let m=(n.buildGuidance??Bo)(d),g=m!==null&&m.trim().length>0;return r.push(Se({name:UF,description:"Re-driving the recorded closure reason through the live guardrail yields actionable recovery guidance",pass:g,expected:`buildClosureGuidance('${d}') returns a non-empty recovery hint`,actual:g?Bt(m):`no guidance for reason '${d}' \u2014 the recorded closure anomaly would still surface with no recovery path`})),o.push({kind:"observed-behavior",ref:"buildClosureGuidance (closure-anomaly recovery hint)",detail:`closure.reason='${d}'; live guardrail ${g?"returned a recovery hint":"returned no guidance"}`},{kind:"fixture",ref:e.replay.fixturePath,detail:`replayed recorded closure reason '${d}'`}),{checks:r,evidence:o}}var bre=Object.freeze([{patternId:"repeated-tool-use",run:fre},{patternId:"closure-anomaly",run:yre}]),wre=[BF,UF];function _S(e){return wre.includes(e)}function jF(e){return bre.find(t=>t.patternId===e)}var Ere="eval-run@v1";function KF(e,t={}){let n=(t.now??(()=>new Date))(),r=Tre(n),o=t.randomSuffix!==void 0?t.randomSuffix():Sre(3).toString("hex");if(!/^[0-9a-f]{6}$/.test(o))throw new Error(`generateEvalRunId: randomSuffix must be 6 lowercase hex chars (got '${o}')`);return`${e}-run-${r}-${o}`}function Tre(e){let t=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0"),r=String(e.getUTCDate()).padStart(2,"0");return`${t}${n}${r}`}async function GF(e,t){let r=(t.now??(()=>new Date))().toISOString(),o=t.clockMs??(()=>Date.now()),s=o(),i=[],a=[],l=[],c=Rre(e,t);i.push(c.check),c.evidence&&a.push(c.evidence);let u=MF(e.assertion.patternId),d=null,p=!1;if(!u)l.push({at:r,text:`No deterministic validation contract is registered for pattern '${e.assertion.patternId}'. Supported: ${OF().join(", ")}.`});else{d=u.id;try{let T=await u.run();i.push(...T.checks),a.push(...T.evidence)}catch(T){p=!0;let x=T instanceof Error?T.message:String(T);l.push({at:r,text:`Contract '${u.id}' threw during execution: ${Bt(x)}`})}}let m=jF(e.assertion.patternId),g=!1;if(m&&c.bytes!==void 0&&c.check.status==="pass")try{let T=await m.run(e,c.bytes,{...t.driveLoop?{driveLoop:t.driveLoop}:{}});i.push(...T.checks),a.push(...T.evidence),g=!0}catch(T){p=!0;let x=T instanceof Error?T.message:String(T);l.push({at:r,text:`Fixture-replay for '${e.assertion.patternId}' threw during execution: ${Bt(x)}`})}let h=i.some(T=>_S(T.name)),b=m!==void 0&&c.check.status==="pass"&&g&&!h,y=xre({hasContract:u!==void 0||g,contractThrew:p,checks:i,replayInconclusive:b}),S=Math.max(0,Math.round(o()-s)),w={schemaVersion:1,evalRunId:t.evalRunId,evalCaseId:e.evalCaseId,cardSlug:e.cardSlug,patternId:e.assertion.patternId,contract:d,status:y,createdAt:r,durationMs:S,checks:i,evidence:a,runner:{version:Ere,mode:"deterministic"},notes:l};return SS.parse(w),w}function xre(e){return e.contractThrew?"error":e.checks.some(t=>t.status==="fail")?"fail":!e.hasContract||e.replayInconclusive===!0?"unsupported":"pass"}function Rre(e,t){let r=(t.resolveFixtureAbsPath??(u=>kre(De(),u)))(e.replay.fixturePath),o=e.replay.sliceSha256,s="fixture-integrity",i="Committed replay fixture exists and matches the eval-case's recorded sha256";if(!PS(r))return{check:Se({name:s,description:i,pass:!1,expected:`fixture present at ${e.replay.fixturePath}`,actual:"fixture file not found on disk"})};let a;try{a=vre(r)}catch(u){let d=u instanceof Error?u.message:String(u);return{check:Se({name:s,description:i,pass:!1,expected:`readable fixture (${o})`,actual:`read error: ${Bt(d)}`})}}let l=cf(a),c=l===o;return{check:Se({name:s,description:i,pass:c,expected:o,actual:l}),evidence:{kind:"fixture",ref:e.replay.fixturePath,detail:`sha256 ${c?"match":"MISMATCH"} (${e.replay.sliceLineCount} lines)`},bytes:a}}function qF(e){let t=SS.parse(e),n=ua();PS(n)||HF(n,{recursive:!0});let r=BL(t.evalRunId),o=UL(t.evalRunId);return Ire(r,t),Pre(o,OS(t)),_re({timestamp:new Date().toISOString(),event:"created",evalRunId:t.evalRunId,evalCaseId:t.evalCaseId,cardSlug:t.cardSlug,patternId:t.patternId,contract:t.contract,status:t.status}),{evalRunId:t.evalRunId,jsonPath:r,markdownPath:o}}var Cre={pass:"\u2713 PASS",fail:"\u2717 FAIL",unsupported:"\u2013 UNSUPPORTED",error:"\u26A0 ERROR"},Are={pass:"\u2713",fail:"\u2717",skipped:"\u2013"};function OS(e){let t=e.checks.filter(i=>i.status==="pass").length,n=e.checks.filter(i=>i.status==="fail").length,r=e.checks.filter(i=>i.status==="skipped").length,o=[];if(o.push(`# ${e.evalRunId} \u2014 \`eval-run\` \u2014 \`${e.status}\``),o.push(""),o.push(`Deterministic guardrail validation of eval-case \`${e.evalCaseId}\`.`),o.push(""),o.push(`**Eval-case:** \`${e.evalCaseId}\` \xB7 **Card:** \`${e.cardSlug}\` \xB7 **Pattern:** \`${e.patternId}\` \xB7 **Contract:** ${e.contract?`\`${e.contract}\``:"_(none)_"} \xB7 **Created:** ${e.createdAt} \xB7 **Duration:** ${e.durationMs}ms`),o.push(""),e.checks.some(i=>_S(i.name))?(o.push("> **What this is.** A deterministic validation of pattern"),o.push(`> \`${e.patternId}\`. It re-drove the failure recorded in the committed`),o.push("> fixture through the LIVE guardrail and asserts the recorded failure is"),o.push("> neutralised at the recorded magnitude \u2014 proving the behaviour is fixed,"),o.push("> not merely that a guardrail exists. It re-drives the recorded failure"),o.push("> conditions; it does NOT re-execute the original tool/LLM.")):(o.push("> **What this is.** A narrow, deterministic check that the guardrail"),o.push(`> mapped to pattern \`${e.patternId}\` is present and behaving. It`),o.push("> validates the guardrail the pattern maps to; the eval-case's own"),o.push("> `pattern-absent` assertion remains the full contract.")),o.push(""),o.push(`## Result: ${Cre[e.status]} (${t}/${e.checks.length} checks passed${n?`, ${n} failed`:""}${r?`, ${r} skipped`:""})`),o.push(""),o.push("## Checks"),o.push(""),e.checks.length===0)o.push("_(none)_");else{o.push("| Check | Status | Expected | Actual |"),o.push("|---|---|---|---|");for(let i of e.checks)o.push(`| ${IS(i.name)} | ${Are[i.status]} ${i.status} | ${IS(i.expected)} | ${IS(i.actual)} |`)}if(o.push(""),o.push("## Evidence"),o.push(""),e.evidence.length===0)o.push("_(none)_");else for(let i of e.evidence)o.push(`- **[${i.kind}]** \`${i.ref}\` \u2014 ${i.detail}`);if(o.push(""),o.push("## Runner"),o.push(""),o.push(`- **Version:** \`${e.runner.version}\` \xB7 **Mode:** \`${e.runner.mode}\``),o.push(""),o.push("## Notes"),o.push(""),e.notes.length===0)o.push("_(none)_");else for(let i of e.notes)o.push(`- _${i.at}_ \u2014 ${i.text}`);return o.push(""),o.join(`
|
|
2232
2232
|
`)}function IS(e){return e.replace(/\|/g,"\\|").replace(/\n/g," ")}function _re(e){let t=ZL.parse(e),n=ua();PS(n)||HF(n,{recursive:!0});try{MS(NL(),JSON.stringify(t)+`
|
|
@@ -2270,9 +2270,9 @@ Safe to run repeatedly \u2014 replaces the index atomically.`).action(async()=>{
|
|
|
2270
2270
|
${i.snippet}
|
|
2271
2271
|
|
|
2272
2272
|
`)}process.stdout.write(`${s.results.length} result${s.results.length===1?"":"s"} (use FTS5 syntax for advanced queries: "exact phrase", term*, AND, OR)
|
|
2273
|
-
`)}catch(o){G(o)}})}Ot();rt();Je();Je();import{realpathSync as ooe}from"fs";jS();jS({path:yt(),override:!1});process.argv.includes("shell-init")||sv();process.env.AFK_FRAMEWORK_DIR??=yn();process.env.AGENT_SURFACE??="afk";lv();var
|
|
2273
|
+
`)}catch(o){G(o)}})}Ot();rt();Je();Je();import{realpathSync as ooe}from"fs";jS();jS({path:yt(),override:!1});process.argv.includes("shell-init")||sv();process.env.AFK_FRAMEWORK_DIR??=yn();process.env.AGENT_SURFACE??="afk";lv();var be=new eoe;be.name("afk").description("AI agent CLI. Starts interactive REPL by default; use `afk chat` for one-shot.").version(xr()).option("--no-update-check","Skip update version check");xI(be);K$(be);fD(be);gD(be);U$(be);bD(be);vD(be);ED(be);j$(be);xD(be);RD(be);CD(be);AD(be);ND(be);QD(be);nL(be);rL(be);oL(be);lL(be);pL(be);RL(be);PL(be);zF(be);Qk(be);YF(be);be.commands.find(e=>e.name()==="chat")?.alias("c");be.commands.find(e=>e.name()==="interactive")?.alias("i");be.commands.find(e=>e.name()==="status")?.alias("s");be.addHelpText("after",`
|
|
2274
2274
|
Examples:
|
|
2275
2275
|
$ afk # start interactive REPL
|
|
2276
2276
|
$ afk --model opus # REPL with specific model
|
|
2277
2277
|
$ afk chat "What is 2+2?" # one-shot message
|
|
2278
|
-
$ afk status --format json`);var toe=new Set(["chat","c","interactive","i","daemon","farm"]);function noe(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:toe.has(r)}async function roe(e=process.argv){if(!noe(e))return;let t=Hg(),n=re(
|
|
2278
|
+
$ afk status --format json`);var toe=new Set(["chat","c","interactive","i","daemon","farm"]);function noe(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:toe.has(r)}async function roe(e=process.argv){if(!noe(e))return;let t=Hg(),n=re(Et());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 Bm(),jS({path:yt(),override:!0})}catch{}}}var XF=process.argv[1]??"",soe=import.meta.url===`file://${XF}`||import.meta.url===`file://${ooe(XF)}`;soe&&(async()=>{await roe();let e=_t(),n=process.argv.slice(2).some(a=>a==="--no-update-check")?"off":e.updatePolicy,r=D$(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),L$(),process.stderr.write=s,B$(r,o),process.argv.length<=2||process.argv[2]==="interactive"||process.argv[2]==="i"?r&&n==="auto"&&Bw(r.latestVersion):(o!==null&&process.stderr.write(o),r&&($m(r),n==="auto"&&Bw(r.latestVersion))),be.parseAsync(process.argv).catch(a=>{console.error(a),process.exitCode=1})})();export{ly as getMaxBudgetUsd,ul as getMaxOutputTokens,cy as getTaskBudget,noe as needsCredentialGate,fi as parseBudget,Xr as parseEffort,gi as parseMaxOutputTokens,Yr as parseThinking,roe as runFirstRunDetector};
|