agent-afk 5.13.1 → 5.14.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/cli.mjs +68 -68
- package/dist/index.mjs +1 -1
- package/dist/telegram.mjs +1 -1
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var ZN=Object.defineProperty;var P=(e,t)=>()=>(e&&(t=e(e=0)),t);var Rc=(e,t)=>{for(var n in t)ZN(e,n,{get:t[n],enumerable:!0})};function Cc(e){return va.find(t=>t.name===e)}function Tv(e){return va.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function Wf(e){return process.env[e]!==void 0}var va,v,J=P(()=>{"use strict";va=[{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_BROWSER_DEFAULT_PROFILE",description:"Name of the persistent session-vault profile the agent reuses for browser sessions. The context restores its login from (and saves it back to) ~/.afk/state/browser/<profile>/storageState.json, so a human runs `afk browser login --profile <name>` once and the agent reuses that authenticated session across unattended runs. Unset defaults to `default` (a fresh, empty profile \u2014 identical to pre-vault behavior). Allowed charset: [A-Za-z0-9_-], max 128 chars.",type:"string",required:!1,example:"work",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],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_BROWSER_DEFAULT_PROFILE(){return process.env.AFK_BROWSER_DEFAULT_PROFILE},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let t of va){if(!t.secret)continue;let n=Object.getOwnPropertyDescriptor(v,t.name);n&&Object.defineProperty(v,t.name,{...n,enumerable:!1})}})()});import{existsSync as xv,mkdirSync as QN,renameSync as eB,cpSync as tB,rmSync as nB}from"fs";import{join as Q,dirname as Av,isAbsolute as _v}from"path";import{homedir as Kf}from"os";import{fileURLToPath as rB}from"url";function Fe(){let e=v.AFK_HOME;if(e!==void 0&&e!==""){if(!_v(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return Q(Kf(),".afk")}function Mt(){return Q(Fe(),"agent-framework")}function _r(){return Q(Mt(),"forge-telemetry.jsonl")}function Ts(){return Q(Mt(),"briefs")}function Pv(){return Q(Mt(),"facets")}function ka(){return Q(Fe(),"skills")}function Ze(){return Q(Fe(),"plugins")}function Iv(){return Q(process.cwd(),".afk")}function Ac(){return Q(Iv(),"skills")}function _c(){return Q(Iv(),"plugins")}function Pc(e=process.cwd()){return Q(e,".afk","plans")}function ue(){return Q(Ze(),".index.json")}function Gf(){return Q(rn(),"schedules.json")}function Vn(){return Q(Ze(),"cache")}function Ea(e){return Q(Vn(),e)}function xs(){let e=rB(import.meta.url),t=Av(e);return Q(t,"bundled-plugins")}function rn(){return Q(Fe(),"config")}function Te(){let e=v.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!_v(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return Q(Fe(),"state")}function Ic(){return Q(Fe(),"cache")}function Rs(){return Q(Fe(),"logs")}function wt(){return Q(Te(),"sessions")}function Mc(){return Q(Te(),"presence")}function qf(){return Q(Te(),"todos")}function Ta(){return Q(Te(),"transcripts")}function Oc(){return Q(Te(),"memory")}function gt(){return Q(Te(),"queue")}function Cs(){return Q(Te(),"session-grants.jsonl")}function xa(){return Q(rn(),"permissions.json")}function Mv(){return Q(Fe(),"farms")}function zf(e){return Q(Mv(),e)}function $c(e){if(!oB.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function As(e){return $c(e),Q(Te(),"witness",e)}function Jf(){return Q(Te(),"receipts")}function Dc(e="default"){return Q(Te(),"daemon",`agent-afk@${e}`)}function Ov(){return Q(Te(),"worktree-sweep.lock")}function St(){return Q(rn(),"afk.env")}function Kt(){return Q(rn(),"afk.config.json")}function $v(){return Q(rn(),"settings.json")}function Dv(e=process.cwd()){return Q(e,".afk","settings.json")}function Fv(){return Q(Kf(),".afk.env")}function Fc(){return Q(Kf(),".afk.config.json")}function sB(){return Q(Fe(),"sessions")}function iB(){return Q(Fe(),"todos")}function aB(){return Q(Fe(),"transcripts")}function Vf(e,t){if(e!==t&&xv(e)&&!xv(t))try{QN(Av(t),{recursive:!0});try{eB(e,t)}catch(n){if(n.code==="EXDEV")try{tB(e,t,{recursive:!0}),nB(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
|
|
3
|
-
`)}}}catch{}}function Lv(){Vf(sB(),wt())}function Nv(){Vf(iB(),qf())}function Bv(){Vf(aB(),Ta())}function Yf(){return Q(Te(),"repl-history.jsonl")}function cB(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(e.length>Rv)throw new Error(`Invalid jobId: exceeds ${Rv} chars`);if(!lB.test(e))throw new Error(`Invalid jobId: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function Ra(){return Q(Te(),"bg")}function vo(e){return cB(e),Q(Ra(),e)}function Lc(e){return Q(vo(e),"events.jsonl")}function Xf(e){return Q(vo(e),"meta.json")}function Ca(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(e.length>Cv)throw new Error(`Invalid browser profile: exceeds ${Cv} chars`);if(!uB.test(e))throw new Error(`Invalid browser profile: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function Zf(){return Q(Te(),"browser")}function Qf(e){return Ca(e),Q(Zf(),e)}function Aa(e){return Q(Qf(e),"storageState.json")}function Nc(e){return typeof e=="string"&&e.length>0&&e.length<=pB&&dB.test(e)}function _a(e){if(!Nc(e))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(e)}`);return Q(wt(),e)}function eg(e){return Q(_a(e),"events.jsonl")}function tg(e){return Q(_a(e),"session.key")}function Pa(){return Q(Te(),"mcp","server-status.json")}var oB,lB,Rv,uB,Cv,dB,pB,K=P(()=>{"use strict";J();oB=/^[a-zA-Z0-9_-]+$/;lB=/^[A-Za-z0-9_-]+$/,Rv=128;uB=/^[A-Za-z0-9_-]+$/,Cv=128;dB=/^[A-Za-z0-9_-]+$/,pB=128});import{randomBytes as mB}from"node:crypto";import{mkdirSync as fB,renameSync as gB,rmSync as Uv,writeFileSync as hB}from"node:fs";import{dirname as yB,isAbsolute as bB,join as wB}from"node:path";function Bc(){return wB(Te(),"last-cwd")}function jv(){try{Uv(Bc(),{force:!0})}catch{}}function Hv(e){if(!bB(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=Bc();fB(yB(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${mB(6).toString("hex")}`;try{hB(n,e,{encoding:"utf8",mode:384}),gB(n,t)}catch(r){try{Uv(n,{force:!0})}catch{}throw r}}catch{}}function Wv(){let e=v.AFK_SHELL_WRAPPER;return e==="1"||e==="true"}var Uc=P(()=>{"use strict";J();K()});var ut,Gt,me,Pr,jc,vt=P(()=>{"use strict";ut=class extends Error{constructor(t){super(t),this.name="AbortError"}},Gt=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},me=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},Pr=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},jc=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 qe(){return v.AFK_DEBUG==="1"||v.DEBUG==="1"}function W(...e){qe()&&console.log(...e)}var Pe=P(()=>{"use strict";J()});async function $s(e,t){if(e)try{await e.write({kind:"tool_call",payload:t})}catch(n){W(`trace.emit tool_call failed: ${Sn(n)}`)}}async function on(e,t){if(e)try{await e.write({kind:"hook_decision",payload:t})}catch(n){W(`trace.emit hook_decision failed: ${Sn(n)}`)}}async function To(e,t){if(e)try{await e.write({kind:"subagent_lifecycle",payload:t})}catch(n){W(`trace.emit subagent_lifecycle failed: ${Sn(n)}`)}}async function Ds(e,t){if(e)try{await e.write({kind:"background_agent",payload:t})}catch(n){W(`trace.emit background_agent failed: ${Sn(n)}`)}}async function mk(e,t){if(e)try{await e.write({kind:"budget",payload:t})}catch(n){W(`trace.emit budget failed: ${Sn(n)}`)}}async function fk(e,t){if(e)try{await e.write({kind:"abort",payload:t})}catch(n){W(`trace.emit abort failed: ${Sn(n)}`)}}async function gk(e,t){if(e)try{await e.write({kind:"compaction",payload:t})}catch(n){W(`trace.emit compaction failed: ${Sn(n)}`)}}async function hk(e,t){if(e)try{await e.write({kind:"closure",payload:t})}catch(n){W(`trace.emit closure failed: ${Sn(n)}`)}}async function st(e,t){if(e)try{await e.write({kind:"browser_event",payload:t})}catch(n){W(`trace.emit browser_event failed: ${Sn(n)}`)}}async function Le(e,t){if(e)try{await e.write({kind:"session_phase",payload:t})}catch(n){W(`trace.emit session_phase failed: ${Sn(n)}`)}}function Sn(e){return e instanceof Error?e.message:String(e)}var He=P(()=>{"use strict";Pe()});function Vc(e){return e.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function $a(e,t,n){let r=t==="oauth"?{authToken:e}:{apiKey:e};return typeof n=="string"&&n.length>0?{...r,baseURL:n}:r}function vn(e,t,n,r){return e!=="oauth"?{}:{"anthropic-beta":r?`${yk},${tU}`:yk,"x-app":"cli","User-Agent":nU,"X-Claude-Code-Session-Id":t,"x-client-request-id":n}}function bk(e){return e!=="oauth"?null:[{type:"text",text:rU}]}var yk,tU,nU,rU,Fs=P(()=>{"use strict";yk="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",tU="effort-2025-11-24",nU="claude-cli/1.0.0 (external, cli)",rU="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;"});function Zc(e){fg=e}function mg(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}function Yc(e,t,n){let r={},o=mg(e);o&&(r.id=o);let s=mg(t);s&&(r.baseUrl=s);let i=mg(n);return i&&(r.apiKey=i),r}function aU(){return{local:Yc(v.AFK_MODEL_LOCAL,v.AFK_MODEL_LOCAL_BASE_URL,v.AFK_MODEL_LOCAL_API_KEY),small:Yc(v.AFK_MODEL_SMALL,v.AFK_MODEL_SMALL_BASE_URL,v.AFK_MODEL_SMALL_API_KEY),medium:Yc(v.AFK_MODEL_MEDIUM,v.AFK_MODEL_MEDIUM_BASE_URL,v.AFK_MODEL_MEDIUM_API_KEY),large:Yc(v.AFK_MODEL_LARGE,v.AFK_MODEL_LARGE_BASE_URL,v.AFK_MODEL_LARGE_API_KEY)}}function yg(e){let t=aU(),n={};for(let r of gg){let o=xo[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 Ls(e){return e||fg||yg()}function Ns(e,t=Ls()){let n=e.trim().toLowerCase();if(!n||n===sU)return;for(let o of gg){let s=t[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:oU[n]}function bg(e,t=Ls()){if(e===void 0)return{id:""};let n=Ns(e,t);if(n)return t[n];let r=iU[e.trim().toLowerCase()];return r?{id:r}:{id:e}}function Ro(e,t=Ls()){if(e!==void 0)return bg(e,t).id}function Bs(e,t=Ls()){if(e===void 0)return;let n=Ns(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 wk(e){let t={};if(!e||typeof e!="object")return t;let n=e;for(let r of gg){let o=cU(n[r]);o&&(t[r]=o)}return t}function lU(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 Xc(e){return typeof e=="string"?e.trim():""}function cU(e){if(typeof e=="string"){let t=e.trim();return t?{id:t}:void 0}if(e&&typeof e=="object"){let t=e,n=Xc(t.id);if(!n)return;let r={id:n},o=Xc(t.name);o&&(r.name=o);let s=lU(t.provider);s&&(r.provider=s);let i=Xc(t.baseUrl);i&&(r.baseUrl=i);let a=Xc(t.apiKey);return a&&(r.apiKey=a),r}}var gg,xo,oU,sU,hg,iU,fg,sn=P(()=>{"use strict";J();gg=["local","small","medium","large"],xo={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-4-6"},large:{id:"claude-opus-4-8"}},oU={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},sU="auto",hg="claude-fable-5",iU={fable:hg}});function Sg(e){return e in wg}function kt(e){return Ro(e)}var wg,Zn=P(()=>{"use strict";sn();wg={opus:xo.large.id,opus_1m:xo.large.id,sonnet:xo.medium.id,sonnet_1m:xo.medium.id,haiku:xo.small.id,fable:hg}});import uU from"@anthropic-ai/sdk";import{randomUUID as Sk}from"node:crypto";async function Us(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=Vc(t),c=$a(t,l),u=a?a(c):new uU(c),d=Sk(),p=Sk(),m=vn(l,d,p),g=kt(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 Qc=P(()=>{"use strict";Fs();Zn()});import{execFileSync as vk}from"child_process";import{existsSync as dU,readFileSync as pU,writeFileSync as mU}from"fs";import{homedir as kk,userInfo as Ek}from"os";import{join as Tk}from"path";function Et(){let e=xk();if(e===void 0)return;let t=Rk(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 vg(){let e=xk();if(e===void 0)return;let t=Rk(e);if(t===void 0)return;if(t.expiresAt!==void 0&&t.expiresAt>Date.now()+hU)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 yU(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}:{}},bU(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
2
|
+
var ZN=Object.defineProperty;var P=(e,t)=>()=>(e&&(t=e(e=0)),t);var Rc=(e,t)=>{for(var n in t)ZN(e,n,{get:t[n],enumerable:!0})};function Cc(e){return va.find(t=>t.name===e)}function Tv(e){return va.filter(t=>!t.required||e!==void 0&&t.category!==e?!1:process.env[t.name]===void 0||process.env[t.name]==="")}function Wf(e){return process.env[e]!==void 0}var va,v,J=P(()=>{"use strict";va=[{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_BROWSER_DEFAULT_PROFILE",description:"Name of the persistent session-vault profile the agent reuses for browser sessions. The context restores its login from (and saves it back to) ~/.afk/state/browser/<profile>/storageState.json, so a human runs `afk browser login --profile <name>` once and the agent reuses that authenticated session across unattended runs. Unset defaults to `default` (a fresh, empty profile \u2014 identical to pre-vault behavior). Allowed charset: [A-Za-z0-9_-], max 128 chars.",type:"string",required:!1,example:"work",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],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_BROWSER_DEFAULT_PROFILE(){return process.env.AFK_BROWSER_DEFAULT_PROFILE},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let t of va){if(!t.secret)continue;let n=Object.getOwnPropertyDescriptor(v,t.name);n&&Object.defineProperty(v,t.name,{...n,enumerable:!1})}})()});import{existsSync as xv,mkdirSync as QN,renameSync as eB,cpSync as tB,rmSync as nB}from"fs";import{join as Q,dirname as Av,isAbsolute as _v}from"path";import{homedir as Kf}from"os";import{fileURLToPath as rB}from"url";function Le(){let e=v.AFK_HOME;if(e!==void 0&&e!==""){if(!_v(e)||e==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${e}`);return e}return Q(Kf(),".afk")}function Mt(){return Q(Le(),"agent-framework")}function _r(){return Q(Mt(),"forge-telemetry.jsonl")}function Ts(){return Q(Mt(),"briefs")}function Pv(){return Q(Mt(),"facets")}function ka(){return Q(Le(),"skills")}function Ze(){return Q(Le(),"plugins")}function Iv(){return Q(process.cwd(),".afk")}function Ac(){return Q(Iv(),"skills")}function _c(){return Q(Iv(),"plugins")}function Pc(e=process.cwd()){return Q(e,".afk","plans")}function ue(){return Q(Ze(),".index.json")}function Gf(){return Q(rn(),"schedules.json")}function Vn(){return Q(Ze(),"cache")}function Ea(e){return Q(Vn(),e)}function xs(){let e=rB(import.meta.url),t=Av(e);return Q(t,"bundled-plugins")}function rn(){return Q(Le(),"config")}function Te(){let e=v.AFK_STATE_DIR;if(e!==void 0&&e!==""){if(!_v(e)||e==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${e}`);return e}return Q(Le(),"state")}function Ic(){return Q(Le(),"cache")}function Rs(){return Q(Le(),"logs")}function wt(){return Q(Te(),"sessions")}function Mc(){return Q(Te(),"presence")}function qf(){return Q(Te(),"todos")}function Ta(){return Q(Te(),"transcripts")}function Oc(){return Q(Te(),"memory")}function gt(){return Q(Te(),"queue")}function Cs(){return Q(Te(),"session-grants.jsonl")}function xa(){return Q(rn(),"permissions.json")}function Mv(){return Q(Le(),"farms")}function zf(e){return Q(Mv(),e)}function $c(e){if(!oB.test(e))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(e)}`)}function As(e){return $c(e),Q(Te(),"witness",e)}function Jf(){return Q(Te(),"receipts")}function Dc(e="default"){return Q(Te(),"daemon",`agent-afk@${e}`)}function Ov(){return Q(Te(),"worktree-sweep.lock")}function St(){return Q(rn(),"afk.env")}function Kt(){return Q(rn(),"afk.config.json")}function $v(){return Q(rn(),"settings.json")}function Dv(e=process.cwd()){return Q(e,".afk","settings.json")}function Fv(){return Q(Kf(),".afk.env")}function Fc(){return Q(Kf(),".afk.config.json")}function sB(){return Q(Le(),"sessions")}function iB(){return Q(Le(),"todos")}function aB(){return Q(Le(),"transcripts")}function Vf(e,t){if(e!==t&&xv(e)&&!xv(t))try{QN(Av(t),{recursive:!0});try{eB(e,t)}catch(n){if(n.code==="EXDEV")try{tB(e,t,{recursive:!0}),nB(e,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${e} \u2192 ${t}: ${String(r)}
|
|
3
|
+
`)}}}catch{}}function Lv(){Vf(sB(),wt())}function Nv(){Vf(iB(),qf())}function Bv(){Vf(aB(),Ta())}function Yf(){return Q(Te(),"repl-history.jsonl")}function cB(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(e.length>Rv)throw new Error(`Invalid jobId: exceeds ${Rv} chars`);if(!lB.test(e))throw new Error(`Invalid jobId: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function Ra(){return Q(Te(),"bg")}function vo(e){return cB(e),Q(Ra(),e)}function Lc(e){return Q(vo(e),"events.jsonl")}function Xf(e){return Q(vo(e),"meta.json")}function Ca(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(e.length>Cv)throw new Error(`Invalid browser profile: exceeds ${Cv} chars`);if(!uB.test(e))throw new Error(`Invalid browser profile: ${JSON.stringify(e)} contains characters outside [A-Za-z0-9_-]`)}function Zf(){return Q(Te(),"browser")}function Qf(e){return Ca(e),Q(Zf(),e)}function Aa(e){return Q(Qf(e),"storageState.json")}function Nc(e){return typeof e=="string"&&e.length>0&&e.length<=pB&&dB.test(e)}function _a(e){if(!Nc(e))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(e)}`);return Q(wt(),e)}function eg(e){return Q(_a(e),"events.jsonl")}function tg(e){return Q(_a(e),"session.key")}function Pa(){return Q(Te(),"mcp","server-status.json")}var oB,lB,Rv,uB,Cv,dB,pB,K=P(()=>{"use strict";J();oB=/^[a-zA-Z0-9_-]+$/;lB=/^[A-Za-z0-9_-]+$/,Rv=128;uB=/^[A-Za-z0-9_-]+$/,Cv=128;dB=/^[A-Za-z0-9_-]+$/,pB=128});import{randomBytes as mB}from"node:crypto";import{mkdirSync as fB,renameSync as gB,rmSync as Uv,writeFileSync as hB}from"node:fs";import{dirname as yB,isAbsolute as bB,join as wB}from"node:path";function Bc(){return wB(Te(),"last-cwd")}function jv(){try{Uv(Bc(),{force:!0})}catch{}}function Hv(e){if(!bB(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=Bc();fB(yB(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${mB(6).toString("hex")}`;try{hB(n,e,{encoding:"utf8",mode:384}),gB(n,t)}catch(r){try{Uv(n,{force:!0})}catch{}throw r}}catch{}}function Wv(){let e=v.AFK_SHELL_WRAPPER;return e==="1"||e==="true"}var Uc=P(()=>{"use strict";J();K()});var ut,Gt,me,Pr,jc,vt=P(()=>{"use strict";ut=class extends Error{constructor(t){super(t),this.name="AbortError"}},Gt=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},me=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},Pr=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},jc=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 qe(){return v.AFK_DEBUG==="1"||v.DEBUG==="1"}function W(...e){qe()&&console.log(...e)}var Pe=P(()=>{"use strict";J()});async function $s(e,t){if(e)try{await e.write({kind:"tool_call",payload:t})}catch(n){W(`trace.emit tool_call failed: ${Sn(n)}`)}}async function on(e,t){if(e)try{await e.write({kind:"hook_decision",payload:t})}catch(n){W(`trace.emit hook_decision failed: ${Sn(n)}`)}}async function To(e,t){if(e)try{await e.write({kind:"subagent_lifecycle",payload:t})}catch(n){W(`trace.emit subagent_lifecycle failed: ${Sn(n)}`)}}async function Ds(e,t){if(e)try{await e.write({kind:"background_agent",payload:t})}catch(n){W(`trace.emit background_agent failed: ${Sn(n)}`)}}async function mk(e,t){if(e)try{await e.write({kind:"budget",payload:t})}catch(n){W(`trace.emit budget failed: ${Sn(n)}`)}}async function fk(e,t){if(e)try{await e.write({kind:"abort",payload:t})}catch(n){W(`trace.emit abort failed: ${Sn(n)}`)}}async function gk(e,t){if(e)try{await e.write({kind:"compaction",payload:t})}catch(n){W(`trace.emit compaction failed: ${Sn(n)}`)}}async function hk(e,t){if(e)try{await e.write({kind:"closure",payload:t})}catch(n){W(`trace.emit closure failed: ${Sn(n)}`)}}async function st(e,t){if(e)try{await e.write({kind:"browser_event",payload:t})}catch(n){W(`trace.emit browser_event failed: ${Sn(n)}`)}}async function Oe(e,t){if(e)try{await e.write({kind:"session_phase",payload:t})}catch(n){W(`trace.emit session_phase failed: ${Sn(n)}`)}}function Sn(e){return e instanceof Error?e.message:String(e)}var Ne=P(()=>{"use strict";Pe()});function Vc(e){return e.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function $a(e,t,n){let r=t==="oauth"?{authToken:e}:{apiKey:e};return typeof n=="string"&&n.length>0?{...r,baseURL:n}:r}function vn(e,t,n,r){return e!=="oauth"?{}:{"anthropic-beta":r?`${yk},${tU}`:yk,"x-app":"cli","User-Agent":nU,"X-Claude-Code-Session-Id":t,"x-client-request-id":n}}function bk(e){return e!=="oauth"?null:[{type:"text",text:rU}]}var yk,tU,nU,rU,Fs=P(()=>{"use strict";yk="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",tU="effort-2025-11-24",nU="claude-cli/1.0.0 (external, cli)",rU="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;"});function Zc(e){fg=e}function mg(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}function Yc(e,t,n){let r={},o=mg(e);o&&(r.id=o);let s=mg(t);s&&(r.baseUrl=s);let i=mg(n);return i&&(r.apiKey=i),r}function aU(){return{local:Yc(v.AFK_MODEL_LOCAL,v.AFK_MODEL_LOCAL_BASE_URL,v.AFK_MODEL_LOCAL_API_KEY),small:Yc(v.AFK_MODEL_SMALL,v.AFK_MODEL_SMALL_BASE_URL,v.AFK_MODEL_SMALL_API_KEY),medium:Yc(v.AFK_MODEL_MEDIUM,v.AFK_MODEL_MEDIUM_BASE_URL,v.AFK_MODEL_MEDIUM_API_KEY),large:Yc(v.AFK_MODEL_LARGE,v.AFK_MODEL_LARGE_BASE_URL,v.AFK_MODEL_LARGE_API_KEY)}}function yg(e){let t=aU(),n={};for(let r of gg){let o=xo[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 Ls(e){return e||fg||yg()}function Ns(e,t=Ls()){let n=e.trim().toLowerCase();if(!n||n===sU)return;for(let o of gg){let s=t[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:oU[n]}function bg(e,t=Ls()){if(e===void 0)return{id:""};let n=Ns(e,t);if(n)return t[n];let r=iU[e.trim().toLowerCase()];return r?{id:r}:{id:e}}function Ro(e,t=Ls()){if(e!==void 0)return bg(e,t).id}function Bs(e,t=Ls()){if(e===void 0)return;let n=Ns(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 wk(e){let t={};if(!e||typeof e!="object")return t;let n=e;for(let r of gg){let o=cU(n[r]);o&&(t[r]=o)}return t}function lU(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 Xc(e){return typeof e=="string"?e.trim():""}function cU(e){if(typeof e=="string"){let t=e.trim();return t?{id:t}:void 0}if(e&&typeof e=="object"){let t=e,n=Xc(t.id);if(!n)return;let r={id:n},o=Xc(t.name);o&&(r.name=o);let s=lU(t.provider);s&&(r.provider=s);let i=Xc(t.baseUrl);i&&(r.baseUrl=i);let a=Xc(t.apiKey);return a&&(r.apiKey=a),r}}var gg,xo,oU,sU,hg,iU,fg,sn=P(()=>{"use strict";J();gg=["local","small","medium","large"],xo={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-4-6"},large:{id:"claude-opus-4-8"}},oU={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},sU="auto",hg="claude-fable-5",iU={fable:hg}});function Sg(e){return e in wg}function kt(e){return Ro(e)}var wg,Zn=P(()=>{"use strict";sn();wg={opus:xo.large.id,opus_1m:xo.large.id,sonnet:xo.medium.id,sonnet_1m:xo.medium.id,haiku:xo.small.id,fable:hg}});import uU from"@anthropic-ai/sdk";import{randomUUID as Sk}from"node:crypto";async function Us(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=Vc(t),c=$a(t,l),u=a?a(c):new uU(c),d=Sk(),p=Sk(),m=vn(l,d,p),g=kt(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 Qc=P(()=>{"use strict";Fs();Zn()});import{execFileSync as vk}from"child_process";import{existsSync as dU,readFileSync as pU,writeFileSync as mU}from"fs";import{homedir as kk,userInfo as Ek}from"os";import{join as Tk}from"path";function Et(){let e=xk();if(e===void 0)return;let t=Rk(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 vg(){let e=xk();if(e===void 0)return;let t=Rk(e);if(t===void 0)return;if(t.expiresAt!==void 0&&t.expiresAt>Date.now()+hU)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 yU(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}:{}},bU(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 xk(){if(process.platform==="darwin")try{return vk("security",["find-generic-password","-s","Claude Code-credentials","-a",Ek().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let e=Tk(kk(),".claude",".credentials.json");if(!dU(e))return;try{return pU(e,"utf-8")}catch{return}}}function Rk(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 yU(e){try{let t=await fetch(gU,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:fU})});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 Or(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 bU(e){if(process.platform==="darwin")vk("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",Ek().username,"-w",e],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let t=Tk(kk(),".claude",".credentials.json");wU(t,e)}}function wU(e,t){mU(e,t,{encoding:"utf-8",mode:384})}var fU,gU,hU,js=P(()=>{"use strict";fU="9d1c250a-e61b-44d9-88ed-5944d1962f5e",gU="https://platform.claude.com/v1/oauth/token",hU=300*1e3});function kn(e){return e==="bypassPermissions"||e==="autonomous"}var Da=P(()=>{"use strict"});function eu(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 tu(){let e=v.AFK_PROMPT_CACHE_TTL;return e==="5m"?"5m":e==="1h"?"1h":SU}function Ck(e,t){if(e.length===0)return e;let n=e[e.length-1],r=_k(n,t);return r===n?e:[...e.slice(0,-1),r]}function Ak(e,t){if(e.length===0)return e;let n=e[e.length-1],r=vU(n,t);return r===n?e:[...e.slice(0,-1),r]}function vU(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=_k(r,t);return o===r?e:{...e,content:[...n.slice(0,-1),o]}}function _k(e,t){return e.type==="thinking"||e.type==="redacted_thinking"?e:{...e,cache_control:{type:"ephemeral",ttl:t}}}var SU,kg=P(()=>{"use strict";J();SU="1h"});function Eg(e){return e!=="plan"?null:{type:"text",text:nu}}var nu,Tg=P(()=>{"use strict";nu=["## 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
|
`)});var Pk=P(()=>{"use strict";Tg()});function xg(e){return e!=="autonomous"?null:{type:"text",text:ru}}var ru,Rg=P(()=>{"use strict";ru=["## 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
|
-
`)});var Ik=P(()=>{"use strict";Rg()});function
|
|
6
|
+
`)});var Ik=P(()=>{"use strict";Rg()});function Be(e){let t=Mk[e];if(!t){let n=Object.keys(Mk).sort(),r=n.length>0?"Available: "+n.join(", "):"";throw new Error("Unknown skill: "+e+". "+r)}return t}var Mk,zt=P(()=>{"use strict";Mk={"audit-fit":{"01-skill-inspector.md":`# Skill Inspector
|
|
7
7
|
|
|
8
8
|
You are an inspector auditing skills for correct type categorization. Skills come from two sources:
|
|
9
9
|
- **User-scope** \u2014 authored directly by the user under \`~/.afk/skills/<name>/SKILL.md\`
|
|
@@ -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 an(e,t){return t?!0:(e.audience??"public")==="public"}function ht(e){ou.set(e.name,e)}function Ge(e){let t=ou.get(e);if(t)return t;let n=Array.from(ou.keys()).sort(),r=n.length>0?`
|
|
858
|
-
Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${e}${r}`)}function En(){return Array.from(ou.keys()).sort()}function Cg(e){return En().filter(t=>an(Ge(t),e))}var ou,Tt=P(()=>{"use strict";ou=new Map});function kU(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}var su,Ok=P(()=>{"use strict";
|
|
858
|
+
Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${e}${r}`)}function En(){return Array.from(ou.keys()).sort()}function Cg(e){return En().filter(t=>an(Ge(t),e))}var ou,Tt=P(()=>{"use strict";ou=new Map});function kU(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}var su,Ok=P(()=>{"use strict";Ne();su=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)}}fk(this.traceWriter,{origin:r,cascadedTo:s,...n!==void 0?{reason:kU(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 au(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 Gt(`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 iu,Ag,lu=P(()=>{"use strict";vt();iu=0,Ag=5e3});function EU(e,t,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new Tn(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 TU(e){return e.continue===!1||e.decision==="block"}function _g(e,t){if(e?.aborted){let n=e.reason,r=`aborted during ${t}${n?`: ${String(n)}`:""}`;throw new ut(r)}}function $k(){return new Pg}var Co,Tn,Pg,Fa=P(()=>{"use strict";vt();Co=3e4;Tn=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"},Pg=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=Co){_g(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){_g(n,t.event);let l;try{let c=a.handler(t,n);l=!a.options.longRunning&&r>0&&Number.isFinite(r)?await EU(c,r,t.event):await c}catch(c){throw c instanceof Tn?c:new me(`hook handler threw during ${t.event}`,t.event,c instanceof Error?c.message:String(c),{cause:c})}if(_g(n,t.event),TU(l))throw new me(`hook handler blocked ${t.event}${l.reason?`: ${l.reason}`:""}`,t.event,l.reason);i=l}return i}}});async function xn(e,t,n,r){if(!e)return;if(r.kind==="blocked"){await on(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 on(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 Dk(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await xn(n.traceWriter,"SubagentStart",{},{kind:"decision",decision:r})}catch(r){throw r instanceof me&&await xn(n.traceWriter,"SubagentStart",{},{kind:"blocked",err:r}),r}}function xU(e,t,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new Tn(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 Fk(e,t,n={}){if(!e)return{};try{let r=await xU(e.dispatch(t,n.signal,Co),Co,"SubagentStop");return await xn(n.traceWriter,"SubagentStop",{},{kind:"decision",decision:r}),r}catch(r){return r instanceof Tn?(console.warn(`[afk] SubagentStop hook timed out after ${Co}ms (subagentId=${t.subagentId}): ${r.message}`),n.onError?.(r),{}):(r instanceof me&&await xn(n.traceWriter,"SubagentStop",{},{kind:"blocked",err:r}),r instanceof me||r instanceof ut?(W(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):(W(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{}))}}async function Ig(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await xn(n.traceWriter,"PreToolUse",{toolName:t.toolName},{kind:"decision",decision:r})}catch(r){throw r instanceof me&&await xn(n.traceWriter,"PreToolUse",{toolName:t.toolName},{kind:"blocked",err:r}),r}}async function Lk(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await xn(n.traceWriter,"PostToolUse",{toolName:t.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof me&&await xn(n.traceWriter,"PostToolUse",{toolName:t.toolName},{kind:"blocked",err:r}),r instanceof me||r instanceof ut){W(`PostToolUse hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}W(`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 xn(n.traceWriter,"PostToolUseFailure",{toolName:t.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof me&&await xn(n.traceWriter,"PostToolUseFailure",{toolName:t.toolName},{kind:"blocked",err:r}),r instanceof me||r instanceof ut){W(`PostToolUseFailure hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}W(`PostToolUseFailure hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var cu=P(()=>{"use strict";Pe();vt();Fa();Ne()});import{mkdir as RU,writeFile as CU}from"fs/promises";import{dirname as AU,join as _U}from"path";function PU(){return _U(Mt(),"routing-decisions.jsonl")}function IU(e){let t={surface:"afk"};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}async function We(e){if(!(v.VITEST||v.NODE_ENV==="test"))try{let t=PU();await RU(AU(t),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,...IU(e)})+`
|
|
859
859
|
`;await CU(t,r,{flag:"a"})}catch{}}var Qn=P(()=>{"use strict";J();K()});import{AsyncLocalStorage as MU}from"node:async_hooks";function Hs(e,t){return Bk.run(e,t)}function Jt(){return Bk.getStore()}var Bk,er=P(()=>{"use strict";Bk=new MU});function Uk(){return $k()}function uu(e,t){return e??t}var du=P(()=>{"use strict";Fa()});function Mg(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 pu(e,t){return jk(e,t)}function mu(e,t){return jk(e,t)}function jk(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 fu=P(()=>{"use strict"});function gj(e){return e.replace(/'[^']*'/g," ").replace(/"(?:[^"\\]|\\.)*"/g,t=>/\$\(|`/.test(t)?t:" ")}function hu(e){if(typeof e!="string"||e.trim().length===0)return{mutating:!1};let t=e.replace(BU," ");for(let s of mj)if(s.re.test(t))return{mutating:!0,reason:s.reason};let n=e.match(oj)?.[1];if(n&&sj.test(n))return{mutating:!0,reason:"interpreter one-liner file write (`-c`/`-e`)"};let r=gj(e);for(let s of fj)if(s.re.test(r))return{mutating:!0,reason:s.reason};let o=r.replace(dj," ").replace(uj," ").replace(/&(>>?)/g,"$1");return pj.test(o)?{mutating:!0,reason:"output redirection to a file (`>`/`>>`)"}:{mutating:!1}}var OU,$U,DU,FU,LU,NU,BU,UU,jU,HU,WU,KU,GU,qU,zU,JU,VU,gu,YU,XU,ZU,QU,ej,tj,nj,rj,oj,sj,ij,aj,lj,cj,uj,dj,pj,mj,fj,Og=P(()=>{"use strict";OU=/\bgit\b[^|;&]*\s(commit|push|pull|merge|rebase|reset|checkout|switch|restore|cherry-pick|revert|am|apply|clean|add|rm|mv|init)\b/i,$U=/\bgit\b[^|;&]*\s+tag\s+-/i,DU=/\bgit\b[^|;&]*\s+branch\s+-[dDmM]\b/i,FU=/\bgit\b[^|;&]*\s+remote\s+(add|remove|rm|set-url|rename)\b/i,LU=/\bgit\b[^|;&]*\s+worktree\s+(remove|prune|move|lock|unlock)\b/i,NU=/\bgit\b[^|;&]*\s+stash\b(?!\s+(list|show)\b)/i,BU=/\bstash@\{[^}]*\}/gi,UU=/\bgit\s+config\b[^|;&]*\s(--add|--unset|--unset-all|--replace-all|--rename-section|--remove-section|--edit|-e)\b/i,jU=/\bgit\s+config\s+(?:--(?:global|system|local|worktree)\s+|(?:--file|-f)\s+\S+\s+)*[\w][\w.-]*\s+\S/i,HU=/\bgh\s+\w[\w-]*\s+(create|merge|close|edit|delete|comment|review|reopen|sync|fork|clone|ready)\b/i,WU=/\bgh\s+api\b.*(-X|--method)\s+(POST|PUT|PATCH|DELETE)\b/i,KU=/\bgh\s+api\b.*(\s-f\b|\s-F\b|--field\b)/i,GU=/\bgh\s+(secret|variable|workflow|release|run|cache|ssh-key|gpg-key)\s+(set|run|rerun|cancel|upload|delete|enable|disable)\b/i,qU=/\|\s*(sh|bash|zsh|dash)\b/i,zU=/\b(rm|rmdir|unlink|mv|cp|mkdir|touch|dd|truncate|tee|sponge|ln|chmod|chown|chgrp|shred|rsync)\b/i,JU=/\bfind\b[^|;&]*\s-delete\b/i,VU=/\bfind\b[^|;&]*\s-exec\s+['"]?\s*(rm|rmdir|unlink|mv|cp|dd|truncate|shred|tee|chmod|chown|chgrp|install|patch)\b/i,gu=String.raw`(?:^|[\n;|&(]|\$\()\s*`,YU=new RegExp(gu+String.raw`patch\b`,"i"),XU=new RegExp(gu+String.raw`install\b`,"i"),ZU=new RegExp(gu+String.raw`(?:source\b|\.\s+\S)`,"i"),QU=/\btar\s+-?[a-zA-Z]*[cxruA][a-zA-Z]*\b/i,ej=new RegExp(gu+String.raw`unzip\b`,"i"),tj=/\bcpio\b[^|;&]*\s-[a-zA-Z]*i\b/i,nj=/\bsed\b[^|;&]*\s-[a-zA-Z]*i\b/i,rj=/\bperl\b[^|;&]*\s-[a-zA-Z]*i\b/i,oj=/\b(?:python3?|nodejs|node|bun|ruby|perl|php)\b[^|;&]*?\s-(?:c|e)\b\s*("(?:[^"\\]|\\.)*"|'[^']*'|`[^`]*`)/i,sj=/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,ij=/\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,aj=/\b(curl|wget)\b[^|;&]*\s(-o\b|-O\b|--output\b)/i,lj=/\bcurl\b[^|;&]*\s-X\s+(POST|PUT|PATCH|DELETE)\b/i,cj=/\bcurl\b[^|;&]*\s(-d\b|--data\b|-F\b|--form\b)/i,uj=/(\d*&?>>?\s*\/dev\/null|\d*>&\d+|&>\s*\/dev\/null|&>>\s*\/dev\/null)/gi,dj=/\$\(\(.*?\)\)/g,pj=/(?<![=<>-])>>?(?!&)/,mj=[{re:OU,reason:"git repository mutation"},{re:$U,reason:"git tag create/delete"},{re:DU,reason:"git branch delete/rename"},{re:FU,reason:"git remote mutation"},{re:NU,reason:"git stash mutation (only `stash list`/`stash show` allowed)"},{re:UU,reason:"git config write flag (only reads allowed)"},{re:jU,reason:"git config set (`<key> <value>`; only reads allowed)"},{re:HU,reason:"gh write operation"},{re:WU,reason:"gh api write method (POST/PUT/PATCH/DELETE)"},{re:KU,reason:"gh api field payload (-f/-F/--field)"},{re:GU,reason:"gh extended write operation (secret/variable/workflow/run/cache)"},{re:LU,reason:"git worktree mutation (remove/prune/move)"},{re:nj,reason:"sed in-place edit (-i)"},{re:rj,reason:"perl in-place edit (-i)"},{re:ij,reason:"package install/modify"},{re:aj,reason:"curl/wget output-to-file"},{re:lj,reason:"curl write method (POST/PUT/PATCH/DELETE)"},{re:cj,reason:"curl data/form payload"},{re:VU,reason:"find -exec with mutating verb"}],fj=[{re:qU,reason:"pipe-to-shell (RCE via piped interpreter)"},{re:zU,reason:"filesystem mutation"},{re:JU,reason:"find -delete (file removal)"},{re:YU,reason:"patch (applies a diff to files)"},{re:XU,reason:"install (writes files)"},{re:ZU,reason:"source/dot-source executes a script"},{re:QU,reason:"tar create/extract/append/update (writes files/archive)"},{re:ej,reason:"unzip (writes files)"},{re:tj,reason:"cpio extract (-i mode writes files)"}]});var hj,yj,bj,wj,Sj,vj,kj,Ej,Tj,Ao,_o,Po,xj,Rj,Cj,Aj,_j,Pj,Ij,Mj,Oj,$j,Dj,Fj,Lj,tr,Rn,Hle,nr=P(()=>{"use strict";hj={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"]}},yj={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"]}},bj={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"]}},wj={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"]}},Sj={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"]}},vj={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"]}},kj={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"]}},Ej={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"]}},Tj={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:[]}},Ao={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,7 +994,7 @@ ${$g}
|
|
|
994
994
|
`,"utf-8")}catch(r){W("WAL append failed (non-fatal):",String(r))}}};Xj=/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;Zj=new Set(["fact","session_start","session_end","supersede"]),Qj=new Set(["preference","convention","decision","learning"])});function eE(e){return t1.has(e)}function Eu(){return v.AFK_MEMORY_EVIDENCE_GATE==="1"}function Dg(e){return eE(e)}function Tu(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function tE(e,t){return eE(e)?Tu(t)?"verified":"unverified":"not-applicable"}function nE(e,t){return t!=="unverified"||e.startsWith(Qk)?e:`${Qk} ${e}`}var t1,Qk,rE=P(()=>{"use strict";J();t1=new Set(["convention"]),Qk="[unverified]"});function r1(e,t){return t?e.map(n=>{if(n.type!=="fact"||!n.category)return{...n,verification:"not-applicable"};let r=tE(n.category,n.evidence);return{...n,verification:r,content:nE(n.content,r)}}):e.map(n=>{let r={...n};return delete r.evidence,delete r.verification,r})}function Na(e,t,n){let r=async i=>{try{let a=o1(i),l=e.search(a.query,{category:a.category,since:a.since,limit:a.limit??10});return{content:JSON.stringify(r1(l,Eu()))}}catch(a){return{content:`memory_search error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},o=async i=>{try{let a=s1(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>=Xk*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=Tu(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 Eu()&&Dg(l)&&!c&&(d.warning=oE),{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:Tu(a.evidence),d={id:e.supersedeFact(a.supersedes,a.content,a.category??void 0,c),action:"supersede",target:"fact",supersedes:a.supersedes};if(Eu()){let p=a.category??l?.category;p&&Dg(p)&&((c===void 0?l?.evidence??null:c)?c===void 0&&(d.warning=n1):d.warning=oE)}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=i1(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 o1(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 s1(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 i1(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 Ws,sE,iE,$r,Io,oE,n1,Fg=P(()=>{"use strict";ku();rE();Ws={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"]}},sE={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"]}},iE={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"]}},$r=[Ws,sE,iE],Io=$r.map(e=>e.name),oE='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.',n1='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 Lg(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 Ng(e){return e==="self"||e==="tools"||e==="subagents"||e==="workspace"||e==="all"?e:"all"}function Ks(e){let n=[`- Working directory: ${e.cwd.replace(/[\r\n]/g," ")}`];n.push(`- Date: ${a1(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 a1(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 Bg=P(()=>{"use strict"});import{spawnSync as l1}from"child_process";function xu(e,t){try{let n=l1("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 Ug(e){let t=xu(e,["rev-parse","--short","HEAD"]);if(t===null)return{...c1};let n=xu(e,["symbolic-ref","--short","HEAD"]),r=xu(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=xu(e,["remote","get-url","origin"]);return{branch:n,headSha:t,dirty:o,dirtyCount:s,remoteUrl:i}}var c1,jg=P(()=>{"use strict";c1={branch:null,headSha:null,dirty:null,dirtyCount:null,remoteUrl:null}});function Ba(e){return{getSelf(){return{sessionId:e.sessionId??null,surface:d1(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:u1(e.permissionMode)}},getTools(){return{enabled:e.getEnabledToolNames(),mcpServers:p1(e.getMcpTools())}},getSubagents(){return e.getSubagents()},getWorkspace(){return Ug(e.cwd)}}}function u1(e){switch(e){case"bypassPermissions":case"acceptEdits":case"dontAsk":case"auto":return"elevated";default:return"default"}}function d1(e){switch(e){case"cli":case"repl":case"daemon":case"telegram":case"subagent":return e;default:return"unknown"}}function p1(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 aE=P(()=>{"use strict";jg()});function Gs(e){return async(t,n)=>{let r=t&&typeof t=="object"?Ng(t.view):"all",o=Lg(e,r);return{content:JSON.stringify(o)}}}function Ua(e,t){let n=Gs(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,Cn]}return s}var Cn,Pt,Hg=P(()=>{"use strict";Bg();Cn={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:[]}},Pt=[Cn.name]});import{mkdir as m1,writeFile as Wg,unlink as uce,readdir as f1,readFile as Kg}from"fs/promises";import{unlinkSync as g1,existsSync as h1}from"fs";import{join as lE}from"path";function Ru(e){return lE(Mc(),`${e}.json`)}async function y1(){try{return await m1(Mc(),{recursive:!0}),!0}catch{return!1}}async function ja(e){try{if(!await y1())return;let n=Ru(e.sessionId);await Wg(n,JSON.stringify(e,null,2),"utf8")}catch{}}async function Gg(e,t){try{let n=Ru(e),r=await Kg(n,"utf8"),o=JSON.parse(r);o.afk=t,await Wg(n,JSON.stringify(o,null,2),"utf8")}catch{}}async function cE(e,t){try{let n=Ru(e),r=await Kg(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=Ru(e);h1(t)&&g1(t)}catch{}}async function qg(){let e=Mc(),t;try{t=await f1(e)}catch{return[]}let n=[];for(let r of t){if(!r.endsWith(".json"))continue;let o=lE(e,r);try{let s=await Kg(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 Ha=P(()=>{"use strict";K()});var or=P(()=>{"use strict";Bg();aE();Hg();jg();Ha()});import zg from"path";import{appendFileSync as b1,mkdirSync as w1}from"fs";import{dirname as S1}from"path";import{createHash as v1}from"node:crypto";function E1(e){return k1.has(e)}function x1(e){let t;try{t=JSON.stringify(e.input)??"null"}catch{t=String(e.input)}return v1("sha256").update(e.name).update("\0").update(t).digest("hex")}function R1(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 k1,qs,T1,Ot,Wa=P(()=>{"use strict";Pe();vt();cu();fu();Og();K();
|
|
997
|
+
`).filter(l=>l.trim().length>0);o=a.length>0,s=a.length}r===null&&(o=null,s=null);let i=xu(e,["remote","get-url","origin"]);return{branch:n,headSha:t,dirty:o,dirtyCount:s,remoteUrl:i}}var c1,jg=P(()=>{"use strict";c1={branch:null,headSha:null,dirty:null,dirtyCount:null,remoteUrl:null}});function Ba(e){return{getSelf(){return{sessionId:e.sessionId??null,surface:d1(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:u1(e.permissionMode)}},getTools(){return{enabled:e.getEnabledToolNames(),mcpServers:p1(e.getMcpTools())}},getSubagents(){return e.getSubagents()},getWorkspace(){return Ug(e.cwd)}}}function u1(e){switch(e){case"bypassPermissions":case"acceptEdits":case"dontAsk":case"auto":return"elevated";default:return"default"}}function d1(e){switch(e){case"cli":case"repl":case"daemon":case"telegram":case"subagent":return e;default:return"unknown"}}function p1(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 aE=P(()=>{"use strict";jg()});function Gs(e){return async(t,n)=>{let r=t&&typeof t=="object"?Ng(t.view):"all",o=Lg(e,r);return{content:JSON.stringify(o)}}}function Ua(e,t){let n=Gs(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,Cn]}return s}var Cn,Pt,Hg=P(()=>{"use strict";Bg();Cn={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:[]}},Pt=[Cn.name]});import{mkdir as m1,writeFile as Wg,unlink as uce,readdir as f1,readFile as Kg}from"fs/promises";import{unlinkSync as g1,existsSync as h1}from"fs";import{join as lE}from"path";function Ru(e){return lE(Mc(),`${e}.json`)}async function y1(){try{return await m1(Mc(),{recursive:!0}),!0}catch{return!1}}async function ja(e){try{if(!await y1())return;let n=Ru(e.sessionId);await Wg(n,JSON.stringify(e,null,2),"utf8")}catch{}}async function Gg(e,t){try{let n=Ru(e),r=await Kg(n,"utf8"),o=JSON.parse(r);o.afk=t,await Wg(n,JSON.stringify(o,null,2),"utf8")}catch{}}async function cE(e,t){try{let n=Ru(e),r=await Kg(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=Ru(e);h1(t)&&g1(t)}catch{}}async function qg(){let e=Mc(),t;try{t=await f1(e)}catch{return[]}let n=[];for(let r of t){if(!r.endsWith(".json"))continue;let o=lE(e,r);try{let s=await Kg(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 Ha=P(()=>{"use strict";K()});var or=P(()=>{"use strict";Bg();aE();Hg();jg();Ha()});import zg from"path";import{appendFileSync as b1,mkdirSync as w1}from"fs";import{dirname as S1}from"path";import{createHash as v1}from"node:crypto";function E1(e){return k1.has(e)}function x1(e){let t;try{t=JSON.stringify(e.input)??"null"}catch{t=String(e.input)}return v1("sha256").update(e.name).update("\0").update(t).digest("hex")}function R1(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 k1,qs,T1,Ot,Wa=P(()=>{"use strict";Pe();vt();cu();fu();Og();K();Ne();nr();Fg();or();k1=new Set([...tr,Ao,_o,Po,...$r,Cn].filter(e=>e.concurrencySafe===!0).map(e=>e.name));qs=8,T1=new Set;Ot=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??E1,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=zg.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=zg.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=zg.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=Cs();w1(S1(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:this.sessionId??null,action:t.action,path:t.path,source:t.source});b1(n,r+`
|
|
998
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=hu(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(T1.has(t.name))return null;let n=x1(t);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<qs?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 on(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 on(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 Ig(this.hookRegistry,u,{signal:t.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(d){if(d instanceof me)return{content:`Tool "${t.name}" blocked by PreToolUse hook: ${d.message}`,isError:!0,failureClass:"hook-block"};throw d}}let n=Mg(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 Ig(this.hookRegistry,p,{signal:a.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(m){if(m instanceof me){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=Mg(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=R1(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}:{}};Lk(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=>{W(`firePostToolUseFailure outer catch (tool=${t}): ${String(i)}`)})}}});function L1(e){let t=e.match(C1);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 N1(e){let t=e.match(A1);if(!t)return null;let n=parseInt(t[1]??"0",10);return{runner:"jest",passed:parseInt(t[2]??"0",10),failed:n}}function B1(e){let t=e.match(_1);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 U1(e){let t=e.match(P1);if(!t)return null;let n=parseInt(t[1]??"0",10),r=e.match(I1),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function j1(e){let t=[...e.matchAll(M1)];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 H1(e){let t=e.match(O1);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 W1(e){let t=e.match($1);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 K1(e){let t=e.match(D1);if(t)return{runner:"phpunit",passed:parseInt(t[1]??"0",10),failed:0};let n=e.match(F1);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 Jg(e){return L1(e)??N1(e)??B1(e)??U1(e)??j1(e)??H1(e)??W1(e)??K1(e)??null}var C1,A1,_1,P1,I1,M1,O1,$1,D1,F1,uE=P(()=>{"use strict";C1=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,A1=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,_1=/={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,}/,P1=/(\d+)\s+passing/,I1=/(\d+)\s+failing/,M1=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,O1=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,$1=/(\d+) examples?, (\d+) failures?/,D1=/OK \((\d+) tests?/,F1=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/});function Mo(e){return e.replace(dE,"").replace(G1," ").trim()}function sr(e){return e.replace(dE,"")}var dE,G1,Oo=P(()=>{"use strict";dE=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,G1=/[\x00-\x1F\x7F-\x9F]/g});import{spawn as q1}from"child_process";function z1(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 Cu(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}=z1(o);return s.aborted?{content:"Command aborted",isError:!0}:(r(),new Promise(c=>{let u=!1;function d(T){u||(u=!0,clearTimeout(m),s.removeEventListener("abort",k),c(T))}let p=q1(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(T){if(S||u||y<b)return;S=!0,console.warn(`[bash] overflow kill: stream=${T} totalBytes=${y} command="${a}"`),We({event:"tool.overflow_kill",tool:"bash",total_bytes:y,stream:T}),p.kill("SIGKILL");let R=(g+h).trimEnd();R=sr(R);let A=Jg(R)??void 0;R.length>b&&(R=R.slice(0,b)),R+=`
|
|
999
999
|
[output truncated \u2014 exceeded 100KB]`,d({content:R,truncated:!0,...A!==void 0?{testResult:A}:{}})}p.stdout.on("data",T=>{let R=b-y,A=T.length<=R?T:T.subarray(0,Math.max(0,R));y+=A.length,g+=A.toString("utf8"),w("stdout")}),p.stderr.on("data",T=>{let R=b-y,A=T.length<=R?T:T.subarray(0,Math.max(0,R));y+=A.length,h+=A.toString("utf8"),w("stderr")});let k=()=>{p.pid!==void 0&&process.kill(-p.pid,"SIGKILL"),d({content:"Command aborted",isError:!0})};s.addEventListener("abort",k),p.on("close",T=>{if(s.aborted){d({content:"Command aborted",isError:!0});return}if(T!==null&&T!==0){let O=h.trimEnd()||g.trimEnd();d({content:`Command exited with code ${T}${O?`
|
|
1000
1000
|
`+O:""}`,isError:!0});return}if(S)return;let R=(g+h).trimEnd();R=sr(R);let A=Jg(R)??void 0,E=!1;R.length>b&&(R=R.slice(0,b)+`
|
|
@@ -1075,10 +1075,10 @@ end
|
|
|
1075
1075
|
${o}`;return s.includes("already checked out")||s.includes("is already used by worktree")?new Error(`Branch '${t}' is already checked out in another worktree. Pick a different name.`):s.includes("already exists")?new Error(`Worktree path '${n}' already exists. Remove it or pick a different branch name.`):new Error(o||r||"git worktree add failed")}async function Mu(e,t){let n=t?.execFile??LE,r=Iu(t?.branchPrefix),o=await NE(n);return await BE(o),KE(o,e,{execFile:n,prefix:r,baseRef:t?.baseRef})}async function UE(e){let t=e?.execFile??LE,n=Iu(e?.branchPrefix),r=await NE(t);await BE(r);let o=await jE(r,e?.baseRef,t),s;return{repoRoot:r,handle:()=>s,async create(i){return s===void 0&&(s=await KE(r,i,{execFile:t,prefix:n,preResolvedBase:o})),s}}}async function jE(e,t,n){let r=OH(t);if(r!==void 0)return ah(r,"worktree base ref"),await HE(e,r,n),{ref:r,sha:await WE(e,r,n)}}function ah(e,t){if(e.trim().length===0)throw new Error(`Invalid worktree base ref from ${t}: '' \u2014 base ref cannot be empty.`);if(e.startsWith("-"))throw new Error(`Invalid worktree base ref from ${t}: '${e}' \u2014 must not start with '-' (would be parsed by git as a flag).`);if(e.includes("\0"))throw new Error(`Invalid worktree base ref from ${t}: contains a NUL byte.`);if(/\s/.test(e))throw new Error(`Invalid worktree base ref from ${t}: '${e}' \u2014 must not contain whitespace.`)}function OH(e){let t=e??v.AFK_WORKTREE_BASE;if(!(t===void 0||t.length===0))return t}async function HE(e,t,n){let r=t.indexOf("/");if(r<=0)return;let o=t.slice(0,r),s;try{let{stdout:a}=await n("git",["-C",e,"remote"]);s=a.split(`
|
|
1076
1076
|
`).map(l=>l.trim()).filter(l=>l.length>0)}catch{return}if(!s.includes(o))return;let i=t.slice(r+1).replace(/[~^@:].*$/,"");if(i.length!==0)try{await n("git",["-C",e,"fetch","--no-tags",o,i])}catch(a){let l=Lr(a)?a.message||a.stderr||"":String(a);console.warn(`Worktree base: could not fetch '${o}/${i}' (${l.trim()}). Using the local copy of '${t}', which may be stale.`)}}async function WE(e,t,n){try{let{stdout:r}=await n("git",["-C",e,"rev-parse","--verify",`${t}^{commit}`]),o=r.trim();if(o.length===0)throw new Error("empty rev-parse output");return o}catch(r){let o=Lr(r)?r.message||r.stderr||"":String(r);throw new Error(`Cannot resolve worktree base ref '${t}': ${o.trim()} \u2014 check the ref exists (for a remote branch, make sure the remote is reachable so it can be fetched).`)}}async function $H(e,t){try{let{stdout:n}=await t("git",["-C",e,"symbolic-ref","--short","--quiet","refs/remotes/origin/HEAD"]),r=n.trim();if(r.length>0)return r}catch{}for(let n of["origin/main","origin/master"])try{let{stdout:r}=await t("git",["-C",e,"rev-parse","--verify","--quiet",`${n}^{commit}`]);if(r.trim().length>0)return n}catch{}}async function DH(e,t,n){try{return await WE(e,t,n)}catch{return}}async function KE(e,t,n){let{execFile:r,prefix:o}=n,s=t===!0?PH(o):t;IH(s);let i=s.replaceAll("/","-"),a=sh(e,".afk-worktrees",i),l,c,u=n.preResolvedBase??await jE(e,n.baseRef,r);if(u!==void 0)c=u.sha,l=u.ref;else{let m=await $H(e,r);if(m!==void 0){await HE(e,m,r);let g=await DH(e,m,r);g!==void 0&&(c=g,l=m)}}let d=["-C",e,"worktree","add","-b",s,a];c!==void 0&&d.push(c);try{await r("git",d)}catch(m){throw MH(m,s,a)}let p={path:a,branch:s,cleanup:async m=>{let g=p.path,h=p.branch;if(m?.force===!0){console.log(`Worktree removed (zero turns \u2014 no work done): ${g}`);try{await r("git",["-C",e,"worktree","remove","--force",g])}catch(y){let S=Lr(y)?y.message||y.stderr||"":String(y);console.warn(`Worktree cleanup: 'git worktree remove --force ${g}' failed (${S}). Manual removal may be needed.`);return}try{await r("git",["-C",e,"branch","-d",h])}catch(y){let S=Lr(y)?y.message||y.stderr||"":String(y);console.warn(`Could not delete branch '${h}': ${S}`)}return}let b;try{b=await r("git",["-C",g,"status","--porcelain"])}catch(y){let S=Lr(y)?y.message||y.stderr||"":String(y);console.warn(`Worktree cleanup: could not check status at ${g} (${S}). Skipping removal \u2014 manual cleanup may be needed.`);return}if(b.stdout.trim().length>0){if(console.log(`Worktree preserved at ${g} (branch: ${h}) \u2014 uncommitted changes.`),Hv(g),!Wv()){let S=nh(v.SHELL)==="fish"?"afk shell-init fish | source (add to ~/.config/fish/config.fish)":'eval "$(afk shell-init)" (add to ~/.zshrc or ~/.bashrc)';console.log(` \u2192 cd ${g}
|
|
1077
1077
|
\u2192 Or install one-time: ${S}`)}return}try{await r("git",["-C",e,"worktree","remove","--force",g])}catch(y){let S=Lr(y)?y.message||y.stderr||"":String(y);console.warn(`Worktree cleanup: 'git worktree remove --force ${g}' failed (${S}). Manual removal may be needed.`);return}try{await r("git",["-C",e,"branch","-d",h])}catch(y){let S=Lr(y)?y.message||y.stderr||"":String(y);console.warn(`Could not delete branch '${h}': ${S}`)}}};try{let m=c??"",g=l??"";if(c===void 0){try{m=(await r("git",["-C",e,"rev-parse","HEAD"])).stdout.trim()}catch{}try{g=(await r("git",["-C",e,"symbolic-ref","--short","HEAD"])).stdout.trim()}catch{}}let h={owner:"interactive",pid:process.pid,createdAt:new Date().toISOString(),baseSha:m,baseBranch:g};await oh.writeFile(sh(a,".afk-worktree-meta.json"),JSON.stringify(h,null,2),"utf-8")}catch{}return p}var LE,CH,AH,FE,Ga=P(()=>{"use strict";J();Uc();rh();LE=kH(vH),CH="afk/",AH=/^[A-Za-z0-9_\-./]*$/,FE=64});import{existsSync as cr,readdirSync as qE,readFileSync as ch,realpathSync as FH,statSync as LH}from"fs";import{homedir as zE}from"os";import{join as $t}from"path";function qa(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Vs){let r=e[n];if(r!==void 0){if(r===!0){t[n]={plugins:!0,skills:!0,mcp:!0};continue}if(r!==!1&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=r;t[n]={plugins:o.plugins===!0,skills:o.skills===!0,mcp:o.mcp===!0}}}}return Object.keys(t).length>0?t:void 0}function BH(){return[Kt(),Fc()]}function Dt(e=BH()){for(let t of e)if(cr(t))try{let n=JSON.parse(ch(t,"utf-8")),r=qa(n.importFrom);if(r!==void 0)return r}catch{}}function ln(e,t=zE()){let n={pluginRoots:[],skillRoots:[],mcpConfigs:[]};if(!e)return n;for(let r of Vs){let o=e[r];if(!o)continue;let s=Ou[r];if(o.plugins)for(let i of s.pluginRoots(t))cr(i)&&n.pluginRoots.push(i);if(o.skills){let i=`imported:${r}`;for(let a of s.skillRoots(t))cr(a)&&n.skillRoots.push({dir:a,origin:i})}if(o.mcp){let i=JE(s.mcpConfigCandidates(t));i&&n.mcpConfigs.push({source:i,format:s.mcpFormat})}}return n}function $u(e=zE()){return Vs.map(t=>UH(t,e))}function UH(e,t){let n=Ou[e],r=[];for(let l of n.pluginRoots(t))r.push(...HH(l));let o=[];for(let l of n.skillRoots(t))o.push(...WH(l));let s=JE(n.mcpConfigCandidates(t)),i=s?KH(s,n.mcpFormat):[],a=r.length>0||o.length>0||s!==null||n.pluginRoots(t).some(cr)||n.skillRoots(t).some(cr);return{binary:e,label:n.label,present:a,plugins:r,skills:o,mcpServers:i,mcpConfigPath:s,mcpFormat:n.mcpFormat}}function JE(e){for(let t of e)if(cr(t))return t;return null}function jH(e){try{let t=JSON.parse(ch($t(e,".claude-plugin","plugin.json"),"utf-8"));return typeof t.name=="string"&&t.name.length>0?t.name:null}catch{return null}}function HH(e){if(!cr(e))return[];let t=[];return VE(e,0,t,new Set),t}function VE(e,t,n,r){let o;try{o=FH(e)}catch{o=e}if(t>NH||r.has(o))return;if(r.add(o),cr($t(e,".claude-plugin","plugin.json"))){let i=jH(e)??e.split("/").filter(Boolean).pop()??e;n.push({name:i,path:e});return}let s;try{s=qE(e)}catch{return}for(let i of s){if(i.startsWith("."))continue;let a=$t(e,i);try{LH(a).isDirectory()&&VE(a,t+1,n,r)}catch{}}}function WH(e){let t;try{t=qE(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t)!r.isDirectory()||r.name.startsWith("_")||r.name.startsWith(".")||cr($t(e,r.name,"SKILL.md"))&&n.push({name:r.name,path:$t(e,r.name)});return n}function KH(e,t){let n;try{n=ch(e,"utf-8")}catch{return[]}return t==="json"?GH(n):qH(n)}function GH(e){let t;try{t=JSON.parse(e)}catch{return[]}if(t===null||typeof t!="object")return[];let n=t.mcpServers;if(n===null||typeof n!="object"||Array.isArray(n))return[];let r=[];for(let[o,s]of Object.entries(n))r.push({name:o,command:JH(s)});return r}function qH(e){let t=[],n=e.split(/\r?\n/),r=!1,o=null,s=null,i=null,a=[],l=()=>{if(r&&o){let u;i!==null?u=i:s!==null?u=a.length>0?[s,...a].join(" "):s:u="(no command)",t.push({name:o,command:u})}o=null,s=null,i=null,a=[]},c=/^\[mcp_servers\.([^\]]+)\]\s*$/;for(let u of n){let d=u.trim();if(d===""||d.startsWith("#"))continue;let p=c.exec(d);if(p){l(),r=!0,o=p[1]??null;continue}if(d.startsWith("[")){l(),r=!1;continue}if(!r)continue;let m=d.indexOf("=");if(m===-1)continue;let g=d.slice(0,m).trim(),h=d.slice(m+1).trim();g==="command"?s=lh(GE(h)):g==="url"?i=lh(GE(h)):g==="args"&&(a=zH(h))}return l(),t}function GE(e){if(e.startsWith('"')||e.startsWith("'"))return e;let t=e.indexOf(" #");return t===-1?e:e.slice(0,t).trimEnd()}function zH(e){let t=e.trim();if(!t.startsWith("["))return[];let n=t.slice(1,t.lastIndexOf("]"));if(!n.trim())return[];try{return n.split(",").map(r=>lh(r.trim())).filter(r=>r.length>0)}catch{return[]}}function lh(e){let t=e.match(/^"([^"]*)"$/)??e.match(/^'([^']*)'$/);return t&&t[1]!==void 0?t[1]:e.startsWith('"')||e.startsWith("'")?e.slice(1):e.endsWith('"')||e.endsWith("'")?e.slice(0,-1):e}function JH(e){if(e===null||typeof e!="object")return"(invalid)";let t=e;if(typeof t.url=="string")return t.url;if(typeof t.command=="string"){let n=Array.isArray(t.args)?t.args.filter(r=>typeof r=="string"):[];return[t.command,...n].join(" ")}return"(no command)"}var Vs,Ou,Vue,NH,ur=P(()=>{"use strict";K();Vs=["claude-code","codex"],Ou={"claude-code":{label:"Claude Code",pluginRoots:e=>[$t(e,".claude","plugins")],skillRoots:e=>[$t(e,".claude","skills")],mcpConfigCandidates:e=>[$t(e,".claude","mcp.json"),$t(e,".claude",".mcp.json"),$t(e,".claude","claude-code","mcp.json")],mcpFormat:"json"},codex:{label:"Codex",pluginRoots:e=>[$t(e,".codex","plugins")],skillRoots:e=>[$t(e,".codex","skills")],mcpConfigCandidates:e=>[$t(e,".codex","config.toml")],mcpFormat:"toml"}},Vue={"claude-code":Ou["claude-code"].label,codex:Ou.codex.label},NH=5});import{readFileSync as ZE,existsSync as dh}from"fs";import{join as Ja}from"path";import{config as VH}from"dotenv";function ph(){return eh()}function YH(e){let t=e.trim();if(!t)return t;let n="/chat/completions";if(t.endsWith(n)){let r=t.slice(0,-n.length);return XE.has(t)||(XE.add(t),console.warn(`[afk] AFK_OPENAI_BASE_URL: stripped trailing "/chat/completions" \u2014 the OpenAI SDK appends it automatically.
|
|
1078
|
-
Effective base URL: ${r}`)),r}return t}function XH(){if(uh!==void 0)return uh;if(!YE){let o=[Ja(process.cwd(),".env"),St(),Fv()];for(let s of o)dh(s)&&VH({path:s,override:!1});YE=!0}let e={},t=v.AFK_MODEL??v.CLAUDE_MODEL;if(t){let o=t.toLowerCase();e.model=Sg(o)?o:t}if(se(t)==="anthropic-direct"){let o=ph();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=YH(v.AFK_OPENAI_BASE_URL)),uh=e,e}function mh(){if(Ys!==void 0)return Ys;let e=[Ja(process.cwd(),"afk.config.json"),Kt(),Fc()];for(let t of e)if(dh(t))try{let n=ZE(t,"utf-8"),r=JSON.parse(n),o={},s=wk(r.models);if(typeof r.model=="string"&&r.model.length>0){let i=r.model.toLowerCase();o.model=Sg(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!==Ja(process.cwd(),"afk.config.json")){let i=qa(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=ih(r.interactive.worktreeBranchPrefix,`${t}#/interactive/worktreeBranchPrefix`)),typeof r.interactive.worktreeBase=="string"&&r.interactive.worktreeBase.trim().length>0&&(ah(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 Ys={config:o,sourcePath:t,modelsPartial:s},Ys}catch(n){console.error(`Warning: Failed to parse ${t}:`,n)}return Ys={config:{},sourcePath:void 0,modelsPartial:{}},Ys}function ZH(){if(Xs!==void 0)return Xs.value;let e=[Ja(process.cwd(),"AFK.md"),Ja(
|
|
1078
|
+
Effective base URL: ${r}`)),r}return t}function XH(){if(uh!==void 0)return uh;if(!YE){let o=[Ja(process.cwd(),".env"),St(),Fv()];for(let s of o)dh(s)&&VH({path:s,override:!1});YE=!0}let e={},t=v.AFK_MODEL??v.CLAUDE_MODEL;if(t){let o=t.toLowerCase();e.model=Sg(o)?o:t}if(se(t)==="anthropic-direct"){let o=ph();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=YH(v.AFK_OPENAI_BASE_URL)),uh=e,e}function mh(){if(Ys!==void 0)return Ys;let e=[Ja(process.cwd(),"afk.config.json"),Kt(),Fc()];for(let t of e)if(dh(t))try{let n=ZE(t,"utf-8"),r=JSON.parse(n),o={},s=wk(r.models);if(typeof r.model=="string"&&r.model.length>0){let i=r.model.toLowerCase();o.model=Sg(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!==Ja(process.cwd(),"afk.config.json")){let i=qa(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=ih(r.interactive.worktreeBranchPrefix,`${t}#/interactive/worktreeBranchPrefix`)),typeof r.interactive.worktreeBase=="string"&&r.interactive.worktreeBase.trim().length>0&&(ah(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 Ys={config:o,sourcePath:t,modelsPartial:s},Ys}catch(n){console.error(`Warning: Failed to parse ${t}:`,n)}return Ys={config:{},sourcePath:void 0,modelsPartial:{}},Ys}function ZH(){if(Xs!==void 0)return Xs.value;let e=[Ja(process.cwd(),"AFK.md"),Ja(Le(),"AFK.md")];for(let t of e)if(dh(t))try{let n=ZE(t,"utf-8").trim();if(n.length>0)return Xs={value:{content:n,path:t}},Xs.value}catch{}return Xs={value:null},Xs.value}function Du(){return mh().config.telegram??{}}function Zs(){return mh().config.permissionMode??QE}function It(e){let t=XH(),{config:n,sourcePath:r,modelsPartial:o}=mh(),s={...za,...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=ZH();c!==null&&(s.systemPrompt=c.content,i=`afk-md:${c.path}`)}let a={model:s.model??za.model,maxTokens:s.maxTokens??za.maxTokens,temperature:s.temperature??za.temperature,updatePolicy:s.updatePolicy??za.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??QE,...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??yg(o);if(Zc(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 za,QE,YE,uh,XE,Ys,Xs,Ft=P(()=>{"use strict";Zn();sn();it();K();Js();Ga();J();ur();za={model:"sonnet",maxTokens:4096,temperature:1,updatePolicy:"notify"},QE="bypassPermissions",YE=!1;XE=new Set});function QH(e,t){return t!==void 0&&Number.isFinite(t)&&t!==0?t:e.find(r=>r>0)??e[0]}function eW(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=QH(n,t.primaryChatId);return o!==void 0?[o]:[]}function tW(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 nW(e){if(!e)return;let t=e.trim().toLowerCase();return t==="primary"||t==="broadcast"||t==="custom"?t:void 0}function rW(){let e=Du().notify??{},t=e.mode??nW(v.AFK_TELEGRAM_NOTIFY_MODE),n=e.primaryChatId??tW(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 Qs(){let e=ME(v.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return eW(e,rW())}var Fu=P(()=>{"use strict";OE();Ft();J()});function fh(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 eT(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),oW(t)||(t=t.replace(/<\/?[bis]>/g,"")),t}function oW(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 tT=P(()=>{"use strict"});var gh={};Rc(gh,{push:()=>ei,pushIfConfigured:()=>An,pushMarkdown:()=>nT});async function ei(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??sW}/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 nT(e){let t=eT(e.text),n=fh(t),r={ok:!0,status:200};for(let o of n)if(r=await ei({...e,text:o,parseMode:"HTML"}),!r.ok)return r.status===400&&/can't parse entities/i.test(r.errorMessage??"")?ei({...e}):r;return r}async function An(e,t={}){let n=v.TELEGRAM_BOT_TOKEN;if(!n)return null;let r=Qs();if(r.length===0)return null;let o=fh(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 nT(l):await ei({...l,...t.parseMode!==void 0?{parseMode:t.parseMode}:{}}))}return s}var sW,Nr=P(()=>{"use strict";Fu();tT();J();sW="https://api.telegram.org"});function iW(e=ei){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>rT)return{content:`Invalid input: message exceeds Telegram's ${rT}-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=Qs();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 rT,oT,sT=P(()=>{"use strict";J();Nr();Fu();rT=4096;oT=iW()});import{JSDOM as aW}from"jsdom";import{Readability as lW}from"@mozilla/readability";import cW from"turndown";function iT(e){return e.replace(/\n{3,}/g,`
|
|
1080
1080
|
|
|
1081
|
-
`).trim()}function uW(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function lT(e,t){let r=new aW(e,{url:t}).window.document,o=(r.title??"").trim(),s=null;try{let c=r.cloneNode(!0);s=new lW(c).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let c=iT(hh.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=iT(hh.turndown(a));return{title:o,markdown:l,textLength:uW(i),usedFallback:!0}}var aT,hh,cT=P(()=>{"use strict";aT=200,hh=new cW({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});hh.remove(["script","style","noscript","iframe"])});function pW(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(t?.reason??new Error("aborted"))},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})})}function uT(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function mW(e,t){let n=e.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,t)}async function Lu(e,t,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??pW,l=n.signal??void 0,c;for(let u=0;u<=o;u++){if(l?.aborted)throw l.reason??new Error("aborted");try{let d=await e(t,n);if(!dW.has(d.status)||u===o)return d;let p=mW(d,i)??uT(u,s,i);W("[web/retryFetch] retrying",{url:t,attempt:u,status:d.status,waitMs:p}),await d.body?.cancel().catch(()=>{}),await a(p,l)}catch(d){if(l?.aborted||(c=d,u===o))throw d;let p=uT(u,s,i);W("[web/retryFetch] retrying after error",{url:t,attempt:u,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var dW,yh=P(()=>{"use strict";Pe();dW=new Set([429,502,503,504])});import{readFileSync as fW}from"node:fs";import{join as gW}from"path";function hW(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function dT(e,t){return hW(t).test(e)}function wW(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(yW.has(t))return!0;if(bW.has(t))return!1}return!1}function pT(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function SW(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 mT(e){let t=e===void 0||e.trim()===""?"default":e.trim();return Ca(t),t}function vW(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function kW(e){try{return fW(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function EW(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 typeof t.defaultProfile=="string"&&(n.defaultProfile=mT(t.defaultProfile)),n}function fT(e){let t=e?.env??v,n=e?.readFileSync??kW,r=e?.surface??t.AGENT_SURFACE,o=wW(t.AFK_BROWSER_HEADLESS,r),s=pT(t.AFK_BROWSER_ALLOWED_DOMAINS),i=pT(t.AFK_BROWSER_BLOCKED_DOMAINS),a=vW(t.AFK_BROWSER_DOM_SNAPSHOTS),l=SW(t.AFK_BROWSER_BACKEND),c=mT(t.AFK_BROWSER_DEFAULT_PROFILE),u={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},d=t.AFK_BROWSER_CONFIG,p=d!==void 0&&d.trim()!==""?d.trim():gW(rn(),"browser.json"),m=n(p);if(m===void 0)return u;let g;try{g=JSON.parse(m)}catch(b){throw new Error(`Failed to parse browser config at ${p}: ${String(b)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${p} must be a JSON object`);let h=EW(u,g);return h.configPath=p,h}function bh(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(dT(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>dT(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var yW,bW,wh=P(()=>{"use strict";J();K();yW=new Set(["daemon","subagent","telegram","afk"]),bW=new Set(["repl","interactive","cli"])});import $o from"node:fs";import Nu from"node:path";import{randomBytes as TW}from"node:crypto";import{chromium as xW}from"playwright";function RW(){try{return"5.13.1"}catch{}try{let e=Nu.resolve(import.meta.dirname,"../../../package.json"),t=$o.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var CW,Bu,gT=P(()=>{"use strict";K();Pe();CW=RW(),Bu=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=xW.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 r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,i),s}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),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let 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/${CW}`}}loadStorageState(t){let n=Aa(t);try{if(!$o.existsSync(n))return;let r=JSON.parse($o.readFileSync(n,"utf8"));return W("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){W("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Aa(t);if(!$o.existsSync(r))return;let o=await n.storageState(),s=Nu.join(Nu.dirname(r),`.${Nu.basename(r)}.${process.pid}.${TW(4).toString("hex")}.tmp`);$o.writeFileSync(s,JSON.stringify(o),{mode:384}),$o.chmodSync(s,384),$o.renameSync(s,r),W("[browser/vault] saved session",{profile:t,file:r})}catch(r){W("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as AW}from"crypto";function Sh(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of _W)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function hT(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&PW.test(e.label))}function yT(e){return AW("sha256").update(e,"utf8").digest("hex").slice(0,8)}function bT(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var _W,PW,Va=P(()=>{"use strict";_W=[{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}];PW=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as IW}from"node:crypto";function MW(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function OW(e,t,n){return`el_${IW("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function $W(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function wT(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function vT(e,t){let n=e.role??"",r=e.name??"";ST.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let s of e.children??[])vT(s,t)}async function DW(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},kT).catch(()=>[])}async function FW(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},kT).catch(()=>[])}function LW(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Uu(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],s=LW(e),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=DW(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=[],vT(d,b)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,b=(await FW(e)).filter(L=>ST.has(L.role??"")));let S=new Map;for(let I of p){let L=wT(I.name),N=S.get(L);(!N||N.bbox.w===0&&I.bbox.w>0)&&S.set(L,I)}let w=b.map(I=>({ax:I,dom:S.get(wT(I.name??""))})),k=r?w:w.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);k.sort((I,L)=>{let N=I.dom?.bbox.y??0,F=L.dom?.bbox.y??0;if(N!==F)return N-F;let U=I.dom?.bbox.x??0,H=L.dom?.bbox.x??0;return U-H}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=k.slice(0,n).map((I,L)=>{let N=I.ax.role??"generic",F=I.ax.name??"",U=OW(N,F,L),H=I.dom?.bbox??{x:0,y:0,w:0,h:0},D=I.dom?.type??null,C=null;I.ax.value!==void 0&&I.ax.value!==null&&(C=String(I.ax.value)),I.ax.checked!==void 0&&(C=String(I.ax.checked)),hT({role:N,kind:D})&&(C="[redacted]");let B={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(B.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(B.selected=I.ax.selected),I.ax.expanded!==void 0&&(B.expanded=I.ax.expanded);let M;I.dom?.testId?M=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(M=`#${I.dom.id}`);let j={id:U,role:N,label:MW(F),kind:D,value:C,state:B,bbox:H};return M!==void 0&&(j.selector=M),j}),A="idle";try{let I=await e.evaluate(()=>document.readyState);I==="loading"?A="loading":I==="interactive"?A="navigating":A="idle"}catch{A="navigating"}A!=="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 E=$W(m),O=`obs_${t.observationCounter.toString(36)}`,_=new Date().toISOString();return{observationId:O,url:g,title:h,textSummary:E,interactive:R,status:{httpStatus:t.httpStatus??null,loadingState:A,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:_}}var ST,kT,ET=P(()=>{"use strict";Va();ST=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);kT="a[href], button, input, select, textarea, [role], [tabindex], label"});async function TT(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 vh(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,s)=>TT(e,s)))).filter(o=>o!==null)}async function NW(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 kh(e,t,n){switch(t.kind){case"element_id":return BW(e,t,n);case"selector":return UW(e,t);case"semantic":return jW(e,t)}}async function BW(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 vh(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function UW(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 vh(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function jW(e,t){return t.role!==void 0?HW(e,t.text,t.role):WW(e,t.text,t)}async function HW(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 vh(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:s}}async function WW(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 NW(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 TT(b.locator,b.index);if(y!==null){let S=`${y.role}:${y.label}:${h}`,w=0;for(let k=0;k<S.length;k++)w=w*31+S.charCodeAt(k)>>>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 xT=P(()=>{"use strict"});import{randomBytes as KW}from"crypto";import{mkdir as GW,stat as qW,writeFile as zW}from"fs/promises";import{join as Eh}from"path";import{gzip as JW}from"zlib";import{promisify as VW}from"util";function YW(e){return Eh(As(e),"browser")}function XW(e){return Eh(YW(e),"screenshots")}function ZW(){return new Date().toISOString().replace(/[:.]/g,"-")}function QW(){return KW(3).toString("hex")}async function Th(e,t,n){if(t.length>RT)throw new Error(`writeScreenshotSidecar: buffer exceeds ${RT} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=XW(e);await GW(r,{recursive:!0});let o=`${ZW()}-${QW()}-${n}.png`,s=Eh(r,o);await zW(s,t);let{size:i}=await qW(s);return{path:s,bytes:i}}var Qde,RT,CT=P(()=>{"use strict";K();Va();Qde=VW(JW);RT=5*1024*1024});var _T={};Rc(_T,{PlaywrightProvider:()=>xh});function AT(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 xh,PT=P(()=>{"use strict";gT();ET();xT();wh();Va();CT();xh=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Bu(t)}async open(t){let n=bh(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 Uu(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 Uu(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 kh(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${AT(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=Sh(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=bh(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 Uu(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 kh(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${AT(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 Th(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 Th(n,o,r);return s}catch{return null}}}});var Fo={};Rc(Fo,{__resetBrowserRegistryForTests:()=>oK,browserProviderActive:()=>nK,closeBrowserProvider:()=>Rh,getBrowserProvider:()=>tK,peekBrowserProvider:()=>rK});function IT(){Promise.resolve(Rh()).then(()=>{process.exit(130)})}function MT(){Promise.resolve(Rh()).then(()=>{process.exit(143)})}function OT(){_n=null}function eK(){ju||(process.on("SIGINT",IT),process.on("SIGTERM",MT),process.on("exit",OT),ju=!0)}function $T(){ju&&(process.removeListener("SIGINT",IT),process.removeListener("SIGTERM",MT),process.removeListener("exit",OT),ju=!1)}async function tK(e){return _n!==null?_n:(Do!==null||(Do=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(PT(),_T)),n=fT(e),r=new t(n);return eK(),_n=r,Do=null,r})()),Do)}async function Rh(){if(_n===null)return;let e=_n;_n=null,Do=null,$T(),await e.shutdown()}function nK(){return _n!==null}function rK(){return _n}function oK(){_n=null,Do=null,$T()}var _n,Do,ju,Lo=P(()=>{"use strict";wh();_n=null,Do=null,ju=!1});function DT(e,t){try{return lT(e,t)}catch(n){return W("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function cK(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Lo(),Fo));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function FT(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??cK,o=null,s=e,i=null,a=null;try{let c=await Lu(n,e,{headers:lK,redirect:"follow",signal:t.signal});i=c.status,s=c.url||e;let u=c.headers.get("content-type")??"";if(c.ok){if(aK.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(iK.test(u)&&!sK.test(u))return{title:"",markdown:d.trim(),finalUrl:s,usedRender:!1};o=DT(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<aT)&&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=DT(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 sK,iK,aK,lK,LT=P(()=>{"use strict";cT();yh();Pe();sK=/(text\/html|application\/xhtml\+xml)/i,iK=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,aK=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,lK={"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 pK(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await t(uK,{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),dK),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let u=await s.text(),d=Mo(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 NT(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?pK({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 BT(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
1081
|
+
`).trim()}function uW(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function lT(e,t){let r=new aW(e,{url:t}).window.document,o=(r.title??"").trim(),s=null;try{let c=r.cloneNode(!0);s=new lW(c).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let c=iT(hh.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=iT(hh.turndown(a));return{title:o,markdown:l,textLength:uW(i),usedFallback:!0}}var aT,hh,cT=P(()=>{"use strict";aT=200,hh=new cW({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});hh.remove(["script","style","noscript","iframe"])});function pW(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(t?.reason??new Error("aborted"))},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})})}function uT(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function mW(e,t){let n=e.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,t)}async function Lu(e,t,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??pW,l=n.signal??void 0,c;for(let u=0;u<=o;u++){if(l?.aborted)throw l.reason??new Error("aborted");try{let d=await e(t,n);if(!dW.has(d.status)||u===o)return d;let p=mW(d,i)??uT(u,s,i);W("[web/retryFetch] retrying",{url:t,attempt:u,status:d.status,waitMs:p}),await d.body?.cancel().catch(()=>{}),await a(p,l)}catch(d){if(l?.aborted||(c=d,u===o))throw d;let p=uT(u,s,i);W("[web/retryFetch] retrying after error",{url:t,attempt:u,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var dW,yh=P(()=>{"use strict";Pe();dW=new Set([429,502,503,504])});import{readFileSync as fW}from"node:fs";import{join as gW}from"path";function hW(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function dT(e,t){return hW(t).test(e)}function wW(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(yW.has(t))return!0;if(bW.has(t))return!1}return!1}function pT(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function SW(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 mT(e){let t=e===void 0||e.trim()===""?"default":e.trim();return Ca(t),t}function vW(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function kW(e){try{return fW(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function EW(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 typeof t.defaultProfile=="string"&&(n.defaultProfile=mT(t.defaultProfile)),n}function fT(e){let t=e?.env??v,n=e?.readFileSync??kW,r=e?.surface??t.AGENT_SURFACE,o=wW(t.AFK_BROWSER_HEADLESS,r),s=pT(t.AFK_BROWSER_ALLOWED_DOMAINS),i=pT(t.AFK_BROWSER_BLOCKED_DOMAINS),a=vW(t.AFK_BROWSER_DOM_SNAPSHOTS),l=SW(t.AFK_BROWSER_BACKEND),c=mT(t.AFK_BROWSER_DEFAULT_PROFILE),u={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},d=t.AFK_BROWSER_CONFIG,p=d!==void 0&&d.trim()!==""?d.trim():gW(rn(),"browser.json"),m=n(p);if(m===void 0)return u;let g;try{g=JSON.parse(m)}catch(b){throw new Error(`Failed to parse browser config at ${p}: ${String(b)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${p} must be a JSON object`);let h=EW(u,g);return h.configPath=p,h}function bh(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(dT(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>dT(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var yW,bW,wh=P(()=>{"use strict";J();K();yW=new Set(["daemon","subagent","telegram","afk"]),bW=new Set(["repl","interactive","cli"])});import $o from"node:fs";import Nu from"node:path";import{randomBytes as TW}from"node:crypto";import{chromium as xW}from"playwright";function RW(){try{return"5.14.0"}catch{}try{let e=Nu.resolve(import.meta.dirname,"../../../package.json"),t=$o.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var CW,Bu,gT=P(()=>{"use strict";K();Pe();CW=RW(),Bu=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=xW.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 r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,i),s}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),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let 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/${CW}`}}loadStorageState(t){let n=Aa(t);try{if(!$o.existsSync(n))return;let r=JSON.parse($o.readFileSync(n,"utf8"));return W("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){W("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Aa(t);if(!$o.existsSync(r))return;let o=await n.storageState(),s=Nu.join(Nu.dirname(r),`.${Nu.basename(r)}.${process.pid}.${TW(4).toString("hex")}.tmp`);$o.writeFileSync(s,JSON.stringify(o),{mode:384}),$o.chmodSync(s,384),$o.renameSync(s,r),W("[browser/vault] saved session",{profile:t,file:r})}catch(r){W("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as AW}from"crypto";function Sh(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of _W)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function hT(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&PW.test(e.label))}function yT(e){return AW("sha256").update(e,"utf8").digest("hex").slice(0,8)}function bT(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var _W,PW,Va=P(()=>{"use strict";_W=[{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}];PW=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as IW}from"node:crypto";function MW(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function OW(e,t,n){return`el_${IW("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function $W(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function wT(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function vT(e,t){let n=e.role??"",r=e.name??"";ST.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let s of e.children??[])vT(s,t)}async function DW(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},kT).catch(()=>[])}async function FW(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},kT).catch(()=>[])}function LW(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Uu(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],s=LW(e),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=DW(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=[],vT(d,b)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,b=(await FW(e)).filter(L=>ST.has(L.role??"")));let S=new Map;for(let I of p){let L=wT(I.name),N=S.get(L);(!N||N.bbox.w===0&&I.bbox.w>0)&&S.set(L,I)}let w=b.map(I=>({ax:I,dom:S.get(wT(I.name??""))})),k=r?w:w.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);k.sort((I,L)=>{let N=I.dom?.bbox.y??0,F=L.dom?.bbox.y??0;if(N!==F)return N-F;let U=I.dom?.bbox.x??0,H=L.dom?.bbox.x??0;return U-H}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=k.slice(0,n).map((I,L)=>{let N=I.ax.role??"generic",F=I.ax.name??"",U=OW(N,F,L),H=I.dom?.bbox??{x:0,y:0,w:0,h:0},D=I.dom?.type??null,C=null;I.ax.value!==void 0&&I.ax.value!==null&&(C=String(I.ax.value)),I.ax.checked!==void 0&&(C=String(I.ax.checked)),hT({role:N,kind:D})&&(C="[redacted]");let B={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(B.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(B.selected=I.ax.selected),I.ax.expanded!==void 0&&(B.expanded=I.ax.expanded);let M;I.dom?.testId?M=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(M=`#${I.dom.id}`);let j={id:U,role:N,label:MW(F),kind:D,value:C,state:B,bbox:H};return M!==void 0&&(j.selector=M),j}),A="idle";try{let I=await e.evaluate(()=>document.readyState);I==="loading"?A="loading":I==="interactive"?A="navigating":A="idle"}catch{A="navigating"}A!=="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 E=$W(m),O=`obs_${t.observationCounter.toString(36)}`,_=new Date().toISOString();return{observationId:O,url:g,title:h,textSummary:E,interactive:R,status:{httpStatus:t.httpStatus??null,loadingState:A,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:_}}var ST,kT,ET=P(()=>{"use strict";Va();ST=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);kT="a[href], button, input, select, textarea, [role], [tabindex], label"});async function TT(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 vh(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,s)=>TT(e,s)))).filter(o=>o!==null)}async function NW(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 kh(e,t,n){switch(t.kind){case"element_id":return BW(e,t,n);case"selector":return UW(e,t);case"semantic":return jW(e,t)}}async function BW(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 vh(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function UW(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 vh(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function jW(e,t){return t.role!==void 0?HW(e,t.text,t.role):WW(e,t.text,t)}async function HW(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 vh(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:s}}async function WW(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 NW(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 TT(b.locator,b.index);if(y!==null){let S=`${y.role}:${y.label}:${h}`,w=0;for(let k=0;k<S.length;k++)w=w*31+S.charCodeAt(k)>>>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 xT=P(()=>{"use strict"});import{randomBytes as KW}from"crypto";import{mkdir as GW,stat as qW,writeFile as zW}from"fs/promises";import{join as Eh}from"path";import{gzip as JW}from"zlib";import{promisify as VW}from"util";function YW(e){return Eh(As(e),"browser")}function XW(e){return Eh(YW(e),"screenshots")}function ZW(){return new Date().toISOString().replace(/[:.]/g,"-")}function QW(){return KW(3).toString("hex")}async function Th(e,t,n){if(t.length>RT)throw new Error(`writeScreenshotSidecar: buffer exceeds ${RT} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=XW(e);await GW(r,{recursive:!0});let o=`${ZW()}-${QW()}-${n}.png`,s=Eh(r,o);await zW(s,t);let{size:i}=await qW(s);return{path:s,bytes:i}}var Qde,RT,CT=P(()=>{"use strict";K();Va();Qde=VW(JW);RT=5*1024*1024});var _T={};Rc(_T,{PlaywrightProvider:()=>xh});function AT(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 xh,PT=P(()=>{"use strict";gT();ET();xT();wh();Va();CT();xh=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Bu(t)}async open(t){let n=bh(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 Uu(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 Uu(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 kh(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${AT(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=Sh(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=bh(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 Uu(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 kh(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${AT(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 Th(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 Th(n,o,r);return s}catch{return null}}}});var Fo={};Rc(Fo,{__resetBrowserRegistryForTests:()=>oK,browserProviderActive:()=>nK,closeBrowserProvider:()=>Rh,getBrowserProvider:()=>tK,peekBrowserProvider:()=>rK});function IT(){Promise.resolve(Rh()).then(()=>{process.exit(130)})}function MT(){Promise.resolve(Rh()).then(()=>{process.exit(143)})}function OT(){_n=null}function eK(){ju||(process.on("SIGINT",IT),process.on("SIGTERM",MT),process.on("exit",OT),ju=!0)}function $T(){ju&&(process.removeListener("SIGINT",IT),process.removeListener("SIGTERM",MT),process.removeListener("exit",OT),ju=!1)}async function tK(e){return _n!==null?_n:(Do!==null||(Do=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(PT(),_T)),n=fT(e),r=new t(n);return eK(),_n=r,Do=null,r})()),Do)}async function Rh(){if(_n===null)return;let e=_n;_n=null,Do=null,$T(),await e.shutdown()}function nK(){return _n!==null}function rK(){return _n}function oK(){_n=null,Do=null,$T()}var _n,Do,ju,Lo=P(()=>{"use strict";wh();_n=null,Do=null,ju=!1});function DT(e,t){try{return lT(e,t)}catch(n){return W("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function cK(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Lo(),Fo));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function FT(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??cK,o=null,s=e,i=null,a=null;try{let c=await Lu(n,e,{headers:lK,redirect:"follow",signal:t.signal});i=c.status,s=c.url||e;let u=c.headers.get("content-type")??"";if(c.ok){if(aK.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(iK.test(u)&&!sK.test(u))return{title:"",markdown:d.trim(),finalUrl:s,usedRender:!1};o=DT(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<aT)&&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=DT(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 sK,iK,aK,lK,LT=P(()=>{"use strict";cT();yh();Pe();sK=/(text\/html|application\/xhtml\+xml)/i,iK=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,aK=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,lK={"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 pK(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await t(uK,{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),dK),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let u=await s.text(),d=Mo(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 NT(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?pK({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 BT(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 uK,dK,UT=P(()=>{"use strict";Oo();uK="https://api.exa.ai/search",dK=10});function SK(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=mK;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,fK)}let a=gK;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,hK)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Ch(e,t){let n=Buffer.from(e,"utf8");return n.byteLength<=t?e:n.subarray(0,t).toString("utf8")+yK}function vK(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 wK.some(o=>r.includes(o))}function kK(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=SK(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 Lu(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:Ch(p,s.maxBytes)}}if(s.mode==="markdown")try{let d=await FT(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:Ch(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=vK(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=NT({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:bK,timeoutMs:s.timeoutMs,signal:i.signal});return{content:Ch(BT(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 mK,fK,gK,hK,yK,bK,wK,jT,HT=P(()=>{"use strict";LT();UT();yh();mK=3e4,fK=12e4,gK=1e6,hK=1e7,yK=`
|
|
@@ -1097,8 +1097,8 @@ ${o}`;return s.includes("already checked out")||s.includes("is already used by w
|
|
|
1097
1097
|
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s<=0)continue;let i=o.slice(0,s).trim(),a=o.slice(s+1);t[i]=a}return t}var Ju=P(()=>{"use strict"});function ti(e){let t=Cc(e);return t?YK.has(e)?"non-config":t.secret?"secret":XK.has(e)||e.endsWith("_BASE_URL")?"protected":"settable":"unknown"}function rx(e,t){if(t.includes(`
|
|
1098
1098
|
`))return{ok:!1,error:`value for ${e.name} must not contain newlines`};switch(e.type){case"number":{let n=Number(t);return Number.isFinite(n)?{ok:!0,value:t.trim()}:{ok:!1,error:`${e.name} expects a number, got ${JSON.stringify(t)}`}}case"boolean":{let n=t.trim().toLowerCase();return["true","false","1","0","yes","no","on","off"].includes(n)?{ok:!0,value:n}:{ok:!1,error:`${e.name} expects a boolean (true/false/1/0/yes/no/on/off), got ${JSON.stringify(t)}`}}case"json":{try{JSON.parse(t)}catch{return{ok:!1,error:`${e.name} expects valid JSON`}}return{ok:!0,value:t}}default:return{ok:!0,value:t}}}function sx(e){return ox.get(e)}function Dh(e){let t=ox.get(e);return t?t.tier:"unknown"}function ix(e,t){switch(e.type){case"boolean":{if(typeof t=="boolean")return{ok:!0,value:t};if(typeof t=="string"){let n=t.trim().toLowerCase();if(["true","1","yes","on"].includes(n))return{ok:!0,value:!0};if(["false","0","no","off"].includes(n))return{ok:!0,value:!1}}return{ok:!1,error:`${e.path} expects a boolean`}}case"number":{let n=typeof t=="number"?t:typeof t=="string"?Number(t):NaN;return Number.isFinite(n)?e.clamp?e.clamp.integer&&!Number.isInteger(n)?{ok:!1,error:`${e.path} expects an integer`}:{ok:!0,value:Math.min(e.clamp.max,Math.max(e.clamp.min,n))}:{ok:!0,value:n}:{ok:!1,error:`${e.path} expects a number`}}case"enum":return typeof t=="string"&&e.enumValues?.includes(t)?{ok:!0,value:t}:{ok:!1,error:`${e.path} expects one of: ${e.enumValues?.join(", ")}`};case"number-array":{let n;if(Array.isArray(t))n=t;else if(typeof t=="string")n=t.split(",").map(o=>o.trim()).filter(o=>o.length>0).map(o=>Number(o));else return{ok:!1,error:`${e.path} expects an array of numbers`};let r=[];for(let o of n){let s=typeof o=="number"?o:Number(o);if(!Number.isFinite(s))return{ok:!1,error:`${e.path} contains a non-number`};r.push(s)}return{ok:!0,value:r}}default:return typeof t!="string"?{ok:!1,error:`${e.path} expects a string`}:t.trim().length===0?{ok:!1,error:`${e.path} must not be empty`}:{ok:!0,value:t}}}function ax(e,t){let n=e;for(let r of t.split(".")){if(n===null||typeof n!="object")return;n=n[r]}return n}function lx(e,t,n){let r=t.split("."),o=e;for(let s=0;s<r.length-1;s++){let i=r[s],a=o[i];(a===null||typeof a!="object"||Array.isArray(a))&&(o[i]={}),o=o[i]}o[r[r.length-1]]=n}function cx(e,t){let n=t.split("."),r=[e],o=e;for(let i=0;i<n.length-1;i++){let a=n[i],l=o[a];if(l===null||typeof l!="object"||Array.isArray(l))return!1;o=l,r.push(o)}let s=n[n.length-1];if(!(s in o))return!1;delete o[s];for(let i=r.length-1;i>=1;i--){let a=r[i];if(Object.keys(a).length===0){let l=n[i-1];delete r[i-1][l]}else break}return!0}var YK,XK,ZK,ox,Fh=P(()=>{"use strict";J();YK=new Set(["HOME","PATH","SHELL","PAGER","NODE_ENV","CI","VITEST","DEBUG","FORCE_COLOR","NO_COLOR","AGENT_SURFACE","AFK_SESSION_ID","NO_UPDATE_NOTIFIER","SCRIPT","ASCIINEMA_REC"]),XK=new Set(["AFK_MODEL_SMALL_BASE_URL","AFK_MODEL_MEDIUM_BASE_URL","AFK_MODEL_LARGE_BASE_URL","AFK_LOCAL_BASE_URL","AFK_OPENAI_BASE_URL","AFK_SYSTEM_PROMPT","AFK_DAEMON_TASK","AFK_DAEMON_TASK_ID","AFK_DAEMON_CWD","AFK_DAEMON_HOST","AFK_BROWSER_ALLOWED_DOMAINS","AFK_BROWSER_BLOCKED_DOMAINS","AFK_BROWSER_CONFIG","AFK_ALLOW_PROJECT_MCP","AFK_INTERNAL","AFK_WORKTREE_BASE","AFK_WORKTREE_BRANCH_PREFIX","AFK_TELEGRAM_ALLOWED_CHAT_IDS","AFK_TELEGRAM_NOTIFY_MODE","AFK_TELEGRAM_PRIMARY_CHAT_ID","AFK_HOME","AFK_STATE_DIR","AFK_FRAMEWORK_DIR","TELEGRAM_DATA_DIR","AFK_TELEGRAM_CWD"]);ZK=[{path:"model",tier:"agent",type:"string",description:"Default model id / alias."},{path:"models.local",tier:"agent",type:"string",description:"Local-tier model id (OpenAI-compatible shim: Ollama, LM Studio, vLLM, MLX)."},{path:"models.small",tier:"agent",type:"string",description:"Small-tier model id."},{path:"models.medium",tier:"agent",type:"string",description:"Medium-tier model id."},{path:"models.large",tier:"agent",type:"string",description:"Large-tier model id."},{path:"maxTokens",tier:"agent",type:"number",clamp:{min:1,max:1e6,integer:!0},description:"Max tokens per turn."},{path:"temperature",tier:"agent",type:"number",clamp:{min:0,max:2},description:"Sampling temperature."},{path:"autoRouting.interactive",tier:"agent",type:"boolean",description:"Auto-route model in the REPL."},{path:"autoRouting.chat",tier:"agent",type:"boolean",description:"Auto-route model for chat."},{path:"autoRouting.telegram",tier:"agent",type:"boolean",description:"Auto-route model for Telegram."},{path:"autoRouting.daemon",tier:"agent",type:"boolean",description:"Auto-route model for the daemon."},{path:"telegram.notify.mode",tier:"human",type:"enum",enumValues:["primary","broadcast","custom"],description:"Telegram notify routing mode (human-tier: notification-redirect vector)."},{path:"telegram.notify.primaryChatId",tier:"human",type:"number",clamp:{min:-1e15,max:1e15,integer:!0},description:"Primary Telegram chat id (human-tier: notification-redirect vector)."},{path:"telegram.notify.targets",tier:"human",type:"number-array",description:"Custom Telegram target chat ids (human-tier: notification-redirect vector)."},{path:"telegram.verifyDone",tier:"human",type:"boolean",description:`Opt-in AFK "Done" verification gate (human-tier: a self-honesty check on the agent's own completion reporting \u2014 the agent must not be able to disable it on its own config, same rationale as enableShellHooks/permissionMode).`},{path:"interactive.worktreeAutoname",tier:"agent",type:"boolean",description:"Auto-name worktrees."},{path:"interactive.suggestGhost",tier:"agent",type:"boolean",description:"Ghost-text suggestions in the REPL."},{path:"updatePolicy",tier:"human",type:"enum",enumValues:["notify","auto","off"],description:"Self-update policy (human-tier: auto self-update is scope-widening)."},{path:"autoResumeOnUsageLimit",tier:"agent",type:"boolean",description:"Auto-resume after a usage-limit pause."},{path:"bgSummaries",tier:"agent",type:"boolean",description:"Background summarisation."},{path:"maxSummaryCallsPerSession",tier:"agent",type:"number",clamp:{min:1,max:500,integer:!0},description:"Cap on summary calls per session."},{path:"systemPrompt",tier:"human",type:"string",description:"Operator system-prompt overlay."},{path:"permissionMode",tier:"human",type:"enum",enumValues:["default","plan","autonomous","bypassPermissions"],description:"Session permission mode for afk chat/interactive (human-tier: privilege-escalation vector). Unset \u2192 bypassPermissions (new-install default); set `default` to re-enable path containment + the approval prompt."},{path:"enableShellHooks",tier:"human",type:"boolean",description:"Enable shell hooks (trust gate)."},{path:"interactive.worktreeBranchPrefix",tier:"human",type:"string",description:"Worktree branch prefix (git-flag sensitive)."},{path:"interactive.worktreeBase",tier:"human",type:"string",description:"Worktree base ref (git-flag sensitive)."},{path:"daemon.task",tier:"human",type:"string",description:"Daemon task prompt."},{path:"daemon.taskId",tier:"human",type:"string",description:"Daemon task id."}],ox=new Map(ZK.map(e=>[e.path,e]))});import{existsSync as ux,readFileSync as QK,copyFileSync as eG,chmodSync as tG}from"fs";function jh(e){return e===void 0||e.length===0?"<unset>":e.length<=4?"set (****)":`set (****${e.slice(-4)})`}function Xu(e){return e?.filePath??St()}function dx(e,t,n){let r=ti(e);if(r==="unknown")throw new Za(e);if(r==="non-config")throw new Lh(e);if(r==="secret"&&!t)throw new Nh(e);if(r==="protected"&&!n)throw new Bh(e);return r}function Zu(e,t,n){let r=dx(e,n?.allowSecret,n?.allowProtected),o=Cc(e),s=rx(o,t);if(!s.ok)throw new Vu(s.error);let i=Xu(n);return un(i,e,s.value),{key:e,class:r,persistedTo:i,display:r==="secret"?jh(s.value):s.value}}function Qu(e,t){let n=dx(e,t?.allowSecret,t?.allowProtected),r=Xu(t),o=ex(r,e);return{key:e,class:n,removed:o,persistedTo:r}}function ed(e,t){let n=ti(e);if(n==="unknown")throw new Za(e);let r=Xu(t),o=tx(r,e),s=Wf(e),i=n==="secret"?o!==void 0?jh(o):void 0:o;return{key:e,class:n,persisted:i,activeInProcess:s}}function td(e){let t=Xu(e),n=nx(t),r=[];for(let o of va){let s=o.name,i=ti(s),a=n[s],l=Wf(s);if(!e?.all&&a===void 0&&!l)continue;let c=i==="secret"?a!==void 0?jh(a):void 0:a;r.push({key:s,class:i,persisted:c,activeInProcess:l})}return r}function nd(e){return e?.filePath??Kt()}function rd(e){if(!ux(e))return{};let t;try{t=JSON.parse(QK(e,"utf-8"))}catch{throw new Yu(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Yu(e);return t}function px(e,t){if(ux(e))try{eG(e,`${e}.bak`),tG(`${e}.bak`,384)}catch{}zu(e,JSON.stringify(t,null,2)+`
|
|
1099
1099
|
`,384)}function mx(e,t){let n=Dh(e);if(n==="unknown")throw new Za(e);if(n==="human"&&!t)throw new Uh(e);return n}function od(e,t,n){let r=mx(e,n?.allowHumanOnly),o=sx(e),s=ix(o,t);if(!s.ok)throw new Vu(s.error);let i=nd(n),a=rd(i);return lx(a,e,s.value),px(i,a),{path:e,class:r,value:s.value,persistedTo:i}}function sd(e,t){let n=mx(e,t?.allowHumanOnly),r=nd(t),o=rd(r),s=cx(o,e);return s&&px(r,o),{path:e,class:n,removed:s,persistedTo:r}}function id(e,t){let n=Dh(e),r=nd(t),o=rd(r);return{path:e,class:n,value:ax(o,e)}}function ad(e){return rd(nd(e))}var Ur,Za,Lh,Nh,Bh,Uh,Vu,Yu,Hh=P(()=>{"use strict";K();J();Ju();Fh();Ur="effective on the next session/daemon restart; the current session is unchanged",Za=class extends Error{constructor(t){super(`unknown config key: ${t}`),this.name="UnknownKeyError"}},Lh=class extends Error{constructor(t){super(`${t} is a process/inherited env var and is not afk-configurable`),this.name="NonConfigKeyError"}},Nh=class extends Error{constructor(t){super(`${t} holds a credential; the agent cannot set it. A human must run \`afk config env set ${t}\` (the value is entered masked and never enters the model context).`),this.name="SecretWriteRefused"}},Bh=class extends Error{constructor(t){super(`${t} controls identity, safety, capability, autonomous runs, request routing, or where AFK's own state lives; the agent cannot set it. A human must run \`afk config env set ${t}\`.`),this.name="ProtectedEnvKeyRefused"}},Uh=class extends Error{constructor(t){super(`${t} is human-gated (prompt/hooks/identity); the agent cannot set it. A human must run \`afk config set ${t}\`.`),this.name="HumanOnlyKeyRefused"}},Vu=class extends Error{constructor(t){super(t),this.name="ConfigValidationError"}},Yu=class extends Error{constructor(t){super(`refusing to write: existing ${t} is not valid JSON (fix or remove it by hand first)`),this.name="MalformedConfigError"}}});function fx(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function gx(e){return e==="env"||e==="config"?e:void 0}function dr(e){return{content:e,isError:!0}}var hx,yx,bx=P(()=>{"use strict";Hh();hx=async e=>{let t=fx(e);if(!t)return dr("config_get: expected an object input");let n=gx(t.target);if(!n)return dr("config_get: `target` must be 'env' or 'config'");let r=typeof t.key=="string"?t.key:void 0,o=t.all===!0;try{if(n==="env"){if(r){let s=ed(r);return{content:JSON.stringify(s,null,2)}}return{content:JSON.stringify(td({all:o}),null,2)}}if(r){let s=id(r);return{content:JSON.stringify(s,null,2)}}return{content:JSON.stringify(ad(),null,2)}}catch(s){return dr(`config_get: ${s.message}`)}},yx=async e=>{let t=fx(e);if(!t)return dr("config_set: expected an object input");let n=gx(t.target);if(!n)return dr("config_set: `target` must be 'env' or 'config'");let r=typeof t.key=="string"?t.key:void 0;if(!r)return dr("config_set: `key` is required");let o=t.action==="unset"?"unset":"set",s=t.value;try{if(o==="unset"){if(n==="env"){let l=Qu(r);return{content:l.removed?`Removed ${l.key} from afk.env (${l.persistedTo}). ${Ur}.`:`${l.key} was not set in afk.env; nothing to remove.`}}let a=sd(r);return{content:a.removed?`Removed ${a.path} from afk.config.json (${a.persistedTo}). ${Ur}.`:`${a.path} was not set in afk.config.json; nothing to remove.`}}if(s==null)return dr(`config_set: \`value\` is required to set ${r}`);if(n==="env"){if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")return dr("config_set: env values must be a string, number, or boolean");let a=Zu(r,String(s));return{content:`Set ${a.key} = ${a.display} in afk.env (${a.persistedTo}). ${Ur}.`}}let i=od(r,s);return{content:`Set ${i.path} = ${JSON.stringify(i.value)} in afk.config.json (${i.persistedTo}). ${Ur}.`}}catch(i){return dr(`config_set: ${i.message}`)}}});function nG(e){return e.length<=wx?e:`${e.slice(0,wx)}\u2026(truncated)`}function rG(e){try{let n=[`\u{1F514} AFK needs you \u2014 stuck on: ${e.title??e.serverName}`,nG(e.message)];e.url!==void 0&&e.url!==""&&n.push(e.url),An(n.join(`
|
|
1100
|
-
`)).catch(()=>{})}catch{}}var ni,wx,Wh,pt,jr=P(()=>{"use strict";Nr();ni={action:"decline"},wx=300;Wh=class{handler=null;queue=Promise.resolve();queueDepth=0;install(t){this.handler=t}uninstall(){this.handler=null}pendingCount(){return this.queueDepth}route(t,n){if(n.signal.aborted)return Promise.resolve(ni);this.queueDepth+=1;let r,o=new Promise(i=>{r=i}),s=this.handler;return this.queue=this.queue.then(async()=>{try{if(n.signal.aborted){r(ni);return}if(!s){rG(t),r(ni);return}let i,a=new Promise(l=>{i=()=>l(ni),n.signal.addEventListener("abort",i,{once:!0})});try{try{n.onActive?.()}catch{}let l=await Promise.race([s(t,n).catch(()=>ni),a]);r(l)}finally{n.signal.removeEventListener("abort",i)}}finally{this.queueDepth-=1,r(ni)}}).catch(()=>{}),o}},pt=new Wh});var Sx,vx=P(()=>{"use strict";jr();Sx=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let n=e,r=n.question;if(typeof r!="string"||r.trim()==="")return{content:"Invalid input: question must be a non-empty string",isError:!0};let o=new Set(["text","confirm","choice","multi_choice","number"]),s=n.type??"text";if(typeof s!="string"||!o.has(s))return{content:"Invalid input: type must be one of: text, confirm, choice, multi_choice, number",isError:!0};if(s==="choice"||s==="multi_choice"){let m=n.choices;if(!Array.isArray(m)||m.length===0)return{content:`Invalid input: choices array is required and must be non-empty for type "${s}"`,isError:!0};if(m.length>100)return{content:`Invalid input: choices array must not exceed 100 items, got ${m.length}`,isError:!0};for(let g of m)if(typeof g!="string")return{content:"Invalid input: all choices must be strings",isError:!0}}let i=n.min,a=n.max;if(i!==void 0&&(typeof i!="number"||!Number.isFinite(i)))return{content:"Invalid input: min must be a finite number",isError:!0};if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)))return{content:"Invalid input: max must be a finite number",isError:!0};if(i!==void 0&&a!==void 0&&i>a)return{content:`Invalid input: min (${i}) must be \u2264 max (${a})`,isError:!0};let l=n.min_length,c=n.max_length;if(l!==void 0&&typeof l!="number")return{content:"Invalid input: min_length must be a number",isError:!0};if(c!==void 0&&typeof c!="number")return{content:"Invalid input: max_length must be a number",isError:!0};if((l!==void 0||c!==void 0)&&s!=="text")return{content:`Invalid input: min_length/max_length are only valid for type "text", got "${s}"`,isError:!0};if(n.allow_custom!==void 0&&s!=="choice"&&s!=="multi_choice")return{content:`Invalid input: allow_custom is only valid for type "choice" or "multi_choice", got "${s}"`,isError:!0};let u={serverName:"agent",message:r.trim(),origin:"agent",type:s,...n.choices!==void 0&&{choices:n.choices},...n.context!==void 0&&typeof n.context=="string"&&{context:n.context},...n.default!==void 0&&{questionDefault:n.default},...l!==void 0&&{minLength:l},...c!==void 0&&{maxLength:c},...i!==void 0&&{min:i},...a!==void 0&&{max:a},...n.allow_skip!==void 0&&{allowSkip:!!n.allow_skip},...n.allow_custom!==void 0&&{allowCustom:!!n.allow_custom}},d=await pt.route(u,{signal:t}),p=d.action==="decline"||d.action==="cancel";return{content:JSON.stringify(d),...p&&{isError:!0,failureClass:"elicitation-declined"}}}});function ld(e){if(e instanceof Error&&e.name==="TimeoutError")return"timeout";let t=e instanceof Error?e.message:String(e);return/Timeout\s+\d+\s*ms exceeded/i.test(t)?"timeout":void 0}function Pn(e){return oG.some(t=>e.includes(t))}function In(e){return e.includes("Executable doesn't exist")?"browser tools require the Playwright chromium binary. Install via: pnpm exec playwright install chromium.":"browser tools require the optional `playwright` peer dependency. Install via: pnpm add playwright (then pnpm exec playwright install chromium). Or pick a different tool."}var oG,ri=P(()=>{"use strict";oG=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"]});function sG(e){if(!e||typeof e!="object")return{error:"browser_open: input must be an object"};let t=e,n=t.url;if(typeof n!="string"||n.length===0)return{error:'browser_open: "url" is required and must be a non-empty string'};let r;try{r=new URL(n)}catch{return{error:`browser_open: "${n}" is not a valid absolute URL`}}if(r.protocol!=="http:"&&r.protocol!=="https:")return{error:`browser_open: protocol "${r.protocol}" is not supported (http/https only)`};let o;if(t.wait_for!==void 0){if(!kx.includes(t.wait_for))return{error:`browser_open: "wait_for" must be one of ${kx.map(a=>`"${a}"`).join(", ")} (got ${JSON.stringify(t.wait_for)})`};o=t.wait_for}let s;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_open: "screenshot" must be a boolean'};s=t.screenshot}let i;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:'browser_open: "timeout_ms" must be a positive finite number'};i=t.timeout_ms}return{url:r.toString(),waitFor:o,screenshot:s,timeoutMs:i}}function iG(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_open aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0,failureClass:"abort"}}let o=sG(t);if("error"in o)return{content:o.error,isError:!0};let s=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i;try{if(e.getBrowserProvider)i=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(Lo(),Fo));i=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Pn(c)?{content:In(c),isError:!0}:{content:`browser_open failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await i.open({sessionId:s,url:o.url,waitFor:o.waitFor,screenshot:o.screenshot,timeoutMs:o.timeoutMs}),c=Date.now()-a;if("outcome"in l&&l.outcome==="blocked_by_policy")return st(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:c}),{content:`browser_open blocked: ${l.reason}`,isError:!0,failureClass:"policy-refusal"};let u=l;return st(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:u.url,status:"ok",durationMs:c,...u.screenshotPath!==null?{screenshotPath:u.screenshotPath}:{}}),{content:JSON.stringify(u,null,2)}}catch(l){let c=Date.now()-a,u=l instanceof Error?l.message:String(l);st(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:u,recoverable:!1}});let d=ld(l);return{content:`browser_open failed: ${u}`,isError:!0,...d?{failureClass:d}:{}}}}}var kx,Ex,Tx=P(()=>{"use strict";J();He();ri();kx=["load","domcontentloaded","networkidle"];Ex=iG()});function aG(e){if(e!=null&&typeof e!="object")return{error:"browser_observe: input must be an object or omitted"};if(!e)return{};let t=e,n;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_observe: "screenshot" must be a boolean'};n=t.screenshot}let r;if(t.include_hidden!==void 0){if(typeof t.include_hidden!="boolean")return{error:'browser_observe: "include_hidden" must be a boolean'};r=t.include_hidden}let o;if(t.max_elements!==void 0){if(typeof t.max_elements!="number"||!Number.isFinite(t.max_elements)||t.max_elements<=0||!Number.isInteger(t.max_elements))return{error:'browser_observe: "max_elements" must be a positive integer'};o=t.max_elements}return{screenshot:n,includeHidden:r,maxElements:o}}function lG(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_observe aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=aG(t);if("error"in o)return{content:o.error,isError:!0};let s=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i;try{if(e.getBrowserProvider)i=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(Lo(),Fo));i=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Pn(c)?{content:In(c),isError:!0}:{content:`browser_observe failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await i.observe({sessionId:s,screenshot:o.screenshot,includeHidden:o.includeHidden,maxElements:o.maxElements}),c=Date.now()-a;return st(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:l.url,urlAfter:l.url,status:"ok",durationMs:c,...l.screenshotPath!==null?{screenshotPath:l.screenshotPath}:{}}),{content:JSON.stringify(l,null,2)}}catch(l){let c=Date.now()-a,u=l instanceof Error?l.message:String(l);return st(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:u,recoverable:!1}}),{content:`browser_observe failed: ${u}`,isError:!0}}}}var xx,Rx=P(()=>{"use strict";J();He();ri();xx=lG()});function cG(e){if(!e||typeof e!="object")return{error:"browser_act: input must be an object"};let t=e;if(typeof t.action!="string")return{error:'browser_act: "action" is required and must be a string'};if(!Cx.includes(t.action))return{error:`browser_act: "action" must be one of ${Cx.map(u=>`"${u}"`).join(", ")} (got ${JSON.stringify(t.action)})`};let n=t.action,r=t.target;if(!r||typeof r!="object")return{error:'browser_act: "target" is required and must be an object'};let o=r;if(typeof o.kind!="string"||!Ax.includes(o.kind))return{error:`browser_act: "target.kind" must be one of ${Ax.map(u=>`"${u}"`).join(", ")} (got ${JSON.stringify(o.kind)})`};let s,i=o.kind;if(i==="semantic"){if(typeof o.text!="string"||o.text.length===0)return{error:'browser_act: target.kind=semantic requires "target.text" (non-empty string)'};s={kind:"semantic",text:o.text,...typeof o.role=="string"&&o.role.length>0?{role:o.role}:{}}}else if(i==="element_id"){if(typeof o.element_id!="string"||o.element_id.length===0)return{error:'browser_act: target.kind=element_id requires "target.element_id" (non-empty string)'};s={kind:"element_id",elementId:o.element_id}}else{if(typeof o.selector!="string"||o.selector.length===0)return{error:'browser_act: target.kind=selector requires "target.selector" (non-empty string)'};s={kind:"selector",selector:o.selector}}let a;if(t.value!==void 0){if(typeof t.value!="string")return{error:'browser_act: "value" must be a string when provided'};a=t.value}let l;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:'browser_act: "timeout_ms" must be a positive finite number'};l=t.timeout_ms}let c;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_act: "screenshot" must be a boolean'};c=t.screenshot}return{action:n,target:s,value:a,timeoutMs:l,screenshot:c}}function uG(e,t){let n=e.role?`"${e.text}" (role: ${e.role})`:`"${e.text}"`;return[`browser_act: ambiguous target \u2014 ${t.length} elements matched ${n}.`,'Retry with target.kind="element_id" using one of the following:',...t.map(o=>` id=${o.id} role=${o.role} label=${o.label}`)].join(`
|
|
1101
|
-
`)}function dG(e){return e.kind==="semantic"?{kind:"semantic",text:bT(e.text),...e.role!==void 0?{role:e.role}:{}}:e.kind==="element_id"?{kind:"element_id",elementId:e.elementId}:{kind:"selector",selectorHash:yT(e.selector)}}function pG(e={}){return async(t,n,r)=>{if(n.aborted){let c=n.reason;return{content:`browser_act aborted: ${c instanceof Error?c.message:String(c??"aborted")}`,isError:!0,failureClass:"abort"}}let o=cG(t);if("error"in o)return{content:o.error,isError:!0};let s=dG(o.target),i=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let a;try{if(e.getBrowserProvider)a=await e.getBrowserProvider();else{let{getBrowserProvider:c}=await Promise.resolve().then(()=>(Lo(),Fo));a=await c()}}catch(c){let u=c instanceof Error?c.message:String(c);return Pn(u)?{content:In(u),isError:!0}:{content:`browser_act failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let c=await a.act({sessionId:i,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),u=Date.now()-l;if("outcome"in c){if(c.outcome==="ambiguous_target")return st(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:u}),{content:uG(c.query,c.candidates),isError:!0};if(c.outcome==="blocked_by_policy")return st(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:u}),{content:`browser_act blocked: ${c.reason}`,isError:!0,failureClass:"policy-refusal"}}return st(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:c.url,urlAfter:c.url,status:"ok",durationMs:u,...c.screenshotPath!==null?{screenshotPath:c.screenshotPath}:{}}),{content:JSON.stringify(c,null,2)}}catch(c){let u=Date.now()-l,d=c instanceof Error?c.message:String(c);st(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:d,recoverable:!1}});let p=ld(c);return{content:`browser_act failed: ${d}`,isError:!0,...p?{failureClass:p}:{}}}}}var Cx,Ax,_x,Px=P(()=>{"use strict";Va();J();
|
|
1100
|
+
`)).catch(()=>{})}catch{}}var ni,wx,Wh,pt,jr=P(()=>{"use strict";Nr();ni={action:"decline"},wx=300;Wh=class{handler=null;queue=Promise.resolve();queueDepth=0;install(t){this.handler=t}uninstall(){this.handler=null}pendingCount(){return this.queueDepth}route(t,n){if(n.signal.aborted)return Promise.resolve(ni);this.queueDepth+=1;let r,o=new Promise(i=>{r=i}),s=this.handler;return this.queue=this.queue.then(async()=>{try{if(n.signal.aborted){r(ni);return}if(!s){rG(t),r(ni);return}let i,a=new Promise(l=>{i=()=>l(ni),n.signal.addEventListener("abort",i,{once:!0})});try{try{n.onActive?.()}catch{}let l=await Promise.race([s(t,n).catch(()=>ni),a]);r(l)}finally{n.signal.removeEventListener("abort",i)}}finally{this.queueDepth-=1,r(ni)}}).catch(()=>{}),o}},pt=new Wh});var Sx,vx=P(()=>{"use strict";jr();Sx=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let n=e,r=n.question;if(typeof r!="string"||r.trim()==="")return{content:"Invalid input: question must be a non-empty string",isError:!0};let o=new Set(["text","confirm","choice","multi_choice","number"]),s=n.type??"text";if(typeof s!="string"||!o.has(s))return{content:"Invalid input: type must be one of: text, confirm, choice, multi_choice, number",isError:!0};if(s==="choice"||s==="multi_choice"){let m=n.choices;if(!Array.isArray(m)||m.length===0)return{content:`Invalid input: choices array is required and must be non-empty for type "${s}"`,isError:!0};if(m.length>100)return{content:`Invalid input: choices array must not exceed 100 items, got ${m.length}`,isError:!0};for(let g of m)if(typeof g!="string")return{content:"Invalid input: all choices must be strings",isError:!0}}let i=n.min,a=n.max;if(i!==void 0&&(typeof i!="number"||!Number.isFinite(i)))return{content:"Invalid input: min must be a finite number",isError:!0};if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)))return{content:"Invalid input: max must be a finite number",isError:!0};if(i!==void 0&&a!==void 0&&i>a)return{content:`Invalid input: min (${i}) must be \u2264 max (${a})`,isError:!0};let l=n.min_length,c=n.max_length;if(l!==void 0&&typeof l!="number")return{content:"Invalid input: min_length must be a number",isError:!0};if(c!==void 0&&typeof c!="number")return{content:"Invalid input: max_length must be a number",isError:!0};if((l!==void 0||c!==void 0)&&s!=="text")return{content:`Invalid input: min_length/max_length are only valid for type "text", got "${s}"`,isError:!0};if(n.allow_custom!==void 0&&s!=="choice"&&s!=="multi_choice")return{content:`Invalid input: allow_custom is only valid for type "choice" or "multi_choice", got "${s}"`,isError:!0};let u={serverName:"agent",message:r.trim(),origin:"agent",type:s,...n.choices!==void 0&&{choices:n.choices},...n.context!==void 0&&typeof n.context=="string"&&{context:n.context},...n.default!==void 0&&{questionDefault:n.default},...l!==void 0&&{minLength:l},...c!==void 0&&{maxLength:c},...i!==void 0&&{min:i},...a!==void 0&&{max:a},...n.allow_skip!==void 0&&{allowSkip:!!n.allow_skip},...n.allow_custom!==void 0&&{allowCustom:!!n.allow_custom}},d=await pt.route(u,{signal:t}),p=d.action==="decline"||d.action==="cancel";return{content:JSON.stringify(d),...p&&{isError:!0,failureClass:"elicitation-declined"}}}});function ld(e){if(e instanceof Error&&e.name==="TimeoutError")return"timeout";let t=e instanceof Error?e.message:String(e);return/Timeout\s+\d+\s*ms exceeded/i.test(t)?"timeout":void 0}function Pn(e){return oG.some(t=>e.includes(t))}function In(e){return e.includes("Executable doesn't exist")?"browser tools require the Playwright chromium binary. Install via: pnpm exec playwright install chromium.":"browser tools require the optional `playwright` peer dependency. Install via: pnpm add playwright (then pnpm exec playwright install chromium). Or pick a different tool."}var oG,ri=P(()=>{"use strict";oG=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"]});function sG(e){if(!e||typeof e!="object")return{error:"browser_open: input must be an object"};let t=e,n=t.url;if(typeof n!="string"||n.length===0)return{error:'browser_open: "url" is required and must be a non-empty string'};let r;try{r=new URL(n)}catch{return{error:`browser_open: "${n}" is not a valid absolute URL`}}if(r.protocol!=="http:"&&r.protocol!=="https:")return{error:`browser_open: protocol "${r.protocol}" is not supported (http/https only)`};let o;if(t.wait_for!==void 0){if(!kx.includes(t.wait_for))return{error:`browser_open: "wait_for" must be one of ${kx.map(a=>`"${a}"`).join(", ")} (got ${JSON.stringify(t.wait_for)})`};o=t.wait_for}let s;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_open: "screenshot" must be a boolean'};s=t.screenshot}let i;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:'browser_open: "timeout_ms" must be a positive finite number'};i=t.timeout_ms}return{url:r.toString(),waitFor:o,screenshot:s,timeoutMs:i}}function iG(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_open aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0,failureClass:"abort"}}let o=sG(t);if("error"in o)return{content:o.error,isError:!0};let s=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i;try{if(e.getBrowserProvider)i=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(Lo(),Fo));i=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Pn(c)?{content:In(c),isError:!0}:{content:`browser_open failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await i.open({sessionId:s,url:o.url,waitFor:o.waitFor,screenshot:o.screenshot,timeoutMs:o.timeoutMs}),c=Date.now()-a;if("outcome"in l&&l.outcome==="blocked_by_policy")return st(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:c}),{content:`browser_open blocked: ${l.reason}`,isError:!0,failureClass:"policy-refusal"};let u=l;return st(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:u.url,status:"ok",durationMs:c,...u.screenshotPath!==null?{screenshotPath:u.screenshotPath}:{}}),{content:JSON.stringify(u,null,2)}}catch(l){let c=Date.now()-a,u=l instanceof Error?l.message:String(l);st(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:u,recoverable:!1}});let d=ld(l);return{content:`browser_open failed: ${u}`,isError:!0,...d?{failureClass:d}:{}}}}}var kx,Ex,Tx=P(()=>{"use strict";J();Ne();ri();kx=["load","domcontentloaded","networkidle"];Ex=iG()});function aG(e){if(e!=null&&typeof e!="object")return{error:"browser_observe: input must be an object or omitted"};if(!e)return{};let t=e,n;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_observe: "screenshot" must be a boolean'};n=t.screenshot}let r;if(t.include_hidden!==void 0){if(typeof t.include_hidden!="boolean")return{error:'browser_observe: "include_hidden" must be a boolean'};r=t.include_hidden}let o;if(t.max_elements!==void 0){if(typeof t.max_elements!="number"||!Number.isFinite(t.max_elements)||t.max_elements<=0||!Number.isInteger(t.max_elements))return{error:'browser_observe: "max_elements" must be a positive integer'};o=t.max_elements}return{screenshot:n,includeHidden:r,maxElements:o}}function lG(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_observe aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=aG(t);if("error"in o)return{content:o.error,isError:!0};let s=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i;try{if(e.getBrowserProvider)i=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(Lo(),Fo));i=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Pn(c)?{content:In(c),isError:!0}:{content:`browser_observe failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await i.observe({sessionId:s,screenshot:o.screenshot,includeHidden:o.includeHidden,maxElements:o.maxElements}),c=Date.now()-a;return st(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:l.url,urlAfter:l.url,status:"ok",durationMs:c,...l.screenshotPath!==null?{screenshotPath:l.screenshotPath}:{}}),{content:JSON.stringify(l,null,2)}}catch(l){let c=Date.now()-a,u=l instanceof Error?l.message:String(l);return st(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:u,recoverable:!1}}),{content:`browser_observe failed: ${u}`,isError:!0}}}}var xx,Rx=P(()=>{"use strict";J();Ne();ri();xx=lG()});function cG(e){if(!e||typeof e!="object")return{error:"browser_act: input must be an object"};let t=e;if(typeof t.action!="string")return{error:'browser_act: "action" is required and must be a string'};if(!Cx.includes(t.action))return{error:`browser_act: "action" must be one of ${Cx.map(u=>`"${u}"`).join(", ")} (got ${JSON.stringify(t.action)})`};let n=t.action,r=t.target;if(!r||typeof r!="object")return{error:'browser_act: "target" is required and must be an object'};let o=r;if(typeof o.kind!="string"||!Ax.includes(o.kind))return{error:`browser_act: "target.kind" must be one of ${Ax.map(u=>`"${u}"`).join(", ")} (got ${JSON.stringify(o.kind)})`};let s,i=o.kind;if(i==="semantic"){if(typeof o.text!="string"||o.text.length===0)return{error:'browser_act: target.kind=semantic requires "target.text" (non-empty string)'};s={kind:"semantic",text:o.text,...typeof o.role=="string"&&o.role.length>0?{role:o.role}:{}}}else if(i==="element_id"){if(typeof o.element_id!="string"||o.element_id.length===0)return{error:'browser_act: target.kind=element_id requires "target.element_id" (non-empty string)'};s={kind:"element_id",elementId:o.element_id}}else{if(typeof o.selector!="string"||o.selector.length===0)return{error:'browser_act: target.kind=selector requires "target.selector" (non-empty string)'};s={kind:"selector",selector:o.selector}}let a;if(t.value!==void 0){if(typeof t.value!="string")return{error:'browser_act: "value" must be a string when provided'};a=t.value}let l;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:'browser_act: "timeout_ms" must be a positive finite number'};l=t.timeout_ms}let c;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_act: "screenshot" must be a boolean'};c=t.screenshot}return{action:n,target:s,value:a,timeoutMs:l,screenshot:c}}function uG(e,t){let n=e.role?`"${e.text}" (role: ${e.role})`:`"${e.text}"`;return[`browser_act: ambiguous target \u2014 ${t.length} elements matched ${n}.`,'Retry with target.kind="element_id" using one of the following:',...t.map(o=>` id=${o.id} role=${o.role} label=${o.label}`)].join(`
|
|
1101
|
+
`)}function dG(e){return e.kind==="semantic"?{kind:"semantic",text:bT(e.text),...e.role!==void 0?{role:e.role}:{}}:e.kind==="element_id"?{kind:"element_id",elementId:e.elementId}:{kind:"selector",selectorHash:yT(e.selector)}}function pG(e={}){return async(t,n,r)=>{if(n.aborted){let c=n.reason;return{content:`browser_act aborted: ${c instanceof Error?c.message:String(c??"aborted")}`,isError:!0,failureClass:"abort"}}let o=cG(t);if("error"in o)return{content:o.error,isError:!0};let s=dG(o.target),i=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let a;try{if(e.getBrowserProvider)a=await e.getBrowserProvider();else{let{getBrowserProvider:c}=await Promise.resolve().then(()=>(Lo(),Fo));a=await c()}}catch(c){let u=c instanceof Error?c.message:String(c);return Pn(u)?{content:In(u),isError:!0}:{content:`browser_act failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let c=await a.act({sessionId:i,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),u=Date.now()-l;if("outcome"in c){if(c.outcome==="ambiguous_target")return st(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:u}),{content:uG(c.query,c.candidates),isError:!0};if(c.outcome==="blocked_by_policy")return st(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:u}),{content:`browser_act blocked: ${c.reason}`,isError:!0,failureClass:"policy-refusal"}}return st(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:c.url,urlAfter:c.url,status:"ok",durationMs:u,...c.screenshotPath!==null?{screenshotPath:c.screenshotPath}:{}}),{content:JSON.stringify(c,null,2)}}catch(c){let u=Date.now()-l,d=c instanceof Error?c.message:String(c);st(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:d,recoverable:!1}});let p=ld(c);return{content:`browser_act failed: ${d}`,isError:!0,...p?{failureClass:p}:{}}}}}var Cx,Ax,_x,Px=P(()=>{"use strict";Va();J();Ne();ri();Cx=["click","fill","press","select","hover","scroll_to","wait_for"],Ax=["semantic","element_id","selector"];_x=pG()});function mG(e){if(typeof e.kind!="string"||!Ix.includes(e.kind))return{error:`browser_screenshot: "target.kind" must be one of ${Ix.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e.kind)})`};let t=e.kind;return t==="semantic"?typeof e.text!="string"||e.text.length===0?{error:'browser_screenshot: target.kind=semantic requires "target.text" (non-empty string)'}:{kind:"semantic",text:e.text,...typeof e.role=="string"&&e.role.length>0?{role:e.role}:{}}:t==="element_id"?typeof e.element_id!="string"||e.element_id.length===0?{error:'browser_screenshot: target.kind=element_id requires "target.element_id" (non-empty string)'}:{kind:"element_id",elementId:e.element_id}:typeof e.selector!="string"||e.selector.length===0?{error:'browser_screenshot: target.kind=selector requires "target.selector" (non-empty string)'}:{kind:"selector",selector:e.selector}}function fG(e){if(e!=null&&typeof e!="object")return{error:"browser_screenshot: input must be an object or omitted"};if(!e)return{};let t=e,n;if(t.target!==void 0){if(!t.target||typeof t.target!="object")return{error:'browser_screenshot: "target" must be an object when provided'};let o=mG(t.target);if("error"in o)return o;n=o}let r;if(t.full_page!==void 0){if(typeof t.full_page!="boolean")return{error:'browser_screenshot: "full_page" must be a boolean'};r=t.full_page}return{target:n,fullPage:r}}function gG(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_screenshot aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=fG(t);if("error"in o)return{content:o.error,isError:!0};let s=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i;try{if(e.getBrowserProvider)i=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(Lo(),Fo));i=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Pn(c)?{content:In(c),isError:!0}:{content:`browser_screenshot failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await i.screenshot({sessionId:s,target:o.target,fullPage:o.fullPage}),c=Date.now()-a,{dataBase64:u,mediaType:d,...p}=l;return st(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:c,screenshotPath:p.path}),p.width>Kh||p.height>Kh?{content:JSON.stringify({...p,imageOmitted:`dimensions ${p.width}x${p.height}px exceed the ${Kh}px model-vision limit; the PNG was saved to the sidecar path but not attached. Use full_page:false (viewport) or target a specific element for a model-visible image.`},null,2)}:{content:JSON.stringify(p,null,2),image:{mediaType:d,data:u}}}catch(l){let c=Date.now()-a,u=l instanceof Error?l.message:String(l);return st(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:u,recoverable:!1}}),{content:`browser_screenshot failed: ${u}`,isError:!0}}}}var Ix,Kh,Mx,Ox=P(()=>{"use strict";J();Ne();ri();Ix=["semantic","element_id","selector"],Kh=8e3;Mx=gG()});function hG(e={}){return async(t,n,r)=>{if(n.aborted){let a=n.reason;return{content:`browser_close aborted: ${a instanceof Error?a.message:String(a??"aborted")}`,isError:!0}}let o=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(o))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(o)}`,isError:!0};let s;try{if(e.getBrowserProvider)s=await e.getBrowserProvider();else{let{getBrowserProvider:a}=await Promise.resolve().then(()=>(Lo(),Fo));s=await a()}}catch(a){let l=a instanceof Error?a.message:String(a);return Pn(l)?{content:In(l),isError:!0}:{content:`browser_close failed to get provider: ${l}`,isError:!0}}let i=Date.now();try{await s.close({sessionId:o});let a=Date.now()-i;return st(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:a}),{content:"Browser session closed."}}catch(a){let l=Date.now()-i,c=a instanceof Error?a.message:String(a);return st(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:l,error:{reason:c,recoverable:!1}}),{content:`browser_close failed: ${c}`,isError:!0}}}}var $x,Dx=P(()=>{"use strict";J();Ne();ri();$x=hG()});function cd(e,t){let n=e!==void 0?Cu(e,t):t!==void 0?Cu("default",t):pE,r=t!==void 0?Zg(t):RE,o=t!==void 0?Qg(t):AE,s=Mh();return new Map([["bash",n],["read_file",hE],["write_file",SE],["edit_file",kE],["glob",r],["grep",o],["list_directory",PE],["send_telegram",oT],["web_scrape",jT],["create_schedule",qT],["list_schedules",zT],["get_schedule_history",JT],["cancel_schedule",VT],["terminal_font_size",s],["config_get",hx],["config_set",yx],["ask_question",Sx],["browser_open",Ex],["browser_observe",xx],["browser_act",_x],["browser_screenshot",Mx],["browser_close",$x]])}var Gh=P(()=>{"use strict";mE();yE();vE();EE();CE();_E();IE();sT();HT();YT();$h();bx();vx();Tx();Rx();Px();Ox();Dx()});function ud(e){return["The user has switched off plan mode. Writes are now permitted. Do two things, in order:","",`1. Save the plan. Write the plan you developed in this conversation to a new markdown file under \`${e}/\` \u2014 pick a short, descriptive kebab-case filename (e.g. \`${e}/refactor-auth-flow.md\`). Capture the full plan: the chosen approach, the concrete step-by-step changes, the risks named, and the alternatives considered. This is the durable record.`,"","2. Implement the plan. Work through the steps you just recorded, verifying as you go \u2014 run the project's lint/test gates where they apply. End in a terminal state: Done with evidence, Blocked with the exact unblock condition, or Asking one precise question."].join(`
|
|
1102
1102
|
`)}var qh=P(()=>{"use strict"});function bG(e){switch(e){case"bypassPermissions":return"Approve \u2014 implement now (restore bypass mode: no prompts, read/write any path)";case"acceptEdits":return"Approve \u2014 implement now (restore accept-edits mode: edits auto-approved)";case"dontAsk":case"auto":return"Approve \u2014 implement now (restore your previous mode: no approval prompts)";default:return"Approve \u2014 implement now (restore default mode: writes ask for confirmation, contained to the workspace)"}}function pd(e){return async(t,n,r)=>{let o=e.getPrePlanMode()??"default",s=bG(o),a={serverName:"agent",origin:"agent",type:"choice",message:"Plan ready. How do you want to proceed? (Your plan is in the conversation above.)",choices:o==="bypassPermissions"?[s,zh]:[s,yG,zh]},l=await pt.route(a,{signal:n});if(l.action!=="accept")return{content:"Plan exit not confirmed (the user did not approve). Stay in plan mode \u2014 keep refining the plan; do not implement. Call exit_plan_mode again when ready."};let c=typeof l.content?.value=="string"?l.content.value:"";if(c.startsWith("Keep")||c===zh)return{content:"User chose to keep planning. Stay in plan mode and refine the plan; do not implement. Call exit_plan_mode again when ready."};let u=c.includes("bypass")?"bypassPermissions":o,d=Pc(r?.resolveBase??r?.cwd??process.cwd());return e.requestImplementSeed(ud(d),u),{content:`Plan approved (mode=${u}). The implementation instruction will follow as a new message \u2014 end your turn now.`}}}var pr,yG,zh,dd,Qa=P(()=>{"use strict";jr();qh();K();pr="exit_plan_mode",yG="Approve \u2014 implement now (bypass mode: no prompts, read/write any path)",zh="Keep planning";dd={name:pr,category:"other",concurrencySafe:!1,description:`Signal that your plan is ready and present it to the user for approval. The user is shown a picker: approve and implement (you pick neither mode \u2014 the user does), or keep planning.
|
|
1103
1103
|
|
|
1104
1104
|
IMPORTANT: only call this in plan mode, and only when the task requires implementation (writing code or files). For research / read-only / understanding tasks, do NOT call it \u2014 just answer.
|
|
@@ -1120,9 +1120,9 @@ ${s}`:s}function jx(e,t){if(typeof e=="string")return e;if(!t.vision)return Ux(e
|
|
|
1120
1120
|
${o}`:o}function BG(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 Hx(e){let t=[],n=BG(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:NG(r.content)}:r):t}var Wx=P(()=>{"use strict"});function HG(){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 Kx(e,t){return e===t||e.includes(t)}function Gx(e){if(!e)return!1;let t=(Ro(e)??e).trim();if(!t)return!1;let n=t.toLowerCase(),{enable:r,disable:o}=HG();return o.some(s=>Kx(n,s))?!1:r.some(s=>Kx(n,s))||UG.has(n)?!0:jG.some(s=>s.test(t))}var UG,jG,qx=P(()=>{"use strict";J();sn();UG=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"]),jG=[/^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 Xh(){return{assistantText:"",reasoningText:"",toolCallsByIndex:new Map,finishReason:null,usage:null,model:null,id:null}}function*zx(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 Jx(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 Zh(e){return[...e.toolCallsByIndex.values()].sort((t,n)=>t.index-n.index)}function Qh(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 Vx=P(()=>{"use strict"});function Yx(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 Xx(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 Zx(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 Qx(e){return e.map(({call:t,result:n})=>({role:"tool",tool_call_id:t.id,content:n.isError?`[error] ${n.content}`:n.content}))}function eR(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 tR=P(()=>{"use strict"});function*nR(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":{ey(t,e),t.finishReason=t.toolCallsByIndex.size>0?"tool_calls":"stop";return}case"response.incomplete":{ey(t,e),t.finishReason=e.response?.incomplete_details?.reason??"incomplete";return}case"response.failed":{ey(t,e),t.finishReason="failed";return}default:return}}function ey(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 rR=P(()=>{"use strict"});function oR(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:WG(i.content)})}let o={input:r};n.length>0&&(o.instructions=n.join(`
|
|
1121
1121
|
|
|
1122
1122
|
`));let s=KG(t);return s.length>0&&(o.tools=s),o}function WG(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 KG(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 sR=P(()=>{"use strict"});function aR(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 lR(e){if(!e)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function qG(e){let t={"OpenAI-Beta":"responses=experimental",originator:"agent-afk"};return e&&(t["chatgpt-account-id"]=e),t}function cR(e,t=!1){return e.source==="chatgpt-oauth"?{mode:"responses",baseURL:GG,headers:qG(e.accountId)}:t?{mode:"responses"}:{mode:"chat-completions"}}var GG,iR,uR=P(()=>{"use strict";GG="https://chatgpt.com/backend-api/codex",iR="You are a helpful assistant."});function dR(e){return(e.inputTokens??0)+(e.outputTokens??0)}function Uo(e){return e.contextWindowTokens??dR(e)}function il(e){return e?{totalTokens:Uo(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 ty(e,t,n){return t<=0||e<=0||n<=0||n>=1?!1:e/t>=n}var ny=P(()=>{"use strict"});function Kr(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})})}var ry=P(()=>{"use strict"});function hd(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(`
|
|
1123
|
-
`)[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:""}var oy=P(()=>{"use strict"});import zG from"openai";import{randomUUID as pR}from"node:crypto";function SR(e){if(e===null||typeof e!="object")return;let t=e;return typeof t.status=="number"?t.status:void 0}function gR(e){let t=SR(e);return t===void 0?!1:wR.has(t)}function hR(e){let t=SR(e);return t===void 0?!1:wR.has(t)}function vR(e,t){let n=tl(e);return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):n}function YG(e,t){let n=vR(e,t);return kR(e)?{max_completion_tokens:n}:{max_tokens:n}}function yR(e){return e??"default"}function kR(e){let t=e.includes("/")?e.slice(e.lastIndexOf("/")+1):e;return/^o[0-9]/.test(t)}function XG(e){switch(e){case"low":return"low";case"medium":return"medium";case"high":case"xhigh":case"max":return"high"}}function bR(e,t){if(e!==void 0&&kR(t))return XG(e)}function ZG(e){let t={apiKey:e.apiKey};return e.baseURL!==void 0&&(t.baseURL=e.baseURL),e.defaultHeaders!==void 0&&(t.defaultHeaders=e.defaultHeaders),new zG(t)}function ER(e,t,n={}){let r=Bo(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=kt(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 bd(a)}var sy,JG,wR,mR,fR,yd,VG,bd,iy=P(()=>{"use strict";
|
|
1123
|
+
`)[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:""}var oy=P(()=>{"use strict"});import zG from"openai";import{randomUUID as pR}from"node:crypto";function SR(e){if(e===null||typeof e!="object")return;let t=e;return typeof t.status=="number"?t.status:void 0}function gR(e){let t=SR(e);return t===void 0?!1:wR.has(t)}function hR(e){let t=SR(e);return t===void 0?!1:wR.has(t)}function vR(e,t){let n=tl(e);return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):n}function YG(e,t){let n=vR(e,t);return kR(e)?{max_completion_tokens:n}:{max_tokens:n}}function yR(e){return e??"default"}function kR(e){let t=e.includes("/")?e.slice(e.lastIndexOf("/")+1):e;return/^o[0-9]/.test(t)}function XG(e){switch(e){case"low":return"low";case"medium":return"medium";case"high":case"xhigh":case"max":return"high"}}function bR(e,t){if(e!==void 0&&kR(t))return XG(e)}function ZG(e){let t={apiKey:e.apiKey};return e.baseURL!==void 0&&(t.baseURL=e.baseURL),e.defaultHeaders!==void 0&&(t.defaultHeaders=e.defaultHeaders),new zG(t)}function ER(e,t,n={}){let r=Bo(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=kt(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 bd(a)}var sy,JG,wR,mR,fR,yd,VG,bd,iy=P(()=>{"use strict";Ne();Da();Vh();nl();Zn();Yh();ay();Pe();sl();Wx();qx();Vx();tR();rR();sR();uR();J();ny();Tg();Rg();ry();oy();sy="openai-compatible",JG=50,wR=new Set([429,500,502,503,529]),mR=3,fR=3,yd=2e3;VG=null;bd=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=yR(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=Yx(o.toolDefs))}let n=(t.useResponsesApi??!1)||lR(v.AFK_OPENAI_USE_RESPONSES),r=cR(t.auth,n);if(this.wireMode=r.mode,t.auth.apiKey===null)this.client=null;else{let o=VG??ZG,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:sy}},this.opts.auth.apiKey===null){yield{type:"error",error:new Error(ol(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=pR();Oe(this.traceWriter,{phase:"loop_start"});try{yield*this._runTurnInner(t,n,r,o)}finally{Oe(this.traceWriter,{phase:"loop_end",durationMs:Date.now()-r})}}async*_runTurnInner(t,n,r,o){let s=Gx(this.currentModel);this.priorTurns.push({role:"user",content:jx(t,{vision:s,model:this.currentModel})});let i={stopReason:null,resultSubtype:"success",isError:!1},a="",l="";for(let c=0;c<JG;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=Jx(u.state);if(i=el(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=Zh(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=Hx({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"?nu:this.currentPermissionMode==="autonomous"?ru:null;o!==null&&(r[0]={...r[0],content:r[0].content+`
|
|
1124
1124
|
|
|
1125
|
-
`+o})}if(this.wireMode==="responses"){let o=this.opts.auth.source==="chatgpt-oauth";if(o&&aR(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=oR(r,this.openAITools),i={model:this.currentModel,input:s.input,stream:!0};o||(i.max_output_tokens=vR(this.currentModel,this.opts.config.maxOutputTokens));let a=s.instructions??(o?iR:void 0);a!==void 0&&(i.instructions=a),o&&(i.store=!1),s.tools&&s.tools.length>0&&(i.tools=s.tools);let l=bR(this.opts.config.effort,this.currentModel);l!==void 0&&(i.reasoning={effort:l});let c=0;for(;;){let u=Xh(),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(gR(y)&&b<mR){let S=yd*Math.pow(2,b);if(await Kr(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 nR(b,u,this.initSessionId))h||(h=!0,
|
|
1125
|
+
`+o})}if(this.wireMode==="responses"){let o=this.opts.auth.source==="chatgpt-oauth";if(o&&aR(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=oR(r,this.openAITools),i={model:this.currentModel,input:s.input,stream:!0};o||(i.max_output_tokens=vR(this.currentModel,this.opts.config.maxOutputTokens));let a=s.instructions??(o?iR:void 0);a!==void 0&&(i.instructions=a),o&&(i.store=!1),s.tools&&s.tools.length>0&&(i.tools=s.tools);let l=bR(this.opts.config.effort,this.currentModel);l!==void 0&&(i.reasoning={effort:l});let c=0;for(;;){let u=Xh(),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(gR(y)&&b<mR){let S=yd*Math.pow(2,b);if(await Kr(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 nR(b,u,this.initSessionId))h||(h=!0,Oe(this.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-d,resolvedModel:this.currentModel})),yield y}}catch(b){if(t.signal.aborted)return null;if(hR(b)&&c<fR){if(c++,yield{type:"stream.retry",sessionId:this.initSessionId},await Kr(yd*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:Qh(u)&&u.toolCallsByIndex.size>0}}}else{let o={model:this.currentModel,messages:r,stream:!0,stream_options:{include_usage:!0}};Object.assign(o,YG(this.currentModel,this.opts.config.maxOutputTokens)),this.openAITools&&this.openAITools.length>0&&(o.tools=this.openAITools);let s=bR(this.opts.config.effort,this.currentModel);s!==void 0&&(o.reasoning_effort=s);let i=0;for(;;){let a=Xh(),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(gR(g)&&m<mR){let h=yd*Math.pow(2,m);if(await Kr(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 zx(m,a,this.initSessionId))p||(p=!0,Oe(this.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-l,resolvedModel:this.currentModel})),yield g}}catch(m){if(t.signal.aborted)return null;if(hR(m)&&i<fR){if(i++,yield{type:"stream.retry",sessionId:this.initSessionId},await Kr(yd*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:Qh(a)&&a.toolCallsByIndex.size>0}}}}async*dispatchAndAppend(t,n,r){if(!this.toolDispatcher)return;let o=Zh(t);for(let u of o)u.id.length===0&&(u.id=pR());let{calls:s,parseErrors:i}=Xx(o,n),a=new Map;for(let u of s){let d=Date.now();a.set(u.id,d),$s(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:hd(u.name,u.input),toolInputRaw:gd(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}
|
|
1126
1126
|
--
|
|
1127
1127
|
${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");$s(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(Zx(t.assistantText,o,t.reasoningText));for(let u of Qx(l))this.priorTurns.push(u);let c=eR(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=kt(t)??t)}async setPermissionMode(t){this.currentPermissionMode=yR(t);let n=kn(this.currentPermissionMode);this.toolDispatcher?.setAllowAll?.(n),this.onPermissionMode?.(this.currentPermissionMode)}setCwd(t){this.toolDispatcher?.setResolveBase?.(t)}async supportedCommands(){return wd()}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=Lt(this.currentModel),r;if(t&&n>0){let i=Uo(t);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=il(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:`${sy} 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?.(),W(`\u{1F7E2} ${sy}: closed`)}}});import QG from"openai";async function TR(e){let{apiKey:t,baseURL:n,model:r,system:o,user:s,maxTokens:i=64,signal:a,clientFactory:l}=e,c=Bo(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??e2,p=d?d(u):new QG(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 e2,xR=P(()=>{"use strict";sl();e2=null});import ly from"path";import{appendFileSync as t2,mkdirSync as n2}from"fs";import{dirname as r2}from"path";var cy,Nt,o2,al=P(()=>{"use strict";K();du();fu();Wa();Da();Gh();Qa();nr();dn();iy();xR();or();Wr();sl();iy();cy="openai-compatible",Nt=class{name=cy;providerOpts;memoryStore;schemas;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_presenceSessionId=null;constructor(t={}){this.providerOpts=t,this.memoryStore=t.memoryStore??new dt;let n=[...tr];t.subagentExecutor&&n.push(Ao),t.skillExecutor&&n.push(_o),t.composeExecutor&&n.push(Po),t.readOnlyMemory===!0?n.push(Ws):n.push(...$r),n.push(Cn);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=Ba({surface:this.providerOpts.surface??"cli",cwd:n.cwd??process.cwd(),modelName:s,providerName:cy,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 Ot?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?Ua(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();ja({sessionId:m,surface:this.providerOpts.surface??"cli",actor:Mn(n.depth),cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:cy,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=Ks({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}
|
|
1128
1128
|
|
|
@@ -1138,10 +1138,10 @@ ${u}`:u};return ER(p,t.prompt,a)}buildDispatcher(t,n){let r=cd(t,n.cwd),o=Na(thi
|
|
|
1138
1138
|
`);try{await at.unlink(n)}catch{}}}},$n=class e{static async listJobs(){let t=Ra(),n;try{n=await at.readdir(t)}catch{return[]}let r=[];for(let o of n.slice(0,1e3)){let s=await e.readMeta(o);s&&r.push(s)}return r.sort((o,s)=>s.startedAt-o.startedAt),r.slice(0,100)}static async readMeta(t){let n;try{n=Xf(t)}catch{return null}try{let r=await at.readFile(n,"utf8"),o=JSON.parse(r);return o.schemaVersion!==1?null:o}catch(r){return r.code==="ENOENT"||process.stderr.write(`[afk] bg-job-log: readMeta parse error for ${t}: ${String(r)}
|
|
1139
1139
|
`),null}}static async*readEvents(t){let n=Lc(t),r;try{r=await at.open(n,"r")}catch(o){if(o.code==="ENOENT")return;throw o}try{let o=$R.createInterface({input:r.createReadStream({encoding:"utf8"}),crlfDelay:1/0});for await(let s of o){let i=s.trim();if(i)try{yield JSON.parse(i)}catch{}}}finally{await r.close()}}static async*tailEvents(t,n){let r=Lc(t),{fromStart:o=!1}=n??{},s=vo(t);try{await at.access(s)}catch{return}let i=0,a="",l=null,c=250;async function*u(){let h=null;try{h=await at.open(r,"r");let b=await h.stat();if(b.size<=i)return;let y=b.size-i,S=Buffer.allocUnsafe(y),{bytesRead:w}=await h.read(S,0,y,i);if(w===0)return;i+=w,a+=S.toString("utf8",0,w);let k=a.split(`
|
|
1140
1140
|
`);a=k.pop()??"";for(let T of k){let R=T.trim();if(R)try{yield JSON.parse(R)}catch{}}}catch(b){b.code!=="ENOENT"&&process.stderr.write(`[afk] bg-job-log: tailEvents read error for ${t}: ${String(b)}
|
|
1141
|
-
`)}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 at.stat(r);return i>=y.size}catch{return!0}}if(o)yield*u();else try{i=(await at.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=si.watch(s,{persistent:!1},()=>{p?.(),p=null})}catch{}try{for(;await g(),yield*u(),!await d(););}finally{m?.(),l?.close()}}}});import{EventEmitter as E2}from"node:events";import*as Jr from"node:fs/promises";import*as LR from"node:path";import{createHash as T2}from"node:crypto";function py(e){We(e).catch(()=>{})}var x2,DR,FR,R2,pl,Td,my=P(()=>{"use strict";Bt();Pe();
|
|
1141
|
+
`)}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 at.stat(r);return i>=y.size}catch{return!0}}if(o)yield*u();else try{i=(await at.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=si.watch(s,{persistent:!1},()=>{p?.(),p=null})}catch{}try{for(;await g(),yield*u(),!await d(););}finally{m?.(),l?.close()}}}});import{EventEmitter as E2}from"node:events";import*as Jr from"node:fs/promises";import*as LR from"node:path";import{createHash as T2}from"node:crypto";function py(e){We(e).catch(()=>{})}var x2,DR,FR,R2,pl,Td,my=P(()=>{"use strict";Bt();Pe();Ne();Ed();K();Qn();x2=300*1e3,DR=4096;FR=5e3,R2=10,pl=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"}},Td=class extends E2{jobs=new Map;counter=Math.floor(Math.random()*65536);traceWriter;maxConcurrentJobs;constructor(t={}){super(),this.traceWriter=t.traceWriter,this.maxConcurrentJobs=t.maxConcurrentJobs??R2,setTimeout(()=>this._sweepOldJobs().catch(r=>process.stderr.write(`[afk] bg sweep error: ${String(r)}
|
|
1142
1142
|
`)),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=>{W("adoptRunning: unexpected rejection from in-flight runPromise",i),this.markTerminal(r,vd(t.handle.id,"failed",i,dl()),o,s)}),this.snapshot(n)}createJobEntry(t){let n=[...this.jobs.values()].filter(d=>d.status==="running").length;if(n>=this.maxConcurrentJobs)throw new pl(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),Ds(this.traceWriter,{transition:"started",jobId:r,subagentId:t.handle.id,label:o,model:t.model}),this.emit("started",this.snapshot(l));let c=new kd(r),u={jobId:r,subagentId:t.handle.id,label:o,promptHash:T2("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 Ds(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 ${FR}ms \u2014 continuing teardown`),o()},FR).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<=DR?r.transcriptTail=o:r.transcriptTail=o.slice(o.length-DR)}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):"";Ds(this.traceWriter,{transition:"completed",jobId:t,subagentId:s.subagentId,durationMs:i,outputBytes:Buffer.byteLength(c,"utf8")}),py({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;Ds(this.traceWriter,{transition:"failed",jobId:t,subagentId:s.subagentId,durationMs:i,errorClass:l?.name??"Error",errorMessage:l?.message??"unknown"}),py({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 Ds(this.traceWriter,{transition:"cancelled",jobId:t,subagentId:s.subagentId,source:s.cancelSource??"explicit"}),py({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)},x2).unref()}async _sweepOldJobs(){let n=Ra(),r;try{r=await Jr.readdir(n)}catch{return}for(let o of r){let s=vo(o),i=LR.join(s,"meta.json");try{if(!(await Jr.lstat(s)).isDirectory()){process.stderr.write(`[afk] bg sweep: skipping non-directory entry ${o}
|
|
1143
1143
|
`);continue}let l=await Jr.readFile(i,"utf8"),c=JSON.parse(l);if(c.status==="running"||c.endedAt===void 0||Date.now()-c.endedAt<6048e5)continue;await Jr.rm(s,{recursive:!0,force:!0})}catch(a){if(a.code==="ENOENT")continue;process.stderr.write(`[afk] bg sweep: error evicting ${o}: ${String(a)}
|
|
1144
|
-
`)}}}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 C2(e){return typeof e=="string"&&e.startsWith("sk-ant-")}function ml(e){let{childModel:t,resolved:n,parentApiKey:r}=e;return n!==void 0&&n.length>0||se(t)==="openai-compatible"?n:C2(r)?r:n}var fy=P(()=>{"use strict";it()});import{isAbsolute as A2}from"node:path";function _2(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(!A2(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 xd(e){try{return We(e).catch(()=>{})}catch{return Promise.resolve()}}function ii(e,t=240){return e.length<=t?e:e.slice(0,t)+"\u2026"}function BR(e){if(e!=null){if(typeof e=="string")return e.length;try{return JSON.stringify(e).length}catch{return}}}function I2(e){if(e==null)return;let t=BR(e);return t!==void 0&&t>P2?{truncated:!0,chars:t}:e}function M2(e){let t={status:e.status,error:ii(e.errorMessage,NR),subagent_id:e.subagentId};e.schemaErrorMessage&&(t.schemaError=ii(e.schemaErrorMessage,NR));let n=I2(e.partialOutput);return n!==void 0&&(t.partialOutput=n),t}var P2,NR,Dn,fl=P(()=>{"use strict";ze();my();it();fy();Js();Vr();Qn();Pe();Oo();Wr();Vr();P2=4096,NR=1024;Dn=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=_2(t.input)}catch(R){return{content:`Agent tool input validation failed: ${R instanceof Error?R.message:String(R)}`,isError:!0}}let r=this.ctx.depth,o=this.ctx.maxDepth??ai,s,i=this.ctx.surface!==void 0?{origin:Hr(this.ctx.surface),actor:Mn(r)}:{},a=n.model??this.ctx.defaultSubagentModel??"sonnet",l=se(a)==="openai-compatible",c=ml({childModel:a,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(a):lr(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 re({parentAbortSignal:t.signal,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),d=jo(t.signal);let R=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}:{}}),A=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,t.signal):void 0;u.provider=this.ctx.childProviderFactory({childExecutor:R,...A!==void 0?{childSkillExecutor:A}:{},...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"?sr(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":sr(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:!0}),d!==void 0&&(d.sessionId=p.id)}catch(R){let A=R instanceof Error?R.message:String(R);return xd({...i,event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:ii(A),depth:r}),{content:`Failed to fork subagent: ${A}`,isError:!0}}if(n.mode==="background"){let R=this.ctx.backgroundRegistry;if(!R)return await p.teardown().catch(O=>W("subagent-executor: handle teardown failed: "+(O instanceof Error?O.message:String(O)))),{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 A;try{A=R.register({handle:p,prompt:n.prompt,model:u.model??"sonnet",parentSessionId:this.ctx.parentSession.sessionId})}catch(O){if(O instanceof pl)return await p.teardown().catch(_=>W("subagent-executor: handle teardown failed after cap error: "+(_ instanceof Error?_.message:String(_)))),{content:O.message,isError:!0};throw O}let E={status:"running",jobId:A.jobId,subagentId:A.subagentId,label:A.label,message:`Background subagent started (jobId=${A.jobId}). It is running detached and its result will NOT auto-inject into this context. Retrieve it later via /bgsub:join ${A.jobId} or ask the user to join.`};return{content:JSON.stringify(E)}}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(R=>{y=R}),w,k=new Promise(R=>{w=R});this.promotionTriggers.set(p.id,{fire:y,ready:k});let T=p.runToResult(n.prompt);try{let R=await Promise.race([T.then(I=>({kind:"result",result:I})),S.then(()=>({kind:"promote"}))]);if(R.kind==="promote"){let I=this.ctx.backgroundRegistry;if(I)try{let L=I.adoptRunning({handle:p,runPromise:T,prompt:n.prompt,model:u.model??"sonnet",parentSessionId:h});return b=!0,t.signal.removeEventListener("abort",m),w({jobId:L.jobId,label:L.label}),{content:JSON.stringify({status:"running",jobId:L.jobId,subagentId:L.subagentId,label:L.label,message:`Subagent backgrounded by user (jobId=${L.jobId}). It keeps running detached and its result will NOT auto-inject into this context. Retrieve it via /bgsub:join ${L.jobId}.`})}}catch(L){W("subagent-executor: promotion failed, staying foreground: "+(L instanceof Error?L.message:String(L))),w(null)}else w(null)}let A=R.kind==="result"?R.result:await T;if(A.status==="succeeded"&&A.message){let I=A.message.content,L=typeof I=="string"?I:JSON.stringify(I),N=A.trace;return xd({...i,event:"subagent.completed",subagent_id:p.id,parent_session_id:h,status:A.status,duration_ms:Date.now()-g,content_chars:L.length,depth:r,tool_call_count:N?.toolCalls.length,thinking_present:N?.thinkingPresent,tool_names:N?.toolCalls.length?JSON.stringify([...new Set(N.toolCalls.map(F=>F.name))]):void 0}),{content:L}}let E=A.error?.message??"Subagent failed with no output",O=A.trace;xd({...i,event:"subagent.failed",subagent_id:p.id,id_prefix:n.id_prefix,parent_session_id:h,status:A.status,duration_ms:Date.now()-g,error_message:ii(E),schema_error:A.schemaError?ii(A.schemaError.message):void 0,partial_output_chars:BR(A.partialOutput),depth:r,tool_call_count:O?.toolCalls.length,thinking_present:O?.thinkingPresent,tool_names:O?.toolCalls.length?JSON.stringify([...new Set(O.toolCalls.map(I=>I.name))]):void 0});let _=M2({status:A.status,errorMessage:E,schemaErrorMessage:A.schemaError?.message,partialOutput:A.partialOutput,subagentId:p.id});return{content:JSON.stringify(_),isError:!0}}catch(R){let A=R instanceof Error?R.message:String(R);throw xd({...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:ii(A),depth:r}),R}finally{this.promotionTriggers.delete(p.id),w(null),b||(t.signal.removeEventListener("abort",m),await s?.teardownAll(),await p.teardown())}}}});function Rd(e,t){return`Skill tool not available at nesting depth ${e} (max ${t}). ${li}`}var li,gy=P(()=>{"use strict";li="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});function jR(e){UR.add(e)}function HR(e){return UR.has(e)}var UR,hy=P(()=>{"use strict";UR=new Set});function WR(e){yy.add(e)}function KR(e){yy.delete(e)}function GR(e){by.add(e)}function qR(e){by.delete(e)}function zR(e){for(let t of yy)t(e)}function JR(e){for(let t of by)t(e)}var yy,by,wy=P(()=>{"use strict";yy=new Set,by=new Set});function VR(e){return O2.has(e)}function D2(e,t=$2){return e.length<=t?e:e.slice(0,t)+"\u2026"}function F2(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 L2(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 O2,$2,Fn,gl=P(()=>{"use strict";Tt();ze();fr();Vr();fl();gy();fy();Js();er();zt();Qn();hy();wy();Pe();Wr();O2=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"]);$2=240;Fn=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:Hr(this.ctx.surface),actor:Mn(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??ai;if(n>=r){let l=F2(t.input);return We({...this.sessionIdentity(),event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:l}).catch(()=>{}),{content:Rd(n,r),isError:!0}}let o;try{o=L2(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||Sy.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=Ho(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=HR(t.name);o&&JR(t.name);let s=this.ctx.depth??0;We({...this.sessionIdentity(),event:"skill.dispatched",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...VR(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),...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}})}catch(u){a=u}finally{let u=Date.now()-i;o&&zR({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;We({...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:D2(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??ai,a={...t},l=r&&o!==void 0?o.filter(m=>Cd.includes(m)):r?[...Cd]:o,c=r;if(!this.ctx.childProviderFactory||s>=i)return r?a.provider=YR(a.model):l!==void 0&&(a.provider=XR(l,a.model)),{childConfig:a,childManager:void 0};let u=new re({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),d=new Dn({subagentManager:u,parentSession:jo(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||Sy.has(t.name),s;try{if(s=Ne(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=ml({childModel:i,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(i):lr(i),parentApiKey:this.ctx.apiKey}),l=new re({parentAbortSignal:r.signal,apiKey:a,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:Jt(),...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
|
+
`)}}}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 C2(e){return typeof e=="string"&&e.startsWith("sk-ant-")}function ml(e){let{childModel:t,resolved:n,parentApiKey:r}=e;return n!==void 0&&n.length>0||se(t)==="openai-compatible"?n:C2(r)?r:n}var fy=P(()=>{"use strict";it()});import{isAbsolute as A2}from"node:path";function _2(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(!A2(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 xd(e){try{return We(e).catch(()=>{})}catch{return Promise.resolve()}}function ii(e,t=240){return e.length<=t?e:e.slice(0,t)+"\u2026"}function BR(e){if(e!=null){if(typeof e=="string")return e.length;try{return JSON.stringify(e).length}catch{return}}}function I2(e){if(e==null)return;let t=BR(e);return t!==void 0&&t>P2?{truncated:!0,chars:t}:e}function M2(e){let t={status:e.status,error:ii(e.errorMessage,NR),subagent_id:e.subagentId};e.schemaErrorMessage&&(t.schemaError=ii(e.schemaErrorMessage,NR));let n=I2(e.partialOutput);return n!==void 0&&(t.partialOutput=n),t}var P2,NR,Dn,fl=P(()=>{"use strict";ze();my();it();fy();Js();Vr();Qn();Pe();Oo();Wr();Vr();P2=4096,NR=1024;Dn=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=_2(t.input)}catch(R){return{content:`Agent tool input validation failed: ${R instanceof Error?R.message:String(R)}`,isError:!0}}let r=this.ctx.depth,o=this.ctx.maxDepth??ai,s,i=this.ctx.surface!==void 0?{origin:Hr(this.ctx.surface),actor:Mn(r)}:{},a=n.model??this.ctx.defaultSubagentModel??"sonnet",l=se(a)==="openai-compatible",c=ml({childModel:a,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(a):lr(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 re({parentAbortSignal:t.signal,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),d=jo(t.signal);let R=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}:{}}),A=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,t.signal):void 0;u.provider=this.ctx.childProviderFactory({childExecutor:R,...A!==void 0?{childSkillExecutor:A}:{},...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"?sr(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":sr(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:!0}),d!==void 0&&(d.sessionId=p.id)}catch(R){let A=R instanceof Error?R.message:String(R);return xd({...i,event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:ii(A),depth:r}),{content:`Failed to fork subagent: ${A}`,isError:!0}}if(n.mode==="background"){let R=this.ctx.backgroundRegistry;if(!R)return await p.teardown().catch(O=>W("subagent-executor: handle teardown failed: "+(O instanceof Error?O.message:String(O)))),{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 A;try{A=R.register({handle:p,prompt:n.prompt,model:u.model??"sonnet",parentSessionId:this.ctx.parentSession.sessionId})}catch(O){if(O instanceof pl)return await p.teardown().catch(_=>W("subagent-executor: handle teardown failed after cap error: "+(_ instanceof Error?_.message:String(_)))),{content:O.message,isError:!0};throw O}let E={status:"running",jobId:A.jobId,subagentId:A.subagentId,label:A.label,message:`Background subagent started (jobId=${A.jobId}). It is running detached and its result will NOT auto-inject into this context. Retrieve it later via /bgsub:join ${A.jobId} or ask the user to join.`};return{content:JSON.stringify(E)}}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(R=>{y=R}),w,k=new Promise(R=>{w=R});this.promotionTriggers.set(p.id,{fire:y,ready:k});let T=p.runToResult(n.prompt);try{let R=await Promise.race([T.then(I=>({kind:"result",result:I})),S.then(()=>({kind:"promote"}))]);if(R.kind==="promote"){let I=this.ctx.backgroundRegistry;if(I)try{let L=I.adoptRunning({handle:p,runPromise:T,prompt:n.prompt,model:u.model??"sonnet",parentSessionId:h});return b=!0,t.signal.removeEventListener("abort",m),w({jobId:L.jobId,label:L.label}),{content:JSON.stringify({status:"running",jobId:L.jobId,subagentId:L.subagentId,label:L.label,message:`Subagent backgrounded by user (jobId=${L.jobId}). It keeps running detached and its result will NOT auto-inject into this context. Retrieve it via /bgsub:join ${L.jobId}.`})}}catch(L){W("subagent-executor: promotion failed, staying foreground: "+(L instanceof Error?L.message:String(L))),w(null)}else w(null)}let A=R.kind==="result"?R.result:await T;if(A.status==="succeeded"&&A.message){let I=A.message.content,L=typeof I=="string"?I:JSON.stringify(I),N=A.trace;return xd({...i,event:"subagent.completed",subagent_id:p.id,parent_session_id:h,status:A.status,duration_ms:Date.now()-g,content_chars:L.length,depth:r,tool_call_count:N?.toolCalls.length,thinking_present:N?.thinkingPresent,tool_names:N?.toolCalls.length?JSON.stringify([...new Set(N.toolCalls.map(F=>F.name))]):void 0}),{content:L}}let E=A.error?.message??"Subagent failed with no output",O=A.trace;xd({...i,event:"subagent.failed",subagent_id:p.id,id_prefix:n.id_prefix,parent_session_id:h,status:A.status,duration_ms:Date.now()-g,error_message:ii(E),schema_error:A.schemaError?ii(A.schemaError.message):void 0,partial_output_chars:BR(A.partialOutput),depth:r,tool_call_count:O?.toolCalls.length,thinking_present:O?.thinkingPresent,tool_names:O?.toolCalls.length?JSON.stringify([...new Set(O.toolCalls.map(I=>I.name))]):void 0});let _=M2({status:A.status,errorMessage:E,schemaErrorMessage:A.schemaError?.message,partialOutput:A.partialOutput,subagentId:p.id});return{content:JSON.stringify(_),isError:!0}}catch(R){let A=R instanceof Error?R.message:String(R);throw xd({...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:ii(A),depth:r}),R}finally{this.promotionTriggers.delete(p.id),w(null),b||(t.signal.removeEventListener("abort",m),await s?.teardownAll(),await p.teardown())}}}});function Rd(e,t){return`Skill tool not available at nesting depth ${e} (max ${t}). ${li}`}var li,gy=P(()=>{"use strict";li="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});function jR(e){UR.add(e)}function HR(e){return UR.has(e)}var UR,hy=P(()=>{"use strict";UR=new Set});function WR(e){yy.add(e)}function KR(e){yy.delete(e)}function GR(e){by.add(e)}function qR(e){by.delete(e)}function zR(e){for(let t of yy)t(e)}function JR(e){for(let t of by)t(e)}var yy,by,wy=P(()=>{"use strict";yy=new Set,by=new Set});function VR(e){return O2.has(e)}function D2(e,t=$2){return e.length<=t?e:e.slice(0,t)+"\u2026"}function F2(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 L2(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 O2,$2,Fn,gl=P(()=>{"use strict";Tt();ze();fr();Vr();fl();gy();fy();Js();er();zt();Qn();hy();wy();Pe();Wr();O2=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"]);$2=240;Fn=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:Hr(this.ctx.surface),actor:Mn(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??ai;if(n>=r){let l=F2(t.input);return We({...this.sessionIdentity(),event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:l}).catch(()=>{}),{content:Rd(n,r),isError:!0}}let o;try{o=L2(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||Sy.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=Ho(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=HR(t.name);o&&JR(t.name);let s=this.ctx.depth??0;We({...this.sessionIdentity(),event:"skill.dispatched",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...VR(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),...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}})}catch(u){a=u}finally{let u=Date.now()-i;o&&zR({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;We({...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:D2(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??ai,a={...t},l=r&&o!==void 0?o.filter(m=>Cd.includes(m)):r?[...Cd]:o,c=r;if(!this.ctx.childProviderFactory||s>=i)return r?a.provider=YR(a.model):l!==void 0&&(a.provider=XR(l,a.model)),{childConfig:a,childManager:void 0};let u=new re({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),d=new Dn({subagentManager:u,parentSession:jo(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||Sy.has(t.name),s;try{if(s=Be(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=ml({childModel:i,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(i):lr(i),parentApiKey:this.ctx.apiKey}),l=new re({parentAbortSignal:r.signal,apiKey:a,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:Jt(),...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]
|
|
1145
1145
|
|
|
1146
1146
|
${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(W),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]
|
|
1147
1147
|
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.
|
|
@@ -1149,9 +1149,9 @@ Arguments: ${o}`}
|
|
|
1149
1149
|
|
|
1150
1150
|
----- skill: ${t} -----
|
|
1151
1151
|
|
|
1152
|
-
${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}:{}};We({event:"skill.dispatched",...i,...VR(t)?{is_gate:!0}:{}}).catch(()=>{}),We({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=
|
|
1152
|
+
${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}:{}};We({event:"skill.dispatched",...i,...VR(t)?{is_gate:!0}:{}}).catch(()=>{}),We({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=Be(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=ml({childModel:l,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(l):lr(l),parentApiKey:this.ctx.apiKey}),u=new re({parentAbortSignal:s.signal,apiKey:c,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:Jt(),...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]
|
|
1153
1153
|
|
|
1154
|
-
${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(W),await m?.teardownAll(),await u.teardownAll()}}getPluginSkillBody(t){return this.pluginBodies||(this.pluginBodies=hl(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 jo(e){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:e}}function ci(e={}){return({childExecutor:t,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:s})=>{let i={permissions:{allowedTools:o??N2},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{}};return se(typeof r=="string"?r:void 0)==="openai-compatible"?new Nt({...i,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{},readOnlyMemory:!0}):new tt({...i,readOnlyMemory:!0})}}function YR(e){let t={allowedTools:[...Cd]};return se(typeof e=="string"?e:void 0)==="openai-compatible"?new Nt({permissions:t,readOnlyBash:!0,readOnlyMemory:!0}):new tt({permissions:t,readOnlyBash:!0,readOnlyMemory:!0})}function ui(e,t,n,r,o,s,i,a,l){let c=(u,d,p)=>new Fn({parentSession:jo(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 XR(e,t){let n={allowedTools:[...e]};return se(typeof t=="string"?t:void 0)==="openai-compatible"?new Nt({permissions:n}):new tt({permissions:n})}function ZR(e,t){let n={allowedTools:[...RR]};return se(typeof t=="string"?t:void 0)==="openai-compatible"?new Nt({permissions:n}):new tt({permissions:n})}var ai,N2,Cd,Sy,Vr=P(()=>{"use strict";Wo();al();it();nr();or();ul();gl();ai=3;N2=[...Rn,...Pt,"memory_search","agent","skill"],Cd=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...Pt,"memory_search","agent","skill"],Sy=new Set(["ground-state"])});var Ad,QR=P(()=>{"use strict";Pe();lu();er();cu();He();Bt();Ad=class{constructor(t,n,r,o,s,i,a,l,c,u,d,p,m,g,h){this.id=t;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=u;this.agentType=d;this.traceWriter=g;this.onSubagentSucceeded=h;this.progressSink=p,this.parentId=m}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;currentTrace=dl();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=au(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",To(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?(To(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(To(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=dl();let s=n??this.progressSink??Jt(),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 MR(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=vd(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??Jt();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(t,o).then(s=>{n?.(s)}).catch(s=>{W("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",To(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 Fk(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)W(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){W(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}}});var B2,re,ze=P(()=>{"use strict";Ok();di();lu();cu();He();Qn();er();Vr();QR();B2=async(e,t)=>({action:"decline"}),re=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 su(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 Dk(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:B2},...t.phaseRole==="read-only"?{provider:ZR("read-only",t.config.model)}:{}},a;try{a=new xt(i)}catch(h){throw this.abortGraph.dispose(n),h}let l=t.parent.getInputStreamRef?.(),c=t.parent.abortSignal,u=this.progressSink??Jt(),d=t.agentType?.trim()||void 0,p=t.parentId?.trim()||void 0,m=new Ad(n,a,s,this.abortGraph,t.outputSchema,t.config.timeoutMs??iu,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 To(t.config.traceWriter,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:g,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await We({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 _d(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 vy=P(()=>{"use strict"});import{fileURLToPath as U2}from"node:url";import{dirname as j2}from"node:path";var H2,Vhe,Zt,ky=P(()=>{"use strict";H2=U2(import.meta.url),Vhe=j2(H2),Zt={name:"research-agent",systemPrompt:`---
|
|
1154
|
+
${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(W),await m?.teardownAll(),await u.teardownAll()}}getPluginSkillBody(t){return this.pluginBodies||(this.pluginBodies=hl(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 jo(e){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:e}}function ci(e={}){return({childExecutor:t,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:s})=>{let i={permissions:{allowedTools:o??N2},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{}};return se(typeof r=="string"?r:void 0)==="openai-compatible"?new Nt({...i,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{},readOnlyMemory:!0}):new tt({...i,readOnlyMemory:!0})}}function YR(e){let t={allowedTools:[...Cd]};return se(typeof e=="string"?e:void 0)==="openai-compatible"?new Nt({permissions:t,readOnlyBash:!0,readOnlyMemory:!0}):new tt({permissions:t,readOnlyBash:!0,readOnlyMemory:!0})}function ui(e,t,n,r,o,s,i,a,l){let c=(u,d,p)=>new Fn({parentSession:jo(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 XR(e,t){let n={allowedTools:[...e]};return se(typeof t=="string"?t:void 0)==="openai-compatible"?new Nt({permissions:n}):new tt({permissions:n})}function ZR(e,t){let n={allowedTools:[...RR]};return se(typeof t=="string"?t:void 0)==="openai-compatible"?new Nt({permissions:n}):new tt({permissions:n})}var ai,N2,Cd,Sy,Vr=P(()=>{"use strict";Wo();al();it();nr();or();ul();gl();ai=3;N2=[...Rn,...Pt,"memory_search","agent","skill"],Cd=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...Pt,"memory_search","agent","skill"],Sy=new Set(["ground-state"])});var Ad,QR=P(()=>{"use strict";Pe();lu();er();cu();Ne();Bt();Ad=class{constructor(t,n,r,o,s,i,a,l,c,u,d,p,m,g,h){this.id=t;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=u;this.agentType=d;this.traceWriter=g;this.onSubagentSucceeded=h;this.progressSink=p,this.parentId=m}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;currentTrace=dl();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=au(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",To(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?(To(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(To(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=dl();let s=n??this.progressSink??Jt(),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 MR(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=vd(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??Jt();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(t,o).then(s=>{n?.(s)}).catch(s=>{W("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",To(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 Fk(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)W(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){W(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}}});var B2,re,ze=P(()=>{"use strict";Ok();di();lu();cu();Ne();Qn();er();Vr();QR();B2=async(e,t)=>({action:"decline"}),re=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 su(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 Dk(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:B2},...t.phaseRole==="read-only"?{provider:ZR("read-only",t.config.model)}:{}},a;try{a=new xt(i)}catch(h){throw this.abortGraph.dispose(n),h}let l=t.parent.getInputStreamRef?.(),c=t.parent.abortSignal,u=this.progressSink??Jt(),d=t.agentType?.trim()||void 0,p=t.parentId?.trim()||void 0,m=new Ad(n,a,s,this.abortGraph,t.outputSchema,t.config.timeoutMs??iu,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 To(t.config.traceWriter,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:g,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await We({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 _d(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 vy=P(()=>{"use strict"});import{fileURLToPath as U2}from"node:url";import{dirname as j2}from"node:path";var H2,Vhe,Zt,ky=P(()=>{"use strict";H2=U2(import.meta.url),Vhe=j2(H2),Zt={name:"research-agent",systemPrompt:`---
|
|
1155
1155
|
name: research-agent
|
|
1156
1156
|
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.
|
|
1157
1157
|
model: sonnet
|
|
@@ -1204,14 +1204,14 @@ Unless the dispatcher specifies a different schema, return:
|
|
|
1204
1204
|
**\`boundary_flag\` is required.** If nothing applies, emit \`"none"\` \u2014 do not omit the field. Treat missing as \`"none"\` is acceptable on the orchestrator side, but emit the field explicitly so downstream synthesizers and validators do not see \`null\`.
|
|
1205
1205
|
|
|
1206
1206
|
If \`scope_check\` flags implementation (non-git), the orchestrator should dispatch a different sub-agent type for follow-up. Do not re-dispatch the same task through \`research-agent\`.
|
|
1207
|
-
`,sourcePath:"vendored/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],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."}});import{existsSync as tC,mkdirSync as W2,readFileSync as K2,renameSync as G2,writeFileSync as q2,unlinkSync as z2}from"fs";import{dirname as eC,join as J2}from"path";import{randomBytes as V2}from"crypto";function Ce(e=ue()){if(!tC(e))return Pd();try{let t=K2(e,"utf8"),n=JSON.parse(t);if(!n||typeof n!="object")return Pd();let r=n,o=r.plugins&&typeof r.plugins=="object"?r.plugins:{};if(r.version===1)return{version:2,plugins:o,marketplaces:{}};if(r.version===2){let s=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:s}}return Pd()}catch{return Pd()}}function yl(e,t=ue()){W2(eC(t),{recursive:!0});let n=J2(eC(t),`.index.json.${process.pid}.${V2(4).toString("hex")}.tmp`),r=JSON.stringify(e,null,2);try{q2(n,r,"utf8"),G2(n,t)}catch(o){try{tC(n)&&z2(n)}catch{}throw o}}function Yr(e,t,n=ue()){let r=Ce(n);return r.plugins[e]=t,yl(r,n),r}function nC(e,t=ue()){let n=Ce(t);return e in n.plugins&&(delete n.plugins[e],yl(n,t)),n}function Ey(e,t,n=ue()){let r=Ce(n),o=r.plugins[e];if(!o)throw new Error(`plugin "${e}" is not in the index`);return o.enabled=t,o.updatedAt=new Date().toISOString(),yl(r,n),r}function bl(e,t,n=ue()){let r=Ce(n);return r.marketplaces[e]=t,yl(r,n),r}function rC(e,t=ue()){let n=Ce(t),r=!1;e in n.marketplaces&&(delete n.marketplaces[e],r=!0);for(let[o,s]of Object.entries(n.plugins))s.marketplace===e&&(delete n.plugins[o],r=!0);return r&&yl(n,t),n}function Pd(){return{version:2,plugins:{},marketplaces:{}}}var Ut=P(()=>{"use strict";K()});import{existsSync as xy,readFileSync as iC,readdirSync as Y2,realpathSync as X2,statSync as Z2}from"fs";import{join as mi,resolve as oC}from"path";function gr(){pi=void 0}function hr(e=Ze(),t={}){let n=t.trustAll===!0,r=n?`${e}\0trustAll`:e;pi||(pi=new Map);let o=pi.get(r);if(o)return[...o];if(!xy(e))return pi.set(r,[]),[];let s=e===Ze()?ue():mi(e,".index.json"),i=Ce(s),a=[];return aC(e,e,0,a,new Set,i.plugins,n),pi.set(r,a),[...a]}function aC(e,t,n,r,o,s,i){if(n>Q2)return;let a;try{a=X2(t)}catch{a=t}if(o.has(a))return;if(o.add(a),xy(mi(t,".claude-plugin","plugin.json"))){let c=Ry(e,t);if(c===null){Ty(r,t);return}if(c.layout==="cache"){if(!i){let d=s[c.key];if(!d||d.enabled===!1)return}Ty(r,t);return}let u=s[c.key];if(u&&u.enabled===!1)return;Ty(r,t);return}let l;try{l=Y2(t)}catch{return}for(let c of l){if(c.startsWith("."))continue;let u=mi(t,c),d;try{d=Z2(u)}catch{continue}d.isDirectory()&&aC(e,u,n+1,r,o,s,i)}}function eq(e){try{let t=iC(mi(e,".claude-plugin","plugin.json"),"utf8"),n=JSON.parse(t);if(n!==null&&typeof n=="object"&&"main"in n){let r=n.main;if(typeof r=="string"&&r.trim()!=="")return r}}catch{}}function Ty(e,t){let n=eq(t);e.push(n!==void 0?{type:"local",path:t,main:n}:{type:"local",path:t})}function Ry(e,t){if(!t.startsWith(e))return null;let n=t.slice(e.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(s=>s.length>0);if(r.length===0)return null;if(r[0]===sC&&r.length>=3){let s=r[1];if(s){let i=mi(e,sC,s),l=tq(i,t)??r[2];if(l)return{layout:"cache",key:`${s}:${l}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function tq(e,t){let n=mi(e,".claude-plugin","marketplace.json");if(!xy(n))return null;let r;try{r=JSON.parse(iC(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=oC(t);for(let i of o){if(!i||typeof i!="object")continue;let a=i;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&oC(e,a.source)===s)return a.name}return null}var Q2,sC,pi,Xr=P(()=>{"use strict";K();Ut();Q2=5,sC="cache"});import{existsSync as Zr,readdirSync as nq,readFileSync as rq}from"fs";import{join as yr}from"path";function cC(e=
|
|
1207
|
+
`,sourcePath:"vendored/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],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."}});import{existsSync as tC,mkdirSync as W2,readFileSync as K2,renameSync as G2,writeFileSync as q2,unlinkSync as z2}from"fs";import{dirname as eC,join as J2}from"path";import{randomBytes as V2}from"crypto";function Ce(e=ue()){if(!tC(e))return Pd();try{let t=K2(e,"utf8"),n=JSON.parse(t);if(!n||typeof n!="object")return Pd();let r=n,o=r.plugins&&typeof r.plugins=="object"?r.plugins:{};if(r.version===1)return{version:2,plugins:o,marketplaces:{}};if(r.version===2){let s=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:s}}return Pd()}catch{return Pd()}}function yl(e,t=ue()){W2(eC(t),{recursive:!0});let n=J2(eC(t),`.index.json.${process.pid}.${V2(4).toString("hex")}.tmp`),r=JSON.stringify(e,null,2);try{q2(n,r,"utf8"),G2(n,t)}catch(o){try{tC(n)&&z2(n)}catch{}throw o}}function Yr(e,t,n=ue()){let r=Ce(n);return r.plugins[e]=t,yl(r,n),r}function nC(e,t=ue()){let n=Ce(t);return e in n.plugins&&(delete n.plugins[e],yl(n,t)),n}function Ey(e,t,n=ue()){let r=Ce(n),o=r.plugins[e];if(!o)throw new Error(`plugin "${e}" is not in the index`);return o.enabled=t,o.updatedAt=new Date().toISOString(),yl(r,n),r}function bl(e,t,n=ue()){let r=Ce(n);return r.marketplaces[e]=t,yl(r,n),r}function rC(e,t=ue()){let n=Ce(t),r=!1;e in n.marketplaces&&(delete n.marketplaces[e],r=!0);for(let[o,s]of Object.entries(n.plugins))s.marketplace===e&&(delete n.plugins[o],r=!0);return r&&yl(n,t),n}function Pd(){return{version:2,plugins:{},marketplaces:{}}}var Ut=P(()=>{"use strict";K()});import{existsSync as xy,readFileSync as iC,readdirSync as Y2,realpathSync as X2,statSync as Z2}from"fs";import{join as mi,resolve as oC}from"path";function gr(){pi=void 0}function hr(e=Ze(),t={}){let n=t.trustAll===!0,r=n?`${e}\0trustAll`:e;pi||(pi=new Map);let o=pi.get(r);if(o)return[...o];if(!xy(e))return pi.set(r,[]),[];let s=e===Ze()?ue():mi(e,".index.json"),i=Ce(s),a=[];return aC(e,e,0,a,new Set,i.plugins,n),pi.set(r,a),[...a]}function aC(e,t,n,r,o,s,i){if(n>Q2)return;let a;try{a=X2(t)}catch{a=t}if(o.has(a))return;if(o.add(a),xy(mi(t,".claude-plugin","plugin.json"))){let c=Ry(e,t);if(c===null){Ty(r,t);return}if(c.layout==="cache"){if(!i){let d=s[c.key];if(!d||d.enabled===!1)return}Ty(r,t);return}let u=s[c.key];if(u&&u.enabled===!1)return;Ty(r,t);return}let l;try{l=Y2(t)}catch{return}for(let c of l){if(c.startsWith("."))continue;let u=mi(t,c),d;try{d=Z2(u)}catch{continue}d.isDirectory()&&aC(e,u,n+1,r,o,s,i)}}function eq(e){try{let t=iC(mi(e,".claude-plugin","plugin.json"),"utf8"),n=JSON.parse(t);if(n!==null&&typeof n=="object"&&"main"in n){let r=n.main;if(typeof r=="string"&&r.trim()!=="")return r}}catch{}}function Ty(e,t){let n=eq(t);e.push(n!==void 0?{type:"local",path:t,main:n}:{type:"local",path:t})}function Ry(e,t){if(!t.startsWith(e))return null;let n=t.slice(e.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(s=>s.length>0);if(r.length===0)return null;if(r[0]===sC&&r.length>=3){let s=r[1];if(s){let i=mi(e,sC,s),l=tq(i,t)??r[2];if(l)return{layout:"cache",key:`${s}:${l}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function tq(e,t){let n=mi(e,".claude-plugin","marketplace.json");if(!xy(n))return null;let r;try{r=JSON.parse(iC(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=oC(t);for(let i of o){if(!i||typeof i!="object")continue;let a=i;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&oC(e,a.source)===s)return a.name}return null}var Q2,sC,pi,Xr=P(()=>{"use strict";K();Ut();Q2=5,sC="cache"});import{existsSync as Zr,readdirSync as nq,readFileSync as rq}from"fs";import{join as yr}from"path";function cC(e=Le()){let t=[],n=yr(e,"skills");if(Zr(n))for(let r of Id(n)){let o=yr(n,r,"SKILL.md");Zr(o)&&t.push({path:o,type:"skill",source:"user"})}for(let r of lC){let o=yr(e,`${r}s`);if(Zr(o))for(let s of Id(o))s.endsWith(".md")&&t.push({path:yr(o,s),type:r,source:"user"})}return t}function uC(e=Ze()){if(!Zr(e))return[];let t=[],n=hr(e);for(let r of n){let s=Ry(e,r.path)?.key,i=yr(r.path,"skills");if(Zr(i))for(let a of Id(i)){let l=yr(i,a,"SKILL.md");if(!Zr(l))continue;let c={path:l,type:"skill",source:"plugin"};s&&(c.plugin_key=s),t.push(c)}for(let a of lC){let l=yr(r.path,`${a}s`);if(Zr(l))for(let c of Id(l)){if(!c.endsWith(".md"))continue;let u={path:yr(l,c),type:a,source:"plugin"};s&&(u.plugin_key=s),t.push(u)}}}return t}function dC(e=yr(Le(),"settings.json")){if(!Zr(e))return[];try{let t=rq(e,"utf8"),r=JSON.parse(t).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a=0;a<i.length;a++)o.push({event:s,index:a,raw:i[a]});return o}catch{return[]}}function Id(e){try{return nq(e).filter(t=>!t.startsWith("."))}catch{return[]}}var lC,pC=P(()=>{"use strict";K();Xr();lC=["command","agent"]});import{z as Ue}from"zod";import{mkdir as mC,appendFile as fC}from"fs/promises";import{join as Cy}from"path";function iq(e){return{runUserDiscovery:e!=="plugin",runPluginDiscovery:e!=="user",runHookInspector:e!=="plugin"}}function aq(e){let t=()=>{let s={};for(let i of yC)s[i]={correct:0,misfit:0,outlier:0};return s},n={user:t(),plugin:t()};for(let s of e)n[s.source][s.type][s.verdict]+=1;let r={high:0,med:1,low:2},o=e.filter(s=>s.verdict==="misfit").slice().sort((s,i)=>r[s.confidence]-r[i.confidence]);return{inventory:n,misfits:o}}function lq(e){return e.verdict==="misfit"&&e.confidence==="high"&&e.source==="user"}function cq(e){let t=e.filter(o=>o.source==="user"),n=e.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),t.length===0)r.push("(none discovered)");else for(let o of t)r.push(`- ${o.path}`);if(r.push(""),r.push('### Plugin-scope artifacts (set `"source": "plugin"`, copy `plugin_key` from each entry)'),n.length===0)r.push("(none discovered)");else for(let o of n){let s=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${s})`)}return r.join(`
|
|
1208
1208
|
`)}function uq(e,t){let n=["","## Discovered hooks (audit only these)",""];if(n.push(`Settings file (use this absolute path verbatim in each verdict's \`path\` field): \`${e}\``),n.push(""),t.length===0)return n.push("(no hooks discovered)"),n.join(`
|
|
1209
1209
|
`);for(let r of t){let o=`${r.event}-${r.index}`;n.push(`### Hook \`${o}\``),n.push(""),n.push("```json"),n.push(JSON.stringify(r.raw,null,2)),n.push("```"),n.push("")}return n.join(`
|
|
1210
|
-
`)}function dq(e,t){if(!t)return{kind:"failure",message:`${e}: no result`};if(t.schemaError)return{kind:"failure",message:`${e}: schema mismatch \u2014 ${t.schemaError.message}`};if(t.status!=="succeeded"){let n=t.error?` \u2014 ${t.error.message}`:"";return{kind:"failure",message:`${e}: ${t.status}${n}`}}return t.output?{kind:"success",output:t.output}:{kind:"failure",message:`${e}: no output`}}async function pq(e,t,n){let r=n?.apiKey,o=n?.defaultSubagentModel??n?.defaultModel??"sonnet",s=n?.callId,i=typeof e=="object"&&e!==null?e:{},a=oq.parse(i),l=a.writeBriefs??!0,c=a.scope??"all",u=iq(c);if(!t?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let d=t.sessionId,p=
|
|
1211
|
-
${cq(F)}`,artifacts:F,runPrompt:`Inspect every ${N} listed in the artifact section.`})}if(u.runHookInspector){let N=m.hook;if(N){let F=Cy(
|
|
1210
|
+
`)}function dq(e,t){if(!t)return{kind:"failure",message:`${e}: no result`};if(t.schemaError)return{kind:"failure",message:`${e}: schema mismatch \u2014 ${t.schemaError.message}`};if(t.status!=="succeeded"){let n=t.error?` \u2014 ${t.error.message}`:"";return{kind:"failure",message:`${e}: ${t.status}${n}`}}return t.output?{kind:"success",output:t.output}:{kind:"failure",message:`${e}: no output`}}async function pq(e,t,n){let r=n?.apiKey,o=n?.defaultSubagentModel??n?.defaultModel??"sonnet",s=n?.callId,i=typeof e=="object"&&e!==null?e:{},a=oq.parse(i),l=a.writeBriefs??!0,c=a.scope??"all",u=iq(c);if(!t?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let d=t.sessionId,p=Be("audit-fit"),m={skill:p["01-skill-inspector.md"],command:p["02-command-inspector.md"],agent:p["03-agent-inspector.md"],hook:p["04-hook-inspector.md"]};for(let N of yC)if(!m[N])throw new Error(`audit-fit skill missing inspector prompt for ${N}`);let g=u.runUserDiscovery?cC():[],h=u.runPluginDiscovery?uC():[],b={skill:[],command:[],agent:[]};for(let N of[...g,...h])b[N.type].push(N);let y=new re({apiKey:r,...n?.traceWriter!==void 0?{traceWriter:n.traceWriter}:{}}),S=()=>async N=>Zt.allowedTools.includes(N)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${N} not allowed for audit-fit inspectors. Allowed tools: ${Zt.allowedTools.join(", ")}`},w=[];for(let N of sq){let F=b[N];if(F.length===0)continue;let U=m[N];U&&w.push({type:N,prompt:`${U}
|
|
1211
|
+
${cq(F)}`,artifacts:F,runPrompt:`Inspect every ${N} listed in the artifact section.`})}if(u.runHookInspector){let N=m.hook;if(N){let F=Cy(Le(),"settings.json"),U=dC(F);w.push({type:"hook",prompt:`${N}
|
|
1212
1212
|
${uq(F,U)}`,artifacts:[],runPrompt:`Inspect every hook listed in the Discovered hooks section. Settings file: ${F}.`})}}let k=[];if(w.length>0){let N=await Promise.all(w.map(H=>y.forkSubagent({parent:{sessionId:d},config:{model:o,systemPrompt:`${Zt.systemPrompt}
|
|
1213
1213
|
|
|
1214
|
-
${H.prompt}`,canUseTool:S()},idPrefix:`inspector-${H.type}`,agentType:`inspector-${H.type}`,outputSchema:
|
|
1214
|
+
${H.prompt}`,canUseTool:S()},idPrefix:`inspector-${H.type}`,agentType:`inspector-${H.type}`,outputSchema:Ue.array(hC),...s?{parentId:s}:{}}))),F=await _d(w.map((H,D)=>{let C=N[D];if(!C)throw new Error(`audit-fit: missing handle for ${H.type} inspector`);return{handle:C,prompt:H.runPrompt}}),{failFast:!1}),U=[];for(let H=0;H<F.length;H++){let D=F[H],C=w[H];if(!C)continue;let B=dq(C.type,D);if(B.kind==="failure"){U.push(B.message);continue}let M=new Map;for(let j of C.artifacts)M.set(j.path,j.source);for(let j of B.output){if(C.type==="hook"){if(j.source!=="user"){U.push(`${C.type}: hook verdict has source=${j.source} (must be 'user')`);continue}}else{let X=M.get(j.path);if(X===void 0){U.push(`${C.type}: verdict for unknown path ${j.path} (not in discovered list)`);continue}if(j.source!==X){U.push(`${C.type}: verdict source mismatch for ${j.path} (expected ${X}, got ${j.source})`);continue}}k.push(j)}}if(U.length>0){let H=U.map(D=>` - ${D}`).join(`
|
|
1215
1215
|
`);throw new Error(`audit-fit: ${U.length} inspector failure(s):
|
|
1216
1216
|
${H}`)}}let{inventory:T,misfits:R}=aq(k),A=0;if(l){let N=Ts();await mC(N,{recursive:!0});for(let F of R.filter(lq)){let U=F.path.replace(/[^a-z0-9]+/gi,"-").toLowerCase().slice(0,30),H=Cy(N,`audit-fit-${U}.md`),D=`---
|
|
1217
1217
|
theme: audit-fit
|
|
@@ -1236,7 +1236,7 @@ ${F.rationale}
|
|
|
1236
1236
|
---
|
|
1237
1237
|
Generated by audit-fit on ${new Date().toISOString().split(".")[0]}Z
|
|
1238
1238
|
`;await fC(H,D),A++}}let E=Mt();await mC(E,{recursive:!0});let O=N=>{let F=0;for(let U of Object.values(N))for(let H of Object.values(U))F+=H;return F},_=N=>{let F=T.user[N]??{},U=T.plugin[N]??{},H=D=>Object.values(D).reduce((C,B)=>C+B,0);return H(F)+H(U)},I={timestamp:new Date().toISOString(),surface:"afk",scope:c,total_artifacts:k.length,misfits_count:R.length,briefs_written:A,by_source:{user:O(T.user),plugin:O(T.plugin)},by_type:{skill:_("skill"),command:_("command"),agent:_("agent"),hook:_("hook")}},L=Cy(E,"audit-fit-telemetry.jsonl");return await fC(L,JSON.stringify(I)+`
|
|
1239
|
-
`),{inventory:T,misfits:R,briefs_written:A,total_artifacts:k.length}}var hC,gC,kye,oq,sq,yC,mq,bC=P(()=>{"use strict";zt();Tt();ze();vy();ky();K();pC();hC=
|
|
1239
|
+
`),{inventory:T,misfits:R,briefs_written:A,total_artifacts:k.length}}var hC,gC,kye,oq,sq,yC,mq,bC=P(()=>{"use strict";zt();Tt();ze();vy();ky();K();pC();hC=Ue.object({path:Ue.string(),type:Ue.enum(["skill","command","agent","hook"]),source:Ue.enum(["user","plugin"]),plugin_key:Ue.string().optional(),verdict:Ue.enum(["correct","misfit","outlier"]),recommended_type:Ue.string(),rationale:Ue.string(),confidence:Ue.enum(["high","med","low"])}),gC=Ue.record(Ue.string(),Ue.record(Ue.string(),Ue.number())),kye=Ue.object({inventory:Ue.object({user:gC,plugin:gC}),misfits:Ue.array(hC),briefs_written:Ue.number(),total_artifacts:Ue.number()}),oq=Ue.object({writeBriefs:Ue.boolean().optional(),scope:Ue.enum(["user","plugin","all"]).optional()}),sq=["skill","command","agent"],yC=["skill","command","agent","hook"];mq={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:pq,argumentHint:"[--write-briefs]",whenToUse:"When the user wants ~/.afk artifacts (skills, commands, agents, hooks) audited for correct type categorization.",flags:["--write-briefs"],audience:"internal"};ht(mq)});import{z as te}from"zod";var Md,wC,Od,SC,vC,kC,fq,EC,$d=P(()=>{"use strict";Md=te.object({id:te.string(),claim:te.string(),confidence:te.number().min(0).max(1),evidence_sources:te.array(te.string()),location:te.string().optional(),proposed_fix:te.string().optional(),coverage_gaps:te.array(te.string()).nullish().transform(e=>e??void 0),boundary_flag:te.string().nullish().transform(e=>e??void 0)}),wC=te.object({hypothesis_id:te.string(),claim:te.string(),verdict:te.enum(["VERIFIED","REFUTED","INCONCLUSIVE"]),evidence:te.string(),gate_reason:te.string()}),Od=te.object({hypothesis_id:te.string(),predicted_pass:te.boolean(),regressions:te.array(te.string()),confidence:te.number().min(0).max(1),verification_log:te.string()}),SC=te.enum(["crash","regression","logic-error","flaky","environment","unknown"]),vC=te.object({failure_type:SC,error_signature:te.string(),affected_area:te.string()}),kC=te.enum(["clear_winner","multiple_plausible","dissent","all_inconclusive","no_hypotheses"]),fq=te.object({reproducer:te.string().optional(),triage:vC.optional(),hypotheses:te.array(Md),premise_verifications:te.array(wC).optional(),winner:te.object({hypothesis_id:te.string(),verification_log:te.string(),proposed_fix:te.string()}).optional(),verification_results:te.array(Od).optional(),outcome:kC.optional(),recommended_next_skill:te.enum(["spec"]).optional()}),EC=te.object({verifications:te.array(te.object({claim:te.string().optional(),verdict:te.string(),evidence:te.string().optional()}))})});function Ay(e,t){let n=`${e}
|
|
1240
1240
|
${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(`
|
|
1241
1241
|
`).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 _y(e){let n=`${e.proposed_fix??""}
|
|
1242
1242
|
${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 Py(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 Iy=P(()=>{"use strict"});function TC(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 xC=P(()=>{"use strict"});import{execFile as gq}from"node:child_process";import{promisify as hq}from"node:util";function bq(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 wq(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 My(e){let t=wq(e);for(let n of t){let r;try{r=JSON.parse(n)}catch{continue}let o=EC.safeParse(r);if(o.success)return o.data.verifications.map(s=>({claim:s.claim??"",verdict:bq(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 Dd(e,t){return e.length<=t?e:`...[truncated]
|
|
@@ -1252,7 +1252,7 @@ Working directory (isolated): ${n}
|
|
|
1252
1252
|
|
|
1253
1253
|
`+o}async function Dy(e,t){let n=e.map(l=>({hypothesis:l,decision:TC(l)})).filter(l=>l.decision.verify);if(n.length===0)return{premise_verifications:[],hypotheses_to_test:e};let r=[],o;try{let l=await t(n.map(c=>c.hypothesis.claim));r=Array.isArray(l)?l:[]}catch(l){o=l instanceof Error?l.message:String(l)}let s=n.map((l,c)=>{let u=r[c];return o!==void 0?{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:"INCONCLUSIVE",evidence:`shadow-verify dispatch failed: ${o}`,gate_reason:l.decision.reason}:u?{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:u.verdict,evidence:u.evidence,gate_reason:l.decision.reason}:{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:"INCONCLUSIVE",evidence:"no verifier result for this claim",gate_reason:l.decision.reason}}),i=new Set(s.filter(l=>l.verdict==="REFUTED").map(l=>l.hypothesis_id)),a=i.size===0?e:e.filter(l=>!i.has(l.id));return{premise_verifications:s,hypotheses_to_test:a}}var yq,Fy=P(()=>{"use strict";J();xC();$d();yq=hq(gq)});import{fileURLToPath as vq}from"node:url";import{dirname as kq}from"node:path";var Eq,Lye,RC,CC=P(()=>{"use strict";Eq=vq(import.meta.url),Lye=kq(Eq),RC={name:"git-investigator",systemPrompt:'---\nname: git-investigator\ndescription: Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.\nmodel: sonnet\ntools: Bash, Read, Grep, Glob\n---\n\nYou are `git-investigator`, a leaf sub-agent specialized for read-only git queries.\n\nYou have Bash, Read, Grep, and Glob. You do not dispatch other sub-agents. You do not Edit or Write. Your Bash surface is restricted **by this prompt** to `git ...` invocations and benign output-shaping pipes.\n\n## Allowed commands\n\nRead-only git only:\n\n- `git status`, `git log`, `git diff`, `git show`\n- `git rev-parse`, `git rev-list`, `git reflog`\n- `git branch -v / -vv / -a` (list only)\n- `git remote -v`, `git ls-remote`\n- `git ls-files`, `git blame`\n- `git merge-base`, `git for-each-ref`, `git describe`\n- `git cat-file`, `git shortlog`\n- `git tag` (list/show only)\n- `git stash list`, `git stash show`\n- `git config --get`, `git config --get-all`, `git config --list`\n- `git worktree list` (read only)\n\nOutput-shaping pipes are fine: `| head`, `| tail`, `| wc`, `| grep`, `| jq`, `| awk \'NR==...\'` (for formatting only \u2014 no mutations).\n\n## Forbidden\n\nAnything that mutates repo or working tree state:\n\n- `commit`, `push`, `pull`, `fetch --prune`\n- `reset`, `revert`, `rebase`, `merge`, `cherry-pick`\n- `checkout` (except `checkout -- <path>` file-restore, and even that is mutation \u2014 avoid it, just report the need)\n- `restore`, `switch`\n- `branch -d / -D / -m / -M`, `branch <new>`\n- `stash push / pop / drop / apply / clear`\n- `tag -d`, creating a new tag\n- `remote add / remove / set-url`\n- `config --set`, `config --unset`\n- `gc`, `fsck`, `prune`, `reflog delete`, `reflog expire`\n- `filter-branch`, `filter-repo`\n- `worktree add / remove / move`\n- `hooks install`, `submodule add / update`\n- Any non-`git` command that mutates: `rm`, `mv`, `cp` (writes), `sed -i`, `> file`, `>> file`, `tee`, `curl`, `wget`, `pip install`, shell builtins that change state.\n\nIf the caller asks for any of the above, do not run it. Return `scope_check: "requires mutation: <reason>"` and stop.\n\n## Behavior\n\n- Run the minimum set of commands needed. Prefer `git log -n 5 --oneline -- <path>` over `git log -- <path>` when a count is fine.\n- Cite concrete evidence: commit SHAs (short form OK), ref names, `path:line` references from blame, diff hunks trimmed to the relevant range.\n- Use `Read`/`Grep`/`Glob` for follow-up inspection of files the git output identifies (e.g., `git show SHA:path | head` then `Read` the current file to diff mentally).\n- Do not speculate beyond what the commands show. If a question needs history the commands don\'t surface (deleted-file recovery, ancient reflog that has expired), say so in `caveats`.\n- Keep output compact \u2014 dispatchers merge your findings into a larger response. No preamble, no ceremony.\n\n## Return shape\n\n```\n{\n "findings": "<summary of what the git data shows>",\n "evidence": ["<SHA>", "<ref>", "<path:line>", ...],\n "git_commands_run": ["git log ...", "git diff ...", ...],\n "caveats": "<gaps, ambiguity, or \'none\'>",\n "scope_check": "pure git research" | "requires mutation: <reason>"\n}\n```\n\nBegin your response with the first schema field. No preamble.\n',sourcePath:"vendored/git-investigator.md",allowedTools:["Bash","Read","Grep","Glob"],description:"Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.",model:"sonnet"}});function AC(e){let t={description:e.description,prompt:e.systemPrompt};return e.allowedTools&&(t.tools=[...e.allowedTools]),e.model&&(t.model=e.model),t}var _C=P(()=>{"use strict"});import{z as PC}from"zod";import{execFile as Tq}from"node:child_process";import{promisify as xq}from"node:util";import{tmpdir as Rq}from"node:os";import{join as IC}from"node:path";function MC(){return async e=>Zt.allowedTools.includes(e)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${e} not allowed. Allowed tools: ${Zt.allowedTools.join(", ")}`}}function Cq(){return async e=>OC.includes(e)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${e} not allowed for git orchestrator. Allowed tools: ${OC.join(", ")}`}}function Aq(){let e=["Edit","Write","Bash","Agent","Task"];return async t=>e.includes(t)?{behavior:"deny",message:`Tool ${t} not allowed in worktree verification. Verification is read-only.`}:Zt.allowedTools.includes(t)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${t} not allowed. Allowed tools: ${Zt.allowedTools.join(", ")}`}}function _q(e){if(!e)return;let t=[/test:\s*(.+)/i,/command:\s*(.+)/i,/reproducer:\s*(.+)/i,/failing test:\s*(.+)/i];for(let n of t){let r=e.match(n);if(r)return r[1]}}async function Pq(e,t,n,r,o,s,i,a,l="sonnet"){let c=IC(Rq(),`diagnose-hyp-${e.id}-${Date.now()}`),u;try{await Fd("git",["worktree","add","--detach",c,"HEAD"],{cwd:n});try{let{writeFile:g}=await import("node:fs/promises"),h="",b="";try{h=(await Fd("git",["rev-parse","HEAD"],{cwd:n})).stdout.trim()}catch{}try{b=(await Fd("git",["symbolic-ref","--short","HEAD"],{cwd:n})).stdout.trim()}catch{}await g(IC(c,".afk-worktree-meta.json"),JSON.stringify({owner:"diagnose",createdAt:new Date().toISOString(),baseSha:h,baseBranch:b},null,2),"utf-8")}catch{}u=await s.forkSubagent({parent:{sessionId:r},config:{model:l,systemPrompt:`${o}
|
|
1254
1254
|
|
|
1255
|
-
You are testing in an isolated worktree at: ${c}`,canUseTool:Aq()},idPrefix:`diagnose-verifier-${e.id}`,agentType:`diagnose-verifier-${e.id}`,outputSchema:Od,...i?{parentId:i}:{}});let p=$y(e,t,c,a??{skipped:!0,reason:"baseline not computed",exitCode:null,stdout:"",stderr:"",timedOut:!1}),m=await u.runToResult(p);return m.status!=="succeeded"||!m.output?{hypothesis_id:e.id,predicted_pass:!1,regressions:[],confidence:0,verification_log:`Verification failed: ${et(m)}`}:m.output}catch(d){return{hypothesis_id:e.id,predicted_pass:!1,regressions:[],confidence:0,verification_log:`Error during verification: ${d instanceof Error?d.message:String(d)}`}}finally{if(u)try{await u.teardown()}catch{}try{await Fd("git",["worktree","remove","--force",c],{cwd:n})}catch{}}}async function $C(e,t,n){let r=n?.apiKey,o=n?.defaultSubagentModel??n?.defaultModel??"sonnet",s=(()=>{if(typeof e=="string")return{failure:e,repoPath:process.cwd(),context:"",maxHypotheses:4};if(typeof e=="object"&&e!==null){let Z=e;if(typeof Z.failure=="string")return{failure:Z.failure,repoPath:Z.repoPath||process.cwd(),context:Z.context||"",maxHypotheses:Math.min(Z.maxHypotheses||4,4)}}throw new Error("diagnose handler requires input.failure (string) or a string argument")})();if(!t?.sessionId)throw new Error("diagnose requires a parent session with sessionId");let i=t.sessionId,a=
|
|
1255
|
+
You are testing in an isolated worktree at: ${c}`,canUseTool:Aq()},idPrefix:`diagnose-verifier-${e.id}`,agentType:`diagnose-verifier-${e.id}`,outputSchema:Od,...i?{parentId:i}:{}});let p=$y(e,t,c,a??{skipped:!0,reason:"baseline not computed",exitCode:null,stdout:"",stderr:"",timedOut:!1}),m=await u.runToResult(p);return m.status!=="succeeded"||!m.output?{hypothesis_id:e.id,predicted_pass:!1,regressions:[],confidence:0,verification_log:`Verification failed: ${et(m)}`}:m.output}catch(d){return{hypothesis_id:e.id,predicted_pass:!1,regressions:[],confidence:0,verification_log:`Error during verification: ${d instanceof Error?d.message:String(d)}`}}finally{if(u)try{await u.teardown()}catch{}try{await Fd("git",["worktree","remove","--force",c],{cwd:n})}catch{}}}async function $C(e,t,n){let r=n?.apiKey,o=n?.defaultSubagentModel??n?.defaultModel??"sonnet",s=(()=>{if(typeof e=="string")return{failure:e,repoPath:process.cwd(),context:"",maxHypotheses:4};if(typeof e=="object"&&e!==null){let Z=e;if(typeof Z.failure=="string")return{failure:Z.failure,repoPath:Z.repoPath||process.cwd(),context:Z.context||"",maxHypotheses:Math.min(Z.maxHypotheses||4,4)}}throw new Error("diagnose handler requires input.failure (string) or a string argument")})();if(!t?.sessionId)throw new Error("diagnose requires a parent session with sessionId");let i=t.sessionId,a=Be("diagnose"),l=a["system.md"],c=a["research.md"],u=a["hypothesis.md"],d=a["verify.md"];if(!l||!c||!u||!d)throw new Error("diagnose skill missing required prompts (system.md, research.md, hypothesis.md, verify.md)");let p=new re({apiKey:r,...n?.traceWriter!==void 0?{traceWriter:n.traceWriter}:{}}),m=_q(s.context),g=Ay(s.failure,s.context),h=`Triage:
|
|
1256
1256
|
failure_type: ${g.failure_type}
|
|
1257
1257
|
error_signature: ${g.error_signature}
|
|
1258
1258
|
affected_area: ${g.affected_area}`,y=`${Zt.systemPrompt}
|
|
@@ -1448,15 +1448,15 @@ ${Dq}
|
|
|
1448
1448
|
|
|
1449
1449
|
${r}`}function fi(){let e=$q(),t=It(),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:Fq(e,n),source:i}}function Ae(){let e=v.AFK_MODEL??v.CLAUDE_MODEL;return Je(e)}function Ld(){return th()}function Je(e){return lr(e)}function Rt(){let e=v.AFK_MODEL??v.CLAUDE_MODEL;return!e||e.length===0?"sonnet":e}function Qt(e){let t=v.AFK_DEFAULT_SUBAGENT_MODEL;return t&&t.length>0?t:typeof e=="string"&&se(e)==="openai-compatible"?e:"sonnet"}function Qr(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 eo(e){if(e!==void 0){if(NC.includes(e))return e;throw new Error(`Invalid --effort value: ${e}. Expected one of: ${NC.join(", ")}`)}}function gi(){return Qr(v.AFK_THINKING)}function hi(){return eo(v.AFK_EFFORT)}function yi(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 yi(v.AFK_MAX_BUDGET_USD)}function Ny(){return yi(v.AFK_TASK_BUDGET)}function bi(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 wl(){return bi(v.AFK_MAX_OUTPUT_TOKENS)}function wi(e,t){let n=e;if(n===void 0&&t?.model!==void 0&&se(t.model,{...t.openaiBaseUrl!==void 0?{openaiBaseUrl:t.openaiBaseUrl}:{}})==="openai-compatible"&&(n="openai-compatible"),n===void 0)return;if(!BC.includes(n))throw new Error(`Invalid --provider value: ${n}. Expected one of: ${BC.join(", ")}`);let r=()=>{let o=[...Rn,...Io,...Pt,pr];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 tt({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 Nt({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}:{}})}function UC(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.addReadRoot=="function"&&typeof t.addWriteRoot=="function"&&typeof t.revokeRoot=="function"&&typeof t.getGrants=="function"}var Dq,NC,BC,Ve=P(()=>{"use strict";it();al();nr();dn();or();Qa();Ft();Js();J();Dq=`# Operator configuration
|
|
1450
1450
|
|
|
1451
|
-
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.`;NC=["low","medium","high","xhigh","max"];BC=["anthropic","anthropic-direct","openai-codex","openai","openai-compatible"]});async function jC(e,t,n,r,o="sonnet"){let i=
|
|
1451
|
+
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.`;NC=["low","medium","high","xhigh","max"];BC=["anthropic","anthropic-direct","openai-codex","openai","openai-compatible"]});async function jC(e,t,n,r,o="sonnet"){let i=Be("mint")["spec.md"];if(!i)throw new Error("mint skill missing spec.md prompt");let c=await(await new re(n!==void 0?{cwd:n}:{}).forkSubagent({parent:{sessionId:t},config:{model:o,systemPrompt:i,apiKey:Ae()},idPrefix:"mint-spec",agentType:"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: ${et(c)}`);return c.message.content}var HC=P(()=>{"use strict";ze();Bt();Ve();zt()});async function WC(e,t,n,r,o="sonnet"){let i=Be("mint")["research.md"];if(!i)throw new Error("mint skill missing research.md prompt");let c=await(await new re(n!==void 0?{cwd:n}:{}).forkSubagent({parent:{sessionId:t},config:{model:o,systemPrompt:i,apiKey:Ae()},idPrefix:"mint-research",agentType:"mint-research",phaseRole:"read-only",...r?{parentId:r}:{}})).runToResult(`Gather context and research for this specification:
|
|
1452
1452
|
|
|
1453
|
-
${e}`);if(c.status!=="succeeded"||!c.message)throw new Error(`research phase failed: ${et(c)}`);return c.message.content}var KC=P(()=>{"use strict";ze();Bt();Ve();zt()});async function GC(e,t,n,r,o,s="sonnet"){let a=
|
|
1453
|
+
${e}`);if(c.status!=="succeeded"||!c.message)throw new Error(`research phase failed: ${et(c)}`);return c.message.content}var KC=P(()=>{"use strict";ze();Bt();Ve();zt()});async function GC(e,t,n,r,o,s="sonnet"){let a=Be("mint")["plan.md"];if(!a)throw new Error("mint skill missing plan.md prompt");let c=await new re(r!==void 0?{cwd:r}:{}).forkSubagent({parent:{sessionId:n},config:{model:s,systemPrompt:a,apiKey:Ae()},idPrefix:"mint-plan",agentType:"mint-plan",phaseRole:"read-only",...o?{parentId:o}:{}}),u=`Specification:
|
|
1454
1454
|
${e}
|
|
1455
1455
|
|
|
1456
1456
|
Research findings:
|
|
1457
1457
|
${t}
|
|
1458
1458
|
|
|
1459
|
-
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: ${et(d)}`);return d.message.content}var qC=P(()=>{"use strict";ze();Bt();Ve();zt()});function Lq(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 zC(e,t,n,r="sonnet"){if(Lq(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=hl().get("parallelize");if(!a)return{kind:"skipped",reason:"skill-body-missing"};let l=new re({parentAbortSignal:t.abortSignal,apiKey:Ae(),...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",agentType:"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 JC=P(()=>{"use strict";Tt();fr();ze();Ve()});function Si(e){let t=Jt();t&&t({type:"panel",spec:e},{subagentId:"__main__"})}var Nd=P(()=>{"use strict";er()});import{z as br}from"zod";async function VC(e,t,n,r,o,s="sonnet"){let a=
|
|
1459
|
+
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: ${et(d)}`);return d.message.content}var qC=P(()=>{"use strict";ze();Bt();Ve();zt()});function Lq(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 zC(e,t,n,r="sonnet"){if(Lq(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=hl().get("parallelize");if(!a)return{kind:"skipped",reason:"skill-body-missing"};let l=new re({parentAbortSignal:t.abortSignal,apiKey:Ae(),...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",agentType:"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 JC=P(()=>{"use strict";Tt();fr();ze();Ve()});function Si(e){let t=Jt();t&&t({type:"panel",spec:e},{subagentId:"__main__"})}var Nd=P(()=>{"use strict";er()});import{z as br}from"zod";async function VC(e,t,n,r,o,s="sonnet"){let a=Be("mint")["build.md"];if(!a)throw new Error("mint skill missing build.md prompt");let c=await new re(r!==void 0?{cwd:r}:{}).forkSubagent({parent:{sessionId:n},config:{model:s,systemPrompt:a,apiKey:Ae()},idPrefix:"mint-build",agentType:"mint-build",outputSchema:Nq,...o?{parentId:o}:{}}),u=`Implementation plan:
|
|
1460
1460
|
${e}
|
|
1461
1461
|
|
|
1462
1462
|
`+(t?`Wave orchestration plan:
|
|
@@ -1470,12 +1470,12 @@ ${JSON.stringify(n,null,2)}
|
|
|
1470
1470
|
|
|
1471
1471
|
Mode: ${e}
|
|
1472
1472
|
|
|
1473
|
-
Run ${e} verification on the implementation.`,d;try{d=await c.runToResult(u)}finally{await c.teardown().catch(()=>{})}if(d.status!=="succeeded"||!d.output)return{passed:!1,issues:[`${e} verification failed: ${et(d)}`]};let p=d.output,m=p.status==="PASS";return{passed:m,issues:m?void 0:p.issues}}async function Bd(e,t,n,r,o,s="sonnet"){let a=
|
|
1473
|
+
Run ${e} verification on the implementation.`,d;try{d=await c.runToResult(u)}finally{await c.teardown().catch(()=>{})}if(d.status!=="succeeded"||!d.output)return{passed:!1,issues:[`${e} verification failed: ${et(d)}`]};let p=d.output,m=p.status==="PASS";return{passed:m,issues:m?void 0:p.issues}}async function Bd(e,t,n,r,o,s="sonnet"){let a=Be("mint")["verify.md"];if(!a)throw new Error("mint skill missing verify.md prompt");let[l,c,u]=await Promise.all([By("test",e,t,n,a,r,o,s),By("lint",e,t,n,a,r,o,s),By("design-review",e,t,n,a,r,o,s)]),d=[];l.issues&&d.push(...l.issues),c.issues&&d.push(...c.issues),u.issues&&d.push(...u.issues);let p={testsPassed:l.passed,lintPassed:c.passed,designReviewPassed:u.passed,...d.length>0?{issues:d}:{}},m=p.testsPassed&&p.lintPassed&&p.designReviewPassed,g=h=>h?"passed":"failed";return Si({kind:m?"checkpoint":"diagnosis",title:"verify",body:[`Tests: ${g(p.testsPassed)} \xB7 Lint: ${g(p.lintPassed)}`,`Design review: ${g(p.designReviewPassed)}`,...m?["Next: ship"]:[`Issues: ${d.length} (heal loop will retry)`]]}),p}var Bq,Uy=P(()=>{"use strict";ze();Bt();Ve();zt();Nd();Bq=vi.object({status:vi.enum(["PASS","FAIL"]),status_reason:vi.string().optional(),issues:vi.array(vi.string()).default([]),summary:vi.string().optional()})});async function XC(e,t,n,r,o,s,i="sonnet"){if(n.testsPassed&&n.lintPassed&&n.designReviewPassed)return{healed:!0,newHealIterations:r,newVerifyResults:n};if(r>=2)return{healed:!1,newHealIterations:r,newVerifyResults:n};try{let a=Ge("diagnose"),l=`Verification failures:
|
|
1474
1474
|
Tests: ${n.testsPassed?"PASS":"FAIL"}
|
|
1475
1475
|
Lint: ${n.lintPassed?"PASS":"FAIL"}
|
|
1476
1476
|
Design: ${n.designReviewPassed?"PASS":"FAIL"}
|
|
1477
1477
|
Issues: ${n.issues?.join(`
|
|
1478
|
-
`)||"none"}`,c=await a.handler({failure:l,repoPath:o.cwd??process.cwd(),context:e}),u="";if(typeof c=="object"&&c!==null&&"winner"in c&&typeof c.winner=="object"&&c.winner!==null){let T=c.winner;typeof T.proposed_fix=="string"&&(u=T.proposed_fix)}let p=
|
|
1478
|
+
`)||"none"}`,c=await a.handler({failure:l,repoPath:o.cwd??process.cwd(),context:e}),u="";if(typeof c=="object"&&c!==null&&"winner"in c&&typeof c.winner=="object"&&c.winner!==null){let T=c.winner;typeof T.proposed_fix=="string"&&(u=T.proposed_fix)}let p=Be("mint")["heal.md"];if(!p)throw new Error("mint skill missing heal.md prompt");let g=await new re(o.cwd!==void 0?{cwd:o.cwd}:{}).forkSubagent({parent:{sessionId:o.sessionId},config:{model:i,systemPrompt:p,apiKey:Ae()},idPrefix:"mint-heal",agentType:"mint-heal",...s?{parentId:s}:{}}),h=n.issues?.join(`
|
|
1479
1479
|
`)??"none",b=`Plan:
|
|
1480
1480
|
${e}
|
|
1481
1481
|
|
|
@@ -1485,7 +1485,7 @@ ${u}
|
|
|
1485
1485
|
Verification issues:
|
|
1486
1486
|
${h}
|
|
1487
1487
|
|
|
1488
|
-
Apply the fix and update the implementation.`,y=await g.runToResult(b);if(y.status!=="succeeded"||!y.message)throw new Error(`heal phase failed: ${et(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 k=await Bd(e,t,o.sessionId,o.cwd,s,i);return{healed:k.testsPassed&&k.lintPassed&&k.designReviewPassed,newHealIterations:w,newVerifyResults:k}}catch{return{healed:!1,newHealIterations:r+1,newVerifyResults:n}}}var ZC=P(()=>{"use strict";Tt();ze();Bt();Ve();zt();Uy()});async function QC(e,t,n,r,o="sonnet"){let i=
|
|
1488
|
+
Apply the fix and update the implementation.`,y=await g.runToResult(b);if(y.status!=="succeeded"||!y.message)throw new Error(`heal phase failed: ${et(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 k=await Bd(e,t,o.sessionId,o.cwd,s,i);return{healed:k.testsPassed&&k.lintPassed&&k.designReviewPassed,newHealIterations:w,newVerifyResults:k}}catch{return{healed:!1,newHealIterations:r+1,newVerifyResults:n}}}var ZC=P(()=>{"use strict";Tt();ze();Bt();Ve();zt();Uy()});async function QC(e,t,n,r,o="sonnet"){let i=Be("mint")["ship.md"];if(!i)throw new Error("mint skill missing ship.md prompt");let l=await new re(n!==void 0?{cwd:n}:{}).forkSubagent({parent:{sessionId:t},config:{model:o,systemPrompt:i,apiKey:Ae()},idPrefix:"mint-ship",agentType:"mint-ship",...r?{parentId:r}:{}}),c=`Idea: ${e.idea}
|
|
1489
1489
|
|
|
1490
1490
|
Specification:
|
|
1491
1491
|
${e.spec}
|
|
@@ -1517,7 +1517,7 @@ ${t.body}`)}var nz,Ky=P(()=>{"use strict";nz=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9
|
|
|
1517
1517
|
`)}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
|
|
1518
1518
|
`),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 kz(e){return e!==void 0?e:new Set([...Rn,...Pt,"memory_search","agent","skill"])}var bz,SA=P(()=>{"use strict";nr();or();bz={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"}});import{z as G}from"zod";var Sl,Ez,Tz,Vy,vA,kA,EA,TA,vl,Hd=P(()=>{"use strict";Sl=1,Ez=G.object({toolName:G.string(),toolUseId:G.string().optional(),input:G.string().optional(),inputRaw:G.string().optional(),result:G.string().optional(),isError:G.boolean().optional()}).passthrough(),Tz=G.object({user:G.string().default(""),assistant:G.string().default(""),timestamp:G.number().optional(),toolEvents:G.array(Ez).optional()}).passthrough(),Vy=G.object({sessionId:G.string().optional(),name:G.string().optional(),source:G.enum(["cli","telegram"]).optional(),telegramChatId:G.number().optional(),model:G.string(),startedAt:G.number(),savedAt:G.number(),totalTurns:G.number(),totalCostUsd:G.number().optional(),totalTokens:G.number().optional(),totalDurationMs:G.number().optional(),turns:G.array(Tz).default([]),forkedFrom:G.string().optional(),forkedAt:G.number().optional()}).passthrough(),vA=G.enum(["fully_achieved","partially_achieved","not_achieved","aborted"]),kA=G.enum(["not_persisted","persisted","unknown"]),EA=G.object({tool:G.string(),label:G.string().optional()}),TA=G.object({files_written:G.number().int(),files_edited:G.number().int(),bash_commands:G.number().int(),commits:G.number().int(),mutated:G.boolean()}),vl=G.object({facet_version:G.number().int(),session_id:G.string(),source:G.enum(["cli","telegram","unknown"]),model:G.string(),derived_at:G.string(),derived_from:G.literal("afk-session"),source_session_path:G.string(),source_session_mtime_ms:G.number(),subagent_persistence:kA,start_time:G.string(),end_time:G.string(),duration_minutes:G.number(),underlying_goal:G.string(),first_prompt:G.string(),goal_categories:G.record(G.string(),G.number()),session_type:G.string(),brief_summary:G.string(),total_turns:G.number().int(),user_message_count:G.number().int(),assistant_message_count:G.number().int(),tool_counts:G.record(G.string(),G.number()),commands:G.array(G.string()),skills:G.array(G.string()),subagents:G.array(EA),tool_errors:G.number().int(),tool_error_categories:G.record(G.string(),G.number()),friction_counts:G.record(G.string(),G.number()),friction_detail:G.string(),outcome:vA,primary_success:G.string(),world_changes:TA,decisions:G.array(G.string()),evidence_pointers:G.array(G.string())}).passthrough()});import{basename as xz}from"path";function Iz(e){if(e)try{let t=JSON.parse(e);return t&&typeof t=="object"?t:void 0}catch{return}}function Wd(e){return typeof e=="string"?e:void 0}function Kd(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Mz(e){return e.replace(/[-_]+/g," ").trim()}function Oz(e,t){return RA.test(e)?"slash_command":t==="telegram"?"chat":"task"}function $z(e){let t=new Map,n=[];for(let r of e)r.toolUseId===void 0?n.push(r):t.set(r.toolUseId,r);return[...t.values(),...n]}function kl(e,t={}){let n=e.turns??[],r=$z(n.flatMap(H=>H.toolEvents??[])),o={},s={},i=[],a=[],l=[],c=0,u=0,d=0,p=0,m=0;for(let H of r){let D=H.toolName;o[D]=(o[D]??0)+1,H.isError===!0&&(c+=1,s[D]=(s[D]??0)+1);let C=Iz(H.inputRaw??H.input);if(D==="write_file"&&(u+=1),D==="edit_file"&&(d+=1),D==="bash"){p+=1;let B=Wd(C?.command)??H.input;B&&Pz.test(B)&&(m+=1)}if(Cz.has(D)){let B=Wd(C?.file_path);B&&!l.includes(B)&&l.length<_z&&l.push(B)}if(Rz.has(D)){let B;D==="skill"?(B=Wd(C?.name),B&&!a.includes(B)&&a.push(B)):D==="agent"?B=Wd(C?.id_prefix):B="compose",i.push(B?{tool:D,label:B}:{tool:D})}}let g=n[0]?.user??"",h=e.source??"cli",b=Oz(g,h),y=[];for(let H of n){let C=RA.exec(H.user??"")?.[1];C&&!y.includes(C)&&y.push(C)}let S=n.filter(H=>(H.user??"").trim().length>0).length,w=n.filter(H=>(H.assistant??"").trim().length>0).length,k=[...n].reverse().find(H=>(H.assistant??"").trim().length>0)?.assistant??"",T;n.length===0?T="aborted":k.trim().length===0?T="partially_achieved":T="fully_achieved";let A=T==="fully_achieved"||T==="partially_achieved"?Kd(k||g||b,160)||b:"none",E=c>0?`${c} tool error(s): ${Object.entries(s).map(([H,D])=>`${H}\xD7${D}`).join(", ")}`:"",O=e.name?Mz(e.name):Kd(g,80),_=Kd(k||g,Az),I=Kd(O?`${O} \u2014 ${_}`:_,400)||"empty session",L=e.sessionId??(t.sourceSessionPath?xz(t.sourceSessionPath,".json"):"unknown"),N=e.totalDurationMs&&e.totalDurationMs>0?e.totalDurationMs:Math.max(0,e.savedAt-e.startedAt),F=t.sourceSessionPath?[...l,t.sourceSessionPath]:l,U={facet_version:Sl,session_id:L,source:h==="telegram"?"telegram":"cli",model:e.model,derived_at:(t.derivedAt??new Date).toISOString(),derived_from:"afk-session",source_session_path:t.sourceSessionPath??"",source_session_mtime_ms:t.sourceSessionMtimeMs??e.savedAt,subagent_persistence:"not_persisted",start_time:new Date(e.startedAt).toISOString(),end_time:new Date(e.savedAt).toISOString(),duration_minutes:Number((N/6e4).toFixed(2)),underlying_goal:g.slice(0,xA),first_prompt:g.slice(0,xA),goal_categories:{[b]:1},session_type:b,brief_summary:I,total_turns:n.length,user_message_count:S,assistant_message_count:w,tool_counts:o,commands:y,skills:a,subagents:i,tool_errors:c,tool_error_categories:s,friction_counts:{...s},friction_detail:E,outcome:T,primary_success:A,world_changes:{files_written:u,files_edited:d,bash_commands:p,commits:m,mutated:u>0||d>0||m>0},decisions:[],evidence_pointers:F};return vl.parse(U)}var Rz,Cz,xA,Az,_z,Pz,RA,Yy=P(()=>{"use strict";Hd();Rz=new Set(["agent","compose","skill"]),Cz=new Set(["read_file","write_file","edit_file"]),xA=1e3,Az=240,_z=50,Pz=/\bgit\s+commit(?![\w-])/,RA=/^\s*\/([a-zA-Z][\w-]*)/});import{existsSync as Gd,mkdirSync as Dz,readFileSync as CA,readdirSync as Fz,renameSync as Lz,statSync as Nz,writeFileSync as Bz}from"fs";import{basename as Uz,dirname as jz,join as AA}from"path";function _A(e,t){return $c(e),AA(t,`${e}.json`)}function Hz(e,t){return $c(e),AA(t,`${e}.json`)}function qd(e,t=wt()){let n=_A(e,t);if(Gd(n))try{let r=JSON.parse(CA(n,"utf8")),o=Vy.safeParse(r);return o.success?o.data:void 0}catch{return}}function Wz(e){if(Gd(e))try{let t=JSON.parse(CA(e,"utf8")),n=vl.safeParse(t);return n.success?n.data:void 0}catch{return}}function Kz(e,t){Dz(jz(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;Bz(n,`${JSON.stringify(t,null,2)}
|
|
1519
1519
|
`,"utf8"),Lz(n,e)}function Gz(e,t){return e.facet_version===Sl&&e.source_session_mtime_ms===t}function Xy(e,t={}){let n=t.sessionsDir??wt(),r=t.cacheDir??Pv(),o=_A(e,n);if(!Gd(o))return;let s=Nz(o).mtimeMs,i=Hz(e,r);if(!t.force){let c=Wz(i);if(c&&Gz(c,s))return c}let a=qd(e,n);if(!a)return;let l=kl(a,{sourceSessionPath:o,sourceSessionMtimeMs:s});return Kz(i,l),l}function Zy(e={}){let t=e.sessionsDir??wt();return Gd(t)?Fz(t).filter(n=>n.endsWith(".json")).map(n=>Uz(n,".json")):[]}var PA=P(()=>{"use strict";K();Yy();Hd()});var IA=P(()=>{"use strict";Hd();Yy();PA()});function MA(e){let t=Ho(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(`
|
|
1520
|
-
`)}function Ho(e){let t=[],n=new Set,r=v.AFK_INTERNAL==="1",o=ln(Dt());wr(ka(),"user"),wr(Ac(),"project");for(let{dir:i,origin:a}of o.skillRoots)wr(i,a);for(let i of En()){let a=Ge(i);an(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??Qy();for(let i of s){if(i.type!=="local")continue;let a=Jy(i.path);for(let l of a)!l.name||n.has(l.name)||an({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 hl(e){let t=new Map,n=e??Qy();for(let r of n){if(r.type!=="local")continue;let o=Jy(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 Qy(){return[...hr(_c()),...hr(),...hr(xs()),...ln(Dt()).pluginRoots.flatMap(e=>hr(e,{trustAll:!0}))]}async function ki(){await bA(Qy(),{pluginApi:{registerSkill:ht,listSkills:En,getSkill:Ge,loadSkillPrompts:Ne,env:v,SubagentManager:re,describeFailure:et,discoverPluginSkillBodies:hl,getAgentFrameworkDir:Mt,getSkillsDir:ka,getSessionsDir:wt,getOrDeriveFacet:Xy,listSessionIds:Zy,deriveSessionFacet:kl,loadStoredSession:qd}})}var fr=P(()=>{"use strict";zy();Tt();zt();qy();Xr();wA();SA();ze();Bt();IA();K();J();ur()});function wd(){try{let e=Ho();return Promise.resolve(e.map(t=>{let n={name:t.name,description:t.description};return t.argumentHint&&(n.argumentHint=t.argumentHint),n}))}catch{return Promise.resolve([])}}var ay=P(()=>{"use strict";fr()});function OA(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 $A=P(()=>{"use strict"});function DA(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 FA=P(()=>{"use strict"});var qz,zd,LA=P(()=>{"use strict";qz="__closed__",zd=class{current=null;pendingReason=null;closedPromise;closeResolve=null;constructor(){this.closedPromise=new Promise(t=>{this.closeResolve=()=>t(qz)})}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 Jz(e,t,n,r,o){let s=zz.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 NA(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=Jz(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 zz,BA=P(()=>{"use strict";Vh();zz=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 Vz(e){let t=e.trim();if(t.length===0)return{};try{return JSON.parse(t)}catch{return{}}}function Yz(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:Vz(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*UA(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:Yz(n,r,o)}}var jA=P(()=>{"use strict";J()});import{randomUUID as Xz}from"node:crypto";function Qz(e){let{name:t,description:n,input_schema:r}=e;return{name:t,...n!==void 0?{description:n}:{},input_schema:r}}function eJ(e){if(!("status"in e))return!1;let t=e.status;return t===529||t===503}function HA(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"}async function tJ(e,t,n,r){for(let o=0;;o++){if(o>0){let s=WA*Math.pow(2,o-1);if(await Kr(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(eJ(i)&&o<eb)continue;throw i}}}async function*tb(e){let t=e.maxToolUseIterations??Zz,n={stopReason:null},r=0,o=0,s=Xz(),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=eu({baseUrl:e.baseUrl})?Ak(e.messages,tu()):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(Qz)}:{},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{output_config:{effort:e.effort}}:{}},u=Date.now(),d;try{d=await tJ(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 k=w instanceof Error?w:new Error(String(w));k.message.includes("thinking")&&nJ(e.messages,k),yield{type:"error",error:k};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 UA(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(HA(w.event.error)&&o<eb&&!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 k=w instanceof Error?w:new Error(String(w));if(HA(k)&&o<eb&&!e.signal.aborted)g=!0;else{yield{type:"error",error:k};return}}if(g){if(o+=1,yield{type:"stream.retry",sessionId:e.ctx.sessionId},await Kr(WA*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=NA(p.usage,p.stopReason,e.model);if(n=el(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(k=>k.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=[],k=new Map;for(let E of p.toolUseBlocks){w.push({id:E.id,name:E.name,input:E.input,signal:e.signal});let O=Date.now();k.set(E.id,O),$s(e.traceWriter,{phase:"started",toolUseId:E.id,name:E.name,inputBytes:Buffer.byteLength(JSON.stringify(E.input??{}),"utf8")}),yield{type:"tool.use.start",toolUseId:E.id,toolName:E.name,toolInput:hd(E.name,E.input),toolInputRaw:gd(E.input),sessionId:e.ctx.sessionId}}if(e.signal.aborted){let E=w.map(O=>({type:"tool_result",tool_use_id:O.id,content:"Tool call aborted",is_error:!0}));e.messages.push({role:"user",content:E}),yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}let T;if(e.toolDispatcher.executeBatch)try{T=await e.toolDispatcher.executeBatch(w)}catch(E){T=w.map(()=>({content:`Tool batch execution failed: ${E instanceof Error?E.message:String(E)}`,isError:!0}))}else{T=[];for(let E of w){if(e.signal.aborted){T.push({content:"Tool call aborted",isError:!0});continue}try{T.push(await e.toolDispatcher.execute(E))}catch(O){let _=O instanceof Error?O.message:String(O);T.push({content:`Tool execution threw: ${_}`,isError:!0})}}}let R=[];for(let E=0;E<w.length;E++){let O=w[E],_=T[E],I=k.get(O.id),L=typeof I=="number"?Date.now()-I:0,N=_.truncated===!0||_.content.includes("[output truncated");$s(e.traceWriter,{phase:"completed",toolUseId:O.id,name:O.name,resultBytes:Buffer.byteLength(_.content,"utf8"),isError:_.isError===!0,truncated:N,durationMs:L,..._.circuitBreaker===!0?{circuitBreaker:!0}:{},..._.failureClass?{failureClass:_.failureClass}:{}}),yield{type:"tool.output",toolUseId:O.id,toolName:O.name,content:_.content,..._.isError===!0?{isError:!0}:{},...N?{truncated:!0}:{},sessionId:e.ctx.sessionId},_.render?.diff&&(yield{type:"tool.diff",toolUseId:O.id,diff:_.render.diff,sessionId:e.ctx.sessionId});let{content:F,isError:U,image:H}=_,D=H!==void 0?[{type:"image",source:{type:"base64",media_type:H.mediaType,data:H.data}},...F.length>0?[{type:"text",text:F}]:[]]:F;R.push({type:"tool_result",tool_use_id:O.id,content:D,...U===!0?{is_error:!0}:{}})}let A={role:"user",content:R};e.messages.push(A)}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 nJ(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 Zz,eb,WA,KA=P(()=>{"use strict";BA();kg();jA();He();Yh();J();ry();oy();Zz=0;eb=3,WA=5e3});function nb(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 GA(e){let{resetsAt:t,signal:n,readToken:r=Et}=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 qA(e){let{signal:t,readToken:n=Et,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 zA=P(()=>{"use strict";js()});var JA=P(()=>{"use strict";js()});import{randomUUID as rb}from"node:crypto";var VA,rJ,Jd,YA=P(()=>{"use strict";KA();Fs();zA();JA();VA=7200*1e3,rJ=60*1e3,Jd=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=Et(),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=Et();return{accountId:Or(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=nb(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=Or(Et()??"");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=qA({signal:t.signal,retryAfterMs:rJ});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=vn(this._authMode,this.initSessionId,rb());let g=null;for await(let h of this.turnWithAuthRetry(t,n)){if(!d&&h.type==="error"){let b=nb(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>VA){yield g;return}}}if(!o)return;if(o.getTime()-Date.now()>VA){yield r;return}let i=Or(Et()??"");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=GA({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=vn(this._authMode,this.initSessionId,rb()),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 tb(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=vn(this._authMode,this.initSessionId,rb()),yield*tb(t)}isRetryableAuth(t){return this._authMode==="oauth"&&this.tokenRefresher!==void 0&&"status"in t&&t.status===401}}});function sJ(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 QA(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&&sJ(o)&&(n+=1,n===t))return r}return-1}function e_(e,t,n){let r=iJ(e);return{model:t,max_tokens:n,system:oJ,messages:[{role:"user",content:`Summarize the following conversation transcript. Follow the system instructions exactly.
|
|
1520
|
+
`)}function Ho(e){let t=[],n=new Set,r=v.AFK_INTERNAL==="1",o=ln(Dt());wr(ka(),"user"),wr(Ac(),"project");for(let{dir:i,origin:a}of o.skillRoots)wr(i,a);for(let i of En()){let a=Ge(i);an(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??Qy();for(let i of s){if(i.type!=="local")continue;let a=Jy(i.path);for(let l of a)!l.name||n.has(l.name)||an({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 hl(e){let t=new Map,n=e??Qy();for(let r of n){if(r.type!=="local")continue;let o=Jy(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 Qy(){return[...hr(_c()),...hr(),...hr(xs()),...ln(Dt()).pluginRoots.flatMap(e=>hr(e,{trustAll:!0}))]}async function ki(){await bA(Qy(),{pluginApi:{registerSkill:ht,listSkills:En,getSkill:Ge,loadSkillPrompts:Be,env:v,SubagentManager:re,describeFailure:et,discoverPluginSkillBodies:hl,getAgentFrameworkDir:Mt,getSkillsDir:ka,getSessionsDir:wt,getOrDeriveFacet:Xy,listSessionIds:Zy,deriveSessionFacet:kl,loadStoredSession:qd}})}var fr=P(()=>{"use strict";zy();Tt();zt();qy();Xr();wA();SA();ze();Bt();IA();K();J();ur()});function wd(){try{let e=Ho();return Promise.resolve(e.map(t=>{let n={name:t.name,description:t.description};return t.argumentHint&&(n.argumentHint=t.argumentHint),n}))}catch{return Promise.resolve([])}}var ay=P(()=>{"use strict";fr()});function OA(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 $A=P(()=>{"use strict"});function DA(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 FA=P(()=>{"use strict"});var qz,zd,LA=P(()=>{"use strict";qz="__closed__",zd=class{current=null;pendingReason=null;closedPromise;closeResolve=null;constructor(){this.closedPromise=new Promise(t=>{this.closeResolve=()=>t(qz)})}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 Jz(e,t,n,r,o){let s=zz.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 NA(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=Jz(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 zz,BA=P(()=>{"use strict";Vh();zz=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 Vz(e){let t=e.trim();if(t.length===0)return{};try{return JSON.parse(t)}catch{return{}}}function Yz(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:Vz(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*UA(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:Yz(n,r,o)}}var jA=P(()=>{"use strict";J()});import{randomUUID as Xz}from"node:crypto";function Qz(e){let{name:t,description:n,input_schema:r}=e;return{name:t,...n!==void 0?{description:n}:{},input_schema:r}}function eJ(e){if(!("status"in e))return!1;let t=e.status;return t===529||t===503}function HA(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"}async function tJ(e,t,n,r){for(let o=0;;o++){if(o>0){let s=WA*Math.pow(2,o-1);if(await Kr(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(eJ(i)&&o<eb)continue;throw i}}}async function*tb(e){let t=e.maxToolUseIterations??Zz,n={stopReason:null},r=0,o=0,s=Xz(),i=Date.now(),a=l=>({...l,durationMs:Date.now()-i});Oe(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=eu({baseUrl:e.baseUrl})?Ak(e.messages,tu()):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(Qz)}:{},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{output_config:{effort:e.effort}}:{}},u=Date.now(),d;try{d=await tJ(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 k=w instanceof Error?w:new Error(String(w));k.message.includes("thinking")&&nJ(e.messages,k),yield{type:"error",error:k};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 UA(d,e.ctx))if(h||(h=!0,Oe(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(HA(w.event.error)&&o<eb&&!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 k=w instanceof Error?w:new Error(String(w));if(HA(k)&&o<eb&&!e.signal.aborted)g=!0;else{yield{type:"error",error:k};return}}if(g){if(o+=1,yield{type:"stream.retry",sessionId:e.ctx.sessionId},await Kr(WA*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=NA(p.usage,p.stopReason,e.model);if(n=el(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(k=>k.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=[],k=new Map;for(let E of p.toolUseBlocks){w.push({id:E.id,name:E.name,input:E.input,signal:e.signal});let O=Date.now();k.set(E.id,O),$s(e.traceWriter,{phase:"started",toolUseId:E.id,name:E.name,inputBytes:Buffer.byteLength(JSON.stringify(E.input??{}),"utf8")}),yield{type:"tool.use.start",toolUseId:E.id,toolName:E.name,toolInput:hd(E.name,E.input),toolInputRaw:gd(E.input),sessionId:e.ctx.sessionId}}if(e.signal.aborted){let E=w.map(O=>({type:"tool_result",tool_use_id:O.id,content:"Tool call aborted",is_error:!0}));e.messages.push({role:"user",content:E}),yield{type:"turn.completed",usage:a(n),sessionId:e.ctx.sessionId};return}let T;if(e.toolDispatcher.executeBatch)try{T=await e.toolDispatcher.executeBatch(w)}catch(E){T=w.map(()=>({content:`Tool batch execution failed: ${E instanceof Error?E.message:String(E)}`,isError:!0}))}else{T=[];for(let E of w){if(e.signal.aborted){T.push({content:"Tool call aborted",isError:!0});continue}try{T.push(await e.toolDispatcher.execute(E))}catch(O){let _=O instanceof Error?O.message:String(O);T.push({content:`Tool execution threw: ${_}`,isError:!0})}}}let R=[];for(let E=0;E<w.length;E++){let O=w[E],_=T[E],I=k.get(O.id),L=typeof I=="number"?Date.now()-I:0,N=_.truncated===!0||_.content.includes("[output truncated");$s(e.traceWriter,{phase:"completed",toolUseId:O.id,name:O.name,resultBytes:Buffer.byteLength(_.content,"utf8"),isError:_.isError===!0,truncated:N,durationMs:L,..._.circuitBreaker===!0?{circuitBreaker:!0}:{},..._.failureClass?{failureClass:_.failureClass}:{}}),yield{type:"tool.output",toolUseId:O.id,toolName:O.name,content:_.content,..._.isError===!0?{isError:!0}:{},...N?{truncated:!0}:{},sessionId:e.ctx.sessionId},_.render?.diff&&(yield{type:"tool.diff",toolUseId:O.id,diff:_.render.diff,sessionId:e.ctx.sessionId});let{content:F,isError:U,image:H}=_,D=H!==void 0?[{type:"image",source:{type:"base64",media_type:H.mediaType,data:H.data}},...F.length>0?[{type:"text",text:F}]:[]]:F;R.push({type:"tool_result",tool_use_id:O.id,content:D,...U===!0?{is_error:!0}:{}})}let A={role:"user",content:R};e.messages.push(A)}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{Oe(e.traceWriter,{phase:"loop_end",durationMs:Date.now()-i})}}function nJ(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 Zz,eb,WA,KA=P(()=>{"use strict";BA();kg();jA();Ne();Yh();J();ry();oy();Zz=0;eb=3,WA=5e3});function nb(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 GA(e){let{resetsAt:t,signal:n,readToken:r=Et}=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 qA(e){let{signal:t,readToken:n=Et,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 zA=P(()=>{"use strict";js()});var JA=P(()=>{"use strict";js()});import{randomUUID as rb}from"node:crypto";var VA,rJ,Jd,YA=P(()=>{"use strict";KA();Fs();zA();JA();VA=7200*1e3,rJ=60*1e3,Jd=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=Et(),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=Et();return{accountId:Or(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=nb(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=Or(Et()??"");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=qA({signal:t.signal,retryAfterMs:rJ});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=vn(this._authMode,this.initSessionId,rb());let g=null;for await(let h of this.turnWithAuthRetry(t,n)){if(!d&&h.type==="error"){let b=nb(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>VA){yield g;return}}}if(!o)return;if(o.getTime()-Date.now()>VA){yield r;return}let i=Or(Et()??"");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=GA({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=vn(this._authMode,this.initSessionId,rb()),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 tb(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=vn(this._authMode,this.initSessionId,rb()),yield*tb(t)}isRetryableAuth(t){return this._authMode==="oauth"&&this.tokenRefresher!==void 0&&"status"in t&&t.status===401}}});function sJ(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 QA(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&&sJ(o)&&(n+=1,n===t))return r}return-1}function e_(e,t,n){let r=iJ(e);return{model:t,max_tokens:n,system:oJ,messages:[{role:"user",content:`Summarize the following conversation transcript. Follow the system instructions exactly.
|
|
1521
1521
|
|
|
1522
1522
|
<transcript>
|
|
1523
1523
|
`+r+`
|
|
@@ -1525,7 +1525,7 @@ ${t.body}`)}var nz,Ky=P(()=>{"use strict";nz=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9
|
|
|
1525
1525
|
|
|
1526
1526
|
`+n},{role:"assistant",content:ZA},...e.slice(t)]}function n_(e,t,n){let r=aJ(e.slice(0,t)),o=XA.length+2+n.length+ZA.length,s=Math.max(0,r-o);return Math.round(s/4)}function iJ(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=r_(o.input);t.push(`[tool call: ${i} ${a}]`)}else if(s==="tool_result"){let i=o.content;t.push(`[tool result: ${o_(i)}]`)}else s==="image"?t.push("[image]"):s==="document"&&t.push("[document]")}t.push("")}return t.join(`
|
|
1527
1527
|
`).trim()}function r_(e){try{let t=JSON.stringify(e);return t.length>240?t.slice(0,237)+"...":t}catch{return"{}"}}function o_(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 aJ(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+=r_(r.input).length:o==="tool_result"&&(t+=o_(r.content).length)}return t}var oJ,XA,ZA,s_=P(()=>{"use strict";oJ=["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(`
|
|
1528
|
-
`),XA="[Compacted summary of earlier conversation]",ZA="Acknowledged. Continuing from the summary above."});import{randomUUID as lJ}from"node:crypto";async function i_(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=pJ(),l=QA(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=mJ(),d=e_(c,u,dJ),p=n.begin(),m;try{if(p.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let y=vn(r.authMode,o,lJ()),S=r.client,w=await Promise.resolve(S.messages.create(d,{headers:y,signal:p.signal}));m=await fJ(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=n_(t.messages,l,m),h=t_(t.messages,l,m);t.messages.splice(0,t.messages.length,...h);let b=t.messages.length;return gk(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 pJ(){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 cJ}function mJ(){let e=v.AFK_COMPACT_MODEL;return e!==void 0&&e.length>0?kt(e)??e:uJ}async function fJ(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 cJ,uJ,dJ,a_=P(()=>{"use strict";Fs();s_();He();Zn();J();cJ=2,uJ="claude-haiku-4-5-20251001",dJ=1024});var l_=P(()=>{"use strict";ny()});import{randomUUID as c_}from"node:crypto";var gJ,Vd,u_=P(()=>{"use strict";Da();Fs();kg();Pk();Ik();ay();nl();Zn();$A();FA();LA();YA();a_();l_();vt();gJ=[{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"}],Vd=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;baseUrl;traceWriter;state;abort;retry;cwdDependentsFactory;onPermissionMode;mcpManager;hookRegistry;constructor(t){this.initSessionId=t.sessionId??c_(),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 Jd({client:t.client,authMode:t.authMode,initSessionId:this.initSessionId,...t.tokenRefresher?{tokenRefresher:t.tokenRefresher}:{},autoResumeOnUsageLimit:t.autoResumeOnUsageLimit??!0}),this.state=DA({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 zd}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}OA(this.state.messages),this.state.messages.push({role:"user",content:s.content});let a=this.composeSystem(),l=vn(this.retry.authMode,this.initSessionId,c_(),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=Lt(this.state.requestedModel);if(d!==null&&p>0){let m=Uo(d);if(ty(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 me))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=Eg(this.state.currentPermissionMode);o!==null&&r.push(o);let s=xg(this.state.currentPermissionMode);return s!==null&&r.push(s),r.length===0?null:eu({baseUrl:this.baseUrl})?Ck(r,tu()):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=kt(t)??t)}async setPermissionMode(t){this.state.currentPermissionMode=t;let n=kn(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(){return wd()}async supportedModels(){return gJ.map(t=>({...t}))}async supportedAgents(){return[]}async getContextUsage(){let t=this.state.lastUsage,n=Lt(this.state.requestedModel),r;if(t&&n>0){let i=Uo(t);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=il(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 i_({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 ob(e){if(e===void 0||e===!1)return;if(e===!0)return yJ;let t=e.threshold;if(!(typeof t!="number"||!Number.isFinite(t)||t<=0||t>=1))return t}function sb(e,t){let n=tl(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 Yd.has(s)||(Yd.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${t} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function d_(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 ib(e,t,n){switch(e.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&hJ(n))return{type:"adaptive",display:"summarized"};let r=Math.floor(t*bJ),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}`;Yd.has(a)||(Yd.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 ab(e,t){if(e!==void 0)return e;let n=t.toLowerCase();if(/(claude-)?(opus|sonnet)-4-[678]/.test(n))return"max"}var hJ,yJ,Yd,bJ,lb=P(()=>{"use strict";nl();hJ=e=>/opus-4-(7|[89])/.test(e),yJ=.9;Yd=new Set,bJ=.25});var Xd,cb,ub,Nve,p_,m_,f_=P(()=>{"use strict";Xd=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
|
|
1528
|
+
`),XA="[Compacted summary of earlier conversation]",ZA="Acknowledged. Continuing from the summary above."});import{randomUUID as lJ}from"node:crypto";async function i_(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=pJ(),l=QA(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=mJ(),d=e_(c,u,dJ),p=n.begin(),m;try{if(p.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let y=vn(r.authMode,o,lJ()),S=r.client,w=await Promise.resolve(S.messages.create(d,{headers:y,signal:p.signal}));m=await fJ(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=n_(t.messages,l,m),h=t_(t.messages,l,m);t.messages.splice(0,t.messages.length,...h);let b=t.messages.length;return gk(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 pJ(){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 cJ}function mJ(){let e=v.AFK_COMPACT_MODEL;return e!==void 0&&e.length>0?kt(e)??e:uJ}async function fJ(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 cJ,uJ,dJ,a_=P(()=>{"use strict";Fs();s_();Ne();Zn();J();cJ=2,uJ="claude-haiku-4-5-20251001",dJ=1024});var l_=P(()=>{"use strict";ny()});import{randomUUID as c_}from"node:crypto";var gJ,Vd,u_=P(()=>{"use strict";Da();Fs();kg();Pk();Ik();ay();nl();Zn();$A();FA();LA();YA();a_();l_();vt();gJ=[{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"}],Vd=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;baseUrl;traceWriter;state;abort;retry;cwdDependentsFactory;onPermissionMode;mcpManager;hookRegistry;constructor(t){this.initSessionId=t.sessionId??c_(),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 Jd({client:t.client,authMode:t.authMode,initSessionId:this.initSessionId,...t.tokenRefresher?{tokenRefresher:t.tokenRefresher}:{},autoResumeOnUsageLimit:t.autoResumeOnUsageLimit??!0}),this.state=DA({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 zd}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}OA(this.state.messages),this.state.messages.push({role:"user",content:s.content});let a=this.composeSystem(),l=vn(this.retry.authMode,this.initSessionId,c_(),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=Lt(this.state.requestedModel);if(d!==null&&p>0){let m=Uo(d);if(ty(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 me))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=Eg(this.state.currentPermissionMode);o!==null&&r.push(o);let s=xg(this.state.currentPermissionMode);return s!==null&&r.push(s),r.length===0?null:eu({baseUrl:this.baseUrl})?Ck(r,tu()):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=kt(t)??t)}async setPermissionMode(t){this.state.currentPermissionMode=t;let n=kn(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(){return wd()}async supportedModels(){return gJ.map(t=>({...t}))}async supportedAgents(){return[]}async getContextUsage(){let t=this.state.lastUsage,n=Lt(this.state.requestedModel),r;if(t&&n>0){let i=Uo(t);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=il(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 i_({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 ob(e){if(e===void 0||e===!1)return;if(e===!0)return yJ;let t=e.threshold;if(!(typeof t!="number"||!Number.isFinite(t)||t<=0||t>=1))return t}function sb(e,t){let n=tl(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 Yd.has(s)||(Yd.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${t} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function d_(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 ib(e,t,n){switch(e.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&hJ(n))return{type:"adaptive",display:"summarized"};let r=Math.floor(t*bJ),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}`;Yd.has(a)||(Yd.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 ab(e,t){if(e!==void 0)return e;let n=t.toLowerCase();if(/(claude-)?(opus|sonnet)-4-[678]/.test(n))return"max"}var hJ,yJ,Yd,bJ,lb=P(()=>{"use strict";nl();hJ=e=>/opus-4-(7|[89])/.test(e),yJ=.9;Yd=new Set,bJ=.25});var Xd,cb,ub,Nve,p_,m_,f_=P(()=>{"use strict";Xd=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
|
|
1529
1529
|
|
|
1530
1530
|
- Use read_file before editing to verify the exact content you want to change.
|
|
1531
1531
|
- Prefer edit_file over write_file for modifying existing files \u2014 write_file is for new files or complete rewrites.
|
|
@@ -1593,7 +1593,7 @@ ${ub}`,R=this.readOnlyMemory?m_:p_,A=[T,R];A.push(Ks({cwd:k,...n.sessionId!==voi
|
|
|
1593
1593
|
|
|
1594
1594
|
`),B=this.buildDispatcher(this._currentPermissionMode,{cwd:U,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:C,dispatcher:B}},F=ab(n.effort,d);return new Vd({client:l,authMode:r?"api-key":s,promptStream:t.prompt,toolDispatcher:g,...I!==void 0?{sessionId:I}:{},...L!==void 0?{initialMessages:L}:{},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:E,systemPrefix:c,tokenRefresher:_,...n.thinking!==void 0?{thinking:ib(n.thinking,p,d)}:{},...F!==void 0?{effort:F}:{},...r?{baseUrl:n.baseUrl}:{},...n.traceWriter?{traceWriter:n.traceWriter}:{},...n.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:n.autoResumeOnUsageLimit}:{},...N!==void 0?{cwdDependentsFactory:N}:{},onPermissionMode:U=>{this._currentPermissionMode=U},...this.mcpManager!==void 0?{mcpManager:this.mcpManager}:{},...ob(n.autoCompact)!==void 0?{autoCompactThreshold:ob(n.autoCompact)}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{}})}};OJ=new tt});function DJ(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 se(e,t){let n=t?.explicit??v.AFK_PROVIDER,r=t?.openaiBaseUrl??v.AFK_OPENAI_BASE_URL,o=DJ(n);if(o)return o;let s=bg(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&&($J.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 Zd(e,t,n){let r=se(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 Nt(i);default:return new tt(i)}}var $J,it=P(()=>{"use strict";Wo();al();Zn();sn();J();Wo();al();$J=new Set([...Object.keys(wg),"auto"])});var Ti,fb=P(()=>{"use strict";Ti=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 Qd(e,t){let n=t??Ls(),r=Ns(e.model,n);if(!r)return;let o=n[r],s=o.provider==="anthropic"?"anthropic-direct":o.provider==="openai"?"openai-compatible":se(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 gb=P(()=>{"use strict";it();sn()});function FJ(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(`
|
|
1595
1595
|
`)}var ep,b_=P(()=>{"use strict";fb();gb();Pe();ep=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,Qd(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 Ti(()=>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?`
|
|
1596
|
-
`:"")+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),W(`\u{1F500} ProviderRouter: switched inner provider \u2192 ${this.active.family} (model=${this.currentModel})`),yield*this.driveUntilInit(!0)))break;for(this.pendingUserText=FJ(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 tp(e,t,n){if(!e)return;if(n.kind==="blocked"){await on(e,{hookEvent:t,decision:"block",...n.err.reason!==void 0?{reason:n.err.reason}:{}});return}let r=n.decision;await on(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 w_(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await tp(n.traceWriter,"SessionStart",{kind:"decision",decision:r})}catch(r){throw r instanceof me&&await tp(n.traceWriter,"SessionStart",{kind:"blocked",err:r}),r}}async function S_(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await tp(n.traceWriter,"SessionEnd",{kind:"decision",decision:r})}catch(r){if(r instanceof me&&await tp(n.traceWriter,"SessionEnd",{kind:"blocked",err:r}),r instanceof me||r instanceof ut){W(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}W(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var v_=P(()=>{"use strict";Pe();vt();
|
|
1596
|
+
`:"")+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),W(`\u{1F500} ProviderRouter: switched inner provider \u2192 ${this.active.family} (model=${this.currentModel})`),yield*this.driveUntilInit(!0)))break;for(this.pendingUserText=FJ(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 tp(e,t,n){if(!e)return;if(n.kind==="blocked"){await on(e,{hookEvent:t,decision:"block",...n.err.reason!==void 0?{reason:n.err.reason}:{}});return}let r=n.decision;await on(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 w_(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await tp(n.traceWriter,"SessionStart",{kind:"decision",decision:r})}catch(r){throw r instanceof me&&await tp(n.traceWriter,"SessionStart",{kind:"blocked",err:r}),r}}async function S_(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await tp(n.traceWriter,"SessionEnd",{kind:"decision",decision:r})}catch(r){if(r instanceof me&&await tp(n.traceWriter,"SessionEnd",{kind:"blocked",err:r}),r instanceof me||r instanceof ut){W(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}W(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var v_=P(()=>{"use strict";Pe();vt();Ne()});function LJ(e){return e==="max_tokens"||e==="length"}function k_(e){return e.maxTurnsHit?"max_turns_exceeded":e.hookBlocked?"hook_blocked":e.dispatchReason==="error"?"abort":e.abort!==null?e.abort:e.sawProviderError?"abort":LJ(e.lastStopReason)?"truncated":"model_end_turn"}var E_=P(()=>{"use strict"});function Ko(e){return e==="abort"?hb:null}var hb,np=P(()=>{"use strict";hb="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 xi from"node:fs";import*as Tl from"node:fs/promises";function rp(e,t){return e.length>t?`${e.slice(0,t)}\u2026 [truncated]`:e}function NJ(e){switch(e.type){case"message":return e.message.role!=="assistant"||!e.message.content?null:{kind:"assistant",text:rp(e.message.content,x_)};case"chunk":{let t=e.chunk;return t.type==="tool_use_detail"?{kind:"tool",toolName:t.toolName,input:rp(t.toolInput,T_)}:t.type==="tool_result"&&t.isError===!0?{kind:"tool_error",content:rp(t.content,T_)}: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 BJ(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*yb(e,t){if(!Nc(e))return;let n=eg(e),r=_a(e),{fromStart:o=!1,signal:s}=t??{},i=0,a="",l=!1;async function*c(){let m=null;try{m=await Tl.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(`
|
|
1597
1597
|
`);a=S.pop()??"";for(let w of S){let k=BJ(w);if(k&&(k.kind==="closed"&&(l=!0),yield k,l))return}}catch(g){g.code!=="ENOENT"&&process.stderr.write(`[afk] session-ledger: tail read error for ${e}: ${String(g)}
|
|
1598
1598
|
`)}finally{m&&await m.close().catch(()=>{})}}if(o){if(yield*c(),l)return}else try{i=(await Tl.stat(n)).size}catch{}let u=null,d=null,p=()=>new Promise(m=>{let g=setTimeout(()=>{d=null,m()},UJ);d=()=>{clearTimeout(g),d=null,m()},s?.addEventListener("abort",()=>{clearTimeout(g),d=null,m()},{once:!0})});try{u=xi.watch(r,{persistent:!1},()=>{d?.()})}catch{}try{for(;!s?.aborted&&!l&&(await p(),!s?.aborted);)yield*c()}finally{u?.close()}}var x_,T_,op,UJ,bb=P(()=>{"use strict";K();x_=8e3,T_=400;op=class{sessionId;ledgerPath;stream=null;errored=!1;closed=!1;streamReady=!1;pendingLines=[];readyPromise=null;readyResolve=null;constructor(t){if(this.sessionId=t,!Nc(t)){this.errored=!0,this.ledgerPath="";return}this.ledgerPath=eg(t);try{xi.mkdirSync(_a(t),{recursive:!0})}catch(n){process.stderr.write(`[afk] session-ledger: mkdir failed for ${t}: ${String(n)}
|
|
1599
1599
|
`),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)+`
|
|
@@ -1602,7 +1602,7 @@ ${ub}`,R=this.readOnlyMemory?m_:p_,A=[T,R];A.push(Ks({cwd:k,...n.sessionId!==voi
|
|
|
1602
1602
|
`),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)}
|
|
1603
1603
|
`),this.errored=!0)})}catch(n){process.stderr.write(`[afk] session-ledger: write threw for ${this.sessionId}: ${String(n)}
|
|
1604
1604
|
`),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())})}};UJ=250});function R_(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 C_(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 A_=P(()=>{"use strict"});var sp,__=P(()=>{"use strict";sp=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 P_(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 I_(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 M_(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 O_=P(()=>{"use strict"});function wb(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)?$_(jJ(o)):o!==null&&typeof o=="object"?$_(HJ(o)):null}function jJ(e){return e.length===0?"[empty array]":e.length===1?"[1 item]":`[${e.length} items]`}function HJ(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 $_(e){return e.length<=80?e:e.slice(0,79)+"\u2026"}var D_=P(()=>{"use strict"});function F_(e,t){if(!e)return null;let n=WJ.get(e);if(!n)return null;try{let r=n(t);if(r===null)return null;let o=Mo(r);return o.length>0?o:null}catch{return null}}var WJ,L_=P(()=>{"use strict";O_();D_();Oo();WJ=new Map([["memory_search",P_],["memory_update",I_],["procedure_write",M_],["bash",wb],["Bash",wb]])});function KJ(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 GJ(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 qJ(e){let t=Buffer.byteLength(e,"utf8"),n=GJ(t),r=e.split(`
|
|
1605
|
-
`);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 zJ(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 JJ(e){let t=e.isError===!0?null:F_(e.toolName,e.content),n=t!==null?{display:t}:{},r=KJ(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}=qJ(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 Sb(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 JJ(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=zJ(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)){mk(t.traceWriter,{kind:"monetary",runningCostUsd:t._runningCostUsd,maxBudgetUsd:t.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new Pr(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 N_=P(()=>{"use strict";vt();He();L_()});import{z as VJ}from"zod";var xt,vb=P(()=>{"use strict";Pe();vt();He();it();b_();Js();lu();v_();vt();E_();np();dy();fb();bb();J();Zn();Wr();Ha();sn();gb();A_();__();N_();xt=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,R_(t.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(t.model);Le(t.traceWriter,{phase:"session_init_start",model:n,resolvedModel:kt(t.model)??n,origin:Hr(t.surface),actor:md(t.parentSessionId)}),this.initSdkLifecycle()}initSdkLifecycle(){this.config.models&&Zc(this.config.models),Qd(this.config);let t=kt(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=C_(this.config,t);this.stateManager=new sp(n,r),this.inputStream=new Ti(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)W(`\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{W("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>Zd(a,void 0,{customTools:this.config.customTools,canUseTool:this.config.canUseTool});this.providerQuery=new ep({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>se(a),resolveApiKey:a=>lr(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 w_(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=Sb(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 me&&(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??iu,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 au(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(VJ.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
|
+
`);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 zJ(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 JJ(e){let t=e.isError===!0?null:F_(e.toolName,e.content),n=t!==null?{display:t}:{},r=KJ(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}=qJ(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 Sb(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 JJ(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=zJ(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)){mk(t.traceWriter,{kind:"monetary",runningCostUsd:t._runningCostUsd,maxBudgetUsd:t.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new Pr(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 N_=P(()=>{"use strict";vt();Ne();L_()});import{z as VJ}from"zod";var xt,vb=P(()=>{"use strict";Pe();vt();Ne();it();b_();Js();lu();v_();vt();E_();np();dy();fb();bb();J();Zn();Wr();Ha();sn();gb();A_();__();N_();xt=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,R_(t.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(t.model);Oe(t.traceWriter,{phase:"session_init_start",model:n,resolvedModel:kt(t.model)??n,origin:Hr(t.surface),actor:md(t.parentSessionId)}),this.initSdkLifecycle()}initSdkLifecycle(){this.config.models&&Zc(this.config.models),Qd(this.config);let t=kt(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=C_(this.config,t);this.stateManager=new sp(n,r),this.inputStream=new Ti(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)W(`\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{W("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>Zd(a,void 0,{customTools:this.config.customTools,canUseTool:this.config.canUseTool});this.providerQuery=new ep({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>se(a),resolveApiKey:a=>lr(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 w_(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=Sb(n,this.buildTransformDeps());if(n.type==="session.init"){await Oe(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 me&&(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??iu,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 au(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(VJ.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.
|
|
1606
1606
|
Validation error: ${l}
|
|
1607
1607
|
Respond again with ONLY a JSON object (optionally in a \`\`\`json fence) that satisfies the schema.`+a,d=await this.sendMessage(u,i),p=Sd(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=Sb(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 op(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 ut("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,Ag))]).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=kt(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){W(`\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&&cE(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,Ag))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(t){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await this.emitClosure(t).catch(()=>{}),await this.sealTraceWriter(t).catch(()=>{}),await S_(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=Ko(r);await hk(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 Pr?n="budget_exceeded":o instanceof Gt?n="timeout":typeof o=="string"&&o.startsWith("Budget ")?n="budget_exceeded":typeof o=="string"&&o.includes("timed out")?n="timeout":n="abort"}return k_({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 ut("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 di=P(()=>{"use strict";vb()});var iI={};Rc(iI,{KeychainOAuthProvider:()=>Di,clearOauthPending:()=>Pb,readOauthPending:()=>sI});import{existsSync as kp,mkdirSync as rI,readFileSync as Ep,writeFileSync as _b}from"node:fs";import{execFileSync as QP}from"node:child_process";import{randomUUID as w4}from"node:crypto";import{homedir as eI,userInfo as tI}from"node:os";import{join as nI,dirname as oI}from"node:path";function v4(){let e=process.platform==="darwin",t=process.platform==="linux";return{read(){if(e)try{return QP("security",["find-generic-password","-s","Claude Code-credentials","-a",tI().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()||void 0}catch{return}if(t){let n=nI(eI(),".claude",".credentials.json");if(!kp(n))return;try{return Ep(n,"utf-8")}catch{return}}},write(n){if(e)QP("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",tI().username,"-w",n],{stdio:["ignore","ignore","ignore"]});else if(t){let r=nI(eI(),".claude",".credentials.json");rI(oI(r),{recursive:!0}),_b(r,n,{encoding:"utf-8",mode:384})}}}}function sI(){let e=Pa();if(!kp(e))return{};let t;try{t=JSON.parse(Ep(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<=S4&&(n[r]={status:"oauth_pending",authorizationUrl:s.authorizationUrl,timestamp:s.timestamp})}return n}function Pb(e){let t=Pa();if(!kp(t))return;let n;try{n=JSON.parse(Ep(t,"utf-8"))}catch{return}e in n&&(delete n[e],_b(t,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}))}function k4(e,t){let n=Pa();rI(oI(n),{recursive:!0});let r={};if(kp(n))try{r=JSON.parse(Ep(n,"utf-8"))}catch{}let o=new URL(t),s=o.origin+o.pathname;r[e]={status:"oauth_pending",authorizationUrl:s,timestamp:Date.now()},_b(n,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384})}var S4,Di,Tp=P(()=>{"use strict";K();S4=600*1e3;Di=class{serverName;backend;constructor(t,n=v4()){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{Pb(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=w4();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.
|
|
1608
1608
|
|
|
@@ -1611,7 +1611,7 @@ ${n}`;k4(this.serverName,n);let o=!1;try{let{pushIfConfigured:s}=await Promise.r
|
|
|
1611
1611
|
Open this URL to authorize:
|
|
1612
1612
|
${n}
|
|
1613
1613
|
Status written to: ${Pa()}
|
|
1614
|
-
`)}_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();Uc();import{config as vv}from"dotenv";import{Command as Tse}from"commander";J();import ng from"chalk";function Kv(){let e=v.FORCE_COLOR;if(e&&e.length>0)return;let t=v.NO_COLOR;if(t&&t.length>0){ng.level=0;return}let n=v.CI;if(n&&n.length>0){ng.level=0;return}process.stdout.isTTY||(ng.level=0)}import hI from"chalk";import L4 from"ora";vt();function Gv(e){let t=e instanceof Error?e.message:String(e);return t.toLowerCase().includes("rate limit")||t.toLowerCase().includes("too many requests")}function qv(e){let t=e instanceof Error?e.message:String(e);return t.toLowerCase().includes("network")||t.toLowerCase().includes("connect")||t.toLowerCase().includes("timeout")}function _s(e){if(e instanceof Pr)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 jc)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 me)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 Gt){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||Gv(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}:qv(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 SB from"string-width";var rg=/\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P^_X][^\x1B]*\x1B\\|[@-OQ-WYZ\\\-])/g,zv=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;function
|
|
1614
|
+
`)}_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();Uc();import{config as vv}from"dotenv";import{Command as Tse}from"commander";J();import ng from"chalk";function Kv(){let e=v.FORCE_COLOR;if(e&&e.length>0)return;let t=v.NO_COLOR;if(t&&t.length>0){ng.level=0;return}let n=v.CI;if(n&&n.length>0){ng.level=0;return}process.stdout.isTTY||(ng.level=0)}import hI from"chalk";import L4 from"ora";vt();function Gv(e){let t=e instanceof Error?e.message:String(e);return t.toLowerCase().includes("rate limit")||t.toLowerCase().includes("too many requests")}function qv(e){let t=e instanceof Error?e.message:String(e);return t.toLowerCase().includes("network")||t.toLowerCase().includes("connect")||t.toLowerCase().includes("timeout")}function _s(e){if(e instanceof Pr)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 jc)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 me)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 Gt){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||Gv(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}:qv(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 SB from"string-width";var rg=/\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P^_X][^\x1B]*\x1B\\|[@-OQ-WYZ\\\-])/g,zv=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;function He(e){return e.replace(rg,"")}function Y(e){return SB(e)}function Hc(e){return e.length===0?[]:zv?Array.from(zv.segment(e),t=>t.segment):Array.from(e)}function vB(e){let t=[],n=0,r;for(rg.lastIndex=0;(r=rg.exec(e))!==null;){if(r.index>n)for(let o of Hc(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 Hc(e.slice(n)))t.push({type:"text",value:o});return t}function ot(e,t){let n=Math.max(0,t-Y(e));return e+" ".repeat(n)}function kB(e,t){let n=Math.max(0,t-Y(e));return" ".repeat(n)+e}function og(e,t,n="left"){let r=Math.max(0,t-Y(e));if(r===0)return e;if(n==="right")return kB(e,t);if(n==="center"){let o=Math.floor(r/2);return" ".repeat(o)+e+" ".repeat(r-o)}return ot(e,t)}var EB=/^\x1b\]8;[^;\x07\x1b]*;(.*?)(?:\x07|\x1b\\)$/s,TB="\x1B]8;;\x1B\\";function oe(e,t,n="\u2026"){if(t<=0)return"";if(Y(e)<=t)return e;let r=Y(n),o=Math.max(0,t-r),s=0,i="",a=!1,l=!1;for(let c of vB(e)){if(c.type==="ansi"){i+=c.value,a=!0;let d=EB.exec(c.value);d&&(l=(d[1]??"").length>0);continue}let u=s+Y(c.value);if(u>o)break;i+=c.value,s=u}return i+n+(l?TB:"")+(a?"\x1B[0m":"")}function Jv(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.trunc(e))):0}function sg(e,t){let n=Jv(t,e.length);if(n===0||e.length===0)return 0;let r=0;for(let o of Hc(e)){let s=r+o.length;if(s>=n)return r;r=s}return r}function ko(e,t){let n=Jv(t,e.length);if(n>=e.length||e.length===0)return e.length;let r=0;for(let o of Hc(e)){let s=r+o.length;if(r>=n||n>r&&n<s)return s;r=s}return e.length}function ee(){let e=process.stdout.columns;return typeof e=="number"&&e>0?e:80}var Wc=new Set,Kc=new Set,Ps=!1,Eo=null;function xB(){for(let e of Wc)try{e()}catch{}}function RB(){for(let e of Kc)try{e()}catch{}}function CB(){Eo!==null&&clearTimeout(Eo),Eo=setTimeout(()=>{Eo=null,xB()},150)}function ig(){RB(),CB()}function AB(e){return Wc.add(e),Ps||(process.stdout.on("resize",ig),Ps=!0),()=>{Wc.delete(e),Vv()}}function _B(e){return Kc.add(e),Ps||(process.stdout.on("resize",ig),Ps=!0),()=>{Kc.delete(e),Vv()}}function Vv(){Wc.size===0&&Kc.size===0&&(Ps&&(process.stdout.off("resize",ig),Ps=!1),Eo!==null&&(clearTimeout(Eo),Eo=null))}var Ke={subscribe:AB,subscribeImmediate:_B};import Yv from"wrap-ansi";function ce(e,t,n={}){if(!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY)return e;let r=Math.floor(t);return Yv(e,r,{hard:n.breakLongWords??!1,trim:!1,wordWrap:!0})}function Xv(e,t){return!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY?e:Yv(e,Math.floor(t),{hard:!0,trim:!1,wordWrap:!1})}import Me from"chalk";var f={brand:Me.hex("#E67E4C"),mint:Me.hex("#5FE3A1"),goblin:Me.hex("#9CB04A"),user:Me.cyan,caret:Me.hex("#7AA2F7"),tool:Me.hex("#DCDCAA"),chrome:Me.hex("#B0B8C2"),syntaxString:Me.italic.hex("#8AB07A"),toolArg:Me.dim.white,thinking:Me.italic.hex("#9B8FB5"),success:Me.green,error:Me.red,warning:Me.yellow,plan:Me.hex("#9F7CE0"),bypass:Me.bold.hex("#FF6AC1"),meta:Me.blackBright,info:Me.hex("#5BA8FF"),fileRef:Me.hex("#56B5A8"),heading:Me.bold.white,label:Me.dim,dim:Me.dim,bold:Me.bold,italic:Me.italic,diffAdd:Me.green,diffRemove:Me.red,diffHunk:Me.blackBright};function qt(){return Math.max(22,ee()-6)}function Ia(e,t){return oe(e,t)}var PB={ok:f.success("\u25CF"),warn:f.warning("\u25CF"),error:f.error("\u25CF"),info:f.info("\u25C6")};function Zv(e,t){let o=t.reduce((w,k)=>Math.max(w,Y(k.label)),0),s=t.reduce((w,k)=>Math.max(w,Y(k.value)),0),i=o+4+2+s,a=Math.min(ee()-4,100),l=Math.max(44,Y(e),i,a);l=Math.min(l,qt());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=ce(e,l).split(`
|
|
1615
1615
|
`).map(w=>g+" "+ot(w,l)+" "+g),y=Math.max(1,l-o-4-2),S=t.map(w=>{let k=w.kind?PB[w.kind]+" ":" ",T=f.dim(ot(Ia(w.label,o),o)),R=" ".repeat(4),A=Ia(w.value,y),E=ot(A,y),O=T+R+k+E;return g+" "+O+" "+g});return[d,...b,p,...S,m].join(`
|
|
1616
1616
|
`)}import{sep as cg}from"node:path";J();J();import ag from"chalk";var Qv={".":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]},Gc=[".......KKKKK.......","......WKKLKKW......",".....KKWMLMWKK.....","..DDKKWLMMMLWKKDD..","DDD..KMMMMMMMK..DDD","..DDKMMMMMMMMMKDD..","...KKMMKKKKKMMKK...","...KMMKKKKKKKMMK...","...KMMMYMDMYMMMK...","...KMMMMMMMMMMMK...","...KKMMXXXXXMMKK...","....KKMMWXXMMKK....",".....KKMWMMMKK.....",".....KKMMMMMKK.....","......KKMMMKK......",".......KKKKK......."],lg=19,Ma=8;function IB(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=Qv[e[r]??"."]??null,s=Qv[t[r]??"."]??null;!o&&!s?n+=" ":o&&!s?n+=ag.rgb(o[0],o[1],o[2])("\u2580"):!o&&s?n+=ag.rgb(s[0],s[1],s[2])("\u2584"):o&&s&&(n+=ag.bgRgb(s[0],s[1],s[2]).rgb(o[0],o[1],o[2])("\u2580"))}return n}function MB(){if(Gc.length!==Ma*2)throw new Error(`GOBLIN_GRID has ${Gc.length} pixel rows but MASCOT_HEIGHT*2 = ${Ma*2}`);let e=[];for(let t=0;t<Ma;t++){let n=Gc[t*2]??"",r=Gc[t*2+1]??"";e.push(IB(n,r))}return e}function ek(e="idle"){return v.AFK_BANNER_PLAIN==="1"?[]:MB()}function tk(){return v.AFK_BANNER_PLAIN==="1"}function rk(e){let t=e.model!==void 0||e.worktree!==void 0||e.cwd!==void 0||e.version!==void 0;return t&&!tk()?$B(e):nk(t?OB(e):e)}function OB(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 ${ok(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(sk(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 nk(e){let t="Agent AFK",n=" \xB7 ",r=f.bold(t)+f.dim(n)+e.mode,o=t+n+e.mode,s=Math.min(ee()-4,120),i=Math.max(54,Y(o)+4,s);i=Math.min(i,qt());let a=i+4,l=f.dim,c=l("\u256D"+"\u2500".repeat(a)+"\u256E"),d=ce(r,i).split(`
|
|
1617
1617
|
`).map(g=>l("\u2502")+" "+ot(g,i)+" "+l("\u2502")),p=l("\u2570"+"\u2500".repeat(a)+"\u256F"),m=[c,...d,p];return e.metaLine!==void 0&&m.push(...ce(f.dim(" "+e.metaLine),ee()).split(`
|
|
@@ -1664,7 +1664,7 @@ The sub-agent that just finished returned output that reads like **decision-driv
|
|
|
1664
1664
|
|
|
1665
1665
|
Single-pass sub-agent reports are prone to confident hallucination \u2014 polished output that falls apart on re-derivation. Before acting on these conclusions, consider dispatching \`/shadow-verify\`. Independent verifiers will re-derive the 2\u20133 most load-bearing claims from scratch (without seeing the original reasoning) and flag any that don't hold up.
|
|
1666
1666
|
|
|
1667
|
-
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).`,eV=YJ.map(e=>new RegExp(`(?:^|-)${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:-|$)`,"i"));function tV(e){return e?eV.some(t=>t.test(e)):!1}function nV(e){return ZJ.some(t=>t.test(e))}function rV(e){let t=0;for(let n of XJ)n.test(e)&&t++;return t}function B_(e){if(e.event!=="SubagentStop")return{};let t=e.lastMessage??"";return t.length<600?{}:tV(e.agentType)?{}:nV(t)?{}:rV(t)<2?{}:{injectContext:QJ}}dn();ul();Og();function U_(e){return function(n){if(n.event!=="PreToolUse")return{};if(n.parentSessionId)return{};if(e()!=="plan")return{};let{toolName:r}=n;if(On(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=hu(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{}}}Ka();ul();import j_ from"path";var oV=["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"],sV=["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"],iV=["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 aV(e){return typeof e=="object"&&e!==null&&"command"in e?String(e.command??""):typeof e=="string"?e:""}function lV(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 cV(e){for(let t of oV)if(e.includes(t))return"high";for(let t of sV)if(e.includes(t))return"medium";for(let t of iV)if(e.includes(t))return"safe";return"medium"}function uV(e,t){if(!e)return"safe";let n=ar(j_.resolve(t.cwd,e)),r=Yg();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=ar(t.workspaceRoot);if(j_.relative(o,n).startsWith(".."))return"high"}return n.includes("/node_modules/")?"medium":"safe"}function H_(e,t,n){let r=e.toLowerCase();if(r==="bash"){let o=aV(t);return cV(o)}if(r==="write_file"||r==="edit_file"){let o=lV(t);return uV(o,n)}return On(e)==="read"?"safe":r==="send_telegram"?"medium":"safe"}jr();
|
|
1667
|
+
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).`,eV=YJ.map(e=>new RegExp(`(?:^|-)${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:-|$)`,"i"));function tV(e){return e?eV.some(t=>t.test(e)):!1}function nV(e){return ZJ.some(t=>t.test(e))}function rV(e){let t=0;for(let n of XJ)n.test(e)&&t++;return t}function B_(e){if(e.event!=="SubagentStop")return{};let t=e.lastMessage??"";return t.length<600?{}:tV(e.agentType)?{}:nV(t)?{}:rV(t)<2?{}:{injectContext:QJ}}dn();ul();Og();function U_(e){return function(n){if(n.event!=="PreToolUse")return{};if(n.parentSessionId)return{};if(e()!=="plan")return{};let{toolName:r}=n;if(On(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=hu(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{}}}Ka();ul();import j_ from"path";var oV=["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"],sV=["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"],iV=["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 aV(e){return typeof e=="object"&&e!==null&&"command"in e?String(e.command??""):typeof e=="string"?e:""}function lV(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 cV(e){for(let t of oV)if(e.includes(t))return"high";for(let t of sV)if(e.includes(t))return"medium";for(let t of iV)if(e.includes(t))return"safe";return"medium"}function uV(e,t){if(!e)return"safe";let n=ar(j_.resolve(t.cwd,e)),r=Yg();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=ar(t.workspaceRoot);if(j_.relative(o,n).startsWith(".."))return"high"}return n.includes("/node_modules/")?"medium":"safe"}function H_(e,t,n){let r=e.toLowerCase();if(r==="bash"){let o=aV(t);return cV(o)}if(r==="write_file"||r==="edit_file"){let o=lV(t);return uV(o,n)}return On(e)==="read"?"safe":r==="send_telegram"?"medium":"safe"}jr();Ne();Ei();var dV=3e5,W_=300;function K_(e,t,n,r){let o=r?.approvalTimeoutMs??dV,s=r?.promptForApproval??!0,i=r?.traceWriter,a=r?.route??((c,u)=>pt.route(c,u));async function l(c,u,d){let p=Date.now(),m=pV(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(A=>{S=()=>{y||(y=setTimeout(()=>{g.abort(),A(b)},o),y.unref?.())}});function k(A,E){let O=Date.now()-p,_=A.decision==="block";return on(i,{hookEvent:"PreToolUse",..._?{decision:"block"}:{},..._&&A.reason!==void 0?{reason:A.reason}:{},..._?{blockedTool:c}:{},durationMs:O,approvalOutcome:E}),A}let T;try{T=await Promise.race([a(m,{signal:g.signal,onActive:S}),w])}finally{y&&clearTimeout(y),d&&d.removeEventListener("abort",h)}if(T===b)return k(xl(c,`no approval arrived within ${Math.round(o/1e3)}s`),"timeout");if(T.action!=="accept")return k(xl(c,T.action==="cancel"?"the operator cancelled the approval prompt":"no operator approval was available"),T.action==="cancel"?"cancel":"decline");let R=String(T.content?.choice??"").toLowerCase();return R==="approve"?k({},"approved"):R==="deny"?k(xl(c,"the operator denied it"),"denied"):k(xl(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 H_(p,u.input,{cwd:m,workspaceRoot:m})!=="high"?{}:u.parentSessionId!==void 0||!s?xl(p,"AFK mode runs autonomously without a human watching"):l(p,u.input,d)}}function pV(e,t){let n=mV(t);return{serverName:"agent-afk",message:`AFK: \`${e}\` is high-risk / irreversible and AFK mode runs unattended. Approve this single call?`+(n?`
|
|
1668
1668
|
|
|
1669
1669
|
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 mV(e){let t;try{t=typeof e=="string"?e:JSON.stringify(e)}catch{t=String(e)}return t?(t=Ye(t),t.length>W_?`${t.slice(0,W_)}\u2026 [truncated]`:t):""}function xl(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.`}}ze();import{mkdirSync as hV,rmSync as yV,writeFileSync as bV}from"fs";import{join as kb}from"path";vt();function fV(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=G_(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 G_(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 gV(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 q_(e,t,n={}){if(e.nodes.length===0)return{outputs:{},failed:[],skipped:[]};fV(e);let{failFast:r=!0,nodeTimeoutMs:o}=n,s=o!==void 0&&Number.isFinite(o)&&o>0,i=G_(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,k=()=>{w.signal.aborted||w.abort(m.signal.reason)};m.signal.aborted?w.abort(m.signal.reason):m.signal.addEventListener("abort",k,{once:!0});let T;s&&!w.signal.aborted&&(T=setTimeout(()=>{w.signal.aborted||w.abort(new Gt(`DAG node "${y}" exceeded nodeTimeoutMs of ${o}ms`,o))},o));let R={};for(let A of i.upstream.get(y)??[])R[A]=l[A];try{let A=await S.run(R,w.signal);return{id:y,result:A}}finally{T!==void 0&&clearTimeout(T),m.signal.removeEventListener("abort",k)}}));for(let y=0;y<b.length;y++){let S=b[y];if(S.status==="fulfilled"){let{id:w,result:k}=S.value;l[w]=k,d.add(w),p.delete(w);for(let T of i.downstream.get(w)??[])p.set(T,p.get(T)-1)}else{let w=S.reason instanceof Error?S.reason:new Error(String(S.reason)),k=h[y];c.push({id:k,error:w}),d.add(k),p.delete(k),gV(k,i.downstream,u),r&&m.abort("fail-fast")}}}}finally{t.removeEventListener("abort",g)}return{outputs:l,failed:c,skipped:Array.from(u)}}Bt();vt();async function ip(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}:{},agentType:c.agentType??c.idPrefix??`dag-${c.id}`,...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 Gt?b=new Error(`Subagent ${c.id} aborted: ${y.message}`,h.error?{cause:h.error}:{}):b=h.error??new Error(`Subagent ${c.id} ${h.status}`),OR(b,{partialOutput:h.partialOutput,subagentId:h.id})}return h.output??h.message?.content}finally{d.removeEventListener("abort",m),await p.teardown().catch(()=>{})}}}));return q_({nodes:l,edges:o},a,{failFast:s,nodeTimeoutMs:i})}it();Qn();Wr();er();K();var z_=1e3,ap=36e5,J_=1,V_=1e3;function wV(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<z_)throw new Error(`"node_timeout_ms" must be at least ${z_}ms (got ${d}). Sub-second timeouts are almost always a unit mistake.`);c=Math.min(ap,d),d>ap&&l.push(`node_timeout_ms clamped: requested ${d}ms exceeds the maximum ${ap}ms; using ${ap}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<J_)throw new Error(`"max_tool_calls_per_node" must be at least ${J_}`);if(d>V_)throw new Error(`"max_tool_calls_per_node" must be at most ${V_} (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 Rl=8e3,Y_=500,X_=4e3;function SV(e){if(e==null)return;let t=typeof e=="string"?e:JSON.stringify(e);if(t.length!==0)return t.length>X_?t.slice(0,X_)+`
|
|
1670
1670
|
\u2026 (truncated)`:t}function vV(e,t,n,r){try{let o=kb(wt(),e,"compose",t);hV(o,{recursive:!0});let s=kb(o,`${n}.txt`);return bV(s,r,"utf8"),s}catch{return}}function kV(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>Rl){let l=vV(t.sessionId,t.callId,o,i);r.push({nodeId:o,emittedChars:Rl,totalChars:i.length,...l!==void 0?{spillPath:l}:{}});let c=l!==void 0?`
|
|
@@ -1751,9 +1751,9 @@ _\u{1F916} Posted by \`agent-afk /review --post github\`_`}function c4(e){let t=
|
|
|
1751
1751
|
${l}`):s,a=!1;for(let l of i){let c=await n.pushIfConfigured(l);if(c===null){e.warn("/review --post telegram skipped: Telegram is not configured (TELEGRAM_BOT_TOKEN / AFK_TELEGRAM_ALLOWED_CHAT_IDS).");return}c.some(u=>u.ok)&&(a=!0)}a?e.success(`/review summary sent to Telegram${i.length>1?` (${i.length} messages)`:""}.`):e.warn("/review --post telegram failed: Telegram rejected all sends.")}catch(r){e.warn(`/review --post telegram failed: ${r instanceof Error?r.message:String(r)} (the review output above is unaffected).`)}}import{Client as aI}from"@modelcontextprotocol/sdk/client/index.js";import{CallToolResultSchema as E4}from"@modelcontextprotocol/sdk/types.js";import{StreamableHTTPError as uI}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{UnauthorizedError as Mb}from"@modelcontextprotocol/sdk/client/auth.js";import{StdioClientTransport as f4}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as g4}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as h4}from"@modelcontextprotocol/sdk/client/sse.js";var m4=/\$(\$)?\{([A-Z_][A-Z0-9_]*)\}/gi;function Sp(e,t=process.env){let n=[];return{value:e.replace(m4,(o,s,i)=>{if(s==="$")return`\${${i}}`;let a=t[i];return a===void 0||a===""?(n.push(i),""):a}),missing:n}}function Ab(e,t=process.env){if(e===void 0)return{value:{},missing:[]};let n={},r=new Set;for(let[o,s]of Object.entries(e)){let{value:i,missing:a}=Sp(s,t);n[o]=i;for(let l of a)r.add(l)}return{value:n,missing:[...r]}}function y4(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"||e==="0.0.0.0"}function b4(){let e=["PATH","HOME","USER","USERNAME","LOGNAME","SHELL","TERM","TMPDIR","TEMP","TMP","LANG","LC_ALL","SYSTEMROOT","APPDATA","LOCALAPPDATA","PROGRAMDATA","PROGRAMFILES","NODE_PATH"],t={};for(let n of e){let r=process.env[n];typeof r=="string"&&(t[n]=r)}return t}function ZP(e,t=process.env){if(e===void 0)return{headers:{},missing:[]};let n={},r=new Set;for(let[o,s]of Object.entries(e)){let{value:i,missing:a}=Sp(s,t);if(a.length>0)for(let l of a)r.add(l);else n[o]=i}return{headers:n,missing:[...r]}}function vp(e,t,n){let r=t.type??(t.command?"stdio":"streamable-http");if(r==="stdio"){if(typeof t.command!="string"||t.command.length===0)throw new Error(`McpTransport(${e}): stdio requires \`command\``);let{value:o,missing:s}=Ab(t.env);s.length>0&&console.warn(`[mcp:${e}] missing env vars (passing as empty): ${s.join(", ")}`);let i={command:t.command,...t.args?{args:t.args}:{},env:{...b4(),...o}};return{transport:new f4(i),isSSE:!1}}if(r==="streamable-http"||r==="sse"){if(typeof t.url!="string"||t.url.length===0)throw new Error(`McpTransport(${e}): ${r} requires \`url\``);let o=new URL(t.url);if(o.protocol!=="https:"&&!y4(o.hostname))throw new Error(`McpTransport(${e}): refusing ${r} URL ${o.protocol}//${o.hostname} \u2014 credentials and tool I/O would transit in plaintext. Use https:, or point the URL at localhost / 127.0.0.1.`);let{headers:s,missing:i}=ZP(t.headers);return i.length>0&&console.warn(`[mcp:${e}] missing header vars (passing as omitted): ${i.join(", ")}`),r==="sse"?(process.stderr.write(`[mcp:${e}] WARNING: SSE transport is deprecated. Upgrade your MCP server to use streamable-HTTP.
|
|
1752
1752
|
`),{transport:new h4(o,{...Object.keys(s).length>0?{requestInit:{headers:s}}:{},...n?{authProvider:n}:{}}),isSSE:!0}):{transport:new g4(o,{...Object.keys(s).length>0?{requestInit:{headers:s}}:{},...n?{authProvider:n}:{}}),isSSE:!1}}throw new Error(`McpTransport(${e}): unknown transport type "${String(r)}"`)}Tp();var lI={name:"agent-afk",version:"2.x"},cI={},Ib=3e4,Fi=class{serverName;config;client;connected=!1;pendingAuthTransport;onTransportError;onToolListChanged;constructor(t,n){this.serverName=t,this.config=n}async connect(){if(this.connected)throw new Error(`McpClient(${this.serverName}): already connected`);let t=this.config.oauth===!0?new Di(this.serverName):void 0,{primary:n,fallback:r}=x4(this.serverName,this.config,t),o=new aI(lI,{capabilities:cI});n.transport.onerror=u=>{this.onTransportError?.(u)};try{let{ToolListChangedNotificationSchema:u}=await import("@modelcontextprotocol/sdk/types.js");o.setNotificationHandler(u,()=>{this.onToolListChanged?.()})}catch{}let s=this.config.timeout??Ib,i=n.isSSE,a=o;try{await xp(o.connect(n.transport),s,()=>new Error(`MCP server "${this.serverName}" connect timed out after ${s}ms`),()=>n.transport.close().catch(()=>{}))}catch(u){if(R4(u)&&r!==null){console.warn(`[mcp:${this.serverName}] streamable-HTTP got ${C4(u)}; falling back to SSE transport`);let d=r();d.transport.onerror=m=>{this.onTransportError?.(m)};let p=new aI(lI,{capabilities:cI});try{let{ToolListChangedNotificationSchema:m}=await import("@modelcontextprotocol/sdk/types.js");p.setNotificationHandler(m,()=>{this.onToolListChanged?.()})}catch{}await xp(p.connect(d.transport),s,()=>new Error(`MCP server "${this.serverName}" (SSE fallback) connect timed out after ${s}ms`),()=>d.transport.close().catch(()=>{})),a=p,i=!0}else throw u instanceof Mb&&(this.pendingAuthTransport=n.transport),u}i&&!n.isSSE&&process.stderr.write(`[mcp:${this.serverName}] WARNING: connected via deprecated SSE transport. Upgrade your MCP server to streamable-HTTP.
|
|
1753
1753
|
`),this.client=a,this.connected=!0,this.pendingAuthTransport=void 0;let l=await xp(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??Ib;return(await xp(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??Ib,s;try{s=await this.client.callTool({name:t,arguments:n??{}},E4,{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 T4(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 T4(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(`
|
|
1754
|
-
`);return{content:n.length===0?"(empty tool result)":n,...e.isError?{isError:!0}:{}}}function x4(e,t,n){let r=t.type??(t.command?"stdio":"streamable-http");return{primary:vp(e,t,n),fallback:r==="streamable-http"?()=>vp(e,{...t,type:"sse"},n):null}}function R4(e){return e instanceof uI&&(e.code===404||e.code===405)}function C4(e){return e instanceof uI?e.code:void 0}function xp(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 A4}from"node:crypto";var dI="mcp__",pI="__",Ob=64,_4=6;function Pl(e){if(e.length===0)return"_";let n=e.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_{2,}/g,"_");return n.length===0?"_":n}function P4(e){return A4("sha256").update(e).digest("hex").slice(0,_4)}function mI(e,t){let n=Pl(e),r=Pl(t),o=`${dI}${n}${pI}${r}`;if(o.length<=Ob)return o;let i=`${`${dI}${P4(e)}${pI}`}${r}`;return i.length<=Ob?i:i.slice(0,Ob)}function Il(e){let t=new Map,n=new Map;for(let{serverName:o,toolNames:s}of e)for(let i of s){let a=mI(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}}
|
|
1754
|
+
`);return{content:n.length===0?"(empty tool result)":n,...e.isError?{isError:!0}:{}}}function x4(e,t,n){let r=t.type??(t.command?"stdio":"streamable-http");return{primary:vp(e,t,n),fallback:r==="streamable-http"?()=>vp(e,{...t,type:"sse"},n):null}}function R4(e){return e instanceof uI&&(e.code===404||e.code===405)}function C4(e){return e instanceof uI?e.code:void 0}function xp(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 A4}from"node:crypto";var dI="mcp__",pI="__",Ob=64,_4=6;function Pl(e){if(e.length===0)return"_";let n=e.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_{2,}/g,"_");return n.length===0?"_":n}function P4(e){return A4("sha256").update(e).digest("hex").slice(0,_4)}function mI(e,t){let n=Pl(e),r=Pl(t),o=`${dI}${n}${pI}${r}`;if(o.length<=Ob)return o;let i=`${`${dI}${P4(e)}${pI}`}${r}`;return i.length<=Ob?i:i.slice(0,Ob)}function Il(e){let t=new Map,n=new Map;for(let{serverName:o,toolNames:s}of e)for(let i of s){let a=mI(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}}Ne();var vr=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=Il(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):
|
|
1755
1755
|
${o.join(`
|
|
1756
|
-
`)}`)}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=Pl(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 Fi(c,u);m.client=g,g.onTransportError=b=>{m.state.status="error",m.state.error=Rp(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:k}=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 T=k?`${k.name}@${k.version}`:"unknown";console.log(`[mcp:${c}] connected (${T}) \u2014 ${w.length} tool(s)`)}catch(w){if(w instanceof Mb){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 k=w instanceof Error?w.message:String(w);if(m.state.status="error",m.state.error=Rp(k,200),u.alwaysLoad===!0)throw new Error(`MCP server "${c}" is marked alwaysLoad but failed to connect: ${k}`);console.warn(`[mcp:${c}] connect failed: ${k}`)}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(I4(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=Il([{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 Fi(t,r.state.config);o.onTransportError=i=>{r.state.status="error",r.state.error=Rp(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=Rp(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=Il([{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 I4(e,t){let n=t.description??`MCP tool ${t.name}`;return{name:e,description:n,input_schema:t.inputSchema}}function Rp(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}J();K();import{existsSync as Ol,lstatSync as M4,readFileSync as O4,readdirSync as $4}from"node:fs";import{join as Ml}from"node:path";function qo(){return Ml(rn(),"mcp.json")}function fI(e=process.cwd()){return Ml(e,".mcp.json")}var D4=5;function $b(e=Ze()){if(!Ol(e))return[];let t=[];return gI(e,e,0,t,new Set),t}function gI(e,t,n,r,o){if(n>D4||o.has(t))return;o.add(t);let s=Ml(t,".claude-plugin","plugin.json");if(Ol(s)){let a=Ml(t,".claude-plugin","mcp.json");Ol(a)&&r.push(a);return}let i;try{i=$4(t)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=Ml(t,a),c;try{c=M4(l)}catch{continue}c.isDirectory()&&gI(e,l,n+1,r,o)}}function F4(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 Li(e){if(!Ol(e))return{mcpServers:{},sources:[],warnings:[]};let t=[],n;try{n=JSON.parse(O4(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=F4(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 zo(e={}){let t=[],n=[];if(e.importedMcpConfigs&&e.importedMcpConfigs.length>0)for(let a of e.importedMcpConfigs)t.push({path:a,loaded:Li(a)});if(e.pluginsRoot!==null){let a=e.pluginsRoot,l=a?$b(a):$b();for(let c of l)t.push({path:c,loaded:Li(c)})}if(!e.skipUserGlobal){let a=qo();t.push({path:a,loaded:Li(a)})}if(!e.skipProjectLocal&&v.AFK_ALLOW_PROJECT_MCP!=="0"){let a=fI(e.cwd);Ol(a)&&(t.push({path:a,loaded:Li(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:Li(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}}Tp();ur();He();function B4(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 yI=10*1024*1024;function bI(){return new Promise((e,t)=>{let n=[],r=0;if(process.stdin.readableEnded){e("");return}let o=s=>{if(r+=s.length,r>yI){process.stdin.destroy(new Error(`stdin exceeds ${yI}-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 wI(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 kI(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.",Rt()).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
|
+
`)}`)}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=Pl(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 Fi(c,u);m.client=g,g.onTransportError=b=>{m.state.status="error",m.state.error=Rp(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();Oe(n.traceWriter,{phase:"mcp_server_start",metadata:{server:c}});let y="error",S=0;try{let{tools:w,serverInfo:k}=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 T=k?`${k.name}@${k.version}`:"unknown";console.log(`[mcp:${c}] connected (${T}) \u2014 ${w.length} tool(s)`)}catch(w){if(w instanceof Mb){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 k=w instanceof Error?w.message:String(w);if(m.state.status="error",m.state.error=Rp(k,200),u.alwaysLoad===!0)throw new Error(`MCP server "${c}" is marked alwaysLoad but failed to connect: ${k}`);console.warn(`[mcp:${c}] connect failed: ${k}`)}finally{Oe(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(I4(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=Il([{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 Fi(t,r.state.config);o.onTransportError=i=>{r.state.status="error",r.state.error=Rp(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=Rp(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=Il([{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 I4(e,t){let n=t.description??`MCP tool ${t.name}`;return{name:e,description:n,input_schema:t.inputSchema}}function Rp(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}J();K();import{existsSync as Ol,lstatSync as M4,readFileSync as O4,readdirSync as $4}from"node:fs";import{join as Ml}from"node:path";function qo(){return Ml(rn(),"mcp.json")}function fI(e=process.cwd()){return Ml(e,".mcp.json")}var D4=5;function $b(e=Ze()){if(!Ol(e))return[];let t=[];return gI(e,e,0,t,new Set),t}function gI(e,t,n,r,o){if(n>D4||o.has(t))return;o.add(t);let s=Ml(t,".claude-plugin","plugin.json");if(Ol(s)){let a=Ml(t,".claude-plugin","mcp.json");Ol(a)&&r.push(a);return}let i;try{i=$4(t)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=Ml(t,a),c;try{c=M4(l)}catch{continue}c.isDirectory()&&gI(e,l,n+1,r,o)}}function F4(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 Li(e){if(!Ol(e))return{mcpServers:{},sources:[],warnings:[]};let t=[],n;try{n=JSON.parse(O4(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=F4(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 zo(e={}){let t=[],n=[];if(e.importedMcpConfigs&&e.importedMcpConfigs.length>0)for(let a of e.importedMcpConfigs)t.push({path:a,loaded:Li(a)});if(e.pluginsRoot!==null){let a=e.pluginsRoot,l=a?$b(a):$b();for(let c of l)t.push({path:c,loaded:Li(c)})}if(!e.skipUserGlobal){let a=qo();t.push({path:a,loaded:Li(a)})}if(!e.skipProjectLocal&&v.AFK_ALLOW_PROJECT_MCP!=="0"){let a=fI(e.cwd);Ol(a)&&(t.push({path:a,loaded:Li(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:Li(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}}Tp();ur();Ne();function B4(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 yI=10*1024*1024;function bI(){return new Promise((e,t)=>{let n=[],r=0;if(process.stdin.readableEnded){e("");return}let o=s=>{if(r+=s.length,r>yI){process.stdin.destroy(new Error(`stdin exceeds ${yI}-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 wI(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 kI(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.",Rt()).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
|
|
1757
1757
|
`),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
|
|
1758
1758
|
`),process.exitCode=1;return}if(n.sessionId!==void 0&&!B4(n.sessionId)){process.stderr.write(`Error: --session-id must be a UUID (got: ${n.sessionId})
|
|
1759
1759
|
`),process.exitCode=1;return}if(n.sessionId!==void 0&&Ii(n.sessionId)!==void 0){process.stderr.write(`Error: session already exists: ${n.sessionId} \u2014 use --resume to continue it
|
|
@@ -1763,15 +1763,15 @@ ${o.join(`
|
|
|
1763
1763
|
`),process.exitCode=1;return}if(o.trim()===""){process.stderr.write(`Error: message is empty \u2014 stdin contained only whitespace
|
|
1764
1764
|
`),process.exitCode=1;return}let i=L4("Initializing agent...").start(),a=null,l,c,u,d,p=!1,m,g=hp(n.model),h=!1,b;try{if(n.worktree!==void 0)try{c=await Mu(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(Re){i.fail("Failed to create worktree"),z(Re)}let y,S,w,k,T,R;try{y=Qr(n.thinking)??gi(),S=eo(n.effort)??hi(),w=yi(n.maxBudgetUsd)??Ly(),k=yi(n.taskBudget)??Ny(),T=bi(n.maxOutputTokens)??wl(),R=void 0}catch(Re){i.fail("Invalid options"),z(Re)}if(n.dumpPrompt!==void 0){let Re=n.dumpPrompt===!0?vI.join(SI.homedir(),".afk","logs",`prompt-dump-${new Date().toISOString().replace(/[:.]/g,"-")}.json`):String(n.dumpPrompt);process.env.AFK_DUMP_PROMPT=Re,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 A=Ae(),{prompt:E,source:O}=fi(),_=It(),I=_.autoRouting?.chat??!1,L=cp(E,I,"one-shot"),N={},F=Mi({resume:n.resume,continue:n.continue});if(n.resume&&F&&!F.stored){i.fail("Session not found"),process.stderr.write(`Error: session not found: ${JSON.stringify(n.resume)}
|
|
1765
1765
|
Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
1766
|
-
`),process.exitCode=1;return}F&&(N=Oi(F),p=!0,m=F.id),n.sessionId!==void 0&&(N={sessionId:n.sessionId},p=!0,m=n.sessionId);let U=F?.stored?.model??n.model,H=Bs(U);if(H)throw new Error(H);g.model=U,F?.stored&&(g.totalTurns=F.stored.totalTurns,g.totalCostUsd=F.stored.totalCostUsd,g.totalTokens=F.stored.totalTokens,g.totalDurationMs=F.stored.totalDurationMs,g.turns=[...F.stored.turns],g.sessionId=F.stored.sessionId??F.resumeId,g.sessionStartTime=F.stored.startedAt??Date.now()),n.sessionId!==void 0&&(g.sessionId=n.sessionId);let D,C=ro();b=C?.tracePath;let B=new re({apiKey:A,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{},...u!==void 0?{cwd:u}:{}}),M=ci(_.openaiBaseUrl!==void 0?{openaiBaseUrl:_.openaiBaseUrl}:{}),j={get sessionId(){return D?.sessionId},getInputStreamRef(){return D?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return D?.abortSignal??new AbortController().signal},get hookRegistry(){return D?.hookRegistry}},X=ui(n.model,A,M,_.baseUrl,C?.writer,void 0,u,Je,"cli"),ie=new Dn({subagentManager:B,parentSession:j,surface:"cli",defaultConfig:{apiKey:A,systemPrompt:E,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{}},defaultSubagentModel:Qt(n.model),childProviderFactory:M,childSkillExecutorFactory:X,resolveApiKeyForModel:Je,depth:0,...u!==void 0?{cwd:u}:{}}),Z=new Fn({parentSession:j,surface:"cli",defaultModel:n.model,defaultSubagentModel:Qt(n.model),apiKey:A,childProviderFactory:M,childSkillExecutorFactory:X,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{},resolveApiKeyForModel:Je,...C?.writer!==void 0?{traceWriter:C.writer}:{},...u!==void 0?{cwd:u}:{}}),fe=new to({parentSession:j,defaultModel:n.model,defaultSubagentModel:Qt(n.model),apiKey:A,resolveApiKeyForModel:Je,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{},...u!==void 0?{cwd:u}:{},systemPrompt:E??"",surface:"cli",depth:0});l=new dt;{let Re=u??process.cwd(),Ie=ln(Dt()).mcpConfigs.filter(
|
|
1766
|
+
`),process.exitCode=1;return}F&&(N=Oi(F),p=!0,m=F.id),n.sessionId!==void 0&&(N={sessionId:n.sessionId},p=!0,m=n.sessionId);let U=F?.stored?.model??n.model,H=Bs(U);if(H)throw new Error(H);g.model=U,F?.stored&&(g.totalTurns=F.stored.totalTurns,g.totalCostUsd=F.stored.totalCostUsd,g.totalTokens=F.stored.totalTokens,g.totalDurationMs=F.stored.totalDurationMs,g.turns=[...F.stored.turns],g.sessionId=F.stored.sessionId??F.resumeId,g.sessionStartTime=F.stored.startedAt??Date.now()),n.sessionId!==void 0&&(g.sessionId=n.sessionId);let D,C=ro();b=C?.tracePath;let B=new re({apiKey:A,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{},...u!==void 0?{cwd:u}:{}}),M=ci(_.openaiBaseUrl!==void 0?{openaiBaseUrl:_.openaiBaseUrl}:{}),j={get sessionId(){return D?.sessionId},getInputStreamRef(){return D?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return D?.abortSignal??new AbortController().signal},get hookRegistry(){return D?.hookRegistry}},X=ui(n.model,A,M,_.baseUrl,C?.writer,void 0,u,Je,"cli"),ie=new Dn({subagentManager:B,parentSession:j,surface:"cli",defaultConfig:{apiKey:A,systemPrompt:E,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{}},defaultSubagentModel:Qt(n.model),childProviderFactory:M,childSkillExecutorFactory:X,resolveApiKeyForModel:Je,depth:0,...u!==void 0?{cwd:u}:{}}),Z=new Fn({parentSession:j,surface:"cli",defaultModel:n.model,defaultSubagentModel:Qt(n.model),apiKey:A,childProviderFactory:M,childSkillExecutorFactory:X,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{},resolveApiKeyForModel:Je,...C?.writer!==void 0?{traceWriter:C.writer}:{},...u!==void 0?{cwd:u}:{}}),fe=new to({parentSession:j,defaultModel:n.model,defaultSubagentModel:Qt(n.model),apiKey:A,resolveApiKeyForModel:Je,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{},...u!==void 0?{cwd:u}:{},systemPrompt:E??"",surface:"cli",depth:0});l=new dt;{let Re=u??process.cwd(),Ie=ln(Dt()).mcpConfigs.filter($e=>$e.format==="json").map($e=>$e.source),Se=zo({cwd:Re,...Ie.length>0?{importedMcpConfigs:Ie}:{},...n.mcpConfig!==void 0?{cliOverride:n.mcpConfig}:{}}),ke=Object.values(Se.mcpServers).filter($e=>!$e.disabled).length;if(ke>0){let $e=Date.now();Oe(C?.writer,{phase:"mcp_connect_start",metadata:{serverCount:ke}});try{d=await vr.fromConfig(Se.mcpServers,{warnings:Se.warnings,...C?.writer!==void 0?{traceWriter:C.writer}:{}})}finally{Oe(C?.writer,{phase:"mcp_connect_done",durationMs:Date.now()-$e,metadata:{serverCount:ke}})}}else if(Se.warnings.length>0)for(let $e of Se.warnings)process.stderr.write(`[mcp] ${$e}
|
|
1767
1767
|
`)}let V=d?.getMcpToolWireNames()??[];R=wi(n.provider,{subagentExecutor:ie,skillExecutor:Z,composeExecutor:fe,memoryStore:l,model:String(n.model),..._.openaiBaseUrl!==void 0?{openaiBaseUrl:_.openaiBaseUrl}:{},...d!==void 0?{mcpManager:d}:{}})??new tt({permissions:{allowedTools:lp(V)},subagentExecutor:ie,skillExecutor:Z,composeExecutor:fe,memoryStore:l,surface:"cli",...d!==void 0?{mcpManager:d}:{}}),await ki(),a=new xt(mr({model:U,surface:"cli",apiKey:Je(U),maxTurns:parseInt(n.maxTurns,10),isNonInteractive:!0,...n.dangerouslySkipPermissions?{permissionMode:"bypassPermissions"}:_.permissionMode!==void 0?{permissionMode:_.permissionMode}:{},hookRegistry:Ci(Re=>{console.log(pp(Re))},"cli",l,void 0,Ri({cwd:u}),{cwd:u,...C?.writer!==void 0?{traceWriter:C.writer}:{}}).registry,...L!==void 0?{systemPrompt:L}:{},...O!==void 0?{systemPromptSource:O}:{},...y!==void 0?{thinking:y}:{},...S!==void 0?{effort:S}:{},...w!==void 0?{maxBudgetUsd:w}:{},...k!==void 0?{taskBudget:k}:{},...T!==void 0?{maxOutputTokens:T}:{},..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{},...C?{traceWriter:C.writer}:{},..._.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:_.autoResumeOnUsageLimit}:{},...u!==void 0?{cwd:u}:{},...N,provider:R})),D=a,i.text="Sending message...";let _e=async(Re,Ie)=>{if(r.length===0||Ie)return;let Se={line:ke=>{process.stderr.write(`${ke??""}
|
|
1768
1768
|
`)},raw:ke=>{process.stderr.write(ke)},success:ke=>{process.stderr.write(`\u2714 ${ke}
|
|
1769
1769
|
`)},info:ke=>{process.stderr.write(`\u2139 ${ke}
|
|
1770
1770
|
`)},warn:ke=>{process.stderr.write(`\u26A0 ${ke}
|
|
1771
1771
|
`)},error:ke=>{process.stderr.write(`\u2716 ${ke}
|
|
1772
1772
|
`)}};try{await wp(Se,{targets:r,reviewText:Re,prRefFromArgs:n.postPr??null})}catch(ke){process.stderr.write(`[--post] publish failed: ${ke instanceof Error?ke.message:String(ke)}
|
|
1773
|
-
`)}};if(n.format==="stream-json"){let Re=(
|
|
1774
|
-
`)
|
|
1773
|
+
`)}};if(n.format==="stream-json"){let Re=($e,_t)=>_t instanceof Date?_t.toISOString():_t instanceof Error?{message:_t.message,name:_t.name}:_t;i.stop();let Ie="",Se=!1,ke=a.sendMessageStream(o);for await(let $e of ke)if(await wI(process.stdout,JSON.stringify($e,Re)+`
|
|
1774
|
+
`),$e.type==="chunk"&&$e.chunk.type==="content"&&(Ie+=$e.chunk.content),$e.type==="done"&&(Go(g,o,Ie,$e.metadata),$e.metadata?.sessionId&&!g.sessionId&&(g.sessionId=String($e.metadata.sessionId))),$e.type==="error"){process.exitCode=1,Se=!0;break}await _e(Ie,Se);return}let Xe=await a.sendMessage(o,{stream:n.stream});i.succeed("Response received");let ge=a.getLastResponseMetadata();if(Go(g,o,Xe.content,ge??void 0),ge?.sessionId&&!g.sessionId&&(g.sessionId=String(ge.sessionId)),n.format==="json"){let Re=ge?Number(ge.usage?.input_tokens??0):0,Ie=ge?Number(ge.usage?.output_tokens??0):0;console.log(JSON.stringify({success:!0,model:U,message:Xe.content,timestamp:Xe.timestamp,...ge?.totalCostUsd!==void 0?{costUsd:ge.totalCostUsd}:{},...ge?.durationMs!==void 0?{durationMs:ge.durationMs}:{},...Re>0?{inputTokens:Re}:{},...Ie>0?{outputTokens:Ie}:{}},null,2))}else{if(console.log(hI.cyan(`
|
|
1775
1775
|
\u{1F916} Claude:`)),console.log(Xn(Xe.content)),ge){let Re=[];ge.durationMs&&Re.push(he(ge.durationMs)),ge.totalCostUsd!==void 0&&Re.push(lt(ge.totalCostUsd));let Ie=Number(ge.usage?.input_tokens??0),Se=Number(ge.usage?.output_tokens??0);Ie+Se>0&&Re.push(ae(Ie+Se)+" tokens"),Re.length>0&&console.log(hI.dim(" \xB7 "+Re.join(" \xB7 ")))}console.log("")}await _e(Xe.content,!1)}catch(y){if(h=!0,n.format==="stream-json"){let S=y instanceof Error?y:new Error(String(y));try{await wI(process.stdout,JSON.stringify({type:"error",error:{message:S.message,name:S.name}})+`
|
|
1776
1776
|
`)}catch{}process.exitCode=1}i.fail("Failed to send message"),z(y)}finally{if(p&&g.totalTurns>0&&!h)try{let S=Nn(g,m).replace(/\.json$/,"").split("/").pop()??m??g.sessionId??"unknown";process.stderr.write(`Continue with: afk chat <msg> --resume ${S}
|
|
1777
1777
|
`)}catch{}if(a&&(await a.close(),b!==void 0))try{let{mdPath:y}=Eb(b);N4(y)&&process.stderr.write(`Receipt: ${y}
|
|
@@ -1815,14 +1815,14 @@ ${u}`}function Xb(e,t){let n=RM[t.status];e.out.line(` ${n} ${f.bold(t.jobId)}
|
|
|
1815
1815
|
`),t&&(n=n.replace(/^\n+/,"").replace(/\n+$/,"")),n}function x5(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qb(e,t){let n=x5(t),r=new RegExp(`<${n}>`,"g"),o=r.test(e);r.lastIndex=0;let s=new RegExp(`(\\n|^)[ \\t]*<${n}>[ \\t]*\\n?`,"gm"),i=new RegExp(`(\\n|^)[ \\t]*</${n}>[ \\t]*\\n?`,"gm"),a=new RegExp(`</${n}>`,"g"),l=!1,c=e;return c=c.replace(s,(u,d)=>(l=!0,d)),c=c.replace(i,(u,d)=>(l=!0,d)),c=c.replace(r,()=>(l=!0,"")),c=c.replace(a,()=>(l=!0,"")),c=c.replace(/^[ \t]+$/gm,""),c=c.replace(/\n{3,}/g,`
|
|
1816
1816
|
|
|
1817
1817
|
`),l&&(c=c.replace(/^\n+/,"").replace(/\n+$/,"")),{text:c,found:o}}J();Pe();J();import jl from"string-width";function Qo(e){let{buffer:t,promptText:n,isTTY:r,attachmentSummary:o}=e,s=o&&o.length>0?o:null;if(!r){let g=n+t;return s!==null?`${g} ${s}`:g}let i=e.terminalWidth??ee(),a=t.includes(`
|
|
1818
|
-
`),l=jl(
|
|
1818
|
+
`),l=jl(He(t)),c=l>=i-2,u;if(!a&&!c){let g=f.user("\u25B6")+" ",h=2,b=i-1,y=Math.max(0,b-l-h);u=g+" ".repeat(y)+t}else u=Ms({kind:"user",body:t});if(s===null)return u;let d=jl(s),p=Math.max(0,i-1-d),m=" ".repeat(p)+f.dim(s);return u+`
|
|
1819
1819
|
`+m}function ew(e,t,n){let r=n||80,o=e.split(`
|
|
1820
|
-
`),s=0;for(let i=0;i<o.length;i++){let a=
|
|
1821
|
-
`),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=
|
|
1820
|
+
`),s=0;for(let i=0;i<o.length;i++){let a=He(o[i]),l=(i===0?t:0)+jl(a);s+=Math.max(1,Math.ceil(l/r))}return Math.max(0,s-1)}function so(e,t,n,r){let o=r||80,s=e.split(`
|
|
1821
|
+
`),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=He(c.slice(0,p)),g=(l===0?n:0)+jl(m),h=Math.floor(g/o),b=g%o;return{row:i+h,col:b}}let d=(l===0?n:0)+jl(He(c));i+=Math.max(1,Math.ceil(d/o)),a+=u}return{row:i,col:0}}function es(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.trunc(e))):0}function Hn(e,t){let n=es(t,e.buffer.length);return n===e.cursor?e:{buffer:e.buffer,cursor:n}}function MM(e,t){let n=es(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 OM(e,t){let n=e.length,r=es(t,n);for(;r<n&&/\s/.test(e.charAt(r));)r++;for(;r<n&&!/\s/.test(e.charAt(r));)r++;return r}function $M(e,t){let n=es(t,e.length),r=n===0?-1:e.lastIndexOf(`
|
|
1822
1822
|
`,n-1);return r<0?0:r+1}function DM(e,t){let n=es(t,e.length),r=e.indexOf(`
|
|
1823
1823
|
`,n);return r<0?e.length:r}function io(e,t,n){let r=es(t.start,e.buffer.length),o=es(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 q={seed(e=""){return{buffer:e,cursor:e.length}},replaceRange:io,insert(e,t){return t.length===0?e:io(e,{start:e.cursor,end:e.cursor},t)},backspace(e){if(e.cursor===0)return e;let t=sg(e.buffer,e.cursor);return io(e,{start:t,end:e.cursor},"")},deleteForward(e){if(e.cursor>=e.buffer.length)return e;let t=ko(e.buffer,e.cursor);return io(e,{start:e.cursor,end:t},"")},deleteWordBackward(e){if(e.cursor===0)return e;let t=MM(e.buffer,e.cursor);return t===e.cursor?e:io(e,{start:t,end:e.cursor},"")},deleteWordForward(e){if(e.cursor>=e.buffer.length)return e;let t=OM(e.buffer,e.cursor);return t===e.cursor?e:io(e,{start:e.cursor,end:t},"")},deleteToLineStart(e){let t=$M(e.buffer,e.cursor);return t===e.cursor?e:io(e,{start:t,end:e.cursor},"")},deleteToLineEnd(e){let t=DM(e.buffer,e.cursor);return t===e.cursor?e:io(e,{start:e.cursor,end:t},"")},moveLeft(e){return Hn(e,sg(e.buffer,e.cursor))},moveRight(e){return Hn(e,ko(e.buffer,e.cursor))},moveHome(e){return Hn(e,0)},moveEnd(e){return Hn(e,e.buffer.length)},moveLineStart(e){return Hn(e,$M(e.buffer,e.cursor))},moveLineEnd(e){return Hn(e,DM(e.buffer,e.cursor))},moveWordBackward(e){return Hn(e,MM(e.buffer,e.cursor))},moveWordForward(e){return Hn(e,OM(e.buffer,e.cursor))},moveUpLine(e,t,n){let r=t||80,{row:o,col:s}=so(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=so(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=Hn(e,l);return u===e?{moved:!1}:{moved:!0,state:u}},moveDownLine(e,t,n){let r=t||80,{row:o,col:s}=so(e.buffer,e.cursor,n,r),i=so(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=so(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=Hn(e,c);return d===e?{moved:!1}:{moved:!0,state:d}}};var FM=["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 tw(){return FM[Math.floor(Math.random()*FM.length)]}Tt();J();var R5=[{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 C5(){let e=[];for(let t of ct())t.hint&&(t.name.includes(":")||e.push({id:`cmd:${t.name}`,text:`${t.name} \u2014 ${t.hint}`,source:"command"}));return e}function A5(e){let t=[];for(let n of En()){let r=`cmd:/${n}`;if(e.has(r))continue;let o;try{o=Ge(n)}catch{continue}an(o,v.AFK_INTERNAL==="1")&&o.whenToUse&&t.push({id:`skill:${n}`,text:`/${n} \u2014 ${o.whenToUse}`,source:"skill"})}return t}function BM(){if(v.AFK_SPINNER_TIPS==="0")return[];let e=C5(),t=new Set(e.map(r=>r.id)),n=A5(t);return[...R5,...e,...n]}var LM=new Set,NM=new Map;function UM(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=NM.get(i);if(a)return a;let l=null,c=e.filter(u=>!LM.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&&(LM.add(l.id),NM.set(i,l)),l}var nw=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],_5=2e3;function jM(e){let t=Date.now()-e;if(t<_5)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 nt(e,t){return`\x1B[${e};1H\x1B[2K${t??""}`}function HM(e,t){let n=" \u{1F4A1} Tip: ",r=Math.max(8,t-Y(n)-1),o=Y(e)>r?oe(e,Math.max(0,r-1),"")+"\u2026":e;return f.dim(n+o)}var Yp=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:tw(),nextVerbRotateAt:r+n,startedAt:r,tipPool:BM(),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(`${nw[this.state.frameIndex]} ${this.state.verb}...`)+jM(this.state.startedAt):null}renderTipRow(t){return this.state?.currentTip?HM(this.state.currentTip.text,t):null}tick(t){if(!this.state)return;this.state.frameIndex=(this.state.frameIndex+1)%nw.length;let n=Date.now();n>=this.state.nextVerbRotateAt&&(this.state.verb=tw(),this.state.nextVerbRotateAt=n+t),this.state.currentTip=UM(this.state.tipPool,{startedAt:this.state.startedAt,now:n}),this.onTick()}};var Xp=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 P5}from"node:crypto";var I5=5,M5=1e3,O5=/\[Pasted text #([0-9a-f]+) \+\d+ (?:lines|chars)\]/g;function $5(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 Zp(e,t){return e.pasteRegistry.size===0?t:t.replace(O5,(n,r)=>e.pasteRegistry.get(r)??n)}function WM(e){return{text:Zp(e,e.input.buffer),queued:e.queued}}function KM(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<I5&&a<M5)return;let l=P5(4).toString("hex");e.pasteRegistry.set(l,o);let c=$5(l,o);e.input=q.replaceRange(e.input,{start:t,end:n},c)}function rw(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=q.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=q.replaceRange(e.input,{start:r,end:s},"");return e.pasteRegistry.delete(i),a}import{readdirSync as F5,statSync as L5}from"fs";import{join as N5}from"path";import{join as qM}from"path";import{homedir as D5}from"os";function Qp(e,t){let n=e?.shift===!0||t==="\x1B[13;2u",r=e?.meta===!0;return n||r}function Hi(e){return e.endsWith("\\")}var zM=50;function em(e,t,n=D5()){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?qM(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?qM(t,o):t,a=o?`${o}/`:"";return{scanDir:i,leafPrefix:s,displayPrefix:a}}async function JM(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(Hi(o)){t+=o.slice(0,-1)+`
|
|
1824
1824
|
`,n=r;continue}return t+=o,t}}function Hl(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=ct().find(c=>c.name===`/${i}`);if(l?.flags&&l.flags.length>0)return{kind:"flag",command:i,query:a}}return null}function tm(e){let t=ct(),n=t.filter(s=>s.name.slice(1).startsWith(e)).map(s=>({value:s.name,summary:s.summary,...s.hint?{hint:s.hint}:{}})),r=Bi().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 nm(e,t=process.cwd(),n){let{scanDir:r,leafPrefix:o,displayPrefix:s}=em(e,t,n);try{return F5(r).filter(a=>a.startsWith(o)).filter(a=>!(a.startsWith(".")&&!o.startsWith("."))).sort().slice(0,zM).map(a=>{let l=s+a;try{L5(N5(r,a)).isDirectory()&&(l+="/")}catch{}return{value:"@"+l}})}catch{return[]}}function Wl(e,t){let n=ct().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)}it();J();var B5=3,U5=250,j5=1500,H5=500;function VM(){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 YM(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(`
|
|
1825
|
-
`)}function Wi(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 XM(e,t){let n=t.trim();return n.startsWith(e)&&n.length>e.length}function QM(e={}){let t=e.debounceMs??U5,n=e.timeoutMs??j5,r=null,o=null,s=null,i=new Map,a=e.resolveProviderFn??Zd,l=new Map;function c(h,b){let y=se(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>=H5&&!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 k of S)if(k.startsWith(h)&&k.length>h.length)return k;let w=/\s+\/([A-Za-z][A-Za-z0-9_:-]*)$/.exec(h);if(w){let T="/"+w[1],R=ct().map(_=>_.name),A=Bi().map(_=>_.alias),O=[...R,...A].filter(_=>_.startsWith(T)).sort((_,I)=>_.localeCompare(I))[0];if(O){let _=h.length-T.length;return h.slice(0,_)+O}}return null}async function p(h,b){let y=d(h,b);if(y!==null)return y;if(!b.llmEnabled()||h.length<B5)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),k=new Promise(T=>{S.signal.aborted?T(null):S.signal.addEventListener("abort",()=>T(null),{once:!0})});try{let T=null,R=!1;if(e.completeFn){let A=await Promise.race([e.completeFn({system:VM(),user:YM(h,b),model:ZM(b),maxTokens:24,signal:S.signal,apiKey:b.apiKey,baseUrl:b.baseUrl}).then(E=>({ok:!0,raw:E})),k.then(()=>({ok:!1}))]);if(A.ok){R=!0;let E=Wi(A.raw).trim();T=XM(h,E)?E:null}}else{let A=ZM(b),E=b.baseUrl?{openaiBaseUrl:b.baseUrl}:void 0,O=c(A,E);if(typeof O.complete!="function"){u(h,null),y(null);return}let _=await Promise.race([O.complete({system:VM(),user:YM(h,b),model:A,maxTokens:24,signal:S.signal,apiKey:b.apiKey,baseUrl:b.baseUrl}).then(I=>({ok:!0,raw:I})),k.then(()=>({ok:!1}))]);if(_.ok){R=!0;let I=Wi(_.raw).trim();T=XM(h,I)?I:null}}R&&u(h,T),y(T)}catch(T){e.onError?.(T),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 ZM(e){let t=v.AFK_SUGGEST_MODEL;if(t)return t;let n=se(e.model);return n==="anthropic-direct"||n==="anthropic"?v.AFK_COMPACT_MODEL??"haiku":e.model}var ts=6;function rm(e){let t=e.autocompleteState;if(!t)return;t.trigger=Hl(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=tm(t.trigger.query).slice(0,12):t.trigger.kind==="file"?t.candidates=nm(t.trigger.query):t.candidates=Wl(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+ts&&(t.viewportStart=t.selectedIndex-ts+1)}function e0(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 t0(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=q.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,rm(e),e.repaint(),!0)}function n0(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+Wi(t.slice(e.input.buffer.length)),o=q.seed(r);return e.input=o,e.activeGhost=null,rm(e),e.repaint(),!0}import K5 from"chalk";import G5 from"string-width";function r0(e,t){if(t<=0)return"";let n=0;for(let r=0;r<e.length;r++)if(n+=G5(e[r]),n>t)return e.slice(0,r)+f.dim("\u2026");return e}function om(e,t,n,r){let o=t?">":" ",s=e.value,i=e.summary?` ${e.summary}`:"",a=`${s}${i}`,l=r0(a,n-4),c=` ${o} ${l}`;return t?K5.inverse(f.user(c)):f.meta(c)}function sm(e,t){if(!e)return null;let n=e.trim();if(n.length===0)return null;let r=r0(n,Math.max(0,t-7));return r.length===0?null:f.dim(` \u21B3 ${r}`)}function o0(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=ko(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=Wi(g.slice(e.input.buffer.length)),b=e.stdout.columns??80,y=Y(
|
|
1825
|
+
`)}function Wi(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 XM(e,t){let n=t.trim();return n.startsWith(e)&&n.length>e.length}function QM(e={}){let t=e.debounceMs??U5,n=e.timeoutMs??j5,r=null,o=null,s=null,i=new Map,a=e.resolveProviderFn??Zd,l=new Map;function c(h,b){let y=se(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>=H5&&!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 k of S)if(k.startsWith(h)&&k.length>h.length)return k;let w=/\s+\/([A-Za-z][A-Za-z0-9_:-]*)$/.exec(h);if(w){let T="/"+w[1],R=ct().map(_=>_.name),A=Bi().map(_=>_.alias),O=[...R,...A].filter(_=>_.startsWith(T)).sort((_,I)=>_.localeCompare(I))[0];if(O){let _=h.length-T.length;return h.slice(0,_)+O}}return null}async function p(h,b){let y=d(h,b);if(y!==null)return y;if(!b.llmEnabled()||h.length<B5)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),k=new Promise(T=>{S.signal.aborted?T(null):S.signal.addEventListener("abort",()=>T(null),{once:!0})});try{let T=null,R=!1;if(e.completeFn){let A=await Promise.race([e.completeFn({system:VM(),user:YM(h,b),model:ZM(b),maxTokens:24,signal:S.signal,apiKey:b.apiKey,baseUrl:b.baseUrl}).then(E=>({ok:!0,raw:E})),k.then(()=>({ok:!1}))]);if(A.ok){R=!0;let E=Wi(A.raw).trim();T=XM(h,E)?E:null}}else{let A=ZM(b),E=b.baseUrl?{openaiBaseUrl:b.baseUrl}:void 0,O=c(A,E);if(typeof O.complete!="function"){u(h,null),y(null);return}let _=await Promise.race([O.complete({system:VM(),user:YM(h,b),model:A,maxTokens:24,signal:S.signal,apiKey:b.apiKey,baseUrl:b.baseUrl}).then(I=>({ok:!0,raw:I})),k.then(()=>({ok:!1}))]);if(_.ok){R=!0;let I=Wi(_.raw).trim();T=XM(h,I)?I:null}}R&&u(h,T),y(T)}catch(T){e.onError?.(T),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 ZM(e){let t=v.AFK_SUGGEST_MODEL;if(t)return t;let n=se(e.model);return n==="anthropic-direct"||n==="anthropic"?v.AFK_COMPACT_MODEL??"haiku":e.model}var ts=6;function rm(e){let t=e.autocompleteState;if(!t)return;t.trigger=Hl(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=tm(t.trigger.query).slice(0,12):t.trigger.kind==="file"?t.candidates=nm(t.trigger.query):t.candidates=Wl(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+ts&&(t.viewportStart=t.selectedIndex-ts+1)}function e0(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 t0(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=q.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,rm(e),e.repaint(),!0)}function n0(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+Wi(t.slice(e.input.buffer.length)),o=q.seed(r);return e.input=o,e.activeGhost=null,rm(e),e.repaint(),!0}import K5 from"chalk";import G5 from"string-width";function r0(e,t){if(t<=0)return"";let n=0;for(let r=0;r<e.length;r++)if(n+=G5(e[r]),n>t)return e.slice(0,r)+f.dim("\u2026");return e}function om(e,t,n,r){let o=t?">":" ",s=e.value,i=e.summary?` ${e.summary}`:"",a=`${s}${i}`,l=r0(a,n-4),c=` ${o} ${l}`;return t?K5.inverse(f.user(c)):f.meta(c)}function sm(e,t){if(!e)return null;let n=e.trim();if(n.length===0)return null;let r=r0(n,Math.max(0,t-7));return r.length===0?null:f.dim(` \u21B3 ${r}`)}function o0(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=ko(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=Wi(g.slice(e.input.buffer.length)),b=e.stdout.columns??80,y=Y(He(e.promptTextFn())),S=Y(He(r))+1,w=Math.max(0,b-y-S-1),k=oe(h,w,"");k.length>0&&(m=f.dim(k))}return e.promptTextFn()+l+d+c+m+n}function s0(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,ts),s=[];for(let i=0;i<o;i++){let a=t.viewportStart+i,l=t.candidates[a];if(!l)continue;let c=om(l,a===t.selectedIndex,r,t.trigger?.kind),u=Y(He(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 i0(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 sm(r.hint,o)??""}function a0(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&&h>0;return{fitsAboveFrame:p,room:m,overflowTargetBottom:g,maxBandModel:h,overflowPriorContiguous:b,overflowRun:y,overflowHasPending:S,useBandHold:w}}function ow(e,t){return e.length>t?e.slice(e.length-t):e}function l0(e,t){e.debugLog("commitAbove:enter",{textLen:t.length,anchorRow:e.anchorRow??null,committing:e.committing,topRow:e.logUpdate?.topRow??null});let n=I=>{e.scrollRegion?e.scrollRegion.withFullScrollRegion(I):I()};if(!e.armed||!e.logUpdate){n(()=>{e.stdout.write(t+`
|
|
1826
1826
|
`)});return}let r=Math.max(1,e.stdout.rows??24),o=t.endsWith(`
|
|
1827
1827
|
`)?t.slice(0,-1):t,s=Math.max(1,e.stdout.columns??80),i=o.split(`
|
|
1828
1828
|
`),a=!1;for(;i.length>1&&i[i.length-1]==="";)i.pop(),a=!0;let l=i.flatMap(I=>Xv(I,s).split(`
|
|
@@ -1858,10 +1858,10 @@ ${u}`}function Xb(e,t){let n=RM[t.status];e.out.line(` ${n} ${f.bold(t.jobId)}
|
|
|
1858
1858
|
`,s=h3(r,n,{trim:!1,hard:!0,wordWrap:!1}).split(`
|
|
1859
1859
|
`);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+=R0),this.previousLineCount>0)for(let y=0;y<this.previousLineCount;y++){let S=this.previousTopRow+y;b+=ql(S,1)+lw}for(let y=0;y<g;y++){let S=h+y;b+=ql(S,1)+lw+(m[y]??"")}if(b+=ql(h+g-1,1),a&&(b+=C0),this.stream.isTTY)try{this.stream.write(y3)}catch{}try{this.stream.write(b)}catch{try{this.stream.isTTY&&this.stream.write(A0)}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+=R0);for(let o=0;o<this.previousLineCount;o++){let s=this.previousTopRow+o;n+=ql(s,1)+lw}n+=ql(Math.max(1,(this.stream.rows??24)-1-t),1),r&&(n+=C0);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(A0)}catch{}}};var zl=null;function Jl(e){if(zl!==null)throw new Error(`stdin claim conflict: '${zl.name}' already holds the claim, '${e}' cannot acquire it concurrently.`);let t=!1,n={release(){t||(t=!0,zl?.handle===n&&(zl=null))}};return zl={name:e,handle:n},n}async function _0(e,t){let n=Jl(e);try{return await t()}finally{n.release()}}function P0(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 I0(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 M0(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 am(e.stdout)),e.stdinClaim=Jl("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(),Vo(e.stdin),e.handleKeypress=(t,n)=>{let r=e.pasting?!1:e.caretBlinkController.resetVisible(),o=e.repaintCount;T0(e,t,n),r&&e.repaintCount===o&&e.repaint()},e.stdin.on("keypress",e.handleKeypress),e.armed=!0,e.canceled=!1,e.resizeUnsub=Ke.subscribe(()=>{e.armed&&e.repaint()}),e.resizeImmediateUnsub=Ke.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 O0(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),b3(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 b3(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)=>nt(o+d,u)).join("");e.stdout.write(`${c}\x1B[${r};1H${`
|
|
1860
1860
|
`.repeat(l.length)}`)}};try{e.scrollRegion?e.scrollRegion.withFullScrollRegion(s):s()}catch{}}function $0(e){e.overlay="",e.input=q.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 qi=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=q.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:""}
|
|
1861
|
-
`)}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 Yp({captureMode:t.captureMode??!1,onTick:()=>this.repaint()}),this.caretBlinkController=new Xp({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(){P0(this)}resumeInput(){I0(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){f0(this,t)}exitPickerMode(){g0(this)}repaintPicker(){h0(this)}setInputMode(t){y0(this,t)}getInputMode(){return b0(this)}async arm(){return M0(this)}disarm(){O0(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){l0(this,t)}clearCommittedBand(){Kl(this)}flushResizeGhostErase(){u0(this)}resetCommittedBand(){c0(this)}repositionCommittedBand(t,n,r){d0(this,t,n,r)}getBuffer(){return WM(this)}getPendingCount(){return this.pendingSubmissions.length}getAttachments(){return[...this.attachments]}get caretVisible(){return this.caretBlinkController.visible}renderInputLine(){return o0(this)}updateAutocomplete(){rm(this)}updateGhost(){e0(this)}renderDropdownRows(){return s0(this)}renderHintRow(){return i0(this)}repaint(){this.repaintCount++,m0(this)}clearScreen(){this.logUpdate?.resetGeometry?.(),this.stdout.write("\x1B[H\x1B[2J"),this.repaint()}resetState(){$0(this)}applyEdit(t){return E0(this,t)}applyDropdownSelection(){return t0(this)}applyGhostAccept(){return n0(this)}};import k3 from"chalk";var E3=/(?<=\s|^)(\/[A-Za-z][\w:-]*)(?=\s|$)/g,T3=/(?<=\s|^)(@[~\w./-]*)(?=\s|$)/g,x3=/\[Pasted text #[0-9a-f]+ \+\d+ (?:lines|chars)\]/g,D0={mint:f.mint};function R3(e){let t=D0[e];if(t)return t;let n=e.lastIndexOf(":");if(n>=0){let r=e.slice(n+1),o=D0[r];if(o)return o}return null}function ao(e,t){return k3.level===0?e:e.replace(E3,o=>{let s=o.slice(1);return t.has(s)?(R3(s)??f.brand)(o):f.meta(o)}).replace(T3,o=>f.fileRef(o)).replace(x3,o=>f.meta(o))}J();import{pathToFileURL as C3}from"node:url";var A3="\x1B]8;;\x1B\\",_3=new Set(["iterm2","wezterm","kitty","vscode","ghostty","windows-terminal","konsole","gnome-terminal","alacritty"]),P3=5e3;function I3(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=Ul(e);if(!_3.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<P3)return!1}return!0}var cw;function lm(){return cw===void 0&&(cw=I3()),cw}function M3(e,t){return`\x1B]8;;${t}\x1B\\${e}${A3}`}function cm(e,t){try{return M3(e,C3(t).href)}catch{return e}}var F0=/[\x00-\x1F\x7F-\x9F]/g;function mt(e){return je(e).replace(F0," ").replace(/ {2,}/g," ").trim()}function uw(e){return je(e).replace(F0," ")}function Vl(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+=L0(e.slice(r,i)),n+=s,r=i+s.length}return n+=L0(e.slice(r)),n}function L0(e){let t=lm();return e.replace(/\/(?:[^/\s,)]+\/){2,}([^/\s,)]+)/g,(n,r)=>t?cm(r,n):r)}function O3(e){let t=/^(\s*[("]?\s*)cd\s+\S+\s+&&\s+(?!cd\s)(.+)$/.exec(e);return t?(t[1]??"")+(t[2]??""):e}var N0=60;function dw(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=mt(i);if(a.length===0)continue;return`(${a.length>N0?oe(a,N0,"\u2026"):a})`}}return e}function B0(e,t){if(e==="bash"||e==="Bash")return O3(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"?dw(t,["id_prefix","prompt"]):e==="Task"?dw(t,["description","prompt"]):e==="skill"||e==="Skill"?dw(t,["name","arguments"]):e==="ask_question"?$3(t):t}function $3(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 D3(e){return e.replace(/[\r\n]+/g," ")}var F3={"(":")","{":"}","[":"]"};function U0(e,t,n="\u2026"){let r=e.charAt(0),o=F3[r];return!(o&&e.endsWith(o)&&e.length>=2)||Y(e)<=t?oe(e,t,n):t<3?t>=2?r+o:oe(e,t,n):oe(e,t-1,n)+o}function kr(e,t){let n=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/s.exec(e);if(n){let r=n[1],o=Vl(B0(r,n[2]??"")),s=On(r),{color:i,glyph:a}=Ai(r),l=uy(s),c=l?` [${l}]`:"";if(t!==void 0){let d=(a+" ").length+r.length+c.length,p=Math.max(1,t-d);o=U0(o,p)}o=D3(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)}J();var j0=8,um=30;function L3(){let e=v.AFK_DIFF_LINES;if(e===void 0)return um;let t=e.trim();if(!/^\d+$/.test(t))return um;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:um}function N3(){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 B3(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 U3=/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;function j3(e){let t=je(e.text).replace(U3,"");return e.kind==="+"?f.diffAdd("+ "+t):e.kind==="-"?f.diffRemove("- "+t):f.dim(" "+t)}var mw=new WeakMap;function Er(e,t,n){if(N3())return[];if(e.hunks.length===0)return[];let r=t==="overlay"?j0:L3(),o=t+"|"+n+"|"+r,s=mw.get(e);if(s!==void 0){let m=s.get(o);if(m!==void 0)return m}let i=[];i.push(n+B3(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:j3(h)})}if(r===0){for(let m of a)i.push(n+m.text);return pw(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 pw(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}`)),pw(e,o,i),i}function pw(e,t,n){let r=mw.get(e);r===void 0&&(r=new Map,mw.set(e,r)),r.set(t,n)}var H3=f.success("\u2713"),W3=f.error("\u2717");function lo(e){return e?W3:H3}var Yl=3,H0=2,W0=3;function K0(e){switch(On(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 K3(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 Tr(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=lm()?cm(a,e.persistedPath):a;return o(`saved \u2192 ${l}`)}if(e.lineCount!==void 0&&e.lineCount>1)return o(`${e.lineCount} ${K3(r,e.lineCount)}`);let i=e.content.length>n?e.content.slice(0,n-3)+"\u2026":e.content;return o(mt(i))}J();function Xl(e,t){if(e.length<=t)return e;let n=e.length-t,r=e.slice(0,n),o=e.slice(n),s=q0(r);return[{kind:"overflow",count:r.length,text:s},...o]}function G3(e,t){return t<=1||e.endsWith("s")||/(sh|ch|x|z)$/i.test(e)?e:e+"s"}var q3=5,G0=60;function q0(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=>Qe.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=mt(u);if(!d){i=!0;break}let p=d.length>G0?d.slice(0,G0-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,q3),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} ${G3(s,i)}`);return`\u2026 +${n} (${o.join(", ")})`}function dm(e,t=pn()){return e.map((n,r)=>({sibling:n,connector:r===e.length-1?t.lastConnector:t.midConnector}))}function fw(e,t){return t?[...e,{kind:"resultSummary",summary:t}]:e}function gw(e){if(e.length===0)return[];let t=new Map;for(let o of e){let s=z0(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=z0(o),i=t.get(s);i.length>=z3(o.toolName)?r.has(s)||(n.push({kind:"group",toolName:o.toolName,label:Qe.has(o.toolName)?o.toolInput:"",entries:i}),r.add(s)):n.push(o)}return n}function hw(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 kr(e.toolName+e.label)+f.dim(` \xD7${t} \u2014 ${s}`)}function z0(e){return Qe.has(e.toolName)?e.toolName+"::"+e.toolInput:e.toolName}function z3(e){return Qe.has(e)?H0:W0}function J0(e,t,n,r){return e>0||t?zi([...n,!0],r):zi(n,r)}function V0(e,t){return!Qe.has(e.toolName)||e.headerEmitted!==!0?!1:(t.get(e.toolUseId)??[]).every(r=>r.kind==="tool"&&V0(r,t))}function pm(e,t,n,r=ee(),o=[],s=pn(),i){let a=zi(o,s),l=Zl(a,s),c=e.filter(h=>h.kind==="text"),u=e.filter(h=>h.kind==="tool").filter(h=>!V0(h,t)),d=gw(u),p=Xl(d,Yl),m=dm(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($e(l+y+f.dim(h.text),r));else if(h.kind==="group")n.push($e(l+y+hw(h),r));else if(h.kind==="resultSummary")n.push($e(l+y+f.dim(h.summary),r));else{let w=h,k=t.get(w.toolUseId);if(Qe.has(w.toolName)&&k&&k.length>0){w.headerEmitted?n.push($e(l+y,r)):n.push($e(l+y+w.prefix,r));let T=i??S;if(pm(k,t,n,r,[...o,T],s,S),w.thinkingTail){let R=Zl(zi([...o,T],s),s);n.push($e(R+f.thinking("\u2307 "+mt(w.thinkingTail)),r))}}else if(!(Qe.has(w.toolName)&&w.headerEmitted))if(w.result){if(n.push($e(l+y+w.prefix+f.dim(" \u2014 ")+lo(w.result.isError)+" "+Tr(w.result,void 0,60,w.toolName),r)),w.diff&&!w.result.isError){let T=l+(S?s.spineClosed:f.dim(s.spine))+" ";for(let R of Er(w.diff,"overlay",T))n.push($e(R,r))}}else{n.push($e(l+y+w.prefix,r));let T=l+(S?s.spineClosed:f.dim(s.spine))+" ";w.thinkingTail?n.push($e(T+f.thinking("\u2307 "+mt(w.thinkingTail)),r)):n.push($e(T+f.dim(K0(w.toolName)),r))}}}let g=J0(u.length,!1,o,s);for(let h of c)for(let b of yw(h.text,g,s))n.push($e(b,r))}function Ql(e,t,n,r,o=ee(),s=[],i=pn(),a){let l=zi(s,i),c=Zl(l,i),u=[],d=e.filter(S=>S.kind==="text"),p=e.filter(S=>S.kind==="tool"),m=gw(p),g=Xl(m,Yl),h=fw(g,r),b=dm(h,i);for(let{sibling:S,connector:w}of b){let k=f.dim(w),T=w===i.lastConnector;if(S.kind==="overflow")u.push($e(c+k+f.dim(S.text),o));else if(S.kind==="resultSummary")u.push($e(c+k+f.dim(S.summary),o));else if(S.kind==="group")u.push($e(c+k+hw(S),o));else{let R=S,A=t.get(R.toolUseId);if(Qe.has(R.toolName)&&A&&A.length>0){if(R.headerEmitted){let O=R.toolInput?`${R.toolName} ${mt(R.toolInput)}`:R.toolName;u.push($e(c+k+f.dim("\u21B3 "+O),o))}else u.push($e(c+k+R.prefix,o));let E=a??T;u.push(...Ql(A,t,n,void 0,o,[...s,E],i,T))}else if(R.result){if(u.push($e(c+k+R.prefix+f.dim(" \u2014 ")+lo(R.result.isError)+" "+Tr(R.result,n,60,R.toolName),o)),R.diff&&!R.result.isError){let E=c+(T?i.spineClosed:f.dim(i.spine))+" ";for(let O of Er(R.diff,"flush",E))u.push($e(O,o))}}else u.push($e(c+k+R.prefix,o))}}let y=J0(p.length,r!=null,s,i);for(let S of d)for(let w of yw(S.text,y,i))u.push($e(w,o));return u}function ec(e,t,n,r,o=[]){let s=pn(),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>Yl&&(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=Ql(t,n,r,e.agentResultSummary,ee(),d,s);return[m,...g].join(`
|
|
1862
|
-
`)}function bw(e,t=[]){let n=pn(),r=f.dim(n.spine.repeat(t.length)),o=f.dim(n.turnRoot);return r+o+e.prefix}function tc(e,t,n,r,o=[]){let s=pn(),i=o;return Ql(t,n,r,e.agentResultSummary,ee(),i,s)}function Ji(e,t,n){let r=[],o=ee();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 ")+lo(a.result.isError)+" "+Tr(a.result,n,60,a.toolName)),a.diff&&!a.result.isError)for(let l of Er(a.diff,"flush"," "))r.push(
|
|
1861
|
+
`)}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 Yp({captureMode:t.captureMode??!1,onTick:()=>this.repaint()}),this.caretBlinkController=new Xp({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(){P0(this)}resumeInput(){I0(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){f0(this,t)}exitPickerMode(){g0(this)}repaintPicker(){h0(this)}setInputMode(t){y0(this,t)}getInputMode(){return b0(this)}async arm(){return M0(this)}disarm(){O0(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){l0(this,t)}clearCommittedBand(){Kl(this)}flushResizeGhostErase(){u0(this)}resetCommittedBand(){c0(this)}repositionCommittedBand(t,n,r){d0(this,t,n,r)}getBuffer(){return WM(this)}getPendingCount(){return this.pendingSubmissions.length}getAttachments(){return[...this.attachments]}get caretVisible(){return this.caretBlinkController.visible}renderInputLine(){return o0(this)}updateAutocomplete(){rm(this)}updateGhost(){e0(this)}renderDropdownRows(){return s0(this)}renderHintRow(){return i0(this)}repaint(){this.repaintCount++,m0(this)}clearScreen(){this.logUpdate?.resetGeometry?.(),this.stdout.write("\x1B[H\x1B[2J"),this.repaint()}resetState(){$0(this)}applyEdit(t){return E0(this,t)}applyDropdownSelection(){return t0(this)}applyGhostAccept(){return n0(this)}};import k3 from"chalk";var E3=/(?<=\s|^)(\/[A-Za-z][\w:-]*)(?=\s|$)/g,T3=/(?<=\s|^)(@[~\w./-]*)(?=\s|$)/g,x3=/\[Pasted text #[0-9a-f]+ \+\d+ (?:lines|chars)\]/g,D0={mint:f.mint};function R3(e){let t=D0[e];if(t)return t;let n=e.lastIndexOf(":");if(n>=0){let r=e.slice(n+1),o=D0[r];if(o)return o}return null}function ao(e,t){return k3.level===0?e:e.replace(E3,o=>{let s=o.slice(1);return t.has(s)?(R3(s)??f.brand)(o):f.meta(o)}).replace(T3,o=>f.fileRef(o)).replace(x3,o=>f.meta(o))}J();import{pathToFileURL as C3}from"node:url";var A3="\x1B]8;;\x1B\\",_3=new Set(["iterm2","wezterm","kitty","vscode","ghostty","windows-terminal","konsole","gnome-terminal","alacritty"]),P3=5e3;function I3(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=Ul(e);if(!_3.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<P3)return!1}return!0}var cw;function lm(){return cw===void 0&&(cw=I3()),cw}function M3(e,t){return`\x1B]8;;${t}\x1B\\${e}${A3}`}function cm(e,t){try{return M3(e,C3(t).href)}catch{return e}}var F0=/[\x00-\x1F\x7F-\x9F]/g;function mt(e){return He(e).replace(F0," ").replace(/ {2,}/g," ").trim()}function uw(e){return He(e).replace(F0," ")}function Vl(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+=L0(e.slice(r,i)),n+=s,r=i+s.length}return n+=L0(e.slice(r)),n}function L0(e){let t=lm();return e.replace(/\/(?:[^/\s,)]+\/){2,}([^/\s,)]+)/g,(n,r)=>t?cm(r,n):r)}function O3(e){let t=/^(\s*[("]?\s*)cd\s+\S+\s+&&\s+(?!cd\s)(.+)$/.exec(e);return t?(t[1]??"")+(t[2]??""):e}var N0=60;function dw(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=mt(i);if(a.length===0)continue;return`(${a.length>N0?oe(a,N0,"\u2026"):a})`}}return e}function B0(e,t){if(e==="bash"||e==="Bash")return O3(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"?dw(t,["id_prefix","prompt"]):e==="Task"?dw(t,["description","prompt"]):e==="skill"||e==="Skill"?dw(t,["name","arguments"]):e==="ask_question"?$3(t):t}function $3(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 D3(e){return e.replace(/[\r\n]+/g," ")}var F3={"(":")","{":"}","[":"]"};function U0(e,t,n="\u2026"){let r=e.charAt(0),o=F3[r];return!(o&&e.endsWith(o)&&e.length>=2)||Y(e)<=t?oe(e,t,n):t<3?t>=2?r+o:oe(e,t,n):oe(e,t-1,n)+o}function kr(e,t){let n=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/s.exec(e);if(n){let r=n[1],o=Vl(B0(r,n[2]??"")),s=On(r),{color:i,glyph:a}=Ai(r),l=uy(s),c=l?` [${l}]`:"";if(t!==void 0){let d=(a+" ").length+r.length+c.length,p=Math.max(1,t-d);o=U0(o,p)}o=D3(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)}J();var j0=8,um=30;function L3(){let e=v.AFK_DIFF_LINES;if(e===void 0)return um;let t=e.trim();if(!/^\d+$/.test(t))return um;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:um}function N3(){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 B3(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 U3=/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;function j3(e){let t=He(e.text).replace(U3,"");return e.kind==="+"?f.diffAdd("+ "+t):e.kind==="-"?f.diffRemove("- "+t):f.dim(" "+t)}var mw=new WeakMap;function Er(e,t,n){if(N3())return[];if(e.hunks.length===0)return[];let r=t==="overlay"?j0:L3(),o=t+"|"+n+"|"+r,s=mw.get(e);if(s!==void 0){let m=s.get(o);if(m!==void 0)return m}let i=[];i.push(n+B3(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:j3(h)})}if(r===0){for(let m of a)i.push(n+m.text);return pw(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 pw(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}`)),pw(e,o,i),i}function pw(e,t,n){let r=mw.get(e);r===void 0&&(r=new Map,mw.set(e,r)),r.set(t,n)}var H3=f.success("\u2713"),W3=f.error("\u2717");function lo(e){return e?W3:H3}var Yl=3,H0=2,W0=3;function K0(e){switch(On(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 K3(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 Tr(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=lm()?cm(a,e.persistedPath):a;return o(`saved \u2192 ${l}`)}if(e.lineCount!==void 0&&e.lineCount>1)return o(`${e.lineCount} ${K3(r,e.lineCount)}`);let i=e.content.length>n?e.content.slice(0,n-3)+"\u2026":e.content;return o(mt(i))}J();function Xl(e,t){if(e.length<=t)return e;let n=e.length-t,r=e.slice(0,n),o=e.slice(n),s=q0(r);return[{kind:"overflow",count:r.length,text:s},...o]}function G3(e,t){return t<=1||e.endsWith("s")||/(sh|ch|x|z)$/i.test(e)?e:e+"s"}var q3=5,G0=60;function q0(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=>Qe.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=mt(u);if(!d){i=!0;break}let p=d.length>G0?d.slice(0,G0-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,q3),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} ${G3(s,i)}`);return`\u2026 +${n} (${o.join(", ")})`}function dm(e,t=pn()){return e.map((n,r)=>({sibling:n,connector:r===e.length-1?t.lastConnector:t.midConnector}))}function fw(e,t){return t?[...e,{kind:"resultSummary",summary:t}]:e}function gw(e){if(e.length===0)return[];let t=new Map;for(let o of e){let s=z0(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=z0(o),i=t.get(s);i.length>=z3(o.toolName)?r.has(s)||(n.push({kind:"group",toolName:o.toolName,label:Qe.has(o.toolName)?o.toolInput:"",entries:i}),r.add(s)):n.push(o)}return n}function hw(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 kr(e.toolName+e.label)+f.dim(` \xD7${t} \u2014 ${s}`)}function z0(e){return Qe.has(e.toolName)?e.toolName+"::"+e.toolInput:e.toolName}function z3(e){return Qe.has(e)?H0:W0}function J0(e,t,n,r){return e>0||t?zi([...n,!0],r):zi(n,r)}function V0(e,t){return!Qe.has(e.toolName)||e.headerEmitted!==!0?!1:(t.get(e.toolUseId)??[]).every(r=>r.kind==="tool"&&V0(r,t))}function pm(e,t,n,r=ee(),o=[],s=pn(),i){let a=zi(o,s),l=Zl(a,s),c=e.filter(h=>h.kind==="text"),u=e.filter(h=>h.kind==="tool").filter(h=>!V0(h,t)),d=gw(u),p=Xl(d,Yl),m=dm(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(De(l+y+f.dim(h.text),r));else if(h.kind==="group")n.push(De(l+y+hw(h),r));else if(h.kind==="resultSummary")n.push(De(l+y+f.dim(h.summary),r));else{let w=h,k=t.get(w.toolUseId);if(Qe.has(w.toolName)&&k&&k.length>0){w.headerEmitted?n.push(De(l+y,r)):n.push(De(l+y+w.prefix,r));let T=i??S;if(pm(k,t,n,r,[...o,T],s,S),w.thinkingTail){let R=Zl(zi([...o,T],s),s);n.push(De(R+f.thinking("\u2307 "+mt(w.thinkingTail)),r))}}else if(!(Qe.has(w.toolName)&&w.headerEmitted))if(w.result){if(n.push(De(l+y+w.prefix+f.dim(" \u2014 ")+lo(w.result.isError)+" "+Tr(w.result,void 0,60,w.toolName),r)),w.diff&&!w.result.isError){let T=l+(S?s.spineClosed:f.dim(s.spine))+" ";for(let R of Er(w.diff,"overlay",T))n.push(De(R,r))}}else{n.push(De(l+y+w.prefix,r));let T=l+(S?s.spineClosed:f.dim(s.spine))+" ";w.thinkingTail?n.push(De(T+f.thinking("\u2307 "+mt(w.thinkingTail)),r)):n.push(De(T+f.dim(K0(w.toolName)),r))}}}let g=J0(u.length,!1,o,s);for(let h of c)for(let b of yw(h.text,g,s))n.push(De(b,r))}function Ql(e,t,n,r,o=ee(),s=[],i=pn(),a){let l=zi(s,i),c=Zl(l,i),u=[],d=e.filter(S=>S.kind==="text"),p=e.filter(S=>S.kind==="tool"),m=gw(p),g=Xl(m,Yl),h=fw(g,r),b=dm(h,i);for(let{sibling:S,connector:w}of b){let k=f.dim(w),T=w===i.lastConnector;if(S.kind==="overflow")u.push(De(c+k+f.dim(S.text),o));else if(S.kind==="resultSummary")u.push(De(c+k+f.dim(S.summary),o));else if(S.kind==="group")u.push(De(c+k+hw(S),o));else{let R=S,A=t.get(R.toolUseId);if(Qe.has(R.toolName)&&A&&A.length>0){if(R.headerEmitted){let O=R.toolInput?`${R.toolName} ${mt(R.toolInput)}`:R.toolName;u.push(De(c+k+f.dim("\u21B3 "+O),o))}else u.push(De(c+k+R.prefix,o));let E=a??T;u.push(...Ql(A,t,n,void 0,o,[...s,E],i,T))}else if(R.result){if(u.push(De(c+k+R.prefix+f.dim(" \u2014 ")+lo(R.result.isError)+" "+Tr(R.result,n,60,R.toolName),o)),R.diff&&!R.result.isError){let E=c+(T?i.spineClosed:f.dim(i.spine))+" ";for(let O of Er(R.diff,"flush",E))u.push(De(O,o))}}else u.push(De(c+k+R.prefix,o))}}let y=J0(p.length,r!=null,s,i);for(let S of d)for(let w of yw(S.text,y,i))u.push(De(w,o));return u}function ec(e,t,n,r,o=[]){let s=pn(),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>Yl&&(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=Ql(t,n,r,e.agentResultSummary,ee(),d,s);return[m,...g].join(`
|
|
1862
|
+
`)}function bw(e,t=[]){let n=pn(),r=f.dim(n.spine.repeat(t.length)),o=f.dim(n.turnRoot);return r+o+e.prefix}function tc(e,t,n,r,o=[]){let s=pn(),i=o;return Ql(t,n,r,e.agentResultSummary,ee(),i,s)}function Ji(e,t,n){let r=[],o=ee();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 ")+lo(a.result.isError)+" "+Tr(a.result,n,60,a.toolName)),a.diff&&!a.result.isError)for(let l of Er(a.diff,"flush"," "))r.push(De(l,o))}else r.push(" "+a.prefix)}else{r.push(Y0(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=mt(c.toolInput),d=Vl(u).trim()||u.trim();r.push(" "+f.dim(`\u2500\u2500 ${d} \u2500\u2500`))}for(let u of Er(c.diff,"flush"," "))r.push(De(u,o))}}}return r}function Y0(e,t,n){let{color:r,glyph:o}=Ai(e),s=t.map(u=>Vl(mt(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=>Tr(d.result,n,60,d.toolName));return" "+i+f.dim(" \u2014 ")+u.join(f.dim(", "))}return" "+i}function De(e,t){return oe(e,t)}var ww=Object.freeze({spine:"\u2502 ",spineClosed:" ",lead:" ",turnRoot:"\u25C9 ",midConnector:"\u251C\u2500 ",lastConnector:"\u2570\u2500 ",textPrefix:"\u2502 "}),J3=Object.freeze({spine:"| ",spineClosed:" ",lead:" ",turnRoot:"o ",midConnector:"+- ",lastConnector:"\\- ",textPrefix:"| "}),$Me=ww.midConnector,DMe=ww.lastConnector;function pn(){let e=v.AGENT_AFK_ASCII;return e&&/^(1|true|yes)$/i.test(e)?J3:ww}function zi(e,t){let n="";for(let r of e)n+=r?t.spineClosed:t.spine;return n+=t.spine,n}function Zl(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 yw(e,t,n){if(!e||!e.trim())return[];let r=f.dim(n.textPrefix),o=Math.max(1,ee()-t.length-2-2),s=Zl(t,n),i=[];for(let a of e.split(`
|
|
1863
1863
|
`)){let l=uw(a),c=ce(l,o);for(let u of c.split(`
|
|
1864
|
-
`))i.push(s+r+u)}return i}var X0=6,nc=class{entries=new Map;order=[];agentIdStack=[];addStart(t,n,r){let o=
|
|
1864
|
+
`))i.push(s+r+u)}return i}var X0=6,nc=class{entries=new Map;order=[];agentIdStack=[];addStart(t,n,r){let o=He(r),s=kr(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),qr.has(n)&&this.agentIdStack.push(t)}addStartWithAgentContext(t,n,r,o,s){let i=He(r),a=this.entries.get(t);if(a?.kind==="tool"){a.toolInput=i,a.prefix=kr(n+i,s),o!==void 0&&(a.agentContext=o);return}let l=kr(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"||!qr.has(o.toolName)||o.toolName==="Agent")return!1;let i=`(${He(n)})`;return o.toolName="Agent",o.toolInput=i,o.prefix=kr("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"&&ll.has(r.toolName))return n}}getOverlay(){let t=this.buildChildMap(),n=[],r=pn(),o=ee(),s=d=>oe(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>X0){let d=i.filter(h=>!h.result),p=i.filter(h=>h.result),m=Math.max(0,X0-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=>Qe.has(d.toolName))?f.dim(r.turnRoot):" ";for(let d of a){let p=t.get(d.toolUseId);if(Qe.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)),pm(p,t,n,o,void 0,r),d.thinkingTail&&n.push(s(f.dim(r.spine)+f.thinking("\u2307 "+mt(d.thinkingTail))));else if(!(Qe.has(d.toolName)&&d.headerEmitted))if(Qe.has(d.toolName))d.result?n.push(s(f.dim(r.turnRoot)+d.prefix+f.dim(" \u2014 ")+lo(d.result.isError)+" "+Tr(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 "+mt(d.thinkingTail))));else if(d.result){if(n.push(s(u+d.prefix+f.dim(" \u2014 ")+lo(d.result.isError)+" "+Tr(d.result,void 0,60,d.toolName))),d.diff&&!d.result.isError)for(let m of Er(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 "+mt(d.thinkingTail))))}return l>0&&n.push(s(" "+f.dim(`\u2026 +${l} done`))),n.join(`
|
|
1865
1865
|
`)}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(bw(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?tc(r,c,l,n,o).join(`
|
|
1866
1866
|
`):ec(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(Qe.has(u.toolName))if(o.push(...Ji(s,i,t)),s.clear(),i.length=0,u.headerEmitted){let p=tc(u,d??[],n,t,[]);o.push(...p)}else o.push(ec(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(...Ji(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(Qe.has(l.toolName))if(o.push(...Ji(s,i,t)),s.clear(),i.length=0,l.headerEmitted){let u=tc(l,c??[],n,t,[]);o.push(...u)}else o.push(ec(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(...Ji(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}};Pe();function Sw(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 Vi=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&&qe()&&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 Sw(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 vw="__main__";function Q0(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 rc(e,t){return{type:"tool_result",toolUseId:"synthetic",content:e,isError:t}}function eO(e){let t=["Done"],n=[];e.stats.toolUses&&n.push(`${e.stats.toolUses} tool${e.stats.toolUses===1?"":"s"}`),e.stats.tokens&&n.push(`${ae(e.stats.tokens)} tok`);let r=e.responseMetadata?.durationMs,o=Date.now()-e.startedAt;typeof r=="number"&&(n.push(he(r)),o>r*1.5&&o-r>=1e3&&n.push(`${he(o)} wall`)),n.length===0&&o>0&&n.push(he(o));let s=e.thinkingLane?.inlineSummary();return s&&n.push(s),n.length>0&&t.push(`(${n.join(" \xB7 ")})`),t.join(" ")}function Ew(e){let t=Math.max(1,ee()-2);return Math.max(1,t-e)}function tO(e,t){return V3(e)?Xn(e,{maxWidth:t}):ce(e,t)}function nO(e,t,n){if(!n||!e.trim())return"";let r;return kw(e)?r=`
|
|
1867
1867
|
\u258D streaming code\u2026
|
|
@@ -1939,8 +1939,8 @@ ${t}`}var QO=!1;function e$(){QO||(QO=!0,Hw("review",zO),VO())}J();var NX=new Se
|
|
|
1939
1939
|
`)},setCompositor(o){n=o}}}var qm=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}};wy();var zm=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=g7(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 g7(e){return e?e.input_tokens+e.output_tokens+e.cache_creation_input_tokens+e.cache_read_input_tokens:0}ze();fl();my();Pe();Qc();var h7="claude-haiku-4-5",y7=15e3,b7=1e3,w7=80,S7=200,v7=3e3,k7='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 E7(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 Jm=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??h7,this.intervalMs=t.intervalMs??y7,this.maxInputTokens=t.maxInputTokens??b7,this.maxOutputTokens=t.maxOutputTokens??w7,this.maxCallsPerSession=t.maxCallsPerSession??S7,this.tickIntervalMs=Math.max(1e3,Math.floor(this.intervalMs/10)),t.callLLM!==void 0?this.callLLM=t.callLLM:this.callLLM=(n,r)=>Us({token:this.apiKey,model:this.model,system:k7,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)*v7%this.intervalMs,a=this.intervalMs-1e3-i,l=this.lastRefreshedAt.get(o.jobId)??0;if(!(t-l<a)){if(this.callsThisSession>=this.maxCallsPerSession){W(`[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:
|
|
1940
1940
|
<transcript>
|
|
1941
1941
|
${E7(i)}
|
|
1942
|
-
</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(W(`[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--}}};gl();Vr();Wo();it();function N$(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}}fr();ur();J();
|
|
1943
|
-
`)},pendingCount:()=>pt.pendingCount(),suspendInput:()=>Hf.current?.suspendForElicitation(),resumeInput:()=>Hf.current?.resumeAfterElicitation()})),ke.requestResume
|
|
1942
|
+
</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(W(`[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--}}};gl();Vr();Wo();it();function N$(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}}fr();ur();J();Ne();function rS(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 ic(e,t,n){let r=n instanceof Error?n.message:String(n);e.fn(f.warning(`\u26A0 [resume-swap] ${t}: ${rS(r)}`))}async function B$(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: ${rS(a)}`}}let r;if(!await n.waitForInitialization().then(()=>!0,i=>(r=rS(i instanceof Error?i.message:String(i)),!1))){await n.close().catch(a=>{ic(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=>{ic(t.completionWriter,"cancelAll failed",i)}),await t.sessionRef.current.close().catch(i=>{ic(t.completionWriter,"session close failed",i)}),t.sessionRef.current=n,e.stored?(Np(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){ic(t.completionWriter,"onSwapped callback threw",i)}t.contextSampler.attach(n),await Mm(n).catch(i=>{ic(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(lt(t.stats.totalCostUsd)),t.stats.totalTokens>0&&s.push(ae(t.stats.totalTokens)+" tokens"),t.completionWriter.fn(f.brand(s.join(" \xB7 "))),Bp(t.stats,t.completionWriter),t.statusLine.repaint(jn(t.stats,t.contextSampler,t.gitStatusSampler)),{ok:!0,sessionId:n.sessionId??t.stats.sessionId??e.resumeId}}function U$(e){return new xt(mr({model:e.model,surface:"cli",apiKey:Je(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 H$(e,t){let n=Date.now(),r=Mi(e),o=Oi(r),s=r?.stored?.model??e.model,i=Bs(s);if(i)throw new Error(i);let a,l,c;a=Qr(e.thinking)??gi(),l=eo(e.effort)??hi(),c=bi(e.maxOutputTokens)??wl();let{prompt:u,source:d}=fi(),p=It(),m=p.autoRouting?.interactive??!0,g=cp(u,m,"repl",wP()),h={current:null},b=Ae(),y=new re({apiKey:b,...p.baseUrl!==void 0?{baseUrl:p.baseUrl}:{},...t?.cwd!==void 0?{cwd:t.cwd}:{}}),S=r?.stored?.sessionId,w=ro(S?{sessionLabel:S}:{});Oe(w?.writer,{phase:"bootstrap_start"});let k=new Td(w?{traceWriter:w.writer}:{});TM(k);let R=p.bgSummaries===!0&&b?new Jm({registry:k,apiKey:b,maxCallsPerSession:p.maxSummaryCallsPerSession??200}):void 0;R?.start(),xM(R);let A=ci(p.openaiBaseUrl!==void 0?{openaiBaseUrl:p.openaiBaseUrl}:{}),E={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}},O=ui(s,b,A,p.baseUrl,w?.writer,k,t?.cwd,Je,"cli"),_=new Dn({subagentManager:y,parentSession:E,surface:"cli",defaultConfig:{apiKey:b,systemPrompt:u,...p.baseUrl!==void 0?{baseUrl:p.baseUrl}:{}},defaultSubagentModel:Qt(s),childProviderFactory:A,childSkillExecutorFactory:O,backgroundRegistry:k,resolveApiKeyForModel:Je,depth:0,...t?.cwd!==void 0?{cwd:t.cwd}:{}}),I=new Fn({parentSession:E,surface:"cli",defaultModel:s,defaultSubagentModel:Qt(s),apiKey:b,childProviderFactory:A,childSkillExecutorFactory:O,backgroundRegistry:k,...p.baseUrl!==void 0?{baseUrl:p.baseUrl}:{},resolveApiKeyForModel:Je,...w?.writer!==void 0?{traceWriter:w.writer}:{},...t?.cwd!==void 0?{cwd:t.cwd}:{}}),L=new to({parentSession:E,defaultModel:s,defaultSubagentModel:Qt(s),apiKey:b,resolveApiKeyForModel:Je,...p.baseUrl!==void 0?{baseUrl:p.baseUrl}:{},...t?.cwd!==void 0?{cwd:t.cwd}:{},systemPrompt:u??"",surface:"cli",depth:0}),N=new dt,F;{let Ee=t?.cwd??process.cwd(),nn=ln(Dt()).mcpConfigs.filter(Jn=>Jn.format==="json").map(Jn=>Jn.source),wn=zo({cwd:Ee,...nn.length>0?{importedMcpConfigs:nn}:{},...e.mcpConfig!==void 0?{cliOverride:e.mcpConfig}:{}}),xc=Object.values(wn.mcpServers).filter(Jn=>!Jn.disabled).length;if(xc>0){let Jn=wn.sources.length===1?wn.sources[0]:`${wn.sources.length} source(s)`;console.log(f.dim(` mcp: ${xc} server(s) from ${Jn??qo()}`));let XN=Date.now();Oe(w?.writer,{phase:"mcp_connect_start",metadata:{serverCount:xc}});try{F=await vr.fromConfig(wn.mcpServers,{warnings:wn.warnings,...w?.writer!==void 0?{traceWriter:w.writer}:{}})}finally{Oe(w?.writer,{phase:"mcp_connect_done",durationMs:Date.now()-XN,metadata:{serverCount:xc}})}}else if(wn.warnings.length>0)for(let Jn of wn.warnings)console.warn(`[mcp] ${Jn}`)}let U=F?.getMcpToolWireNames()??[],D=N$(Ee=>wi(e.provider,{subagentExecutor:_,skillExecutor:I,composeExecutor:L,memoryStore:N,model:Ee!==void 0?Ee:String(s),...p.openaiBaseUrl!==void 0?{openaiBaseUrl:p.openaiBaseUrl}:{},...F!==void 0?{mcpManager:F}:{}})??new tt({permissions:{allowedTools:lp(U)},subagentExecutor:_,skillExecutor:I,composeExecutor:L,memoryStore:N,surface:"cli",...F!==void 0?{mcpManager:F}:{}}),Ee=>e.provider??se(Ee!==void 0?Ee:String(s),p.openaiBaseUrl!==void 0?{openaiBaseUrl:p.openaiBaseUrl}:void 0)),C=D(String(s)),B=hp(s);r?.stored&&Np(B,r.stored,r.resumeId);let M=e.dangerouslySkipPermissions?"bypassPermissions":p.permissionMode;M!==void 0&&(B.permissionMode=M),B.cwd=t?.cwd??process.cwd(),w&&console.log(f.dim(` trace: ${w.tracePath}`));let j={fn:Ee=>console.log(Ee),idleFn:Ee=>console.log(Ee)},X=new Fp,ie=L$(process.stdout,{statusLine:X}),Z=Ci(Ee=>{j.fn(pp(Ee))},"cli",N,()=>B.permissionMode,Ri({cwd:t?.cwd}),{cwd:t?.cwd,...w?.writer!==void 0?{traceWriter:w.writer}:{}},()=>t?.cwd??process.cwd()),fe=Z.registry,V=Z.pathApprovalGrantRef,_e={model:s,resumeConfig:o,systemPrompt:g,systemPromptSource:d,thinking:a,effort:l,maxOutputTokens:c,...p.baseUrl!==void 0?{baseUrl:p.baseUrl}:{},providerFactory:D,hookRegistry:fe,traceWriter:w?.writer,cwd:t?.cwd,maxTurns:parseInt(e.maxTurns,10),autoResumeOnUsageLimit:p.autoResumeOnUsageLimit,...M!==void 0?{permissionMode:M}:{}};await ki();let Xe=U$(_e);h.current=Xe,y.setOnSubagentSucceeded((Ee,nn)=>{h.current?.recordSubagentCompletion(Ee,nn)});let ge=new qm,Re=Qi(j),Ie=new zm(Xe),Se=new Lp({cwd:B.cwd??process.cwd(),branchTtlMs:1e3}),ke={session:h,stats:B,out:Re,ui:{clearScreen:()=>{let Ee=ke.getCompositor?.();Ee?.setOverlay(""),Ee?.resetCommittedBand(),X.stop(),Ie.reset(),process.stdout.write("\x1B[3J\x1B[2J\x1B[H"),X.start(),X.repaint(jn(B,Ie,Se))},repaintStatusLine:()=>X.repaint(jn(B,Ie,Se))},ledger:ge,...F!==void 0?{mcpManager:F}:{}},$e=Ee=>(ge.clear(),B$(Ee,{sessionRef:h,stats:B,contextSampler:Ie,gitStatusSampler:Se,statusLine:X,backgroundRegistry:k,completionWriter:j,isInFlight:()=>_t.getInFlight?.()??!1,onSwapped:nn=>{_t.resumeTarget=nn,_t.clearVerdictLedger?.()},buildSession:nn=>U$({..._e,model:nn.stored?.model??_e.model,resumeConfig:Oi(nn),permissionMode:B.permissionMode})})),_t={session:h,memoryStore:N,stats:B,statusLine:X,contextSampler:Ie,gitStatusSampler:Se,completionWriter:j,replRenderer:ie,slashCtx:ke,rl:null,options:e,...r!==void 0?{resumeTarget:r}:{},teardownTrustedSkillEvents:void 0,backgroundRegistry:k,subagentControl:_,...R!==void 0?{bgSummarizer:R}:{},requestResume:$e,getInFlight:()=>!1,...F!==void 0?{mcpManager:F}:{},suggestApiKey:b,...p.openaiBaseUrl!==void 0?{suggestBaseUrl:p.openaiBaseUrl}:{},...p.interactive?.suggestGhost!==void 0?{suggestGhostConfig:p.interactive.suggestGhost}:{},hookRegistry:Z.registry},kv=Ee=>{j.fn(EO(Ee,{isTTY:process.stdout.isTTY,columns:process.stdout.columns}))},Ev=Ee=>{j.fn(kO(Ee,{isTTY:process.stdout.isTTY,columns:process.stdout.columns})),ge.record(Ee)};GR(kv),WR(Ev),_t.teardownTrustedSkillEvents=()=>{qR(kv),KR(Ev)},F$(),UC(C)?(RO(C),V.current=C,iP(C)):v.AFK_DISABLE_PATH_APPROVAL!=="1"&&console.warn("[path-approval] active provider does not implement GrantManager \u2014 path-approval elicitation and bash restricted-path checks will not fire.");let jf=j$.createInterface({input:process.stdin,output:process.stdout,terminal:!1});_t.rl=jf;let Hf={current:null};return _t.inputSurfaceRef=Hf,pt.install(Dp({readLine:Ee=>new Promise((nn,wn)=>{jf.question(Ee,nn),jf.once("close",()=>wn(new Error("readline closed")))}),writer:{line:(Ee="")=>process.stdout.write(Ee+`
|
|
1943
|
+
`)},pendingCount:()=>pt.pendingCount(),suspendInput:()=>Hf.current?.suspendForElicitation(),resumeInput:()=>Hf.current?.resumeAfterElicitation()})),ke.requestResume=$e,Oe(w?.writer,{phase:"bootstrap_done",durationMs:Date.now()-n}),_t}jr();K();import{promises as oS}from"node:fs";import*as K$ from"node:path";async function W$(e,t,n=!1){await oS.mkdir(e,{recursive:!0});let r=new Date().toISOString().replace(/[:.]/g,"-"),o=K$.join(e,`${r}.md`),s=n?" (continued)":"";return await oS.writeFile(o,`# Session \u2014 ${new Date().toISOString()}${s}
|
|
1944
1944
|
|
|
1945
1945
|
- model: ${t}
|
|
1946
1946
|
|
|
@@ -1988,18 +1988,18 @@ _ended: ${new Date().toISOString()}_
|
|
|
1988
1988
|
`);return}let s=[];try{let i=await J$(t,"utf8");for(let a of i.split(`
|
|
1989
1989
|
`)){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(ms=s.length,s.length<ac-1){let i=await sS(t,iS|aS|q$|lS,384);try{await i.writeFile(r)}finally{await i.close()}ms++}else{let i=s.slice(-(ac-1));i.push(n);let a=i.map(c=>JSON.stringify(c)).join(`
|
|
1990
1990
|
`)+`
|
|
1991
|
-
`,l=await sS(t,iS|aS|C7|lS,384);try{await l.writeFile(a)}finally{await l.close()}ms=ac}})}async function Y$(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 JM({rl:e.rl,promptFn:e.promptFn}),attachments:[]}}finally{t&&process.removeListener("SIGINT",t)}}import*as Ht from"ansi-escapes";import cS from"string-width";var M7="\x1B[?2004h",O7="\x1B[?2004l";function X$(e,t){let n=e.isRaw;e.setRawMode(!0),e.resume(),t.write(M7);let r=!1;return{restore(){if(!r){r=!0;try{t.write(O7)}catch{}try{e.setRawMode(n)}catch{}}}}}function Ym(){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 Z$(e){let t=process.stdin,n=process.stdout,r=e.compositor?.isArmed()??!1,o=r?{restore:()=>{}}:X$(t,n),s=r?null:Jl("reader.readWithAutocomplete"),i=e.statusLine?.getExtraRows()??0;Vo(t);let a=e.promptFn(),l=cS(
|
|
1991
|
+
`,l=await sS(t,iS|aS|C7|lS,384);try{await l.writeFile(a)}finally{await l.close()}ms=ac}})}async function Y$(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 JM({rl:e.rl,promptFn:e.promptFn}),attachments:[]}}finally{t&&process.removeListener("SIGINT",t)}}import*as Ht from"ansi-escapes";import cS from"string-width";var M7="\x1B[?2004h",O7="\x1B[?2004l";function X$(e,t){let n=e.isRaw;e.setRawMode(!0),e.resume(),t.write(M7);let r=!1;return{restore(){if(!r){r=!0;try{t.write(O7)}catch{}try{e.setRawMode(n)}catch{}}}}}function Ym(){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 Z$(e){let t=process.stdin,n=process.stdout,r=e.compositor?.isArmed()??!1,o=r?{restore:()=>{}}:X$(t,n),s=r?null:Jl("reader.readWithAutocomplete"),i=e.statusLine?.getExtraRows()??0;Vo(t);let a=e.promptFn(),l=cS(He(a)),c=null,u=null;try{return e.statusLine?.setExtraRows(i+1),await new Promise((d,p)=>{let m=q.seed(e.initialBuffer??""),g=e.autocompleteState??Ym();g.reset();let h=0,b=!1,y=!1,S=0,w=0,k=0,T=null,R=[],A=6,E=0,O=!1,_=8,I={has:B=>ct().some(M=>M.name===`/${B}`)},L=()=>{if((k>0||w>0)&&n.write(Ht.cursorUp(k+w)),n.write("\r"),n.write(Ht.eraseDown),R.length>0)n.write(Gl(R)+`
|
|
1992
1992
|
`),k=1;else if(T!==null){let fe=T;T=null,n.write(fe+`
|
|
1993
1993
|
`),k=1}else k=0;n.write(a+ao(m.buffer,I)),g.trigger=Hl(m.buffer,m.cursor);let B=`${m.cursor}:${m.buffer}`;g.suppressedSignature!==null&&g.suppressedSignature!==B&&(g.suppressedSignature=null),g.trigger&&g.suppressedSignature===null?(g.trigger.kind==="slash"?g.candidates=tm(g.trigger.query).slice(0,12):g.trigger.kind==="file"?g.candidates=nm(g.trigger.query):g.candidates=Wl(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+A&&(g.viewportStart=g.selectedIndex-A+1);let M=n.columns||80;if(h=0,g.dropdownOpen&&M>40){let fe=Math.min(M-4,60),V=Math.min(g.candidates.length-g.viewportStart,A);for(let ge=0;ge<V;ge++){let Re=g.viewportStart+ge,Ie=om(g.candidates[Re],Re===g.selectedIndex,fe,g.trigger?.kind);n.write(`
|
|
1994
|
-
`+Ie);let Se=cS(
|
|
1995
|
-
`+Xe);let ge=cS(
|
|
1994
|
+
`+Ie);let Se=cS(He(Ie));h+=Math.max(1,Math.ceil(Se/M))}let _e=Math.min(M-4,80),Xe=sm(g.candidates[g.selectedIndex]?.hint,_e);if(Xe!==null){n.write(`
|
|
1995
|
+
`+Xe);let ge=cS(He(Xe));h+=Math.max(1,Math.ceil(ge/M))}}let j=ew(m.buffer,l,M),{row:X,col:ie}=so(m.buffer,m.cursor,l,M),Z=Math.max(0,j-X+h);Z>0&&n.write(Ht.cursorUp(Z)),n.write("\r"),ie>0&&n.write(Ht.cursorForward(ie)),w=j},N=!1,F=()=>{O||(O=!0,setImmediate(()=>{O&&!N&&(O=!1,L())}))};L();let U=()=>{let B=g.candidates[g.selectedIndex];if(!B)return!1;let M=m.buffer.slice(0,m.cursor),j=m.buffer.slice(m.cursor),X,ie;if(g.trigger?.kind==="slash"){let Z=/\/[A-Za-z_-]*$/.exec(M);X=Z?M.length-Z[0].length:m.cursor,ie=B.value+(j.startsWith(" ")?"":" ")}else if(g.trigger?.kind==="flag"){let Z=/--[a-z0-9-]*$/.exec(M);X=Z?M.length-Z[0].length:m.cursor,ie=B.value+(j.startsWith(" ")?"":" ")}else{let Z=M.search(/[^\s]*$/);X=Z>=0?Z:m.cursor,ie=B.value}return m=q.replaceRange(m,{start:X,end:m.cursor},ie),g.dropdownOpen=!1,g.viewportStart=0,g.selectedIndex=0,L(),!0},H=()=>{(k>0||w>0)&&n.write(Ht.cursorUp(k+w)),n.write("\r"),n.write(Ht.eraseDown),h=0;let B=Qo({buffer:ao(m.buffer,I),promptText:a,isTTY:!!n.isTTY,attachmentSummary:Ki(R)}),M=()=>n.write(B+`
|
|
1996
1996
|
`);e.statusLine?.withFullScrollRegion?e.statusLine.withFullScrollRegion(M):M(),C(),d({text:m.buffer,attachments:[...R]}),w=0},D=B=>{w>0&&n.write(Ht.cursorUp(w)),h>0&&(n.write(Ht.eraseDown),h=0),n.write(`
|
|
1997
1997
|
`),C(),p(B),w=0},C=()=>{N=!0,c&&t.removeListener("keypress",c),u&&u(),c=null,u=null};c=(B,M)=>{let j=Date.now(),X=j-E<_;E=j;let ie=M?.sequence||"";if(ie==="\x1B[200~"){b=!0,S=m.buffer.length;return}if(ie==="\x1B[201~"){b=!1,m.buffer.length===S?y||(y=!0,os().then(V=>{V?(T=null,R.push(V)):T="[clipboard: no image found]",F()}).catch(()=>{}).finally(()=>{y=!1})):(L(),y||(y=!0,os().then(V=>{V&&(T=null,R.push(V),F())}).catch(()=>{}).finally(()=>{y=!1})));return}if(M?.ctrl&&M?.name==="c"){e.onSigint?e.onSigint():D(new Error("SIGINT"));return}if(M?.ctrl&&M?.name==="d"){m.buffer.length===0&&((k>0||w>0)&&n.write(Ht.cursorUp(k+w)),h>0&&(n.write(Ht.eraseDown),h=0),n.write(`
|
|
1998
1998
|
`),C(),d({text:"",attachments:[...R]}),w=0);return}if(M?.ctrl&&M?.name==="v"){y||(y=!0,os().then(V=>{V?(T=null,R.push(V)):T="[clipboard: no image found]",F()}).catch(()=>{}).finally(()=>{y=!1}));return}if(M?.name==="escape"){g.dropdownOpen&&(g.suppressedSignature=`${m.cursor}:${m.buffer}`,g.dropdownOpen=!1,g.candidates=[],L());return}if(M?.ctrl&&M?.name==="a"){let V=q.moveLineStart(m);V!==m&&(m=V,L());return}if(M?.ctrl&&M?.name==="e"){let V=q.moveLineEnd(m);V!==m&&(m=V,L());return}if(M?.ctrl&&M?.name==="b"){let V=q.moveLeft(m);V!==m&&(m=V,L());return}if(M?.ctrl&&M?.name==="f"){let V=q.moveRight(m);V!==m&&(m=V,L());return}if(M?.meta&&M?.name==="b"){let V=q.moveWordBackward(m);V!==m&&(m=V,L());return}if(M?.meta&&M?.name==="f"){let V=q.moveWordForward(m);V!==m&&(m=V,L());return}if(M?.ctrl&&M?.name==="w"){let V=q.deleteWordBackward(m);V!==m&&(m=V,e.history?.resetRecall(),L());return}if(M?.ctrl&&M?.name==="l"){w=0,k=0,n.write("\x1B[H\x1B[2J"),L();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),L());return}let V=n.columns||80,_e=q.moveUpLine(m,V,l);if(_e.moved)m=_e.state,e.history?.resetRecall(),L();else if(e.history){let Xe=e.history.back(m.buffer);Xe!==null&&(m=q.seed(Xe),L())}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+A&&(g.viewportStart=g.selectedIndex-A+1),L());return}let V=n.columns||80,_e=q.moveDownLine(m,V,l);if(_e.moved)m=_e.state,e.history?.resetRecall(),L();else if(e.history){let Xe=e.history.forward();Xe!==null&&(m=q.seed(Xe),L())}return}if(M?.name==="left"){let V=q.moveLeft(m);V!==m&&(m=V,L());return}if(M?.name==="right"){let V=q.moveRight(m);V!==m&&(m=V,L());return}if(M?.name==="home"){let V=q.moveHome(m);V!==m&&(m=V,L());return}if(M?.name==="end"){let V=q.moveEnd(m);V!==m&&(m=V,L());return}if(M?.ctrl&&M?.name==="u"){let V=q.deleteToLineStart(m);V!==m&&(m=V,e.history?.resetRecall(),L());return}if(M?.ctrl&&M?.name==="k"){let V=q.deleteToLineEnd(m);V!==m&&(m=V,e.history?.resetRecall(),L());return}if(M?.ctrl&&M?.name==="x"){R.length>0&&(R.pop(),L());return}if(M?.name==="backspace"){if(M?.meta){let _e=q.deleteWordBackward(m);_e!==m&&(m=_e,e.history?.resetRecall(),L());return}let V=q.backspace(m);V!==m?(m=V,e.history?.resetRecall(),L()):R.length>0&&(R.pop(),L());return}if(M?.name==="delete"){if(M?.meta){let _e=q.deleteWordForward(m);_e!==m&&(m=_e,e.history?.resetRecall(),L());return}let V=q.deleteForward(m);V!==m&&(m=V,e.history?.resetRecall(),L());return}if(M?.name==="return"){if(Qp(M,ie)){m=q.insert(m,`
|
|
1999
1999
|
`),e.history?.resetRecall(),L();return}if(b){m=q.insert(m,`
|
|
2000
2000
|
`);return}if(X){m=q.insert(m,`
|
|
2001
2001
|
`),F();return}if(g.dropdownOpen){let V=g.trigger?.kind,_e=U();V==="slash"&&_e&&H()}else Hi(m.buffer)?(m=q.replaceRange(m,{start:m.buffer.length-1,end:m.buffer.length},`
|
|
2002
|
-
`),L()):H();return}if(M?.shift&&M?.name==="tab"||M?.sequence==="\x1B[Z"){e.onShiftTab?.();return}if(M?.name==="tab"){if(g.dropdownOpen)U();else{let V=m.buffer.slice(0,m.cursor),_e=/\s+\/([A-Za-z][A-Za-z0-9_:-]*)$/.exec(V);if(_e){let ge="/"+_e[1],Ie=[...ct().map(Se=>Se.name),...Bi().map(Se=>Se.alias)].filter(Se=>Se.startsWith(ge)).sort((Se,ke)=>Se.localeCompare(ke))[0];if(Ie){let Se=m.buffer.slice(m.cursor),ke=m.cursor-ge.length
|
|
2002
|
+
`),L()):H();return}if(M?.shift&&M?.name==="tab"||M?.sequence==="\x1B[Z"){e.onShiftTab?.();return}if(M?.name==="tab"){if(g.dropdownOpen)U();else{let V=m.buffer.slice(0,m.cursor),_e=/\s+\/([A-Za-z][A-Za-z0-9_:-]*)$/.exec(V);if(_e){let ge="/"+_e[1],Ie=[...ct().map(Se=>Se.name),...Bi().map(Se=>Se.alias)].filter(Se=>Se.startsWith(ge)).sort((Se,ke)=>Se.localeCompare(ke))[0];if(Ie){let Se=m.buffer.slice(m.cursor),ke=m.cursor-ge.length,$e=Ie+(Se.startsWith(" ")?"":" ");m=q.replaceRange(m,{start:ke,end:m.cursor},$e),L()}}}return}let Z=!M?.ctrl&&!M?.meta,fe=Z&&typeof B=="string"&&Gi(B)?B:Z&&typeof M?.sequence=="string"&&Gi(M.sequence)?M.sequence:null;fe!==null&&(m=q.insert(m,fe),e.history?.resetRecall(),b||(X?F():L()))},u=Ke.subscribe(()=>{w=0,k=0,h=0,L()}),t.on("keypress",c)})}finally{e.statusLine?.setExtraRows(i),o.restore(),s?.release()}}async function Q$(e){return!process.stdout.isTTY||!process.stdin.isTTY?Y$(e):Z$(e)}var Xm=class{history;autocompleteState;rl;statusLine;compositor=null;armedStdout=null;backgroundHandler=null;softStopHandler=null;pauseInterruptHandler=null;pendingReadReject=null;slashRegistryView={has:t=>ct().some(n=>n.name===`/${t}`)};constructor(t){this.rl=t.rl,this.history=t.history,this.statusLine=t.statusLine,this.autocompleteState=Ym()}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 qi({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=>ao(s,this.slashRegistryView),caretBlink:xI()&&!Pp(),captureMode:_p(),...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=Qo({buffer:ao(l,this.slashRegistryView),promptText:t.promptFn(),isTTY:!!a.isTTY,attachmentSummary:Ki([...i.attachments])});mn(n,c.split(`
|
|
2003
2003
|
`)),r({text:i.text,attachments:[...i.attachments]})};n.setOnSubmit(s),n.setInputMode("idle"),n.repaint()})}return Q$({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}}};J();jr();var $7="\u25B8",D7=" ",F7="\u25C9",L7="\u25EF",N7="\u2191/\u2193 navigate \xB7 enter select \xB7 esc cancel",B7="\u2191/\u2193 navigate \xB7 space toggle \xB7 enter confirm \xB7 esc cancel";function Zm(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=U7(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,k=w?f.brand($7):D7,T;if(s){let R=c.has(y),A=R?f.success(F7):f.dim(L7),E=w&&!R?f.bold(S):S;T=` ${k} ${A} ${E}`}else{let R=w?f.bold(S):f.dim(S);T=` ${k} ${R}`}b.push(T)}return b.push(f.dim(" "+(s?B7:N7))),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 k=o[w];k!==void 0&&S.push(k)}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 U7(e,t,n){return n<t||e<t?t:e>n?n:e}var j7="enter to submit \xB7 esc to cancel",H7=">";function eD(e,t){return new Promise(n=>{let{header:r,initial:o="",help:s=j7,validate:i,signal:a}=t;if(a?.aborted){n(null);return}let l=q.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(W7(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=q.moveLeft(l),c=null,e.repaintPicker();return}if(y.name==="right"||y.ctrl&&y.name==="f"){l=q.moveRight(l),c=null,e.repaintPicker();return}if(y.name==="home"||y.ctrl&&y.name==="a"){l=q.moveHome(l),c=null,e.repaintPicker();return}if(y.name==="end"||y.ctrl&&y.name==="e"){l=q.moveEnd(l),c=null,e.repaintPicker();return}if(y.name==="backspace"){l=q.backspace(l),c=null,e.repaintPicker();return}if(y.name==="delete"){l=q.deleteForward(l),c=null,e.repaintPicker();return}if(y.ctrl&&y.name==="w"){l=q.deleteWordBackward(l),c=null,e.repaintPicker();return}if(y.ctrl&&y.name==="u"){l=q.deleteToLineStart(l),c=null,e.repaintPicker();return}if(y.ctrl&&y.name==="k"){l=q.deleteToLineEnd(l),c=null,e.repaintPicker();return}if(b!==void 0&&b.length>0&&!K7(b)){l=q.insert(l,b),c=null,e.repaintPicker();return}S&&(c=null,e.repaintPicker())}};e.enterPickerMode(h)})}function W7(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(H7)} ${r}${a}${i}`}function K7(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t<32||t===127}Pe();J();var uS=["default","plan","bypassPermissions"];function G7(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 Qm(e){let t=e.stats.permissionMode;if(t==="autonomous"){await Nl(e,!1);return}let n=uS.indexOf(t),r=uS[(n+1)%uS.length]??"default";try{await e.session.current.setPermissionMode(r),e.stats.permissionMode=r,e.ui.repaintStatusLine(),G7(e,r)}catch(o){e.out.error(`Could not switch permission mode: ${o instanceof Error?o.message:String(o)}`)}}function ra(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 tD(e,t,n,r,o,s,i){let a=QM({onError:p=>W("[afk suggest] Tier-2 completion failed:",p)});await t.armCompositor({promptFn:()=>ra(e.stats.permissionMode),onCancel:o,onShiftTab:()=>{Qm(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=Dp({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+`
|
|
2004
2004
|
`)}},pendingCount:()=>pt.pendingCount(),...l?{pickFromList:p=>Zm(l,p),readTextOverlay:p=>eD(l,p)}:{}});pt.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(jn(e.stats,e.contextSampler,e.gitStatusSampler))},e.slashCtx.transcript=r,e.slashCtx.stdinElicitationHandler=c,e.slashCtx.swapElicitationHandler=p=>pt.install(p??c),e.inputSurfaceRef&&(e.inputSurfaceRef.current=t),e.gitStatusSampler.setOnUpdate(()=>{e.statusLine.repaint(jn(e.stats,e.contextSampler,e.gitStatusSampler))}),e.gitStatusSampler.refresh(),{installSoftStop:d}}function nD(e={}){let t=e.load??Hp,n=e.onResize??(i=>Ke.subscribe(i)),r="",o,s=n(()=>{r=""});return{renderIfChanged(i){let a=i??"unbound",l=t(a),c=lM(l);return a===o&&c===r?[]:(o=a,r=c,c===""?[]:Wp(l))},invalidate(){r=""},dispose(){try{s()}catch{}}}}var dS={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 rD(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(T=>{let R=dS[T];return R.color(`${R.glyph} ${R.label}`)}),y=f.dim(` (${n.length} turn${n.length===1?"":"s"})`),S=g+b.join(h)+y,w=Math.max(20,ee()-2);if(Y(S)<=w)return S;let k=g+n.map(T=>dS[T].color(dS[T].glyph)).join(f.dim(" "))+y;return oe(k,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=Ke.subscribe(()=>d()),d())},stop(){s&&(s=!1,l!==null&&(l(),l=null),i>0&&(p(),i=0,a?.(0)),r=null)},repaint(){d()}}}var oD=["\u25D0","\u25D1","\u25D2","\u25D3"],ef=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=Ke.subscribe(()=>this.repaint()),this.resizeImmediateUnsub=Ke.subscribeImmediate(()=>this.resetGeometry()),this.spinnerInterval=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%oD.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(oD[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(he(a))),oe(" "+i.join(" "),n)}};import{spawn as q7}from"node:child_process";var z7=/\x1b(?:\[[0-9;]*[a-zA-Z]|[\]P^_X][^\x07\x1b]*(?:\x07|\x1b\\)|[@-OQ-WYZ\\])/g;function J7(){let e="";return{strip(t){let r=(e+t).replace(z7,""),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 sD(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 iD=12e4,aD=1e5;function pS(e){let t=Date.now(),n=e.timeoutMs??iD,r=e.maxBytes??aD,o=J7(),s;try{s=q7(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(T){let R=T instanceof Error?T.message:String(T);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: ${R}`})}}s.unref();let i,a=!1,l=new Promise(T=>{i=R=>{a||(a=!0,T(R))}}),c="",u="",d=0,p=0,m=!1,g=!1,h=!1;function b(T){let R=r-d;if(R>0){let A=T.length<=R?T:sD(T,R);d+=A.length,c+=A.toString("utf8"),T.length>R&&(m=!0)}else T.length>0&&(m=!0);if(p<r){let A=o.strip(T.toString("utf8")),E=Buffer.byteLength(A,"utf8"),O=r-p;if(E<=O)u+=A,p+=E;else{let _=Buffer.from(A,"utf8");u+=sD(_,O).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 k(){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",T=>{b(T);try{e.onChunk?.(T,"stdout")}catch{}k()}),s.stderr?.on("data",T=>{b(T);try{e.onChunk?.(T,"stderr")}catch{}k()}),s.on("error",T=>{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: ${T.message}`})}),s.on("close",(T,R)=>{if(clearTimeout(S),e.abort.removeEventListener("abort",w),!(g||a)){if(o.flush(),h){i({exitCode:T,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m,errorReason:"abort",errorMessage:"Command killed"});return}if(T!==null&&T!==0){i({exitCode:T,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m,errorReason:"nonzero-exit",errorMessage:`Command exited with code ${T}`});return}if(T===null){i({exitCode:null,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m,errorReason:"signal-killed",errorMessage:R?`Command killed by signal ${R}`:"Command killed by signal"});return}i({exitCode:T,durationMs:Date.now()-t,displayCaptured:c,modelCaptured:u,truncated:m})}}),{pid:s.pid,promise:l,kill:(T="SIGKILL")=>{if(!(s.pid===void 0||s.pid===0||s.killed)){h=!0;try{process.kill(-s.pid,T)}catch{}}}}}import{EventEmitter as V7}from"node:events";var lD=200,lc=class extends V7{jobs=new Map;handles=new Map;aborts=new Map;counter=0;start(t){let n=`sh-${++this.counter}`,r=new AbortController,o=pS({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=Y7(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<=lD))for(let[t,n]of this.jobs){if(this.jobs.size<=lD)break;n.status!=="running"&&this.jobs.delete(t)}}};function Y7(e){return e.errorReason===void 0?"completed":e.errorReason==="abort"?"killed":"failed"}function X7(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 Z7(e,t){let n=he(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 cD(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Q7(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="${he(n.durationMs)}"`),n.truncated&&o.push('truncated="true"'),r.push(`<bash-passthrough ${o.join(" ")}>`),r.push(`<command>${cD(e)}</command>`),r.push("<output>"),r.push(cD(n.modelCaptured)),r.push("</output>"),r.push("</bash-passthrough>"),r.join(`
|
|
2005
2005
|
`)}var tf=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 lc;pendingInjections=[];pendingNotifications=[];activeFgJobId=null;static MAX_PENDING_INJECTIONS=25;static MAX_PENDING_NOTIFICATIONS=50;async dispatch(t){let n=X7(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=>Q7(n.command,n.mode,n.result));return this.pendingInjections=[],t.join(`
|
|
@@ -2015,7 +2015,7 @@ _ended: ${new Date().toISOString()}_
|
|
|
2015
2015
|
${k}${S}
|
|
2016
2016
|
${w}
|
|
2017
2017
|
${k}`})}return{fileBlocks:a,warnings:l}}async function hD(e,t,n,r,o="summary",s,i){let a=p0(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,k=[],T=new Map,R=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,A=()=>{let N=r.subagentControl;N?.hasPromotableForeground()&&N.promoteActiveForeground().then(F=>{for(let U of F)(s??{fn:console.log}).fn(f.dim(` \u2192 subagent backgrounded as ${U.jobId}: ${U.label}`))}).catch(()=>{})},E=r.getCompositor?r.getCompositor():null,O=()=>new Zi({out:Qi(s),thinkingMode:o,...R?{activeSkillName:R}:{},onCancel:()=>{t.interrupt().catch(N=>{qe()&&console.error(" "+f.error("session.interrupt() failed:"),N)})},...r.subagentControl?{onBackground:A}:{},...i?.history?{history:i.history}:{},...i?.autocompleteState?{autocompleteState:i.autocompleteState}:{},...i?.promptText!==void 0?{promptText:i.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...E?{compositor:E}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),_=O(),I=async()=>{if(!p){p=!0;try{await _.dispose()}catch{}}},L=async()=>{await _.arm();let N=_.getCompositor();if(s&&N){let F=N;s.fn=U=>F.commitAbove(U)}r.setActiveCompositor?.(N),r.setInterruptNotifier?.(F=>_.setInterrupting(F)),r.rearmStatus?.()};try{E?E.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{h=!0,t.interrupt().catch(C=>{qe()&&console.error(" "+f.error("soft-stop session.interrupt() failed:"),C)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{b=!0,t.interrupt().catch(C=>{qe()&&console.error(" "+f.error("pause-interrupt session.interrupt() failed:"),C)})}),await L(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(A);let{fileBlocks:N,warnings:F}=gD(e.text,{rootDir:process.cwd()});for(let C of F)(s??{fn:console.log}).fn(f.dim(` @-file: ${C}`));let U=N.length>0||e.attachments.length>0?mD(e.text,e.attachments,void 0,N):e.text,H=t.sendMessageStream(U);if(await Hs((C,B)=>{_.process(C,B)},async()=>{for await(let C of H){if(h||b)break;if(C.type==="chunk"&&C.chunk.type==="content"?(l+=C.chunk.content,u=!0):C.type==="message"&&!u&&(l=C.message.content),C.type==="stream_retry"&&(l=l.slice(0,c)),C.type==="chunk"&&C.chunk.type==="tool_use_detail"){let B=C.chunk,M={toolName:B.toolName,toolUseId:B.toolUseId,input:B.toolInput,...B.toolInputRaw!==void 0&&{inputRaw:B.toolInputRaw}};T.set(B.toolUseId,M),k.push(M)}else if(C.type==="chunk"&&C.chunk.type==="tool_result"){let B=C.chunk;c=l.length;let M=T.get(B.toolUseId);if(M&&(M.result=B.content,M.isError=B.isError,T.delete(B.toolUseId)),r.onContextProgress){let j=Date.now();if(j-S>=w){S=j;try{let X=r.onContextProgress();X instanceof Promise&&await X}catch(X){qe()&&console.error(" "+f.error("onContextProgress (status refresh) failed:"),X)}}}}if(C.type==="paused"){if(r.setPausedState?.(!0),await I(),E&&C.autoResume===!0){let B=new AbortController;y.abort=B;let M=C.resetsAt?C.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",X="Switch model / provider (type /model after)",ie="Stop waiting",Z=[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."),""];Zm(E,{header:Z,options:[j,X,ie],signal:B.signal,initialIndex:0}).then(fe=>{if(y.abort=null,!fe)return;let V=fe[0];V===void 0||V===j||(b=!0,V===X&&(s??{fn:console.log}).fn(f.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(_e=>{qe()&&console.error(" "+f.error("picker pause-interrupt session.interrupt() failed:"),_e)}))}).catch(fe=>{qe()&&console.error(" "+f.error("picker promise rejected:"),fe)})}else(s??{fn:console.log}).fn(ik({reason:C.reason,...C.resetsAt!==void 0?{resetsAt:C.resetsAt}:{},...C.accountId!==void 0?{accountId:C.accountId}:{},...C.autoResume!==void 0?{autoResume:C.autoResume}:{}}));continue}if(C.type==="resumed"){r.setPausedState?.(!1),y.abort?.abort(),y.abort=null;let B=C.hotSwapped&&C.accountId?`\u25B6 Resumed on ${C.accountId}`:"\u25B6 Resumed";l="",c=0,u=!1,k.length=0,T.clear(),m=!1,g=void 0,d=!1,_=O(),p=!1,await L(),(s??{fn:console.log}).fn(f.success(B));continue}if(C.type==="error"){await I(),Os(_s(C.error)),d=!0;continue}_.process(C),C.type==="done"&&(m=!0,g=C.metadata)}}),await I(),h){let C=s?s.fn:console.log;C(f.warning("\u23F8 Stopped \u2014 work so far kept.")+f.dim(" Send a message to continue.")),C("")}if(b){let C=s?s.fn:console.log;C(f.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),C("")}if(m&&!h&&!b){Go(n,a,l,g,k),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),Ip(process.stdout);let C=M=>{s?s.fn(M):console.log(M)},B=dD(l);if(B){if(C(pD(B)),C(""),r.onTerminalState)try{r.onTerminalState(B)}catch{}if(n.permissionMode==="autonomous"){let M=B.kind==="done"&&Du().verifyDone===!0&&!NI(k);UI(B,void 0,{unverified:M})}}if(wZ(g,n,C),r.onAfterTurn){let M=r.onAfterTurn();M instanceof Promise&&await M.catch(()=>{})}}}catch(N){await I(),d||Os(_s(N))}finally{await I(),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 wZ(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(he(e.durationMs)),e.totalCostUsd!==void 0&&r.push(lt(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),s=Number(e.usage?.output_tokens??0);o+s>0&&r.push(ae(o+s)+" tok"),r.length>0&&n(f.dim(" \u25E6 "+r.join(" \xB7 ")));let i=Nb(t),a=Lt(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 ~${ae(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 ${ae(a)}`))}n("")}var SZ=5e3;async function vZ(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 yD(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=>{qe()&&(p=Up(y)),await Mm(e.session.current),qe()&&(m=d$())}).catch(()=>{});let g,h=!1,b=!1;for(;;){if(p&&(e.replRenderer.writeLine(p),e.replRenderer.writeLine(""),p=null),m.length>0){for(let E of m)e.replRenderer.writeLine(E);e.replRenderer.writeLine(""),m=[]}let y=d.drainNotifications();for(let{job:E,result:O}of y){let _=O.errorReason===void 0?"\u2713":"\u2717",I=O.errorReason==="abort"?"killed":O.errorReason==="timeout"?"timed out":O.errorReason==="signal-killed"?"killed by signal":`exit ${O.exitCode??0}`,L=Math.max(0,Math.round(O.durationMs/100)/10);e.replRenderer.writeLine(f.dim(` ${_} [${E.id}] ${I} \xB7 ${L}s \xB7 `)+E.command)}let S=l.renderIfChanged(e.stats.sessionId);if(S.length>0){for(let E of S)e.replRenderer.writeLine(E);e.replRenderer.writeLine("")}let w,k;if(g===void 0){let E=await e.session.current.takePendingPlanExitSeed();E!==void 0&&(g={text:E,attachments:[]})}if(g!==void 0){let E=g;g=void 0;let O=ra(e.stats.permissionMode),_=Qo({buffer:E.text,promptText:O,isTTY:!!process.stdout.isTTY,attachmentSummary:Ki([...E.attachments])});e.replRenderer.writeLine(_),w=E.text.trim(),k=E.attachments}else{let E=await o.readLine({promptFn:()=>ra(e.stats.permissionMode),onSigint:r,onShiftTab:()=>{Qm(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});w=E.text.trim(),k=E.attachments}if(!w&&k.length===0)continue;if(w.startsWith("!")){let E=/^(0|false|off|no)$/i.test(v.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!E&&(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 T=!1;if(w.startsWith("/")){let E=await PI(w,e.slashCtx,k);if(E.handled){if(E.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()),E.result!==null&&typeof E.result=="object"&&"kind"in E.result&&E.result.kind==="submit"){g={text:E.result.message,attachments:k??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}T=!0}a.push(w),await vZ(e,w);let R=w;if(T){let E=Lb(w);if(E){let O=E.name.replace(/^\//,"").split(":").pop()??"";if(O&&Ww(O)){let _={skillName:O,rawArgs:E.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},I=e.session.current.sessionId,L=ls(I),N=Date.now();W(`[afk trace] preflight.start commandName=${O}`);let F=!1,U=await as(_,{cwd:e.stats.cwd??process.cwd(),artifactDir:L},H=>{qe()&&e.replRenderer.writeLine(f.warning(`\u26A0 preflight(${O}) failed: `)+(H instanceof Error?H.message:String(H)))});F=U!==null,W(`[afk trace] preflight.end commandName=${O} durationMs=${Date.now()-N} success=${F}`),R=Gw(U?.manifestBlock,w)}}}let A=d.drainInjections();if(A.length>0&&(R=A+R),e.hookRegistry)try{let E={event:"UserPromptSubmit",prompt:R,sessionId:e.stats.sessionId},O=await e.hookRegistry.dispatch(E);O.injectContext&&(R=O.injectContext+R)}catch(E){if(E instanceof me){e.replRenderer.writeLine(f.warning("\u2298 Turn blocked by hook")+(E.reason?f.dim(`: ${Mo(E.reason)}`):"")),e.statusLine.rearm();continue}if(E instanceof Tn){e.replRenderer.writeLine(f.warning("\u2298 Turn blocked by hook")+f.dim(`: handler timed out after ${E.timeoutMs}ms`)),e.statusLine.rearm();continue}throw E}if(await hD({text:R,attachments:k},e.session.current,e.stats,{setInFlight(E){n.turnInFlight=E},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(E){await t.appendUser(E)},async onTurnComplete(E,O){if(await t.appendTurn(E,O),e.stats.sessionId)try{Nn(e.stats)}catch(_){b||(b=!0,e.replRenderer.writeLine(f.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(_ instanceof Error?_.message:String(_))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:E=>u?.push(E),setActiveCompositor:E=>{n.activeCompositor=E},setInterruptNotifier:E=>{n.notifyInterrupting=E},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:E=>o.setBackgroundHandler(E),setSoftStopHandler:s,setPausedState:E=>o.setPausedState(E),setPauseInterruptHandler:E=>o.setPauseInterruptHandler(E),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(jn(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:E=>c.repaint(E)}:{}},e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(ra(e.stats.permissionMode))),e.hookRegistry)try{await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId},void 0,SZ)}catch(E){if(E instanceof ut)throw E;E instanceof Tn?(W("[stop hook] handler timed out"),e.completionWriter.fn(f.dim(" [stop hook] timed out"))):E instanceof me?e.completionWriter.fn(f.dim(` [stop hook] blocked: ${Mo(E.reason??"no reason given")}`)):W("[stop hook] unexpected error: "+String(E))}}}function kZ(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 bD(e,t,n,r){let o=await V$(),s=new Xm({rl:e.rl,history:o,statusLine:e.statusLine}),i=kZ(v.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await tD(e,s,n,t,r,i,{getLoopStageBar:()=>a?.loopStageBar});a=uD(e,n),await yD(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)}}Ga();import{execFile as EZ}from"node:child_process";import{dirname as TZ,isAbsolute as xZ,resolve as RZ}from"node:path";import{promisify as CZ}from"node:util";var wD=CZ(EZ),AZ=3e3,_Z=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function PZ(){let t=(await wD("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=xZ(t)?t:RZ(process.cwd(),t);return TZ(n)}async function SD(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await PZ()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),AZ)});try{let o=Wn({execFile:wD,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=>_Z.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}Qc();Ga();import{promises as IZ}from"node:fs";import{dirname as MZ,join as ED}from"node:path";import{randomBytes as OZ}from"node:crypto";var $Z=["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(`
|
|
2018
|
-
`),vD=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,mS=30,DZ=1024,FZ=8e3,LZ="haiku";async function NZ(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=HZ(n,DZ),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??FZ),i=t.signal?WZ([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await Us({token:t.token,model:t.model??LZ,system:$Z,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=BZ(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=MZ(t.worktreePath);return await UZ(l,c)}function BZ(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(vD.test(t)&&t.length<=mS)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>mS)break;o=i}return vD.test(o)?o:null}async function UZ(e,t){if(!await jZ(ED(t,e)))return e;let n=OZ(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,mS-5)}-${n}`}async function jZ(e){try{return await IZ.access(e),!0}catch{return!1}}function HZ(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 WZ(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 TD(e){let t,n,r=ED(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await NZ(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=`${Iu(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return kD(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 kD(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 kD(e,t){e&&e.setCwd(t),KZ(t)}function KZ(e){try{process.chdir(e)}catch{}}Ve();Ft();K();import{spawn as RD}from"child_process";import{existsSync as CD,mkdirSync as VZ,readFileSync as AD,unlinkSync as xD,writeFileSync as YZ}from"fs";import{get as XZ}from"https";import{join as _D}from"path";import{readFileSync as GZ}from"fs";import{dirname as qZ,join as zZ}from"path";import{fileURLToPath as JZ}from"url";function Cr(){try{return"5.
|
|
2018
|
+
`),vD=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,mS=30,DZ=1024,FZ=8e3,LZ="haiku";async function NZ(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=HZ(n,DZ),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??FZ),i=t.signal?WZ([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await Us({token:t.token,model:t.model??LZ,system:$Z,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=BZ(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=MZ(t.worktreePath);return await UZ(l,c)}function BZ(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(vD.test(t)&&t.length<=mS)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>mS)break;o=i}return vD.test(o)?o:null}async function UZ(e,t){if(!await jZ(ED(t,e)))return e;let n=OZ(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,mS-5)}-${n}`}async function jZ(e){try{return await IZ.access(e),!0}catch{return!1}}function HZ(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 WZ(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 TD(e){let t,n,r=ED(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await NZ(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=`${Iu(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return kD(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 kD(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 kD(e,t){e&&e.setCwd(t),KZ(t)}function KZ(e){try{process.chdir(e)}catch{}}Ve();Ft();K();import{spawn as RD}from"child_process";import{existsSync as CD,mkdirSync as VZ,readFileSync as AD,unlinkSync as xD,writeFileSync as YZ}from"fs";import{get as XZ}from"https";import{join as _D}from"path";import{readFileSync as GZ}from"fs";import{dirname as qZ,join as zZ}from"path";import{fileURLToPath as JZ}from"url";function Cr(){try{return"5.14.0"}catch{}try{let e=qZ(JZ(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(GZ(zZ(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}J();var ZZ=64*1024,QZ=1440*60*1e3,eQ=3600*1e3,tQ="update-check.json",nQ="pending-update.json";function PD(){return _D(Ic(),tQ)}function cc(){return _D(Ic(),nQ)}function ID(){let e=Ic();CD(e)||VZ(e,{recursive:!0})}function rQ(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 oQ(){try{let e=AD(PD(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function sQ(){try{ID();let e=`
|
|
2019
2019
|
const https = require('https');
|
|
2020
2020
|
const fs = require('fs');
|
|
2021
2021
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|
|
@@ -2054,8 +2054,8 @@ Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
|
2054
2054
|
`)),console.log(` Model: ${f.info(o?s:s+" (default)")}`),console.log(` Provider: ${f.plan(i)}`),console.log(i==="anthropic"?` API Key: ${c?f.success("\u2713 Set (ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN)"):f.warning("\u26A0 Not set \u2014 subprocess will fall back to OAuth / keychain")}`:` API Key: ${c?f.success("\u2713 Set (OPENAI_API_KEY / CODEX_API_KEY)"):f.warning("\u26A0 Not set \u2014 falling back to `codex login` state")}`);let g=v.AFK_THINKING||"(unset \u2014 SDK default)";console.log(` Thinking: ${f.info(g)}`);let h=v.AFK_EFFORT||"(unset \u2014 SDK default)";console.log(` Effort: ${f.info(h)}`),console.log(` Permission Mode: ${m?f.warning(`${p} (bypass \u2014 path containment off)`):f.info(`${p} (path containment on)`)}`),console.log(f.meta(`
|
|
2055
2055
|
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=id(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=ad();console.log(JSON.stringify(s,null,2))}}catch(s){gs(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=od(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}
|
|
2056
2056
|
${Ur}.`))}catch(i){gs(i.message)}}),t.command("unset <key>").description("Remove an afk.config.json key").option("--json","Output JSON").action((r,o)=>{try{let s=sd(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){gs(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=ed(r);o.json?console.log(JSON.stringify(s)):console.log(`${s.key} [${s.class}]: ${s.persisted??f.meta("(unset)")}`)}else{let s=td({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){gs(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=ti(r),a=o;if(i==="secret")s.stdin?a=UD():a=await of(`${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=UD();else{gs(`${r} requires a value`);return}let l=Zu(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}
|
|
2057
|
-
${Ur}.`))}catch(i){gs(i.message)}}),n.command("unset <key>").description("Remove an afk.env var").option("--json","Output JSON").action((r,o)=>{try{let s=Qu(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){gs(s.message)}})}J();import HQ from"path";import WQ from"os";import{createServer as RQ}from"node:http";import{writeFileSync as CQ,unlinkSync as AQ,mkdirSync as _Q,readFileSync as PQ}from"node:fs";import{dirname as IQ,join as MQ}from"node:path";J();import{mkdirSync as wQ,appendFileSync as SQ}from"node:fs";import{dirname as vQ}from"node:path";import{execFile as kQ}from"node:child_process";import{promisify as EQ}from"node:util";import{randomUUID as TQ}from"node:crypto";import*as nF from"node-cron";var sf=class{_count=0;increment(){this._count++}decrement(){this._count>0&&this._count--}isIdle(){return this._count===0}count(){return this._count}};K();Ei();import{mkdirSync as oa,readdirSync as uc,readFileSync as SS,renameSync as bS,statSync as KD,unlinkSync as dc,writeFileSync as fQ}from"node:fs";import{randomBytes as wS}from"node:crypto";import{join as zn}from"node:path";function GD(e,t={},n=gt()){oa(n,{recursive:!0});let o=uc(n).filter(m=>m.endsWith(".json")).length+1,s=`q-${Date.now()}-${wS(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=zn(n,c),d=wS(4).toString("hex"),p=zn(n,`.tmp-${d}.json`);try{fQ(p,JSON.stringify(a),"utf-8"),bS(p,u)}catch(m){try{dc(p)}catch{}throw m}return a}var HD="poison";function qD(e=gt()){oa(e,{recursive:!0});let t=uc(e).filter(n=>n.endsWith(".json")&&!n.startsWith(".tmp-")).sort();for(let n of t){let r=zn(e,n),o;try{o=SS(r,"utf-8")}catch(i){WD(e,n,i);continue}let s;try{s=JSON.parse(o)}catch(i){WD(e,n,i);continue}return dc(r),s}return null}function WD(e,t,n){let r=Ye(t),o=n instanceof SyntaxError?"SyntaxError: invalid JSON":Ye(n instanceof Error?n.message:String(n)),s=zn(e,HD),i=zn(e,t);try{oa(s,{recursive:!0});let a=zn(s,t);try{bS(i,a)}catch{a=zn(s,`${Date.now()}-${wS(3).toString("hex")}-${t}`),bS(i,a)}console.error(`[daemon] pull-queue: quarantined malformed entry ${r} \u2192 ${HD}/ (${o})`)}catch(a){let l=Ye(a instanceof Error?a.message:String(a));console.error(`[daemon] pull-queue: failed to quarantine malformed entry ${r}; removing to unblock queue (${l})`);try{dc(i)}catch(c){let u=Ye(c instanceof Error?c.message:String(c));console.error(`[daemon] pull-queue: could not remove unquarantinable entry ${r}; will retry next tick (${u})`)}}}function vS(e=gt()){try{oa(e,{recursive:!0})}catch{return[]}let t=uc(e).filter(r=>r.endsWith(".json")&&!r.startsWith(".tmp-")).sort(),n=[];for(let r of t){let o=zn(e,r);try{n.push(JSON.parse(SS(o,"utf-8")))}catch(s){let i=Ye(r),a=s instanceof SyntaxError?"SyntaxError: invalid JSON":Ye(s instanceof Error?s.message:String(s));console.error(`[daemon] pull-queue: skipping unreadable entry ${i} in listPending (${a})`)}}return n}function zD(e=gt(),t){try{oa(e,{recursive:!0})}catch{return!1}let n=uc(e).filter(r=>r.endsWith(".json")&&!r.startsWith(".tmp-")).sort();for(let r of n){let o=zn(e,r);try{if(KD(o).isDirectory())continue}catch{continue}let s;try{s=JSON.parse(SS(o,"utf-8"))}catch{continue}if(s.id===t)return dc(o),!0}return!1}function JD(e=gt()){try{oa(e,{recursive:!0})}catch{return 0}let t=uc(e).filter(r=>r.endsWith(".json")&&!r.startsWith(".tmp-")).sort(),n=0;for(let r of t){let o=zn(e,r);try{if(KD(o).isDirectory())continue}catch{continue}try{dc(o),n+=1}catch(s){let i=Ye(r),a=Ye(s instanceof Error?s.message:String(s));console.error(`[daemon] pull-queue: failed to remove entry ${i} in clearPending (${a})`)}}return n}K();vb();dn();ur();K();Ei();function VD(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 YD,readFileSync as gQ,readdirSync as hQ}from"node:fs";var XD=360*60*1e3;function ZD(){return Ts()}function yQ(e,t){if(!YD(t))return null;let n;try{n=gQ(t,"utf-8")}catch{return null}let r=n.split(`
|
|
2058
|
-
`);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 bQ(e){if(!YD(e))return 0;try{return hQ(e,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(".md")).length}catch{return 0}}function QD(e){let t=yQ(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=bQ(e.briefsDir);return n>0?{fire:!1,skipReason:"briefs_pending",pendingBriefCount:n,...t!==null?{lastFiredAtMs:t}:{}}:{fire:!0,...t!==null?{lastFiredAtMs:t}:{}}}var eF=EQ(kQ);async function xQ(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 tF(e){return`${e.replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"task"}-${TQ()}`}var af=class{registry=new Map;options;defaultCooldownMs;briefsDir;now;idleDetector=new sf;pullPollTimer;isDequeuing=!1;queueDir;constructor(t={}){this.options=t,this.defaultCooldownMs=t.cooldownMs??XD,this.briefsDir=t.briefsDir??ZD(),this.now=t.now??Date.now,this.queueDir=t.queueDir??gt(),this.ensureTelemetrySink()}register(t){if(VD(t),this.registry.has(t.taskId))throw new Error(`task ${t.taskId} is already registered`);let n;(t.trigger==="cron"||t.trigger==="both")&&(n=nF.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=QD({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=qD(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=Ye(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:Ye(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=Ye(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:Ye(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 xQ(eF,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 Wn({execFile:eF,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:Ye(i instanceof Error?i.message:String(i))};return this.writeTelemetry(a,t),a}}async spawnSession(t){let n=tF(t),r=this.options.sessionConfig?.cwd??process.cwd(),o=ro({sessionLabel:tF(t)}),{registry:s,memoryStore:i}=Ci(void 0,"daemon",void 0,void 0,Ri({cwd:r}),{cwd:r,sessionId:n,...o?.writer!==void 0?{traceWriter:o.writer}:{}}),a,l=ln(Dt()).mcpConfigs.filter(p=>p.format==="json").map(p=>p.source),c=zo({cwd:r,...l.length>0?{importedMcpConfigs:l}:{}}),u=Object.values(c.mcpServers).filter(p=>!p.disabled).length;try{if(u>0)a=await vr.fromConfig(c.mcpServers,{warnings:c.warnings,...o?.writer!==void 0?{traceWriter:o.writer}:{}})
|
|
2057
|
+
${Ur}.`))}catch(i){gs(i.message)}}),n.command("unset <key>").description("Remove an afk.env var").option("--json","Output JSON").action((r,o)=>{try{let s=Qu(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){gs(s.message)}})}J();import HQ from"path";import WQ from"os";import{createServer as RQ}from"node:http";import{writeFileSync as CQ,unlinkSync as AQ,mkdirSync as _Q,readFileSync as PQ}from"node:fs";import{dirname as IQ,join as MQ}from"node:path";J();import{mkdirSync as wQ,appendFileSync as SQ}from"node:fs";import{dirname as vQ}from"node:path";import{execFile as kQ}from"node:child_process";import{promisify as EQ}from"node:util";import{randomUUID as TQ}from"node:crypto";import*as nF from"node-cron";var sf=class{_count=0;increment(){this._count++}decrement(){this._count>0&&this._count--}isIdle(){return this._count===0}count(){return this._count}};K();Ei();import{mkdirSync as oa,readdirSync as uc,readFileSync as SS,renameSync as bS,statSync as KD,unlinkSync as dc,writeFileSync as fQ}from"node:fs";import{randomBytes as wS}from"node:crypto";import{join as zn}from"node:path";function GD(e,t={},n=gt()){oa(n,{recursive:!0});let o=uc(n).filter(m=>m.endsWith(".json")).length+1,s=`q-${Date.now()}-${wS(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=zn(n,c),d=wS(4).toString("hex"),p=zn(n,`.tmp-${d}.json`);try{fQ(p,JSON.stringify(a),"utf-8"),bS(p,u)}catch(m){try{dc(p)}catch{}throw m}return a}var HD="poison";function qD(e=gt()){oa(e,{recursive:!0});let t=uc(e).filter(n=>n.endsWith(".json")&&!n.startsWith(".tmp-")).sort();for(let n of t){let r=zn(e,n),o;try{o=SS(r,"utf-8")}catch(i){WD(e,n,i);continue}let s;try{s=JSON.parse(o)}catch(i){WD(e,n,i);continue}return dc(r),s}return null}function WD(e,t,n){let r=Ye(t),o=n instanceof SyntaxError?"SyntaxError: invalid JSON":Ye(n instanceof Error?n.message:String(n)),s=zn(e,HD),i=zn(e,t);try{oa(s,{recursive:!0});let a=zn(s,t);try{bS(i,a)}catch{a=zn(s,`${Date.now()}-${wS(3).toString("hex")}-${t}`),bS(i,a)}console.error(`[daemon] pull-queue: quarantined malformed entry ${r} \u2192 ${HD}/ (${o})`)}catch(a){let l=Ye(a instanceof Error?a.message:String(a));console.error(`[daemon] pull-queue: failed to quarantine malformed entry ${r}; removing to unblock queue (${l})`);try{dc(i)}catch(c){let u=Ye(c instanceof Error?c.message:String(c));console.error(`[daemon] pull-queue: could not remove unquarantinable entry ${r}; will retry next tick (${u})`)}}}function vS(e=gt()){try{oa(e,{recursive:!0})}catch{return[]}let t=uc(e).filter(r=>r.endsWith(".json")&&!r.startsWith(".tmp-")).sort(),n=[];for(let r of t){let o=zn(e,r);try{n.push(JSON.parse(SS(o,"utf-8")))}catch(s){let i=Ye(r),a=s instanceof SyntaxError?"SyntaxError: invalid JSON":Ye(s instanceof Error?s.message:String(s));console.error(`[daemon] pull-queue: skipping unreadable entry ${i} in listPending (${a})`)}}return n}function zD(e=gt(),t){try{oa(e,{recursive:!0})}catch{return!1}let n=uc(e).filter(r=>r.endsWith(".json")&&!r.startsWith(".tmp-")).sort();for(let r of n){let o=zn(e,r);try{if(KD(o).isDirectory())continue}catch{continue}let s;try{s=JSON.parse(SS(o,"utf-8"))}catch{continue}if(s.id===t)return dc(o),!0}return!1}function JD(e=gt()){try{oa(e,{recursive:!0})}catch{return 0}let t=uc(e).filter(r=>r.endsWith(".json")&&!r.startsWith(".tmp-")).sort(),n=0;for(let r of t){let o=zn(e,r);try{if(KD(o).isDirectory())continue}catch{continue}try{dc(o),n+=1}catch(s){let i=Ye(r),a=Ye(s instanceof Error?s.message:String(s));console.error(`[daemon] pull-queue: failed to remove entry ${i} in clearPending (${a})`)}}return n}K();vb();dn();ur();Ne();K();Ei();function VD(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 YD,readFileSync as gQ,readdirSync as hQ}from"node:fs";var XD=360*60*1e3;function ZD(){return Ts()}function yQ(e,t){if(!YD(t))return null;let n;try{n=gQ(t,"utf-8")}catch{return null}let r=n.split(`
|
|
2058
|
+
`);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 bQ(e){if(!YD(e))return 0;try{return hQ(e,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(".md")).length}catch{return 0}}function QD(e){let t=yQ(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=bQ(e.briefsDir);return n>0?{fire:!1,skipReason:"briefs_pending",pendingBriefCount:n,...t!==null?{lastFiredAtMs:t}:{}}:{fire:!0,...t!==null?{lastFiredAtMs:t}:{}}}var eF=EQ(kQ);async function xQ(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 tF(e){return`${e.replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"task"}-${TQ()}`}var af=class{registry=new Map;options;defaultCooldownMs;briefsDir;now;idleDetector=new sf;pullPollTimer;isDequeuing=!1;queueDir;constructor(t={}){this.options=t,this.defaultCooldownMs=t.cooldownMs??XD,this.briefsDir=t.briefsDir??ZD(),this.now=t.now??Date.now,this.queueDir=t.queueDir??gt(),this.ensureTelemetrySink()}register(t){if(VD(t),this.registry.has(t.taskId))throw new Error(`task ${t.taskId} is already registered`);let n;(t.trigger==="cron"||t.trigger==="both")&&(n=nF.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=QD({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=qD(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=Ye(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:Ye(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=Ye(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:Ye(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 xQ(eF,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 Wn({execFile:eF,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:Ye(i instanceof Error?i.message:String(i))};return this.writeTelemetry(a,t),a}}async spawnSession(t){let n=tF(t),r=this.options.sessionConfig?.cwd??process.cwd(),o=ro({sessionLabel:tF(t)}),{registry:s,memoryStore:i}=Ci(void 0,"daemon",void 0,void 0,Ri({cwd:r}),{cwd:r,sessionId:n,...o?.writer!==void 0?{traceWriter:o.writer}:{}}),a,l=ln(Dt()).mcpConfigs.filter(p=>p.format==="json").map(p=>p.source),c=zo({cwd:r,...l.length>0?{importedMcpConfigs:l}:{}}),u=Object.values(c.mcpServers).filter(p=>!p.disabled).length;try{if(u>0){let p=Date.now();Oe(o?.writer,{phase:"mcp_connect_start",metadata:{serverCount:u}});try{a=await vr.fromConfig(c.mcpServers,{warnings:c.warnings,...o?.writer!==void 0?{traceWriter:o.writer}:{}})}finally{Oe(o?.writer,{phase:"mcp_connect_done",durationMs:Date.now()-p,metadata:{serverCount:u}})}}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 xt(mr(d)),memoryStore:i,...a!==void 0?{mcpManager:a}:{}}}catch(p){throw a&&await a.disconnectAll().catch(()=>{}),i.close(),p}}telemetryPath(){return this.options.telemetryPath??_r()}ensureTelemetrySink(){try{wQ(vQ(this.telemetryPath()),{recursive:!0})}catch{}}writeTelemetry(t,n,r){try{SQ(this.telemetryPath(),`${JSON.stringify(t)}
|
|
2059
2059
|
`,"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 OQ=7777,$Q="127.0.0.1";async function rF(e={}){let t=new af({...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=MQ(Dc("default"),"port"),o=RQ((a,l)=>FQ(a,l,t)),{port:s,address:i}=await NQ(o,e.port??OQ,e.host??$Q);if(n)try{_Q(IQ(r),{recursive:!0}),CQ(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{PQ(r,"utf-8").trim()===String(s)&&AQ(r)}catch{}await BQ(o)}}}function DQ(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 FQ(e,t,n){LQ(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 LQ(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 DQ(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 NQ(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 BQ(e){return new Promise((t,n)=>{e.close(r=>{r?n(r):t()})})}K();Nr();function oF(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 sF(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 iF(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 UQ="",kS="default";function fo(e){if(e!==void 0&&e.trim()!=="")return e}function aF(e,t,n){return fo(e)??fo(t)??fo(n)??UQ}function lF(e,t,n){return fo(e)??fo(t)??fo(n)??kS}var jQ="127.0.0.1";function cF(e,t){return fo(e)??fo(t)??jQ}function uF(e){let t=e.trim().toLowerCase();return t==="127.0.0.1"||t==="localhost"||t==="::1"}Ft();Ve();Ku();di();dn();ze();fl();gl();fr();Vr();Wo();nr();dn();or();function KQ(e){let t;return n=>{let r=new AbortController,o=jo(r.signal),s=new re({...e.apiKey!==void 0?{apiKey:e.apiKey}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.cwd!==void 0?{cwd:e.cwd}:{}}),i=ci(e.openaiBaseUrl!==void 0?{openaiBaseUrl:e.openaiBaseUrl}:{}),a=ui(e.model,e.apiKey,i,e.baseUrl,void 0,void 0,e.cwd,Je,"daemon"),l=new Dn({subagentManager:s,parentSession:o,surface:"daemon",defaultConfig:{...e.apiKey!==void 0?{apiKey:e.apiKey}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}},defaultSubagentModel:Qt(e.model),childProviderFactory:i,childSkillExecutorFactory:a,resolveApiKeyForModel:Je,depth:0,...e.cwd!==void 0?{cwd:e.cwd}:{}}),c=new Fn({parentSession:o,surface:"daemon",defaultModel:e.model,defaultSubagentModel:Qt(e.model),...e.apiKey!==void 0?{apiKey:e.apiKey}:{},childProviderFactory:i,childSkillExecutorFactory:a,resolveApiKeyForModel:Je,...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.cwd!==void 0?{cwd:e.cwd}:{}}),u=new to({parentSession:o,defaultModel:e.model,defaultSubagentModel:Qt(e.model),...e.apiKey!==void 0?{apiKey:e.apiKey}:{},resolveApiKeyForModel:Je,...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.cwd!==void 0?{cwd:e.cwd}:{},systemPrompt:"",surface:"daemon",depth:0});t??=new dt;let d=n.mcpManager,p=d?.getMcpToolWireNames()??[],m=wi(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 tt({permissions:{allowedTools:[...Rn,...Io,...Pt,"agent","skill","compose",...p]},subagentExecutor:l,skillExecutor:c,composeExecutor:u,memoryStore:t,surface:"daemon",...d!==void 0?{mcpManager:d}:{}});return new xt(mr({...n,provider:m,isNonInteractive:!0,surface:"daemon"}))}}function GQ(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(`
|
|
2060
2060
|
`)}function dF(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: ${kS})`).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)&&z(new Error(`Invalid port: ${t.port}`));let r=It(),o=aF(t.task,v.AFK_DAEMON_TASK,r.daemon?.task),s=lF(t.taskId,v.AFK_DAEMON_TASK_ID,r.daemon?.taskId),i=cF(t.host,v.AFK_DAEMON_HOST),a,l,c;try{a=oF(t.timeoutMs,v.AFK_TIMEOUT_MS),l=sF(t.sessionstartCooldownMs,v.AFK_SESSIONSTART_COOLDOWN_MS),c=iF(t.trigger,t.cron)}catch(_){z(_)}(c==="cron"||c==="both")&&!t.cron&&z(new Error(`--cron is required when --trigger is '${c}'.`)),(c==="cron"||c==="both")&&o.trim()===""&&z(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=Qr(t.thinking)??gi(),d=eo(t.effort)??hi()}catch(_){z(_)}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=Xt();for(let _ of y)_.enabled&&b.push(GT(_));if(t.dumpPrompt!==void 0&&t.dumpPrompt!==!1){let _=t.dumpPrompt===!0?HQ.join(WQ.homedir(),".afk","logs",`prompt-dump-${new Date().toISOString().replace(/[:.]/g,"-")}.json`):t.dumpPrompt;process.env.AFK_DUMP_PROMPT=_}let S=0,w=6e4,k=(_,I)=>{let L=Date.now();if(L-S<w)return;S=L;let N=I instanceof Error?`${I.name}: ${I.message}`:String(I);An(`\u{1F6D1} agent-afk daemon ${_}
|
|
2061
2061
|
${N.slice(0,500)}`).catch(F=>{console.error("[daemon] crash notification push failed:",F instanceof Error?F.message:String(F))})};process.on("uncaughtException",_=>{k("uncaughtException",_),process.exit(1)}),process.on("unhandledRejection",_=>{k("unhandledRejection",_),process.exit(1)});let T=v.AFK_DAEMON_CWD,R=Rt(),A=Ae(),E=T!==void 0&&T.length>0?T:void 0;await ki();let O=KQ({model:R,...A!==void 0?{apiKey:A}:{},...r.baseUrl!==void 0?{baseUrl:r.baseUrl}:{},...r.openaiBaseUrl!==void 0?{openaiBaseUrl:r.openaiBaseUrl}:{},...E!==void 0?{cwd:E}:{}});try{let _=await rF({port:n,host:i,...t.once?{writePortFile:!1}:{},sessionConfig:{model:R,...A!==void 0?{apiKey:A}:{},...r.baseUrl!==void 0?{baseUrl:r.baseUrl}:{},...a!==void 0?{timeoutMs:a}:{},...u!==void 0?{thinking:u}:{},...d!==void 0?{effort:d}:{},...E!==void 0?{cwd:E}:{}},sessionFactory:O,...l!==void 0?{cooldownMs:l}:{},...t.briefsDir!==void 0?{briefsDir:t.briefsDir}:{},...c==="pull"?{pullPollIntervalMs:3e4,queueDir:gt()}:{},tasks:b,onTaskComplete:(L,N)=>{An(GQ(L,N),{markdown:!0}).catch(()=>{})}});if(t.once){console.log(f.info(`\u25B6 Firing task '${s}' once...`));let L=await _.tickOnce(s);console.log(JSON.stringify(L,null,2)),await _.stop(),process.exit(L.status==="success"?0:1)}if(c==="sessionstart"||c==="both"){let L=await _.fireOnStart();for(let N of L){let F=N.status==="success"?"\u2714":N.status==="skipped"?"\u23ED":"\u2717";console.log(f.info(`${F} sessionstart: ${JSON.stringify(N)}`))}}console.log(f.success(`\u2714 Daemon listening on http://${_.host}:${_.port}`)),uF(_.host)||console.log(f.warning(`\u26A0 Control surface bound to ${_.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: ${gt()} 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 I=async()=>{console.log(f.dim(`
|
|
@@ -2165,21 +2165,21 @@ complete -c afk -n '__fish_seen_subcommand_from plugin' -a 'disable' -d 'Disable
|
|
|
2165
2165
|
# flags: --model, --format, --trigger
|
|
2166
2166
|
complete -c afk -l model -s m -x -a '${e}' -d 'Model to use'
|
|
2167
2167
|
complete -c afk -l format -s f -x -a '${t}' -d 'Output format'
|
|
2168
|
-
complete -c afk -l trigger -x -a '${n}' -d 'Trigger type'`}function xF(e){e.command("completion <shell>").description("Emit shell completion script (zsh|bash|fish)").action(t=>{let n=["zsh","bash","fish"];if(!n.includes(t)){e.error(`unknown shell: ${t}. Choose from: ${n.join(", ")}`);return}let r="";switch(t){case"zsh":r=vee();break;case"bash":r=kee();break;case"fish":r=Eee();break}console.log(r)})}import
|
|
2169
|
-
`);return r.length>0&&r[r.length-1]===""&&r.pop(),r.slice(-t)}catch{return[]}}function Pee(e){try{if(process.platform==="linux"){let t=`/proc/${e}/stat`;if(!aa(t))return{};let r=uf(t,"utf-8").split(" "),o=Number.parseInt(r[21]??"0",10),l=Ree("/proc/1").mtimeMs/1e3+o/100,c=Math.floor(Date.now()/1e3-l),d=uf(`/proc/${e}/status`,"utf-8").match(/VmRSS:\s+(\d+)\s+kB/),p=d?Math.round(Number.parseInt(d[1]??"0",10)/1024):void 0;return{uptimeSec:c,memoryMb:p}}if(process.platform==="darwin"){let t=Tee("ps",["-p",String(e),"-o","etime=,rss="],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim(),[n,r]=t.split(/\s+/);return{uptimeSec:Iee(n??""),memoryMb:r?Math.round(Number.parseInt(r,10)/1024):void 0}}}catch{}return{}}function Iee(e){if(!e)return;let t=e.split("-"),n=0,r=e;t.length===2&&(n=Number.parseInt(t[0]??"0",10),r=t[1]??"");let o=r.split(":").map(l=>Number.parseInt(l,10));if(o.some(l=>!Number.isFinite(l)))return;let s=0,i=0,a=0;if(o.length===3)[s,i,a]=o;else if(o.length===2)[i,a]=o;else if(o.length===1)[a]=o;else return;return n*86400+s*3600+i*60+a}Ju();K();J();import{existsSync as Mee,readFileSync as Oee}from"fs";import{createInterface as $ee}from"readline";import
|
|
2170
|
-
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1||o.slice(0,s).trim()!==t)continue;let a=o.slice(s+1).trim();return(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),a}}async function IF(e){let t=PF(e,"TELEGRAM_BOT_TOKEN");if(!t)return{set:!1,valid:!1,reason:"unset"};let n=await DS(t);return n?{set:!0,valid:!0,botId:n.id,...n.username!==void 0?{username:n.username}:{}}:{set:!0,valid:!1,reason:"unauthorized"}}async function MF(e,t={}){let n=PF(e,"TELEGRAM_BOT_TOKEN");if(!n)return{found:!1,chats:[],reason:"unset"};let r=t.timeoutSec??60,o=2e3,s=Math.max(1,Math.ceil(r*1e3/o)),i=await OF(n,{maxAttempts:s,intervalMs:o});return i.length===0?{found:!1,chats:[],reason:"timeout"}:{found:!0,chats:i}}async function DS(e){try{let t=await fetch(`${_F}/bot${e}/getMe`);if(!t.ok)return null;let n=await t.json();return!n.ok||!n.result?.id||!n.result?.first_name?null:{id:n.result.id,...n.result.username!==void 0?{username:n.result.username}:{},firstName:n.result.first_name}}catch{return null}}function Dee(e){let t=new Map;for(let n of e){let o=(n.message??n.edited_message)?.chat;!o||typeof o.id!="number"||t.set(o.id,{chatId:o.id,type:o.type??"unknown",...o.username!==void 0?{username:o.username}:{},...o.first_name!==void 0?{firstName:o.first_name}:{}})}return[...t.values()].reverse()}async function Fee(e){try{let t=await fetch(`${_F}/bot${e}/getUpdates`);if(!t.ok)return[];let n=await t.json();return!n.ok||!Array.isArray(n.result)?[]:n.result}catch{return[]}}async function OF(e,t={}){let n=t.maxAttempts??30,r=t.intervalMs??2e3;for(let o=0;o<n;o++){let s=await Fee(e),i=Dee(s);if(i.length>0)return i;o<n-1&&await new Promise(a=>setTimeout(a,r))}return[]}function AF(e){let t=$ee({input:process.stdin,output:process.stdout});return _0("telegram.setup-wizard",()=>new Promise(n=>{t.question(e,r=>{t.close(),n(r.trim())})}))}function Lee(e){return process.stdin.isTTY||(console.error(
|
|
2168
|
+
complete -c afk -l trigger -x -a '${n}' -d 'Trigger type'`}function xF(e){e.command("completion <shell>").description("Emit shell completion script (zsh|bash|fish)").action(t=>{let n=["zsh","bash","fish"];if(!n.includes(t)){e.error(`unknown shell: ${t}. Choose from: ${n.join(", ")}`);return}let r="";switch(t){case"zsh":r=vee();break;case"bash":r=kee();break;case"fish":r=Eee();break}console.log(r)})}import Fe from"chalk";import{spawn as Nee}from"child_process";import{existsSync as Bee,readFileSync as Uee}from"fs";K();import{execFileSync as Tee,spawn as xee}from"child_process";import{existsSync as aa,mkdirSync as RF,readFileSync as uf,statSync as Ree,unlinkSync as df,writeFileSync as Cee,openSync as CF}from"fs";import{join as ia,dirname as AS}from"path";import{fileURLToPath as Aee}from"url";var _ee=AS(Aee(import.meta.url));function PS(){let e=ia(Te(),"telegram");return{pidFile:ia(e,"bot.pid"),logFile:ia(Rs(),"telegram.log")}}function pc(e){if(!aa(e))return null;let t=uf(e,"utf-8").trim(),n=Number.parseInt(t,10);if(!Number.isFinite(n)||n<=0)return df(e),null;try{return process.kill(n,0),n}catch{return df(e),null}}function IS(e=_ee,t=aa){let n=[ia(e,"telegram.mjs"),ia(e,"..","telegram.js"),ia(e,"..","telegram.ts")];for(let r of n)if(t(r))return r;throw new Error(`Telegram entrypoint not found. Searched: ${n.join(", ")}`)}async function MS(){let{pidFile:e,logFile:t}=PS(),n=pc(e);if(n!==null)return{kind:"already-running",pid:n,message:`Bot already running (PID ${n}). Use 'afk telegram stop' first.`};RF(AS(e),{recursive:!0}),RF(AS(t),{recursive:!0});let r=IS(),o=CF(t,"a"),s=CF(t,"a"),i;try{i=xee(process.execPath,[r],{detached:!0,stdio:["ignore",o,s],env:process.env})}catch(a){return{kind:"spawn-failed",message:`Failed to spawn bot: ${a.message}`}}return i.pid===void 0?{kind:"spawn-failed",message:"Spawned child has no PID"}:(Cee(e,String(i.pid),{mode:420}),i.unref(),await new Promise(a=>setTimeout(a,1500)),pc(e)===null?{kind:"exited-immediately",logTail:_S(t,20),message:"Bot exited immediately after launch. Check the log for details."}:{kind:"started",pid:i.pid,logFile:t})}async function OS(){let{pidFile:e}=PS(),t=pc(e);if(t===null)return{kind:"not-running"};try{process.kill(t,"SIGTERM")}catch{return aa(e)&&df(e),{kind:"stopped",pid:t}}for(let n=0;n<50;n++)if(await new Promise(r=>setTimeout(r,100)),pc(e)===null)return{kind:"stopped",pid:t};try{process.kill(t,"SIGKILL")}catch{}return aa(e)&&df(e),{kind:"force-killed",pid:t}}function $S(){let{pidFile:e,logFile:t}=PS(),n=pc(e),r={running:n!==null,pidFile:e,logFile:t};if(n===null)return{...r,logTail:_S(t,10)};let o=Pee(n);return{...r,pid:n,...o,logTail:_S(t,10)}}function _S(e,t){if(!aa(e))return[];try{let r=uf(e,"utf-8").split(`
|
|
2169
|
+
`);return r.length>0&&r[r.length-1]===""&&r.pop(),r.slice(-t)}catch{return[]}}function Pee(e){try{if(process.platform==="linux"){let t=`/proc/${e}/stat`;if(!aa(t))return{};let r=uf(t,"utf-8").split(" "),o=Number.parseInt(r[21]??"0",10),l=Ree("/proc/1").mtimeMs/1e3+o/100,c=Math.floor(Date.now()/1e3-l),d=uf(`/proc/${e}/status`,"utf-8").match(/VmRSS:\s+(\d+)\s+kB/),p=d?Math.round(Number.parseInt(d[1]??"0",10)/1024):void 0;return{uptimeSec:c,memoryMb:p}}if(process.platform==="darwin"){let t=Tee("ps",["-p",String(e),"-o","etime=,rss="],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim(),[n,r]=t.split(/\s+/);return{uptimeSec:Iee(n??""),memoryMb:r?Math.round(Number.parseInt(r,10)/1024):void 0}}}catch{}return{}}function Iee(e){if(!e)return;let t=e.split("-"),n=0,r=e;t.length===2&&(n=Number.parseInt(t[0]??"0",10),r=t[1]??"");let o=r.split(":").map(l=>Number.parseInt(l,10));if(o.some(l=>!Number.isFinite(l)))return;let s=0,i=0,a=0;if(o.length===3)[s,i,a]=o;else if(o.length===2)[i,a]=o;else if(o.length===1)[a]=o;else return;return n*86400+s*3600+i*60+a}Ju();K();J();import{existsSync as Mee,readFileSync as Oee}from"fs";import{createInterface as $ee}from"readline";import je from"chalk";var _F="https://api.telegram.org";function PF(e,t){if(!Mee(e))return;let n=Oee(e,"utf-8");for(let r of n.split(`
|
|
2170
|
+
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1||o.slice(0,s).trim()!==t)continue;let a=o.slice(s+1).trim();return(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),a}}async function IF(e){let t=PF(e,"TELEGRAM_BOT_TOKEN");if(!t)return{set:!1,valid:!1,reason:"unset"};let n=await DS(t);return n?{set:!0,valid:!0,botId:n.id,...n.username!==void 0?{username:n.username}:{}}:{set:!0,valid:!1,reason:"unauthorized"}}async function MF(e,t={}){let n=PF(e,"TELEGRAM_BOT_TOKEN");if(!n)return{found:!1,chats:[],reason:"unset"};let r=t.timeoutSec??60,o=2e3,s=Math.max(1,Math.ceil(r*1e3/o)),i=await OF(n,{maxAttempts:s,intervalMs:o});return i.length===0?{found:!1,chats:[],reason:"timeout"}:{found:!0,chats:i}}async function DS(e){try{let t=await fetch(`${_F}/bot${e}/getMe`);if(!t.ok)return null;let n=await t.json();return!n.ok||!n.result?.id||!n.result?.first_name?null:{id:n.result.id,...n.result.username!==void 0?{username:n.result.username}:{},firstName:n.result.first_name}}catch{return null}}function Dee(e){let t=new Map;for(let n of e){let o=(n.message??n.edited_message)?.chat;!o||typeof o.id!="number"||t.set(o.id,{chatId:o.id,type:o.type??"unknown",...o.username!==void 0?{username:o.username}:{},...o.first_name!==void 0?{firstName:o.first_name}:{}})}return[...t.values()].reverse()}async function Fee(e){try{let t=await fetch(`${_F}/bot${e}/getUpdates`);if(!t.ok)return[];let n=await t.json();return!n.ok||!Array.isArray(n.result)?[]:n.result}catch{return[]}}async function OF(e,t={}){let n=t.maxAttempts??30,r=t.intervalMs??2e3;for(let o=0;o<n;o++){let s=await Fee(e),i=Dee(s);if(i.length>0)return i;o<n-1&&await new Promise(a=>setTimeout(a,r))}return[]}function AF(e){let t=$ee({input:process.stdin,output:process.stdout});return _0("telegram.setup-wizard",()=>new Promise(n=>{t.question(e,r=>{t.close(),n(r.trim())})}))}function Lee(e){return process.stdin.isTTY||(console.error(je.red(`Cannot securely prompt for secret on a non-TTY stdin: "${e.trim()}"`)),console.error(je.gray(" Supply TELEGRAM_BOT_TOKEN via environment variable or ~/.afk/config/afk.env instead.")),process.exit(1)),new Promise(t=>{process.stdout.write(e);let n=[];process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf-8");let r=o=>{o==="\r"||o===`
|
|
2171
2171
|
`||o===""?(process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",r),process.stdout.write(`
|
|
2172
2172
|
`),t(n.join("").trim())):o===""?(process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write(`
|
|
2173
|
-
`),process.exit(1)):o==="\x7F"?n.pop():n.push(o)};process.stdin.on("data",r)})}async function $F(){let e=St();console.log(""),console.log(
|
|
2174
|
-
Multiple chats found:`)),o.forEach((l,c)=>{let u=l.username?`@${l.username}`:l.firstName??l.type;console.log(` [${c+1}] ${u} (id ${l.chatId}, ${l.type})`)});let i=await AF("Which chat should be allowed? [1]: "),a=Number.parseInt(i||"1",10)-1;Number.isFinite(a)&&a>=0&&a<o.length&&(s=o[a])}else{let i=s.username?`@${s.username}`:s.firstName??s.type;console.log(
|
|
2175
|
-
`)}),t.command("discover-chat").description("Poll getUpdates for chats that have DM'd the bot; emit JSON {found, chats, reason?}").option("--timeout-sec <n>","How long to poll before giving up","60").action(async n=>{let r=Number.parseInt(n.timeoutSec??"60",10);(!Number.isFinite(r)||r<1)&&(console.error(
|
|
2173
|
+
`),process.exit(1)):o==="\x7F"?n.pop():n.push(o)};process.stdin.on("data",r)})}async function $F(){let e=St();console.log(""),console.log(je.bold("\u{1F916} Telegram bot setup")),console.log(""),console.log(je.gray(`Config will be written to ${e}`)),console.log("");let t=v.TELEGRAM_BOT_TOKEN?.trim()??"",n=null;for(t&&(console.log(je.gray("Validating existing TELEGRAM_BOT_TOKEN...")),n=await DS(t),n?console.log(je.green(`\u2713 Token valid for @${n.username??n.firstName} (id ${n.id})`)):(console.log(je.yellow("\u26A0 Existing TELEGRAM_BOT_TOKEN is invalid; prompting for a new one")),t=""));!n;)t=await Lee("Paste your bot token (from @BotFather): "),t||(console.error(je.red("No token provided. Aborting.")),process.exit(1)),n=await DS(t),n||console.log(je.red("\u2717 Token rejected by getMe. Try again or Ctrl-C to abort."));un(e,"TELEGRAM_BOT_TOKEN",t),console.log(je.green(`\u2713 Saved TELEGRAM_BOT_TOKEN \u2192 ${e}`)),console.log(""),console.log(je.bold("Now DM your bot to authorize your account."));let r=n.username?`@${n.username}`:`"${n.firstName}"`;console.log(` 1. Open Telegram and find ${je.cyan(r)}`),console.log(' 2. Send any message (e.g. "hi")'),console.log(""),console.log(je.gray("Polling for your chat ID (up to 60s)..."));let o=await OF(t);if(o.length===0){console.error(je.red("\u2717 No chats found after 60s.")),console.error(je.gray(" Send a message to the bot and run `afk telegram setup` again,")),console.error(je.gray(" or paste your chat ID manually:"));let i=await AF("Chat ID: "),a=Number.parseInt(i,10);return Number.isFinite(a)||(console.error(je.red("Invalid chat ID. Aborting.")),process.exit(1)),un(e,"AFK_TELEGRAM_ALLOWED_CHAT_IDS",String(a)),console.log(je.green(`\u2713 Saved AFK_TELEGRAM_ALLOWED_CHAT_IDS=${a}`)),{envPath:e,bot:n,chatId:a}}let s=o[0];if(o.length>1){console.log(je.bold(`
|
|
2174
|
+
Multiple chats found:`)),o.forEach((l,c)=>{let u=l.username?`@${l.username}`:l.firstName??l.type;console.log(` [${c+1}] ${u} (id ${l.chatId}, ${l.type})`)});let i=await AF("Which chat should be allowed? [1]: "),a=Number.parseInt(i||"1",10)-1;Number.isFinite(a)&&a>=0&&a<o.length&&(s=o[a])}else{let i=s.username?`@${s.username}`:s.firstName??s.type;console.log(je.green(`\u2713 Found chat with ${i} (id ${s.chatId})`))}return un(e,"AFK_TELEGRAM_ALLOWED_CHAT_IDS",String(s.chatId)),console.log(je.green(`\u2713 Saved AFK_TELEGRAM_ALLOWED_CHAT_IDS=${s.chatId} \u2192 ${e}`)),console.log(""),console.log(je.bold("Setup complete. Start the bot with:")),console.log(je.cyan(" afk telegram start")),console.log(""),{envPath:e,bot:n,chatId:s.chatId}}K();function DF(e){let t=e.command("telegram").description("Manage the Agent AFK Telegram bot (setup, start, stop, status)");t.command("setup").description("Interactive setup: validate bot token, discover chat ID, persist to ~/.afk/config/afk.env").action(async()=>{try{await $F()}catch(n){console.error(Fe.red(`Setup failed: ${n.message}`)),process.exit(1)}}),t.command("check-token").description("Validate TELEGRAM_BOT_TOKEN via getMe; emit JSON {set, valid, username?, botId?, reason?}").action(async()=>{let n=await IF(St());process.stdout.write(JSON.stringify(n)+`
|
|
2175
|
+
`)}),t.command("discover-chat").description("Poll getUpdates for chats that have DM'd the bot; emit JSON {found, chats, reason?}").option("--timeout-sec <n>","How long to poll before giving up","60").action(async n=>{let r=Number.parseInt(n.timeoutSec??"60",10);(!Number.isFinite(r)||r<1)&&(console.error(Fe.red("--timeout-sec must be a positive integer")),process.exit(2));let o=await MF(St(),{timeoutSec:r});process.stdout.write(JSON.stringify(o)+`
|
|
2176
2176
|
`)}),t.command("set-allowed-chat <chatId>").description("Persist AFK_TELEGRAM_ALLOWED_CHAT_IDS=<chatId> to ~/.afk/config/afk.env; emit JSON {ok, path}").action(n=>{let r=Number.parseInt(n,10);Number.isFinite(r)||(process.stdout.write(JSON.stringify({ok:!1,reason:"invalid-chat-id"})+`
|
|
2177
2177
|
`),process.exit(2));let o=St();un(o,"AFK_TELEGRAM_ALLOWED_CHAT_IDS",String(r)),process.stdout.write(JSON.stringify({ok:!0,path:o})+`
|
|
2178
|
-
`)}),t.command("start").description("Start the bot as a background daemon").action(async()=>{let n=await MS();if(n.kind==="started"){console.log(
|
|
2178
|
+
`)}),t.command("start").description("Start the bot as a background daemon").action(async()=>{let n=await MS();if(n.kind==="started"){console.log(Fe.green(`\u2713 Bot started (PID ${n.pid})`)),console.log(Fe.gray(` Logs: ${n.logFile}`)),console.log(Fe.gray(" Tail with: afk telegram logs --follow"));return}if(n.kind==="already-running"&&(console.log(Fe.yellow(`\u26A0 ${n.message}`)),process.exit(1)),n.kind==="exited-immediately"){if(console.error(Fe.red(`\u2717 ${n.message}`)),n.logTail&&n.logTail.length>0){console.error(""),console.error(Fe.bold("Last log entries:"));for(let r of n.logTail)console.error(Fe.gray(` ${r}`))}process.exit(1)}console.error(Fe.red(`\u2717 ${n.message}`)),process.exit(1)}),t.command("stop").description("Stop the bot (SIGTERM, then SIGKILL after 5s)").action(async()=>{let n=await OS();if(n.kind==="not-running"){console.log(Fe.yellow("\u26A0 Bot is not running"));return}if(n.kind==="stopped"){console.log(Fe.green(`\u2713 Bot stopped (PID ${n.pid})`));return}console.log(Fe.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 OS();(n.kind==="stopped"||n.kind==="force-killed")&&console.log(Fe.gray(`Stopped (PID ${n.pid})`));let r=await MS();if(r.kind==="started"){console.log(Fe.green(`\u2713 Bot restarted (PID ${r.pid})`));return}console.error(Fe.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=$S();jee(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}=$S();if(!Bee(r)){console.log(Fe.yellow(`No log file at ${r}`)),console.log(Fe.gray("Start the bot first: afk telegram start"));return}let o=Number.parseInt(n.lines??"50",10);if(n.follow){Nee("tail",["-n",String(o),"-f",r],{stdio:"inherit"}).on("error",a=>{console.error(Fe.red(`Failed to spawn tail: ${a.message}`))});return}let s=Uee(r,"utf-8").split(`
|
|
2179
2179
|
`).slice(-o-1);console.log(s.join(`
|
|
2180
|
-
`))})}function jee(e){if(console.log(
|
|
2180
|
+
`))})}function jee(e){if(console.log(Fe.bold("\u{1F4CA} Telegram Bot Status")),console.log(""),e.running?(console.log(` ${Fe.green("\u25CF")} Running (PID ${e.pid})`),e.uptimeSec!==void 0&&console.log(` Uptime: ${Hee(e.uptimeSec)}`),e.memoryMb!==void 0&&console.log(` Memory: ${e.memoryMb} MB`)):console.log(` ${Fe.red("\u25CF")} Stopped`),console.log(` PID: ${e.pidFile}`),console.log(` Logs: ${e.logFile}`),e.logTail&&e.logTail.length>0){console.log(""),console.log(Fe.bold("Recent log entries:"));for(let t of e.logTail)console.log(Fe.gray(` ${t}`))}}function Hee(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 yte}from"node:child_process";import{promisify as bte}from"node:util";import xe from"chalk";K();import{execFile as Wee}from"node:child_process";import{randomBytes as Kee}from"node:crypto";import{promises as la}from"node:fs";import{join as pf}from"node:path";import{promisify as Gee}from"node:util";var qee=Gee(Wee),FF=16;var At=class extends Error{cause;code;constructor(t,n,r){super(t),this.name="WorktreeError",this.cause=n,this.code=r}};function FS(e,t=40){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||"task"}function zee(){return Kee(4).toString("hex").slice(0,4)}function Jee(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 Vee(e,t={}){let n=(t.now??(()=>new Date))(),r=(t.randomSuffix??zee)();return`${Jee(n)}-${FS(e,32)}-${r}`}async function hs(e,t){try{let n=await qee("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 At(`git ${t.join(" ")} failed: ${o}`,n)}}async function Yee(e){let{stdout:t}=await hs(e,["rev-parse","--show-toplevel"]);if(!t)throw new At(`not a git repository: ${e}`);return t}async function Xee(e,t){if(t){let{stdout:o}=await hs(e,["rev-parse",t]);return{sha:o}}let{stdout:n}=await hs(e,["rev-parse","HEAD"]),r;try{let{stdout:o}=await hs(e,["symbolic-ref","--quiet","HEAD"]);o&&(r=o)}catch{}return{sha:n,branch:r}}function Zee(e,t,n){let r=n?FS(n,32):`branch-${t}`;return`afk/farm/${e}/${t}-${r}`}function Qee(e,t){return pf(e,`branch-${t}`)}async function ete(e,t){try{await hs(e,["worktree","remove","--force",t])}catch{}}async function tte(e,t){try{await hs(e,["branch","-D",t])}catch{}}async function LF(e){if(e.count<1||e.count>FF)throw new At(`count must be between 1 and ${FF}, got ${e.count}`);if(e.labels&&e.labels.length!==e.count)throw new At(`labels.length (${e.labels.length}) must equal count (${e.count})`);let t=e.cwd??process.cwd(),n=await Yee(t),{sha:r,branch:o}=await Xee(n,e.baseRef),s=(e.now??(()=>new Date))(),i=e.taskSlug??Vee(e.taskName,{now:()=>s,randomSuffix:e.randomSuffix}),a=e.taskSlug??i,l=zf(i);try{throw await la.access(l),new At(`farm directory already exists: ${l}`)}catch(d){if(d.code!=="ENOENT")throw d instanceof At?d:new At(`failed to check farm dir ${l}`,d)}await la.mkdir(l,{recursive:!0});let c=[];try{for(let d=1;d<=e.count;d++){let p=e.labels?.[d-1],m=Zee(i,d,p),g=Qee(l,d);await hs(n,["worktree","add","-b",m,g,r]),c.push({index:d,label:p?FS(p,32):void 0,path:g,branch:m})}}catch(d){for(let p of c.slice().reverse())await ete(n,p.path),await tte(n,p.branch);throw await la.rm(l,{recursive:!0,force:!0}).catch(()=>{}),d instanceof At?d:new At("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 la.writeFile(pf(l,"farm.json"),JSON.stringify(u,null,2)+`
|
|
2181
2181
|
`,"utf8"),u}function nte(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 rte(e){let t=pf(zf(e),"farm.json");try{let n=await la.readFile(t,"utf8"),r=JSON.parse(n);if(r.schemaVersion!==1&&r.schemaVersion!==2&&r.schemaVersion!==3)throw new At(`unsupported farm manifest schema: ${r.schemaVersion} (expected 1, 2, or 3)`,void 0,"unsupported-schema");return nte(r)}catch(n){if(n.code==="ENOENT")return null;throw n instanceof At?n:new At(`failed to load farm manifest ${t}`,n,"invalid")}}async function NF(e,t){let n=await rte(e);if(!n)throw new At(`farm not found: ${e}`);return n.memoryFactId=t,n.schemaVersion=3,await la.writeFile(pf(n.farmDir,"farm.json"),JSON.stringify(n,null,2)+`
|
|
2182
|
-
`,"utf8"),n}ze();Ve();import{spawn as ote}from"child_process";import{promises as mf}from"fs";import{join as mc,dirname as
|
|
2182
|
+
`,"utf8"),n}ze();Ve();import{spawn as ote}from"child_process";import{promises as mf}from"fs";import{join as mc,dirname as eGe}from"path";var ste=1,ff=12e4;async function HF(e){let{branchPath:t,baseSha:n,testCmd:r,timeoutMs:o=ff,_spawn:s=ote,_readPackageJson:i=ite,_now:a=Date.now,_nowIso:l=()=>new Date().toISOString()}=e,c=r??await ate(t,i),u=0,d=0,p=0,m;if(c){let y=await KF(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: ${ute(y.stderr,200)}`):y.exitCode===0?u=1:d=1}else m="no test command found (no package.json scripts.test)";let g=await lte(t,o,s,a),h=await cte(t,n,s),b={schemaVersion:ste,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 WF(e,t,n){let r=mc(e,"scores");await mf.mkdir(r,{recursive:!0});let o=mc(r,`branch-${t}.json`);return await mf.writeFile(o,JSON.stringify(n,null,2)+`
|
|
2183
2183
|
`,"utf8"),o}function fc(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=BF(s),l=BF(i);if(a!==l)return l-a;let c=UF(s.lint_ok),u=UF(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 ite(e){try{let t=await mf.readFile(e,"utf8");return JSON.parse(t)}catch{return null}}async function ate(e,t){let n=await t(mc(e,"package.json"));if(!jF(n))return;let r=n.scripts;return!jF(r)||typeof r.test!="string"?void 0:await GF(mc(e,"pnpm-lock.yaml"))?"pnpm test":"npm test"}async function KF(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 lte(e,t,n,r){if(!await GF(mc(e,"tsconfig.json")))return null;let o=await KF("npx --no-install tsc --noEmit",e,t,n,r);return o.crashed||o.timedOut?null:o.exitCode===0}async function cte(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 BF(e){let t=e.pass+e.fail;return t===0?0:e.pass/t}function UF(e){return e===!0?2:e===!1?1:0}function ute(e,t){return e.length<=t?e:e.slice(0,t)+"\u2026"}function jF(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function GF(e){try{return await mf.access(e),!0}catch{return!1}}ku();function qF(e,t){let n;try{n=t?._store??new dt}catch(r){return{skipped:!0,reason:r instanceof Error?r.message:String(r)}}try{let r=dte(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 dte(e){let t=pte(e.branches),n=e.winner??null,r=mte(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 pte(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 mte(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 fte="afk:f:";var gte=/^[a-z0-9T][a-z0-9T-]{0,62}$/;function gc(e,t){if(!gte.test(t))throw new Error(`buildFarmCallback: invalid taskSlug ${JSON.stringify(t)}`);let n=`${fte}${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 zF(e){return{inline_keyboard:[[{text:"\u2705 Open PR",callback_data:gc("p",e)},{text:"\u{1F501} Respawn from winner",callback_data:gc("r",e)}],[{text:"\u{1F50D} Full diff",callback_data:gc("d",e)},{text:"\u274C Discard all",callback_data:gc("x",e)}]]}}function hte(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=fc(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,k=S.label?` (${S.label})`:"",T=S.score??null,R=T===null?"\u2014":T.pass>0?"\u2713":"\u2717",A=T===null?"\u2014":T.lint_ok===!0?"\u2713":T.lint_ok===!1?"\u2717":"?",E=T===null?"?":T.loc_delta>0?`+${T.loc_delta}`:T.loc_delta<0?`${T.loc_delta}`:"0",O=w?" \u2190 winner":"";m.push(`#${g} ${S.branch}${k} tests${R} lint${A} ${E} LoC${O}`),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(`
|
|
2184
2184
|
`)}async function JF(e,t){let n=hte(e),r=zF(e.taskSlug),o=t?._push??await Promise.resolve().then(()=>(Nr(),gh)).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 VF=bte(yte);async function wte(e,t){try{let{stdout:n}=await VF("git",["-C",e,"rev-list",`${t}..HEAD`,"--count"],{maxBuffer:4194304});return parseInt(n.trim(),10)||0}catch{return 0}}async function Ste(e){try{let{stdout:t}=await VF("git",["-C",e,"status","--porcelain"],{maxBuffer:4194304});return t.trim()?t.trim().split(`
|
|
2185
2185
|
`).filter(Boolean):[]}catch{return[]}}var LS=class extends Error{dirtyFiles;constructor(t){super(`Source repository has uncommitted changes after farm run. Dirty files:
|
|
@@ -2214,10 +2214,10 @@ or "latest" (the default) \u2014 the most recently written trace.`).option("--al
|
|
|
2214
2214
|
`)}}catch(r){z(r)}})}import bt from"chalk";import{execFileSync as pne}from"child_process";import{existsSync as vL}from"fs";K();import{homedir as uL}from"os";import{join as HS}from"path";var da=["telegram","daemon"];function yt(e){return`com.afk.${e}`}function WS(e=uL()){return HS(e,"Library","LaunchAgents")}function ho(e,t=uL()){return HS(WS(t),`${yt(e)}.plist`)}function pa(e){return HS(Rs(),`service-${e}.log`)}function hc(){return`gui/${process.getuid?.()??501}`}var ys=8e3;import{execFileSync as Vte}from"child_process";import{existsSync as dL,realpathSync as pL}from"fs";import{homedir as Yte}from"os";import{delimiter as Xte,dirname as Zte,resolve as Qte}from"path";function yo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function mL(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>${yo(e.label)}</string>`),t.push(" <key>ProgramArguments</key>"),t.push(" <array>");for(let n of e.programArguments)t.push(` <string>${yo(n)}</string>`);if(t.push(" </array>"),t.push(" <key>WorkingDirectory</key>"),t.push(` <string>${yo(e.workingDirectory)}</string>`),t.push(" <key>StandardOutPath</key>"),t.push(` <string>${yo(e.standardOutPath)}</string>`),t.push(" <key>StandardErrorPath</key>"),t.push(` <string>${yo(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>${yo(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>${yo(r)}</key>`),t.push(` <string>${yo(o)}</string>`)}t.push(" </dict>")}return t.push("</dict>"),t.push("</plist>"),t.join(`
|
|
2215
2215
|
`)+`
|
|
2216
2216
|
`}var ene=["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin","/usr/sbin","/sbin"];function fL(e=process.execPath){let t=Zte(e),n=new Set,r=[];for(let o of[t,...ene])o.length>0&&!n.has(o)&&(n.add(o),r.push(o));return r.join(Xte)}function tne(e=["/usr/local/bin/afk","/opt/homebrew/bin/afk"],t=dL,n=nne,r=pL){let o=process.argv[1];if(o)try{let i=r(o);if(gL.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 gL=["/usr/local/bin/","/opt/homebrew/bin/","/usr/bin/","/opt/local/bin/"];function nne(){try{let e=Vte("which",["afk"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(!e)return;let t;try{t=pL(e)}catch{return}return gL.some(n=>t.startsWith(n))?t:void 0}catch{return}}function KS(e,t=dL){if(e==="telegram"){let r=IS();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[tne(),"daemon"]}function hL(e,t){let n=KS(e,t),r=e==="telegram"?n[1]:void 0;if(!r)return;let o=Qte(r),s=Yte();if(o.startsWith(s)&&!(o.includes("/node_modules/")||o.includes("/homebrew/")))return[o]}import{execFileSync as rne}from"child_process";import{existsSync as one}from"fs";function sne(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(`
|
|
2217
|
-
`)){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 GS(e){let t=ho(e),n={name:e,label:yt(e),installed:one(t),plistPath:t,logFile:pa(e)};if(!n.installed)return n;try{let r=rne("launchctl",["list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:ys}),o=sne(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 yf}from"child_process";import{existsSync as bL,mkdirSync as yL,readFileSync as
|
|
2217
|
+
`)){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 GS(e){let t=ho(e),n={name:e,label:yt(e),installed:one(t),plistPath:t,logFile:pa(e)};if(!n.installed)return n;try{let r=rne("launchctl",["list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:ys}),o=sne(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 yf}from"child_process";import{existsSync as bL,mkdirSync as yL,readFileSync as d2e,renameSync as ine,rmSync as ane,unlinkSync as lne,writeFileSync as cne}from"fs";import{homedir as une}from"os";import{dirname as dne}from"path";function wL(e,t={}){let n=ho(e);if(bL(n))return{kind:"already-installed",plistPath:n,label:yt(e)};let r;try{r=KS(e,t._entrypointExistsCheck)}catch(u){return{kind:"failed",reason:u.message}}let o=t.noWatch?void 0:hL(e,t._entrypointExistsCheck),s=pa(e);yL(WS(),{recursive:!0}),yL(dne(s),{recursive:!0});let i={PATH:fL(),...t.environment??{}},a={label:yt(e),programArguments:r,workingDirectory:une(),standardOutPath:s,standardErrorPath:s,...o?{watchPaths:o}:{},environmentVariables:i},l=mL(a),c=`${n}.tmp`;try{cne(c,l,{encoding:"utf-8",flag:"wx",mode:384})}catch(u){return{kind:"failed",reason:`Failed to write plist (tmp ${c}): ${u.message}`}}try{ine(c,n)}catch(u){try{lne(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:yt(e),watchPathsActive:!!o};try{yf("launchctl",["bootstrap",hc(),n],{stdio:["ignore","pipe","pipe"],timeout:ys})}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{yf("launchctl",["bootout",`${hc()}/${yt(e)}`],{stdio:["ignore","pipe","pipe"],timeout:ys})}catch(m){p=m.message}try{yf("launchctl",["bootstrap",hc(),n],{stdio:["ignore","pipe","pipe"],timeout:ys})}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:yt(e),watchPathsActive:!!o}}function SL(e,t={}){let n=ho(e);if(!bL(n))return{kind:"not-installed",plistPath:n};if(!t.skipBootout)try{yf("launchctl",["bootout",`${hc()}/${yt(e)}`],{stdio:"ignore",timeout:ys})}catch{}try{ane(n,{force:!0})}catch(r){return{kind:"failed",reason:`Failed to remove plist: ${r.message}`}}return{kind:"uninstalled",plistPath:n}}function yc(){if(process.platform!=="darwin")throw new Error(`'afk service' uses macOS launchd and is only supported on darwin. Detected: ${process.platform}.`)}function bf(e){let t=e.toLowerCase();if(da.includes(t))return t;throw new Error(`Unknown service '${e}'. Supported: ${da.join(", ")}.`)}function EL(e){let t=e.command("service").description("Manage AFK background services via macOS launchd (always-on, auto-restart)");t.command("install <name>").description(`Install <${da.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{yc();let o=bf(n),s=wL(o,{noWatch:r.watch===!1,skipBootstrap:!!r.dryRun});if(s.kind==="already-installed"&&(console.log(bt.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(bt.red(`\u2717 Install failed: ${s.reason}`)),process.exit(1)),console.log(bt.green(`\u2713 Installed ${s.label}`)),console.log(f.meta(` Plist: ${s.plistPath}`)),console.log(f.meta(` Log: ${pa(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){z(o)}}),t.command("uninstall <name>").description("Stop the service and remove its LaunchAgent plist").action(n=>{try{yc();let r=bf(n),o=SL(r);if(o.kind==="not-installed"){console.log(bt.yellow(`\u26A0 ${yt(r)} is not installed (no plist at ${o.plistPath})`));return}o.kind==="failed"&&(console.error(bt.red(`\u2717 Uninstall failed: ${o.reason}`)),process.exit(1)),console.log(bt.green(`\u2713 Uninstalled ${yt(r)}`)),console.log(f.meta(` Removed: ${o.plistPath}`))}catch(r){z(r)}}),t.command("status [name]").description("Show running PID, last exit status, and log file for one or all services").action(n=>{try{if(yc(),n){let r=GS(bf(n));kL(r);return}for(let r of da)kL(GS(r)),console.log("")}catch(r){z(r)}}),t.command("list").description("List recognised service names and whether each is installed").action(()=>{try{yc(),console.log(bt.bold("AFK services:"));for(let n of da){let r=ho(n),o=vL(r),s=o?bt.green("\u25CF"):bt.dim("\u25CB"),i=o?f.meta("installed"):f.meta("not installed");console.log(` ${s} ${n.padEnd(10)} ${i} ${f.meta(r)}`)}}catch(n){z(n)}}),t.command("restart <name>").description("Restart the service (launchctl kickstart -k)").action(n=>{try{yc();let r=bf(n),o=ho(r);if(vL(o)||(console.error(bt.red(`\u2717 ${yt(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{pne("launchctl",["kickstart","-k",`gui/${s}/${yt(r)}`],{stdio:["ignore","pipe","pipe"],timeout:8e3}),console.log(bt.green(`\u2713 Restarted ${yt(r)}`))}catch(i){console.error(bt.red(`\u2717 Restart failed: ${i.message}`)),process.exit(1)}}catch(r){z(r)}})}function kL(e){if(console.log(bt.bold(`${e.label}`)),!e.installed){console.log(` ${bt.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(` ${bt.green("\u25CF")} Running (PID ${e.pid})`):(console.log(` ${bt.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 yn from"chalk";import{execFileSync as mne}from"child_process";import{chmodSync as fne,existsSync as bc,mkdirSync as RL,readdirSync as gne,readFileSync as hne,renameSync as CL,writeFileSync as AL}from"fs";import{basename as yne,dirname as zS,join as JS}from"path";import{randomBytes as _L}from"crypto";import{createInterface as bne}from"node:readline";K();function wne(e){let t=bne({input:process.stdin,output:process.stdout});return new Promise(n=>{t.question(e,()=>{t.close(),n()})})}var bo="chrome-devtools",qS=["stable","beta","canary","dev"];function Sne(e="stable"){let t=["chrome-devtools-mcp@latest","--autoConnect"];return e!=="stable"&&t.push("--channel",e),{command:"npx",args:t}}function TL(e){if(!bc(e))return{mcpServers:{}};let t;try{t=hne(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 xL(e,t){RL(zS(e),{recursive:!0});let n=JS(zS(e),`.mcp.json.${process.pid}.${_L(4).toString("hex")}.tmp`);AL(n,`${JSON.stringify(t,null,2)}
|
|
2218
2218
|
`,"utf-8"),CL(n,e)}function vne(){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=mne(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 kne(){let e=vne();console.log(""),console.log(yn.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(yn.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("Give the agent web hands: connect your real Chrome, or save a login it reuses");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 (${qS.join("|")})`,"stable").action(n=>{try{let r=(n.channel??"stable").toLowerCase();if(!qS.includes(r))throw new Error(`--channel must be one of ${qS.join(", ")} (got "${n.channel}")`);let o=qo(),s=TL(o);s.mcpServers===void 0&&(s.mcpServers={});let i=Sne(r),a=s.mcpServers[bo];if(a!==void 0&&JSON.stringify(a)===JSON.stringify(i))console.log(yn.green(`\u2713 "${bo}" already configured`)),console.log(f.meta(` Config: ${o}`));else{s.mcpServers[bo]=i,xL(o,s);let l=a===void 0?"Added":"Updated";console.log(yn.green(`\u2713 ${l} "${bo}" MCP server`)),console.log(f.meta(` Config: ${o}`)),console.log(f.meta(` Runs: npx ${i.args?.join(" ")??""}`))}kne()}catch(r){z(r)}}),t.command("disconnect").description("Remove the chrome-devtools server from your MCP config").action(()=>{try{let n=qo();if(!bc(n)){console.log(yn.yellow(`\u26A0 No MCP config at ${n} \u2014 nothing to remove.`));return}let r=TL(n);if(r.mcpServers===void 0||r.mcpServers[bo]===void 0){console.log(yn.yellow(`\u26A0 "${bo}" is not configured \u2014 nothing to remove.`));return}delete r.mcpServers[bo],xL(n,r),console.log(yn.green(`\u2713 Removed "${bo}" from ${n}`))}catch(n){z(n)}}),t.command("login <url>").description("Open a headed browser, log in manually, and save the session to a vault profile the agent's native browser tools reuse").option("--profile <name>","Vault profile name to save the session under","default").action(async(n,r)=>{try{let o=(r.profile??"default").trim();Ca(o);let s;try{s=new URL(n)}catch{throw new Error(`Invalid URL: ${n}`)}if(s.protocol!=="http:"&&s.protocol!=="https:")throw new Error(`login URL must be http(s), got: ${s.protocol}`);let i=Aa(o),{chromium:a}=await import("playwright");console.log(f.meta(`Launching a browser for profile "${o}"\u2026`));let l=await a.launch({headless:!1}),c=await l.newContext(bc(i)?{storageState:i}:{});await(await c.newPage()).goto(n,{waitUntil:"load"}).catch(()=>{}),console.log(""),console.log(yn.bold("Log in to the site in the opened browser window.")),console.log(f.meta("When fully logged in, return here and press Enter to save the session.")),console.log(f.meta("(Do NOT close the browser window yourself \u2014 this command closes it for you.)")),await wne("Press Enter to save the session\u2026 ");let d=await c.storageState();RL(Qf(o),{recursive:!0});let p=JS(zS(i),`.${yne(i)}.${process.pid}.${_L(4).toString("hex")}.tmp`);AL(p,JSON.stringify(d),{mode:384}),fne(p,384),CL(p,i),await l.close().catch(()=>{}),console.log(yn.green(`\u2713 Saved session for profile "${o}"`)),console.log(f.meta(` Vault: ${i} (0600 \u2014 treat as a credential)`)),console.log(f.meta(" Point the agent at it:")),console.log(f.meta(` export AFK_BROWSER_DEFAULT_PROFILE=${o}`))}catch(o){z(o)}}),t.command("profiles").description("List saved browser session-vault profiles").action(()=>{try{let n=Zf(),r=bc(n)?gne(n,{withFileTypes:!0}).filter(o=>o.isDirectory()):[];if(r.length===0){console.log(f.meta("No saved profiles. Create one with `afk browser login <url> --profile <name>`."));return}console.log(yn.bold("Saved browser profiles:"));for(let o of r){let s=bc(JS(n,o.name,"storageState.json")),i=s?yn.green("\u25CF"):f.meta("\u25CB"),a=s?"":f.meta(" (no saved session)");console.log(` ${i} ${o.name}${a}`)}console.log(""),console.log(f.meta("Use one: export AFK_BROWSER_DEFAULT_PROFILE=<name>"))}catch(n){z(n)}})}import{readFileSync as Ene,readdirSync as Tne,statSync as xne}from"fs";import{join as ZS}from"path";K();import{join as rt}from"path";function wf(){return rt(Mt(),"improve")}function wo(){return rt(wf(),"failure-cards")}function IL(){return rt(wo(),".index.jsonl")}function wc(e){return rt(wo(),`${e}.json`)}function Sf(e){return rt(wo(),`${e}.md`)}function ML(){return rt(Te(),"witness")}function bs(){return rt(wf(),"proposals")}function OL(){return rt(bs(),".index.jsonl")}function VS(e){return rt(bs(),`${e}.json`)}function $L(e){return rt(bs(),`${e}.md`)}function So(){return rt(wf(),"eval-cases")}function DL(){return rt(So(),".index.jsonl")}function YS(e){return rt(So(),`${e}.json`)}function XS(e){return rt(So(),`${e}.fixture.jsonl`)}function FL(e){return rt(So(),`${e}.md`)}function ma(){return rt(wf(),"eval-runs")}function LL(){return rt(ma(),".index.jsonl")}function NL(e){return rt(ma(),`${e}.json`)}function BL(e){return rt(ma(),`${e}.md`)}J();function UL(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 jL(e={}){let t=e.witnessRoot??ML(),n=e.afkHome??v.AFK_HOME??Rne(),r=e.sinceMs,o={sessionsScanned:0,sessionsSkippedOld:0,sessionsSkippedEmpty:0,invalidLineCount:0,sessions:[]},s;try{s=Tne(t)}catch{return o}for(let i of s){if(i.startsWith("."))continue;let a=ZS(t,i),l;try{l=xne(a)}catch{continue}if(!l.isDirectory())continue;if(r!==void 0&&l.mtimeMs<r){o.sessionsSkippedOld+=1;continue}let c=ZS(a,"trace.jsonl"),u;try{u=Ene(c,"utf-8")}catch{o.sessionsSkippedEmpty+=1;continue}let d=Cne(c,n),p=fa({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 fa(e){let{sessionId:t,tracePath:n,relativeTracePath:r,content:o,sessionMtimeMs:s}=e,i=[],a=0,l=o.split(`
|
|
2219
2219
|
`);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=OP.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 Rne(){let e=v.AFK_HOME;return e&&e.length>0?e:ZS(v.HOME??"",".afk")}function Cne(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 Ane}from"crypto";var Ar=4,_ne=8,Pne="v1-bytes-tuple";function vf(e,t={}){let n=t.minRepeats??Ar;if(n<2)throw new Error(`minRepeats must be >= 2 (got ${n})`);let r=[];for(let o of e){let s=Ine(o,n);r.push(...s)}return r}function Ine(e,t){let n=Mne(e.events),r=One(n),o=[];for(let[s,i]of r.entries()){let a=$ne(i,t);for(let l of a)o.push(Fne(e,l,s))}return o}function Mne(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=Dne({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 One(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 $ne(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 Dne(e){let t=[e.name,String(e.inputBytes),String(e.resultBytes),e.isError?"1":"0",e.subagentId??""].join("|");return Ane("sha256").update(t).digest("hex")}function Fne(e,t,n){let r=t[0];if(!r)throw new Error("repeated-tool-use: empty run");let o=jne(r.name,r.fingerprint),s=new Date().toISOString(),i=t.slice(0,_ne),a=[{sessionId:e.sessionId,tracePath:e.relativeTracePath,eventIndices:i.map(l=>l.completedSeq),excerpt:Lne(i),annotation:Nne(t,n)}];return{slug:o,title:Bne(r.name,t.length),pattern:"repeated-tool-use",severity:Une(t.length),observedAt:s,evidence:a,detail:{detector:"repeated-tool-use@v1",fingerprintAlgorithm:Pne,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 Lne(e){let t=e.map(n=>n.rawLine).join(`
|
|
2220
|
-
`);return t.length<=2e3?t:t.slice(0,1997)+"..."}function Nne(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 Bne(e,t){return`'${e}' tool repeated ${t}\xD7 with identical fingerprint`}function Une(e){return e>=10?"high":e>=4?"medium":"low"}function jne(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 Hne=new Set(["budget_exceeded","timeout","hook_blocked","abort","iteration_cap","max_turns_exceeded"]);function kf(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(!Hne.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(Kne(s,i));return o}var Wne=8;function Kne(e,t){let n=qne(e),r=new Date().toISOString(),s=t.slice(0,Wne).map(l=>({sessionId:l.sessionId,tracePath:l.relativeTracePath,eventIndices:[l.seq],excerpt:zne(l.rawLine),annotation:`closure.reason='${l.reason}' \xB7 cost=${Jne(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:Gne(e,t.length),observedAt:r,evidence:s,detail:{detector:"closure-anomaly@v1",closureReason:e,affectedSessions:t.length,totalCostUsd:HL(i),avgTurnCount:Vne(a),maxCostUsd:HL(Math.max(...t.map(l=>l.finalCostUsd))),sessionIds:t.map(l=>l.sessionId),seqs:t.map(l=>l.seq)}}}function Gne(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 qne(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`closure-anomaly-${t.length>0?t:"unknown"}`}function zne(e){return e.length<=2e3?e:e.slice(0,1997)+"..."}function Jne(e){return`$${e.toFixed(4)}`}function HL(e){return Math.round(e*1e4)/1e4}function Vne(e){return Math.round(e*100)/100}import{createHash as Yne}from"crypto";var ws=2,Xne="v1-hook-reason-tuple",Zne=8;function WL(e,t={}){let n=t.minOccurrences??ws;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=Qne({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(tre(s,i));return o}function Qne(e){let t=[e.hookEvent,e.reason,e.blockedTool??""].join("|");return Yne("sha256").update(t).digest("hex")}function ere(e){return`subagent-block-${e.slice(0,12)}`}function tre(e,t){let n=t[0];if(!n)throw new Error("subagent-block: empty sighting bucket");let r=ere(e),o=new Date().toISOString(),i=t.slice(0,Zne).map(l=>({sessionId:l.sessionId,tracePath:l.relativeTracePath,eventIndices:[l.seq],excerpt:sre(l.rawLine),annotation:ore(l)})),a=new Set(t.map(l=>l.sessionId)).size;return{slug:r,title:rre(n.reason,t.length,a),pattern:"subagent-block",severity:nre(t.length,a),observedAt:o,evidence:i,detail:{detector:"subagent-block@v1",fingerprintAlgorithm:Xne,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 nre(e,t){return e>=6||t>=3?"high":e>=3?"medium":"low"}function rre(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 ore(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 sre(e){return e.length<=2e3?e:e.slice(0,1997)+"..."}var ire=new Set(["policy-refusal","permission-denied","hook-block","abort","elicitation-declined"]),Ss=3,vs=.25,are=8;function ga(e,t={}){let n=t.minFailures??Ss,r=t.minFailureRate??vs;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=lre(o,l.payload.name),u=l.payload.failureClass;if(u!==void 0&&ire.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(cre(i,a))}return s.sort((i,a)=>i.slug.localeCompare(a.slug)),s}function lre(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 cre(e,t){let n=pre(e.toolName),r=new Date().toISOString(),s=e.failures.slice(0,are).map(u=>({sessionId:u.sessionId,tracePath:u.relativeTracePath,eventIndices:[u.seq],excerpt:mre(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:dre(e.toolName,e.failures.length,e.totalCalls,t),pattern:"tool-failure-density",severity:ure(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:fre(t),affectedSessionCount:e.affectedSessions.size,truncatedFailureCount:e.truncatedFailureCount,avgFailureDurationMs:gre(a),failureClassBreakdown:l,excludedByClass:c,sessionIds:Array.from(e.affectedSessions),seqs:e.failures.map(u=>u.seq)}}}function ure(e,t){return t>=1||t>=.5?"high":t>=.25?e>=10?"high":"medium":e>=10?"medium":"low"}function dre(e,t,n,r){let o=(r*100).toFixed(1);return`'${e}' tool failed ${t}/${n} calls (${o}%)`}function pre(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`tool-failure-${t.length>0?t:"unknown"}`}function mre(e){return e.length<=2e3?e:e.slice(0,1997)+"..."}function fre(e){return Math.round(e*1e4)/1e4}function gre(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 ${Ar})`,run:(e,t)=>vf(e,{minRepeats:t.minRepeats??Ar})},{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)=>kf(e,{minOccurrences:t.closureAnomalyMinOccurrences??1})},{name:"subagent-block",description:`Same SubagentStart hook block reason recurring across \u2265N events (default ${ws})`,enabledByDefault:!1,run:(e,t)=>WL(e,{minOccurrences:t.subagentBlockMinOccurrences??ws})},{name:"tool-failure-density",description:`Tool with \u2265N failures (isError: true) AND failure rate \u2265R (defaults: ${Ss} failures, ${vs} rate)`,enabledByDefault:!0,run:(e,t)=>ga(e,{minFailures:t.toolFailureMinFailures??Ss,minFailureRate:t.toolFailureMinRate??vs})}]);function KL(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 GL(){return Ef.filter(e=>e.enabledByDefault!==!1).map(e=>e.name)}function ha(){return Ef.filter(e=>e.enabledByDefault===!1).map(e=>e.name)}import{existsSync as kc,mkdirSync as eN,readFileSync as Ore,readdirSync as tN,renameSync as nN,writeFileSync as tv}from"fs";import{join as rN}from"path";import{z as $}from"zod";var ya=$.enum(["repeated-tool-use","subagent-block","closure-anomaly","tool-failure-density"]),xf=$.enum(["low","medium","high"]),hre=$.enum(["open","deferred","resolved"]),qL=$.object({sessionId:$.string().min(1),tracePath:$.string().min(1),eventIndices:$.array($.number().int().nonnegative()).min(1),excerpt:$.string().max(2e3),annotation:$.string().optional()}),Rf=$.object({at:$.string().datetime(),text:$.string()}),vc=$.object({schemaVersion:$.literal(1),slug:$.string().regex(/^[a-z0-9][a-z0-9-]*$/,"slug must be lowercase alphanumeric with hyphens"),title:$.string().min(1).max(200),pattern:ya,severity:xf,status:hre,firstSeen:$.string().datetime(),lastSeen:$.string().datetime(),occurrenceCount:$.number().int().nonnegative(),evidence:$.array(qL).min(1),detail:$.record($.string(),$.unknown()),notes:$.array(Rf).default([])}),iqe=$.object({slug:$.string().regex(/^[a-z0-9][a-z0-9-]*$/),title:$.string().min(1).max(200),pattern:ya,severity:xf,observedAt:$.string().datetime(),evidence:$.array(qL).min(1),detail:$.record($.string(),$.unknown())}),zL=$.object({timestamp:$.string().datetime(),event:$.enum(["created","updated","merged-noop"]),slug:$.string(),pattern:ya,occurrenceCount:$.number().int().nonnegative(),evidenceAdded:$.number().int().nonnegative()}),yre=$.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"]),bre=$.enum(["safe","moderate","high","forbidden"]),wre=$.enum(["low","medium","high"]),Sre=$.object({cardSlug:$.string(),eventIndices:$.array($.number().int().nonnegative()).min(1),annotation:$.string().optional()}),vre=$.object({path:$.string().min(1),rationale:$.string(),riskTier:bre,confidence:wre}),kre=$.object({unitTests:$.array($.string()),evalCases:$.array($.string()),smokeChecks:$.array($.string()),manualChecks:$.array($.string())}),Ere=$.object({forbiddenPaths:$.array($.string()),requiresExplicitApproval:$.boolean()}),Tre=$.enum(["draft","approved","rejected","superseded"]),QS=$.object({schemaVersion:$.literal(1),proposalId:$.string().regex(/^[a-z0-9][a-z0-9-]*$/),cardSlug:$.string().regex(/^[a-z0-9][a-z0-9-]*$/),title:$.string().min(1).max(200),hypothesis:$.string().min(1),rootCauseClass:yre,evidenceRefs:$.array(Sre).min(1),fixSketch:$.string().min(1),likelyFiles:$.array(vre),riskLevel:xf,validationPlan:kre,scopeFreeze:Ere,generatedBy:$.enum(["template","llm"]),createdAt:$.string().datetime(),status:Tre,notes:$.array(Rf).default([])}),JL=$.object({timestamp:$.string().datetime(),event:$.enum(["created","triaged","superseded"]),proposalId:$.string(),cardSlug:$.string(),generatedBy:$.enum(["template","llm"]),riskLevel:xf}),xre=$.object({sourceSessionId:$.string().min(1),sourceTracePath:$.string().min(1),fixturePath:$.string().min(1),evidenceRowIndex:$.number().int().nonnegative(),evidenceEventIndices:$.array($.number().int().nonnegative()).min(1),sliceLineRange:$.object({startLine:$.number().int().positive(),endLine:$.number().int().positive()}),sliceLineCount:$.number().int().positive(),sliceSha256:$.string().regex(/^[0-9a-f]{64}$/,"sliceSha256 must be 64 lowercase hex chars")}),Rre=$.object({kind:$.literal("pattern-absent"),patternId:ya,detectorVersion:$.string().min(1),rationale:$.string().min(1)}),Cre=$.object({detectorAtGeneration:$.string().min(1),fingerprintAtGeneration:$.string().nullable(),cardOccurrenceCountAtGeneration:$.number().int().nonnegative(),cardLastSeenAtGeneration:$.string().datetime(),generatedBy:$.literal("replay-fixture")}),Are=$.enum(["draft","approved","rejected","superseded"]),Cf=$.object({schemaVersion:$.literal(1),evalCaseId:$.string().regex(/^[a-z0-9][a-z0-9-]*$/,"evalCaseId must be lowercase alphanumeric with hyphens"),cardSlug:$.string().regex(/^[a-z0-9][a-z0-9-]*$/),proposalId:$.string().regex(/^[a-z0-9][a-z0-9-]*$/).nullable(),title:$.string().min(1).max(200),createdAt:$.string().datetime(),kind:$.literal("replay"),replay:xre,assertion:Rre,provenance:Cre,status:Are,notes:$.array(Rf).default([])}),VL=$.object({timestamp:$.string().datetime(),event:$.enum(["created","triaged","superseded"]),evalCaseId:$.string(),cardSlug:$.string(),proposalId:$.string().nullable(),kind:$.literal("replay")}),_re=$.enum(["pass","fail","skipped"]),Pre=$.object({name:$.string().min(1),description:$.string().min(1),status:_re,expected:$.string(),actual:$.string()}),Ire=$.enum(["config-value","observed-behavior","source-symbol","fixture"]),Mre=$.object({kind:Ire,ref:$.string().min(1),detail:$.string()}),YL=$.enum(["pass","fail","unsupported","error"]),ev=$.object({schemaVersion:$.literal(1),evalRunId:$.string().regex(/^[a-z0-9][a-z0-9-]*$/,"evalRunId must be lowercase alphanumeric with hyphens"),evalCaseId:$.string().min(1),cardSlug:$.string().min(1),patternId:ya,contract:$.string().min(1).nullable(),status:YL,createdAt:$.string().datetime(),durationMs:$.number().int().nonnegative(),checks:$.array(Pre),evidence:$.array(Mre),runner:$.object({version:$.string().min(1),mode:$.literal("deterministic")}),notes:$.array(Rf).default([])}),XL=$.object({timestamp:$.string().datetime(),event:$.literal("created"),evalRunId:$.string(),evalCaseId:$.string(),cardSlug:$.string(),patternId:ya,contract:$.string().nullable(),status:YL}),ZL=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 oN(e){let t=wo();kc(t)||eN(t,{recursive:!0});let n=wc(e.slug),r=Sf(e.slug),o=ba(n),s=$re(o,e),i=o===void 0,a=s.evidence.length-(o?.evidence.length??0),l=i?"created":a>0?"updated":"merged-noop",c=vc.parse(s);return Lre(n,c),Nre(r,Ec(c)),Fre({timestamp:Bre(),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 ba(e){if(kc(e))try{let t=Ore(e,"utf-8"),n=JSON.parse(t),r=vc.safeParse(n);return r.success?r.data:void 0}catch{return}}function $re(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=Dre(e.evidence,t.evidence),r=Ure(e.firstSeen,t.observedAt),o=jre(e.lastSeen,t.observedAt),s=Hre(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 Dre(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 Ec(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
|
+
`);return t.length<=2e3?t:t.slice(0,1997)+"..."}function Nne(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 Bne(e,t){return`'${e}' tool repeated ${t}\xD7 with identical fingerprint`}function Une(e){return e>=10?"high":e>=4?"medium":"low"}function jne(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 Hne=new Set(["budget_exceeded","timeout","hook_blocked","abort","iteration_cap","max_turns_exceeded"]);function kf(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(!Hne.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(Kne(s,i));return o}var Wne=8;function Kne(e,t){let n=qne(e),r=new Date().toISOString(),s=t.slice(0,Wne).map(l=>({sessionId:l.sessionId,tracePath:l.relativeTracePath,eventIndices:[l.seq],excerpt:zne(l.rawLine),annotation:`closure.reason='${l.reason}' \xB7 cost=${Jne(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:Gne(e,t.length),observedAt:r,evidence:s,detail:{detector:"closure-anomaly@v1",closureReason:e,affectedSessions:t.length,totalCostUsd:HL(i),avgTurnCount:Vne(a),maxCostUsd:HL(Math.max(...t.map(l=>l.finalCostUsd))),sessionIds:t.map(l=>l.sessionId),seqs:t.map(l=>l.seq)}}}function Gne(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 qne(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`closure-anomaly-${t.length>0?t:"unknown"}`}function zne(e){return e.length<=2e3?e:e.slice(0,1997)+"..."}function Jne(e){return`$${e.toFixed(4)}`}function HL(e){return Math.round(e*1e4)/1e4}function Vne(e){return Math.round(e*100)/100}import{createHash as Yne}from"crypto";var ws=2,Xne="v1-hook-reason-tuple",Zne=8;function WL(e,t={}){let n=t.minOccurrences??ws;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=Qne({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(tre(s,i));return o}function Qne(e){let t=[e.hookEvent,e.reason,e.blockedTool??""].join("|");return Yne("sha256").update(t).digest("hex")}function ere(e){return`subagent-block-${e.slice(0,12)}`}function tre(e,t){let n=t[0];if(!n)throw new Error("subagent-block: empty sighting bucket");let r=ere(e),o=new Date().toISOString(),i=t.slice(0,Zne).map(l=>({sessionId:l.sessionId,tracePath:l.relativeTracePath,eventIndices:[l.seq],excerpt:sre(l.rawLine),annotation:ore(l)})),a=new Set(t.map(l=>l.sessionId)).size;return{slug:r,title:rre(n.reason,t.length,a),pattern:"subagent-block",severity:nre(t.length,a),observedAt:o,evidence:i,detail:{detector:"subagent-block@v1",fingerprintAlgorithm:Xne,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 nre(e,t){return e>=6||t>=3?"high":e>=3?"medium":"low"}function rre(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 ore(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 sre(e){return e.length<=2e3?e:e.slice(0,1997)+"..."}var ire=new Set(["policy-refusal","permission-denied","hook-block","abort","elicitation-declined"]),Ss=3,vs=.25,are=8;function ga(e,t={}){let n=t.minFailures??Ss,r=t.minFailureRate??vs;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=lre(o,l.payload.name),u=l.payload.failureClass;if(u!==void 0&&ire.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(cre(i,a))}return s.sort((i,a)=>i.slug.localeCompare(a.slug)),s}function lre(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 cre(e,t){let n=pre(e.toolName),r=new Date().toISOString(),s=e.failures.slice(0,are).map(u=>({sessionId:u.sessionId,tracePath:u.relativeTracePath,eventIndices:[u.seq],excerpt:mre(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:dre(e.toolName,e.failures.length,e.totalCalls,t),pattern:"tool-failure-density",severity:ure(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:fre(t),affectedSessionCount:e.affectedSessions.size,truncatedFailureCount:e.truncatedFailureCount,avgFailureDurationMs:gre(a),failureClassBreakdown:l,excludedByClass:c,sessionIds:Array.from(e.affectedSessions),seqs:e.failures.map(u=>u.seq)}}}function ure(e,t){return t>=1||t>=.5?"high":t>=.25?e>=10?"high":"medium":e>=10?"medium":"low"}function dre(e,t,n,r){let o=(r*100).toFixed(1);return`'${e}' tool failed ${t}/${n} calls (${o}%)`}function pre(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`tool-failure-${t.length>0?t:"unknown"}`}function mre(e){return e.length<=2e3?e:e.slice(0,1997)+"..."}function fre(e){return Math.round(e*1e4)/1e4}function gre(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 ${Ar})`,run:(e,t)=>vf(e,{minRepeats:t.minRepeats??Ar})},{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)=>kf(e,{minOccurrences:t.closureAnomalyMinOccurrences??1})},{name:"subagent-block",description:`Same SubagentStart hook block reason recurring across \u2265N events (default ${ws})`,enabledByDefault:!1,run:(e,t)=>WL(e,{minOccurrences:t.subagentBlockMinOccurrences??ws})},{name:"tool-failure-density",description:`Tool with \u2265N failures (isError: true) AND failure rate \u2265R (defaults: ${Ss} failures, ${vs} rate)`,enabledByDefault:!0,run:(e,t)=>ga(e,{minFailures:t.toolFailureMinFailures??Ss,minFailureRate:t.toolFailureMinRate??vs})}]);function KL(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 GL(){return Ef.filter(e=>e.enabledByDefault!==!1).map(e=>e.name)}function ha(){return Ef.filter(e=>e.enabledByDefault===!1).map(e=>e.name)}import{existsSync as kc,mkdirSync as eN,readFileSync as Ore,readdirSync as tN,renameSync as nN,writeFileSync as tv}from"fs";import{join as rN}from"path";import{z as $}from"zod";var ya=$.enum(["repeated-tool-use","subagent-block","closure-anomaly","tool-failure-density"]),xf=$.enum(["low","medium","high"]),hre=$.enum(["open","deferred","resolved"]),qL=$.object({sessionId:$.string().min(1),tracePath:$.string().min(1),eventIndices:$.array($.number().int().nonnegative()).min(1),excerpt:$.string().max(2e3),annotation:$.string().optional()}),Rf=$.object({at:$.string().datetime(),text:$.string()}),vc=$.object({schemaVersion:$.literal(1),slug:$.string().regex(/^[a-z0-9][a-z0-9-]*$/,"slug must be lowercase alphanumeric with hyphens"),title:$.string().min(1).max(200),pattern:ya,severity:xf,status:hre,firstSeen:$.string().datetime(),lastSeen:$.string().datetime(),occurrenceCount:$.number().int().nonnegative(),evidence:$.array(qL).min(1),detail:$.record($.string(),$.unknown()),notes:$.array(Rf).default([])}),aqe=$.object({slug:$.string().regex(/^[a-z0-9][a-z0-9-]*$/),title:$.string().min(1).max(200),pattern:ya,severity:xf,observedAt:$.string().datetime(),evidence:$.array(qL).min(1),detail:$.record($.string(),$.unknown())}),zL=$.object({timestamp:$.string().datetime(),event:$.enum(["created","updated","merged-noop"]),slug:$.string(),pattern:ya,occurrenceCount:$.number().int().nonnegative(),evidenceAdded:$.number().int().nonnegative()}),yre=$.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"]),bre=$.enum(["safe","moderate","high","forbidden"]),wre=$.enum(["low","medium","high"]),Sre=$.object({cardSlug:$.string(),eventIndices:$.array($.number().int().nonnegative()).min(1),annotation:$.string().optional()}),vre=$.object({path:$.string().min(1),rationale:$.string(),riskTier:bre,confidence:wre}),kre=$.object({unitTests:$.array($.string()),evalCases:$.array($.string()),smokeChecks:$.array($.string()),manualChecks:$.array($.string())}),Ere=$.object({forbiddenPaths:$.array($.string()),requiresExplicitApproval:$.boolean()}),Tre=$.enum(["draft","approved","rejected","superseded"]),QS=$.object({schemaVersion:$.literal(1),proposalId:$.string().regex(/^[a-z0-9][a-z0-9-]*$/),cardSlug:$.string().regex(/^[a-z0-9][a-z0-9-]*$/),title:$.string().min(1).max(200),hypothesis:$.string().min(1),rootCauseClass:yre,evidenceRefs:$.array(Sre).min(1),fixSketch:$.string().min(1),likelyFiles:$.array(vre),riskLevel:xf,validationPlan:kre,scopeFreeze:Ere,generatedBy:$.enum(["template","llm"]),createdAt:$.string().datetime(),status:Tre,notes:$.array(Rf).default([])}),JL=$.object({timestamp:$.string().datetime(),event:$.enum(["created","triaged","superseded"]),proposalId:$.string(),cardSlug:$.string(),generatedBy:$.enum(["template","llm"]),riskLevel:xf}),xre=$.object({sourceSessionId:$.string().min(1),sourceTracePath:$.string().min(1),fixturePath:$.string().min(1),evidenceRowIndex:$.number().int().nonnegative(),evidenceEventIndices:$.array($.number().int().nonnegative()).min(1),sliceLineRange:$.object({startLine:$.number().int().positive(),endLine:$.number().int().positive()}),sliceLineCount:$.number().int().positive(),sliceSha256:$.string().regex(/^[0-9a-f]{64}$/,"sliceSha256 must be 64 lowercase hex chars")}),Rre=$.object({kind:$.literal("pattern-absent"),patternId:ya,detectorVersion:$.string().min(1),rationale:$.string().min(1)}),Cre=$.object({detectorAtGeneration:$.string().min(1),fingerprintAtGeneration:$.string().nullable(),cardOccurrenceCountAtGeneration:$.number().int().nonnegative(),cardLastSeenAtGeneration:$.string().datetime(),generatedBy:$.literal("replay-fixture")}),Are=$.enum(["draft","approved","rejected","superseded"]),Cf=$.object({schemaVersion:$.literal(1),evalCaseId:$.string().regex(/^[a-z0-9][a-z0-9-]*$/,"evalCaseId must be lowercase alphanumeric with hyphens"),cardSlug:$.string().regex(/^[a-z0-9][a-z0-9-]*$/),proposalId:$.string().regex(/^[a-z0-9][a-z0-9-]*$/).nullable(),title:$.string().min(1).max(200),createdAt:$.string().datetime(),kind:$.literal("replay"),replay:xre,assertion:Rre,provenance:Cre,status:Are,notes:$.array(Rf).default([])}),VL=$.object({timestamp:$.string().datetime(),event:$.enum(["created","triaged","superseded"]),evalCaseId:$.string(),cardSlug:$.string(),proposalId:$.string().nullable(),kind:$.literal("replay")}),_re=$.enum(["pass","fail","skipped"]),Pre=$.object({name:$.string().min(1),description:$.string().min(1),status:_re,expected:$.string(),actual:$.string()}),Ire=$.enum(["config-value","observed-behavior","source-symbol","fixture"]),Mre=$.object({kind:Ire,ref:$.string().min(1),detail:$.string()}),YL=$.enum(["pass","fail","unsupported","error"]),ev=$.object({schemaVersion:$.literal(1),evalRunId:$.string().regex(/^[a-z0-9][a-z0-9-]*$/,"evalRunId must be lowercase alphanumeric with hyphens"),evalCaseId:$.string().min(1),cardSlug:$.string().min(1),patternId:ya,contract:$.string().min(1).nullable(),status:YL,createdAt:$.string().datetime(),durationMs:$.number().int().nonnegative(),checks:$.array(Pre),evidence:$.array(Mre),runner:$.object({version:$.string().min(1),mode:$.literal("deterministic")}),notes:$.array(Rf).default([])}),XL=$.object({timestamp:$.string().datetime(),event:$.literal("created"),evalRunId:$.string(),evalCaseId:$.string(),cardSlug:$.string(),patternId:ya,contract:$.string().nullable(),status:YL}),ZL=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 oN(e){let t=wo();kc(t)||eN(t,{recursive:!0});let n=wc(e.slug),r=Sf(e.slug),o=ba(n),s=$re(o,e),i=o===void 0,a=s.evidence.length-(o?.evidence.length??0),l=i?"created":a>0?"updated":"merged-noop",c=vc.parse(s);return Lre(n,c),Nre(r,Ec(c)),Fre({timestamp:Bre(),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 ba(e){if(kc(e))try{let t=Ore(e,"utf-8"),n=JSON.parse(t),r=vc.safeParse(n);return r.success?r.data:void 0}catch{return}}function $re(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=Dre(e.evidence,t.evidence),r=Ure(e.firstSeen,t.observedAt),o=jre(e.lastSeen,t.observedAt),s=Hre(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 Dre(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 Ec(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(`
|
|
2221
2221
|
`)}function Fre(e){let t=zL.parse(e),n=IL(),r=wo();kc(r)||eN(r,{recursive:!0});try{tv(n,JSON.stringify(t)+`
|
|
2222
2222
|
`,{flag:"a"})}catch{}}function Lre(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;tv(n,JSON.stringify(t,null,2)),nN(n,e)}function Nre(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;tv(n,t),nN(n,e)}function Bre(){return new Date().toISOString()}function Ure(e,t){return e<=t?e:t}function jre(e,t){return e>=t?e:t}var QL={low:0,medium:1,high:2};function Hre(e,t){return QL[e]>=QL[t]?e:t}function sN(){let e=wo();if(!kc(e))return[];let t=[];for(let n of tN(e)){if(!n.endsWith(".json")||n.startsWith("."))continue;let r=ba(rN(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 Af(e){return ba(wc(e))}function iN(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 Wre(e){if(e.status!=="resolved"&&e.status!=="deferred")return!1;let t=iN(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 Kre(e){let t=[];for(let n of e){if(!Wre(n))continue;let r=iN(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 aN(){let e=wo();if(!kc(e))return[];let t=[];for(let n of tN(e)){if(!n.endsWith(".json")||n.startsWith("."))continue;let r=ba(rN(e,n));r&&t.push(r)}return Kre(t)}import{existsSync as Gre,mkdirSync as qre,renameSync as lN,writeFileSync as cN}from"fs";import{dirname as zre}from"path";var ks=class extends Error{constructor(n,r){super(r);this.code=n;this.name="TriageError"}code};function uN(e,t){let n=wc(e),r=Sf(e),o=ba(n);if(!o)throw new ks("card-not-found",`No failure card found for slug '${e}'`);if(t.note!==void 0&&t.note.trim().length===0)throw new ks("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 ks("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=vc.parse(d);return Jre(n),Vre(n,p),Yre(r,Ec(p)),{slug:e,card:p,noteAdded:i,statusChanged:a?{from:o.status,to:u}:void 0,jsonPath:n,markdownPath:r}}function Jre(e){let t=zre(e);Gre(t)||qre(t,{recursive:!0})}function Vre(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;cN(n,JSON.stringify(t,null,2)),lN(n,e)}function Yre(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;cN(n,t),lN(n,e)}var Xre={"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(`
|
|
2223
2223
|
`),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(`
|
|
@@ -2225,11 +2225,11 @@ or "latest" (the default) \u2014 the most recently written trace.`).option("--al
|
|
|
2225
2225
|
`)},likelyFiles:[{path:"src/agent/tools/dispatcher.ts",rationale:"Tool dispatch core. Every isError: true path goes through here: hook block, permission denied, handler throw, unknown tool. Read this to understand which class each failure falls into.",riskTier:"high",confidence:"medium"},{path:"src/agent/tools/handlers/",rationale:"Tool handlers. If a specific handler is buggy, the fix lives in the handler file matching the tool name (e.g. handlers/bash.ts for the Bash tool).",riskTier:"moderate",confidence:"medium"},{path:"src/improve/scan/detectors/tool-failure-density.ts",rationale:"If the detector is flagging legitimate isError-as-signal behavior, tune the threshold here or document the tool as expected-failures.",riskTier:"safe",confidence:"low"}],riskFloor:"medium",validationPlan:{unitTests:["pnpm test -- src/improve/scan/detectors/tool-failure-density","pnpm test -- src/agent/tools/dispatcher"],evalCases:[],smokeChecks:["pnpm lint","afk improve scan --only tool-failure-density --since 7d # after fix, failure rate should drop"],manualChecks:["Open the trace at the evidence seqs and read the failure annotations (resultBytes, durationMs).","Inspect the session message history for the actual tool input that triggered the failure.","Decide which of the four root cause classes (handler bug / input shape / permission / detector noise) the failures belong to."]}},"closure-anomaly":{rootCauseClass:"unknown",hypothesis:e=>{let t=typeof e.detail.closureReason=="string"?e.detail.closureReason:"<unknown>",n=typeof e.detail.affectedSessions=="number"?e.detail.affectedSessions:"?",r=typeof e.detail.totalCostUsd=="number"?e.detail.totalCostUsd:null,o=r!==null?` totalling $${r.toFixed(4)}`:"";return`${n} session(s) closed with reason='${t}'${o}. Anomalous closure reasons signal one of: budget mis-configuration, timeout too tight, a hook returning block at the session edge, or an explicit/cascaded abort. The right fix depends on the reason value.`},fixSketch:e=>{let t=typeof e.detail.closureReason=="string"?e.detail.closureReason:"<unknown>",r=(Array.isArray(e.detail.sessionIds)?e.detail.sessionIds:[])[0]??"<session-id>",o=Zre(t);return[`## Closure reason: \`${t}\``,"",o,"","## Diagnostic steps","",`1. Inspect the trace for one of the affected sessions: \`cat ~/.afk/state/witness/${r}/trace.jsonl | tail -20\``,"2. Check the events immediately before the closure \u2014 what was the runtime trying to do?","3. Cross-reference with `~/.afk/agent-framework/routing-decisions.jsonl` for any subagent activity at the same timestamp."].join(`
|
|
2226
2226
|
`)},likelyFiles:[{path:"src/agent/session/agent-session.ts",rationale:"Closure-event emission lives here. Field meanings and the reason classification are owned by this module.",riskTier:"high",confidence:"medium"},{path:"src/agent/session/stream-consumer.ts",rationale:"Budget threshold detection / closure-reason routing. Touch only if the closure CAUSE is here.",riskTier:"high",confidence:"low"},{path:"src/agent/abort-graph.ts",rationale:"Origin tracking for abort-type closures.",riskTier:"moderate",confidence:"low"}],riskFloor:"medium",validationPlan:{unitTests:["pnpm test -- src/agent/session","pnpm test -- src/improve/scan/detectors/closure-anomaly"],evalCases:[],smokeChecks:["pnpm lint"],manualChecks:["Read the closure events at the seqs listed in the evidence.","Confirm the closure reason is correct semantically (not a misclassification)."]}}};function Zre(e){switch(e){case"budget_exceeded":return"The monetary ceiling tripped. Confirm `AFK_MAX_BUDGET_USD` is set to a realistic value for the workload; if so, the LLM call shape (cache use, output cap, model choice) is the next place to look.";case"timeout":return"The wall-clock cap fired. Check whether the timeout is configured too tightly for the workload, or whether a tool call is hanging. Tool-call durations in the same trace will tell you which.";case"hook_blocked":return"A hook returned `decision: 'block'` at the session edge. Cross-reference with any `subagent-block` cards on this scan \u2014 the underlying cause is likely the same handler.";case"abort":return"An explicit or cascaded abort closed the session. If origin is `user_signal`, no action needed. If `cascade`/`budget`/`timeout`, the originating cause is the real issue.";case"iteration_cap":return"Loop iteration ceiling tripped. The model could not make progress in N turns. Either the task is genuinely impossible at that budget, or a tool is in an unproductive loop (cross-reference repeated-tool-use cards).";case"max_turns_exceeded":return"Turn ceiling tripped. Same diagnostic as iteration_cap.";default:return"Reason not in the known anomalous set. Inspect the trace and update the detector if this is a new closure variant."}}function pN(e,t){let n=Xre[e.pattern];if(!n)throw new Error(`template-engine: no template for pattern '${e.pattern}' \u2014 add one to TEMPLATES`);let r=(t.now??(()=>new Date))().toISOString(),o=n.hypothesis(e),s=n.fixSketch(e),i=n.likelyFiles.map(c=>({...c})),a=Qre(n.riskFloor,i),l=e.evidence.map(c=>({cardSlug:e.slug,eventIndices:[...c.eventIndices],...c.annotation!==void 0?{annotation:c.annotation}:{}}));return{schemaVersion:1,proposalId:t.proposalId,cardSlug:e.slug,title:noe(e),hypothesis:o,rootCauseClass:n.rootCauseClass,evidenceRefs:l,fixSketch:s,likelyFiles:i,riskLevel:a,validationPlan:roe(n.validationPlan),scopeFreeze:{forbiddenPaths:[...ZL],requiresExplicitApproval:a==="high"},generatedBy:"template",createdAt:r,status:"draft",notes:[]}}function Qre(e,t){let n=eoe(t);return n==="forbidden"||n==="high"?"high":n==="moderate"?toe(e,"medium"):e}function eoe(e){let t=["safe","moderate","high","forbidden"],n=0;for(let r of e){let o=t.indexOf(r.riskTier);o>n&&(n=o)}return t[n]}var dN={low:0,medium:1,high:2};function toe(e,t){return dN[e]>=dN[t]?e:t}function noe(e){return`Proposal: address ${e.pattern} \u2014 ${e.title}`.slice(0,200)}function roe(e){return{unitTests:[...e.unitTests],evalCases:[...e.evalCases],smokeChecks:[...e.smokeChecks],manualChecks:[...e.manualChecks]}}import{randomBytes as ooe}from"crypto";import{existsSync as _f,mkdirSync as mN,readFileSync as soe,readdirSync as ioe,renameSync as fN,writeFileSync as nv}from"fs";import{join as aoe}from"path";function gN(e){let t=QS.parse(e),n=bs();_f(n)||mN(n,{recursive:!0});let r=VS(t.proposalId),o=$L(t.proposalId);return uoe(r,t),doe(o,Pf(t)),coe({timestamp:new Date().toISOString(),event:"created",proposalId:t.proposalId,cardSlug:t.cardSlug,generatedBy:t.generatedBy,riskLevel:t.riskLevel}),{proposalId:t.proposalId,jsonPath:r,markdownPath:o}}function hN(e,t={}){let n=(t.now??(()=>new Date))(),r=loe(n),o=t.randomSuffix!==void 0?t.randomSuffix():ooe(3).toString("hex");if(!/^[0-9a-f]{6}$/.test(o))throw new Error(`generateProposalId: randomSuffix must be 6 lowercase hex chars (got '${o}')`);return`${e}-${r}-${o}`}function loe(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 Pf(e){let t=[];if(t.push(`# ${e.proposalId} \u2014 \`${e.riskLevel}\` \u2014 \`${e.status}\``),t.push(""),t.push(e.title),t.push(""),t.push(`**Card:** \`${e.cardSlug}\` \xB7 **Root cause class:** \`${e.rootCauseClass}\` \xB7 **Generated by:** \`${e.generatedBy}\` \xB7 **Created:** ${e.createdAt}`),t.push(""),t.push("## Hypothesis"),t.push(""),t.push(e.hypothesis),t.push(""),t.push(e.fixSketch),t.push(""),t.push("## Likely files"),t.push(""),e.likelyFiles.length===0)t.push("_(none suggested by the template)_");else{t.push("| Path | Risk | Confidence | Rationale |"),t.push("| --- | --- | --- | --- |");for(let n of e.likelyFiles){let r=n.path.replace(/\|/g,"\\|"),o=n.rationale.replace(/\n/g," ").replace(/\|/g,"\\|");t.push(`| \`${r}\` | ${n.riskTier} | ${n.confidence} | ${o} |`)}}t.push(""),t.push("## Evidence references"),t.push("");for(let n of e.evidenceRefs)t.push(`- card \`${n.cardSlug}\` \xB7 seqs ${n.eventIndices.join(", ")}${n.annotation?` \xB7 ${n.annotation}`:""}`);t.push(""),t.push("## Validation plan"),t.push(""),t.push("**Unit tests:**"),e.validationPlan.unitTests.length===0&&t.push("- _(none)_");for(let n of e.validationPlan.unitTests)t.push(`- \`${n}\``);if(t.push(""),t.push("**Eval cases:**"),e.validationPlan.evalCases.length===0)t.push(`- _(none \u2014 generate one with \`afk improve eval-gen ${e.cardSlug}\`)_`);else for(let n of e.validationPlan.evalCases)t.push(`- ${n}`);t.push(""),t.push("**Smoke checks:**"),e.validationPlan.smokeChecks.length===0&&t.push("- _(none)_");for(let n of e.validationPlan.smokeChecks)t.push(`- \`${n}\``);t.push(""),t.push("**Manual checks:**"),e.validationPlan.manualChecks.length===0&&t.push("- _(none)_");for(let n of e.validationPlan.manualChecks)t.push(`- ${n}`);t.push(""),t.push("## Scope freeze"),t.push(""),t.push(`**Requires explicit approval:** ${e.scopeFreeze.requiresExplicitApproval?"**yes**":"no"}`),t.push(""),t.push("**Forbidden paths** (never auto-edited by a future `apply`):");for(let n of e.scopeFreeze.forbiddenPaths)t.push(`- \`${n}\``);if(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(`
|
|
2227
2227
|
`)}function yN(){let e=bs();if(!_f(e))return[];let t=[];for(let n of ioe(e)){if(!n.endsWith(".json")||n.startsWith("."))continue;let r=bN(aoe(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 rv(e){return bN(VS(e))}function bN(e){if(_f(e))try{let t=soe(e,"utf-8"),n=JSON.parse(t),r=QS.safeParse(n);return r.success?r.data:void 0}catch{return}}function coe(e){let t=JL.parse(e),n=OL(),r=bs();_f(r)||mN(r,{recursive:!0});try{nv(n,JSON.stringify(t)+`
|
|
2228
|
-
`,{flag:"a"})}catch{}}function uoe(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;nv(n,JSON.stringify(t,null,2)),fN(n,e)}function doe(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;nv(n,t),fN(n,e)}import{createHash as wN}from"crypto";import{existsSync as poe,readFileSync as moe}from"fs";var tn=class extends Error{code;constructor(t,n){super(t),this.name="EvalGenError",this.code=n}};function SN(e,t){if(!poe(e))throw new tn(`replay-fixture: source trace not found: ${e}`,"source-not-found");let n=t.startLine??1;if(n!==1)throw new tn(`replay-fixture: only startLine=1 (prefix slice) is supported in Sprint 3 (got ${n})`,"unsupported-window");let r=moe(e);if(r.length===0)throw new tn(`replay-fixture: source trace is empty: ${e}`,"source-empty");let o=foe(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 tn(`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=wN("sha256").update(c).digest("hex");return{bytes:c,startLine:1,endLine:i,sliceLineCount:i,sliceSha256:u,sourceLineCount:s}}function If(e){return wN("sha256").update(e).digest("hex")}function foe(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 goe}from"crypto";import{existsSync as Mf,mkdirSync as vN,readFileSync as kN,readdirSync as hoe,renameSync as ov,writeFileSync as Of}from"fs";import{join as EN,relative as yoe}from"path";K();function TN(e,t={}){let n=(t.now??(()=>new Date))(),r=boe(n),o=t.randomSuffix!==void 0?t.randomSuffix():goe(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 boe(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 xN(e,t){if(t.evidenceRowIndex<0||t.evidenceRowIndex>=e.evidence.length)throw new tn(`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 tn(`buildEvalCase: evidence row ${t.evidenceRowIndex} has no eventIndices`,"seq-not-found");let r=Math.max(...n.eventIndices),s=(t.resolveTraceAbsPath??woe)(n.tracePath),i=SN(s,{endSeq:r}),a=(t.now??(()=>new Date))().toISOString(),l=XS(t.evalCaseId),c=yoe(
|
|
2228
|
+
`,{flag:"a"})}catch{}}function uoe(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;nv(n,JSON.stringify(t,null,2)),fN(n,e)}function doe(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;nv(n,t),fN(n,e)}import{createHash as wN}from"crypto";import{existsSync as poe,readFileSync as moe}from"fs";var tn=class extends Error{code;constructor(t,n){super(t),this.name="EvalGenError",this.code=n}};function SN(e,t){if(!poe(e))throw new tn(`replay-fixture: source trace not found: ${e}`,"source-not-found");let n=t.startLine??1;if(n!==1)throw new tn(`replay-fixture: only startLine=1 (prefix slice) is supported in Sprint 3 (got ${n})`,"unsupported-window");let r=moe(e);if(r.length===0)throw new tn(`replay-fixture: source trace is empty: ${e}`,"source-empty");let o=foe(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 tn(`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=wN("sha256").update(c).digest("hex");return{bytes:c,startLine:1,endLine:i,sliceLineCount:i,sliceSha256:u,sourceLineCount:s}}function If(e){return wN("sha256").update(e).digest("hex")}function foe(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 goe}from"crypto";import{existsSync as Mf,mkdirSync as vN,readFileSync as kN,readdirSync as hoe,renameSync as ov,writeFileSync as Of}from"fs";import{join as EN,relative as yoe}from"path";K();function TN(e,t={}){let n=(t.now??(()=>new Date))(),r=boe(n),o=t.randomSuffix!==void 0?t.randomSuffix():goe(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 boe(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 xN(e,t){if(t.evidenceRowIndex<0||t.evidenceRowIndex>=e.evidence.length)throw new tn(`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 tn(`buildEvalCase: evidence row ${t.evidenceRowIndex} has no eventIndices`,"seq-not-found");let r=Math.max(...n.eventIndices),s=(t.resolveTraceAbsPath??woe)(n.tracePath),i=SN(s,{endSeq:r}),a=(t.now??(()=>new Date))().toISOString(),l=XS(t.evalCaseId),c=yoe(Le(),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:Soe(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:voe({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 Cf.parse(m),{evalCase:m,sliceBytes:i.bytes}}function woe(e){return EN(Le(),e)}function Soe(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 voe(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 RN(e,t){let n=Cf.parse(e),r=So();Mf(r)||vN(r,{recursive:!0});let o=YS(n.evalCaseId),s=XS(n.evalCaseId),i=FL(n.evalCaseId);xoe(s,t);let a=If(kN(s));if(a!==n.replay.sliceSha256)throw new tn(`writeEvalCase: fixture sha256 mismatch after write (expected ${n.replay.sliceSha256}, got ${a}, path ${s})`,"fixture-mismatch");return Eoe(o,n),Toe(i,$f(n)),koe({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 $f(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(`
|
|
2229
2229
|
`)}function sv(){let e=So();if(!Mf(e))return[];let t=[];for(let n of hoe(e)){if(!n.endsWith(".json")||n.startsWith(".")||n.endsWith(".fixture.jsonl"))continue;let r=AN(EN(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 Df(e){return AN(YS(e))}function CN(e){return sv().filter(t=>t.cardSlug===e).map(t=>Df(t.evalCaseId)).filter(t=>t!==void 0)}function AN(e){if(Mf(e))try{let t=kN(e,"utf-8"),n=JSON.parse(t),r=Cf.safeParse(n);return r.success?r.data:void 0}catch{return}}function koe(e){let t=VL.parse(e),n=DL(),r=So();Mf(r)||vN(r,{recursive:!0});try{Of(n,JSON.stringify(t)+`
|
|
2230
|
-
`,{flag:"a"})}catch{}}function Eoe(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;Of(n,JSON.stringify(t,null,2)),ov(n,e)}function Toe(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;Of(n,t),ov(n,e)}function xoe(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;Of(n,t),ov(n,e)}import{randomBytes as Koe}from"crypto";import{existsSync as dv,mkdirSync as jN,readFileSync as Goe,readdirSync as
|
|
2230
|
+
`,{flag:"a"})}catch{}}function Eoe(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;Of(n,JSON.stringify(t,null,2)),ov(n,e)}function Toe(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;Of(n,t),ov(n,e)}function xoe(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;Of(n,t),ov(n,e)}import{randomBytes as Koe}from"crypto";import{existsSync as dv,mkdirSync as jN,readFileSync as Goe,readdirSync as tze,renameSync as HN,writeFileSync as pv}from"fs";import{join as qoe}from"path";K();Wa();gy();np();var _N=400;function Wt(e){let n=(typeof e=="string"?e:String(e)).replace(/\s+/g," ").trim();return n.length>_N?n.slice(0,_N-1)+"\u2026":n}function ve(e){return{name:e.name,description:e.description,status:e.status??(e.pass?"pass":"fail"),expected:Wt(e.expected),actual:Wt(e.actual)}}var Tc="eval_run_probe_tool";async function Roe(){let e=qs,t=0,n=async()=>(t+=1,{content:"probe-ok"}),r=new Ot({handlers:new Map([[Tc,n]]),schemas:[],hookRegistry:void 0,permissions:{allowedTools:[Tc]}}),o=new AbortController().signal,s=h=>({id:"eval-run-probe",name:Tc,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=[ve({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`}),ve({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`}),ve({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(Tc),expected:`mentions "circuit breaker" and the tool name "${Tc}"`,actual:c.content}),ve({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 Coe(){let n=Rd(3,3);return{checks:[ve({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}),ve({name:"recovery-hint-present",description:"Refusal carries the recovery hint clause",pass:n.includes(li),expected:"contains SKILL_MAX_DEPTH_RECOVERY_HINT",actual:n}),ve({name:"hint-directs-inline-work",description:"Hint tells the model to work inline instead of delegating further",pass:/perform the work inline/i.test(li)&&/skill\/agent\/compose/i.test(li),expected:'hint mentions "perform the work inline" and "skill/agent/compose"',actual:li})],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 Es="tool-failure-density",bn="flaky_tool",wa="refusal_only_tool",Sa="tool-failure-flaky-tool",Aoe="tool-failure-refusal-only-tool";async function _oe(){let e=GL(),t=ha(),n=[ve({name:"in-default-enabled-set",description:`${Es} runs in a default scan`,pass:e.includes(Es),expected:`defaultEnabledDetectorNames() includes "${Es}"`,actual:`[${e.join(", ")}]`}),ve({name:"not-opt-in",description:`${Es} is not in the disabled-by-default set`,pass:!t.includes(Es),expected:`disabledByDefaultDetectorNames() excludes "${Es}"`,actual:`[${t.join(", ")}]`})],r=[{kind:"config-value",ref:"DETECTOR_REGISTRY['tool-failure-density'].enabledByDefault",detail:String(e.includes(Es))}];return{checks:n,evidence:r}}function ft(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 iv(e,t){let n=`state/witness/${e}/trace.jsonl`;return fa({sessionId:e,tracePath:n,relativeTracePath:n,content:t.join(`
|
|
2231
2231
|
`)+`
|
|
2232
|
-
`,sessionMtimeMs:0})}function Poe(){let e=iv("tfd-sess-a",[ft(0,bn,{isError:!1}),ft(1,bn,{isError:!0,failureClass:"timeout"}),ft(2,bn,{isError:!0}),ft(3,bn,{isError:!0,failureClass:"policy-refusal"}),ft(4,bn,{isError:!0,circuitBreaker:!0})]),t=iv("tfd-sess-b",[ft(0,bn,{isError:!0}),ft(1,bn,{isError:!1}),ft(2,bn,{isError:!0,failureClass:"permission-denied"}),ft(3,bn,{isError:!0,failureClass:"abort"}),ft(4,bn,{isError:!0,failureClass:"hook-block"}),ft(5,bn,{isError:!0,failureClass:"elicitation-declined"})]),n=iv("tfd-sess-c",[ft(0,wa,{isError:!1}),ft(1,wa,{isError:!0,failureClass:"policy-refusal"}),ft(2,wa,{isError:!0,failureClass:"policy-refusal"}),ft(3,wa,{isError:!0,failureClass:"permission-denied"}),ft(4,wa,{isError:!0,failureClass:"hook-block"}),ft(5,wa,{isError:!0,failureClass:"abort"})]);return[e,t,n]}function Ff(e,t){let n=e[t];return typeof n=="number"?n:void 0}function av(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 PN(e,t){let n=av(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 Ioe(e){return Array.isArray(e)?e.filter(t=>typeof t=="number"):[]}function Moe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Ooe(){let e=Poe(),t=ga(e,{}),n=t.find(T=>T.slug===Sa),r=t.find(T=>T.slug===Aoe),o=n?.detail??{},s=Ff(o,"failureCount"),i=Ff(o,"totalCalls"),a=Ff(o,"failureRate"),l=Ff(o,"affectedSessionCount"),c=av(o.failureClassBreakdown),u=av(o.excludedByClass),d=Moe(o.sessionIds).slice().sort(),p=Ioe(o.seqs),m=ga(e,{minFailures:4}),g=ga(e,{minFailureRate:.7}),h=!m.some(T=>T.slug===Sa),b=!g.some(T=>T.slug===Sa),y={"policy-refusal":1,"permission-denied":1,abort:1,"hook-block":1,"elicitation-declined":1},S={timeout:1,unclassified:2},w=[ve({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 '${Sa}' with failureCount=3, totalCalls=5, failureRate=0.6`,actual:n===void 0?`no '${Sa}' card; ${t.length} card(s): [${t.map(T=>T.slug).join(", ")}]`:`${t.length} card(s); failureCount=${s}, totalCalls=${i}, failureRate=${a}`}),ve({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:PN(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"}`}),ve({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(", ")}]`}),ve({name:"classification-counts-timeout-and-unclassified",description:"timeout and unclassified (no failureClass) failures DO count toward the failure stats",pass:PN(c,S),expected:"failureClassBreakdown={timeout:1,unclassified:2}",actual:`failureClassBreakdown=${JSON.stringify(c)}`}),ve({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"}`}),ve({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(",")}]`})],k=[{kind:"source-symbol",ref:"src/improve/scan/detectors/tool-failure-density.ts#detectToolFailureDensity",detail:n===void 0?`synthetic corpus \u2192 ${t.length} card(s); '${Sa}' 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:k}}async function $oe(){let e=await _oe(),t=Ooe();return{checks:[...e.checks,...t.checks],evidence:[...e.evidence,...t.evidence]}}async function Doe(){let e=Ko("abort"),t=Ko("model_end_turn"),n=[ve({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)":Wt(e)}),ve({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":Wt(e)}),ve({name:"guidance-is-the-canonical-constant",description:"The wired hint is the exported CLOSURE_ABORT_RECOVERY_HINT (no drift)",pass:e===hb,expected:'buildClosureGuidance("abort") === CLOSURE_ABORT_RECOVERY_HINT',actual:e===null?"null":Wt(e)}),ve({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":Wt(t)})],r=[{kind:"source-symbol",ref:"src/agent/session/closure-guidance.ts#buildClosureGuidance",detail:e===null?"null":Wt(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 lv=Object.freeze([{id:"repeat-loop-circuit-breaker",patternId:"repeated-tool-use",title:"Repeat-loop circuit breaker trips at the consecutive-identical threshold",run:Roe},{id:"skill-max-depth-recovery-hint",patternId:"subagent-block",title:"Skill max-depth refusal carries an actionable recovery hint",run:Coe},{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:$oe},{id:"closure-abort-recovery-hint",patternId:"closure-anomaly",title:"Anomalous abort closure carries an actionable recovery hint",run:Doe}]);function IN(e){return lv.find(t=>t.patternId===e)}function MN(){return lv.map(e=>e.patternId)}function ON(){return lv.map(e=>e.id)}Wa();np();var Nf="replay:",$N=`${Nf}fixture-reproduces-pattern`,NN=`${Nf}guardrail-neutralizes-recorded-loop`,DN=`${Nf}fixture-reproduces-closure-anomaly`,BN=`${Nf}guardrail-guides-recorded-closure`,FN="The committed fixture still reproduces the recorded repeated-tool-use loop when re-scanned by the detector",Foe=Object.freeze({replay:"byte-identical-input"}),Loe=async(e,t)=>{let n=async()=>({content:"replay-probe-ok"}),r=new Ot({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:Foe,signal:o},c=await r.execute(l);if(i=a,c.circuitBreaker===!0){s=a;break}}return{trippedAtCall:s,callsDriven:i}};function Lf(e){let t=e.detail.runLength;return typeof t=="number"?t:0}async function Noe(e,t,n){let r=[],o=[],s=t.toString("utf8"),i=fa({sessionId:e.replay.sourceSessionId,tracePath:e.replay.sourceTracePath,relativeTracePath:e.replay.sourceTracePath,content:s,sessionMtimeMs:0}),a=vf([i],{minRepeats:Ar}),l=e.provenance.fingerprintAtGeneration,c=l?a.find(S=>S.detail.fingerprint===l):void 0,u=[...a].sort((S,w)=>Lf(w)-Lf(S))[0],d=c??u;if(d===void 0)return r.push(ve({name:$N,description:FN,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(ve({name:$N,description:FN,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${Lf(d)}`}));let p=String(d.detail.toolName),m=Lf(d),g=n.driveLoop??Loe,h=Math.min(m,qs),b=await g(p,h),y=b.trippedAtCall!==null&&b.trippedAtCall<=m;return r.push(ve({name:NN,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 ${qs})`},{kind:"fixture",ref:e.replay.fixturePath,detail:`replayed recorded loop on '${p}' (run length ${m})`}),{checks:r,evidence:o}}function Boe(e){let t=e.detail.closureReason;return typeof t=="string"?t:null}function Uoe(e){let t=e.detail.seqs;return Array.isArray(t)?t.filter(n=>typeof n=="number"):[]}var LN="The committed fixture still reproduces the recorded anomalous closure when re-scanned by the detector";async function joe(e,t,n){let r=[],o=[],s=t.toString("utf8"),i=fa({sessionId:e.replay.sourceSessionId,tracePath:e.replay.sourceTracePath,relativeTracePath:e.replay.sourceTracePath,content:s,sessionMtimeMs:0}),a=kf([i],{minOccurrences:1}),l=Math.max(...e.replay.evidenceEventIndices),u=a.find(h=>Uoe(h).includes(l))??a[0];if(u===void 0)return r.push(ve({name:DN,description:LN,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=Boe(u)??"";r.push(ve({name:DN,description:LN,pass:!0,expected:"detector finds \u22651 anomalous closure in the fixture",actual:`found closure.reason='${d}' (seq ${l})`}));let m=(n.buildGuidance??Ko)(d),g=m!==null&&m.trim().length>0;return r.push(ve({name:BN,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?Wt(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 Hoe=Object.freeze([{patternId:"repeated-tool-use",run:Noe},{patternId:"closure-anomaly",run:joe}]),Woe=[NN,BN];function cv(e){return Woe.includes(e)}function UN(e){return Hoe.find(t=>t.patternId===e)}var zoe="eval-run@v1";function WN(e,t={}){let n=(t.now??(()=>new Date))(),r=Joe(n),o=t.randomSuffix!==void 0?t.randomSuffix():Koe(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 Joe(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 KN(e,t){let r=(t.now??(()=>new Date))().toISOString(),o=t.clockMs??(()=>Date.now()),s=o(),i=[],a=[],l=[],c=Yoe(e,t);i.push(c.check),c.evidence&&a.push(c.evidence);let u=IN(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: ${MN().join(", ")}.`});else{d=u.id;try{let k=await u.run();i.push(...k.checks),a.push(...k.evidence)}catch(k){p=!0;let T=k instanceof Error?k.message:String(k);l.push({at:r,text:`Contract '${u.id}' threw during execution: ${Wt(T)}`})}}let m=UN(e.assertion.patternId),g=!1;if(m&&c.bytes!==void 0&&c.check.status==="pass")try{let k=await m.run(e,c.bytes,{...t.driveLoop?{driveLoop:t.driveLoop}:{}});i.push(...k.checks),a.push(...k.evidence),g=!0}catch(k){p=!0;let T=k instanceof Error?k.message:String(k);l.push({at:r,text:`Fixture-replay for '${e.assertion.patternId}' threw during execution: ${Wt(T)}`})}let h=i.some(k=>cv(k.name)),b=m!==void 0&&c.check.status==="pass"&&g&&!h,y=Voe({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:zoe,mode:"deterministic"},notes:l};return ev.parse(w),w}function Voe(e){return e.contractThrew?"error":e.checks.some(t=>t.status==="fail")?"fail":!e.hasContract||e.replayInconclusive===!0?"unsupported":"pass"}function Yoe(e,t){let r=(t.resolveFixtureAbsPath??(u=>qoe(Fe(),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(!dv(r))return{check:ve({name:s,description:i,pass:!1,expected:`fixture present at ${e.replay.fixturePath}`,actual:"fixture file not found on disk"})};let a;try{a=Goe(r)}catch(u){let d=u instanceof Error?u.message:String(u);return{check:ve({name:s,description:i,pass:!1,expected:`readable fixture (${o})`,actual:`read error: ${Wt(d)}`})}}let l=If(a),c=l===o;return{check:ve({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 GN(e){let t=ev.parse(e),n=ma();dv(n)||jN(n,{recursive:!0});let r=NL(t.evalRunId),o=BL(t.evalRunId);return ese(r,t),tse(o,mv(t)),Qoe({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 Xoe={pass:"\u2713 PASS",fail:"\u2717 FAIL",unsupported:"\u2013 UNSUPPORTED",error:"\u26A0 ERROR"},Zoe={pass:"\u2713",fail:"\u2717",skipped:"\u2013"};function mv(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=>cv(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: ${Xoe[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(`| ${uv(i.name)} | ${Zoe[i.status]} ${i.status} | ${uv(i.expected)} | ${uv(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
|
+
`,sessionMtimeMs:0})}function Poe(){let e=iv("tfd-sess-a",[ft(0,bn,{isError:!1}),ft(1,bn,{isError:!0,failureClass:"timeout"}),ft(2,bn,{isError:!0}),ft(3,bn,{isError:!0,failureClass:"policy-refusal"}),ft(4,bn,{isError:!0,circuitBreaker:!0})]),t=iv("tfd-sess-b",[ft(0,bn,{isError:!0}),ft(1,bn,{isError:!1}),ft(2,bn,{isError:!0,failureClass:"permission-denied"}),ft(3,bn,{isError:!0,failureClass:"abort"}),ft(4,bn,{isError:!0,failureClass:"hook-block"}),ft(5,bn,{isError:!0,failureClass:"elicitation-declined"})]),n=iv("tfd-sess-c",[ft(0,wa,{isError:!1}),ft(1,wa,{isError:!0,failureClass:"policy-refusal"}),ft(2,wa,{isError:!0,failureClass:"policy-refusal"}),ft(3,wa,{isError:!0,failureClass:"permission-denied"}),ft(4,wa,{isError:!0,failureClass:"hook-block"}),ft(5,wa,{isError:!0,failureClass:"abort"})]);return[e,t,n]}function Ff(e,t){let n=e[t];return typeof n=="number"?n:void 0}function av(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 PN(e,t){let n=av(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 Ioe(e){return Array.isArray(e)?e.filter(t=>typeof t=="number"):[]}function Moe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Ooe(){let e=Poe(),t=ga(e,{}),n=t.find(T=>T.slug===Sa),r=t.find(T=>T.slug===Aoe),o=n?.detail??{},s=Ff(o,"failureCount"),i=Ff(o,"totalCalls"),a=Ff(o,"failureRate"),l=Ff(o,"affectedSessionCount"),c=av(o.failureClassBreakdown),u=av(o.excludedByClass),d=Moe(o.sessionIds).slice().sort(),p=Ioe(o.seqs),m=ga(e,{minFailures:4}),g=ga(e,{minFailureRate:.7}),h=!m.some(T=>T.slug===Sa),b=!g.some(T=>T.slug===Sa),y={"policy-refusal":1,"permission-denied":1,abort:1,"hook-block":1,"elicitation-declined":1},S={timeout:1,unclassified:2},w=[ve({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 '${Sa}' with failureCount=3, totalCalls=5, failureRate=0.6`,actual:n===void 0?`no '${Sa}' card; ${t.length} card(s): [${t.map(T=>T.slug).join(", ")}]`:`${t.length} card(s); failureCount=${s}, totalCalls=${i}, failureRate=${a}`}),ve({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:PN(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"}`}),ve({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(", ")}]`}),ve({name:"classification-counts-timeout-and-unclassified",description:"timeout and unclassified (no failureClass) failures DO count toward the failure stats",pass:PN(c,S),expected:"failureClassBreakdown={timeout:1,unclassified:2}",actual:`failureClassBreakdown=${JSON.stringify(c)}`}),ve({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"}`}),ve({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(",")}]`})],k=[{kind:"source-symbol",ref:"src/improve/scan/detectors/tool-failure-density.ts#detectToolFailureDensity",detail:n===void 0?`synthetic corpus \u2192 ${t.length} card(s); '${Sa}' 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:k}}async function $oe(){let e=await _oe(),t=Ooe();return{checks:[...e.checks,...t.checks],evidence:[...e.evidence,...t.evidence]}}async function Doe(){let e=Ko("abort"),t=Ko("model_end_turn"),n=[ve({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)":Wt(e)}),ve({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":Wt(e)}),ve({name:"guidance-is-the-canonical-constant",description:"The wired hint is the exported CLOSURE_ABORT_RECOVERY_HINT (no drift)",pass:e===hb,expected:'buildClosureGuidance("abort") === CLOSURE_ABORT_RECOVERY_HINT',actual:e===null?"null":Wt(e)}),ve({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":Wt(t)})],r=[{kind:"source-symbol",ref:"src/agent/session/closure-guidance.ts#buildClosureGuidance",detail:e===null?"null":Wt(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 lv=Object.freeze([{id:"repeat-loop-circuit-breaker",patternId:"repeated-tool-use",title:"Repeat-loop circuit breaker trips at the consecutive-identical threshold",run:Roe},{id:"skill-max-depth-recovery-hint",patternId:"subagent-block",title:"Skill max-depth refusal carries an actionable recovery hint",run:Coe},{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:$oe},{id:"closure-abort-recovery-hint",patternId:"closure-anomaly",title:"Anomalous abort closure carries an actionable recovery hint",run:Doe}]);function IN(e){return lv.find(t=>t.patternId===e)}function MN(){return lv.map(e=>e.patternId)}function ON(){return lv.map(e=>e.id)}Wa();np();var Nf="replay:",$N=`${Nf}fixture-reproduces-pattern`,NN=`${Nf}guardrail-neutralizes-recorded-loop`,DN=`${Nf}fixture-reproduces-closure-anomaly`,BN=`${Nf}guardrail-guides-recorded-closure`,FN="The committed fixture still reproduces the recorded repeated-tool-use loop when re-scanned by the detector",Foe=Object.freeze({replay:"byte-identical-input"}),Loe=async(e,t)=>{let n=async()=>({content:"replay-probe-ok"}),r=new Ot({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:Foe,signal:o},c=await r.execute(l);if(i=a,c.circuitBreaker===!0){s=a;break}}return{trippedAtCall:s,callsDriven:i}};function Lf(e){let t=e.detail.runLength;return typeof t=="number"?t:0}async function Noe(e,t,n){let r=[],o=[],s=t.toString("utf8"),i=fa({sessionId:e.replay.sourceSessionId,tracePath:e.replay.sourceTracePath,relativeTracePath:e.replay.sourceTracePath,content:s,sessionMtimeMs:0}),a=vf([i],{minRepeats:Ar}),l=e.provenance.fingerprintAtGeneration,c=l?a.find(S=>S.detail.fingerprint===l):void 0,u=[...a].sort((S,w)=>Lf(w)-Lf(S))[0],d=c??u;if(d===void 0)return r.push(ve({name:$N,description:FN,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(ve({name:$N,description:FN,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${Lf(d)}`}));let p=String(d.detail.toolName),m=Lf(d),g=n.driveLoop??Loe,h=Math.min(m,qs),b=await g(p,h),y=b.trippedAtCall!==null&&b.trippedAtCall<=m;return r.push(ve({name:NN,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 ${qs})`},{kind:"fixture",ref:e.replay.fixturePath,detail:`replayed recorded loop on '${p}' (run length ${m})`}),{checks:r,evidence:o}}function Boe(e){let t=e.detail.closureReason;return typeof t=="string"?t:null}function Uoe(e){let t=e.detail.seqs;return Array.isArray(t)?t.filter(n=>typeof n=="number"):[]}var LN="The committed fixture still reproduces the recorded anomalous closure when re-scanned by the detector";async function joe(e,t,n){let r=[],o=[],s=t.toString("utf8"),i=fa({sessionId:e.replay.sourceSessionId,tracePath:e.replay.sourceTracePath,relativeTracePath:e.replay.sourceTracePath,content:s,sessionMtimeMs:0}),a=kf([i],{minOccurrences:1}),l=Math.max(...e.replay.evidenceEventIndices),u=a.find(h=>Uoe(h).includes(l))??a[0];if(u===void 0)return r.push(ve({name:DN,description:LN,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=Boe(u)??"";r.push(ve({name:DN,description:LN,pass:!0,expected:"detector finds \u22651 anomalous closure in the fixture",actual:`found closure.reason='${d}' (seq ${l})`}));let m=(n.buildGuidance??Ko)(d),g=m!==null&&m.trim().length>0;return r.push(ve({name:BN,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?Wt(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 Hoe=Object.freeze([{patternId:"repeated-tool-use",run:Noe},{patternId:"closure-anomaly",run:joe}]),Woe=[NN,BN];function cv(e){return Woe.includes(e)}function UN(e){return Hoe.find(t=>t.patternId===e)}var zoe="eval-run@v1";function WN(e,t={}){let n=(t.now??(()=>new Date))(),r=Joe(n),o=t.randomSuffix!==void 0?t.randomSuffix():Koe(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 Joe(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 KN(e,t){let r=(t.now??(()=>new Date))().toISOString(),o=t.clockMs??(()=>Date.now()),s=o(),i=[],a=[],l=[],c=Yoe(e,t);i.push(c.check),c.evidence&&a.push(c.evidence);let u=IN(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: ${MN().join(", ")}.`});else{d=u.id;try{let k=await u.run();i.push(...k.checks),a.push(...k.evidence)}catch(k){p=!0;let T=k instanceof Error?k.message:String(k);l.push({at:r,text:`Contract '${u.id}' threw during execution: ${Wt(T)}`})}}let m=UN(e.assertion.patternId),g=!1;if(m&&c.bytes!==void 0&&c.check.status==="pass")try{let k=await m.run(e,c.bytes,{...t.driveLoop?{driveLoop:t.driveLoop}:{}});i.push(...k.checks),a.push(...k.evidence),g=!0}catch(k){p=!0;let T=k instanceof Error?k.message:String(k);l.push({at:r,text:`Fixture-replay for '${e.assertion.patternId}' threw during execution: ${Wt(T)}`})}let h=i.some(k=>cv(k.name)),b=m!==void 0&&c.check.status==="pass"&&g&&!h,y=Voe({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:zoe,mode:"deterministic"},notes:l};return ev.parse(w),w}function Voe(e){return e.contractThrew?"error":e.checks.some(t=>t.status==="fail")?"fail":!e.hasContract||e.replayInconclusive===!0?"unsupported":"pass"}function Yoe(e,t){let r=(t.resolveFixtureAbsPath??(u=>qoe(Le(),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(!dv(r))return{check:ve({name:s,description:i,pass:!1,expected:`fixture present at ${e.replay.fixturePath}`,actual:"fixture file not found on disk"})};let a;try{a=Goe(r)}catch(u){let d=u instanceof Error?u.message:String(u);return{check:ve({name:s,description:i,pass:!1,expected:`readable fixture (${o})`,actual:`read error: ${Wt(d)}`})}}let l=If(a),c=l===o;return{check:ve({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 GN(e){let t=ev.parse(e),n=ma();dv(n)||jN(n,{recursive:!0});let r=NL(t.evalRunId),o=BL(t.evalRunId);return ese(r,t),tse(o,mv(t)),Qoe({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 Xoe={pass:"\u2713 PASS",fail:"\u2717 FAIL",unsupported:"\u2013 UNSUPPORTED",error:"\u26A0 ERROR"},Zoe={pass:"\u2713",fail:"\u2717",skipped:"\u2013"};function mv(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=>cv(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: ${Xoe[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(`| ${uv(i.name)} | ${Zoe[i.status]} ${i.status} | ${uv(i.expected)} | ${uv(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(`
|
|
2233
2233
|
`)}function uv(e){return e.replace(/\|/g,"\\|").replace(/\n/g," ")}function Qoe(e){let t=XL.parse(e),n=ma();dv(n)||jN(n,{recursive:!0});try{pv(LL(),JSON.stringify(t)+`
|
|
2234
2234
|
`,{flag:"a"})}catch{}}function ese(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;pv(n,JSON.stringify(t,null,2)),HN(n,e)}function tse(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;pv(n,t),HN(n,e)}var fv=["open","deferred","resolved"],gv=["draft","approved","rejected","superseded"],hv=["repeated-tool-use","subagent-block","closure-anomaly"];function qN(e){let t=e.command("improve").description("Self-improvement pipeline: scan traces, triage cards, draft proposals, generate replay eval-cases.");nse(t),ose(t),sse(t),ise(t),ase(t),lse(t),cse(t)}function nse(e){e.command("scan").description(`Run registered detectors against witness traces. Dry-run by default.
|
|
2235
2235
|
Some detectors are disabled by default (pass --include-disabled to enable): ${ha().join(", ")}.`).option("--since <duration>","Only scan sessions newer than this (e.g. 7d, 24h, all)","7d").option("--write","Persist failure cards to disk. Without this flag, scan is dry-run.",!1).option("--min-repeats <n>",`repeated-tool-use threshold (default ${Ar})`,String(Ar)).option("--closure-min-occurrences <n>",`closure-anomaly threshold (default ${1})`,String(1)).option("--block-min-occurrences <n>",`subagent-block threshold (default ${ws})`,String(ws)).option("--tool-failure-min-failures <n>",`tool-failure-density absolute count threshold (default ${Ss})`,String(Ss)).option("--tool-failure-min-rate <rate>",`tool-failure-density rate threshold, 0\u20131 (default ${vs})`,String(vs)).option("--only <names>",`Comma-separated detector names to run (any of: ${Tf().join(", ")})`).option("--include-disabled",`Run detectors marked disabled-by-default (currently: ${ha().join(", ")})`,!1).action(t=>{try{let n=Bf(t.minRepeats,"min-repeats",2),r=Bf(t.closureMinOccurrences,"closure-min-occurrences",1),o=Bf(t.blockMinOccurrences,"block-min-occurrences",1),s=Bf(t.toolFailureMinFailures,"tool-failure-min-failures",1),i=dse(t.toolFailureMinRate,"tool-failure-min-rate"),a;if(t.only){let y=t.only.split(",").map(k=>k.trim()).filter(k=>k.length>0),S=new Set(Tf()),w=y.filter(k=>!S.has(k));w.length>0&&(console.error(`Unknown detector(s): ${w.join(", ")}. Known: ${Tf().join(", ")}`),process.exit(2)),a=new Set(y)}let l;if(t.since&&t.since!=="all"){let y=UL(t.since);y===void 0&&(console.error(`Invalid --since: '${t.since}'. Use forms like '7d', '24h', '30m', '3600s', or 'all'.`),process.exit(2)),l=Date.now()-y}let c=jL({sinceMs:l}),u={minRepeats:n,closureAnomalyMinOccurrences:r,subagentBlockMinOccurrences:o,toolFailureMinFailures:s,toolFailureMinRate:i},d=KL(c.sessions,u,a,t.includeDisabled);console.log(`Scanned ${c.sessionsScanned} sessions`),c.sessionsSkippedOld>0&&console.log(` \u21B3 skipped ${c.sessionsSkippedOld} older than --since`),c.sessionsSkippedEmpty>0&&console.log(` \u21B3 skipped ${c.sessionsSkippedEmpty} with missing/unreadable trace.jsonl`),c.invalidLineCount>0&&console.log(` \u26A0 ${c.invalidLineCount} invalid JSONL lines skipped`);let p=ha();!t.only&&!t.includeDisabled&&p.length>0&&console.log(`Skipped ${p.length} detectors (disabled by default \u2014 pass --only or --include-disabled): ${p.join(", ")}`);let m=new Map;for(let y of d)m.set(y.pattern,(m.get(y.pattern)??0)+1);console.log(`Detections: ${d.length}`);for(let[y,S]of m.entries())console.log(` \u21B3 ${y}: ${S}`);if(d.length===0){t.write&&console.log("No cards written.");return}for(let y of d)console.log(` \u2022 ${y.slug} [${y.severity}] ${y.pattern} evidence=${y.evidence.length}`);if(!t.write){console.log(""),console.log("(dry-run \u2014 pass --write to persist cards)");return}let g=0,h=0,b=0;for(let y of d){let S=oN(y);S.event==="created"?g+=1:S.event==="updated"?h+=1:b+=1}console.log(""),console.log(`Wrote cards: ${g} created, ${h} updated, ${b} no-op merges.`)}catch(n){z(n)}})}function rse(e){let t=aN();if(e.pattern&&(t=t.filter(o=>o.pattern===e.pattern)),e.severity&&(t=t.filter(o=>o.severity===e.severity)),e.status&&(t=t.filter(o=>o.status===e.status)),e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log("No regressed cards found (no resolved/deferred card has fired since its latest triage note).");return}let n="SLUG | PATTERN | SEV | STATUS | N | LAST SEEN | LATEST NOTE",r="-".repeat(n.length);console.log(`${t.length} regressed card(s): triaged, then fired again afterwards.`),console.log(n),console.log(r);for(let o of t)console.log([o.slug.padEnd(50).slice(0,50),o.pattern.padEnd(20),o.severity.padEnd(6),o.status.padEnd(9),String(o.occurrenceCount).padEnd(4),o.lastSeen.padEnd(24),o.latestNoteAt].join(" | "))}function ose(e){let t=e.command("cards").description("Inspect and triage failure cards written by `afk improve scan`");t.command("list").description("List all failure cards, newest first").option("--pattern <name>","Filter by pattern name").option("--severity <level>","Filter by severity: low | medium | high").option("--status <state>","Filter by status: open | deferred | resolved").option("--regressed","Only show resolved/deferred cards that fired again after their latest triage note",!1).option("--json","Emit JSON instead of a table",!1).action(n=>{try{if(n.regressed){rse(n);return}let r=sN();if(n.pattern&&(r=r.filter(i=>i.pattern===n.pattern)),n.severity&&(r=r.filter(i=>i.severity===n.severity)),n.status&&(r=r.filter(i=>i.status===n.status)),n.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log("No failure cards found.");return}let o="SLUG | PATTERN | SEV | STATUS | N | LAST SEEN",s="-".repeat(o.length);console.log(o),console.log(s);for(let i of r)console.log([i.slug.padEnd(50).slice(0,50),i.pattern.padEnd(20),i.severity.padEnd(6),i.status.padEnd(9),String(i.occurrenceCount).padEnd(4),i.lastSeen].join(" | "))}catch(r){z(r)}}),t.command("show <slug>").description("Print a failure card by slug").option("--json","Emit raw JSON instead of rendered markdown",!1).action((n,r)=>{try{let o=Af(n);if(o||(console.error(`Card not found: ${n}`),process.exit(1)),r.json){console.log(JSON.stringify(o,null,2));return}console.log(Ec(o))}catch(o){z(o)}}),t.command("triage <slug>").description("Append a human note and/or change status on a failure card").option("--note <text>","Note text to append (non-empty)").option("--status <state>",`New status (one of: ${fv.join(", ")})`).option("--json","Emit the resulting card as JSON",!1).action((n,r)=>{try{let o;r.status!==void 0&&(fv.includes(r.status)||(console.error(`Invalid --status: '${r.status}'. Must be one of: ${fv.join(", ")}`),process.exit(2)),o=r.status);let s=uN(n,{...r.note!==void 0?{note:r.note}:{},...o!==void 0?{status:o}:{}});if(r.json){console.log(JSON.stringify(s.card,null,2));return}let i=[];s.noteAdded&&i.push("note appended"),s.statusChanged&&i.push(`status: ${s.statusChanged.from} \u2192 ${s.statusChanged.to}`),console.log(`Triaged ${n}: ${i.join(" \xB7 ")}`),console.log(` json: ${s.jsonPath}`),console.log(` md: ${s.markdownPath}`)}catch(o){o instanceof ks&&(console.error(`triage failed [${o.code}]: ${o.message}`),process.exit(o.code==="card-not-found"?1:2)),z(o)}})}function sse(e){e.command("propose <slug>").description("Generate a template-mode improvement proposal for a failure card. No LLM calls.").option("--id <override>","Override the auto-generated proposal id").option("--json","Emit the proposal JSON to stdout (still writes to disk)",!1).option("--no-write","Render the proposal without persisting to disk (preview mode)").action((t,n)=>{try{let r=Af(t);r||(console.error(`Card not found: ${t}`),process.exit(1));let o=n.id??hN(t),s=pN(r,{proposalId:o});if(n.write===!1){n.json?console.log(JSON.stringify(s,null,2)):(console.log("(preview \u2014 not persisted; remove --no-write to save)"),console.log(""),console.log(Pf(s)));return}let i=gN(s);if(n.json){console.log(JSON.stringify({...s,_paths:i},null,2));return}console.log(`Wrote proposal: ${i.proposalId}`),console.log(` json: ${i.jsonPath}`),console.log(` md: ${i.markdownPath}`),console.log(` risk: ${s.riskLevel} \xB7 root cause: ${s.rootCauseClass} \xB7 approval required: ${s.scopeFreeze.requiresExplicitApproval?"yes":"no"}`)}catch(r){z(r)}})}function ise(e){let t=e.command("proposals").description("Inspect improvement proposals on disk");t.command("list").description("List all proposals, newest first").option("--card <slug>","Filter by card slug").option("--risk <level>","Filter by risk: low | medium | high").option("--json","Emit JSON instead of a table",!1).action(n=>{try{let r=yN();if(n.card&&(r=r.filter(i=>i.cardSlug===n.card)),n.risk&&(r=r.filter(i=>i.riskLevel===n.risk)),n.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log("No proposals found.");return}let o="PROPOSAL ID | CARD | RISK | STATUS | CREATED",s="-".repeat(o.length);console.log(o),console.log(s);for(let i of r)console.log([i.proposalId.padEnd(64).slice(0,64),i.cardSlug.padEnd(44).slice(0,44),i.riskLevel.padEnd(6),i.status.padEnd(9),i.createdAt].join(" | "))}catch(r){z(r)}}),t.command("show <id>").description("Print a proposal by id").option("--json","Emit raw JSON instead of rendered markdown",!1).action((n,r)=>{try{let o=rv(n);if(o||(console.error(`Proposal not found: ${n}`),process.exit(1)),r.json){console.log(JSON.stringify(o,null,2));return}console.log(Pf(o))}catch(o){z(o)}})}function ase(e){e.command("eval-gen <cardSlug>").description("Generate a replay-mode eval-case from a failure card. Slices a byte-identical fixture from the source witness trace.").option("--proposal <id>","Back-reference to a proposal (validated to exist). Sprint 3 does NOT mutate the proposal artifact.").option("--evidence-row <index>","0-based index into the card's evidence array. Default: the most recent row (length - 1).").option("--id <override>","Override the auto-generated eval-case id").option("--json","Emit the eval-case JSON to stdout (still writes to disk)",!1).option("--no-write","Render the eval-case without persisting to disk (preview mode). Still reads the source trace.").action((t,n)=>{try{let r=Af(t);if(r||(console.error(`Card not found: ${t}`),process.exit(1)),n.proposal!==void 0){let c=rv(n.proposal);c||(console.error(`Proposal not found: ${n.proposal}`),process.exit(1)),c.cardSlug!==t&&(console.error(`Proposal ${n.proposal} targets card '${c.cardSlug}', not '${t}'.`),process.exit(2))}let o=r.evidence.length-1;if(n.evidenceRow!==void 0){let c=Number.parseInt(n.evidenceRow,10);(!Number.isFinite(c)||c<0)&&(console.error(`Invalid --evidence-row: '${n.evidenceRow}' (must be non-negative integer)`),process.exit(2)),o=c}let s=n.id??TN(t),{evalCase:i,sliceBytes:a}=xN(r,{evalCaseId:s,evidenceRowIndex:o,proposalId:n.proposal??null});if(n.write===!1){n.json?console.log(JSON.stringify(i,null,2)):(console.log("(preview \u2014 not persisted; remove --no-write to save)"),console.log(""),console.log($f(i)),console.log(""),console.log(`Fixture would be ${a.length} bytes, ${i.replay.sliceLineCount} lines.`));return}let l=RN(i,a);if(n.json){console.log(JSON.stringify({...i,_paths:l},null,2));return}console.log(`Wrote eval-case: ${l.evalCaseId}`),console.log(` json: ${l.jsonPath}`),console.log(` fixture: ${l.fixturePath}`),console.log(` md: ${l.markdownPath}`),console.log(` pattern: ${i.assertion.patternId} \xB7 slice: lines ${i.replay.sliceLineRange.startLine}\u2013${i.replay.sliceLineRange.endLine} (${i.replay.sliceLineCount} lines) \xB7 sha256 ${i.replay.sliceSha256.slice(0,12)}\u2026`),i.proposalId&&console.log(` proposal: ${i.proposalId} (back-reference only \u2014 Sprint 3 does not back-fill validationPlan.evalCases)`)}catch(r){if(r instanceof tn){console.error(`eval-gen failed [${r.code}]: ${r.message}`);let o=r.code==="evidence-row-out-of-range"||r.code==="unsupported-window"?2:1;process.exit(o)}z(r)}})}function lse(e){let t=e.command("eval-cases").description("Inspect replay-mode eval-cases on disk");t.command("list").description("List all eval-cases, newest first").option("--card <slug>","Filter by card slug").option("--pattern <name>",`Filter by pattern (one of: ${hv.join(", ")})`).option("--status <state>",`Filter by status (one of: ${gv.join(", ")})`).option("--json","Emit JSON instead of a table",!1).action(n=>{try{n.pattern&&!hv.includes(n.pattern)&&(console.error(`Invalid --pattern: '${n.pattern}'. Must be one of: ${hv.join(", ")}`),process.exit(2)),n.status&&!gv.includes(n.status)&&(console.error(`Invalid --status: '${n.status}'. Must be one of: ${gv.join(", ")}`),process.exit(2));let r=sv();if(n.card&&(r=r.filter(i=>i.cardSlug===n.card)),n.pattern&&(r=r.filter(i=>i.patternId===n.pattern)),n.status&&(r=r.filter(i=>i.status===n.status)),n.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log("No eval-cases found.");return}let o="EVAL CASE ID | CARD | PATTERN | STATUS | CREATED",s="-".repeat(o.length);console.log(o),console.log(s);for(let i of r)console.log([i.evalCaseId.padEnd(70).slice(0,70),i.cardSlug.padEnd(44).slice(0,44),i.patternId.padEnd(20),i.status.padEnd(9),i.createdAt].join(" | "))}catch(r){z(r)}}),t.command("show <id>").description("Print an eval-case by id").option("--json","Emit raw JSON instead of rendered markdown",!1).action((n,r)=>{try{let o=Df(n);if(o||(console.error(`Eval-case not found: ${n}`),process.exit(1)),r.json){console.log(JSON.stringify(o,null,2));return}console.log($f(o))}catch(o){z(o)}})}function cse(e){e.command("eval-run <evalCaseIdOrCardSlug>").description(`Run the smallest deterministic validation contract for an eval-case's pattern.
|