agent-afk 5.35.3 → 5.36.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/plugins/tool-injector.d.ts +1 -0
- package/dist/agent/tools/nesting.d.ts +1 -1
- package/dist/agent/tools/skill-bridge.d.ts +1 -0
- package/dist/agent/tools/skill-executor/fork-dispatch.d.ts +1 -1
- package/dist/cli.mjs +436 -429
- package/dist/index.mjs +6 -6
- package/dist/service/index.d.ts +4 -0
- package/dist/service/launchd/manager.d.ts +2 -0
- package/dist/service/systemd/install.d.ts +7 -0
- package/dist/service/systemd/manager.d.ts +2 -0
- package/dist/service/systemd/paths.d.ts +11 -0
- package/dist/service/systemd/status.d.ts +9 -0
- package/dist/service/systemd/unit.d.ts +20 -0
- package/dist/service/types.d.ts +63 -0
- package/dist/telegram.mjs +106 -106
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
var Vg=Object.defineProperty;var ge=(t,e)=>()=>(t&&(e=t(t=0)),e);var al=(t,e)=>{for(var n in e)Vg(t,n,{get:e[n],enumerable:!0})};function gr(t){return mr.find(e=>e.name===t)}function $s(t){return process.env[t]!==void 0}var mr,S,N=ge(()=>{"use strict";mr=[{name:"AFK_COMPACT_KEEP_LAST_TURNS",description:"Number of recent turns the compactor keeps verbatim during /compact. Default tuned in compact-handler.ts.",type:"number",required:!1,example:"6",category:"model"},{name:"AFK_COMPACT_MODEL",description:"Override the model used by the /compact summarizer. Falls back to a cheap default (haiku-class).",type:"string",required:!1,example:"claude-haiku-4-5",category:"model"},{name:"AFK_DEFAULT_SUBAGENT_MODEL",description:"Override the default model used when a subagent is dispatched without an explicit model.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_DIAGNOSE_BASELINE",description:"Kill switch for /diagnose reproducer baseline execution. When set to '0', the /diagnose skill skips executing the detected reproducer command for a ground-truth baseline; default enabled (runs). Set to '0' to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_DISABLE_PROMPT_CACHE",description:"Disable Anthropic prompt caching when set to 1/true/yes/on. Unset = caching enabled.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_DISABLE_BASH_INTERPRETER_GUARD",description:"Skip ONLY the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) when set to 1, leaving the rest of path-approval intact. Applies on interactive surfaces (REPL/Telegram), where the denylist is active but your workflow legitimately runs interpreter one-liners. The restricted-root substring check is unaffected. Default: denylist active on interactive surfaces; headless already fails open (opt in with AFK_FORCE_BASH_INTERPRETER_GUARD=1). To disable all of path-approval + bash restriction instead, use AFK_DISABLE_PATH_APPROVAL=1.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_DISABLE_PATH_APPROVAL",description:"Skip the path-approval + bash-restriction hooks entirely when set to 1. Use for headless flows that need wide-open file access (CI scripts, batch jobs). Default: hooks enabled. Note: on headless surfaces (afk chat, daemon) no grant manager is wired, so the interpreter denylist (python -c, node -e, sh -c, ...) fails OPEN by default \u2014 opt headless flows into it with AFK_FORCE_BASH_INTERPRETER_GUARD=1, or set this var to 1 to disable all of path-approval.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_FORCE_BASH_INTERPRETER_GUARD",description:"Apply the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) even on headless surfaces (afk chat, daemon) where no grant manager is wired. By default the denylist fires only on interactive surfaces (REPL/Telegram), failing open on headless so legitimate automation is not hard-blocked with no recourse. Set to 1 to opt headless flows back into the guard. Overridden by AFK_DISABLE_BASH_INTERPRETER_GUARD=1. Default: off (headless fails open).",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_EFFORT",description:"Effort hint guiding adaptive-thinking depth, forwarded as Anthropic output_config.effort (model-gated; ignored where unsupported). Accepts low | medium | high | xhigh | max.",type:"string",required:!1,example:"medium",category:"model"},{name:"AFK_MAX_BUDGET_USD",description:"Cumulative USD budget ceiling for the session. Aborts the turn when the running cost crosses this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. Falls back to provider default when unset.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Deprecated and inert: not read by the generation path. Use AFK_MAX_OUTPUT_TOKENS (or --max-output-tokens) to cap per-response output tokens; falls back to the model output ceiling when unset.",type:"number",required:!1,default:"4096",example:"8192",category:"model"},{name:"AFK_MAX_TOOL_USE_ITERATIONS",description:"Opt-in ceiling on tool-use rounds per turn for TOP-LEVEL (non-subagent) sessions, on both providers. Mirrors the maxToolUseIterations config key / max_tool_use_iterations tool param. Unset, non-numeric, or <=0 means unlimited (the default \u2014 zero behavior change): a top-level turn ends only when the model stops calling tools, the abort signal fires, the provider errors, or the dollar budget trips. A positive integer N makes top-level turns wind down gracefully after N tool rounds (one tools-stripped final round). An explicit config/CLI value wins over this env default. Does NOT affect subagent forks \u2014 they keep their own non-zero anti-hang default (SUBAGENT_DEFAULT_MAX_TOOL_USE_ITERATIONS) regardless of this var.",type:"number",required:!1,default:"0",example:"150",category:"model"},{name:"AFK_MEMORY_EVIDENCE_GATE",description:'Opt-in (set to 1) evidence gate for durable memory writes. When enabled, a codebase fact (memory_update category "convention") stored without an `evidence` citation is recalled as [unverified], and memory_search results carry a verification verdict. User preferences and agent reflections are never gated. Default off \u2014 memory behaves identically to legacy when unset.',type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), legacy aliases (opus, sonnet, haiku), the fixed-id fable alias (Claude Fable 5), or full model IDs.",type:"string",required:!1,default:"sonnet",example:"claude-opus-4-5",category:"model"},{name:"AFK_VISION_MODELS",description:'Comma-separated override for image (vision) capability detection on the openai-compatible provider. Each token force-enables a model id by exact or substring match (e.g. "qwen2.5-vl" matches a local VL id); prefix a token with "!" to force-disable. Use to send images to a local vision-language model AFK does not recognise by name, or to blacklist a mis-detected id. Built-in detection already covers gpt-4o/4.1/5.x, o1/o3/o4-mini, Claude, and common VL families.',type:"string",required:!1,example:"qwen2.5-vl,!gpt-4o-mini",category:"model"},{name:"AFK_MODEL_LOCAL",description:'Bind the "local" capability tier (cheapest/fastest, user-configured) to a model id. Overrides afk.config.json models.local. Point at a local Ollama, LM Studio, or any OpenAI-compatible shim.',type:"string",required:!1,example:"llama3.2:3b",category:"model"},{name:"AFK_MODEL_LOCAL_API_KEY",description:'Per-slot API key for the "local" tier. Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LOCAL_BASE_URL",description:'Per-slot endpoint base URL for the "local" tier. Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:11434/v1",category:"model"},{name:"AFK_MODEL_LARGE",description:'Bind the "large" capability tier (most capable) to a model id/alias. Overrides afk.config.json models.large.',type:"string",required:!1,example:"claude-opus-4-8",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-5",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_THINKING_UI",description:"Default thinking-display mode for the interactive REPL: summary | live | digest | off. Display-only \u2014 controls how extended-thinking blocks render, never whether thinking runs (cost/latency unaffected). Overridden per-launch by --thinking-ui and mutable mid-session via /thinking. Precedence: --thinking-ui flag > this env > interactive.thinkingUi config > live. Invalid values are ignored.",type:"string",required:!1,default:"live",example:"digest",category:"misc"},{name:"AFK_TIMEOUT_MS",description:"Per-turn timeout in milliseconds. Provider/SDK default if unset.",type:"number",required:!1,example:"120000",category:"model"},{name:"CLAUDE_MODEL",description:"Legacy alias for AFK_MODEL \u2014 supported for back-compat with pre-AFK_* deployments.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_SYSTEM_PROMPT",description:'Raw operator-overlay prompt. Highest-priority overlay (over afk.config.json and AFK.md). Appended on top of the framework base (prompts/system-prompt.md) under an "# Operator configuration" header \u2014 it augments, never replaces, the base.',type:"string",required:!1,example:"You are a helpful agent.",category:"model"},{name:"AFK_DUMP_PROMPT",description:"Write the resolved system prompt to a file at startup. Accepts a path or 1 for default location.",type:"string",required:!1,example:"/tmp/afk-prompt.txt",category:"debug"},{name:"ANTHROPIC_API_KEY",description:"Anthropic API key. Tier-1 credential \u2014 overrides keychain OAuth and CLAUDE_CODE_OAUTH_TOKEN.",type:"string",required:!1,category:"auth",secret:!0},{name:"CLAUDE_CODE_OAUTH_TOKEN",description:"Claude Code OAuth token. Tier-2 credential \u2014 used when ANTHROPIC_API_KEY is unset; falls back to keychain.",type:"string",required:!1,category:"auth",secret:!0},{name:"OPENAI_API_KEY",description:"OpenAI API key for the openai-compatible provider (gpt-*, o1*, o3*, o4* models).",type:"string",required:!1,category:"auth",secret:!0},{name:"CODEX_API_KEY",description:"Fallback OpenAI API key for the openai-compatible provider, read after OPENAI_API_KEY. Legacy name from the removed @openai/codex-sdk integration \u2014 prefer OPENAI_API_KEY.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_LOCAL_API_KEY",description:"Placeholder API key for local Anthropic-compatible servers (vllm-mlx, etc.). Set when AFK_LOCAL_BASE_URL is configured.",type:"string",required:!1,default:"local",example:"local",category:"auth",secret:!0},{name:"AFK_LOCAL_BASE_URL",description:"Base URL for a self-hosted Anthropic-compatible server. When set, routes traffic away from api.anthropic.com.",type:"string",required:!1,example:"http://127.0.0.1:8080",category:"model"},{name:"AFK_OPENAI_BASE_URL",description:"Base URL override for the OpenAI-compatible provider. Used for local shims (mlx_lm.server, Ollama, vLLM, LM Studio). The OpenAI SDK appends `/chat/completions` itself \u2014 a value ending in `/chat/completions` will be stripped at config-load time with a one-shot warning.",type:"string",required:!1,example:"http://127.0.0.1:8000/v1",category:"model"},{name:"AFK_OPENAI_USE_RESPONSES",description:"Opt the OpenAI-compatible provider into the OpenAI Responses API instead of Chat Completions for API-key sessions. Truthy values: 1, true, yes, on. The ChatGPT-subscription OAuth path uses Responses automatically regardless of this flag.",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_OPENAI_CHATGPT_OAUTH",description:"Opt into using ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. Off by default. READ-ONLY: AFK never refreshes these tokens \u2014 re-run `codex` when the access token expires. Routes requests over the Responses API to the private ChatGPT backend (chatgpt.com/backend-api).",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_PROVIDER",description:"Force provider selection (anthropic | anthropic-direct | openai | openai-compatible | openai-codex). Overrides the model-name heuristic. Same surface as the --provider CLI flag; CLI flag wins when both are set.",type:"string",required:!1,example:"openai-compatible",category:"model"},{name:"EXA_API_KEY",description:"Exa (exa.ai) search API key, enabling web_scrape search mode. Free tier (20k requests/month) available at https://exa.ai. When unset, search mode returns an actionable error; markdown and raw modes are unaffected.",type:"string",required:!1,category:"auth",secret:!0},{name:"TELEGRAM_BOT_TOKEN",description:"Telegram bot token from @BotFather. Required to run the Telegram bot surface.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_BOT_TOKEN",description:"Alternative env var name for the Telegram bot token, accepted by the setup wizard.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_ALLOWED_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs allowed to interact with the bot. Required when the bot is running.",type:"string",required:!1,example:"123456789,987654321",category:"telegram"},{name:"AFK_TELEGRAM_PRIMARY_CHAT_ID",description:"Default chat ID for outbound notifications (primary-mode routing). When unset, notifications go to the first private/DM chat in AFK_TELEGRAM_ALLOWED_CHAT_IDS. The afk.config.json telegram.notify block takes precedence.",type:"string",required:!1,example:"123456789",category:"telegram"},{name:"AFK_TELEGRAM_NOTIFY_MODE",description:"Outbound notification fan-out: primary (default \u2014 one chat), broadcast (every allowed chat), or custom (afk.config.json telegram.notify.targets). The afk.config.json telegram.notify.mode takes precedence.",type:"string",required:!1,example:"broadcast",category:"telegram"},{name:"TELEGRAM_DATA_DIR",description:"Override the directory where Telegram bot state is stored. Defaults to ~/.afk/state/telegram/.",type:"string",required:!1,category:"telegram"},{name:"TELEGRAM_VERBOSE",description:"Set to 1 to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"1",category:"telegram"},{name:"AFK_TELEGRAM_TRACE",description:"Set to 1 to dump raw bridge traffic between the agent and the Telegram bot \u2014 debugging only.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_TELEGRAM_CWD",description:"Override the working directory used by the Telegram bot when spawning agent sessions.",type:"string",required:!1,category:"telegram"},{name:"AFK_HOME",description:"Override the AFK home directory. Default: ~/.afk/.",type:"string",required:!1,default:"~/.afk",example:"/opt/afk",category:"paths"},{name:"AFK_STATE_DIR",description:"Override the entire AFK state tier (sessions/, todos/, transcripts/, memory/, daemon/, etc.), not just one subdirectory. Must be an absolute path (not /). Default: $AFK_HOME/state/.",type:"string",required:!1,category:"paths"},{name:"AFK_FRAMEWORK_DIR",description:"Override the AFK agent-framework directory used for telemetry and briefs. Default: $AFK_HOME/agent-framework/.",type:"string",required:!1,category:"paths"},{name:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Controls auto-loading of MCP configuration from <cwd>/.mcp.json. Auto-loaded by default \u2014 set to 0 to disable (mitigates config-injection risk in shared/CI environments).",type:"boolean",required:!1,example:"0",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BG_AUTO_DELIVER",description:"Auto-deliver background subagent results into the model context on the next user turn (interactive REPL). On by default. Set to 0, false, off, or no (case-insensitive) to disable, restoring the manual /bgsub:join retrieval flow.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless for daemon and subagent surfaces and headed for repl/interactive \u2014 so an operator can watch the agent work in REPL mode.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_ALLOWED_DOMAINS",description:"Comma-separated allowlist of URL host globs. When set, browser_open and any navigation that targets a host outside the list returns status: blocked_by_policy. Unset means no allowlist (permissive). Patterns use simple `*` glob matching against the URL host. Combines with AFK_BROWSER_BLOCKED_DOMAINS \u2014 block wins.",type:"string",required:!1,example:"github.com,*.atlassian.net",category:"browser"},{name:"AFK_BROWSER_BLOCKED_DOMAINS",description:"Comma-separated blocklist of URL host globs. Browser navigation that matches any entry returns status: blocked_by_policy regardless of the allowlist.",type:"string",required:!1,example:"*.ads.example.com",category:"browser"},{name:"AFK_BROWSER_DOM_SNAPSHOTS",description:"Phase 2 opt-in: when set to 1, every browser_act writes a gzipped DOM snapshot sidecar under ~/.afk/state/witness/<sid>/browser/dom-snapshots/. Off by default because snapshots are large; useful for post-mortem analysis of failed actions.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_BACKEND",description:"Select the browser provider backend. Phase 1 supports only `playwright`. Reserved for future `cdp` / `mcp` adapters. Unset defaults to `playwright`.",type:"string",required:!1,example:"playwright",category:"browser"},{name:"AFK_BROWSER_CONFIG",description:"Absolute path to an alternate browser config file. Overrides the default ~/.afk/config/browser.json lookup. Useful for per-project overrides in CI.",type:"string",required:!1,example:"/path/to/browser.json",category:"browser"},{name:"AFK_BROWSER_DEFAULT_PROFILE",description:"Name of the persistent session-vault profile the agent reuses for browser sessions. The context restores its login from (and saves it back to) ~/.afk/state/browser/<profile>/storageState.json, so a human runs `afk browser login --profile <name>` once and the agent reuses that authenticated session across unattended runs. Unset defaults to `default` (a fresh, empty profile \u2014 identical to pre-vault behavior). Allowed charset: [A-Za-z0-9_-], max 128 chars.",type:"string",required:!1,example:"work",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],S={get AFK_COMPACT_KEEP_LAST_TURNS(){return process.env.AFK_COMPACT_KEEP_LAST_TURNS},get AFK_COMPACT_MODEL(){return process.env.AFK_COMPACT_MODEL},get AFK_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_OUTPUT_TOKENS(){return process.env.AFK_MAX_OUTPUT_TOKENS},get AFK_MAX_TOKENS(){return process.env.AFK_MAX_TOKENS},get AFK_MAX_TOOL_USE_ITERATIONS(){return process.env.AFK_MAX_TOOL_USE_ITERATIONS},get AFK_MEMORY_EVIDENCE_GATE(){return process.env.AFK_MEMORY_EVIDENCE_GATE},get AFK_MODEL(){return process.env.AFK_MODEL},get AFK_MODEL_LARGE(){return process.env.AFK_MODEL_LARGE},get AFK_MODEL_LARGE_API_KEY(){return process.env.AFK_MODEL_LARGE_API_KEY},get AFK_MODEL_LARGE_BASE_URL(){return process.env.AFK_MODEL_LARGE_BASE_URL},get AFK_MODEL_LOCAL(){return process.env.AFK_MODEL_LOCAL},get AFK_MODEL_LOCAL_API_KEY(){return process.env.AFK_MODEL_LOCAL_API_KEY},get AFK_MODEL_LOCAL_BASE_URL(){return process.env.AFK_MODEL_LOCAL_BASE_URL},get AFK_MODEL_MEDIUM(){return process.env.AFK_MODEL_MEDIUM},get AFK_MODEL_MEDIUM_API_KEY(){return process.env.AFK_MODEL_MEDIUM_API_KEY},get AFK_MODEL_MEDIUM_BASE_URL(){return process.env.AFK_MODEL_MEDIUM_BASE_URL},get AFK_MODEL_SMALL(){return process.env.AFK_MODEL_SMALL},get AFK_MODEL_SMALL_API_KEY(){return process.env.AFK_MODEL_SMALL_API_KEY},get AFK_MODEL_SMALL_BASE_URL(){return process.env.AFK_MODEL_SMALL_BASE_URL},get AFK_VISION_MODELS(){return process.env.AFK_VISION_MODELS},get AFK_PROMPT_CACHE_TTL(){return process.env.AFK_PROMPT_CACHE_TTL},get AFK_SUGGEST_ENABLED(){return process.env.AFK_SUGGEST_ENABLED},get AFK_SUGGEST_GHOST(){return process.env.AFK_SUGGEST_GHOST},get AFK_SUGGEST_MODEL(){return process.env.AFK_SUGGEST_MODEL},get AFK_TASK_BUDGET(){return process.env.AFK_TASK_BUDGET},get AFK_TEMPERATURE(){return process.env.AFK_TEMPERATURE},get AFK_THINKING(){return process.env.AFK_THINKING},get AFK_THINKING_UI(){return process.env.AFK_THINKING_UI},get AFK_TIMEOUT_MS(){return process.env.AFK_TIMEOUT_MS},get CLAUDE_MODEL(){return process.env.CLAUDE_MODEL},get AFK_SYSTEM_PROMPT(){return process.env.AFK_SYSTEM_PROMPT},get AFK_DUMP_PROMPT(){return process.env.AFK_DUMP_PROMPT},get ANTHROPIC_API_KEY(){return process.env.ANTHROPIC_API_KEY},get CLAUDE_CODE_OAUTH_TOKEN(){return process.env.CLAUDE_CODE_OAUTH_TOKEN},get OPENAI_API_KEY(){return process.env.OPENAI_API_KEY},get CODEX_API_KEY(){return process.env.CODEX_API_KEY},get AFK_LOCAL_API_KEY(){return process.env.AFK_LOCAL_API_KEY},get AFK_LOCAL_BASE_URL(){return process.env.AFK_LOCAL_BASE_URL},get AFK_OPENAI_BASE_URL(){return process.env.AFK_OPENAI_BASE_URL},get AFK_OPENAI_USE_RESPONSES(){return process.env.AFK_OPENAI_USE_RESPONSES},get AFK_OPENAI_CHATGPT_OAUTH(){return process.env.AFK_OPENAI_CHATGPT_OAUTH},get AFK_PROVIDER(){return process.env.AFK_PROVIDER},get EXA_API_KEY(){return process.env.EXA_API_KEY},get TELEGRAM_BOT_TOKEN(){return process.env.TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_BOT_TOKEN(){return process.env.AFK_TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_ALLOWED_CHAT_IDS(){return process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS},get AFK_TELEGRAM_PRIMARY_CHAT_ID(){return process.env.AFK_TELEGRAM_PRIMARY_CHAT_ID},get AFK_TELEGRAM_NOTIFY_MODE(){return process.env.AFK_TELEGRAM_NOTIFY_MODE},get TELEGRAM_DATA_DIR(){return process.env.TELEGRAM_DATA_DIR},get TELEGRAM_VERBOSE(){return process.env.TELEGRAM_VERBOSE},get AFK_TELEGRAM_TRACE(){return process.env.AFK_TELEGRAM_TRACE},get AFK_TELEGRAM_CWD(){return process.env.AFK_TELEGRAM_CWD},get AFK_HOME(){return process.env.AFK_HOME},get AFK_STATE_DIR(){return process.env.AFK_STATE_DIR},get AFK_FRAMEWORK_DIR(){return process.env.AFK_FRAMEWORK_DIR},get HOME(){return process.env.HOME},get PATH(){return process.env.PATH},get AFK_DAEMON_CWD(){return process.env.AFK_DAEMON_CWD},get AFK_DAEMON_TASK(){return process.env.AFK_DAEMON_TASK},get AFK_DAEMON_TASK_ID(){return process.env.AFK_DAEMON_TASK_ID},get AFK_DAEMON_HOST(){return process.env.AFK_DAEMON_HOST},get AFK_SESSIONSTART_COOLDOWN_MS(){return process.env.AFK_SESSIONSTART_COOLDOWN_MS},get AFK_WORKTREE_AUTONAME(){return process.env.AFK_WORKTREE_AUTONAME},get AFK_WORKTREE_BRANCH_PREFIX(){return process.env.AFK_WORKTREE_BRANCH_PREFIX},get AFK_WORKTREE_BASE(){return process.env.AFK_WORKTREE_BASE},get AFK_WORKTREE_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BG_AUTO_DELIVER(){return process.env.AFK_BG_AUTO_DELIVER},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},get AFK_SHOW_DIFFS(){return process.env.AFK_SHOW_DIFFS},get AFK_SKILL_STREAM_VERBOSE(){return process.env.AFK_SKILL_STREAM_VERBOSE},get FORCE_COLOR(){return process.env.FORCE_COLOR},get NO_COLOR(){return process.env.NO_COLOR},get AFK_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_BROWSER_DEFAULT_PROFILE(){return process.env.AFK_BROWSER_DEFAULT_PROFILE},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let e of mr){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(S,e.name);n&&Object.defineProperty(S,e.name,{...n,enumerable:!1})}})()});function Yg(){return S.AFK_DEBUG==="1"||S.DEBUG==="1"}function M(...t){Yg()&&console.log(...t)}var Q=ge(()=>{"use strict";N()});import{existsSync as Ll,mkdirSync as bh,renameSync as wh,cpSync as Sh,rmSync as kh}from"fs";import{join as B,dirname as Qs,basename as vh,isAbsolute as Ul}from"path";import{homedir as $l}from"os";import{fileURLToPath as _h}from"url";function ae(){let t=S.AFK_HOME;if(t!==void 0&&t!==""){if(!Ul(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return B($l(),".afk")}function _e(){return B(ae(),"agent-framework")}function xr(){return B(_e(),"forge-telemetry.jsonl")}function Bl(){return B(_e(),"briefs")}function jl(){return B(_e(),"facets")}function an(){return B(ae(),"skills")}function Tt(){return B(ae(),"plugins")}function Hl(t=process.cwd()){return B(t,".afk")}function Wl(t=process.cwd()){return B(Hl(t),"skills")}function Kl(t=process.cwd()){return B(Hl(t),"plugins")}function Gl(t=process.cwd()){return B(t,".afk","plans")}function Tr(){return B(Tt(),".index.json")}function Zs(){return B(ln(),"schedules.json")}function ql(){let t=_h(import.meta.url),e=Qs(t);return B(e,"bundled-plugins")}function ln(){return B(ae(),"config")}function Fe(){let t=S.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!Ul(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return B(ae(),"state")}function le(){return B(Fe(),"sessions")}function Rr(){return B(Fe(),"presence")}function Ir(){return B(Fe(),"memory")}function Pr(){return B(Fe(),"session-grants.jsonl")}function zl(){return B(ae(),"farms")}function Jl(t){return B(zl(),t)}function Cr(t){if(!Eh.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function Vl(t){return Cr(t),B(Fe(),"witness",t)}function Yl(t){return!t||t.startsWith("in-memory:")?null:vh(Qs(t))}function Xl(t="default"){return B(Fe(),"daemon",`agent-afk@${t}`)}function Ql(){return B(Fe(),"worktree-sweep.lock")}function ei(){return B(ln(),"afk.env")}function Rt(){return B(ln(),"afk.config.json")}function Mr(){return B($l(),".afk.config.json")}function Ah(){return B(ae(),"sessions")}function xh(t,e){if(t!==e&&Ll(t)&&!Ll(e))try{bh(Qs(e),{recursive:!0});try{wh(t,e)}catch(n){if(n.code==="EXDEV")try{Sh(t,e,{recursive:!0}),kh(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
|
|
2
|
-
`)}}}catch{}}function Zl(){xh(Ah(),le())}function ti(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>Nl)throw new Error(`Invalid browser profile: exceeds ${Nl} chars`);if(!Th.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function Rh(){return B(Fe(),"browser")}function Ih(t){return ti(t),B(Rh(),t)}function ni(t){return B(Ih(t),"storageState.json")}function cn(t){return typeof t=="string"&&t.length>0&&t.length<=Ch&&Ph.test(t)}function dn(t){if(!cn(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return B(le(),t)}function Or(t){return B(dn(t),"events.jsonl")}function ec(t){return B(dn(t),"session.key")}var Eh,Th,Nl,Ph,Ch,U=ge(()=>{"use strict";N();Eh=/^[a-zA-Z0-9_-]+$/;Th=/^[A-Za-z0-9_-]+$/,Nl=128;Ph=/^[A-Za-z0-9_-]+$/,Ch=128});import{readFileSync as AS}from"node:fs";import{join as xS}from"path";function TS(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Ad(t,e){return TS(e).test(t)}function PS(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(RS.has(e))return!0;if(IS.has(e))return!1}return!1}function xd(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function CS(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 Td(t){let e=t===void 0||t.trim()===""?"default":t.trim();return ti(e),e}function MS(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function OS(t){try{return AS(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function DS(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 typeof e.defaultProfile=="string"&&(n.defaultProfile=Td(e.defaultProfile)),n}function Rd(t){let e=t?.env??S,n=t?.readFileSync??OS,r=t?.surface??e.AGENT_SURFACE,o=PS(e.AFK_BROWSER_HEADLESS,r),s=xd(e.AFK_BROWSER_ALLOWED_DOMAINS),i=xd(e.AFK_BROWSER_BLOCKED_DOMAINS),a=MS(e.AFK_BROWSER_DOM_SNAPSHOTS),l=CS(e.AFK_BROWSER_BACKEND),c=Td(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():xS(ln(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(h){throw new Error(`Failed to parse browser config at ${p}: ${String(h)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=DS(d,m);return g.configPath=p,g}function Oi(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(Ad(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Ad(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var RS,IS,Di=ge(()=>{"use strict";N();U();RS=new Set(["daemon","subagent","telegram","afk"]),IS=new Set(["repl","interactive","cli"])});import gt from"node:fs";import lo from"node:path";import{randomBytes as FS}from"node:crypto";import{chromium as LS}from"playwright";function NS(){try{return"5.35.3"}catch{}try{let t=lo.resolve(import.meta.dirname,"../../../package.json"),e=gt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var US,co,Id=ge(()=>{"use strict";U();Q();US=NS(),co=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=LS.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 r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}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}),l=await i.content(),c=i.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,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),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let 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/${US}`}}loadStorageState(e){let n=ni(e);try{if(!gt.existsSync(n))return;let r=JSON.parse(gt.readFileSync(n,"utf8"));return M("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){M("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=ni(e);if(!gt.existsSync(r))return;let o=await n.storageState(),s=lo.join(lo.dirname(r),`.${lo.basename(r)}.${process.pid}.${FS(4).toString("hex")}.tmp`);gt.writeFileSync(s,JSON.stringify(o),{mode:384}),gt.chmodSync(s,384),gt.renameSync(s,r),M("[browser/vault] saved session",{profile:e,file:r})}catch(r){M("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as $S}from"crypto";function Fi(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of BS)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function Pd(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&jS.test(t.label))}function Cd(t){return $S("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Md(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var BS,jS,Cn=ge(()=>{"use strict";BS=[{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}];jS=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as HS}from"node:crypto";function WS(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function KS(t,e,n){return`el_${HS("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function GS(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Od(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Fd(t,e){let n=t.role??"",r=t.name??"";Dd.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Fd(s,e)}async function qS(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(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},Ld).catch(()=>[])}async function zS(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")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)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,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},Ld).catch(()=>[])}function JS(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function uo(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=JS(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=qS(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,b=!1;u!==null?(h=[],Fd(u,h)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,h=(await zS(t)).filter(L=>Dd.has(L.role??"")));let _=new Map;for(let v of p){let L=Od(v.name),D=_.get(L);(!D||D.bbox.w===0&&v.bbox.w>0)&&_.set(L,v)}let A=h.map(v=>({ax:v,dom:_.get(Od(v.name??""))})),y=r?A:A.filter(v=>v.dom?v.dom.bbox.w>0||v.dom.bbox.h>0:!0);y.sort((v,L)=>{let D=v.dom?.bbox.y??0,x=L.dom?.bbox.y??0;if(D!==x)return D-x;let F=v.dom?.bbox.x??0,O=L.dom?.bbox.x??0;return F-O}),y.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=y.slice(0,n).map((v,L)=>{let D=v.ax.role??"generic",x=v.ax.name??"",F=KS(D,x,L),O=v.dom?.bbox??{x:0,y:0,w:0,h:0},I=v.dom?.type??null,j=null;v.ax.value!==void 0&&v.ax.value!==null&&(j=String(v.ax.value)),v.ax.checked!==void 0&&(j=String(v.ax.checked)),Pd({role:D,kind:I})&&(j="[redacted]");let R={disabled:v.ax.disabled??!1};v.ax.checked!==void 0&&(R.checked=v.ax.checked===!0||v.ax.checked==="mixed"),v.ax.selected!==void 0&&(R.selected=v.ax.selected),v.ax.expanded!==void 0&&(R.expanded=v.ax.expanded);let P;v.dom?.testId?P=`[data-testid="${v.dom.testId}"]`:v.dom?.id&&(P=`#${v.dom.id}`);let z={id:F,role:D,label:WS(x),kind:I,value:j,state:R,bbox:O};return P!==void 0&&(z.selector=P),z}),w="idle";try{let v=await t.evaluate(()=>document.readyState);v==="loading"?w="loading":v==="interactive"?w="navigating":w="idle"}catch{w="navigating"}w!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let C=GS(f),$=`obs_${e.observationCounter.toString(36)}`,G=new Date().toISOString();return{observationId:$,url:m,title:g,textSummary:C,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:w,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:G}}var Dd,Ld,Nd=ge(()=>{"use strict";Cn();Dd=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Ld="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Ud(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,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 Li(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Ud(t,s)))).filter(o=>o!==null)}async function VS(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 l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Ni(t,e,n){switch(e.kind){case"element_id":return YS(t,e,n);case"selector":return XS(t,e);case"semantic":return QS(t,e)}}async function YS(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 l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}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 Li(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function XS(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 Li(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function QS(t,e){return e.role!==void 0?ZS(t,e.text,e.role):ek(t,e.text,e)}async function ZS(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 Li(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function ek(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:s,count:l});let u=await VS(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let h=p[g];if(h===void 0)continue;let b=await Ud(h.locator,h.index);if(b!==null){let _=`${b.role}:${b.label}:${g}`,A=0;for(let y=0;y<_.length;y++)A=A*31+_.charCodeAt(y)>>>0;f.push({...b,id:`el_${A.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var $d=ge(()=>{"use strict"});import{randomBytes as tk}from"crypto";import{mkdir as nk,stat as rk,writeFile as ok}from"fs/promises";import{join as Ui}from"path";import{gzip as sk}from"zlib";import{promisify as ik}from"util";function ak(t){return Ui(Vl(t),"browser")}function lk(t){return Ui(ak(t),"screenshots")}function ck(){return new Date().toISOString().replace(/[:.]/g,"-")}function dk(){return tk(3).toString("hex")}async function $i(t,e,n){if(e.length>Bd)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Bd} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=lk(t);await nk(r,{recursive:!0});let o=`${ck()}-${dk()}-${n}.png`,s=Ui(r,o);await ok(s,e);let{size:i}=await rk(s);return{path:s,bytes:i}}var L0,Bd,jd=ge(()=>{"use strict";U();Cn();L0=ik(sk);Bd=5*1024*1024});var Wd={};al(Wd,{PlaywrightProvider:()=>Bi});function Hd(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 Bi,Kd=ge(()=>{"use strict";Id();Nd();$d();Di();Cn();jd();Bi=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new co(e)}async open(e){let n=Oi(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(c){a=c}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await uo(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(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 uo(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 Ni(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Hd(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":{let g=Fi(e.value??"");await l.fill(e.value??"");break}case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){c=h}else c=g}let u=r.url();if(u!==s){let g=Oi(u,this.config);if(!g.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:g.reason}}let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await uo(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;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 Ni(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Hd(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 $i(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,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 $i(n,o,r);return s}catch{return null}}}});var yt={};al(yt,{__resetBrowserRegistryForTests:()=>gk,browserProviderActive:()=>fk,closeBrowserProvider:()=>ji,getBrowserProvider:()=>pk,peekBrowserProvider:()=>mk});function Gd(){Promise.resolve(ji()).then(()=>{process.exit(130)})}function qd(){Promise.resolve(ji()).then(()=>{process.exit(143)})}function zd(){Ie=null}function uk(){po||(process.on("SIGINT",Gd),process.on("SIGTERM",qd),process.on("exit",zd),po=!0)}function Jd(){po&&(process.removeListener("SIGINT",Gd),process.removeListener("SIGTERM",qd),process.removeListener("exit",zd),po=!1)}async function pk(t){return Ie!==null?Ie:(ht!==null||(ht=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Kd(),Wd)),n=Rd(t),r=new e(n);return uk(),Ie=r,ht=null,r})()),ht)}async function ji(){if(Ie===null)return;let t=Ie;Ie=null,ht=null,Jd(),await t.shutdown()}function fk(){return Ie!==null}function mk(){return Ie}function gk(){Ie=null,ht=null,Jd()}var Ie,ht,po,bt=ge(()=>{"use strict";Di();Ie=null,ht=null,po=!1});Q();var ue=class extends Error{constructor(e){super(e),this.name="AbortError"}},qe=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},H=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},vt=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};Q();async function _t(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){M(`trace.emit tool_call failed: ${De(n)}`)}}async function Oe(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){M(`trace.emit hook_decision failed: ${De(n)}`)}}async function at(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){M(`trace.emit subagent_lifecycle failed: ${De(n)}`)}}async function ll(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){M(`trace.emit budget failed: ${De(n)}`)}}async function cl(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){M(`trace.emit abort failed: ${De(n)}`)}}async function hr(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){M(`trace.emit compaction failed: ${De(n)}`)}}async function dl(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){M(`trace.emit closure failed: ${De(n)}`)}}async function ne(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){M(`trace.emit browser_event failed: ${De(n)}`)}}async function Z(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){M(`trace.emit session_phase failed: ${De(n)}`)}}function De(t){return t instanceof Error?t.message:String(t)}import Tm from"@anthropic-ai/sdk";var ul="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",Xg="effort-2025-11-24",Qg="claude-cli/1.0.0 (external, cli)",Zg="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function yr(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function on(t,e,n,r){let o=e==="oauth"?{authToken:t}:{apiKey:t},s=typeof n=="string"&&n.length>0?{...o,baseURL:n}:o;return r?{...s,fetch:r}:s}function he(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${ul},${Xg}`:ul,"x-app":"cli","User-Agent":Qg,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function pl(t){return t!=="oauth"?null:[{type:"text",text:Zg}]}import rh from"@anthropic-ai/sdk";N();var wr=["local","small","medium","large"],lt={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-5"},large:{id:"claude-opus-4-8"}},ml={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},gl="auto",Hs="claude-fable-5",hl={fable:Hs},js;function Ws(t){js=t}function Bs(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function br(t,e,n){let r={},o=Bs(t);o&&(r.id=o);let s=Bs(e);s&&(r.baseUrl=s);let i=Bs(n);return i&&(r.apiKey=i),r}function eh(){return{local:br(S.AFK_MODEL_LOCAL,S.AFK_MODEL_LOCAL_BASE_URL,S.AFK_MODEL_LOCAL_API_KEY),small:br(S.AFK_MODEL_SMALL,S.AFK_MODEL_SMALL_BASE_URL,S.AFK_MODEL_SMALL_API_KEY),medium:br(S.AFK_MODEL_MEDIUM,S.AFK_MODEL_MEDIUM_BASE_URL,S.AFK_MODEL_MEDIUM_API_KEY),large:br(S.AFK_MODEL_LARGE,S.AFK_MODEL_LARGE_BASE_URL,S.AFK_MODEL_LARGE_API_KEY)}}function yl(t){let e=eh(),n={};for(let r of wr){let o=lt[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},l=s?.name;l&&(a.name=l);let c=s?.provider;c&&(a.provider=c);let 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 At(t){return t||js||yl()}function xt(t,e=At()){let n=t.trim().toLowerCase();if(!n||n===gl)return;for(let o of wr){let s=e[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:ml[n]}function Ks(t,e=At()){if(t===void 0)return{id:""};let n=xt(t,e);if(n)return e[n];let r=hl[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function ze(t,e=At()){if(t!==void 0)return Ks(t,e).id}function bl(t,e=At()){if(t===void 0)return;let n=xt(t,e);if(n&&e[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function wl(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of wr){let o=nh(n[r]);o&&(e[r]=o)}return e}function Sl(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 Et(t){return typeof t=="string"?t.trim():""}function fl(t){return/[\x00-\x1f\x7f]/.test(t)}var th=new Set([...wr,...Object.keys(ml),gl,...Object.keys(hl)]);function nh(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=Et(e.id);if(!n)return;let r={id:n},o=Et(e.name);o&&(r.name=o);let s=Sl(e.provider);s&&(r.provider=s);let i=Et(e.baseUrl);i&&(r.baseUrl=i);let a=Et(e.apiKey);return a&&(r.apiKey=a),r}}function kl(t){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:'model binding must be an object with at least an "id"'};let e=t;if("apiKey"in e||"api_key"in e)return{ok:!1,error:"per-slot API keys are credentials; set AFK_MODEL_<TIER>_API_KEY via `afk config env set` instead of afk.config.json"};if("baseUrl"in e||"base_url"in e)return{ok:!1,error:"per-slot baseUrl is an endpoint-redirect credential vector; set AFK_MODEL_<TIER>_BASE_URL via `afk config env set` instead of afk.config.json"};let n=Et(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(fl(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=Et(e.name);if(o){if(fl(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(th.has(o.trim().toLowerCase()))return{ok:!1,error:`model binding "name" must not shadow a built-in alias ("${o}")`};r.name=o}if(e.provider!==void 0&&e.provider!==""){let s=Sl(e.provider);if(!s)return{ok:!1,error:'model binding "provider" must be one of: anthropic, openai (aliases: anthropic-direct, openai-compatible)'};r.provider=s}return{ok:!0,value:r}}var Gs={opus:lt.large.id,opus_1m:lt.large.id,sonnet:lt.medium.id,sonnet_1m:lt.medium.id,haiku:lt.small.id,fable:Hs};function Sr(t){return t in Gs}function se(t){return ze(t)}import{randomUUID as vl}from"node:crypto";async function _l(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 l=yr(e),c=on(e,l),d=a?a(c):new rh(c),u=vl(),p=vl(),f=he(l,u,p),m=se(n)??n,g={};Object.keys(f).length>0&&(g.headers=f),i&&(g.signal=i);let h=await d.messages.create({model:m,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(g).length>0?g:void 0),b=[];for(let A of h.content)A.type==="text"&&b.push(A.text);let _=b.join("").trim();return _.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),_}import{execFileSync as El}from"child_process";import{existsSync as oh,readFileSync as sh,writeFileSync as ih}from"fs";import{homedir as Al,userInfo as xl}from"os";import{join as Tl}from"path";var ah="9d1c250a-e61b-44d9-88ed-5944d1962f5e",lh="https://platform.claude.com/v1/oauth/token",ch=300*1e3;function ye(){let t=Rl();if(t===void 0)return;let e=Il(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 qs(){let t=Rl();if(t===void 0)return;let e=Il(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+ch)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 dh(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}:{}},uh(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
2
|
+
`)}}}catch{}}function Zl(){xh(Ah(),le())}function ti(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>Nl)throw new Error(`Invalid browser profile: exceeds ${Nl} chars`);if(!Th.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function Rh(){return B(Fe(),"browser")}function Ih(t){return ti(t),B(Rh(),t)}function ni(t){return B(Ih(t),"storageState.json")}function cn(t){return typeof t=="string"&&t.length>0&&t.length<=Ch&&Ph.test(t)}function dn(t){if(!cn(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return B(le(),t)}function Or(t){return B(dn(t),"events.jsonl")}function ec(t){return B(dn(t),"session.key")}var Eh,Th,Nl,Ph,Ch,U=ge(()=>{"use strict";N();Eh=/^[a-zA-Z0-9_-]+$/;Th=/^[A-Za-z0-9_-]+$/,Nl=128;Ph=/^[A-Za-z0-9_-]+$/,Ch=128});import{readFileSync as AS}from"node:fs";import{join as xS}from"path";function TS(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Ad(t,e){return TS(e).test(t)}function PS(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(RS.has(e))return!0;if(IS.has(e))return!1}return!1}function xd(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function CS(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 Td(t){let e=t===void 0||t.trim()===""?"default":t.trim();return ti(e),e}function MS(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function OS(t){try{return AS(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function DS(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 typeof e.defaultProfile=="string"&&(n.defaultProfile=Td(e.defaultProfile)),n}function Rd(t){let e=t?.env??S,n=t?.readFileSync??OS,r=t?.surface??e.AGENT_SURFACE,o=PS(e.AFK_BROWSER_HEADLESS,r),s=xd(e.AFK_BROWSER_ALLOWED_DOMAINS),i=xd(e.AFK_BROWSER_BLOCKED_DOMAINS),a=MS(e.AFK_BROWSER_DOM_SNAPSHOTS),l=CS(e.AFK_BROWSER_BACKEND),c=Td(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():xS(ln(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(h){throw new Error(`Failed to parse browser config at ${p}: ${String(h)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=DS(d,m);return g.configPath=p,g}function Oi(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(Ad(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Ad(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var RS,IS,Di=ge(()=>{"use strict";N();U();RS=new Set(["daemon","subagent","telegram","afk"]),IS=new Set(["repl","interactive","cli"])});import gt from"node:fs";import lo from"node:path";import{randomBytes as FS}from"node:crypto";import{chromium as LS}from"playwright";function NS(){try{return"5.36.1"}catch{}try{let t=lo.resolve(import.meta.dirname,"../../../package.json"),e=gt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var US,co,Id=ge(()=>{"use strict";U();Q();US=NS(),co=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=LS.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 r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}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}),l=await i.content(),c=i.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,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),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let 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/${US}`}}loadStorageState(e){let n=ni(e);try{if(!gt.existsSync(n))return;let r=JSON.parse(gt.readFileSync(n,"utf8"));return M("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){M("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=ni(e);if(!gt.existsSync(r))return;let o=await n.storageState(),s=lo.join(lo.dirname(r),`.${lo.basename(r)}.${process.pid}.${FS(4).toString("hex")}.tmp`);gt.writeFileSync(s,JSON.stringify(o),{mode:384}),gt.chmodSync(s,384),gt.renameSync(s,r),M("[browser/vault] saved session",{profile:e,file:r})}catch(r){M("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as $S}from"crypto";function Fi(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of BS)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function Pd(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&jS.test(t.label))}function Cd(t){return $S("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Md(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var BS,jS,Cn=ge(()=>{"use strict";BS=[{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}];jS=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as HS}from"node:crypto";function WS(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function KS(t,e,n){return`el_${HS("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function GS(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Od(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Fd(t,e){let n=t.role??"",r=t.name??"";Dd.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Fd(s,e)}async function qS(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(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},Ld).catch(()=>[])}async function zS(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")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)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,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},Ld).catch(()=>[])}function JS(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function uo(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=JS(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=qS(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,b=!1;u!==null?(h=[],Fd(u,h)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,h=(await zS(t)).filter(L=>Dd.has(L.role??"")));let _=new Map;for(let v of p){let L=Od(v.name),D=_.get(L);(!D||D.bbox.w===0&&v.bbox.w>0)&&_.set(L,v)}let A=h.map(v=>({ax:v,dom:_.get(Od(v.name??""))})),y=r?A:A.filter(v=>v.dom?v.dom.bbox.w>0||v.dom.bbox.h>0:!0);y.sort((v,L)=>{let D=v.dom?.bbox.y??0,x=L.dom?.bbox.y??0;if(D!==x)return D-x;let F=v.dom?.bbox.x??0,O=L.dom?.bbox.x??0;return F-O}),y.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=y.slice(0,n).map((v,L)=>{let D=v.ax.role??"generic",x=v.ax.name??"",F=KS(D,x,L),O=v.dom?.bbox??{x:0,y:0,w:0,h:0},I=v.dom?.type??null,j=null;v.ax.value!==void 0&&v.ax.value!==null&&(j=String(v.ax.value)),v.ax.checked!==void 0&&(j=String(v.ax.checked)),Pd({role:D,kind:I})&&(j="[redacted]");let R={disabled:v.ax.disabled??!1};v.ax.checked!==void 0&&(R.checked=v.ax.checked===!0||v.ax.checked==="mixed"),v.ax.selected!==void 0&&(R.selected=v.ax.selected),v.ax.expanded!==void 0&&(R.expanded=v.ax.expanded);let P;v.dom?.testId?P=`[data-testid="${v.dom.testId}"]`:v.dom?.id&&(P=`#${v.dom.id}`);let z={id:F,role:D,label:WS(x),kind:I,value:j,state:R,bbox:O};return P!==void 0&&(z.selector=P),z}),w="idle";try{let v=await t.evaluate(()=>document.readyState);v==="loading"?w="loading":v==="interactive"?w="navigating":w="idle"}catch{w="navigating"}w!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let C=GS(f),$=`obs_${e.observationCounter.toString(36)}`,G=new Date().toISOString();return{observationId:$,url:m,title:g,textSummary:C,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:w,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:G}}var Dd,Ld,Nd=ge(()=>{"use strict";Cn();Dd=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Ld="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Ud(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,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 Li(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Ud(t,s)))).filter(o=>o!==null)}async function VS(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 l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Ni(t,e,n){switch(e.kind){case"element_id":return YS(t,e,n);case"selector":return XS(t,e);case"semantic":return QS(t,e)}}async function YS(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 l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}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 Li(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function XS(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 Li(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function QS(t,e){return e.role!==void 0?ZS(t,e.text,e.role):ek(t,e.text,e)}async function ZS(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 Li(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function ek(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:s,count:l});let u=await VS(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let h=p[g];if(h===void 0)continue;let b=await Ud(h.locator,h.index);if(b!==null){let _=`${b.role}:${b.label}:${g}`,A=0;for(let y=0;y<_.length;y++)A=A*31+_.charCodeAt(y)>>>0;f.push({...b,id:`el_${A.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var $d=ge(()=>{"use strict"});import{randomBytes as tk}from"crypto";import{mkdir as nk,stat as rk,writeFile as ok}from"fs/promises";import{join as Ui}from"path";import{gzip as sk}from"zlib";import{promisify as ik}from"util";function ak(t){return Ui(Vl(t),"browser")}function lk(t){return Ui(ak(t),"screenshots")}function ck(){return new Date().toISOString().replace(/[:.]/g,"-")}function dk(){return tk(3).toString("hex")}async function $i(t,e,n){if(e.length>Bd)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Bd} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=lk(t);await nk(r,{recursive:!0});let o=`${ck()}-${dk()}-${n}.png`,s=Ui(r,o);await ok(s,e);let{size:i}=await rk(s);return{path:s,bytes:i}}var L0,Bd,jd=ge(()=>{"use strict";U();Cn();L0=ik(sk);Bd=5*1024*1024});var Wd={};al(Wd,{PlaywrightProvider:()=>Bi});function Hd(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 Bi,Kd=ge(()=>{"use strict";Id();Nd();$d();Di();Cn();jd();Bi=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new co(e)}async open(e){let n=Oi(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(c){a=c}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await uo(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(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 uo(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 Ni(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Hd(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":{let g=Fi(e.value??"");await l.fill(e.value??"");break}case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){c=h}else c=g}let u=r.url();if(u!==s){let g=Oi(u,this.config);if(!g.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:g.reason}}let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await uo(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;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 Ni(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Hd(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 $i(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,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 $i(n,o,r);return s}catch{return null}}}});var yt={};al(yt,{__resetBrowserRegistryForTests:()=>gk,browserProviderActive:()=>fk,closeBrowserProvider:()=>ji,getBrowserProvider:()=>pk,peekBrowserProvider:()=>mk});function Gd(){Promise.resolve(ji()).then(()=>{process.exit(130)})}function qd(){Promise.resolve(ji()).then(()=>{process.exit(143)})}function zd(){Ie=null}function uk(){po||(process.on("SIGINT",Gd),process.on("SIGTERM",qd),process.on("exit",zd),po=!0)}function Jd(){po&&(process.removeListener("SIGINT",Gd),process.removeListener("SIGTERM",qd),process.removeListener("exit",zd),po=!1)}async function pk(t){return Ie!==null?Ie:(ht!==null||(ht=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Kd(),Wd)),n=Rd(t),r=new e(n);return uk(),Ie=r,ht=null,r})()),ht)}async function ji(){if(Ie===null)return;let t=Ie;Ie=null,ht=null,Jd(),await t.shutdown()}function fk(){return Ie!==null}function mk(){return Ie}function gk(){Ie=null,ht=null,Jd()}var Ie,ht,po,bt=ge(()=>{"use strict";Di();Ie=null,ht=null,po=!1});Q();var ue=class extends Error{constructor(e){super(e),this.name="AbortError"}},qe=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},H=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},vt=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};Q();async function _t(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){M(`trace.emit tool_call failed: ${De(n)}`)}}async function Oe(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){M(`trace.emit hook_decision failed: ${De(n)}`)}}async function at(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){M(`trace.emit subagent_lifecycle failed: ${De(n)}`)}}async function ll(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){M(`trace.emit budget failed: ${De(n)}`)}}async function cl(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){M(`trace.emit abort failed: ${De(n)}`)}}async function hr(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){M(`trace.emit compaction failed: ${De(n)}`)}}async function dl(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){M(`trace.emit closure failed: ${De(n)}`)}}async function ne(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){M(`trace.emit browser_event failed: ${De(n)}`)}}async function Z(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){M(`trace.emit session_phase failed: ${De(n)}`)}}function De(t){return t instanceof Error?t.message:String(t)}import Tm from"@anthropic-ai/sdk";var ul="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",Xg="effort-2025-11-24",Qg="claude-cli/1.0.0 (external, cli)",Zg="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function yr(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function on(t,e,n,r){let o=e==="oauth"?{authToken:t}:{apiKey:t},s=typeof n=="string"&&n.length>0?{...o,baseURL:n}:o;return r?{...s,fetch:r}:s}function he(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${ul},${Xg}`:ul,"x-app":"cli","User-Agent":Qg,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function pl(t){return t!=="oauth"?null:[{type:"text",text:Zg}]}import rh from"@anthropic-ai/sdk";N();var wr=["local","small","medium","large"],lt={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-5"},large:{id:"claude-opus-4-8"}},ml={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},gl="auto",Hs="claude-fable-5",hl={fable:Hs},js;function Ws(t){js=t}function Bs(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function br(t,e,n){let r={},o=Bs(t);o&&(r.id=o);let s=Bs(e);s&&(r.baseUrl=s);let i=Bs(n);return i&&(r.apiKey=i),r}function eh(){return{local:br(S.AFK_MODEL_LOCAL,S.AFK_MODEL_LOCAL_BASE_URL,S.AFK_MODEL_LOCAL_API_KEY),small:br(S.AFK_MODEL_SMALL,S.AFK_MODEL_SMALL_BASE_URL,S.AFK_MODEL_SMALL_API_KEY),medium:br(S.AFK_MODEL_MEDIUM,S.AFK_MODEL_MEDIUM_BASE_URL,S.AFK_MODEL_MEDIUM_API_KEY),large:br(S.AFK_MODEL_LARGE,S.AFK_MODEL_LARGE_BASE_URL,S.AFK_MODEL_LARGE_API_KEY)}}function yl(t){let e=eh(),n={};for(let r of wr){let o=lt[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},l=s?.name;l&&(a.name=l);let c=s?.provider;c&&(a.provider=c);let 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 At(t){return t||js||yl()}function xt(t,e=At()){let n=t.trim().toLowerCase();if(!n||n===gl)return;for(let o of wr){let s=e[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:ml[n]}function Ks(t,e=At()){if(t===void 0)return{id:""};let n=xt(t,e);if(n)return e[n];let r=hl[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function ze(t,e=At()){if(t!==void 0)return Ks(t,e).id}function bl(t,e=At()){if(t===void 0)return;let n=xt(t,e);if(n&&e[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function wl(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of wr){let o=nh(n[r]);o&&(e[r]=o)}return e}function Sl(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 Et(t){return typeof t=="string"?t.trim():""}function fl(t){return/[\x00-\x1f\x7f]/.test(t)}var th=new Set([...wr,...Object.keys(ml),gl,...Object.keys(hl)]);function nh(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=Et(e.id);if(!n)return;let r={id:n},o=Et(e.name);o&&(r.name=o);let s=Sl(e.provider);s&&(r.provider=s);let i=Et(e.baseUrl);i&&(r.baseUrl=i);let a=Et(e.apiKey);return a&&(r.apiKey=a),r}}function kl(t){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:'model binding must be an object with at least an "id"'};let e=t;if("apiKey"in e||"api_key"in e)return{ok:!1,error:"per-slot API keys are credentials; set AFK_MODEL_<TIER>_API_KEY via `afk config env set` instead of afk.config.json"};if("baseUrl"in e||"base_url"in e)return{ok:!1,error:"per-slot baseUrl is an endpoint-redirect credential vector; set AFK_MODEL_<TIER>_BASE_URL via `afk config env set` instead of afk.config.json"};let n=Et(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(fl(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=Et(e.name);if(o){if(fl(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(th.has(o.trim().toLowerCase()))return{ok:!1,error:`model binding "name" must not shadow a built-in alias ("${o}")`};r.name=o}if(e.provider!==void 0&&e.provider!==""){let s=Sl(e.provider);if(!s)return{ok:!1,error:'model binding "provider" must be one of: anthropic, openai (aliases: anthropic-direct, openai-compatible)'};r.provider=s}return{ok:!0,value:r}}var Gs={opus:lt.large.id,opus_1m:lt.large.id,sonnet:lt.medium.id,sonnet_1m:lt.medium.id,haiku:lt.small.id,fable:Hs};function Sr(t){return t in Gs}function se(t){return ze(t)}import{randomUUID as vl}from"node:crypto";async function _l(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 l=yr(e),c=on(e,l),d=a?a(c):new rh(c),u=vl(),p=vl(),f=he(l,u,p),m=se(n)??n,g={};Object.keys(f).length>0&&(g.headers=f),i&&(g.signal=i);let h=await d.messages.create({model:m,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(g).length>0?g:void 0),b=[];for(let A of h.content)A.type==="text"&&b.push(A.text);let _=b.join("").trim();return _.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),_}import{execFileSync as El}from"child_process";import{existsSync as oh,readFileSync as sh,writeFileSync as ih}from"fs";import{homedir as Al,userInfo as xl}from"os";import{join as Tl}from"path";var ah="9d1c250a-e61b-44d9-88ed-5944d1962f5e",lh="https://platform.claude.com/v1/oauth/token",ch=300*1e3;function ye(){let t=Rl();if(t===void 0)return;let e=Il(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 qs(){let t=Rl();if(t===void 0)return;let e=Il(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+ch)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 dh(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}:{}},uh(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 Rl(){if(process.platform==="darwin")try{return El("security",["find-generic-password","-s","Claude Code-credentials","-a",xl().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=Tl(Al(),".claude",".credentials.json");if(!oh(t))return;try{return sh(t,"utf-8")}catch{return}}}function Il(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 dh(t){try{let e=await fetch(lh,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:ah})});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 sn(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 uh(t){if(process.platform==="darwin")El("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",xl().username,"-w",t],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let e=Tl(Al(),".claude",".credentials.json");ph(e,t)}}function ph(t,e){ih(t,e,{encoding:"utf-8",mode:384})}function oe(t,e){if(t===null||typeof t!="object")return;let n=t.headers;if(n==null)return;if(typeof n.get=="function")return n.get(e)??void 0;if(typeof n=="object"){let o=n,s=o[e]??o[e.toUpperCase()];return typeof s=="string"?s:void 0}}function ct(t){let e=oe(t,"retry-after-ms");if(e!==void 0){let r=Number(e);if(Number.isFinite(r)&&r>=0)return r}let n=oe(t,"retry-after");if(n!==void 0){let r=Number(n);if(Number.isFinite(r)&&r>=0)return Math.round(r*1e3);let o=Date.parse(n);if(!Number.isNaN(o)){let s=o-Date.now();if(s>=0)return s}}}var fh=300*1e3;var mh=864e13;function Pl(t){if(!Number.isFinite(t)||t<=0)return;let e=t*1e3;if(!(e>mh))return new Date(e)}function kr(t){if(!("status"in t))return null;let e=t.status;if(e===429){let n=t.message.split("|");if(n.length>=2){let l=Pl(parseInt(n[1].trim(),10));if(l!==void 0)return{kind:"oauth-limit",resetsAt:l}}let r=oe(t,"anthropic-ratelimit-unified-representative-claim"),o=oe(t,"anthropic-ratelimit-unified-overage-status"),s=oe(t,"anthropic-ratelimit-unified-status");if(r!==void 0||o!==void 0||s==="rejected"){let l=oe(t,"anthropic-ratelimit-unified-reset");if(l!==void 0){let c=Pl(Number(l));if(c!==void 0)return{kind:"oauth-limit",resetsAt:c}}return{kind:"oauth-limit-no-ts"}}if(oe(t,"anthropic-ratelimit-requests-remaining")!==void 0||oe(t,"anthropic-ratelimit-requests-limit")!==void 0||oe(t,"anthropic-ratelimit-requests-reset")!==void 0||oe(t,"anthropic-ratelimit-input-tokens-remaining")!==void 0||oe(t,"anthropic-ratelimit-input-tokens-limit")!==void 0||oe(t,"anthropic-ratelimit-input-tokens-reset")!==void 0||oe(t,"anthropic-ratelimit-output-tokens-remaining")!==void 0||oe(t,"anthropic-ratelimit-output-tokens-limit")!==void 0||oe(t,"anthropic-ratelimit-output-tokens-reset")!==void 0)return{kind:"rate-limit-transient",retryAfterMs:ct(t)};let a=ct(t);return a!==void 0&&a<=fh?{kind:"rate-limit-transient",retryAfterMs:a}:{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 Cl(t){let{resetsAt:e,signal:n,readToken:r=ye}=t,o=r(),s=e.getTime()+3e4;return new Promise(i=>{let a,l=!1,c=p=>{l||(l=!0,a!==void 0&&clearInterval(a),n.removeEventListener("abort",d),i(p))},d=()=>{c("aborted")},u=()=>n.aborted?(c("aborted"),!0):Date.now()>=s?(c("timer"),!0):r()!==o?(c("hot-swap"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),n.addEventListener("abort",d,{once:!0}))})}async function Ml(t){let{signal:e,readToken:n=ye,retryAfterMs:r}=t,o=n(),s=r!==void 0?Date.now()+r:void 0;return new Promise(i=>{let a,l=!1,c=p=>{l||(l=!0,a!==void 0&&clearInterval(a),e.removeEventListener("abort",d),i(p))},d=()=>{c("aborted")},u=()=>e.aborted?(c("aborted"),!0):n()!==o?(c("hot-swap"),!0):s!==void 0&&Date.now()>=s?(c("timer"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),e.addEventListener("abort",d,{once:!0}))})}var gh=new Set([429,503,529]);function zs(t,e=fetch){return t?async(n,r)=>{let o=await e(n,r);if(gh.has(o.status)){let s=ct({headers:o.headers}),i={status:o.status,reason:o.status===429?"rate-limit":"overloaded",source:"sdk-fetch"};s!==void 0&&(i.retryAfterMs=s),Z(t,{phase:"rate_limit",...s!==void 0?{durationMs:s}:{},metadata:i})}return o}:e}import{randomUUID as Sm}from"node:crypto";function ve(t){return t==="bypassPermissions"||t==="autonomous"}N();var hh="1h";function vr(t){if(typeof t?.baseUrl=="string"&&t.baseUrl.length>0)return!1;let e=S.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 _r(){let t=S.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":t==="1h"?"1h":hh}function Ol(t,e){if(t.length===0)return t;let n=t[t.length-1],r=Fl(n,e);return r===n?t:[...t.slice(0,-1),r]}function Dl(t,e){if(t.length===0)return t;let n=t[t.length-1],r=yh(n,e);return r===n?t:[...t.slice(0,-1),r]}function yh(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=Fl(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function Fl(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}var Er=["## Plan mode is active","","File and memory write tools (`write_file`, `edit_file`, `memory_update`, `procedure_write`) are refused at the hook layer.","`bash` runs for read-only investigation (git status/log/diff, ls, cat, grep, find \u2014 chained or not); state-mutating bash (file writes, rm, installs, commits, pushes) is refused while planning. The user has asked you to plan, not yet to act \u2014 exit plan mode to make changes.","Treat this turn as planning work.","","Traverse the shape that matches the work \u2014 skip steps the terrain already covers, do not skip steps the terrain hides:",""," unknown field \u2192 ground the current terrain \u2192 gather missing codebase context \u2192"," research missing external context \u2192 reveal chaos / constraints / risks \u2192"," name the failure geometry \u2192 form a candidate plan \u2192 apply adversarial pressure \u2192 embody the final plan","","Reach for these skills (invoke via the `skill` tool) when the cost of skipping exceeds the cost of dispatching:"," - `ground-state` \u2014 survey git, infra, memory before non-trivial work"," - `gather` \u2014 parallel context-gathering for a code area"," - `research` \u2014 parallel external + local context for the current task"," - `devils-advocate` \u2014 generate alternatives and rank them before committing"," - `shadow-verify` \u2014 independently re-derive load-bearing claims","","Do not declare readiness silently. When the plan is ready, state: chosen approach, risks named, and alternatives considered.","","Then, IF the task requires implementation (writing code or files), call the `exit_plan_mode` tool to present your plan. The user picks how to proceed (approve and implement, or keep planning). After calling it, END YOUR TURN \u2014 on approval you will receive a separate instruction to save the plan to a file and implement it. Do NOT use `ask_question` to ask whether the plan is OK; that is exactly what `exit_plan_mode` does \u2014 use `ask_question` only to resolve open requirement questions first. For research / read-only tasks that need no code changes, do NOT call `exit_plan_mode` \u2014 just answer.","","Manual fallbacks remain: the user can exit with `/plan off` (same save-and-implement handoff), and Shift+Tab advances the permission-mode ring without saving or implementing. Keep the plan concrete and complete enough to act on directly."].join(`
|
|
4
4
|
`);function Js(t){return t!=="plan"?null:{type:"text",text:Er}}var Ar=["## AFK mode is active","","The operator is away from keyboard. Your channel to them is Telegram via the `send_telegram` tool \u2014 not this transcript, which no one is watching live. At the end of each turn, push your terminal state (Done / Blocked / Asking) to Telegram so the operator can review asynchronously.","","Posture \u2014 bounded autonomy, not unchecked action:"," - Proceed autonomously on reversible work. Do not stop to confirm actions you are already authorized to take and can undo (edits, reads, tests, local commits, non-force pushes, installs)."," - At a one-way door \u2014 anything irreversible, externally visible, credential- or payment-touching, or where multiple readings lead to materially different work \u2014 do NOT guess. Push a concise Asking summary to Telegram naming the decision and your recommended default, then stop and end the turn in the Asking state."," - A mechanical gate refuses high-risk and irreversible operations at the hook layer regardless of this text. Treat a gate refusal as a signal to surface the decision to the operator, not an obstacle to work around.","","Communication discipline:"," - Batch updates. Send a Telegram message at terminal state (and at a genuinely blocking fork), not a play-by-play \u2014 the operator gets a push notification for every message."," - Keep pushes short and scannable: what happened, what changed, what (if anything) you need. Never paste raw tool output, logs, secrets, or full file contents into a push.","","Exit: the operator returns and runs `/afk off` (or Shift+Tab) to restore default permissions and terminal-channel interaction."].join(`
|
|
5
5
|
`);function Vs(t){return t!=="autonomous"?null:{type:"text",text:Ar}}function Ys(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 Xs(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{config as XI}from"dotenv";U();N();function tc(){return S.ANTHROPIC_API_KEY||S.CLAUDE_CODE_OAUTH_TOKEN||ye()}function nc(){return S.OPENAI_API_KEY||S.CODEX_API_KEY||void 0}function X(t){let e=V(t);return e==="openai-compatible"||e==="openai-codex"?nc():tc()}N();import{readFileSync as Uh,existsSync as $h}from"fs";import{join as dc}from"path";U();N();import{execFile as Mh}from"node:child_process";import{promisify as Oh}from"node:util";N();U();N();var wP=Oh(Mh);var Dh=/^[A-Za-z0-9_\-./]*$/,rc=64;function oc(t,e){if(t.length>rc)throw new Error(`Invalid branch prefix from ${e}: length ${t.length} exceeds ${rc}.`);if(!Dh.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 sc(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.`)}U();import{existsSync as pn,readdirSync as vP,readFileSync as ic,realpathSync as _P,statSync as EP}from"fs";import{homedir as ac}from"os";import{join as Le}from"path";var lc=["claude-code","codex"],un=new Map,Dr={"claude-code":{label:"Claude Code",pluginRoots:t=>[Le(t,".claude","plugins")],skillRoots:t=>[Le(t,".claude","skills")],mcpConfigCandidates:t=>[Le(t,".claude","mcp.json"),Le(t,".claude",".mcp.json"),Le(t,".claude","claude-code","mcp.json")],mcpFormat:"json",pluginEnabledState:t=>Nh(t)},codex:{label:"Codex",pluginRoots:t=>[Le(t,".codex","plugins")],skillRoots:t=>[Le(t,".codex","skills")],mcpConfigCandidates:t=>[Le(t,".codex","config.toml")],mcpFormat:"toml",pluginEnabledState:()=>un}},RP={"claude-code":Dr["claude-code"].label,codex:Dr.codex.label};function ri(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e={};for(let n of lc){let r=t[n];if(r!==void 0){if(r===!0){e[n]={plugins:!0,skills:!0,mcp:!0};continue}if(r!==!1&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=r;e[n]={plugins:o.plugins===!0,skills:o.skills===!0,mcp:o.mcp===!0}}}}return Object.keys(e).length>0?e:void 0}function Fh(){return[Rt(),Mr()]}function oi(t=Fh()){for(let e of t)if(pn(e))try{let n=JSON.parse(ic(e,"utf-8")),r=ri(n.importFrom);if(r!==void 0)return r}catch{}}function si(t,e=ac()){let n={pluginRoots:[],skillRoots:[],mcpConfigs:[]};if(!t)return n;for(let r of lc){let o=t[r];if(!o)continue;let s=Dr[r];if(o.plugins)for(let i of s.pluginRoots(e))pn(i)&&n.pluginRoots.push({dir:i,binary:r});if(o.skills){let i=`imported:${r}`;for(let a of s.skillRoots(e))pn(a)&&n.skillRoots.push({dir:a,origin:i})}if(o.mcp){let i=Lh(s.mcpConfigCandidates(e));i&&n.mcpConfigs.push({source:i,format:s.mcpFormat})}}return n}function cc(t,e=ac()){return Dr[t].pluginEnabledState(e)}function Lh(t){for(let e of t)if(pn(e))return e;return null}function Nh(t){let e=Le(t,".claude","settings.json");if(!pn(e))return un;let n;try{n=JSON.parse(ic(e,"utf-8"))}catch{return un}if(!n||typeof n!="object")return un;let r=n.enabledPlugins;if(!r||typeof r!="object"||Array.isArray(r))return un;let o=new Map;for(let[s,i]of Object.entries(r))typeof i=="boolean"&&o.set(s,i);return o}var It;function uc(){if(It!==void 0)return It;let t=[dc(process.cwd(),"afk.config.json"),Rt(),Mr()];for(let e of t)if($h(e))try{let n=Uh(e,"utf-8"),r=JSON.parse(n),o={},s=wl(r.models);if(typeof r.model=="string"&&r.model.length>0){let i=r.model.toLowerCase();o.model=Sr(i)?i:r.model}if(typeof r.maxTokens=="number"&&(o.maxTokens=r.maxTokens),typeof r.temperature=="number"&&(o.temperature=r.temperature),typeof r.systemPrompt=="string"&&r.systemPrompt.length>0&&(o.systemPrompt=r.systemPrompt),typeof r.permissionMode=="string"){let i=r.permissionMode;(i==="default"||i==="plan"||i==="autonomous"||i==="bypassPermissions")&&(o.permissionMode=i)}if(r.autoRouting&&typeof r.autoRouting=="object"){let i={};typeof r.autoRouting.interactive=="boolean"&&(i.interactive=r.autoRouting.interactive),typeof r.autoRouting.chat=="boolean"&&(i.chat=r.autoRouting.chat),typeof r.autoRouting.telegram=="boolean"&&(i.telegram=r.autoRouting.telegram),typeof r.autoRouting.daemon=="boolean"&&(i.daemon=r.autoRouting.daemon),o.autoRouting=i}if(r.daemon&&typeof r.daemon=="object"){let i={};typeof r.daemon.task=="string"&&(i.task=r.daemon.task),typeof r.daemon.taskId=="string"&&(i.taskId=r.daemon.taskId);let a=r.daemon.worktreePrune;a&&typeof a=="object"&&(i.worktreePrune={enabled:typeof a.enabled=="boolean"?a.enabled:!0,cron:typeof a.cron=="string"?a.cron:"0 4 * * *",maxAgeDaysClean:typeof a.maxAgeDaysClean=="number"?a.maxAgeDaysClean:14,maxAgeDaysDirty:typeof a.maxAgeDaysDirty=="number"?a.maxAgeDaysDirty:30,scope:typeof a.scope=="string"?a.scope:"all"}),o.daemon=i}if(r.telegram&&typeof r.telegram=="object"){let i={},a=r.telegram.notify;if(a&&typeof a=="object"){let l={};if((a.mode==="primary"||a.mode==="broadcast"||a.mode==="custom")&&(l.mode=a.mode),typeof a.primaryChatId=="number"&&Number.isFinite(a.primaryChatId)&&(l.primaryChatId=a.primaryChatId),Array.isArray(a.targets)){let c=a.targets.filter(d=>typeof d=="number"&&Number.isFinite(d));c.length>0&&(l.targets=c)}i.notify=l}typeof r.telegram.verifyDone=="boolean"&&(i.verifyDone=r.telegram.verifyDone),o.telegram=i}if(r.updatePolicy&&["notify","auto","off"].includes(r.updatePolicy)&&(o.updatePolicy=r.updatePolicy),typeof r.autoResumeOnUsageLimit=="boolean"&&(o.autoResumeOnUsageLimit=r.autoResumeOnUsageLimit),typeof r.bgSummaries=="boolean"&&(o.bgSummaries=r.bgSummaries),typeof r.maxSummaryCallsPerSession=="number"&&(o.maxSummaryCallsPerSession=Math.min(500,Math.max(1,r.maxSummaryCallsPerSession))),r.hooks!==null&&typeof r.hooks=="object"&&!Array.isArray(r.hooks)&&(o.hooks=r.hooks),typeof r.enableShellHooks=="boolean"&&(o.enableShellHooks=r.enableShellHooks),e!==dc(process.cwd(),"afk.config.json")){let i=ri(r.importFrom);i!==void 0&&(o.importFrom=i)}if(r.interactive&&typeof r.interactive=="object"){let i={};typeof r.interactive.worktreeAutoname=="boolean"&&(i.worktreeAutoname=r.interactive.worktreeAutoname),typeof r.interactive.worktreeBranchPrefix=="string"&&(i.worktreeBranchPrefix=oc(r.interactive.worktreeBranchPrefix,`${e}#/interactive/worktreeBranchPrefix`)),typeof r.interactive.worktreeBase=="string"&&r.interactive.worktreeBase.trim().length>0&&(sc(r.interactive.worktreeBase,`${e}#/interactive/worktreeBase`),i.worktreeBase=r.interactive.worktreeBase),typeof r.interactive.suggestGhost=="boolean"&&(i.suggestGhost=r.interactive.suggestGhost),(r.interactive.thinkingUi==="summary"||r.interactive.thinkingUi==="live"||r.interactive.thinkingUi==="digest"||r.interactive.thinkingUi==="off")&&(i.thinkingUi=r.interactive.thinkingUi),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}U();function pc(){return uc().config.telegram??{}}N();function jh(t,e){return e!==void 0&&Number.isFinite(e)&&e!==0?e:t.find(r=>r>0)??t[0]}function Hh(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=jh(n,e.primaryChatId);return o!==void 0?[o]:[]}function Wh(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 Kh(t){if(!t)return;let e=t.trim().toLowerCase();return e==="primary"||e==="broadcast"||e==="custom"?e:void 0}function Gh(){let t=pc().notify??{},e=t.mode??Kh(S.AFK_TELEGRAM_NOTIFY_MODE),n=t.primaryChatId??Wh(S.AFK_TELEGRAM_PRIMARY_CHAT_ID);return{...e!==void 0?{mode:e}:{},...n!==void 0?{primaryChatId:n}:{},...t.targets!==void 0?{targets:t.targets}:{}}}function Fr(){let t=Ys(S.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return Hh(t,Gh())}function ce(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(`
|
|
@@ -313,7 +313,7 @@ Your role is to showcase how skills load markdown prompts from a \`prompts/\` di
|
|
|
313
313
|
Example user instruction for the template skill.
|
|
314
314
|
|
|
315
315
|
This prompt demonstrates how multiple markdown files are loaded, sorted alphabetically, and merged into a single prompt for subagent execution.
|
|
316
|
-
`},"get-started":{"system.md":"You are running first-time setup for AFK (Agent AFK) with a new user. Walk them from a cold install to their first useful task as a guided boot sequence. Be terse and operational \u2014 confirm each step in one line, don't narrate. Use `\u2713` / `\u2717` and code fences for commands. `$ARGUMENTS` may carry an initial hint (a name or a goal); use it if present.\n\n## Hard rules\n\n1. **You cannot run slash commands for the user.** You *recommend* `/init` and `/clear` and the user types them. You MAY dispatch the `skill` tool for `/telegram-setup` and `/service-setup` yourself (they are setup sub-skills).\n2. **Never touch the Telegram token.** All Telegram setup goes through `/telegram-setup`. Do not read `~/.afk/config/afk.env`.\n3. **Never shell into interactive `afk migrate` or `afk telegram setup`** \u2014 their stdin prompts conflict with the REPL. Use only the non-interactive paths below (`afk migrate --dry-run`, `afk migrate -y`).\n4. **One question at a time** via `ask_question`. Keep moving; don't loop waiting.\n\n## Step 0 \u2014 Surface gate\n\nCall `get_runtime_state` (view `self`). If the surface is NOT interactive (daemon, one-shot `chat`, or a sub-agent \u2014 where `ask_question` will be declined), do NOT ask anything: print the setup checklist below as plain text and stop. Only continue the interactive flow on the REPL or Telegram.\n\n> Setup checklist: 1) set `ANTHROPIC_API_KEY` 2) `afk migrate` to import Claude Code/Codex tooling 3) `afk telegram setup` for push 4) `/init` to generate AFK.md 5) `/clear` then start working.\n\n## Step 1 \u2014 Preflight\n\nRun these and read the results (don't dump raw JSON at the user \u2014 summarize):\n\n```\nafk doctor -f json\ngit rev-parse --is-inside-work-tree\n```\n\nAlso check whether `AFK.md` exists in the current directory. Build a short status list: model provider (API key) \u2713/\u2717, git repo \u2713/\u2717, AFK.md present \u2713/\u2717, and from the doctor JSON: Telegram, importable Claude Code/Codex assets. Exa Search = is `EXA_API_KEY` set in the environment.\n\n**Idempotency:** if AFK.md already exists AND a model provider is configured AND (Telegram is configured or the user clearly isn't new), say so in one line \u2014 \"Looks like AFK is already set up here.\" \u2014 and skip straight to Step 6 (first job). Don't re-run the full flow.\n\n## Step 2 \u2014 Name + intro\n\nAsk once with `ask_question` (type `text`): **\"What should I call you?\"** (skip if `$ARGUMENTS` already gave a name). When they answer, offer to remember it: call `memory_update` with `target: hot`, a short identity line (e.g. \"User's name is <name>.\"). Hot memory survives `/clear` and is present in every future session.\n\nThen give a 4\u20136 line intro, e.g.:\n\n> AFK lets you hand work to an agent, step away, and come back to an inspectable trace. It can improve a repo, research, automate recurring jobs, run unattended as a background service, and report to you over Telegram. You drive it from this REPL or async from your phone.\n\n## Step 3 \u2014 Toolbox (bring + connect capabilities)\n\n**3a. Migrate existing tooling.** If the doctor preflight flagged importable Claude Code / Codex assets, run `afk migrate --dry-run` (read-only preview \u2014 safe, no prompt) and summarize what it found (plugins / skills / MCP servers). Then `ask_question` (type `confirm`): \"Import these into AFK?\" On yes, run `afk migrate -y` (add `--mcp` only if they explicitly want MCP servers, which auto-run commands on connect). If nothing is importable, skip this silently.\n\n**3b. Optional capabilities.** Offer only the ones not already configured:\n- **Exa Search** (web research/grounding): if `EXA_API_KEY` is unset, tell them to set it in `~/.afk/config/afk.env`; offer to explain how.\n- **Telegram** (drive/monitor AFK from your phone): if unconfigured, dispatch the `skill` tool with `/telegram-setup`.\n- **Background service** (always-on bot/daemon): **macOS
|
|
316
|
+
`},"get-started":{"system.md":"You are running first-time setup for AFK (Agent AFK) with a new user. Walk them from a cold install to their first useful task as a guided boot sequence. Be terse and operational \u2014 confirm each step in one line, don't narrate. Use `\u2713` / `\u2717` and code fences for commands. `$ARGUMENTS` may carry an initial hint (a name or a goal); use it if present.\n\n## Hard rules\n\n1. **You cannot run slash commands for the user.** You *recommend* `/init` and `/clear` and the user types them. You MAY dispatch the `skill` tool for `/telegram-setup` and `/service-setup` yourself (they are setup sub-skills).\n2. **Never touch the Telegram token.** All Telegram setup goes through `/telegram-setup`. Do not read `~/.afk/config/afk.env`.\n3. **Never shell into interactive `afk migrate` or `afk telegram setup`** \u2014 their stdin prompts conflict with the REPL. Use only the non-interactive paths below (`afk migrate --dry-run`, `afk migrate -y`).\n4. **One question at a time** via `ask_question`. Keep moving; don't loop waiting.\n\n## Step 0 \u2014 Surface gate\n\nCall `get_runtime_state` (view `self`). If the surface is NOT interactive (daemon, one-shot `chat`, or a sub-agent \u2014 where `ask_question` will be declined), do NOT ask anything: print the setup checklist below as plain text and stop. Only continue the interactive flow on the REPL or Telegram.\n\n> Setup checklist: 1) set `ANTHROPIC_API_KEY` 2) `afk migrate` to import Claude Code/Codex tooling 3) `afk telegram setup` for push 4) `/init` to generate AFK.md 5) `/clear` then start working.\n\n## Step 1 \u2014 Preflight\n\nRun these and read the results (don't dump raw JSON at the user \u2014 summarize):\n\n```\nafk doctor -f json\ngit rev-parse --is-inside-work-tree\n```\n\nAlso check whether `AFK.md` exists in the current directory. Build a short status list: model provider (API key) \u2713/\u2717, git repo \u2713/\u2717, AFK.md present \u2713/\u2717, and from the doctor JSON: Telegram, importable Claude Code/Codex assets. Exa Search = is `EXA_API_KEY` set in the environment.\n\n**Idempotency:** if AFK.md already exists AND a model provider is configured AND (Telegram is configured or the user clearly isn't new), say so in one line \u2014 \"Looks like AFK is already set up here.\" \u2014 and skip straight to Step 6 (first job). Don't re-run the full flow.\n\n## Step 2 \u2014 Name + intro\n\nAsk once with `ask_question` (type `text`): **\"What should I call you?\"** (skip if `$ARGUMENTS` already gave a name). When they answer, offer to remember it: call `memory_update` with `target: hot`, a short identity line (e.g. \"User's name is <name>.\"). Hot memory survives `/clear` and is present in every future session.\n\nThen give a 4\u20136 line intro, e.g.:\n\n> AFK lets you hand work to an agent, step away, and come back to an inspectable trace. It can improve a repo, research, automate recurring jobs, run unattended as a background service, and report to you over Telegram. You drive it from this REPL or async from your phone.\n\n## Step 3 \u2014 Toolbox (bring + connect capabilities)\n\n**3a. Migrate existing tooling.** If the doctor preflight flagged importable Claude Code / Codex assets, run `afk migrate --dry-run` (read-only preview \u2014 safe, no prompt) and summarize what it found (plugins / skills / MCP servers). Then `ask_question` (type `confirm`): \"Import these into AFK?\" On yes, run `afk migrate -y` (add `--mcp` only if they explicitly want MCP servers, which auto-run commands on connect). If nothing is importable, skip this silently.\n\n**3b. Optional capabilities.** Offer only the ones not already configured:\n- **Exa Search** (web research/grounding): if `EXA_API_KEY` is unset, tell them to set it in `~/.afk/config/afk.env`; offer to explain how.\n- **Telegram** (drive/monitor AFK from your phone): if unconfigured, dispatch the `skill` tool with `/telegram-setup`.\n- **Background service** (always-on bot/daemon): **macOS + Linux** \u2014 first check the platform (`uname` \u2192 `Darwin` for launchd, `Linux` for systemd `--user`). On other platforms (e.g. Windows), skip and say service mode isn't supported there. Otherwise, if they want it, dispatch the `skill` tool with `/service-setup`.\n\nDon't push all three \u2014 suggest based on what they said they want. Re-check the relevant signal after each so you can confirm \u2713.\n\n## Step 4 \u2014 Project context (/init)\n\nIf no `AFK.md` exists (or it's stale), recommend it:\n\n> Next, set up this project's context so every AFK session here understands it. Run:\n> ```\n> /init\n> ```\n> That scans the repo and writes an `AFK.md` (it also picks up any existing CLAUDE.md / AGENTS.md / .cursor/rules). Reply when it's done.\n\nYou can't run `/init` yourself \u2014 wait for them to run it.\n\n## Step 5 \u2014 Save point (/clear)\n\nAfter `/init`, recommend a fresh window \u2014 this is the natural save point:\n\n> `AFK.md` is saved (and persists, along with what I remembered about you). For a clean context window, run:\n> ```\n> /clear\n> ```\n\n`/clear` MUST be last and user-run \u2014 it wipes this session. Don't recommend it before `/init`.\n\n## Step 6 \u2014 First job\n\nEnd on a useful action, not on setup. Ask with `ask_question` (type `choice`): **\"What do you want AFK to do first?\"** Offer, conditionally:\n- Improve this repo \u2192 `afk improve` (or describe the change and I'll do it)\n- Research something \u2192 `/research`\n- Review a diff / PR \u2192 `/review`\n- Integrate an external API \u2192 `/integrate` *(only list if that skill is available)*\n- Automate a recurring job \u2192 `/automate` *(only list if that skill is available)*\n- Nothing yet \u2014 just finish setup\n\nOnly list `/integrate` and `/automate` if they're actually registered (they aren't bundled with AFK \u2014 they're operator-installed). If unsure, omit them and mention the user can install them later.\n\nRoute to the choice and hand off. Done.\n\n## Tone\n\nOperational and warm, not corporate. This is one-time setup; the user wants it done, then to start working. Don't re-explain AFK after the Step 2 intro.\n"},mint:{"build.md":`# Phase 5: Build
|
|
317
317
|
|
|
318
318
|
You are a developer executing an implementation plan. Your task is to write code that realizes the specification and passes the tests defined in the plan.
|
|
319
319
|
|
|
@@ -559,7 +559,7 @@ Return a well-structured specification (700\u20131000 words) that a developer ca
|
|
|
559
559
|
- How to validate success
|
|
560
560
|
|
|
561
561
|
Be direct and clear. Avoid marketing language; favor technical precision.
|
|
562
|
-
`,"verify.md":'# Phase 6: Verify (Ship-Yesterday Gate)\n\nYou are a quality gate. Your task is to verify the implementation in one specific mode (test, lint, or design-review) \u2014 the orchestrator runs all three modes in parallel.\n\n## Input\nYou are given:\n- The implementation plan from Phase 3 (verification commands, success criteria)\n- The build results from Phase 5 (files changed, test status)\n- Your **mode** \u2014 one of: `test`, `lint`, `design-review`\n\n## Your Task\n\nThe orchestrator runs three modes in parallel: `test` and `lint` are **programmatic** checks; `design-review` is a code-quality review. A green status across all three is the bar to ship.\n\n**If mode is `test`:**\n- Run the full test suite specified in the plan.\n- Capture failures and concrete error messages.\n\n**If mode is `lint`:**\n- Run linting and type-checking.\n- Capture each lint/type error with file:line where possible.\n\n**If mode is `design-review`:**\nEvaluate the implementation diff on two axes \u2014 **spec compliance** (did it build what the plan specified?) and **code quality** (is the build any good?). A red on *either* axis is a FAIL.\n\n**Spec compliance \u2014 check this FIRST, against the Phase 3 plan\'s success criteria (in your input):**\n- **Completeness** \u2014 every success criterion / acceptance condition in the plan has a corresponding change in the diff. A criterion with no implementing change is a blocker.\n- **No scope creep** \u2014 nothing substantive was built beyond what the plan asked for. Unrequested features or behavior changes are a blocker (cite `file:line`).\n- If the plan carries **no explicit success criteria** to check against, do NOT silently treat the global constraints \u2014 or the diff\'s own apparent goals \u2014 as "the spec" and pass. Emit a blocker: `spec-compliance not assessable \u2014 plan lacks explicit success criteria`. A reviewer who invents the spec rubber-stamps everything.\n\n**Code quality \u2014 evaluate the implementation diff across these dimensions:**\n\n1. **Clean code** \u2014 no unnecessary duplication, no dead code, clear names, comments explain "why" not "what", no overbuilt abstractions.\n2. **Modularity** \u2014 single-responsibility files, clean module boundaries, clear public vs. private APIs.\n3. **Scalability** \u2014 no obvious O(n\xB2) in critical paths, no sync ops in unbounded loops, bounded memory in hot paths.\n4. **Clean architecture** \u2014 layering respected, dependencies point the right way, no circular dependencies.\n5. **Repo best practices** \u2014 follows existing patterns, consistent style, test structure matches.\n6. **Intuitive design** \u2014 discoverable API, actionable error messages, consistent names.\n7. **Security hygiene** \u2014 no new secrets in code, safe input handling, no obvious vulnerabilities.\n\nA red on the spec-compliance axis or any code-quality dimension is a FAIL; yellows are nice-to-have and do not block.\n\n## Output\n\nRespond with a single fenced JSON code block and no prose outside it. The JSON must conform to:\n\n```json\n{\n "status": "PASS",\n "status_reason": "short reason \u2014 only when status is FAIL, omit otherwise",\n "issues": ["src/example.ts:42 \u2014 concrete issue description"],\n "summary": "Optional one-paragraph human-readable summary of what was checked.",\n "signal": {\n "issue": "stable-slug-or-question",\n "stance": "supports",\n "confidence": 0.9,\n "evidence": ["src/example.ts:42"],\n "claim": "Implementation passes this verification mode without blockers."\n }\n}\n```\n\nField semantics:\n- `status` \u2014 `"PASS"` if this mode is green; `"FAIL"` if anything red.\n- `status_reason` \u2014 short reason when `FAIL`; omit when `PASS`.\n- `issues` \u2014 concrete blockers with file:line citations where possible. Empty array when `PASS`.\n- `summary` \u2014 optional narrative; the orchestrator may surface it to the user. Keep it concise.\n- `signal` \u2014 OPTIONAL passive-observation field (v0). When the\n implementation cleanly passes or cleanly fails your mode, you MAY emit a\n `signal` object conforming to the shape shown. See `docs/signal-block.md`\n for the full convention. Rules:\n - `issue` \u2014 a stable slug naming what was checked (e.g.\n `"verify-test-mode"`, `"verify-lint-mode"`, `"verify-design-review"`).\n Use the same slug across reruns of the same mode.\n - `stance` \u2014 `supports` when `status: "PASS"`; `opposes` when\n `status: "FAIL"`; `uncertain` when issues are real but ambiguous;\n `blocks` when the verification tool itself failed (e.g. test runner\n crashed).\n - `confidence` \u2014 how sure you are about the verdict, not how sure you\n are that the code is good overall.\n - `evidence` \u2014 at least one `file:line` citation matching an entry in\n `issues[]`, or pointing to a test/lint output. Empty array permitted\n when `status: "PASS"` and there is nothing to cite.\n - `claim` \u2014 one sentence summarizing your mode-specific verdict.\n - OMIT the entire `signal` field when verification was inconclusive\n (e.g., you could not run the tests). Do not fabricate a stance.\n'},"service-setup":{"system.md":"You are installing an AFK background process (telegram bot or daemon) as a macOS LaunchAgent so it auto-starts on login and relaunches on crash. The user-facing surface is the `afk service` command group; you orchestrate its lifecycle and refuse to install in states that would produce a `KeepAlive` crash loop.\n\n## Hard rules\n\n1. **macOS only.** Before doing anything, run `uname` and confirm output is `Darwin`. On anything else, tell the user `afk service` is macOS-only (uses `launchctl` and `~/Library/LaunchAgents/`) and stop. Do not attempt a workaround.\n2. **Use only the sanctioned subcommands.** Never invoke `launchctl` directly, never write to `~/Library/LaunchAgents/` yourself, never read `~/.afk/config/afk.env`. The sanctioned surface:\n - `afk service install <telegram|daemon> [--no-watch] [--dry-run]`\n - `afk service uninstall <name>`\n - `afk service status [name]`\n - `afk service restart <name>`\n - `afk service list`\n - `afk telegram check-token` \u2014 JSON `{set, valid, username?, botId?, reason?}` (only used during pre-flight for the telegram service)\n3. **Never install the telegram service if the token isn't valid.** `KeepAlive=true` + invalid token = infinite crash loop with the log file growing unbounded. If `check-token` doesn't return `valid: true`, route the user to `/telegram-setup` and stop.\n4. **`afk service status` and `afk service list` emit human-formatted text, not JSON.** Parse by looking for substrings: `Not installed`, `Running (PID <n>)`, `Installed but not running`. Do not invent fields.\n\n## The flow\n\n### Step 1 \u2014 Identify the target service\n\nIf the user named a service in the invocation args (`telegram` or `daemon`), use that. Otherwise ask:\n\n> Which AFK service do you want to install as always-on?\n>\n> - `telegram` \u2014 the bot that lets you drive AFK from your phone\n> - `daemon` \u2014 the cron-based headless runner for scheduled tasks\n>\n> (Reply `telegram` or `daemon`.)\n\nWait for their answer. Anything outside the two values: re-ask once, then bail with a clear message if still ambiguous.\n\n### Step 2 \u2014 Platform check\n\nRun `uname`. If the trimmed stdout is not `Darwin`, tell the user:\n\n> `afk service` only works on macOS \u2014 it uses `launchctl` and `~/Library/LaunchAgents/`. On Linux you'd want a systemd user unit (not yet shipped). Detected platform: `<output>`.\n\nThen stop.\n\n### Step 3 \u2014 Check current install state\n\nRun `afk service status <name>`. Three branches based on the human-formatted output:\n\n- Contains `Not installed` \u2192 not installed yet. Continue to Step 4.\n- Contains `Running (PID <n>)` \u2192 already installed and running. Tell the user:\n\n > \u2713 `<name>` is already installed and running (PID <n>). Manage it with:\n > - `afk service status <name>` \u2014 running state + log path\n > - `afk service restart <name>` \u2014 bounce the process\n > - `afk service uninstall <name>` \u2014 stop + remove plist\n > - Log file is shown in the status output above.\n\n Then stop. Do not reinstall.\n\n- Contains `Installed but not running` \u2192 installed but the process exited. Ask:\n\n > `<name>` is installed but not running (last exit may indicate why \u2014 see status output above). Want to restart it (`afk service restart <name>`) or uninstall and reinstall fresh?\n\n Honor the user's choice. If they pick restart, run `afk service restart <name>` and skip to Step 6. If reinstall, run `afk service uninstall <name>` and continue to Step 4.\n\n### Step 4 \u2014 Pre-flight prerequisites\n\nPer service:\n\n**For `telegram`:** run `afk telegram check-token` and parse the JSON.\n\n- `{set: true, valid: true, username: \"FooBot\"}` \u2192 proceed.\n- `{set: false}` or `{valid: false}` \u2192 tell the user:\n\n > Before I install the telegram bot as a LaunchAgent, the bot token needs to be set and valid \u2014 otherwise `KeepAlive` will crash-loop the service. Run `/telegram-setup` first to configure the token, then come back and run `/service-setup telegram`.\n\n Then stop. Do not attempt the install.\n\n**For `daemon`:** no automated pre-flight is run here (the daemon reads schedules from `~/.afk/config/schedules.json` at boot and gracefully handles an empty list). Just warn the user once:\n\n> Note: the daemon reads schedules from `~/.afk/config/schedules.json`. If you haven't created any with `afk schedule add` yet, the service will run idle until you do \u2014 that's fine.\n\nThen continue.\n\n### Step 5 \u2014 Install\n\nRun `afk service install <name>`. Read the human-formatted output:\n\n- `\u2713 Installed com.afk.<name>` \u2192 success. Note the WatchPaths line from the output (telegram only). Continue to Step 6.\n- `\u26A0 ... already installed` \u2192 race with Step 3 (or the user installed manually between steps). Re-run status; do not force-reinstall.\n- `\u2717 Install failed: <reason>` \u2192 surface the exact reason verbatim. Common causes worth naming when you see them:\n - \"Telegram entrypoint resolved to a `.ts` file\" \u2192 user is running from source without building. Tell them to run `pnpm build` first; launchd needs the compiled `.mjs` entrypoint.\n - \"Already bootstrapped\" \u2192 orphan plist from a prior install. Run `afk service uninstall <name>` and retry once.\n\n Then stop. Don't loop indefinitely.\n\n### Step 6 \u2014 Verify\n\nRun `afk service status <name>` again. If the output shows `Running (PID <n>)`:\n\n> \u2713 `<name>` is now running as a LaunchAgent (PID <n>). It will auto-start on login and relaunch if it crashes.\n\nIf it still shows `Installed but not running` after install:\n\n> Plist is installed but the process didn't start. Check the log:\n> ```\n> tail -50 ~/.afk/logs/service-<name>.log\n> ```\n> If you can share the tail, I can help diagnose. Otherwise try `afk service restart <name>` once.\n\nDon't loop \u2014 let the user inspect and come back.\n\n### Step 7 \u2014 Hand off the cheatsheet\n\nEnd with the management commands the user will need later:\n\n> Management:\n> - `afk service status <name>` \u2014 check running state, PID, last exit\n> - `afk service restart <name>` \u2014 bounce after config changes\n> - `afk service uninstall <name>` \u2014 stop and remove the plist\n> - Logs: `~/.afk/logs/service-<name>.log`\n>\n> Note: `afk telegram status` reports \"stopped\" when launchd is the supervisor \u2014 that's expected. Use `afk service status telegram` to introspect the LaunchAgent-managed instance.\n\nThen stop.\n\n## Tone\n\nTerse and operational. One line per step confirmation. Use `\u2713` / `\u2717` markers. Code-fence any command the user should run. Don't narrate the launchd internals unless asked \u2014 the user wants the service running, not a tutorial.\n\n## Surface awareness\n\nIf the user is reaching you over Telegram (mentioned phone, or session metadata indicates so), note once at Step 1:\n\n> Heads up \u2014 `afk service` installs a per-user LaunchAgent on the machine where AFK is installed. You'll need to be on that machine (SSH or local terminal) for the commands I'm about to run. I can still walk through them, but the install happens there.\n"},"telegram-setup":{"system.md":`You are walking the user through first-time Telegram bot setup for AFK (Agent AFK). Your job: get them from "no bot" to a working push-notification channel with the token never leaving their local machine.
|
|
562
|
+
`,"verify.md":'# Phase 6: Verify (Ship-Yesterday Gate)\n\nYou are a quality gate. Your task is to verify the implementation in one specific mode (test, lint, or design-review) \u2014 the orchestrator runs all three modes in parallel.\n\n## Input\nYou are given:\n- The implementation plan from Phase 3 (verification commands, success criteria)\n- The build results from Phase 5 (files changed, test status)\n- Your **mode** \u2014 one of: `test`, `lint`, `design-review`\n\n## Your Task\n\nThe orchestrator runs three modes in parallel: `test` and `lint` are **programmatic** checks; `design-review` is a code-quality review. A green status across all three is the bar to ship.\n\n**If mode is `test`:**\n- Run the full test suite specified in the plan.\n- Capture failures and concrete error messages.\n\n**If mode is `lint`:**\n- Run linting and type-checking.\n- Capture each lint/type error with file:line where possible.\n\n**If mode is `design-review`:**\nEvaluate the implementation diff on two axes \u2014 **spec compliance** (did it build what the plan specified?) and **code quality** (is the build any good?). A red on *either* axis is a FAIL.\n\n**Spec compliance \u2014 check this FIRST, against the Phase 3 plan\'s success criteria (in your input):**\n- **Completeness** \u2014 every success criterion / acceptance condition in the plan has a corresponding change in the diff. A criterion with no implementing change is a blocker.\n- **No scope creep** \u2014 nothing substantive was built beyond what the plan asked for. Unrequested features or behavior changes are a blocker (cite `file:line`).\n- If the plan carries **no explicit success criteria** to check against, do NOT silently treat the global constraints \u2014 or the diff\'s own apparent goals \u2014 as "the spec" and pass. Emit a blocker: `spec-compliance not assessable \u2014 plan lacks explicit success criteria`. A reviewer who invents the spec rubber-stamps everything.\n\n**Code quality \u2014 evaluate the implementation diff across these dimensions:**\n\n1. **Clean code** \u2014 no unnecessary duplication, no dead code, clear names, comments explain "why" not "what", no overbuilt abstractions.\n2. **Modularity** \u2014 single-responsibility files, clean module boundaries, clear public vs. private APIs.\n3. **Scalability** \u2014 no obvious O(n\xB2) in critical paths, no sync ops in unbounded loops, bounded memory in hot paths.\n4. **Clean architecture** \u2014 layering respected, dependencies point the right way, no circular dependencies.\n5. **Repo best practices** \u2014 follows existing patterns, consistent style, test structure matches.\n6. **Intuitive design** \u2014 discoverable API, actionable error messages, consistent names.\n7. **Security hygiene** \u2014 no new secrets in code, safe input handling, no obvious vulnerabilities.\n\nA red on the spec-compliance axis or any code-quality dimension is a FAIL; yellows are nice-to-have and do not block.\n\n## Output\n\nRespond with a single fenced JSON code block and no prose outside it. The JSON must conform to:\n\n```json\n{\n "status": "PASS",\n "status_reason": "short reason \u2014 only when status is FAIL, omit otherwise",\n "issues": ["src/example.ts:42 \u2014 concrete issue description"],\n "summary": "Optional one-paragraph human-readable summary of what was checked.",\n "signal": {\n "issue": "stable-slug-or-question",\n "stance": "supports",\n "confidence": 0.9,\n "evidence": ["src/example.ts:42"],\n "claim": "Implementation passes this verification mode without blockers."\n }\n}\n```\n\nField semantics:\n- `status` \u2014 `"PASS"` if this mode is green; `"FAIL"` if anything red.\n- `status_reason` \u2014 short reason when `FAIL`; omit when `PASS`.\n- `issues` \u2014 concrete blockers with file:line citations where possible. Empty array when `PASS`.\n- `summary` \u2014 optional narrative; the orchestrator may surface it to the user. Keep it concise.\n- `signal` \u2014 OPTIONAL passive-observation field (v0). When the\n implementation cleanly passes or cleanly fails your mode, you MAY emit a\n `signal` object conforming to the shape shown. See `docs/signal-block.md`\n for the full convention. Rules:\n - `issue` \u2014 a stable slug naming what was checked (e.g.\n `"verify-test-mode"`, `"verify-lint-mode"`, `"verify-design-review"`).\n Use the same slug across reruns of the same mode.\n - `stance` \u2014 `supports` when `status: "PASS"`; `opposes` when\n `status: "FAIL"`; `uncertain` when issues are real but ambiguous;\n `blocks` when the verification tool itself failed (e.g. test runner\n crashed).\n - `confidence` \u2014 how sure you are about the verdict, not how sure you\n are that the code is good overall.\n - `evidence` \u2014 at least one `file:line` citation matching an entry in\n `issues[]`, or pointing to a test/lint output. Empty array permitted\n when `status: "PASS"` and there is nothing to cite.\n - `claim` \u2014 one sentence summarizing your mode-specific verdict.\n - OMIT the entire `signal` field when verification was inconclusive\n (e.g., you could not run the tests). Do not fabricate a stance.\n'},"service-setup":{"system.md":"You are installing an AFK background process (telegram bot or daemon) as an OS-supervised service so it auto-starts on login and relaunches on crash. The backend is chosen per platform: macOS uses a launchd LaunchAgent (`~/Library/LaunchAgents/`), Linux uses a systemd `--user` unit (`~/.config/systemd/user/`). The user-facing surface is the `afk service` command group; you orchestrate its lifecycle and refuse to install in states that would produce a crash loop (launchd `KeepAlive` / systemd `Restart=always`).\n\n## Hard rules\n\n1. **macOS or Linux only.** Before doing anything, run `uname` and confirm output is `Darwin` (macOS \u2192 launchd) or `Linux` (\u2192 systemd `--user`). On anything else (e.g. Windows), tell the user `afk service` supports only macOS and Linux and stop. Do not attempt a workaround.\n2. **Use only the sanctioned subcommands.** Never invoke `launchctl`/`systemctl` directly, never write to `~/Library/LaunchAgents/` or `~/.config/systemd/user/` yourself, never read `~/.afk/config/afk.env`. The sanctioned surface:\n - `afk service install <telegram|daemon> [--no-watch] [--dry-run]`\n - `afk service uninstall <name>`\n - `afk service status [name]`\n - `afk service restart <name>`\n - `afk service list`\n - `afk telegram check-token` \u2014 JSON `{set, valid, username?, botId?, reason?}` (only used during pre-flight for the telegram service)\n3. **Never install the telegram service if the token isn't valid.** `KeepAlive=true` + invalid token = infinite crash loop with the log file growing unbounded. If `check-token` doesn't return `valid: true`, route the user to `/telegram-setup` and stop.\n4. **`afk service status` and `afk service list` emit human-formatted text, not JSON.** Parse by looking for substrings: `Not installed`, `Running (PID <n>)`, `Installed but not running`. Do not invent fields.\n\n## The flow\n\n### Step 1 \u2014 Identify the target service\n\nIf the user named a service in the invocation args (`telegram` or `daemon`), use that. Otherwise ask:\n\n> Which AFK service do you want to install as always-on?\n>\n> - `telegram` \u2014 the bot that lets you drive AFK from your phone\n> - `daemon` \u2014 the cron-based headless runner for scheduled tasks\n>\n> (Reply `telegram` or `daemon`.)\n\nWait for their answer. Anything outside the two values: re-ask once, then bail with a clear message if still ambiguous.\n\n### Step 2 \u2014 Platform check\n\nRun `uname`. If the trimmed stdout is `Darwin` (macOS \u2192 launchd) or `Linux` (\u2192 systemd `--user`), continue. Otherwise tell the user:\n\n> `afk service` supports only macOS (launchd) and Linux (systemd `--user`). Detected platform: `<output>`.\n\nThen stop.\n\nOn **Linux**, also note once (systemd `--user` services stop at logout without lingering):\n\n> Heads up \u2014 on Linux, a systemd `--user` service only survives logout/reboot if user lingering is enabled. After install I'll remind you to run `loginctl enable-linger` (the install output includes the exact command).\n\n### Step 3 \u2014 Check current install state\n\nRun `afk service status <name>`. Three branches based on the human-formatted output:\n\n- Contains `Not installed` \u2192 not installed yet. Continue to Step 4.\n- Contains `Running (PID <n>)` \u2192 already installed and running. Tell the user:\n\n > \u2713 `<name>` is already installed and running (PID <n>). Manage it with:\n > - `afk service status <name>` \u2014 running state + log path\n > - `afk service restart <name>` \u2014 bounce the process\n > - `afk service uninstall <name>` \u2014 stop + remove plist\n > - Log file is shown in the status output above.\n\n Then stop. Do not reinstall.\n\n- Contains `Installed but not running` \u2192 installed but the process exited. Ask:\n\n > `<name>` is installed but not running (last exit may indicate why \u2014 see status output above). Want to restart it (`afk service restart <name>`) or uninstall and reinstall fresh?\n\n Honor the user's choice. If they pick restart, run `afk service restart <name>` and skip to Step 6. If reinstall, run `afk service uninstall <name>` and continue to Step 4.\n\n### Step 4 \u2014 Pre-flight prerequisites\n\nPer service:\n\n**For `telegram`:** run `afk telegram check-token` and parse the JSON.\n\n- `{set: true, valid: true, username: \"FooBot\"}` \u2192 proceed.\n- `{set: false}` or `{valid: false}` \u2192 tell the user:\n\n > Before I install the telegram bot as a LaunchAgent, the bot token needs to be set and valid \u2014 otherwise `KeepAlive` will crash-loop the service. Run `/telegram-setup` first to configure the token, then come back and run `/service-setup telegram`.\n\n Then stop. Do not attempt the install.\n\n**For `daemon`:** no automated pre-flight is run here (the daemon reads schedules from `~/.afk/config/schedules.json` at boot and gracefully handles an empty list). Just warn the user once:\n\n> Note: the daemon reads schedules from `~/.afk/config/schedules.json`. If you haven't created any with `afk schedule add` yet, the service will run idle until you do \u2014 that's fine.\n\nThen continue.\n\n### Step 5 \u2014 Install\n\nRun `afk service install <name>`. Read the human-formatted output:\n\n- `\u2713 Installed <label>` \u2192 success (label is `com.afk.<name>` on launchd, `afk-<name>.service` on systemd). Note the `Auto-restart on rebuild` line (telegram dev-tree only) and any post-install notes (on Linux this includes the `loginctl enable-linger` command \u2014 surface it to the user). Continue to Step 6.\n- `\u26A0 ... already installed` \u2192 race with Step 3 (or the user installed manually between steps). Re-run status; do not force-reinstall.\n- `\u2717 Install failed: <reason>` \u2192 surface the exact reason verbatim. Common causes worth naming when you see them:\n - \"Telegram entrypoint resolved to a `.ts` file\" \u2192 user is running from source without building. Tell them to run `pnpm build` first; the supervisor runs the compiled `.mjs` entrypoint directly (no tsx/loader).\n - \"Already bootstrapped\" (launchd) / \"unit already exists\" (systemd) \u2192 orphan config from a prior install. Run `afk service uninstall <name>` and retry once.\n\n Then stop. Don't loop indefinitely.\n\n### Step 6 \u2014 Verify\n\nRun `afk service status <name>` again. If the output shows `Running (PID <n>)`:\n\n> \u2713 `<name>` is now running as an OS service (PID <n>). It will auto-start on login and relaunch if it crashes.\n\nIf it still shows `Installed but not running` after install:\n\n> Plist is installed but the process didn't start. Check the log:\n> ```\n> tail -50 ~/.afk/logs/service-<name>.log\n> ```\n> If you can share the tail, I can help diagnose. Otherwise try `afk service restart <name>` once.\n\nDon't loop \u2014 let the user inspect and come back.\n\n### Step 7 \u2014 Hand off the cheatsheet\n\nEnd with the management commands the user will need later:\n\n> Management:\n> - `afk service status <name>` \u2014 check running state, PID, last exit\n> - `afk service restart <name>` \u2014 bounce after config changes\n> - `afk service uninstall <name>` \u2014 stop and remove the service config\n> - Logs: `~/.afk/logs/service-<name>.log`\n> - **Linux only:** for always-on across logout/reboot, run `loginctl enable-linger` once.\n>\n> Note: `afk telegram status` reports \"stopped\" when the OS supervisor (launchd/systemd) runs the bot \u2014 that's expected, because the PID file isn't written in that mode. Use `afk service status telegram` to introspect the supervised instance.\n\nThen stop.\n\n## Tone\n\nTerse and operational. One line per step confirmation. Use `\u2713` / `\u2717` markers. Code-fence any command the user should run. Don't narrate the launchd/systemd internals unless asked \u2014 the user wants the service running, not a tutorial.\n\n## Surface awareness\n\nIf the user is reaching you over Telegram (mentioned phone, or session metadata indicates so), note once at Step 1:\n\n> Heads up \u2014 `afk service` installs a per-user OS service (launchd LaunchAgent on macOS, systemd `--user` unit on Linux) on the machine where AFK is installed. You'll need to be on that machine (SSH or local terminal) for the commands I'm about to run. I can still walk through them, but the install happens there.\n"},"telegram-setup":{"system.md":`You are walking the user through first-time Telegram bot setup for AFK (Agent AFK). Your job: get them from "no bot" to a working push-notification channel with the token never leaving their local machine.
|
|
563
563
|
|
|
564
564
|
## Hard rules (read before doing anything)
|
|
565
565
|
|
|
@@ -922,7 +922,7 @@ ${h.content}`,isError:!0,...h.truncated===!0?{truncated:!0}:{}}),u.push({call:g,
|
|
|
922
922
|
---`);if(o===-1)return{};let s=r.slice(0,o),i=r.slice(o+4).trim(),a={},l=s.split(`
|
|
923
923
|
`);for(let c=0;c<l.length;c++){let d=l[c];if(!d)continue;let u=d.indexOf(":");if(u===-1)continue;let p=d.slice(0,u).trim(),f=d.slice(u+1).trim();if(p==="name")a.name=f.replace(/^["']|["']$/g,"");else if(p==="description")a.description=f.replace(/^["']|["']$/g,"");else if(p==="argumentHint")a.argumentHint=f.replace(/^["']|["']$/g,"");else if(p==="tools"){let m=l.slice(c+1),g=af(f,m),h=_E(e),b=[];for(let _ of g){let A=qo(_,h);A!==void 0?b.includes(A)||b.push(A):process.stderr.write(`[afk] plugin skill at ${t}: unknown tool "${_}" in \`tools:\` frontmatter \u2014 ignored
|
|
924
924
|
`)}b.length===0&&g.length>0&&process.stderr.write(`[afk] plugin skill at ${t}: \`tools:\` declared but no valid tools resolved \u2014 subagent will be blocked from all tools
|
|
925
|
-
`),a.allowedTools=b}else if(p==="audience"){let m=f.replace(/^["']|["']$/g,"");(m==="public"||m==="internal")&&(a.audience=m)}else p==="context"
|
|
925
|
+
`),a.allowedTools=b}else if(p==="audience"){let m=f.replace(/^["']|["']$/g,"");(m==="public"||m==="internal")&&(a.audience=m)}else if(p==="context")a.context=f.replace(/^["']|["']$/g,"");else if(p==="read-only"||p==="readOnly")f.replace(/^["']|["']$/g,"").trim()==="true"&&(a.readOnly=!0);else if(p==="model"){let m=f.replace(/^["']|["']$/g,"").trim();m.length>0&&(a.model=m)}}return i.length>0&&(a.body=i),a}catch{return{}}}function _E(t){return t!==void 0?t:new Set([...Te,...de,"memory_search","agent","skill"])}var NU=new Set([...Te,...de,"memory_search","agent","skill"]);import{fileURLToPath as EE}from"node:url";import{dirname as AE}from"node:path";var xE=EE(import.meta.url),HU=AE(xE),zo={name:"research-agent",systemPrompt:`---
|
|
926
926
|
name: research-agent
|
|
927
927
|
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.
|
|
928
928
|
model: sonnet
|
|
@@ -1063,7 +1063,7 @@ ${JSON.stringify(t.verifyResults,null,2)}
|
|
|
1063
1063
|
|
|
1064
1064
|
Heal iterations used: ${t.healIterations}
|
|
1065
1065
|
|
|
1066
|
-
Create a ship-ready summary with next steps.`,d=await l.runToResult(c);if(d.status!=="succeeded"||!d.message)throw new Error(`ship phase failed: ${re(d)}`);let u=t.buildResults?.filesChanged.length??0,p=t.healIterations;return Gt({kind:"checkpoint",title:"ship \u2014 done",body:[`Files changed: ${u}`,`Heal iterations: ${p}`,`Idea: ${t.idea}`]}),d.message.content}U();import{existsSync as Ff,mkdirSync as vA,readFileSync as _A,unlinkSync as EA,writeFileSync as AA}from"fs";import{dirname as xA,join as TA}from"path";function Ma(t){return TA(le(),t,"mint-state.json")}function Lf(t,e){let n=Ma(t);vA(xA(n),{recursive:!0}),AA(n,JSON.stringify(e,null,2),"utf-8")}function RA(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 Nf(t){let e=Ma(t);if(!Ff(e))return null;try{let n=JSON.parse(_A(e,"utf-8"));return RA(n)?n:null}catch{return null}}function Oa(t){let e=Ma(t);if(Ff(e))try{EA(e)}catch{}}var IA=2,Uf=/^\s*(?:--continue(?:\s+(?:approved|yes|y))?|approved?|yes|y|lgtm|sure)\s*$/i,PA='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 Me(t,e,n){t.history.push({phase:e,output:n,timestamp:Date.now()})}function Hf(t){if("completed"in t&&"paused"in t)throw new Error("mint: invariant violation \u2014 MintResult carries both completed and paused keys simultaneously")}var $f=240;function CA(t){return t.length<=$f?t:t.slice(0,$f)+"\u2026"}function Wf(t){if(typeof t=="string"){if(Uf.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 Wf(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&&Uf.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 Bf(t,e,n,r="sonnet",o){if(!e.sessionId)throw new Error("runPhasesAfterSpec requires parentSession.sessionId");let s=e.sessionId,i=e.cwd;try{t.currentPhase="research",t.research=await Rf(t.spec,s,i,n,r),Me(t,"research",t.research),t.currentPhase="plan",t.plan=await If(t.spec,t.research,s,i,n,r),Me(t,"plan",t.plan),t.currentPhase="parallelize";let a=await Cf(t.plan,e,n,r);if(a.kind==="plan")t.waveOrchestrationPlan=a.plan,Me(t,"parallelize",JSON.stringify(a.plan));else if(a.kind==="skipped")t.waveOrchestrationPlan=void 0,Me(t,"parallelize",`skipped: ${a.reason}`);else if(a.kind==="failed"){t.waveOrchestrationPlan=void 0;let d=CA(a.error);Me(t,"parallelize",`failed: ${d}`),pe({event:"fallback.inline",parent_session_id:s,reason:"parallelize-dispatch-failed",error_message:d}),console.warn(`[mint] parallelize dispatch failed (single-lane fallback): ${d}`)}else{let d=a}t.currentPhase="build",t.buildResults=await Mf(t.plan,t.waveOrchestrationPlan,s,i,n,r),Me(t,"build",JSON.stringify(t.buildResults)),t.currentPhase="verify",t.verifyResults=await es(t.plan,t.buildResults,s,i,n,r),Me(t,"verify",JSON.stringify(t.verifyResults)),t.currentPhase="heal";let l=t.verifyResults.testsPassed&&t.verifyResults.lintPassed&&t.verifyResults.designReviewPassed;for(;!l&&t.healIterations<IA;){let d=await Of(t.plan,t.buildResults,t.verifyResults,t.healIterations,e,n,r,o);t.healIterations=d.newHealIterations,t.verifyResults=d.newVerifyResults,l=d.healed,Me(t,"heal",`Iterations: ${t.healIterations}, Success: ${l}`)}if(!l)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 c=await Df(t,s,i,n,r);return Me(t,"ship",c),{completed:!0,artifact:c,state:t}}catch(a){throw new Error(`mint failed at ${t.currentPhase}: ${a}`)}}function jf(t,e){return Hf(e),("completed"in e||e.phase==="heal-failed")&&Oa(t),e}async function MA(t,e,n){let r=Wf(t);if(!e?.sessionId)throw new Error("mint handler requires a parent session to fork subagents");let o=e.sessionId,s=n?.callId,i=n?.defaultSubagentModel??n?.defaultModel??"sonnet";if(r.userApproved){let c=r.resumeFrom??Nf(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 d=await Bf(c,e,s,i,n?.dispatchSkill);return jf(o,d)}if(!r.idea)throw new Error("mint: no idea provided. Run /mint <idea> to start, or /mint --continue approved to resume a paused spec.");Oa(o);let a={currentPhase:"spec",idea:r.idea,healIterations:0,history:[]};try{a.spec=await Tf(r.idea,o,e.cwd,s,i),Me(a,"spec",a.spec)}catch(c){throw new Error(`mint failed at spec: ${c}`)}if(!r.autoApprove){Lf(o,a);let c={paused:!0,phase:"spec",spec:a.spec,state:a,nextStep:PA};return Hf(c),c}let l=await Bf(a,e,s,i,n?.dispatchSkill);return jf(o,l)}var OA={name:"mint",description:"Takes a feature idea or refactor scope and delivers a ship-ready, verified implementation end-to-end",handler:MA,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"]};ie(OA);async function DA(){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 FA={name:"service-setup",description:"Install an AFK background process (telegram bot or daemon) as a
|
|
1066
|
+
Create a ship-ready summary with next steps.`,d=await l.runToResult(c);if(d.status!=="succeeded"||!d.message)throw new Error(`ship phase failed: ${re(d)}`);let u=t.buildResults?.filesChanged.length??0,p=t.healIterations;return Gt({kind:"checkpoint",title:"ship \u2014 done",body:[`Files changed: ${u}`,`Heal iterations: ${p}`,`Idea: ${t.idea}`]}),d.message.content}U();import{existsSync as Ff,mkdirSync as vA,readFileSync as _A,unlinkSync as EA,writeFileSync as AA}from"fs";import{dirname as xA,join as TA}from"path";function Ma(t){return TA(le(),t,"mint-state.json")}function Lf(t,e){let n=Ma(t);vA(xA(n),{recursive:!0}),AA(n,JSON.stringify(e,null,2),"utf-8")}function RA(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 Nf(t){let e=Ma(t);if(!Ff(e))return null;try{let n=JSON.parse(_A(e,"utf-8"));return RA(n)?n:null}catch{return null}}function Oa(t){let e=Ma(t);if(Ff(e))try{EA(e)}catch{}}var IA=2,Uf=/^\s*(?:--continue(?:\s+(?:approved|yes|y))?|approved?|yes|y|lgtm|sure)\s*$/i,PA='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 Me(t,e,n){t.history.push({phase:e,output:n,timestamp:Date.now()})}function Hf(t){if("completed"in t&&"paused"in t)throw new Error("mint: invariant violation \u2014 MintResult carries both completed and paused keys simultaneously")}var $f=240;function CA(t){return t.length<=$f?t:t.slice(0,$f)+"\u2026"}function Wf(t){if(typeof t=="string"){if(Uf.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 Wf(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&&Uf.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 Bf(t,e,n,r="sonnet",o){if(!e.sessionId)throw new Error("runPhasesAfterSpec requires parentSession.sessionId");let s=e.sessionId,i=e.cwd;try{t.currentPhase="research",t.research=await Rf(t.spec,s,i,n,r),Me(t,"research",t.research),t.currentPhase="plan",t.plan=await If(t.spec,t.research,s,i,n,r),Me(t,"plan",t.plan),t.currentPhase="parallelize";let a=await Cf(t.plan,e,n,r);if(a.kind==="plan")t.waveOrchestrationPlan=a.plan,Me(t,"parallelize",JSON.stringify(a.plan));else if(a.kind==="skipped")t.waveOrchestrationPlan=void 0,Me(t,"parallelize",`skipped: ${a.reason}`);else if(a.kind==="failed"){t.waveOrchestrationPlan=void 0;let d=CA(a.error);Me(t,"parallelize",`failed: ${d}`),pe({event:"fallback.inline",parent_session_id:s,reason:"parallelize-dispatch-failed",error_message:d}),console.warn(`[mint] parallelize dispatch failed (single-lane fallback): ${d}`)}else{let d=a}t.currentPhase="build",t.buildResults=await Mf(t.plan,t.waveOrchestrationPlan,s,i,n,r),Me(t,"build",JSON.stringify(t.buildResults)),t.currentPhase="verify",t.verifyResults=await es(t.plan,t.buildResults,s,i,n,r),Me(t,"verify",JSON.stringify(t.verifyResults)),t.currentPhase="heal";let l=t.verifyResults.testsPassed&&t.verifyResults.lintPassed&&t.verifyResults.designReviewPassed;for(;!l&&t.healIterations<IA;){let d=await Of(t.plan,t.buildResults,t.verifyResults,t.healIterations,e,n,r,o);t.healIterations=d.newHealIterations,t.verifyResults=d.newVerifyResults,l=d.healed,Me(t,"heal",`Iterations: ${t.healIterations}, Success: ${l}`)}if(!l)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 c=await Df(t,s,i,n,r);return Me(t,"ship",c),{completed:!0,artifact:c,state:t}}catch(a){throw new Error(`mint failed at ${t.currentPhase}: ${a}`)}}function jf(t,e){return Hf(e),("completed"in e||e.phase==="heal-failed")&&Oa(t),e}async function MA(t,e,n){let r=Wf(t);if(!e?.sessionId)throw new Error("mint handler requires a parent session to fork subagents");let o=e.sessionId,s=n?.callId,i=n?.defaultSubagentModel??n?.defaultModel??"sonnet";if(r.userApproved){let c=r.resumeFrom??Nf(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 d=await Bf(c,e,s,i,n?.dispatchSkill);return jf(o,d)}if(!r.idea)throw new Error("mint: no idea provided. Run /mint <idea> to start, or /mint --continue approved to resume a paused spec.");Oa(o);let a={currentPhase:"spec",idea:r.idea,healIterations:0,history:[]};try{a.spec=await Tf(r.idea,o,e.cwd,s,i),Me(a,"spec",a.spec)}catch(c){throw new Error(`mint failed at spec: ${c}`)}if(!r.autoApprove){Lf(o,a);let c={paused:!0,phase:"spec",spec:a.spec,state:a,nextStep:PA};return Hf(c),c}let l=await Bf(a,e,s,i,n?.dispatchSkill);return jf(o,l)}var OA={name:"mint",description:"Takes a feature idea or refactor scope and delivers a ship-ready, verified implementation end-to-end",handler:MA,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"]};ie(OA);async function DA(){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 FA={name:"service-setup",description:"Install an AFK background process (telegram bot or daemon) as an OS-supervised service \u2014 a launchd LaunchAgent on macOS or a systemd `--user` unit on Linux \u2014 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/Restart=always), invokes `afk service install`, verifies with `afk service status`, and surfaces the management cheatsheet (including the `loginctl enable-linger` step on Linux). macOS + Linux \u2014 gracefully refuses on other platforms.",handler:DA,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."};ie(FA);async function LA(){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 NA={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:LA,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.`};ie(NA);U();import{readdirSync as BA,readFileSync as jA}from"fs";import{join as qf}from"path";var UA=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9-]*)(?![a-zA-Z0-9_-])/g;function Kf(t){return t.startsWith("--")?t:`--${t}`}function $A(t){let e=new Set;for(let n of t.matchAll(UA))n[1]&&e.add(`--${n[1]}`);return Array.from(e).sort()}function Da(t){if(!t.startsWith(`---
|
|
1067
1067
|
`))return{frontmatter:null,frontmatterFlags:null,body:t};let e=t.indexOf(`
|
|
1068
1068
|
---
|
|
1069
1069
|
`,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(`
|
|
@@ -1074,7 +1074,7 @@ ${e.body}`)}function HA(t,e){return t.length===0||t.length>64?{valid:!1,reason:`
|
|
|
1074
1074
|
`),0}let r=0;for(let o of n){if(!o.isDirectory()||o.name.startsWith("_")||o.name.startsWith("."))continue;let s;try{s=jA(qf(t,o.name,"SKILL.md"),"utf-8")}catch(c){let d=c;d.code!=="ENOENT"&&process.stderr.write(`[afk] skipping skill ${o.name}: ${d.message}
|
|
1075
1075
|
`);continue}let i=WA(s,o.name);if(!i)continue;i.dir=qf(t,o.name);let l={name:GA(i.name,e),description:i.description,handler:KA(i),origin:e};i.argumentHint&&(l.argumentHint=i.argumentHint),i.flags&&i.flags.length>0&&(l.flags=i.flags),i.context!=="fork"&&(l.context="load",l.loadBody=i.body.replace(/\$\{?SKILL_ROOT\}?/g,()=>i.dir)),ie(l),r++}return r}import{isAbsolute as qA,resolve as zA}from"path";import{pathToFileURL as JA}from"url";var Jf=new Set;async function Vf(t,e={}){let n=e.importer??(r=>import(r));for(let r of t){if(r.main===void 0)continue;let o=qA(r.main)?r.main:zA(r.path,r.main);if(!Jf.has(o)){Jf.add(o);try{let i=(await n(JA(o).href))?.default;typeof i=="function"&&await i(e.pluginApi)}catch(s){e.onError?.(r,s)}}}}import{z as E}from"zod";var Yn=1,VA=E.object({toolName:E.string(),toolUseId:E.string().optional(),input:E.string().optional(),inputRaw:E.string().optional(),result:E.string().optional(),isError:E.boolean().optional()}).passthrough(),YA=E.object({user:E.string().default(""),assistant:E.string().default(""),timestamp:E.number().optional(),toolEvents:E.array(VA).optional()}).passthrough(),Fa=E.object({sessionId:E.string().optional(),name:E.string().optional(),source:E.enum(["cli","telegram"]).optional(),telegramChatId:E.number().optional(),model:E.string(),startedAt:E.number(),savedAt:E.number(),totalTurns:E.number(),totalCostUsd:E.number().optional(),totalTokens:E.number().optional(),totalDurationMs:E.number().optional(),turns:E.array(YA).default([]),forkedFrom:E.string().optional(),forkedAt:E.number().optional()}).passthrough(),Yf=E.enum(["fully_achieved","partially_achieved","not_achieved","aborted"]),Xf=E.enum(["not_persisted","persisted","unknown"]),Qf=E.object({tool:E.string(),label:E.string().optional()}),Zf=E.object({files_written:E.number().int(),files_edited:E.number().int(),bash_commands:E.number().int(),commits:E.number().int(),mutated:E.boolean()}),Xn=E.object({facet_version:E.number().int(),session_id:E.string(),source:E.enum(["cli","telegram","unknown"]),model:E.string(),derived_at:E.string(),derived_from:E.literal("afk-session"),source_session_path:E.string(),source_session_mtime_ms:E.number(),subagent_persistence:Xf,start_time:E.string(),end_time:E.string(),duration_minutes:E.number(),underlying_goal:E.string(),first_prompt:E.string(),goal_categories:E.record(E.string(),E.number()),session_type:E.string(),brief_summary:E.string(),total_turns:E.number().int(),user_message_count:E.number().int(),assistant_message_count:E.number().int(),tool_counts:E.record(E.string(),E.number()),commands:E.array(E.string()),skills:E.array(E.string()),subagents:E.array(Qf),tool_errors:E.number().int(),tool_error_categories:E.record(E.string(),E.number()),friction_counts:E.record(E.string(),E.number()),friction_detail:E.string(),outcome:Yf,primary_success:E.string(),world_changes:Zf,decisions:E.array(E.string()),evidence_pointers:E.array(E.string())}).passthrough();import{basename as XA}from"path";var QA=new Set(["agent","compose","skill"]),ZA=new Set(["read_file","write_file","edit_file"]),em=1e3,ex=240,tx=50,nx=/\bgit\s+commit(?![\w-])/,tm=/^\s*\/([a-zA-Z][\w-]*)/;function rx(t){if(t)try{let e=JSON.parse(t);return e&&typeof e=="object"?e:void 0}catch{return}}function ts(t){return typeof t=="string"?t:void 0}function ns(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function ox(t){return t.replace(/[-_]+/g," ").trim()}function sx(t,e){return tm.test(t)?"slash_command":e==="telegram"?"chat":"task"}function ix(t){let e=new Map,n=[];for(let r of t)r.toolUseId===void 0?n.push(r):e.set(r.toolUseId,r);return[...e.values(),...n]}function zt(t,e={}){let n=t.turns??[],r=ix(n.flatMap(O=>O.toolEvents??[])),o={},s={},i=[],a=[],l=[],c=0,d=0,u=0,p=0,f=0;for(let O of r){let I=O.toolName;o[I]=(o[I]??0)+1,O.isError===!0&&(c+=1,s[I]=(s[I]??0)+1);let j=rx(O.inputRaw??O.input);if(I==="write_file"&&(d+=1),I==="edit_file"&&(u+=1),I==="bash"){p+=1;let R=ts(j?.command)??O.input;R&&nx.test(R)&&(f+=1)}if(ZA.has(I)){let R=ts(j?.file_path);R&&!l.includes(R)&&l.length<tx&&l.push(R)}if(QA.has(I)){let R;I==="skill"?(R=ts(j?.name),R&&!a.includes(R)&&a.push(R)):I==="agent"?R=ts(j?.id_prefix):R="compose",i.push(R?{tool:I,label:R}:{tool:I})}}let m=n[0]?.user??"",g=t.source??"cli",h=sx(m,g),b=[];for(let O of n){let j=tm.exec(O.user??"")?.[1];j&&!b.includes(j)&&b.push(j)}let _=n.filter(O=>(O.user??"").trim().length>0).length,A=n.filter(O=>(O.assistant??"").trim().length>0).length,y=[...n].reverse().find(O=>(O.assistant??"").trim().length>0)?.assistant??"",T;n.length===0?T="aborted":y.trim().length===0?T="partially_achieved":T="fully_achieved";let w=T==="fully_achieved"||T==="partially_achieved"?ns(y||m||h,160)||h:"none",C=c>0?`${c} tool error(s): ${Object.entries(s).map(([O,I])=>`${O}\xD7${I}`).join(", ")}`:"",$=t.name?ox(t.name):ns(m,80),G=ns(y||m,ex),v=ns($?`${$} \u2014 ${G}`:G,400)||"empty session",L=t.sessionId??(e.sourceSessionPath?XA(e.sourceSessionPath,".json"):"unknown"),D=t.totalDurationMs&&t.totalDurationMs>0?t.totalDurationMs:Math.max(0,t.savedAt-t.startedAt),x=e.sourceSessionPath?[...l,e.sourceSessionPath]:l,F={facet_version:Yn,session_id:L,source:g==="telegram"?"telegram":"cli",model:t.model,derived_at:(e.derivedAt??new Date).toISOString(),derived_from:"afk-session",source_session_path:e.sourceSessionPath??"",source_session_mtime_ms:e.sourceSessionMtimeMs??t.savedAt,subagent_persistence:"not_persisted",start_time:new Date(t.startedAt).toISOString(),end_time:new Date(t.savedAt).toISOString(),duration_minutes:Number((D/6e4).toFixed(2)),underlying_goal:m.slice(0,em),first_prompt:m.slice(0,em),goal_categories:{[h]:1},session_type:h,brief_summary:v,total_turns:n.length,user_message_count:_,assistant_message_count:A,tool_counts:o,commands:b,skills:a,subagents:i,tool_errors:c,tool_error_categories:s,friction_counts:{...s},friction_detail:C,outcome:T,primary_success:w,world_changes:{files_written:d,files_edited:u,bash_commands:p,commits:f,mutated:d>0||u>0||f>0},decisions:[],evidence_pointers:x};return Xn.parse(F)}U();import{existsSync as rs,mkdirSync as ax,readFileSync as nm,readdirSync as lx,renameSync as cx,statSync as dx,writeFileSync as ux}from"fs";import{basename as px,dirname as fx,join as rm}from"path";function om(t,e){return Cr(t),rm(e,`${t}.json`)}function mx(t,e){return Cr(t),rm(e,`${t}.json`)}function Qn(t,e=le()){let n=om(t,e);if(rs(n))try{let r=JSON.parse(nm(n,"utf8")),o=Fa.safeParse(r);return o.success?o.data:void 0}catch{return}}function gx(t){if(rs(t))try{let e=JSON.parse(nm(t,"utf8")),n=Xn.safeParse(e);return n.success?n.data:void 0}catch{return}}function hx(t,e){ax(fx(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;ux(n,`${JSON.stringify(e,null,2)}
|
|
1076
1076
|
`,"utf8"),cx(n,t)}function yx(t,e){return t.facet_version===Yn&&t.source_session_mtime_ms===e}function os(t,e={}){let n=e.sessionsDir??le(),r=e.cacheDir??jl(),o=om(t,n);if(!rs(o))return;let s=dx(o).mtimeMs,i=mx(t,r);if(!e.force){let c=gx(i);if(c&&yx(c,s))return c}let a=Qn(t,n);if(!a)return;let l=zt(a,{sourceSessionPath:o,sourceSessionMtimeMs:s});return hx(i,l),l}function ss(t={}){let e=t.sessionsDir??le();return rs(e)?lx(e).filter(n=>n.endsWith(".json")).map(n=>px(n,".json")):[]}U();N();function Wo(t,e){let n=Jo(t,e);if(n.length===0)return"";let r=[];for(let o of n){let s=o.argumentHint?`${o.argumentHint}`:"",i=s?`- \`${o.name} ${s}\`: ${o.description}`:`- ${o.name}: ${o.description}`;r.push(i),o.whenToUse&&r.push(` When to use: ${o.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.","",...r].join(`
|
|
1077
|
-
`)}function Jo(t,e){let n=[],r=new Set,o=S.AFK_INTERNAL==="1",s=si(oi());Vn(an(),"user"),_c("project"),Vn(Wl(e?.cwd),"project");for(let{dir:a,origin:l}of s.skillRoots)Vn(a,l);for(let a of Br()){let l=Ne(a);di(l,o)&&(n.push({name:a,description:l.description,source:l.origin==="user"?"user":l.origin==="project"?"project":l.origin?.startsWith("imported:")?"imported":"builtin",argumentHint:l.argumentHint,whenToUse:l.whenToUse}),r.add(a))}let i=t??La(e);for(let a of i){if(a.type!=="local")continue;let l=_a(a.path);for(let c of l)!c.name||r.has(c.name)||di({audience:c.audience},o)&&(n.push({name:c.name,description:c.description??`Skill from plugin at ${a.path}`,source:"plugin"}),r.add(c.name))}return n}function qn(t,e){let n=new Map,r=t??La(e);for(let o of r){if(o.type!=="local")continue;let s=_a(o.path);for(let i of s)i.name&&i.body&&i.body.length>0&&!n.has(i.name)&&n.set(i.name,{body:i.body,pluginPath:o.path,...i.allowedTools!==void 0?{allowedTools:i.allowedTools}:{},...i.context!==void 0?{context:i.context}:{},...i.readOnly===!0?{readOnly:!0}:{}})}return n}function La(t){return[...kt(Kl(t?.cwd)),...kt(),...kt(ql()),...si(oi()).pluginRoots.flatMap(({dir:e,binary:n})=>kt(e,{trustAll:!0,sourceEnabled:cc(n)}))]}async function sm(){await Vf(La(),{pluginApi:{registerSkill:ie,listSkills:Br,getSkill:Ne,loadSkillPrompts:Y,env:S,SubagentManager:K,describeFailure:re,discoverPluginSkillBodies:qn,getAgentFrameworkDir:_e,getSkillsDir:an,getSessionsDir:le,getOrDeriveFacet:os,listSessionIds:ss,deriveSessionFacet:zt,loadStoredSession:Qn}})}function Ho(){try{let t=Jo();return Promise.resolve(t.map(e=>{let n={name:e.name,description:e.description};return e.argumentHint&&(n.argumentHint=e.argumentHint),n}))}catch{return Promise.resolve([])}}function im(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 am(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 bx="__closed__",is=class{current=null;pendingReason=null;closedPromise;closeResolve=null;constructor(){this.closedPromise=new Promise(e=>{this.closeResolve=()=>e(bx)})}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 as}from"node:crypto";import{randomUUID as _x}from"node:crypto";var wx=new Map([["claude-sonnet-5",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["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 Sx(t,e,n,r,o){let s=wx.get(t);if(!s)return;let i=1e6,l=Math.max(0,e-r-o)/i*s.inputPerMTok,c=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 l+c+p+f}function lm(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=Sx(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}N();function kx(t){let e=t.trim();if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function vx(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}):a.kind==="redacted_thinking"?r.push({type:"redacted_thinking",data:a.data}):r.push({type:"tool_use",id:a.id,name:a.name,input:kx(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*cm(t,e){let n=[],r=null,o=null,s=!1,i=!!S.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 l=a.message?.usage;l&&(o={...l});break}case"content_block_start":{let l=a.content_block;l.type==="text"?n[a.index]={kind:"text",text:""}:l.type==="thinking"?n[a.index]={kind:"thinking",thinking:"",signature:""}:l.type==="redacted_thinking"?n[a.index]={kind:"redacted_thinking",data:l.data}:l.type==="tool_use"&&(n[a.index]={kind:"tool_use",id:l.id,name:l.name,partialJson:""},yield{kind:"event",event:{type:"tool.use.start",toolUseId:l.id,toolName:l.name,toolInput:" \u2026",sessionId:e.sessionId}});break}case"content_block_delta":{let l=n[a.index],c=a.delta;c.type==="text_delta"?(l&&l.kind==="text"&&(l.text+=c.text),yield{kind:"event",event:{type:"delta.text",text:c.text,sessionId:e.sessionId}}):c.type==="input_json_delta"?l&&l.kind==="tool_use"&&(l.partialJson+=c.partial_json):c.type==="thinking_delta"?(l&&l.kind==="thinking"&&(l.thinking+=c.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:c.thinking,sessionId:e.sessionId}}):c.type==="signature_delta"&&l&&l.kind==="thinking"&&(l.signature=c.signature);break}case"content_block_stop":{let l=n[a.index];l&&l.kind==="tool_use"&&(yield{kind:"event",event:{type:"tool.use",summary:l.name,toolUseIds:[l.id],sessionId:e.sessionId}});break}case"message_delta":{a.delta&&a.delta.stop_reason!==void 0&&(r=a.delta.stop_reason);let l=a.usage;l&&(o!==null?(o.output_tokens=l.output_tokens,l.cache_creation_input_tokens!=null&&(o.cache_creation_input_tokens=l.cache_creation_input_tokens),l.cache_read_input_tokens!=null&&(o.cache_read_input_tokens=l.cache_read_input_tokens),l.input_tokens!=null&&(o.input_tokens=l.input_tokens)):o={cache_creation:null,cache_creation_input_tokens:l.cache_creation_input_tokens??null,cache_read_input_tokens:l.cache_read_input_tokens??null,inference_geo:null,input_tokens:l.input_tokens??0,output_tokens:l.output_tokens,server_tool_use:null,service_tier:null});break}case"message_stop":{s=!0;break}default:break}if(s)break}i&&console.log("[translate] SDK iteration ended naturally, stopped=",s)}catch(a){i&&console.log("[translate] SDK iteration threw:",a.message),yield{kind:"event",event:{type:"error",error:a instanceof Error?a:new Error(String(a))}};return}i&&console.log("[translate] yielding turn-result"),yield{kind:"turn-result",result:vx(n,r,o)}}N();function Ex(t){let{name:e,description:n,input_schema:r}=t;return{name:e,...n!==void 0?{description:n}:{},input_schema:r}}var Na=3,um=5e3;function Ax(t){if(!("status"in t))return!1;let e=t.status;return e===529||e===503}function dm(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"}async function xx(t,e,n,r){for(let o=0;;o++){if(o>0){let s=um*Math.pow(2,o-1);if(await tt(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(Ax(i)&&o<Na)continue;throw i}}}async function*Ua(t){let e=Uo(t.maxToolUseIterations),n={stopReason:null},r=0,o=0,s=!1,i=0,a=_x(),l=Date.now(),c=d=>({...d,durationMs:Date.now()-l});Z(t.traceWriter,{phase:"loop_start"});try{for(;;){if(t.signal.aborted){yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId};return}let d=vr({baseUrl:t.baseUrl})?Dl(t.messages,_r()):t.messages,u={model:t.model,max_tokens:t.maxTokens,messages:d,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0&&!s?{tools:t.tools.map(Ex)}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{output_config:{effort:t.effort}}:{}},p=Date.now(),f;try{f=await xx(t.client,u,t.headers,t.signal)}catch(k){if(t.signal.aborted){yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId};return}let w=k instanceof Error?k:new Error(String(k));w.message.includes("thinking")&&Tx(t.messages,w),yield{type:"error",error:w};return}let m=null,g=!1,h=!1,b=!1;try{S.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let k of cm(f,t.ctx))if(b||(b=!0,Z(t.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-p,resolvedModel:t.model})),S.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",k.kind,k.kind==="event"?k.event.type:""),k.kind==="event"){if(k.event.type==="error"){if(dm(k.event.error)&&i<Na&&!t.signal.aborted){h=!0;break}yield k.event,g=!0;break}yield k.event}else{m=k.result;break}S.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",m?"set":"null")}catch(k){if(t.signal.aborted){yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId};return}let w=k instanceof Error?k:new Error(String(k));if(dm(w)&&i<Na&&!t.signal.aborted)h=!0;else{yield{type:"error",error:w};return}}if(h){if(i+=1,Z(t.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:i}}),yield{type:"stream.retry",sessionId:t.ctx.sessionId},await tt(um*Math.pow(2,i-1),t.signal),t.signal.aborted){yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId};return}continue}if(i=0,g){t.signal.aborted&&(yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId});return}if(m===null){yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId};return}let _=lm(m.usage,m.stopReason,t.model);if(n=Ln(n,_),n.contextWindowTokens=(_.inputTokens??0)+(_.outputTokens??0)+(_.cachedInputTokens??0)+(_.cacheCreationTokens??0),t.onUsageProgress?.(n),m.stopReason!=="tool_use"){if(m.stopReason==="refusal"){yield{type:"assistant.message",text:m.text.length>0?m.text:`The model stopped with a content-safety refusal (stop_reason: "refusal") and returned no output. This is Anthropic's safety system declining the request \u2014 not an afk error. Because the flagged context stays in the conversation, follow-up messages will likely be refused the same way; rephrase the request or start a fresh session to continue.`,sessionId:t.ctx.sessionId},yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId};return}m.text.length>0&&(yield{type:"assistant.message",text:m.text,sessionId:t.ctx.sessionId},m.text.length<=200&&(yield{type:"suggestion",suggestion:m.text,sessionId:t.ctx.sessionId}));let k=m.assistantBlocks.filter(w=>w.type!=="tool_use");k.length>0&&t.messages.push({role:"assistant",content:k}),yield{type:"turn.completed",usage:c(s?{...n,stopReason:Wt}:n),sessionId:t.ctx.sessionId};return}let A=t.messages.length;t.messages.push({role:"assistant",content:m.assistantBlocks});try{o+=m.toolUseBlocks.length;let k=[],w=new Map;for(let v of m.toolUseBlocks){k.push({id:v.id,name:v.name,input:v.input,signal:t.signal});let L=Date.now();w.set(v.id,L),_t(t.traceWriter,{phase:"started",toolUseId:v.id,name:v.name,inputBytes:Buffer.byteLength(JSON.stringify(v.input??{}),"utf8")}),yield{type:"tool.use.start",toolUseId:v.id,toolName:v.name,toolInput:St(v.name,v.input),toolInputRaw:Lo(v.input),sessionId:t.ctx.sessionId}}if(t.signal.aborted){let v=k.map(L=>({type:"tool_result",tool_use_id:L.id,content:"Tool call aborted",is_error:!0}));t.messages.push({role:"user",content:v}),yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId};return}let C;if(t.toolDispatcher.executeBatch)try{C=await t.toolDispatcher.executeBatch(k)}catch(v){C=k.map(()=>({content:`Tool batch execution failed: ${v instanceof Error?v.message:String(v)}`,isError:!0}))}else{C=[];for(let v of k){if(t.signal.aborted){C.push({content:"Tool call aborted",isError:!0});continue}try{C.push(await t.toolDispatcher.execute(v))}catch(L){let D=L instanceof Error?L.message:String(L);C.push({content:`Tool execution threw: ${D}`,isError:!0})}}}let $=[];for(let v=0;v<k.length;v++){let L=k[v],D=C[v],x=w.get(L.id),F=typeof x=="number"?Date.now()-x:0,O=D.truncated===!0||D.content.includes("[output truncated");_t(t.traceWriter,{phase:"completed",toolUseId:L.id,name:L.name,resultBytes:Buffer.byteLength(D.content,"utf8"),isError:D.isError===!0,truncated:O,durationMs:F,...D.circuitBreaker===!0?{circuitBreaker:!0}:{},...D.failureClass?{failureClass:D.failureClass}:{},...typeof D.batchIndex=="number"&&typeof D.batchSize=="number"?{batchIndex:D.batchIndex,batchSize:D.batchSize}:{}}),yield{type:"tool.output",toolUseId:L.id,toolName:L.name,content:D.content,...D.isError===!0?{isError:!0}:{},...O?{truncated:!0}:{},...typeof D.batchIndex=="number"&&typeof D.batchSize=="number"?{batchIndex:D.batchIndex,batchSize:D.batchSize}:{},sessionId:t.ctx.sessionId},D.render?.diff&&(yield{type:"tool.diff",toolUseId:L.id,diff:D.render.diff,sessionId:t.ctx.sessionId});let{content:I,isError:j,image:R}=D,P=R!==void 0?[{type:"image",source:{type:"base64",media_type:R.mediaType,data:R.data}},...I.length>0?[{type:"text",text:I}]:[]]:I;$.push({type:"tool_result",tool_use_id:L.id,content:P,...j===!0?{is_error:!0}:{}})}let G={role:"user",content:$};t.messages.push(G)}catch(k){throw t.messages.splice(A),k}r+=1;let y=m.toolUseBlocks[m.toolUseBlocks.length-1],T=y?`${y.name}${St(y.name,y.input)}`:"unknown";if(yield{type:"progress",progress:{taskId:a,description:"Working",summary:`round ${r}: ${T}`,lastToolName:y?.name,totalTokens:n.totalTokens??0,toolUses:o,durationMs:Date.now()-l},sessionId:t.ctx.sessionId},s){yield{type:"turn.completed",usage:c({...n,stopReason:Wt}),sessionId:t.ctx.sessionId};return}if($o(r,e)){let k=t.messages[t.messages.length-1];k!==void 0&&k.role==="user"&&Array.isArray(k.content)&&k.content.push({type:"text",text:No}),s=!0;continue}}}finally{Z(t.traceWriter,{phase:"loop_end",durationMs:Date.now()-l})}}function Tx(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 l=a;(!l.thinking||!l.signature)&&n.push({msgIdx:r,blockIdx:i,thinking:l.thinking?`(${l.thinking.length} chars)`:"(empty)",sigLen:l.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",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{}}var pm=7200*1e3,Rx=3,Ix=12e4,Px=5e3,Cx=1e3,Mx=60*1e3,ls=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=ye(),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=ye();return{accountId:sn(r??""),swapped:e!==r}}async*turnWithRetries(e,n){yield*this.turnWithUsageLimitRetry(e,n)}async*turnWithUsageLimitRetry(e,n){let r=null,o=null,s=!1,i=0;for(;;){let d,u=!1;for await(let m of this.turnWithAuthRetry(e,n)){if(m.type==="error"){let g=kr(m.error);if(g&&g.kind==="oauth-limit"){o=g.resetsAt,r=m;break}if(g&&g.kind==="oauth-limit-no-ts"){s=!0,r=m;break}if(g&&g.kind==="rate-limit-transient"&&i<Rx){u=!0,d=g.retryAfterMs;break}}yield m}if(!u)break;if(i+=1,n()||e.signal.aborted)return;let f=Math.min(d??Px,Ix)+Math.floor(Math.random()*Cx);if(Z(e.traceWriter,{phase:"rate_limit",metadata:{reason:"retry-after",source:"retry-layer",attempt:i,waitMs:f}}),await tt(f,e.signal),n()||e.signal.aborted)return;e.headers=he(this._authMode,this.initSessionId,as())}if(!r)return;if(s){let d=sn(ye()??"");if(yield{type:"paused",reason:"usage-limit",accountId:d,autoResume:this.autoResumeOnUsageLimit},!this.autoResumeOnUsageLimit){yield r;return}let u=Date.now(),p=!1;for(;;){let f;if(this.usageLimitWaitPromise)f="aborted";else{this.usageLimitWaitPromise=Ml({signal:e.signal,retryAfterMs:Mx});try{f=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(f==="aborted")return;let m=d;if(f==="hot-swap"){let h=await this.forceClientRefresh();h&&(e.client=this._client,m=h.accountId)}e.headers=he(this._authMode,this.initSessionId,as());let g=null;for await(let h of this.turnWithAuthRetry(e,n)){if(!p&&h.type==="error"){let b=kr(h.error);if(b&&(b.kind==="oauth-limit"||b.kind==="oauth-limit-no-ts")){g=h;break}}p||(yield{type:"resumed",hotSwapped:f==="hot-swap",accountId:m},p=!0),yield h}if(!g)return;if(Date.now()-u>pm){yield g;return}}}if(!o)return;if(o.getTime()-Date.now()>pm){yield r;return}let a=sn(ye()??"");if(yield{type:"paused",reason:"usage-limit",resetsAt:o,accountId:a,autoResume:this.autoResumeOnUsageLimit},!this.autoResumeOnUsageLimit){yield r;return}let l;if(this.usageLimitWaitPromise)l=await this.usageLimitWaitPromise;else{this.usageLimitWaitPromise=Cl({resetsAt:o,signal:e.signal});try{l=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(l==="aborted")return;let c=a;if(l==="hot-swap"){let d=await this.forceClientRefresh();d&&(e.client=this._client,c=d.accountId)}e.headers=he(this._authMode,this.initSessionId,as()),yield{type:"resumed",hotSwapped:l==="hot-swap",accountId:c},yield*this.turnWithAuthRetry(e,n)}async*turnWithAuthRetry(e,n){let r=null;for await(let s of Ua(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=he(this._authMode,this.initSessionId,as()),yield*Ua(e)}isRetryableAuth(e){return this._authMode==="oauth"&&this.tokenRefresher!==void 0&&"status"in e&&e.status===401}};import{randomUUID as Lx}from"node:crypto";function Ox(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 Dx(t){let n=[(t.role==="user"?"User":"Assistant")+":"];if(typeof t.content=="string")n.push(t.content);else if(Array.isArray(t.content))for(let r of t.content){let o=r.type;if(o==="text"&&"text"in r)n.push(r.text);else if(o==="tool_use"){let s=r.name??"unknown",i=ym(r.input);n.push(`[tool call: ${s} ${i}]`)}else if(o==="tool_result"){let s=r.content;n.push(`[tool result: ${bm(s)}]`)}else o==="image"?n.push("[image]"):o==="document"&&n.push("[document]")}return n.join(`
|
|
1077
|
+
`)}function Jo(t,e){let n=[],r=new Set,o=S.AFK_INTERNAL==="1",s=si(oi());Vn(an(),"user"),_c("project"),Vn(Wl(e?.cwd),"project");for(let{dir:a,origin:l}of s.skillRoots)Vn(a,l);for(let a of Br()){let l=Ne(a);di(l,o)&&(n.push({name:a,description:l.description,source:l.origin==="user"?"user":l.origin==="project"?"project":l.origin?.startsWith("imported:")?"imported":"builtin",argumentHint:l.argumentHint,whenToUse:l.whenToUse}),r.add(a))}let i=t??La(e);for(let a of i){if(a.type!=="local")continue;let l=_a(a.path);for(let c of l)!c.name||r.has(c.name)||di({audience:c.audience},o)&&(n.push({name:c.name,description:c.description??`Skill from plugin at ${a.path}`,source:"plugin"}),r.add(c.name))}return n}function qn(t,e){let n=new Map,r=t??La(e);for(let o of r){if(o.type!=="local")continue;let s=_a(o.path);for(let i of s)i.name&&i.body&&i.body.length>0&&!n.has(i.name)&&n.set(i.name,{body:i.body,pluginPath:o.path,...i.allowedTools!==void 0?{allowedTools:i.allowedTools}:{},...i.context!==void 0?{context:i.context}:{},...i.readOnly===!0?{readOnly:!0}:{},...i.model!==void 0?{model:i.model}:{}})}return n}function La(t){return[...kt(Kl(t?.cwd)),...kt(),...kt(ql()),...si(oi()).pluginRoots.flatMap(({dir:e,binary:n})=>kt(e,{trustAll:!0,sourceEnabled:cc(n)}))]}async function sm(){await Vf(La(),{pluginApi:{registerSkill:ie,listSkills:Br,getSkill:Ne,loadSkillPrompts:Y,env:S,SubagentManager:K,describeFailure:re,discoverPluginSkillBodies:qn,getAgentFrameworkDir:_e,getSkillsDir:an,getSessionsDir:le,getOrDeriveFacet:os,listSessionIds:ss,deriveSessionFacet:zt,loadStoredSession:Qn}})}function Ho(){try{let t=Jo();return Promise.resolve(t.map(e=>{let n={name:e.name,description:e.description};return e.argumentHint&&(n.argumentHint=e.argumentHint),n}))}catch{return Promise.resolve([])}}function im(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 am(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 bx="__closed__",is=class{current=null;pendingReason=null;closedPromise;closeResolve=null;constructor(){this.closedPromise=new Promise(e=>{this.closeResolve=()=>e(bx)})}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 as}from"node:crypto";import{randomUUID as _x}from"node:crypto";var wx=new Map([["claude-sonnet-5",{inputPerMTok:3,outputPerMTok:15,cacheWritePerMTok:3.75,cacheReadPerMTok:.3}],["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 Sx(t,e,n,r,o){let s=wx.get(t);if(!s)return;let i=1e6,l=Math.max(0,e-r-o)/i*s.inputPerMTok,c=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 l+c+p+f}function lm(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=Sx(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}N();function kx(t){let e=t.trim();if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function vx(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}):a.kind==="redacted_thinking"?r.push({type:"redacted_thinking",data:a.data}):r.push({type:"tool_use",id:a.id,name:a.name,input:kx(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*cm(t,e){let n=[],r=null,o=null,s=!1,i=!!S.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 l=a.message?.usage;l&&(o={...l});break}case"content_block_start":{let l=a.content_block;l.type==="text"?n[a.index]={kind:"text",text:""}:l.type==="thinking"?n[a.index]={kind:"thinking",thinking:"",signature:""}:l.type==="redacted_thinking"?n[a.index]={kind:"redacted_thinking",data:l.data}:l.type==="tool_use"&&(n[a.index]={kind:"tool_use",id:l.id,name:l.name,partialJson:""},yield{kind:"event",event:{type:"tool.use.start",toolUseId:l.id,toolName:l.name,toolInput:" \u2026",sessionId:e.sessionId}});break}case"content_block_delta":{let l=n[a.index],c=a.delta;c.type==="text_delta"?(l&&l.kind==="text"&&(l.text+=c.text),yield{kind:"event",event:{type:"delta.text",text:c.text,sessionId:e.sessionId}}):c.type==="input_json_delta"?l&&l.kind==="tool_use"&&(l.partialJson+=c.partial_json):c.type==="thinking_delta"?(l&&l.kind==="thinking"&&(l.thinking+=c.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:c.thinking,sessionId:e.sessionId}}):c.type==="signature_delta"&&l&&l.kind==="thinking"&&(l.signature=c.signature);break}case"content_block_stop":{let l=n[a.index];l&&l.kind==="tool_use"&&(yield{kind:"event",event:{type:"tool.use",summary:l.name,toolUseIds:[l.id],sessionId:e.sessionId}});break}case"message_delta":{a.delta&&a.delta.stop_reason!==void 0&&(r=a.delta.stop_reason);let l=a.usage;l&&(o!==null?(o.output_tokens=l.output_tokens,l.cache_creation_input_tokens!=null&&(o.cache_creation_input_tokens=l.cache_creation_input_tokens),l.cache_read_input_tokens!=null&&(o.cache_read_input_tokens=l.cache_read_input_tokens),l.input_tokens!=null&&(o.input_tokens=l.input_tokens)):o={cache_creation:null,cache_creation_input_tokens:l.cache_creation_input_tokens??null,cache_read_input_tokens:l.cache_read_input_tokens??null,inference_geo:null,input_tokens:l.input_tokens??0,output_tokens:l.output_tokens,server_tool_use:null,service_tier:null});break}case"message_stop":{s=!0;break}default:break}if(s)break}i&&console.log("[translate] SDK iteration ended naturally, stopped=",s)}catch(a){i&&console.log("[translate] SDK iteration threw:",a.message),yield{kind:"event",event:{type:"error",error:a instanceof Error?a:new Error(String(a))}};return}i&&console.log("[translate] yielding turn-result"),yield{kind:"turn-result",result:vx(n,r,o)}}N();function Ex(t){let{name:e,description:n,input_schema:r}=t;return{name:e,...n!==void 0?{description:n}:{},input_schema:r}}var Na=3,um=5e3;function Ax(t){if(!("status"in t))return!1;let e=t.status;return e===529||e===503}function dm(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"}async function xx(t,e,n,r){for(let o=0;;o++){if(o>0){let s=um*Math.pow(2,o-1);if(await tt(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(Ax(i)&&o<Na)continue;throw i}}}async function*Ua(t){let e=Uo(t.maxToolUseIterations),n={stopReason:null},r=0,o=0,s=!1,i=0,a=_x(),l=Date.now(),c=d=>({...d,durationMs:Date.now()-l});Z(t.traceWriter,{phase:"loop_start"});try{for(;;){if(t.signal.aborted){yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId};return}let d=vr({baseUrl:t.baseUrl})?Dl(t.messages,_r()):t.messages,u={model:t.model,max_tokens:t.maxTokens,messages:d,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0&&!s?{tools:t.tools.map(Ex)}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{output_config:{effort:t.effort}}:{}},p=Date.now(),f;try{f=await xx(t.client,u,t.headers,t.signal)}catch(k){if(t.signal.aborted){yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId};return}let w=k instanceof Error?k:new Error(String(k));w.message.includes("thinking")&&Tx(t.messages,w),yield{type:"error",error:w};return}let m=null,g=!1,h=!1,b=!1;try{S.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let k of cm(f,t.ctx))if(b||(b=!0,Z(t.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-p,resolvedModel:t.model})),S.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",k.kind,k.kind==="event"?k.event.type:""),k.kind==="event"){if(k.event.type==="error"){if(dm(k.event.error)&&i<Na&&!t.signal.aborted){h=!0;break}yield k.event,g=!0;break}yield k.event}else{m=k.result;break}S.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",m?"set":"null")}catch(k){if(t.signal.aborted){yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId};return}let w=k instanceof Error?k:new Error(String(k));if(dm(w)&&i<Na&&!t.signal.aborted)h=!0;else{yield{type:"error",error:w};return}}if(h){if(i+=1,Z(t.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:i}}),yield{type:"stream.retry",sessionId:t.ctx.sessionId},await tt(um*Math.pow(2,i-1),t.signal),t.signal.aborted){yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId};return}continue}if(i=0,g){t.signal.aborted&&(yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId});return}if(m===null){yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId};return}let _=lm(m.usage,m.stopReason,t.model);if(n=Ln(n,_),n.contextWindowTokens=(_.inputTokens??0)+(_.outputTokens??0)+(_.cachedInputTokens??0)+(_.cacheCreationTokens??0),t.onUsageProgress?.(n),m.stopReason!=="tool_use"){if(m.stopReason==="refusal"){yield{type:"assistant.message",text:m.text.length>0?m.text:`The model stopped with a content-safety refusal (stop_reason: "refusal") and returned no output. This is Anthropic's safety system declining the request \u2014 not an afk error. Because the flagged context stays in the conversation, follow-up messages will likely be refused the same way; rephrase the request or start a fresh session to continue.`,sessionId:t.ctx.sessionId},yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId};return}m.text.length>0&&(yield{type:"assistant.message",text:m.text,sessionId:t.ctx.sessionId},m.text.length<=200&&(yield{type:"suggestion",suggestion:m.text,sessionId:t.ctx.sessionId}));let k=m.assistantBlocks.filter(w=>w.type!=="tool_use");k.length>0&&t.messages.push({role:"assistant",content:k}),yield{type:"turn.completed",usage:c(s?{...n,stopReason:Wt}:n),sessionId:t.ctx.sessionId};return}let A=t.messages.length;t.messages.push({role:"assistant",content:m.assistantBlocks});try{o+=m.toolUseBlocks.length;let k=[],w=new Map;for(let v of m.toolUseBlocks){k.push({id:v.id,name:v.name,input:v.input,signal:t.signal});let L=Date.now();w.set(v.id,L),_t(t.traceWriter,{phase:"started",toolUseId:v.id,name:v.name,inputBytes:Buffer.byteLength(JSON.stringify(v.input??{}),"utf8")}),yield{type:"tool.use.start",toolUseId:v.id,toolName:v.name,toolInput:St(v.name,v.input),toolInputRaw:Lo(v.input),sessionId:t.ctx.sessionId}}if(t.signal.aborted){let v=k.map(L=>({type:"tool_result",tool_use_id:L.id,content:"Tool call aborted",is_error:!0}));t.messages.push({role:"user",content:v}),yield{type:"turn.completed",usage:c(n),sessionId:t.ctx.sessionId};return}let C;if(t.toolDispatcher.executeBatch)try{C=await t.toolDispatcher.executeBatch(k)}catch(v){C=k.map(()=>({content:`Tool batch execution failed: ${v instanceof Error?v.message:String(v)}`,isError:!0}))}else{C=[];for(let v of k){if(t.signal.aborted){C.push({content:"Tool call aborted",isError:!0});continue}try{C.push(await t.toolDispatcher.execute(v))}catch(L){let D=L instanceof Error?L.message:String(L);C.push({content:`Tool execution threw: ${D}`,isError:!0})}}}let $=[];for(let v=0;v<k.length;v++){let L=k[v],D=C[v],x=w.get(L.id),F=typeof x=="number"?Date.now()-x:0,O=D.truncated===!0||D.content.includes("[output truncated");_t(t.traceWriter,{phase:"completed",toolUseId:L.id,name:L.name,resultBytes:Buffer.byteLength(D.content,"utf8"),isError:D.isError===!0,truncated:O,durationMs:F,...D.circuitBreaker===!0?{circuitBreaker:!0}:{},...D.failureClass?{failureClass:D.failureClass}:{},...typeof D.batchIndex=="number"&&typeof D.batchSize=="number"?{batchIndex:D.batchIndex,batchSize:D.batchSize}:{}}),yield{type:"tool.output",toolUseId:L.id,toolName:L.name,content:D.content,...D.isError===!0?{isError:!0}:{},...O?{truncated:!0}:{},...typeof D.batchIndex=="number"&&typeof D.batchSize=="number"?{batchIndex:D.batchIndex,batchSize:D.batchSize}:{},sessionId:t.ctx.sessionId},D.render?.diff&&(yield{type:"tool.diff",toolUseId:L.id,diff:D.render.diff,sessionId:t.ctx.sessionId});let{content:I,isError:j,image:R}=D,P=R!==void 0?[{type:"image",source:{type:"base64",media_type:R.mediaType,data:R.data}},...I.length>0?[{type:"text",text:I}]:[]]:I;$.push({type:"tool_result",tool_use_id:L.id,content:P,...j===!0?{is_error:!0}:{}})}let G={role:"user",content:$};t.messages.push(G)}catch(k){throw t.messages.splice(A),k}r+=1;let y=m.toolUseBlocks[m.toolUseBlocks.length-1],T=y?`${y.name}${St(y.name,y.input)}`:"unknown";if(yield{type:"progress",progress:{taskId:a,description:"Working",summary:`round ${r}: ${T}`,lastToolName:y?.name,totalTokens:n.totalTokens??0,toolUses:o,durationMs:Date.now()-l},sessionId:t.ctx.sessionId},s){yield{type:"turn.completed",usage:c({...n,stopReason:Wt}),sessionId:t.ctx.sessionId};return}if($o(r,e)){let k=t.messages[t.messages.length-1];k!==void 0&&k.role==="user"&&Array.isArray(k.content)&&k.content.push({type:"text",text:No}),s=!0;continue}}}finally{Z(t.traceWriter,{phase:"loop_end",durationMs:Date.now()-l})}}function Tx(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 l=a;(!l.thinking||!l.signature)&&n.push({msgIdx:r,blockIdx:i,thinking:l.thinking?`(${l.thinking.length} chars)`:"(empty)",sigLen:l.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",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{}}var pm=7200*1e3,Rx=3,Ix=12e4,Px=5e3,Cx=1e3,Mx=60*1e3,ls=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=ye(),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=ye();return{accountId:sn(r??""),swapped:e!==r}}async*turnWithRetries(e,n){yield*this.turnWithUsageLimitRetry(e,n)}async*turnWithUsageLimitRetry(e,n){let r=null,o=null,s=!1,i=0;for(;;){let d,u=!1;for await(let m of this.turnWithAuthRetry(e,n)){if(m.type==="error"){let g=kr(m.error);if(g&&g.kind==="oauth-limit"){o=g.resetsAt,r=m;break}if(g&&g.kind==="oauth-limit-no-ts"){s=!0,r=m;break}if(g&&g.kind==="rate-limit-transient"&&i<Rx){u=!0,d=g.retryAfterMs;break}}yield m}if(!u)break;if(i+=1,n()||e.signal.aborted)return;let f=Math.min(d??Px,Ix)+Math.floor(Math.random()*Cx);if(Z(e.traceWriter,{phase:"rate_limit",metadata:{reason:"retry-after",source:"retry-layer",attempt:i,waitMs:f}}),await tt(f,e.signal),n()||e.signal.aborted)return;e.headers=he(this._authMode,this.initSessionId,as())}if(!r)return;if(s){let d=sn(ye()??"");if(yield{type:"paused",reason:"usage-limit",accountId:d,autoResume:this.autoResumeOnUsageLimit},!this.autoResumeOnUsageLimit){yield r;return}let u=Date.now(),p=!1;for(;;){let f;if(this.usageLimitWaitPromise)f="aborted";else{this.usageLimitWaitPromise=Ml({signal:e.signal,retryAfterMs:Mx});try{f=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(f==="aborted")return;let m=d;if(f==="hot-swap"){let h=await this.forceClientRefresh();h&&(e.client=this._client,m=h.accountId)}e.headers=he(this._authMode,this.initSessionId,as());let g=null;for await(let h of this.turnWithAuthRetry(e,n)){if(!p&&h.type==="error"){let b=kr(h.error);if(b&&(b.kind==="oauth-limit"||b.kind==="oauth-limit-no-ts")){g=h;break}}p||(yield{type:"resumed",hotSwapped:f==="hot-swap",accountId:m},p=!0),yield h}if(!g)return;if(Date.now()-u>pm){yield g;return}}}if(!o)return;if(o.getTime()-Date.now()>pm){yield r;return}let a=sn(ye()??"");if(yield{type:"paused",reason:"usage-limit",resetsAt:o,accountId:a,autoResume:this.autoResumeOnUsageLimit},!this.autoResumeOnUsageLimit){yield r;return}let l;if(this.usageLimitWaitPromise)l=await this.usageLimitWaitPromise;else{this.usageLimitWaitPromise=Cl({resetsAt:o,signal:e.signal});try{l=await this.usageLimitWaitPromise}finally{this.usageLimitWaitPromise=null}}if(l==="aborted")return;let c=a;if(l==="hot-swap"){let d=await this.forceClientRefresh();d&&(e.client=this._client,c=d.accountId)}e.headers=he(this._authMode,this.initSessionId,as()),yield{type:"resumed",hotSwapped:l==="hot-swap",accountId:c},yield*this.turnWithAuthRetry(e,n)}async*turnWithAuthRetry(e,n){let r=null;for await(let s of Ua(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=he(this._authMode,this.initSessionId,as()),yield*Ua(e)}isRetryableAuth(e){return this._authMode==="oauth"&&this.tokenRefresher!==void 0&&"status"in e&&e.status===401}};import{randomUUID as Lx}from"node:crypto";function Ox(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 Dx(t){let n=[(t.role==="user"?"User":"Assistant")+":"];if(typeof t.content=="string")n.push(t.content);else if(Array.isArray(t.content))for(let r of t.content){let o=r.type;if(o==="text"&&"text"in r)n.push(r.text);else if(o==="tool_use"){let s=r.name??"unknown",i=ym(r.input);n.push(`[tool call: ${s} ${i}]`)}else if(o==="tool_result"){let s=r.content;n.push(`[tool result: ${bm(s)}]`)}else o==="image"?n.push("[image]"):o==="document"&&n.push("[document]")}return n.join(`
|
|
1078
1078
|
`)}function Fx(t){let e=0;if(typeof t.content=="string")e+=t.content.length;else if(Array.isArray(t.content))for(let n of t.content){let r=n.type;r==="text"&&"text"in n?e+=n.text.length:r==="tool_use"?e+=ym(n.input).length:r==="tool_result"&&(e+=bm(n.content).length)}return e}var cs={isFreshUserTurn:Ox,renderMessage:Dx,buildPreamble(t){return[{role:"user",content:Wn+`
|
|
1079
1079
|
|
|
1080
1080
|
`+t},{role:"assistant",content:Kn}]},countChars:Fx};function fm(t,e){return da(t,e,cs)}function mm(t,e,n){let r=ua(t,cs);return{model:e,max_tokens:n,system:Oo,messages:[{role:"user",content:Do(r)}],stream:!0}}function gm(t,e,n){return pa(t,e,n,cs)}function hm(t,e,n){return fa(t,e,n,cs)}function ym(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function bm(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""}N();var Nx=2,Ux="claude-haiku-4-5-20251001",$x=1024;async function wm(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=Bx(),l=fm(e.messages,a);if(l<0)return{compacted:!1,reason:"history-too-short",messagesBefore:i,messagesAfter:i};if(l===0)return{compacted:!1,reason:"nothing-to-summarize",messagesBefore:i,messagesAfter:i};let c=e.messages.slice(0,l),d=jx(),u=mm(c,d,$x),p=n.begin(),f;try{if(p.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let b=he(r.authMode,o,Lx()),_=r.client,A=await Promise.resolve(_.messages.create(u,{headers:b,signal:p.signal}));f=await Hx(A)}catch(b){return p.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i}:{compacted:!1,reason:"summarization-failed: "+(b instanceof Error?b.message:String(b)),messagesBefore:i,messagesAfter:i}}finally{n.clear(p)}if(f.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:i,messagesAfter:i};let m=hm(e.messages,l,f),g=gm(e.messages,l,f);e.messages.splice(0,e.messages.length,...g);let h=e.messages.length;return hr(s,{trigger:"manual",preCompactionMessages:c,summary:f,keptTailCount:i-l,keepLastNConfig:a,messagesBefore:i,messagesAfter:h,tokensSavedEstimate:m}),{compacted:!0,messagesBefore:i,messagesAfter:h,tokensSavedEstimate:m}}function Bx(){let t=S.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 Nx}function jx(){let t=S.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?se(t)??t:Ux}async function Hx(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 Wx=[{value:"claude-sonnet-5",displayName:"Claude Sonnet 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"}],ds=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;baseUrl;maxToolUseIterations;traceWriter;state;abort;retry;cwdDependentsFactory;onPermissionMode;mcpManager;hookRegistry;constructor(e){this.initSessionId=e.sessionId??Sm(),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),e.maxToolUseIterations!==void 0&&(this.maxToolUseIterations=e.maxToolUseIterations),this.traceWriter=e.traceWriter,this.cwdDependentsFactory=e.cwdDependentsFactory,this.onPermissionMode=e.onPermissionMode,this.mcpManager=e.mcpManager,e.hookRegistry!==void 0&&(this.hookRegistry=e.hookRegistry),this.retry=new ls({client:e.client,authMode:e.authMode,initSessionId:this.initSessionId,...e.tokenRefresher?{tokenRefresher:e.tokenRefresher}:{},autoResumeOnUsageLimit:e.autoResumeOnUsageLimit??!0}),this.state=am({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 is}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}im(this.state.messages),this.state.messages.push({role:"user",content:s.content});let a=this.composeSystem(),l=he(this.retry.authMode,this.initSessionId,Sm(),this.effort!==void 0),c={client:this.retry.client,messages:this.state.messages,system:a,tools:this.state.currentPermissionMode==="plan"?this.tools:this.tools?.filter(u=>u.name!==Ae)??null,toolDispatcher:this.state.toolDispatcher,model:this.state.currentModel,maxTokens:this.maxTokens,headers:l,signal:i.signal,ctx:{sessionId:this.initSessionId},...this.thinking!==void 0?{thinking:this.thinking}:{},...this.effort!==void 0?{effort:this.effort}:{},...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{},...this.maxToolUseIterations!==void 0?{maxToolUseIterations:this.maxToolUseIterations}:{},...this.traceWriter?{traceWriter:this.traceWriter}:{},onUsageProgress:u=>{this.state.lastUsage=u}},d=!1;try{for await(let u of this.retry.turnWithRetries(c,()=>this.state.closed)){if(this.state.closed)return;u.type==="turn.completed"&&(this.state.lastUsage=u.usage,this.abort.clear(i)),(u.type==="turn.completed"||u.type==="error")&&(d=!0),yield u}}catch(u){if(this.state.closed)return;if(i.signal.aborted){this.abort.clear(i),d||(yield this.makeInterruptedTurnEvent());continue}yield{type:"error",error:u instanceof Error?u:new Error(String(u))};return}finally{this.abort.clear(i)}if(this.state.closed)return;if(i.signal.aborted){d||(yield this.makeInterruptedTurnEvent());continue}if(this.state.autoCompactThreshold!==void 0&&!this.state.closed){let u=this.state.lastUsage,p=Po(this.state.requestedModel);if(u!==null&&p>0){let f=et(u);if(Hn(f,p,this.state.autoCompactThreshold))try{this.hookRegistry&&await this.hookRegistry.dispatch({event:"PreCompact",sessionId:this.initSessionId,trigger:"auto"}),await this.compact()}catch(m){if(!(m instanceof H))throw m}}}}}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=Js(this.state.currentPermissionMode);o!==null&&r.push(o);let s=Vs(this.state.currentPermissionMode);return s!==null&&r.push(s),r.length===0?null:vr({baseUrl:this.baseUrl})?Ol(r,_r()):r}async interrupt(){this.abort.requestAbort("interrupted")}makeInterruptedTurnEvent(){return{type:"turn.completed",usage:{stopReason:"interrupted",resultSubtype:"interrupted",isError:!1},sessionId:this.initSessionId}}async setModel(e){e!==void 0&&e.length>0&&(this.state.requestedModel=e,this.state.currentModel=se(e)??e)}async setPermissionMode(e){this.state.currentPermissionMode=e;let n=ve(e);this.state.toolDispatcher.setAllowAll?.(n),this.onPermissionMode?.(e)}setCwd(e){if(this.state.toolDispatcher.setResolveBase?.(e),!this.cwdDependentsFactory)return;let{userSystem:n,dispatcher:r}=this.cwdDependentsFactory(e);this.state.userSystem=n,this.state.toolDispatcher=r}async supportedCommands(){return Ho()}async supportedModels(){return Wx.map(e=>({...e}))}async supportedAgents(){return[]}async getContextUsage(){let e=this.state.lastUsage,n=Un(this.state.requestedModel),r;if(e&&n>0){let i=et(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=jn(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 wm({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 Kx=t=>/opus-4-(7|[89])/.test(t),Gx=t=>Kx(t)||/(claude-)?sonnet-5/.test(t),us=new Set,qx=.25;function $a(t,e){let n=Io(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 us.has(s)||(us.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${e} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function km(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 Ba(t,e,n){switch(t.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&Gx(n))return{type:"adaptive",display:"summarized"};let r=Math.floor(e*qx),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}`;us.has(a)||(us.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 ja(t,e){if(t!==void 0)return t;let n=e.toLowerCase();if(/(claude-)?(opus|sonnet)-4-[678]|(claude-)?sonnet-5/.test(n))return"max"}N();import{mkdirSync as zx,appendFileSync as Jx,existsSync as Vx}from"fs";import{resolve as Yx}from"path";import{dirname as Xx}from"path";var Qx=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
|