agent-afk 3.100.0 → 3.101.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 +213 -213
- package/dist/index.mjs +29 -29
- package/dist/telegram.mjs +31 -31
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
var Md=Object.defineProperty;var pe=(t,e)=>()=>(t&&(e=t(t=0)),e);var cs=(t,e)=>{for(var n in e)Md(t,n,{get:e[n],enumerable:!0})};var Od,y,F=pe(()=>{"use strict";Od=[{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_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_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:"Per-turn USD budget ceiling. Aborts the turn when projected spend would exceed this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. Falls back to provider default when unset.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Cap on total tokens per turn (input + output). Default 4096.",type:"number",required:!1,default:"4096",example:"8192",category:"model"},{name:"AFK_MODEL",description:"Default model for agent turns. Accepts slot names (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_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:"BRAVE_SEARCH_API_KEY",description:"Brave Search API subscription token, enabling web_scrape search mode. Free tier available at https://brave.com/search/api/. 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 AFK state directory. 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_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:"Allow loading MCP configuration from <cwd>/.mcp.json. Disabled by default \u2014 opt-in to mitigate config-injection risks.",type:"boolean",required:!1,example:"1",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:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless for daemon and subagent surfaces and headed for repl/interactive \u2014 so an operator can watch the agent work in REPL mode.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_ALLOWED_DOMAINS",description:"Comma-separated allowlist of URL host globs. When set, browser_open and any navigation that targets a host outside the list returns status: blocked_by_policy. Unset means no allowlist (permissive). Patterns use simple `*` glob matching against the URL host. Combines with AFK_BROWSER_BLOCKED_DOMAINS \u2014 block wins.",type:"string",required:!1,example:"github.com,*.atlassian.net",category:"browser"},{name:"AFK_BROWSER_BLOCKED_DOMAINS",description:"Comma-separated blocklist of URL host globs. Browser navigation that matches any entry returns status: blocked_by_policy regardless of the allowlist.",type:"string",required:!1,example:"*.ads.example.com",category:"browser"},{name:"AFK_BROWSER_DOM_SNAPSHOTS",description:"Phase 2 opt-in: when set to 1, every browser_act writes a gzipped DOM snapshot sidecar under ~/.afk/state/witness/<sid>/browser/dom-snapshots/. Off by default because snapshots are large; useful for post-mortem analysis of failed actions.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_BACKEND",description:"Select the browser provider backend. Phase 1 supports only `playwright`. Reserved for future `cdp` / `mcp` adapters. Unset defaults to `playwright`.",type:"string",required:!1,example:"playwright",category:"browser"},{name:"AFK_BROWSER_CONFIG",description:"Absolute path to an alternate browser config file. Overrides the default ~/.afk/config/browser.json lookup. Useful for per-project overrides in CI.",type:"string",required:!1,example:"/path/to/browser.json",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],y={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_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_OUTPUT_TOKENS(){return process.env.AFK_MAX_OUTPUT_TOKENS},get AFK_MAX_TOKENS(){return process.env.AFK_MAX_TOKENS},get AFK_MODEL(){return process.env.AFK_MODEL},get AFK_MODEL_LARGE(){return process.env.AFK_MODEL_LARGE},get AFK_MODEL_LARGE_API_KEY(){return process.env.AFK_MODEL_LARGE_API_KEY},get AFK_MODEL_LARGE_BASE_URL(){return process.env.AFK_MODEL_LARGE_BASE_URL},get AFK_MODEL_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_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 BRAVE_SEARCH_API_KEY(){return process.env.BRAVE_SEARCH_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_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 DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let e of Od){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(y,e.name);n&&Object.defineProperty(y,e.name,{...n,enumerable:!1})}})()});import{existsSync as Fs,mkdirSync as ou,renameSync as su,cpSync as iu,rmSync as au}from"fs";import{join as B,dirname as Ls,isAbsolute as cu}from"path";import{homedir as Ns}from"os";import{fileURLToPath as lu}from"url";function Z(){let t=y.AFK_HOME;if(t!==void 0&&t!==""){if(!cu(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return B(Ns(),".afk")}function Qe(){return B(Z(),"agent-framework")}function $s(){return B(Qe(),"forge-telemetry.jsonl")}function Us(){return B(Qe(),"briefs")}function Or(){return B(Z(),"skills")}function Ze(){return B(Z(),"plugins")}function Bs(){return B(process.cwd(),".afk")}function Hs(){return B(Bs(),"skills")}function Dr(){return B(Bs(),"plugins")}function mn(){return B(Ze(),".index.json")}function Fr(){return B(gn(),"schedules.json")}function Lr(){let t=lu(import.meta.url),e=Ls(t);return B(e,"bundled-plugins")}function gn(){return B(Z(),"config")}function He(){return B(Z(),"state")}function et(){return B(He(),"sessions")}function hn(){return B(He(),"presence")}function yn(){return B(He(),"memory")}function tt(){return B(He(),"session-grants.jsonl")}function js(){return B(Z(),"farms")}function Ks(t){return B(js(),t)}function uu(t){if(!du.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function Ws(t){return uu(t),B(He(),"witness",t)}function Gs(t="default"){return B(He(),"daemon",`agent-afk@${t}`)}function qs(){return B(gn(),"afk.config.json")}function zs(){return B(Ns(),".afk.config.json")}function pu(){return B(Z(),"sessions")}function fu(t,e){if(t!==e&&Fs(t)&&!Fs(e))try{ou(Ls(e),{recursive:!0});try{su(t,e)}catch(n){if(n.code==="EXDEV")try{iu(t,e,{recursive:!0}),au(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
|
|
2
|
-
`)}}}catch{}}function Js(){fu(pu(),et())}function Ct(t){return typeof t=="string"&&t.length>0&&t.length<=gu&&mu.test(t)}function bn(t){if(!Ct(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return B(et(),t)}function wn(t){return B(bn(t),"events.jsonl")}var du,mu,gu,H=pe(()=>{"use strict";F();du=/^[a-zA-Z0-9_-]+$/;mu=/^[A-Za-z0-9_-]+$/,gu=128});import{readFileSync as _m}from"node:fs";import{join as Em}from"path";function Am(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function qi(t,e){return Am(e).test(t)}function Rm(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(xm.has(e))return!0;if(Tm.has(e))return!1}return!1}function zi(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function Pm(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function Im(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Cm(t){try{return _m(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function Mm(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return n}function Ji(t){let e=t?.env??y,n=t?.readFileSync??Cm,r=t?.surface??e.AGENT_SURFACE,o=Rm(e.AFK_BROWSER_HEADLESS,r),s=zi(e.AFK_BROWSER_ALLOWED_DOMAINS),i=zi(e.AFK_BROWSER_BLOCKED_DOMAINS),a=Im(e.AFK_BROWSER_DOM_SNAPSHOTS),c=Pm(e.AFK_BROWSER_BACKEND),l={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null},d=e.AFK_BROWSER_CONFIG,u=d!==void 0&&d.trim()!==""?d.trim():Em(gn(),"browser.json"),p=n(u);if(p===void 0)return l;let f;try{f=JSON.parse(p)}catch(m){throw new Error(`Failed to parse browser config at ${u}: ${String(m)}`)}if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`Browser config at ${u} must be a JSON object`);let g=Mm(l,f);return g.configPath=u,g}function eo(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(qi(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>qi(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var xm,Tm,to=pe(()=>{"use strict";F();H();xm=new Set(["daemon","subagent","telegram"]),Tm=new Set(["repl","interactive","cli"])});import Om from"node:fs";import Dm from"node:path";import{chromium as Fm}from"playwright";function Lm(){try{return"3.100.0"}catch{}try{let t=Dm.resolve(import.meta.dirname,"../../../package.json"),e=Om.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Nm,Dn,Vi=pe(()=>{"use strict";Nm=Lm(),Dn=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(e){this.config=e}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=Fm.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,e)).catch(e=>{throw this.launchPromise=void 0,e}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s={context:o,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,s),o}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),c=await i.content(),l=i.url(),d=a!==null?a.status():null;return{html:c,finalUrl:l,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${Nm}`}}}});import{createHash as $m}from"crypto";function no(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of Um)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function Yi(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&Bm.test(t.label))}function Xi(t){return $m("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Qi(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var Um,Bm,Wt=pe(()=>{"use strict";Um=[{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}];Bm=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Hm}from"node:crypto";function jm(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Km(t,e,n){return`el_${Hm("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function Wm(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Zi(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function ta(t,e){let n=t.role??"",r=t.name??"";ea.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])ta(s,e)}async function Gm(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},na).catch(()=>[])}async function qm(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let m=s.type;m==="checkbox"?l="checkbox":m==="radio"?l="radio":m==="button"||m==="submit"||m==="reset"?l="button":m==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,g={role:l,name:c,disabled:p};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},na).catch(()=>[])}function zm(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Fn(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=zm(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Gm(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,g,m]=await Promise.all([i,a,c,l,d]),k,_=!1;u!==null?(k=[],ta(u,k)):(o.push("observation skipped accessibility tree (returned null)"),_=!0,k=(await qm(t)).filter(h=>ea.has(h.role??"")));let b=new Map;for(let v of p){let h=Zi(v.name),x=b.get(h);(!x||x.bbox.w===0&&v.bbox.w>0)&&b.set(h,v)}let S=k.map(v=>({ax:v,dom:b.get(Zi(v.name??""))})),w=r?S:S.filter(v=>v.dom?v.dom.bbox.w>0||v.dom.bbox.h>0:!0);w.sort((v,h)=>{let x=v.dom?.bbox.y??0,R=h.dom?.bbox.y??0;if(x!==R)return x-R;let T=v.dom?.bbox.x??0,O=h.dom?.bbox.x??0;return T-O}),w.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=w.slice(0,n).map((v,h)=>{let x=v.ax.role??"generic",R=v.ax.name??"",T=Km(x,R,h),O=v.dom?.bbox??{x:0,y:0,w:0,h:0},j=v.dom?.type??null,W=null;v.ax.value!==void 0&&v.ax.value!==null&&(W=String(v.ax.value)),v.ax.checked!==void 0&&(W=String(v.ax.checked)),Yi({role:x,kind:j})&&(W="[redacted]");let Q={disabled:v.ax.disabled??!1};v.ax.checked!==void 0&&(Q.checked=v.ax.checked===!0||v.ax.checked==="mixed"),v.ax.selected!==void 0&&(Q.selected=v.ax.selected),v.ax.expanded!==void 0&&(Q.expanded=v.ax.expanded);let U;v.dom?.testId?U=`[data-testid="${v.dom.testId}"]`:v.dom?.id&&(U=`#${v.dom.id}`);let ue={id:T,role:x,label:jm(R),kind:j,value:W,state:Q,bbox:O};return U!==void 0&&(ue.selector=U),ue}),I="idle";try{let v=await t.evaluate(()=>document.readyState);v==="loading"?I="loading":v==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),_&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let C=Wm(f),M=`obs_${e.observationCounter.toString(36)}`,L=new Date().toISOString();return{observationId:M,url:g,title:m,textSummary:C,interactive:A,status:{httpStatus:e.httpStatus??null,loadingState:I,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:L}}var ea,na,ra=pe(()=>{"use strict";Wt();ea=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);na="a[href], button, input, select, textarea, [role], [tabindex], label"});async function oa(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function ro(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>oa(t,s)))).filter(o=>o!==null)}async function Jm(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function oo(t,e,n){switch(e.kind){case"element_id":return Vm(t,e,n);case"selector":return Ym(t,e);case"semantic":return Xm(t,e)}}async function Vm(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await ro(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Ym(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await ro(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function Xm(t,e){return e.role!==void 0?Qm(t,e.text,e.role):Zm(t,e.text,e)}async function Qm(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await ro(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Zm(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await Jm(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let m=u[0];return m===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:m.locator.nth(m.index)}}let p=u.slice(0,5),f=[];for(let m=0;m<p.length;m++){let k=p[m];if(k===void 0)continue;let _=await oa(k.locator,k.index);if(_!==null){let b=`${_.role}:${_.label}:${m}`,S=0;for(let w=0;w<b.length;w++)S=S*31+b.charCodeAt(w)>>>0;f.push({..._,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var sa=pe(()=>{"use strict"});import{randomBytes as eg}from"crypto";import{mkdir as tg,stat as ng,writeFile as rg}from"fs/promises";import{join as so}from"path";import{gzip as og}from"zlib";import{promisify as sg}from"util";function ig(t){return so(Ws(t),"browser")}function ag(t){return so(ig(t),"screenshots")}function cg(){return new Date().toISOString().replace(/[:.]/g,"-")}function lg(){return eg(3).toString("hex")}async function io(t,e,n){if(e.length>ia)throw new Error(`writeScreenshotSidecar: buffer exceeds ${ia} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=ag(t);await tg(r,{recursive:!0});let o=`${cg()}-${lg()}-${n}.png`,s=so(r,o);await rg(s,e);let{size:i}=await ng(s);return{path:s,bytes:i}}var HE,ia,aa=pe(()=>{"use strict";H();Wt();HE=sg(og);ia=5*1024*1024});var la={};cs(la,{PlaywrightProvider:()=>ao});function ca(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var ao,da=pe(()=>{"use strict";Vi();ra();sa();to();Wt();aa();ao=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Dn(e)}async open(e){let n=eo(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(l){a=l}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let c=await Fn(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,c.interactive,c.url,c.title,"browser_open"),a!==null)throw a;return c}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Fn(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await oo(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${ca(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":{let m=no(e.value??"");await c.fill(e.value??"");break}case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(m){if(m instanceof Error&&/navigation|net::ERR/i.test(m.message))try{await d()}catch(k){l=k}else l=m}let u=r.url();if(u!==s){let m=eo(u,this.config);if(!m.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:m.reason}}let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Fn(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await oo(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${ca(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await io(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await io(n,o,r);return s}catch{return null}}}});var qe={};cs(qe,{__resetBrowserRegistryForTests:()=>mg,browserProviderActive:()=>pg,closeBrowserProvider:()=>co,getBrowserProvider:()=>ug,peekBrowserProvider:()=>fg});function ua(){Promise.resolve(co()).then(()=>{process.exit(130)})}function pa(){Promise.resolve(co()).then(()=>{process.exit(143)})}function fa(){he=null}function dg(){Ln||(process.on("SIGINT",ua),process.on("SIGTERM",pa),process.on("exit",fa),Ln=!0)}function ma(){Ln&&(process.removeListener("SIGINT",ua),process.removeListener("SIGTERM",pa),process.removeListener("exit",fa),Ln=!1)}async function ug(t){return he!==null?he:(Ge!==null||(Ge=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(da(),la)),n=Ji(t),r=new e(n);return dg(),he=r,Ge=null,r})()),Ge)}async function co(){if(he===null)return;let t=he;he=null,Ge=null,ma(),await t.shutdown()}function pg(){return he!==null}function fg(){return he}function mg(){he=null,Ge=null,ma()}var he,Ge,Ln,ze=pe(()=>{"use strict";to();he=null,Ge=null,Ln=!1});F();function Dd(){return y.AFK_DEBUG==="1"||y.DEBUG==="1"}function D(...t){Dd()&&console.log(...t)}var oe=class extends Error{constructor(e){super(e),this.name="AbortError"}},Te=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},q=class extends Error{constructor(n,r,o,s){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",s?.cause!==void 0&&(this.cause=s.cause)}event;reason;cause};var Ye=class extends Error{constructor(n,r,o){super(o??`Budget ceiling reached: $${n.toFixed(4)} cumulative >= $${r.toFixed(4)} limit`);this.runningCostUsd=n;this.maxBudgetUsd=r;this.name="BudgetExceededError"}runningCostUsd;maxBudgetUsd};async function Sr(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){D(`trace.emit tool_call failed: ${Re(n)}`)}}async function Xe(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){D(`trace.emit hook_decision failed: ${Re(n)}`)}}async function $e(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){D(`trace.emit subagent_lifecycle failed: ${Re(n)}`)}}async function ls(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){D(`trace.emit budget failed: ${Re(n)}`)}}async function ds(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){D(`trace.emit abort failed: ${Re(n)}`)}}async function us(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){D(`trace.emit compaction failed: ${Re(n)}`)}}async function ps(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){D(`trace.emit closure failed: ${Re(n)}`)}}async function Ue(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){D(`trace.emit session_phase failed: ${Re(n)}`)}}function Re(t){return t instanceof Error?t.message:String(t)}import Go from"path";import{appendFileSync as pw,mkdirSync as fw}from"fs";import{dirname as mw}from"path";import Il from"@anthropic-ai/sdk";var fs="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",Fd="effort-2025-11-24",Ld="claude-cli/1.0.0 (external, cli)",Nd="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function an(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function kt(t,e,n){let r=e==="oauth"?{authToken:t}:{apiKey:t};return typeof n=="string"&&n.length>0?{...r,baseURL:n}:r}function fe(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${fs},${Fd}`:fs,"x-app":"cli","User-Agent":Ld,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function ms(t){return t!=="oauth"?null:[{type:"text",text:Nd}]}import Wd from"@anthropic-ai/sdk";F();var Er=["small","medium","large"],Be={small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-4-6"},large:{id:"claude-opus-4-8"}},$d={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},Ud="auto",Ar="claude-fable-5",Bd={fable:Ar},_r;function xr(t){_r=t}function vr(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function kr(t,e,n){let r={},o=vr(t);o&&(r.id=o);let s=vr(e);s&&(r.baseUrl=s);let i=vr(n);return i&&(r.apiKey=i),r}function Hd(){return{small:kr(y.AFK_MODEL_SMALL,y.AFK_MODEL_SMALL_BASE_URL,y.AFK_MODEL_SMALL_API_KEY),medium:kr(y.AFK_MODEL_MEDIUM,y.AFK_MODEL_MEDIUM_BASE_URL,y.AFK_MODEL_MEDIUM_API_KEY),large:kr(y.AFK_MODEL_LARGE,y.AFK_MODEL_LARGE_BASE_URL,y.AFK_MODEL_LARGE_API_KEY)}}function gs(t){let e=Hd(),n={};for(let r of Er){let o=Be[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},c=s?.name;c&&(a.name=c);let l=s?.provider;l&&(a.provider=l);let d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function _t(t){return t||_r||gs()}function Et(t,e=_t()){let n=t.trim().toLowerCase();if(!n||n===Ud)return;for(let o of Er){let s=e[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="small"||n==="medium"||n==="large"?n:$d[n]}function Tr(t,e=_t()){if(t===void 0)return{id:""};let n=Et(t,e);if(n)return e[n];let r=Bd[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function At(t,e=_t()){if(t!==void 0)return Tr(t,e).id}function hs(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of Er){let o=Kd(n[r]);o&&(e[r]=o)}return e}function jd(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="anthropic"||e==="anthropic-direct")return"anthropic";if(e==="openai"||e==="openai-compatible")return"openai"}function cn(t){return typeof t=="string"?t.trim():""}function Kd(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=cn(e.id);if(!n)return;let r={id:n},o=cn(e.name);o&&(r.name=o);let s=jd(e.provider);s&&(r.provider=s);let i=cn(e.baseUrl);i&&(r.baseUrl=i);let a=cn(e.apiKey);return a&&(r.apiKey=a),r}}var Rr={opus:Be.large.id,opus_1m:Be.large.id,sonnet:Be.medium.id,sonnet_1m:Be.medium.id,haiku:Be.small.id,fable:Ar};function ys(t){return t in Rr}function se(t){return At(t)}import{randomUUID as bs}from"node:crypto";async function ws(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let c=an(e),l=kt(e,c),d=a?a(l):new Wd(l),u=bs(),p=bs(),f=fe(c,u,p),g=se(n)??n,m={};Object.keys(f).length>0&&(m.headers=f),i&&(m.signal=i);let k=await d.messages.create({model:g,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(m).length>0?m:void 0),_=[];for(let S of k.content)S.type==="text"&&_.push(S.text);let b=_.join("").trim();return b.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),b}import{execFileSync as Ss}from"child_process";import{existsSync as Gd,readFileSync as qd,writeFileSync as zd}from"fs";import{homedir as vs,userInfo as ks}from"os";import{join as _s}from"path";var Jd="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Vd="https://platform.claude.com/v1/oauth/token",Yd=300*1e3;function ie(){let t=Es();if(t===void 0)return;let e=As(t);if(e!==void 0){if(e.expiresAt!==void 0&&e.expiresAt<=Date.now()){process.stderr.write("agent-afk: Claude Code OAuth token in keychain is expired. Run `claude login` to refresh.\n");return}return e.accessToken}}async function Pr(){let t=Es();if(t===void 0)return;let e=As(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+Yd)return e.accessToken;if(!e.refreshToken){process.stderr.write("agent-afk: OAuth token expired and no refresh token available. Run `claude login` to refresh.\n");return}let n=await Xd(e.refreshToken);if(!n){process.stderr.write("agent-afk: OAuth token refresh failed. Run `claude login` to refresh.\n");return}try{let r={};try{r=JSON.parse(t)}catch{}let o=r.claudeAiOauth??{};r.claudeAiOauth={...o,accessToken:n.accessToken,expiresAt:n.expiresAt,...n.refreshToken!==void 0?{refreshToken:n.refreshToken}:{}},Qd(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
2
|
+
`)}}}catch{}}function Js(){fu(pu(),et())}function Ct(t){return typeof t=="string"&&t.length>0&&t.length<=gu&&mu.test(t)}function bn(t){if(!Ct(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return B(et(),t)}function wn(t){return B(bn(t),"events.jsonl")}var du,mu,gu,H=pe(()=>{"use strict";F();du=/^[a-zA-Z0-9_-]+$/;mu=/^[A-Za-z0-9_-]+$/,gu=128});import{readFileSync as _m}from"node:fs";import{join as Em}from"path";function Am(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function qi(t,e){return Am(e).test(t)}function Rm(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(xm.has(e))return!0;if(Tm.has(e))return!1}return!1}function zi(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function Pm(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function Im(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Cm(t){try{return _m(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function Mm(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return n}function Ji(t){let e=t?.env??y,n=t?.readFileSync??Cm,r=t?.surface??e.AGENT_SURFACE,o=Rm(e.AFK_BROWSER_HEADLESS,r),s=zi(e.AFK_BROWSER_ALLOWED_DOMAINS),i=zi(e.AFK_BROWSER_BLOCKED_DOMAINS),a=Im(e.AFK_BROWSER_DOM_SNAPSHOTS),c=Pm(e.AFK_BROWSER_BACKEND),l={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null},d=e.AFK_BROWSER_CONFIG,u=d!==void 0&&d.trim()!==""?d.trim():Em(gn(),"browser.json"),p=n(u);if(p===void 0)return l;let f;try{f=JSON.parse(p)}catch(m){throw new Error(`Failed to parse browser config at ${u}: ${String(m)}`)}if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`Browser config at ${u} must be a JSON object`);let g=Mm(l,f);return g.configPath=u,g}function eo(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(qi(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>qi(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var xm,Tm,to=pe(()=>{"use strict";F();H();xm=new Set(["daemon","subagent","telegram"]),Tm=new Set(["repl","interactive","cli"])});import Om from"node:fs";import Dm from"node:path";import{chromium as Fm}from"playwright";function Lm(){try{return"3.101.0"}catch{}try{let t=Dm.resolve(import.meta.dirname,"../../../package.json"),e=Om.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Nm,Dn,Vi=pe(()=>{"use strict";Nm=Lm(),Dn=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(e){this.config=e}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=Fm.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,e)).catch(e=>{throw this.launchPromise=void 0,e}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s={context:o,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,s),o}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),c=await i.content(),l=i.url(),d=a!==null?a.status():null;return{html:c,finalUrl:l,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${Nm}`}}}});import{createHash as $m}from"crypto";function no(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of Um)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function Yi(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&Bm.test(t.label))}function Xi(t){return $m("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Qi(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var Um,Bm,Wt=pe(()=>{"use strict";Um=[{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}];Bm=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Hm}from"node:crypto";function jm(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Km(t,e,n){return`el_${Hm("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function Wm(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Zi(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function ta(t,e){let n=t.role??"",r=t.name??"";ea.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])ta(s,e)}async function Gm(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},na).catch(()=>[])}async function qm(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let m=s.type;m==="checkbox"?l="checkbox":m==="radio"?l="radio":m==="button"||m==="submit"||m==="reset"?l="button":m==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,g={role:l,name:c,disabled:p};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},na).catch(()=>[])}function zm(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Fn(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=zm(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Gm(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,g,m]=await Promise.all([i,a,c,l,d]),k,_=!1;u!==null?(k=[],ta(u,k)):(o.push("observation skipped accessibility tree (returned null)"),_=!0,k=(await qm(t)).filter(h=>ea.has(h.role??"")));let b=new Map;for(let v of p){let h=Zi(v.name),x=b.get(h);(!x||x.bbox.w===0&&v.bbox.w>0)&&b.set(h,v)}let S=k.map(v=>({ax:v,dom:b.get(Zi(v.name??""))})),w=r?S:S.filter(v=>v.dom?v.dom.bbox.w>0||v.dom.bbox.h>0:!0);w.sort((v,h)=>{let x=v.dom?.bbox.y??0,R=h.dom?.bbox.y??0;if(x!==R)return x-R;let T=v.dom?.bbox.x??0,O=h.dom?.bbox.x??0;return T-O}),w.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=w.slice(0,n).map((v,h)=>{let x=v.ax.role??"generic",R=v.ax.name??"",T=Km(x,R,h),O=v.dom?.bbox??{x:0,y:0,w:0,h:0},j=v.dom?.type??null,W=null;v.ax.value!==void 0&&v.ax.value!==null&&(W=String(v.ax.value)),v.ax.checked!==void 0&&(W=String(v.ax.checked)),Yi({role:x,kind:j})&&(W="[redacted]");let Q={disabled:v.ax.disabled??!1};v.ax.checked!==void 0&&(Q.checked=v.ax.checked===!0||v.ax.checked==="mixed"),v.ax.selected!==void 0&&(Q.selected=v.ax.selected),v.ax.expanded!==void 0&&(Q.expanded=v.ax.expanded);let U;v.dom?.testId?U=`[data-testid="${v.dom.testId}"]`:v.dom?.id&&(U=`#${v.dom.id}`);let ue={id:T,role:x,label:jm(R),kind:j,value:W,state:Q,bbox:O};return U!==void 0&&(ue.selector=U),ue}),I="idle";try{let v=await t.evaluate(()=>document.readyState);v==="loading"?I="loading":v==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),_&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let C=Wm(f),M=`obs_${e.observationCounter.toString(36)}`,L=new Date().toISOString();return{observationId:M,url:g,title:m,textSummary:C,interactive:A,status:{httpStatus:e.httpStatus??null,loadingState:I,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:L}}var ea,na,ra=pe(()=>{"use strict";Wt();ea=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);na="a[href], button, input, select, textarea, [role], [tabindex], label"});async function oa(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function ro(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>oa(t,s)))).filter(o=>o!==null)}async function Jm(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function oo(t,e,n){switch(e.kind){case"element_id":return Vm(t,e,n);case"selector":return Ym(t,e);case"semantic":return Xm(t,e)}}async function Vm(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await ro(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Ym(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await ro(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function Xm(t,e){return e.role!==void 0?Qm(t,e.text,e.role):Zm(t,e.text,e)}async function Qm(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await ro(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Zm(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await Jm(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let m=u[0];return m===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:m.locator.nth(m.index)}}let p=u.slice(0,5),f=[];for(let m=0;m<p.length;m++){let k=p[m];if(k===void 0)continue;let _=await oa(k.locator,k.index);if(_!==null){let b=`${_.role}:${_.label}:${m}`,S=0;for(let w=0;w<b.length;w++)S=S*31+b.charCodeAt(w)>>>0;f.push({..._,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var sa=pe(()=>{"use strict"});import{randomBytes as eg}from"crypto";import{mkdir as tg,stat as ng,writeFile as rg}from"fs/promises";import{join as so}from"path";import{gzip as og}from"zlib";import{promisify as sg}from"util";function ig(t){return so(Ws(t),"browser")}function ag(t){return so(ig(t),"screenshots")}function cg(){return new Date().toISOString().replace(/[:.]/g,"-")}function lg(){return eg(3).toString("hex")}async function io(t,e,n){if(e.length>ia)throw new Error(`writeScreenshotSidecar: buffer exceeds ${ia} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=ag(t);await tg(r,{recursive:!0});let o=`${cg()}-${lg()}-${n}.png`,s=so(r,o);await rg(s,e);let{size:i}=await ng(s);return{path:s,bytes:i}}var HE,ia,aa=pe(()=>{"use strict";H();Wt();HE=sg(og);ia=5*1024*1024});var la={};cs(la,{PlaywrightProvider:()=>ao});function ca(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var ao,da=pe(()=>{"use strict";Vi();ra();sa();to();Wt();aa();ao=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Dn(e)}async open(e){let n=eo(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(l){a=l}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let c=await Fn(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,c.interactive,c.url,c.title,"browser_open"),a!==null)throw a;return c}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Fn(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await oo(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${ca(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":{let m=no(e.value??"");await c.fill(e.value??"");break}case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(m){if(m instanceof Error&&/navigation|net::ERR/i.test(m.message))try{await d()}catch(k){l=k}else l=m}let u=r.url();if(u!==s){let m=eo(u,this.config);if(!m.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:m.reason}}let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Fn(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await oo(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${ca(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await io(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await io(n,o,r);return s}catch{return null}}}});var qe={};cs(qe,{__resetBrowserRegistryForTests:()=>mg,browserProviderActive:()=>pg,closeBrowserProvider:()=>co,getBrowserProvider:()=>ug,peekBrowserProvider:()=>fg});function ua(){Promise.resolve(co()).then(()=>{process.exit(130)})}function pa(){Promise.resolve(co()).then(()=>{process.exit(143)})}function fa(){he=null}function dg(){Ln||(process.on("SIGINT",ua),process.on("SIGTERM",pa),process.on("exit",fa),Ln=!0)}function ma(){Ln&&(process.removeListener("SIGINT",ua),process.removeListener("SIGTERM",pa),process.removeListener("exit",fa),Ln=!1)}async function ug(t){return he!==null?he:(Ge!==null||(Ge=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(da(),la)),n=Ji(t),r=new e(n);return dg(),he=r,Ge=null,r})()),Ge)}async function co(){if(he===null)return;let t=he;he=null,Ge=null,ma(),await t.shutdown()}function pg(){return he!==null}function fg(){return he}function mg(){he=null,Ge=null,ma()}var he,Ge,Ln,ze=pe(()=>{"use strict";to();he=null,Ge=null,Ln=!1});F();function Dd(){return y.AFK_DEBUG==="1"||y.DEBUG==="1"}function D(...t){Dd()&&console.log(...t)}var se=class extends Error{constructor(e){super(e),this.name="AbortError"}},Te=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},q=class extends Error{constructor(n,r,o,s){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",s?.cause!==void 0&&(this.cause=s.cause)}event;reason;cause};var Ye=class extends Error{constructor(n,r,o){super(o??`Budget ceiling reached: $${n.toFixed(4)} cumulative >= $${r.toFixed(4)} limit`);this.runningCostUsd=n;this.maxBudgetUsd=r;this.name="BudgetExceededError"}runningCostUsd;maxBudgetUsd};async function Sr(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){D(`trace.emit tool_call failed: ${Re(n)}`)}}async function Xe(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){D(`trace.emit hook_decision failed: ${Re(n)}`)}}async function $e(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){D(`trace.emit subagent_lifecycle failed: ${Re(n)}`)}}async function ls(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){D(`trace.emit budget failed: ${Re(n)}`)}}async function ds(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){D(`trace.emit abort failed: ${Re(n)}`)}}async function us(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){D(`trace.emit compaction failed: ${Re(n)}`)}}async function ps(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){D(`trace.emit closure failed: ${Re(n)}`)}}async function Ue(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){D(`trace.emit session_phase failed: ${Re(n)}`)}}function Re(t){return t instanceof Error?t.message:String(t)}import Go from"path";import{appendFileSync as pw,mkdirSync as fw}from"fs";import{dirname as mw}from"path";import Il from"@anthropic-ai/sdk";var fs="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",Fd="effort-2025-11-24",Ld="claude-cli/1.0.0 (external, cli)",Nd="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function an(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function kt(t,e,n){let r=e==="oauth"?{authToken:t}:{apiKey:t};return typeof n=="string"&&n.length>0?{...r,baseURL:n}:r}function fe(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${fs},${Fd}`:fs,"x-app":"cli","User-Agent":Ld,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function ms(t){return t!=="oauth"?null:[{type:"text",text:Nd}]}import Wd from"@anthropic-ai/sdk";F();var Er=["small","medium","large"],Be={small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-4-6"},large:{id:"claude-opus-4-8"}},$d={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},Ud="auto",Ar="claude-fable-5",Bd={fable:Ar},_r;function xr(t){_r=t}function vr(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function kr(t,e,n){let r={},o=vr(t);o&&(r.id=o);let s=vr(e);s&&(r.baseUrl=s);let i=vr(n);return i&&(r.apiKey=i),r}function Hd(){return{small:kr(y.AFK_MODEL_SMALL,y.AFK_MODEL_SMALL_BASE_URL,y.AFK_MODEL_SMALL_API_KEY),medium:kr(y.AFK_MODEL_MEDIUM,y.AFK_MODEL_MEDIUM_BASE_URL,y.AFK_MODEL_MEDIUM_API_KEY),large:kr(y.AFK_MODEL_LARGE,y.AFK_MODEL_LARGE_BASE_URL,y.AFK_MODEL_LARGE_API_KEY)}}function gs(t){let e=Hd(),n={};for(let r of Er){let o=Be[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},c=s?.name;c&&(a.name=c);let l=s?.provider;l&&(a.provider=l);let d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function _t(t){return t||_r||gs()}function Et(t,e=_t()){let n=t.trim().toLowerCase();if(!n||n===Ud)return;for(let o of Er){let s=e[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="small"||n==="medium"||n==="large"?n:$d[n]}function Tr(t,e=_t()){if(t===void 0)return{id:""};let n=Et(t,e);if(n)return e[n];let r=Bd[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function At(t,e=_t()){if(t!==void 0)return Tr(t,e).id}function hs(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of Er){let o=Kd(n[r]);o&&(e[r]=o)}return e}function jd(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="anthropic"||e==="anthropic-direct")return"anthropic";if(e==="openai"||e==="openai-compatible")return"openai"}function cn(t){return typeof t=="string"?t.trim():""}function Kd(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=cn(e.id);if(!n)return;let r={id:n},o=cn(e.name);o&&(r.name=o);let s=jd(e.provider);s&&(r.provider=s);let i=cn(e.baseUrl);i&&(r.baseUrl=i);let a=cn(e.apiKey);return a&&(r.apiKey=a),r}}var Rr={opus:Be.large.id,opus_1m:Be.large.id,sonnet:Be.medium.id,sonnet_1m:Be.medium.id,haiku:Be.small.id,fable:Ar};function ys(t){return t in Rr}function te(t){return At(t)}import{randomUUID as bs}from"node:crypto";async function ws(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let c=an(e),l=kt(e,c),d=a?a(l):new Wd(l),u=bs(),p=bs(),f=fe(c,u,p),g=te(n)??n,m={};Object.keys(f).length>0&&(m.headers=f),i&&(m.signal=i);let k=await d.messages.create({model:g,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(m).length>0?m:void 0),_=[];for(let S of k.content)S.type==="text"&&_.push(S.text);let b=_.join("").trim();return b.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),b}import{execFileSync as Ss}from"child_process";import{existsSync as Gd,readFileSync as qd,writeFileSync as zd}from"fs";import{homedir as vs,userInfo as ks}from"os";import{join as _s}from"path";var Jd="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Vd="https://platform.claude.com/v1/oauth/token",Yd=300*1e3;function ie(){let t=Es();if(t===void 0)return;let e=As(t);if(e!==void 0){if(e.expiresAt!==void 0&&e.expiresAt<=Date.now()){process.stderr.write("agent-afk: Claude Code OAuth token in keychain is expired. Run `claude login` to refresh.\n");return}return e.accessToken}}async function Pr(){let t=Es();if(t===void 0)return;let e=As(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+Yd)return e.accessToken;if(!e.refreshToken){process.stderr.write("agent-afk: OAuth token expired and no refresh token available. Run `claude login` to refresh.\n");return}let n=await Xd(e.refreshToken);if(!n){process.stderr.write("agent-afk: OAuth token refresh failed. Run `claude login` to refresh.\n");return}try{let r={};try{r=JSON.parse(t)}catch{}let o=r.claudeAiOauth??{};r.claudeAiOauth={...o,accessToken:n.accessToken,expiresAt:n.expiresAt,...n.refreshToken!==void 0?{refreshToken:n.refreshToken}:{}},Qd(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
3
3
|
`)}return n.accessToken}function Es(){if(process.platform==="darwin")try{return Ss("security",["find-generic-password","-s","Claude Code-credentials","-a",ks().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=_s(vs(),".claude",".credentials.json");if(!Gd(t))return;try{return qd(t,"utf-8")}catch{return}}}function As(t){let e;try{e=JSON.parse(t)}catch{return}if(typeof e!="object"||e===null)return;let n=e.claudeAiOauth;if(typeof n!="object"||n===null)return;let r=n,o=r.accessToken;if(typeof o!="string"||o.length===0)return;let s={accessToken:o},i=r.refreshToken;typeof i=="string"&&i.length>0&&(s.refreshToken=i);let a=r.expiresAt;return typeof a=="number"&&(s.expiresAt=a),s}async function Xd(t){try{let e=await fetch(Vd,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:Jd})});if(!e.ok)return;let n=await e.json(),r=n.access_token,o=n.expires_in;if(typeof r!="string"||typeof o!="number")return;let s=n.refresh_token;return{accessToken:r,expiresAt:Date.now()+o*1e3,...typeof s=="string"&&s.length>0?{refreshToken:s}:{}}}catch{return}}function xt(t){if(!t||t.length<3)return"token:(unknown)";try{let n=t.split(".");if(n.length<2)throw new Error("not a JWT");let r=Buffer.from(n[1],"base64url").toString("utf-8"),o=JSON.parse(r),s=typeof o.email=="string"&&o.email||typeof o.sub=="string"&&o.sub||typeof o.account_id=="string"&&o.account_id||typeof o.preferred_username=="string"&&o.preferred_username;if(s)return s}catch{}return`token:${t.length>=8?t.slice(-8):t}`}function Qd(t){if(process.platform==="darwin")Ss("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",ks().username,"-w",t],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let e=_s(vs(),".claude",".credentials.json");Zd(e,t)}}function Zd(t,e){zd(t,e,{encoding:"utf-8",mode:384})}import{randomUUID as xl}from"node:crypto";F();var eu="1h";function ln(t){if(typeof t?.baseUrl=="string"&&t.baseUrl.length>0)return!1;let e=y.AFK_DISABLE_PROMPT_CACHE;if(e===void 0||e.length===0)return!0;let n=e.toLowerCase();return!(n==="1"||n==="true"||n==="yes"||n==="on")}function dn(){let t=y.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":t==="1h"?"1h":eu}function xs(t,e){if(t.length===0)return t;let n=t[t.length-1],r=Rs(n,e);return r===n?t:[...t.slice(0,-1),r]}function Ts(t,e){if(t.length===0)return t;let n=t[t.length-1],r=tu(n,e);return r===n?t:[...t.slice(0,-1),r]}function tu(t,e){let n=t.content;if(typeof n=="string")return n.length===0?t:{...t,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:e}}]};if(!Array.isArray(n)||n.length===0)return t;let r=n[n.length-1],o=Rs(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function Rs(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}var Ir=["## Plan mode is active","","Write-class tools (`write_file`, `edit_file`, write-intent `bash`) are refused at the hook layer.","The user has asked you to plan, not yet to act. Treat this turn as planning work.","","Traverse the shape that matches the work \u2014 skip steps the terrain already covers, do not skip steps the terrain hides:",""," unknown field \u2192 ground the current terrain \u2192 gather missing codebase context \u2192"," research missing external context \u2192 reveal chaos / constraints / risks \u2192"," name the failure geometry \u2192 form a candidate plan \u2192 apply adversarial pressure \u2192 embody the final plan","","Reach for these skills (invoke via the `skill` tool) when the cost of skipping exceeds the cost of dispatching:"," - `ground-state` \u2014 survey git, infra, memory before non-trivial work"," - `gather` \u2014 parallel context-gathering for a code area"," - `research` \u2014 parallel external + local context for the current task"," - `devils-advocate` \u2014 generate alternatives and rank them before committing"," - `shadow-verify` \u2014 independently re-derive load-bearing claims","","Do not declare readiness silently. When the plan is ready, state: chosen approach, risks named, and alternatives considered. The user will then exit plan mode with `/plan off`, which has you save this plan to a file and implement it (Shift+Tab exits without implementing) \u2014 so keep the plan concrete and complete enough to act on directly."].join(`
|
|
4
4
|
`);function Ps(t){return t!=="plan"?null:{type:"text",text:Ir}}import{z as K}from"zod";import{mkdir as Tc,appendFile as Rc}from"fs/promises";import{join as Oo}from"path";var Is={"audit-fit":{"01-skill-inspector.md":`# Skill Inspector
|
|
5
5
|
|
|
@@ -838,9 +838,9 @@ Don't refuse the flow; just clarify where the wizard runs.
|
|
|
838
838
|
## Tone
|
|
839
839
|
|
|
840
840
|
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.
|
|
841
|
-
`}};function z(t){let e=Is[t];if(!e){let n=Object.keys(Is).sort(),r=n.length>0?"Available: "+n.join(", "):"";throw new Error("Unknown skill: "+t+". "+r)}return e}function Cr(t,e){return e?!0:(t.audience??"public")==="public"}var un=new Map;function
|
|
842
|
-
Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${t}${r}`)}function Cs(){return Array.from(un.keys()).sort()}var Tt=class{nodes=new Map;traceWriter;constructor(e){this.traceWriter=e}register(e,n){this.nodes.has(e)||this.nodes.set(e,{controller:n,children:new Set,listeners:new Set,cascading:!1})}has(e){return this.nodes.has(e)}getController(e){return this.nodes.get(e)?.controller}childrenOf(e){let n=this.nodes.get(e);return n?Array.from(n.children):[]}linkChild(e,n){let r=this.nodes.get(e),o=this.nodes.get(n);if(!r)throw new Error(`AbortGraph: parent ${e} not registered`);if(!o)throw new Error(`AbortGraph: child ${n} not registered`);if(o.parentId=e,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!==e||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!==e||s.cascading)return;let i=this.nodes.get(e);if(!i)return;let a={parentId:e,childId:n,reason:s.controller.signal.reason};for(let c of i.listeners)try{c(a)}catch{}},{once:!0})}onChildAborted(e,n){let r=this.nodes.get(e);if(!r)throw new Error(`AbortGraph: ${e} not registered`);return r.listeners.add(n),()=>{r.listeners.delete(n)}}abort(e,n,r="user_signal"){let o=this.nodes.get(e);if(!o||o.controller.signal.aborted)return;let s=[],i=[...o.children],a=new Set;for(;i.length;){let c=i.shift();if(a.has(c))continue;a.add(c);let l=this.nodes.get(c);if(l){l.cascading=!0,s.push(c);for(let d of l.children)i.push(d)}}ds(this.traceWriter,{origin:r,cascadedTo:s,...n!==void 0?{reason:nu(n)}:{}}),o.controller.abort(n);for(let c of s){let l=this.nodes.get(c);l&&!l.controller.signal.aborted&&l.controller.abort(n)}}dispose(e){let n=this.nodes.get(e);if(n){n.parentId&&this.nodes.get(n.parentId)?.children.delete(e);for(let r of n.children){let o=this.nodes.get(r);o&&(o.parentId=void 0)}this.nodes.delete(e)}}};function nu(t){if(typeof t=="string")return t;if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}var Rt=0,pn=5e3;async function Pt(t,e,n={}){if(!Number.isFinite(e)||e<=0)return t;let r,o=new Promise((s,i)=>{r=setTimeout(()=>{let a=n.label?` (${n.label})`:"",c=new Te(`Operation timed out after ${e}ms${a}`,e);n.controller&&!n.controller.signal.aborted&&n.controller.abort(c),i(c)},e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}var fn=3e4;var It=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"};async function Pe(t,e,n,r){if(!t)return;if(r.kind==="blocked"){await Xe(t,{hookEvent:e,decision:"block",...r.err.reason!==void 0?{reason:r.err.reason}:{},...e==="PreToolUse"&&n.toolName!==void 0?{blockedTool:n.toolName}:{}});return}let o=r.decision;await Xe(t,{hookEvent:e,decision:o.decision,...o.reason!==void 0?{reason:o.reason}:{},...o.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(o.injectContext,"utf8")}:{}})}async function Ms(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Pe(n.traceWriter,"SubagentStart",{},{kind:"decision",decision:r})}catch(r){throw r instanceof q&&await Pe(n.traceWriter,"SubagentStart",{},{kind:"blocked",err:r}),r}}function ru(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new It(n,e)))},e);i.unref(),t.then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}async function Os(t,e,n={}){if(!t)return{};try{let r=await ru(t.dispatch(e,n.signal,fn),fn,"SubagentStop");return await Pe(n.traceWriter,"SubagentStop",{},{kind:"decision",decision:r}),r}catch(r){return r instanceof It?(console.warn(`[afk] SubagentStop hook timed out after ${fn}ms (subagentId=${e.subagentId}): ${r.message}`),n.onError?.(r),{}):(r instanceof q&&await Pe(n.traceWriter,"SubagentStop",{},{kind:"blocked",err:r}),r instanceof q||r instanceof
|
|
843
|
-
`;await yu(e,o,{flag:"a"})}catch{}}import{AsyncLocalStorage as vu}from"node:async_hooks";var Vs=new vu;function Ys(t,e){return Vs.run(t,e)}function Ie(){return Vs.getStore()}H();import Ao from"path";import{appendFileSync as Kh,mkdirSync as Wh}from"fs";import{dirname as Gh}from"path";import jr from"path";import{appendFileSync as rf,mkdirSync as of}from"fs";import{dirname as sf}from"path";import{createHash as af}from"node:crypto";function Mt(t,e){return e?.allowedTools?e.allowedTools.includes(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" is not in the configured allowlist`}:{allowed:!0}}var ku=/\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,Eu=/\bgit\b[^|;&]*\s+branch\s+-[dDmM]\b/i,Au=/\bgit\b[^|;&]*\s+remote\s+(add|remove|rm|set-url|rename)\b/i,xu=/\bgit\b[^|;&]*\s+worktree\s+(remove|prune|move|lock|unlock)\b/i,Tu=/\bgit\b[^|;&]*\s+stash\b(?!\s+(list|show)\b)/i,Ru=/\bstash@\{[^}]*\}/gi,Pu=/\bgit\s+config\b[^|;&]*\s(--add|--unset|--unset-all|--replace-all|--rename-section|--remove-section|--edit|-e)\b/i,Iu=/\bgit\s+config\s+(?:--(?:global|system|local|worktree)\s+|(?:--file|-f)\s+\S+\s+)*[\w][\w.-]*\s+\S/i,Cu=/\bgh\s+\w[\w-]*\s+(create|merge|close|edit|delete|comment|review|reopen|sync|fork|clone|ready)\b/i,Mu=/\bgh\s+api\b.*(-X|--method)\s+(POST|PUT|PATCH|DELETE)\b/i,Ou=/\bgh\s+api\b.*(\s-f\b|\s-F\b|--field\b)/i,Du=/\bgh\s+(secret|variable|workflow|release|run|cache|ssh-key|gpg-key)\s+(set|run|rerun|cancel|upload|delete|enable|disable)\b/i,Fu=/\|\s*(sh|bash|zsh|dash)\b/i,Lu=/\b(rm|rmdir|unlink|mv|cp|mkdir|touch|dd|truncate|tee|sponge|ln|chmod|chown|chgrp|shred|rsync)\b/i,Nu=/\bfind\b[^|;&]*\s-delete\b/i,$u=/\bfind\b[^|;&]*\s-exec\s+['"]?\s*(rm|rmdir|unlink|mv|cp|dd|truncate|shred|tee|chmod|chown|chgrp|install|patch)\b/i,Sn=String.raw`(?:^|[\n;|&(]|\$\()\s*`,Uu=new RegExp(Sn+String.raw`patch\b`,"i"),Bu=new RegExp(Sn+String.raw`install\b`,"i"),Hu=new RegExp(Sn+String.raw`(?:source\b|\.\s+\S)`,"i"),ju=/\btar\b[^|;&]*\s-?[a-zA-Z]*x[a-zA-Z]*\b/i,Ku=new RegExp(Sn+String.raw`unzip\b`,"i"),Wu=/\bcpio\b[^|;&]*\s-[a-zA-Z]*i\b/i,Gu=/\bsed\b[^|;&]*\s-[a-zA-Z]*i\b/i,qu=/\bperl\b[^|;&]*\s-[a-zA-Z]*i\b/i,zu=/\b(?:python3?|nodejs|node|bun|ruby|perl|php)\b[^|;&]*?\s-(?:c|e)\b\s*("(?:[^"\\]|\\.)*"|'[^']*'|`[^`]*`)/i,Ju=/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,Vu=/\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,Yu=/\b(curl|wget)\b[^|;&]*\s(-o\b|-O\b|--output\b)/i,Xu=/\bcurl\b[^|;&]*\s-X\s+(POST|PUT|PATCH|DELETE)\b/i,Qu=/\bcurl\b[^|;&]*\s(-d\b|--data\b|-F\b|--form\b)/i,Zu=/(\d*&?>>?\s*\/dev\/null|\d*>&\d+|&>\s*\/dev\/null|&>>\s*\/dev\/null)/gi,ep=/\$\(\(.*?\)\)/g,tp=/(?<![=<>-])>>?(?!&)/,np=[{re:ku,reason:"git repository mutation"},{re:_u,reason:"git tag create/delete"},{re:Eu,reason:"git branch delete/rename"},{re:Au,reason:"git remote mutation"},{re:Tu,reason:"git stash mutation (only `stash list`/`stash show` allowed)"},{re:Pu,reason:"git config write flag (only reads allowed)"},{re:Iu,reason:"git config set (`<key> <value>`; only reads allowed)"},{re:Cu,reason:"gh write operation"},{re:Mu,reason:"gh api write method (POST/PUT/PATCH/DELETE)"},{re:Ou,reason:"gh api field payload (-f/-F/--field)"},{re:Du,reason:"gh extended write operation (secret/variable/workflow/run/cache)"},{re:xu,reason:"git worktree mutation (remove/prune/move)"},{re:Gu,reason:"sed in-place edit (-i)"},{re:qu,reason:"perl in-place edit (-i)"},{re:Vu,reason:"package install/modify"},{re:Yu,reason:"curl/wget output-to-file"},{re:Xu,reason:"curl write method (POST/PUT/PATCH/DELETE)"},{re:Qu,reason:"curl data/form payload"},{re:$u,reason:"find -exec with mutating verb"}],rp=[{re:Fu,reason:"pipe-to-shell (RCE via piped interpreter)"},{re:Lu,reason:"filesystem mutation"},{re:Nu,reason:"find -delete (file removal)"},{re:Uu,reason:"patch (applies a diff to files)"},{re:Bu,reason:"install (writes files)"},{re:Hu,reason:"source/dot-source executes a script"},{re:ju,reason:"tar extract (writes files)"},{re:Ku,reason:"unzip (writes files)"},{re:Wu,reason:"cpio extract (-i mode writes files)"}];function op(t){return t.replace(/'[^']*'/g," ").replace(/"(?:[^"\\]|\\.)*"/g,e=>/\$\(|`/.test(e)?e:" ")}function Xs(t){if(typeof t!="string"||t.trim().length===0)return{mutating:!1};let e=t.replace(Ru," ");for(let s of np)if(s.re.test(e))return{mutating:!0,reason:s.reason};let n=t.match(zu)?.[1];if(n&&Ju.test(n))return{mutating:!0,reason:"interpreter one-liner file write (`-c`/`-e`)"};let r=op(t);for(let s of rp)if(s.re.test(r))return{mutating:!0,reason:s.reason};let o=r.replace(ep," ").replace(Zu," ").replace(/&(>>?)/g,"$1");return tp.test(o)?{mutating:!0,reason:"output redirection to a file (`>`/`>>`)"}:{mutating:!1}}H();var sp={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"]}},ip={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"]}},ap={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"]}},cp={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"]}},lp={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"]}},dp={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"]}},up={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"]}},pp={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"]}},fp={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 `BRAVE_SEARCH_API_KEY` (free tier at https://brave.com/search/api/); 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:[]}},Ce={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.
|
|
841
|
+
`}};function z(t){let e=Is[t];if(!e){let n=Object.keys(Is).sort(),r=n.length>0?"Available: "+n.join(", "):"";throw new Error("Unknown skill: "+t+". "+r)}return e}function Cr(t,e){return e?!0:(t.audience??"public")==="public"}var un=new Map;function ne(t){un.set(t.name,t)}function Se(t){let e=un.get(t);if(e)return e;let n=Array.from(un.keys()).sort(),r=n.length>0?`
|
|
842
|
+
Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${t}${r}`)}function Cs(){return Array.from(un.keys()).sort()}var Tt=class{nodes=new Map;traceWriter;constructor(e){this.traceWriter=e}register(e,n){this.nodes.has(e)||this.nodes.set(e,{controller:n,children:new Set,listeners:new Set,cascading:!1})}has(e){return this.nodes.has(e)}getController(e){return this.nodes.get(e)?.controller}childrenOf(e){let n=this.nodes.get(e);return n?Array.from(n.children):[]}linkChild(e,n){let r=this.nodes.get(e),o=this.nodes.get(n);if(!r)throw new Error(`AbortGraph: parent ${e} not registered`);if(!o)throw new Error(`AbortGraph: child ${n} not registered`);if(o.parentId=e,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!==e||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!==e||s.cascading)return;let i=this.nodes.get(e);if(!i)return;let a={parentId:e,childId:n,reason:s.controller.signal.reason};for(let c of i.listeners)try{c(a)}catch{}},{once:!0})}onChildAborted(e,n){let r=this.nodes.get(e);if(!r)throw new Error(`AbortGraph: ${e} not registered`);return r.listeners.add(n),()=>{r.listeners.delete(n)}}abort(e,n,r="user_signal"){let o=this.nodes.get(e);if(!o||o.controller.signal.aborted)return;let s=[],i=[...o.children],a=new Set;for(;i.length;){let c=i.shift();if(a.has(c))continue;a.add(c);let l=this.nodes.get(c);if(l){l.cascading=!0,s.push(c);for(let d of l.children)i.push(d)}}ds(this.traceWriter,{origin:r,cascadedTo:s,...n!==void 0?{reason:nu(n)}:{}}),o.controller.abort(n);for(let c of s){let l=this.nodes.get(c);l&&!l.controller.signal.aborted&&l.controller.abort(n)}}dispose(e){let n=this.nodes.get(e);if(n){n.parentId&&this.nodes.get(n.parentId)?.children.delete(e);for(let r of n.children){let o=this.nodes.get(r);o&&(o.parentId=void 0)}this.nodes.delete(e)}}};function nu(t){if(typeof t=="string")return t;if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}var Rt=0,pn=5e3;async function Pt(t,e,n={}){if(!Number.isFinite(e)||e<=0)return t;let r,o=new Promise((s,i)=>{r=setTimeout(()=>{let a=n.label?` (${n.label})`:"",c=new Te(`Operation timed out after ${e}ms${a}`,e);n.controller&&!n.controller.signal.aborted&&n.controller.abort(c),i(c)},e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}var fn=3e4;var It=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"};async function Pe(t,e,n,r){if(!t)return;if(r.kind==="blocked"){await Xe(t,{hookEvent:e,decision:"block",...r.err.reason!==void 0?{reason:r.err.reason}:{},...e==="PreToolUse"&&n.toolName!==void 0?{blockedTool:n.toolName}:{}});return}let o=r.decision;await Xe(t,{hookEvent:e,decision:o.decision,...o.reason!==void 0?{reason:o.reason}:{},...o.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(o.injectContext,"utf8")}:{}})}async function Ms(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Pe(n.traceWriter,"SubagentStart",{},{kind:"decision",decision:r})}catch(r){throw r instanceof q&&await Pe(n.traceWriter,"SubagentStart",{},{kind:"blocked",err:r}),r}}function ru(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new It(n,e)))},e);i.unref(),t.then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}async function Os(t,e,n={}){if(!t)return{};try{let r=await ru(t.dispatch(e,n.signal,fn),fn,"SubagentStop");return await Pe(n.traceWriter,"SubagentStop",{},{kind:"decision",decision:r}),r}catch(r){return r instanceof It?(console.warn(`[afk] SubagentStop hook timed out after ${fn}ms (subagentId=${e.subagentId}): ${r.message}`),n.onError?.(r),{}):(r instanceof q&&await Pe(n.traceWriter,"SubagentStop",{},{kind:"blocked",err:r}),r instanceof q||r instanceof se?(D(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):(D(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{}))}}async function Mr(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Pe(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){throw r instanceof q&&await Pe(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r}}async function Ds(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Pe(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof q&&await Pe(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof q||r instanceof se){D(`PostToolUse hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}D(`PostToolUse hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}F();H();import{mkdir as hu,writeFile as yu}from"fs/promises";import{dirname as bu,join as wu}from"path";function Su(){return wu(Qe(),"routing-decisions.jsonl")}async function ae(t){if(!(y.VITEST||y.NODE_ENV==="test"))try{let e=Su();await hu(bu(e),{recursive:!0});let r={ts:new Date().toISOString().split(".")[0]+"Z",surface:"afk"};for(let[s,i]of Object.entries(t))i!==void 0&&(r[s]=i);let o=JSON.stringify(r)+`
|
|
843
|
+
`;await yu(e,o,{flag:"a"})}catch{}}import{AsyncLocalStorage as vu}from"node:async_hooks";var Vs=new vu;function Ys(t,e){return Vs.run(t,e)}function Ie(){return Vs.getStore()}H();import Ao from"path";import{appendFileSync as Kh,mkdirSync as Wh}from"fs";import{dirname as Gh}from"path";import jr from"path";import{appendFileSync as rf,mkdirSync as of}from"fs";import{dirname as sf}from"path";import{createHash as af}from"node:crypto";function Mt(t,e){return e?.allowedTools?e.allowedTools.includes(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" is not in the configured allowlist`}:{allowed:!0}}var ku=/\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,Eu=/\bgit\b[^|;&]*\s+branch\s+-[dDmM]\b/i,Au=/\bgit\b[^|;&]*\s+remote\s+(add|remove|rm|set-url|rename)\b/i,xu=/\bgit\b[^|;&]*\s+worktree\s+(remove|prune|move|lock|unlock)\b/i,Tu=/\bgit\b[^|;&]*\s+stash\b(?!\s+(list|show)\b)/i,Ru=/\bstash@\{[^}]*\}/gi,Pu=/\bgit\s+config\b[^|;&]*\s(--add|--unset|--unset-all|--replace-all|--rename-section|--remove-section|--edit|-e)\b/i,Iu=/\bgit\s+config\s+(?:--(?:global|system|local|worktree)\s+|(?:--file|-f)\s+\S+\s+)*[\w][\w.-]*\s+\S/i,Cu=/\bgh\s+\w[\w-]*\s+(create|merge|close|edit|delete|comment|review|reopen|sync|fork|clone|ready)\b/i,Mu=/\bgh\s+api\b.*(-X|--method)\s+(POST|PUT|PATCH|DELETE)\b/i,Ou=/\bgh\s+api\b.*(\s-f\b|\s-F\b|--field\b)/i,Du=/\bgh\s+(secret|variable|workflow|release|run|cache|ssh-key|gpg-key)\s+(set|run|rerun|cancel|upload|delete|enable|disable)\b/i,Fu=/\|\s*(sh|bash|zsh|dash)\b/i,Lu=/\b(rm|rmdir|unlink|mv|cp|mkdir|touch|dd|truncate|tee|sponge|ln|chmod|chown|chgrp|shred|rsync)\b/i,Nu=/\bfind\b[^|;&]*\s-delete\b/i,$u=/\bfind\b[^|;&]*\s-exec\s+['"]?\s*(rm|rmdir|unlink|mv|cp|dd|truncate|shred|tee|chmod|chown|chgrp|install|patch)\b/i,Sn=String.raw`(?:^|[\n;|&(]|\$\()\s*`,Uu=new RegExp(Sn+String.raw`patch\b`,"i"),Bu=new RegExp(Sn+String.raw`install\b`,"i"),Hu=new RegExp(Sn+String.raw`(?:source\b|\.\s+\S)`,"i"),ju=/\btar\s+-?[a-zA-Z]*[cxruA][a-zA-Z]*\b/i,Ku=new RegExp(Sn+String.raw`unzip\b`,"i"),Wu=/\bcpio\b[^|;&]*\s-[a-zA-Z]*i\b/i,Gu=/\bsed\b[^|;&]*\s-[a-zA-Z]*i\b/i,qu=/\bperl\b[^|;&]*\s-[a-zA-Z]*i\b/i,zu=/\b(?:python3?|nodejs|node|bun|ruby|perl|php)\b[^|;&]*?\s-(?:c|e)\b\s*("(?:[^"\\]|\\.)*"|'[^']*'|`[^`]*`)/i,Ju=/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,Vu=/\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,Yu=/\b(curl|wget)\b[^|;&]*\s(-o\b|-O\b|--output\b)/i,Xu=/\bcurl\b[^|;&]*\s-X\s+(POST|PUT|PATCH|DELETE)\b/i,Qu=/\bcurl\b[^|;&]*\s(-d\b|--data\b|-F\b|--form\b)/i,Zu=/(\d*&?>>?\s*\/dev\/null|\d*>&\d+|&>\s*\/dev\/null|&>>\s*\/dev\/null)/gi,ep=/\$\(\(.*?\)\)/g,tp=/(?<![=<>-])>>?(?!&)/,np=[{re:ku,reason:"git repository mutation"},{re:_u,reason:"git tag create/delete"},{re:Eu,reason:"git branch delete/rename"},{re:Au,reason:"git remote mutation"},{re:Tu,reason:"git stash mutation (only `stash list`/`stash show` allowed)"},{re:Pu,reason:"git config write flag (only reads allowed)"},{re:Iu,reason:"git config set (`<key> <value>`; only reads allowed)"},{re:Cu,reason:"gh write operation"},{re:Mu,reason:"gh api write method (POST/PUT/PATCH/DELETE)"},{re:Ou,reason:"gh api field payload (-f/-F/--field)"},{re:Du,reason:"gh extended write operation (secret/variable/workflow/run/cache)"},{re:xu,reason:"git worktree mutation (remove/prune/move)"},{re:Gu,reason:"sed in-place edit (-i)"},{re:qu,reason:"perl in-place edit (-i)"},{re:Vu,reason:"package install/modify"},{re:Yu,reason:"curl/wget output-to-file"},{re:Xu,reason:"curl write method (POST/PUT/PATCH/DELETE)"},{re:Qu,reason:"curl data/form payload"},{re:$u,reason:"find -exec with mutating verb"}],rp=[{re:Fu,reason:"pipe-to-shell (RCE via piped interpreter)"},{re:Lu,reason:"filesystem mutation"},{re:Nu,reason:"find -delete (file removal)"},{re:Uu,reason:"patch (applies a diff to files)"},{re:Bu,reason:"install (writes files)"},{re:Hu,reason:"source/dot-source executes a script"},{re:ju,reason:"tar create/extract/append/update (writes files/archive)"},{re:Ku,reason:"unzip (writes files)"},{re:Wu,reason:"cpio extract (-i mode writes files)"}];function op(t){return t.replace(/'[^']*'/g," ").replace(/"(?:[^"\\]|\\.)*"/g,e=>/\$\(|`/.test(e)?e:" ")}function Xs(t){if(typeof t!="string"||t.trim().length===0)return{mutating:!1};let e=t.replace(Ru," ");for(let s of np)if(s.re.test(e))return{mutating:!0,reason:s.reason};let n=t.match(zu)?.[1];if(n&&Ju.test(n))return{mutating:!0,reason:"interpreter one-liner file write (`-c`/`-e`)"};let r=op(t);for(let s of rp)if(s.re.test(r))return{mutating:!0,reason:s.reason};let o=r.replace(ep," ").replace(Zu," ").replace(/&(>>?)/g,"$1");return tp.test(o)?{mutating:!0,reason:"output redirection to a file (`>`/`>>`)"}:{mutating:!1}}H();var sp={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"]}},ip={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"]}},ap={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"]}},cp={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"]}},lp={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"]}},dp={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"]}},up={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"]}},pp={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"]}},fp={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 `BRAVE_SEARCH_API_KEY` (free tier at https://brave.com/search/api/); 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:[]}},Ce={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.
|
|
844
844
|
|
|
845
845
|
Parallelize: dispatch multiple \`agent\` calls in a single tool-use turn to run independent investigations concurrently.
|
|
846
846
|
|
|
@@ -973,16 +973,16 @@ ${n.join(`
|
|
|
973
973
|
`)}catch{}}get toolDefs(){return this.schemas}checkReadOnlyBash(e){if(!this.readOnlyBash||e.name!=="bash")return null;let n=e.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=Xs(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}:null}checkRepeatCircuitBreaker(e){if(df.has(e.name))return null;let n=uf(e);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<lf?null:{content:`Loop circuit breaker: "${e.name}" has been called ${this.repeatBreaker.count} times in a row with byte-identical input. The result will not change. Stop repeating this call \u2014 reuse the previous result, change the input, try a different tool, or end the turn.`,isError:!0,circuitBreaker:!0}}async execute(e){if(e.signal.aborted)return{content:"Tool call aborted",isError:!0};if(this.hookRegistry){let a={event:"PreToolUse",toolName:e.name,input:e.input,...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};try{await Mr(this.hookRegistry,a,{signal:e.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(c){if(c instanceof q)return{content:`Tool "${e.name}" blocked by PreToolUse hook: ${c.message}`,isError:!0};throw c}}let n=Mt(e.name,this.permissions);if(!n.allowed)return{content:n.reason??`Tool "${e.name}" is not permitted`,isError:!0};let r=this.checkReadOnlyBash(e);if(r)return r;let o=this.checkRepeatCircuitBreaker(e);if(o)return o;if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let a;try{a=await this.subagentExecutor.execute(e)}catch(c){a={content:`Agent tool error: ${c instanceof Error?c.message:String(c)}`,isError:!0}}return this.firePostToolUse(e.name,a.content,e.signal),a}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let a;try{a=await this.skillExecutor.execute(e)}catch(c){a={content:`Skill tool error: ${c instanceof Error?c.message:String(c)}`,isError:!0}}return this.firePostToolUse(e.name,a.content,e.signal),a}if(e.name==="compose"){let a=await this.executeCompose(e);return this.firePostToolUse(e.name,a.content,e.signal),a}let s=this.handlers.get(e.name);if(!s)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let i;try{i=await s(e.input,e.signal,this.handlerContext)}catch(a){i={content:`Tool execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}return this.firePostToolUse(e.name,i.content,e.signal),i}async executeBatch(e){if(e.length===0)return[];if(e.length===1)return[await this.execute(e[0])];let n=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){let a=e[i];if(a.signal.aborted){n[i]={content:"Tool call aborted",isError:!0},r.add(i);continue}if(this.hookRegistry){let u={event:"PreToolUse",toolName:a.name,input:a.input,...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};try{await Mr(this.hookRegistry,u,{signal:a.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(p){if(p instanceof q){n[i]={content:`Tool "${a.name}" blocked by PreToolUse hook: ${p.message}`,isError:!0},r.add(i);continue}throw p}}let c=Mt(a.name,this.permissions);if(!c.allowed){n[i]={content:c.reason??`Tool "${a.name}" is not permitted`,isError:!0},r.add(i);continue}let l=this.checkReadOnlyBash(a);if(l){n[i]=l,r.add(i);continue}let d=this.checkRepeatCircuitBreaker(a);if(d){n[i]=d,r.add(i);continue}}let o=e.map((i,a)=>({call:i,originalIndex:a})).filter((i,a)=>!r.has(a));if(o.length===0)return n;let s=pf(o.map(i=>i.call),this.classifier);for(let i of s)if(i.isConcurrencySafe){let a=await Promise.allSettled(i.indices.map(async c=>{let{call:l,originalIndex:d}=o[c];return l.signal.aborted?{result:{content:"Tool call aborted",isError:!0},originalIndex:d}:{result:await this.executeCore(l),originalIndex:d}}));for(let c of a)if(c.status==="fulfilled")n[c.value.originalIndex]=c.value.result;else{let l=c.reason instanceof Error?c.reason.message:String(c.reason),d=i.indices[a.indexOf(c)];n[o[d].originalIndex]={content:`Tool execution error: ${l}`,isError:!0}}}else for(let a of i.indices){let{call:c,originalIndex:l}=o[a];if(c.signal.aborted){n[l]={content:"Tool call aborted",isError:!0};continue}n[l]=await this.executeCore(c)}return n}async executeCore(e){if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let o;try{o=await this.subagentExecutor.execute(e)}catch(s){o={content:`Agent tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}return this.firePostToolUse(e.name,o.content,e.signal),o}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let o;try{o=await this.skillExecutor.execute(e)}catch(s){o={content:`Skill tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}return this.firePostToolUse(e.name,o.content,e.signal),o}if(e.name==="compose"){let o=await this.executeCompose(e);return this.firePostToolUse(e.name,o.content,e.signal),o}let n=this.handlers.get(e.name);if(!n)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let r;try{r=await n(e.input,e.signal,this.handlerContext)}catch(o){r={content:`Tool execution error: ${o instanceof Error?o.message:String(o)}`,isError:!0}}return this.firePostToolUse(e.name,r.content,e.signal),r}async executeCompose(e){if(!this.composeExecutor)return{content:"Compose tool is not available in this session configuration",isError:!0};try{return await this.composeExecutor.execute(e)}catch(n){return{content:`Compose tool error: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}firePostToolUse(e,n,r){if(!this.hookRegistry)return;let o={event:"PostToolUse",toolName:e,output:n};Ds(this.hookRegistry,o,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(()=>{})}};import{spawn as Mf}from"child_process";var ff=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,mf=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,gf=/={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,}/,hf=/(\d+)\s+passing/,yf=/(\d+)\s+failing/,bf=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,wf=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,Sf=/(\d+) examples?, (\d+) failures?/,vf=/OK \((\d+) tests?/,kf=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/;function _f(t){let e=t.match(ff);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10),o=e[3]!==void 0?parseInt(e[3],10):void 0;return{runner:"vitest",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function Ef(t){let e=t.match(mf);if(!e)return null;let n=parseInt(e[1]??"0",10);return{runner:"jest",passed:parseInt(e[2]??"0",10),failed:n}}function Af(t){let e=t.match(gf);if(!e)return null;if(e[2]!==void 0){let n=parseInt(e[2],10),r=parseInt(e[1]??"0",10);return{runner:"pytest",passed:n,failed:r}}return e[4]!==void 0?{runner:"pytest",passed:parseInt(e[4],10),failed:0}:null}function xf(t){let e=t.match(hf);if(!e)return null;let n=parseInt(e[1]??"0",10),r=t.match(yf),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function Tf(t){let e=[...t.matchAll(bf)];if(e.length===0)return null;let n=0,r=0;for(let o of e)o[1]==="ok"?n++:o[1]==="FAIL"&&r++;return{runner:"go-test",passed:n,failed:r}}function Rf(t){let e=t.match(wf);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10),o=e[3]!==void 0?parseInt(e[3],10):void 0;return{runner:"cargo",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function Pf(t){let e=t.match(Sf);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10);return{runner:"rspec",passed:n-r,failed:r}}function If(t){let e=t.match(vf);if(e)return{runner:"phpunit",passed:parseInt(e[1]??"0",10),failed:0};let n=t.match(kf);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 Kr(t){return _f(t)??Ef(t)??Af(t)??xf(t)??Tf(t)??Rf(t)??Pf(t)??If(t)??null}var hi=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,Cf=/[\x00-\x1F\x7F-\x9F]/g;function Tn(t){return t.replace(hi,"").replace(Cf," ").trim()}function Ke(t){return t.replace(hi,"")}function Of(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(e.timeout_ms<0||e.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=e.timeout_ms}return{command:e.command,timeout_ms:n}}function Rn(t,e){let n=!1;function r(){n||t==="bypassPermissions"&&(n=!0,console.warn("[security] bash handler: shell=true with bypassPermissions \u2014 all shell metacharacters are interpreted without confirmation. Migrate to execFile to eliminate this risk (tracked: C4)."))}return async(o,s,i)=>{let{command:a,timeout_ms:c}=Of(o);return s.aborted?{content:"Command aborted",isError:!0}:(r(),new Promise(l=>{let d=!1;function u(E){d||(d=!0,clearTimeout(f),s.removeEventListener("abort",w),l(E))}let p=Mf(a,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...(i?.resolveBase??i?.cwd??e)!==void 0?{cwd:i?.resolveBase??i?.cwd??e}:{},...i?.env!==void 0?{env:{...process.env,...i.env}}:{}});p.unref();let f=setTimeout(()=>{p.pid!==void 0&&process.kill(-p.pid,"SIGKILL"),u({content:`Command timed out after ${c}ms`,isError:!0})},c),g="",m="",k=1e5,_=0,b=!1;function S(E){if(b||d||_<k)return;b=!0,console.warn(`[bash] overflow kill: stream=${E} totalBytes=${_} command="${a}"`),ae({event:"tool.overflow_kill",tool:"bash",total_bytes:_,stream:E}),p.kill("SIGKILL");let A=(g+m).trimEnd();A=Ke(A);let I=Kr(A)??void 0;A.length>k&&(A=A.slice(0,k)),A+=`
|
|
974
974
|
[output truncated \u2014 exceeded 100KB]`,u({content:A,truncated:!0,...I!==void 0?{testResult:I}:{}})}p.stdout.on("data",E=>{let A=k-_,I=E.length<=A?E:E.subarray(0,Math.max(0,A));_+=I.length,g+=I.toString("utf8"),S("stdout")}),p.stderr.on("data",E=>{let A=k-_,I=E.length<=A?E:E.subarray(0,Math.max(0,A));_+=I.length,m+=I.toString("utf8"),S("stderr")});let w=()=>{p.pid!==void 0&&process.kill(-p.pid,"SIGKILL"),u({content:"Command aborted",isError:!0})};s.addEventListener("abort",w),p.on("close",E=>{if(s.aborted){u({content:"Command aborted",isError:!0});return}if(E!==null&&E!==0){let M=m.trimEnd()||g.trimEnd();u({content:`Command exited with code ${E}${M?`
|
|
975
975
|
`+M:""}`,isError:!0});return}if(b)return;let A=(g+m).trimEnd();A=Ke(A);let I=Kr(A)??void 0,C=!1;A.length>k&&(A=A.slice(0,k)+`
|
|
976
|
-
[output truncated \u2014 exceeded 100KB]`,C=!0),u({content:A,...C?{truncated:!0}:{},...I!==void 0?{testResult:I}:{}})}),p.on("error",E=>{u({content:`Failed to execute: ${E.message}`,isError:!0})})}))}}var yi=Rn("default");import{promises as Df}from"fs";import Wr from"path";function
|
|
976
|
+
[output truncated \u2014 exceeded 100KB]`,C=!0),u({content:A,...C?{truncated:!0}:{},...I!==void 0?{testResult:I}:{}})}),p.on("error",E=>{u({content:`Failed to execute: ${E.message}`,isError:!0})})}))}}var yi=Rn("default");import{promises as Df}from"fs";import Wr from"path";function re(t,e,n="read"){let r=e?.resolveBase??e?.cwd,o=Wr.isAbsolute(t)?t:Wr.resolve(r??process.cwd(),t);if(r===void 0)return o;let s=n==="read"?e?.readRoots??[r]:e?.writeRoots??[r];for(let c of s)if(!Wr.relative(c,o).startsWith(".."))return o;let i=s.map(c=>`\`${c}\``).join(", "),a=n==="read"?"read roots":"write roots";throw new Error(`Path \`${t}\` is outside the allowed ${a} [${i}].`)}var bi=async(t,e,n)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let r=t,o=r.file_path,s=r.offset??1,i=r.limit??2e3;if(typeof o!="string")return{content:"Invalid input: file_path must be a string",isError:!0};if(typeof s!="number"||s<1)return{content:"Invalid input: offset must be a positive number",isError:!0};if(typeof i!="number"||i<1)return{content:"Invalid input: limit must be a positive number",isError:!0};let a;try{a=re(o,n,"read")}catch(c){return{content:c instanceof Error?c.message:String(c),isError:!0}}try{let c=await Df.readFile(a),l=Math.min(8192,c.length);for(let b=0;b<l;b++)if(c[b]===0)return{content:`File appears to be binary: ${a}`,isError:!0};let d=c.toString("utf-8");if(d.length===0)return{content:""};let u=d.split(`
|
|
977
977
|
`),p=Math.max(0,s-1),f=Math.min(u.length,p+i),g=u.slice(p,f),m=u.length;if(g.length===0)return{content:`... (offset ${s} is past end of file \u2014 file has ${m} lines)`};let k=String(m).length,_=g.map((b,S)=>{let w=p+S+1;return`${String(w).padStart(k," ")} ${b}`}).join(`
|
|
978
978
|
`);if(g.length<m){let b=p+1,S=p+g.length,w=S<m?` \u2014 pass offset=${S+1} to continue`:"";return{content:`${_}
|
|
979
|
-
... (showing lines ${b}-${S} of ${m}${w})`}}return{content:_}}catch(c){if(c instanceof Error){let l=c;return l.code==="ENOENT"?{content:`File not found: ${a}`,isError:!0}:l.code==="EACCES"?{content:`Permission denied: ${a}`,isError:!0}:{content:`Error reading file: ${c.message}`,isError:!0}}return{content:"Unknown error reading file",isError:!0}}};F();import{readFile as Hf,writeFile as jf,mkdir as Kf,stat as Wf}from"fs/promises";import{dirname as Gf}from"path";F();import{realpathSync as wi}from"fs";import{dirname as Ff,resolve as Pn,join as Lf}from"path";import{homedir as Fe}from"os";var Nf=[`${Fe()}/.ssh`,`${Fe()}/.aws`,`${Fe()}/.gnupg`,`${Fe()}/.config/gcloud`,"/etc","/System","/private/etc","/usr/local/etc",`${Fe()}/.afk/config`,`${Fe()}/.afk/state`,`${Fe()}/.npmrc`,`${Fe()}/.docker/config.json`];function $f(){let t=y.AFK_WRITE_DENYLIST,e=t?t.split(":").map(n=>Gr(Pn(n))).filter(Boolean):[];return[...Nf.map(n=>Gr(Pn(n))),...e]}function Gr(t){let e=Pn(t);try{return wi(e)}catch{}let n=[],r=e;for(let o=0;o<64;o++){let s=Ff(r);if(s===r)break;n.unshift(r.slice(s.length+1)),r=s;try{let i=wi(r);return Lf(i,...n)}catch{}}return e}function In(t,e="write_file"){let n=Gr(Pn(t));for(let r of $f())if(n===r||n.startsWith(r+"/"))throw new Error(`${e}: refusing to write to protected path: ${n} (matches denylist entry: ${r})`)}function Si(t){if(t==="")return[];let e=t.split(/\r?\n/);return e.length>0&&e[e.length-1]===""&&/\r?\n$/.test(t)&&e.pop(),e}function Uf(t,e){let n=t.length,r=e.length;if((n+1)*(r+1)>=4e6){let l=[];for(let d of t)l.push({op:"del",text:d});for(let d of e)l.push({op:"add",text:d});return l}let o=r+1,s=new Int32Array((n+1)*o);for(let l=1;l<=n;l++)for(let d=1;d<=r;d++)if(t[l-1]===e[d-1])s[l*o+d]=s[(l-1)*o+(d-1)]+1;else{let u=s[(l-1)*o+d],p=s[l*o+(d-1)];s[l*o+d]=u>=p?u:p}let i=[],a=n,c=r;for(;a>0||c>0;)a>0&&c>0&&t[a-1]===e[c-1]?(i.push({op:"same",text:t[a-1]}),a--,c--):c>0&&(a===0||s[a*o+(c-1)]>=s[(a-1)*o+c])?(i.push({op:"add",text:e[c-1]}),c--):(i.push({op:"del",text:t[a-1]}),a--);return i.reverse(),i}function Bf(t){let e=new Int32Array(t.length+1);e[t.length]=t.length;for(let i=t.length-1;i>=0;i--)e[i]=t[i].op==="same"?e[i+1]:i;let n=[],r=1,o=1,s=0;for(;s<t.length;){if(t[s].op==="same"){r++,o++,s++;continue}let i=s,a=0;for(;i>0&&t[i-1].op==="same"&&a<3;)i--,a++;let c=Math.max(1,r-a),l=Math.max(1,o-a),d=[],u=0,p=0;for(let g=i;g<s;g++)d.push({kind:" ",text:t[g].text}),u++,p++;let f=!1;for(;!f&&s<t.length;){let g=t[s];if(g.op==="same"){let m=e[s],k=m-s;if(m===t.length||k>6){for(let b=0;b<3&&s<t.length&&t[s].op==="same";b++)d.push({kind:" ",text:t[s].text}),u++,p++,r++,o++,s++;f=!0}else d.push({kind:" ",text:g.text}),u++,p++,r++,o++,s++}else g.op==="add"?(d.push({kind:"+",text:g.text}),p++,o++,s++):(d.push({kind:"-",text:g.text}),u++,r++,s++)}n.push({oldStart:c,oldLines:u,newStart:l,newLines:p,lines:d})}return n}function Cn(t,e){if(t===e)return null;let n=Si(t),r=Si(e),o=Uf(n,r),s=Bf(o);if(s.length===0)return null;let i=0,a=0;for(let c of s)for(let l of c.lines)l.kind==="+"?i++:l.kind==="-"&&a++;return{hunks:s,addedLines:i,removedLines:a}}function qf(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.file_path!="string")throw new Error('Input must have a "file_path" field of type string');if(typeof e.content!="string")throw new Error('Input must have a "content" field of type string');return{file_path:e.file_path,content:e.content}}var vi=async(t,e,n)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:r,content:o}=qf(t),s;try{s=
|
|
979
|
+
... (showing lines ${b}-${S} of ${m}${w})`}}return{content:_}}catch(c){if(c instanceof Error){let l=c;return l.code==="ENOENT"?{content:`File not found: ${a}`,isError:!0}:l.code==="EACCES"?{content:`Permission denied: ${a}`,isError:!0}:{content:`Error reading file: ${c.message}`,isError:!0}}return{content:"Unknown error reading file",isError:!0}}};F();import{readFile as Hf,writeFile as jf,mkdir as Kf,stat as Wf}from"fs/promises";import{dirname as Gf}from"path";F();import{realpathSync as wi}from"fs";import{dirname as Ff,resolve as Pn,join as Lf}from"path";import{homedir as Fe}from"os";var Nf=[`${Fe()}/.ssh`,`${Fe()}/.aws`,`${Fe()}/.gnupg`,`${Fe()}/.config/gcloud`,"/etc","/System","/private/etc","/usr/local/etc",`${Fe()}/.afk/config`,`${Fe()}/.afk/state`,`${Fe()}/.npmrc`,`${Fe()}/.docker/config.json`];function $f(){let t=y.AFK_WRITE_DENYLIST,e=t?t.split(":").map(n=>Gr(Pn(n))).filter(Boolean):[];return[...Nf.map(n=>Gr(Pn(n))),...e]}function Gr(t){let e=Pn(t);try{return wi(e)}catch{}let n=[],r=e;for(let o=0;o<64;o++){let s=Ff(r);if(s===r)break;n.unshift(r.slice(s.length+1)),r=s;try{let i=wi(r);return Lf(i,...n)}catch{}}return e}function In(t,e="write_file"){let n=Gr(Pn(t));for(let r of $f())if(n===r||n.startsWith(r+"/"))throw new Error(`${e}: refusing to write to protected path: ${n} (matches denylist entry: ${r})`)}function Si(t){if(t==="")return[];let e=t.split(/\r?\n/);return e.length>0&&e[e.length-1]===""&&/\r?\n$/.test(t)&&e.pop(),e}function Uf(t,e){let n=t.length,r=e.length;if((n+1)*(r+1)>=4e6){let l=[];for(let d of t)l.push({op:"del",text:d});for(let d of e)l.push({op:"add",text:d});return l}let o=r+1,s=new Int32Array((n+1)*o);for(let l=1;l<=n;l++)for(let d=1;d<=r;d++)if(t[l-1]===e[d-1])s[l*o+d]=s[(l-1)*o+(d-1)]+1;else{let u=s[(l-1)*o+d],p=s[l*o+(d-1)];s[l*o+d]=u>=p?u:p}let i=[],a=n,c=r;for(;a>0||c>0;)a>0&&c>0&&t[a-1]===e[c-1]?(i.push({op:"same",text:t[a-1]}),a--,c--):c>0&&(a===0||s[a*o+(c-1)]>=s[(a-1)*o+c])?(i.push({op:"add",text:e[c-1]}),c--):(i.push({op:"del",text:t[a-1]}),a--);return i.reverse(),i}function Bf(t){let e=new Int32Array(t.length+1);e[t.length]=t.length;for(let i=t.length-1;i>=0;i--)e[i]=t[i].op==="same"?e[i+1]:i;let n=[],r=1,o=1,s=0;for(;s<t.length;){if(t[s].op==="same"){r++,o++,s++;continue}let i=s,a=0;for(;i>0&&t[i-1].op==="same"&&a<3;)i--,a++;let c=Math.max(1,r-a),l=Math.max(1,o-a),d=[],u=0,p=0;for(let g=i;g<s;g++)d.push({kind:" ",text:t[g].text}),u++,p++;let f=!1;for(;!f&&s<t.length;){let g=t[s];if(g.op==="same"){let m=e[s],k=m-s;if(m===t.length||k>6){for(let b=0;b<3&&s<t.length&&t[s].op==="same";b++)d.push({kind:" ",text:t[s].text}),u++,p++,r++,o++,s++;f=!0}else d.push({kind:" ",text:g.text}),u++,p++,r++,o++,s++}else g.op==="add"?(d.push({kind:"+",text:g.text}),p++,o++,s++):(d.push({kind:"-",text:g.text}),u++,r++,s++)}n.push({oldStart:c,oldLines:u,newStart:l,newLines:p,lines:d})}return n}function Cn(t,e){if(t===e)return null;let n=Si(t),r=Si(e),o=Uf(n,r),s=Bf(o);if(s.length===0)return null;let i=0,a=0;for(let c of s)for(let l of c.lines)l.kind==="+"?i++:l.kind==="-"&&a++;return{hunks:s,addedLines:i,removedLines:a}}function qf(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.file_path!="string")throw new Error('Input must have a "file_path" field of type string');if(typeof e.content!="string")throw new Error('Input must have a "content" field of type string');return{file_path:e.file_path,content:e.content}}var vi=async(t,e,n)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:r,content:o}=qf(t),s;try{s=re(r,n,"write")}catch(i){return{content:i instanceof Error?i.message:String(i),isError:!0}}try{In(s,"write_file");let i=(()=>{let p=y.AFK_WRITE_DIFF;if(p===void 0)return!1;let f=p.trim().toLowerCase();return f==="0"||f==="false"||f==="no"||f==="off"})(),a=10*1024*1024,c=null;if(!i)try{let p=await Wf(s);if(p.size>a)y.AFK_DEBUG&&console.debug(`[write_file] skipping diff: prior file ${p.size} bytes > ${a}`);else{let f=await Hf(s);try{c=new TextDecoder("utf-8",{fatal:!0}).decode(f)}catch{c=null}}}catch(p){p instanceof Error&&"code"in p&&p.code==="ENOENT"&&(c="")}let l=Gf(s);await Kf(l,{recursive:!0}),await jf(s,o,{signal:e});let d=null;if(c!==null&&!o.includes("\0")){let p=performance.now();d=Cn(c,o);let f=performance.now()-p;f>=500?console.warn(`[write_file] computeLineDiff took ${f.toFixed(1)}ms`):f>=50&&y.AFK_DEBUG&&console.debug(`[write_file] computeLineDiff took ${f.toFixed(1)}ms`)}return{content:`Wrote ${Buffer.byteLength(o,"utf8")} bytes to ${s}`,...d?{render:{diff:d}}:{}}}catch(i){return i instanceof Error?"code"in i&&i.code==="EACCES"?{content:`Permission denied: ${s}`,isError:!0}:{content:`Error writing file: ${i.message}`,isError:!0}:{content:"Unknown error writing file",isError:!0}}};F();import{readFile as zf,writeFile as Jf}from"fs/promises";function Vf(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.file_path!="string")throw new Error('Input must have a "file_path" field of type string');if(typeof e.old_string!="string")throw new Error('Input must have an "old_string" field of type string');if(typeof e.new_string!="string")throw new Error('Input must have a "new_string" field of type string');let n=!1;if(e.replace_all!==void 0){if(typeof e.replace_all!="boolean")throw new Error("replace_all must be a boolean");n=e.replace_all}return{file_path:e.file_path,old_string:e.old_string,new_string:e.new_string,replace_all:n}}function Yf(t,e){if(e.length===0)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=e.length;return n}var ki=async(t,e,n)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:r,old_string:o,new_string:s,replace_all:i}=Vf(t),a;try{a=re(r,n,"write")}catch(c){return{content:c instanceof Error?c.message:String(c),isError:!0}}try{In(a,"edit_file");let c=await zf(a,"utf-8"),l=Yf(c,o);if(l===0)return{content:`old_string not found in ${a}`,isError:!0};if(l>1&&!i)return{content:`old_string matches ${l} locations in ${a}. Use replace_all: true or provide more context.`,isError:!0};let d;if(i)d=c.split(o).join(s);else{let m=c.indexOf(o);d=c.slice(0,m)+s+c.slice(m+o.length)}await Jf(a,d,"utf-8");let u=l===1?`Replaced 1 occurrence in ${a}`:`Replaced ${l} occurrences in ${a}`,p=performance.now(),f=Cn(c,d),g=performance.now()-p;return g>=500?console.warn(`[edit_file] computeLineDiff took ${g.toFixed(1)}ms`):g>=50&&y.AFK_DEBUG&&console.debug(`[edit_file] computeLineDiff took ${g.toFixed(1)}ms`),{content:u,...f?{render:{diff:f}}:{}}}catch(c){return{content:`Error: ${c instanceof Error?c.message:String(c)}`,isError:!0}}};import{promises as Ei}from"fs";import Xf from"path";function Qf(t,e){let n=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/");if(r.includes("**")){let s=r.split("**"),i=0;for(let a=0;a<s.length;a++){let c=s[a]??"",l=_i(c);if(a===0){let d=n.match(new RegExp(`^${l}`));if(!d)return!1;i=d[0].length}else if(a===s.length-1){let d=new RegExp(`${l}$`);if(!n.slice(i).match(d))return!1}else{let d=new RegExp(l),u=n.slice(i).match(d);if(!u)return!1;let p=u.index??0;i+=p+u[0].length}}return!0}return new RegExp(`^${_i(r)}$`).test(n)}function _i(t){return t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]")}async function Zf(t,e){let n=[];async function o(s,i){if(n.length>=500)return!0;try{let a=await Ei.readdir(s,{withFileTypes:!0});for(let c of a){if(n.length>=500)return!0;let l=Xf.join(s,c.name),d=i?`${i}/${c.name}`:c.name;if(Qf(d,e)&&n.push(d),c.isDirectory()&&await o(l,d))return!0}}catch{}return!1}return await o(t,""),n}function qr(t){return async(e,n,r)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let o=e,s=o.pattern,i=o.path??r?.resolveBase??r?.cwd??t??process.cwd();if(typeof s!="string")return{content:"Invalid input: pattern must be a string",isError:!0};if(s.trim()==="")return{content:"Invalid input: pattern cannot be empty",isError:!0};if(typeof i!="string")return{content:"Invalid input: path must be a string",isError:!0};let a;try{a=re(i,r,"read")}catch(c){return{content:c instanceof Error?c.message:String(c),isError:!0}}try{if(!(await Ei.stat(a)).isDirectory())return{content:`Invalid input: path is not a directory: ${a}`,isError:!0};let l=await Zf(a,s);if(l.length===0)return{content:`No files matched pattern '${s}' in ${a}`};let d=l.join(`
|
|
980
980
|
`);return l.length>=500&&(d+=`
|
|
981
|
-
[results capped at 500 entries]`),{content:d}}catch(c){return c instanceof Error?"code"in c&&c.code==="ENOENT"?{content:`Path not found: ${a}`,isError:!0}:"code"in c&&c.code==="EACCES"?{content:`Permission denied: ${a}`,isError:!0}:{content:`Error scanning directory: ${c.message}`,isError:!0}:{content:"Unknown error scanning directory",isError:!0}}}}var Ai=qr();import{spawn as em}from"child_process";function tm(t,e,n){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let r=t;if(typeof r.pattern!="string")throw new Error('Input must have a "pattern" field of type string');let o=typeof r.path=="string"?r.path:e?.resolveBase??e?.cwd??n??process.cwd(),s=
|
|
981
|
+
[results capped at 500 entries]`),{content:d}}catch(c){return c instanceof Error?"code"in c&&c.code==="ENOENT"?{content:`Path not found: ${a}`,isError:!0}:"code"in c&&c.code==="EACCES"?{content:`Permission denied: ${a}`,isError:!0}:{content:`Error scanning directory: ${c.message}`,isError:!0}:{content:"Unknown error scanning directory",isError:!0}}}}var Ai=qr();import{spawn as em}from"child_process";function tm(t,e,n){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let r=t;if(typeof r.pattern!="string")throw new Error('Input must have a "pattern" field of type string');let o=typeof r.path=="string"?r.path:e?.resolveBase??e?.cwd??n??process.cwd(),s=re(o,e,"read"),i;if(r.include!==void 0){if(typeof r.include!="string")throw new Error("include must be a string");i=r.include}let a=!1;if(r.extended!==void 0){if(typeof r.extended!="boolean")throw new Error("extended must be a boolean");a=r.extended}return{pattern:r.pattern,path:s,include:i,extended:a}}function nm(t){return/(?<!\\)\|/.test(t)}function zr(t){return async(e,n,r)=>{let{pattern:o,path:s,include:i,extended:a}=tm(e,r,t);return n.aborted?{content:"Search aborted",isError:!0}:new Promise(c=>{let l=!1;function d(w){l||(l=!0,n.removeEventListener("abort",S),c(w))}let u=["-rn"];a&&u.push("-E"),i&&u.push(`--include=${i}`),u.push(o,s);let p=em("grep",u,t!==void 0?{cwd:t}:{}),f="",g="",m=1e5,k=0,_=!1;function b(w){if(_||l||k<m)return;_=!0,console.warn(`[grep] overflow kill: stream=${w} totalBytes=${k} pattern=${o} path=${s}`),ae({event:"tool.overflow_kill",tool:"grep",total_bytes:k,stream:w}),p.kill("SIGKILL");let E=(f+g).trimEnd();E=Ke(E),E.length>m&&(E=E.slice(0,m)),E+=`
|
|
982
982
|
[output truncated]`,d({content:E,truncated:!0})}p.stdout.on("data",w=>{let E=m-k,A=w.length<=E?w:w.subarray(0,Math.max(0,E));k+=A.length,f+=A.toString("utf8"),b("stdout")}),p.stderr.on("data",w=>{let E=m-k,A=w.length<=E?w:w.subarray(0,Math.max(0,E));k+=A.length,g+=A.toString("utf8"),b("stderr")});let S=()=>{p.kill(),d({content:"Search aborted",isError:!0})};n.addEventListener("abort",S),p.on("close",w=>{if(_)return;if(w===1){let I=`No matches found for '${o}' in ${s}`;!a&&nm(o)&&(I+=`
|
|
983
983
|
|
|
984
984
|
Note: this search ran in basic-regex (BRE) mode, where '|' is a literal pipe \u2014 not alternation. If you intended "A or B", retry with extended: true (extended regex / ERE). If you meant the literal character '|', this empty result stands.`),d({content:I});return}if(w===2){d({content:`grep error: ${g.trim()}`,isError:!0});return}let E=f.trimEnd();E=Ke(E);let A=!1;E.length>m&&(E=E.slice(0,m)+`
|
|
985
|
-
[output truncated]`,A=!0),d({content:E,...A?{truncated:!0}:{}})}),p.on("error",w=>{d({content:`Failed to execute grep: ${w.message}`,isError:!0})})})}}var xi=zr();import{promises as rm}from"fs";var Ti=async(t,e,n)=>{if(!t||typeof t!="object")throw new Error("Invalid input: expected an object");let o=t.path;if(typeof o!="string")throw new Error("Invalid input: path must be a string");let s;try{s=
|
|
985
|
+
[output truncated]`,A=!0),d({content:E,...A?{truncated:!0}:{}})}),p.on("error",w=>{d({content:`Failed to execute grep: ${w.message}`,isError:!0})})})}}var xi=zr();import{promises as rm}from"fs";var Ti=async(t,e,n)=>{if(!t||typeof t!="object")throw new Error("Invalid input: expected an object");let o=t.path;if(typeof o!="string")throw new Error("Invalid input: path must be a string");let s;try{s=re(o,n,"read")}catch(i){return{content:i instanceof Error?i.message:String(i),isError:!0}}try{let i=await rm.readdir(s,{withFileTypes:!0}),a=i.filter(u=>u.isDirectory()).map(u=>`${u.name}/`),c=i.filter(u=>!u.isDirectory()).map(u=>u.name);a.sort(),c.sort();let l=[...a,...c];return l.length===0?{content:"(empty directory)"}:{content:l.join(`
|
|
986
986
|
`)}}catch(i){if(i instanceof Error){let a=i;return a.code==="ENOENT"?{content:`Directory not found: ${s}`,isError:!0}:a.code==="ENOTDIR"?{content:`Not a directory: ${s}`,isError:!0}:a.code==="EACCES"?{content:`Permission denied: ${s}`,isError:!0}:{content:`Error listing directory: ${i.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}};F();function Jr(t,e=()=>{}){let n=new Set;if(!t)return n;for(let r of t.split(",")){let o=r.trim();if(o){if(!/^-?\d+$/.test(o)){e("[allowlist] Ignoring non-numeric chat ID:",o);continue}n.add(Number(o))}}return n}function Vr(t,e=()=>{}){return async(n,r)=>{let o=n.chat?.id;if(o===void 0||!t.has(o)){e("[allowlist] Rejecting update from chat:",o??"<unknown>");return}await r()}}import{readFileSync as am,existsSync as cm}from"fs";import{join as lm}from"path";import{config as z_}from"dotenv";H();F();function Ri(){return y.ANTHROPIC_API_KEY||y.CLAUDE_CODE_OAUTH_TOKEN||ie()}function Pi(){return y.OPENAI_API_KEY||y.CODEX_API_KEY||void 0}function st(t){let e=V(t);return e==="openai-compatible"||e==="openai-codex"?Pi():Ri()}F();import{execFile as om}from"node:child_process";import{promisify as sm}from"node:util";F();H();F();var U_=sm(om);var im=/^[A-Za-z0-9_\-./]*$/,Ii=64;function Ci(t,e){if(t.length>Ii)throw new Error(`Invalid branch prefix from ${e}: length ${t.length} exceeds ${Ii}.`);if(!im.test(t))throw new Error(`Invalid branch prefix from ${e}: '${t}' \u2014 only [A-Za-z0-9_-./] are allowed.`);if(t.startsWith("-"))throw new Error(`Invalid branch prefix from ${e}: '${t}' \u2014 must not start with '-' (would be parsed by git as a flag).`);return t}function Mi(t,e){if(t.trim().length===0)throw new Error(`Invalid worktree base ref from ${e}: '' \u2014 base ref cannot be empty.`);if(t.startsWith("-"))throw new Error(`Invalid worktree base ref from ${e}: '${t}' \u2014 must not start with '-' (would be parsed by git as a flag).`);if(t.includes("\0"))throw new Error(`Invalid worktree base ref from ${e}: contains a NUL byte.`);if(/\s/.test(t))throw new Error(`Invalid worktree base ref from ${e}: '${t}' \u2014 must not contain whitespace.`)}F();var it;function dm(){if(it!==void 0)return it;let t=[lm(process.cwd(),"afk.config.json"),qs(),zs()];for(let e of t)if(cm(e))try{let n=am(e,"utf-8"),r=JSON.parse(n),o={},s=hs(r.models);if(typeof r.model=="string"&&r.model.length>0){let i=r.model.toLowerCase();o.model=ys(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),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 c={};if((a.mode==="primary"||a.mode==="broadcast"||a.mode==="custom")&&(c.mode=a.mode),typeof a.primaryChatId=="number"&&Number.isFinite(a.primaryChatId)&&(c.primaryChatId=a.primaryChatId),Array.isArray(a.targets)){let l=a.targets.filter(d=>typeof d=="number"&&Number.isFinite(d));l.length>0&&(c.targets=l)}i.notify=c}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),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=Ci(r.interactive.worktreeBranchPrefix,`${e}#/interactive/worktreeBranchPrefix`)),typeof r.interactive.worktreeBase=="string"&&r.interactive.worktreeBase.trim().length>0&&(Mi(r.interactive.worktreeBase,`${e}#/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 it={config:o,sourcePath:e,modelsPartial:s},it}catch(n){console.error(`Warning: Failed to parse ${e}:`,n)}return it={config:{},sourcePath:void 0,modelsPartial:{}},it}function Oi(){return dm().config.telegram??{}}F();function um(t,e){return e!==void 0&&Number.isFinite(e)&&e!==0?e:t.find(r=>r>0)??t[0]}function pm(t,e={}){let n=[...t],r=e.mode??"primary";if(r==="broadcast")return n;if(r==="custom"){let s=(e.targets??[]).filter(i=>typeof i=="number"&&Number.isFinite(i)&&i!==0);if(s.length>0)return[...new Set(s)]}let o=um(n,e.primaryChatId);return o!==void 0?[o]:[]}function fm(t){if(!t)return;let e=t.trim();if(!/^-?\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)&&n!==0?n:void 0}function mm(t){if(!t)return;let e=t.trim().toLowerCase();return e==="primary"||e==="broadcast"||e==="custom"?e:void 0}function gm(){let t=Oi().notify??{},e=t.mode??mm(y.AFK_TELEGRAM_NOTIFY_MODE),n=t.primaryChatId??fm(y.AFK_TELEGRAM_PRIMARY_CHAT_ID);return{...e!==void 0?{mode:e}:{},...n!==void 0?{primaryChatId:n}:{},...t.targets!==void 0?{targets:t.targets}:{}}}function Yr(){let t=Jr(y.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return pm(t,gm())}function ge(t,e=4096){if(t.length<=e)return[t];let n=[],r=t;for(;r.length>0;){if(r.length<=e){n.push(r);break}let o=e,s=r.lastIndexOf(`
|
|
987
987
|
`,e);if(s>e-500&&s>0)o=s+1;else{let i=r.slice(0,e).match(/[.!?]\s+(?=[A-Z])/g);if(i&&i.length>0){let a=i[i.length-1];if(a){let c=r.lastIndexOf(a,e);c>e-200&&c>0&&(o=c+2)}}else{let a=r.lastIndexOf(" ",e);a>e-100&&a>0&&(o=a+1)}}n.push(r.slice(0,o).trim()),r=r.slice(o).trim()}return n}function Ut(t){t=t.replace(/[\x02\x03]/g,"");let e=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),n=[];e=e.replace(/^ {0,3}```([\w]*)\n([\s\S]*?)```/gm,(o,s,i)=>{let a=n.length;if(i.trim()===""){let c=s?`(empty ${s} block)`:"(empty code block)";n.push(`<i>${c}</i>`)}else n.push(`<pre>${i}</pre>`);return`FENCED${a}`});let r=[];return e=e.replace(/`([^`]+)`/g,(o,s)=>{let i=r.length;return r.push(`<code>${s}</code>`),`CODE${i}`}),e=e.replace(/\*\*([^*]+)\*\*/g,"<b>$1</b>"),e=e.replace(/__([^_]+)__/g,"<b>$1</b>"),e=e.replace(/\*([^*]+)\*/g,"<i>$1</i>"),e=e.replace(/(^|[^\w])_([^_\n]+?)_(?!\w)/gm,"$1<i>$2</i>"),e=e.replace(/~~([^~]+)~~/g,"<s>$1</s>"),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(o,s,i)=>'<a href="'+i.replace(/"/g,""")+'">'+s+"</a>"),e=e.replace(/^#{1,6}\s+/gm,""),e=e.replace(/\x02CODE(\d+)\x03/g,(o,s)=>r[Number(s)]??o),e=e.replace(/\x02FENCED(\d+)\x03/g,(o,s)=>n[Number(s)]??o),e}function We(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Xr(t,e){return t==="ENOENT"?`\u274C Directory not found: ${e}`:t==="EACCES"?`\u274C Permission denied: ${e}`:`\u274C Unexpected error (${t}): ${e}`}function Mn(t){return`\u23F3 Queued (#${t} in line)`}function N(t){return`\u274C Error: ${t instanceof Error?t.message:t}`}function On(){return"\u26A0\uFE0F An internal error occurred. Please try again."}function Di(t){let e=["\u{1F4CB} Commands:",""," /start \u2014 Show welcome"," /help \u2014 Show this list"," /clear \u2014 Clear conversation history"," /compact \u2014 Summarize older messages"," /model \u2014 Switch Claude model"," /cd \u2014 Change working directory"," /name \u2014 Show or set the session name"," /watch \u2014 Live-tail a CLI session from this chat"," /unwatch \u2014 Stop watching a session","","Also works from the CLI."];return t&&t.length>0&&e.push("","\u{1F4CB} Session commands (from SDK, when using settingSources):","",...t.map(n=>` /${n.replace(/^\//,"")}`)),e.push("","Just send a message to chat with Claude."),e.join(`
|
|
988
988
|
`)}function Qr(){return`\u{1F44B} Welcome! I'm an agent-afk bot powered by Claude.
|
|
@@ -1007,7 +1007,7 @@ Usage: /name <name>`}function $i(){return N("Invalid name \u2014 use letters, nu
|
|
|
1007
1007
|
Resume from CLI:
|
|
1008
1008
|
${e}`:`\u{1F3F7}\uFE0F Named: ${t} (saves on first turn)`}function jt(t){if(!t)return"\u{1F4E6} Conversation compacted (older messages summarized).";let e=t.tokensSavedEstimate!==void 0&&t.tokensSavedEstimate>0?` (~${hm(t.tokensSavedEstimate)} input tokens saved)`:"";return`\u{1F4E6} Compacted ${t.before} \u2192 ${t.after} messages${e}.`}function Kt(t){return t==="aborted"?"\u{1F4E6} Compaction cancelled.":t==="history-too-short"?"\u{1F4E6} Not enough history to compact yet.":t==="not-supported"?"\u{1F4E6} Compaction isn't available for the current model.":t.startsWith("summarization-failed")?`\u26A0\uFE0F Compaction failed: ${t}. History unchanged.`:`\u{1F4E6} Nothing to compact (${t}).`}function hm(t){return t>=1e3?`${Math.round(t/100)/10}k`:String(t)}F();var ym="https://api.telegram.org";async function Bi(t){if(!t.token)throw new Error("push: token is required");if(t.chatId===""||t.chatId==null||t.chatId===0)throw new Error("push: chatId is required");let e=t.fetchImpl??fetch,r=`${t.apiBase??ym}/bot${t.token}/sendMessage`,o={chat_id:t.chatId,text:t.text.slice(0,4096)};t.parseMode&&(o.parse_mode=t.parseMode),t.replyMarkup&&(o.reply_markup=t.replyMarkup);let s=new AbortController,i=setTimeout(()=>s.abort(),1e4);try{let a=await e(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 c;try{c=(await a.json()).description}catch{c=`HTTP ${a.status}`}return{ok:!1,status:a.status,...c!==void 0?{errorMessage:c}:{}}}catch(a){return{ok:!1,status:0,errorMessage:a instanceof Error?a.message:String(a)}}finally{clearTimeout(i)}}var Hi=4096;function bm(t=Bi){return async(e,n)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let o=e.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>Hi)return{content:`Invalid input: message exceeds Telegram's ${Hi}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let s=y.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=Yr();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 c of i){let l=await t({token:s,chatId:c,text:o});l.ok||a.push(`chat ${c}: ${l.errorMessage??`HTTP ${l.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 ji=bm();import{JSDOM as wm}from"jsdom";import{Readability as Sm}from"@mozilla/readability";import vm from"turndown";var Wi=200,Zr=new vm({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});Zr.remove(["script","style","noscript","iframe"]);function Ki(t){return t.replace(/\n{3,}/g,`
|
|
1009
1009
|
|
|
1010
|
-
`).trim()}function km(t){return(t?.textContent??"").replace(/\s+/g," ").trim().length}function Gi(t,e){let r=new wm(t,{url:e}).window.document,o=(r.title??"").trim(),s=null;try{let l=r.cloneNode(!0);s=new Sm(l).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let l=Ki(Zr.turndown(s.content)),d=(s.title??"").trim()||o,u=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:d,markdown:l,textLength:u,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",c=Ki(Zr.turndown(a));return{title:o,markdown:c,textLength:km(i),usedFallback:!0}}var gg=/(text\/html|application\/xhtml\+xml)/i,hg=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,yg=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,bg={"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 ga(t,e){try{return Gi(t,e)}catch{return{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function wg(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(ze(),qe));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function ha(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??wg,o=null,s=t,i=null,a=null;try{let l=await n(t,{headers:bg,redirect:"follow",signal:e.signal});i=l.status,s=l.url||t;let d=l.headers.get("content-type")??"";if(l.ok){if(yg.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await l.text();if(hg.test(d)&&!gg.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};o=ga(u,s)}}catch(l){if(e.signal.aborted||l instanceof Error&&l.message.startsWith("web_scrape markdown mode received binary"))throw l;a=l}if(!(o===null||o.textLength<Wi)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let l=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal}),d=ga(l.html,l.finalUrl);if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:l.finalUrl,usedRender:!0}}catch(l){if(e.signal.aborted)throw l;if(o===null){let d=l instanceof Error?l.message:String(l),u=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${t}: fetch failed (${u}) and render failed (${d}).`);throw p.cause=l,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 ${t} (HTTP ${i??"error"}).`)}var Sg="https://api.search.brave.com/res/v1/web/search",vg=20;function ya(t){return t.replace(/<[^>]*>/g,"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/\s+/g," ").trim()}function kg(t){let e=t.fetchFn??globalThis.fetch;return{name:"brave",async search(n,{limit:r,signal:o}){let s=new URL(Sg);s.searchParams.set("q",n),s.searchParams.set("count",String(Math.min(Math.max(r,1),vg)));let i=await e(s.toString(),{method:"GET",headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":t.apiKey,"User-Agent":"agent-afk/web_scrape"},signal:o});if(!i.ok){let l="";try{let u=await i.text(),p=Tn(u);p&&(l=`: ${p.length>200?p.slice(0,200)+"\u2026":p}`)}catch{}let d=i.statusText?` ${i.statusText}`:"";throw new Error(`Brave Search HTTP ${i.status}${d}${l}`)}let a;try{a=await i.json()}catch(l){throw new Error(`Brave Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(a.web?.results??[]).slice(0,r).map(l=>({title:ya(l.title??"")||"(untitled)",url:l.url??"",description:ya(l.description??"")})).filter(l=>l.url.length>0)}}}function ba(t){return t.braveApiKey!==void 0&&t.braveApiKey.trim()!==""?kg({apiKey:t.braveApiKey,fetchFn:t.fetchFn}):{error:'web_scrape search mode requires a search backend. Set BRAVE_SEARCH_API_KEY (free tier at https://brave.com/search/api/) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function wa(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
1010
|
+
`).trim()}function km(t){return(t?.textContent??"").replace(/\s+/g," ").trim().length}function Gi(t,e){let r=new wm(t,{url:e}).window.document,o=(r.title??"").trim(),s=null;try{let l=r.cloneNode(!0);s=new Sm(l).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let l=Ki(Zr.turndown(s.content)),d=(s.title??"").trim()||o,u=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:d,markdown:l,textLength:u,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",c=Ki(Zr.turndown(a));return{title:o,markdown:c,textLength:km(i),usedFallback:!0}}var gg=/(text\/html|application\/xhtml\+xml)/i,hg=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,yg=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,bg={"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 ga(t,e){try{return Gi(t,e)}catch(n){return D("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function wg(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(ze(),qe));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function ha(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??wg,o=null,s=t,i=null,a=null;try{let l=await n(t,{headers:bg,redirect:"follow",signal:e.signal});i=l.status,s=l.url||t;let d=l.headers.get("content-type")??"";if(l.ok){if(yg.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await l.text();if(hg.test(d)&&!gg.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};o=ga(u,s)}}catch(l){if(e.signal.aborted||l instanceof Error&&l.message.startsWith("web_scrape markdown mode received binary"))throw l;a=l}if(!(o===null||o.textLength<Wi)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let l=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal}),d=ga(l.html,l.finalUrl);if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:l.finalUrl,usedRender:!0}}catch(l){if(e.signal.aborted)throw l;if(o===null){let d=l instanceof Error?l.message:String(l),u=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${t}: fetch failed (${u}) and render failed (${d}).`);throw p.cause=l,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 ${t} (HTTP ${i??"error"}).`)}var Sg="https://api.search.brave.com/res/v1/web/search",vg=20;function ya(t){return t.replace(/<[^>]*>/g,"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/\s+/g," ").trim()}function kg(t){let e=t.fetchFn??globalThis.fetch;return{name:"brave",async search(n,{limit:r,signal:o}){let s=new URL(Sg);s.searchParams.set("q",n),s.searchParams.set("count",String(Math.min(Math.max(r,1),vg)));let i=await e(s.toString(),{method:"GET",headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":t.apiKey,"User-Agent":"agent-afk/web_scrape"},signal:o});if(!i.ok){let l="";try{let u=await i.text(),p=Tn(u);p&&(l=`: ${p.length>200?p.slice(0,200)+"\u2026":p}`)}catch{}let d=i.statusText?` ${i.statusText}`:"";throw new Error(`Brave Search HTTP ${i.status}${d}${l}`)}let a;try{a=await i.json()}catch(l){throw new Error(`Brave Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(a.web?.results??[]).slice(0,r).map(l=>({title:ya(l.title??"")||"(untitled)",url:l.url??"",description:ya(l.description??"")})).filter(l=>l.url.length>0)}}}function ba(t){return t.braveApiKey!==void 0&&t.braveApiKey.trim()!==""?kg({apiKey:t.braveApiKey,fetchFn:t.fetchFn}):{error:'web_scrape search mode requires a search backend. Set BRAVE_SEARCH_API_KEY (free tier at https://brave.com/search/api/) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function wa(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
1011
1011
|
|
|
1012
1012
|
(no results)`;let n=[`# Search results for "${t}"`,""];return e.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(`
|
|
1013
1013
|
`).trimEnd()}var _g=3e4,Eg=12e4,Ag=1e6,xg=1e7,Tg=`
|
|
@@ -1032,10 +1032,10 @@ ${s}`}}}return{...t,systemPrompt:r}}import Lh from"openai";import{randomUUID as
|
|
|
1032
1032
|
`+Ir});let r=Ja();if(this.wireMode==="responses"){let o=this.opts.auth.source==="chatgpt-oauth";if(o&&sc(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=rc(n,this.openAITools),i={model:this.currentModel,input:s.input,stream:!0},a=s.instructions??(o?oc:void 0);a!==void 0&&(i.instructions=a),o&&(i.store=!1),s.tools&&s.tools.length>0&&(i.tools=s.tools);let c;try{c=await this.client.responses.create(i,{signal:e.signal})}catch(l){return e.signal.aborted||(yield{type:"error",error:this.clarifyResponsesError(l,o)}),null}try{for await(let l of c){if(this.closed)return null;for(let d of nc(l,r,this.initSessionId))yield d}}catch(l){return e.signal.aborted||(yield{type:"error",error:this.clarifyResponsesError(l,o)}),null}}else{let o={model:this.currentModel,messages:n,stream:!0,stream_options:{include_usage:!0}};this.openAITools&&this.openAITools.length>0&&(o.tools=this.openAITools);let s;try{s=await this.client.chat.completions.create(o,{signal:e.signal})}catch(i){return e.signal.aborted||(yield{type:"error",error:i instanceof Error?i:new Error(String(i))}),null}try{for await(let i of s){if(this.closed)return null;for(let a of Va(i,r,this.initSessionId))yield a}}catch(i){return e.signal.aborted||(yield{type:"error",error:i instanceof Error?i:new Error(String(i))}),null}}return{state:r,events:[],text:r.assistantText,needsToolDispatch:Xa(r)&&r.toolCallsByIndex.size>0}}async*dispatchAndAppend(e,n){if(!this.toolDispatcher)return;let r=ko(e);for(let a of r)a.id.length===0&&(a.id=lc());let{calls:o,parseErrors:s}=Za(r,n);for(let a of o)yield{type:"tool.use.start",toolUseId:a.id,toolName:a.name,toolInput:Bh(a.name,a.input),sessionId:this.initSessionId};let i=[];if(n.aborted)for(let a of o){let c={content:"Tool call aborted",isError:!0};i.push({call:a,result:c}),yield{type:"tool.output",toolUseId:a.id,toolName:a.name,content:c.content,isError:!0,sessionId:this.initSessionId}}else{let a;try{if(this.toolDispatcher.executeBatch)a=await this.toolDispatcher.executeBatch(o);else{a=[];for(let c of o){if(n.aborted){a.push({content:"Tool call aborted",isError:!0});continue}try{a.push(await this.toolDispatcher.execute(c))}catch(l){let d=l instanceof Error?l.message:String(l);a.push({content:`Tool execution threw: ${d}`,isError:!0})}}}}catch(c){let l=c instanceof Error?c.message:String(c);a=o.map(()=>({content:`Tool batch execution failed: ${l}`,isError:!0}))}for(let c=0;c<o.length;c++){let l=o[c],d=a[c],u=s.get(l.id);u!==void 0&&(d={content:`${u}
|
|
1033
1033
|
--
|
|
1034
1034
|
${d.content}`,isError:!0,...d.truncated===!0?{truncated:!0}:{}}),i.push({call:l,result:d}),yield{type:"tool.output",toolUseId:l.id,toolName:l.name,content:d.content,...d.isError===!0?{isError:!0}:{},...d.truncated===!0?{truncated:!0}:{},sessionId:this.initSessionId},d.render?.diff&&(yield{type:"tool.diff",toolUseId:l.id,diff:d.render.diff,sessionId:this.initSessionId})}}this.priorTurns.push(ec(e.assistantText,r,e.reasoningText));for(let a of tc(i))this.priorTurns.push(a)}async interrupt(){let e=this.abortController;if(e&&!e.signal.aborted){e.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(e){e!==void 0&&(this.currentModel=e)}async setPermissionMode(e){this.currentPermissionMode=dc(e)}setCwd(e){this.toolDispatcher?.setResolveBase?.(e)}async supportedCommands(){try{return ut().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return[{value:"gpt-4o",displayName:"GPT-4o",description:"OpenAI flagship multimodal"},{value:"gpt-4o-mini",displayName:"GPT-4o mini",description:"Fast/cheap GPT-4o"},{value:"gpt-4.1",displayName:"GPT-4.1",description:"Long-context GPT-4"},{value:"gpt-4.1-mini",displayName:"GPT-4.1 mini",description:"Fast 4.1 variant"},{value:"o1",displayName:"o1",description:"Reasoning model"},{value:"o1-mini",displayName:"o1 mini",description:"Fast reasoning"},{value:"o3-mini",displayName:"o3 mini",description:"Newer reasoning, faster"}]}async supportedAgents(){return[]}async getContextUsage(){let e=this.lastUsage,n=Jt(this.currentModel),r;if(e&&n>0){let i=dt(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=$n(e);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(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{authSource:this.opts.auth.source}}async rewindFiles(e,n){return{canRewind:!1,error:`${Eo} provider does not support file checkpoint rewind yet.`}}close(){this.closed=!0;let e=this.abortController;e&&!e.signal.aborted?e.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.(),D(`\u{1F7E2} ${Eo}: closed`)}};function Uh(t){let e={apiKey:t.apiKey};return t.baseURL!==void 0&&(e.baseURL=t.baseURL),t.defaultHeaders!==void 0&&(e.defaultHeaders=t.defaultHeaders),new Lh(e)}function Bh(t,e){if(!e||typeof e!="object")return"";let n=e;if(t==="skill"||t==="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(`
|
|
1035
|
-
`)[0];return" "+(i.length>80?i.slice(0,77)+"\u2026":i)}let s=n.query??n.pattern??n.url??n.description;return typeof s=="string"?" "+s:""}function uc(t,e,n={}){let r=Yt(t.apiKey,n.authDeps),o=t.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=typeof t.model=="string"?t.model:"gpt-4o-mini",i=
|
|
1035
|
+
`)[0];return" "+(i.length>80?i.slice(0,77)+"\u2026":i)}let s=n.query??n.pattern??n.url??n.description;return typeof s=="string"?" "+s:""}function uc(t,e,n={}){let r=Yt(t.apiKey,n.authDeps),o=t.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=typeof t.model=="string"?t.model:"gpt-4o-mini",i=te(s)??s,a={auth:r,model:i,synthesizedSessionId:o,promptStream:e,config:t};return n.baseURL!==void 0&&(a.baseURL=n.baseURL),n.toolDispatcher!==void 0&&(a.toolDispatcher=n.toolDispatcher),n.mcpManager!==void 0&&(a.mcpManager=n.mcpManager),n.useResponsesApi!==void 0&&(a.useResponsesApi=n.useResponsesApi),new Un(a)}import Hh from"openai";var jh=null;async function pc(t){let{apiKey:e,baseURL:n,model:r,system:o,user:s,maxTokens:i=64,signal:a,clientFactory:c}=t,l=Yt(e);if(l.apiKey===null)throw new Error("oneShotChatCompletion: no usable OpenAI auth (set OPENAI_API_KEY or pass apiKey)");let d={apiKey:l.apiKey};n!==void 0&&(d.baseURL=n);let u=c??jh,p=u?u(d):new Hh(d),f=r.includes("/")?r.slice(r.lastIndexOf("/")+1):r,g=/^o[0-9]/.test(f)?{max_completion_tokens:i}:{max_tokens:i},k=(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 k=="string"?k.trim():""}var xo="openai-compatible",de=class{name=xo;providerOpts;memoryStore;schemas;_sharedReadRoots;_sharedWriteRoots;_initialResolveBase;_presenceSessionId=null;constructor(e={}){this.providerOpts=e,this.memoryStore=e.memoryStore??new ve;let n=[...ce];e.subagentExecutor&&n.push(Ce),e.skillExecutor&&n.push(Me),e.composeExecutor&&n.push(Oe),e.readOnlyMemory===!0?n.push(nt):n.push(...De),n.push(me),this.schemas=n}query(e){let n=e.config,r=n.permissionMode??"default";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=Lt({surface:this.providerOpts.surface??"cli",cwd:n.cwd??process.cwd(),modelName:s,providerName:xo,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 le?o.toolDefs.map(f=>f.name):[],getMcpTools:()=>this.providerOpts.mcpManager?.getMcpTools()??[],getSubagents:()=>this.providerOpts.subagentExecutor?this.providerOpts.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});o=this.providerOpts.tools?Nt(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}:{}});let a={},c=n.openaiBaseUrl??this.providerOpts.baseURL;if(c!==void 0&&(a.baseURL=c),a.toolDispatcher=o,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 f=n.sessionId,g=i.getWorkspace();$t({sessionId:f,surface:this.providerOpts.surface??"cli",cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:xo,name:s},workspace:g,pid:process.pid}),process.once("exit",()=>{ke(f)}),process.once("SIGINT",()=>{ke(f),process.exit(130)}),process.once("SIGTERM",()=>{ke(f),process.exit(143)})}let d=rt({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()}),u=typeof n.systemPrompt=="string"?n.systemPrompt:void 0,p={...n,systemPrompt:u!==void 0?`${u}
|
|
1036
1036
|
|
|
1037
1037
|
${d}`:d};return uc(p,e.prompt,a)}buildDispatcher(e,n){let r=lt(e,n.cwd),o=Ft(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[c,l]of o)this.providerOpts.readOnlyMemory===!0&&c!=="memory_search"||r.set(c,l);n.runtimeStateSource&&r.set("get_runtime_state",ot(n.runtimeStateSource));let s=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[c,l]of this.providerOpts.mcpManager.getMcpHandlers())r.set(c,l);let i=n.isSkillDispatch?this.schemas.filter(c=>c.name!=="ask_question"&&c.name!=="terminal_font_size"):this.schemas,a={handlers:r,schemas:[...i,...s]};return this.providerOpts.hookRegistry!==void 0&&(a.hookRegistry=this.providerOpts.hookRegistry),this.providerOpts.permissions!==void 0&&(a.permissions=this.providerOpts.permissions),this.providerOpts.subagentExecutor!==void 0&&(a.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(a.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(a.composeExecutor=this.providerOpts.composeExecutor),n.cwd!==void 0&&(a.cwd=n.cwd),n.readRoots!==void 0&&(a.readRoots=n.readRoots),n.writeRoots!==void 0&&(a.writeRoots=n.writeRoots),n.sessionId!==void 0&&(a.sessionId=n.sessionId),n.parentSessionId!==void 0&&(a.parentSessionId=n.parentSessionId),n.traceWriter!==void 0&&(a.traceWriter=n.traceWriter),this.providerOpts.readOnlyBash===!0&&(a.readOnlyBash=!0),new le(a)}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e)}}addReadRoot(e,n="slash",r){this.ensureSharedRoots();let o=Ao.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this.appendProviderAuditLog({action:"grant-read",path:o,source:n,sessionId:r})}addWriteRoot(e,n="slash",r){this.ensureSharedRoots();let o=Ao.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this._sharedWriteRoots.includes(o)||this._sharedWriteRoots.push(o),this.appendProviderAuditLog({action:"grant-write",path:o,source:n,sessionId:r})}revokeRoot(e,n="slash",r){if(!this._sharedReadRoots)return;let o=Ao.resolve(e);if(this._initialResolveBase&&o===this._initialResolveBase)return;let s=this._sharedReadRoots.indexOf(o);if(s!==-1&&this._sharedReadRoots.splice(s,1),this._sharedWriteRoots){let i=this._sharedWriteRoots.indexOf(o);i!==-1&&this._sharedWriteRoots.splice(i,1)}this.appendProviderAuditLog({action:"revoke",path:o,source:n,sessionId:r})}getGrants(){return{resolveBase:this._initialResolveBase,readRoots:this._sharedReadRoots?.slice()??[],writeRoots:this._sharedWriteRoots?.slice()??[]}}appendProviderAuditLog(e){try{let n=tt();Wh(Gh(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??null,action:e.action,path:e.path,source:e.source});Kh(n,r+`
|
|
1038
|
-
`)}catch{}}close(){this.memoryStore.close()}async complete(e){let n={model:e.model??"gpt-4o-mini",system:e.system,user:e.user,maxTokens:e.maxTokens??64};e.apiKey!==void 0&&(n.apiKey=e.apiKey);let r=e.baseUrl??this.providerOpts.baseURL;return r!==void 0&&(n.baseURL=r),e.signal&&(n.signal=e.signal),pc(n)}},To=new de;var qh=new Set(["Agent","Task","agent"]),zh=new Set(["Skill","skill"]),Jh=new Set(["Compose","compose"]),gT=new Set([...qh,...Jh,...zh]);var fc=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","memory_search",...je];H();H();var TT=300*1e3;var _R=[...vn,...je,"memory_search","agent","skill"],Zh=["read_file","glob","grep","list_directory","bash","web_scrape",...je,"memory_search","agent","skill"];function gc(t,e){let n={allowedTools:[...fc]};return V(typeof e=="string"?e:void 0)==="openai-compatible"?new de({permissions:n}):new _e({permissions:n})}function Po(t){let e=ey(t);return e!==void 0?e:ty(t)}function ey(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=e.exec(t))!==null;)n=r[1];if(n)return hc(n.trim())}function ty(t){for(let e=t.length-1;e>=0;e--){if(t[e]!=="}")continue;let n=ny(t,e);if(n===-1)continue;let r=t.slice(n,e+1),o=hc(r);if(o!==void 0)return o}}function ny(t,e){let n=0,r=!1,o=!1;for(let s=e;s>=0;s--){let i=t[s];if(o){o=!1;continue}if(r){if(i==="\\"){o=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="}")n++;else if(i==="{"&&(n--,n===0))return s}return-1}function hc(t){try{return JSON.parse(t)}catch{return}}function Io(){return{toolCalls:[],toolResults:[],thinkingPresent:!1,turnCount:0}}function yc(t,e,n,r,o){if(!r)return{id:t,status:e,message:n,trace:o};let s=Po(n.content),i=r.safeParse(s);return i.success?{id:t,status:e,message:n,output:i.data,trace:o}:{id:t,status:"failed",message:n,error:new Error(`structured output did not match schema: ${i.error.message}`,{cause:i.error}),schemaError:i.error,trace:o}}function bc(t,e,n,r){let o=n instanceof Error?n:new Error(String(n));return{id:t,status:e,error:o,trace:r}}function Y(t){return`${t.status}${t.error?`: ${t.error.message}`:""}`}var Bn=class{constructor(e,n,r,o,s,i,a,c,l,d,u,p,f,g,m){this.id=e;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=c;this.parentInputStreamRef=l;this.parentAbortSignal=d;this.agentType=u;this.traceWriter=g;this.onSubagentSucceeded=m;this.progressSink=p,this.parentId=f}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=Io();lastStreamedContent="";get status(){return this.currentStatus}async run(e,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=Pt(this.streamToFinalMessage(e,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",$e(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?($e(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):($e(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(e,n){let r,o;this.lastStreamedContent="",this.currentTrace=Io();let s=n??this.progressSink??Ie(),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(e)){if(s&&s(a,i),a.type==="chunk"){let c=a.chunk;c.type==="content"?this.lastStreamedContent+=c.content:c.type==="tool_use_detail"?this.currentTrace.toolCalls.push({id:c.toolUseId,name:c.toolName,inputBytes:Buffer.byteLength(c.toolInput,"utf8")}):c.type==="tool_result"?this.currentTrace.toolResults.push({toolUseId:c.toolUseId,isError:c.isError,truncated:c.truncated,sizeBytes:c.sizeBytes}):c.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 c=a.metadata.usage;this.currentTrace.usage={inputTokens:typeof c.input_tokens=="number"?c.input_tokens:void 0,outputTokens:typeof c.output_tokens=="number"?c.output_tokens:void 0,cacheReadTokens:typeof c.cache_read_input_tokens=="number"?c.cache_read_input_tokens:void 0,cacheCreationTokens:typeof c.cache_creation_input_tokens=="number"?c.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(e,n){try{let r=await this.run(e,n);return yc(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=bc(this.id,this.currentStatus,r,this.currentTrace);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(e,n,r){let o;if(r){let s=this.progressSink??Ie();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{D("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",$e(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(e)}}async teardown(){if(this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async dispatchStopAndRelease(e){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let n=await Os(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:e,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)D(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){D(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}};var ry=async(t,e)=>({action:"decline"}),$=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentCwd;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(e={}){if(this.parentCanUseTool=e.canUseTool,this.hookRegistry=e.hookRegistry,this.progressSink=e.progressSink,this.parentApiKey=e.apiKey,this.parentBaseUrl=e.baseUrl,this.parentCwd=e.cwd,this.onSubagentSucceededCb=e.onSubagentSucceeded,this.abortGraph=new Tt(e.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),e.parentAbortSignal){let n=e.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(e=>({id:e.id,status:e.status}))}get(e){return this.active.get(e)}onChildAborted(e){return this.abortGraph.onChildAborted(this.rootId,e)}setOnSubagentSucceeded(e){this.onSubagentSucceededCb=e}abortAll(e,n="user_signal"){this.abortGraph.abort(this.rootId,e,n)}async forkSubagent(e){if(e.phaseRole!==void 0&&e.phaseRole!=="read-write"&&e.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${e.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=`${e.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=e.parent.sessionId,o=e.config.hookRegistry??this.hookRegistry??e.parent.hookRegistry;o&&await Ms(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal,...e.config.traceWriter?{traceWriter:e.config.traceWriter}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i={...e.config,resume:r,forkSession:r?!0:e.config.forkSession,abortSignal:s.signal,apiKey:e.config.apiKey||this.parentApiKey,baseUrl:e.config.baseUrl??this.parentBaseUrl,...e.config.parentSessionId===void 0&&e.parent.sessionId!==void 0?{parentSessionId:e.parent.sessionId}:{},...e.config.phaseRole===void 0&&e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},...e.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},hookRegistry:o,permissionBubbler:e.config.permissionBubbler??(this.parentCanUseTool!==void 0&&e.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...e.denyElicitations===!0?{onElicitation:ry}:{},...e.phaseRole==="read-only"?{provider:gc("read-only",e.config.model)}:{}},a;try{a=new Je(i)}catch(m){throw this.abortGraph.dispose(n),m}let c=e.parent.getInputStreamRef?.(),l=e.parent.abortSignal,d=this.progressSink??Ie(),u=e.agentType?.trim()||void 0,p=e.parentId?.trim()||void 0,f=new Bn(n,a,s,this.abortGraph,e.outputSchema,e.config.timeoutMs??Rt,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},c,l,u??e.idPrefix,d,p??e.parent.sessionId,e.config.traceWriter,this.onSubagentSucceededCb);this.active.set(n,f);let g=typeof e.config.model=="string"?e.config.model:JSON.stringify(e.config.model);return $e(e.config.traceWriter,{transition:"started",subagentId:n,parentId:e.parent.sessionId??this.rootId,model:g,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await ae({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,model:g,parent_session_id:e.parent.sessionId}),f}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}};async function Hn(t,e={}){let{failFast:n=!0,teardown:r=!0}=e;if(t.length===0)return[];let o=new Array(t.length),s=new Set(t.map((a,c)=>c)),i=t.map((a,c)=>a.handle.runToResult(a.prompt).then(l=>{if(o[c]=l,s.delete(c),n&&l.status!=="succeeded")for(let d of s){let u=t[d];u&&u.handle.status==="running"&&u.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(t.map(a=>a.handle.teardown())),o}import{fileURLToPath as oy}from"node:url";import{dirname as sy}from"node:path";var iy=oy(import.meta.url),VR=sy(iy),re={name:"research-agent",systemPrompt:`---
|
|
1038
|
+
`)}catch{}}close(){this.memoryStore.close()}async complete(e){let n={model:e.model??"gpt-4o-mini",system:e.system,user:e.user,maxTokens:e.maxTokens??64};e.apiKey!==void 0&&(n.apiKey=e.apiKey);let r=e.baseUrl??this.providerOpts.baseURL;return r!==void 0&&(n.baseURL=r),e.signal&&(n.signal=e.signal),pc(n)}},To=new de;var qh=new Set(["Agent","Task","agent"]),zh=new Set(["Skill","skill"]),Jh=new Set(["Compose","compose"]),hT=new Set([...qh,...Jh,...zh]);var fc=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","memory_search",...je];H();H();var RT=300*1e3;var ER=[...vn,...je,"memory_search","agent","skill"],Zh=["read_file","glob","grep","list_directory","bash","web_scrape",...je,"memory_search","agent","skill"];function gc(t,e){let n={allowedTools:[...fc]};return V(typeof e=="string"?e:void 0)==="openai-compatible"?new de({permissions:n}):new _e({permissions:n})}function Po(t){let e=ey(t);return e!==void 0?e:ty(t)}function ey(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=e.exec(t))!==null;)n=r[1];if(n)return hc(n.trim())}function ty(t){for(let e=t.length-1;e>=0;e--){if(t[e]!=="}")continue;let n=ny(t,e);if(n===-1)continue;let r=t.slice(n,e+1),o=hc(r);if(o!==void 0)return o}}function ny(t,e){let n=0,r=!1,o=!1;for(let s=e;s>=0;s--){let i=t[s];if(o){o=!1;continue}if(r){if(i==="\\"){o=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="}")n++;else if(i==="{"&&(n--,n===0))return s}return-1}function hc(t){try{return JSON.parse(t)}catch{return}}function Io(){return{toolCalls:[],toolResults:[],thinkingPresent:!1,turnCount:0}}function yc(t,e,n,r,o){if(!r)return{id:t,status:e,message:n,trace:o};let s=Po(n.content),i=r.safeParse(s);return i.success?{id:t,status:e,message:n,output:i.data,trace:o}:{id:t,status:"failed",message:n,error:new Error(`structured output did not match schema: ${i.error.message}`,{cause:i.error}),schemaError:i.error,trace:o}}function bc(t,e,n,r){let o=n instanceof Error?n:new Error(String(n));return{id:t,status:e,error:o,trace:r}}function Y(t){return`${t.status}${t.error?`: ${t.error.message}`:""}`}var Bn=class{constructor(e,n,r,o,s,i,a,c,l,d,u,p,f,g,m){this.id=e;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=c;this.parentInputStreamRef=l;this.parentAbortSignal=d;this.agentType=u;this.traceWriter=g;this.onSubagentSucceeded=m;this.progressSink=p,this.parentId=f}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=Io();lastStreamedContent="";get status(){return this.currentStatus}async run(e,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=Pt(this.streamToFinalMessage(e,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",$e(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?($e(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):($e(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(e,n){let r,o;this.lastStreamedContent="",this.currentTrace=Io();let s=n??this.progressSink??Ie(),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(e)){if(s&&s(a,i),a.type==="chunk"){let c=a.chunk;c.type==="content"?this.lastStreamedContent+=c.content:c.type==="tool_use_detail"?this.currentTrace.toolCalls.push({id:c.toolUseId,name:c.toolName,inputBytes:Buffer.byteLength(c.toolInput,"utf8")}):c.type==="tool_result"?this.currentTrace.toolResults.push({toolUseId:c.toolUseId,isError:c.isError,truncated:c.truncated,sizeBytes:c.sizeBytes}):c.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 c=a.metadata.usage;this.currentTrace.usage={inputTokens:typeof c.input_tokens=="number"?c.input_tokens:void 0,outputTokens:typeof c.output_tokens=="number"?c.output_tokens:void 0,cacheReadTokens:typeof c.cache_read_input_tokens=="number"?c.cache_read_input_tokens:void 0,cacheCreationTokens:typeof c.cache_creation_input_tokens=="number"?c.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(e,n){try{let r=await this.run(e,n);return yc(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=bc(this.id,this.currentStatus,r,this.currentTrace);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(e,n,r){let o;if(r){let s=this.progressSink??Ie();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{D("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",$e(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(e)}}async teardown(){if(this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async dispatchStopAndRelease(e){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let n=await Os(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:e,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)D(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){D(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}};var ry=async(t,e)=>({action:"decline"}),$=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentCwd;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(e={}){if(this.parentCanUseTool=e.canUseTool,this.hookRegistry=e.hookRegistry,this.progressSink=e.progressSink,this.parentApiKey=e.apiKey,this.parentBaseUrl=e.baseUrl,this.parentCwd=e.cwd,this.onSubagentSucceededCb=e.onSubagentSucceeded,this.abortGraph=new Tt(e.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),e.parentAbortSignal){let n=e.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(e=>({id:e.id,status:e.status}))}get(e){return this.active.get(e)}onChildAborted(e){return this.abortGraph.onChildAborted(this.rootId,e)}setOnSubagentSucceeded(e){this.onSubagentSucceededCb=e}abortAll(e,n="user_signal"){this.abortGraph.abort(this.rootId,e,n)}async forkSubagent(e){if(e.phaseRole!==void 0&&e.phaseRole!=="read-write"&&e.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${e.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=`${e.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=e.parent.sessionId,o=e.config.hookRegistry??this.hookRegistry??e.parent.hookRegistry;o&&await Ms(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal,...e.config.traceWriter?{traceWriter:e.config.traceWriter}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i={...e.config,resume:r,forkSession:r?!0:e.config.forkSession,abortSignal:s.signal,apiKey:e.config.apiKey||this.parentApiKey,baseUrl:e.config.baseUrl??this.parentBaseUrl,...e.config.parentSessionId===void 0&&e.parent.sessionId!==void 0?{parentSessionId:e.parent.sessionId}:{},...e.config.phaseRole===void 0&&e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},...e.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},hookRegistry:o,permissionBubbler:e.config.permissionBubbler??(this.parentCanUseTool!==void 0&&e.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...e.denyElicitations===!0?{onElicitation:ry}:{},...e.phaseRole==="read-only"?{provider:gc("read-only",e.config.model)}:{}},a;try{a=new Je(i)}catch(m){throw this.abortGraph.dispose(n),m}let c=e.parent.getInputStreamRef?.(),l=e.parent.abortSignal,d=this.progressSink??Ie(),u=e.agentType?.trim()||void 0,p=e.parentId?.trim()||void 0,f=new Bn(n,a,s,this.abortGraph,e.outputSchema,e.config.timeoutMs??Rt,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},c,l,u??e.idPrefix,d,p??e.parent.sessionId,e.config.traceWriter,this.onSubagentSucceededCb);this.active.set(n,f);let g=typeof e.config.model=="string"?e.config.model:JSON.stringify(e.config.model);return $e(e.config.traceWriter,{transition:"started",subagentId:n,parentId:e.parent.sessionId??this.rootId,model:g,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await ae({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,model:g,parent_session_id:e.parent.sessionId}),f}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}};async function Hn(t,e={}){let{failFast:n=!0,teardown:r=!0}=e;if(t.length===0)return[];let o=new Array(t.length),s=new Set(t.map((a,c)=>c)),i=t.map((a,c)=>a.handle.runToResult(a.prompt).then(l=>{if(o[c]=l,s.delete(c),n&&l.status!=="succeeded")for(let d of s){let u=t[d];u&&u.handle.status==="running"&&u.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(t.map(a=>a.handle.teardown())),o}import{fileURLToPath as oy}from"node:url";import{dirname as sy}from"node:path";var iy=oy(import.meta.url),YR=sy(iy),oe={name:"research-agent",systemPrompt:`---
|
|
1039
1039
|
name: research-agent
|
|
1040
1040
|
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.
|
|
1041
1041
|
model: sonnet
|
|
@@ -1088,12 +1088,12 @@ Unless the dispatcher specifies a different schema, return:
|
|
|
1088
1088
|
**\`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\`.
|
|
1089
1089
|
|
|
1090
1090
|
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\`.
|
|
1091
|
-
`,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."};H();H();import{existsSync as Le,readdirSync as my,readFileSync as gy}from"fs";import{join as Ae}from"path";H();import{existsSync as Co,readFileSync as ly,readdirSync as dy,statSync as uy}from"fs";import{join as Qt,resolve as Sc}from"path";import{existsSync as ay,mkdirSync as
|
|
1091
|
+
`,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."};H();H();import{existsSync as Le,readdirSync as my,readFileSync as gy}from"fs";import{join as Ae}from"path";H();import{existsSync as Co,readFileSync as ly,readdirSync as dy,statSync as uy}from"fs";import{join as Qt,resolve as Sc}from"path";import{existsSync as ay,mkdirSync as ZR,readFileSync as cy,renameSync as eP,writeFileSync as tP,unlinkSync as nP}from"fs";H();function wc(t=mn()){if(!ay(t))return jn();try{let e=cy(t,"utf8"),n=JSON.parse(e);if(!n||typeof n!="object")return jn();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 jn()}catch{return jn()}}function jn(){return{version:2,plugins:{},marketplaces:{}}}var py=5,vc="cache",Xt;function Ee(t=Ze()){Xt||(Xt=new Map);let e=Xt.get(t);if(e)return[...e];if(!Co(t))return Xt.set(t,[]),[];let n=t===Ze()?mn():Qt(t,".index.json"),r=wc(n),o=[];return kc(t,t,0,o,new Set,r.plugins),Xt.set(t,o),[...o]}function kc(t,e,n,r,o,s){if(n>py||o.has(e))return;if(o.add(e),Co(Qt(e,".claude-plugin","plugin.json"))){let a=Mo(t,e);if(a===null){r.push({type:"local",path:e});return}if(a.layout==="cache"){let l=s[a.key];if(!l||l.enabled===!1)return;r.push({type:"local",path:e});return}let c=s[a.key];if(c&&c.enabled===!1)return;r.push({type:"local",path:e});return}let i;try{i=dy(e)}catch{return}for(let a of i){if(a.startsWith("."))continue;let c=Qt(e,a),l;try{l=uy(c)}catch{continue}l.isDirectory()&&kc(t,c,n+1,r,o,s)}}function Mo(t,e){if(!e.startsWith(t))return null;let n=e.slice(t.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(s=>s.length>0);if(r.length===0)return null;if(r[0]===vc&&r.length>=3){let s=r[1];if(s){let i=Qt(t,vc,s),c=fy(i,e)??r[2];if(c)return{layout:"cache",key:`${s}:${c}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function fy(t,e){let n=Qt(t,".claude-plugin","marketplace.json");if(!Co(n))return null;let r;try{r=JSON.parse(ly(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=Sc(e);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("../"))&&Sc(t,a.source)===s)return a.name}return null}var _c=["command","agent"];function Ec(t=Z()){let e=[],n=Ae(t,"skills");if(Le(n))for(let r of Kn(n)){let o=Ae(n,r,"SKILL.md");Le(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of _c){let o=Ae(t,`${r}s`);if(Le(o))for(let s of Kn(o))s.endsWith(".md")&&e.push({path:Ae(o,s),type:r,source:"user"})}return e}function Ac(t=Ze()){if(!Le(t))return[];let e=[],n=Ee(t);for(let r of n){let s=Mo(t,r.path)?.key,i=Ae(r.path,"skills");if(Le(i))for(let a of Kn(i)){let c=Ae(i,a,"SKILL.md");if(!Le(c))continue;let l={path:c,type:"skill",source:"plugin"};s&&(l.plugin_key=s),e.push(l)}for(let a of _c){let c=Ae(r.path,`${a}s`);if(Le(c))for(let l of Kn(c)){if(!l.endsWith(".md"))continue;let d={path:Ae(c,l),type:a,source:"plugin"};s&&(d.plugin_key=s),e.push(d)}}}return e}function xc(t=Ae(Z(),"settings.json")){if(!Le(t))return[];try{let e=gy(t,"utf8"),r=JSON.parse(e).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 Kn(t){try{return my(t).filter(e=>!e.startsWith("."))}catch{return[]}}var Ic=K.object({path:K.string(),type:K.enum(["skill","command","agent","hook"]),source:K.enum(["user","plugin"]),plugin_key:K.string().optional(),verdict:K.enum(["correct","misfit","outlier"]),recommended_type:K.string(),rationale:K.string(),confidence:K.enum(["high","med","low"])}),Pc=K.record(K.string(),K.record(K.string(),K.number())),AP=K.object({inventory:K.object({user:Pc,plugin:Pc}),misfits:K.array(Ic),briefs_written:K.number(),total_artifacts:K.number()}),hy=K.object({writeBriefs:K.boolean().optional(),scope:K.enum(["user","plugin","all"]).optional()}),yy=["skill","command","agent"],Cc=["skill","command","agent","hook"];function by(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function wy(t){let e=()=>{let s={};for(let i of Cc)s[i]={correct:0,misfit:0,outlier:0};return s},n={user:e(),plugin:e()};for(let s of t)n[s.source][s.type][s.verdict]+=1;let r={high:0,med:1,low:2},o=t.filter(s=>s.verdict==="misfit").slice().sort((s,i)=>r[s.confidence]-r[i.confidence]);return{inventory:n,misfits:o}}function Sy(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function vy(t){let e=t.filter(o=>o.source==="user"),n=t.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),e.length===0)r.push("(none discovered)");else for(let o of e)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(`
|
|
1092
1092
|
`)}function ky(t,e){let n=["","## Discovered hooks (audit only these)",""];if(n.push(`Settings file (use this absolute path verbatim in each verdict's \`path\` field): \`${t}\``),n.push(""),e.length===0)return n.push("(no hooks discovered)"),n.join(`
|
|
1093
1093
|
`);for(let r of e){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(`
|
|
1094
|
-
`)}function _y(t,e){if(!e)return{kind:"failure",message:`${t}: no result`};if(e.schemaError)return{kind:"failure",message:`${t}: schema mismatch \u2014 ${e.schemaError.message}`};if(e.status!=="succeeded"){let n=e.error?` \u2014 ${e.error.message}`:"";return{kind:"failure",message:`${t}: ${e.status}${n}`}}return e.output?{kind:"success",output:e.output}:{kind:"failure",message:`${t}: no output`}}async function Ey(t,e,n){let r=n?.apiKey,o=n?.callId,s=typeof t=="object"&&t!==null?t:{},i=hy.parse(s),a=i.writeBriefs??!0,c=i.scope??"all",l=by(c);if(!e?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let d=e.sessionId,u=z("audit-fit"),p={skill:u["01-skill-inspector.md"],command:u["02-command-inspector.md"],agent:u["03-agent-inspector.md"],hook:u["04-hook-inspector.md"]};for(let h of Cc)if(!p[h])throw new Error(`audit-fit skill missing inspector prompt for ${h}`);let f=l.runUserDiscovery?Ec():[],g=l.runPluginDiscovery?Ac():[],m={skill:[],command:[],agent:[]};for(let h of[...f,...g])m[h.type].push(h);let k=new $({apiKey:r}),_=()=>async h=>
|
|
1094
|
+
`)}function _y(t,e){if(!e)return{kind:"failure",message:`${t}: no result`};if(e.schemaError)return{kind:"failure",message:`${t}: schema mismatch \u2014 ${e.schemaError.message}`};if(e.status!=="succeeded"){let n=e.error?` \u2014 ${e.error.message}`:"";return{kind:"failure",message:`${t}: ${e.status}${n}`}}return e.output?{kind:"success",output:e.output}:{kind:"failure",message:`${t}: no output`}}async function Ey(t,e,n){let r=n?.apiKey,o=n?.callId,s=typeof t=="object"&&t!==null?t:{},i=hy.parse(s),a=i.writeBriefs??!0,c=i.scope??"all",l=by(c);if(!e?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let d=e.sessionId,u=z("audit-fit"),p={skill:u["01-skill-inspector.md"],command:u["02-command-inspector.md"],agent:u["03-agent-inspector.md"],hook:u["04-hook-inspector.md"]};for(let h of Cc)if(!p[h])throw new Error(`audit-fit skill missing inspector prompt for ${h}`);let f=l.runUserDiscovery?Ec():[],g=l.runPluginDiscovery?Ac():[],m={skill:[],command:[],agent:[]};for(let h of[...f,...g])m[h.type].push(h);let k=new $({apiKey:r}),_=()=>async h=>oe.allowedTools.includes(h)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${h} not allowed for audit-fit inspectors. Allowed tools: ${oe.allowedTools.join(", ")}`},b=[];for(let h of yy){let x=m[h];if(x.length===0)continue;let R=p[h];R&&b.push({type:h,prompt:`${R}
|
|
1095
1095
|
${vy(x)}`,artifacts:x,runPrompt:`Inspect every ${h} listed in the artifact section.`})}if(l.runHookInspector){let h=p.hook;if(h){let x=Oo(Z(),"settings.json"),R=xc(x);b.push({type:"hook",prompt:`${h}
|
|
1096
|
-
${ky(x,R)}`,artifacts:[],runPrompt:`Inspect every hook listed in the Discovered hooks section. Settings file: ${x}.`})}}let S=[];if(b.length>0){let h=await Promise.all(b.map(T=>k.forkSubagent({parent:{sessionId:d},config:{model:"sonnet",systemPrompt:`${
|
|
1096
|
+
${ky(x,R)}`,artifacts:[],runPrompt:`Inspect every hook listed in the Discovered hooks section. Settings file: ${x}.`})}}let S=[];if(b.length>0){let h=await Promise.all(b.map(T=>k.forkSubagent({parent:{sessionId:d},config:{model:"sonnet",systemPrompt:`${oe.systemPrompt}
|
|
1097
1097
|
|
|
1098
1098
|
${T.prompt}`,canUseTool:_()},idPrefix:`inspector-${T.type}`,outputSchema:K.array(Ic),...o?{parentId:o}:{}}))),x=await Hn(b.map((T,O)=>{let j=h[O];if(!j)throw new Error(`audit-fit: missing handle for ${T.type} inspector`);return{handle:j,prompt:T.runPrompt}}),{failFast:!1}),R=[];for(let T=0;T<x.length;T++){let O=x[T],j=b[T];if(!j)continue;let W=_y(j.type,O);if(W.kind==="failure"){R.push(W.message);continue}let Q=new Map;for(let U of j.artifacts)Q.set(U.path,U.source);for(let U of W.output){if(j.type==="hook"){if(U.source!=="user"){R.push(`${j.type}: hook verdict has source=${U.source} (must be 'user')`);continue}}else{let ue=Q.get(U.path);if(ue===void 0){R.push(`${j.type}: verdict for unknown path ${U.path} (not in discovered list)`);continue}if(U.source!==ue){R.push(`${j.type}: verdict source mismatch for ${U.path} (expected ${ue}, got ${U.source})`);continue}}S.push(U)}}if(R.length>0){let T=R.map(O=>` - ${O}`).join(`
|
|
1099
1099
|
`);throw new Error(`audit-fit: ${R.length} inspector failure(s):
|
|
@@ -1120,10 +1120,10 @@ ${x.rationale}
|
|
|
1120
1120
|
---
|
|
1121
1121
|
Generated by audit-fit on ${new Date().toISOString().split(".")[0]}Z
|
|
1122
1122
|
`;await Rc(T,O),A++}}let I=Qe();await Tc(I,{recursive:!0});let C=h=>{let x=0;for(let R of Object.values(h))for(let T of Object.values(R))x+=T;return x},M=h=>{let x=w.user[h]??{},R=w.plugin[h]??{},T=O=>Object.values(O).reduce((j,W)=>j+W,0);return T(x)+T(R)},L={timestamp:new Date().toISOString(),surface:"afk",scope:c,total_artifacts:S.length,misfits_count:E.length,briefs_written:A,by_source:{user:C(w.user),plugin:C(w.plugin)},by_type:{skill:M("skill"),command:M("command"),agent:M("agent"),hook:M("hook")}},v=Oo(I,"audit-fit-telemetry.jsonl");return await Rc(v,JSON.stringify(L)+`
|
|
1123
|
-
`),{inventory:w,misfits:E,briefs_written:A,total_artifacts:S.length}}var Ay={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:Ey,argumentHint:"[--write-briefs]",whenToUse:"When the user wants ~/.afk artifacts (skills, commands, agents, hooks) audited for correct type categorization.",flags:["--write-briefs"],audience:"internal"};
|
|
1123
|
+
`),{inventory:w,misfits:E,briefs_written:A,total_artifacts:S.length}}var Ay={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:Ey,argumentHint:"[--write-briefs]",whenToUse:"When the user wants ~/.afk artifacts (skills, commands, agents, hooks) audited for correct type categorization.",flags:["--write-briefs"],audience:"internal"};ne(Ay);import{z as P}from"zod";import{execFile as Py}from"node:child_process";import{promisify as Iy}from"node:util";import{tmpdir as Cy}from"node:os";import{join as Fc}from"node:path";function Mc(t){return t.confidence<.5?{verify:!0,reason:`low confidence (${t.confidence.toFixed(2)} < ${.5})`}:t.boundary_flag&&t.boundary_flag.length>0?{verify:!0,reason:`boundary flag set: ${t.boundary_flag}`}:t.coverage_gaps&&t.coverage_gaps.length>0?{verify:!0,reason:`coverage gap${t.coverage_gaps.length===1?"":"s"}: ${t.coverage_gaps.length} unresolved`}:{verify:!1,reason:`confidence ${t.confidence.toFixed(2)} with no gaps or boundary`}}import{fileURLToPath as xy}from"node:url";import{dirname as Ty}from"node:path";var Ry=xy(import.meta.url),CP=Ty(Ry),Oc={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 Dc(t){let e={description:t.description,prompt:t.systemPrompt};return t.allowedTools&&(e.tools=[...t.allowedTools]),t.model&&(e.model=t.model),e}function My(t){let e=t.trim().toUpperCase();return["VERIFIED","CONFIRMED","CONFIRM","SUPPORTED","TRUE","PASS","PASSED"].includes(e)?"VERIFIED":["REFUTED","REFUTE","DISAGREE","DISAGREED","CONTRADICTED","FALSE","FAIL","FAILED"].includes(e)?"REFUTED":"INCONCLUSIVE"}var Oy=P.object({verifications:P.array(P.object({claim:P.string().optional(),verdict:P.string(),evidence:P.string().optional()}))});function Dy(t){let e=[],n=0,r=-1,o=!1,s=!1;for(let i=0;i<t.length;i++){let a=t[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&&(e.push(t.slice(r,i+1)),r=-1))}return e}function Fy(t){let e=Dy(t);for(let n of e){let r;try{r=JSON.parse(n)}catch{continue}let o=Oy.safeParse(r);if(o.success)return o.data.verifications.map(s=>({claim:s.claim??"",verdict:My(s.verdict),evidence:s.evidence??""}))}throw new Error(`shadow-verify did not return a parseable {"verifications":[...]} envelope (${e.length} JSON-like span(s) found, none matched the schema); raw output (first 300 chars): ${t.slice(0,300)}`)}var Wn=Iy(Py),$c=P.object({id:P.string(),claim:P.string(),confidence:P.number().min(0).max(1),evidence_sources:P.array(P.string()),location:P.string().optional(),proposed_fix:P.string().optional(),coverage_gaps:P.array(P.string()).nullish().transform(t=>t??void 0),boundary_flag:P.string().nullish().transform(t=>t??void 0)}),Ly=P.object({hypothesis_id:P.string(),claim:P.string(),verdict:P.enum(["VERIFIED","REFUTED","INCONCLUSIVE"]),evidence:P.string(),gate_reason:P.string()}),Uc=P.object({hypothesis_id:P.string(),reproducer_passed:P.boolean(),regressions:P.array(P.string()),confidence:P.number().min(0).max(1),verification_log:P.string()}),Ny=P.enum(["crash","regression","logic-error","flaky","environment","unknown"]),$y=P.object({failure_type:Ny,error_signature:P.string(),affected_area:P.string()}),Uy=P.enum(["clear_winner","multiple_plausible","dissent","all_inconclusive","no_hypotheses"]),JP=P.object({reproducer:P.string().optional(),triage:$y.optional(),hypotheses:P.array($c),premise_verifications:P.array(Ly).optional(),winner:P.object({hypothesis_id:P.string(),verification_log:P.string(),proposed_fix:P.string()}).optional(),verification_results:P.array(Uc).optional(),outcome:Uy.optional(),recommended_next_skill:P.enum(["spec"]).optional()});async function By(t,e){let n=t.map(c=>({hypothesis:c,decision:Mc(c)})).filter(c=>c.decision.verify);if(n.length===0)return{premise_verifications:[],hypotheses_to_test:t};let r=[],o;try{let c=await e(n.map(l=>l.hypothesis.claim));r=Array.isArray(c)?c:[]}catch(c){o=c instanceof Error?c.message:String(c)}let s=n.map((c,l)=>{let d=r[l];return o!==void 0?{hypothesis_id:c.hypothesis.id,claim:c.hypothesis.claim,verdict:"INCONCLUSIVE",evidence:`shadow-verify dispatch failed: ${o}`,gate_reason:c.decision.reason}:d?{hypothesis_id:c.hypothesis.id,claim:c.hypothesis.claim,verdict:d.verdict,evidence:d.evidence,gate_reason:c.decision.reason}:{hypothesis_id:c.hypothesis.id,claim:c.hypothesis.claim,verdict:"INCONCLUSIVE",evidence:"no verifier result for this claim",gate_reason:c.decision.reason}}),i=new Set(s.filter(c=>c.verdict==="REFUTED").map(c=>c.hypothesis_id)),a=i.size===0?t:t.filter(c=>!i.has(c.id));return{premise_verifications:s,hypotheses_to_test:a}}async function Hy(t,e,n){let r=n?.apiKey,o=(()=>{if(typeof t=="string")return{failure:t,repoPath:process.cwd(),context:"",maxHypotheses:4};if(typeof t=="object"&&t!==null){let G=t;if(typeof G.failure=="string")return{failure:G.failure,repoPath:G.repoPath||process.cwd(),context:G.context||"",maxHypotheses:Math.min(G.maxHypotheses||4,4)}}throw new Error("diagnose handler requires input.failure (string) or a string argument")})();if(!e?.sessionId)throw new Error("diagnose requires a parent session with sessionId");let s=e.sessionId,i=z("diagnose"),a=i["system.md"],c=i["research.md"],l=i["hypothesis.md"],d=i["verify.md"];if(!a||!c||!l||!d)throw new Error("diagnose skill missing required prompts (system.md, research.md, hypothesis.md, verify.md)");let u=new $({apiKey:r}),p=Gy(o.context),f=jy(o.failure,o.context),g=`Triage:
|
|
1124
1124
|
failure_type: ${f.failure_type}
|
|
1125
1125
|
error_signature: ${f.error_signature}
|
|
1126
|
-
affected_area: ${f.affected_area}`,k=`${
|
|
1126
|
+
affected_area: ${f.affected_area}`,k=`${oe.systemPrompt}
|
|
1127
1127
|
|
|
1128
1128
|
## Lane override (codebase research)
|
|
1129
1129
|
|
|
@@ -1134,7 +1134,7 @@ ${c}
|
|
|
1134
1134
|
Focus: CODEBASE
|
|
1135
1135
|
${g}
|
|
1136
1136
|
Failure: ${o.failure}${o.context?`
|
|
1137
|
-
Context: ${o.context}`:""}`,_=`${
|
|
1137
|
+
Context: ${o.context}`:""}`,_=`${oe.systemPrompt}
|
|
1138
1138
|
|
|
1139
1139
|
${c}
|
|
1140
1140
|
|
|
@@ -1161,7 +1161,7 @@ OUTPUT CONTRACT (required): after your verification, end your reply with a singl
|
|
|
1161
1161
|
{"verifications":[{"claim":"<echo of the claim>","verdict":"VERIFIED|REFUTED|INCONCLUSIVE","evidence":"<1-2 sentences; cite file:line or source>"}]}`}),Cd=await n.dispatchSkill("shadow-verify",wr);return Fy(Cd)});if(x.length===0)return{reproducer:p,triage:f,hypotheses:v,premise_verifications:h,verification_results:[],outcome:"no_hypotheses"};let R=p||o.failure,T=x.map(G=>zy(G,R,o.repoPath,s,d,u,b)),O=await Promise.all(T),W=O.filter(G=>G.reproducer_passed&&G.regressions.length===0).slice().sort((G,wr)=>wr.confidence-G.confidence)[0]??O.find(G=>G.reproducer_passed),Q=Wy(v,O),U=W?v.find(G=>G.id===W.hypothesis_id):void 0,ue=Q==="clear_winner"&&U&&Ky(U)?"spec":void 0;return{reproducer:p,triage:f,hypotheses:v,premise_verifications:h.length>0?h:void 0,winner:W?{hypothesis_id:W.hypothesis_id,verification_log:W.verification_log,proposed_fix:U?.proposed_fix||""}:void 0,verification_results:O,outcome:Q,recommended_next_skill:ue}}function jy(t,e){let n=`${t}
|
|
1162
1162
|
${e}`,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=t.split(`
|
|
1163
1163
|
`).map(u=>u.trim()).find(u=>u.length>0),c;a?s.test(a)&&!i.test(t)?c="prose-question":a.length>200?c=`${a.slice(0,197)}...`:c=a:c="unknown";let d=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:c,affected_area:d}}function Ky(t){let n=`${t.proposed_fix??""}
|
|
1164
|
-
${t.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 Wy(t,e){if(t.length===0)return"no_hypotheses";let n=e.filter(o=>o.reproducer_passed&&o.regressions.length===0);return n.length===1?"clear_winner":n.length>=2?"multiple_plausible":t.filter(o=>o.confidence>=.7).length>=2?"dissent":"all_inconclusive"}function Gy(t){if(!t)return;let e=[/test:\s*(.+)/i,/command:\s*(.+)/i,/reproducer:\s*(.+)/i,/failing test:\s*(.+)/i];for(let n of e){let r=t.match(n);if(r)return r[1]}}function Lc(){return async t=>
|
|
1164
|
+
${t.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 Wy(t,e){if(t.length===0)return"no_hypotheses";let n=e.filter(o=>o.reproducer_passed&&o.regressions.length===0);return n.length===1?"clear_winner":n.length>=2?"multiple_plausible":t.filter(o=>o.confidence>=.7).length>=2?"dissent":"all_inconclusive"}function Gy(t){if(!t)return;let e=[/test:\s*(.+)/i,/command:\s*(.+)/i,/reproducer:\s*(.+)/i,/failing test:\s*(.+)/i];for(let n of e){let r=t.match(n);if(r)return r[1]}}function Lc(){return async t=>oe.allowedTools.includes(t)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${t} not allowed. Allowed tools: ${oe.allowedTools.join(", ")}`}}var Nc=[...oe.allowedTools,"Agent"];function qy(){return async t=>Nc.includes(t)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${t} not allowed for git orchestrator. Allowed tools: ${Nc.join(", ")}`}}async function zy(t,e,n,r,o,s,i){let a=Fc(Cy(),`diagnose-hyp-${t.id}-${Date.now()}`),c;try{await Wn("git",["worktree","add","--detach",a,"HEAD"],{cwd:n});try{let{writeFile:u}=await import("node:fs/promises"),p="",f="";try{p=(await Wn("git",["rev-parse","HEAD"],{cwd:n})).stdout.trim()}catch{}try{f=(await Wn("git",["symbolic-ref","--short","HEAD"],{cwd:n})).stdout.trim()}catch{}await u(Fc(a,".afk-worktree-meta.json"),JSON.stringify({owner:"diagnose",createdAt:new Date().toISOString(),baseSha:p,baseBranch:f},null,2),"utf-8")}catch{}c=await s.forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:`${o}
|
|
1165
1165
|
|
|
1166
1166
|
You are testing in an isolated worktree at: ${a}`,canUseTool:Jy()},idPrefix:`diagnose-verifier-${t.id}`,outputSchema:Uc,...i?{parentId:i}:{}});let l=`Test this hypothesis:
|
|
1167
1167
|
|
|
@@ -1170,7 +1170,7 @@ Location: ${t.location||"unknown"}
|
|
|
1170
1170
|
Proposed fix: ${t.proposed_fix||"unknown"}
|
|
1171
1171
|
Reproducer: ${e}
|
|
1172
1172
|
|
|
1173
|
-
Working directory (isolated): ${a}`,d=await c.runToResult(l);return d.status!=="succeeded"||!d.output?{hypothesis_id:t.id,reproducer_passed:!1,regressions:[],confidence:0,verification_log:`Verification failed: ${Y(d)}`}:d.output}catch(l){return{hypothesis_id:t.id,reproducer_passed:!1,regressions:[],confidence:0,verification_log:`Error during verification: ${l instanceof Error?l.message:String(l)}`}}finally{if(c)try{await c.teardown()}catch{}try{await Wn("git",["worktree","remove","--force",a],{cwd:n})}catch{}}}function Jy(){let t=["Edit","Write","Bash","Agent","Task"];return async e=>t.includes(e)?{behavior:"deny",message:`Tool ${e} not allowed in worktree verification. Verification is read-only.`}:
|
|
1173
|
+
Working directory (isolated): ${a}`,d=await c.runToResult(l);return d.status!=="succeeded"||!d.output?{hypothesis_id:t.id,reproducer_passed:!1,regressions:[],confidence:0,verification_log:`Verification failed: ${Y(d)}`}:d.output}catch(l){return{hypothesis_id:t.id,reproducer_passed:!1,regressions:[],confidence:0,verification_log:`Error during verification: ${l instanceof Error?l.message:String(l)}`}}finally{if(c)try{await c.teardown()}catch{}try{await Wn("git",["worktree","remove","--force",a],{cwd:n})}catch{}}}function Jy(){let t=["Edit","Write","Bash","Agent","Task"];return async e=>t.includes(e)?{behavior:"deny",message:`Tool ${e} not allowed in worktree verification. Verification is read-only.`}:oe.allowedTools.includes(e)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${e} not allowed. Allowed tools: ${oe.allowedTools.join(", ")}`}}var Vy={name:"diagnose",description:"Parallel root-cause analysis for bugs and failing tests \u2014 forks research subagents, synthesizes hypotheses, and validates each in isolated worktrees",handler:Hy,argumentHint:"<bug-or-failing-test>",whenToUse:"When a test is failing, a bug is reported, or behavior is unexplained \u2014 runs parallel root-cause analysis with hypothesis sub-agents."};ne(Vy);F();function X(){let t=y.AFK_MODEL??y.CLAUDE_MODEL;return Yy(t)}function Yy(t){return st(t)}async function Bc(t,e,n,r){let s=z("mint")["spec.md"];if(!s)throw new Error("mint skill missing spec.md prompt");let c=await(await new $(n!==void 0?{cwd:n}:{}).forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:s,apiKey:X()},idPrefix:"mint-spec",phaseRole:"read-only",...r?{parentId:r}:{}})).runToResult(`Create a detailed specification for: ${t}`);if(c.status!=="succeeded"||!c.message)throw new Error(`spec phase failed: ${Y(c)}`);return c.message.content}async function Hc(t,e,n,r){let s=z("mint")["research.md"];if(!s)throw new Error("mint skill missing research.md prompt");let c=await(await new $(n!==void 0?{cwd:n}:{}).forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:s,apiKey:X()},idPrefix:"mint-research",phaseRole:"read-only",...r?{parentId:r}:{}})).runToResult(`Gather context and research for this specification:
|
|
1174
1174
|
|
|
1175
1175
|
${t}`);if(c.status!=="succeeded"||!c.message)throw new Error(`research phase failed: ${Y(c)}`);return c.message.content}async function jc(t,e,n,r,o){let i=z("mint")["plan.md"];if(!i)throw new Error("mint skill missing plan.md prompt");let c=await new $(r!==void 0?{cwd:r}:{}).forkSubagent({parent:{sessionId:n},config:{model:"sonnet",systemPrompt:i,apiKey:X()},idPrefix:"mint-plan",phaseRole:"read-only",...o?{parentId:o}:{}}),l=`Specification:
|
|
1176
1176
|
${t}
|
|
@@ -1223,7 +1223,7 @@ ${JSON.stringify(t.verifyResults,null,2)}
|
|
|
1223
1223
|
|
|
1224
1224
|
Heal iterations used: ${t.healIterations}
|
|
1225
1225
|
|
|
1226
|
-
Create a ship-ready summary with next steps.`,l=await a.runToResult(c);if(l.status!=="succeeded"||!l.message)throw new Error(`ship phase failed: ${Y(l)}`);let d=t.buildResults?.filesChanged.length??0,u=t.healIterations;return pt({kind:"checkpoint",title:"ship \u2014 done",body:[`Files changed: ${d}`,`Heal iterations: ${u}`,`Idea: ${t.idea}`]}),l.message.content}H();import{existsSync as zc,mkdirSync as eb,readFileSync as tb,unlinkSync as nb,writeFileSync as rb}from"fs";import{dirname as ob,join as sb}from"path";function Fo(t){return sb(et(),t,"mint-state.json")}function Jc(t,e){let n=Fo(t);eb(ob(n),{recursive:!0}),rb(n,JSON.stringify(e,null,2),"utf-8")}function ib(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.currentPhase=="string"&&typeof e.idea=="string"&&typeof e.spec=="string"&&typeof e.healIterations=="number"&&Array.isArray(e.history)}function Vc(t){let e=Fo(t);if(!zc(e))return null;try{let n=JSON.parse(tb(e,"utf-8"));return ib(n)?n:null}catch{return null}}function Lo(t){let e=Fo(t);if(zc(e))try{nb(e)}catch{}}var ab=2,Yc=/^\s*(?:--continue(?:\s+(?:approved|yes|y))?|approved?|yes|y|lgtm|sure)\s*$/i,cb='To approve and run the rest of the pipeline, say "approve", "yes", "sure", or "lgtm" \u2014 or invoke /mint --continue approved. The handler will reload the spec state from disk.';function we(t,e,n){t.history.push({phase:e,output:n,timestamp:Date.now()})}function el(t){if("completed"in t&&"paused"in t)throw new Error("mint: invariant violation \u2014 MintResult carries both completed and paused keys simultaneously")}var Xc=240;function lb(t){return t.length<=Xc?t:t.slice(0,Xc)+"\u2026"}function tl(t){if(typeof t=="string"){if(Yc.test(t))return{userApproved:!0};if(t.length>1&&t.trimStart().startsWith("{"))try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null)return tl(e)}catch{}return{idea:t}}if(typeof t=="object"&&t!==null){let e=t,n=typeof e.idea=="string"?e.idea:void 0;if(n!==void 0&&Yc.test(n))return{userApproved:!0};if("idea"in e||"resumeFrom"in e||e.userApproved===!0)return e}throw new Error("mint handler requires input.idea (string), input as string, or {userApproved: true} to resume")}async function Qc(t,e,n){if(!e.sessionId)throw new Error("runPhasesAfterSpec requires parentSession.sessionId");let r=e.sessionId,o=e.cwd;try{t.currentPhase="research",t.research=await Hc(t.spec,r,o,n),we(t,"research",t.research),t.currentPhase="plan",t.plan=await jc(t.spec,t.research,r,o,n),we(t,"plan",t.plan),t.currentPhase="parallelize";let s=await Kc(t.plan,e,n);if(s.kind==="plan")t.waveOrchestrationPlan=s.plan,we(t,"parallelize",JSON.stringify(s.plan));else if(s.kind==="skipped")t.waveOrchestrationPlan=void 0,we(t,"parallelize",`skipped: ${s.reason}`);else if(s.kind==="failed"){t.waveOrchestrationPlan=void 0;let c=lb(s.error);we(t,"parallelize",`failed: ${c}`),ae({event:"fallback.inline",parent_session_id:r,reason:"parallelize-dispatch-failed",error_message:c}),console.warn(`[mint] parallelize dispatch failed (single-lane fallback): ${c}`)}else{let c=s}t.currentPhase="build",t.buildResults=await Wc(t.plan,t.waveOrchestrationPlan,r,o,n),we(t,"build",JSON.stringify(t.buildResults)),t.currentPhase="verify",t.verifyResults=await Gn(t.plan,t.buildResults,r,o,n),we(t,"verify",JSON.stringify(t.verifyResults)),t.currentPhase="heal";let i=t.verifyResults.testsPassed&&t.verifyResults.lintPassed&&t.verifyResults.designReviewPassed;for(;!i&&t.healIterations<ab;){let c=await Gc(t.plan,t.buildResults,t.verifyResults,t.healIterations,e,n);t.healIterations=c.newHealIterations,t.verifyResults=c.newVerifyResults,i=c.healed,we(t,"heal",`Iterations: ${t.healIterations}, Success: ${i}`)}if(!i)return{paused:!0,phase:"heal-failed",reason:`Heal capped at ${t.healIterations} iterations; still have failures`,state:t,nextStep:"Heal loop exhausted. Inspect verifyResults, fix manually, then re-invoke /mint with a fresh idea \u2014 resume is not supported from heal-failed."};t.currentPhase="ship";let a=await qc(t,r,o,n);return we(t,"ship",a),{completed:!0,artifact:a,state:t}}catch(s){throw new Error(`mint failed at ${t.currentPhase}: ${s}`)}}function Zc(t,e){return el(e),("completed"in e||e.phase==="heal-failed")&&Lo(t),e}async function db(t,e,n){let r=tl(t);if(!e?.sessionId)throw new Error("mint handler requires a parent session to fork subagents");let o=e.sessionId,s=n?.callId;if(r.userApproved){let c=r.resumeFrom??Vc(o);if(!c)throw new Error("mint: no paused spec found for this session to continue. Run /mint <idea> first, then /mint --continue approved.");let l=await Qc(c,e,s);return Zc(o,l)}if(!r.idea)throw new Error("mint: no idea provided. Run /mint <idea> to start, or /mint --continue approved to resume a paused spec.");Lo(o);let i={currentPhase:"spec",idea:r.idea,healIterations:0,history:[]};try{i.spec=await Bc(r.idea,o,e.cwd,s),we(i,"spec",i.spec)}catch(c){throw new Error(`mint failed at spec: ${c}`)}if(!r.autoApprove){Jc(o,i);let c={paused:!0,phase:"spec",spec:i.spec,state:i,nextStep:cb};return el(c),c}let a=await Qc(i,e,s);return Zc(o,a)}var ub={name:"mint",description:"Takes a feature idea or refactor scope and delivers a ship-ready, verified implementation end-to-end",handler:db,argumentHint:"<idea> | --continue [approved]",whenToUse:'When the user wants a feature or refactor delivered end-to-end (spec \u2192 research \u2192 build \u2192 verify) in one ship-ready pass. After the spec phase pauses for approval, resume by invoking mint again with the literal string `"approved"` (or `"yes"`, `"lgtm"`, `"--continue approved"`) as the arguments. Equivalent JSON forms `{"userApproved": true}` and `{"idea": "approved"}` are also accepted. The handler reloads the spec state from disk and runs phases 2\u20138.',flags:["--continue"]};
|
|
1226
|
+
Create a ship-ready summary with next steps.`,l=await a.runToResult(c);if(l.status!=="succeeded"||!l.message)throw new Error(`ship phase failed: ${Y(l)}`);let d=t.buildResults?.filesChanged.length??0,u=t.healIterations;return pt({kind:"checkpoint",title:"ship \u2014 done",body:[`Files changed: ${d}`,`Heal iterations: ${u}`,`Idea: ${t.idea}`]}),l.message.content}H();import{existsSync as zc,mkdirSync as eb,readFileSync as tb,unlinkSync as nb,writeFileSync as rb}from"fs";import{dirname as ob,join as sb}from"path";function Fo(t){return sb(et(),t,"mint-state.json")}function Jc(t,e){let n=Fo(t);eb(ob(n),{recursive:!0}),rb(n,JSON.stringify(e,null,2),"utf-8")}function ib(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.currentPhase=="string"&&typeof e.idea=="string"&&typeof e.spec=="string"&&typeof e.healIterations=="number"&&Array.isArray(e.history)}function Vc(t){let e=Fo(t);if(!zc(e))return null;try{let n=JSON.parse(tb(e,"utf-8"));return ib(n)?n:null}catch{return null}}function Lo(t){let e=Fo(t);if(zc(e))try{nb(e)}catch{}}var ab=2,Yc=/^\s*(?:--continue(?:\s+(?:approved|yes|y))?|approved?|yes|y|lgtm|sure)\s*$/i,cb='To approve and run the rest of the pipeline, say "approve", "yes", "sure", or "lgtm" \u2014 or invoke /mint --continue approved. The handler will reload the spec state from disk.';function we(t,e,n){t.history.push({phase:e,output:n,timestamp:Date.now()})}function el(t){if("completed"in t&&"paused"in t)throw new Error("mint: invariant violation \u2014 MintResult carries both completed and paused keys simultaneously")}var Xc=240;function lb(t){return t.length<=Xc?t:t.slice(0,Xc)+"\u2026"}function tl(t){if(typeof t=="string"){if(Yc.test(t))return{userApproved:!0};if(t.length>1&&t.trimStart().startsWith("{"))try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null)return tl(e)}catch{}return{idea:t}}if(typeof t=="object"&&t!==null){let e=t,n=typeof e.idea=="string"?e.idea:void 0;if(n!==void 0&&Yc.test(n))return{userApproved:!0};if("idea"in e||"resumeFrom"in e||e.userApproved===!0)return e}throw new Error("mint handler requires input.idea (string), input as string, or {userApproved: true} to resume")}async function Qc(t,e,n){if(!e.sessionId)throw new Error("runPhasesAfterSpec requires parentSession.sessionId");let r=e.sessionId,o=e.cwd;try{t.currentPhase="research",t.research=await Hc(t.spec,r,o,n),we(t,"research",t.research),t.currentPhase="plan",t.plan=await jc(t.spec,t.research,r,o,n),we(t,"plan",t.plan),t.currentPhase="parallelize";let s=await Kc(t.plan,e,n);if(s.kind==="plan")t.waveOrchestrationPlan=s.plan,we(t,"parallelize",JSON.stringify(s.plan));else if(s.kind==="skipped")t.waveOrchestrationPlan=void 0,we(t,"parallelize",`skipped: ${s.reason}`);else if(s.kind==="failed"){t.waveOrchestrationPlan=void 0;let c=lb(s.error);we(t,"parallelize",`failed: ${c}`),ae({event:"fallback.inline",parent_session_id:r,reason:"parallelize-dispatch-failed",error_message:c}),console.warn(`[mint] parallelize dispatch failed (single-lane fallback): ${c}`)}else{let c=s}t.currentPhase="build",t.buildResults=await Wc(t.plan,t.waveOrchestrationPlan,r,o,n),we(t,"build",JSON.stringify(t.buildResults)),t.currentPhase="verify",t.verifyResults=await Gn(t.plan,t.buildResults,r,o,n),we(t,"verify",JSON.stringify(t.verifyResults)),t.currentPhase="heal";let i=t.verifyResults.testsPassed&&t.verifyResults.lintPassed&&t.verifyResults.designReviewPassed;for(;!i&&t.healIterations<ab;){let c=await Gc(t.plan,t.buildResults,t.verifyResults,t.healIterations,e,n);t.healIterations=c.newHealIterations,t.verifyResults=c.newVerifyResults,i=c.healed,we(t,"heal",`Iterations: ${t.healIterations}, Success: ${i}`)}if(!i)return{paused:!0,phase:"heal-failed",reason:`Heal capped at ${t.healIterations} iterations; still have failures`,state:t,nextStep:"Heal loop exhausted. Inspect verifyResults, fix manually, then re-invoke /mint with a fresh idea \u2014 resume is not supported from heal-failed."};t.currentPhase="ship";let a=await qc(t,r,o,n);return we(t,"ship",a),{completed:!0,artifact:a,state:t}}catch(s){throw new Error(`mint failed at ${t.currentPhase}: ${s}`)}}function Zc(t,e){return el(e),("completed"in e||e.phase==="heal-failed")&&Lo(t),e}async function db(t,e,n){let r=tl(t);if(!e?.sessionId)throw new Error("mint handler requires a parent session to fork subagents");let o=e.sessionId,s=n?.callId;if(r.userApproved){let c=r.resumeFrom??Vc(o);if(!c)throw new Error("mint: no paused spec found for this session to continue. Run /mint <idea> first, then /mint --continue approved.");let l=await Qc(c,e,s);return Zc(o,l)}if(!r.idea)throw new Error("mint: no idea provided. Run /mint <idea> to start, or /mint --continue approved to resume a paused spec.");Lo(o);let i={currentPhase:"spec",idea:r.idea,healIterations:0,history:[]};try{i.spec=await Bc(r.idea,o,e.cwd,s),we(i,"spec",i.spec)}catch(c){throw new Error(`mint failed at spec: ${c}`)}if(!r.autoApprove){Jc(o,i);let c={paused:!0,phase:"spec",spec:i.spec,state:i,nextStep:cb};return el(c),c}let a=await Qc(i,e,s);return Zc(o,a)}var ub={name:"mint",description:"Takes a feature idea or refactor scope and delivers a ship-ready, verified implementation end-to-end",handler:db,argumentHint:"<idea> | --continue [approved]",whenToUse:'When the user wants a feature or refactor delivered end-to-end (spec \u2192 research \u2192 build \u2192 verify) in one ship-ready pass. After the spec phase pauses for approval, resume by invoking mint again with the literal string `"approved"` (or `"yes"`, `"lgtm"`, `"--continue approved"`) as the arguments. Equivalent JSON forms `{"userApproved": true}` and `{"idea": "approved"}` are also accepted. The handler reloads the spec state from disk and runs phases 2\u20138.',flags:["--continue"]};ne(ub);async function pb(){throw new Error("service-setup is a fork skill; its handler should never be called directly. Invoke via the `skill` tool or `/service-setup` slash command.")}var fb={name:"service-setup",description:"Install an AFK background process (telegram bot or daemon) as a macOS LaunchAgent so it auto-starts on login and relaunches on crash. Runs pre-flight checks (e.g., refuses to install the telegram service with an invalid token, which would otherwise crash-loop under KeepAlive), invokes `afk service install`, verifies with `afk service status`, and surfaces the management cheatsheet. macOS-only \u2014 gracefully refuses on other platforms.",handler:pb,context:"fork",whenToUse:"When the user wants to make `afk telegram start` or `afk daemon` always-on \u2014 i.e., survive reboot, crash, OOM. Triggers on phrasings like 'install as a service', 'auto-start on login', 'keep the bot running', 'launchd', 'always-on telegram', or right after a successful `/telegram-setup` when the user asks how to make it persistent."};ne(fb);async function mb(){throw new Error("telegram-setup is a fork skill; its handler should never be called directly. Invoke via the `skill` tool or `/telegram-setup` slash command.")}var gb={name:"telegram-setup",description:"Guide the user through first-time Telegram bot onboarding without leaking the bearer token. Walks the user to run `afk telegram setup` in a terminal for token entry, then uses the sanctioned `afk telegram check-token`/`discover-chat`/`set-allowed-chat` subcommands to validate and finish allowlist setup \u2014 the token never enters the model context. Works in REPL or Telegram. Use when the user wants to set up Telegram push notifications for the first time, or to debug a partially-configured install.",handler:mb,context:"fork",whenToUse:`When the user wants to set up Telegram bot notifications for the first time, or when they say something like "set up telegram", "connect telegram", "enable push", or you detect that TELEGRAM_BOT_TOKEN is unset and they're asking for notifications.`};ne(gb);H();import{readdirSync as bb,readFileSync as wb}from"fs";import{join as ol}from"path";var hb=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9-]*)(?![a-zA-Z0-9_-])/g;function nl(t){return t.startsWith("--")?t:`--${t}`}function yb(t){let e=new Set;for(let n of t.matchAll(hb))n[1]&&e.add(`--${n[1]}`);return Array.from(e).sort()}function No(t){if(!t.startsWith(`---
|
|
1227
1227
|
`))return{frontmatter:null,frontmatterFlags:null,body:t};let e=t.indexOf(`
|
|
1228
1228
|
---
|
|
1229
1229
|
`,4);if(e===-1)return{frontmatter:null,frontmatterFlags:null,body:t};let n=t.slice(4,e),r=t.slice(e+5),o={},s=null,i=n.split(`
|
|
@@ -1232,12 +1232,12 @@ ${e.body}`)}function Sb(t,e){return t.length===0||t.length>64?{valid:!1,reason:`
|
|
|
1232
1232
|
`),null;if(o.length>sl)return process.stderr.write(`[afk] skipping skill ${e}: description exceeds ${sl} characters (got ${o.length})
|
|
1233
1233
|
`),null;let a=n.frontmatter["argument-hint"]??n.frontmatter.argumentHint,c=rl(t),l={name:r,description:o,body:s,dir:""};a&&a.length>0&&(l.argumentHint=a),c.length>0&&(l.flags=c);let d=n.frontmatter.context;return(d==="inline"||d==="fork"||d==="load")&&(l.context=d),l}function kb(t){return async(e,n,r)=>{let o=typeof e=="string"&&e.length>0?e:`Run the ${t.name} skill now, following the instructions in your system prompt.`,s=new $({parentAbortSignal:n?.abortSignal}),i=r?.callId;return await(await s.forkSubagent({parent:{sessionId:n?.sessionId,getInputStreamRef:n?.getInputStreamRef?.bind(n),abortSignal:n?.abortSignal},config:{model:"sonnet",systemPrompt:t.body,env:{SKILL_ROOT:t.dir},isSkillDispatch:!0},idPrefix:`user-skill-${t.name}`,...i?{parentId:i}:{}})).runToResult(o)}}function _b(t,e){try{return Se(t).origin===e?t:`${e}:${t}`}catch{return t}}function qn(t,e){let n;try{n=bb(t,{withFileTypes:!0})}catch(o){let s=o;return s.code!=="ENOENT"&&process.stderr.write(`[afk] skipping skills dir ${t}: ${s.message}
|
|
1234
1234
|
`),0}let r=0;for(let o of n){if(!o.isDirectory()||o.name.startsWith("_")||o.name.startsWith("."))continue;let s;try{s=wb(ol(t,o.name,"SKILL.md"),"utf-8")}catch(l){let d=l;d.code!=="ENOENT"&&process.stderr.write(`[afk] skipping skill ${o.name}: ${d.message}
|
|
1235
|
-
`);continue}let i=vb(s,o.name);if(!i)continue;i.dir=ol(t,o.name);let c={name:_b(i.name,e),description:i.description,handler:kb(i),origin:e};i.argumentHint&&(c.argumentHint=i.argumentHint),i.flags&&i.flags.length>0&&(c.flags=i.flags),i.context!=="fork"&&(c.context="load",c.loadBody=i.body.replace(/\$\{?SKILL_ROOT\}?/g,()=>i.dir)),
|
|
1235
|
+
`);continue}let i=vb(s,o.name);if(!i)continue;i.dir=ol(t,o.name);let c={name:_b(i.name,e),description:i.description,handler:kb(i),origin:e};i.argumentHint&&(c.argumentHint=i.argumentHint),i.flags&&i.flags.length>0&&(c.flags=i.flags),i.context!=="fork"&&(c.context="load",c.loadBody=i.body.replace(/\$\{?SKILL_ROOT\}?/g,()=>i.dir)),ne(c),r++}return r}import{existsSync as Eb,readdirSync as Ab,readFileSync as xb,statSync as Tb}from"fs";import{join as Rb}from"path";function $o(t){let e=[];function n(r,o=0){if(o>10||!Eb(r))return;let s;try{s=Ab(r)}catch{return}for(let i of s){if(i.startsWith("."))continue;let a=Rb(r,i),c;try{c=Tb(a)}catch{continue}if(c.isFile()&&i==="SKILL.md"){let l=Pb(a);l.name&&e.push(l)}else c.isDirectory()&&n(a,o+1)}}return n(t),e}function Pb(t){try{let e=xb(t,"utf-8");if(!e.startsWith(`---
|
|
1236
1236
|
`))return{};let n=e.slice(4),r=n.indexOf(`
|
|
1237
1237
|
---`);if(r===-1)return{};let o=n.slice(0,r),s=n.slice(r+4).trim(),i={},a=o.split(`
|
|
1238
1238
|
`);for(let c of a){if(!c)continue;let l=c.indexOf(":");if(l===-1)continue;let d=c.slice(0,l).trim(),u=c.slice(l+1).trim();if(d==="name")i.name=u.replace(/^["']|["']$/g,"");else if(d==="description")i.description=u.replace(/^["']|["']$/g,"");else if(d==="argumentHint")i.argumentHint=u.replace(/^["']|["']$/g,"");else if(d==="audience"){let p=u.replace(/^["']|["']$/g,"");(p==="public"||p==="internal")&&(i.audience=p)}else d==="context"?i.context=u.replace(/^["']|["']$/g,""):(d==="read-only"||d==="readOnly")&&u.replace(/^["']|["']$/g,"").trim()==="true"&&(i.readOnly=!0)}return s.length>0&&(i.body=s),i}catch{return{}}}H();F();function il(t){let e=ut(t);if(e.length===0)return"";let n=[];for(let r of e){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(`
|
|
1239
1239
|
`)}function ut(t){let e=[],n=new Set,r=y.AFK_INTERNAL==="1";qn(Or(),"user"),qn(Hs(),"project");for(let s of Cs()){let i=Se(s);Cr(i,r)&&(e.push({name:s,description:i.description,source:i.origin==="user"?"user":i.origin==="project"?"project":"builtin",argumentHint:i.argumentHint,whenToUse:i.whenToUse}),n.add(s))}let o=t??[...Ee(Dr()),...Ee(),...Ee(Lr())];for(let s of o){if(s.type!=="local")continue;let i=$o(s.path);for(let a of i)!a.name||n.has(a.name)||Cr({audience:a.audience},r)&&(e.push({name:a.name,description:a.description??`Skill from plugin at ${s.path}`,source:"plugin"}),n.add(a.name))}return e}function Ro(t){let e=new Map,n=t??[...Ee(Dr()),...Ee(),...Ee(Lr())];for(let r of n){if(r.type!=="local")continue;let o=$o(r.path);for(let s of o)s.name&&s.body&&s.body.length>0&&!e.has(s.name)&&e.set(s.name,{body:s.body,pluginPath:r.path,...s.context!==void 0?{context:s.context}:{},...s.readOnly===!0?{readOnly:!0}:{}})}return e}function al(t){if(t.length===0)return;let e=t[t.length-1];if(!e||e.role!=="assistant"||typeof e.content=="string")return;let n=e.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}))};t.push(o)}function cl(t){return{messages:t.initialMessages?[...t.initialMessages]:[],currentModel:t.model,requestedModel:t.requestedModel??t.model,currentPermissionMode:t.permissionMode,userSystem:t.userSystem,toolDispatcher:t.toolDispatcher,lastUsage:null,closed:!1,autoCompactThreshold:t.autoCompactThreshold}}var Ib="__closed__",zn=class{current=null;pendingReason=null;closedPromise;closeResolve=null;constructor(){this.closedPromise=new Promise(e=>{this.closeResolve=()=>e(Ib)})}begin(){let e=new AbortController;return this.current=e,this.pendingReason!==null&&!e.signal.aborted&&(e.abort(this.pendingReason),this.pendingReason=null),e}clear(e){this.current===e&&(this.current=null)}requestAbort(e){let n=this.current;if(n&&!n.signal.aborted){n.abort(e);return}this.pendingReason=e}isIdle(){return this.current===null}markClosed(){this.closeResolve?.()}};import{randomUUID as Ho}from"node:crypto";import{randomUUID as Fb}from"node:crypto";var Cb=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 Mb(t,e,n,r,o){let s=Cb.get(t);if(!s)return;let i=1e6,c=Math.max(0,e-r-o)/i*s.inputPerMTok,l=n/i*s.outputPerMTok,d=s.cacheWritePerMTok??s.inputPerMTok*1.25,u=s.cacheReadPerMTok??s.inputPerMTok*.1,p=o/i*d,f=r/i*u;return c+l+p+f}function ll(t,e,n){if(!t)return{stopReason:e??null};let r={inputTokens:t.input_tokens,outputTokens:t.output_tokens,stopReason:e??null};if(t.cache_read_input_tokens!=null&&(r.cachedInputTokens=t.cache_read_input_tokens),t.cache_creation_input_tokens!=null&&(r.cacheCreationTokens=t.cache_creation_input_tokens),r.totalTokens=(t.input_tokens??0)+(t.output_tokens??0),n){let o=Mb(n,t.input_tokens??0,t.output_tokens??0,t.cache_read_input_tokens??0,t.cache_creation_input_tokens??0);o!==void 0&&(r.totalCostUsd=o)}return r}F();function Ob(t){let e=t.trim();if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function Db(t,e,n){let r=[],o=[];for(let a of t)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}):r.push({type:"tool_use",id:a.id,name:a.name,input:Ob(a.partialJson)}));let s=a=>a.type==="tool_use",i=r.filter(s);return{stopReason:e,assistantBlocks:r,toolUseBlocks:i,usage:n,text:o.join("")}}async function*dl(t,e){let n=[],r=null,o=null,s=!1,i=!!y.AFK_TELEGRAM_TRACE;try{i&&console.log("[translate] starting SDK event iteration");for await(let a of t){switch(i&&console.log("[translate] SDK evt:",a.type),a.type){case"message_start":{let c=a.message?.usage;c&&(o={...c});break}case"content_block_start":{let c=a.content_block;c.type==="text"?n[a.index]={kind:"text",text:""}:c.type==="thinking"?n[a.index]={kind:"thinking",thinking:"",signature:""}:c.type==="tool_use"&&(n[a.index]={kind:"tool_use",id:c.id,name:c.name,partialJson:""},yield{kind:"event",event:{type:"tool.use.start",toolUseId:c.id,toolName:c.name,toolInput:" \u2026",sessionId:e.sessionId}});break}case"content_block_delta":{let c=n[a.index],l=a.delta;l.type==="text_delta"?(c&&c.kind==="text"&&(c.text+=l.text),yield{kind:"event",event:{type:"delta.text",text:l.text,sessionId:e.sessionId}}):l.type==="input_json_delta"?c&&c.kind==="tool_use"&&(c.partialJson+=l.partial_json):l.type==="thinking_delta"?(c&&c.kind==="thinking"&&(c.thinking+=l.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:l.thinking,sessionId:e.sessionId}}):l.type==="signature_delta"&&c&&c.kind==="thinking"&&(c.signature=l.signature);break}case"content_block_stop":{let c=n[a.index];c&&c.kind==="tool_use"&&(yield{kind:"event",event:{type:"tool.use",summary:c.name,toolUseIds:[c.id],sessionId:e.sessionId}});break}case"message_delta":{a.delta&&a.delta.stop_reason!==void 0&&(r=a.delta.stop_reason);let c=a.usage;c&&(o!==null?(o.output_tokens=c.output_tokens,c.cache_creation_input_tokens!=null&&(o.cache_creation_input_tokens=c.cache_creation_input_tokens),c.cache_read_input_tokens!=null&&(o.cache_read_input_tokens=c.cache_read_input_tokens),c.input_tokens!=null&&(o.input_tokens=c.input_tokens)):o={cache_creation:null,cache_creation_input_tokens:c.cache_creation_input_tokens??null,cache_read_input_tokens:c.cache_read_input_tokens??null,inference_geo:null,input_tokens:c.input_tokens??0,output_tokens:c.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:Db(n,r,o)}}F();var Lb=0;function Nb(t){let{name:e,description:n,input_schema:r}=t;return{name:e,...n!==void 0?{description:n}:{},input_schema:r}}var Uo=3,pl=5e3;function $b(t){if(!("status"in t))return!1;let e=t.status;return e===529||e===503}function ul(t){if(t===null||typeof t!="object")return!1;let e=t;if(e.status===529||e.status===503)return!0;let n=e.error;if(n===null||typeof n!="object")return!1;let r=n;return((r.error!==null&&typeof r.error=="object"?r.error.type:void 0)??r.type)==="overloaded_error"}function fl(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=setTimeout(n,t);r.unref(),e.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}async function Ub(t,e,n,r){for(let o=0;;o++){if(o>0){let s=pl*Math.pow(2,o-1);if(await fl(s,r),r.aborted)throw new Error("aborted")}try{return await Promise.resolve(t.messages.create(e,{headers:n,signal:r}))}catch(s){if(r.aborted)throw s;let i=s instanceof Error?s:new Error(String(s));if($b(i)&&o<Uo)continue;throw i}}}function Bb(t,e){if(!e||typeof e!="object")return"";let n=e;if(t==="skill"||t==="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(`
|
|
1240
|
-
`)[0];return" "+(i.length>80?i.slice(0,77)+"\u2026":i)}let s=n.query??n.pattern??n.url??n.description;return typeof s=="string"?" "+s:""}async function*Bo(t){let e=t.maxToolUseIterations??Lb,n={stopReason:null},r=0,o=0,s=Fb(),i=Date.now(),a=c=>({...c,durationMs:Date.now()-i});Ue(t.traceWriter,{phase:"loop_start"});try{for(;;){if(t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let c=ln({baseUrl:t.baseUrl})?Ts(t.messages,dn()):t.messages,l={model:t.model,max_tokens:t.maxTokens,messages:c,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0?{tools:t.tools.map(Nb)}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{output_config:{effort:t.effort}}:{}},d=Date.now(),u;try{u=await Ub(t.client,l,t.headers,t.signal)}catch(S){if(t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let w=S instanceof Error?S:new Error(String(S));w.message.includes("thinking")&&Hb(t.messages,w),yield{type:"error",error:w};return}let p=null,f=!1,g=!1,m=!1;try{y.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let S of dl(u,t.ctx))if(m||(m=!0,Ue(t.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-d})),y.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",S.kind,S.kind==="event"?S.event.type:""),S.kind==="event"){if(S.event.type==="error"){if(ul(S.event.error)&&o<Uo&&!t.signal.aborted){g=!0;break}yield S.event,f=!0;break}yield S.event}else{p=S.result;break}y.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",p?"set":"null")}catch(S){if(t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let w=S instanceof Error?S:new Error(String(S));if(ul(w)&&o<Uo&&!t.signal.aborted)g=!0;else{yield{type:"error",error:w};return}}if(g){if(o+=1,yield{type:"stream.retry",sessionId:t.ctx.sessionId},await fl(pl*Math.pow(2,o-1),t.signal),t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}continue}if(o=0,f){t.signal.aborted&&(yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId});return}if(p===null){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let k=ll(p.usage,p.stopReason,t.model);if(n=zt(n,k),n.contextWindowTokens=(k.inputTokens??0)+(k.outputTokens??0)+(k.cachedInputTokens??0)+(k.cacheCreationTokens??0),t.onUsageProgress?.(n),p.stopReason!=="tool_use"){p.text.length>0&&(yield{type:"assistant.message",text:p.text,sessionId:t.ctx.sessionId},p.text.length<=200&&(yield{type:"suggestion",suggestion:p.text,sessionId:t.ctx.sessionId}));let S=p.assistantBlocks.filter(w=>w.type!=="tool_use");S.length>0&&t.messages.push({role:"assistant",content:S}),yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let _=t.messages.length;t.messages.push({role:"assistant",content:p.assistantBlocks});try{let S=[],w=new Map;for(let C of p.toolUseBlocks){S.push({id:C.id,name:C.name,input:C.input,signal:t.signal});let M=Date.now();w.set(C.id,M),Sr(t.traceWriter,{phase:"started",toolUseId:C.id,name:C.name,inputBytes:Buffer.byteLength(JSON.stringify(C.input??{}),"utf8")}),yield{type:"tool.use.start",toolUseId:C.id,toolName:C.name,toolInput:Bb(C.name,C.input),sessionId:t.ctx.sessionId}}if(t.signal.aborted){let C=S.map(M=>({type:"tool_result",tool_use_id:M.id,content:"Tool call aborted",is_error:!0}));t.messages.push({role:"user",content:C}),yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let E;if(t.toolDispatcher.executeBatch)try{E=await t.toolDispatcher.executeBatch(S)}catch(C){E=S.map(()=>({content:`Tool batch execution failed: ${C instanceof Error?C.message:String(C)}`,isError:!0}))}else{E=[];for(let C of S){if(t.signal.aborted){E.push({content:"Tool call aborted",isError:!0});continue}try{E.push(await t.toolDispatcher.execute(C))}catch(M){let L=M instanceof Error?M.message:String(M);E.push({content:`Tool execution threw: ${L}`,isError:!0})}}}let A=[];for(let C=0;C<S.length;C++){let M=S[C],L=E[C],v=w.get(M.id),h=typeof v=="number"?Date.now()-v:0,x=L.truncated===!0||L.content.includes("[output truncated");Sr(t.traceWriter,{phase:"completed",toolUseId:M.id,name:M.name,resultBytes:Buffer.byteLength(L.content,"utf8"),isError:L.isError===!0,truncated:x,durationMs:h,...L.circuitBreaker===!0?{circuitBreaker:!0}:{}}),yield{type:"tool.output",toolUseId:M.id,toolName:M.name,content:L.content,...L.isError===!0?{isError:!0}:{},...x?{truncated:!0}:{},sessionId:t.ctx.sessionId},L.render?.diff&&(yield{type:"tool.diff",toolUseId:M.id,diff:L.render.diff,sessionId:t.ctx.sessionId});let{content:R,isError:T,image:O}=L,j=O!==void 0?[{type:"image",source:{type:"base64",media_type:O.mediaType,data:O.data}},...R.length>0?[{type:"text",text:R}]:[]]:R;A.push({type:"tool_result",tool_use_id:M.id,content:j,...T===!0?{is_error:!0}:{}})}let I={role:"user",content:A};t.messages.push(I)}catch(S){throw t.messages.splice(_),S}r+=1;let b=p.toolUseBlocks[p.toolUseBlocks.length-1];if(yield{type:"progress",progress:{taskId:s,description:"Tool-use loop",summary:`Iteration ${r}: used ${b?.name??"unknown"}`,lastToolName:b?.name,totalTokens:n.totalTokens??0,toolUses:r,durationMs:Date.now()-i},sessionId:t.ctx.sessionId},e>0&&r>=e){yield{type:"turn.completed",usage:a({...n,stopReason:"tool_use_loop_capped"}),sessionId:t.ctx.sessionId};return}}}finally{Ue(t.traceWriter,{phase:"loop_end",durationMs:Date.now()-i})}}function Hb(t,e){try{let n=[];for(let r=0;r<t.length;r++){let o=t[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 c=a;(!c.thinking||!c.signature)&&n.push({msgIdx:r,blockIdx:i,thinking:c.thinking?`(${c.thinking.length} chars)`:"(empty)",sigLen:c.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",e.message),console.error(`[afk] messages.length=${t.length}, invalid thinking blocks:`,n.length>0?JSON.stringify(n):"none found (cause may be elsewhere)")}catch{}}function Jn(t){if(!("status"in t))return null;let e=t.status;if(e===429){let n=t.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 e===400&&t.message.includes("invalid_request_error")&&t.message.includes("credit balance")?{kind:"credit-exhausted"}:null}async function ml(t){let{resetsAt:e,signal:n,readToken:r=ie}=t,o=r(),s=e.getTime()+3e4;return new Promise(i=>{let a,c=!1,l=p=>{c||(c=!0,a!==void 0&&clearInterval(a),n.removeEventListener("abort",d),i(p))},d=()=>{l("aborted")},u=()=>n.aborted?(l("aborted"),!0):Date.now()>=s?(l("timer"),!0):r()!==o?(l("hot-swap"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),n.addEventListener("abort",d,{once:!0}))})}async function gl(t){let{signal:e,readToken:n=ie,retryAfterMs:r}=t,o=n(),s=r!==void 0?Date.now()+r:void 0;return new Promise(i=>{let a,c=!1,l=p=>{c||(c=!0,a!==void 0&&clearInterval(a),e.removeEventListener("abort",d),i(p))},d=()=>{l("aborted")},u=()=>e.aborted?(l("aborted"),!0):n()!==o?(l("hot-swap"),!0):s!==void 0&&Date.now()>=s?(l("timer"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),e.addEventListener("abort",d,{once:!0}))})}var hl=7200*1e3,jb=60*1e3,Vn=class{_client;_authMode;initSessionId;tokenRefresher;autoResumeOnUsageLimit;refreshPromise=null;usageLimitWaitPromise=null;constructor(e){this._client=e.client,this._authMode=e.authMode,this.initSessionId=e.initSessionId,this.tokenRefresher=e.tokenRefresher,this.autoResumeOnUsageLimit=e.autoResumeOnUsageLimit}get client(){return this._client}get authMode(){return this._authMode}async forceClientRefresh(){if(!this.tokenRefresher)return null;let e=ie(),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=ie();return{accountId:xt(r??""),swapped:e!==r}}async*turnWithRetries(e,n){yield*this.turnWithUsageLimitRetry(e,n)}async*turnWithUsageLimitRetry(e,n){let r=null,o=null,s=!1;for await(let l of this.turnWithAuthRetry(e,n)){if(l.type==="error"){let d=Jn(l.error);if(d&&d.kind==="oauth-limit"){o=d.resetsAt,r=l;break}if(d&&d.kind==="oauth-limit-no-ts"){s=!0,r=l;break}}yield l}if(!r)return;if(s){let l=xt(ie()??"");if(yield{type:"paused",reason:"usage-limit",accountId:l,autoResume:this.autoResumeOnUsageLimit},!this.autoResumeOnUsageLimit){yield r;return}let d=Date.now(),u=!1;for(;;){let p;if(this.usageLimitWaitPromise)p="aborted";else{this.usageLimitWaitPromise=gl({signal:e.signal,retryAfterMs:jb});try{p=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(p==="aborted")return;let f=l;if(p==="hot-swap"){let m=await this.forceClientRefresh();m&&(e.client=this._client,f=m.accountId)}e.headers=fe(this._authMode,this.initSessionId,Ho());let g=null;for await(let m of this.turnWithAuthRetry(e,n)){if(!u&&m.type==="error"){let k=Jn(m.error);if(k&&(k.kind==="oauth-limit"||k.kind==="oauth-limit-no-ts")){g=m;break}}u||(yield{type:"resumed",hotSwapped:p==="hot-swap",accountId:f},u=!0),yield m}if(!g)return;if(Date.now()-d>hl){yield g;return}}}if(!o)return;if(o.getTime()-Date.now()>hl){yield r;return}let i=xt(ie()??"");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=ml({resetsAt:o,signal:e.signal});try{a=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(a==="aborted")return;let c=i;if(a==="hot-swap"){let l=await this.forceClientRefresh();l&&(e.client=this._client,c=l.accountId)}e.headers=fe(this._authMode,this.initSessionId,Ho()),yield{type:"resumed",hotSwapped:a==="hot-swap",accountId:c},yield*this.turnWithAuthRetry(e,n)}async*turnWithAuthRetry(e,n){let r=null;for await(let s of Bo(e)){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}e.client=this._client,e.headers=fe(this._authMode,this.initSessionId,Ho()),yield*Bo(e)}isRetryableAuth(e){return this._authMode==="oauth"&&this.tokenRefresher!==void 0&&"status"in e&&e.status===401}};import{randomUUID as zb}from"node:crypto";var Kb=["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(`
|
|
1240
|
+
`)[0];return" "+(i.length>80?i.slice(0,77)+"\u2026":i)}let s=n.query??n.pattern??n.url??n.description;return typeof s=="string"?" "+s:""}async function*Bo(t){let e=t.maxToolUseIterations??Lb,n={stopReason:null},r=0,o=0,s=Fb(),i=Date.now(),a=c=>({...c,durationMs:Date.now()-i});Ue(t.traceWriter,{phase:"loop_start"});try{for(;;){if(t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let c=ln({baseUrl:t.baseUrl})?Ts(t.messages,dn()):t.messages,l={model:t.model,max_tokens:t.maxTokens,messages:c,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0?{tools:t.tools.map(Nb)}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{output_config:{effort:t.effort}}:{}},d=Date.now(),u;try{u=await Ub(t.client,l,t.headers,t.signal)}catch(S){if(t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let w=S instanceof Error?S:new Error(String(S));w.message.includes("thinking")&&Hb(t.messages,w),yield{type:"error",error:w};return}let p=null,f=!1,g=!1,m=!1;try{y.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let S of dl(u,t.ctx))if(m||(m=!0,Ue(t.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-d,resolvedModel:t.model})),y.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",S.kind,S.kind==="event"?S.event.type:""),S.kind==="event"){if(S.event.type==="error"){if(ul(S.event.error)&&o<Uo&&!t.signal.aborted){g=!0;break}yield S.event,f=!0;break}yield S.event}else{p=S.result;break}y.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",p?"set":"null")}catch(S){if(t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let w=S instanceof Error?S:new Error(String(S));if(ul(w)&&o<Uo&&!t.signal.aborted)g=!0;else{yield{type:"error",error:w};return}}if(g){if(o+=1,yield{type:"stream.retry",sessionId:t.ctx.sessionId},await fl(pl*Math.pow(2,o-1),t.signal),t.signal.aborted){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}continue}if(o=0,f){t.signal.aborted&&(yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId});return}if(p===null){yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let k=ll(p.usage,p.stopReason,t.model);if(n=zt(n,k),n.contextWindowTokens=(k.inputTokens??0)+(k.outputTokens??0)+(k.cachedInputTokens??0)+(k.cacheCreationTokens??0),t.onUsageProgress?.(n),p.stopReason!=="tool_use"){p.text.length>0&&(yield{type:"assistant.message",text:p.text,sessionId:t.ctx.sessionId},p.text.length<=200&&(yield{type:"suggestion",suggestion:p.text,sessionId:t.ctx.sessionId}));let S=p.assistantBlocks.filter(w=>w.type!=="tool_use");S.length>0&&t.messages.push({role:"assistant",content:S}),yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let _=t.messages.length;t.messages.push({role:"assistant",content:p.assistantBlocks});try{let S=[],w=new Map;for(let C of p.toolUseBlocks){S.push({id:C.id,name:C.name,input:C.input,signal:t.signal});let M=Date.now();w.set(C.id,M),Sr(t.traceWriter,{phase:"started",toolUseId:C.id,name:C.name,inputBytes:Buffer.byteLength(JSON.stringify(C.input??{}),"utf8")}),yield{type:"tool.use.start",toolUseId:C.id,toolName:C.name,toolInput:Bb(C.name,C.input),sessionId:t.ctx.sessionId}}if(t.signal.aborted){let C=S.map(M=>({type:"tool_result",tool_use_id:M.id,content:"Tool call aborted",is_error:!0}));t.messages.push({role:"user",content:C}),yield{type:"turn.completed",usage:a(n),sessionId:t.ctx.sessionId};return}let E;if(t.toolDispatcher.executeBatch)try{E=await t.toolDispatcher.executeBatch(S)}catch(C){E=S.map(()=>({content:`Tool batch execution failed: ${C instanceof Error?C.message:String(C)}`,isError:!0}))}else{E=[];for(let C of S){if(t.signal.aborted){E.push({content:"Tool call aborted",isError:!0});continue}try{E.push(await t.toolDispatcher.execute(C))}catch(M){let L=M instanceof Error?M.message:String(M);E.push({content:`Tool execution threw: ${L}`,isError:!0})}}}let A=[];for(let C=0;C<S.length;C++){let M=S[C],L=E[C],v=w.get(M.id),h=typeof v=="number"?Date.now()-v:0,x=L.truncated===!0||L.content.includes("[output truncated");Sr(t.traceWriter,{phase:"completed",toolUseId:M.id,name:M.name,resultBytes:Buffer.byteLength(L.content,"utf8"),isError:L.isError===!0,truncated:x,durationMs:h,...L.circuitBreaker===!0?{circuitBreaker:!0}:{}}),yield{type:"tool.output",toolUseId:M.id,toolName:M.name,content:L.content,...L.isError===!0?{isError:!0}:{},...x?{truncated:!0}:{},sessionId:t.ctx.sessionId},L.render?.diff&&(yield{type:"tool.diff",toolUseId:M.id,diff:L.render.diff,sessionId:t.ctx.sessionId});let{content:R,isError:T,image:O}=L,j=O!==void 0?[{type:"image",source:{type:"base64",media_type:O.mediaType,data:O.data}},...R.length>0?[{type:"text",text:R}]:[]]:R;A.push({type:"tool_result",tool_use_id:M.id,content:j,...T===!0?{is_error:!0}:{}})}let I={role:"user",content:A};t.messages.push(I)}catch(S){throw t.messages.splice(_),S}r+=1;let b=p.toolUseBlocks[p.toolUseBlocks.length-1];if(yield{type:"progress",progress:{taskId:s,description:"Tool-use loop",summary:`Iteration ${r}: used ${b?.name??"unknown"}`,lastToolName:b?.name,totalTokens:n.totalTokens??0,toolUses:r,durationMs:Date.now()-i},sessionId:t.ctx.sessionId},e>0&&r>=e){yield{type:"turn.completed",usage:a({...n,stopReason:"tool_use_loop_capped"}),sessionId:t.ctx.sessionId};return}}}finally{Ue(t.traceWriter,{phase:"loop_end",durationMs:Date.now()-i})}}function Hb(t,e){try{let n=[];for(let r=0;r<t.length;r++){let o=t[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 c=a;(!c.thinking||!c.signature)&&n.push({msgIdx:r,blockIdx:i,thinking:c.thinking?`(${c.thinking.length} chars)`:"(empty)",sigLen:c.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",e.message),console.error(`[afk] messages.length=${t.length}, invalid thinking blocks:`,n.length>0?JSON.stringify(n):"none found (cause may be elsewhere)")}catch{}}function Jn(t){if(!("status"in t))return null;let e=t.status;if(e===429){let n=t.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 e===400&&t.message.includes("invalid_request_error")&&t.message.includes("credit balance")?{kind:"credit-exhausted"}:null}async function ml(t){let{resetsAt:e,signal:n,readToken:r=ie}=t,o=r(),s=e.getTime()+3e4;return new Promise(i=>{let a,c=!1,l=p=>{c||(c=!0,a!==void 0&&clearInterval(a),n.removeEventListener("abort",d),i(p))},d=()=>{l("aborted")},u=()=>n.aborted?(l("aborted"),!0):Date.now()>=s?(l("timer"),!0):r()!==o?(l("hot-swap"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),n.addEventListener("abort",d,{once:!0}))})}async function gl(t){let{signal:e,readToken:n=ie,retryAfterMs:r}=t,o=n(),s=r!==void 0?Date.now()+r:void 0;return new Promise(i=>{let a,c=!1,l=p=>{c||(c=!0,a!==void 0&&clearInterval(a),e.removeEventListener("abort",d),i(p))},d=()=>{l("aborted")},u=()=>e.aborted?(l("aborted"),!0):n()!==o?(l("hot-swap"),!0):s!==void 0&&Date.now()>=s?(l("timer"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),e.addEventListener("abort",d,{once:!0}))})}var hl=7200*1e3,jb=60*1e3,Vn=class{_client;_authMode;initSessionId;tokenRefresher;autoResumeOnUsageLimit;refreshPromise=null;usageLimitWaitPromise=null;constructor(e){this._client=e.client,this._authMode=e.authMode,this.initSessionId=e.initSessionId,this.tokenRefresher=e.tokenRefresher,this.autoResumeOnUsageLimit=e.autoResumeOnUsageLimit}get client(){return this._client}get authMode(){return this._authMode}async forceClientRefresh(){if(!this.tokenRefresher)return null;let e=ie(),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=ie();return{accountId:xt(r??""),swapped:e!==r}}async*turnWithRetries(e,n){yield*this.turnWithUsageLimitRetry(e,n)}async*turnWithUsageLimitRetry(e,n){let r=null,o=null,s=!1;for await(let l of this.turnWithAuthRetry(e,n)){if(l.type==="error"){let d=Jn(l.error);if(d&&d.kind==="oauth-limit"){o=d.resetsAt,r=l;break}if(d&&d.kind==="oauth-limit-no-ts"){s=!0,r=l;break}}yield l}if(!r)return;if(s){let l=xt(ie()??"");if(yield{type:"paused",reason:"usage-limit",accountId:l,autoResume:this.autoResumeOnUsageLimit},!this.autoResumeOnUsageLimit){yield r;return}let d=Date.now(),u=!1;for(;;){let p;if(this.usageLimitWaitPromise)p="aborted";else{this.usageLimitWaitPromise=gl({signal:e.signal,retryAfterMs:jb});try{p=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(p==="aborted")return;let f=l;if(p==="hot-swap"){let m=await this.forceClientRefresh();m&&(e.client=this._client,f=m.accountId)}e.headers=fe(this._authMode,this.initSessionId,Ho());let g=null;for await(let m of this.turnWithAuthRetry(e,n)){if(!u&&m.type==="error"){let k=Jn(m.error);if(k&&(k.kind==="oauth-limit"||k.kind==="oauth-limit-no-ts")){g=m;break}}u||(yield{type:"resumed",hotSwapped:p==="hot-swap",accountId:f},u=!0),yield m}if(!g)return;if(Date.now()-d>hl){yield g;return}}}if(!o)return;if(o.getTime()-Date.now()>hl){yield r;return}let i=xt(ie()??"");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=ml({resetsAt:o,signal:e.signal});try{a=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(a==="aborted")return;let c=i;if(a==="hot-swap"){let l=await this.forceClientRefresh();l&&(e.client=this._client,c=l.accountId)}e.headers=fe(this._authMode,this.initSessionId,Ho()),yield{type:"resumed",hotSwapped:a==="hot-swap",accountId:c},yield*this.turnWithAuthRetry(e,n)}async*turnWithAuthRetry(e,n){let r=null;for await(let s of Bo(e)){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}e.client=this._client,e.headers=fe(this._authMode,this.initSessionId,Ho()),yield*Bo(e)}isRetryableAuth(e){return this._authMode==="oauth"&&this.tokenRefresher!==void 0&&"status"in e&&e.status===401}};import{randomUUID as zb}from"node:crypto";var Kb=["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(`
|
|
1241
1241
|
`),yl="[Compacted summary of earlier conversation]",bl="Acknowledged. Continuing from the summary above.";function Wb(t){if(t.role!=="user")return!1;let e=t.content;if(typeof e=="string")return!0;if(!Array.isArray(e))return!1;for(let n of e)if(n.type==="tool_result")return!1;return!0}function wl(t,e){if(e<=0)return t.length;let n=0;for(let r=t.length-1;r>=0;r--){let o=t[r];if(o&&Wb(o)&&(n+=1,n===e))return r}return-1}function Sl(t,e,n){let r=Gb(t);return{model:e,max_tokens:n,system:Kb,messages:[{role:"user",content:`Summarize the following conversation transcript. Follow the system instructions exactly.
|
|
1242
1242
|
|
|
1243
1243
|
<transcript>
|
|
@@ -1245,7 +1245,7 @@ ${e.body}`)}function Sb(t,e){return t.length===0||t.length>64?{valid:!1,reason:`
|
|
|
1245
1245
|
</transcript>`}],stream:!0}}function vl(t,e,n){return[{role:"user",content:yl+`
|
|
1246
1246
|
|
|
1247
1247
|
`+n},{role:"assistant",content:bl},...t.slice(e)]}function kl(t,e,n){let r=qb(t.slice(0,e)),o=yl.length+2+n.length+bl.length,s=Math.max(0,r-o);return Math.round(s/4)}function Gb(t){let e=[];for(let n of t){let r=n.role==="user"?"User":"Assistant";if(e.push(r+":"),typeof n.content=="string")e.push(n.content);else if(Array.isArray(n.content))for(let o of n.content){let s=o.type;if(s==="text"&&"text"in o)e.push(o.text);else if(s==="tool_use"){let i=o.name??"unknown",a=_l(o.input);e.push(`[tool call: ${i} ${a}]`)}else if(s==="tool_result"){let i=o.content;e.push(`[tool result: ${El(i)}]`)}else s==="image"?e.push("[image]"):s==="document"&&e.push("[document]")}e.push("")}return e.join(`
|
|
1248
|
-
`).trim()}function _l(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function El(t){if(typeof t=="string")return t.length>320?t.slice(0,317)+"...":t;if(Array.isArray(t)){let e=[];for(let r of t)r.type==="text"&&"text"in r&&e.push(r.text);let n=e.join(" ");return n.length>320?n.slice(0,317)+"...":n}return""}function qb(t){let e=0;for(let n of t)if(typeof n.content=="string")e+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content){let o=r.type;o==="text"&&"text"in r?e+=r.text.length:o==="tool_use"?e+=_l(r.input).length:o==="tool_result"&&(e+=El(r.content).length)}return e}F();var Jb=2,Vb="claude-haiku-4-5-20251001",Yb=1024;async function Al(t){let{state:e,abort:n,retry:r,initSessionId:o,traceWriter:s}=t,i=e.messages.length;if(e.closed)return{compacted:!1,reason:"session-closed",messagesBefore:i,messagesAfter:i};if(!n.isIdle())return{compacted:!1,reason:"turn-in-flight",messagesBefore:i,messagesAfter:i};let a=Xb(),c=wl(e.messages,a);if(c<0)return{compacted:!1,reason:"history-too-short",messagesBefore:i,messagesAfter:i};if(c===0)return{compacted:!1,reason:"nothing-to-summarize",messagesBefore:i,messagesAfter:i};let l=e.messages.slice(0,c),d=Qb(),u=Sl(l,d,Yb),p=n.begin(),f;try{if(p.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let _=fe(r.authMode,o,zb()),b=r.client,S=await Promise.resolve(b.messages.create(u,{headers:_,signal:p.signal}));f=await Zb(S)}catch(_){return p.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i}:{compacted:!1,reason:"summarization-failed: "+(_ instanceof Error?_.message:String(_)),messagesBefore:i,messagesAfter:i}}finally{n.clear(p)}if(f.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:i,messagesAfter:i};let g=kl(e.messages,c,f),m=vl(e.messages,c,f);e.messages.splice(0,e.messages.length,...m);let k=e.messages.length;return us(s,{trigger:"manual",preCompactionMessages:l,summary:f,keptTailCount:i-c,keepLastNConfig:a,messagesBefore:i,messagesAfter:k,tokensSavedEstimate:g}),{compacted:!0,messagesBefore:i,messagesAfter:k,tokensSavedEstimate:g}}function Xb(){let t=y.AFK_COMPACT_KEEP_LAST_TURNS;if(t!==void 0&&t.length>0){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return Jb}function Qb(){let t=y.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?t:Vb}async function Zb(t){let e="";for await(let n of t)if(n.type==="content_block_delta"){let r=n.delta;r.type==="text_delta"&&typeof r.text=="string"&&(e+=r.text)}return e}var ew=[{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"}],Yn=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;baseUrl;traceWriter;state;abort;retry;cwdDependentsFactory;mcpManager;constructor(e){this.initSessionId=e.sessionId??xl(),this.promptStream=e.promptStream,this.maxTokens=e.maxTokens,this.tools=e.tools,this.systemPrefix=e.systemPrefix,this.thinking=e.thinking,e.effort!==void 0&&(this.effort=e.effort),e.baseUrl!==void 0&&(this.baseUrl=e.baseUrl),this.traceWriter=e.traceWriter,this.cwdDependentsFactory=e.cwdDependentsFactory,this.mcpManager=e.mcpManager,this.retry=new Vn({client:e.client,authMode:e.authMode,initSessionId:this.initSessionId,...e.tokenRefresher?{tokenRefresher:e.tokenRefresher}:{},autoResumeOnUsageLimit:e.autoResumeOnUsageLimit??!0}),this.state=cl({model:e.model,...e.requestedModel!==void 0?{requestedModel:e.requestedModel}:{},permissionMode:e.permissionMode??"default",userSystem:e.userSystem,toolDispatcher:e.toolDispatcher,...e.initialMessages?{initialMessages:e.initialMessages}:{},...e.autoCompactThreshold!==void 0?{autoCompactThreshold:e.autoCompactThreshold}:{}}),this.abort=new zn}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}al(this.state.messages),this.state.messages.push({role:"user",content:s.content});let a=this.composeSystem(),c=fe(this.retry.authMode,this.initSessionId,xl(),this.effort!==void 0),l={client:this.retry.client,messages:this.state.messages,system:a,tools:this.tools,toolDispatcher:this.state.toolDispatcher,model:this.state.currentModel,maxTokens:this.maxTokens,headers:c,signal:i.signal,ctx:{sessionId:this.initSessionId},...this.thinking!==void 0?{thinking:this.thinking}:{},...this.effort!==void 0?{effort:this.effort}:{},...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{},...this.traceWriter?{traceWriter:this.traceWriter}:{},onUsageProgress:d=>{this.state.lastUsage=d}};try{for await(let d of this.retry.turnWithRetries(l,()=>this.state.closed)){if(this.state.closed)return;d.type==="turn.completed"&&(this.state.lastUsage=d.usage,this.abort.clear(i)),yield d}}catch(d){if(i.signal.aborted)return;yield{type:"error",error:d instanceof Error?d:new Error(String(d))};return}finally{this.abort.clear(i)}if(this.state.autoCompactThreshold!==void 0&&!this.state.closed){let d=this.state.lastUsage,u=Jt(this.state.requestedModel);if(d!==null&&u>0){let p=dt(d);cc(p,u,this.state.autoCompactThreshold)&&await this.compact()}}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}composeSystem(){let e=this.systemPrefix,n=this.state.userSystem,r=[];e&&e.length>0&&r.push(...e),n&&n.length>0&&r.push({type:"text",text:n});let o=Ps(this.state.currentPermissionMode);return o!==null&&r.push(o),r.length===0?null:ln({baseUrl:this.baseUrl})?xs(r,dn()):r}async interrupt(){this.abort.requestAbort("interrupted")}async setModel(e){e!==void 0&&e.length>0&&(this.state.requestedModel=e,this.state.currentModel=
|
|
1248
|
+
`).trim()}function _l(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function El(t){if(typeof t=="string")return t.length>320?t.slice(0,317)+"...":t;if(Array.isArray(t)){let e=[];for(let r of t)r.type==="text"&&"text"in r&&e.push(r.text);let n=e.join(" ");return n.length>320?n.slice(0,317)+"...":n}return""}function qb(t){let e=0;for(let n of t)if(typeof n.content=="string")e+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content){let o=r.type;o==="text"&&"text"in r?e+=r.text.length:o==="tool_use"?e+=_l(r.input).length:o==="tool_result"&&(e+=El(r.content).length)}return e}F();var Jb=2,Vb="claude-haiku-4-5-20251001",Yb=1024;async function Al(t){let{state:e,abort:n,retry:r,initSessionId:o,traceWriter:s}=t,i=e.messages.length;if(e.closed)return{compacted:!1,reason:"session-closed",messagesBefore:i,messagesAfter:i};if(!n.isIdle())return{compacted:!1,reason:"turn-in-flight",messagesBefore:i,messagesAfter:i};let a=Xb(),c=wl(e.messages,a);if(c<0)return{compacted:!1,reason:"history-too-short",messagesBefore:i,messagesAfter:i};if(c===0)return{compacted:!1,reason:"nothing-to-summarize",messagesBefore:i,messagesAfter:i};let l=e.messages.slice(0,c),d=Qb(),u=Sl(l,d,Yb),p=n.begin(),f;try{if(p.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let _=fe(r.authMode,o,zb()),b=r.client,S=await Promise.resolve(b.messages.create(u,{headers:_,signal:p.signal}));f=await Zb(S)}catch(_){return p.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i}:{compacted:!1,reason:"summarization-failed: "+(_ instanceof Error?_.message:String(_)),messagesBefore:i,messagesAfter:i}}finally{n.clear(p)}if(f.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:i,messagesAfter:i};let g=kl(e.messages,c,f),m=vl(e.messages,c,f);e.messages.splice(0,e.messages.length,...m);let k=e.messages.length;return us(s,{trigger:"manual",preCompactionMessages:l,summary:f,keptTailCount:i-c,keepLastNConfig:a,messagesBefore:i,messagesAfter:k,tokensSavedEstimate:g}),{compacted:!0,messagesBefore:i,messagesAfter:k,tokensSavedEstimate:g}}function Xb(){let t=y.AFK_COMPACT_KEEP_LAST_TURNS;if(t!==void 0&&t.length>0){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return Jb}function Qb(){let t=y.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?t:Vb}async function Zb(t){let e="";for await(let n of t)if(n.type==="content_block_delta"){let r=n.delta;r.type==="text_delta"&&typeof r.text=="string"&&(e+=r.text)}return e}var ew=[{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"}],Yn=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;baseUrl;traceWriter;state;abort;retry;cwdDependentsFactory;mcpManager;constructor(e){this.initSessionId=e.sessionId??xl(),this.promptStream=e.promptStream,this.maxTokens=e.maxTokens,this.tools=e.tools,this.systemPrefix=e.systemPrefix,this.thinking=e.thinking,e.effort!==void 0&&(this.effort=e.effort),e.baseUrl!==void 0&&(this.baseUrl=e.baseUrl),this.traceWriter=e.traceWriter,this.cwdDependentsFactory=e.cwdDependentsFactory,this.mcpManager=e.mcpManager,this.retry=new Vn({client:e.client,authMode:e.authMode,initSessionId:this.initSessionId,...e.tokenRefresher?{tokenRefresher:e.tokenRefresher}:{},autoResumeOnUsageLimit:e.autoResumeOnUsageLimit??!0}),this.state=cl({model:e.model,...e.requestedModel!==void 0?{requestedModel:e.requestedModel}:{},permissionMode:e.permissionMode??"default",userSystem:e.userSystem,toolDispatcher:e.toolDispatcher,...e.initialMessages?{initialMessages:e.initialMessages}:{},...e.autoCompactThreshold!==void 0?{autoCompactThreshold:e.autoCompactThreshold}:{}}),this.abort=new zn}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}al(this.state.messages),this.state.messages.push({role:"user",content:s.content});let a=this.composeSystem(),c=fe(this.retry.authMode,this.initSessionId,xl(),this.effort!==void 0),l={client:this.retry.client,messages:this.state.messages,system:a,tools:this.tools,toolDispatcher:this.state.toolDispatcher,model:this.state.currentModel,maxTokens:this.maxTokens,headers:c,signal:i.signal,ctx:{sessionId:this.initSessionId},...this.thinking!==void 0?{thinking:this.thinking}:{},...this.effort!==void 0?{effort:this.effort}:{},...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{},...this.traceWriter?{traceWriter:this.traceWriter}:{},onUsageProgress:d=>{this.state.lastUsage=d}};try{for await(let d of this.retry.turnWithRetries(l,()=>this.state.closed)){if(this.state.closed)return;d.type==="turn.completed"&&(this.state.lastUsage=d.usage,this.abort.clear(i)),yield d}}catch(d){if(i.signal.aborted)return;yield{type:"error",error:d instanceof Error?d:new Error(String(d))};return}finally{this.abort.clear(i)}if(this.state.autoCompactThreshold!==void 0&&!this.state.closed){let d=this.state.lastUsage,u=Jt(this.state.requestedModel);if(d!==null&&u>0){let p=dt(d);cc(p,u,this.state.autoCompactThreshold)&&await this.compact()}}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}composeSystem(){let e=this.systemPrefix,n=this.state.userSystem,r=[];e&&e.length>0&&r.push(...e),n&&n.length>0&&r.push({type:"text",text:n});let o=Ps(this.state.currentPermissionMode);return o!==null&&r.push(o),r.length===0?null:ln({baseUrl:this.baseUrl})?xs(r,dn()):r}async interrupt(){this.abort.requestAbort("interrupted")}async setModel(e){e!==void 0&&e.length>0&&(this.state.requestedModel=e,this.state.currentModel=te(e)??e)}async setPermissionMode(e){this.state.currentPermissionMode=e}setCwd(e){if(this.state.toolDispatcher.setResolveBase?.(e),!this.cwdDependentsFactory)return;let{userSystem:n,dispatcher:r}=this.cwdDependentsFactory(e);this.state.userSystem=n,this.state.toolDispatcher=r}async supportedCommands(){try{return ut().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return ew.map(e=>({...e}))}async supportedAgents(){return[]}async getContextUsage(){let e=this.state.lastUsage,n=Jt(this.state.requestedModel),r;if(e&&n>0){let i=dt(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=$n(e);return{tools:[],agents:[],isAutoCompactEnabled:this.state.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.mcpManager?this.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{subscriptionType:this.retry.authMode==="oauth"?"claude-subscription":"api-key"}}async reauth(){return this.retry.forceClientRefresh()}async rewindFiles(e,n){return{canRewind:!1,error:"anthropic-direct provider does not support file checkpoint rewind"}}async compact(){return Al({state:this.state,abort:this.abort,retry:this.retry,initSessionId:this.initSessionId,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}close(){this.state.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed()}};var Xn=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
|
|
1249
1249
|
|
|
1250
1250
|
- Use read_file before editing to verify the exact content you want to change.
|
|
1251
1251
|
- Prefer edit_file over write_file for modifying existing files \u2014 write_file is for new files or complete rewrites.
|
|
@@ -1254,7 +1254,7 @@ ${e.body}`)}function Sb(t,e){return t.length===0||t.length>64?{valid:!1,reason:`
|
|
|
1254
1254
|
- Use glob and grep to discover files before reading individual files.
|
|
1255
1255
|
- When bash output is very long, it may be truncated. If you need the full output, redirect to a file and read it.
|
|
1256
1256
|
- Use absolute paths for file operations.
|
|
1257
|
-
- Prefer \`agent\` (and \`skill\`) for multi-file investigation, verification, parallel hypotheses, and any work that would otherwise consume large amounts of inline context. The main session is the coordinator; subagents are the investigators.`,jo="When you see a `<command-name>` tag in the current conversation turn, the skill has ALREADY been loaded by the user typing a slash command. Do NOT re-invoke the skill tool to dispatch that same skill again. Instead, treat the `<command-message>` as the skill name and `<command-args>` as its arguments, then follow the instructions in the body block immediately following the tag. You MAY still invoke the skill tool to dispatch OTHER skills that are not the one already loaded.",Ko='When a user message contains a `<bash-passthrough>` block, it represents a shell command the **user ran directly** in the REPL using the `!` prefix (e.g. `!ls` or `!&pnpm test`). This is distinct from the `bash` tool you invoke yourself:\n\n- `<bash-passthrough>` = human-initiated shell run, output injected into your context automatically\n- `bash` tool result = model-initiated command you explicitly called\n\nAttributes on the opening tag:\n- `mode="foreground"` \u2014 user waited for the command to finish before the next prompt\n- `mode="background"` \u2014 command ran detached (`!&` prefix); output arrives after it completes\n- `exit="N"` \u2014 shell exit code (0 = success)\n- `reason="..."` \u2014 error category when nonzero: `nonzero-exit`, `abort` (Ctrl+C), `timeout`, `overflow`, `spawn-failed`, `signal-killed`\n- `duration="1.3s"` \u2014 wall-clock runtime\n- `truncated="true"` \u2014 output was capped; full output not available\n\nThe `<command>` child contains the literal command the user typed (XML-escaped). The `<output>` child contains ANSI-stripped, XML-escaped captured stdout/stderr.'
|
|
1257
|
+
- Prefer \`agent\` (and \`skill\`) for multi-file investigation, verification, parallel hypotheses, and any work that would otherwise consume large amounts of inline context. The main session is the coordinator; subagents are the investigators.`,jo="When you see a `<command-name>` tag in the current conversation turn, the skill has ALREADY been loaded by the user typing a slash command. Do NOT re-invoke the skill tool to dispatch that same skill again. Instead, treat the `<command-message>` as the skill name and `<command-args>` as its arguments, then follow the instructions in the body block immediately following the tag. You MAY still invoke the skill tool to dispatch OTHER skills that are not the one already loaded.",Ko='When a user message contains a `<bash-passthrough>` block, it represents a shell command the **user ran directly** in the REPL using the `!` prefix (e.g. `!ls` or `!&pnpm test`). This is distinct from the `bash` tool you invoke yourself:\n\n- `<bash-passthrough>` = human-initiated shell run, output injected into your context automatically\n- `bash` tool result = model-initiated command you explicitly called\n\nAttributes on the opening tag:\n- `mode="foreground"` \u2014 user waited for the command to finish before the next prompt\n- `mode="background"` \u2014 command ran detached (`!&` prefix); output arrives after it completes\n- `exit="N"` \u2014 shell exit code (0 = success)\n- `reason="..."` \u2014 error category when nonzero: `nonzero-exit`, `abort` (Ctrl+C), `timeout`, `overflow`, `spawn-failed`, `signal-killed`\n- `duration="1.3s"` \u2014 wall-clock runtime\n- `truncated="true"` \u2014 output was capped; full output not available\n\nThe `<command>` child contains the literal command the user typed (XML-escaped). The `<output>` child contains ANSI-stripped, XML-escaped captured stdout/stderr.',UM=`${Xn}
|
|
1258
1258
|
|
|
1259
1259
|
${jo}
|
|
1260
1260
|
|
|
@@ -1303,7 +1303,7 @@ Use FTS5 syntax: "exact phrase", term1 AND term2, prefix*.`;F();import{mkdirSync
|
|
|
1303
1303
|
`;process.stderr.write(c);return}let i=ow(e),a=sw(i);try{tw(a,{recursive:!0});let l=(!rw(i)?iw:"")+JSON.stringify(s)+`
|
|
1304
1304
|
`;nw(i,l)}catch(c){let l=`[prompt-dump] Failed to write to ${i}: ${String(c)}
|
|
1305
1305
|
`;process.stderr.write(l)}}H();F();var Zt="anthropic-direct",Cl="claude-sonnet-4-5-20250929",gw=t=>/opus-4-(7|[89])/.test(t),qo=null;var _e=class{name=Zt;externalTools;memoryStore;providerFactory;skillExecutor;schemas;hookRegistry;permissions;subagentExecutor;composeExecutor;surface;readOnlyMemory;readOnlyBash;mcpManager;_sharedReadRoots;_sharedWriteRoots;_initialResolveBase;_currentCwd;_mcpToolsCache=null;_mcpHandlersCache=null;_presenceSessionId=null;constructor(e={}){let n=[...ce];if(e.subagentExecutor&&n.push(Ce),e.skillExecutor&&n.push(Me),e.composeExecutor&&n.push(Oe),e.readOnlyMemory===!0?n.push(nt):n.push(...De),n.push(me),this.memoryStore=e.memoryStore??new ve,this.externalTools=e.tools,this.skillExecutor=e.skillExecutor,this.schemas=n,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.subagentExecutor=e.subagentExecutor,this.composeExecutor=e.composeExecutor,this.surface=e.surface??"cli",this.readOnlyMemory=e.readOnlyMemory===!0,this.readOnlyBash=e.readOnlyBash===!0,this.mcpManager=e.mcpManager,e.mcpManager){let r=e.mcpManager.onToolsRefreshed;e.mcpManager.onToolsRefreshed=o=>{this._mcpToolsCache=null,this._mcpHandlersCache=null,r?.(o)}}e.clientFactory&&(this.providerFactory=e.clientFactory)}buildDispatcher(e,n){let r=lt(e,n?.cwd),o=Ft(this.memoryStore,void 0,this.surface);for(let[i,a]of o)this.readOnlyMemory&&i!=="memory_search"||r.set(i,a);if(n?.runtimeStateSource&&r.set("get_runtime_state",ot(n.runtimeStateSource)),this.mcpManager){this._mcpToolsCache||(this._mcpToolsCache=this.mcpManager.getMcpTools()),this._mcpHandlersCache||(this._mcpHandlersCache=this.mcpManager.getMcpHandlers());for(let[i,a]of this._mcpHandlersCache)r.set(i,a)}let s=this._mcpToolsCache??[];return new le({handlers:r,schemas:[...this.schemas,...s],hookRegistry:this.hookRegistry,permissions:this.permissions,subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,cwd:n?.cwd,readRoots:n?.readRoots,writeRoots:n?.writeRoots,...n?.env!==void 0?{env:n.env}:{},sessionId:n?.sessionId,parentSessionId:n?.parentSessionId,...n?.traceWriter?{traceWriter:n.traceWriter}:{},readOnlyBash:this.readOnlyBash})}close(){this.memoryStore.close()}async complete(e){let n=e.apiKey&&e.apiKey.length>0?e.apiKey:y.ANTHROPIC_API_KEY||y.CLAUDE_CODE_OAUTH_TOKEN||"";if(!n)throw new Error(`${Zt} complete() requires an API key or OAuth token (config apiKey, ANTHROPIC_API_KEY, or CLAUDE_CODE_OAUTH_TOKEN)`);let r={token:n,model:e.model??Cl,system:e.system,user:e.user,maxTokens:e.maxTokens??64};e.signal&&(r.signal=e.signal);let o=this.providerFactory??qo;return o&&(r.clientFactory=o),ws(r)}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e),e&&!this._currentCwd&&(this._currentCwd=e)}}addReadRoot(e,n="slash",r){this.ensureSharedRoots();let o=Go.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this.appendProviderAuditLog({action:"grant-read",path:o,source:n,sessionId:r})}addWriteRoot(e,n="slash",r){this.ensureSharedRoots();let o=Go.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this._sharedWriteRoots.includes(o)||this._sharedWriteRoots.push(o),this.appendProviderAuditLog({action:"grant-write",path:o,source:n,sessionId:r})}revokeRoot(e,n="slash",r){if(!this._sharedReadRoots)return;let o=Go.resolve(e);if(this._initialResolveBase&&o===this._initialResolveBase)return;let s=this._sharedReadRoots.indexOf(o);if(s!==-1&&this._sharedReadRoots.splice(s,1),this._sharedWriteRoots){let i=this._sharedWriteRoots.indexOf(o);i!==-1&&this._sharedWriteRoots.splice(i,1)}this.appendProviderAuditLog({action:"revoke",path:o,source:n,sessionId:r})}getGrants(){return{resolveBase:this._initialResolveBase,readRoots:this._sharedReadRoots?.slice()??[],writeRoots:this._sharedWriteRoots?.slice()??[]}}appendProviderAuditLog(e){try{let n=tt();fw(mw(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??null,action:e.action,path:e.path,source:e.source});pw(n,r+`
|
|
1306
|
-
`)}catch{}}query(e){let n=e.config,r=typeof n.baseUrl=="string"&&n.baseUrl.length>0,o=r?n.apiKey&&n.apiKey.length>0?n.apiKey:y.AFK_LOCAL_API_KEY||"local":n.apiKey&&n.apiKey.length>0?n.apiKey:y.ANTHROPIC_API_KEY||y.CLAUDE_CODE_OAUTH_TOKEN||"";if(!o||o.length===0)throw new Error(`${Zt} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=an(o),i=kt(o,s,n.baseUrl),a=this.providerFactory??qo,c=a?a(i):new Il(i),l=r?null:ms(s),d=hw(n.systemPrompt),u=typeof n.model=="string"&&n.model.length>0?
|
|
1306
|
+
`)}catch{}}query(e){let n=e.config,r=typeof n.baseUrl=="string"&&n.baseUrl.length>0,o=r?n.apiKey&&n.apiKey.length>0?n.apiKey:y.AFK_LOCAL_API_KEY||"local":n.apiKey&&n.apiKey.length>0?n.apiKey:y.ANTHROPIC_API_KEY||y.CLAUDE_CODE_OAUTH_TOKEN||"";if(!o||o.length===0)throw new Error(`${Zt} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=an(o),i=kt(o,s,n.baseUrl),a=this.providerFactory??qo,c=a?a(i):new Il(i),l=r?null:ms(s),d=hw(n.systemPrompt),u=typeof n.model=="string"&&n.model.length>0?te(n.model)??n.model:Cl,p=ww(n,u),f=n.permissionMode??"default";this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let g,m=Lt({surface:this.surface,cwd:n.cwd??process.cwd(),modelName:u,providerName:Zt,permissionMode:f,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>g instanceof le?g.toolDefs.map(T=>T.name):[],getMcpTools:()=>this.mcpManager?.getMcpTools()??[],getSubagents:()=>this.subagentExecutor?this.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});if((n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let T=n.sessionId,O=m.getWorkspace();$t({sessionId:T,surface:this.surface,cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:Zt,name:u},workspace:O,pid:process.pid}),process.once("exit",()=>{ke(T)}),process.once("SIGINT",()=>{ke(T),process.exit(130)}),process.once("SIGTERM",()=>{ke(T),process.exit(143)})}g=this.externalTools?Nt(this.externalTools,m):this.buildDispatcher(f,{cwd:n.cwd,readRoots:this._sharedReadRoots,writeRoots:this._sharedWriteRoots,...n.env!==void 0?{env:n.env}:{},sessionId:n.sessionId,parentSessionId:n.parentSessionId,traceWriter:n.traceWriter,runtimeStateSource:m});let _=g instanceof le?[...g.toolDefs]:[...ce,me],b=n.isSkillDispatch?_.filter(T=>T.name!=="ask_question"&&T.name!=="terminal_font_size"):_,S=this.skillExecutor?il():"",w=n.cwd||process.cwd(),E=n.isSkillDispatch?Xn:`${Xn}
|
|
1307
1307
|
|
|
1308
1308
|
${jo}
|
|
1309
1309
|
|
|
@@ -1313,7 +1313,7 @@ ${Ko}`,A=this.readOnlyMemory?Rl:Tl,I=[E,A];I.push(rt({cwd:w,...n.sessionId!==voi
|
|
|
1313
1313
|
|
|
1314
1314
|
`),Q=this.buildDispatcher(f,{cwd:T,readRoots:this._sharedReadRoots,writeRoots:this._sharedWriteRoots,...n.env!==void 0?{env:n.env}:{},sessionId:n.sessionId,parentSessionId:n.parentSessionId,traceWriter:n.traceWriter,runtimeStateSource:m});return{userSystem:W,dispatcher:Q}},R=kw(n.effort,u);return new Yn({client:c,authMode:r?"api-key":s,promptStream:e.prompt,toolDispatcher:g,...v!==void 0?{sessionId:v}:{},...h!==void 0?{initialMessages:h}:{},model:u,requestedModel:typeof n.model=="string"&&n.model.length>0?n.model:u,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:p,tools:b,userSystem:C,systemPrefix:l,tokenRefresher:L,...n.thinking!==void 0?{thinking:vw(n.thinking,p,u)}:{},...R!==void 0?{effort:R}:{},...r?{baseUrl:n.baseUrl}:{},...n.traceWriter?{traceWriter:n.traceWriter}:{},...n.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:n.autoResumeOnUsageLimit}:{},...x!==void 0?{cwdDependentsFactory:x}:{},...this.mcpManager!==void 0?{mcpManager:this.mcpManager}:{},...Ml(n.autoCompact)!==void 0?{autoCompactThreshold:Ml(n.autoCompact)}:{}})}};function hw(t){if(t===void 0)return null;if(typeof t=="string")return t.length>0?t:null;if(typeof t=="object"&&t!==null&&"append"in t){let e=t.append;return e&&e.length>0?e:null}return null}var yw=.9;function Ml(t){if(t===void 0||t===!1)return;if(t===!0)return yw;let e=t.threshold;if(!(typeof e!="number"||!Number.isFinite(e)||e<=0||e>=1))return e}var Qn=new Set,bw=.25;function ww(t,e){let n=Wa(e),r=t.maxOutputTokens;if(typeof r=="number"&&Number.isFinite(r)&&r>0){let o=Math.floor(r);if(o>n){let s=`max:${e}:${o}`;return Qn.has(s)||(Qn.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${e} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function Sw(t){if(!t||t.length===0)return;let e=[];for(let n of t)n.user.length>0&&e.push({role:"user",content:n.user}),n.assistant.length>0&&e.push({role:"assistant",content:n.assistant});return e.length>0?e:void 0}function vw(t,e,n){switch(t.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&gw(n))return{type:"adaptive",display:"summarized"};let r=Math.floor(e*bw),o=Math.max(1024,e-1-r),s=t.budgetTokens!==void 0&&Number.isFinite(t.budgetTokens)?Math.floor(t.budgetTokens):void 0,i=Math.min(Math.max(s??o,1024),o);if(s!==void 0&&s>o){let a=`think:${n??"default"}:${s}:${e}`;Qn.has(a)||(Qn.add(a),console.warn(`[afk] thinking budgetTokens ${s} leaves too little of max_tokens ${e} for the reply; clamping to ${o}.`))}return{type:"enabled",budget_tokens:i,display:"summarized"}}}}function kw(t,e){if(t!==void 0)return t;let n=e.toLowerCase();if(/(claude-)?(opus|sonnet)-4-[678]/.test(n))return"max"}var _w=new _e;F();var Ew=new Set([...Object.keys(Rr),"auto"]);function Aw(t){if(!t)return;let e=t.trim().toLowerCase();if(e){if(e==="anthropic"||e==="anthropic-direct")return"anthropic-direct";if(e==="openai"||e==="openai-compatible"||e==="openai-codex")return"openai-compatible"}}function V(t,e){let n=e?.explicit??y.AFK_PROVIDER,r=e?.openaiBaseUrl??y.AFK_OPENAI_BASE_URL,o=Aw(n);if(o)return o;let s=Tr(t,e?.slots);if(s.provider==="anthropic")return"anthropic-direct";if(s.provider==="openai")return"openai-compatible";let i=s.id.trim().toLowerCase();return i&&(Ew.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("/"))||r&&r.trim()?"openai-compatible":"anthropic-direct"}function Zn(t,e){switch(V(t,e)){case"openai-compatible":case"openai-codex":return new de;default:return new _e}}var mt=class{pendingResolve=null;bufferedMessages=[];getSessionId;constructor(e){this.getSessionId=e}pushUserMessage(e){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:e,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessages.push(e)}createIterable(){let e=this;return{[Symbol.asyncIterator](){return{next(){if(e.bufferedMessages.length>0){let n=e.bufferedMessages.shift(),r=e.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{e.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}};function er(t,e){let n=e??_t(),r=Et(t.model,n);if(!r)return;let o=n[r],s=o.provider==="anthropic"?"anthropic-direct":o.provider==="openai"?"openai-compatible":V(t.model,e?{slots:e}:void 0);o.apiKey!==void 0?t.apiKey=o.apiKey:(s==="openai-compatible"||o.baseUrl!==void 0)&&(t.apiKey=void 0),o.baseUrl!==void 0&&(s==="openai-compatible"?t.openaiBaseUrl=o.baseUrl:t.baseUrl=o.baseUrl)}function xw(t){return typeof t=="string"?t:t.map(e=>{let n=e;return n.type==="text"&&typeof n.text=="string"?n.text:""}).filter(e=>e.length>0).join(`
|
|
1315
1315
|
`)}var tr=class{outerIterator;baseConfig;deps;currentModel;currentPermissionMode;currentCwd;startupFamily;active;closed=!1;shadowHistory;pendingUserText;pendingAssistantText="";lastSessionId;constructor(e,n){this.outerIterator=e.prompt[Symbol.asyncIterator](),this.baseConfig=e.config,this.deps=n,this.currentModel=typeof e.config.model=="string"?e.config.model:void 0,this.currentPermissionMode=e.config.permissionMode,this.currentCwd=e.config.cwd,this.startupFamily=n.providerNameForModel(this.currentModel),this.shadowHistory=[...e.config.resumeHistory??[]]}buildInner(e,n){let r=this.deps.resolveProvider(e),o=new mt(()=>this.lastSessionId),s={...this.baseConfig};s.model=e??this.baseConfig.model;let i=r.name===this.startupFamily&&this.baseConfig.apiKey!==void 0?this.baseConfig.apiKey:this.deps.resolveApiKey(e);i!==void 0?s.apiKey=i:delete s.apiKey,er(s),this.currentPermissionMode!==void 0&&(s.permissionMode=this.currentPermissionMode),this.currentCwd!==void 0&&(s.cwd=this.currentCwd),n&&(s.resumeHistory=[...this.shadowHistory]);let a=r.query({prompt:o.createIterable(),config:s});return{family:r.name,query:a,iterator:a[Symbol.asyncIterator](),input:o}}async closeActive(){let e=this.active;if(e){this.active=void 0;try{await e.iterator.return?.(void 0)}catch{}try{await e.query.close()}catch{}}}observeEvent(e){e.type==="assistant.message"&&(this.pendingAssistantText+=(this.pendingAssistantText?`
|
|
1316
|
-
`:"")+e.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),yield*this.driveUntilInit(!1);!this.closed;){let e=await this.outerIterator.next();if(e.done)break;let n=e.value;this.lastSessionId=n.sessionId;let r=this.deps.providerNameForModel(this.currentModel);if((!this.active||r!==this.active.family)&&(await this.closeActive(),this.active=this.buildInner(this.currentModel,!0),D(`\u{1F500} ProviderRouter: switched inner provider \u2192 ${this.active.family} (model=${this.currentModel})`),yield*this.driveUntilInit(!0)))break;for(this.pendingUserText=xw(n.content),this.pendingAssistantText="",this.active.input.pushUserMessage(n.content);;){let o=await this.active.iterator.next();if(o.done){this.closed=!0;break}let s=o.value;if(this.observeEvent(s),yield s,s.type==="turn.completed"){this.commitShadowTurn();break}if(s.type==="error"){this.commitShadowTurn();break}}}}finally{await this.closeActive()}}async*driveUntilInit(e){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 e||(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(e){typeof e=="string"&&e.length>0&&(this.currentModel=e,this.active&&this.deps.providerNameForModel(e)===this.active.family&&await this.active.query.setModel(e))}async setPermissionMode(e){this.currentPermissionMode=e,await this.active?.query.setPermissionMode(e)}setCwd(e){this.currentCwd=e,this.active?.query.setCwd?.(e)}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(e,n){let r=this.active;return r?r.query.rewindFiles(e,n):{canRewind:!1,error:"no active provider"}}async compact(){let e=this.active;return e?.query.compact?e.query.compact():{compacted:!1,reason:"provider does not support compaction",messagesBefore:0,messagesAfter:0}}async reloadPlugins(...e){let n=this.active?.query;if(n&&typeof n.reloadPlugins=="function")return n.reloadPlugins(...e)}async close(){this.closed=!0,await this.closeActive()}};async function nr(t,e,n){if(!t)return;if(n.kind==="blocked"){await Xe(t,{hookEvent:e,decision:"block",...n.err.reason!==void 0?{reason:n.err.reason}:{}});return}let r=n.decision;await Xe(t,{hookEvent:e,decision:r.decision,...r.reason!==void 0?{reason:r.reason}:{},...r.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(r.injectContext,"utf8")}:{}})}async function Ol(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await nr(n.traceWriter,"SessionStart",{kind:"decision",decision:r})}catch(r){throw r instanceof q&&await nr(n.traceWriter,"SessionStart",{kind:"blocked",err:r}),r}}async function Dl(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await nr(n.traceWriter,"SessionEnd",{kind:"decision",decision:r})}catch(r){if(r instanceof q&&await nr(n.traceWriter,"SessionEnd",{kind:"blocked",err:r}),r instanceof q||r instanceof
|
|
1316
|
+
`:"")+e.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),yield*this.driveUntilInit(!1);!this.closed;){let e=await this.outerIterator.next();if(e.done)break;let n=e.value;this.lastSessionId=n.sessionId;let r=this.deps.providerNameForModel(this.currentModel);if((!this.active||r!==this.active.family)&&(await this.closeActive(),this.active=this.buildInner(this.currentModel,!0),D(`\u{1F500} ProviderRouter: switched inner provider \u2192 ${this.active.family} (model=${this.currentModel})`),yield*this.driveUntilInit(!0)))break;for(this.pendingUserText=xw(n.content),this.pendingAssistantText="",this.active.input.pushUserMessage(n.content);;){let o=await this.active.iterator.next();if(o.done){this.closed=!0;break}let s=o.value;if(this.observeEvent(s),yield s,s.type==="turn.completed"){this.commitShadowTurn();break}if(s.type==="error"){this.commitShadowTurn();break}}}}finally{await this.closeActive()}}async*driveUntilInit(e){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 e||(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(e){typeof e=="string"&&e.length>0&&(this.currentModel=e,this.active&&this.deps.providerNameForModel(e)===this.active.family&&await this.active.query.setModel(e))}async setPermissionMode(e){this.currentPermissionMode=e,await this.active?.query.setPermissionMode(e)}setCwd(e){this.currentCwd=e,this.active?.query.setCwd?.(e)}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(e,n){let r=this.active;return r?r.query.rewindFiles(e,n):{canRewind:!1,error:"no active provider"}}async compact(){let e=this.active;return e?.query.compact?e.query.compact():{compacted:!1,reason:"provider does not support compaction",messagesBefore:0,messagesAfter:0}}async reloadPlugins(...e){let n=this.active?.query;if(n&&typeof n.reloadPlugins=="function")return n.reloadPlugins(...e)}async close(){this.closed=!0,await this.closeActive()}};async function nr(t,e,n){if(!t)return;if(n.kind==="blocked"){await Xe(t,{hookEvent:e,decision:"block",...n.err.reason!==void 0?{reason:n.err.reason}:{}});return}let r=n.decision;await Xe(t,{hookEvent:e,decision:r.decision,...r.reason!==void 0?{reason:r.reason}:{},...r.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(r.injectContext,"utf8")}:{}})}async function Ol(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await nr(n.traceWriter,"SessionStart",{kind:"decision",decision:r})}catch(r){throw r instanceof q&&await nr(n.traceWriter,"SessionStart",{kind:"blocked",err:r}),r}}async function Dl(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await nr(n.traceWriter,"SessionEnd",{kind:"decision",decision:r})}catch(r){if(r instanceof q&&await nr(n.traceWriter,"SessionEnd",{kind:"blocked",err:r}),r instanceof q||r instanceof se){D(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}D(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}function Tw(t){return t==="max_tokens"||t==="length"}function Fl(t){return t.maxTurnsHit?"max_turns_exceeded":t.hookBlocked?"hook_blocked":t.dispatchReason==="error"?"abort":t.abort!==null?t.abort:Tw(t.lastStopReason)?"truncated":"model_end_turn"}var Rw="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.";function Ll(t){return t==="abort"?Rw:null}import*as gt from"node:fs";import*as ht from"node:fs/promises";H();var $l=8e3,Nl=400;function rr(t,e){return t.length>e?`${t.slice(0,e)}\u2026 [truncated]`:t}function Pw(t){switch(t.type){case"message":return t.message.role!=="assistant"||!t.message.content?null:{kind:"assistant",text:rr(t.message.content,$l)};case"chunk":{let e=t.chunk;return e.type==="tool_use_detail"?{kind:"tool",toolName:e.toolName,input:rr(e.toolInput,Nl)}:e.type==="tool_result"&&e.isError===!0?{kind:"tool_error",content:rr(e.content,Nl)}:null}case"done":{let e=t.metadata?.totalCostUsd,n=t.metadata?.durationMs;return{kind:"done",...typeof e=="number"?{costUsd:e}:{},...typeof n=="number"?{durationMs:n}:{}}}case"error":return{kind:"error",message:t.error.message};case"paused":return{kind:"paused",...t.resetsAt?{resetsAt:t.resetsAt.toISOString()}:{}};case"resumed":return{kind:"resumed"};default:return null}}var or=class{sessionId;ledgerPath;stream=null;errored=!1;closed=!1;streamReady=!1;pendingLines=[];readyPromise=null;readyResolve=null;constructor(e){if(this.sessionId=e,!Ct(e)){this.errored=!0,this.ledgerPath="";return}this.ledgerPath=wn(e);try{gt.mkdirSync(bn(e),{recursive:!0})}catch(n){process.stderr.write(`[afk] session-ledger: mkdir failed for ${e}: ${String(n)}
|
|
1317
1317
|
`),this.errored=!0}}get active(){return!this.errored&&!this.closed}record(e){if(this.errored||this.closed)return;let n={v:1,ts:Date.now(),...e},r=JSON.stringify(n)+`
|
|
1318
1318
|
`;if(!this.stream){this.pendingLines.push(r),this._openStream();return}if(!this.streamReady){this.pendingLines.push(r);return}this._writeLine(r)}recordEvent(e){let n=Pw(e);n&&this.record(n)}recordUser(e){this.record({kind:"user",text:rr(e,$l)})}_openStream(){if(!this.stream){this.readyPromise=new Promise(e=>{this.readyResolve=e});try{let e=gt.createWriteStream(this.ledgerPath,{flags:"a",encoding:"utf8",mode:384});this.stream=e,e.once("open",()=>{this.streamReady=!0;for(let n of this.pendingLines)this._writeLine(n);this.pendingLines=[],this.readyResolve?.(),this.readyResolve=null}),e.once("error",n=>{process.stderr.write(`[afk] session-ledger: stream error for ${this.sessionId}: ${String(n)}
|
|
1319
1319
|
`),this.errored=!0,this.pendingLines=[],this.readyResolve?.(),this.readyResolve=null})}catch(e){process.stderr.write(`[afk] session-ledger: createWriteStream failed for ${this.sessionId}: ${String(e)}
|
|
@@ -1322,13 +1322,13 @@ ${Ko}`,A=this.readOnlyMemory?Rl:Tl,I=[E,A];I.push(rt({cwd:w,...n.sessionId!==voi
|
|
|
1322
1322
|
`),this.errored=!0}}async close(e){if(!this.closed)return this.record({kind:"closed",...e!==void 0?{reason:e}:{}}),this.closed=!0,this.readyPromise&&await this.readyPromise,new Promise(n=>{if(!this.stream){n();return}this.stream.end(()=>n())})}};function Iw(t){let e=t.trim();if(!e)return null;try{let n=JSON.parse(e);return n.v!==1||typeof n.ts!="number"||typeof n.kind!="string"?null:n}catch{return null}}async function sr(t){if(!Ct(t))return!1;try{return await ht.access(wn(t)),!0}catch{return!1}}var Cw=250;async function*Ul(t,e){if(!Ct(t))return;let n=wn(t),r=bn(t),{fromStart:o=!1,signal:s}=e??{},i=0,a="",c=!1;async function*l(){let f=null;try{f=await ht.open(n,"r");let g=await f.stat();if(g.size<=i)return;let m=g.size-i,k=Buffer.allocUnsafe(m),{bytesRead:_}=await f.read(k,0,m,i);if(_===0)return;i+=_,a+=k.toString("utf8",0,_);let b=a.split(`
|
|
1323
1323
|
`);a=b.pop()??"";for(let S of b){let w=Iw(S);if(w&&(w.kind==="closed"&&(c=!0),yield w,c))return}}catch(g){g.code!=="ENOENT"&&process.stderr.write(`[afk] session-ledger: tail read error for ${t}: ${String(g)}
|
|
1324
1324
|
`)}finally{f&&await f.close().catch(()=>{})}}if(o){if(yield*l(),c)return}else try{i=(await ht.stat(n)).size}catch{}let d=null,u=null,p=()=>new Promise(f=>{let g=setTimeout(()=>{u=null,f()},Cw);u=()=>{clearTimeout(g),u=null,f()},s?.addEventListener("abort",()=>{clearTimeout(g),u=null,f()},{once:!0})});try{d=gt.watch(r,{persistent:!1},()=>{u?.()})}catch{}try{for(;!s?.aborted&&!c&&(await p(),!s?.aborted);)yield*l()}finally{d?.close()}}F();function Bl(t,e,n){t&&(t.aborted?e.abort(t.reason):t.addEventListener("abort",()=>{e.signal.aborted||e.abort(t.reason)},{once:!0})),e.signal.addEventListener("abort",n,{once:!0})}function Hl(t,e){let n=t.permissionMode??"default",r=t.persistSession??!0,o={sessionId:t.sessionId,configuredSessionId:t.sessionId,resume:t.resume,resumeSessionAt:t.resumeSessionAt,continue:t.continue,forkSession:t.forkSession,persistSession:r},s={sessionId:t.sessionId,model:e,permissionMode:n};return{sessionIdentity:o,metadata:s}}var ir=class{initializationPromise;resolveInitialization;rejectInitialization;initializationSettled=!1;sessionMetadata;sessionIdentity;constructor(e,n){this.sessionIdentity=e,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(e){e&&(this.sessionIdentity={...this.sessionIdentity,sessionId:e},this.sessionMetadata={...this.sessionMetadata,sessionId:e})}setSessionMetadata(e){this.sessionMetadata=e(this.sessionMetadata)}resolveInitializationIfNeeded(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}resolveInitializationOnce(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}rejectInitializationOnce(e){this.initializationSettled||(this.initializationSettled=!0,this.rejectInitialization(e))}isInitializationSettled(){return this.initializationSettled}};function jl(t){try{let e=JSON.parse(t);if(!Array.isArray(e))return null;let n=e.length;if(n===0)return"no results";let r=0,o=0;for(let a of e)if(a&&typeof a=="object"){let c=a.type;c==="fact"?r++:c==="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 Kl(t){try{let e=JSON.parse(t);if(!e||typeof e!="object")return null;let n=e;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 Wl(t){try{let e=JSON.parse(t);if(!e||typeof e!="object")return null;let n=e;return typeof n.name=="string"&&n.written===!0?`wrote procedure '${n.name}'`:null}catch{return null}}function zo(t){let e=t.trim();if(e.length===0)return null;let n=e[0];if(n!=="{"&&n!=="[")return null;let r=e[e.length-1];if(n==="{"&&r!=="}"||n==="["&&r!=="]")return null;let o;try{o=JSON.parse(e)}catch{return null}return Array.isArray(o)?Gl(Mw(o)):o!==null&&typeof o=="object"?Gl(Ow(o)):null}function Mw(t){return t.length===0?"[empty array]":t.length===1?"[1 item]":`[${t.length} items]`}function Ow(t){let e=Object.keys(t);if(e.length===0)return"{empty object}";let n=e.slice(0,4),r=e.length>4?", \u2026":"";return`{${n.join(", ")}${r}}`}function Gl(t){return t.length<=80?t:t.slice(0,79)+"\u2026"}var Dw=new Map([["memory_search",jl],["memory_update",Kl],["procedure_write",Wl],["bash",zo],["Bash",zo]]);function ql(t,e){if(!t)return null;let n=Dw.get(t);if(!n)return null;try{let r=n(e);if(r===null)return null;let o=Tn(r);return o.length>0?o:null}catch{return null}}function Fw(t){let e=/Output too large \((\d+(?:\.\d+)?)\s*(B|KB|MB|GB)\)\.\s*Full output saved to:\s*(\/[^\n]+)/,n=t.match(e);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 c=r;return i%1===0&&(c=String(Math.floor(i))),c+=o,{sizeLabel:c,sizeBytes:Math.round(a),absolutePath:s.trim()}}function Lw(t){if(t<1024)return`${t}B`;let e=t/1024;if(e<1024)return e%1===0?`${Math.floor(e)}KB`:`${e.toFixed(1)}KB`;let n=e/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 Nw(t){let e=Buffer.byteLength(t,"utf8"),n=Lw(e),r=t.split(`
|
|
1325
|
-
`);if(r.length<=1&&t.length<=80)return{content:t,truncated:!1,sizeBytes:e,sizeLabel:n};if(r.length<=1)return t.length<=80?{content:t,truncated:!1,sizeBytes:e,sizeLabel:n}:{content:t.substring(0,80)+"\u2026",truncated:!0,sizeBytes:e,sizeLabel:n};if(t.length<=80)return{content:t,truncated:!1,sizeBytes:e,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:e,sizeLabel:n}}function $w(t,e){let n={...t.raw??{}};return t.inputTokens!==void 0&&(n.input_tokens=t.inputTokens),t.outputTokens!==void 0&&(n.output_tokens=t.outputTokens),t.cachedInputTokens!==void 0&&(n.cache_read_input_tokens=t.cachedInputTokens),t.cacheCreationTokens!==void 0&&(n.cache_creation_input_tokens=t.cacheCreationTokens),t.totalTokens!==void 0&&(n.total_tokens=t.totalTokens),t.contextWindowTokens!==void 0&&(n.context_window_tokens=t.contextWindowTokens),{sessionId:e,stopReason:t.stopReason??void 0,resultSubtype:t.resultSubtype,durationMs:t.durationMs,durationApiMs:t.durationApiMs,totalCostUsd:t.totalCostUsd,isError:t.isError,usage:Object.keys(n).length>0?n:void 0,modelUsage:t.modelUsage,permissionDenials:t.permissionDenials,errors:t.errors}}function Uw(t){let e=t.isError===!0?null:ql(t.toolName,t.content),n=e!==null?{display:e}:{},r=Fw(t.content);if(r)return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:`Output persisted (${r.sizeLabel}) \u2192 ${r.absolutePath}`,isError:t.isError===!0,persistedPath:r.absolutePath,sizeBytes:r.sizeBytes,sizeLabel:r.sizeLabel,...n}};let{content:o,lineCount:s,sizeBytes:i,sizeLabel:a}=Nw(t.content);return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:o,isError:t.isError===!0,sizeBytes:i,sizeLabel:a,...t.truncated===!0&&{truncated:!0},...s!==void 0&&{lineCount:s},...n}}}function Jo(t,e){switch(t.type){case"session.init":{let n=t.info;return e.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}:{}})),e.updateSessionIdentity(n.sessionId),e.resolveInitialization(),null}case"session.status":return e.setSessionMetadata(n=>({...n,sessionId:t.sessionId,...t.permissionMode!==void 0?{permissionMode:t.permissionMode}:{permissionMode:n.permissionMode},...t.status!==void 0?{status:t.status}:{}})),null;case"delta.text":return{type:"chunk",chunk:{type:"content",content:t.text,metadata:{eventType:"delta",deltaType:"text_delta"}}};case"delta.reasoning":return{type:"chunk",chunk:{type:"thinking",content:t.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}};case"assistant.message":if(t.sessionId&&e.updateSessionIdentity(t.sessionId),t.text){let n={role:"assistant",content:t.text,timestamp:new Date};return e.conversationHistory.push(n),{type:"message",message:n}}return null;case"tool.use.start":return{type:"chunk",chunk:{type:"tool_use_detail",toolUseId:t.toolUseId,toolName:t.toolName,toolInput:t.toolInput}};case"tool.use":return{type:"chunk",chunk:{type:"tool_use",content:t.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:t.toolUseIds}}};case"tool.output":return Uw(t);case"tool.diff":return{type:"chunk",chunk:{type:"tool_diff",toolUseId:t.toolUseId,diff:t.diff}};case"progress":return{type:"progress",progress:{taskId:t.progress.taskId,description:t.progress.description,...t.progress.summary!==void 0?{summary:t.progress.summary}:{},...t.progress.lastToolName!==void 0?{lastToolName:t.progress.lastToolName}:{},totalTokens:t.progress.totalTokens,toolUses:t.progress.toolUses,durationMs:t.progress.durationMs}};case"suggestion":return{type:"suggestion",suggestion:t.suggestion};case"turn.completed":{let n=$w(t.usage,t.sessionId??e.getSessionMetadata().sessionId);e.setLastResponseMetadata(n);for(let r=e.conversationHistory.length-1;r>=0;r--){let o=e.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}if(e.maxBudgetUsd!==void 0&&e.abortBudget!==void 0&&typeof n.totalCostUsd=="number"&&(e._runningCostUsd=(e._runningCostUsd??0)+n.totalCostUsd,e._runningCostUsd>=e.maxBudgetUsd)){ls(e.traceWriter,{kind:"monetary",runningCostUsd:e._runningCostUsd,maxBudgetUsd:e.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new Ye(e._runningCostUsd,e.maxBudgetUsd);return e.abortBudget(r.message),{type:"error",error:r}}return{type:"done",metadata:n}}case"error":return{type:"error",error:t.error};case"paused":return{type:"paused",reason:t.reason,...t.resetsAt!==void 0?{resetsAt:t.resetsAt}:{},...t.accountId!==void 0?{accountId:t.accountId}:{},...t.autoResume!==void 0?{autoResume:t.autoResume}:{}};case"resumed":return{type:"resumed",hotSwapped:t.hotSwapped,...t.accountId!==void 0?{accountId:t.accountId}:{}};case"stream.retry":return{type:"stream_retry"};default:return null}}var Je=class{config;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;sessionStartedAt=Date.now();subagentCompletedCount=0;subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};subagentRunningCostUsd=0;ledger=null;ledgerInitAttempted=!1;constructor(e){this.config=e,this.abortController=new AbortController,this._hookRegistry=e.hookRegistry,Bl(e.abortSignal,this.abortController,()=>{this.onAbort()}),Ue(e.traceWriter,{phase:"session_init_start"}),this.initSdkLifecycle()}initSdkLifecycle(){this.config.models&&xr(this.config.models),er(this.config);let e=se(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=Hl(this.config,e);this.stateManager=new ir(n,r),this.inputStream=new mt(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)D(`\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{D("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>Zn(a);this.providerQuery=new tr({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>V(a),resolveApiKey:a=>st(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.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 Ol(this._hookRegistry,{event:"SessionStart",sessionId:this.sessionId},{signal:this.abortController.signal,...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}});;){let e=await this.providerIterator.next();if(e.done){this.stateManager.resolveInitializationIfNeeded();return}let n=e.value,r=Jo(n,this.buildTransformDeps());if(n.type==="session.init"){await Ue(this.config.traceWriter,{phase:"session_init_done",durationMs:Date.now()-this.sessionStartedAt});return}if(r&&r.type==="error")return}}catch(e){let n=e instanceof Error?e:new Error(String(e));n instanceof q&&(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:e=>this.stateManager.setSessionMetadata(e),updateSessionIdentity:e=>this.stateManager.updateSessionIdentity(e),resolveInitialization:()=>this.stateManager.resolveInitializationOnce(),setLastResponseMetadata:e=>{this.lastResponseMetadata=e,typeof e.totalCostUsd=="number"&&Number.isFinite(e.totalCostUsd)&&(this.sessionRunningCostUsd+=e.totalCostUsd);let n=e.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 e.stopReason=="string"&&(this.lastStopReason=e.stopReason)},maxBudgetUsd:this.config.maxBudgetUsd,abortBudget:e=>{this.abortController.signal.aborted||this.abortController.abort(e)},...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(e){if(e==="closed"||e.startsWith("Budget ")||e.includes("timed out"))throw new Error(`AgentSession.abort: reserved reason "${e}" (use a caller-specific string like 'sigint')`);this.abortController.signal.aborted||this.abortController.abort(e)}async sendMessage(e,n={}){this.assertCanSend();let r=this.config.timeoutMs??Rt,o=async()=>{let s=null,i="";this.currentState=n.stream?"streaming":"processing";for await(let a of this.sendMessageStreamInternal(e)){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 Pt(o(),r,{controller:this.abortController,label:this.sessionId??"session"})}finally{this.currentState==="processing"&&(this.currentState="idle")}}async*sendMessageStream(e){this.assertCanSend(),this.currentState="streaming";try{yield*this.sendMessageStreamInternal(e)}finally{this.currentState==="streaming"&&(this.currentState="idle")}}async*sendMessageStreamInternal(e){this.initPromise&&await this.initPromise;let n=typeof e=="string"?e:this.summarizeContentBlocks(e),r={role:"user",content:n,timestamp:new Date};this.conversationHistory.push(r),this.inputStream.pushUserMessage(e),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=Jo(i,o);if(a&&(a.type==="done"&&this.turnCount++,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)||y.AFK_SESSION_LEDGER_DISABLED==="1")return;let e=this.sessionId;if(!e)return;let n=new or(e);if(!n.active)return;this.ledger=n;let r=this.getSessionMetadata();n.record({kind:"meta",sessionId:e,model:r.model??String(this.config.model),...r.cwd!==void 0?{cwd:r.cwd}:{}})}sealLedger(e){let n=this.ledger;return n?(this.ledger=null,this.ledgerInitAttempted=!1,n.close(e)):Promise.resolve()}summarizeContentBlocks(e){let n=[],r=0;for(let s of e)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 oe("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(e=>setTimeout(e,pn))]).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(e){throw this.currentState="closed",new Error(`Session reset failed during lifecycle rebuild: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async onAbort(){this.sealLedger("abort");try{await this.providerQuery.interrupt()}catch{}}async setModel(e){let n=se(e);typeof e=="string"&&e.length>0&&await this.providerQuery.setModel(e),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(e){await this.providerQuery.setPermissionMode(e),this.stateManager.setSessionMetadata(n=>({...n,permissionMode:e}))}setCwd(e){this.config={...this.config,cwd:e},this.providerQuery.setCwd?.(e)}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(e,n){return this.providerQuery.rewindFiles(e,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 e=this.providerQuery.compact?.bind(this.providerQuery);if(!e)return{compacted:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0};this.currentState="compacting";try{return await e()}finally{this.currentState="idle"}}getLastResponseMetadata(){return this.lastResponseMetadata}getOutputStream(){throw new Error("getOutputStream() is not supported \u2014 use sendMessageStream() instead")}getInputStreamRef(){return{pushUserMessage:e=>this.inputStream.pushUserMessage(e)}}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(e=>setTimeout(e,pn))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(e){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await this.emitClosure(e).catch(()=>{}),await this.sealTraceWriter(e).catch(()=>{}),await Dl(this._hookRegistry,{event:"SessionEnd",sessionId:this.sessionId,reason:e,parentSessionId:this.config.parentSessionId},this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}))}async emitClosure(e){let n=this.config.traceWriter;if(!n)return;let r=this.deriveClosureReason(e),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=Ll(r);await ps(n,{reason:r,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,finalTokens:o,...this.lastStopReason!==void 0?{lastStopReason:this.lastStopReason}:{},...s!==null?{guidance:s}:{}})}deriveClosureReason(e){let n=null,r=this.abortController.signal;if(r.aborted&&r.reason!=="closed"){let o=r.reason;o instanceof Ye?n="budget_exceeded":o instanceof Te?n="timeout":typeof o=="string"&&o.startsWith("Budget ")?n="budget_exceeded":typeof o=="string"&&o.includes("timed out")?n="timeout":n="abort"}return Fl({dispatchReason:e,maxTurnsHit:this.maxTurnsHit,hookBlocked:this.hookBlocked,abort:n,lastStopReason:this.lastStopReason})}async sealTraceWriter(e){let n=this.config.traceWriter;if(!n)return;let r=this.deriveSealStatus(e),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,c=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}:{},...c!==void 0?{subagentCostUsd:c}:{}})}recordSubagentCompletion(e,n){if(this.subagentCompletedCount++,e){let r=(o,s)=>{typeof o=="number"&&Number.isFinite(o)&&o>0&&(this.subagentRunningTokens[s]+=o)};r(e.inputTokens,"input"),r(e.outputTokens,"output"),r(e.cacheReadTokens,"cacheRead"),r(e.cacheCreationTokens,"cacheCreation")}typeof n=="number"&&Number.isFinite(n)&&n>0&&(this.subagentRunningCostUsd+=n)}deriveSealStatus(e){if(e==="error")return"failed";let n=this.abortController.signal;return n.aborted&&n.reason!=="closed"?"cancelled":"succeeded"}assertCanSend(){if(this.currentState==="closed")throw new Error("Cannot send message: session is closed");if(this.abortController.signal.aborted)throw new oe("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`)}};function Bw(t){let e=new Map,n=t.defaultMode??"ask";if(t.tools)for(let[r,o]of Object.entries(t.tools))typeof o=="string"?e.set(r,{mode:o}):e.set(r,{mode:o.mode,reason:o.reason});if(t.list)for(let r of t.list)e.set(r.tool,{mode:r.mode,reason:r.reason});return{defaultMode:n,byTool:e}}function Hw(t){return t.behavior==="allow"?{behavior:"allow"}:{behavior:"deny",message:t.reason??"Tool denied by permission rules"}}function zl(t){let{defaultMode:e,byTool:n}=Bw(t.rules);return async(r,o)=>{let s={toolName:r,input:o},i=n.get(r),a=i?.mode??e,c=i?.reason,l;return a==="ask"&&t.onAsk?l=await t.onAsk(s):a==="deny"?l={behavior:"deny",reason:c}:l={behavior:"allow"},t.onDecision?.(s,l),Hw(l)}}import{Telegraf as HS}from"telegraf";function ar(t){let e=t.toLowerCase().replace(/[`*_~]/g," ").replace(/[^\w\s-]/g," ").replace(/[\s_]+/g," ").trim();return e?e.split(" ").filter(Boolean).slice(0,6).join("-").slice(0,48).replace(/-+$/g,""):""}function Jl(t){return{totalTurns:0,totalCostUsd:0,totalTokens:0,totalDurationMs:0,sessionStartTime:Date.now(),turnCosts:[],turnTokens:[],turns:[],model:t,planMode:!1}}function Vl(t,e,n,r,o){let s=r?.totalCostUsd??0,i=r?.durationMs??0,a=Number(r?.usage?.input_tokens??0),c=Number(r?.usage?.output_tokens??0),l=a,d=c,u=Number(r?.usage?.cache_read_input_tokens??0)+Number(r?.usage?.cache_creation_input_tokens??0),p=r?.usage?.iterations;if(Array.isArray(p)&&p.length>0){let _=p[p.length-1];if(_&&typeof _=="object"){let b=_;l=Number(b.input_tokens??0),d=Number(b.output_tokens??0),u=Number(b.cache_read_input_tokens??0)+Number(b.cache_creation_input_tokens??0)}}t.totalTurns+=1,t.totalCostUsd+=s,t.totalDurationMs+=i,t.totalTokens+=a+c,t.turnCosts.push(s);let f=Number(r?.usage?.context_window_tokens??NaN),g=Array.isArray(p)&&p.length>0,m=Number.isFinite(f)?f:g?l+d+u:void 0;if(t.turnTokens.push({input:l,output:d,cache:u,...m!==void 0?{footprint:m}:{}}),r?.sessionId&&!t.sessionId&&(t.sessionId=String(r.sessionId)),!t.name){let _=ar(e);_&&(t.name=_)}let k={user:e,assistant:n,timestamp:Date.now(),costUsd:s,durationMs:i,inputTokens:a,outputTokens:c,...o&&o.length>0?{toolEvents:o}:{}};return t.turns.push(k),k}import{readFileSync as Kw,writeFileSync as Ww,existsSync as cr,mkdirSync as Gw,readdirSync as qw,statSync as zw,realpathSync as Yl}from"fs";import{join as Ql,basename as Zl,resolve as Xl,sep as Jw}from"path";H();function en(){return Js(),et()}function Vw(t){return Ql(en(),`${t}.json`)}function Vo(t,{write:e=!1}={}){let n=t.includes("/")?t:Vw(t),r,o;if(!e&&cr(n)?(r=Yl(n),o=Yl(en())):(r=Xl(n),o=Xl(en())),!r.startsWith(o+Jw)&&r!==o)throw new Error(`Session path escapes sessions directory: ${t}`);return r}function Yo(t,e){let n=en();cr(n)||Gw(n,{recursive:!0});let r=e??t.sessionId??`session-${Date.now()}`,o={sessionId:t.sessionId,...t.name?{name:t.name}:{},...t.source?{source:t.source}:{},...t.telegramChatId!==void 0?{telegramChatId:t.telegramChatId}:{},model:t.model,startedAt:t.sessionStartTime,savedAt:Date.now(),totalTurns:t.totalTurns,totalCostUsd:t.totalCostUsd,totalTokens:t.totalTokens,totalDurationMs:t.totalDurationMs,turns:t.turns},s=Vo(r,{write:!0});return Ww(s,JSON.stringify(o,null,2)),s}function yt(t){let e;try{e=Vo(t)}catch{return}if(cr(e))try{let n=Kw(e,"utf-8");return JSON.parse(n)}catch{return}}function ed(t){let e;try{e=Vo(t)}catch{return}let n=yt(e);if(n)return{path:e,id:Zl(e,".json"),data:n};let r=Xo();for(let s of r){if(s.id!==t&&s.sessionId!==t&&s.name!==t)continue;let i=yt(s.path);if(i)return{path:s.path,id:s.id,data:i}}if(t.length>=3){let s=r.filter(i=>i.name!==void 0&&i.name.startsWith(t));if(s.length===1){let i=s[0];if(i){let a=yt(i.path);if(a)return{path:i.path,id:i.id,data:a}}}}}function Xo(){let t=en();if(!cr(t))return[];let e=[];for(let n of qw(t)){if(!n.endsWith(".json"))continue;let r=Ql(t,n);try{if(!zw(r).isFile())continue;let s=yt(r);if(!s||typeof s.savedAt!="number"||typeof s.model!="string")continue;e.push({path:r,id:Zl(n,".json"),sessionId:s.sessionId,name:s.name,source:s.source,model:s.model,startedAt:s.startedAt,savedAt:s.savedAt,totalTurns:s.totalTurns,totalCostUsd:s.totalCostUsd})}catch{}}return e.sort((n,r)=>r.savedAt-n.savedAt),e}import{promises as tn}from"fs";import{join as td}from"path";var bt=class{sessions=new Map;pendingSessions=new Map;sessionData=new Map;sessionStats=new Map;autosaveFailureLogged=new Set;options;constructor(e){this.options={dataDir:e.dataDir||"./data/telegram-sessions",defaultModel:e.defaultModel||"sonnet",apiKey:e.apiKey,settingSources:e.settingSources,thinking:e.thinking,effort:e.effort,botCwd:e.botCwd,createSession:e.createSession}}getSessionIfExists(e){return this.sessions.get(e)}async getSession(e){let n=this.sessions.get(e);if(n)return this._touchActivity(e),n;let r=this.pendingSessions.get(e);if(r)try{return await r}finally{this._touchActivity(e)}let o=this.sessionData.get(e)??{chatId:e,model:this.options.defaultModel,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()},s=(async()=>{let i={model:o.model,apiKey:this.options.apiKey};this.options.settingSources?.length&&(i.settingSources=this.options.settingSources),this.options.thinking!==void 0&&(i.thinking=this.options.thinking),this.options.effort!==void 0&&(i.effort=this.options.effort);let a=o.cwd??this.options.botCwd;a!==void 0&&a.length>0&&(i.cwd=a);let c=await this.options.createSession(bo(i));return this.sessions.set(e,c),this.sessionData.set(e,o),c})();this.pendingSessions.set(e,s);try{let i=await s;return this._touchActivity(e),i}finally{this.pendingSessions.delete(e)}}_touchActivity(e){let n=this.sessionData.get(e);n&&(n.lastActivity=new Date().toISOString())}recordTelegramTurn(e,n,r,o){let s=this._getOrCreateStats(e),i=this.sessions.get(e);!s.sessionId&&i?.sessionId&&(s.sessionId=i.sessionId),Vl(s,n,r,o),!s.sessionId&&i?.sessionId&&(s.sessionId=i.sessionId);let a=this.sessionData.get(e);if(a&&s.sessionId&&(a.sessionId=s.sessionId),s.sessionId)try{Yo(s)}catch(c){this.autosaveFailureLogged.has(e)||(this.autosaveFailureLogged.add(e),console.error(`[session-manager] autosave failed for chat ${e} \u2014 conversation may not be resumable:`,c))}}_hydrateStatsFromStore(e){if(this.sessionStats.has(e))return;let n=this.sessionData.get(e)?.sessionId;if(!n)return;let r=yt(n);if(!r||r.source!=="telegram"||r.telegramChatId!==e)return;let o={sessionId:r.sessionId,name:r.name,model:r.model,source:r.source,telegramChatId:r.telegramChatId,sessionStartTime:r.startedAt,totalTurns:r.totalTurns,totalCostUsd:r.totalCostUsd,totalTokens:r.totalTokens,totalDurationMs:r.totalDurationMs,turns:r.turns,turnCosts:[],turnTokens:[],planMode:!1},s=this.sessionData.get(e)?.cwd;s!==void 0&&(o.cwd=s),this.sessionStats.set(e,o)}getSessionName(e){return this._hydrateStatsFromStore(e),this.sessionStats.get(e)?.name}setSessionName(e,n){let r=this._getOrCreateStats(e);r.name=n;let o=this.sessions.get(e);if(!r.sessionId&&o?.sessionId&&(r.sessionId=o.sessionId),r.totalTurns>0&&r.sessionId){let s=this.sessionData.get(e);return s&&(s.sessionId=r.sessionId),Yo(r),{persisted:!0}}return{persisted:!1}}_getOrCreateStats(e){this._hydrateStatsFromStore(e);let n=this.sessionStats.get(e);if(!n){n=Jl(this.getModel(e)),n.source="telegram",n.telegramChatId=e;let r=this.getCwd(e);r&&(n.cwd=r),this.sessionStats.set(e,n)}return n}_resetStats(e){this.sessionStats.delete(e),this.autosaveFailureLogged.delete(e);let n=this.sessionData.get(e);n&&delete n.sessionId}async resetSession(e){let n=this.sessions.get(e);n&&(await n.close(),this.sessions.delete(e)),this._resetStats(e);let r=this.sessionData.get(e);r&&(r.lastActivity=new Date().toISOString())}async switchModel(e,n){let r=this.sessions.get(e);r&&(await r.close(),this.sessions.delete(e)),this._resetStats(e);let o=this.sessionData.get(e);o?(o.model=n,o.lastActivity=new Date().toISOString()):(o={chatId:e,model:n,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()},this.sessionData.set(e,o))}getModel(e){return this.sessionData.get(e)?.model||this.options.defaultModel}async setCwd(e,n){let r=this.sessions.get(e);r&&(await r.close(),this.sessions.delete(e)),this._resetStats(e);let o=this.sessionData.get(e);o?(o.cwd=n,o.lastActivity=new Date().toISOString()):(o={chatId:e,model:this.options.defaultModel,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString(),cwd:n},this.sessionData.set(e,o))}getCwd(e){return this.sessionData.get(e)?.cwd??this.options.botCwd}async loadSessions(){try{await tn.mkdir(this.options.dataDir,{recursive:!0});let e=await tn.readdir(this.options.dataDir);for(let n of e)if(n.endsWith(".json")){let r=td(this.options.dataDir,n),o=await tn.readFile(r,"utf-8"),s=JSON.parse(o);this.sessionData.set(s.chatId,s)}}catch(e){e.code!=="ENOENT"&&console.error("Failed to load sessions:",e)}}async saveSessions(){try{await tn.mkdir(this.options.dataDir,{recursive:!0});for(let[e,n]of this.sessionData.entries()){let r=td(this.options.dataDir,`${e}.json`);await tn.writeFile(r,JSON.stringify(n,null,2))}}catch(e){console.error("Failed to save sessions:",e)}}async closeAll(){await this.saveSessions();let e=Array.from(this.sessions.values()).map(n=>n.close().catch(r=>console.error("Error closing session:",r)));await Promise.all(e),this.sessions.clear()}getSessionCount(){return this.sessions.size}getChatCount(){return this.sessionData.size}};async function Qo(t){await t.reply(Qr())}async function Zo(t,e){let n=t.chat?.id,r,o=n?e.getSessionIfExists(n):void 0;if(o)try{await Promise.race([o.waitForInitialization(),new Promise((i,a)=>setTimeout(()=>a(new Error("timeout")),2e3))]);let s=o.getSessionMetadata();s.slashCommands?.length&&(r=s.slashCommands)}catch{}await t.reply(Di(r))}import{Markup as od}from"telegraf";import{promises as Xw}from"fs";import{homedir as sd}from"os";import{isAbsolute as Qw,resolve as es}from"path";var Yw=/^[A-Za-z0-9_@%+=:,./-]+$/;function nd(t){return Yw.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function rd(t,e){let n=["afk","interactive"];return typeof e=="string"&&e.length>0&&n.push("--model",nd(e)),n.push("--resume",nd(t)),n.join(" ")}var nn=["small","medium","large","opus","opus_1m","sonnet","sonnet_1m","haiku","fable"];async function ts(t,e,n,r){let o=t.chat?.id;if(!o){await t.reply(N("Could not identify chat"));return}try{await e.resetSession(o),n.delete(o),await t.reply(Ht())}catch(s){r("Clear error:",s),await t.reply(N(s))}}async function id(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}try{let o=await e.getSession(r);await t.sendChatAction("typing").catch(()=>{});let s=await o.compact();s.compacted?await t.reply(jt({before:s.messagesBefore,after:s.messagesAfter,...s.tokensSavedEstimate!==void 0?{tokensSavedEstimate:s.tokensSavedEstimate}:{}})):await t.reply(Kt(s.reason??"unknown"))}catch(o){n("Compact error:",o),await t.reply(N(o))}}async function ns(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1);if(s.length===0){let u=e.getModel(r),p=nn.map(f=>[od.button.callback(f,`afk:m:${f}`)]);await t.reply(`Current model: <b>${We(u.toUpperCase())}</b>
|
|
1325
|
+
`);if(r.length<=1&&t.length<=80)return{content:t,truncated:!1,sizeBytes:e,sizeLabel:n};if(r.length<=1)return t.length<=80?{content:t,truncated:!1,sizeBytes:e,sizeLabel:n}:{content:t.substring(0,80)+"\u2026",truncated:!0,sizeBytes:e,sizeLabel:n};if(t.length<=80)return{content:t,truncated:!1,sizeBytes:e,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:e,sizeLabel:n}}function $w(t,e){let n={...t.raw??{}};return t.inputTokens!==void 0&&(n.input_tokens=t.inputTokens),t.outputTokens!==void 0&&(n.output_tokens=t.outputTokens),t.cachedInputTokens!==void 0&&(n.cache_read_input_tokens=t.cachedInputTokens),t.cacheCreationTokens!==void 0&&(n.cache_creation_input_tokens=t.cacheCreationTokens),t.totalTokens!==void 0&&(n.total_tokens=t.totalTokens),t.contextWindowTokens!==void 0&&(n.context_window_tokens=t.contextWindowTokens),{sessionId:e,stopReason:t.stopReason??void 0,resultSubtype:t.resultSubtype,durationMs:t.durationMs,durationApiMs:t.durationApiMs,totalCostUsd:t.totalCostUsd,isError:t.isError,usage:Object.keys(n).length>0?n:void 0,modelUsage:t.modelUsage,permissionDenials:t.permissionDenials,errors:t.errors}}function Uw(t){let e=t.isError===!0?null:ql(t.toolName,t.content),n=e!==null?{display:e}:{},r=Fw(t.content);if(r)return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:`Output persisted (${r.sizeLabel}) \u2192 ${r.absolutePath}`,isError:t.isError===!0,persistedPath:r.absolutePath,sizeBytes:r.sizeBytes,sizeLabel:r.sizeLabel,...n}};let{content:o,lineCount:s,sizeBytes:i,sizeLabel:a}=Nw(t.content);return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:o,isError:t.isError===!0,sizeBytes:i,sizeLabel:a,...t.truncated===!0&&{truncated:!0},...s!==void 0&&{lineCount:s},...n}}}function Jo(t,e){switch(t.type){case"session.init":{let n=t.info;return e.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}:{}})),e.updateSessionIdentity(n.sessionId),e.resolveInitialization(),null}case"session.status":return e.setSessionMetadata(n=>({...n,sessionId:t.sessionId,...t.permissionMode!==void 0?{permissionMode:t.permissionMode}:{permissionMode:n.permissionMode},...t.status!==void 0?{status:t.status}:{}})),null;case"delta.text":return{type:"chunk",chunk:{type:"content",content:t.text,metadata:{eventType:"delta",deltaType:"text_delta"}}};case"delta.reasoning":return{type:"chunk",chunk:{type:"thinking",content:t.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}};case"assistant.message":if(t.sessionId&&e.updateSessionIdentity(t.sessionId),t.text){let n={role:"assistant",content:t.text,timestamp:new Date};return e.conversationHistory.push(n),{type:"message",message:n}}return null;case"tool.use.start":return{type:"chunk",chunk:{type:"tool_use_detail",toolUseId:t.toolUseId,toolName:t.toolName,toolInput:t.toolInput}};case"tool.use":return{type:"chunk",chunk:{type:"tool_use",content:t.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:t.toolUseIds}}};case"tool.output":return Uw(t);case"tool.diff":return{type:"chunk",chunk:{type:"tool_diff",toolUseId:t.toolUseId,diff:t.diff}};case"progress":return{type:"progress",progress:{taskId:t.progress.taskId,description:t.progress.description,...t.progress.summary!==void 0?{summary:t.progress.summary}:{},...t.progress.lastToolName!==void 0?{lastToolName:t.progress.lastToolName}:{},totalTokens:t.progress.totalTokens,toolUses:t.progress.toolUses,durationMs:t.progress.durationMs}};case"suggestion":return{type:"suggestion",suggestion:t.suggestion};case"turn.completed":{let n=$w(t.usage,t.sessionId??e.getSessionMetadata().sessionId);e.setLastResponseMetadata(n);for(let r=e.conversationHistory.length-1;r>=0;r--){let o=e.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}if(e.maxBudgetUsd!==void 0&&e.abortBudget!==void 0&&typeof n.totalCostUsd=="number"&&(e._runningCostUsd=(e._runningCostUsd??0)+n.totalCostUsd,e._runningCostUsd>=e.maxBudgetUsd)){ls(e.traceWriter,{kind:"monetary",runningCostUsd:e._runningCostUsd,maxBudgetUsd:e.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new Ye(e._runningCostUsd,e.maxBudgetUsd);return e.abortBudget(r.message),{type:"error",error:r}}return{type:"done",metadata:n}}case"error":return{type:"error",error:t.error};case"paused":return{type:"paused",reason:t.reason,...t.resetsAt!==void 0?{resetsAt:t.resetsAt}:{},...t.accountId!==void 0?{accountId:t.accountId}:{},...t.autoResume!==void 0?{autoResume:t.autoResume}:{}};case"resumed":return{type:"resumed",hotSwapped:t.hotSwapped,...t.accountId!==void 0?{accountId:t.accountId}:{}};case"stream.retry":return{type:"stream_retry"};default:return null}}var Je=class{config;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;sessionStartedAt=Date.now();subagentCompletedCount=0;subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};subagentRunningCostUsd=0;ledger=null;ledgerInitAttempted=!1;constructor(e){this.config=e,this.abortController=new AbortController,this._hookRegistry=e.hookRegistry,Bl(e.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(e.model);Ue(e.traceWriter,{phase:"session_init_start",model:n,resolvedModel:te(e.model)??n}),this.initSdkLifecycle()}initSdkLifecycle(){this.config.models&&xr(this.config.models),er(this.config);let e=te(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=Hl(this.config,e);this.stateManager=new ir(n,r),this.inputStream=new mt(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)D(`\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{D("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>Zn(a);this.providerQuery=new tr({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>V(a),resolveApiKey:a=>st(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.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 Ol(this._hookRegistry,{event:"SessionStart",sessionId:this.sessionId},{signal:this.abortController.signal,...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}});;){let e=await this.providerIterator.next();if(e.done){this.stateManager.resolveInitializationIfNeeded();return}let n=e.value,r=Jo(n,this.buildTransformDeps());if(n.type==="session.init"){await Ue(this.config.traceWriter,{phase:"session_init_done",durationMs:Date.now()-this.sessionStartedAt});return}if(r&&r.type==="error")return}}catch(e){let n=e instanceof Error?e:new Error(String(e));n instanceof q&&(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:e=>this.stateManager.setSessionMetadata(e),updateSessionIdentity:e=>this.stateManager.updateSessionIdentity(e),resolveInitialization:()=>this.stateManager.resolveInitializationOnce(),setLastResponseMetadata:e=>{this.lastResponseMetadata=e,typeof e.totalCostUsd=="number"&&Number.isFinite(e.totalCostUsd)&&(this.sessionRunningCostUsd+=e.totalCostUsd);let n=e.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 e.stopReason=="string"&&(this.lastStopReason=e.stopReason)},maxBudgetUsd:this.config.maxBudgetUsd,abortBudget:e=>{this.abortController.signal.aborted||this.abortController.abort(e)},...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(e){if(e==="closed"||e.startsWith("Budget ")||e.includes("timed out"))throw new Error(`AgentSession.abort: reserved reason "${e}" (use a caller-specific string like 'sigint')`);this.abortController.signal.aborted||this.abortController.abort(e)}async sendMessage(e,n={}){this.assertCanSend();let r=this.config.timeoutMs??Rt,o=async()=>{let s=null,i="";this.currentState=n.stream?"streaming":"processing";for await(let a of this.sendMessageStreamInternal(e)){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 Pt(o(),r,{controller:this.abortController,label:this.sessionId??"session"})}finally{this.currentState==="processing"&&(this.currentState="idle")}}async*sendMessageStream(e){this.assertCanSend(),this.currentState="streaming";try{yield*this.sendMessageStreamInternal(e)}finally{this.currentState==="streaming"&&(this.currentState="idle")}}async*sendMessageStreamInternal(e){this.initPromise&&await this.initPromise;let n=typeof e=="string"?e:this.summarizeContentBlocks(e),r={role:"user",content:n,timestamp:new Date};this.conversationHistory.push(r),this.inputStream.pushUserMessage(e),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=Jo(i,o);if(a&&(a.type==="done"&&this.turnCount++,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)||y.AFK_SESSION_LEDGER_DISABLED==="1")return;let e=this.sessionId;if(!e)return;let n=new or(e);if(!n.active)return;this.ledger=n;let r=this.getSessionMetadata();n.record({kind:"meta",sessionId:e,model:r.model??String(this.config.model),...r.cwd!==void 0?{cwd:r.cwd}:{}})}sealLedger(e){let n=this.ledger;return n?(this.ledger=null,this.ledgerInitAttempted=!1,n.close(e)):Promise.resolve()}summarizeContentBlocks(e){let n=[],r=0;for(let s of e)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 se("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(e=>setTimeout(e,pn))]).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(e){throw this.currentState="closed",new Error(`Session reset failed during lifecycle rebuild: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async onAbort(){this.sealLedger("abort");try{await this.providerQuery.interrupt()}catch{}}async setModel(e){let n=te(e);typeof e=="string"&&e.length>0&&await this.providerQuery.setModel(e),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(e){await this.providerQuery.setPermissionMode(e),this.stateManager.setSessionMetadata(n=>({...n,permissionMode:e}))}setCwd(e){this.config={...this.config,cwd:e},this.providerQuery.setCwd?.(e)}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(e,n){return this.providerQuery.rewindFiles(e,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 e=this.providerQuery.compact?.bind(this.providerQuery);if(!e)return{compacted:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0};this.currentState="compacting";try{return await e()}finally{this.currentState="idle"}}getLastResponseMetadata(){return this.lastResponseMetadata}getOutputStream(){throw new Error("getOutputStream() is not supported \u2014 use sendMessageStream() instead")}getInputStreamRef(){return{pushUserMessage:e=>this.inputStream.pushUserMessage(e)}}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(e=>setTimeout(e,pn))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(e){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await this.emitClosure(e).catch(()=>{}),await this.sealTraceWriter(e).catch(()=>{}),await Dl(this._hookRegistry,{event:"SessionEnd",sessionId:this.sessionId,reason:e,parentSessionId:this.config.parentSessionId},this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}))}async emitClosure(e){let n=this.config.traceWriter;if(!n)return;let r=this.deriveClosureReason(e),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=Ll(r);await ps(n,{reason:r,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,finalTokens:o,...this.lastStopReason!==void 0?{lastStopReason:this.lastStopReason}:{},...s!==null?{guidance:s}:{}})}deriveClosureReason(e){let n=null,r=this.abortController.signal;if(r.aborted&&r.reason!=="closed"){let o=r.reason;o instanceof Ye?n="budget_exceeded":o instanceof Te?n="timeout":typeof o=="string"&&o.startsWith("Budget ")?n="budget_exceeded":typeof o=="string"&&o.includes("timed out")?n="timeout":n="abort"}return Fl({dispatchReason:e,maxTurnsHit:this.maxTurnsHit,hookBlocked:this.hookBlocked,abort:n,lastStopReason:this.lastStopReason})}async sealTraceWriter(e){let n=this.config.traceWriter;if(!n)return;let r=this.deriveSealStatus(e),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,c=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}:{},...c!==void 0?{subagentCostUsd:c}:{}})}recordSubagentCompletion(e,n){if(this.subagentCompletedCount++,e){let r=(o,s)=>{typeof o=="number"&&Number.isFinite(o)&&o>0&&(this.subagentRunningTokens[s]+=o)};r(e.inputTokens,"input"),r(e.outputTokens,"output"),r(e.cacheReadTokens,"cacheRead"),r(e.cacheCreationTokens,"cacheCreation")}typeof n=="number"&&Number.isFinite(n)&&n>0&&(this.subagentRunningCostUsd+=n)}deriveSealStatus(e){if(e==="error")return"failed";let n=this.abortController.signal;return n.aborted&&n.reason!=="closed"?"cancelled":"succeeded"}assertCanSend(){if(this.currentState==="closed")throw new Error("Cannot send message: session is closed");if(this.abortController.signal.aborted)throw new se("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`)}};function Bw(t){let e=new Map,n=t.defaultMode??"ask";if(t.tools)for(let[r,o]of Object.entries(t.tools))typeof o=="string"?e.set(r,{mode:o}):e.set(r,{mode:o.mode,reason:o.reason});if(t.list)for(let r of t.list)e.set(r.tool,{mode:r.mode,reason:r.reason});return{defaultMode:n,byTool:e}}function Hw(t){return t.behavior==="allow"?{behavior:"allow"}:{behavior:"deny",message:t.reason??"Tool denied by permission rules"}}function zl(t){let{defaultMode:e,byTool:n}=Bw(t.rules);return async(r,o)=>{let s={toolName:r,input:o},i=n.get(r),a=i?.mode??e,c=i?.reason,l;return a==="ask"&&t.onAsk?l=await t.onAsk(s):a==="deny"?l={behavior:"deny",reason:c}:l={behavior:"allow"},t.onDecision?.(s,l),Hw(l)}}import{Telegraf as HS}from"telegraf";function ar(t){let e=t.toLowerCase().replace(/[`*_~]/g," ").replace(/[^\w\s-]/g," ").replace(/[\s_]+/g," ").trim();return e?e.split(" ").filter(Boolean).slice(0,6).join("-").slice(0,48).replace(/-+$/g,""):""}function Jl(t){return{totalTurns:0,totalCostUsd:0,totalTokens:0,totalDurationMs:0,sessionStartTime:Date.now(),turnCosts:[],turnTokens:[],turns:[],model:t,planMode:!1}}function Vl(t,e,n,r,o){let s=r?.totalCostUsd??0,i=r?.durationMs??0,a=Number(r?.usage?.input_tokens??0),c=Number(r?.usage?.output_tokens??0),l=a,d=c,u=Number(r?.usage?.cache_read_input_tokens??0)+Number(r?.usage?.cache_creation_input_tokens??0),p=r?.usage?.iterations;if(Array.isArray(p)&&p.length>0){let _=p[p.length-1];if(_&&typeof _=="object"){let b=_;l=Number(b.input_tokens??0),d=Number(b.output_tokens??0),u=Number(b.cache_read_input_tokens??0)+Number(b.cache_creation_input_tokens??0)}}t.totalTurns+=1,t.totalCostUsd+=s,t.totalDurationMs+=i,t.totalTokens+=a+c,t.turnCosts.push(s);let f=Number(r?.usage?.context_window_tokens??NaN),g=Array.isArray(p)&&p.length>0,m=Number.isFinite(f)?f:g?l+d+u:void 0;if(t.turnTokens.push({input:l,output:d,cache:u,...m!==void 0?{footprint:m}:{}}),r?.sessionId&&!t.sessionId&&(t.sessionId=String(r.sessionId)),!t.name){let _=ar(e);_&&(t.name=_)}let k={user:e,assistant:n,timestamp:Date.now(),costUsd:s,durationMs:i,inputTokens:a,outputTokens:c,...o&&o.length>0?{toolEvents:o}:{}};return t.turns.push(k),k}import{readFileSync as Kw,writeFileSync as Ww,existsSync as cr,mkdirSync as Gw,readdirSync as qw,statSync as zw,realpathSync as Yl}from"fs";import{join as Ql,basename as Zl,resolve as Xl,sep as Jw}from"path";H();function en(){return Js(),et()}function Vw(t){return Ql(en(),`${t}.json`)}function Vo(t,{write:e=!1}={}){let n=t.includes("/")?t:Vw(t),r,o;if(!e&&cr(n)?(r=Yl(n),o=Yl(en())):(r=Xl(n),o=Xl(en())),!r.startsWith(o+Jw)&&r!==o)throw new Error(`Session path escapes sessions directory: ${t}`);return r}function Yo(t,e){let n=en();cr(n)||Gw(n,{recursive:!0});let r=e??t.sessionId??`session-${Date.now()}`,o={sessionId:t.sessionId,...t.name?{name:t.name}:{},...t.source?{source:t.source}:{},...t.telegramChatId!==void 0?{telegramChatId:t.telegramChatId}:{},model:t.model,startedAt:t.sessionStartTime,savedAt:Date.now(),totalTurns:t.totalTurns,totalCostUsd:t.totalCostUsd,totalTokens:t.totalTokens,totalDurationMs:t.totalDurationMs,turns:t.turns},s=Vo(r,{write:!0});return Ww(s,JSON.stringify(o,null,2)),s}function yt(t){let e;try{e=Vo(t)}catch{return}if(cr(e))try{let n=Kw(e,"utf-8");return JSON.parse(n)}catch{return}}function ed(t){let e;try{e=Vo(t)}catch{return}let n=yt(e);if(n)return{path:e,id:Zl(e,".json"),data:n};let r=Xo();for(let s of r){if(s.id!==t&&s.sessionId!==t&&s.name!==t)continue;let i=yt(s.path);if(i)return{path:s.path,id:s.id,data:i}}if(t.length>=3){let s=r.filter(i=>i.name!==void 0&&i.name.startsWith(t));if(s.length===1){let i=s[0];if(i){let a=yt(i.path);if(a)return{path:i.path,id:i.id,data:a}}}}}function Xo(){let t=en();if(!cr(t))return[];let e=[];for(let n of qw(t)){if(!n.endsWith(".json"))continue;let r=Ql(t,n);try{if(!zw(r).isFile())continue;let s=yt(r);if(!s||typeof s.savedAt!="number"||typeof s.model!="string")continue;e.push({path:r,id:Zl(n,".json"),sessionId:s.sessionId,name:s.name,source:s.source,model:s.model,startedAt:s.startedAt,savedAt:s.savedAt,totalTurns:s.totalTurns,totalCostUsd:s.totalCostUsd})}catch{}}return e.sort((n,r)=>r.savedAt-n.savedAt),e}import{promises as tn}from"fs";import{join as td}from"path";var bt=class{sessions=new Map;pendingSessions=new Map;sessionData=new Map;sessionStats=new Map;autosaveFailureLogged=new Set;options;constructor(e){this.options={dataDir:e.dataDir||"./data/telegram-sessions",defaultModel:e.defaultModel||"sonnet",apiKey:e.apiKey,settingSources:e.settingSources,thinking:e.thinking,effort:e.effort,botCwd:e.botCwd,createSession:e.createSession}}getSessionIfExists(e){return this.sessions.get(e)}async getSession(e){let n=this.sessions.get(e);if(n)return this._touchActivity(e),n;let r=this.pendingSessions.get(e);if(r)try{return await r}finally{this._touchActivity(e)}let o=this.sessionData.get(e)??{chatId:e,model:this.options.defaultModel,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()},s=(async()=>{let i={model:o.model,apiKey:this.options.apiKey};this.options.settingSources?.length&&(i.settingSources=this.options.settingSources),this.options.thinking!==void 0&&(i.thinking=this.options.thinking),this.options.effort!==void 0&&(i.effort=this.options.effort);let a=o.cwd??this.options.botCwd;a!==void 0&&a.length>0&&(i.cwd=a);let c=await this.options.createSession(bo(i));return this.sessions.set(e,c),this.sessionData.set(e,o),c})();this.pendingSessions.set(e,s);try{let i=await s;return this._touchActivity(e),i}finally{this.pendingSessions.delete(e)}}_touchActivity(e){let n=this.sessionData.get(e);n&&(n.lastActivity=new Date().toISOString())}recordTelegramTurn(e,n,r,o){let s=this._getOrCreateStats(e),i=this.sessions.get(e);!s.sessionId&&i?.sessionId&&(s.sessionId=i.sessionId),Vl(s,n,r,o),!s.sessionId&&i?.sessionId&&(s.sessionId=i.sessionId);let a=this.sessionData.get(e);if(a&&s.sessionId&&(a.sessionId=s.sessionId),s.sessionId)try{Yo(s)}catch(c){this.autosaveFailureLogged.has(e)||(this.autosaveFailureLogged.add(e),console.error(`[session-manager] autosave failed for chat ${e} \u2014 conversation may not be resumable:`,c))}}_hydrateStatsFromStore(e){if(this.sessionStats.has(e))return;let n=this.sessionData.get(e)?.sessionId;if(!n)return;let r=yt(n);if(!r||r.source!=="telegram"||r.telegramChatId!==e)return;let o={sessionId:r.sessionId,name:r.name,model:r.model,source:r.source,telegramChatId:r.telegramChatId,sessionStartTime:r.startedAt,totalTurns:r.totalTurns,totalCostUsd:r.totalCostUsd,totalTokens:r.totalTokens,totalDurationMs:r.totalDurationMs,turns:r.turns,turnCosts:[],turnTokens:[],planMode:!1},s=this.sessionData.get(e)?.cwd;s!==void 0&&(o.cwd=s),this.sessionStats.set(e,o)}getSessionName(e){return this._hydrateStatsFromStore(e),this.sessionStats.get(e)?.name}setSessionName(e,n){let r=this._getOrCreateStats(e);r.name=n;let o=this.sessions.get(e);if(!r.sessionId&&o?.sessionId&&(r.sessionId=o.sessionId),r.totalTurns>0&&r.sessionId){let s=this.sessionData.get(e);return s&&(s.sessionId=r.sessionId),Yo(r),{persisted:!0}}return{persisted:!1}}_getOrCreateStats(e){this._hydrateStatsFromStore(e);let n=this.sessionStats.get(e);if(!n){n=Jl(this.getModel(e)),n.source="telegram",n.telegramChatId=e;let r=this.getCwd(e);r&&(n.cwd=r),this.sessionStats.set(e,n)}return n}_resetStats(e){this.sessionStats.delete(e),this.autosaveFailureLogged.delete(e);let n=this.sessionData.get(e);n&&delete n.sessionId}async resetSession(e){let n=this.sessions.get(e);n&&(await n.close(),this.sessions.delete(e)),this._resetStats(e);let r=this.sessionData.get(e);r&&(r.lastActivity=new Date().toISOString())}async switchModel(e,n){let r=this.sessions.get(e);r&&(await r.close(),this.sessions.delete(e)),this._resetStats(e);let o=this.sessionData.get(e);o?(o.model=n,o.lastActivity=new Date().toISOString()):(o={chatId:e,model:n,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()},this.sessionData.set(e,o))}getModel(e){return this.sessionData.get(e)?.model||this.options.defaultModel}async setCwd(e,n){let r=this.sessions.get(e);r&&(await r.close(),this.sessions.delete(e)),this._resetStats(e);let o=this.sessionData.get(e);o?(o.cwd=n,o.lastActivity=new Date().toISOString()):(o={chatId:e,model:this.options.defaultModel,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString(),cwd:n},this.sessionData.set(e,o))}getCwd(e){return this.sessionData.get(e)?.cwd??this.options.botCwd}async loadSessions(){try{await tn.mkdir(this.options.dataDir,{recursive:!0});let e=await tn.readdir(this.options.dataDir);for(let n of e)if(n.endsWith(".json")){let r=td(this.options.dataDir,n),o=await tn.readFile(r,"utf-8"),s=JSON.parse(o);this.sessionData.set(s.chatId,s)}}catch(e){e.code!=="ENOENT"&&console.error("Failed to load sessions:",e)}}async saveSessions(){try{await tn.mkdir(this.options.dataDir,{recursive:!0});for(let[e,n]of this.sessionData.entries()){let r=td(this.options.dataDir,`${e}.json`);await tn.writeFile(r,JSON.stringify(n,null,2))}}catch(e){console.error("Failed to save sessions:",e)}}async closeAll(){await this.saveSessions();let e=Array.from(this.sessions.values()).map(n=>n.close().catch(r=>console.error("Error closing session:",r)));await Promise.all(e),this.sessions.clear()}getSessionCount(){return this.sessions.size}getChatCount(){return this.sessionData.size}};async function Qo(t){await t.reply(Qr())}async function Zo(t,e){let n=t.chat?.id,r,o=n?e.getSessionIfExists(n):void 0;if(o)try{await Promise.race([o.waitForInitialization(),new Promise((i,a)=>setTimeout(()=>a(new Error("timeout")),2e3))]);let s=o.getSessionMetadata();s.slashCommands?.length&&(r=s.slashCommands)}catch{}await t.reply(Di(r))}import{Markup as od}from"telegraf";import{promises as Xw}from"fs";import{homedir as sd}from"os";import{isAbsolute as Qw,resolve as es}from"path";var Yw=/^[A-Za-z0-9_@%+=:,./-]+$/;function nd(t){return Yw.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function rd(t,e){let n=["afk","interactive"];return typeof e=="string"&&e.length>0&&n.push("--model",nd(e)),n.push("--resume",nd(t)),n.join(" ")}var nn=["small","medium","large","opus","opus_1m","sonnet","sonnet_1m","haiku","fable"];async function ts(t,e,n,r){let o=t.chat?.id;if(!o){await t.reply(N("Could not identify chat"));return}try{await e.resetSession(o),n.delete(o),await t.reply(Ht())}catch(s){r("Clear error:",s),await t.reply(N(s))}}async function id(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}try{let o=await e.getSession(r);await t.sendChatAction("typing").catch(()=>{});let s=await o.compact();s.compacted?await t.reply(jt({before:s.messagesBefore,after:s.messagesAfter,...s.tokensSavedEstimate!==void 0?{tokensSavedEstimate:s.tokensSavedEstimate}:{}})):await t.reply(Kt(s.reason??"unknown"))}catch(o){n("Compact error:",o),await t.reply(N(o))}}async function ns(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1);if(s.length===0){let u=e.getModel(r),p=nn.map(f=>[od.button.callback(f,`afk:m:${f}`)]);await t.reply(`Current model: <b>${We(u.toUpperCase())}</b>
|
|
1326
1326
|
|
|
1327
1327
|
Switch to:`,{parse_mode:"HTML",reply_markup:od.inlineKeyboard(p).reply_markup});return}let i=s[0];if(!i){await t.reply(N("Please specify a model: small, medium, large, opus, sonnet, haiku, or an org/model id"));return}let a=i.toLowerCase(),c=nn.includes(a),l=Et(a)!==void 0,d=V(a)==="openai-compatible";if(!c&&!l&&!d){await t.reply(N(`Invalid model: ${i}
|
|
1328
|
-
Aliases: ${nn.join(", ")}, or org/model HF id`));return}try{await e.switchModel(r,a),await t.reply(Bt(a))}catch(u){n("Model switch error:",u),await t.reply(N(u))}}function Zw(t,e){let n=t.trim();return n==="~"?sd():n.startsWith("~/")?es(sd(),n.slice(2)):Qw(n)?es(n):es(e,n)}async function ad(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1).filter(l=>l.length>0);if(s.length===0){let l=e.getCwd(r);await t.reply(Fi(l));return}let i=s[0];if(!i){await t.reply(N("Please specify a directory path"));return}let a=e.getCwd(r)??process.cwd(),c=Zw(i,a);try{if(!(await Xw.stat(c)).isDirectory()){await t.reply(N(`Not a directory: ${c}`));return}}catch(l){let d=l.code;d==="ENOENT"?await t.reply(Xr("ENOENT",c)):d==="EACCES"?await t.reply(Xr("EACCES",c)):(n("cwd stat error:",l),await t.reply(N(l)));return}try{await e.setCwd(r,c),await t.reply(Li(c))}catch(l){n("Cwd switch error:",l),await t.reply(N(l))}}async function cd(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1).join(" ").trim();if(!s){await t.reply(Ni(e.getSessionName(r)));return}let i=ar(s);if(!i){await t.reply($i());return}try{let{persisted:a}=e.setSessionName(r,i),c=a?rd(i,e.getModel(r)):void 0;await t.reply(Ui(i,c))}catch(a){n("Name set error:",a),await t.reply(`\u{1F3F7}\uFE0F Named "${i}" but couldn't save it \u2014 it'll retry on your next message.`)}}import{execFile as yS,spawn as bS}from"node:child_process";import{promisify as wS}from"node:util";H();import{execFile as eS}from"node:child_process";import{randomBytes as tS}from"node:crypto";import{promises as lr}from"node:fs";import{join as dr}from"node:path";import{promisify as nS}from"node:util";var
|
|
1328
|
+
Aliases: ${nn.join(", ")}, or org/model HF id`));return}try{await e.switchModel(r,a),await t.reply(Bt(a))}catch(u){n("Model switch error:",u),await t.reply(N(u))}}function Zw(t,e){let n=t.trim();return n==="~"?sd():n.startsWith("~/")?es(sd(),n.slice(2)):Qw(n)?es(n):es(e,n)}async function ad(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1).filter(l=>l.length>0);if(s.length===0){let l=e.getCwd(r);await t.reply(Fi(l));return}let i=s[0];if(!i){await t.reply(N("Please specify a directory path"));return}let a=e.getCwd(r)??process.cwd(),c=Zw(i,a);try{if(!(await Xw.stat(c)).isDirectory()){await t.reply(N(`Not a directory: ${c}`));return}}catch(l){let d=l.code;d==="ENOENT"?await t.reply(Xr("ENOENT",c)):d==="EACCES"?await t.reply(Xr("EACCES",c)):(n("cwd stat error:",l),await t.reply(N(l)));return}try{await e.setCwd(r,c),await t.reply(Li(c))}catch(l){n("Cwd switch error:",l),await t.reply(N(l))}}async function cd(t,e,n){let r=t.chat?.id;if(!r){await t.reply(N("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1).join(" ").trim();if(!s){await t.reply(Ni(e.getSessionName(r)));return}let i=ar(s);if(!i){await t.reply($i());return}try{let{persisted:a}=e.setSessionName(r,i),c=a?rd(i,e.getModel(r)):void 0;await t.reply(Ui(i,c))}catch(a){n("Name set error:",a),await t.reply(`\u{1F3F7}\uFE0F Named "${i}" but couldn't save it \u2014 it'll retry on your next message.`)}}import{execFile as yS,spawn as bS}from"node:child_process";import{promisify as wS}from"node:util";H();import{execFile as eS}from"node:child_process";import{randomBytes as tS}from"node:crypto";import{promises as lr}from"node:fs";import{join as dr}from"node:path";import{promisify as nS}from"node:util";var CD=nS(eS);var Ne=class extends Error{cause;code;constructor(e,n,r){super(e),this.name="WorktreeError",this.cause=n,this.code=r}};function rS(t,e=40){return t.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,e).replace(/-+$/g,"")||"task"}function oS(){return tS(4).toString("hex").slice(0,4)}function sS(t){let e=n=>String(n).padStart(2,"0");return`${t.getUTCFullYear()}${e(t.getUTCMonth()+1)}${e(t.getUTCDate())}T${e(t.getUTCHours())}${e(t.getUTCMinutes())}${e(t.getUTCSeconds())}`}function ld(t,e={}){let n=(e.now??(()=>new Date))(),r=(e.randomSuffix??oS)();return`${sS(n)}-${rS(t,32)}-${r}`}function iS(t){let e=t;return e.respawnedAt===void 0&&(e.respawnedAt=void 0),e.respawnedAs===void 0&&(e.respawnedAs=void 0),e.prUrl===void 0&&(e.prUrl=void 0),e.prCreatedAt===void 0&&(e.prCreatedAt=void 0),e}async function wt(t){let e=dr(Ks(t),"farm.json");try{let n=await lr.readFile(e,"utf8"),r=JSON.parse(n);if(r.schemaVersion!==1&&r.schemaVersion!==2&&r.schemaVersion!==3)throw new Ne(`unsupported farm manifest schema: ${r.schemaVersion} (expected 1, 2, or 3)`,void 0,"unsupported-schema");return iS(r)}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Ne?n:new Ne(`failed to load farm manifest ${e}`,n,"invalid")}}async function dd(t,e){let n=await wt(t);if(!n)throw new Ne(`farm not found: ${t}`);return n.human_decision=e,n.decidedAt=new Date().toISOString(),n.schemaVersion=3,await lr.writeFile(dr(n.farmDir,"farm.json"),JSON.stringify(n,null,2)+`
|
|
1329
1329
|
`,"utf8"),n}async function ud(t,e){let n=await wt(t);if(!n)throw new Ne(`farm not found: ${t}`);return n.respawnedAt=new Date().toISOString(),n.respawnedAs=e,n.schemaVersion=3,await lr.writeFile(dr(n.farmDir,"farm.json"),JSON.stringify(n,null,2)+`
|
|
1330
1330
|
`,"utf8"),n}async function pd(t,e){let n=await wt(t);if(!n)throw new Ne(`farm not found: ${t}`);return n.prUrl=e,n.prCreatedAt=new Date().toISOString(),n.schemaVersion=3,await lr.writeFile(dr(n.farmDir,"farm.json"),JSON.stringify(n,null,2)+`
|
|
1331
|
-
`,"utf8"),n}import{execFile as aS,spawn as
|
|
1331
|
+
`,"utf8"),n}import{execFile as aS,spawn as DD}from"node:child_process";import{promisify as cS}from"node:util";var lS=cS(aS),dS=2e4,on=class extends Error{kind;exitCode;stderr;constructor(e,n,r,o){super(e),this.name="GhError",this.kind=n,this.exitCode=r,this.stderr=o}},ur=null,rn=null;function uS(t,e,n){return n===!0?"timeout":e==="ENOENT"?"not-found":/already exists/i.test(t)?"already-exists":/authentication|please log in|HTTP 40[13]|bad credentials|token|scope/i.test(t)?"unauthed":/ETIMEDOUT|ECONNRESET|ECONNREFUSED/i.test(t+(e??""))?"network":"unknown"}function fd(t,e){return lS(t,e,{timeout:dS,killSignal:"SIGTERM"}).then(n=>({stdout:n.stdout,stderr:n.stderr}))}async function md(t={}){let e=(t._now??(()=>Date.now()))(),n=t.ttlMs??6e4,r=t.execFn??fd,o=t.log??(()=>{});return ur&&ur.expiresAt>e?(o("[gh] checkGhReady cache hit"),ur.result):(o("[gh] checkGhReady cache miss \u2014 probing"),rn||(rn=(async()=>{try{await r("gh",["--version"])}catch(a){let c=a;return c.killed?{ok:!1,hint:"`gh` timed out \u2014 check connectivity"}:c.code==="ENOENT"?{ok:!1,hint:"`gh` CLI not found \u2014 install with: brew install gh"}:{ok:!1,hint:"`gh --version` failed unexpectedly \u2014 check gh installation"}}try{await r("gh",["auth","status"])}catch(a){let c=a;return c.killed||/ETIMEDOUT|ECONNRESET|ENOTFOUND/i.test(String(c.code??""))?{ok:!1,hint:"check network \u2014 cannot reach GitHub"}:{ok:!1,hint:"`gh` is not authenticated \u2014 run: gh auth login"}}let i={ok:!0};return n>0&&(ur={result:i,expiresAt:e+n}),i})().finally(()=>{rn=null}),rn))}async function gd(t,e){let n=e??fd,r=["pr","create","--base",t.base,"--head",t.head,"--title",t.title,"--body",t.body];try{let{stdout:o}=await n("gh",r);return o.trim()}catch(o){let s=o,i=s.stderr??"",a=s.code,c=s.exitCode??1,l=uS(i,a,s.killed);throw new on(`gh pr create failed (${l}): ${i.trim()}`,l,c,i)}}function hd(t,e){let n;try{n=e?._store??new ve}catch(r){return{skipped:!0,reason:r instanceof Error?r.message:String(r)}}try{let r={type:"farm-decision",taskSlug:t.taskSlug,decision:t.decision,decidedAt:t.decidedAt,via:t.via};return{factId:n.storeFact({category:"decision",content:JSON.stringify(r),source_surface:"afk"})}}catch(r){return{skipped:!0,reason:r instanceof Error?r.message:String(r)}}}import{promises as pS}from"node:fs";import{join as fS}from"node:path";function wd(t){let e=t.filter(r=>r.score!==null),n=t.filter(r=>r.score===null).map(r=>r.index).sort((r,o)=>r-o);return e.sort((r,o)=>{let s=r.score,i=o.score,a=yd(s),c=yd(i);if(a!==c)return c-a;let l=bd(s.lint_ok),d=bd(i.lint_ok);return l!==d?d-l:s.loc_delta!==i.loc_delta?s.loc_delta-i.loc_delta:r.index-o.index}),[...e.map(r=>r.index),...n]}function yd(t){let e=t.pass+t.fail;return e===0?0:t.pass/e}function bd(t){return t===!0?2:t===!1?1:0}async function pr(t,e={}){if(t.branches.length===0)throw new Error(`resolveWinnerBranch: farm ${t.taskSlug} has no branches`);let n=e.loadScore??mS,r=await Promise.all(t.branches.map(async i=>({index:i.index,score:await n(t.farmDir,i.index)}))),o=wd(r),s=new Map(t.branches.map(i=>[i.index,i]));for(let i of o){let a=r.find(c=>c.index===i)?.score;if(a&&a.pass>0&&a.fail===0){let c=s.get(i);if(c)return{branch:c,source:"winner"}}}for(let i of o)if(r.find(c=>c.index===i)?.score){let c=s.get(i);if(c)return{branch:c,source:"top-scored"}}return{branch:t.branches[0],source:"fallback-first-branch"}}async function mS(t,e){let n=fS(t,"scores",`branch-${e}.json`);try{let r=await pS.readFile(n,"utf8");return JSON.parse(r)}catch(r){return r.code==="ENOENT",null}}var fr="afk:f:";var gS=new Set(["p","d","r","x"]),hS=/^[a-z0-9T][a-z0-9T-]{0,62}$/;function Sd(t){if(!t||!t.startsWith(fr)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(fr.length),n=e.indexOf(":");if(n<1)return null;let r=e.slice(0,n),o=e.slice(n+1);return!gS.has(r)||!hS.test(o)?null:{action:r,taskSlug:o}}var SS=wS(yS),rs=new Map;async function kd(t,e={}){let n=e.log??(()=>{}),r=vS(t),o=Sd(r);if(!o){await J(t,"Unknown action",n);return}if(t.chat?.id===void 0){await J(t,"No chat context",n);return}let s=e.loadFarm??wt,i;try{i=await s(o.taskSlug)}catch(a){n("[farm-callback] loadFarm failed:",a),await J(t,"Farm load failed",n);return}if(!i){await J(t,"Farm not found (already GC\u2019d?)",n);return}try{await kS(o.action,t,i,e,n)}catch(a){n("[farm-callback] dispatch error:",a),await J(t,"Internal error",n)}}function vS(t){return t.callbackQuery?.data}async function J(t,e,n){try{await t.answerCbQuery(e)}catch(r){n("[farm-callback] answerCbQuery failed:",r)}}async function kS(t,e,n,r,o){switch(t){case"x":return xS(e,n,r,o);case"d":return TS(e,n,r,o);case"p":return vd(`p:${n.taskSlug}`,e,n,r,o,_S);case"r":return vd(`r:${n.taskSlug}`,e,n,r,o,AS)}}async function vd(t,e,n,r,o,s){let i=rs.get(t);if(i){o(`[farm-callback] ${t} \u2014 second tap, awaiting in-flight lock`);try{await i}catch{}let c=r.loadFarm??wt,l;try{l=await c(n.taskSlug)}catch{await J(e,"Farm load failed",o);return}if(!l){await J(e,"Farm not found",o);return}return s(e,l,r,o)}let a=s(e,n,r,o);return rs.set(t,a),a.finally(()=>{rs.delete(t)}),a}async function _S(t,e,n,r){if(e.prUrl){await J(t,`PR already open: ${e.prUrl}`,r);return}await J(t,"Opening PR\u2026",r);let o=n.checkGhReady??md,s;try{s=await o()}catch(m){r("[farm-callback] checkGhReady threw:",m);try{await t.reply("gh readiness check failed \u2014 see daemon logs")}catch{}return}if(!s.ok){try{await t.reply(s.hint)}catch{}return}let i=n.resolveWinnerBranch??pr,a;try{a=await i(e)}catch(m){r("[farm-callback] resolveWinnerBranch failed:",m);try{await t.reply("Winner lookup failed")}catch{}return}let c=a.branch.branch,l=e.baseBranch??"main",d=`Auto PR: ${e.taskName}`,u=`Auto-generated by afk farm ${e.taskSlug} | winner: ${c} | created: ${new Date().toISOString()}`,p=n.createPr??gd,f;try{f=await p({base:l,head:c,title:d,body:u})}catch(m){if(m instanceof on){let k={"not-found":"gh CLI not found \u2014 install with: brew install gh","already-exists":"PR already exists for this branch",unauthed:"gh is not authenticated \u2014 run: gh auth login",network:"Network error \u2014 check gh connectivity",timeout:"gh timed out \u2014 check connectivity",unknown:"gh pr create failed \u2014 see daemon logs"};try{await t.reply(k[m.kind])}catch{}return}r("[farm-callback] createPr failed:",m);try{await t.reply("gh pr create failed \u2014 see daemon logs")}catch{}return}let g=n.recordPrCreated??pd;try{await g(e.taskSlug,f)}catch(m){r("[farm-callback] recordPrCreated failed:",m)}try{await t.reply(`PR opened \u2713
|
|
1332
1332
|
\u{1F517} ${f}`)}catch(m){r("[farm-callback] reply failed:",m)}}function ES(t,e=()=>{}){e("[farm] spawning child afk process",{args:t});let n=bS("afk",t,{detached:!0,stdio:"ignore"});n.on("error",r=>{e("[farm] child spawn error",{args:t,err:r.message})}),n.on("exit",(r,o)=>{r!==0&&e("[farm] child exited with non-zero code",{args:t,code:r,signal:o})}),n.unref()}async function AS(t,e,n,r){if(e.respawnedAs){await J(t,`Already respawned as ${e.respawnedAs}`,r);return}if(e.branches.length===0){await J(t,"No branches remain \u2014 cannot respawn",r);return}await J(t,"Respawning\u2026",r);let o=n.resolveWinnerBranch??pr,s;try{s=await o(e)}catch(u){r("[farm-callback] resolveWinnerBranch failed:",u);try{await t.reply("Winner lookup failed")}catch{}return}let i=s.branch,a=ld(e.taskName,{now:n._now,randomSuffix:n._randomSuffix}),c=e.branches.length;r("[farm] spawning child",{childSlug:a,baseRef:i.branch,branches:c});let l=n.spawnFarm??(u=>ES(u,r));try{l(["farm",e.taskName,"--branches",String(c),"--base-ref",i.branch,"--task-slug",a])}catch(u){r("[farm-callback] spawnFarm failed:",u);try{await t.reply("Respawn failed")}catch{}return}let d=n.recordRespawn??ud;try{await d(e.taskSlug,a)}catch(u){r("[farm-callback] recordRespawn failed:",u)}try{await t.reply(`Respawning as \`${a}\` from ${i.branch} \u2713
|
|
1333
1333
|
\u{1F504} Farm \`${e.taskSlug}\` respawned.
|
|
1334
1334
|
Child slug: \`${a}\`
|